Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/tests/pipelines/unclip/test_unclip_image_variation.py
1451 views
1
# coding=utf-8
2
# Copyright 2023 HuggingFace Inc.
3
#
4
# Licensed under the Apache License, Version 2.0 (the "License");
5
# you may not use this file except in compliance with the License.
6
# You may obtain a copy of the License at
7
#
8
# http://www.apache.org/licenses/LICENSE-2.0
9
#
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS,
12
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
# See the License for the specific language governing permissions and
14
# limitations under the License.
15
16
import gc
17
import random
18
import unittest
19
20
import numpy as np
21
import torch
22
from transformers import (
23
CLIPImageProcessor,
24
CLIPTextConfig,
25
CLIPTextModelWithProjection,
26
CLIPTokenizer,
27
CLIPVisionConfig,
28
CLIPVisionModelWithProjection,
29
)
30
31
from diffusers import (
32
DiffusionPipeline,
33
UnCLIPImageVariationPipeline,
34
UnCLIPScheduler,
35
UNet2DConditionModel,
36
UNet2DModel,
37
)
38
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
39
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
40
from diffusers.utils.testing_utils import load_image, require_torch_gpu, skip_mps
41
42
from ...pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
43
from ...test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
44
45
46
class UnCLIPImageVariationPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
47
pipeline_class = UnCLIPImageVariationPipeline
48
params = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"}
49
batch_params = IMAGE_VARIATION_BATCH_PARAMS
50
51
required_optional_params = [
52
"generator",
53
"return_dict",
54
"decoder_num_inference_steps",
55
"super_res_num_inference_steps",
56
]
57
58
@property
59
def text_embedder_hidden_size(self):
60
return 32
61
62
@property
63
def time_input_dim(self):
64
return 32
65
66
@property
67
def block_out_channels_0(self):
68
return self.time_input_dim
69
70
@property
71
def time_embed_dim(self):
72
return self.time_input_dim * 4
73
74
@property
75
def cross_attention_dim(self):
76
return 100
77
78
@property
79
def dummy_tokenizer(self):
80
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
81
return tokenizer
82
83
@property
84
def dummy_text_encoder(self):
85
torch.manual_seed(0)
86
config = CLIPTextConfig(
87
bos_token_id=0,
88
eos_token_id=2,
89
hidden_size=self.text_embedder_hidden_size,
90
projection_dim=self.text_embedder_hidden_size,
91
intermediate_size=37,
92
layer_norm_eps=1e-05,
93
num_attention_heads=4,
94
num_hidden_layers=5,
95
pad_token_id=1,
96
vocab_size=1000,
97
)
98
return CLIPTextModelWithProjection(config)
99
100
@property
101
def dummy_image_encoder(self):
102
torch.manual_seed(0)
103
config = CLIPVisionConfig(
104
hidden_size=self.text_embedder_hidden_size,
105
projection_dim=self.text_embedder_hidden_size,
106
num_hidden_layers=5,
107
num_attention_heads=4,
108
image_size=32,
109
intermediate_size=37,
110
patch_size=1,
111
)
112
return CLIPVisionModelWithProjection(config)
113
114
@property
115
def dummy_text_proj(self):
116
torch.manual_seed(0)
117
118
model_kwargs = {
119
"clip_embeddings_dim": self.text_embedder_hidden_size,
120
"time_embed_dim": self.time_embed_dim,
121
"cross_attention_dim": self.cross_attention_dim,
122
}
123
124
model = UnCLIPTextProjModel(**model_kwargs)
125
return model
126
127
@property
128
def dummy_decoder(self):
129
torch.manual_seed(0)
130
131
model_kwargs = {
132
"sample_size": 32,
133
# RGB in channels
134
"in_channels": 3,
135
# Out channels is double in channels because predicts mean and variance
136
"out_channels": 6,
137
"down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
138
"up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
139
"mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
140
"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
141
"layers_per_block": 1,
142
"cross_attention_dim": self.cross_attention_dim,
143
"attention_head_dim": 4,
144
"resnet_time_scale_shift": "scale_shift",
145
"class_embed_type": "identity",
146
}
147
148
model = UNet2DConditionModel(**model_kwargs)
149
return model
150
151
@property
152
def dummy_super_res_kwargs(self):
153
return {
154
"sample_size": 64,
155
"layers_per_block": 1,
156
"down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
157
"up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
158
"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
159
"in_channels": 6,
160
"out_channels": 3,
161
}
162
163
@property
164
def dummy_super_res_first(self):
165
torch.manual_seed(0)
166
167
model = UNet2DModel(**self.dummy_super_res_kwargs)
168
return model
169
170
@property
171
def dummy_super_res_last(self):
172
# seeded differently to get different unet than `self.dummy_super_res_first`
173
torch.manual_seed(1)
174
175
model = UNet2DModel(**self.dummy_super_res_kwargs)
176
return model
177
178
def get_dummy_components(self):
179
decoder = self.dummy_decoder
180
text_proj = self.dummy_text_proj
181
text_encoder = self.dummy_text_encoder
182
tokenizer = self.dummy_tokenizer
183
super_res_first = self.dummy_super_res_first
184
super_res_last = self.dummy_super_res_last
185
186
decoder_scheduler = UnCLIPScheduler(
187
variance_type="learned_range",
188
prediction_type="epsilon",
189
num_train_timesteps=1000,
190
)
191
192
super_res_scheduler = UnCLIPScheduler(
193
variance_type="fixed_small_log",
194
prediction_type="epsilon",
195
num_train_timesteps=1000,
196
)
197
198
feature_extractor = CLIPImageProcessor(crop_size=32, size=32)
199
200
image_encoder = self.dummy_image_encoder
201
202
return {
203
"decoder": decoder,
204
"text_encoder": text_encoder,
205
"tokenizer": tokenizer,
206
"text_proj": text_proj,
207
"feature_extractor": feature_extractor,
208
"image_encoder": image_encoder,
209
"super_res_first": super_res_first,
210
"super_res_last": super_res_last,
211
"decoder_scheduler": decoder_scheduler,
212
"super_res_scheduler": super_res_scheduler,
213
}
214
215
def get_dummy_inputs(self, device, seed=0, pil_image=True):
216
input_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
217
if str(device).startswith("mps"):
218
generator = torch.manual_seed(seed)
219
else:
220
generator = torch.Generator(device=device).manual_seed(seed)
221
222
if pil_image:
223
input_image = input_image * 0.5 + 0.5
224
input_image = input_image.clamp(0, 1)
225
input_image = input_image.cpu().permute(0, 2, 3, 1).float().numpy()
226
input_image = DiffusionPipeline.numpy_to_pil(input_image)[0]
227
228
return {
229
"image": input_image,
230
"generator": generator,
231
"decoder_num_inference_steps": 2,
232
"super_res_num_inference_steps": 2,
233
"output_type": "np",
234
}
235
236
def test_unclip_image_variation_input_tensor(self):
237
device = "cpu"
238
239
components = self.get_dummy_components()
240
241
pipe = self.pipeline_class(**components)
242
pipe = pipe.to(device)
243
244
pipe.set_progress_bar_config(disable=None)
245
246
pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
247
248
output = pipe(**pipeline_inputs)
249
image = output.images
250
251
tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
252
253
image_from_tuple = pipe(
254
**tuple_pipeline_inputs,
255
return_dict=False,
256
)[0]
257
258
image_slice = image[0, -3:, -3:, -1]
259
image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
260
261
assert image.shape == (1, 64, 64, 3)
262
263
expected_slice = np.array(
264
[
265
0.9997,
266
0.0002,
267
0.9997,
268
0.9997,
269
0.9969,
270
0.0023,
271
0.9997,
272
0.9969,
273
0.9970,
274
]
275
)
276
277
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
278
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
279
280
def test_unclip_image_variation_input_image(self):
281
device = "cpu"
282
283
components = self.get_dummy_components()
284
285
pipe = self.pipeline_class(**components)
286
pipe = pipe.to(device)
287
288
pipe.set_progress_bar_config(disable=None)
289
290
pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
291
292
output = pipe(**pipeline_inputs)
293
image = output.images
294
295
tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
296
297
image_from_tuple = pipe(
298
**tuple_pipeline_inputs,
299
return_dict=False,
300
)[0]
301
302
image_slice = image[0, -3:, -3:, -1]
303
image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
304
305
assert image.shape == (1, 64, 64, 3)
306
307
expected_slice = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971])
308
309
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
310
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
311
312
def test_unclip_image_variation_input_list_images(self):
313
device = "cpu"
314
315
components = self.get_dummy_components()
316
317
pipe = self.pipeline_class(**components)
318
pipe = pipe.to(device)
319
320
pipe.set_progress_bar_config(disable=None)
321
322
pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
323
pipeline_inputs["image"] = [
324
pipeline_inputs["image"],
325
pipeline_inputs["image"],
326
]
327
328
output = pipe(**pipeline_inputs)
329
image = output.images
330
331
tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
332
tuple_pipeline_inputs["image"] = [
333
tuple_pipeline_inputs["image"],
334
tuple_pipeline_inputs["image"],
335
]
336
337
image_from_tuple = pipe(
338
**tuple_pipeline_inputs,
339
return_dict=False,
340
)[0]
341
342
image_slice = image[0, -3:, -3:, -1]
343
image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
344
345
assert image.shape == (2, 64, 64, 3)
346
347
expected_slice = np.array(
348
[
349
0.9997,
350
0.9989,
351
0.0008,
352
0.0021,
353
0.9960,
354
0.0018,
355
0.0014,
356
0.0002,
357
0.9933,
358
]
359
)
360
361
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
362
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
363
364
def test_unclip_passed_image_embed(self):
365
device = torch.device("cpu")
366
367
class DummyScheduler:
368
init_noise_sigma = 1
369
370
components = self.get_dummy_components()
371
372
pipe = self.pipeline_class(**components)
373
pipe = pipe.to(device)
374
375
pipe.set_progress_bar_config(disable=None)
376
377
generator = torch.Generator(device=device).manual_seed(0)
378
dtype = pipe.decoder.dtype
379
batch_size = 1
380
381
shape = (batch_size, pipe.decoder.in_channels, pipe.decoder.sample_size, pipe.decoder.sample_size)
382
decoder_latents = pipe.prepare_latents(
383
shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
384
)
385
386
shape = (
387
batch_size,
388
pipe.super_res_first.in_channels // 2,
389
pipe.super_res_first.sample_size,
390
pipe.super_res_first.sample_size,
391
)
392
super_res_latents = pipe.prepare_latents(
393
shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
394
)
395
396
pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
397
398
img_out_1 = pipe(
399
**pipeline_inputs, decoder_latents=decoder_latents, super_res_latents=super_res_latents
400
).images
401
402
pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
403
# Don't pass image, instead pass embedding
404
image = pipeline_inputs.pop("image")
405
image_embeddings = pipe.image_encoder(image).image_embeds
406
407
img_out_2 = pipe(
408
**pipeline_inputs,
409
decoder_latents=decoder_latents,
410
super_res_latents=super_res_latents,
411
image_embeddings=image_embeddings,
412
).images
413
414
# make sure passing text embeddings manually is identical
415
assert np.abs(img_out_1 - img_out_2).max() < 1e-4
416
417
# Overriding PipelineTesterMixin::test_attention_slicing_forward_pass
418
# because UnCLIP GPU undeterminism requires a looser check.
419
@skip_mps
420
def test_attention_slicing_forward_pass(self):
421
test_max_difference = torch_device == "cpu"
422
423
self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference)
424
425
# Overriding PipelineTesterMixin::test_inference_batch_single_identical
426
# because UnCLIP undeterminism requires a looser check.
427
@skip_mps
428
def test_inference_batch_single_identical(self):
429
test_max_difference = torch_device == "cpu"
430
relax_max_difference = True
431
additional_params_copy_to_batched_inputs = [
432
"decoder_num_inference_steps",
433
"super_res_num_inference_steps",
434
]
435
436
self._test_inference_batch_single_identical(
437
test_max_difference=test_max_difference,
438
relax_max_difference=relax_max_difference,
439
additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,
440
)
441
442
def test_inference_batch_consistent(self):
443
additional_params_copy_to_batched_inputs = [
444
"decoder_num_inference_steps",
445
"super_res_num_inference_steps",
446
]
447
448
if torch_device == "mps":
449
# TODO: MPS errors with larger batch sizes
450
batch_sizes = [2, 3]
451
self._test_inference_batch_consistent(
452
batch_sizes=batch_sizes,
453
additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,
454
)
455
else:
456
self._test_inference_batch_consistent(
457
additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs
458
)
459
460
@skip_mps
461
def test_dict_tuple_outputs_equivalent(self):
462
return super().test_dict_tuple_outputs_equivalent()
463
464
@skip_mps
465
def test_save_load_local(self):
466
return super().test_save_load_local()
467
468
@skip_mps
469
def test_save_load_optional_components(self):
470
return super().test_save_load_optional_components()
471
472
473
@slow
474
@require_torch_gpu
475
class UnCLIPImageVariationPipelineIntegrationTests(unittest.TestCase):
476
def tearDown(self):
477
# clean up the VRAM after each test
478
super().tearDown()
479
gc.collect()
480
torch.cuda.empty_cache()
481
482
def test_unclip_image_variation_karlo(self):
483
input_image = load_image(
484
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png"
485
)
486
expected_image = load_numpy(
487
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
488
"/unclip/karlo_v1_alpha_cat_variation_fp16.npy"
489
)
490
491
pipeline = UnCLIPImageVariationPipeline.from_pretrained(
492
"kakaobrain/karlo-v1-alpha-image-variations", torch_dtype=torch.float16
493
)
494
pipeline = pipeline.to(torch_device)
495
pipeline.set_progress_bar_config(disable=None)
496
497
generator = torch.Generator(device="cpu").manual_seed(0)
498
output = pipeline(
499
input_image,
500
generator=generator,
501
output_type="np",
502
)
503
504
image = output.images[0]
505
506
assert image.shape == (256, 256, 3)
507
508
assert_mean_pixel_difference(image, expected_image)
509
510