Ouzhang commited on
Commit
c874abc
·
verified ·
1 Parent(s): 7e060ae

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. diffusers/tests/pipelines/ace_step/__init__.py +0 -0
  2. diffusers/tests/pipelines/ace_step/test_ace_step.py +486 -0
  3. diffusers/tests/pipelines/allegro/__init__.py +0 -0
  4. diffusers/tests/pipelines/allegro/test_allegro.py +377 -0
  5. diffusers/tests/pipelines/animatediff/__init__.py +0 -0
  6. diffusers/tests/pipelines/animatediff/test_animatediff.py +621 -0
  7. diffusers/tests/pipelines/animatediff/test_animatediff_controlnet.py +527 -0
  8. diffusers/tests/pipelines/animatediff/test_animatediff_sdxl.py +286 -0
  9. diffusers/tests/pipelines/animatediff/test_animatediff_sparsectrl.py +494 -0
  10. diffusers/tests/pipelines/animatediff/test_animatediff_video2video.py +554 -0
  11. diffusers/tests/pipelines/animatediff/test_animatediff_video2video_controlnet.py +543 -0
  12. diffusers/tests/pipelines/audioldm2/__init__.py +0 -0
  13. diffusers/tests/pipelines/audioldm2/test_audioldm2.py +667 -0
  14. diffusers/tests/pipelines/bria/__init__.py +0 -0
  15. diffusers/tests/pipelines/bria/test_pipeline_bria.py +320 -0
  16. diffusers/tests/pipelines/bria_fibo/__init__.py +0 -0
  17. diffusers/tests/pipelines/bria_fibo/test_pipeline_bria_fibo.py +139 -0
  18. diffusers/tests/pipelines/chroma/__init__.py +1 -0
  19. diffusers/tests/pipelines/chroma/test_pipeline_chroma.py +161 -0
  20. diffusers/tests/pipelines/cogvideo/__init__.py +0 -0
  21. diffusers/tests/pipelines/cogvideo/test_cogvideox.py +375 -0
  22. diffusers/tests/pipelines/cogvideo/test_cogvideox_fun_control.py +330 -0
  23. diffusers/tests/pipelines/cogvideo/test_cogvideox_image2video.py +392 -0
  24. diffusers/tests/pipelines/cogvideo/test_cogvideox_video2video.py +326 -0
  25. diffusers/tests/pipelines/cogview3/__init__.py +0 -0
  26. diffusers/tests/pipelines/cogview3/test_cogview3plus.py +276 -0
  27. diffusers/tests/pipelines/cogview4/__init__.py +0 -0
  28. diffusers/tests/pipelines/cogview4/test_cogview4.py +234 -0
  29. diffusers/tests/pipelines/consisid/__init__.py +0 -0
  30. diffusers/tests/pipelines/consisid/test_consisid.py +366 -0
  31. diffusers/tests/pipelines/consistency_models/__init__.py +0 -0
  32. diffusers/tests/pipelines/consistency_models/test_consistency_models.py +309 -0
  33. diffusers/tests/pipelines/controlnet_flux/__init__.py +0 -0
  34. diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux.py +276 -0
  35. diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux_img2img.py +218 -0
  36. diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux_inpaint.py +215 -0
  37. diffusers/tests/pipelines/cosmos/test_cosmos.py +358 -0
  38. diffusers/tests/pipelines/cosmos/test_cosmos2_5_predict.py +337 -0
  39. diffusers/tests/pipelines/cosmos/test_cosmos2_5_transfer.py +440 -0
  40. diffusers/tests/pipelines/cosmos/test_cosmos2_text2image.py +342 -0
  41. diffusers/tests/pipelines/cosmos/test_cosmos2_video2world.py +356 -0
  42. diffusers/tests/pipelines/cosmos/test_cosmos_video2world.py +371 -0
  43. diffusers/tests/pipelines/ddim/__init__.py +0 -0
  44. diffusers/tests/pipelines/ddim/test_ddim.py +142 -0
  45. diffusers/tests/pipelines/ddpm/__init__.py +0 -0
  46. diffusers/tests/pipelines/ddpm/test_ddpm.py +111 -0
  47. diffusers/tests/pipelines/dit/test_dit.py +166 -0
  48. diffusers/tests/pipelines/flux/__init__.py +0 -0
  49. diffusers/tests/pipelines/flux/test_pipeline_flux.py +378 -0
  50. diffusers/tests/pipelines/flux/test_pipeline_flux_control.py +176 -0
diffusers/tests/pipelines/ace_step/__init__.py ADDED
File without changes
diffusers/tests/pipelines/ace_step/test_ace_step.py ADDED
@@ -0,0 +1,486 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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
+
17
+ import math
18
+ import unittest
19
+
20
+ import torch
21
+ from transformers import AutoTokenizer, Qwen3Config, Qwen3Model
22
+
23
+ from diffusers import AutoencoderOobleck, FlowMatchEulerDiscreteScheduler
24
+ from diffusers.models.transformers.ace_step_transformer import AceStepTransformer1DModel
25
+ from diffusers.pipelines.ace_step import (
26
+ AceStepAudioTokenDetokenizer,
27
+ AceStepAudioTokenizer,
28
+ AceStepConditionEncoder,
29
+ AceStepPipeline,
30
+ )
31
+
32
+ from ...testing_utils import enable_full_determinism
33
+ from ..test_pipelines_common import PipelineTesterMixin
34
+
35
+
36
+ enable_full_determinism()
37
+
38
+
39
+ class AceStepConditionEncoderTests(unittest.TestCase):
40
+ """Fast tests for the AceStepConditionEncoder."""
41
+
42
+ def get_tiny_config(self):
43
+ return {
44
+ "hidden_size": 32,
45
+ "intermediate_size": 64,
46
+ "text_hidden_dim": 16,
47
+ "timbre_hidden_dim": 8,
48
+ "num_lyric_encoder_hidden_layers": 2,
49
+ "num_timbre_encoder_hidden_layers": 2,
50
+ "num_attention_heads": 4,
51
+ "num_key_value_heads": 2,
52
+ "head_dim": 8,
53
+ "rope_theta": 10000.0,
54
+ "attention_bias": False,
55
+ "attention_dropout": 0.0,
56
+ "rms_norm_eps": 1e-6,
57
+ "sliding_window": 16,
58
+ }
59
+
60
+ def test_forward_shape(self):
61
+ """Test that the condition encoder produces packed hidden states."""
62
+ config = self.get_tiny_config()
63
+ encoder = AceStepConditionEncoder(**config)
64
+ encoder.eval()
65
+
66
+ batch_size = 2
67
+ text_seq_len = 8
68
+ lyric_seq_len = 12
69
+ text_dim = config["text_hidden_dim"]
70
+ timbre_dim = config["timbre_hidden_dim"]
71
+ timbre_time = 10
72
+
73
+ text_hidden_states = torch.randn(batch_size, text_seq_len, text_dim)
74
+ text_attention_mask = torch.ones(batch_size, text_seq_len)
75
+ lyric_hidden_states = torch.randn(batch_size, lyric_seq_len, text_dim)
76
+ lyric_attention_mask = torch.ones(batch_size, lyric_seq_len)
77
+
78
+ # Packed reference audio: 3 references across 2 batch items
79
+ refer_audio = torch.randn(3, timbre_time, timbre_dim)
80
+ refer_order_mask = torch.tensor([0, 0, 1], dtype=torch.long)
81
+
82
+ with torch.no_grad():
83
+ enc_hidden, enc_mask = encoder(
84
+ text_hidden_states=text_hidden_states,
85
+ text_attention_mask=text_attention_mask,
86
+ lyric_hidden_states=lyric_hidden_states,
87
+ lyric_attention_mask=lyric_attention_mask,
88
+ refer_audio_acoustic_hidden_states_packed=refer_audio,
89
+ refer_audio_order_mask=refer_order_mask,
90
+ )
91
+
92
+ # Output should be packed: batch_size x (lyric + timbre + text seq_len) x hidden_size
93
+ self.assertEqual(enc_hidden.shape[0], batch_size)
94
+ self.assertEqual(enc_hidden.shape[2], config["hidden_size"])
95
+ self.assertEqual(enc_mask.shape[0], batch_size)
96
+ self.assertEqual(enc_mask.shape[1], enc_hidden.shape[1])
97
+
98
+ def test_save_load_config(self):
99
+ """Test that the condition encoder config can be saved and loaded."""
100
+ import tempfile
101
+
102
+ config = self.get_tiny_config()
103
+ encoder = AceStepConditionEncoder(**config)
104
+
105
+ with tempfile.TemporaryDirectory() as tmpdir:
106
+ encoder.save_config(tmpdir)
107
+ loaded = AceStepConditionEncoder.from_config(tmpdir)
108
+
109
+ self.assertEqual(encoder.config.hidden_size, loaded.config.hidden_size)
110
+ self.assertEqual(encoder.config.text_hidden_dim, loaded.config.text_hidden_dim)
111
+ self.assertEqual(encoder.config.timbre_hidden_dim, loaded.config.timbre_hidden_dim)
112
+
113
+
114
+ class AceStepPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
115
+ """Fast end-to-end tests for AceStepPipeline with tiny models."""
116
+
117
+ pipeline_class = AceStepPipeline
118
+ params = frozenset(
119
+ [
120
+ "prompt",
121
+ "lyrics",
122
+ "audio_duration",
123
+ "vocal_language",
124
+ "guidance_scale",
125
+ "shift",
126
+ ]
127
+ )
128
+ batch_params = frozenset(["prompt", "lyrics"])
129
+ required_optional_params = frozenset(
130
+ [
131
+ "num_inference_steps",
132
+ "generator",
133
+ "latents",
134
+ "output_type",
135
+ "return_dict",
136
+ ]
137
+ )
138
+
139
+ # ACE-Step uses custom attention, not standard diffusers attention processors
140
+ test_attention_slicing = False
141
+ test_xformers_attention = False
142
+ supports_dduf = False
143
+
144
+ def get_dummy_components(self):
145
+ torch.manual_seed(0)
146
+ transformer = AceStepTransformer1DModel(
147
+ hidden_size=32,
148
+ intermediate_size=64,
149
+ num_hidden_layers=2,
150
+ num_attention_heads=4,
151
+ num_key_value_heads=2,
152
+ head_dim=8,
153
+ in_channels=24,
154
+ audio_acoustic_hidden_dim=8,
155
+ patch_size=2,
156
+ rope_theta=10000.0,
157
+ sliding_window=16,
158
+ )
159
+
160
+ # Create a tiny Qwen3Model for testing (matching the real Qwen3-Embedding-0.6B architecture)
161
+ torch.manual_seed(0)
162
+ qwen3_config = Qwen3Config(
163
+ hidden_size=32,
164
+ intermediate_size=64,
165
+ num_hidden_layers=2,
166
+ num_attention_heads=4,
167
+ num_key_value_heads=2,
168
+ head_dim=8,
169
+ vocab_size=151936, # Qwen3 vocab size
170
+ max_position_embeddings=256,
171
+ )
172
+ text_encoder = Qwen3Model(qwen3_config)
173
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-Embedding-0.6B")
174
+ text_hidden_dim = qwen3_config.hidden_size # 32
175
+
176
+ torch.manual_seed(0)
177
+ condition_encoder = AceStepConditionEncoder(
178
+ hidden_size=32,
179
+ intermediate_size=64,
180
+ text_hidden_dim=text_hidden_dim,
181
+ timbre_hidden_dim=8,
182
+ num_lyric_encoder_hidden_layers=2,
183
+ num_timbre_encoder_hidden_layers=2,
184
+ num_attention_heads=4,
185
+ num_key_value_heads=2,
186
+ head_dim=8,
187
+ rope_theta=10000.0,
188
+ sliding_window=16,
189
+ )
190
+
191
+ audio_tokenizer_kwargs = {
192
+ "hidden_size": 32,
193
+ "intermediate_size": 64,
194
+ "audio_acoustic_hidden_dim": 8,
195
+ "pool_window_size": 2,
196
+ "fsq_dim": 32,
197
+ "fsq_input_levels": [4, 4, 4],
198
+ "fsq_input_num_quantizers": 1,
199
+ "num_attention_pooler_hidden_layers": 1,
200
+ "num_attention_heads": 4,
201
+ "num_key_value_heads": 2,
202
+ "head_dim": 8,
203
+ "rope_theta": 10000.0,
204
+ "sliding_window": 16,
205
+ }
206
+ torch.manual_seed(0)
207
+ audio_tokenizer = AceStepAudioTokenizer(**audio_tokenizer_kwargs)
208
+ torch.manual_seed(0)
209
+ audio_token_detokenizer = AceStepAudioTokenDetokenizer(
210
+ hidden_size=32,
211
+ intermediate_size=64,
212
+ audio_acoustic_hidden_dim=8,
213
+ pool_window_size=2,
214
+ num_attention_pooler_hidden_layers=1,
215
+ num_attention_heads=4,
216
+ num_key_value_heads=2,
217
+ head_dim=8,
218
+ rope_theta=10000.0,
219
+ sliding_window=16,
220
+ )
221
+
222
+ torch.manual_seed(0)
223
+ vae = AutoencoderOobleck(
224
+ encoder_hidden_size=6,
225
+ downsampling_ratios=[1, 2],
226
+ decoder_channels=3,
227
+ decoder_input_channels=8,
228
+ audio_channels=2,
229
+ channel_multiples=[2, 4],
230
+ sampling_rate=4,
231
+ )
232
+
233
+ scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1, shift=1.0)
234
+
235
+ components = {
236
+ "transformer": transformer,
237
+ "condition_encoder": condition_encoder,
238
+ "vae": vae,
239
+ "text_encoder": text_encoder,
240
+ "tokenizer": tokenizer,
241
+ "scheduler": scheduler,
242
+ "audio_tokenizer": audio_tokenizer,
243
+ "audio_token_detokenizer": audio_token_detokenizer,
244
+ }
245
+ return components
246
+
247
+ def get_dummy_inputs(self, device, seed=0):
248
+ if str(device).startswith("mps"):
249
+ generator = torch.manual_seed(seed)
250
+ else:
251
+ generator = torch.Generator(device=device).manual_seed(seed)
252
+ inputs = {
253
+ "prompt": "A beautiful piano piece",
254
+ "lyrics": "[verse]\nSoft notes in the morning",
255
+ "audio_duration": 0.4, # Very short for fast test (10 latent frames at 25Hz)
256
+ "num_inference_steps": 2,
257
+ "generator": generator,
258
+ "max_text_length": 32,
259
+ }
260
+ return inputs
261
+
262
+ def test_ace_step_basic(self):
263
+ """Test basic text-to-music generation."""
264
+ device = "cpu"
265
+ components = self.get_dummy_components()
266
+ pipe = AceStepPipeline(**components)
267
+ pipe = pipe.to(device)
268
+ pipe.set_progress_bar_config(disable=None)
269
+
270
+ generator = torch.Generator(device=device).manual_seed(0)
271
+ output = pipe(
272
+ prompt="A beautiful piano piece",
273
+ lyrics="[verse]\nSoft notes in the morning",
274
+ audio_duration=0.4,
275
+ num_inference_steps=2,
276
+ generator=generator,
277
+ max_text_length=32,
278
+ )
279
+ audio = output.audios
280
+ self.assertIsNotNone(audio)
281
+ self.assertEqual(audio.ndim, 3) # [batch, channels, samples]
282
+
283
+ def test_ace_step_batch(self):
284
+ """Test batch generation."""
285
+ device = "cpu"
286
+ components = self.get_dummy_components()
287
+ pipe = AceStepPipeline(**components)
288
+ pipe = pipe.to(device)
289
+ pipe.set_progress_bar_config(disable=None)
290
+
291
+ generator = torch.Generator(device=device).manual_seed(42)
292
+ output = pipe(
293
+ prompt=["Piano piece", "Guitar solo"],
294
+ lyrics=["[verse]\nHello", "[chorus]\nWorld"],
295
+ audio_duration=0.4,
296
+ num_inference_steps=2,
297
+ generator=generator,
298
+ max_text_length=32,
299
+ )
300
+ audio = output.audios
301
+ self.assertIsNotNone(audio)
302
+ self.assertEqual(audio.shape[0], 2) # batch size = 2
303
+
304
+ def test_ace_step_latent_output(self):
305
+ """Test that output_type='latent' returns latents."""
306
+ device = "cpu"
307
+ components = self.get_dummy_components()
308
+ pipe = AceStepPipeline(**components)
309
+ pipe = pipe.to(device)
310
+ pipe.set_progress_bar_config(disable=None)
311
+
312
+ generator = torch.Generator(device=device).manual_seed(0)
313
+ output = pipe(
314
+ prompt="A test prompt",
315
+ lyrics="",
316
+ audio_duration=0.4,
317
+ num_inference_steps=2,
318
+ generator=generator,
319
+ output_type="latent",
320
+ max_text_length=32,
321
+ )
322
+ latents = output.audios
323
+ self.assertIsNotNone(latents)
324
+ # Latent shape: [batch, latent_length, acoustic_dim]
325
+ self.assertEqual(latents.ndim, 3)
326
+ self.assertEqual(latents.shape[0], 1)
327
+
328
+ def test_ace_step_return_dict_false(self):
329
+ """Test that return_dict=False returns a tuple."""
330
+ device = "cpu"
331
+ components = self.get_dummy_components()
332
+ pipe = AceStepPipeline(**components)
333
+ pipe = pipe.to(device)
334
+ pipe.set_progress_bar_config(disable=None)
335
+
336
+ generator = torch.Generator(device=device).manual_seed(0)
337
+ output = pipe(
338
+ prompt="A test prompt",
339
+ lyrics="",
340
+ audio_duration=0.4,
341
+ num_inference_steps=2,
342
+ generator=generator,
343
+ return_dict=False,
344
+ max_text_length=32,
345
+ )
346
+ self.assertIsInstance(output, tuple)
347
+ self.assertEqual(len(output), 1)
348
+
349
+ def test_audio_codes_cover_path(self):
350
+ components = self.get_dummy_components()
351
+ pipe = AceStepPipeline(**components)
352
+
353
+ output = pipe(
354
+ prompt="A test prompt",
355
+ lyrics="",
356
+ audio_codes="<|audio_code_1|><|audio_code_2|>",
357
+ num_inference_steps=1,
358
+ output_type="latent",
359
+ max_text_length=32,
360
+ )
361
+
362
+ self.assertEqual(output.audios.shape[1], 4)
363
+
364
+ def test_save_load_local(self, expected_max_difference=7e-3):
365
+ # increase tolerance to account for large composite model
366
+ super().test_save_load_local(expected_max_difference=expected_max_difference)
367
+
368
+ def test_save_load_optional_components(self, expected_max_difference=7e-3):
369
+ # increase tolerance to account for large composite model
370
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
371
+
372
+ def test_inference_batch_single_identical(self, batch_size=3, expected_max_diff=7e-3):
373
+ # increase tolerance for audio pipeline
374
+ super().test_inference_batch_single_identical(batch_size=batch_size, expected_max_diff=expected_max_diff)
375
+
376
+ def test_dict_tuple_outputs_equivalent(self, expected_slice=None, expected_max_difference=7e-3):
377
+ # increase tolerance for audio pipeline
378
+ super().test_dict_tuple_outputs_equivalent(
379
+ expected_slice=expected_slice, expected_max_difference=expected_max_difference
380
+ )
381
+
382
+ # ACE-Step does not use num_images_per_prompt
383
+ def test_num_images_per_prompt(self):
384
+ pass
385
+
386
+ # ACE-Step does not use standard schedulers
387
+ @unittest.skip("ACE-Step uses built-in flow matching schedule, not diffusers schedulers")
388
+ def test_karras_schedulers_shape(self):
389
+ pass
390
+
391
+ # ACE-Step does not support prompt_embeds directly
392
+ @unittest.skip("ACE-Step does not support prompt_embeds / negative_prompt_embeds")
393
+ def test_cfg(self):
394
+ pass
395
+
396
+ def test_float16_inference(self, expected_max_diff=5e-2):
397
+ super().test_float16_inference(expected_max_diff=expected_max_diff)
398
+
399
+ @unittest.skip(
400
+ "ACE-Step __call__ does not accept prompt_embeds, so encode_prompt isolation test is not applicable"
401
+ )
402
+ def test_encode_prompt_works_in_isolation(self):
403
+ pass
404
+
405
+ @unittest.skip("Sequential CPU offloading produces NaN with tiny random models")
406
+ def test_sequential_cpu_offload_forward_pass(self):
407
+ pass
408
+
409
+ @unittest.skip("Sequential CPU offloading produces NaN with tiny random models")
410
+ def test_sequential_offload_forward_pass_twice(self):
411
+ pass
412
+
413
+ def test_encode_prompt(self):
414
+ """Test that encode_prompt returns correct shapes."""
415
+ device = "cpu"
416
+ components = self.get_dummy_components()
417
+ pipe = AceStepPipeline(**components)
418
+ pipe = pipe.to(device)
419
+
420
+ text_hidden, text_mask, lyric_hidden, lyric_mask = pipe.encode_prompt(
421
+ prompt="A test prompt",
422
+ lyrics="[verse]\nHello world",
423
+ device=device,
424
+ max_text_length=32,
425
+ max_lyric_length=64,
426
+ )
427
+
428
+ self.assertEqual(text_hidden.ndim, 3) # [batch, seq_len, hidden_dim]
429
+ self.assertEqual(text_mask.ndim, 2) # [batch, seq_len]
430
+ self.assertEqual(lyric_hidden.ndim, 3)
431
+ self.assertEqual(lyric_mask.ndim, 2)
432
+ self.assertEqual(text_hidden.shape[0], 1)
433
+ self.assertEqual(lyric_hidden.shape[0], 1)
434
+
435
+ def test_prepare_latents(self):
436
+ """Test that prepare_latents returns correct shapes."""
437
+ device = "cpu"
438
+ components = self.get_dummy_components()
439
+ pipe = AceStepPipeline(**components)
440
+ pipe = pipe.to(device)
441
+
442
+ latents = pipe.prepare_latents(
443
+ batch_size=2,
444
+ audio_duration=1.0,
445
+ dtype=torch.float32,
446
+ device=device,
447
+ )
448
+
449
+ expected_length = math.ceil(1.0 * pipe.latents_per_second)
450
+ self.assertEqual(latents.shape, (2, expected_length, 8))
451
+
452
+ def test_timestep_schedule(self):
453
+ """Test that the timestep schedule is generated correctly."""
454
+ components = self.get_dummy_components()
455
+ pipe = AceStepPipeline(**components)
456
+
457
+ # Test standard schedule
458
+ schedule = pipe._get_timestep_schedule(num_inference_steps=8, shift=3.0)
459
+ self.assertEqual(len(schedule), 8)
460
+ self.assertAlmostEqual(schedule[0].item(), 1.0, places=5)
461
+
462
+ # Test truncated schedule
463
+ schedule = pipe._get_timestep_schedule(num_inference_steps=4, shift=3.0)
464
+ self.assertEqual(len(schedule), 4)
465
+
466
+ def test_format_prompt(self):
467
+ """Test that prompt formatting works correctly."""
468
+ components = self.get_dummy_components()
469
+ pipe = AceStepPipeline(**components)
470
+
471
+ text, lyrics = pipe._format_prompt(
472
+ prompt="A piano piece",
473
+ lyrics="[verse]\nHello",
474
+ vocal_language="en",
475
+ audio_duration=30.0,
476
+ )
477
+
478
+ self.assertIn("A piano piece", text)
479
+ self.assertIn("30 seconds", text)
480
+ self.assertIn("[verse]", lyrics)
481
+ self.assertIn("Hello", lyrics)
482
+ self.assertIn("en", lyrics)
483
+
484
+
485
+ if __name__ == "__main__":
486
+ unittest.main()
diffusers/tests/pipelines/allegro/__init__.py ADDED
File without changes
diffusers/tests/pipelines/allegro/test_allegro.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import inspect
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import AutoTokenizer, T5Config, T5EncoderModel
24
+
25
+ from diffusers import AllegroPipeline, AllegroTransformer3DModel, AutoencoderKLAllegro, DDIMScheduler
26
+
27
+ from ...testing_utils import (
28
+ backend_empty_cache,
29
+ enable_full_determinism,
30
+ numpy_cosine_similarity_distance,
31
+ require_hf_hub_version_greater,
32
+ require_torch_accelerator,
33
+ require_transformers_version_greater,
34
+ slow,
35
+ torch_device,
36
+ )
37
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
38
+ from ..test_pipelines_common import PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, to_np
39
+
40
+
41
+ enable_full_determinism()
42
+
43
+
44
+ class AllegroPipelineFastTests(PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, unittest.TestCase):
45
+ pipeline_class = AllegroPipeline
46
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
47
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
48
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
49
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
50
+ required_optional_params = frozenset(
51
+ [
52
+ "num_inference_steps",
53
+ "generator",
54
+ "latents",
55
+ "return_dict",
56
+ "callback_on_step_end",
57
+ "callback_on_step_end_tensor_inputs",
58
+ ]
59
+ )
60
+ test_xformers_attention = False
61
+ test_layerwise_casting = True
62
+ test_group_offloading = True
63
+
64
+ def get_dummy_components(self, num_layers: int = 1):
65
+ torch.manual_seed(0)
66
+ transformer = AllegroTransformer3DModel(
67
+ num_attention_heads=2,
68
+ attention_head_dim=12,
69
+ in_channels=4,
70
+ out_channels=4,
71
+ num_layers=num_layers,
72
+ cross_attention_dim=24,
73
+ sample_width=8,
74
+ sample_height=8,
75
+ sample_frames=8,
76
+ caption_channels=24,
77
+ )
78
+
79
+ torch.manual_seed(0)
80
+ vae = AutoencoderKLAllegro(
81
+ in_channels=3,
82
+ out_channels=3,
83
+ down_block_types=(
84
+ "AllegroDownBlock3D",
85
+ "AllegroDownBlock3D",
86
+ "AllegroDownBlock3D",
87
+ "AllegroDownBlock3D",
88
+ ),
89
+ up_block_types=(
90
+ "AllegroUpBlock3D",
91
+ "AllegroUpBlock3D",
92
+ "AllegroUpBlock3D",
93
+ "AllegroUpBlock3D",
94
+ ),
95
+ block_out_channels=(8, 8, 8, 8),
96
+ latent_channels=4,
97
+ layers_per_block=1,
98
+ norm_num_groups=2,
99
+ temporal_compression_ratio=4,
100
+ )
101
+
102
+ # TODO(aryan): Only for now, since VAE decoding without tiling is not yet implemented here
103
+ vae.enable_tiling()
104
+
105
+ torch.manual_seed(0)
106
+ scheduler = DDIMScheduler()
107
+
108
+ text_encoder_config = T5Config(
109
+ **{
110
+ "d_ff": 37,
111
+ "d_kv": 8,
112
+ "d_model": 24,
113
+ "num_decoder_layers": 2,
114
+ "num_heads": 4,
115
+ "num_layers": 2,
116
+ "relative_attention_num_buckets": 8,
117
+ "vocab_size": 1103,
118
+ }
119
+ )
120
+ text_encoder = T5EncoderModel(text_encoder_config)
121
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
122
+
123
+ components = {
124
+ "transformer": transformer,
125
+ "vae": vae,
126
+ "scheduler": scheduler,
127
+ "text_encoder": text_encoder,
128
+ "tokenizer": tokenizer,
129
+ }
130
+ return components
131
+
132
+ def get_dummy_inputs(self, device, seed=0):
133
+ if str(device).startswith("mps"):
134
+ generator = torch.manual_seed(seed)
135
+ else:
136
+ generator = torch.Generator(device=device).manual_seed(seed)
137
+
138
+ inputs = {
139
+ "prompt": "dance monkey",
140
+ "negative_prompt": "",
141
+ "generator": generator,
142
+ "num_inference_steps": 2,
143
+ "guidance_scale": 6.0,
144
+ "height": 16,
145
+ "width": 16,
146
+ "num_frames": 8,
147
+ "max_sequence_length": 16,
148
+ "output_type": "pt",
149
+ }
150
+
151
+ return inputs
152
+
153
+ @unittest.skip("Decoding without tiling is not yet implemented")
154
+ def test_save_load_local(self):
155
+ pass
156
+
157
+ @unittest.skip("Decoding without tiling is not yet implemented")
158
+ def test_save_load_optional_components(self):
159
+ pass
160
+
161
+ @unittest.skip("Decoding without tiling is not yet implemented")
162
+ def test_pipeline_with_accelerator_device_map(self):
163
+ pass
164
+
165
+ def test_inference(self):
166
+ device = "cpu"
167
+
168
+ components = self.get_dummy_components()
169
+ pipe = self.pipeline_class(**components)
170
+ pipe.to(device)
171
+ pipe.set_progress_bar_config(disable=None)
172
+
173
+ inputs = self.get_dummy_inputs(device)
174
+ video = pipe(**inputs).frames
175
+ generated_video = video[0]
176
+
177
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
178
+ expected_video = torch.randn(8, 3, 16, 16)
179
+ max_diff = np.abs(generated_video - expected_video).max()
180
+ self.assertLessEqual(max_diff, 1e10)
181
+
182
+ def test_callback_inputs(self):
183
+ sig = inspect.signature(self.pipeline_class.__call__)
184
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
185
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
186
+
187
+ if not (has_callback_tensor_inputs and has_callback_step_end):
188
+ return
189
+
190
+ components = self.get_dummy_components()
191
+ pipe = self.pipeline_class(**components)
192
+ pipe = pipe.to(torch_device)
193
+ pipe.set_progress_bar_config(disable=None)
194
+ self.assertTrue(
195
+ hasattr(pipe, "_callback_tensor_inputs"),
196
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
197
+ )
198
+
199
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
200
+ # iterate over callback args
201
+ for tensor_name, tensor_value in callback_kwargs.items():
202
+ # check that we're only passing in allowed tensor inputs
203
+ assert tensor_name in pipe._callback_tensor_inputs
204
+
205
+ return callback_kwargs
206
+
207
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
208
+ for tensor_name in pipe._callback_tensor_inputs:
209
+ assert tensor_name in callback_kwargs
210
+
211
+ # iterate over callback args
212
+ for tensor_name, tensor_value in callback_kwargs.items():
213
+ # check that we're only passing in allowed tensor inputs
214
+ assert tensor_name in pipe._callback_tensor_inputs
215
+
216
+ return callback_kwargs
217
+
218
+ inputs = self.get_dummy_inputs(torch_device)
219
+
220
+ # Test passing in a subset
221
+ inputs["callback_on_step_end"] = callback_inputs_subset
222
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
223
+ output = pipe(**inputs)[0]
224
+
225
+ # Test passing in a everything
226
+ inputs["callback_on_step_end"] = callback_inputs_all
227
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
228
+ output = pipe(**inputs)[0]
229
+
230
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
231
+ is_last = i == (pipe.num_timesteps - 1)
232
+ if is_last:
233
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
234
+ return callback_kwargs
235
+
236
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
237
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
238
+ output = pipe(**inputs)[0]
239
+ assert output.abs().sum() < 1e10
240
+
241
+ def test_inference_batch_single_identical(self):
242
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
243
+
244
+ def test_attention_slicing_forward_pass(
245
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
246
+ ):
247
+ if not self.test_attention_slicing:
248
+ return
249
+
250
+ components = self.get_dummy_components()
251
+ pipe = self.pipeline_class(**components)
252
+ for component in pipe.components.values():
253
+ if hasattr(component, "set_default_attn_processor"):
254
+ component.set_default_attn_processor()
255
+ pipe.to(torch_device)
256
+ pipe.set_progress_bar_config(disable=None)
257
+
258
+ generator_device = "cpu"
259
+ inputs = self.get_dummy_inputs(generator_device)
260
+ output_without_slicing = pipe(**inputs)[0]
261
+
262
+ pipe.enable_attention_slicing(slice_size=1)
263
+ inputs = self.get_dummy_inputs(generator_device)
264
+ output_with_slicing1 = pipe(**inputs)[0]
265
+
266
+ pipe.enable_attention_slicing(slice_size=2)
267
+ inputs = self.get_dummy_inputs(generator_device)
268
+ output_with_slicing2 = pipe(**inputs)[0]
269
+
270
+ if test_max_difference:
271
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
272
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
273
+ self.assertLess(
274
+ max(max_diff1, max_diff2),
275
+ expected_max_diff,
276
+ "Attention slicing should not affect the inference results",
277
+ )
278
+
279
+ # TODO(aryan)
280
+ @unittest.skip("Decoding without tiling is not yet implemented.")
281
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
282
+ generator_device = "cpu"
283
+ components = self.get_dummy_components()
284
+
285
+ pipe = self.pipeline_class(**components)
286
+ pipe.to("cpu")
287
+ pipe.set_progress_bar_config(disable=None)
288
+
289
+ # Without tiling
290
+ inputs = self.get_dummy_inputs(generator_device)
291
+ inputs["height"] = inputs["width"] = 128
292
+ output_without_tiling = pipe(**inputs)[0]
293
+
294
+ # With tiling
295
+ pipe.vae.enable_tiling(
296
+ tile_sample_min_height=96,
297
+ tile_sample_min_width=96,
298
+ tile_overlap_factor_height=1 / 12,
299
+ tile_overlap_factor_width=1 / 12,
300
+ )
301
+ inputs = self.get_dummy_inputs(generator_device)
302
+ inputs["height"] = inputs["width"] = 128
303
+ output_with_tiling = pipe(**inputs)[0]
304
+
305
+ self.assertLess(
306
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
307
+ expected_diff_max,
308
+ "VAE tiling should not affect the inference results",
309
+ )
310
+
311
+ @require_hf_hub_version_greater("0.26.5")
312
+ @require_transformers_version_greater("4.47.1")
313
+ def test_save_load_dduf(self):
314
+ # reimplement because it needs `enable_tiling()` on the loaded pipe.
315
+ from huggingface_hub import export_folder_as_dduf
316
+
317
+ components = self.get_dummy_components()
318
+ pipe = self.pipeline_class(**components)
319
+ pipe = pipe.to(torch_device)
320
+ pipe.set_progress_bar_config(disable=None)
321
+
322
+ inputs = self.get_dummy_inputs(device="cpu")
323
+ inputs.pop("generator")
324
+ inputs["generator"] = torch.manual_seed(0)
325
+
326
+ pipeline_out = pipe(**inputs)[0].cpu()
327
+
328
+ with tempfile.TemporaryDirectory() as tmpdir:
329
+ dduf_filename = os.path.join(tmpdir, f"{pipe.__class__.__name__.lower()}.dduf")
330
+ pipe.save_pretrained(tmpdir, safe_serialization=True)
331
+ export_folder_as_dduf(dduf_filename, folder_path=tmpdir)
332
+ loaded_pipe = self.pipeline_class.from_pretrained(tmpdir, dduf_file=dduf_filename).to(torch_device)
333
+
334
+ loaded_pipe.vae.enable_tiling()
335
+ inputs["generator"] = torch.manual_seed(0)
336
+ loaded_pipeline_out = loaded_pipe(**inputs)[0].cpu()
337
+
338
+ assert np.allclose(pipeline_out, loaded_pipeline_out)
339
+
340
+
341
+ @slow
342
+ @require_torch_accelerator
343
+ class AllegroPipelineIntegrationTests(unittest.TestCase):
344
+ prompt = "A painting of a squirrel eating a burger."
345
+
346
+ def setUp(self):
347
+ super().setUp()
348
+ gc.collect()
349
+ backend_empty_cache(torch_device)
350
+
351
+ def tearDown(self):
352
+ super().tearDown()
353
+ gc.collect()
354
+ backend_empty_cache(torch_device)
355
+
356
+ def test_allegro(self):
357
+ generator = torch.Generator("cpu").manual_seed(0)
358
+
359
+ pipe = AllegroPipeline.from_pretrained("rhymes-ai/Allegro", torch_dtype=torch.float16)
360
+ pipe.enable_model_cpu_offload(device=torch_device)
361
+ prompt = self.prompt
362
+
363
+ videos = pipe(
364
+ prompt=prompt,
365
+ height=720,
366
+ width=1280,
367
+ num_frames=88,
368
+ generator=generator,
369
+ num_inference_steps=2,
370
+ output_type="pt",
371
+ ).frames
372
+
373
+ video = videos[0]
374
+ expected_video = torch.randn(1, 88, 720, 1280, 3).numpy()
375
+
376
+ max_diff = numpy_cosine_similarity_distance(video, expected_video)
377
+ assert max_diff < 1e-3, f"Max diff is too high. got {video}"
diffusers/tests/pipelines/animatediff/__init__.py ADDED
File without changes
diffusers/tests/pipelines/animatediff/test_animatediff.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import unittest
3
+
4
+ import numpy as np
5
+ import torch
6
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
7
+
8
+ import diffusers
9
+ from diffusers import (
10
+ AnimateDiffPipeline,
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DPMSolverMultistepScheduler,
14
+ LCMScheduler,
15
+ MotionAdapter,
16
+ StableDiffusionPipeline,
17
+ UNet2DConditionModel,
18
+ UNetMotionModel,
19
+ )
20
+ from diffusers.models.attention import FreeNoiseTransformerBlock
21
+ from diffusers.utils import is_xformers_available, logging
22
+
23
+ from ...testing_utils import (
24
+ backend_empty_cache,
25
+ numpy_cosine_similarity_distance,
26
+ require_accelerator,
27
+ require_torch_accelerator,
28
+ slow,
29
+ torch_device,
30
+ )
31
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
32
+ from ..test_pipelines_common import (
33
+ IPAdapterTesterMixin,
34
+ PipelineFromPipeTesterMixin,
35
+ PipelineTesterMixin,
36
+ SDFunctionTesterMixin,
37
+ )
38
+
39
+
40
+ def to_np(tensor):
41
+ if isinstance(tensor, torch.Tensor):
42
+ tensor = tensor.detach().cpu().numpy()
43
+
44
+ return tensor
45
+
46
+
47
+ class AnimateDiffPipelineFastTests(
48
+ IPAdapterTesterMixin, SDFunctionTesterMixin, PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase
49
+ ):
50
+ pipeline_class = AnimateDiffPipeline
51
+ params = TEXT_TO_IMAGE_PARAMS
52
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
53
+ required_optional_params = frozenset(
54
+ [
55
+ "num_inference_steps",
56
+ "generator",
57
+ "latents",
58
+ "return_dict",
59
+ "callback_on_step_end",
60
+ "callback_on_step_end_tensor_inputs",
61
+ ]
62
+ )
63
+ test_layerwise_casting = True
64
+ test_group_offloading = True
65
+
66
+ def get_dummy_components(self):
67
+ cross_attention_dim = 8
68
+ block_out_channels = (8, 8)
69
+
70
+ torch.manual_seed(0)
71
+ unet = UNet2DConditionModel(
72
+ block_out_channels=block_out_channels,
73
+ layers_per_block=2,
74
+ sample_size=8,
75
+ in_channels=4,
76
+ out_channels=4,
77
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
78
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
79
+ cross_attention_dim=cross_attention_dim,
80
+ norm_num_groups=2,
81
+ )
82
+ scheduler = DDIMScheduler(
83
+ beta_start=0.00085,
84
+ beta_end=0.012,
85
+ beta_schedule="linear",
86
+ clip_sample=False,
87
+ )
88
+ torch.manual_seed(0)
89
+ vae = AutoencoderKL(
90
+ block_out_channels=block_out_channels,
91
+ in_channels=3,
92
+ out_channels=3,
93
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
94
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
95
+ latent_channels=4,
96
+ norm_num_groups=2,
97
+ )
98
+ torch.manual_seed(0)
99
+ text_encoder_config = CLIPTextConfig(
100
+ bos_token_id=0,
101
+ eos_token_id=2,
102
+ hidden_size=cross_attention_dim,
103
+ intermediate_size=37,
104
+ layer_norm_eps=1e-05,
105
+ num_attention_heads=4,
106
+ num_hidden_layers=5,
107
+ pad_token_id=1,
108
+ vocab_size=1000,
109
+ )
110
+ text_encoder = CLIPTextModel(text_encoder_config)
111
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
112
+ torch.manual_seed(0)
113
+ motion_adapter = MotionAdapter(
114
+ block_out_channels=block_out_channels,
115
+ motion_layers_per_block=2,
116
+ motion_norm_num_groups=2,
117
+ motion_num_attention_heads=4,
118
+ )
119
+
120
+ components = {
121
+ "unet": unet,
122
+ "scheduler": scheduler,
123
+ "vae": vae,
124
+ "motion_adapter": motion_adapter,
125
+ "text_encoder": text_encoder,
126
+ "tokenizer": tokenizer,
127
+ "feature_extractor": None,
128
+ "image_encoder": None,
129
+ }
130
+ return components
131
+
132
+ def get_dummy_inputs(self, device, seed=0):
133
+ if str(device).startswith("mps"):
134
+ generator = torch.manual_seed(seed)
135
+ else:
136
+ generator = torch.Generator(device=device).manual_seed(seed)
137
+
138
+ inputs = {
139
+ "prompt": "A painting of a squirrel eating a burger",
140
+ "generator": generator,
141
+ "num_inference_steps": 2,
142
+ "guidance_scale": 7.5,
143
+ "output_type": "pt",
144
+ }
145
+ return inputs
146
+
147
+ def test_from_pipe_consistent_config(self):
148
+ assert self.original_pipeline_class == StableDiffusionPipeline
149
+ original_repo = "hf-internal-testing/tinier-stable-diffusion-pipe"
150
+ original_kwargs = {"requires_safety_checker": False}
151
+
152
+ # create original_pipeline_class(sd)
153
+ pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)
154
+
155
+ # original_pipeline_class(sd) -> pipeline_class
156
+ pipe_components = self.get_dummy_components()
157
+ pipe_additional_components = {}
158
+ for name, component in pipe_components.items():
159
+ if name not in pipe_original.components:
160
+ pipe_additional_components[name] = component
161
+
162
+ pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)
163
+
164
+ # pipeline_class -> original_pipeline_class(sd)
165
+ original_pipe_additional_components = {}
166
+ for name, component in pipe_original.components.items():
167
+ if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
168
+ original_pipe_additional_components[name] = component
169
+
170
+ pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)
171
+
172
+ # compare the config
173
+ original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
174
+ original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
175
+ assert original_config_2 == original_config
176
+
177
+ def test_motion_unet_loading(self):
178
+ components = self.get_dummy_components()
179
+ pipe = AnimateDiffPipeline(**components)
180
+
181
+ assert isinstance(pipe.unet, UNetMotionModel)
182
+
183
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
184
+ def test_attention_slicing_forward_pass(self):
185
+ pass
186
+
187
+ def test_ip_adapter(self):
188
+ expected_pipe_slice = None
189
+ if torch_device == "cpu":
190
+ expected_pipe_slice = np.array(
191
+ [
192
+ 0.5216,
193
+ 0.5620,
194
+ 0.4927,
195
+ 0.5082,
196
+ 0.4786,
197
+ 0.5932,
198
+ 0.5125,
199
+ 0.4514,
200
+ 0.5315,
201
+ 0.4694,
202
+ 0.3276,
203
+ 0.4863,
204
+ 0.3920,
205
+ 0.3684,
206
+ 0.5745,
207
+ 0.4499,
208
+ 0.5081,
209
+ 0.5414,
210
+ 0.6014,
211
+ 0.5062,
212
+ 0.3630,
213
+ 0.5296,
214
+ 0.6018,
215
+ 0.5098,
216
+ 0.4948,
217
+ 0.5101,
218
+ 0.5620,
219
+ ]
220
+ )
221
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
222
+
223
+ def test_dict_tuple_outputs_equivalent(self):
224
+ expected_slice = None
225
+ if torch_device == "cpu":
226
+ expected_slice = np.array([0.5125, 0.4514, 0.5315, 0.4499, 0.5081, 0.5414, 0.4948, 0.5101, 0.5620])
227
+ return super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
228
+
229
+ def test_inference_batch_single_identical(
230
+ self,
231
+ batch_size=2,
232
+ expected_max_diff=1e-4,
233
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
234
+ ):
235
+ components = self.get_dummy_components()
236
+ pipe = self.pipeline_class(**components)
237
+ for components in pipe.components.values():
238
+ if hasattr(components, "set_default_attn_processor"):
239
+ components.set_default_attn_processor()
240
+
241
+ pipe.to(torch_device)
242
+ pipe.set_progress_bar_config(disable=None)
243
+ inputs = self.get_dummy_inputs(torch_device)
244
+ # Reset generator in case it is has been used in self.get_dummy_inputs
245
+ inputs["generator"] = self.get_generator(0)
246
+
247
+ logger = logging.get_logger(pipe.__module__)
248
+ logger.setLevel(level=diffusers.logging.FATAL)
249
+
250
+ # batchify inputs
251
+ batched_inputs = {}
252
+ batched_inputs.update(inputs)
253
+
254
+ for name in self.batch_params:
255
+ if name not in inputs:
256
+ continue
257
+
258
+ value = inputs[name]
259
+ if name == "prompt":
260
+ len_prompt = len(value)
261
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
262
+ batched_inputs[name][-1] = 100 * "very long"
263
+
264
+ else:
265
+ batched_inputs[name] = batch_size * [value]
266
+
267
+ if "generator" in inputs:
268
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
269
+
270
+ if "batch_size" in inputs:
271
+ batched_inputs["batch_size"] = batch_size
272
+
273
+ for arg in additional_params_copy_to_batched_inputs:
274
+ batched_inputs[arg] = inputs[arg]
275
+
276
+ output = pipe(**inputs)
277
+ output_batch = pipe(**batched_inputs)
278
+
279
+ assert output_batch[0].shape[0] == batch_size
280
+
281
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
282
+ assert max_diff < expected_max_diff
283
+
284
+ @require_accelerator
285
+ def test_to_device(self):
286
+ components = self.get_dummy_components()
287
+ pipe = self.pipeline_class(**components)
288
+ pipe.set_progress_bar_config(disable=None)
289
+
290
+ pipe.to("cpu")
291
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
292
+ model_devices = [
293
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
294
+ ]
295
+ self.assertTrue(all(device == "cpu" for device in model_devices))
296
+
297
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
298
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
299
+
300
+ pipe.to(torch_device)
301
+ model_devices = [
302
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
303
+ ]
304
+ self.assertTrue(all(device == torch_device for device in model_devices))
305
+
306
+ output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
307
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
308
+
309
+ def test_to_dtype(self):
310
+ components = self.get_dummy_components()
311
+ pipe = self.pipeline_class(**components)
312
+ pipe.set_progress_bar_config(disable=None)
313
+
314
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
315
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
316
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
317
+
318
+ pipe.to(dtype=torch.float16)
319
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
320
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
321
+
322
+ def test_prompt_embeds(self):
323
+ components = self.get_dummy_components()
324
+ pipe = self.pipeline_class(**components)
325
+ pipe.set_progress_bar_config(disable=None)
326
+ pipe.to(torch_device)
327
+
328
+ inputs = self.get_dummy_inputs(torch_device)
329
+ inputs.pop("prompt")
330
+ inputs["prompt_embeds"] = torch.randn((1, 4, pipe.text_encoder.config.hidden_size), device=torch_device)
331
+ pipe(**inputs)
332
+
333
+ def test_free_init(self):
334
+ components = self.get_dummy_components()
335
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
336
+ pipe.set_progress_bar_config(disable=None)
337
+ pipe.to(torch_device)
338
+
339
+ inputs_normal = self.get_dummy_inputs(torch_device)
340
+ frames_normal = pipe(**inputs_normal).frames[0]
341
+
342
+ pipe.enable_free_init(
343
+ num_iters=2,
344
+ use_fast_sampling=True,
345
+ method="butterworth",
346
+ order=4,
347
+ spatial_stop_frequency=0.25,
348
+ temporal_stop_frequency=0.25,
349
+ )
350
+ inputs_enable_free_init = self.get_dummy_inputs(torch_device)
351
+ frames_enable_free_init = pipe(**inputs_enable_free_init).frames[0]
352
+
353
+ pipe.disable_free_init()
354
+ inputs_disable_free_init = self.get_dummy_inputs(torch_device)
355
+ frames_disable_free_init = pipe(**inputs_disable_free_init).frames[0]
356
+
357
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
358
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_init)).max()
359
+ self.assertGreater(
360
+ sum_enabled, 1e1, "Enabling of FreeInit should lead to results different from the default pipeline results"
361
+ )
362
+ self.assertLess(
363
+ max_diff_disabled,
364
+ 1e-4,
365
+ "Disabling of FreeInit should lead to results similar to the default pipeline results",
366
+ )
367
+
368
+ def test_free_init_with_schedulers(self):
369
+ components = self.get_dummy_components()
370
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
371
+ pipe.set_progress_bar_config(disable=None)
372
+ pipe.to(torch_device)
373
+
374
+ inputs_normal = self.get_dummy_inputs(torch_device)
375
+ frames_normal = pipe(**inputs_normal).frames[0]
376
+
377
+ schedulers_to_test = [
378
+ DPMSolverMultistepScheduler.from_config(
379
+ components["scheduler"].config,
380
+ timestep_spacing="linspace",
381
+ beta_schedule="linear",
382
+ algorithm_type="dpmsolver++",
383
+ steps_offset=1,
384
+ clip_sample=False,
385
+ ),
386
+ LCMScheduler.from_config(
387
+ components["scheduler"].config,
388
+ timestep_spacing="linspace",
389
+ beta_schedule="linear",
390
+ steps_offset=1,
391
+ clip_sample=False,
392
+ ),
393
+ ]
394
+ components.pop("scheduler")
395
+
396
+ for scheduler in schedulers_to_test:
397
+ components["scheduler"] = scheduler
398
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
399
+ pipe.set_progress_bar_config(disable=None)
400
+ pipe.to(torch_device)
401
+
402
+ pipe.enable_free_init(num_iters=2, use_fast_sampling=False)
403
+
404
+ inputs = self.get_dummy_inputs(torch_device)
405
+ frames_enable_free_init = pipe(**inputs).frames[0]
406
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
407
+
408
+ self.assertGreater(
409
+ sum_enabled,
410
+ 1e1,
411
+ "Enabling of FreeInit should lead to results different from the default pipeline results",
412
+ )
413
+
414
+ def test_free_noise_blocks(self):
415
+ components = self.get_dummy_components()
416
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
417
+ pipe.set_progress_bar_config(disable=None)
418
+ pipe.to(torch_device)
419
+
420
+ pipe.enable_free_noise()
421
+ for block in pipe.unet.down_blocks:
422
+ for motion_module in block.motion_modules:
423
+ for transformer_block in motion_module.transformer_blocks:
424
+ self.assertTrue(
425
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
426
+ "Motion module transformer blocks must be an instance of `FreeNoiseTransformerBlock` after enabling FreeNoise.",
427
+ )
428
+
429
+ pipe.disable_free_noise()
430
+ for block in pipe.unet.down_blocks:
431
+ for motion_module in block.motion_modules:
432
+ for transformer_block in motion_module.transformer_blocks:
433
+ self.assertFalse(
434
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
435
+ "Motion module transformer blocks must not be an instance of `FreeNoiseTransformerBlock` after disabling FreeNoise.",
436
+ )
437
+
438
+ def test_free_noise(self):
439
+ components = self.get_dummy_components()
440
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
441
+ pipe.set_progress_bar_config(disable=None)
442
+ pipe.to(torch_device)
443
+
444
+ inputs_normal = self.get_dummy_inputs(torch_device)
445
+ frames_normal = pipe(**inputs_normal).frames[0]
446
+
447
+ for context_length in [8, 9]:
448
+ for context_stride in [4, 6]:
449
+ pipe.enable_free_noise(context_length, context_stride)
450
+
451
+ inputs_enable_free_noise = self.get_dummy_inputs(torch_device)
452
+ frames_enable_free_noise = pipe(**inputs_enable_free_noise).frames[0]
453
+
454
+ pipe.disable_free_noise()
455
+
456
+ inputs_disable_free_noise = self.get_dummy_inputs(torch_device)
457
+ frames_disable_free_noise = pipe(**inputs_disable_free_noise).frames[0]
458
+
459
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_noise)).sum()
460
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_noise)).max()
461
+ self.assertGreater(
462
+ sum_enabled,
463
+ 1e1,
464
+ "Enabling of FreeNoise should lead to results different from the default pipeline results",
465
+ )
466
+ self.assertLess(
467
+ max_diff_disabled,
468
+ 1e-4,
469
+ "Disabling of FreeNoise should lead to results similar to the default pipeline results",
470
+ )
471
+
472
+ def test_free_noise_split_inference(self):
473
+ components = self.get_dummy_components()
474
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
475
+ pipe.set_progress_bar_config(disable=None)
476
+ pipe.to(torch_device)
477
+
478
+ pipe.enable_free_noise(8, 4)
479
+
480
+ inputs_normal = self.get_dummy_inputs(torch_device)
481
+ frames_normal = pipe(**inputs_normal).frames[0]
482
+
483
+ # Test FreeNoise with split inference memory-optimization
484
+ pipe.enable_free_noise_split_inference(spatial_split_size=16, temporal_split_size=4)
485
+
486
+ inputs_enable_split_inference = self.get_dummy_inputs(torch_device)
487
+ frames_enable_split_inference = pipe(**inputs_enable_split_inference).frames[0]
488
+
489
+ sum_split_inference = np.abs(to_np(frames_normal) - to_np(frames_enable_split_inference)).sum()
490
+ self.assertLess(
491
+ sum_split_inference,
492
+ 1e-4,
493
+ "Enabling FreeNoise Split Inference memory-optimizations should lead to results similar to the default pipeline results",
494
+ )
495
+
496
+ def test_free_noise_multi_prompt(self):
497
+ components = self.get_dummy_components()
498
+ pipe: AnimateDiffPipeline = self.pipeline_class(**components)
499
+ pipe.set_progress_bar_config(disable=None)
500
+ pipe.to(torch_device)
501
+
502
+ context_length = 8
503
+ context_stride = 4
504
+ pipe.enable_free_noise(context_length, context_stride)
505
+
506
+ # Make sure that pipeline works when prompt indices are within num_frames bounds
507
+ inputs = self.get_dummy_inputs(torch_device)
508
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf"}
509
+ inputs["num_frames"] = 16
510
+ pipe(**inputs).frames[0]
511
+
512
+ with self.assertRaises(ValueError):
513
+ # Ensure that prompt indices are within bounds
514
+ inputs = self.get_dummy_inputs(torch_device)
515
+ inputs["num_frames"] = 16
516
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf", 42: "Error on a leaf"}
517
+ pipe(**inputs).frames[0]
518
+
519
+ @unittest.skipIf(
520
+ torch_device != "cuda" or not is_xformers_available(),
521
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
522
+ )
523
+ def test_xformers_attention_forwardGenerator_pass(self):
524
+ components = self.get_dummy_components()
525
+ pipe = self.pipeline_class(**components)
526
+ for component in pipe.components.values():
527
+ if hasattr(component, "set_default_attn_processor"):
528
+ component.set_default_attn_processor()
529
+ pipe.to(torch_device)
530
+ pipe.set_progress_bar_config(disable=None)
531
+
532
+ inputs = self.get_dummy_inputs(torch_device)
533
+ output_without_offload = pipe(**inputs).frames[0]
534
+ output_without_offload = (
535
+ output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
536
+ )
537
+
538
+ pipe.enable_xformers_memory_efficient_attention()
539
+ inputs = self.get_dummy_inputs(torch_device)
540
+ output_with_offload = pipe(**inputs).frames[0]
541
+ output_with_offload = (
542
+ output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
543
+ )
544
+
545
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
546
+ self.assertLess(max_diff, 1e-4, "XFormers attention should not affect the inference results")
547
+
548
+ def test_vae_slicing(self):
549
+ return super().test_vae_slicing(image_count=2)
550
+
551
+ def test_encode_prompt_works_in_isolation(self):
552
+ extra_required_param_value_dict = {
553
+ "device": torch.device(torch_device).type,
554
+ "num_images_per_prompt": 1,
555
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
556
+ }
557
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
558
+
559
+
560
+ @slow
561
+ @require_torch_accelerator
562
+ class AnimateDiffPipelineSlowTests(unittest.TestCase):
563
+ def setUp(self):
564
+ # clean up the VRAM before each test
565
+ super().setUp()
566
+ gc.collect()
567
+ backend_empty_cache(torch_device)
568
+
569
+ def tearDown(self):
570
+ # clean up the VRAM after each test
571
+ super().tearDown()
572
+ gc.collect()
573
+ backend_empty_cache(torch_device)
574
+
575
+ def test_animatediff(self):
576
+ adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
577
+ pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
578
+ pipe = pipe.to(torch_device)
579
+ pipe.scheduler = DDIMScheduler(
580
+ beta_start=0.00085,
581
+ beta_end=0.012,
582
+ beta_schedule="linear",
583
+ steps_offset=1,
584
+ clip_sample=False,
585
+ )
586
+ pipe.enable_vae_slicing()
587
+ pipe.enable_model_cpu_offload(device=torch_device)
588
+ pipe.set_progress_bar_config(disable=None)
589
+
590
+ prompt = "night, b&w photo of old house, post apocalypse, forest, storm weather, wind, rocks, 8k uhd, dslr, soft lighting, high quality, film grain"
591
+ negative_prompt = "bad quality, worse quality"
592
+
593
+ generator = torch.Generator("cpu").manual_seed(0)
594
+ output = pipe(
595
+ prompt,
596
+ negative_prompt=negative_prompt,
597
+ num_frames=16,
598
+ generator=generator,
599
+ guidance_scale=7.5,
600
+ num_inference_steps=3,
601
+ output_type="np",
602
+ )
603
+
604
+ image = output.frames[0]
605
+ assert image.shape == (16, 512, 512, 3)
606
+
607
+ image_slice = image[0, -3:, -3:, -1]
608
+ expected_slice = np.array(
609
+ [
610
+ 0.11357737,
611
+ 0.11285847,
612
+ 0.11180121,
613
+ 0.11084166,
614
+ 0.11414117,
615
+ 0.09785956,
616
+ 0.10742754,
617
+ 0.10510018,
618
+ 0.08045256,
619
+ ]
620
+ )
621
+ assert numpy_cosine_similarity_distance(image_slice.flatten(), expected_slice.flatten()) < 1e-3
diffusers/tests/pipelines/animatediff/test_animatediff_controlnet.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
7
+
8
+ import diffusers
9
+ from diffusers import (
10
+ AnimateDiffControlNetPipeline,
11
+ AutoencoderKL,
12
+ ControlNetModel,
13
+ DDIMScheduler,
14
+ DPMSolverMultistepScheduler,
15
+ LCMScheduler,
16
+ MotionAdapter,
17
+ StableDiffusionPipeline,
18
+ UNet2DConditionModel,
19
+ UNetMotionModel,
20
+ )
21
+ from diffusers.models.attention import FreeNoiseTransformerBlock
22
+ from diffusers.utils import logging
23
+ from diffusers.utils.import_utils import is_xformers_available
24
+
25
+ from ...testing_utils import require_accelerator, torch_device
26
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
27
+ from ..test_pipelines_common import (
28
+ IPAdapterTesterMixin,
29
+ PipelineFromPipeTesterMixin,
30
+ PipelineTesterMixin,
31
+ SDFunctionTesterMixin,
32
+ )
33
+
34
+
35
+ def to_np(tensor):
36
+ if isinstance(tensor, torch.Tensor):
37
+ tensor = tensor.detach().cpu().numpy()
38
+
39
+ return tensor
40
+
41
+
42
+ class AnimateDiffControlNetPipelineFastTests(
43
+ IPAdapterTesterMixin, SDFunctionTesterMixin, PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase
44
+ ):
45
+ pipeline_class = AnimateDiffControlNetPipeline
46
+ params = TEXT_TO_IMAGE_PARAMS
47
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"conditioning_frames"})
48
+ required_optional_params = frozenset(
49
+ [
50
+ "num_inference_steps",
51
+ "generator",
52
+ "latents",
53
+ "return_dict",
54
+ "callback_on_step_end",
55
+ "callback_on_step_end_tensor_inputs",
56
+ ]
57
+ )
58
+
59
+ def get_dummy_components(self):
60
+ cross_attention_dim = 8
61
+ block_out_channels = (8, 8)
62
+
63
+ torch.manual_seed(0)
64
+ unet = UNet2DConditionModel(
65
+ block_out_channels=block_out_channels,
66
+ layers_per_block=2,
67
+ sample_size=8,
68
+ in_channels=4,
69
+ out_channels=4,
70
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
71
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
72
+ cross_attention_dim=cross_attention_dim,
73
+ norm_num_groups=2,
74
+ )
75
+ scheduler = DDIMScheduler(
76
+ beta_start=0.00085,
77
+ beta_end=0.012,
78
+ beta_schedule="linear",
79
+ clip_sample=False,
80
+ )
81
+ torch.manual_seed(0)
82
+ controlnet = ControlNetModel(
83
+ block_out_channels=block_out_channels,
84
+ layers_per_block=2,
85
+ in_channels=4,
86
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
87
+ cross_attention_dim=cross_attention_dim,
88
+ conditioning_embedding_out_channels=(8, 8),
89
+ norm_num_groups=1,
90
+ )
91
+ torch.manual_seed(0)
92
+ vae = AutoencoderKL(
93
+ block_out_channels=block_out_channels,
94
+ in_channels=3,
95
+ out_channels=3,
96
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
97
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
98
+ latent_channels=4,
99
+ norm_num_groups=2,
100
+ )
101
+ torch.manual_seed(0)
102
+ text_encoder_config = CLIPTextConfig(
103
+ bos_token_id=0,
104
+ eos_token_id=2,
105
+ hidden_size=cross_attention_dim,
106
+ intermediate_size=37,
107
+ layer_norm_eps=1e-05,
108
+ num_attention_heads=4,
109
+ num_hidden_layers=5,
110
+ pad_token_id=1,
111
+ vocab_size=1000,
112
+ )
113
+ text_encoder = CLIPTextModel(text_encoder_config)
114
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
115
+ motion_adapter = MotionAdapter(
116
+ block_out_channels=block_out_channels,
117
+ motion_layers_per_block=2,
118
+ motion_norm_num_groups=2,
119
+ motion_num_attention_heads=4,
120
+ )
121
+
122
+ components = {
123
+ "unet": unet,
124
+ "controlnet": controlnet,
125
+ "scheduler": scheduler,
126
+ "vae": vae,
127
+ "motion_adapter": motion_adapter,
128
+ "text_encoder": text_encoder,
129
+ "tokenizer": tokenizer,
130
+ "feature_extractor": None,
131
+ "image_encoder": None,
132
+ }
133
+ return components
134
+
135
+ def get_dummy_inputs(self, device, seed: int = 0, num_frames: int = 2):
136
+ if str(device).startswith("mps"):
137
+ generator = torch.manual_seed(seed)
138
+ else:
139
+ generator = torch.Generator(device=device).manual_seed(seed)
140
+
141
+ video_height = 32
142
+ video_width = 32
143
+ conditioning_frames = [Image.new("RGB", (video_width, video_height))] * num_frames
144
+
145
+ inputs = {
146
+ "prompt": "A painting of a squirrel eating a burger",
147
+ "conditioning_frames": conditioning_frames,
148
+ "generator": generator,
149
+ "num_inference_steps": 2,
150
+ "num_frames": num_frames,
151
+ "guidance_scale": 7.5,
152
+ "output_type": "pt",
153
+ }
154
+ return inputs
155
+
156
+ def test_from_pipe_consistent_config(self):
157
+ assert self.original_pipeline_class == StableDiffusionPipeline
158
+ original_repo = "hf-internal-testing/tinier-stable-diffusion-pipe"
159
+ original_kwargs = {"requires_safety_checker": False}
160
+
161
+ # create original_pipeline_class(sd)
162
+ pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)
163
+
164
+ # original_pipeline_class(sd) -> pipeline_class
165
+ pipe_components = self.get_dummy_components()
166
+ pipe_additional_components = {}
167
+ for name, component in pipe_components.items():
168
+ if name not in pipe_original.components:
169
+ pipe_additional_components[name] = component
170
+
171
+ pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)
172
+
173
+ # pipeline_class -> original_pipeline_class(sd)
174
+ original_pipe_additional_components = {}
175
+ for name, component in pipe_original.components.items():
176
+ if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
177
+ original_pipe_additional_components[name] = component
178
+
179
+ pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)
180
+
181
+ # compare the config
182
+ original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
183
+ original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
184
+ assert original_config_2 == original_config
185
+
186
+ def test_motion_unet_loading(self):
187
+ components = self.get_dummy_components()
188
+ pipe = self.pipeline_class(**components)
189
+
190
+ assert isinstance(pipe.unet, UNetMotionModel)
191
+
192
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
193
+ def test_attention_slicing_forward_pass(self):
194
+ pass
195
+
196
+ def test_ip_adapter(self):
197
+ expected_pipe_slice = None
198
+ if torch_device == "cpu":
199
+ expected_pipe_slice = np.array(
200
+ [
201
+ 0.6604,
202
+ 0.4099,
203
+ 0.4928,
204
+ 0.5706,
205
+ 0.5096,
206
+ 0.5012,
207
+ 0.6051,
208
+ 0.5169,
209
+ 0.5021,
210
+ 0.4864,
211
+ 0.4261,
212
+ 0.5779,
213
+ 0.5822,
214
+ 0.4049,
215
+ 0.5253,
216
+ 0.6160,
217
+ 0.4150,
218
+ 0.5155,
219
+ ]
220
+ )
221
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
222
+
223
+ def test_dict_tuple_outputs_equivalent(self):
224
+ expected_slice = None
225
+ if torch_device == "cpu":
226
+ expected_slice = np.array([0.6051, 0.5169, 0.5021, 0.6160, 0.4150, 0.5155])
227
+ return super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
228
+
229
+ def test_inference_batch_single_identical(
230
+ self,
231
+ batch_size=2,
232
+ expected_max_diff=1e-4,
233
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
234
+ ):
235
+ components = self.get_dummy_components()
236
+ pipe = self.pipeline_class(**components)
237
+ for components in pipe.components.values():
238
+ if hasattr(components, "set_default_attn_processor"):
239
+ components.set_default_attn_processor()
240
+
241
+ pipe.to(torch_device)
242
+ pipe.set_progress_bar_config(disable=None)
243
+ inputs = self.get_dummy_inputs(torch_device)
244
+ # Reset generator in case it is has been used in self.get_dummy_inputs
245
+ inputs["generator"] = self.get_generator(0)
246
+
247
+ logger = logging.get_logger(pipe.__module__)
248
+ logger.setLevel(level=diffusers.logging.FATAL)
249
+
250
+ # batchify inputs
251
+ batched_inputs = {}
252
+ batched_inputs.update(inputs)
253
+
254
+ for name in self.batch_params:
255
+ if name not in inputs:
256
+ continue
257
+
258
+ value = inputs[name]
259
+ if name == "prompt":
260
+ len_prompt = len(value)
261
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
262
+ batched_inputs[name][-1] = 100 * "very long"
263
+
264
+ else:
265
+ batched_inputs[name] = batch_size * [value]
266
+
267
+ if "generator" in inputs:
268
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
269
+
270
+ if "batch_size" in inputs:
271
+ batched_inputs["batch_size"] = batch_size
272
+
273
+ for arg in additional_params_copy_to_batched_inputs:
274
+ batched_inputs[arg] = inputs[arg]
275
+
276
+ output = pipe(**inputs)
277
+ output_batch = pipe(**batched_inputs)
278
+
279
+ assert output_batch[0].shape[0] == batch_size
280
+
281
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
282
+ assert max_diff < expected_max_diff
283
+
284
+ @require_accelerator
285
+ def test_to_device(self):
286
+ components = self.get_dummy_components()
287
+ pipe = self.pipeline_class(**components)
288
+ pipe.set_progress_bar_config(disable=None)
289
+
290
+ pipe.to("cpu")
291
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
292
+ model_devices = [
293
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
294
+ ]
295
+ self.assertTrue(all(device == "cpu" for device in model_devices))
296
+
297
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
298
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
299
+
300
+ pipe.to(torch_device)
301
+ model_devices = [
302
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
303
+ ]
304
+ self.assertTrue(all(device == torch_device for device in model_devices))
305
+
306
+ output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
307
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
308
+
309
+ def test_to_dtype(self):
310
+ components = self.get_dummy_components()
311
+ pipe = self.pipeline_class(**components)
312
+ pipe.set_progress_bar_config(disable=None)
313
+
314
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
315
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
316
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
317
+
318
+ pipe.to(dtype=torch.float16)
319
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
320
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
321
+
322
+ def test_prompt_embeds(self):
323
+ components = self.get_dummy_components()
324
+ pipe = self.pipeline_class(**components)
325
+ pipe.set_progress_bar_config(disable=None)
326
+ pipe.to(torch_device)
327
+
328
+ inputs = self.get_dummy_inputs(torch_device)
329
+ inputs.pop("prompt")
330
+ inputs["prompt_embeds"] = torch.randn((1, 4, pipe.text_encoder.config.hidden_size), device=torch_device)
331
+ pipe(**inputs)
332
+
333
+ @unittest.skipIf(
334
+ torch_device != "cuda" or not is_xformers_available(),
335
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
336
+ )
337
+ def test_xformers_attention_forwardGenerator_pass(self):
338
+ super()._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=False)
339
+
340
+ def test_free_init(self):
341
+ components = self.get_dummy_components()
342
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
343
+ pipe.set_progress_bar_config(disable=None)
344
+ pipe.to(torch_device)
345
+
346
+ inputs_normal = self.get_dummy_inputs(torch_device)
347
+ frames_normal = pipe(**inputs_normal).frames[0]
348
+
349
+ pipe.enable_free_init(
350
+ num_iters=2,
351
+ use_fast_sampling=True,
352
+ method="butterworth",
353
+ order=4,
354
+ spatial_stop_frequency=0.25,
355
+ temporal_stop_frequency=0.25,
356
+ )
357
+ inputs_enable_free_init = self.get_dummy_inputs(torch_device)
358
+ frames_enable_free_init = pipe(**inputs_enable_free_init).frames[0]
359
+
360
+ pipe.disable_free_init()
361
+ inputs_disable_free_init = self.get_dummy_inputs(torch_device)
362
+ frames_disable_free_init = pipe(**inputs_disable_free_init).frames[0]
363
+
364
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
365
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_init)).max()
366
+ self.assertGreater(
367
+ sum_enabled, 1e1, "Enabling of FreeInit should lead to results different from the default pipeline results"
368
+ )
369
+ self.assertLess(
370
+ max_diff_disabled,
371
+ 1e-4,
372
+ "Disabling of FreeInit should lead to results similar to the default pipeline results",
373
+ )
374
+
375
+ def test_free_init_with_schedulers(self):
376
+ components = self.get_dummy_components()
377
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
378
+ pipe.set_progress_bar_config(disable=None)
379
+ pipe.to(torch_device)
380
+
381
+ inputs_normal = self.get_dummy_inputs(torch_device)
382
+ frames_normal = pipe(**inputs_normal).frames[0]
383
+
384
+ schedulers_to_test = [
385
+ DPMSolverMultistepScheduler.from_config(
386
+ components["scheduler"].config,
387
+ timestep_spacing="linspace",
388
+ beta_schedule="linear",
389
+ algorithm_type="dpmsolver++",
390
+ steps_offset=1,
391
+ clip_sample=False,
392
+ ),
393
+ LCMScheduler.from_config(
394
+ components["scheduler"].config,
395
+ timestep_spacing="linspace",
396
+ beta_schedule="linear",
397
+ steps_offset=1,
398
+ clip_sample=False,
399
+ ),
400
+ ]
401
+ components.pop("scheduler")
402
+
403
+ for scheduler in schedulers_to_test:
404
+ components["scheduler"] = scheduler
405
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
406
+ pipe.set_progress_bar_config(disable=None)
407
+ pipe.to(torch_device)
408
+
409
+ pipe.enable_free_init(num_iters=2, use_fast_sampling=False)
410
+
411
+ inputs = self.get_dummy_inputs(torch_device)
412
+ frames_enable_free_init = pipe(**inputs).frames[0]
413
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
414
+
415
+ self.assertGreater(
416
+ sum_enabled,
417
+ 1e1,
418
+ "Enabling of FreeInit should lead to results different from the default pipeline results",
419
+ )
420
+
421
+ def test_free_noise_blocks(self):
422
+ components = self.get_dummy_components()
423
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
424
+ pipe.set_progress_bar_config(disable=None)
425
+ pipe.to(torch_device)
426
+
427
+ pipe.enable_free_noise()
428
+ for block in pipe.unet.down_blocks:
429
+ for motion_module in block.motion_modules:
430
+ for transformer_block in motion_module.transformer_blocks:
431
+ self.assertTrue(
432
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
433
+ "Motion module transformer blocks must be an instance of `FreeNoiseTransformerBlock` after enabling FreeNoise.",
434
+ )
435
+
436
+ pipe.disable_free_noise()
437
+ for block in pipe.unet.down_blocks:
438
+ for motion_module in block.motion_modules:
439
+ for transformer_block in motion_module.transformer_blocks:
440
+ self.assertFalse(
441
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
442
+ "Motion module transformer blocks must not be an instance of `FreeNoiseTransformerBlock` after disabling FreeNoise.",
443
+ )
444
+
445
+ def test_free_noise(self):
446
+ components = self.get_dummy_components()
447
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
448
+ pipe.set_progress_bar_config(disable=None)
449
+ pipe.to(torch_device)
450
+
451
+ inputs_normal = self.get_dummy_inputs(torch_device, num_frames=16)
452
+ frames_normal = pipe(**inputs_normal).frames[0]
453
+
454
+ for context_length in [8, 9]:
455
+ for context_stride in [4, 6]:
456
+ pipe.enable_free_noise(context_length, context_stride)
457
+
458
+ inputs_enable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
459
+ frames_enable_free_noise = pipe(**inputs_enable_free_noise).frames[0]
460
+
461
+ pipe.disable_free_noise()
462
+
463
+ inputs_disable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
464
+ frames_disable_free_noise = pipe(**inputs_disable_free_noise).frames[0]
465
+
466
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_noise)).sum()
467
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_noise)).max()
468
+ self.assertGreater(
469
+ sum_enabled,
470
+ 1e1,
471
+ "Enabling of FreeNoise should lead to results different from the default pipeline results",
472
+ )
473
+ self.assertLess(
474
+ max_diff_disabled,
475
+ 1e-4,
476
+ "Disabling of FreeNoise should lead to results similar to the default pipeline results",
477
+ )
478
+
479
+ def test_free_noise_multi_prompt(self):
480
+ components = self.get_dummy_components()
481
+ pipe: AnimateDiffControlNetPipeline = self.pipeline_class(**components)
482
+ pipe.set_progress_bar_config(disable=None)
483
+ pipe.to(torch_device)
484
+
485
+ context_length = 8
486
+ context_stride = 4
487
+ pipe.enable_free_noise(context_length, context_stride)
488
+
489
+ # Make sure that pipeline works when prompt indices are within num_frames bounds
490
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
491
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf"}
492
+ pipe(**inputs).frames[0]
493
+
494
+ with self.assertRaises(ValueError):
495
+ # Ensure that prompt indices are within bounds
496
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
497
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf", 42: "Error on a leaf"}
498
+ pipe(**inputs).frames[0]
499
+
500
+ def test_vae_slicing(self, video_count=2):
501
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
502
+ components = self.get_dummy_components()
503
+ pipe = self.pipeline_class(**components)
504
+ pipe = pipe.to(device)
505
+ pipe.set_progress_bar_config(disable=None)
506
+
507
+ inputs = self.get_dummy_inputs(device)
508
+ inputs["prompt"] = [inputs["prompt"]] * video_count
509
+ inputs["conditioning_frames"] = [inputs["conditioning_frames"]] * video_count
510
+ output_1 = pipe(**inputs)
511
+
512
+ # make sure sliced vae decode yields the same result
513
+ pipe.enable_vae_slicing()
514
+ inputs = self.get_dummy_inputs(device)
515
+ inputs["prompt"] = [inputs["prompt"]] * video_count
516
+ inputs["conditioning_frames"] = [inputs["conditioning_frames"]] * video_count
517
+ output_2 = pipe(**inputs)
518
+
519
+ assert np.abs(output_2[0].flatten() - output_1[0].flatten()).max() < 1e-2
520
+
521
+ def test_encode_prompt_works_in_isolation(self):
522
+ extra_required_param_value_dict = {
523
+ "device": torch.device(torch_device).type,
524
+ "num_images_per_prompt": 1,
525
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
526
+ }
527
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
diffusers/tests/pipelines/animatediff/test_animatediff_sdxl.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
6
+
7
+ import diffusers
8
+ from diffusers import (
9
+ AnimateDiffSDXLPipeline,
10
+ AutoencoderKL,
11
+ DDIMScheduler,
12
+ MotionAdapter,
13
+ UNet2DConditionModel,
14
+ UNetMotionModel,
15
+ )
16
+ from diffusers.utils import is_xformers_available, logging
17
+
18
+ from ...testing_utils import require_accelerator, torch_device
19
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS, TEXT_TO_IMAGE_PARAMS
20
+ from ..test_pipelines_common import (
21
+ IPAdapterTesterMixin,
22
+ PipelineTesterMixin,
23
+ SDFunctionTesterMixin,
24
+ )
25
+
26
+
27
+ def to_np(tensor):
28
+ if isinstance(tensor, torch.Tensor):
29
+ tensor = tensor.detach().cpu().numpy()
30
+
31
+ return tensor
32
+
33
+
34
+ class AnimateDiffPipelineSDXLFastTests(
35
+ IPAdapterTesterMixin,
36
+ SDFunctionTesterMixin,
37
+ PipelineTesterMixin,
38
+ unittest.TestCase,
39
+ ):
40
+ pipeline_class = AnimateDiffSDXLPipeline
41
+ params = TEXT_TO_IMAGE_PARAMS
42
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
43
+ required_optional_params = frozenset(
44
+ [
45
+ "num_inference_steps",
46
+ "generator",
47
+ "latents",
48
+ "return_dict",
49
+ "callback_on_step_end",
50
+ "callback_on_step_end_tensor_inputs",
51
+ ]
52
+ )
53
+ callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union({"add_text_embeds", "add_time_ids"})
54
+
55
+ def get_dummy_components(self, time_cond_proj_dim=None):
56
+ torch.manual_seed(0)
57
+ unet = UNet2DConditionModel(
58
+ block_out_channels=(32, 64, 128),
59
+ layers_per_block=2,
60
+ time_cond_proj_dim=time_cond_proj_dim,
61
+ sample_size=32,
62
+ in_channels=4,
63
+ out_channels=4,
64
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D"),
65
+ up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D"),
66
+ # SD2-specific config below
67
+ attention_head_dim=(2, 4, 8),
68
+ use_linear_projection=True,
69
+ addition_embed_type="text_time",
70
+ addition_time_embed_dim=8,
71
+ transformer_layers_per_block=(1, 2, 4),
72
+ projection_class_embeddings_input_dim=80, # 6 * 8 + 32
73
+ cross_attention_dim=64,
74
+ norm_num_groups=1,
75
+ )
76
+ scheduler = DDIMScheduler(
77
+ beta_start=0.00085,
78
+ beta_end=0.012,
79
+ beta_schedule="linear",
80
+ clip_sample=False,
81
+ )
82
+ torch.manual_seed(0)
83
+ vae = AutoencoderKL(
84
+ block_out_channels=[32, 64],
85
+ in_channels=3,
86
+ out_channels=3,
87
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
88
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
89
+ latent_channels=4,
90
+ sample_size=128,
91
+ )
92
+ torch.manual_seed(0)
93
+ text_encoder_config = CLIPTextConfig(
94
+ bos_token_id=0,
95
+ eos_token_id=2,
96
+ hidden_size=32,
97
+ intermediate_size=37,
98
+ layer_norm_eps=1e-05,
99
+ num_attention_heads=4,
100
+ num_hidden_layers=5,
101
+ pad_token_id=1,
102
+ vocab_size=1000,
103
+ # SD2-specific config below
104
+ hidden_act="gelu",
105
+ projection_dim=32,
106
+ )
107
+ text_encoder = CLIPTextModel(text_encoder_config)
108
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
109
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
110
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
111
+ motion_adapter = MotionAdapter(
112
+ block_out_channels=(32, 64, 128),
113
+ motion_layers_per_block=2,
114
+ motion_norm_num_groups=2,
115
+ motion_num_attention_heads=4,
116
+ use_motion_mid_block=False,
117
+ )
118
+
119
+ components = {
120
+ "unet": unet,
121
+ "scheduler": scheduler,
122
+ "vae": vae,
123
+ "motion_adapter": motion_adapter,
124
+ "text_encoder": text_encoder,
125
+ "tokenizer": tokenizer,
126
+ "text_encoder_2": text_encoder_2,
127
+ "tokenizer_2": tokenizer_2,
128
+ "feature_extractor": None,
129
+ "image_encoder": None,
130
+ }
131
+ return components
132
+
133
+ def get_dummy_inputs(self, device, seed=0):
134
+ if str(device).startswith("mps"):
135
+ generator = torch.manual_seed(seed)
136
+ else:
137
+ generator = torch.Generator(device=device).manual_seed(seed)
138
+
139
+ inputs = {
140
+ "prompt": "A painting of a squirrel eating a burger",
141
+ "generator": generator,
142
+ "num_inference_steps": 2,
143
+ "guidance_scale": 7.5,
144
+ "output_type": "np",
145
+ }
146
+ return inputs
147
+
148
+ def test_motion_unet_loading(self):
149
+ components = self.get_dummy_components()
150
+ pipe = AnimateDiffSDXLPipeline(**components)
151
+
152
+ assert isinstance(pipe.unet, UNetMotionModel)
153
+
154
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
155
+ def test_attention_slicing_forward_pass(self):
156
+ pass
157
+
158
+ def test_inference_batch_single_identical(
159
+ self,
160
+ batch_size=2,
161
+ expected_max_diff=1e-4,
162
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
163
+ ):
164
+ components = self.get_dummy_components()
165
+ pipe = self.pipeline_class(**components)
166
+ for components in pipe.components.values():
167
+ if hasattr(components, "set_default_attn_processor"):
168
+ components.set_default_attn_processor()
169
+
170
+ pipe.to(torch_device)
171
+ pipe.set_progress_bar_config(disable=None)
172
+ inputs = self.get_dummy_inputs(torch_device)
173
+ # Reset generator in case it is has been used in self.get_dummy_inputs
174
+ inputs["generator"] = self.get_generator(0)
175
+
176
+ logger = logging.get_logger(pipe.__module__)
177
+ logger.setLevel(level=diffusers.logging.FATAL)
178
+
179
+ # batchify inputs
180
+ batched_inputs = {}
181
+ batched_inputs.update(inputs)
182
+
183
+ for name in self.batch_params:
184
+ if name not in inputs:
185
+ continue
186
+
187
+ value = inputs[name]
188
+ if name == "prompt":
189
+ len_prompt = len(value)
190
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
191
+ batched_inputs[name][-1] = 100 * "very long"
192
+
193
+ else:
194
+ batched_inputs[name] = batch_size * [value]
195
+
196
+ if "generator" in inputs:
197
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
198
+
199
+ if "batch_size" in inputs:
200
+ batched_inputs["batch_size"] = batch_size
201
+
202
+ for arg in additional_params_copy_to_batched_inputs:
203
+ batched_inputs[arg] = inputs[arg]
204
+
205
+ output = pipe(**inputs)
206
+ output_batch = pipe(**batched_inputs)
207
+
208
+ assert output_batch[0].shape[0] == batch_size
209
+
210
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
211
+ assert max_diff < expected_max_diff
212
+
213
+ @require_accelerator
214
+ def test_to_device(self):
215
+ components = self.get_dummy_components()
216
+ pipe = self.pipeline_class(**components)
217
+ pipe.set_progress_bar_config(disable=None)
218
+
219
+ pipe.to("cpu")
220
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
221
+ model_devices = [
222
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
223
+ ]
224
+ self.assertTrue(all(device == "cpu" for device in model_devices))
225
+
226
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
227
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
228
+
229
+ pipe.to(torch_device)
230
+ model_devices = [
231
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
232
+ ]
233
+ self.assertTrue(all(device == torch_device for device in model_devices))
234
+
235
+ output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
236
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
237
+
238
+ def test_to_dtype(self):
239
+ components = self.get_dummy_components()
240
+ pipe = self.pipeline_class(**components)
241
+ pipe.set_progress_bar_config(disable=None)
242
+
243
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
244
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
245
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
246
+
247
+ pipe.to(dtype=torch.float16)
248
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
249
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
250
+
251
+ @unittest.skipIf(
252
+ torch_device != "cuda" or not is_xformers_available(),
253
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
254
+ )
255
+ def test_xformers_attention_forwardGenerator_pass(self):
256
+ components = self.get_dummy_components()
257
+ pipe = self.pipeline_class(**components)
258
+ for component in pipe.components.values():
259
+ if hasattr(component, "set_default_attn_processor"):
260
+ component.set_default_attn_processor()
261
+ pipe.to(torch_device)
262
+ pipe.set_progress_bar_config(disable=None)
263
+
264
+ inputs = self.get_dummy_inputs(torch_device)
265
+ output_without_offload = pipe(**inputs).frames[0]
266
+ output_without_offload = (
267
+ output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
268
+ )
269
+
270
+ pipe.enable_xformers_memory_efficient_attention()
271
+ inputs = self.get_dummy_inputs(torch_device)
272
+ output_with_offload = pipe(**inputs).frames[0]
273
+ output_with_offload = (
274
+ output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
275
+ )
276
+
277
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
278
+ self.assertLess(max_diff, 1e-4, "XFormers attention should not affect the inference results")
279
+
280
+ @unittest.skip("Test currently not supported.")
281
+ def test_encode_prompt_works_in_isolation(self):
282
+ pass
283
+
284
+ @unittest.skip("Functionality is tested elsewhere.")
285
+ def test_save_load_optional_components(self):
286
+ pass
diffusers/tests/pipelines/animatediff/test_animatediff_sparsectrl.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
7
+
8
+ import diffusers
9
+ from diffusers import (
10
+ AnimateDiffSparseControlNetPipeline,
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DPMSolverMultistepScheduler,
14
+ LCMScheduler,
15
+ MotionAdapter,
16
+ SparseControlNetModel,
17
+ StableDiffusionPipeline,
18
+ UNet2DConditionModel,
19
+ UNetMotionModel,
20
+ )
21
+ from diffusers.utils import logging
22
+ from diffusers.utils.import_utils import is_xformers_available
23
+
24
+ from ...testing_utils import require_accelerator, torch_device
25
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
26
+ from ..test_pipelines_common import (
27
+ IPAdapterTesterMixin,
28
+ PipelineFromPipeTesterMixin,
29
+ PipelineTesterMixin,
30
+ SDFunctionTesterMixin,
31
+ )
32
+
33
+
34
+ def to_np(tensor):
35
+ if isinstance(tensor, torch.Tensor):
36
+ tensor = tensor.detach().cpu().numpy()
37
+
38
+ return tensor
39
+
40
+
41
+ class AnimateDiffSparseControlNetPipelineFastTests(
42
+ IPAdapterTesterMixin, SDFunctionTesterMixin, PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase
43
+ ):
44
+ pipeline_class = AnimateDiffSparseControlNetPipeline
45
+ params = TEXT_TO_IMAGE_PARAMS
46
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
47
+ required_optional_params = frozenset(
48
+ [
49
+ "num_inference_steps",
50
+ "generator",
51
+ "latents",
52
+ "return_dict",
53
+ "callback_on_step_end",
54
+ "callback_on_step_end_tensor_inputs",
55
+ ]
56
+ )
57
+
58
+ def get_dummy_components(self):
59
+ cross_attention_dim = 8
60
+ block_out_channels = (8, 8)
61
+
62
+ torch.manual_seed(0)
63
+ unet = UNet2DConditionModel(
64
+ block_out_channels=block_out_channels,
65
+ layers_per_block=2,
66
+ sample_size=8,
67
+ in_channels=4,
68
+ out_channels=4,
69
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
70
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
71
+ cross_attention_dim=cross_attention_dim,
72
+ norm_num_groups=2,
73
+ )
74
+ scheduler = DDIMScheduler(
75
+ beta_start=0.00085,
76
+ beta_end=0.012,
77
+ beta_schedule="linear",
78
+ clip_sample=False,
79
+ )
80
+ torch.manual_seed(0)
81
+ controlnet = SparseControlNetModel(
82
+ block_out_channels=block_out_channels,
83
+ layers_per_block=2,
84
+ in_channels=4,
85
+ conditioning_channels=3,
86
+ down_block_types=("CrossAttnDownBlockMotion", "DownBlockMotion"),
87
+ cross_attention_dim=cross_attention_dim,
88
+ conditioning_embedding_out_channels=(8, 8),
89
+ norm_num_groups=1,
90
+ use_simplified_condition_embedding=False,
91
+ )
92
+ torch.manual_seed(0)
93
+ vae = AutoencoderKL(
94
+ block_out_channels=block_out_channels,
95
+ in_channels=3,
96
+ out_channels=3,
97
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
98
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
99
+ latent_channels=4,
100
+ norm_num_groups=2,
101
+ )
102
+ torch.manual_seed(0)
103
+ text_encoder_config = CLIPTextConfig(
104
+ bos_token_id=0,
105
+ eos_token_id=2,
106
+ hidden_size=cross_attention_dim,
107
+ intermediate_size=37,
108
+ layer_norm_eps=1e-05,
109
+ num_attention_heads=4,
110
+ num_hidden_layers=5,
111
+ pad_token_id=1,
112
+ vocab_size=1000,
113
+ )
114
+ text_encoder = CLIPTextModel(text_encoder_config)
115
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
116
+ motion_adapter = MotionAdapter(
117
+ block_out_channels=block_out_channels,
118
+ motion_layers_per_block=2,
119
+ motion_norm_num_groups=2,
120
+ motion_num_attention_heads=4,
121
+ )
122
+
123
+ components = {
124
+ "unet": unet,
125
+ "controlnet": controlnet,
126
+ "scheduler": scheduler,
127
+ "vae": vae,
128
+ "motion_adapter": motion_adapter,
129
+ "text_encoder": text_encoder,
130
+ "tokenizer": tokenizer,
131
+ "feature_extractor": None,
132
+ "image_encoder": None,
133
+ }
134
+ return components
135
+
136
+ def get_dummy_inputs(self, device, seed: int = 0, num_frames: int = 2):
137
+ if str(device).startswith("mps"):
138
+ generator = torch.manual_seed(seed)
139
+ else:
140
+ generator = torch.Generator(device=device).manual_seed(seed)
141
+
142
+ video_height = 32
143
+ video_width = 32
144
+ conditioning_frames = [Image.new("RGB", (video_width, video_height))] * num_frames
145
+
146
+ inputs = {
147
+ "prompt": "A painting of a squirrel eating a burger",
148
+ "conditioning_frames": conditioning_frames,
149
+ "controlnet_frame_indices": list(range(num_frames)),
150
+ "generator": generator,
151
+ "num_inference_steps": 2,
152
+ "num_frames": num_frames,
153
+ "guidance_scale": 7.5,
154
+ "output_type": "pt",
155
+ }
156
+ return inputs
157
+
158
+ def test_from_pipe_consistent_config(self):
159
+ assert self.original_pipeline_class == StableDiffusionPipeline
160
+ original_repo = "hf-internal-testing/tinier-stable-diffusion-pipe"
161
+ original_kwargs = {"requires_safety_checker": False}
162
+
163
+ # create original_pipeline_class(sd)
164
+ pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)
165
+
166
+ # original_pipeline_class(sd) -> pipeline_class
167
+ pipe_components = self.get_dummy_components()
168
+ pipe_additional_components = {}
169
+ for name, component in pipe_components.items():
170
+ if name not in pipe_original.components:
171
+ pipe_additional_components[name] = component
172
+
173
+ pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)
174
+
175
+ # pipeline_class -> original_pipeline_class(sd)
176
+ original_pipe_additional_components = {}
177
+ for name, component in pipe_original.components.items():
178
+ if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
179
+ original_pipe_additional_components[name] = component
180
+
181
+ pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)
182
+
183
+ # compare the config
184
+ original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
185
+ original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
186
+ assert original_config_2 == original_config
187
+
188
+ def test_motion_unet_loading(self):
189
+ components = self.get_dummy_components()
190
+ pipe = AnimateDiffSparseControlNetPipeline(**components)
191
+
192
+ assert isinstance(pipe.unet, UNetMotionModel)
193
+
194
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
195
+ def test_attention_slicing_forward_pass(self):
196
+ pass
197
+
198
+ def test_ip_adapter(self):
199
+ expected_pipe_slice = None
200
+ if torch_device == "cpu":
201
+ expected_pipe_slice = np.array(
202
+ [
203
+ 0.6604,
204
+ 0.4099,
205
+ 0.4928,
206
+ 0.5706,
207
+ 0.5096,
208
+ 0.5012,
209
+ 0.6051,
210
+ 0.5169,
211
+ 0.5021,
212
+ 0.4864,
213
+ 0.4261,
214
+ 0.5779,
215
+ 0.5822,
216
+ 0.4049,
217
+ 0.5253,
218
+ 0.6160,
219
+ 0.4150,
220
+ 0.5155,
221
+ ]
222
+ )
223
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
224
+
225
+ def test_dict_tuple_outputs_equivalent(self):
226
+ expected_slice = None
227
+ if torch_device == "cpu":
228
+ expected_slice = np.array([0.6051, 0.5169, 0.5021, 0.6160, 0.4150, 0.5155])
229
+ return super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
230
+
231
+ def test_inference_batch_single_identical(
232
+ self,
233
+ batch_size=2,
234
+ expected_max_diff=1e-4,
235
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
236
+ ):
237
+ components = self.get_dummy_components()
238
+ pipe = self.pipeline_class(**components)
239
+ for components in pipe.components.values():
240
+ if hasattr(components, "set_default_attn_processor"):
241
+ components.set_default_attn_processor()
242
+
243
+ pipe.to(torch_device)
244
+ pipe.set_progress_bar_config(disable=None)
245
+ inputs = self.get_dummy_inputs(torch_device)
246
+ # Reset generator in case it is has been used in self.get_dummy_inputs
247
+ inputs["generator"] = self.get_generator(0)
248
+
249
+ logger = logging.get_logger(pipe.__module__)
250
+ logger.setLevel(level=diffusers.logging.FATAL)
251
+
252
+ # batchify inputs
253
+ batched_inputs = {}
254
+ batched_inputs.update(inputs)
255
+
256
+ for name in self.batch_params:
257
+ if name not in inputs:
258
+ continue
259
+
260
+ value = inputs[name]
261
+ if name == "prompt":
262
+ len_prompt = len(value)
263
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
264
+ batched_inputs[name][-1] = 100 * "very long"
265
+
266
+ else:
267
+ batched_inputs[name] = batch_size * [value]
268
+
269
+ if "generator" in inputs:
270
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
271
+
272
+ if "batch_size" in inputs:
273
+ batched_inputs["batch_size"] = batch_size
274
+
275
+ for arg in additional_params_copy_to_batched_inputs:
276
+ batched_inputs[arg] = inputs[arg]
277
+
278
+ output = pipe(**inputs)
279
+ output_batch = pipe(**batched_inputs)
280
+
281
+ assert output_batch[0].shape[0] == batch_size
282
+
283
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
284
+ assert max_diff < expected_max_diff
285
+
286
+ def test_inference_batch_single_identical_use_simplified_condition_embedding_true(
287
+ self,
288
+ batch_size=2,
289
+ expected_max_diff=1e-4,
290
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
291
+ ):
292
+ components = self.get_dummy_components()
293
+
294
+ torch.manual_seed(0)
295
+ old_controlnet = components.pop("controlnet")
296
+ components["controlnet"] = SparseControlNetModel.from_config(
297
+ old_controlnet.config, conditioning_channels=4, use_simplified_condition_embedding=True
298
+ )
299
+
300
+ pipe = self.pipeline_class(**components)
301
+ for components in pipe.components.values():
302
+ if hasattr(components, "set_default_attn_processor"):
303
+ components.set_default_attn_processor()
304
+
305
+ pipe.to(torch_device)
306
+ pipe.set_progress_bar_config(disable=None)
307
+ inputs = self.get_dummy_inputs(torch_device)
308
+ # Reset generator in case it is has been used in self.get_dummy_inputs
309
+ inputs["generator"] = self.get_generator(0)
310
+
311
+ logger = logging.get_logger(pipe.__module__)
312
+ logger.setLevel(level=diffusers.logging.FATAL)
313
+
314
+ # batchify inputs
315
+ batched_inputs = {}
316
+ batched_inputs.update(inputs)
317
+
318
+ for name in self.batch_params:
319
+ if name not in inputs:
320
+ continue
321
+
322
+ value = inputs[name]
323
+ if name == "prompt":
324
+ len_prompt = len(value)
325
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
326
+ batched_inputs[name][-1] = 100 * "very long"
327
+
328
+ else:
329
+ batched_inputs[name] = batch_size * [value]
330
+
331
+ if "generator" in inputs:
332
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
333
+
334
+ if "batch_size" in inputs:
335
+ batched_inputs["batch_size"] = batch_size
336
+
337
+ for arg in additional_params_copy_to_batched_inputs:
338
+ batched_inputs[arg] = inputs[arg]
339
+
340
+ output = pipe(**inputs)
341
+ output_batch = pipe(**batched_inputs)
342
+
343
+ assert output_batch[0].shape[0] == batch_size
344
+
345
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
346
+ assert max_diff < expected_max_diff
347
+
348
+ @require_accelerator
349
+ def test_to_device(self):
350
+ components = self.get_dummy_components()
351
+ pipe = self.pipeline_class(**components)
352
+ pipe.set_progress_bar_config(disable=None)
353
+
354
+ pipe.to("cpu")
355
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
356
+ model_devices = [
357
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
358
+ ]
359
+ self.assertTrue(all(device == "cpu" for device in model_devices))
360
+
361
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
362
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
363
+
364
+ pipe.to(torch_device)
365
+ model_devices = [
366
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
367
+ ]
368
+ self.assertTrue(all(device == torch_device for device in model_devices))
369
+
370
+ output_cuda = pipe(**self.get_dummy_inputs(torch_device))[0]
371
+ self.assertTrue(np.isnan(to_np(output_cuda)).sum() == 0)
372
+
373
+ def test_to_dtype(self):
374
+ components = self.get_dummy_components()
375
+ pipe = self.pipeline_class(**components)
376
+ pipe.set_progress_bar_config(disable=None)
377
+
378
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
379
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
380
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
381
+
382
+ pipe.to(dtype=torch.float16)
383
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
384
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
385
+
386
+ def test_prompt_embeds(self):
387
+ components = self.get_dummy_components()
388
+ pipe = self.pipeline_class(**components)
389
+ pipe.set_progress_bar_config(disable=None)
390
+ pipe.to(torch_device)
391
+
392
+ inputs = self.get_dummy_inputs(torch_device)
393
+ inputs.pop("prompt")
394
+ inputs["prompt_embeds"] = torch.randn((1, 4, pipe.text_encoder.config.hidden_size), device=torch_device)
395
+ pipe(**inputs)
396
+
397
+ @unittest.skipIf(
398
+ torch_device != "cuda" or not is_xformers_available(),
399
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
400
+ )
401
+ def test_xformers_attention_forwardGenerator_pass(self):
402
+ super()._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=False)
403
+
404
+ def test_free_init(self):
405
+ components = self.get_dummy_components()
406
+ pipe: AnimateDiffSparseControlNetPipeline = self.pipeline_class(**components)
407
+ pipe.set_progress_bar_config(disable=None)
408
+ pipe.to(torch_device)
409
+
410
+ inputs_normal = self.get_dummy_inputs(torch_device)
411
+ frames_normal = pipe(**inputs_normal).frames[0]
412
+
413
+ pipe.enable_free_init(
414
+ num_iters=2,
415
+ use_fast_sampling=True,
416
+ method="butterworth",
417
+ order=4,
418
+ spatial_stop_frequency=0.25,
419
+ temporal_stop_frequency=0.25,
420
+ )
421
+ inputs_enable_free_init = self.get_dummy_inputs(torch_device)
422
+ frames_enable_free_init = pipe(**inputs_enable_free_init).frames[0]
423
+
424
+ pipe.disable_free_init()
425
+ inputs_disable_free_init = self.get_dummy_inputs(torch_device)
426
+ frames_disable_free_init = pipe(**inputs_disable_free_init).frames[0]
427
+
428
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
429
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_init)).max()
430
+ self.assertGreater(
431
+ sum_enabled, 1e1, "Enabling of FreeInit should lead to results different from the default pipeline results"
432
+ )
433
+ self.assertLess(
434
+ max_diff_disabled,
435
+ 1e-4,
436
+ "Disabling of FreeInit should lead to results similar to the default pipeline results",
437
+ )
438
+
439
+ def test_free_init_with_schedulers(self):
440
+ components = self.get_dummy_components()
441
+ pipe: AnimateDiffSparseControlNetPipeline = self.pipeline_class(**components)
442
+ pipe.set_progress_bar_config(disable=None)
443
+ pipe.to(torch_device)
444
+
445
+ inputs_normal = self.get_dummy_inputs(torch_device)
446
+ frames_normal = pipe(**inputs_normal).frames[0]
447
+
448
+ schedulers_to_test = [
449
+ DPMSolverMultistepScheduler.from_config(
450
+ components["scheduler"].config,
451
+ timestep_spacing="linspace",
452
+ beta_schedule="linear",
453
+ algorithm_type="dpmsolver++",
454
+ steps_offset=1,
455
+ clip_sample=False,
456
+ ),
457
+ LCMScheduler.from_config(
458
+ components["scheduler"].config,
459
+ timestep_spacing="linspace",
460
+ beta_schedule="linear",
461
+ steps_offset=1,
462
+ clip_sample=False,
463
+ ),
464
+ ]
465
+ components.pop("scheduler")
466
+
467
+ for scheduler in schedulers_to_test:
468
+ components["scheduler"] = scheduler
469
+ pipe: AnimateDiffSparseControlNetPipeline = self.pipeline_class(**components)
470
+ pipe.set_progress_bar_config(disable=None)
471
+ pipe.to(torch_device)
472
+
473
+ pipe.enable_free_init(num_iters=2, use_fast_sampling=False)
474
+
475
+ inputs = self.get_dummy_inputs(torch_device)
476
+ frames_enable_free_init = pipe(**inputs).frames[0]
477
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
478
+
479
+ self.assertGreater(
480
+ sum_enabled,
481
+ 1e1,
482
+ "Enabling of FreeInit should lead to results different from the default pipeline results",
483
+ )
484
+
485
+ def test_vae_slicing(self):
486
+ return super().test_vae_slicing(image_count=2)
487
+
488
+ def test_encode_prompt_works_in_isolation(self):
489
+ extra_required_param_value_dict = {
490
+ "device": torch.device(torch_device).type,
491
+ "num_images_per_prompt": 1,
492
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
493
+ }
494
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
diffusers/tests/pipelines/animatediff/test_animatediff_video2video.py ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
7
+
8
+ import diffusers
9
+ from diffusers import (
10
+ AnimateDiffVideoToVideoPipeline,
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DPMSolverMultistepScheduler,
14
+ LCMScheduler,
15
+ MotionAdapter,
16
+ StableDiffusionPipeline,
17
+ UNet2DConditionModel,
18
+ UNetMotionModel,
19
+ )
20
+ from diffusers.models.attention import FreeNoiseTransformerBlock
21
+ from diffusers.utils import is_xformers_available, logging
22
+
23
+ from ...testing_utils import require_accelerator, torch_device
24
+ from ..pipeline_params import TEXT_TO_IMAGE_PARAMS, VIDEO_TO_VIDEO_BATCH_PARAMS
25
+ from ..test_pipelines_common import IPAdapterTesterMixin, PipelineFromPipeTesterMixin, PipelineTesterMixin
26
+
27
+
28
+ def to_np(tensor):
29
+ if isinstance(tensor, torch.Tensor):
30
+ tensor = tensor.detach().cpu().numpy()
31
+
32
+ return tensor
33
+
34
+
35
+ class AnimateDiffVideoToVideoPipelineFastTests(
36
+ IPAdapterTesterMixin, PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase
37
+ ):
38
+ pipeline_class = AnimateDiffVideoToVideoPipeline
39
+ params = TEXT_TO_IMAGE_PARAMS
40
+ batch_params = VIDEO_TO_VIDEO_BATCH_PARAMS
41
+ required_optional_params = frozenset(
42
+ [
43
+ "num_inference_steps",
44
+ "generator",
45
+ "latents",
46
+ "return_dict",
47
+ "callback_on_step_end",
48
+ "callback_on_step_end_tensor_inputs",
49
+ ]
50
+ )
51
+
52
+ def get_dummy_components(self):
53
+ cross_attention_dim = 8
54
+ block_out_channels = (8, 8)
55
+
56
+ torch.manual_seed(0)
57
+ unet = UNet2DConditionModel(
58
+ block_out_channels=block_out_channels,
59
+ layers_per_block=2,
60
+ sample_size=8,
61
+ in_channels=4,
62
+ out_channels=4,
63
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
64
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
65
+ cross_attention_dim=cross_attention_dim,
66
+ norm_num_groups=2,
67
+ )
68
+ scheduler = DDIMScheduler(
69
+ beta_start=0.00085,
70
+ beta_end=0.012,
71
+ beta_schedule="linear",
72
+ clip_sample=False,
73
+ )
74
+ torch.manual_seed(0)
75
+ vae = AutoencoderKL(
76
+ block_out_channels=block_out_channels,
77
+ in_channels=3,
78
+ out_channels=3,
79
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
80
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
81
+ latent_channels=4,
82
+ norm_num_groups=2,
83
+ )
84
+ torch.manual_seed(0)
85
+ text_encoder_config = CLIPTextConfig(
86
+ bos_token_id=0,
87
+ eos_token_id=2,
88
+ hidden_size=cross_attention_dim,
89
+ intermediate_size=37,
90
+ layer_norm_eps=1e-05,
91
+ num_attention_heads=4,
92
+ num_hidden_layers=5,
93
+ pad_token_id=1,
94
+ vocab_size=1000,
95
+ )
96
+ text_encoder = CLIPTextModel(text_encoder_config)
97
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
98
+ torch.manual_seed(0)
99
+ motion_adapter = MotionAdapter(
100
+ block_out_channels=block_out_channels,
101
+ motion_layers_per_block=2,
102
+ motion_norm_num_groups=2,
103
+ motion_num_attention_heads=4,
104
+ )
105
+
106
+ components = {
107
+ "unet": unet,
108
+ "scheduler": scheduler,
109
+ "vae": vae,
110
+ "motion_adapter": motion_adapter,
111
+ "text_encoder": text_encoder,
112
+ "tokenizer": tokenizer,
113
+ "feature_extractor": None,
114
+ "image_encoder": None,
115
+ }
116
+ return components
117
+
118
+ def get_dummy_inputs(self, device, seed=0, num_frames: int = 2):
119
+ if str(device).startswith("mps"):
120
+ generator = torch.manual_seed(seed)
121
+ else:
122
+ generator = torch.Generator(device=device).manual_seed(seed)
123
+
124
+ video_height = 32
125
+ video_width = 32
126
+ video = [Image.new("RGB", (video_width, video_height))] * num_frames
127
+
128
+ inputs = {
129
+ "video": video,
130
+ "prompt": "A painting of a squirrel eating a burger",
131
+ "generator": generator,
132
+ "num_inference_steps": 2,
133
+ "guidance_scale": 7.5,
134
+ "output_type": "pt",
135
+ }
136
+ return inputs
137
+
138
+ def test_from_pipe_consistent_config(self):
139
+ assert self.original_pipeline_class == StableDiffusionPipeline
140
+ original_repo = "hf-internal-testing/tinier-stable-diffusion-pipe"
141
+ original_kwargs = {"requires_safety_checker": False}
142
+
143
+ # create original_pipeline_class(sd)
144
+ pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)
145
+
146
+ # original_pipeline_class(sd) -> pipeline_class
147
+ pipe_components = self.get_dummy_components()
148
+ pipe_additional_components = {}
149
+ for name, component in pipe_components.items():
150
+ if name not in pipe_original.components:
151
+ pipe_additional_components[name] = component
152
+
153
+ pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)
154
+
155
+ # pipeline_class -> original_pipeline_class(sd)
156
+ original_pipe_additional_components = {}
157
+ for name, component in pipe_original.components.items():
158
+ if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
159
+ original_pipe_additional_components[name] = component
160
+
161
+ pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)
162
+
163
+ # compare the config
164
+ original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
165
+ original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
166
+ assert original_config_2 == original_config
167
+
168
+ def test_motion_unet_loading(self):
169
+ components = self.get_dummy_components()
170
+ pipe = AnimateDiffVideoToVideoPipeline(**components)
171
+
172
+ assert isinstance(pipe.unet, UNetMotionModel)
173
+
174
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
175
+ def test_attention_slicing_forward_pass(self):
176
+ pass
177
+
178
+ def test_ip_adapter(self):
179
+ expected_pipe_slice = None
180
+
181
+ if torch_device == "cpu":
182
+ expected_pipe_slice = np.array(
183
+ [
184
+ 0.5569,
185
+ 0.6250,
186
+ 0.4145,
187
+ 0.5613,
188
+ 0.5563,
189
+ 0.5213,
190
+ 0.5092,
191
+ 0.4950,
192
+ 0.4950,
193
+ 0.5685,
194
+ 0.3858,
195
+ 0.4864,
196
+ 0.6458,
197
+ 0.4312,
198
+ 0.5518,
199
+ 0.5608,
200
+ 0.4418,
201
+ 0.5378,
202
+ ]
203
+ )
204
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
205
+
206
+ def test_inference_batch_single_identical(
207
+ self,
208
+ batch_size=2,
209
+ expected_max_diff=1e-4,
210
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
211
+ ):
212
+ components = self.get_dummy_components()
213
+ pipe = self.pipeline_class(**components)
214
+ for components in pipe.components.values():
215
+ if hasattr(components, "set_default_attn_processor"):
216
+ components.set_default_attn_processor()
217
+
218
+ pipe.to(torch_device)
219
+ pipe.set_progress_bar_config(disable=None)
220
+ inputs = self.get_dummy_inputs(torch_device)
221
+ # Reset generator in case it is has been used in self.get_dummy_inputs
222
+ inputs["generator"] = self.get_generator(0)
223
+
224
+ logger = logging.get_logger(pipe.__module__)
225
+ logger.setLevel(level=diffusers.logging.FATAL)
226
+
227
+ # batchify inputs
228
+ batched_inputs = {}
229
+ batched_inputs.update(inputs)
230
+
231
+ for name in self.batch_params:
232
+ if name not in inputs:
233
+ continue
234
+
235
+ value = inputs[name]
236
+ if name == "prompt":
237
+ len_prompt = len(value)
238
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
239
+ batched_inputs[name][-1] = 100 * "very long"
240
+
241
+ else:
242
+ batched_inputs[name] = batch_size * [value]
243
+
244
+ if "generator" in inputs:
245
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
246
+
247
+ if "batch_size" in inputs:
248
+ batched_inputs["batch_size"] = batch_size
249
+
250
+ for arg in additional_params_copy_to_batched_inputs:
251
+ batched_inputs[arg] = inputs[arg]
252
+
253
+ output = pipe(**inputs)
254
+ output_batch = pipe(**batched_inputs)
255
+
256
+ assert output_batch[0].shape[0] == batch_size
257
+
258
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
259
+ assert max_diff < expected_max_diff
260
+
261
+ @require_accelerator
262
+ def test_to_device(self):
263
+ components = self.get_dummy_components()
264
+ pipe = self.pipeline_class(**components)
265
+ pipe.set_progress_bar_config(disable=None)
266
+
267
+ pipe.to("cpu")
268
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
269
+ model_devices = [
270
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
271
+ ]
272
+ self.assertTrue(all(device == "cpu" for device in model_devices))
273
+
274
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
275
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
276
+
277
+ pipe.to(torch_device)
278
+ model_devices = [
279
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
280
+ ]
281
+ self.assertTrue(all(device == torch_device for device in model_devices))
282
+
283
+ output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
284
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
285
+
286
+ def test_to_dtype(self):
287
+ components = self.get_dummy_components()
288
+ pipe = self.pipeline_class(**components)
289
+ pipe.set_progress_bar_config(disable=None)
290
+
291
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
292
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
293
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
294
+
295
+ pipe.to(dtype=torch.float16)
296
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
297
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
298
+
299
+ def test_prompt_embeds(self):
300
+ components = self.get_dummy_components()
301
+ pipe = self.pipeline_class(**components)
302
+ pipe.set_progress_bar_config(disable=None)
303
+ pipe.to(torch_device)
304
+
305
+ inputs = self.get_dummy_inputs(torch_device)
306
+ inputs.pop("prompt")
307
+ inputs["prompt_embeds"] = torch.randn((1, 4, pipe.text_encoder.config.hidden_size), device=torch_device)
308
+ pipe(**inputs)
309
+
310
+ def test_latent_inputs(self):
311
+ components = self.get_dummy_components()
312
+ pipe = self.pipeline_class(**components)
313
+ pipe.set_progress_bar_config(disable=None)
314
+ pipe.to(torch_device)
315
+
316
+ inputs = self.get_dummy_inputs(torch_device)
317
+ sample_size = pipe.unet.config.sample_size
318
+ inputs["latents"] = torch.randn((1, 4, 1, sample_size, sample_size), device=torch_device)
319
+ inputs.pop("video")
320
+ pipe(**inputs)
321
+
322
+ @unittest.skipIf(
323
+ torch_device != "cuda" or not is_xformers_available(),
324
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
325
+ )
326
+ def test_xformers_attention_forwardGenerator_pass(self):
327
+ components = self.get_dummy_components()
328
+ pipe = self.pipeline_class(**components)
329
+ for component in pipe.components.values():
330
+ if hasattr(component, "set_default_attn_processor"):
331
+ component.set_default_attn_processor()
332
+ pipe.to(torch_device)
333
+ pipe.set_progress_bar_config(disable=None)
334
+
335
+ inputs = self.get_dummy_inputs(torch_device)
336
+ output_without_offload = pipe(**inputs).frames[0]
337
+ output_without_offload = (
338
+ output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
339
+ )
340
+
341
+ pipe.enable_xformers_memory_efficient_attention()
342
+ inputs = self.get_dummy_inputs(torch_device)
343
+ output_with_offload = pipe(**inputs).frames[0]
344
+ output_with_offload = (
345
+ output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
346
+ )
347
+
348
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
349
+ self.assertLess(max_diff, 1e-4, "XFormers attention should not affect the inference results")
350
+
351
+ def test_free_init(self):
352
+ components = self.get_dummy_components()
353
+ pipe = self.pipeline_class(**components)
354
+ pipe.set_progress_bar_config(disable=None)
355
+ pipe.to(torch_device)
356
+
357
+ inputs_normal = self.get_dummy_inputs(torch_device)
358
+ frames_normal = pipe(**inputs_normal).frames[0]
359
+
360
+ pipe.enable_free_init(
361
+ num_iters=2,
362
+ use_fast_sampling=True,
363
+ method="butterworth",
364
+ order=4,
365
+ spatial_stop_frequency=0.25,
366
+ temporal_stop_frequency=0.25,
367
+ )
368
+ inputs_enable_free_init = self.get_dummy_inputs(torch_device)
369
+ frames_enable_free_init = pipe(**inputs_enable_free_init).frames[0]
370
+
371
+ pipe.disable_free_init()
372
+ inputs_disable_free_init = self.get_dummy_inputs(torch_device)
373
+ frames_disable_free_init = pipe(**inputs_disable_free_init).frames[0]
374
+
375
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
376
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_init)).max()
377
+ self.assertGreater(
378
+ sum_enabled, 1e1, "Enabling of FreeInit should lead to results different from the default pipeline results"
379
+ )
380
+ self.assertLess(
381
+ max_diff_disabled,
382
+ 1e-4,
383
+ "Disabling of FreeInit should lead to results similar to the default pipeline results",
384
+ )
385
+
386
+ def test_free_init_with_schedulers(self):
387
+ components = self.get_dummy_components()
388
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
389
+ pipe.set_progress_bar_config(disable=None)
390
+ pipe.to(torch_device)
391
+
392
+ inputs_normal = self.get_dummy_inputs(torch_device)
393
+ frames_normal = pipe(**inputs_normal).frames[0]
394
+
395
+ schedulers_to_test = [
396
+ DPMSolverMultistepScheduler.from_config(
397
+ components["scheduler"].config,
398
+ timestep_spacing="linspace",
399
+ beta_schedule="linear",
400
+ algorithm_type="dpmsolver++",
401
+ steps_offset=1,
402
+ clip_sample=False,
403
+ ),
404
+ LCMScheduler.from_config(
405
+ components["scheduler"].config,
406
+ timestep_spacing="linspace",
407
+ beta_schedule="linear",
408
+ steps_offset=1,
409
+ clip_sample=False,
410
+ ),
411
+ ]
412
+ components.pop("scheduler")
413
+
414
+ for scheduler in schedulers_to_test:
415
+ components["scheduler"] = scheduler
416
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
417
+ pipe.set_progress_bar_config(disable=None)
418
+ pipe.to(torch_device)
419
+
420
+ pipe.enable_free_init(num_iters=2, use_fast_sampling=False)
421
+
422
+ inputs = self.get_dummy_inputs(torch_device)
423
+ frames_enable_free_init = pipe(**inputs).frames[0]
424
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
425
+
426
+ self.assertGreater(
427
+ sum_enabled,
428
+ 1e1,
429
+ "Enabling of FreeInit should lead to results different from the default pipeline results",
430
+ )
431
+
432
+ def test_free_noise_blocks(self):
433
+ components = self.get_dummy_components()
434
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
435
+ pipe.set_progress_bar_config(disable=None)
436
+ pipe.to(torch_device)
437
+
438
+ pipe.enable_free_noise()
439
+ for block in pipe.unet.down_blocks:
440
+ for motion_module in block.motion_modules:
441
+ for transformer_block in motion_module.transformer_blocks:
442
+ self.assertTrue(
443
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
444
+ "Motion module transformer blocks must be an instance of `FreeNoiseTransformerBlock` after enabling FreeNoise.",
445
+ )
446
+
447
+ pipe.disable_free_noise()
448
+ for block in pipe.unet.down_blocks:
449
+ for motion_module in block.motion_modules:
450
+ for transformer_block in motion_module.transformer_blocks:
451
+ self.assertFalse(
452
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
453
+ "Motion module transformer blocks must not be an instance of `FreeNoiseTransformerBlock` after disabling FreeNoise.",
454
+ )
455
+
456
+ def test_free_noise(self):
457
+ components = self.get_dummy_components()
458
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
459
+ pipe.set_progress_bar_config(disable=None)
460
+ pipe.to(torch_device)
461
+
462
+ inputs_normal = self.get_dummy_inputs(torch_device, num_frames=16)
463
+ inputs_normal["num_inference_steps"] = 2
464
+ inputs_normal["strength"] = 0.5
465
+ frames_normal = pipe(**inputs_normal).frames[0]
466
+
467
+ for context_length in [8, 9]:
468
+ for context_stride in [4, 6]:
469
+ pipe.enable_free_noise(context_length, context_stride)
470
+
471
+ inputs_enable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
472
+ inputs_enable_free_noise["num_inference_steps"] = 2
473
+ inputs_enable_free_noise["strength"] = 0.5
474
+ frames_enable_free_noise = pipe(**inputs_enable_free_noise).frames[0]
475
+
476
+ pipe.disable_free_noise()
477
+ inputs_disable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
478
+ inputs_disable_free_noise["num_inference_steps"] = 2
479
+ inputs_disable_free_noise["strength"] = 0.5
480
+ frames_disable_free_noise = pipe(**inputs_disable_free_noise).frames[0]
481
+
482
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_noise)).sum()
483
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_noise)).max()
484
+ self.assertGreater(
485
+ sum_enabled,
486
+ 1e1,
487
+ "Enabling of FreeNoise should lead to results different from the default pipeline results",
488
+ )
489
+ self.assertLess(
490
+ max_diff_disabled,
491
+ 1e-4,
492
+ "Disabling of FreeNoise should lead to results similar to the default pipeline results",
493
+ )
494
+
495
+ def test_free_noise_split_inference(self):
496
+ components = self.get_dummy_components()
497
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
498
+ pipe.set_progress_bar_config(disable=None)
499
+ pipe.to(torch_device)
500
+
501
+ pipe.enable_free_noise(8, 4)
502
+
503
+ inputs_normal = self.get_dummy_inputs(torch_device, num_frames=16)
504
+ inputs_normal["num_inference_steps"] = 2
505
+ inputs_normal["strength"] = 0.5
506
+ frames_normal = pipe(**inputs_normal).frames[0]
507
+
508
+ # Test FreeNoise with split inference memory-optimization
509
+ pipe.enable_free_noise_split_inference(spatial_split_size=16, temporal_split_size=4)
510
+
511
+ inputs_enable_split_inference = self.get_dummy_inputs(torch_device, num_frames=16)
512
+ inputs_enable_split_inference["num_inference_steps"] = 2
513
+ inputs_enable_split_inference["strength"] = 0.5
514
+ frames_enable_split_inference = pipe(**inputs_enable_split_inference).frames[0]
515
+
516
+ sum_split_inference = np.abs(to_np(frames_normal) - to_np(frames_enable_split_inference)).sum()
517
+ self.assertLess(
518
+ sum_split_inference,
519
+ 1e-4,
520
+ "Enabling FreeNoise Split Inference memory-optimizations should lead to results similar to the default pipeline results",
521
+ )
522
+
523
+ def test_free_noise_multi_prompt(self):
524
+ components = self.get_dummy_components()
525
+ pipe: AnimateDiffVideoToVideoPipeline = self.pipeline_class(**components)
526
+ pipe.set_progress_bar_config(disable=None)
527
+ pipe.to(torch_device)
528
+
529
+ context_length = 8
530
+ context_stride = 4
531
+ pipe.enable_free_noise(context_length, context_stride)
532
+
533
+ # Make sure that pipeline works when prompt indices are within num_frames bounds
534
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
535
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf"}
536
+ inputs["num_inference_steps"] = 2
537
+ inputs["strength"] = 0.5
538
+ pipe(**inputs).frames[0]
539
+
540
+ with self.assertRaises(ValueError):
541
+ # Ensure that prompt indices are within bounds
542
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
543
+ inputs["num_inference_steps"] = 2
544
+ inputs["strength"] = 0.5
545
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf", 42: "Error on a leaf"}
546
+ pipe(**inputs).frames[0]
547
+
548
+ def test_encode_prompt_works_in_isolation(self):
549
+ extra_required_param_value_dict = {
550
+ "device": torch.device(torch_device).type,
551
+ "num_images_per_prompt": 1,
552
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
553
+ }
554
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
diffusers/tests/pipelines/animatediff/test_animatediff_video2video_controlnet.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
7
+
8
+ import diffusers
9
+ from diffusers import (
10
+ AnimateDiffVideoToVideoControlNetPipeline,
11
+ AutoencoderKL,
12
+ ControlNetModel,
13
+ DDIMScheduler,
14
+ DPMSolverMultistepScheduler,
15
+ LCMScheduler,
16
+ MotionAdapter,
17
+ StableDiffusionPipeline,
18
+ UNet2DConditionModel,
19
+ UNetMotionModel,
20
+ )
21
+ from diffusers.models.attention import FreeNoiseTransformerBlock
22
+ from diffusers.utils import is_xformers_available, logging
23
+
24
+ from ...testing_utils import require_accelerator, torch_device
25
+ from ..pipeline_params import TEXT_TO_IMAGE_PARAMS, VIDEO_TO_VIDEO_BATCH_PARAMS
26
+ from ..test_pipelines_common import IPAdapterTesterMixin, PipelineFromPipeTesterMixin, PipelineTesterMixin
27
+
28
+
29
+ def to_np(tensor):
30
+ if isinstance(tensor, torch.Tensor):
31
+ tensor = tensor.detach().cpu().numpy()
32
+
33
+ return tensor
34
+
35
+
36
+ class AnimateDiffVideoToVideoControlNetPipelineFastTests(
37
+ IPAdapterTesterMixin, PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase
38
+ ):
39
+ pipeline_class = AnimateDiffVideoToVideoControlNetPipeline
40
+ params = TEXT_TO_IMAGE_PARAMS
41
+ batch_params = VIDEO_TO_VIDEO_BATCH_PARAMS.union({"conditioning_frames"})
42
+ required_optional_params = frozenset(
43
+ [
44
+ "num_inference_steps",
45
+ "generator",
46
+ "latents",
47
+ "return_dict",
48
+ "callback_on_step_end",
49
+ "callback_on_step_end_tensor_inputs",
50
+ ]
51
+ )
52
+
53
+ def get_dummy_components(self):
54
+ cross_attention_dim = 8
55
+ block_out_channels = (8, 8)
56
+
57
+ torch.manual_seed(0)
58
+ unet = UNet2DConditionModel(
59
+ block_out_channels=block_out_channels,
60
+ layers_per_block=2,
61
+ sample_size=8,
62
+ in_channels=4,
63
+ out_channels=4,
64
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
65
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
66
+ cross_attention_dim=cross_attention_dim,
67
+ norm_num_groups=2,
68
+ )
69
+ scheduler = DDIMScheduler(
70
+ beta_start=0.00085,
71
+ beta_end=0.012,
72
+ beta_schedule="linear",
73
+ clip_sample=False,
74
+ )
75
+ torch.manual_seed(0)
76
+ controlnet = ControlNetModel(
77
+ block_out_channels=block_out_channels,
78
+ layers_per_block=2,
79
+ in_channels=4,
80
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
81
+ cross_attention_dim=cross_attention_dim,
82
+ conditioning_embedding_out_channels=(8, 8),
83
+ norm_num_groups=1,
84
+ )
85
+ torch.manual_seed(0)
86
+ vae = AutoencoderKL(
87
+ block_out_channels=block_out_channels,
88
+ in_channels=3,
89
+ out_channels=3,
90
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
91
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
92
+ latent_channels=4,
93
+ norm_num_groups=2,
94
+ )
95
+ torch.manual_seed(0)
96
+ text_encoder_config = CLIPTextConfig(
97
+ bos_token_id=0,
98
+ eos_token_id=2,
99
+ hidden_size=cross_attention_dim,
100
+ intermediate_size=37,
101
+ layer_norm_eps=1e-05,
102
+ num_attention_heads=4,
103
+ num_hidden_layers=5,
104
+ pad_token_id=1,
105
+ vocab_size=1000,
106
+ )
107
+ text_encoder = CLIPTextModel(text_encoder_config)
108
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
109
+ torch.manual_seed(0)
110
+ motion_adapter = MotionAdapter(
111
+ block_out_channels=block_out_channels,
112
+ motion_layers_per_block=2,
113
+ motion_norm_num_groups=2,
114
+ motion_num_attention_heads=4,
115
+ )
116
+
117
+ components = {
118
+ "unet": unet,
119
+ "controlnet": controlnet,
120
+ "scheduler": scheduler,
121
+ "vae": vae,
122
+ "motion_adapter": motion_adapter,
123
+ "text_encoder": text_encoder,
124
+ "tokenizer": tokenizer,
125
+ "feature_extractor": None,
126
+ "image_encoder": None,
127
+ }
128
+ return components
129
+
130
+ def get_dummy_inputs(self, device, seed=0, num_frames: int = 2):
131
+ if str(device).startswith("mps"):
132
+ generator = torch.manual_seed(seed)
133
+ else:
134
+ generator = torch.Generator(device=device).manual_seed(seed)
135
+
136
+ video_height = 32
137
+ video_width = 32
138
+ video = [Image.new("RGB", (video_width, video_height))] * num_frames
139
+
140
+ video_height = 32
141
+ video_width = 32
142
+ conditioning_frames = [Image.new("RGB", (video_width, video_height))] * num_frames
143
+
144
+ inputs = {
145
+ "video": video,
146
+ "conditioning_frames": conditioning_frames,
147
+ "prompt": "A painting of a squirrel eating a burger",
148
+ "generator": generator,
149
+ "num_inference_steps": 2,
150
+ "guidance_scale": 7.5,
151
+ "output_type": "pt",
152
+ }
153
+ return inputs
154
+
155
+ def test_from_pipe_consistent_config(self):
156
+ assert self.original_pipeline_class == StableDiffusionPipeline
157
+ original_repo = "hf-internal-testing/tinier-stable-diffusion-pipe"
158
+ original_kwargs = {"requires_safety_checker": False}
159
+
160
+ # create original_pipeline_class(sd)
161
+ pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)
162
+
163
+ # original_pipeline_class(sd) -> pipeline_class
164
+ pipe_components = self.get_dummy_components()
165
+ pipe_additional_components = {}
166
+ for name, component in pipe_components.items():
167
+ if name not in pipe_original.components:
168
+ pipe_additional_components[name] = component
169
+
170
+ pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)
171
+
172
+ # pipeline_class -> original_pipeline_class(sd)
173
+ original_pipe_additional_components = {}
174
+ for name, component in pipe_original.components.items():
175
+ if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
176
+ original_pipe_additional_components[name] = component
177
+
178
+ pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)
179
+
180
+ # compare the config
181
+ original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
182
+ original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
183
+ assert original_config_2 == original_config
184
+
185
+ def test_motion_unet_loading(self):
186
+ components = self.get_dummy_components()
187
+ pipe = AnimateDiffVideoToVideoControlNetPipeline(**components)
188
+
189
+ assert isinstance(pipe.unet, UNetMotionModel)
190
+
191
+ @unittest.skip("Attention slicing is not enabled in this pipeline")
192
+ def test_attention_slicing_forward_pass(self):
193
+ pass
194
+
195
+ def test_ip_adapter(self):
196
+ expected_pipe_slice = None
197
+ if torch_device == "cpu":
198
+ expected_pipe_slice = np.array(
199
+ [
200
+ 0.5569,
201
+ 0.6250,
202
+ 0.4144,
203
+ 0.5613,
204
+ 0.5563,
205
+ 0.5213,
206
+ 0.5091,
207
+ 0.4950,
208
+ 0.4950,
209
+ 0.5684,
210
+ 0.3858,
211
+ 0.4863,
212
+ 0.6457,
213
+ 0.4311,
214
+ 0.5517,
215
+ 0.5608,
216
+ 0.4417,
217
+ 0.5377,
218
+ ]
219
+ )
220
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
221
+
222
+ def test_inference_batch_single_identical(
223
+ self,
224
+ batch_size=2,
225
+ expected_max_diff=1e-4,
226
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
227
+ ):
228
+ components = self.get_dummy_components()
229
+ pipe = self.pipeline_class(**components)
230
+ for components in pipe.components.values():
231
+ if hasattr(components, "set_default_attn_processor"):
232
+ components.set_default_attn_processor()
233
+
234
+ pipe.to(torch_device)
235
+ pipe.set_progress_bar_config(disable=None)
236
+ inputs = self.get_dummy_inputs(torch_device)
237
+ # Reset generator in case it is has been used in self.get_dummy_inputs
238
+ inputs["generator"] = self.get_generator(0)
239
+
240
+ logger = logging.get_logger(pipe.__module__)
241
+ logger.setLevel(level=diffusers.logging.FATAL)
242
+
243
+ # batchify inputs
244
+ batched_inputs = {}
245
+ batched_inputs.update(inputs)
246
+
247
+ for name in self.batch_params:
248
+ if name not in inputs:
249
+ continue
250
+
251
+ value = inputs[name]
252
+ if name == "prompt":
253
+ len_prompt = len(value)
254
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
255
+ batched_inputs[name][-1] = 100 * "very long"
256
+
257
+ else:
258
+ batched_inputs[name] = batch_size * [value]
259
+
260
+ if "generator" in inputs:
261
+ batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
262
+
263
+ if "batch_size" in inputs:
264
+ batched_inputs["batch_size"] = batch_size
265
+
266
+ for arg in additional_params_copy_to_batched_inputs:
267
+ batched_inputs[arg] = inputs[arg]
268
+
269
+ output = pipe(**inputs)
270
+ output_batch = pipe(**batched_inputs)
271
+
272
+ assert output_batch[0].shape[0] == batch_size
273
+
274
+ max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
275
+ assert max_diff < expected_max_diff
276
+
277
+ @require_accelerator
278
+ def test_to_device(self):
279
+ components = self.get_dummy_components()
280
+ pipe = self.pipeline_class(**components)
281
+ pipe.set_progress_bar_config(disable=None)
282
+
283
+ pipe.to("cpu")
284
+ # pipeline creates a new motion UNet under the hood. So we need to check the device from pipe.components
285
+ model_devices = [
286
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
287
+ ]
288
+ self.assertTrue(all(device == "cpu" for device in model_devices))
289
+
290
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
291
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
292
+
293
+ pipe.to(torch_device)
294
+ model_devices = [
295
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
296
+ ]
297
+ self.assertTrue(all(device == torch_device for device in model_devices))
298
+
299
+ output_cuda = pipe(**self.get_dummy_inputs(torch_device))[0]
300
+ self.assertTrue(np.isnan(to_np(output_cuda)).sum() == 0)
301
+
302
+ def test_to_dtype(self):
303
+ components = self.get_dummy_components()
304
+ pipe = self.pipeline_class(**components)
305
+ pipe.set_progress_bar_config(disable=None)
306
+
307
+ # pipeline creates a new motion UNet under the hood. So we need to check the dtype from pipe.components
308
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
309
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
310
+
311
+ pipe.to(dtype=torch.float16)
312
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
313
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
314
+
315
+ def test_prompt_embeds(self):
316
+ components = self.get_dummy_components()
317
+ pipe = self.pipeline_class(**components)
318
+ pipe.set_progress_bar_config(disable=None)
319
+ pipe.to(torch_device)
320
+
321
+ inputs = self.get_dummy_inputs(torch_device)
322
+ inputs.pop("prompt")
323
+ inputs["prompt_embeds"] = torch.randn((1, 4, pipe.text_encoder.config.hidden_size), device=torch_device)
324
+ pipe(**inputs)
325
+
326
+ def test_latent_inputs(self):
327
+ components = self.get_dummy_components()
328
+ pipe = self.pipeline_class(**components)
329
+ pipe.set_progress_bar_config(disable=None)
330
+ pipe.to(torch_device)
331
+
332
+ inputs = self.get_dummy_inputs(torch_device)
333
+ sample_size = pipe.unet.config.sample_size
334
+ num_frames = len(inputs["conditioning_frames"])
335
+ inputs["latents"] = torch.randn((1, 4, num_frames, sample_size, sample_size), device=torch_device)
336
+ inputs.pop("video")
337
+ pipe(**inputs)
338
+
339
+ @unittest.skipIf(
340
+ torch_device != "cuda" or not is_xformers_available(),
341
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
342
+ )
343
+ def test_xformers_attention_forwardGenerator_pass(self):
344
+ components = self.get_dummy_components()
345
+ pipe = self.pipeline_class(**components)
346
+ for component in pipe.components.values():
347
+ if hasattr(component, "set_default_attn_processor"):
348
+ component.set_default_attn_processor()
349
+ pipe.to(torch_device)
350
+ pipe.set_progress_bar_config(disable=None)
351
+
352
+ inputs = self.get_dummy_inputs(torch_device)
353
+ output_without_offload = pipe(**inputs).frames[0]
354
+ output_without_offload = (
355
+ output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
356
+ )
357
+
358
+ pipe.enable_xformers_memory_efficient_attention()
359
+ inputs = self.get_dummy_inputs(torch_device)
360
+ output_with_offload = pipe(**inputs).frames[0]
361
+ output_with_offload = (
362
+ output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
363
+ )
364
+
365
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
366
+ self.assertLess(max_diff, 1e-4, "XFormers attention should not affect the inference results")
367
+
368
+ def test_free_init(self):
369
+ components = self.get_dummy_components()
370
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
371
+ pipe.set_progress_bar_config(disable=None)
372
+ pipe.to(torch_device)
373
+
374
+ inputs_normal = self.get_dummy_inputs(torch_device)
375
+ frames_normal = pipe(**inputs_normal).frames[0]
376
+
377
+ pipe.enable_free_init(
378
+ num_iters=2,
379
+ use_fast_sampling=True,
380
+ method="butterworth",
381
+ order=4,
382
+ spatial_stop_frequency=0.25,
383
+ temporal_stop_frequency=0.25,
384
+ )
385
+ inputs_enable_free_init = self.get_dummy_inputs(torch_device)
386
+ frames_enable_free_init = pipe(**inputs_enable_free_init).frames[0]
387
+
388
+ pipe.disable_free_init()
389
+ inputs_disable_free_init = self.get_dummy_inputs(torch_device)
390
+ frames_disable_free_init = pipe(**inputs_disable_free_init).frames[0]
391
+
392
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
393
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_init)).max()
394
+ self.assertGreater(
395
+ sum_enabled, 1e1, "Enabling of FreeInit should lead to results different from the default pipeline results"
396
+ )
397
+ self.assertLess(
398
+ max_diff_disabled,
399
+ 1e-4,
400
+ "Disabling of FreeInit should lead to results similar to the default pipeline results",
401
+ )
402
+
403
+ def test_free_init_with_schedulers(self):
404
+ components = self.get_dummy_components()
405
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
406
+ pipe.set_progress_bar_config(disable=None)
407
+ pipe.to(torch_device)
408
+
409
+ inputs_normal = self.get_dummy_inputs(torch_device)
410
+ frames_normal = pipe(**inputs_normal).frames[0]
411
+
412
+ schedulers_to_test = [
413
+ DPMSolverMultistepScheduler.from_config(
414
+ components["scheduler"].config,
415
+ timestep_spacing="linspace",
416
+ beta_schedule="linear",
417
+ algorithm_type="dpmsolver++",
418
+ steps_offset=1,
419
+ clip_sample=False,
420
+ ),
421
+ LCMScheduler.from_config(
422
+ components["scheduler"].config,
423
+ timestep_spacing="linspace",
424
+ beta_schedule="linear",
425
+ steps_offset=1,
426
+ clip_sample=False,
427
+ ),
428
+ ]
429
+ components.pop("scheduler")
430
+
431
+ for scheduler in schedulers_to_test:
432
+ components["scheduler"] = scheduler
433
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
434
+ pipe.set_progress_bar_config(disable=None)
435
+ pipe.to(torch_device)
436
+
437
+ pipe.enable_free_init(num_iters=2, use_fast_sampling=False)
438
+
439
+ inputs = self.get_dummy_inputs(torch_device)
440
+ frames_enable_free_init = pipe(**inputs).frames[0]
441
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_init)).sum()
442
+
443
+ self.assertGreater(
444
+ sum_enabled,
445
+ 1e1,
446
+ "Enabling of FreeInit should lead to results different from the default pipeline results",
447
+ )
448
+
449
+ def test_free_noise_blocks(self):
450
+ components = self.get_dummy_components()
451
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
452
+ pipe.set_progress_bar_config(disable=None)
453
+ pipe.to(torch_device)
454
+
455
+ pipe.enable_free_noise()
456
+ for block in pipe.unet.down_blocks:
457
+ for motion_module in block.motion_modules:
458
+ for transformer_block in motion_module.transformer_blocks:
459
+ self.assertTrue(
460
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
461
+ "Motion module transformer blocks must be an instance of `FreeNoiseTransformerBlock` after enabling FreeNoise.",
462
+ )
463
+
464
+ pipe.disable_free_noise()
465
+ for block in pipe.unet.down_blocks:
466
+ for motion_module in block.motion_modules:
467
+ for transformer_block in motion_module.transformer_blocks:
468
+ self.assertFalse(
469
+ isinstance(transformer_block, FreeNoiseTransformerBlock),
470
+ "Motion module transformer blocks must not be an instance of `FreeNoiseTransformerBlock` after disabling FreeNoise.",
471
+ )
472
+
473
+ def test_free_noise(self):
474
+ components = self.get_dummy_components()
475
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
476
+ pipe.set_progress_bar_config(disable=None)
477
+ pipe.to(torch_device)
478
+
479
+ inputs_normal = self.get_dummy_inputs(torch_device, num_frames=16)
480
+ inputs_normal["num_inference_steps"] = 2
481
+ inputs_normal["strength"] = 0.5
482
+ frames_normal = pipe(**inputs_normal).frames[0]
483
+
484
+ for context_length in [8, 9]:
485
+ for context_stride in [4, 6]:
486
+ pipe.enable_free_noise(context_length, context_stride)
487
+
488
+ inputs_enable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
489
+ inputs_enable_free_noise["num_inference_steps"] = 2
490
+ inputs_enable_free_noise["strength"] = 0.5
491
+ frames_enable_free_noise = pipe(**inputs_enable_free_noise).frames[0]
492
+
493
+ pipe.disable_free_noise()
494
+ inputs_disable_free_noise = self.get_dummy_inputs(torch_device, num_frames=16)
495
+ inputs_disable_free_noise["num_inference_steps"] = 2
496
+ inputs_disable_free_noise["strength"] = 0.5
497
+ frames_disable_free_noise = pipe(**inputs_disable_free_noise).frames[0]
498
+
499
+ sum_enabled = np.abs(to_np(frames_normal) - to_np(frames_enable_free_noise)).sum()
500
+ max_diff_disabled = np.abs(to_np(frames_normal) - to_np(frames_disable_free_noise)).max()
501
+ self.assertGreater(
502
+ sum_enabled,
503
+ 1e1,
504
+ "Enabling of FreeNoise should lead to results different from the default pipeline results",
505
+ )
506
+ self.assertLess(
507
+ max_diff_disabled,
508
+ 1e-4,
509
+ "Disabling of FreeNoise should lead to results similar to the default pipeline results",
510
+ )
511
+
512
+ def test_free_noise_multi_prompt(self):
513
+ components = self.get_dummy_components()
514
+ pipe: AnimateDiffVideoToVideoControlNetPipeline = self.pipeline_class(**components)
515
+ pipe.set_progress_bar_config(disable=None)
516
+ pipe.to(torch_device)
517
+
518
+ context_length = 8
519
+ context_stride = 4
520
+ pipe.enable_free_noise(context_length, context_stride)
521
+
522
+ # Make sure that pipeline works when prompt indices are within num_frames bounds
523
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
524
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf"}
525
+ inputs["num_inference_steps"] = 2
526
+ inputs["strength"] = 0.5
527
+ pipe(**inputs).frames[0]
528
+
529
+ with self.assertRaises(ValueError):
530
+ # Ensure that prompt indices are within bounds
531
+ inputs = self.get_dummy_inputs(torch_device, num_frames=16)
532
+ inputs["num_inference_steps"] = 2
533
+ inputs["strength"] = 0.5
534
+ inputs["prompt"] = {0: "Caterpillar on a leaf", 10: "Butterfly on a leaf", 42: "Error on a leaf"}
535
+ pipe(**inputs).frames[0]
536
+
537
+ def test_encode_prompt_works_in_isolation(self):
538
+ extra_required_param_value_dict = {
539
+ "device": torch.device(torch_device).type,
540
+ "num_images_per_prompt": 1,
541
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
542
+ }
543
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
diffusers/tests/pipelines/audioldm2/__init__.py ADDED
File without changes
diffusers/tests/pipelines/audioldm2/test_audioldm2.py ADDED
@@ -0,0 +1,667 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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
+
17
+ import gc
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import pytest
22
+ import torch
23
+ from transformers import (
24
+ ClapConfig,
25
+ ClapFeatureExtractor,
26
+ ClapModel,
27
+ GPT2Config,
28
+ GPT2LMHeadModel,
29
+ RobertaTokenizer,
30
+ SpeechT5HifiGan,
31
+ SpeechT5HifiGanConfig,
32
+ T5Config,
33
+ T5EncoderModel,
34
+ T5Tokenizer,
35
+ )
36
+
37
+ from diffusers import (
38
+ AudioLDM2Pipeline,
39
+ AudioLDM2ProjectionModel,
40
+ AudioLDM2UNet2DConditionModel,
41
+ AutoencoderKL,
42
+ DDIMScheduler,
43
+ LMSDiscreteScheduler,
44
+ PNDMScheduler,
45
+ )
46
+ from diffusers.utils import is_transformers_version
47
+
48
+ from ...testing_utils import (
49
+ backend_empty_cache,
50
+ enable_full_determinism,
51
+ is_torch_version,
52
+ nightly,
53
+ torch_device,
54
+ )
55
+ from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
56
+ from ..test_pipelines_common import PipelineTesterMixin
57
+
58
+
59
+ enable_full_determinism()
60
+
61
+
62
+ class AudioLDM2PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
63
+ pipeline_class = AudioLDM2Pipeline
64
+ params = TEXT_TO_AUDIO_PARAMS
65
+ batch_params = TEXT_TO_AUDIO_BATCH_PARAMS
66
+ required_optional_params = frozenset(
67
+ [
68
+ "num_inference_steps",
69
+ "num_waveforms_per_prompt",
70
+ "generator",
71
+ "latents",
72
+ "output_type",
73
+ "return_dict",
74
+ "callback",
75
+ "callback_steps",
76
+ ]
77
+ )
78
+
79
+ supports_dduf = False
80
+
81
+ def get_dummy_components(self):
82
+ torch.manual_seed(0)
83
+ unet = AudioLDM2UNet2DConditionModel(
84
+ block_out_channels=(8, 16),
85
+ layers_per_block=1,
86
+ norm_num_groups=8,
87
+ sample_size=32,
88
+ in_channels=4,
89
+ out_channels=4,
90
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
91
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
92
+ cross_attention_dim=(8, 16),
93
+ )
94
+ scheduler = DDIMScheduler(
95
+ beta_start=0.00085,
96
+ beta_end=0.012,
97
+ beta_schedule="scaled_linear",
98
+ clip_sample=False,
99
+ set_alpha_to_one=False,
100
+ )
101
+ torch.manual_seed(0)
102
+ vae = AutoencoderKL(
103
+ block_out_channels=[8, 16],
104
+ in_channels=1,
105
+ out_channels=1,
106
+ norm_num_groups=8,
107
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
108
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
109
+ latent_channels=4,
110
+ )
111
+ torch.manual_seed(0)
112
+ text_branch_config = {
113
+ "bos_token_id": 0,
114
+ "eos_token_id": 2,
115
+ "hidden_size": 8,
116
+ "intermediate_size": 37,
117
+ "layer_norm_eps": 1e-05,
118
+ "num_attention_heads": 1,
119
+ "num_hidden_layers": 1,
120
+ "pad_token_id": 1,
121
+ "vocab_size": 1000,
122
+ "projection_dim": 8,
123
+ }
124
+ audio_branch_config = {
125
+ "spec_size": 8,
126
+ "window_size": 4,
127
+ "num_mel_bins": 8,
128
+ "intermediate_size": 37,
129
+ "layer_norm_eps": 1e-05,
130
+ "depths": [1, 1],
131
+ "num_attention_heads": [1, 1],
132
+ "num_hidden_layers": 1,
133
+ "hidden_size": 192,
134
+ "projection_dim": 8,
135
+ "patch_size": 2,
136
+ "patch_stride": 2,
137
+ "patch_embed_input_channels": 4,
138
+ }
139
+ text_encoder_config = ClapConfig(
140
+ text_config=text_branch_config, audio_config=audio_branch_config, projection_dim=16
141
+ )
142
+ text_encoder = ClapModel(text_encoder_config)
143
+ tokenizer = RobertaTokenizer.from_pretrained("hf-internal-testing/tiny-random-roberta", model_max_length=77)
144
+ feature_extractor = ClapFeatureExtractor.from_pretrained(
145
+ "hf-internal-testing/tiny-random-ClapModel", hop_length=7900
146
+ )
147
+
148
+ torch.manual_seed(0)
149
+ text_encoder_2_config = T5Config(
150
+ vocab_size=32100,
151
+ d_model=32,
152
+ d_ff=37,
153
+ d_kv=8,
154
+ num_heads=1,
155
+ num_layers=1,
156
+ )
157
+ text_encoder_2 = T5EncoderModel(text_encoder_2_config)
158
+ tokenizer_2 = T5Tokenizer.from_pretrained("hf-internal-testing/tiny-random-T5Model", model_max_length=77)
159
+
160
+ torch.manual_seed(0)
161
+ language_model_config = GPT2Config(
162
+ n_embd=16,
163
+ n_head=1,
164
+ n_layer=1,
165
+ vocab_size=1000,
166
+ n_ctx=99,
167
+ n_positions=99,
168
+ )
169
+ language_model = GPT2LMHeadModel(language_model_config)
170
+ language_model.config.max_new_tokens = 8
171
+
172
+ torch.manual_seed(0)
173
+ projection_model = AudioLDM2ProjectionModel(
174
+ text_encoder_dim=16,
175
+ text_encoder_1_dim=32,
176
+ langauge_model_dim=16,
177
+ )
178
+
179
+ vocoder_config = SpeechT5HifiGanConfig(
180
+ model_in_dim=8,
181
+ sampling_rate=16000,
182
+ upsample_initial_channel=16,
183
+ upsample_rates=[2, 2],
184
+ upsample_kernel_sizes=[4, 4],
185
+ resblock_kernel_sizes=[3, 7],
186
+ resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]],
187
+ normalize_before=False,
188
+ )
189
+
190
+ vocoder = SpeechT5HifiGan(vocoder_config)
191
+
192
+ components = {
193
+ "unet": unet,
194
+ "scheduler": scheduler,
195
+ "vae": vae,
196
+ "text_encoder": text_encoder,
197
+ "text_encoder_2": text_encoder_2,
198
+ "tokenizer": tokenizer,
199
+ "tokenizer_2": tokenizer_2,
200
+ "feature_extractor": feature_extractor,
201
+ "language_model": language_model,
202
+ "projection_model": projection_model,
203
+ "vocoder": vocoder,
204
+ }
205
+ return components
206
+
207
+ def get_dummy_inputs(self, device, seed=0):
208
+ if str(device).startswith("mps"):
209
+ generator = torch.manual_seed(seed)
210
+ else:
211
+ generator = torch.Generator(device=device).manual_seed(seed)
212
+ inputs = {
213
+ "prompt": "A hammer hitting a wooden surface",
214
+ "generator": generator,
215
+ "num_inference_steps": 2,
216
+ "guidance_scale": 6.0,
217
+ }
218
+ return inputs
219
+
220
+ @pytest.mark.xfail(
221
+ condition=is_transformers_version(">=", "4.54.1"),
222
+ reason="Test currently fails on Transformers version 4.54.1.",
223
+ strict=False,
224
+ )
225
+ def test_audioldm2_ddim(self):
226
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
227
+
228
+ components = self.get_dummy_components()
229
+ audioldm_pipe = AudioLDM2Pipeline(**components)
230
+ audioldm_pipe = audioldm_pipe.to(torch_device)
231
+ audioldm_pipe.set_progress_bar_config(disable=None)
232
+
233
+ inputs = self.get_dummy_inputs(device)
234
+ output = audioldm_pipe(**inputs)
235
+ audio = output.audios[0]
236
+
237
+ assert audio.ndim == 1
238
+ assert len(audio) == 256
239
+
240
+ audio_slice = audio[:10]
241
+ expected_slice = np.array(
242
+ [
243
+ 2.602e-03,
244
+ 1.729e-03,
245
+ 1.863e-03,
246
+ -2.219e-03,
247
+ -2.656e-03,
248
+ -2.017e-03,
249
+ -2.648e-03,
250
+ -2.115e-03,
251
+ -2.502e-03,
252
+ -2.081e-03,
253
+ ]
254
+ )
255
+
256
+ assert np.abs(audio_slice - expected_slice).max() < 1e-4
257
+
258
+ def test_audioldm2_prompt_embeds(self):
259
+ components = self.get_dummy_components()
260
+ audioldm_pipe = AudioLDM2Pipeline(**components)
261
+ audioldm_pipe = audioldm_pipe.to(torch_device)
262
+ audioldm_pipe = audioldm_pipe.to(torch_device)
263
+ audioldm_pipe.set_progress_bar_config(disable=None)
264
+
265
+ inputs = self.get_dummy_inputs(torch_device)
266
+ inputs["prompt"] = 3 * [inputs["prompt"]]
267
+
268
+ # forward
269
+ output = audioldm_pipe(**inputs)
270
+ audio_1 = output.audios[0]
271
+
272
+ inputs = self.get_dummy_inputs(torch_device)
273
+ prompt = 3 * [inputs.pop("prompt")]
274
+
275
+ text_inputs = audioldm_pipe.tokenizer(
276
+ prompt,
277
+ padding="max_length",
278
+ max_length=audioldm_pipe.tokenizer.model_max_length,
279
+ truncation=True,
280
+ return_tensors="pt",
281
+ )
282
+ text_inputs = text_inputs["input_ids"].to(torch_device)
283
+
284
+ clap_prompt_embeds = audioldm_pipe.text_encoder.get_text_features(text_inputs)
285
+ if hasattr(clap_prompt_embeds, "pooler_output"):
286
+ clap_prompt_embeds = clap_prompt_embeds.pooler_output
287
+ clap_prompt_embeds = clap_prompt_embeds[:, None, :]
288
+
289
+ text_inputs = audioldm_pipe.tokenizer_2(
290
+ prompt,
291
+ padding="max_length",
292
+ max_length=True,
293
+ truncation=True,
294
+ return_tensors="pt",
295
+ )
296
+ text_inputs = text_inputs["input_ids"].to(torch_device)
297
+
298
+ t5_prompt_embeds = audioldm_pipe.text_encoder_2(
299
+ text_inputs,
300
+ )
301
+ t5_prompt_embeds = t5_prompt_embeds[0]
302
+
303
+ projection_embeds = audioldm_pipe.projection_model(clap_prompt_embeds, t5_prompt_embeds)[0]
304
+ generated_prompt_embeds = audioldm_pipe.generate_language_model(projection_embeds, max_new_tokens=8)
305
+
306
+ inputs["prompt_embeds"] = t5_prompt_embeds
307
+ inputs["generated_prompt_embeds"] = generated_prompt_embeds
308
+
309
+ # forward
310
+ output = audioldm_pipe(**inputs)
311
+ audio_2 = output.audios[0]
312
+
313
+ assert np.abs(audio_1 - audio_2).max() < 1e-2
314
+
315
+ def test_audioldm2_negative_prompt_embeds(self):
316
+ components = self.get_dummy_components()
317
+ audioldm_pipe = AudioLDM2Pipeline(**components)
318
+ audioldm_pipe = audioldm_pipe.to(torch_device)
319
+ audioldm_pipe.set_progress_bar_config(disable=None)
320
+
321
+ inputs = self.get_dummy_inputs(torch_device)
322
+ negative_prompt = 3 * ["this is a negative prompt"]
323
+ inputs["negative_prompt"] = negative_prompt
324
+ inputs["prompt"] = 3 * [inputs["prompt"]]
325
+
326
+ # forward
327
+ output = audioldm_pipe(**inputs)
328
+ audio_1 = output.audios[0]
329
+
330
+ inputs = self.get_dummy_inputs(torch_device)
331
+ prompt = 3 * [inputs.pop("prompt")]
332
+
333
+ embeds = []
334
+ generated_embeds = []
335
+ for p in [prompt, negative_prompt]:
336
+ text_inputs = audioldm_pipe.tokenizer(
337
+ p,
338
+ padding="max_length",
339
+ max_length=audioldm_pipe.tokenizer.model_max_length,
340
+ truncation=True,
341
+ return_tensors="pt",
342
+ )
343
+ text_inputs = text_inputs["input_ids"].to(torch_device)
344
+
345
+ clap_prompt_embeds = audioldm_pipe.text_encoder.get_text_features(text_inputs)
346
+ if hasattr(clap_prompt_embeds, "pooler_output"):
347
+ clap_prompt_embeds = clap_prompt_embeds.pooler_output
348
+ clap_prompt_embeds = clap_prompt_embeds[:, None, :]
349
+
350
+ text_inputs = audioldm_pipe.tokenizer_2(
351
+ prompt,
352
+ padding="max_length",
353
+ max_length=True if len(embeds) == 0 else embeds[0].shape[1],
354
+ truncation=True,
355
+ return_tensors="pt",
356
+ )
357
+ text_inputs = text_inputs["input_ids"].to(torch_device)
358
+
359
+ t5_prompt_embeds = audioldm_pipe.text_encoder_2(
360
+ text_inputs,
361
+ )
362
+ t5_prompt_embeds = t5_prompt_embeds[0]
363
+
364
+ projection_embeds = audioldm_pipe.projection_model(clap_prompt_embeds, t5_prompt_embeds)[0]
365
+ generated_prompt_embeds = audioldm_pipe.generate_language_model(projection_embeds, max_new_tokens=8)
366
+
367
+ embeds.append(t5_prompt_embeds)
368
+ generated_embeds.append(generated_prompt_embeds)
369
+
370
+ inputs["prompt_embeds"], inputs["negative_prompt_embeds"] = embeds
371
+ inputs["generated_prompt_embeds"], inputs["negative_generated_prompt_embeds"] = generated_embeds
372
+
373
+ # forward
374
+ output = audioldm_pipe(**inputs)
375
+ audio_2 = output.audios[0]
376
+
377
+ assert np.abs(audio_1 - audio_2).max() < 1e-2
378
+
379
+ @pytest.mark.xfail(
380
+ condition=is_transformers_version(">=", "4.54.1"),
381
+ reason="Test currently fails on Transformers version 4.54.1.",
382
+ strict=False,
383
+ )
384
+ def test_audioldm2_negative_prompt(self):
385
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
386
+ components = self.get_dummy_components()
387
+ components["scheduler"] = PNDMScheduler(skip_prk_steps=True)
388
+ audioldm_pipe = AudioLDM2Pipeline(**components)
389
+ audioldm_pipe = audioldm_pipe.to(device)
390
+ audioldm_pipe.set_progress_bar_config(disable=None)
391
+
392
+ inputs = self.get_dummy_inputs(device)
393
+ negative_prompt = "egg cracking"
394
+ output = audioldm_pipe(**inputs, negative_prompt=negative_prompt)
395
+ audio = output.audios[0]
396
+
397
+ assert audio.ndim == 1
398
+ assert len(audio) == 256
399
+
400
+ audio_slice = audio[:10]
401
+ expected_slice = np.array(
402
+ [0.0026, 0.0017, 0.0018, -0.0022, -0.0026, -0.002, -0.0026, -0.0021, -0.0025, -0.0021]
403
+ )
404
+
405
+ assert np.abs(audio_slice - expected_slice).max() < 1e-4
406
+
407
+ def test_audioldm2_num_waveforms_per_prompt(self):
408
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
409
+ components = self.get_dummy_components()
410
+ components["scheduler"] = PNDMScheduler(skip_prk_steps=True)
411
+ audioldm_pipe = AudioLDM2Pipeline(**components)
412
+ audioldm_pipe = audioldm_pipe.to(device)
413
+ audioldm_pipe.set_progress_bar_config(disable=None)
414
+
415
+ prompt = "A hammer hitting a wooden surface"
416
+
417
+ # test num_waveforms_per_prompt=1 (default)
418
+ audios = audioldm_pipe(prompt, num_inference_steps=2).audios
419
+
420
+ assert audios.shape == (1, 256)
421
+
422
+ # test num_waveforms_per_prompt=1 (default) for batch of prompts
423
+ batch_size = 2
424
+ audios = audioldm_pipe([prompt] * batch_size, num_inference_steps=2).audios
425
+
426
+ assert audios.shape == (batch_size, 256)
427
+
428
+ # test num_waveforms_per_prompt for single prompt
429
+ num_waveforms_per_prompt = 1
430
+ audios = audioldm_pipe(prompt, num_inference_steps=2, num_waveforms_per_prompt=num_waveforms_per_prompt).audios
431
+
432
+ assert audios.shape == (num_waveforms_per_prompt, 256)
433
+
434
+ # test num_waveforms_per_prompt for batch of prompts
435
+ batch_size = 2
436
+ audios = audioldm_pipe(
437
+ [prompt] * batch_size, num_inference_steps=2, num_waveforms_per_prompt=num_waveforms_per_prompt
438
+ ).audios
439
+
440
+ assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)
441
+
442
+ def test_audioldm2_audio_length_in_s(self):
443
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
444
+ components = self.get_dummy_components()
445
+ audioldm_pipe = AudioLDM2Pipeline(**components)
446
+ audioldm_pipe = audioldm_pipe.to(torch_device)
447
+ audioldm_pipe.set_progress_bar_config(disable=None)
448
+ vocoder_sampling_rate = audioldm_pipe.vocoder.config.sampling_rate
449
+
450
+ inputs = self.get_dummy_inputs(device)
451
+ output = audioldm_pipe(audio_length_in_s=0.016, **inputs)
452
+ audio = output.audios[0]
453
+
454
+ assert audio.ndim == 1
455
+ assert len(audio) / vocoder_sampling_rate == 0.016
456
+
457
+ output = audioldm_pipe(audio_length_in_s=0.032, **inputs)
458
+ audio = output.audios[0]
459
+
460
+ assert audio.ndim == 1
461
+ assert len(audio) / vocoder_sampling_rate == 0.032
462
+
463
+ def test_audioldm2_vocoder_model_in_dim(self):
464
+ components = self.get_dummy_components()
465
+ audioldm_pipe = AudioLDM2Pipeline(**components)
466
+ audioldm_pipe = audioldm_pipe.to(torch_device)
467
+ audioldm_pipe.set_progress_bar_config(disable=None)
468
+
469
+ prompt = ["hey"]
470
+
471
+ output = audioldm_pipe(prompt, num_inference_steps=1)
472
+ audio_shape = output.audios.shape
473
+ assert audio_shape == (1, 256)
474
+
475
+ config = audioldm_pipe.vocoder.config
476
+ config.model_in_dim *= 2
477
+ audioldm_pipe.vocoder = SpeechT5HifiGan(config).to(torch_device)
478
+ output = audioldm_pipe(prompt, num_inference_steps=1)
479
+ audio_shape = output.audios.shape
480
+ # waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
481
+ assert audio_shape == (1, 256)
482
+
483
+ def test_attention_slicing_forward_pass(self):
484
+ self._test_attention_slicing_forward_pass(test_mean_pixel_difference=False)
485
+
486
+ @unittest.skip("Raises a not implemented error in AudioLDM2")
487
+ def test_xformers_attention_forwardGenerator_pass(self):
488
+ pass
489
+
490
+ def test_dict_tuple_outputs_equivalent(self):
491
+ # increase tolerance from 1e-4 -> 3e-4 to account for large composite model
492
+ super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-4)
493
+
494
+ @pytest.mark.xfail(
495
+ condition=is_torch_version(">=", "2.7"),
496
+ reason="Test currently fails on PyTorch 2.7.",
497
+ strict=False,
498
+ )
499
+ def test_inference_batch_single_identical(self):
500
+ # increase tolerance from 1e-4 -> 2e-4 to account for large composite model
501
+ self._test_inference_batch_single_identical(expected_max_diff=2e-4)
502
+
503
+ def test_save_load_local(self):
504
+ # increase tolerance from 1e-4 -> 2e-4 to account for large composite model
505
+ super().test_save_load_local(expected_max_difference=2e-4)
506
+
507
+ def test_save_load_optional_components(self):
508
+ # increase tolerance from 1e-4 -> 2e-4 to account for large composite model
509
+ super().test_save_load_optional_components(expected_max_difference=2e-4)
510
+
511
+ def test_to_dtype(self):
512
+ components = self.get_dummy_components()
513
+ pipe = self.pipeline_class(**components)
514
+ pipe.set_progress_bar_config(disable=None)
515
+
516
+ # The method component.dtype returns the dtype of the first parameter registered in the model, not the
517
+ # dtype of the entire model. In the case of CLAP, the first parameter is a float64 constant (logit scale)
518
+ model_dtypes = {key: component.dtype for key, component in components.items() if hasattr(component, "dtype")}
519
+
520
+ # Without the logit scale parameters, everything is float32
521
+ model_dtypes.pop("text_encoder")
522
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes.values()))
523
+
524
+ # the CLAP sub-models are float32
525
+ model_dtypes["clap_text_branch"] = components["text_encoder"].text_model.dtype
526
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes.values()))
527
+
528
+ # Once we send to fp16, all params are in half-precision, including the logit scale
529
+ pipe.to(dtype=torch.float16)
530
+ model_dtypes = {key: component.dtype for key, component in components.items() if hasattr(component, "dtype")}
531
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes.values()))
532
+
533
+ @unittest.skip("Test not supported.")
534
+ def test_sequential_cpu_offload_forward_pass(self):
535
+ pass
536
+
537
+ @unittest.skip("Test not supported for now because of the use of `projection_model` in `encode_prompt()`.")
538
+ def test_encode_prompt_works_in_isolation(self):
539
+ pass
540
+
541
+ @unittest.skip("Not supported yet due to CLAPModel.")
542
+ def test_sequential_offload_forward_pass_twice(self):
543
+ pass
544
+
545
+ @unittest.skip("Not supported yet, the second forward has mixed devices and `vocoder` is not offloaded.")
546
+ def test_cpu_offload_forward_pass_twice(self):
547
+ pass
548
+
549
+ @unittest.skip("Not supported yet. `vocoder` is not offloaded.")
550
+ def test_model_cpu_offload_forward_pass(self):
551
+ pass
552
+
553
+
554
+ @nightly
555
+ class AudioLDM2PipelineSlowTests(unittest.TestCase):
556
+ def setUp(self):
557
+ super().setUp()
558
+ gc.collect()
559
+ backend_empty_cache(torch_device)
560
+
561
+ def tearDown(self):
562
+ super().tearDown()
563
+ gc.collect()
564
+ backend_empty_cache(torch_device)
565
+
566
+ def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
567
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
568
+ latents = np.random.RandomState(seed).standard_normal((1, 8, 128, 16))
569
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
570
+ inputs = {
571
+ "prompt": "A hammer hitting a wooden surface",
572
+ "latents": latents,
573
+ "generator": generator,
574
+ "num_inference_steps": 3,
575
+ "guidance_scale": 2.5,
576
+ }
577
+ return inputs
578
+
579
+ def get_inputs_tts(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
580
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
581
+ latents = np.random.RandomState(seed).standard_normal((1, 8, 128, 16))
582
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
583
+ inputs = {
584
+ "prompt": "A men saying",
585
+ "transcription": "hello my name is John",
586
+ "latents": latents,
587
+ "generator": generator,
588
+ "num_inference_steps": 3,
589
+ "guidance_scale": 2.5,
590
+ }
591
+ return inputs
592
+
593
+ def test_audioldm2(self):
594
+ audioldm_pipe = AudioLDM2Pipeline.from_pretrained("cvssp/audioldm2")
595
+ audioldm_pipe = audioldm_pipe.to(torch_device)
596
+ audioldm_pipe.set_progress_bar_config(disable=None)
597
+
598
+ inputs = self.get_inputs(torch_device)
599
+ inputs["num_inference_steps"] = 25
600
+ audio = audioldm_pipe(**inputs).audios[0]
601
+
602
+ assert audio.ndim == 1
603
+ assert len(audio) == 81952
604
+
605
+ # check the portion of the generated audio with the largest dynamic range (reduces flakiness)
606
+ audio_slice = audio[17275:17285]
607
+ expected_slice = np.array([0.0791, 0.0666, 0.1158, 0.1227, 0.1171, -0.2880, -0.1940, -0.0283, -0.0126, 0.1127])
608
+ max_diff = np.abs(expected_slice - audio_slice).max()
609
+ assert max_diff < 1e-3
610
+
611
+ def test_audioldm2_lms(self):
612
+ audioldm_pipe = AudioLDM2Pipeline.from_pretrained("cvssp/audioldm2")
613
+ audioldm_pipe.scheduler = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config)
614
+ audioldm_pipe = audioldm_pipe.to(torch_device)
615
+ audioldm_pipe.set_progress_bar_config(disable=None)
616
+
617
+ inputs = self.get_inputs(torch_device)
618
+ audio = audioldm_pipe(**inputs).audios[0]
619
+
620
+ assert audio.ndim == 1
621
+ assert len(audio) == 81952
622
+
623
+ # check the portion of the generated audio with the largest dynamic range (reduces flakiness)
624
+ audio_slice = audio[31390:31400]
625
+ expected_slice = np.array(
626
+ [-0.1318, -0.0577, 0.0446, -0.0573, 0.0659, 0.1074, -0.2600, 0.0080, -0.2190, -0.4301]
627
+ )
628
+ max_diff = np.abs(expected_slice - audio_slice).max()
629
+ assert max_diff < 1e-3
630
+
631
+ def test_audioldm2_large(self):
632
+ audioldm_pipe = AudioLDM2Pipeline.from_pretrained("cvssp/audioldm2-large")
633
+ audioldm_pipe = audioldm_pipe.to(torch_device)
634
+ audioldm_pipe.set_progress_bar_config(disable=None)
635
+
636
+ inputs = self.get_inputs(torch_device)
637
+ audio = audioldm_pipe(**inputs).audios[0]
638
+
639
+ assert audio.ndim == 1
640
+ assert len(audio) == 81952
641
+
642
+ # check the portion of the generated audio with the largest dynamic range (reduces flakiness)
643
+ audio_slice = audio[8825:8835]
644
+ expected_slice = np.array(
645
+ [-0.1829, -0.1461, 0.0759, -0.1493, -0.1396, 0.5783, 0.3001, -0.3038, -0.0639, -0.2244]
646
+ )
647
+ max_diff = np.abs(expected_slice - audio_slice).max()
648
+ assert max_diff < 1e-3
649
+
650
+ def test_audioldm2_tts(self):
651
+ audioldm_tts_pipe = AudioLDM2Pipeline.from_pretrained("anhnct/audioldm2_gigaspeech")
652
+ audioldm_tts_pipe = audioldm_tts_pipe.to(torch_device)
653
+ audioldm_tts_pipe.set_progress_bar_config(disable=None)
654
+
655
+ inputs = self.get_inputs_tts(torch_device)
656
+ audio = audioldm_tts_pipe(**inputs).audios[0]
657
+
658
+ assert audio.ndim == 1
659
+ assert len(audio) == 81952
660
+
661
+ # check the portion of the generated audio with the largest dynamic range (reduces flakiness)
662
+ audio_slice = audio[8825:8835]
663
+ expected_slice = np.array(
664
+ [-0.1829, -0.1461, 0.0759, -0.1493, -0.1396, 0.5783, 0.3001, -0.3038, -0.0639, -0.2244]
665
+ )
666
+ max_diff = np.abs(expected_slice - audio_slice).max()
667
+ assert max_diff < 1e-3
diffusers/tests/pipelines/bria/__init__.py ADDED
File without changes
diffusers/tests/pipelines/bria/test_pipeline_bria.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bria AI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import tempfile
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from huggingface_hub import hf_hub_download
22
+ from transformers import AutoConfig, T5EncoderModel, T5TokenizerFast
23
+
24
+ from diffusers import (
25
+ AutoencoderKL,
26
+ BriaTransformer2DModel,
27
+ FlowMatchEulerDiscreteScheduler,
28
+ )
29
+ from diffusers.pipelines.bria import BriaPipeline
30
+
31
+ # from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
32
+ from tests.pipelines.test_pipelines_common import PipelineTesterMixin, to_np
33
+
34
+ from ...testing_utils import (
35
+ backend_empty_cache,
36
+ enable_full_determinism,
37
+ numpy_cosine_similarity_distance,
38
+ require_torch_accelerator,
39
+ slow,
40
+ torch_device,
41
+ )
42
+
43
+
44
+ enable_full_determinism()
45
+
46
+
47
+ class BriaPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
48
+ pipeline_class = BriaPipeline
49
+ params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds"])
50
+ batch_params = frozenset(["prompt"])
51
+ test_xformers_attention = False
52
+
53
+ # there is no xformers processor for Flux
54
+ test_xformers_attention = False
55
+ test_layerwise_casting = True
56
+ test_group_offloading = True
57
+
58
+ def get_dummy_components(self):
59
+ torch.manual_seed(0)
60
+ transformer = BriaTransformer2DModel(
61
+ patch_size=1,
62
+ in_channels=16,
63
+ num_layers=1,
64
+ num_single_layers=1,
65
+ attention_head_dim=8,
66
+ num_attention_heads=2,
67
+ joint_attention_dim=32,
68
+ pooled_projection_dim=None,
69
+ axes_dims_rope=[0, 4, 4],
70
+ )
71
+
72
+ torch.manual_seed(0)
73
+ vae = AutoencoderKL(
74
+ act_fn="silu",
75
+ block_out_channels=(32,),
76
+ in_channels=3,
77
+ out_channels=3,
78
+ down_block_types=["DownEncoderBlock2D"],
79
+ up_block_types=["UpDecoderBlock2D"],
80
+ latent_channels=4,
81
+ sample_size=32,
82
+ shift_factor=0,
83
+ scaling_factor=0.13025,
84
+ use_post_quant_conv=True,
85
+ use_quant_conv=True,
86
+ force_upcast=False,
87
+ )
88
+
89
+ scheduler = FlowMatchEulerDiscreteScheduler()
90
+
91
+ torch.manual_seed(0)
92
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
93
+ text_encoder = T5EncoderModel(config)
94
+ tokenizer = T5TokenizerFast.from_pretrained("hf-internal-testing/tiny-random-t5")
95
+
96
+ components = {
97
+ "scheduler": scheduler,
98
+ "text_encoder": text_encoder,
99
+ "tokenizer": tokenizer,
100
+ "transformer": transformer,
101
+ "vae": vae,
102
+ "image_encoder": None,
103
+ "feature_extractor": None,
104
+ }
105
+ return components
106
+
107
+ def get_dummy_inputs(self, device, seed=0):
108
+ if str(device).startswith("mps"):
109
+ generator = torch.manual_seed(seed)
110
+ else:
111
+ generator = torch.Generator(device="cpu").manual_seed(seed)
112
+
113
+ inputs = {
114
+ "prompt": "A painting of a squirrel eating a burger",
115
+ "negative_prompt": "bad, ugly",
116
+ "generator": generator,
117
+ "num_inference_steps": 2,
118
+ "guidance_scale": 5.0,
119
+ "height": 16,
120
+ "width": 16,
121
+ "max_sequence_length": 48,
122
+ "output_type": "np",
123
+ }
124
+ return inputs
125
+
126
+ def test_encode_prompt_works_in_isolation(self):
127
+ pass
128
+
129
+ def test_bria_different_prompts(self):
130
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
131
+ inputs = self.get_dummy_inputs(torch_device)
132
+ output_same_prompt = pipe(**inputs).images[0]
133
+ inputs = self.get_dummy_inputs(torch_device)
134
+ inputs["prompt"] = "a different prompt"
135
+ output_different_prompts = pipe(**inputs).images[0]
136
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
137
+ assert max_diff > 1e-6
138
+
139
+ def test_image_output_shape(self):
140
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
141
+ inputs = self.get_dummy_inputs(torch_device)
142
+
143
+ height_width_pairs = [(32, 32), (72, 57)]
144
+ for height, width in height_width_pairs:
145
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
146
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
147
+
148
+ inputs.update({"height": height, "width": width})
149
+ image = pipe(**inputs).images[0]
150
+ output_height, output_width, _ = image.shape
151
+ assert (output_height, output_width) == (expected_height, expected_width)
152
+
153
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
154
+ @require_torch_accelerator
155
+ def test_save_load_float16(self, expected_max_diff=1e-2):
156
+ components = self.get_dummy_components()
157
+ for name, module in components.items():
158
+ if hasattr(module, "half"):
159
+ components[name] = module.to(torch_device).half()
160
+
161
+ pipe = self.pipeline_class(**components)
162
+ for component in pipe.components.values():
163
+ if hasattr(component, "set_default_attn_processor"):
164
+ component.set_default_attn_processor()
165
+ pipe.to(torch_device)
166
+ pipe.set_progress_bar_config(disable=None)
167
+
168
+ inputs = self.get_dummy_inputs(torch_device)
169
+ output = pipe(**inputs)[0]
170
+
171
+ with tempfile.TemporaryDirectory() as tmpdir:
172
+ pipe.save_pretrained(tmpdir)
173
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16)
174
+ for component in pipe_loaded.components.values():
175
+ if hasattr(component, "set_default_attn_processor"):
176
+ component.set_default_attn_processor()
177
+ pipe_loaded.to(torch_device)
178
+ pipe_loaded.set_progress_bar_config(disable=None)
179
+
180
+ for name, component in pipe_loaded.components.items():
181
+ if name == "vae":
182
+ continue
183
+ if hasattr(component, "dtype"):
184
+ self.assertTrue(
185
+ component.dtype == torch.float16,
186
+ f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
187
+ )
188
+
189
+ inputs = self.get_dummy_inputs(torch_device)
190
+ output_loaded = pipe_loaded(**inputs)[0]
191
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
192
+ self.assertLess(
193
+ max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
194
+ )
195
+
196
+ def test_bria_image_output_shape(self):
197
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
198
+ inputs = self.get_dummy_inputs(torch_device)
199
+
200
+ height_width_pairs = [(16, 16), (32, 32), (64, 64)]
201
+ for height, width in height_width_pairs:
202
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
203
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
204
+
205
+ inputs.update({"height": height, "width": width})
206
+ image = pipe(**inputs).images[0]
207
+ output_height, output_width, _ = image.shape
208
+ assert (output_height, output_width) == (expected_height, expected_width)
209
+
210
+ def test_to_dtype(self):
211
+ components = self.get_dummy_components()
212
+ pipe = self.pipeline_class(**components)
213
+ pipe.set_progress_bar_config(disable=None)
214
+
215
+ model_dtypes = [component.dtype for component in components.values() if hasattr(component, "dtype")]
216
+ self.assertTrue([dtype == torch.float32 for dtype in model_dtypes] == [True, True, True])
217
+
218
+ def test_torch_dtype_dict(self):
219
+ components = self.get_dummy_components()
220
+ pipe = self.pipeline_class(**components)
221
+
222
+ with tempfile.TemporaryDirectory() as tmpdirname:
223
+ pipe.save_pretrained(tmpdirname)
224
+ torch_dtype_dict = {"transformer": torch.bfloat16, "default": torch.float16}
225
+ loaded_pipe = self.pipeline_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype_dict)
226
+
227
+ self.assertEqual(loaded_pipe.transformer.dtype, torch.bfloat16)
228
+ self.assertEqual(loaded_pipe.text_encoder.dtype, torch.float16)
229
+ self.assertEqual(loaded_pipe.vae.dtype, torch.float16)
230
+
231
+ with tempfile.TemporaryDirectory() as tmpdirname:
232
+ pipe.save_pretrained(tmpdirname)
233
+ torch_dtype_dict = {"default": torch.float16}
234
+ loaded_pipe = self.pipeline_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype_dict)
235
+
236
+ self.assertEqual(loaded_pipe.transformer.dtype, torch.float16)
237
+ self.assertEqual(loaded_pipe.text_encoder.dtype, torch.float16)
238
+ self.assertEqual(loaded_pipe.vae.dtype, torch.float16)
239
+
240
+
241
+ @slow
242
+ @require_torch_accelerator
243
+ class BriaPipelineSlowTests(unittest.TestCase):
244
+ pipeline_class = BriaPipeline
245
+ repo_id = "briaai/BRIA-3.2"
246
+
247
+ def setUp(self):
248
+ super().setUp()
249
+ gc.collect()
250
+ backend_empty_cache(torch_device)
251
+
252
+ def tearDown(self):
253
+ super().tearDown()
254
+ gc.collect()
255
+ backend_empty_cache(torch_device)
256
+
257
+ def get_inputs(self, device, seed=0):
258
+ generator = torch.Generator(device="cpu").manual_seed(seed)
259
+
260
+ prompt_embeds = torch.load(
261
+ hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
262
+ ).to(torch_device)
263
+
264
+ return {
265
+ "prompt_embeds": prompt_embeds,
266
+ "num_inference_steps": 2,
267
+ "guidance_scale": 0.0,
268
+ "max_sequence_length": 256,
269
+ "output_type": "np",
270
+ "generator": generator,
271
+ }
272
+
273
+ def test_bria_inference_bf16(self):
274
+ pipe = self.pipeline_class.from_pretrained(
275
+ self.repo_id, torch_dtype=torch.bfloat16, text_encoder=None, tokenizer=None
276
+ )
277
+ pipe.to(torch_device)
278
+
279
+ inputs = self.get_inputs(torch_device)
280
+
281
+ image = pipe(**inputs).images[0]
282
+ image_slice = image[0, :10, :10].flatten()
283
+
284
+ expected_slice = np.array(
285
+ [
286
+ 0.59729785,
287
+ 0.6153719,
288
+ 0.595112,
289
+ 0.5884763,
290
+ 0.59366125,
291
+ 0.5795311,
292
+ 0.58325,
293
+ 0.58449626,
294
+ 0.57737637,
295
+ 0.58432233,
296
+ 0.5867875,
297
+ 0.57824117,
298
+ 0.5819089,
299
+ 0.5830988,
300
+ 0.57730293,
301
+ 0.57647324,
302
+ 0.5769151,
303
+ 0.57312685,
304
+ 0.57926565,
305
+ 0.5823928,
306
+ 0.57783926,
307
+ 0.57162863,
308
+ 0.575649,
309
+ 0.5745547,
310
+ 0.5740556,
311
+ 0.5799735,
312
+ 0.57799566,
313
+ 0.5715559,
314
+ 0.5771242,
315
+ 0.5773058,
316
+ ],
317
+ dtype=np.float32,
318
+ )
319
+ max_diff = numpy_cosine_similarity_distance(expected_slice, image_slice)
320
+ self.assertLess(max_diff, 1e-4, f"Image slice is different from expected slice: {max_diff:.4f}")
diffusers/tests/pipelines/bria_fibo/__init__.py ADDED
File without changes
diffusers/tests/pipelines/bria_fibo/test_pipeline_bria_fibo.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bria AI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import unittest
16
+
17
+ import numpy as np
18
+ import torch
19
+ from transformers import AutoTokenizer
20
+ from transformers.models.smollm3.modeling_smollm3 import SmolLM3Config, SmolLM3ForCausalLM
21
+
22
+ from diffusers import (
23
+ AutoencoderKLWan,
24
+ BriaFiboPipeline,
25
+ FlowMatchEulerDiscreteScheduler,
26
+ )
27
+ from diffusers.models.transformers.transformer_bria_fibo import BriaFiboTransformer2DModel
28
+ from tests.pipelines.test_pipelines_common import PipelineTesterMixin
29
+
30
+ from ...testing_utils import (
31
+ enable_full_determinism,
32
+ torch_device,
33
+ )
34
+
35
+
36
+ enable_full_determinism()
37
+
38
+
39
+ class BriaFiboPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
40
+ pipeline_class = BriaFiboPipeline
41
+ params = frozenset(["prompt", "height", "width", "guidance_scale"])
42
+ batch_params = frozenset(["prompt"])
43
+ test_xformers_attention = False
44
+ test_layerwise_casting = False
45
+ test_group_offloading = False
46
+ supports_dduf = False
47
+
48
+ def get_dummy_components(self):
49
+ torch.manual_seed(0)
50
+ transformer = BriaFiboTransformer2DModel(
51
+ patch_size=1,
52
+ in_channels=16,
53
+ num_layers=1,
54
+ num_single_layers=1,
55
+ attention_head_dim=8,
56
+ num_attention_heads=2,
57
+ joint_attention_dim=64,
58
+ text_encoder_dim=32,
59
+ pooled_projection_dim=None,
60
+ axes_dims_rope=[0, 4, 4],
61
+ )
62
+
63
+ torch.manual_seed(0)
64
+ vae = AutoencoderKLWan(
65
+ base_dim=160,
66
+ decoder_base_dim=256,
67
+ num_res_blocks=2,
68
+ out_channels=12,
69
+ patch_size=2,
70
+ scale_factor_spatial=16,
71
+ scale_factor_temporal=4,
72
+ temperal_downsample=[False, True, True],
73
+ z_dim=16,
74
+ )
75
+
76
+ scheduler = FlowMatchEulerDiscreteScheduler()
77
+
78
+ torch.manual_seed(0)
79
+ text_encoder = SmolLM3ForCausalLM(SmolLM3Config(hidden_size=32))
80
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
81
+
82
+ components = {
83
+ "scheduler": scheduler,
84
+ "text_encoder": text_encoder,
85
+ "tokenizer": tokenizer,
86
+ "transformer": transformer,
87
+ "vae": vae,
88
+ }
89
+ return components
90
+
91
+ def get_dummy_inputs(self, device, seed=0):
92
+ if str(device).startswith("mps"):
93
+ generator = torch.manual_seed(seed)
94
+ else:
95
+ generator = torch.Generator(device="cpu").manual_seed(seed)
96
+
97
+ inputs = {
98
+ "prompt": "{'text': 'A painting of a squirrel eating a burger'}",
99
+ "negative_prompt": "bad, ugly",
100
+ "generator": generator,
101
+ "num_inference_steps": 2,
102
+ "guidance_scale": 5.0,
103
+ "height": 32,
104
+ "width": 32,
105
+ "output_type": "np",
106
+ }
107
+ return inputs
108
+
109
+ @unittest.skip(reason="will not be supported due to dim-fusion")
110
+ def test_encode_prompt_works_in_isolation(self):
111
+ pass
112
+
113
+ def test_bria_fibo_different_prompts(self):
114
+ pipe = self.pipeline_class(**self.get_dummy_components())
115
+ pipe = pipe.to(torch_device)
116
+ inputs = self.get_dummy_inputs(torch_device)
117
+ output_same_prompt = pipe(**inputs).images[0]
118
+
119
+ inputs = self.get_dummy_inputs(torch_device)
120
+ inputs["prompt"] = "a different prompt"
121
+ output_different_prompts = pipe(**inputs).images[0]
122
+
123
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
124
+ assert max_diff > 1e-6
125
+
126
+ def test_image_output_shape(self):
127
+ pipe = self.pipeline_class(**self.get_dummy_components())
128
+ pipe = pipe.to(torch_device)
129
+ inputs = self.get_dummy_inputs(torch_device)
130
+
131
+ height_width_pairs = [(32, 32), (64, 64), (32, 64)]
132
+ for height, width in height_width_pairs:
133
+ expected_height = height
134
+ expected_width = width
135
+
136
+ inputs.update({"height": height, "width": width})
137
+ image = pipe(**inputs).images[0]
138
+ output_height, output_width, _ = image.shape
139
+ assert (output_height, output_width) == (expected_height, expected_width)
diffusers/tests/pipelines/chroma/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
diffusers/tests/pipelines/chroma/test_pipeline_chroma.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
6
+
7
+ from diffusers import AutoencoderKL, ChromaPipeline, ChromaTransformer2DModel, FlowMatchEulerDiscreteScheduler
8
+
9
+ from ...testing_utils import torch_device
10
+ from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin, check_qkv_fused_layers_exist
11
+
12
+
13
+ class ChromaPipelineFastTests(
14
+ unittest.TestCase,
15
+ PipelineTesterMixin,
16
+ FluxIPAdapterTesterMixin,
17
+ ):
18
+ pipeline_class = ChromaPipeline
19
+ params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds"])
20
+ batch_params = frozenset(["prompt"])
21
+
22
+ # there is no xformers processor for Flux
23
+ test_xformers_attention = False
24
+ test_layerwise_casting = True
25
+ test_group_offloading = True
26
+
27
+ def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
28
+ torch.manual_seed(0)
29
+ transformer = ChromaTransformer2DModel(
30
+ patch_size=1,
31
+ in_channels=4,
32
+ num_layers=num_layers,
33
+ num_single_layers=num_single_layers,
34
+ attention_head_dim=16,
35
+ num_attention_heads=2,
36
+ joint_attention_dim=32,
37
+ axes_dims_rope=[4, 4, 8],
38
+ approximator_hidden_dim=32,
39
+ approximator_layers=1,
40
+ approximator_num_channels=16,
41
+ )
42
+
43
+ torch.manual_seed(0)
44
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
45
+ text_encoder = T5EncoderModel(config)
46
+
47
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
48
+
49
+ torch.manual_seed(0)
50
+ vae = AutoencoderKL(
51
+ sample_size=32,
52
+ in_channels=3,
53
+ out_channels=3,
54
+ block_out_channels=(4,),
55
+ layers_per_block=1,
56
+ latent_channels=1,
57
+ norm_num_groups=1,
58
+ use_quant_conv=False,
59
+ use_post_quant_conv=False,
60
+ shift_factor=0.0609,
61
+ scaling_factor=1.5035,
62
+ )
63
+
64
+ scheduler = FlowMatchEulerDiscreteScheduler()
65
+
66
+ return {
67
+ "scheduler": scheduler,
68
+ "text_encoder": text_encoder,
69
+ "tokenizer": tokenizer,
70
+ "transformer": transformer,
71
+ "vae": vae,
72
+ "image_encoder": None,
73
+ "feature_extractor": None,
74
+ }
75
+
76
+ def get_dummy_inputs(self, device, seed=0):
77
+ if str(device).startswith("mps"):
78
+ generator = torch.manual_seed(seed)
79
+ else:
80
+ generator = torch.Generator(device="cpu").manual_seed(seed)
81
+
82
+ inputs = {
83
+ "prompt": "A painting of a squirrel eating a burger",
84
+ "negative_prompt": "bad, ugly",
85
+ "generator": generator,
86
+ "num_inference_steps": 2,
87
+ "guidance_scale": 5.0,
88
+ "height": 8,
89
+ "width": 8,
90
+ "max_sequence_length": 48,
91
+ "output_type": "np",
92
+ }
93
+ return inputs
94
+
95
+ def test_chroma_different_prompts(self):
96
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
97
+
98
+ inputs = self.get_dummy_inputs(torch_device)
99
+ output_same_prompt = pipe(**inputs).images[0]
100
+
101
+ inputs = self.get_dummy_inputs(torch_device)
102
+ inputs["prompt"] = "a different prompt"
103
+ output_different_prompts = pipe(**inputs).images[0]
104
+
105
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
106
+
107
+ # Outputs should be different here
108
+ # For some reasons, they don't show large differences
109
+ assert max_diff > 1e-6
110
+
111
+ def test_fused_qkv_projections(self):
112
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
113
+ components = self.get_dummy_components()
114
+ pipe = self.pipeline_class(**components)
115
+ pipe = pipe.to(device)
116
+ pipe.set_progress_bar_config(disable=None)
117
+
118
+ inputs = self.get_dummy_inputs(device)
119
+ image = pipe(**inputs).images
120
+ original_image_slice = image[0, -3:, -3:, -1]
121
+
122
+ # TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
123
+ # to the pipeline level.
124
+ pipe.transformer.fuse_qkv_projections()
125
+ self.assertTrue(
126
+ check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
127
+ ("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
128
+ )
129
+
130
+ inputs = self.get_dummy_inputs(device)
131
+ image = pipe(**inputs).images
132
+ image_slice_fused = image[0, -3:, -3:, -1]
133
+
134
+ pipe.transformer.unfuse_qkv_projections()
135
+ inputs = self.get_dummy_inputs(device)
136
+ image = pipe(**inputs).images
137
+ image_slice_disabled = image[0, -3:, -3:, -1]
138
+
139
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
140
+ "Fusion of QKV projections shouldn't affect the outputs."
141
+ )
142
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
143
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
144
+ )
145
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
146
+ "Original outputs should match when fused QKV projections are disabled."
147
+ )
148
+
149
+ def test_chroma_image_output_shape(self):
150
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
151
+ inputs = self.get_dummy_inputs(torch_device)
152
+
153
+ height_width_pairs = [(32, 32), (72, 57)]
154
+ for height, width in height_width_pairs:
155
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
156
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
157
+
158
+ inputs.update({"height": height, "width": width})
159
+ image = pipe(**inputs).images[0]
160
+ output_height, output_width, _ = image.shape
161
+ assert (output_height, output_width) == (expected_height, expected_width)
diffusers/tests/pipelines/cogvideo/__init__.py ADDED
File without changes
diffusers/tests/pipelines/cogvideo/test_cogvideox.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import inspect
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
22
+
23
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXPipeline, CogVideoXTransformer3DModel, DDIMScheduler
24
+
25
+ from ...testing_utils import (
26
+ backend_empty_cache,
27
+ enable_full_determinism,
28
+ numpy_cosine_similarity_distance,
29
+ require_torch_accelerator,
30
+ slow,
31
+ torch_device,
32
+ )
33
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
34
+ from ..test_pipelines_common import (
35
+ FasterCacheTesterMixin,
36
+ FirstBlockCacheTesterMixin,
37
+ PipelineTesterMixin,
38
+ PyramidAttentionBroadcastTesterMixin,
39
+ check_qkv_fusion_matches_attn_procs_length,
40
+ check_qkv_fusion_processors_exist,
41
+ to_np,
42
+ )
43
+
44
+
45
+ enable_full_determinism()
46
+
47
+
48
+ class CogVideoXPipelineFastTests(
49
+ PipelineTesterMixin,
50
+ PyramidAttentionBroadcastTesterMixin,
51
+ FasterCacheTesterMixin,
52
+ FirstBlockCacheTesterMixin,
53
+ unittest.TestCase,
54
+ ):
55
+ pipeline_class = CogVideoXPipeline
56
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
57
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
58
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
59
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
60
+ required_optional_params = frozenset(
61
+ [
62
+ "num_inference_steps",
63
+ "generator",
64
+ "latents",
65
+ "return_dict",
66
+ "callback_on_step_end",
67
+ "callback_on_step_end_tensor_inputs",
68
+ ]
69
+ )
70
+ test_xformers_attention = False
71
+ test_layerwise_casting = True
72
+ test_group_offloading = True
73
+
74
+ def get_dummy_components(self, num_layers: int = 1):
75
+ torch.manual_seed(0)
76
+ transformer = CogVideoXTransformer3DModel(
77
+ # Product of num_attention_heads * attention_head_dim must be divisible by 16 for 3D positional embeddings
78
+ # But, since we are using tiny-random-t5 here, we need the internal dim of CogVideoXTransformer3DModel
79
+ # to be 32. The internal dim is product of num_attention_heads and attention_head_dim
80
+ num_attention_heads=4,
81
+ attention_head_dim=8,
82
+ in_channels=4,
83
+ out_channels=4,
84
+ time_embed_dim=2,
85
+ text_embed_dim=32, # Must match with tiny-random-t5
86
+ num_layers=num_layers,
87
+ sample_width=2, # latent width: 2 -> final width: 16
88
+ sample_height=2, # latent height: 2 -> final height: 16
89
+ sample_frames=9, # latent frames: (9 - 1) / 4 + 1 = 3 -> final frames: 9
90
+ patch_size=2,
91
+ temporal_compression_ratio=4,
92
+ max_text_seq_length=16,
93
+ )
94
+
95
+ torch.manual_seed(0)
96
+ vae = AutoencoderKLCogVideoX(
97
+ in_channels=3,
98
+ out_channels=3,
99
+ down_block_types=(
100
+ "CogVideoXDownBlock3D",
101
+ "CogVideoXDownBlock3D",
102
+ "CogVideoXDownBlock3D",
103
+ "CogVideoXDownBlock3D",
104
+ ),
105
+ up_block_types=(
106
+ "CogVideoXUpBlock3D",
107
+ "CogVideoXUpBlock3D",
108
+ "CogVideoXUpBlock3D",
109
+ "CogVideoXUpBlock3D",
110
+ ),
111
+ block_out_channels=(8, 8, 8, 8),
112
+ latent_channels=4,
113
+ layers_per_block=1,
114
+ norm_num_groups=2,
115
+ temporal_compression_ratio=4,
116
+ )
117
+
118
+ torch.manual_seed(0)
119
+ scheduler = DDIMScheduler()
120
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
121
+ text_encoder = T5EncoderModel(config)
122
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
123
+
124
+ components = {
125
+ "transformer": transformer,
126
+ "vae": vae,
127
+ "scheduler": scheduler,
128
+ "text_encoder": text_encoder,
129
+ "tokenizer": tokenizer,
130
+ }
131
+ return components
132
+
133
+ def get_dummy_inputs(self, device, seed=0):
134
+ if str(device).startswith("mps"):
135
+ generator = torch.manual_seed(seed)
136
+ else:
137
+ generator = torch.Generator(device=device).manual_seed(seed)
138
+ inputs = {
139
+ "prompt": "dance monkey",
140
+ "negative_prompt": "",
141
+ "generator": generator,
142
+ "num_inference_steps": 2,
143
+ "guidance_scale": 6.0,
144
+ # Cannot reduce because convolution kernel becomes bigger than sample
145
+ "height": 16,
146
+ "width": 16,
147
+ "num_frames": 8,
148
+ "max_sequence_length": 16,
149
+ "output_type": "pt",
150
+ }
151
+ return inputs
152
+
153
+ def test_inference(self):
154
+ device = "cpu"
155
+
156
+ components = self.get_dummy_components()
157
+ pipe = self.pipeline_class(**components)
158
+ pipe.to(device)
159
+ pipe.set_progress_bar_config(disable=None)
160
+
161
+ inputs = self.get_dummy_inputs(device)
162
+ video = pipe(**inputs).frames
163
+ generated_video = video[0]
164
+
165
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
166
+ expected_video = torch.randn(8, 3, 16, 16)
167
+ max_diff = np.abs(generated_video - expected_video).max()
168
+ self.assertLessEqual(max_diff, 1e10)
169
+
170
+ def test_callback_inputs(self):
171
+ sig = inspect.signature(self.pipeline_class.__call__)
172
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
173
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
174
+
175
+ if not (has_callback_tensor_inputs and has_callback_step_end):
176
+ return
177
+
178
+ components = self.get_dummy_components()
179
+ pipe = self.pipeline_class(**components)
180
+ pipe = pipe.to(torch_device)
181
+ pipe.set_progress_bar_config(disable=None)
182
+ self.assertTrue(
183
+ hasattr(pipe, "_callback_tensor_inputs"),
184
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
185
+ )
186
+
187
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
188
+ # iterate over callback args
189
+ for tensor_name, tensor_value in callback_kwargs.items():
190
+ # check that we're only passing in allowed tensor inputs
191
+ assert tensor_name in pipe._callback_tensor_inputs
192
+
193
+ return callback_kwargs
194
+
195
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
196
+ for tensor_name in pipe._callback_tensor_inputs:
197
+ assert tensor_name in callback_kwargs
198
+
199
+ # iterate over callback args
200
+ for tensor_name, tensor_value in callback_kwargs.items():
201
+ # check that we're only passing in allowed tensor inputs
202
+ assert tensor_name in pipe._callback_tensor_inputs
203
+
204
+ return callback_kwargs
205
+
206
+ inputs = self.get_dummy_inputs(torch_device)
207
+
208
+ # Test passing in a subset
209
+ inputs["callback_on_step_end"] = callback_inputs_subset
210
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
211
+ output = pipe(**inputs)[0]
212
+
213
+ # Test passing in a everything
214
+ inputs["callback_on_step_end"] = callback_inputs_all
215
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
216
+ output = pipe(**inputs)[0]
217
+
218
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
219
+ is_last = i == (pipe.num_timesteps - 1)
220
+ if is_last:
221
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
222
+ return callback_kwargs
223
+
224
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
225
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
226
+ output = pipe(**inputs)[0]
227
+ assert output.abs().sum() < 1e10
228
+
229
+ def test_inference_batch_single_identical(self):
230
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
231
+
232
+ def test_attention_slicing_forward_pass(
233
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
234
+ ):
235
+ if not self.test_attention_slicing:
236
+ return
237
+
238
+ components = self.get_dummy_components()
239
+ for key in components:
240
+ if "text_encoder" in key and hasattr(components[key], "eval"):
241
+ components[key].eval()
242
+ pipe = self.pipeline_class(**components)
243
+ for component in pipe.components.values():
244
+ if hasattr(component, "set_default_attn_processor"):
245
+ component.set_default_attn_processor()
246
+ pipe.to(torch_device)
247
+ pipe.set_progress_bar_config(disable=None)
248
+
249
+ generator_device = "cpu"
250
+ inputs = self.get_dummy_inputs(generator_device)
251
+ output_without_slicing = pipe(**inputs)[0]
252
+
253
+ pipe.enable_attention_slicing(slice_size=1)
254
+ inputs = self.get_dummy_inputs(generator_device)
255
+ output_with_slicing1 = pipe(**inputs)[0]
256
+
257
+ pipe.enable_attention_slicing(slice_size=2)
258
+ inputs = self.get_dummy_inputs(generator_device)
259
+ output_with_slicing2 = pipe(**inputs)[0]
260
+
261
+ if test_max_difference:
262
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
263
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
264
+ self.assertLess(
265
+ max(max_diff1, max_diff2),
266
+ expected_max_diff,
267
+ "Attention slicing should not affect the inference results",
268
+ )
269
+
270
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
271
+ generator_device = "cpu"
272
+ components = self.get_dummy_components()
273
+
274
+ pipe = self.pipeline_class(**components)
275
+ pipe.to("cpu")
276
+ pipe.set_progress_bar_config(disable=None)
277
+
278
+ # Without tiling
279
+ inputs = self.get_dummy_inputs(generator_device)
280
+ inputs["height"] = inputs["width"] = 128
281
+ output_without_tiling = pipe(**inputs)[0]
282
+
283
+ # With tiling
284
+ pipe.vae.enable_tiling(
285
+ tile_sample_min_height=96,
286
+ tile_sample_min_width=96,
287
+ tile_overlap_factor_height=1 / 12,
288
+ tile_overlap_factor_width=1 / 12,
289
+ )
290
+ inputs = self.get_dummy_inputs(generator_device)
291
+ inputs["height"] = inputs["width"] = 128
292
+ output_with_tiling = pipe(**inputs)[0]
293
+
294
+ self.assertLess(
295
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
296
+ expected_diff_max,
297
+ "VAE tiling should not affect the inference results",
298
+ )
299
+
300
+ def test_fused_qkv_projections(self):
301
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
302
+ components = self.get_dummy_components()
303
+ pipe = self.pipeline_class(**components)
304
+ pipe = pipe.to(device)
305
+ pipe.set_progress_bar_config(disable=None)
306
+
307
+ inputs = self.get_dummy_inputs(device)
308
+ frames = pipe(**inputs).frames # [B, F, C, H, W]
309
+ original_image_slice = frames[0, -2:, -1, -3:, -3:]
310
+
311
+ pipe.fuse_qkv_projections()
312
+ assert check_qkv_fusion_processors_exist(pipe.transformer), (
313
+ "Something wrong with the fused attention processors. Expected all the attention processors to be fused."
314
+ )
315
+ assert check_qkv_fusion_matches_attn_procs_length(
316
+ pipe.transformer, pipe.transformer.original_attn_processors
317
+ ), "Something wrong with the attention processors concerning the fused QKV projections."
318
+
319
+ inputs = self.get_dummy_inputs(device)
320
+ frames = pipe(**inputs).frames
321
+ image_slice_fused = frames[0, -2:, -1, -3:, -3:]
322
+
323
+ pipe.transformer.unfuse_qkv_projections()
324
+ inputs = self.get_dummy_inputs(device)
325
+ frames = pipe(**inputs).frames
326
+ image_slice_disabled = frames[0, -2:, -1, -3:, -3:]
327
+
328
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
329
+ "Fusion of QKV projections shouldn't affect the outputs."
330
+ )
331
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
332
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
333
+ )
334
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
335
+ "Original outputs should match when fused QKV projections are disabled."
336
+ )
337
+
338
+
339
+ @slow
340
+ @require_torch_accelerator
341
+ class CogVideoXPipelineIntegrationTests(unittest.TestCase):
342
+ prompt = "A painting of a squirrel eating a burger."
343
+
344
+ def setUp(self):
345
+ super().setUp()
346
+ gc.collect()
347
+ backend_empty_cache(torch_device)
348
+
349
+ def tearDown(self):
350
+ super().tearDown()
351
+ gc.collect()
352
+ backend_empty_cache(torch_device)
353
+
354
+ def test_cogvideox(self):
355
+ generator = torch.Generator("cpu").manual_seed(0)
356
+
357
+ pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16)
358
+ pipe.enable_model_cpu_offload(device=torch_device)
359
+ prompt = self.prompt
360
+
361
+ videos = pipe(
362
+ prompt=prompt,
363
+ height=480,
364
+ width=720,
365
+ num_frames=16,
366
+ generator=generator,
367
+ num_inference_steps=2,
368
+ output_type="pt",
369
+ ).frames
370
+
371
+ video = videos[0]
372
+ expected_video = torch.randn(1, 16, 480, 720, 3).numpy()
373
+
374
+ max_diff = numpy_cosine_similarity_distance(video, expected_video)
375
+ assert max_diff < 1e-3, f"Max diff is too high. got {video}"
diffusers/tests/pipelines/cogvideo/test_cogvideox_fun_control.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+ from PIL import Image
21
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
22
+
23
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXFunControlPipeline, CogVideoXTransformer3DModel, DDIMScheduler
24
+
25
+ from ...testing_utils import (
26
+ enable_full_determinism,
27
+ torch_device,
28
+ )
29
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
30
+ from ..test_pipelines_common import (
31
+ PipelineTesterMixin,
32
+ check_qkv_fusion_matches_attn_procs_length,
33
+ check_qkv_fusion_processors_exist,
34
+ to_np,
35
+ )
36
+
37
+
38
+ enable_full_determinism()
39
+
40
+
41
+ class CogVideoXFunControlPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
42
+ pipeline_class = CogVideoXFunControlPipeline
43
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
44
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"control_video"})
45
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
46
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
47
+ required_optional_params = frozenset(
48
+ [
49
+ "num_inference_steps",
50
+ "generator",
51
+ "latents",
52
+ "return_dict",
53
+ "callback_on_step_end",
54
+ "callback_on_step_end_tensor_inputs",
55
+ ]
56
+ )
57
+ test_xformers_attention = False
58
+ test_layerwise_casting = True
59
+ test_group_offloading = True
60
+
61
+ def get_dummy_components(self):
62
+ torch.manual_seed(0)
63
+ transformer = CogVideoXTransformer3DModel(
64
+ # Product of num_attention_heads * attention_head_dim must be divisible by 16 for 3D positional embeddings
65
+ # But, since we are using tiny-random-t5 here, we need the internal dim of CogVideoXTransformer3DModel
66
+ # to be 32. The internal dim is product of num_attention_heads and attention_head_dim
67
+ num_attention_heads=4,
68
+ attention_head_dim=8,
69
+ in_channels=8,
70
+ out_channels=4,
71
+ time_embed_dim=2,
72
+ text_embed_dim=32, # Must match with tiny-random-t5
73
+ num_layers=1,
74
+ sample_width=2, # latent width: 2 -> final width: 16
75
+ sample_height=2, # latent height: 2 -> final height: 16
76
+ sample_frames=9, # latent frames: (9 - 1) / 4 + 1 = 3 -> final frames: 9
77
+ patch_size=2,
78
+ temporal_compression_ratio=4,
79
+ max_text_seq_length=16,
80
+ )
81
+
82
+ torch.manual_seed(0)
83
+ vae = AutoencoderKLCogVideoX(
84
+ in_channels=3,
85
+ out_channels=3,
86
+ down_block_types=(
87
+ "CogVideoXDownBlock3D",
88
+ "CogVideoXDownBlock3D",
89
+ "CogVideoXDownBlock3D",
90
+ "CogVideoXDownBlock3D",
91
+ ),
92
+ up_block_types=(
93
+ "CogVideoXUpBlock3D",
94
+ "CogVideoXUpBlock3D",
95
+ "CogVideoXUpBlock3D",
96
+ "CogVideoXUpBlock3D",
97
+ ),
98
+ block_out_channels=(8, 8, 8, 8),
99
+ latent_channels=4,
100
+ layers_per_block=1,
101
+ norm_num_groups=2,
102
+ temporal_compression_ratio=4,
103
+ )
104
+
105
+ torch.manual_seed(0)
106
+ scheduler = DDIMScheduler()
107
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
108
+ text_encoder = T5EncoderModel(config)
109
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
110
+
111
+ components = {
112
+ "transformer": transformer,
113
+ "vae": vae,
114
+ "scheduler": scheduler,
115
+ "text_encoder": text_encoder,
116
+ "tokenizer": tokenizer,
117
+ }
118
+ return components
119
+
120
+ def get_dummy_inputs(self, device, seed: int = 0, num_frames: int = 8):
121
+ if str(device).startswith("mps"):
122
+ generator = torch.manual_seed(seed)
123
+ else:
124
+ generator = torch.Generator(device=device).manual_seed(seed)
125
+
126
+ # Cannot reduce because convolution kernel becomes bigger than sample
127
+ height = 16
128
+ width = 16
129
+
130
+ control_video = [Image.new("RGB", (width, height))] * num_frames
131
+
132
+ inputs = {
133
+ "prompt": "dance monkey",
134
+ "negative_prompt": "",
135
+ "control_video": control_video,
136
+ "generator": generator,
137
+ "num_inference_steps": 2,
138
+ "guidance_scale": 6.0,
139
+ "height": height,
140
+ "width": width,
141
+ "max_sequence_length": 16,
142
+ "output_type": "pt",
143
+ }
144
+ return inputs
145
+
146
+ def test_inference(self):
147
+ device = "cpu"
148
+
149
+ components = self.get_dummy_components()
150
+ pipe = self.pipeline_class(**components)
151
+ pipe.to(device)
152
+ pipe.set_progress_bar_config(disable=None)
153
+
154
+ inputs = self.get_dummy_inputs(device)
155
+ video = pipe(**inputs).frames
156
+ generated_video = video[0]
157
+
158
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
159
+ expected_video = torch.randn(8, 3, 16, 16)
160
+ max_diff = np.abs(generated_video - expected_video).max()
161
+ self.assertLessEqual(max_diff, 1e10)
162
+
163
+ def test_callback_inputs(self):
164
+ sig = inspect.signature(self.pipeline_class.__call__)
165
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
166
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
167
+
168
+ if not (has_callback_tensor_inputs and has_callback_step_end):
169
+ return
170
+
171
+ components = self.get_dummy_components()
172
+ pipe = self.pipeline_class(**components)
173
+ pipe = pipe.to(torch_device)
174
+ pipe.set_progress_bar_config(disable=None)
175
+ self.assertTrue(
176
+ hasattr(pipe, "_callback_tensor_inputs"),
177
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
178
+ )
179
+
180
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
181
+ # iterate over callback args
182
+ for tensor_name, tensor_value in callback_kwargs.items():
183
+ # check that we're only passing in allowed tensor inputs
184
+ assert tensor_name in pipe._callback_tensor_inputs
185
+
186
+ return callback_kwargs
187
+
188
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
189
+ for tensor_name in pipe._callback_tensor_inputs:
190
+ assert tensor_name in callback_kwargs
191
+
192
+ # iterate over callback args
193
+ for tensor_name, tensor_value in callback_kwargs.items():
194
+ # check that we're only passing in allowed tensor inputs
195
+ assert tensor_name in pipe._callback_tensor_inputs
196
+
197
+ return callback_kwargs
198
+
199
+ inputs = self.get_dummy_inputs(torch_device)
200
+
201
+ # Test passing in a subset
202
+ inputs["callback_on_step_end"] = callback_inputs_subset
203
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
204
+ output = pipe(**inputs)[0]
205
+
206
+ # Test passing in a everything
207
+ inputs["callback_on_step_end"] = callback_inputs_all
208
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
209
+ output = pipe(**inputs)[0]
210
+
211
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
212
+ is_last = i == (pipe.num_timesteps - 1)
213
+ if is_last:
214
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
215
+ return callback_kwargs
216
+
217
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
218
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
219
+ output = pipe(**inputs)[0]
220
+ assert output.abs().sum() < 1e10
221
+
222
+ def test_inference_batch_single_identical(self):
223
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
224
+
225
+ def test_attention_slicing_forward_pass(
226
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
227
+ ):
228
+ if not self.test_attention_slicing:
229
+ return
230
+
231
+ components = self.get_dummy_components()
232
+ for key in components:
233
+ if "text_encoder" in key and hasattr(components[key], "eval"):
234
+ components[key].eval()
235
+ pipe = self.pipeline_class(**components)
236
+ for component in pipe.components.values():
237
+ if hasattr(component, "set_default_attn_processor"):
238
+ component.set_default_attn_processor()
239
+ pipe.to(torch_device)
240
+ pipe.set_progress_bar_config(disable=None)
241
+
242
+ generator_device = "cpu"
243
+ inputs = self.get_dummy_inputs(generator_device)
244
+ output_without_slicing = pipe(**inputs)[0]
245
+
246
+ pipe.enable_attention_slicing(slice_size=1)
247
+ inputs = self.get_dummy_inputs(generator_device)
248
+ output_with_slicing1 = pipe(**inputs)[0]
249
+
250
+ pipe.enable_attention_slicing(slice_size=2)
251
+ inputs = self.get_dummy_inputs(generator_device)
252
+ output_with_slicing2 = pipe(**inputs)[0]
253
+
254
+ if test_max_difference:
255
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
256
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
257
+ self.assertLess(
258
+ max(max_diff1, max_diff2),
259
+ expected_max_diff,
260
+ "Attention slicing should not affect the inference results",
261
+ )
262
+
263
+ def test_vae_tiling(self, expected_diff_max: float = 0.5):
264
+ # NOTE(aryan): This requires a higher expected_max_diff than other CogVideoX pipelines
265
+ generator_device = "cpu"
266
+ components = self.get_dummy_components()
267
+
268
+ pipe = self.pipeline_class(**components)
269
+ pipe.to("cpu")
270
+ pipe.set_progress_bar_config(disable=None)
271
+
272
+ # Without tiling
273
+ inputs = self.get_dummy_inputs(generator_device)
274
+ inputs["height"] = inputs["width"] = 128
275
+ output_without_tiling = pipe(**inputs)[0]
276
+
277
+ # With tiling
278
+ pipe.vae.enable_tiling(
279
+ tile_sample_min_height=96,
280
+ tile_sample_min_width=96,
281
+ tile_overlap_factor_height=1 / 12,
282
+ tile_overlap_factor_width=1 / 12,
283
+ )
284
+ inputs = self.get_dummy_inputs(generator_device)
285
+ inputs["height"] = inputs["width"] = 128
286
+ output_with_tiling = pipe(**inputs)[0]
287
+
288
+ self.assertLess(
289
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
290
+ expected_diff_max,
291
+ "VAE tiling should not affect the inference results",
292
+ )
293
+
294
+ def test_fused_qkv_projections(self):
295
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
296
+ components = self.get_dummy_components()
297
+ pipe = self.pipeline_class(**components)
298
+ pipe = pipe.to(device)
299
+ pipe.set_progress_bar_config(disable=None)
300
+
301
+ inputs = self.get_dummy_inputs(device)
302
+ frames = pipe(**inputs).frames # [B, F, C, H, W]
303
+ original_image_slice = frames[0, -2:, -1, -3:, -3:]
304
+
305
+ pipe.fuse_qkv_projections()
306
+ assert check_qkv_fusion_processors_exist(pipe.transformer), (
307
+ "Something wrong with the fused attention processors. Expected all the attention processors to be fused."
308
+ )
309
+ assert check_qkv_fusion_matches_attn_procs_length(
310
+ pipe.transformer, pipe.transformer.original_attn_processors
311
+ ), "Something wrong with the attention processors concerning the fused QKV projections."
312
+
313
+ inputs = self.get_dummy_inputs(device)
314
+ frames = pipe(**inputs).frames
315
+ image_slice_fused = frames[0, -2:, -1, -3:, -3:]
316
+
317
+ pipe.transformer.unfuse_qkv_projections()
318
+ inputs = self.get_dummy_inputs(device)
319
+ frames = pipe(**inputs).frames
320
+ image_slice_disabled = frames[0, -2:, -1, -3:, -3:]
321
+
322
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
323
+ "Fusion of QKV projections shouldn't affect the outputs."
324
+ )
325
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
326
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
327
+ )
328
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
329
+ "Original outputs should match when fused QKV projections are disabled."
330
+ )
diffusers/tests/pipelines/cogvideo/test_cogvideox_image2video.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import inspect
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
23
+
24
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXImageToVideoPipeline, CogVideoXTransformer3DModel, DDIMScheduler
25
+ from diffusers.utils import load_image
26
+
27
+ from ...testing_utils import (
28
+ backend_empty_cache,
29
+ enable_full_determinism,
30
+ numpy_cosine_similarity_distance,
31
+ require_torch_accelerator,
32
+ slow,
33
+ torch_device,
34
+ )
35
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
36
+ from ..test_pipelines_common import (
37
+ PipelineTesterMixin,
38
+ check_qkv_fusion_matches_attn_procs_length,
39
+ check_qkv_fusion_processors_exist,
40
+ to_np,
41
+ )
42
+
43
+
44
+ enable_full_determinism()
45
+
46
+
47
+ class CogVideoXImageToVideoPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
48
+ pipeline_class = CogVideoXImageToVideoPipeline
49
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
50
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image"})
51
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
52
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
53
+ required_optional_params = frozenset(
54
+ [
55
+ "num_inference_steps",
56
+ "generator",
57
+ "latents",
58
+ "return_dict",
59
+ "callback_on_step_end",
60
+ "callback_on_step_end_tensor_inputs",
61
+ ]
62
+ )
63
+ test_xformers_attention = False
64
+
65
+ def get_dummy_components(self):
66
+ torch.manual_seed(0)
67
+ transformer = CogVideoXTransformer3DModel(
68
+ # Product of num_attention_heads * attention_head_dim must be divisible by 16 for 3D positional embeddings
69
+ # But, since we are using tiny-random-t5 here, we need the internal dim of CogVideoXTransformer3DModel
70
+ # to be 32. The internal dim is product of num_attention_heads and attention_head_dim
71
+ # Note: The num_attention_heads and attention_head_dim is different from the T2V and I2V tests because
72
+ # attention_head_dim must be divisible by 16 for RoPE to work. We also need to maintain a product of 32 as
73
+ # detailed above.
74
+ num_attention_heads=2,
75
+ attention_head_dim=16,
76
+ in_channels=8,
77
+ out_channels=4,
78
+ time_embed_dim=2,
79
+ text_embed_dim=32, # Must match with tiny-random-t5
80
+ num_layers=1,
81
+ sample_width=2, # latent width: 2 -> final width: 16
82
+ sample_height=2, # latent height: 2 -> final height: 16
83
+ sample_frames=9, # latent frames: (9 - 1) / 4 + 1 = 3 -> final frames: 9
84
+ patch_size=2,
85
+ temporal_compression_ratio=4,
86
+ max_text_seq_length=16,
87
+ use_rotary_positional_embeddings=True,
88
+ use_learned_positional_embeddings=True,
89
+ )
90
+
91
+ torch.manual_seed(0)
92
+ vae = AutoencoderKLCogVideoX(
93
+ in_channels=3,
94
+ out_channels=3,
95
+ down_block_types=(
96
+ "CogVideoXDownBlock3D",
97
+ "CogVideoXDownBlock3D",
98
+ "CogVideoXDownBlock3D",
99
+ "CogVideoXDownBlock3D",
100
+ ),
101
+ up_block_types=(
102
+ "CogVideoXUpBlock3D",
103
+ "CogVideoXUpBlock3D",
104
+ "CogVideoXUpBlock3D",
105
+ "CogVideoXUpBlock3D",
106
+ ),
107
+ block_out_channels=(8, 8, 8, 8),
108
+ latent_channels=4,
109
+ layers_per_block=1,
110
+ norm_num_groups=2,
111
+ temporal_compression_ratio=4,
112
+ )
113
+
114
+ torch.manual_seed(0)
115
+ scheduler = DDIMScheduler()
116
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
117
+ text_encoder = T5EncoderModel(config)
118
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
119
+
120
+ components = {
121
+ "transformer": transformer,
122
+ "vae": vae,
123
+ "scheduler": scheduler,
124
+ "text_encoder": text_encoder,
125
+ "tokenizer": tokenizer,
126
+ }
127
+ return components
128
+
129
+ def get_dummy_inputs(self, device, seed=0):
130
+ if str(device).startswith("mps"):
131
+ generator = torch.manual_seed(seed)
132
+ else:
133
+ generator = torch.Generator(device=device).manual_seed(seed)
134
+
135
+ # Cannot reduce below 16 because convolution kernel becomes bigger than sample
136
+ # Cannot reduce below 32 because 3D RoPE errors out
137
+ image_height = 16
138
+ image_width = 16
139
+ image = Image.new("RGB", (image_width, image_height))
140
+ inputs = {
141
+ "image": image,
142
+ "prompt": "dance monkey",
143
+ "negative_prompt": "",
144
+ "generator": generator,
145
+ "num_inference_steps": 2,
146
+ "guidance_scale": 6.0,
147
+ "height": image_height,
148
+ "width": image_width,
149
+ "num_frames": 8,
150
+ "max_sequence_length": 16,
151
+ "output_type": "pt",
152
+ }
153
+ return inputs
154
+
155
+ def test_inference(self):
156
+ device = "cpu"
157
+
158
+ components = self.get_dummy_components()
159
+ pipe = self.pipeline_class(**components)
160
+ pipe.to(device)
161
+ pipe.set_progress_bar_config(disable=None)
162
+
163
+ inputs = self.get_dummy_inputs(device)
164
+ video = pipe(**inputs).frames
165
+ generated_video = video[0]
166
+
167
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
168
+ expected_video = torch.randn(8, 3, 16, 16)
169
+ max_diff = np.abs(generated_video - expected_video).max()
170
+ self.assertLessEqual(max_diff, 1e10)
171
+
172
+ def test_callback_inputs(self):
173
+ sig = inspect.signature(self.pipeline_class.__call__)
174
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
175
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
176
+
177
+ if not (has_callback_tensor_inputs and has_callback_step_end):
178
+ return
179
+
180
+ components = self.get_dummy_components()
181
+ pipe = self.pipeline_class(**components)
182
+ pipe = pipe.to(torch_device)
183
+ pipe.set_progress_bar_config(disable=None)
184
+ self.assertTrue(
185
+ hasattr(pipe, "_callback_tensor_inputs"),
186
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
187
+ )
188
+
189
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
190
+ # iterate over callback args
191
+ for tensor_name, tensor_value in callback_kwargs.items():
192
+ # check that we're only passing in allowed tensor inputs
193
+ assert tensor_name in pipe._callback_tensor_inputs
194
+
195
+ return callback_kwargs
196
+
197
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
198
+ for tensor_name in pipe._callback_tensor_inputs:
199
+ assert tensor_name in callback_kwargs
200
+
201
+ # iterate over callback args
202
+ for tensor_name, tensor_value in callback_kwargs.items():
203
+ # check that we're only passing in allowed tensor inputs
204
+ assert tensor_name in pipe._callback_tensor_inputs
205
+
206
+ return callback_kwargs
207
+
208
+ inputs = self.get_dummy_inputs(torch_device)
209
+
210
+ # Test passing in a subset
211
+ inputs["callback_on_step_end"] = callback_inputs_subset
212
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
213
+ output = pipe(**inputs)[0]
214
+
215
+ # Test passing in a everything
216
+ inputs["callback_on_step_end"] = callback_inputs_all
217
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
218
+ output = pipe(**inputs)[0]
219
+
220
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
221
+ is_last = i == (pipe.num_timesteps - 1)
222
+ if is_last:
223
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
224
+ return callback_kwargs
225
+
226
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
227
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
228
+ output = pipe(**inputs)[0]
229
+ assert output.abs().sum() < 1e10
230
+
231
+ def test_inference_batch_single_identical(self):
232
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
233
+
234
+ def test_attention_slicing_forward_pass(
235
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
236
+ ):
237
+ if not self.test_attention_slicing:
238
+ return
239
+
240
+ components = self.get_dummy_components()
241
+ for key in components:
242
+ if "text_encoder" in key and hasattr(components[key], "eval"):
243
+ components[key].eval()
244
+ pipe = self.pipeline_class(**components)
245
+ for component in pipe.components.values():
246
+ if hasattr(component, "set_default_attn_processor"):
247
+ component.set_default_attn_processor()
248
+ pipe.to(torch_device)
249
+ pipe.set_progress_bar_config(disable=None)
250
+
251
+ generator_device = "cpu"
252
+ inputs = self.get_dummy_inputs(generator_device)
253
+ output_without_slicing = pipe(**inputs)[0]
254
+
255
+ pipe.enable_attention_slicing(slice_size=1)
256
+ inputs = self.get_dummy_inputs(generator_device)
257
+ output_with_slicing1 = pipe(**inputs)[0]
258
+
259
+ pipe.enable_attention_slicing(slice_size=2)
260
+ inputs = self.get_dummy_inputs(generator_device)
261
+ output_with_slicing2 = pipe(**inputs)[0]
262
+
263
+ if test_max_difference:
264
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
265
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
266
+ self.assertLess(
267
+ max(max_diff1, max_diff2),
268
+ expected_max_diff,
269
+ "Attention slicing should not affect the inference results",
270
+ )
271
+
272
+ def test_vae_tiling(self, expected_diff_max: float = 0.3):
273
+ # Note(aryan): Investigate why this needs a bit higher tolerance
274
+ generator_device = "cpu"
275
+ components = self.get_dummy_components()
276
+
277
+ # The reason to modify it this way is because I2V Transformer limits the generation to resolutions used during initialization.
278
+ # This limitation comes from using learned positional embeddings which cannot be generated on-the-fly like sincos or RoPE embeddings.
279
+ # See the if-statement on "self.use_learned_positional_embeddings" in diffusers/models/embeddings.py
280
+ components["transformer"] = CogVideoXTransformer3DModel.from_config(
281
+ components["transformer"].config,
282
+ sample_height=16,
283
+ sample_width=16,
284
+ )
285
+
286
+ pipe = self.pipeline_class(**components)
287
+ pipe.to("cpu")
288
+ pipe.set_progress_bar_config(disable=None)
289
+
290
+ # Without tiling
291
+ inputs = self.get_dummy_inputs(generator_device)
292
+ inputs["height"] = inputs["width"] = 128
293
+ output_without_tiling = pipe(**inputs)[0]
294
+
295
+ # With tiling
296
+ pipe.vae.enable_tiling(
297
+ tile_sample_min_height=96,
298
+ tile_sample_min_width=96,
299
+ tile_overlap_factor_height=1 / 12,
300
+ tile_overlap_factor_width=1 / 12,
301
+ )
302
+ inputs = self.get_dummy_inputs(generator_device)
303
+ inputs["height"] = inputs["width"] = 128
304
+ output_with_tiling = pipe(**inputs)[0]
305
+
306
+ self.assertLess(
307
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
308
+ expected_diff_max,
309
+ "VAE tiling should not affect the inference results",
310
+ )
311
+
312
+ def test_fused_qkv_projections(self):
313
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
314
+ components = self.get_dummy_components()
315
+ pipe = self.pipeline_class(**components)
316
+ pipe = pipe.to(device)
317
+ pipe.set_progress_bar_config(disable=None)
318
+
319
+ inputs = self.get_dummy_inputs(device)
320
+ frames = pipe(**inputs).frames # [B, F, C, H, W]
321
+ original_image_slice = frames[0, -2:, -1, -3:, -3:]
322
+
323
+ pipe.fuse_qkv_projections()
324
+ assert check_qkv_fusion_processors_exist(pipe.transformer), (
325
+ "Something wrong with the fused attention processors. Expected all the attention processors to be fused."
326
+ )
327
+ assert check_qkv_fusion_matches_attn_procs_length(
328
+ pipe.transformer, pipe.transformer.original_attn_processors
329
+ ), "Something wrong with the attention processors concerning the fused QKV projections."
330
+
331
+ inputs = self.get_dummy_inputs(device)
332
+ frames = pipe(**inputs).frames
333
+ image_slice_fused = frames[0, -2:, -1, -3:, -3:]
334
+
335
+ pipe.transformer.unfuse_qkv_projections()
336
+ inputs = self.get_dummy_inputs(device)
337
+ frames = pipe(**inputs).frames
338
+ image_slice_disabled = frames[0, -2:, -1, -3:, -3:]
339
+
340
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
341
+ "Fusion of QKV projections shouldn't affect the outputs."
342
+ )
343
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
344
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
345
+ )
346
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
347
+ "Original outputs should match when fused QKV projections are disabled."
348
+ )
349
+
350
+
351
+ @slow
352
+ @require_torch_accelerator
353
+ class CogVideoXImageToVideoPipelineIntegrationTests(unittest.TestCase):
354
+ prompt = "A painting of a squirrel eating a burger."
355
+
356
+ def setUp(self):
357
+ super().setUp()
358
+ gc.collect()
359
+ backend_empty_cache(torch_device)
360
+
361
+ def tearDown(self):
362
+ super().tearDown()
363
+ gc.collect()
364
+ backend_empty_cache(torch_device)
365
+
366
+ def test_cogvideox(self):
367
+ generator = torch.Generator("cpu").manual_seed(0)
368
+
369
+ pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16)
370
+ pipe.enable_model_cpu_offload(device=torch_device)
371
+
372
+ prompt = self.prompt
373
+ image = load_image(
374
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
375
+ )
376
+
377
+ videos = pipe(
378
+ image=image,
379
+ prompt=prompt,
380
+ height=480,
381
+ width=720,
382
+ num_frames=16,
383
+ generator=generator,
384
+ num_inference_steps=2,
385
+ output_type="pt",
386
+ ).frames
387
+
388
+ video = videos[0]
389
+ expected_video = torch.randn(1, 16, 480, 720, 3).numpy()
390
+
391
+ max_diff = numpy_cosine_similarity_distance(video, expected_video)
392
+ assert max_diff < 1e-3, f"Max diff is too high. got {video}"
diffusers/tests/pipelines/cogvideo/test_cogvideox_video2video.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+ from PIL import Image
21
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
22
+
23
+ from diffusers import AutoencoderKLCogVideoX, CogVideoXTransformer3DModel, CogVideoXVideoToVideoPipeline, DDIMScheduler
24
+
25
+ from ...testing_utils import enable_full_determinism, torch_device
26
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
27
+ from ..test_pipelines_common import (
28
+ PipelineTesterMixin,
29
+ check_qkv_fusion_matches_attn_procs_length,
30
+ check_qkv_fusion_processors_exist,
31
+ to_np,
32
+ )
33
+
34
+
35
+ enable_full_determinism()
36
+
37
+
38
+ class CogVideoXVideoToVideoPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
39
+ pipeline_class = CogVideoXVideoToVideoPipeline
40
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
41
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"video"})
42
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
43
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
44
+ required_optional_params = frozenset(
45
+ [
46
+ "num_inference_steps",
47
+ "generator",
48
+ "latents",
49
+ "return_dict",
50
+ "callback_on_step_end",
51
+ "callback_on_step_end_tensor_inputs",
52
+ ]
53
+ )
54
+ test_xformers_attention = False
55
+
56
+ def get_dummy_components(self):
57
+ torch.manual_seed(0)
58
+ transformer = CogVideoXTransformer3DModel(
59
+ # Product of num_attention_heads * attention_head_dim must be divisible by 16 for 3D positional embeddings
60
+ # But, since we are using tiny-random-t5 here, we need the internal dim of CogVideoXTransformer3DModel
61
+ # to be 32. The internal dim is product of num_attention_heads and attention_head_dim
62
+ num_attention_heads=4,
63
+ attention_head_dim=8,
64
+ in_channels=4,
65
+ out_channels=4,
66
+ time_embed_dim=2,
67
+ text_embed_dim=32, # Must match with tiny-random-t5
68
+ num_layers=1,
69
+ sample_width=2, # latent width: 2 -> final width: 16
70
+ sample_height=2, # latent height: 2 -> final height: 16
71
+ sample_frames=9, # latent frames: (9 - 1) / 4 + 1 = 3 -> final frames: 9
72
+ patch_size=2,
73
+ temporal_compression_ratio=4,
74
+ max_text_seq_length=16,
75
+ )
76
+
77
+ torch.manual_seed(0)
78
+ vae = AutoencoderKLCogVideoX(
79
+ in_channels=3,
80
+ out_channels=3,
81
+ down_block_types=(
82
+ "CogVideoXDownBlock3D",
83
+ "CogVideoXDownBlock3D",
84
+ "CogVideoXDownBlock3D",
85
+ "CogVideoXDownBlock3D",
86
+ ),
87
+ up_block_types=(
88
+ "CogVideoXUpBlock3D",
89
+ "CogVideoXUpBlock3D",
90
+ "CogVideoXUpBlock3D",
91
+ "CogVideoXUpBlock3D",
92
+ ),
93
+ block_out_channels=(8, 8, 8, 8),
94
+ latent_channels=4,
95
+ layers_per_block=1,
96
+ norm_num_groups=2,
97
+ temporal_compression_ratio=4,
98
+ )
99
+
100
+ torch.manual_seed(0)
101
+ scheduler = DDIMScheduler()
102
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
103
+ text_encoder = T5EncoderModel(config)
104
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
105
+
106
+ components = {
107
+ "transformer": transformer,
108
+ "vae": vae,
109
+ "scheduler": scheduler,
110
+ "text_encoder": text_encoder,
111
+ "tokenizer": tokenizer,
112
+ }
113
+ return components
114
+
115
+ def get_dummy_inputs(self, device, seed: int = 0, num_frames: int = 8):
116
+ if str(device).startswith("mps"):
117
+ generator = torch.manual_seed(seed)
118
+ else:
119
+ generator = torch.Generator(device=device).manual_seed(seed)
120
+
121
+ video_height = 16
122
+ video_width = 16
123
+ video = [Image.new("RGB", (video_width, video_height))] * num_frames
124
+
125
+ inputs = {
126
+ "video": video,
127
+ "prompt": "dance monkey",
128
+ "negative_prompt": "",
129
+ "generator": generator,
130
+ "num_inference_steps": 2,
131
+ "strength": 0.5,
132
+ "guidance_scale": 6.0,
133
+ # Cannot reduce because convolution kernel becomes bigger than sample
134
+ "height": video_height,
135
+ "width": video_width,
136
+ "max_sequence_length": 16,
137
+ "output_type": "pt",
138
+ }
139
+ return inputs
140
+
141
+ def test_inference(self):
142
+ device = "cpu"
143
+
144
+ components = self.get_dummy_components()
145
+ pipe = self.pipeline_class(**components)
146
+ pipe.to(device)
147
+ pipe.set_progress_bar_config(disable=None)
148
+
149
+ inputs = self.get_dummy_inputs(device)
150
+ video = pipe(**inputs).frames
151
+ generated_video = video[0]
152
+
153
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
154
+ expected_video = torch.randn(8, 3, 16, 16)
155
+ max_diff = np.abs(generated_video - expected_video).max()
156
+ self.assertLessEqual(max_diff, 1e10)
157
+
158
+ def test_callback_inputs(self):
159
+ sig = inspect.signature(self.pipeline_class.__call__)
160
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
161
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
162
+
163
+ if not (has_callback_tensor_inputs and has_callback_step_end):
164
+ return
165
+
166
+ components = self.get_dummy_components()
167
+ pipe = self.pipeline_class(**components)
168
+ pipe = pipe.to(torch_device)
169
+ pipe.set_progress_bar_config(disable=None)
170
+ self.assertTrue(
171
+ hasattr(pipe, "_callback_tensor_inputs"),
172
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
173
+ )
174
+
175
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
176
+ # iterate over callback args
177
+ for tensor_name, tensor_value in callback_kwargs.items():
178
+ # check that we're only passing in allowed tensor inputs
179
+ assert tensor_name in pipe._callback_tensor_inputs
180
+
181
+ return callback_kwargs
182
+
183
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
184
+ for tensor_name in pipe._callback_tensor_inputs:
185
+ assert tensor_name in callback_kwargs
186
+
187
+ # iterate over callback args
188
+ for tensor_name, tensor_value in callback_kwargs.items():
189
+ # check that we're only passing in allowed tensor inputs
190
+ assert tensor_name in pipe._callback_tensor_inputs
191
+
192
+ return callback_kwargs
193
+
194
+ inputs = self.get_dummy_inputs(torch_device)
195
+
196
+ # Test passing in a subset
197
+ inputs["callback_on_step_end"] = callback_inputs_subset
198
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
199
+ output = pipe(**inputs)[0]
200
+
201
+ # Test passing in a everything
202
+ inputs["callback_on_step_end"] = callback_inputs_all
203
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
204
+ output = pipe(**inputs)[0]
205
+
206
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
207
+ is_last = i == (pipe.num_timesteps - 1)
208
+ if is_last:
209
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
210
+ return callback_kwargs
211
+
212
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
213
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
214
+ output = pipe(**inputs)[0]
215
+ assert output.abs().sum() < 1e10
216
+
217
+ def test_inference_batch_single_identical(self):
218
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
219
+
220
+ def test_attention_slicing_forward_pass(
221
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
222
+ ):
223
+ if not self.test_attention_slicing:
224
+ return
225
+
226
+ components = self.get_dummy_components()
227
+ pipe = self.pipeline_class(**components)
228
+ for component in pipe.components.values():
229
+ if hasattr(component, "set_default_attn_processor"):
230
+ component.set_default_attn_processor()
231
+ pipe.to(torch_device)
232
+ pipe.set_progress_bar_config(disable=None)
233
+
234
+ generator_device = "cpu"
235
+ inputs = self.get_dummy_inputs(generator_device)
236
+ output_without_slicing = pipe(**inputs)[0]
237
+
238
+ pipe.enable_attention_slicing(slice_size=1)
239
+ inputs = self.get_dummy_inputs(generator_device)
240
+ output_with_slicing1 = pipe(**inputs)[0]
241
+
242
+ pipe.enable_attention_slicing(slice_size=2)
243
+ inputs = self.get_dummy_inputs(generator_device)
244
+ output_with_slicing2 = pipe(**inputs)[0]
245
+
246
+ if test_max_difference:
247
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
248
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
249
+ self.assertLess(
250
+ max(max_diff1, max_diff2),
251
+ expected_max_diff,
252
+ "Attention slicing should not affect the inference results",
253
+ )
254
+
255
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
256
+ # Since VideoToVideo uses both encoder and decoder tiling, there seems to be much more numerical
257
+ # difference. We seem to need a higher tolerance here...
258
+ # TODO(aryan): Look into this more deeply
259
+ expected_diff_max = 0.4
260
+
261
+ generator_device = "cpu"
262
+ components = self.get_dummy_components()
263
+
264
+ pipe = self.pipeline_class(**components)
265
+ pipe.to("cpu")
266
+ pipe.set_progress_bar_config(disable=None)
267
+
268
+ # Without tiling
269
+ inputs = self.get_dummy_inputs(generator_device)
270
+ inputs["height"] = inputs["width"] = 128
271
+ output_without_tiling = pipe(**inputs)[0]
272
+
273
+ # With tiling
274
+ pipe.vae.enable_tiling(
275
+ tile_sample_min_height=96,
276
+ tile_sample_min_width=96,
277
+ tile_overlap_factor_height=1 / 12,
278
+ tile_overlap_factor_width=1 / 12,
279
+ )
280
+ inputs = self.get_dummy_inputs(generator_device)
281
+ inputs["height"] = inputs["width"] = 128
282
+ output_with_tiling = pipe(**inputs)[0]
283
+
284
+ self.assertLess(
285
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
286
+ expected_diff_max,
287
+ "VAE tiling should not affect the inference results",
288
+ )
289
+
290
+ def test_fused_qkv_projections(self):
291
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
292
+ components = self.get_dummy_components()
293
+ pipe = self.pipeline_class(**components)
294
+ pipe = pipe.to(device)
295
+ pipe.set_progress_bar_config(disable=None)
296
+
297
+ inputs = self.get_dummy_inputs(device)
298
+ frames = pipe(**inputs).frames # [B, F, C, H, W]
299
+ original_image_slice = frames[0, -2:, -1, -3:, -3:]
300
+
301
+ pipe.fuse_qkv_projections()
302
+ assert check_qkv_fusion_processors_exist(pipe.transformer), (
303
+ "Something wrong with the fused attention processors. Expected all the attention processors to be fused."
304
+ )
305
+ assert check_qkv_fusion_matches_attn_procs_length(
306
+ pipe.transformer, pipe.transformer.original_attn_processors
307
+ ), "Something wrong with the attention processors concerning the fused QKV projections."
308
+
309
+ inputs = self.get_dummy_inputs(device)
310
+ frames = pipe(**inputs).frames
311
+ image_slice_fused = frames[0, -2:, -1, -3:, -3:]
312
+
313
+ pipe.transformer.unfuse_qkv_projections()
314
+ inputs = self.get_dummy_inputs(device)
315
+ frames = pipe(**inputs).frames
316
+ image_slice_disabled = frames[0, -2:, -1, -3:, -3:]
317
+
318
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
319
+ "Fusion of QKV projections shouldn't affect the outputs."
320
+ )
321
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
322
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
323
+ )
324
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
325
+ "Original outputs should match when fused QKV projections are disabled."
326
+ )
diffusers/tests/pipelines/cogview3/__init__.py ADDED
File without changes
diffusers/tests/pipelines/cogview3/test_cogview3plus.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import inspect
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
22
+
23
+ from diffusers import AutoencoderKL, CogVideoXDDIMScheduler, CogView3PlusPipeline, CogView3PlusTransformer2DModel
24
+
25
+ from ...testing_utils import (
26
+ backend_empty_cache,
27
+ enable_full_determinism,
28
+ numpy_cosine_similarity_distance,
29
+ require_torch_accelerator,
30
+ slow,
31
+ torch_device,
32
+ )
33
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
34
+ from ..test_pipelines_common import (
35
+ PipelineTesterMixin,
36
+ to_np,
37
+ )
38
+
39
+
40
+ enable_full_determinism()
41
+
42
+
43
+ class CogView3PlusPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
44
+ pipeline_class = CogView3PlusPipeline
45
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
46
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
47
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
48
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
49
+ required_optional_params = frozenset(
50
+ [
51
+ "num_inference_steps",
52
+ "generator",
53
+ "latents",
54
+ "return_dict",
55
+ "callback_on_step_end",
56
+ "callback_on_step_end_tensor_inputs",
57
+ ]
58
+ )
59
+ test_xformers_attention = False
60
+ test_layerwise_casting = True
61
+ test_group_offloading = True
62
+
63
+ def get_dummy_components(self):
64
+ torch.manual_seed(0)
65
+ transformer = CogView3PlusTransformer2DModel(
66
+ patch_size=2,
67
+ in_channels=4,
68
+ num_layers=1,
69
+ attention_head_dim=4,
70
+ num_attention_heads=2,
71
+ out_channels=4,
72
+ text_embed_dim=32, # Must match with tiny-random-t5
73
+ time_embed_dim=8,
74
+ condition_dim=2,
75
+ pos_embed_max_size=8,
76
+ sample_size=8,
77
+ )
78
+
79
+ torch.manual_seed(0)
80
+ vae = AutoencoderKL(
81
+ block_out_channels=[32, 64],
82
+ in_channels=3,
83
+ out_channels=3,
84
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
85
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
86
+ latent_channels=4,
87
+ sample_size=128,
88
+ )
89
+
90
+ torch.manual_seed(0)
91
+ scheduler = CogVideoXDDIMScheduler()
92
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
93
+ text_encoder = T5EncoderModel(config)
94
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
95
+
96
+ components = {
97
+ "transformer": transformer,
98
+ "vae": vae,
99
+ "scheduler": scheduler,
100
+ "text_encoder": text_encoder,
101
+ "tokenizer": tokenizer,
102
+ }
103
+ return components
104
+
105
+ def get_dummy_inputs(self, device, seed=0):
106
+ if str(device).startswith("mps"):
107
+ generator = torch.manual_seed(seed)
108
+ else:
109
+ generator = torch.Generator(device=device).manual_seed(seed)
110
+ inputs = {
111
+ "prompt": "dance monkey",
112
+ "negative_prompt": "",
113
+ "generator": generator,
114
+ "num_inference_steps": 2,
115
+ "guidance_scale": 6.0,
116
+ "height": 16,
117
+ "width": 16,
118
+ "max_sequence_length": 16,
119
+ "output_type": "pt",
120
+ }
121
+ return inputs
122
+
123
+ def test_inference(self):
124
+ device = "cpu"
125
+
126
+ components = self.get_dummy_components()
127
+ pipe = self.pipeline_class(**components)
128
+ pipe.to(device)
129
+ pipe.set_progress_bar_config(disable=None)
130
+
131
+ inputs = self.get_dummy_inputs(device)
132
+ image = pipe(**inputs)[0]
133
+ generated_image = image[0]
134
+
135
+ self.assertEqual(generated_image.shape, (3, 16, 16))
136
+ expected_image = torch.randn(3, 16, 16)
137
+ max_diff = np.abs(generated_image - expected_image).max()
138
+ self.assertLessEqual(max_diff, 1e10)
139
+
140
+ def test_callback_inputs(self):
141
+ sig = inspect.signature(self.pipeline_class.__call__)
142
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
143
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
144
+
145
+ if not (has_callback_tensor_inputs and has_callback_step_end):
146
+ return
147
+
148
+ components = self.get_dummy_components()
149
+ pipe = self.pipeline_class(**components)
150
+ pipe = pipe.to(torch_device)
151
+ pipe.set_progress_bar_config(disable=None)
152
+ self.assertTrue(
153
+ hasattr(pipe, "_callback_tensor_inputs"),
154
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
155
+ )
156
+
157
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
158
+ # iterate over callback args
159
+ for tensor_name, tensor_value in callback_kwargs.items():
160
+ # check that we're only passing in allowed tensor inputs
161
+ assert tensor_name in pipe._callback_tensor_inputs
162
+
163
+ return callback_kwargs
164
+
165
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
166
+ for tensor_name in pipe._callback_tensor_inputs:
167
+ assert tensor_name in callback_kwargs
168
+
169
+ # iterate over callback args
170
+ for tensor_name, tensor_value in callback_kwargs.items():
171
+ # check that we're only passing in allowed tensor inputs
172
+ assert tensor_name in pipe._callback_tensor_inputs
173
+
174
+ return callback_kwargs
175
+
176
+ inputs = self.get_dummy_inputs(torch_device)
177
+
178
+ # Test passing in a subset
179
+ inputs["callback_on_step_end"] = callback_inputs_subset
180
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
181
+ output = pipe(**inputs)[0]
182
+
183
+ # Test passing in a everything
184
+ inputs["callback_on_step_end"] = callback_inputs_all
185
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
186
+ output = pipe(**inputs)[0]
187
+
188
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
189
+ is_last = i == (pipe.num_timesteps - 1)
190
+ if is_last:
191
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
192
+ return callback_kwargs
193
+
194
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
195
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
196
+ output = pipe(**inputs)[0]
197
+ assert output.abs().sum() < 1e10
198
+
199
+ def test_inference_batch_single_identical(self):
200
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
201
+
202
+ def test_attention_slicing_forward_pass(
203
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
204
+ ):
205
+ if not self.test_attention_slicing:
206
+ return
207
+
208
+ components = self.get_dummy_components()
209
+ pipe = self.pipeline_class(**components)
210
+ for component in pipe.components.values():
211
+ if hasattr(component, "set_default_attn_processor"):
212
+ component.set_default_attn_processor()
213
+ pipe.to(torch_device)
214
+ pipe.set_progress_bar_config(disable=None)
215
+
216
+ generator_device = "cpu"
217
+ inputs = self.get_dummy_inputs(generator_device)
218
+ output_without_slicing = pipe(**inputs)[0]
219
+
220
+ pipe.enable_attention_slicing(slice_size=1)
221
+ inputs = self.get_dummy_inputs(generator_device)
222
+ output_with_slicing1 = pipe(**inputs)[0]
223
+
224
+ pipe.enable_attention_slicing(slice_size=2)
225
+ inputs = self.get_dummy_inputs(generator_device)
226
+ output_with_slicing2 = pipe(**inputs)[0]
227
+
228
+ if test_max_difference:
229
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
230
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
231
+ self.assertLess(
232
+ max(max_diff1, max_diff2),
233
+ expected_max_diff,
234
+ "Attention slicing should not affect the inference results",
235
+ )
236
+
237
+ def test_encode_prompt_works_in_isolation(self):
238
+ return super().test_encode_prompt_works_in_isolation(atol=1e-3, rtol=1e-3)
239
+
240
+
241
+ @slow
242
+ @require_torch_accelerator
243
+ class CogView3PlusPipelineIntegrationTests(unittest.TestCase):
244
+ prompt = "A painting of a squirrel eating a burger."
245
+
246
+ def setUp(self):
247
+ super().setUp()
248
+ gc.collect()
249
+ backend_empty_cache(torch_device)
250
+
251
+ def tearDown(self):
252
+ super().tearDown()
253
+ gc.collect()
254
+ backend_empty_cache(torch_device)
255
+
256
+ def test_cogview3plus(self):
257
+ generator = torch.Generator("cpu").manual_seed(0)
258
+
259
+ pipe = CogView3PlusPipeline.from_pretrained("THUDM/CogView3Plus-3b", torch_dtype=torch.float16)
260
+ pipe.enable_model_cpu_offload(device=torch_device)
261
+ prompt = self.prompt
262
+
263
+ images = pipe(
264
+ prompt=prompt,
265
+ height=1024,
266
+ width=1024,
267
+ generator=generator,
268
+ num_inference_steps=2,
269
+ output_type="np",
270
+ )[0]
271
+
272
+ image = images[0]
273
+ expected_image = torch.randn(1, 1024, 1024, 3).numpy()
274
+
275
+ max_diff = numpy_cosine_similarity_distance(image, expected_image)
276
+ assert max_diff < 1e-3, f"Max diff is too high. got {image}"
diffusers/tests/pipelines/cogview4/__init__.py ADDED
File without changes
diffusers/tests/pipelines/cogview4/test_cogview4.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import AutoTokenizer, GlmConfig, GlmForCausalLM
21
+
22
+ from diffusers import AutoencoderKL, CogView4Pipeline, CogView4Transformer2DModel, FlowMatchEulerDiscreteScheduler
23
+
24
+ from ...testing_utils import enable_full_determinism, torch_device
25
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
26
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
27
+
28
+
29
+ enable_full_determinism()
30
+
31
+
32
+ class CogView4PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
33
+ pipeline_class = CogView4Pipeline
34
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
35
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
36
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
37
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
38
+ required_optional_params = frozenset(
39
+ [
40
+ "num_inference_steps",
41
+ "generator",
42
+ "latents",
43
+ "return_dict",
44
+ "callback_on_step_end",
45
+ "callback_on_step_end_tensor_inputs",
46
+ ]
47
+ )
48
+
49
+ supports_dduf = False
50
+ test_xformers_attention = False
51
+ test_layerwise_casting = True
52
+
53
+ def get_dummy_components(self):
54
+ torch.manual_seed(0)
55
+ transformer = CogView4Transformer2DModel(
56
+ patch_size=2,
57
+ in_channels=4,
58
+ num_layers=2,
59
+ attention_head_dim=4,
60
+ num_attention_heads=4,
61
+ out_channels=4,
62
+ text_embed_dim=32,
63
+ time_embed_dim=8,
64
+ condition_dim=4,
65
+ )
66
+
67
+ torch.manual_seed(0)
68
+ vae = AutoencoderKL(
69
+ block_out_channels=[32, 64],
70
+ in_channels=3,
71
+ out_channels=3,
72
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
73
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
74
+ latent_channels=4,
75
+ sample_size=128,
76
+ )
77
+
78
+ torch.manual_seed(0)
79
+ scheduler = FlowMatchEulerDiscreteScheduler(
80
+ base_shift=0.25,
81
+ max_shift=0.75,
82
+ base_image_seq_len=256,
83
+ use_dynamic_shifting=True,
84
+ time_shift_type="linear",
85
+ )
86
+
87
+ torch.manual_seed(0)
88
+ text_encoder_config = GlmConfig(
89
+ hidden_size=32, intermediate_size=8, num_hidden_layers=2, num_attention_heads=4, head_dim=8
90
+ )
91
+ text_encoder = GlmForCausalLM(text_encoder_config)
92
+ # TODO(aryan): change this to THUDM/CogView4 once released
93
+ tokenizer = AutoTokenizer.from_pretrained("THUDM/glm-4-9b-chat", trust_remote_code=True)
94
+
95
+ components = {
96
+ "transformer": transformer,
97
+ "vae": vae,
98
+ "scheduler": scheduler,
99
+ "text_encoder": text_encoder,
100
+ "tokenizer": tokenizer,
101
+ }
102
+ return components
103
+
104
+ def get_dummy_inputs(self, device, seed=0):
105
+ if str(device).startswith("mps"):
106
+ generator = torch.manual_seed(seed)
107
+ else:
108
+ generator = torch.Generator(device=device).manual_seed(seed)
109
+ inputs = {
110
+ "prompt": "dance monkey",
111
+ "negative_prompt": "bad",
112
+ "generator": generator,
113
+ "num_inference_steps": 2,
114
+ "guidance_scale": 6.0,
115
+ "height": 16,
116
+ "width": 16,
117
+ "max_sequence_length": 16,
118
+ "output_type": "pt",
119
+ }
120
+ return inputs
121
+
122
+ def test_inference(self):
123
+ device = "cpu"
124
+
125
+ components = self.get_dummy_components()
126
+ pipe = self.pipeline_class(**components)
127
+ pipe.to(device)
128
+ pipe.set_progress_bar_config(disable=None)
129
+
130
+ inputs = self.get_dummy_inputs(device)
131
+ image = pipe(**inputs)[0]
132
+ generated_image = image[0]
133
+
134
+ self.assertEqual(generated_image.shape, (3, 16, 16))
135
+ expected_image = torch.randn(3, 16, 16)
136
+ max_diff = np.abs(generated_image - expected_image).max()
137
+ self.assertLessEqual(max_diff, 1e10)
138
+
139
+ def test_callback_inputs(self):
140
+ sig = inspect.signature(self.pipeline_class.__call__)
141
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
142
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
143
+
144
+ if not (has_callback_tensor_inputs and has_callback_step_end):
145
+ return
146
+
147
+ components = self.get_dummy_components()
148
+ pipe = self.pipeline_class(**components)
149
+ pipe = pipe.to(torch_device)
150
+ pipe.set_progress_bar_config(disable=None)
151
+ self.assertTrue(
152
+ hasattr(pipe, "_callback_tensor_inputs"),
153
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
154
+ )
155
+
156
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
157
+ # iterate over callback args
158
+ for tensor_name, tensor_value in callback_kwargs.items():
159
+ # check that we're only passing in allowed tensor inputs
160
+ assert tensor_name in pipe._callback_tensor_inputs
161
+
162
+ return callback_kwargs
163
+
164
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
165
+ for tensor_name in pipe._callback_tensor_inputs:
166
+ assert tensor_name in callback_kwargs
167
+
168
+ # iterate over callback args
169
+ for tensor_name, tensor_value in callback_kwargs.items():
170
+ # check that we're only passing in allowed tensor inputs
171
+ assert tensor_name in pipe._callback_tensor_inputs
172
+
173
+ return callback_kwargs
174
+
175
+ inputs = self.get_dummy_inputs(torch_device)
176
+
177
+ # Test passing in a subset
178
+ inputs["callback_on_step_end"] = callback_inputs_subset
179
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
180
+ output = pipe(**inputs)[0]
181
+
182
+ # Test passing in a everything
183
+ inputs["callback_on_step_end"] = callback_inputs_all
184
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
185
+ output = pipe(**inputs)[0]
186
+
187
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
188
+ is_last = i == (pipe.num_timesteps - 1)
189
+ if is_last:
190
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
191
+ return callback_kwargs
192
+
193
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
194
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
195
+ output = pipe(**inputs)[0]
196
+ assert output.abs().sum() < 1e10
197
+
198
+ def test_inference_batch_single_identical(self):
199
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
200
+
201
+ def test_attention_slicing_forward_pass(
202
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
203
+ ):
204
+ if not self.test_attention_slicing:
205
+ return
206
+
207
+ components = self.get_dummy_components()
208
+ pipe = self.pipeline_class(**components)
209
+ for component in pipe.components.values():
210
+ if hasattr(component, "set_default_attn_processor"):
211
+ component.set_default_attn_processor()
212
+ pipe.to(torch_device)
213
+ pipe.set_progress_bar_config(disable=None)
214
+
215
+ generator_device = "cpu"
216
+ inputs = self.get_dummy_inputs(generator_device)
217
+ output_without_slicing = pipe(**inputs)[0]
218
+
219
+ pipe.enable_attention_slicing(slice_size=1)
220
+ inputs = self.get_dummy_inputs(generator_device)
221
+ output_with_slicing1 = pipe(**inputs)[0]
222
+
223
+ pipe.enable_attention_slicing(slice_size=2)
224
+ inputs = self.get_dummy_inputs(generator_device)
225
+ output_with_slicing2 = pipe(**inputs)[0]
226
+
227
+ if test_max_difference:
228
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
229
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
230
+ self.assertLess(
231
+ max(max_diff1, max_diff2),
232
+ expected_max_diff,
233
+ "Attention slicing should not affect the inference results",
234
+ )
diffusers/tests/pipelines/consisid/__init__.py ADDED
File without changes
diffusers/tests/pipelines/consisid/test_consisid.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import gc
16
+ import inspect
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
23
+
24
+ from diffusers import AutoencoderKLCogVideoX, ConsisIDPipeline, ConsisIDTransformer3DModel, DDIMScheduler
25
+ from diffusers.utils import load_image
26
+
27
+ from ...testing_utils import (
28
+ backend_empty_cache,
29
+ enable_full_determinism,
30
+ numpy_cosine_similarity_distance,
31
+ require_torch_accelerator,
32
+ slow,
33
+ torch_device,
34
+ )
35
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
36
+ from ..test_pipelines_common import (
37
+ PipelineTesterMixin,
38
+ to_np,
39
+ )
40
+
41
+
42
+ enable_full_determinism()
43
+
44
+
45
+ class ConsisIDPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
46
+ pipeline_class = ConsisIDPipeline
47
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
48
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image"})
49
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
50
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
51
+ required_optional_params = frozenset(
52
+ [
53
+ "num_inference_steps",
54
+ "generator",
55
+ "latents",
56
+ "return_dict",
57
+ "callback_on_step_end",
58
+ "callback_on_step_end_tensor_inputs",
59
+ ]
60
+ )
61
+ test_xformers_attention = False
62
+ test_layerwise_casting = True
63
+ test_group_offloading = True
64
+
65
+ def get_dummy_components(self):
66
+ torch.manual_seed(0)
67
+ transformer = ConsisIDTransformer3DModel(
68
+ num_attention_heads=2,
69
+ attention_head_dim=16,
70
+ in_channels=8,
71
+ out_channels=4,
72
+ time_embed_dim=2,
73
+ text_embed_dim=32,
74
+ num_layers=1,
75
+ sample_width=2,
76
+ sample_height=2,
77
+ sample_frames=9,
78
+ patch_size=2,
79
+ temporal_compression_ratio=4,
80
+ max_text_seq_length=16,
81
+ use_rotary_positional_embeddings=True,
82
+ use_learned_positional_embeddings=True,
83
+ cross_attn_interval=1,
84
+ is_kps=False,
85
+ is_train_face=True,
86
+ cross_attn_dim_head=1,
87
+ cross_attn_num_heads=1,
88
+ LFE_id_dim=2,
89
+ LFE_vit_dim=2,
90
+ LFE_depth=5,
91
+ LFE_dim_head=8,
92
+ LFE_num_heads=2,
93
+ LFE_num_id_token=1,
94
+ LFE_num_querie=1,
95
+ LFE_output_dim=21,
96
+ LFE_ff_mult=1,
97
+ LFE_num_scale=1,
98
+ )
99
+
100
+ torch.manual_seed(0)
101
+ vae = AutoencoderKLCogVideoX(
102
+ in_channels=3,
103
+ out_channels=3,
104
+ down_block_types=(
105
+ "CogVideoXDownBlock3D",
106
+ "CogVideoXDownBlock3D",
107
+ "CogVideoXDownBlock3D",
108
+ "CogVideoXDownBlock3D",
109
+ ),
110
+ up_block_types=(
111
+ "CogVideoXUpBlock3D",
112
+ "CogVideoXUpBlock3D",
113
+ "CogVideoXUpBlock3D",
114
+ "CogVideoXUpBlock3D",
115
+ ),
116
+ block_out_channels=(8, 8, 8, 8),
117
+ latent_channels=4,
118
+ layers_per_block=1,
119
+ norm_num_groups=2,
120
+ temporal_compression_ratio=4,
121
+ )
122
+
123
+ torch.manual_seed(0)
124
+ scheduler = DDIMScheduler()
125
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
126
+ text_encoder = T5EncoderModel(config)
127
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
128
+
129
+ components = {
130
+ "transformer": transformer,
131
+ "vae": vae,
132
+ "scheduler": scheduler,
133
+ "text_encoder": text_encoder,
134
+ "tokenizer": tokenizer,
135
+ }
136
+ return components
137
+
138
+ def get_dummy_inputs(self, device, seed=0):
139
+ if str(device).startswith("mps"):
140
+ generator = torch.manual_seed(seed)
141
+ else:
142
+ generator = torch.Generator(device=device).manual_seed(seed)
143
+
144
+ image_height = 16
145
+ image_width = 16
146
+ image = Image.new("RGB", (image_width, image_height))
147
+ id_vit_hidden = [torch.ones([1, 2, 2])] * 1
148
+ id_cond = torch.ones(1, 2)
149
+ inputs = {
150
+ "image": image,
151
+ "prompt": "dance monkey",
152
+ "negative_prompt": "",
153
+ "generator": generator,
154
+ "num_inference_steps": 2,
155
+ "guidance_scale": 6.0,
156
+ "height": image_height,
157
+ "width": image_width,
158
+ "num_frames": 8,
159
+ "max_sequence_length": 16,
160
+ "id_vit_hidden": id_vit_hidden,
161
+ "id_cond": id_cond,
162
+ "output_type": "pt",
163
+ }
164
+ return inputs
165
+
166
+ def test_inference(self):
167
+ device = "cpu"
168
+
169
+ components = self.get_dummy_components()
170
+ pipe = self.pipeline_class(**components)
171
+ pipe.to(device)
172
+ pipe.set_progress_bar_config(disable=None)
173
+
174
+ inputs = self.get_dummy_inputs(device)
175
+ video = pipe(**inputs).frames
176
+ generated_video = video[0]
177
+
178
+ self.assertEqual(generated_video.shape, (8, 3, 16, 16))
179
+ expected_video = torch.randn(8, 3, 16, 16)
180
+ max_diff = np.abs(generated_video - expected_video).max()
181
+ self.assertLessEqual(max_diff, 1e10)
182
+
183
+ def test_callback_inputs(self):
184
+ sig = inspect.signature(self.pipeline_class.__call__)
185
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
186
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
187
+
188
+ if not (has_callback_tensor_inputs and has_callback_step_end):
189
+ return
190
+
191
+ components = self.get_dummy_components()
192
+ pipe = self.pipeline_class(**components)
193
+ pipe = pipe.to(torch_device)
194
+ pipe.set_progress_bar_config(disable=None)
195
+ self.assertTrue(
196
+ hasattr(pipe, "_callback_tensor_inputs"),
197
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
198
+ )
199
+
200
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
201
+ # iterate over callback args
202
+ for tensor_name, tensor_value in callback_kwargs.items():
203
+ # check that we're only passing in allowed tensor inputs
204
+ assert tensor_name in pipe._callback_tensor_inputs
205
+
206
+ return callback_kwargs
207
+
208
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
209
+ for tensor_name in pipe._callback_tensor_inputs:
210
+ assert tensor_name in callback_kwargs
211
+
212
+ # iterate over callback args
213
+ for tensor_name, tensor_value in callback_kwargs.items():
214
+ # check that we're only passing in allowed tensor inputs
215
+ assert tensor_name in pipe._callback_tensor_inputs
216
+
217
+ return callback_kwargs
218
+
219
+ inputs = self.get_dummy_inputs(torch_device)
220
+
221
+ # Test passing in a subset
222
+ inputs["callback_on_step_end"] = callback_inputs_subset
223
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
224
+ output = pipe(**inputs)[0]
225
+
226
+ # Test passing in a everything
227
+ inputs["callback_on_step_end"] = callback_inputs_all
228
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
229
+ output = pipe(**inputs)[0]
230
+
231
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
232
+ is_last = i == (pipe.num_timesteps - 1)
233
+ if is_last:
234
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
235
+ return callback_kwargs
236
+
237
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
238
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
239
+ output = pipe(**inputs)[0]
240
+ assert output.abs().sum() < 1e10
241
+
242
+ def test_inference_batch_single_identical(self):
243
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
244
+
245
+ def test_attention_slicing_forward_pass(
246
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
247
+ ):
248
+ if not self.test_attention_slicing:
249
+ return
250
+
251
+ components = self.get_dummy_components()
252
+ for key in components:
253
+ if "text_encoder" in key and hasattr(components[key], "eval"):
254
+ components[key].eval()
255
+ pipe = self.pipeline_class(**components)
256
+ for component in pipe.components.values():
257
+ if hasattr(component, "set_default_attn_processor"):
258
+ component.set_default_attn_processor()
259
+ pipe.to(torch_device)
260
+ pipe.set_progress_bar_config(disable=None)
261
+
262
+ generator_device = "cpu"
263
+ inputs = self.get_dummy_inputs(generator_device)
264
+ output_without_slicing = pipe(**inputs)[0]
265
+
266
+ pipe.enable_attention_slicing(slice_size=1)
267
+ inputs = self.get_dummy_inputs(generator_device)
268
+ output_with_slicing1 = pipe(**inputs)[0]
269
+
270
+ pipe.enable_attention_slicing(slice_size=2)
271
+ inputs = self.get_dummy_inputs(generator_device)
272
+ output_with_slicing2 = pipe(**inputs)[0]
273
+
274
+ if test_max_difference:
275
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
276
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
277
+ self.assertLess(
278
+ max(max_diff1, max_diff2),
279
+ expected_max_diff,
280
+ "Attention slicing should not affect the inference results",
281
+ )
282
+
283
+ def test_vae_tiling(self, expected_diff_max: float = 0.4):
284
+ generator_device = "cpu"
285
+ components = self.get_dummy_components()
286
+
287
+ # The reason to modify it this way is because ConsisID Transformer limits the generation to resolutions used during initialization.
288
+ # This limitation comes from using learned positional embeddings which cannot be generated on-the-fly like sincos or RoPE embeddings.
289
+ # See the if-statement on "self.use_learned_positional_embeddings" in diffusers/models/embeddings.py
290
+ components["transformer"] = ConsisIDTransformer3DModel.from_config(
291
+ components["transformer"].config,
292
+ sample_height=16,
293
+ sample_width=16,
294
+ )
295
+
296
+ pipe = self.pipeline_class(**components)
297
+ pipe.to("cpu")
298
+ pipe.set_progress_bar_config(disable=None)
299
+
300
+ # Without tiling
301
+ inputs = self.get_dummy_inputs(generator_device)
302
+ inputs["height"] = inputs["width"] = 128
303
+ output_without_tiling = pipe(**inputs)[0]
304
+
305
+ # With tiling
306
+ pipe.vae.enable_tiling(
307
+ tile_sample_min_height=96,
308
+ tile_sample_min_width=96,
309
+ tile_overlap_factor_height=1 / 12,
310
+ tile_overlap_factor_width=1 / 12,
311
+ )
312
+ inputs = self.get_dummy_inputs(generator_device)
313
+ inputs["height"] = inputs["width"] = 128
314
+ output_with_tiling = pipe(**inputs)[0]
315
+
316
+ self.assertLess(
317
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
318
+ expected_diff_max,
319
+ "VAE tiling should not affect the inference results",
320
+ )
321
+
322
+
323
+ @slow
324
+ @require_torch_accelerator
325
+ class ConsisIDPipelineIntegrationTests(unittest.TestCase):
326
+ prompt = "A painting of a squirrel eating a burger."
327
+
328
+ def setUp(self):
329
+ super().setUp()
330
+ gc.collect()
331
+ backend_empty_cache(torch_device)
332
+
333
+ def tearDown(self):
334
+ super().tearDown()
335
+ gc.collect()
336
+ backend_empty_cache(torch_device)
337
+
338
+ def test_consisid(self):
339
+ generator = torch.Generator("cpu").manual_seed(0)
340
+
341
+ pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16)
342
+ pipe.enable_model_cpu_offload()
343
+
344
+ prompt = self.prompt
345
+ image = load_image("https://github.com/PKU-YuanGroup/ConsisID/blob/main/asserts/example_images/2.png?raw=true")
346
+ id_vit_hidden = [torch.ones([1, 577, 1024])] * 5
347
+ id_cond = torch.ones(1, 1280)
348
+
349
+ videos = pipe(
350
+ image=image,
351
+ prompt=prompt,
352
+ height=480,
353
+ width=720,
354
+ num_frames=16,
355
+ id_vit_hidden=id_vit_hidden,
356
+ id_cond=id_cond,
357
+ generator=generator,
358
+ num_inference_steps=1,
359
+ output_type="pt",
360
+ ).frames
361
+
362
+ video = videos[0]
363
+ expected_video = torch.randn(1, 16, 480, 720, 3).numpy()
364
+
365
+ max_diff = numpy_cosine_similarity_distance(video.cpu(), expected_video)
366
+ assert max_diff < 1e-3, f"Max diff is too high. got {video}"
diffusers/tests/pipelines/consistency_models/__init__.py ADDED
File without changes
diffusers/tests/pipelines/consistency_models/test_consistency_models.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import unittest
3
+
4
+ import numpy as np
5
+ import torch
6
+ from torch.backends.cuda import sdp_kernel
7
+
8
+ from diffusers import (
9
+ CMStochasticIterativeScheduler,
10
+ ConsistencyModelPipeline,
11
+ UNet2DModel,
12
+ )
13
+ from diffusers.utils.torch_utils import randn_tensor
14
+
15
+ from ...testing_utils import (
16
+ Expectations,
17
+ backend_empty_cache,
18
+ enable_full_determinism,
19
+ nightly,
20
+ require_torch_2,
21
+ require_torch_accelerator,
22
+ torch_device,
23
+ )
24
+ from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
25
+ from ..test_pipelines_common import PipelineTesterMixin
26
+
27
+
28
+ enable_full_determinism()
29
+
30
+
31
+ class ConsistencyModelPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
32
+ pipeline_class = ConsistencyModelPipeline
33
+ params = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
34
+ batch_params = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
35
+
36
+ # Override required_optional_params to remove num_images_per_prompt
37
+ required_optional_params = frozenset(
38
+ [
39
+ "num_inference_steps",
40
+ "generator",
41
+ "latents",
42
+ "output_type",
43
+ "return_dict",
44
+ "callback",
45
+ "callback_steps",
46
+ ]
47
+ )
48
+
49
+ @property
50
+ def dummy_uncond_unet(self):
51
+ unet = UNet2DModel.from_pretrained(
52
+ "diffusers/consistency-models-test",
53
+ subfolder="test_unet",
54
+ )
55
+ return unet
56
+
57
+ @property
58
+ def dummy_cond_unet(self):
59
+ unet = UNet2DModel.from_pretrained(
60
+ "diffusers/consistency-models-test",
61
+ subfolder="test_unet_class_cond",
62
+ )
63
+ return unet
64
+
65
+ def get_dummy_components(self, class_cond=False):
66
+ if class_cond:
67
+ unet = self.dummy_cond_unet
68
+ else:
69
+ unet = self.dummy_uncond_unet
70
+
71
+ # Default to CM multistep sampler
72
+ scheduler = CMStochasticIterativeScheduler(
73
+ num_train_timesteps=40,
74
+ sigma_min=0.002,
75
+ sigma_max=80.0,
76
+ )
77
+
78
+ components = {
79
+ "unet": unet,
80
+ "scheduler": scheduler,
81
+ }
82
+
83
+ return components
84
+
85
+ def get_dummy_inputs(self, device, seed=0):
86
+ if str(device).startswith("mps"):
87
+ generator = torch.manual_seed(seed)
88
+ else:
89
+ generator = torch.Generator(device=device).manual_seed(seed)
90
+
91
+ inputs = {
92
+ "batch_size": 1,
93
+ "num_inference_steps": None,
94
+ "timesteps": [22, 0],
95
+ "generator": generator,
96
+ "output_type": "np",
97
+ }
98
+
99
+ return inputs
100
+
101
+ def test_consistency_model_pipeline_multistep(self):
102
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
103
+ components = self.get_dummy_components()
104
+ pipe = ConsistencyModelPipeline(**components)
105
+ pipe = pipe.to(device)
106
+ pipe.set_progress_bar_config(disable=None)
107
+
108
+ inputs = self.get_dummy_inputs(device)
109
+ image = pipe(**inputs).images
110
+ assert image.shape == (1, 32, 32, 3)
111
+
112
+ image_slice = image[0, -3:, -3:, -1]
113
+ expected_slice = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004])
114
+
115
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
116
+
117
+ def test_consistency_model_pipeline_multistep_class_cond(self):
118
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
119
+ components = self.get_dummy_components(class_cond=True)
120
+ pipe = ConsistencyModelPipeline(**components)
121
+ pipe = pipe.to(device)
122
+ pipe.set_progress_bar_config(disable=None)
123
+
124
+ inputs = self.get_dummy_inputs(device)
125
+ inputs["class_labels"] = 0
126
+ image = pipe(**inputs).images
127
+ assert image.shape == (1, 32, 32, 3)
128
+
129
+ image_slice = image[0, -3:, -3:, -1]
130
+ expected_slice = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004])
131
+
132
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
133
+
134
+ def test_consistency_model_pipeline_onestep(self):
135
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
136
+ components = self.get_dummy_components()
137
+ pipe = ConsistencyModelPipeline(**components)
138
+ pipe = pipe.to(device)
139
+ pipe.set_progress_bar_config(disable=None)
140
+
141
+ inputs = self.get_dummy_inputs(device)
142
+ inputs["num_inference_steps"] = 1
143
+ inputs["timesteps"] = None
144
+ image = pipe(**inputs).images
145
+ assert image.shape == (1, 32, 32, 3)
146
+
147
+ image_slice = image[0, -3:, -3:, -1]
148
+ expected_slice = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987])
149
+
150
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
151
+
152
+ def test_consistency_model_pipeline_onestep_class_cond(self):
153
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
154
+ components = self.get_dummy_components(class_cond=True)
155
+ pipe = ConsistencyModelPipeline(**components)
156
+ pipe = pipe.to(device)
157
+ pipe.set_progress_bar_config(disable=None)
158
+
159
+ inputs = self.get_dummy_inputs(device)
160
+ inputs["num_inference_steps"] = 1
161
+ inputs["timesteps"] = None
162
+ inputs["class_labels"] = 0
163
+ image = pipe(**inputs).images
164
+ assert image.shape == (1, 32, 32, 3)
165
+
166
+ image_slice = image[0, -3:, -3:, -1]
167
+ expected_slice = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987])
168
+
169
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
170
+
171
+
172
+ @nightly
173
+ @require_torch_accelerator
174
+ class ConsistencyModelPipelineSlowTests(unittest.TestCase):
175
+ def setUp(self):
176
+ super().setUp()
177
+ gc.collect()
178
+ backend_empty_cache(torch_device)
179
+
180
+ def tearDown(self):
181
+ super().tearDown()
182
+ gc.collect()
183
+ backend_empty_cache(torch_device)
184
+
185
+ def get_inputs(self, seed=0, get_fixed_latents=False, device="cpu", dtype=torch.float32, shape=(1, 3, 64, 64)):
186
+ generator = torch.manual_seed(seed)
187
+
188
+ inputs = {
189
+ "num_inference_steps": None,
190
+ "timesteps": [22, 0],
191
+ "class_labels": 0,
192
+ "generator": generator,
193
+ "output_type": "np",
194
+ }
195
+
196
+ if get_fixed_latents:
197
+ latents = self.get_fixed_latents(seed=seed, device=device, dtype=dtype, shape=shape)
198
+ inputs["latents"] = latents
199
+
200
+ return inputs
201
+
202
+ def get_fixed_latents(self, seed=0, device="cpu", dtype=torch.float32, shape=(1, 3, 64, 64)):
203
+ if isinstance(device, str):
204
+ device = torch.device(device)
205
+ generator = torch.Generator(device=device).manual_seed(seed)
206
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
207
+ return latents
208
+
209
+ def test_consistency_model_cd_multistep(self):
210
+ unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
211
+ scheduler = CMStochasticIterativeScheduler(
212
+ num_train_timesteps=40,
213
+ sigma_min=0.002,
214
+ sigma_max=80.0,
215
+ )
216
+ pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
217
+ pipe.to(torch_device=torch_device)
218
+ pipe.set_progress_bar_config(disable=None)
219
+
220
+ inputs = self.get_inputs()
221
+ image = pipe(**inputs).images
222
+ assert image.shape == (1, 64, 64, 3)
223
+
224
+ image_slice = image[0, -3:, -3:, -1]
225
+
226
+ expected_slice = np.array([0.0146, 0.0158, 0.0092, 0.0086, 0.0000, 0.0000, 0.0000, 0.0000, 0.0058])
227
+
228
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
229
+
230
+ def test_consistency_model_cd_onestep(self):
231
+ unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
232
+ scheduler = CMStochasticIterativeScheduler(
233
+ num_train_timesteps=40,
234
+ sigma_min=0.002,
235
+ sigma_max=80.0,
236
+ )
237
+ pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
238
+ pipe.to(torch_device=torch_device)
239
+ pipe.set_progress_bar_config(disable=None)
240
+
241
+ inputs = self.get_inputs()
242
+ inputs["num_inference_steps"] = 1
243
+ inputs["timesteps"] = None
244
+ image = pipe(**inputs).images
245
+ assert image.shape == (1, 64, 64, 3)
246
+
247
+ image_slice = image[0, -3:, -3:, -1]
248
+
249
+ expected_slice = np.array([0.0059, 0.0003, 0.0000, 0.0023, 0.0052, 0.0007, 0.0165, 0.0081, 0.0095])
250
+
251
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
252
+
253
+ @require_torch_2
254
+ def test_consistency_model_cd_multistep_flash_attn(self):
255
+ unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
256
+ scheduler = CMStochasticIterativeScheduler(
257
+ num_train_timesteps=40,
258
+ sigma_min=0.002,
259
+ sigma_max=80.0,
260
+ )
261
+ pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
262
+ pipe.to(torch_device=torch_device, torch_dtype=torch.float16)
263
+ pipe.set_progress_bar_config(disable=None)
264
+
265
+ inputs = self.get_inputs(get_fixed_latents=True, device=torch_device)
266
+ # Ensure usage of flash attention in torch 2.0
267
+ with sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
268
+ image = pipe(**inputs).images
269
+
270
+ assert image.shape == (1, 64, 64, 3)
271
+
272
+ image_slice = image[0, -3:, -3:, -1]
273
+
274
+ expected_slices = Expectations(
275
+ {
276
+ ("xpu", 3): np.array([0.0816, 0.0518, 0.0445, 0.0594, 0.0739, 0.0534, 0.0805, 0.0457, 0.0765]),
277
+ ("cuda", 7): np.array([0.1845, 0.1371, 0.1211, 0.2035, 0.1954, 0.1323, 0.1773, 0.1593, 0.1314]),
278
+ ("cuda", 8): np.array([0.0816, 0.0518, 0.0445, 0.0594, 0.0739, 0.0534, 0.0805, 0.0457, 0.0765]),
279
+ }
280
+ )
281
+ expected_slice = expected_slices.get_expectation()
282
+
283
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
284
+
285
+ @require_torch_2
286
+ def test_consistency_model_cd_onestep_flash_attn(self):
287
+ unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
288
+ scheduler = CMStochasticIterativeScheduler(
289
+ num_train_timesteps=40,
290
+ sigma_min=0.002,
291
+ sigma_max=80.0,
292
+ )
293
+ pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
294
+ pipe.to(torch_device=torch_device, torch_dtype=torch.float16)
295
+ pipe.set_progress_bar_config(disable=None)
296
+
297
+ inputs = self.get_inputs(get_fixed_latents=True, device=torch_device)
298
+ inputs["num_inference_steps"] = 1
299
+ inputs["timesteps"] = None
300
+ # Ensure usage of flash attention in torch 2.0
301
+ with sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
302
+ image = pipe(**inputs).images
303
+ assert image.shape == (1, 64, 64, 3)
304
+
305
+ image_slice = image[0, -3:, -3:, -1]
306
+
307
+ expected_slice = np.array([0.1623, 0.2009, 0.2387, 0.1731, 0.1168, 0.1202, 0.2031, 0.1327, 0.2447])
308
+
309
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
diffusers/tests/pipelines/controlnet_flux/__init__.py ADDED
File without changes
diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 HuggingFace Inc and The InstantX Team.
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 unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from huggingface_hub import hf_hub_download
22
+ from transformers import AutoConfig, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
23
+
24
+ from diffusers import (
25
+ AutoencoderKL,
26
+ FlowMatchEulerDiscreteScheduler,
27
+ FluxControlNetPipeline,
28
+ FluxTransformer2DModel,
29
+ )
30
+ from diffusers.models import FluxControlNetModel
31
+ from diffusers.utils import load_image
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+
34
+ from ...testing_utils import (
35
+ backend_empty_cache,
36
+ enable_full_determinism,
37
+ nightly,
38
+ numpy_cosine_similarity_distance,
39
+ require_big_accelerator,
40
+ torch_device,
41
+ )
42
+ from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin
43
+
44
+
45
+ enable_full_determinism()
46
+
47
+
48
+ class FluxControlNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin, FluxIPAdapterTesterMixin):
49
+ pipeline_class = FluxControlNetPipeline
50
+
51
+ params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
52
+ batch_params = frozenset(["prompt"])
53
+ test_layerwise_casting = True
54
+ test_group_offloading = True
55
+
56
+ def get_dummy_components(self):
57
+ torch.manual_seed(0)
58
+ transformer = FluxTransformer2DModel(
59
+ patch_size=1,
60
+ in_channels=16,
61
+ num_layers=1,
62
+ num_single_layers=1,
63
+ attention_head_dim=16,
64
+ num_attention_heads=2,
65
+ joint_attention_dim=32,
66
+ pooled_projection_dim=32,
67
+ axes_dims_rope=[4, 4, 8],
68
+ )
69
+
70
+ torch.manual_seed(0)
71
+ controlnet = FluxControlNetModel(
72
+ patch_size=1,
73
+ in_channels=16,
74
+ num_layers=1,
75
+ num_single_layers=1,
76
+ attention_head_dim=16,
77
+ num_attention_heads=2,
78
+ joint_attention_dim=32,
79
+ pooled_projection_dim=32,
80
+ axes_dims_rope=[4, 4, 8],
81
+ )
82
+
83
+ clip_text_encoder_config = CLIPTextConfig(
84
+ bos_token_id=0,
85
+ eos_token_id=2,
86
+ hidden_size=32,
87
+ intermediate_size=37,
88
+ layer_norm_eps=1e-05,
89
+ num_attention_heads=4,
90
+ num_hidden_layers=5,
91
+ pad_token_id=1,
92
+ vocab_size=1000,
93
+ hidden_act="gelu",
94
+ projection_dim=32,
95
+ )
96
+ torch.manual_seed(0)
97
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
98
+
99
+ torch.manual_seed(0)
100
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
101
+ text_encoder_2 = T5EncoderModel(config)
102
+
103
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
104
+ tokenizer_2 = T5TokenizerFast.from_pretrained("hf-internal-testing/tiny-random-t5")
105
+
106
+ torch.manual_seed(0)
107
+ vae = AutoencoderKL(
108
+ sample_size=32,
109
+ in_channels=3,
110
+ out_channels=3,
111
+ block_out_channels=(4,),
112
+ layers_per_block=1,
113
+ latent_channels=4,
114
+ norm_num_groups=1,
115
+ use_quant_conv=False,
116
+ use_post_quant_conv=False,
117
+ shift_factor=0.0609,
118
+ scaling_factor=1.5035,
119
+ )
120
+
121
+ scheduler = FlowMatchEulerDiscreteScheduler()
122
+
123
+ return {
124
+ "scheduler": scheduler,
125
+ "text_encoder": text_encoder,
126
+ "text_encoder_2": text_encoder_2,
127
+ "tokenizer": tokenizer,
128
+ "tokenizer_2": tokenizer_2,
129
+ "transformer": transformer,
130
+ "vae": vae,
131
+ "controlnet": controlnet,
132
+ "image_encoder": None,
133
+ "feature_extractor": None,
134
+ }
135
+
136
+ def get_dummy_inputs(self, device, seed=0):
137
+ if str(device).startswith("mps"):
138
+ generator = torch.manual_seed(seed)
139
+ else:
140
+ generator = torch.Generator(device="cpu").manual_seed(seed)
141
+
142
+ control_image = randn_tensor(
143
+ (1, 3, 32, 32),
144
+ generator=generator,
145
+ device=torch.device(device),
146
+ dtype=torch.float16,
147
+ )
148
+
149
+ controlnet_conditioning_scale = 0.5
150
+
151
+ inputs = {
152
+ "prompt": "A painting of a squirrel eating a burger",
153
+ "generator": generator,
154
+ "num_inference_steps": 2,
155
+ "guidance_scale": 3.5,
156
+ "output_type": "np",
157
+ "control_image": control_image,
158
+ "controlnet_conditioning_scale": controlnet_conditioning_scale,
159
+ }
160
+
161
+ return inputs
162
+
163
+ def test_controlnet_flux(self):
164
+ components = self.get_dummy_components()
165
+ flux_pipe = FluxControlNetPipeline(**components)
166
+ flux_pipe = flux_pipe.to(torch_device, dtype=torch.float16)
167
+ flux_pipe.set_progress_bar_config(disable=None)
168
+
169
+ inputs = self.get_dummy_inputs(torch_device)
170
+ output = flux_pipe(**inputs)
171
+ image = output.images
172
+
173
+ image_slice = image[0, -3:, -3:, -1]
174
+
175
+ assert image.shape == (1, 32, 32, 3)
176
+
177
+ expected_slice = np.array(
178
+ [0.47387695, 0.63134766, 0.5605469, 0.61621094, 0.7207031, 0.7089844, 0.70410156, 0.6113281, 0.64160156]
179
+ )
180
+
181
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
182
+ f"Expected: {expected_slice}, got: {image_slice.flatten()}"
183
+ )
184
+
185
+ @unittest.skip("xFormersAttnProcessor does not work with SD3 Joint Attention")
186
+ def test_xformers_attention_forwardGenerator_pass(self):
187
+ pass
188
+
189
+ def test_flux_image_output_shape(self):
190
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
191
+ inputs = self.get_dummy_inputs(torch_device)
192
+
193
+ height_width_pairs = [(32, 32), (72, 56)]
194
+ for height, width in height_width_pairs:
195
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
196
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
197
+
198
+ inputs.update(
199
+ {
200
+ "control_image": randn_tensor(
201
+ (1, 3, height, width),
202
+ device=torch_device,
203
+ dtype=torch.float16,
204
+ )
205
+ }
206
+ )
207
+ image = pipe(**inputs).images[0]
208
+ output_height, output_width, _ = image.shape
209
+ assert (output_height, output_width) == (expected_height, expected_width)
210
+
211
+
212
+ @nightly
213
+ @require_big_accelerator
214
+ class FluxControlNetPipelineSlowTests(unittest.TestCase):
215
+ pipeline_class = FluxControlNetPipeline
216
+
217
+ def setUp(self):
218
+ super().setUp()
219
+ gc.collect()
220
+ backend_empty_cache(torch_device)
221
+
222
+ def tearDown(self):
223
+ super().tearDown()
224
+ gc.collect()
225
+ backend_empty_cache(torch_device)
226
+
227
+ def test_canny(self):
228
+ controlnet = FluxControlNetModel.from_pretrained(
229
+ "InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16
230
+ )
231
+ pipe = FluxControlNetPipeline.from_pretrained(
232
+ "black-forest-labs/FLUX.1-dev",
233
+ text_encoder=None,
234
+ text_encoder_2=None,
235
+ controlnet=controlnet,
236
+ torch_dtype=torch.bfloat16,
237
+ ).to(torch_device)
238
+ pipe.set_progress_bar_config(disable=None)
239
+
240
+ generator = torch.Generator(device="cpu").manual_seed(0)
241
+ control_image = load_image(
242
+ "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
243
+ ).resize((512, 512))
244
+
245
+ prompt_embeds = torch.load(
246
+ hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
247
+ ).to(torch_device)
248
+ pooled_prompt_embeds = torch.load(
249
+ hf_hub_download(
250
+ repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
251
+ )
252
+ ).to(torch_device)
253
+
254
+ output = pipe(
255
+ prompt_embeds=prompt_embeds,
256
+ pooled_prompt_embeds=pooled_prompt_embeds,
257
+ control_image=control_image,
258
+ controlnet_conditioning_scale=0.6,
259
+ num_inference_steps=2,
260
+ guidance_scale=3.5,
261
+ max_sequence_length=256,
262
+ output_type="np",
263
+ height=512,
264
+ width=512,
265
+ generator=generator,
266
+ )
267
+
268
+ image = output.images[0]
269
+
270
+ assert image.shape == (512, 512, 3)
271
+
272
+ original_image = image[-3:, -3:, -1].flatten()
273
+
274
+ expected_image = np.array([0.2734, 0.2852, 0.2852, 0.2734, 0.2754, 0.2891, 0.2617, 0.2637, 0.2773])
275
+
276
+ assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux_img2img.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
6
+
7
+ from diffusers import (
8
+ AutoencoderKL,
9
+ FlowMatchEulerDiscreteScheduler,
10
+ FluxControlNetImg2ImgPipeline,
11
+ FluxControlNetModel,
12
+ FluxTransformer2DModel,
13
+ )
14
+ from diffusers.utils.torch_utils import randn_tensor
15
+
16
+ from ...testing_utils import torch_device
17
+ from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
18
+
19
+
20
+ class FluxControlNetImg2ImgPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
21
+ pipeline_class = FluxControlNetImg2ImgPipeline
22
+ params = frozenset(
23
+ [
24
+ "prompt",
25
+ "image",
26
+ "control_image",
27
+ "height",
28
+ "width",
29
+ "strength",
30
+ "guidance_scale",
31
+ "controlnet_conditioning_scale",
32
+ "prompt_embeds",
33
+ "pooled_prompt_embeds",
34
+ ]
35
+ )
36
+ batch_params = frozenset(["prompt", "image", "control_image"])
37
+
38
+ test_xformers_attention = False
39
+
40
+ def get_dummy_components(self):
41
+ torch.manual_seed(0)
42
+ transformer = FluxTransformer2DModel(
43
+ patch_size=1,
44
+ in_channels=4,
45
+ num_layers=1,
46
+ num_single_layers=1,
47
+ attention_head_dim=16,
48
+ num_attention_heads=2,
49
+ joint_attention_dim=32,
50
+ pooled_projection_dim=32,
51
+ axes_dims_rope=[4, 4, 8],
52
+ )
53
+ clip_text_encoder_config = CLIPTextConfig(
54
+ bos_token_id=0,
55
+ eos_token_id=2,
56
+ hidden_size=32,
57
+ intermediate_size=37,
58
+ layer_norm_eps=1e-05,
59
+ num_attention_heads=4,
60
+ num_hidden_layers=5,
61
+ pad_token_id=1,
62
+ vocab_size=1000,
63
+ hidden_act="gelu",
64
+ projection_dim=32,
65
+ )
66
+
67
+ torch.manual_seed(0)
68
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
69
+
70
+ torch.manual_seed(0)
71
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
72
+ text_encoder_2 = T5EncoderModel(config)
73
+
74
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
75
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
76
+
77
+ torch.manual_seed(0)
78
+ vae = AutoencoderKL(
79
+ sample_size=32,
80
+ in_channels=3,
81
+ out_channels=3,
82
+ block_out_channels=(4,),
83
+ layers_per_block=1,
84
+ latent_channels=1,
85
+ norm_num_groups=1,
86
+ use_quant_conv=False,
87
+ use_post_quant_conv=False,
88
+ shift_factor=0.0609,
89
+ scaling_factor=1.5035,
90
+ )
91
+
92
+ torch.manual_seed(0)
93
+ controlnet = FluxControlNetModel(
94
+ in_channels=4,
95
+ num_layers=1,
96
+ num_single_layers=1,
97
+ attention_head_dim=16,
98
+ num_attention_heads=2,
99
+ joint_attention_dim=32,
100
+ pooled_projection_dim=32,
101
+ axes_dims_rope=[4, 4, 8],
102
+ )
103
+
104
+ scheduler = FlowMatchEulerDiscreteScheduler()
105
+
106
+ return {
107
+ "scheduler": scheduler,
108
+ "text_encoder": text_encoder,
109
+ "text_encoder_2": text_encoder_2,
110
+ "tokenizer": tokenizer,
111
+ "tokenizer_2": tokenizer_2,
112
+ "transformer": transformer,
113
+ "vae": vae,
114
+ "controlnet": controlnet,
115
+ }
116
+
117
+ def get_dummy_inputs(self, device, seed=0):
118
+ if str(device).startswith("mps"):
119
+ generator = torch.manual_seed(seed)
120
+ else:
121
+ generator = torch.Generator(device="cpu").manual_seed(seed)
122
+
123
+ image = torch.randn(1, 3, 32, 32).to(device)
124
+ control_image = torch.randn(1, 3, 32, 32).to(device)
125
+
126
+ inputs = {
127
+ "prompt": "A painting of a squirrel eating a burger",
128
+ "image": image,
129
+ "control_image": control_image,
130
+ "generator": generator,
131
+ "num_inference_steps": 2,
132
+ "guidance_scale": 5.0,
133
+ "controlnet_conditioning_scale": 1.0,
134
+ "strength": 0.8,
135
+ "height": 32,
136
+ "width": 32,
137
+ "max_sequence_length": 48,
138
+ "output_type": "np",
139
+ }
140
+ return inputs
141
+
142
+ def test_flux_controlnet_different_prompts(self):
143
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
144
+
145
+ inputs = self.get_dummy_inputs(torch_device)
146
+ output_same_prompt = pipe(**inputs).images[0]
147
+
148
+ inputs = self.get_dummy_inputs(torch_device)
149
+ inputs["prompt_2"] = "a different prompt"
150
+ output_different_prompts = pipe(**inputs).images[0]
151
+
152
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
153
+
154
+ assert max_diff > 1e-6
155
+
156
+ def test_fused_qkv_projections(self):
157
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
158
+ components = self.get_dummy_components()
159
+ pipe = self.pipeline_class(**components)
160
+ pipe = pipe.to(device)
161
+ pipe.set_progress_bar_config(disable=None)
162
+
163
+ inputs = self.get_dummy_inputs(device)
164
+ image = pipe(**inputs).images
165
+ original_image_slice = image[0, -3:, -3:, -1]
166
+
167
+ pipe.transformer.fuse_qkv_projections()
168
+ self.assertTrue(
169
+ check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
170
+ ("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
171
+ )
172
+
173
+ inputs = self.get_dummy_inputs(device)
174
+ image = pipe(**inputs).images
175
+ image_slice_fused = image[0, -3:, -3:, -1]
176
+
177
+ pipe.transformer.unfuse_qkv_projections()
178
+ inputs = self.get_dummy_inputs(device)
179
+ image = pipe(**inputs).images
180
+ image_slice_disabled = image[0, -3:, -3:, -1]
181
+
182
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
183
+ "Fusion of QKV projections shouldn't affect the outputs."
184
+ )
185
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
186
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
187
+ )
188
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
189
+ "Original outputs should match when fused QKV projections are disabled."
190
+ )
191
+
192
+ def test_flux_image_output_shape(self):
193
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
194
+ inputs = self.get_dummy_inputs(torch_device)
195
+
196
+ height_width_pairs = [(32, 32), (72, 56)]
197
+ for height, width in height_width_pairs:
198
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
199
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
200
+ inputs.update(
201
+ {
202
+ "control_image": randn_tensor(
203
+ (1, 3, height, width),
204
+ device=torch_device,
205
+ dtype=torch.float16,
206
+ ),
207
+ "image": randn_tensor(
208
+ (1, 3, height, width),
209
+ device=torch_device,
210
+ dtype=torch.float16,
211
+ ),
212
+ "height": height,
213
+ "width": width,
214
+ }
215
+ )
216
+ image = pipe(**inputs).images[0]
217
+ output_height, output_width, _ = image.shape
218
+ assert (output_height, output_width) == (expected_height, expected_width)
diffusers/tests/pipelines/controlnet_flux/test_controlnet_flux_inpaint.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import unittest
3
+
4
+ import numpy as np
5
+ import torch
6
+ from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
7
+
8
+ from diffusers import (
9
+ AutoencoderKL,
10
+ FlowMatchEulerDiscreteScheduler,
11
+ FluxControlNetInpaintPipeline,
12
+ FluxControlNetModel,
13
+ FluxTransformer2DModel,
14
+ )
15
+ from diffusers.utils.torch_utils import randn_tensor
16
+
17
+ from ...testing_utils import enable_full_determinism, floats_tensor, torch_device
18
+ from ..test_pipelines_common import PipelineTesterMixin
19
+
20
+
21
+ enable_full_determinism()
22
+
23
+
24
+ class FluxControlNetInpaintPipelineTests(unittest.TestCase, PipelineTesterMixin):
25
+ pipeline_class = FluxControlNetInpaintPipeline
26
+ params = frozenset(
27
+ [
28
+ "prompt",
29
+ "height",
30
+ "width",
31
+ "guidance_scale",
32
+ "prompt_embeds",
33
+ "pooled_prompt_embeds",
34
+ "image",
35
+ "mask_image",
36
+ "control_image",
37
+ "strength",
38
+ "num_inference_steps",
39
+ "controlnet_conditioning_scale",
40
+ ]
41
+ )
42
+ batch_params = frozenset(["prompt", "image", "mask_image", "control_image"])
43
+ test_xformers_attention = False
44
+
45
+ def get_dummy_components(self):
46
+ torch.manual_seed(0)
47
+ transformer = FluxTransformer2DModel(
48
+ patch_size=1,
49
+ in_channels=8,
50
+ num_layers=1,
51
+ num_single_layers=1,
52
+ attention_head_dim=16,
53
+ num_attention_heads=2,
54
+ joint_attention_dim=32,
55
+ pooled_projection_dim=32,
56
+ axes_dims_rope=[4, 4, 8],
57
+ )
58
+ clip_text_encoder_config = CLIPTextConfig(
59
+ bos_token_id=0,
60
+ eos_token_id=2,
61
+ hidden_size=32,
62
+ intermediate_size=37,
63
+ layer_norm_eps=1e-05,
64
+ num_attention_heads=4,
65
+ num_hidden_layers=5,
66
+ pad_token_id=1,
67
+ vocab_size=1000,
68
+ hidden_act="gelu",
69
+ projection_dim=32,
70
+ )
71
+
72
+ torch.manual_seed(0)
73
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
74
+
75
+ torch.manual_seed(0)
76
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
77
+ text_encoder_2 = T5EncoderModel(config)
78
+
79
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
80
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
81
+
82
+ torch.manual_seed(0)
83
+ vae = AutoencoderKL(
84
+ sample_size=32,
85
+ in_channels=3,
86
+ out_channels=3,
87
+ block_out_channels=(4,),
88
+ layers_per_block=1,
89
+ latent_channels=2,
90
+ norm_num_groups=1,
91
+ use_quant_conv=False,
92
+ use_post_quant_conv=False,
93
+ shift_factor=0.0609,
94
+ scaling_factor=1.5035,
95
+ )
96
+
97
+ torch.manual_seed(0)
98
+ controlnet = FluxControlNetModel(
99
+ patch_size=1,
100
+ in_channels=8,
101
+ num_layers=1,
102
+ num_single_layers=1,
103
+ attention_head_dim=16,
104
+ num_attention_heads=2,
105
+ joint_attention_dim=32,
106
+ pooled_projection_dim=32,
107
+ axes_dims_rope=[4, 4, 8],
108
+ )
109
+
110
+ scheduler = FlowMatchEulerDiscreteScheduler()
111
+
112
+ return {
113
+ "scheduler": scheduler,
114
+ "text_encoder": text_encoder,
115
+ "text_encoder_2": text_encoder_2,
116
+ "tokenizer": tokenizer,
117
+ "tokenizer_2": tokenizer_2,
118
+ "transformer": transformer,
119
+ "vae": vae,
120
+ "controlnet": controlnet,
121
+ }
122
+
123
+ def get_dummy_inputs(self, device, seed=0):
124
+ if str(device).startswith("mps"):
125
+ generator = torch.manual_seed(seed)
126
+ else:
127
+ generator = torch.Generator(device=device).manual_seed(seed)
128
+
129
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
130
+ mask_image = torch.ones((1, 1, 32, 32)).to(device)
131
+ control_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
132
+
133
+ inputs = {
134
+ "prompt": "A painting of a squirrel eating a burger",
135
+ "image": image,
136
+ "mask_image": mask_image,
137
+ "control_image": control_image,
138
+ "generator": generator,
139
+ "num_inference_steps": 2,
140
+ "guidance_scale": 5.0,
141
+ "height": 32,
142
+ "width": 32,
143
+ "max_sequence_length": 48,
144
+ "strength": 0.8,
145
+ "output_type": "np",
146
+ }
147
+ return inputs
148
+
149
+ def test_flux_controlnet_inpaint_with_num_images_per_prompt(self):
150
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
151
+ components = self.get_dummy_components()
152
+ pipe = self.pipeline_class(**components)
153
+ pipe = pipe.to(device)
154
+ pipe.set_progress_bar_config(disable=None)
155
+
156
+ inputs = self.get_dummy_inputs(device)
157
+ inputs["num_images_per_prompt"] = 2
158
+ output = pipe(**inputs)
159
+ images = output.images
160
+
161
+ assert images.shape == (2, 32, 32, 3)
162
+
163
+ def test_flux_controlnet_inpaint_with_controlnet_conditioning_scale(self):
164
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
165
+ components = self.get_dummy_components()
166
+ pipe = self.pipeline_class(**components)
167
+ pipe = pipe.to(device)
168
+ pipe.set_progress_bar_config(disable=None)
169
+
170
+ inputs = self.get_dummy_inputs(device)
171
+ output_default = pipe(**inputs)
172
+ image_default = output_default.images
173
+
174
+ inputs["controlnet_conditioning_scale"] = 0.5
175
+ output_scaled = pipe(**inputs)
176
+ image_scaled = output_scaled.images
177
+
178
+ # Ensure that changing the controlnet_conditioning_scale produces a different output
179
+ assert not np.allclose(image_default, image_scaled, atol=0.01)
180
+
181
+ def test_attention_slicing_forward_pass(self):
182
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
183
+
184
+ def test_inference_batch_single_identical(self):
185
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
186
+
187
+ def test_flux_image_output_shape(self):
188
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
189
+ inputs = self.get_dummy_inputs(torch_device)
190
+
191
+ height_width_pairs = [(32, 32), (72, 56)]
192
+ for height, width in height_width_pairs:
193
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
194
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
195
+
196
+ inputs.update(
197
+ {
198
+ "control_image": randn_tensor(
199
+ (1, 3, height, width),
200
+ device=torch_device,
201
+ dtype=torch.float16,
202
+ ),
203
+ "image": randn_tensor(
204
+ (1, 3, height, width),
205
+ device=torch_device,
206
+ dtype=torch.float16,
207
+ ),
208
+ "mask_image": torch.ones((1, 1, height, width)).to(torch_device),
209
+ "height": height,
210
+ "width": width,
211
+ }
212
+ )
213
+ image = pipe(**inputs).images[0]
214
+ output_height, output_width, _ = image.shape
215
+ assert (output_height, output_width) == (expected_height, expected_width)
diffusers/tests/pipelines/cosmos/test_cosmos.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
24
+
25
+ from diffusers import AutoencoderKLCosmos, CosmosTextToWorldPipeline, CosmosTransformer3DModel, EDMEulerScheduler
26
+
27
+ from ...testing_utils import enable_full_determinism, torch_device
28
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
29
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
30
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
31
+
32
+
33
+ enable_full_determinism()
34
+
35
+
36
+ class CosmosTextToWorldPipelineWrapper(CosmosTextToWorldPipeline):
37
+ @staticmethod
38
+ def from_pretrained(*args, **kwargs):
39
+ kwargs["safety_checker"] = DummyCosmosSafetyChecker()
40
+ return CosmosTextToWorldPipeline.from_pretrained(*args, **kwargs)
41
+
42
+
43
+ class CosmosTextToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
44
+ pipeline_class = CosmosTextToWorldPipelineWrapper
45
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
46
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
47
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
48
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
49
+ required_optional_params = frozenset(
50
+ [
51
+ "num_inference_steps",
52
+ "generator",
53
+ "latents",
54
+ "return_dict",
55
+ "callback_on_step_end",
56
+ "callback_on_step_end_tensor_inputs",
57
+ ]
58
+ )
59
+ supports_dduf = False
60
+ test_xformers_attention = False
61
+ test_layerwise_casting = True
62
+ test_group_offloading = True
63
+
64
+ def get_dummy_components(self):
65
+ torch.manual_seed(0)
66
+ transformer = CosmosTransformer3DModel(
67
+ in_channels=4,
68
+ out_channels=4,
69
+ num_attention_heads=2,
70
+ attention_head_dim=16,
71
+ num_layers=2,
72
+ mlp_ratio=2,
73
+ text_embed_dim=32,
74
+ adaln_lora_dim=4,
75
+ max_size=(4, 32, 32),
76
+ patch_size=(1, 2, 2),
77
+ rope_scale=(2.0, 1.0, 1.0),
78
+ concat_padding_mask=True,
79
+ extra_pos_embed_type="learnable",
80
+ )
81
+
82
+ torch.manual_seed(0)
83
+ vae = AutoencoderKLCosmos(
84
+ in_channels=3,
85
+ out_channels=3,
86
+ latent_channels=4,
87
+ encoder_block_out_channels=(8, 8, 8, 8),
88
+ decode_block_out_channels=(8, 8, 8, 8),
89
+ attention_resolutions=(8,),
90
+ resolution=64,
91
+ num_layers=2,
92
+ patch_size=4,
93
+ patch_type="haar",
94
+ scaling_factor=1.0,
95
+ spatial_compression_ratio=4,
96
+ temporal_compression_ratio=4,
97
+ )
98
+
99
+ torch.manual_seed(0)
100
+ scheduler = EDMEulerScheduler(
101
+ sigma_min=0.002,
102
+ sigma_max=80,
103
+ sigma_data=0.5,
104
+ sigma_schedule="karras",
105
+ num_train_timesteps=1000,
106
+ prediction_type="epsilon",
107
+ rho=7.0,
108
+ final_sigmas_type="sigma_min",
109
+ )
110
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
111
+ text_encoder = T5EncoderModel(config)
112
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
113
+
114
+ components = {
115
+ "transformer": transformer,
116
+ "vae": vae,
117
+ "scheduler": scheduler,
118
+ "text_encoder": text_encoder,
119
+ "tokenizer": tokenizer,
120
+ # We cannot run the Cosmos Guardrail for fast tests due to the large model size
121
+ "safety_checker": DummyCosmosSafetyChecker(),
122
+ }
123
+ return components
124
+
125
+ def get_dummy_inputs(self, device, seed=0):
126
+ if str(device).startswith("mps"):
127
+ generator = torch.manual_seed(seed)
128
+ else:
129
+ generator = torch.Generator(device=device).manual_seed(seed)
130
+
131
+ inputs = {
132
+ "prompt": "dance monkey",
133
+ "negative_prompt": "bad quality",
134
+ "generator": generator,
135
+ "num_inference_steps": 2,
136
+ "guidance_scale": 3.0,
137
+ "height": 32,
138
+ "width": 32,
139
+ "num_frames": 9,
140
+ "max_sequence_length": 16,
141
+ "output_type": "pt",
142
+ }
143
+
144
+ return inputs
145
+
146
+ def test_inference(self):
147
+ device = "cpu"
148
+
149
+ components = self.get_dummy_components()
150
+ pipe = self.pipeline_class(**components)
151
+ pipe.to(device)
152
+ pipe.set_progress_bar_config(disable=None)
153
+
154
+ inputs = self.get_dummy_inputs(device)
155
+ video = pipe(**inputs).frames
156
+ generated_video = video[0]
157
+ self.assertEqual(generated_video.shape, (9, 3, 32, 32))
158
+
159
+ # fmt: off
160
+ expected_slice = torch.tensor([0.0, 0.9686, 0.8549, 0.8078, 0.0, 0.8431, 1.0, 0.4863, 0.7098, 0.1098, 0.8157, 0.4235, 0.6353, 0.2549, 0.5137, 0.5333])
161
+ # fmt: on
162
+
163
+ generated_slice = generated_video.flatten()
164
+ generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
165
+ self.assertTrue(torch.allclose(generated_slice, expected_slice, atol=1e-3))
166
+
167
+ def test_callback_inputs(self):
168
+ sig = inspect.signature(self.pipeline_class.__call__)
169
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
170
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
171
+
172
+ if not (has_callback_tensor_inputs and has_callback_step_end):
173
+ return
174
+
175
+ components = self.get_dummy_components()
176
+ pipe = self.pipeline_class(**components)
177
+ pipe = pipe.to(torch_device)
178
+ pipe.set_progress_bar_config(disable=None)
179
+ self.assertTrue(
180
+ hasattr(pipe, "_callback_tensor_inputs"),
181
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
182
+ )
183
+
184
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
185
+ # iterate over callback args
186
+ for tensor_name, tensor_value in callback_kwargs.items():
187
+ # check that we're only passing in allowed tensor inputs
188
+ assert tensor_name in pipe._callback_tensor_inputs
189
+
190
+ return callback_kwargs
191
+
192
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
193
+ for tensor_name in pipe._callback_tensor_inputs:
194
+ assert tensor_name in callback_kwargs
195
+
196
+ # iterate over callback args
197
+ for tensor_name, tensor_value in callback_kwargs.items():
198
+ # check that we're only passing in allowed tensor inputs
199
+ assert tensor_name in pipe._callback_tensor_inputs
200
+
201
+ return callback_kwargs
202
+
203
+ inputs = self.get_dummy_inputs(torch_device)
204
+
205
+ # Test passing in a subset
206
+ inputs["callback_on_step_end"] = callback_inputs_subset
207
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
208
+ output = pipe(**inputs)[0]
209
+
210
+ # Test passing in a everything
211
+ inputs["callback_on_step_end"] = callback_inputs_all
212
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
213
+ output = pipe(**inputs)[0]
214
+
215
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
216
+ is_last = i == (pipe.num_timesteps - 1)
217
+ if is_last:
218
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
219
+ return callback_kwargs
220
+
221
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
222
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
223
+ output = pipe(**inputs)[0]
224
+ assert output.abs().sum() < 1e10
225
+
226
+ def test_inference_batch_single_identical(self):
227
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
228
+
229
+ def test_attention_slicing_forward_pass(
230
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
231
+ ):
232
+ if not self.test_attention_slicing:
233
+ return
234
+
235
+ components = self.get_dummy_components()
236
+ for key in components:
237
+ if "text_encoder" in key and hasattr(components[key], "eval"):
238
+ components[key].eval()
239
+ pipe = self.pipeline_class(**components)
240
+ for component in pipe.components.values():
241
+ if hasattr(component, "set_default_attn_processor"):
242
+ component.set_default_attn_processor()
243
+ pipe.to(torch_device)
244
+ pipe.set_progress_bar_config(disable=None)
245
+
246
+ generator_device = "cpu"
247
+ inputs = self.get_dummy_inputs(generator_device)
248
+ output_without_slicing = pipe(**inputs)[0]
249
+
250
+ pipe.enable_attention_slicing(slice_size=1)
251
+ inputs = self.get_dummy_inputs(generator_device)
252
+ output_with_slicing1 = pipe(**inputs)[0]
253
+
254
+ pipe.enable_attention_slicing(slice_size=2)
255
+ inputs = self.get_dummy_inputs(generator_device)
256
+ output_with_slicing2 = pipe(**inputs)[0]
257
+
258
+ if test_max_difference:
259
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
260
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
261
+ self.assertLess(
262
+ max(max_diff1, max_diff2),
263
+ expected_max_diff,
264
+ "Attention slicing should not affect the inference results",
265
+ )
266
+
267
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
268
+ generator_device = "cpu"
269
+ components = self.get_dummy_components()
270
+
271
+ pipe = self.pipeline_class(**components)
272
+ pipe.to("cpu")
273
+ pipe.set_progress_bar_config(disable=None)
274
+
275
+ # Without tiling
276
+ inputs = self.get_dummy_inputs(generator_device)
277
+ inputs["height"] = inputs["width"] = 128
278
+ output_without_tiling = pipe(**inputs)[0]
279
+
280
+ # With tiling
281
+ pipe.vae.enable_tiling(
282
+ tile_sample_min_height=96,
283
+ tile_sample_min_width=96,
284
+ tile_sample_stride_height=64,
285
+ tile_sample_stride_width=64,
286
+ )
287
+ inputs = self.get_dummy_inputs(generator_device)
288
+ inputs["height"] = inputs["width"] = 128
289
+ output_with_tiling = pipe(**inputs)[0]
290
+
291
+ self.assertLess(
292
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
293
+ expected_diff_max,
294
+ "VAE tiling should not affect the inference results",
295
+ )
296
+
297
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
298
+ self.pipeline_class._optional_components.remove("safety_checker")
299
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
300
+ self.pipeline_class._optional_components.append("safety_checker")
301
+
302
+ def test_serialization_with_variants(self):
303
+ components = self.get_dummy_components()
304
+ pipe = self.pipeline_class(**components)
305
+ model_components = [
306
+ component_name
307
+ for component_name, component in pipe.components.items()
308
+ if isinstance(component, torch.nn.Module)
309
+ ]
310
+ model_components.remove("safety_checker")
311
+ variant = "fp16"
312
+
313
+ with tempfile.TemporaryDirectory() as tmpdir:
314
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
315
+
316
+ with open(f"{tmpdir}/model_index.json", "r") as f:
317
+ config = json.load(f)
318
+
319
+ for subfolder in os.listdir(tmpdir):
320
+ if not os.path.isfile(subfolder) and subfolder in model_components:
321
+ folder_path = os.path.join(tmpdir, subfolder)
322
+ is_folder = os.path.isdir(folder_path) and subfolder in config
323
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
324
+
325
+ def test_torch_dtype_dict(self):
326
+ components = self.get_dummy_components()
327
+ if not components:
328
+ self.skipTest("No dummy components defined.")
329
+
330
+ pipe = self.pipeline_class(**components)
331
+
332
+ specified_key = next(iter(components.keys()))
333
+
334
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
335
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
336
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
337
+ loaded_pipe = self.pipeline_class.from_pretrained(
338
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
339
+ )
340
+
341
+ for name, component in loaded_pipe.components.items():
342
+ if name == "safety_checker":
343
+ continue
344
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
345
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
346
+ self.assertEqual(
347
+ component.dtype,
348
+ expected_dtype,
349
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
350
+ )
351
+
352
+ @unittest.skip(
353
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
354
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
355
+ "too large and slow to run on CI."
356
+ )
357
+ def test_encode_prompt_works_in_isolation(self):
358
+ pass
diffusers/tests/pipelines/cosmos/test_cosmos2_5_predict.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer
24
+
25
+ from diffusers import (
26
+ AutoencoderKLWan,
27
+ Cosmos2_5_PredictBasePipeline,
28
+ CosmosTransformer3DModel,
29
+ UniPCMultistepScheduler,
30
+ )
31
+
32
+ from ...testing_utils import enable_full_determinism, torch_device
33
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
34
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
35
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
36
+
37
+
38
+ enable_full_determinism()
39
+
40
+
41
+ class Cosmos2_5_PredictBaseWrapper(Cosmos2_5_PredictBasePipeline):
42
+ @staticmethod
43
+ def from_pretrained(*args, **kwargs):
44
+ if "safety_checker" not in kwargs or kwargs["safety_checker"] is None:
45
+ safety_checker = DummyCosmosSafetyChecker()
46
+ device_map = kwargs.get("device_map", "cpu")
47
+ torch_dtype = kwargs.get("torch_dtype")
48
+ if device_map is not None or torch_dtype is not None:
49
+ safety_checker = safety_checker.to(device_map, dtype=torch_dtype)
50
+ kwargs["safety_checker"] = safety_checker
51
+ return Cosmos2_5_PredictBasePipeline.from_pretrained(*args, **kwargs)
52
+
53
+
54
+ class Cosmos2_5_PredictPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
55
+ pipeline_class = Cosmos2_5_PredictBaseWrapper
56
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
57
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
58
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
59
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
60
+ required_optional_params = frozenset(
61
+ [
62
+ "num_inference_steps",
63
+ "generator",
64
+ "latents",
65
+ "return_dict",
66
+ "callback_on_step_end",
67
+ "callback_on_step_end_tensor_inputs",
68
+ ]
69
+ )
70
+ supports_dduf = False
71
+ test_xformers_attention = False
72
+ test_layerwise_casting = True
73
+ test_group_offloading = True
74
+
75
+ def get_dummy_components(self):
76
+ torch.manual_seed(0)
77
+ transformer = CosmosTransformer3DModel(
78
+ in_channels=16 + 1,
79
+ out_channels=16,
80
+ num_attention_heads=2,
81
+ attention_head_dim=16,
82
+ num_layers=2,
83
+ mlp_ratio=2,
84
+ text_embed_dim=32,
85
+ adaln_lora_dim=4,
86
+ max_size=(4, 32, 32),
87
+ patch_size=(1, 2, 2),
88
+ rope_scale=(2.0, 1.0, 1.0),
89
+ concat_padding_mask=True,
90
+ extra_pos_embed_type="learnable",
91
+ )
92
+
93
+ torch.manual_seed(0)
94
+ vae = AutoencoderKLWan(
95
+ base_dim=3,
96
+ z_dim=16,
97
+ dim_mult=[1, 1, 1, 1],
98
+ num_res_blocks=1,
99
+ temperal_downsample=[False, True, True],
100
+ )
101
+
102
+ torch.manual_seed(0)
103
+ scheduler = UniPCMultistepScheduler()
104
+
105
+ torch.manual_seed(0)
106
+ config = Qwen2_5_VLConfig(
107
+ text_config={
108
+ "hidden_size": 16,
109
+ "intermediate_size": 16,
110
+ "num_hidden_layers": 2,
111
+ "num_attention_heads": 2,
112
+ "num_key_value_heads": 2,
113
+ "rope_scaling": {
114
+ "mrope_section": [1, 1, 2],
115
+ "rope_type": "default",
116
+ "type": "default",
117
+ },
118
+ "rope_theta": 1000000.0,
119
+ },
120
+ vision_config={
121
+ "depth": 2,
122
+ "hidden_size": 16,
123
+ "intermediate_size": 16,
124
+ "num_heads": 2,
125
+ "out_hidden_size": 16,
126
+ },
127
+ hidden_size=16,
128
+ vocab_size=152064,
129
+ vision_end_token_id=151653,
130
+ vision_start_token_id=151652,
131
+ vision_token_id=151654,
132
+ )
133
+ text_encoder = Qwen2_5_VLForConditionalGeneration(config)
134
+ tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
135
+
136
+ components = {
137
+ "transformer": transformer,
138
+ "vae": vae,
139
+ "scheduler": scheduler,
140
+ "text_encoder": text_encoder,
141
+ "tokenizer": tokenizer,
142
+ "safety_checker": DummyCosmosSafetyChecker(),
143
+ }
144
+ return components
145
+
146
+ def get_dummy_inputs(self, device, seed=0):
147
+ if str(device).startswith("mps"):
148
+ generator = torch.manual_seed(seed)
149
+ else:
150
+ generator = torch.Generator(device=device).manual_seed(seed)
151
+
152
+ inputs = {
153
+ "prompt": "dance monkey",
154
+ "negative_prompt": "bad quality",
155
+ "generator": generator,
156
+ "num_inference_steps": 2,
157
+ "guidance_scale": 3.0,
158
+ "height": 32,
159
+ "width": 32,
160
+ "num_frames": 3,
161
+ "max_sequence_length": 16,
162
+ "output_type": "pt",
163
+ }
164
+
165
+ return inputs
166
+
167
+ def test_components_function(self):
168
+ init_components = self.get_dummy_components()
169
+ init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
170
+ pipe = self.pipeline_class(**init_components)
171
+ self.assertTrue(hasattr(pipe, "components"))
172
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
173
+
174
+ def test_inference(self):
175
+ device = "cpu"
176
+
177
+ components = self.get_dummy_components()
178
+ pipe = self.pipeline_class(**components)
179
+ pipe.to(device)
180
+ pipe.set_progress_bar_config(disable=None)
181
+
182
+ inputs = self.get_dummy_inputs(device)
183
+ video = pipe(**inputs).frames
184
+ generated_video = video[0]
185
+ self.assertEqual(generated_video.shape, (3, 3, 32, 32))
186
+ self.assertTrue(torch.isfinite(generated_video).all())
187
+
188
+ def test_callback_inputs(self):
189
+ sig = inspect.signature(self.pipeline_class.__call__)
190
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
191
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
192
+
193
+ if not (has_callback_tensor_inputs and has_callback_step_end):
194
+ return
195
+
196
+ components = self.get_dummy_components()
197
+ pipe = self.pipeline_class(**components)
198
+ pipe = pipe.to(torch_device)
199
+ pipe.set_progress_bar_config(disable=None)
200
+ self.assertTrue(
201
+ hasattr(pipe, "_callback_tensor_inputs"),
202
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
203
+ )
204
+
205
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
206
+ for tensor_name in callback_kwargs.keys():
207
+ assert tensor_name in pipe._callback_tensor_inputs
208
+ return callback_kwargs
209
+
210
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
211
+ for tensor_name in pipe._callback_tensor_inputs:
212
+ assert tensor_name in callback_kwargs
213
+ for tensor_name in callback_kwargs.keys():
214
+ assert tensor_name in pipe._callback_tensor_inputs
215
+ return callback_kwargs
216
+
217
+ inputs = self.get_dummy_inputs(torch_device)
218
+
219
+ inputs["callback_on_step_end"] = callback_inputs_subset
220
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
221
+ _ = pipe(**inputs)[0]
222
+
223
+ inputs["callback_on_step_end"] = callback_inputs_all
224
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
225
+ _ = pipe(**inputs)[0]
226
+
227
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
228
+ is_last = i == (pipe.num_timesteps - 1)
229
+ if is_last:
230
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
231
+ return callback_kwargs
232
+
233
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
234
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
235
+ output = pipe(**inputs)[0]
236
+ assert output.abs().sum() < 1e10
237
+
238
+ def test_inference_batch_single_identical(self):
239
+ self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=1e-2)
240
+
241
+ def test_attention_slicing_forward_pass(
242
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
243
+ ):
244
+ if not getattr(self, "test_attention_slicing", True):
245
+ return
246
+
247
+ components = self.get_dummy_components()
248
+ pipe = self.pipeline_class(**components)
249
+ for component in pipe.components.values():
250
+ if hasattr(component, "set_default_attn_processor"):
251
+ component.set_default_attn_processor()
252
+ pipe.to(torch_device)
253
+ pipe.set_progress_bar_config(disable=None)
254
+
255
+ generator_device = "cpu"
256
+ inputs = self.get_dummy_inputs(generator_device)
257
+ output_without_slicing = pipe(**inputs)[0]
258
+
259
+ pipe.enable_attention_slicing(slice_size=1)
260
+ inputs = self.get_dummy_inputs(generator_device)
261
+ output_with_slicing1 = pipe(**inputs)[0]
262
+
263
+ pipe.enable_attention_slicing(slice_size=2)
264
+ inputs = self.get_dummy_inputs(generator_device)
265
+ output_with_slicing2 = pipe(**inputs)[0]
266
+
267
+ if test_max_difference:
268
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
269
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
270
+ self.assertLess(
271
+ max(max_diff1, max_diff2),
272
+ expected_max_diff,
273
+ "Attention slicing should not affect the inference results",
274
+ )
275
+
276
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
277
+ self.pipeline_class._optional_components.remove("safety_checker")
278
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
279
+ self.pipeline_class._optional_components.append("safety_checker")
280
+
281
+ def test_serialization_with_variants(self):
282
+ components = self.get_dummy_components()
283
+ pipe = self.pipeline_class(**components)
284
+ model_components = [
285
+ component_name
286
+ for component_name, component in pipe.components.items()
287
+ if isinstance(component, torch.nn.Module)
288
+ ]
289
+ model_components.remove("safety_checker")
290
+ variant = "fp16"
291
+
292
+ with tempfile.TemporaryDirectory() as tmpdir:
293
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
294
+
295
+ with open(f"{tmpdir}/model_index.json", "r") as f:
296
+ config = json.load(f)
297
+
298
+ for subfolder in os.listdir(tmpdir):
299
+ if not os.path.isfile(subfolder) and subfolder in model_components:
300
+ folder_path = os.path.join(tmpdir, subfolder)
301
+ is_folder = os.path.isdir(folder_path) and subfolder in config
302
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
303
+
304
+ def test_torch_dtype_dict(self):
305
+ components = self.get_dummy_components()
306
+ if not components:
307
+ self.skipTest("No dummy components defined.")
308
+
309
+ pipe = self.pipeline_class(**components)
310
+
311
+ specified_key = next(iter(components.keys()))
312
+
313
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
314
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
315
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
316
+ loaded_pipe = self.pipeline_class.from_pretrained(
317
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
318
+ )
319
+
320
+ for name, component in loaded_pipe.components.items():
321
+ if name == "safety_checker":
322
+ continue
323
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
324
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
325
+ self.assertEqual(
326
+ component.dtype,
327
+ expected_dtype,
328
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
329
+ )
330
+
331
+ @unittest.skip(
332
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
333
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
334
+ "too large and slow to run on CI."
335
+ )
336
+ def test_encode_prompt_works_in_isolation(self):
337
+ pass
diffusers/tests/pipelines/cosmos/test_cosmos2_5_transfer.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGeneration, Qwen2Tokenizer
24
+
25
+ from diffusers import (
26
+ AutoencoderKLWan,
27
+ Cosmos2_5_TransferPipeline,
28
+ CosmosControlNetModel,
29
+ CosmosTransformer3DModel,
30
+ UniPCMultistepScheduler,
31
+ )
32
+
33
+ from ...testing_utils import enable_full_determinism, torch_device
34
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
35
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
36
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
37
+
38
+
39
+ enable_full_determinism()
40
+
41
+
42
+ class Cosmos2_5_TransferWrapper(Cosmos2_5_TransferPipeline):
43
+ @staticmethod
44
+ def from_pretrained(*args, **kwargs):
45
+ if "safety_checker" not in kwargs or kwargs["safety_checker"] is None:
46
+ safety_checker = DummyCosmosSafetyChecker()
47
+ device_map = kwargs.get("device_map", "cpu")
48
+ torch_dtype = kwargs.get("torch_dtype")
49
+ if device_map is not None or torch_dtype is not None:
50
+ safety_checker = safety_checker.to(device_map, dtype=torch_dtype)
51
+ kwargs["safety_checker"] = safety_checker
52
+ return Cosmos2_5_TransferPipeline.from_pretrained(*args, **kwargs)
53
+
54
+
55
+ class Cosmos2_5_TransferPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
56
+ pipeline_class = Cosmos2_5_TransferWrapper
57
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
58
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"controls"})
59
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
60
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
61
+ required_optional_params = frozenset(
62
+ [
63
+ "num_inference_steps",
64
+ "generator",
65
+ "latents",
66
+ "return_dict",
67
+ "callback_on_step_end",
68
+ "callback_on_step_end_tensor_inputs",
69
+ ]
70
+ )
71
+ supports_dduf = False
72
+ test_xformers_attention = False
73
+ test_layerwise_casting = True
74
+ test_group_offloading = True
75
+
76
+ def get_dummy_components(self):
77
+ torch.manual_seed(0)
78
+ # Transformer with img_context support for Transfer2.5
79
+ transformer = CosmosTransformer3DModel(
80
+ in_channels=16 + 1,
81
+ out_channels=16,
82
+ num_attention_heads=2,
83
+ attention_head_dim=16,
84
+ num_layers=2,
85
+ mlp_ratio=2,
86
+ text_embed_dim=32,
87
+ adaln_lora_dim=4,
88
+ max_size=(4, 32, 32),
89
+ patch_size=(1, 2, 2),
90
+ rope_scale=(2.0, 1.0, 1.0),
91
+ concat_padding_mask=True,
92
+ extra_pos_embed_type="learnable",
93
+ controlnet_block_every_n=1,
94
+ img_context_dim_in=32,
95
+ img_context_num_tokens=4,
96
+ img_context_dim_out=32,
97
+ )
98
+
99
+ torch.manual_seed(0)
100
+ controlnet = CosmosControlNetModel(
101
+ n_controlnet_blocks=2,
102
+ in_channels=16 + 1 + 1, # control latent channels + condition_mask + padding_mask
103
+ latent_channels=16 + 1 + 1, # base latent channels (16) + condition_mask (1) + padding_mask (1) = 18
104
+ model_channels=32,
105
+ num_attention_heads=2,
106
+ attention_head_dim=16,
107
+ mlp_ratio=2,
108
+ text_embed_dim=32,
109
+ adaln_lora_dim=4,
110
+ patch_size=(1, 2, 2),
111
+ max_size=(4, 32, 32),
112
+ rope_scale=(2.0, 1.0, 1.0),
113
+ extra_pos_embed_type="learnable", # Match transformer's config
114
+ img_context_dim_in=32,
115
+ img_context_dim_out=32,
116
+ use_crossattn_projection=False, # Test doesn't need this projection
117
+ )
118
+
119
+ torch.manual_seed(0)
120
+ vae = AutoencoderKLWan(
121
+ base_dim=3,
122
+ z_dim=16,
123
+ dim_mult=[1, 1, 1, 1],
124
+ num_res_blocks=1,
125
+ temperal_downsample=[False, True, True],
126
+ )
127
+
128
+ torch.manual_seed(0)
129
+ scheduler = UniPCMultistepScheduler()
130
+
131
+ torch.manual_seed(0)
132
+ config = Qwen2_5_VLConfig(
133
+ text_config={
134
+ "hidden_size": 16,
135
+ "intermediate_size": 16,
136
+ "num_hidden_layers": 2,
137
+ "num_attention_heads": 2,
138
+ "num_key_value_heads": 2,
139
+ "rope_scaling": {
140
+ "mrope_section": [1, 1, 2],
141
+ "rope_type": "default",
142
+ "type": "default",
143
+ },
144
+ "rope_theta": 1000000.0,
145
+ },
146
+ vision_config={
147
+ "depth": 2,
148
+ "hidden_size": 16,
149
+ "intermediate_size": 16,
150
+ "num_heads": 2,
151
+ "out_hidden_size": 16,
152
+ },
153
+ hidden_size=16,
154
+ vocab_size=152064,
155
+ vision_end_token_id=151653,
156
+ vision_start_token_id=151652,
157
+ vision_token_id=151654,
158
+ )
159
+ text_encoder = Qwen2_5_VLForConditionalGeneration(config)
160
+ tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
161
+
162
+ components = {
163
+ "transformer": transformer,
164
+ "controlnet": controlnet,
165
+ "vae": vae,
166
+ "scheduler": scheduler,
167
+ "text_encoder": text_encoder,
168
+ "tokenizer": tokenizer,
169
+ "safety_checker": DummyCosmosSafetyChecker(),
170
+ }
171
+ return components
172
+
173
+ def get_dummy_inputs(self, device, seed=0):
174
+ if str(device).startswith("mps"):
175
+ generator = torch.manual_seed(seed)
176
+ else:
177
+ generator = torch.Generator(device=device).manual_seed(seed)
178
+
179
+ controls_generator = torch.Generator(device="cpu").manual_seed(seed)
180
+
181
+ inputs = {
182
+ "prompt": "dance monkey",
183
+ "negative_prompt": "bad quality",
184
+ "controls": [torch.randn(3, 32, 32, generator=controls_generator) for _ in range(5)],
185
+ "generator": generator,
186
+ "num_inference_steps": 2,
187
+ "guidance_scale": 3.0,
188
+ "height": 32,
189
+ "width": 32,
190
+ "num_frames": 3,
191
+ "num_frames_per_chunk": 16,
192
+ "max_sequence_length": 16,
193
+ "output_type": "pt",
194
+ }
195
+
196
+ return inputs
197
+
198
+ def test_components_function(self):
199
+ init_components = self.get_dummy_components()
200
+ init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
201
+ pipe = self.pipeline_class(**init_components)
202
+ self.assertTrue(hasattr(pipe, "components"))
203
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
204
+
205
+ def test_inference(self):
206
+ device = "cpu"
207
+
208
+ components = self.get_dummy_components()
209
+ pipe = self.pipeline_class(**components)
210
+ pipe.to(device)
211
+ pipe.set_progress_bar_config(disable=None)
212
+
213
+ inputs = self.get_dummy_inputs(device)
214
+ video = pipe(**inputs).frames
215
+ generated_video = video[0]
216
+ self.assertEqual(generated_video.shape, (3, 3, 32, 32))
217
+ self.assertTrue(torch.isfinite(generated_video).all())
218
+
219
+ def test_inference_autoregressive_multi_chunk(self):
220
+ device = "cpu"
221
+
222
+ components = self.get_dummy_components()
223
+ pipe = self.pipeline_class(**components)
224
+ pipe.to(device)
225
+ pipe.set_progress_bar_config(disable=None)
226
+
227
+ inputs = self.get_dummy_inputs(device)
228
+ inputs["num_frames"] = 5
229
+ inputs["num_frames_per_chunk"] = 3
230
+ inputs["num_ar_conditional_frames"] = 1
231
+
232
+ video = pipe(**inputs).frames
233
+ generated_video = video[0]
234
+ self.assertEqual(generated_video.shape, (5, 3, 32, 32))
235
+ self.assertTrue(torch.isfinite(generated_video).all())
236
+
237
+ def test_inference_autoregressive_multi_chunk_no_condition_frames(self):
238
+ device = "cpu"
239
+
240
+ components = self.get_dummy_components()
241
+ pipe = self.pipeline_class(**components)
242
+ pipe.to(device)
243
+ pipe.set_progress_bar_config(disable=None)
244
+
245
+ inputs = self.get_dummy_inputs(device)
246
+ inputs["num_frames"] = 5
247
+ inputs["num_frames_per_chunk"] = 3
248
+ inputs["num_ar_conditional_frames"] = 0
249
+
250
+ video = pipe(**inputs).frames
251
+ generated_video = video[0]
252
+ self.assertEqual(generated_video.shape, (5, 3, 32, 32))
253
+ self.assertTrue(torch.isfinite(generated_video).all())
254
+
255
+ def test_num_frames_per_chunk_above_rope_raises(self):
256
+ device = "cpu"
257
+
258
+ components = self.get_dummy_components()
259
+ pipe = self.pipeline_class(**components)
260
+ pipe.to(device)
261
+ pipe.set_progress_bar_config(disable=None)
262
+
263
+ inputs = self.get_dummy_inputs(device)
264
+ inputs["num_frames_per_chunk"] = 17
265
+
266
+ with self.assertRaisesRegex(ValueError, "too large for RoPE setting"):
267
+ pipe(**inputs)
268
+
269
+ def test_inference_with_controls(self):
270
+ """Test inference with control inputs (ControlNet)."""
271
+ device = "cpu"
272
+
273
+ components = self.get_dummy_components()
274
+ pipe = self.pipeline_class(**components)
275
+ pipe.to(device)
276
+ pipe.set_progress_bar_config(disable=None)
277
+
278
+ inputs = self.get_dummy_inputs(device)
279
+ inputs["controls"] = [torch.randn(3, 32, 32) for _ in range(5)] # list of 5 frames (C, H, W)
280
+ inputs["controls_conditioning_scale"] = 1.0
281
+ inputs["num_frames"] = None
282
+
283
+ video = pipe(**inputs).frames
284
+ generated_video = video[0]
285
+ self.assertEqual(generated_video.shape, (5, 3, 32, 32))
286
+ self.assertTrue(torch.isfinite(generated_video).all())
287
+
288
+ def test_callback_inputs(self):
289
+ sig = inspect.signature(self.pipeline_class.__call__)
290
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
291
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
292
+
293
+ if not (has_callback_tensor_inputs and has_callback_step_end):
294
+ return
295
+
296
+ components = self.get_dummy_components()
297
+ pipe = self.pipeline_class(**components)
298
+ pipe = pipe.to(torch_device)
299
+ pipe.set_progress_bar_config(disable=None)
300
+ self.assertTrue(
301
+ hasattr(pipe, "_callback_tensor_inputs"),
302
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
303
+ )
304
+
305
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
306
+ for tensor_name in callback_kwargs.keys():
307
+ assert tensor_name in pipe._callback_tensor_inputs
308
+ return callback_kwargs
309
+
310
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
311
+ for tensor_name in pipe._callback_tensor_inputs:
312
+ assert tensor_name in callback_kwargs
313
+ for tensor_name in callback_kwargs.keys():
314
+ assert tensor_name in pipe._callback_tensor_inputs
315
+ return callback_kwargs
316
+
317
+ inputs = self.get_dummy_inputs(torch_device)
318
+
319
+ inputs["callback_on_step_end"] = callback_inputs_subset
320
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
321
+ _ = pipe(**inputs)[0]
322
+
323
+ inputs["callback_on_step_end"] = callback_inputs_all
324
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
325
+ _ = pipe(**inputs)[0]
326
+
327
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
328
+ is_last = i == (pipe.num_timesteps - 1)
329
+ if is_last:
330
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
331
+ return callback_kwargs
332
+
333
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
334
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
335
+ output = pipe(**inputs)[0]
336
+ assert output.abs().sum() < 1e10
337
+
338
+ def test_inference_batch_single_identical(self):
339
+ self._test_inference_batch_single_identical(batch_size=2, expected_max_diff=1e-2)
340
+
341
+ def test_attention_slicing_forward_pass(
342
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
343
+ ):
344
+ if not getattr(self, "test_attention_slicing", True):
345
+ return
346
+
347
+ components = self.get_dummy_components()
348
+ pipe = self.pipeline_class(**components)
349
+ for component in pipe.components.values():
350
+ if hasattr(component, "set_default_attn_processor"):
351
+ component.set_default_attn_processor()
352
+ pipe.to(torch_device)
353
+ pipe.set_progress_bar_config(disable=None)
354
+
355
+ generator_device = "cpu"
356
+ inputs = self.get_dummy_inputs(generator_device)
357
+ output_without_slicing = pipe(**inputs)[0]
358
+
359
+ pipe.enable_attention_slicing(slice_size=1)
360
+ inputs = self.get_dummy_inputs(generator_device)
361
+ output_with_slicing1 = pipe(**inputs)[0]
362
+
363
+ pipe.enable_attention_slicing(slice_size=2)
364
+ inputs = self.get_dummy_inputs(generator_device)
365
+ output_with_slicing2 = pipe(**inputs)[0]
366
+
367
+ if test_max_difference:
368
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
369
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
370
+ self.assertLess(
371
+ max(max_diff1, max_diff2),
372
+ expected_max_diff,
373
+ "Attention slicing should not affect the inference results",
374
+ )
375
+
376
+ def test_serialization_with_variants(self):
377
+ components = self.get_dummy_components()
378
+ pipe = self.pipeline_class(**components)
379
+ model_components = [
380
+ component_name
381
+ for component_name, component in pipe.components.items()
382
+ if isinstance(component, torch.nn.Module)
383
+ ]
384
+ # Remove components that aren't saved as standard diffusers models
385
+ if "safety_checker" in model_components:
386
+ model_components.remove("safety_checker")
387
+ variant = "fp16"
388
+
389
+ with tempfile.TemporaryDirectory() as tmpdir:
390
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
391
+
392
+ with open(f"{tmpdir}/model_index.json", "r") as f:
393
+ config = json.load(f)
394
+
395
+ for subfolder in os.listdir(tmpdir):
396
+ if not os.path.isfile(subfolder) and subfolder in model_components:
397
+ folder_path = os.path.join(tmpdir, subfolder)
398
+ is_folder = os.path.isdir(folder_path) and subfolder in config
399
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
400
+
401
+ def test_torch_dtype_dict(self):
402
+ components = self.get_dummy_components()
403
+ if not components:
404
+ self.skipTest("No dummy components defined.")
405
+
406
+ pipe = self.pipeline_class(**components)
407
+
408
+ specified_key = next(iter(components.keys()))
409
+
410
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
411
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
412
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
413
+ loaded_pipe = self.pipeline_class.from_pretrained(
414
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
415
+ )
416
+
417
+ for name, component in loaded_pipe.components.items():
418
+ # Skip components that are not loaded from disk or have special handling
419
+ if name == "safety_checker":
420
+ continue
421
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
422
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
423
+ self.assertEqual(
424
+ component.dtype,
425
+ expected_dtype,
426
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
427
+ )
428
+
429
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
430
+ self.pipeline_class._optional_components.remove("safety_checker")
431
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
432
+ self.pipeline_class._optional_components.append("safety_checker")
433
+
434
+ @unittest.skip(
435
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
436
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
437
+ "too large and slow to run on CI."
438
+ )
439
+ def test_encode_prompt_works_in_isolation(self):
440
+ pass
diffusers/tests/pipelines/cosmos/test_cosmos2_text2image.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
24
+
25
+ from diffusers import (
26
+ AutoencoderKLWan,
27
+ Cosmos2TextToImagePipeline,
28
+ CosmosTransformer3DModel,
29
+ FlowMatchEulerDiscreteScheduler,
30
+ )
31
+
32
+ from ...testing_utils import enable_full_determinism, torch_device
33
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
34
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
35
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
36
+
37
+
38
+ enable_full_determinism()
39
+
40
+
41
+ class Cosmos2TextToImagePipelineWrapper(Cosmos2TextToImagePipeline):
42
+ @staticmethod
43
+ def from_pretrained(*args, **kwargs):
44
+ kwargs["safety_checker"] = DummyCosmosSafetyChecker()
45
+ return Cosmos2TextToImagePipeline.from_pretrained(*args, **kwargs)
46
+
47
+
48
+ class Cosmos2TextToImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
49
+ pipeline_class = Cosmos2TextToImagePipelineWrapper
50
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
51
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
52
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
53
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
54
+ required_optional_params = frozenset(
55
+ [
56
+ "num_inference_steps",
57
+ "generator",
58
+ "latents",
59
+ "return_dict",
60
+ "callback_on_step_end",
61
+ "callback_on_step_end_tensor_inputs",
62
+ ]
63
+ )
64
+ supports_dduf = False
65
+ test_xformers_attention = False
66
+ test_layerwise_casting = True
67
+ test_group_offloading = True
68
+
69
+ def get_dummy_components(self):
70
+ torch.manual_seed(0)
71
+ transformer = CosmosTransformer3DModel(
72
+ in_channels=16,
73
+ out_channels=16,
74
+ num_attention_heads=2,
75
+ attention_head_dim=16,
76
+ num_layers=2,
77
+ mlp_ratio=2,
78
+ text_embed_dim=32,
79
+ adaln_lora_dim=4,
80
+ max_size=(4, 32, 32),
81
+ patch_size=(1, 2, 2),
82
+ rope_scale=(2.0, 1.0, 1.0),
83
+ concat_padding_mask=True,
84
+ extra_pos_embed_type="learnable",
85
+ )
86
+
87
+ torch.manual_seed(0)
88
+ vae = AutoencoderKLWan(
89
+ base_dim=3,
90
+ z_dim=16,
91
+ dim_mult=[1, 1, 1, 1],
92
+ num_res_blocks=1,
93
+ temperal_downsample=[False, True, True],
94
+ )
95
+
96
+ torch.manual_seed(0)
97
+ scheduler = FlowMatchEulerDiscreteScheduler(use_karras_sigmas=True)
98
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
99
+ text_encoder = T5EncoderModel(config)
100
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
101
+
102
+ components = {
103
+ "transformer": transformer,
104
+ "vae": vae,
105
+ "scheduler": scheduler,
106
+ "text_encoder": text_encoder,
107
+ "tokenizer": tokenizer,
108
+ # We cannot run the Cosmos Guardrail for fast tests due to the large model size
109
+ "safety_checker": DummyCosmosSafetyChecker(),
110
+ }
111
+ return components
112
+
113
+ def get_dummy_inputs(self, device, seed=0):
114
+ if str(device).startswith("mps"):
115
+ generator = torch.manual_seed(seed)
116
+ else:
117
+ generator = torch.Generator(device=device).manual_seed(seed)
118
+
119
+ inputs = {
120
+ "prompt": "dance monkey",
121
+ "negative_prompt": "bad quality",
122
+ "generator": generator,
123
+ "num_inference_steps": 2,
124
+ "guidance_scale": 3.0,
125
+ "height": 32,
126
+ "width": 32,
127
+ "max_sequence_length": 16,
128
+ "output_type": "pt",
129
+ }
130
+
131
+ return inputs
132
+
133
+ def test_inference(self):
134
+ device = "cpu"
135
+
136
+ components = self.get_dummy_components()
137
+ pipe = self.pipeline_class(**components)
138
+ pipe.to(device)
139
+ pipe.set_progress_bar_config(disable=None)
140
+
141
+ inputs = self.get_dummy_inputs(device)
142
+ image = pipe(**inputs).images
143
+ generated_image = image[0]
144
+ self.assertEqual(generated_image.shape, (3, 32, 32))
145
+
146
+ # fmt: off
147
+ expected_slice = torch.tensor([0.451, 0.451, 0.4471, 0.451, 0.451, 0.451, 0.451, 0.451, 0.4784, 0.4784, 0.4784, 0.4784, 0.4784, 0.4902, 0.4588, 0.5333])
148
+ # fmt: on
149
+
150
+ generated_slice = generated_image.flatten()
151
+ generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
152
+ self.assertTrue(torch.allclose(generated_slice, expected_slice, atol=1e-3))
153
+
154
+ def test_callback_inputs(self):
155
+ sig = inspect.signature(self.pipeline_class.__call__)
156
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
157
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
158
+
159
+ if not (has_callback_tensor_inputs and has_callback_step_end):
160
+ return
161
+
162
+ components = self.get_dummy_components()
163
+ pipe = self.pipeline_class(**components)
164
+ pipe = pipe.to(torch_device)
165
+ pipe.set_progress_bar_config(disable=None)
166
+ self.assertTrue(
167
+ hasattr(pipe, "_callback_tensor_inputs"),
168
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
169
+ )
170
+
171
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
172
+ # iterate over callback args
173
+ for tensor_name, tensor_value in callback_kwargs.items():
174
+ # check that we're only passing in allowed tensor inputs
175
+ assert tensor_name in pipe._callback_tensor_inputs
176
+
177
+ return callback_kwargs
178
+
179
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
180
+ for tensor_name in pipe._callback_tensor_inputs:
181
+ assert tensor_name in callback_kwargs
182
+
183
+ # iterate over callback args
184
+ for tensor_name, tensor_value in callback_kwargs.items():
185
+ # check that we're only passing in allowed tensor inputs
186
+ assert tensor_name in pipe._callback_tensor_inputs
187
+
188
+ return callback_kwargs
189
+
190
+ inputs = self.get_dummy_inputs(torch_device)
191
+
192
+ # Test passing in a subset
193
+ inputs["callback_on_step_end"] = callback_inputs_subset
194
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
195
+ output = pipe(**inputs)[0]
196
+
197
+ # Test passing in a everything
198
+ inputs["callback_on_step_end"] = callback_inputs_all
199
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
200
+ output = pipe(**inputs)[0]
201
+
202
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
203
+ is_last = i == (pipe.num_timesteps - 1)
204
+ if is_last:
205
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
206
+ return callback_kwargs
207
+
208
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
209
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
210
+ output = pipe(**inputs)[0]
211
+ assert output.abs().sum() < 1e10
212
+
213
+ def test_inference_batch_single_identical(self):
214
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
215
+
216
+ def test_attention_slicing_forward_pass(
217
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
218
+ ):
219
+ if not self.test_attention_slicing:
220
+ return
221
+
222
+ components = self.get_dummy_components()
223
+ pipe = self.pipeline_class(**components)
224
+ for component in pipe.components.values():
225
+ if hasattr(component, "set_default_attn_processor"):
226
+ component.set_default_attn_processor()
227
+ pipe.to(torch_device)
228
+ pipe.set_progress_bar_config(disable=None)
229
+
230
+ generator_device = "cpu"
231
+ inputs = self.get_dummy_inputs(generator_device)
232
+ output_without_slicing = pipe(**inputs)[0]
233
+
234
+ pipe.enable_attention_slicing(slice_size=1)
235
+ inputs = self.get_dummy_inputs(generator_device)
236
+ output_with_slicing1 = pipe(**inputs)[0]
237
+
238
+ pipe.enable_attention_slicing(slice_size=2)
239
+ inputs = self.get_dummy_inputs(generator_device)
240
+ output_with_slicing2 = pipe(**inputs)[0]
241
+
242
+ if test_max_difference:
243
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
244
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
245
+ self.assertLess(
246
+ max(max_diff1, max_diff2),
247
+ expected_max_diff,
248
+ "Attention slicing should not affect the inference results",
249
+ )
250
+
251
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
252
+ generator_device = "cpu"
253
+ components = self.get_dummy_components()
254
+
255
+ pipe = self.pipeline_class(**components)
256
+ pipe.to("cpu")
257
+ pipe.set_progress_bar_config(disable=None)
258
+
259
+ # Without tiling
260
+ inputs = self.get_dummy_inputs(generator_device)
261
+ inputs["height"] = inputs["width"] = 128
262
+ output_without_tiling = pipe(**inputs)[0]
263
+
264
+ # With tiling
265
+ pipe.vae.enable_tiling(
266
+ tile_sample_min_height=96,
267
+ tile_sample_min_width=96,
268
+ tile_sample_stride_height=64,
269
+ tile_sample_stride_width=64,
270
+ )
271
+ inputs = self.get_dummy_inputs(generator_device)
272
+ inputs["height"] = inputs["width"] = 128
273
+ output_with_tiling = pipe(**inputs)[0]
274
+
275
+ self.assertLess(
276
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
277
+ expected_diff_max,
278
+ "VAE tiling should not affect the inference results",
279
+ )
280
+
281
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
282
+ self.pipeline_class._optional_components.remove("safety_checker")
283
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
284
+ self.pipeline_class._optional_components.append("safety_checker")
285
+
286
+ def test_serialization_with_variants(self):
287
+ components = self.get_dummy_components()
288
+ pipe = self.pipeline_class(**components)
289
+ model_components = [
290
+ component_name
291
+ for component_name, component in pipe.components.items()
292
+ if isinstance(component, torch.nn.Module)
293
+ ]
294
+ model_components.remove("safety_checker")
295
+ variant = "fp16"
296
+
297
+ with tempfile.TemporaryDirectory() as tmpdir:
298
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
299
+
300
+ with open(f"{tmpdir}/model_index.json", "r") as f:
301
+ config = json.load(f)
302
+
303
+ for subfolder in os.listdir(tmpdir):
304
+ if not os.path.isfile(subfolder) and subfolder in model_components:
305
+ folder_path = os.path.join(tmpdir, subfolder)
306
+ is_folder = os.path.isdir(folder_path) and subfolder in config
307
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
308
+
309
+ def test_torch_dtype_dict(self):
310
+ components = self.get_dummy_components()
311
+ if not components:
312
+ self.skipTest("No dummy components defined.")
313
+
314
+ pipe = self.pipeline_class(**components)
315
+
316
+ specified_key = next(iter(components.keys()))
317
+
318
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
319
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
320
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
321
+ loaded_pipe = self.pipeline_class.from_pretrained(
322
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
323
+ )
324
+
325
+ for name, component in loaded_pipe.components.items():
326
+ if name == "safety_checker":
327
+ continue
328
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
329
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
330
+ self.assertEqual(
331
+ component.dtype,
332
+ expected_dtype,
333
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
334
+ )
335
+
336
+ @unittest.skip(
337
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
338
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
339
+ "too large and slow to run on CI."
340
+ )
341
+ def test_encode_prompt_works_in_isolation(self):
342
+ pass
diffusers/tests/pipelines/cosmos/test_cosmos2_video2world.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import PIL.Image
23
+ import torch
24
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
25
+
26
+ from diffusers import (
27
+ AutoencoderKLWan,
28
+ Cosmos2VideoToWorldPipeline,
29
+ CosmosTransformer3DModel,
30
+ FlowMatchEulerDiscreteScheduler,
31
+ )
32
+
33
+ from ...testing_utils import enable_full_determinism, torch_device
34
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
35
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
36
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
37
+
38
+
39
+ enable_full_determinism()
40
+
41
+
42
+ class Cosmos2VideoToWorldPipelineWrapper(Cosmos2VideoToWorldPipeline):
43
+ @staticmethod
44
+ def from_pretrained(*args, **kwargs):
45
+ kwargs["safety_checker"] = DummyCosmosSafetyChecker()
46
+ return Cosmos2VideoToWorldPipeline.from_pretrained(*args, **kwargs)
47
+
48
+
49
+ class Cosmos2VideoToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
50
+ pipeline_class = Cosmos2VideoToWorldPipelineWrapper
51
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
52
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image", "video"})
53
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
54
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
55
+ required_optional_params = frozenset(
56
+ [
57
+ "num_inference_steps",
58
+ "generator",
59
+ "latents",
60
+ "return_dict",
61
+ "callback_on_step_end",
62
+ "callback_on_step_end_tensor_inputs",
63
+ ]
64
+ )
65
+ supports_dduf = False
66
+ test_xformers_attention = False
67
+ test_layerwise_casting = True
68
+ test_group_offloading = True
69
+
70
+ def get_dummy_components(self):
71
+ torch.manual_seed(0)
72
+ transformer = CosmosTransformer3DModel(
73
+ in_channels=16 + 1,
74
+ out_channels=16,
75
+ num_attention_heads=2,
76
+ attention_head_dim=16,
77
+ num_layers=2,
78
+ mlp_ratio=2,
79
+ text_embed_dim=32,
80
+ adaln_lora_dim=4,
81
+ max_size=(4, 32, 32),
82
+ patch_size=(1, 2, 2),
83
+ rope_scale=(2.0, 1.0, 1.0),
84
+ concat_padding_mask=True,
85
+ extra_pos_embed_type="learnable",
86
+ )
87
+
88
+ torch.manual_seed(0)
89
+ vae = AutoencoderKLWan(
90
+ base_dim=3,
91
+ z_dim=16,
92
+ dim_mult=[1, 1, 1, 1],
93
+ num_res_blocks=1,
94
+ temperal_downsample=[False, True, True],
95
+ )
96
+
97
+ torch.manual_seed(0)
98
+ scheduler = FlowMatchEulerDiscreteScheduler(use_karras_sigmas=True)
99
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
100
+ text_encoder = T5EncoderModel(config)
101
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
102
+
103
+ components = {
104
+ "transformer": transformer,
105
+ "vae": vae,
106
+ "scheduler": scheduler,
107
+ "text_encoder": text_encoder,
108
+ "tokenizer": tokenizer,
109
+ # We cannot run the Cosmos Guardrail for fast tests due to the large model size
110
+ "safety_checker": DummyCosmosSafetyChecker(),
111
+ }
112
+ return components
113
+
114
+ def get_dummy_inputs(self, device, seed=0):
115
+ if str(device).startswith("mps"):
116
+ generator = torch.manual_seed(seed)
117
+ else:
118
+ generator = torch.Generator(device=device).manual_seed(seed)
119
+
120
+ image_height = 32
121
+ image_width = 32
122
+ image = PIL.Image.new("RGB", (image_width, image_height))
123
+
124
+ inputs = {
125
+ "image": image,
126
+ "prompt": "dance monkey",
127
+ "negative_prompt": "bad quality",
128
+ "generator": generator,
129
+ "num_inference_steps": 2,
130
+ "guidance_scale": 3.0,
131
+ "height": image_height,
132
+ "width": image_width,
133
+ "num_frames": 9,
134
+ "max_sequence_length": 16,
135
+ "output_type": "pt",
136
+ }
137
+
138
+ return inputs
139
+
140
+ def test_inference(self):
141
+ device = "cpu"
142
+
143
+ components = self.get_dummy_components()
144
+ pipe = self.pipeline_class(**components)
145
+ pipe.to(device)
146
+ pipe.set_progress_bar_config(disable=None)
147
+
148
+ inputs = self.get_dummy_inputs(device)
149
+ video = pipe(**inputs).frames
150
+ generated_video = video[0]
151
+ self.assertEqual(generated_video.shape, (9, 3, 32, 32))
152
+
153
+ # fmt: off
154
+ expected_slice = torch.tensor([0.451, 0.451, 0.4471, 0.451, 0.451, 0.451, 0.451, 0.451, 0.5098, 0.5137, 0.5176, 0.5098, 0.5255, 0.5412, 0.5098, 0.5059])
155
+ # fmt: on
156
+
157
+ generated_slice = generated_video.flatten()
158
+ generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
159
+ self.assertTrue(torch.allclose(generated_slice, expected_slice, atol=1e-3))
160
+
161
+ def test_components_function(self):
162
+ init_components = self.get_dummy_components()
163
+ init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
164
+ pipe = self.pipeline_class(**init_components)
165
+ self.assertTrue(hasattr(pipe, "components"))
166
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
167
+
168
+ def test_callback_inputs(self):
169
+ sig = inspect.signature(self.pipeline_class.__call__)
170
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
171
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
172
+
173
+ if not (has_callback_tensor_inputs and has_callback_step_end):
174
+ return
175
+
176
+ components = self.get_dummy_components()
177
+ pipe = self.pipeline_class(**components)
178
+ pipe = pipe.to(torch_device)
179
+ pipe.set_progress_bar_config(disable=None)
180
+ self.assertTrue(
181
+ hasattr(pipe, "_callback_tensor_inputs"),
182
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
183
+ )
184
+
185
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
186
+ # iterate over callback args
187
+ for tensor_name, tensor_value in callback_kwargs.items():
188
+ # check that we're only passing in allowed tensor inputs
189
+ assert tensor_name in pipe._callback_tensor_inputs
190
+
191
+ return callback_kwargs
192
+
193
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
194
+ for tensor_name in pipe._callback_tensor_inputs:
195
+ assert tensor_name in callback_kwargs
196
+
197
+ # iterate over callback args
198
+ for tensor_name, tensor_value in callback_kwargs.items():
199
+ # check that we're only passing in allowed tensor inputs
200
+ assert tensor_name in pipe._callback_tensor_inputs
201
+
202
+ return callback_kwargs
203
+
204
+ inputs = self.get_dummy_inputs(torch_device)
205
+
206
+ # Test passing in a subset
207
+ inputs["callback_on_step_end"] = callback_inputs_subset
208
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
209
+ output = pipe(**inputs)[0]
210
+
211
+ # Test passing in a everything
212
+ inputs["callback_on_step_end"] = callback_inputs_all
213
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
214
+ output = pipe(**inputs)[0]
215
+
216
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
217
+ is_last = i == (pipe.num_timesteps - 1)
218
+ if is_last:
219
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
220
+ return callback_kwargs
221
+
222
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
223
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
224
+ output = pipe(**inputs)[0]
225
+ assert output.abs().sum() < 1e10
226
+
227
+ def test_inference_batch_single_identical(self):
228
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
229
+
230
+ def test_attention_slicing_forward_pass(
231
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
232
+ ):
233
+ if not self.test_attention_slicing:
234
+ return
235
+
236
+ components = self.get_dummy_components()
237
+ pipe = self.pipeline_class(**components)
238
+ for component in pipe.components.values():
239
+ if hasattr(component, "set_default_attn_processor"):
240
+ component.set_default_attn_processor()
241
+ pipe.to(torch_device)
242
+ pipe.set_progress_bar_config(disable=None)
243
+
244
+ generator_device = "cpu"
245
+ inputs = self.get_dummy_inputs(generator_device)
246
+ output_without_slicing = pipe(**inputs)[0]
247
+
248
+ pipe.enable_attention_slicing(slice_size=1)
249
+ inputs = self.get_dummy_inputs(generator_device)
250
+ output_with_slicing1 = pipe(**inputs)[0]
251
+
252
+ pipe.enable_attention_slicing(slice_size=2)
253
+ inputs = self.get_dummy_inputs(generator_device)
254
+ output_with_slicing2 = pipe(**inputs)[0]
255
+
256
+ if test_max_difference:
257
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
258
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
259
+ self.assertLess(
260
+ max(max_diff1, max_diff2),
261
+ expected_max_diff,
262
+ "Attention slicing should not affect the inference results",
263
+ )
264
+
265
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
266
+ generator_device = "cpu"
267
+ components = self.get_dummy_components()
268
+
269
+ pipe = self.pipeline_class(**components)
270
+ pipe.to("cpu")
271
+ pipe.set_progress_bar_config(disable=None)
272
+
273
+ # Without tiling
274
+ inputs = self.get_dummy_inputs(generator_device)
275
+ inputs["height"] = inputs["width"] = 128
276
+ output_without_tiling = pipe(**inputs)[0]
277
+
278
+ # With tiling
279
+ pipe.vae.enable_tiling(
280
+ tile_sample_min_height=96,
281
+ tile_sample_min_width=96,
282
+ tile_sample_stride_height=64,
283
+ tile_sample_stride_width=64,
284
+ )
285
+ inputs = self.get_dummy_inputs(generator_device)
286
+ inputs["height"] = inputs["width"] = 128
287
+ output_with_tiling = pipe(**inputs)[0]
288
+
289
+ self.assertLess(
290
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
291
+ expected_diff_max,
292
+ "VAE tiling should not affect the inference results",
293
+ )
294
+
295
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
296
+ self.pipeline_class._optional_components.remove("safety_checker")
297
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
298
+ self.pipeline_class._optional_components.append("safety_checker")
299
+
300
+ def test_serialization_with_variants(self):
301
+ components = self.get_dummy_components()
302
+ pipe = self.pipeline_class(**components)
303
+ model_components = [
304
+ component_name
305
+ for component_name, component in pipe.components.items()
306
+ if isinstance(component, torch.nn.Module)
307
+ ]
308
+ model_components.remove("safety_checker")
309
+ variant = "fp16"
310
+
311
+ with tempfile.TemporaryDirectory() as tmpdir:
312
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
313
+
314
+ with open(f"{tmpdir}/model_index.json", "r") as f:
315
+ config = json.load(f)
316
+
317
+ for subfolder in os.listdir(tmpdir):
318
+ if not os.path.isfile(subfolder) and subfolder in model_components:
319
+ folder_path = os.path.join(tmpdir, subfolder)
320
+ is_folder = os.path.isdir(folder_path) and subfolder in config
321
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
322
+
323
+ def test_torch_dtype_dict(self):
324
+ components = self.get_dummy_components()
325
+ if not components:
326
+ self.skipTest("No dummy components defined.")
327
+
328
+ pipe = self.pipeline_class(**components)
329
+
330
+ specified_key = next(iter(components.keys()))
331
+
332
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
333
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
334
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
335
+ loaded_pipe = self.pipeline_class.from_pretrained(
336
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
337
+ )
338
+
339
+ for name, component in loaded_pipe.components.items():
340
+ if name == "safety_checker":
341
+ continue
342
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
343
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
344
+ self.assertEqual(
345
+ component.dtype,
346
+ expected_dtype,
347
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
348
+ )
349
+
350
+ @unittest.skip(
351
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
352
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
353
+ "too large and slow to run on CI."
354
+ )
355
+ def test_encode_prompt_works_in_isolation(self):
356
+ pass
diffusers/tests/pipelines/cosmos/test_cosmos_video2world.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The HuggingFace Team.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ import json
17
+ import os
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import PIL.Image
23
+ import torch
24
+ from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
25
+
26
+ from diffusers import AutoencoderKLCosmos, CosmosTransformer3DModel, CosmosVideoToWorldPipeline, EDMEulerScheduler
27
+
28
+ from ...testing_utils import enable_full_determinism, torch_device
29
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
30
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
31
+ from .cosmos_guardrail import DummyCosmosSafetyChecker
32
+
33
+
34
+ enable_full_determinism()
35
+
36
+
37
+ class CosmosVideoToWorldPipelineWrapper(CosmosVideoToWorldPipeline):
38
+ @staticmethod
39
+ def from_pretrained(*args, **kwargs):
40
+ kwargs["safety_checker"] = DummyCosmosSafetyChecker()
41
+ return CosmosVideoToWorldPipeline.from_pretrained(*args, **kwargs)
42
+
43
+
44
+ class CosmosVideoToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
45
+ pipeline_class = CosmosVideoToWorldPipelineWrapper
46
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
47
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image", "video"})
48
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
49
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
50
+ required_optional_params = frozenset(
51
+ [
52
+ "num_inference_steps",
53
+ "generator",
54
+ "latents",
55
+ "return_dict",
56
+ "callback_on_step_end",
57
+ "callback_on_step_end_tensor_inputs",
58
+ ]
59
+ )
60
+ supports_dduf = False
61
+ test_xformers_attention = False
62
+ test_layerwise_casting = True
63
+ test_group_offloading = True
64
+
65
+ def get_dummy_components(self):
66
+ torch.manual_seed(0)
67
+ transformer = CosmosTransformer3DModel(
68
+ in_channels=4 + 1,
69
+ out_channels=4,
70
+ num_attention_heads=2,
71
+ attention_head_dim=16,
72
+ num_layers=2,
73
+ mlp_ratio=2,
74
+ text_embed_dim=32,
75
+ adaln_lora_dim=4,
76
+ max_size=(4, 32, 32),
77
+ patch_size=(1, 2, 2),
78
+ rope_scale=(2.0, 1.0, 1.0),
79
+ concat_padding_mask=True,
80
+ extra_pos_embed_type="learnable",
81
+ )
82
+
83
+ torch.manual_seed(0)
84
+ vae = AutoencoderKLCosmos(
85
+ in_channels=3,
86
+ out_channels=3,
87
+ latent_channels=4,
88
+ encoder_block_out_channels=(8, 8, 8, 8),
89
+ decode_block_out_channels=(8, 8, 8, 8),
90
+ attention_resolutions=(8,),
91
+ resolution=64,
92
+ num_layers=2,
93
+ patch_size=4,
94
+ patch_type="haar",
95
+ scaling_factor=1.0,
96
+ spatial_compression_ratio=4,
97
+ temporal_compression_ratio=4,
98
+ )
99
+
100
+ torch.manual_seed(0)
101
+ scheduler = EDMEulerScheduler(
102
+ sigma_min=0.002,
103
+ sigma_max=80,
104
+ sigma_data=0.5,
105
+ sigma_schedule="karras",
106
+ num_train_timesteps=1000,
107
+ prediction_type="epsilon",
108
+ rho=7.0,
109
+ final_sigmas_type="sigma_min",
110
+ )
111
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
112
+ text_encoder = T5EncoderModel(config)
113
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
114
+
115
+ components = {
116
+ "transformer": transformer,
117
+ "vae": vae,
118
+ "scheduler": scheduler,
119
+ "text_encoder": text_encoder,
120
+ "tokenizer": tokenizer,
121
+ # We cannot run the Cosmos Guardrail for fast tests due to the large model size
122
+ "safety_checker": DummyCosmosSafetyChecker(),
123
+ }
124
+ return components
125
+
126
+ def get_dummy_inputs(self, device, seed=0):
127
+ if str(device).startswith("mps"):
128
+ generator = torch.manual_seed(seed)
129
+ else:
130
+ generator = torch.Generator(device=device).manual_seed(seed)
131
+
132
+ image_height = 32
133
+ image_width = 32
134
+ image = PIL.Image.new("RGB", (image_width, image_height))
135
+
136
+ inputs = {
137
+ "image": image,
138
+ "prompt": "dance monkey",
139
+ "negative_prompt": "bad quality",
140
+ "generator": generator,
141
+ "num_inference_steps": 2,
142
+ "guidance_scale": 3.0,
143
+ "height": image_height,
144
+ "width": image_width,
145
+ "num_frames": 9,
146
+ "max_sequence_length": 16,
147
+ "output_type": "pt",
148
+ }
149
+
150
+ return inputs
151
+
152
+ def test_inference(self):
153
+ device = "cpu"
154
+
155
+ components = self.get_dummy_components()
156
+ pipe = self.pipeline_class(**components)
157
+ pipe.to(device)
158
+ pipe.set_progress_bar_config(disable=None)
159
+
160
+ inputs = self.get_dummy_inputs(device)
161
+ video = pipe(**inputs).frames
162
+ generated_video = video[0]
163
+ self.assertEqual(generated_video.shape, (9, 3, 32, 32))
164
+
165
+ # fmt: off
166
+ expected_slice = torch.tensor([0.0, 0.8275, 0.7529, 0.7294, 0.0, 0.6, 1.0, 0.3804, 0.6667, 0.0863, 0.8784, 0.5922, 0.6627, 0.2784, 0.5725, 0.7765])
167
+ # fmt: on
168
+
169
+ generated_slice = generated_video.flatten()
170
+ generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
171
+ self.assertTrue(torch.allclose(generated_slice, expected_slice, atol=1e-3))
172
+
173
+ def test_components_function(self):
174
+ init_components = self.get_dummy_components()
175
+ init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
176
+ pipe = self.pipeline_class(**init_components)
177
+ self.assertTrue(hasattr(pipe, "components"))
178
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
179
+
180
+ def test_callback_inputs(self):
181
+ sig = inspect.signature(self.pipeline_class.__call__)
182
+ has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
183
+ has_callback_step_end = "callback_on_step_end" in sig.parameters
184
+
185
+ if not (has_callback_tensor_inputs and has_callback_step_end):
186
+ return
187
+
188
+ components = self.get_dummy_components()
189
+ pipe = self.pipeline_class(**components)
190
+ pipe = pipe.to(torch_device)
191
+ pipe.set_progress_bar_config(disable=None)
192
+ self.assertTrue(
193
+ hasattr(pipe, "_callback_tensor_inputs"),
194
+ f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
195
+ )
196
+
197
+ def callback_inputs_subset(pipe, i, t, callback_kwargs):
198
+ # iterate over callback args
199
+ for tensor_name, tensor_value in callback_kwargs.items():
200
+ # check that we're only passing in allowed tensor inputs
201
+ assert tensor_name in pipe._callback_tensor_inputs
202
+
203
+ return callback_kwargs
204
+
205
+ def callback_inputs_all(pipe, i, t, callback_kwargs):
206
+ for tensor_name in pipe._callback_tensor_inputs:
207
+ assert tensor_name in callback_kwargs
208
+
209
+ # iterate over callback args
210
+ for tensor_name, tensor_value in callback_kwargs.items():
211
+ # check that we're only passing in allowed tensor inputs
212
+ assert tensor_name in pipe._callback_tensor_inputs
213
+
214
+ return callback_kwargs
215
+
216
+ inputs = self.get_dummy_inputs(torch_device)
217
+
218
+ # Test passing in a subset
219
+ inputs["callback_on_step_end"] = callback_inputs_subset
220
+ inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
221
+ output = pipe(**inputs)[0]
222
+
223
+ # Test passing in a everything
224
+ inputs["callback_on_step_end"] = callback_inputs_all
225
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
226
+ output = pipe(**inputs)[0]
227
+
228
+ def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
229
+ is_last = i == (pipe.num_timesteps - 1)
230
+ if is_last:
231
+ callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
232
+ return callback_kwargs
233
+
234
+ inputs["callback_on_step_end"] = callback_inputs_change_tensor
235
+ inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
236
+ output = pipe(**inputs)[0]
237
+ assert output.abs().sum() < 1e10
238
+
239
+ def test_inference_batch_single_identical(self):
240
+ self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
241
+
242
+ def test_attention_slicing_forward_pass(
243
+ self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
244
+ ):
245
+ if not self.test_attention_slicing:
246
+ return
247
+
248
+ components = self.get_dummy_components()
249
+ for key in components:
250
+ if "text_encoder" in key and hasattr(components[key], "eval"):
251
+ components[key].eval()
252
+ pipe = self.pipeline_class(**components)
253
+ for component in pipe.components.values():
254
+ if hasattr(component, "set_default_attn_processor"):
255
+ component.set_default_attn_processor()
256
+ pipe.to(torch_device)
257
+ pipe.set_progress_bar_config(disable=None)
258
+
259
+ generator_device = "cpu"
260
+ inputs = self.get_dummy_inputs(generator_device)
261
+ output_without_slicing = pipe(**inputs)[0]
262
+
263
+ pipe.enable_attention_slicing(slice_size=1)
264
+ inputs = self.get_dummy_inputs(generator_device)
265
+ output_with_slicing1 = pipe(**inputs)[0]
266
+
267
+ pipe.enable_attention_slicing(slice_size=2)
268
+ inputs = self.get_dummy_inputs(generator_device)
269
+ output_with_slicing2 = pipe(**inputs)[0]
270
+
271
+ if test_max_difference:
272
+ max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
273
+ max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
274
+ self.assertLess(
275
+ max(max_diff1, max_diff2),
276
+ expected_max_diff,
277
+ "Attention slicing should not affect the inference results",
278
+ )
279
+
280
+ def test_vae_tiling(self, expected_diff_max: float = 0.2):
281
+ generator_device = "cpu"
282
+ components = self.get_dummy_components()
283
+
284
+ pipe = self.pipeline_class(**components)
285
+ pipe.to("cpu")
286
+ pipe.set_progress_bar_config(disable=None)
287
+
288
+ # Without tiling
289
+ inputs = self.get_dummy_inputs(generator_device)
290
+ inputs["height"] = inputs["width"] = 128
291
+ output_without_tiling = pipe(**inputs)[0]
292
+
293
+ # With tiling
294
+ pipe.vae.enable_tiling(
295
+ tile_sample_min_height=96,
296
+ tile_sample_min_width=96,
297
+ tile_sample_stride_height=64,
298
+ tile_sample_stride_width=64,
299
+ )
300
+ inputs = self.get_dummy_inputs(generator_device)
301
+ inputs["height"] = inputs["width"] = 128
302
+ output_with_tiling = pipe(**inputs)[0]
303
+
304
+ self.assertLess(
305
+ (to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
306
+ expected_diff_max,
307
+ "VAE tiling should not affect the inference results",
308
+ )
309
+
310
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
311
+ self.pipeline_class._optional_components.remove("safety_checker")
312
+ super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
313
+ self.pipeline_class._optional_components.append("safety_checker")
314
+
315
+ def test_serialization_with_variants(self):
316
+ components = self.get_dummy_components()
317
+ pipe = self.pipeline_class(**components)
318
+ model_components = [
319
+ component_name
320
+ for component_name, component in pipe.components.items()
321
+ if isinstance(component, torch.nn.Module)
322
+ ]
323
+ model_components.remove("safety_checker")
324
+ variant = "fp16"
325
+
326
+ with tempfile.TemporaryDirectory() as tmpdir:
327
+ pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
328
+
329
+ with open(f"{tmpdir}/model_index.json", "r") as f:
330
+ config = json.load(f)
331
+
332
+ for subfolder in os.listdir(tmpdir):
333
+ if not os.path.isfile(subfolder) and subfolder in model_components:
334
+ folder_path = os.path.join(tmpdir, subfolder)
335
+ is_folder = os.path.isdir(folder_path) and subfolder in config
336
+ assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
337
+
338
+ def test_torch_dtype_dict(self):
339
+ components = self.get_dummy_components()
340
+ if not components:
341
+ self.skipTest("No dummy components defined.")
342
+
343
+ pipe = self.pipeline_class(**components)
344
+
345
+ specified_key = next(iter(components.keys()))
346
+
347
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
348
+ pipe.save_pretrained(tmpdirname, safe_serialization=False)
349
+ torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
350
+ loaded_pipe = self.pipeline_class.from_pretrained(
351
+ tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
352
+ )
353
+
354
+ for name, component in loaded_pipe.components.items():
355
+ if name == "safety_checker":
356
+ continue
357
+ if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
358
+ expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
359
+ self.assertEqual(
360
+ component.dtype,
361
+ expected_dtype,
362
+ f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
363
+ )
364
+
365
+ @unittest.skip(
366
+ "The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
367
+ "a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
368
+ "too large and slow to run on CI."
369
+ )
370
+ def test_encode_prompt_works_in_isolation(self):
371
+ pass
diffusers/tests/pipelines/ddim/__init__.py ADDED
File without changes
diffusers/tests/pipelines/ddim/test_ddim.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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 unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ from diffusers import DDIMPipeline, DDIMScheduler, UNet2DModel
22
+
23
+ from ...testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
24
+ from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
25
+ from ..test_pipelines_common import PipelineTesterMixin
26
+
27
+
28
+ enable_full_determinism()
29
+
30
+
31
+ class DDIMPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
32
+ pipeline_class = DDIMPipeline
33
+ params = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
34
+ required_optional_params = PipelineTesterMixin.required_optional_params - {
35
+ "num_images_per_prompt",
36
+ "latents",
37
+ "callback",
38
+ "callback_steps",
39
+ }
40
+ batch_params = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
41
+
42
+ def get_dummy_components(self):
43
+ torch.manual_seed(0)
44
+ unet = UNet2DModel(
45
+ block_out_channels=(4, 8),
46
+ layers_per_block=1,
47
+ norm_num_groups=4,
48
+ sample_size=8,
49
+ in_channels=3,
50
+ out_channels=3,
51
+ down_block_types=("DownBlock2D", "AttnDownBlock2D"),
52
+ up_block_types=("AttnUpBlock2D", "UpBlock2D"),
53
+ )
54
+ scheduler = DDIMScheduler()
55
+ components = {"unet": unet, "scheduler": scheduler}
56
+ return components
57
+
58
+ def get_dummy_inputs(self, device, seed=0):
59
+ if str(device).startswith("mps"):
60
+ generator = torch.manual_seed(seed)
61
+ else:
62
+ generator = torch.Generator(device=device).manual_seed(seed)
63
+ inputs = {
64
+ "batch_size": 1,
65
+ "generator": generator,
66
+ "num_inference_steps": 2,
67
+ "output_type": "np",
68
+ }
69
+ return inputs
70
+
71
+ def test_inference(self):
72
+ device = "cpu"
73
+
74
+ components = self.get_dummy_components()
75
+ pipe = self.pipeline_class(**components)
76
+ pipe.to(device)
77
+ pipe.set_progress_bar_config(disable=None)
78
+
79
+ inputs = self.get_dummy_inputs(device)
80
+ image = pipe(**inputs).images
81
+ image_slice = image[0, -3:, -3:, -1]
82
+
83
+ self.assertEqual(image.shape, (1, 8, 8, 3))
84
+ expected_slice = np.array([0.0, 9.979e-01, 0.0, 9.999e-01, 9.986e-01, 9.991e-01, 7.106e-04, 0.0, 0.0])
85
+ max_diff = np.abs(image_slice.flatten() - expected_slice).max()
86
+ self.assertLessEqual(max_diff, 1e-3)
87
+
88
+ def test_dict_tuple_outputs_equivalent(self):
89
+ super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3)
90
+
91
+ def test_save_load_local(self):
92
+ super().test_save_load_local(expected_max_difference=3e-3)
93
+
94
+ def test_save_load_optional_components(self):
95
+ super().test_save_load_optional_components(expected_max_difference=3e-3)
96
+
97
+ def test_inference_batch_single_identical(self):
98
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
99
+
100
+
101
+ @slow
102
+ @require_torch_accelerator
103
+ class DDIMPipelineIntegrationTests(unittest.TestCase):
104
+ def test_inference_cifar10(self):
105
+ model_id = "google/ddpm-cifar10-32"
106
+
107
+ unet = UNet2DModel.from_pretrained(model_id)
108
+ scheduler = DDIMScheduler()
109
+
110
+ ddim = DDIMPipeline(unet=unet, scheduler=scheduler)
111
+ ddim.to(torch_device)
112
+ ddim.set_progress_bar_config(disable=None)
113
+
114
+ generator = torch.manual_seed(0)
115
+ image = ddim(generator=generator, eta=0.0, output_type="np").images
116
+
117
+ image_slice = image[0, -3:, -3:, -1]
118
+
119
+ assert image.shape == (1, 32, 32, 3)
120
+ expected_slice = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453])
121
+
122
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
123
+
124
+ def test_inference_ema_bedroom(self):
125
+ model_id = "google/ddpm-ema-bedroom-256"
126
+
127
+ unet = UNet2DModel.from_pretrained(model_id)
128
+ scheduler = DDIMScheduler.from_pretrained(model_id)
129
+
130
+ ddpm = DDIMPipeline(unet=unet, scheduler=scheduler)
131
+ ddpm.to(torch_device)
132
+ ddpm.set_progress_bar_config(disable=None)
133
+
134
+ generator = torch.manual_seed(0)
135
+ image = ddpm(generator=generator, output_type="np").images
136
+
137
+ image_slice = image[0, -3:, -3:, -1]
138
+
139
+ assert image.shape == (1, 256, 256, 3)
140
+ expected_slice = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069])
141
+
142
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
diffusers/tests/pipelines/ddpm/__init__.py ADDED
File without changes
diffusers/tests/pipelines/ddpm/test_ddpm.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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 unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ from diffusers import DDPMPipeline, DDPMScheduler, UNet2DModel
22
+
23
+ from ...testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
24
+
25
+
26
+ enable_full_determinism()
27
+
28
+
29
+ class DDPMPipelineFastTests(unittest.TestCase):
30
+ @property
31
+ def dummy_uncond_unet(self):
32
+ torch.manual_seed(0)
33
+ model = UNet2DModel(
34
+ block_out_channels=(4, 8),
35
+ layers_per_block=1,
36
+ norm_num_groups=4,
37
+ sample_size=8,
38
+ in_channels=3,
39
+ out_channels=3,
40
+ down_block_types=("DownBlock2D", "AttnDownBlock2D"),
41
+ up_block_types=("AttnUpBlock2D", "UpBlock2D"),
42
+ )
43
+ return model
44
+
45
+ def test_fast_inference(self):
46
+ device = "cpu"
47
+ unet = self.dummy_uncond_unet
48
+ scheduler = DDPMScheduler()
49
+
50
+ ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
51
+ ddpm.to(device)
52
+ ddpm.set_progress_bar_config(disable=None)
53
+
54
+ generator = torch.Generator(device=device).manual_seed(0)
55
+ image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
56
+
57
+ generator = torch.Generator(device=device).manual_seed(0)
58
+ image_from_tuple = ddpm(generator=generator, num_inference_steps=2, output_type="np", return_dict=False)[0]
59
+
60
+ image_slice = image[0, -3:, -3:, -1]
61
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
62
+
63
+ assert image.shape == (1, 8, 8, 3)
64
+ expected_slice = np.array([0.0, 0.9996672, 0.00329116, 1.0, 0.9995991, 1.0, 0.0060907, 0.00115037, 0.0])
65
+
66
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
67
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
68
+
69
+ def test_inference_predict_sample(self):
70
+ unet = self.dummy_uncond_unet
71
+ scheduler = DDPMScheduler(prediction_type="sample")
72
+
73
+ ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
74
+ ddpm.to(torch_device)
75
+ ddpm.set_progress_bar_config(disable=None)
76
+
77
+ generator = torch.manual_seed(0)
78
+ image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
79
+
80
+ generator = torch.manual_seed(0)
81
+ image_eps = ddpm(generator=generator, num_inference_steps=2, output_type="np")[0]
82
+
83
+ image_slice = image[0, -3:, -3:, -1]
84
+ image_eps_slice = image_eps[0, -3:, -3:, -1]
85
+
86
+ assert image.shape == (1, 8, 8, 3)
87
+ tolerance = 1e-2 if torch_device != "mps" else 3e-2
88
+ assert np.abs(image_slice.flatten() - image_eps_slice.flatten()).max() < tolerance
89
+
90
+
91
+ @slow
92
+ @require_torch_accelerator
93
+ class DDPMPipelineIntegrationTests(unittest.TestCase):
94
+ def test_inference_cifar10(self):
95
+ model_id = "google/ddpm-cifar10-32"
96
+
97
+ unet = UNet2DModel.from_pretrained(model_id)
98
+ scheduler = DDPMScheduler.from_pretrained(model_id)
99
+
100
+ ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
101
+ ddpm.to(torch_device)
102
+ ddpm.set_progress_bar_config(disable=None)
103
+
104
+ generator = torch.manual_seed(0)
105
+ image = ddpm(generator=generator, output_type="np").images
106
+
107
+ image_slice = image[0, -3:, -3:, -1]
108
+
109
+ assert image.shape == (1, 32, 32, 3)
110
+ expected_slice = np.array([0.4200, 0.3588, 0.1939, 0.3847, 0.3382, 0.2647, 0.4155, 0.3582, 0.3385])
111
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
diffusers/tests/pipelines/dit/test_dit.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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 unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+
22
+ from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DiTTransformer2DModel, DPMSolverMultistepScheduler
23
+ from diffusers.utils import is_xformers_available
24
+
25
+ from ...testing_utils import (
26
+ backend_empty_cache,
27
+ enable_full_determinism,
28
+ load_numpy,
29
+ nightly,
30
+ numpy_cosine_similarity_distance,
31
+ require_torch_accelerator,
32
+ torch_device,
33
+ )
34
+ from ..pipeline_params import (
35
+ CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
36
+ CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
37
+ )
38
+ from ..test_pipelines_common import PipelineTesterMixin
39
+
40
+
41
+ enable_full_determinism()
42
+
43
+
44
+ class DiTPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
45
+ pipeline_class = DiTPipeline
46
+ params = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
47
+ required_optional_params = PipelineTesterMixin.required_optional_params - {
48
+ "latents",
49
+ "num_images_per_prompt",
50
+ "callback",
51
+ "callback_steps",
52
+ }
53
+ batch_params = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
54
+
55
+ def get_dummy_components(self):
56
+ torch.manual_seed(0)
57
+ transformer = DiTTransformer2DModel(
58
+ sample_size=16,
59
+ num_layers=2,
60
+ patch_size=4,
61
+ attention_head_dim=8,
62
+ num_attention_heads=2,
63
+ in_channels=4,
64
+ out_channels=8,
65
+ attention_bias=True,
66
+ activation_fn="gelu-approximate",
67
+ num_embeds_ada_norm=1000,
68
+ norm_type="ada_norm_zero",
69
+ norm_elementwise_affine=False,
70
+ )
71
+ vae = AutoencoderKL()
72
+ scheduler = DDIMScheduler()
73
+ components = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler}
74
+ return components
75
+
76
+ def get_dummy_inputs(self, device, seed=0):
77
+ if str(device).startswith("mps"):
78
+ generator = torch.manual_seed(seed)
79
+ else:
80
+ generator = torch.Generator(device=device).manual_seed(seed)
81
+ inputs = {
82
+ "class_labels": [1],
83
+ "generator": generator,
84
+ "num_inference_steps": 2,
85
+ "output_type": "np",
86
+ }
87
+ return inputs
88
+
89
+ def test_inference(self):
90
+ device = "cpu"
91
+
92
+ components = self.get_dummy_components()
93
+ pipe = self.pipeline_class(**components)
94
+ pipe.to(device)
95
+ pipe.set_progress_bar_config(disable=None)
96
+
97
+ inputs = self.get_dummy_inputs(device)
98
+ image = pipe(**inputs).images
99
+ image_slice = image[0, -3:, -3:, -1]
100
+
101
+ self.assertEqual(image.shape, (1, 16, 16, 3))
102
+ expected_slice = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457])
103
+ max_diff = np.abs(image_slice.flatten() - expected_slice).max()
104
+ self.assertLessEqual(max_diff, 1e-3)
105
+
106
+ def test_inference_batch_single_identical(self):
107
+ self._test_inference_batch_single_identical(expected_max_diff=1e-3)
108
+
109
+ @unittest.skipIf(
110
+ torch_device != "cuda" or not is_xformers_available(),
111
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
112
+ )
113
+ def test_xformers_attention_forwardGenerator_pass(self):
114
+ self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
115
+
116
+
117
+ @nightly
118
+ @require_torch_accelerator
119
+ class DiTPipelineIntegrationTests(unittest.TestCase):
120
+ def setUp(self):
121
+ super().setUp()
122
+ gc.collect()
123
+ backend_empty_cache(torch_device)
124
+
125
+ def tearDown(self):
126
+ super().tearDown()
127
+ gc.collect()
128
+ backend_empty_cache(torch_device)
129
+
130
+ def test_dit_256(self):
131
+ generator = torch.manual_seed(0)
132
+
133
+ pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256")
134
+ pipe.to(torch_device)
135
+
136
+ words = ["vase", "umbrella", "white shark", "white wolf"]
137
+ ids = pipe.get_label_ids(words)
138
+
139
+ images = pipe(ids, generator=generator, num_inference_steps=40, output_type="np").images
140
+
141
+ for word, image in zip(words, images):
142
+ expected_image = load_numpy(
143
+ f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy"
144
+ )
145
+ assert np.abs((expected_image - image).max()) < 1e-2
146
+
147
+ def test_dit_512(self):
148
+ pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512")
149
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
150
+ pipe.to(torch_device)
151
+
152
+ words = ["vase", "umbrella"]
153
+ ids = pipe.get_label_ids(words)
154
+
155
+ generator = torch.manual_seed(0)
156
+ images = pipe(ids, generator=generator, num_inference_steps=25, output_type="np").images
157
+
158
+ for word, image in zip(words, images):
159
+ expected_image = load_numpy(
160
+ f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}_512.npy"
161
+ )
162
+
163
+ expected_slice = expected_image.flatten()
164
+ output_slice = image.flatten()
165
+
166
+ assert numpy_cosine_similarity_distance(expected_slice, output_slice) < 1e-2
diffusers/tests/pipelines/flux/__init__.py ADDED
File without changes
diffusers/tests/pipelines/flux/test_pipeline_flux.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import unittest
3
+
4
+ import numpy as np
5
+ import torch
6
+ from huggingface_hub import hf_hub_download
7
+ from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
8
+
9
+ from diffusers import (
10
+ AutoencoderKL,
11
+ FasterCacheConfig,
12
+ FlowMatchEulerDiscreteScheduler,
13
+ FluxPipeline,
14
+ FluxTransformer2DModel,
15
+ )
16
+
17
+ from ...testing_utils import (
18
+ Expectations,
19
+ backend_empty_cache,
20
+ nightly,
21
+ numpy_cosine_similarity_distance,
22
+ require_big_accelerator,
23
+ slow,
24
+ torch_device,
25
+ )
26
+ from ..test_pipelines_common import (
27
+ FasterCacheTesterMixin,
28
+ FirstBlockCacheTesterMixin,
29
+ FluxIPAdapterTesterMixin,
30
+ MagCacheTesterMixin,
31
+ PipelineTesterMixin,
32
+ PyramidAttentionBroadcastTesterMixin,
33
+ TaylorSeerCacheTesterMixin,
34
+ check_qkv_fused_layers_exist,
35
+ )
36
+
37
+
38
+ class FluxPipelineFastTests(
39
+ PipelineTesterMixin,
40
+ FluxIPAdapterTesterMixin,
41
+ PyramidAttentionBroadcastTesterMixin,
42
+ FasterCacheTesterMixin,
43
+ FirstBlockCacheTesterMixin,
44
+ TaylorSeerCacheTesterMixin,
45
+ MagCacheTesterMixin,
46
+ unittest.TestCase,
47
+ ):
48
+ pipeline_class = FluxPipeline
49
+ params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
50
+ batch_params = frozenset(["prompt"])
51
+
52
+ # there is no xformers processor for Flux
53
+ test_xformers_attention = False
54
+ test_layerwise_casting = True
55
+ test_group_offloading = True
56
+
57
+ faster_cache_config = FasterCacheConfig(
58
+ spatial_attention_block_skip_range=2,
59
+ spatial_attention_timestep_skip_range=(-1, 901),
60
+ unconditional_batch_skip_range=2,
61
+ attention_weight_callback=lambda _: 0.5,
62
+ is_guidance_distilled=True,
63
+ )
64
+
65
+ def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
66
+ torch.manual_seed(0)
67
+ transformer = FluxTransformer2DModel(
68
+ patch_size=1,
69
+ in_channels=4,
70
+ num_layers=num_layers,
71
+ num_single_layers=num_single_layers,
72
+ attention_head_dim=16,
73
+ num_attention_heads=2,
74
+ joint_attention_dim=32,
75
+ pooled_projection_dim=32,
76
+ axes_dims_rope=[4, 4, 8],
77
+ )
78
+ clip_text_encoder_config = CLIPTextConfig(
79
+ bos_token_id=0,
80
+ eos_token_id=2,
81
+ hidden_size=32,
82
+ intermediate_size=37,
83
+ layer_norm_eps=1e-05,
84
+ num_attention_heads=4,
85
+ num_hidden_layers=5,
86
+ pad_token_id=1,
87
+ vocab_size=1000,
88
+ hidden_act="gelu",
89
+ projection_dim=32,
90
+ )
91
+
92
+ torch.manual_seed(0)
93
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
94
+
95
+ torch.manual_seed(0)
96
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
97
+ text_encoder_2 = T5EncoderModel(config)
98
+
99
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
100
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
101
+
102
+ torch.manual_seed(0)
103
+ vae = AutoencoderKL(
104
+ sample_size=32,
105
+ in_channels=3,
106
+ out_channels=3,
107
+ block_out_channels=(4,),
108
+ layers_per_block=1,
109
+ latent_channels=1,
110
+ norm_num_groups=1,
111
+ use_quant_conv=False,
112
+ use_post_quant_conv=False,
113
+ shift_factor=0.0609,
114
+ scaling_factor=1.5035,
115
+ )
116
+
117
+ scheduler = FlowMatchEulerDiscreteScheduler()
118
+
119
+ return {
120
+ "scheduler": scheduler,
121
+ "text_encoder": text_encoder,
122
+ "text_encoder_2": text_encoder_2,
123
+ "tokenizer": tokenizer,
124
+ "tokenizer_2": tokenizer_2,
125
+ "transformer": transformer,
126
+ "vae": vae,
127
+ "image_encoder": None,
128
+ "feature_extractor": None,
129
+ }
130
+
131
+ def get_dummy_inputs(self, device, seed=0):
132
+ if str(device).startswith("mps"):
133
+ generator = torch.manual_seed(seed)
134
+ else:
135
+ generator = torch.Generator(device="cpu").manual_seed(seed)
136
+
137
+ inputs = {
138
+ "prompt": "A painting of a squirrel eating a burger",
139
+ "generator": generator,
140
+ "num_inference_steps": 2,
141
+ "guidance_scale": 5.0,
142
+ "height": 8,
143
+ "width": 8,
144
+ "max_sequence_length": 48,
145
+ "output_type": "np",
146
+ }
147
+ return inputs
148
+
149
+ def test_flux_different_prompts(self):
150
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
151
+
152
+ inputs = self.get_dummy_inputs(torch_device)
153
+ output_same_prompt = pipe(**inputs).images[0]
154
+
155
+ inputs = self.get_dummy_inputs(torch_device)
156
+ inputs["prompt_2"] = "a different prompt"
157
+ output_different_prompts = pipe(**inputs).images[0]
158
+
159
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
160
+
161
+ # Outputs should be different here
162
+ # For some reasons, they don't show large differences
163
+ self.assertGreater(max_diff, 1e-6, "Outputs should be different for different prompts.")
164
+
165
+ def test_fused_qkv_projections(self):
166
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
167
+ components = self.get_dummy_components()
168
+ pipe = self.pipeline_class(**components)
169
+ pipe = pipe.to(device)
170
+ pipe.set_progress_bar_config(disable=None)
171
+
172
+ inputs = self.get_dummy_inputs(device)
173
+ image = pipe(**inputs).images
174
+ original_image_slice = image[0, -3:, -3:, -1]
175
+
176
+ # TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
177
+ # to the pipeline level.
178
+ pipe.transformer.fuse_qkv_projections()
179
+ self.assertTrue(
180
+ check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
181
+ ("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
182
+ )
183
+
184
+ inputs = self.get_dummy_inputs(device)
185
+ image = pipe(**inputs).images
186
+ image_slice_fused = image[0, -3:, -3:, -1]
187
+
188
+ pipe.transformer.unfuse_qkv_projections()
189
+ inputs = self.get_dummy_inputs(device)
190
+ image = pipe(**inputs).images
191
+ image_slice_disabled = image[0, -3:, -3:, -1]
192
+
193
+ self.assertTrue(
194
+ np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3),
195
+ ("Fusion of QKV projections shouldn't affect the outputs."),
196
+ )
197
+ self.assertTrue(
198
+ np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3),
199
+ ("Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."),
200
+ )
201
+ self.assertTrue(
202
+ np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2),
203
+ ("Original outputs should match when fused QKV projections are disabled."),
204
+ )
205
+
206
+ def test_flux_image_output_shape(self):
207
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
208
+ inputs = self.get_dummy_inputs(torch_device)
209
+
210
+ height_width_pairs = [(32, 32), (72, 57)]
211
+ for height, width in height_width_pairs:
212
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
213
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
214
+
215
+ inputs.update({"height": height, "width": width})
216
+ image = pipe(**inputs).images[0]
217
+ output_height, output_width, _ = image.shape
218
+ self.assertEqual(
219
+ (output_height, output_width),
220
+ (expected_height, expected_width),
221
+ f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
222
+ )
223
+
224
+ def test_flux_true_cfg(self):
225
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
226
+ inputs = self.get_dummy_inputs(torch_device)
227
+ inputs.pop("generator")
228
+
229
+ no_true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
230
+ inputs["negative_prompt"] = "bad quality"
231
+ inputs["true_cfg_scale"] = 2.0
232
+ true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
233
+ self.assertFalse(
234
+ np.allclose(no_true_cfg_out, true_cfg_out), "Outputs should be different when true_cfg_scale is set."
235
+ )
236
+
237
+
238
+ @nightly
239
+ @require_big_accelerator
240
+ class FluxPipelineSlowTests(unittest.TestCase):
241
+ pipeline_class = FluxPipeline
242
+ repo_id = "black-forest-labs/FLUX.1-schnell"
243
+
244
+ def setUp(self):
245
+ super().setUp()
246
+ gc.collect()
247
+ backend_empty_cache(torch_device)
248
+
249
+ def tearDown(self):
250
+ super().tearDown()
251
+ gc.collect()
252
+ backend_empty_cache(torch_device)
253
+
254
+ def get_inputs(self, device, seed=0):
255
+ generator = torch.Generator(device="cpu").manual_seed(seed)
256
+
257
+ prompt_embeds = torch.load(
258
+ hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
259
+ ).to(torch_device)
260
+ pooled_prompt_embeds = torch.load(
261
+ hf_hub_download(
262
+ repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
263
+ )
264
+ ).to(torch_device)
265
+ return {
266
+ "prompt_embeds": prompt_embeds,
267
+ "pooled_prompt_embeds": pooled_prompt_embeds,
268
+ "num_inference_steps": 2,
269
+ "guidance_scale": 0.0,
270
+ "max_sequence_length": 256,
271
+ "output_type": "np",
272
+ "generator": generator,
273
+ }
274
+
275
+ def test_flux_inference(self):
276
+ pipe = self.pipeline_class.from_pretrained(
277
+ self.repo_id, torch_dtype=torch.bfloat16, text_encoder=None, text_encoder_2=None
278
+ ).to(torch_device)
279
+
280
+ inputs = self.get_inputs(torch_device)
281
+
282
+ image = pipe(**inputs).images[0]
283
+ image_slice = image[0, :10, :10]
284
+ # fmt: off
285
+
286
+ expected_slices = Expectations(
287
+ {
288
+ ("cuda", None): np.array([0.3242, 0.3203, 0.3164, 0.3164, 0.3125, 0.3125, 0.3281, 0.3242, 0.3203, 0.3301, 0.3262, 0.3242, 0.3281, 0.3242, 0.3203, 0.3262, 0.3262, 0.3164, 0.3262, 0.3281, 0.3184, 0.3281, 0.3281, 0.3203, 0.3281, 0.3281, 0.3164, 0.3320, 0.3320, 0.3203], dtype=np.float32,),
289
+ ("xpu", 3): np.array([0.3301, 0.3281, 0.3359, 0.3203, 0.3203, 0.3281, 0.3281, 0.3301, 0.3340, 0.3281, 0.3320, 0.3359, 0.3281, 0.3301, 0.3320, 0.3242, 0.3301, 0.3281, 0.3242, 0.3320, 0.3320, 0.3281, 0.3320, 0.3320, 0.3262, 0.3320, 0.3301, 0.3301, 0.3359, 0.3320], dtype=np.float32,),
290
+ }
291
+ )
292
+ expected_slice = expected_slices.get_expectation()
293
+ # fmt: on
294
+
295
+ max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
296
+ self.assertLess(
297
+ max_diff, 1e-4, f"Image slice is different from expected slice: {image_slice} != {expected_slice}"
298
+ )
299
+
300
+
301
+ @slow
302
+ @require_big_accelerator
303
+ class FluxIPAdapterPipelineSlowTests(unittest.TestCase):
304
+ pipeline_class = FluxPipeline
305
+ repo_id = "black-forest-labs/FLUX.1-dev"
306
+ image_encoder_pretrained_model_name_or_path = "openai/clip-vit-large-patch14"
307
+ weight_name = "ip_adapter.safetensors"
308
+ ip_adapter_repo_id = "XLabs-AI/flux-ip-adapter"
309
+
310
+ def setUp(self):
311
+ super().setUp()
312
+ gc.collect()
313
+ backend_empty_cache(torch_device)
314
+
315
+ def tearDown(self):
316
+ super().tearDown()
317
+ gc.collect()
318
+ backend_empty_cache(torch_device)
319
+
320
+ def get_inputs(self, device, seed=0):
321
+ if str(device).startswith("mps"):
322
+ generator = torch.manual_seed(seed)
323
+ else:
324
+ generator = torch.Generator(device="cpu").manual_seed(seed)
325
+
326
+ prompt_embeds = torch.load(
327
+ hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
328
+ )
329
+ pooled_prompt_embeds = torch.load(
330
+ hf_hub_download(
331
+ repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
332
+ )
333
+ )
334
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
335
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
336
+ ip_adapter_image = np.zeros((1024, 1024, 3), dtype=np.uint8)
337
+ return {
338
+ "prompt_embeds": prompt_embeds,
339
+ "pooled_prompt_embeds": pooled_prompt_embeds,
340
+ "negative_prompt_embeds": negative_prompt_embeds,
341
+ "negative_pooled_prompt_embeds": negative_pooled_prompt_embeds,
342
+ "ip_adapter_image": ip_adapter_image,
343
+ "num_inference_steps": 2,
344
+ "guidance_scale": 3.5,
345
+ "true_cfg_scale": 4.0,
346
+ "max_sequence_length": 256,
347
+ "output_type": "np",
348
+ "generator": generator,
349
+ }
350
+
351
+ def test_flux_ip_adapter_inference(self):
352
+ pipe = self.pipeline_class.from_pretrained(
353
+ self.repo_id, torch_dtype=torch.bfloat16, text_encoder=None, text_encoder_2=None
354
+ )
355
+ pipe.load_ip_adapter(
356
+ self.ip_adapter_repo_id,
357
+ weight_name=self.weight_name,
358
+ image_encoder_pretrained_model_name_or_path=self.image_encoder_pretrained_model_name_or_path,
359
+ )
360
+ pipe.set_ip_adapter_scale(1.0)
361
+ pipe.enable_model_cpu_offload()
362
+
363
+ inputs = self.get_inputs(torch_device)
364
+
365
+ image = pipe(**inputs).images[0]
366
+ image_slice = image[0, :10, :10]
367
+
368
+ # fmt: off
369
+ expected_slice = np.array(
370
+ [0.1855, 0.1680, 0.1406, 0.1953, 0.1699, 0.1465, 0.2012, 0.1738, 0.1484, 0.2051, 0.1797, 0.1523, 0.2012, 0.1719, 0.1445, 0.2070, 0.1777, 0.1465, 0.2090, 0.1836, 0.1484, 0.2129, 0.1875, 0.1523, 0.2090, 0.1816, 0.1484, 0.2110, 0.1836, 0.1543],
371
+ dtype=np.float32,
372
+ )
373
+ # fmt: on
374
+
375
+ max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
376
+ self.assertLess(
377
+ max_diff, 1e-4, f"Image slice is different from expected slice: {image_slice} != {expected_slice}"
378
+ )
diffusers/tests/pipelines/flux/test_pipeline_flux_control.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image
6
+ from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
7
+
8
+ from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxControlPipeline, FluxTransformer2DModel
9
+
10
+ from ...testing_utils import torch_device
11
+ from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
12
+
13
+
14
+ class FluxControlPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
15
+ pipeline_class = FluxControlPipeline
16
+ params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
17
+ batch_params = frozenset(["prompt"])
18
+
19
+ # there is no xformers processor for Flux
20
+ test_xformers_attention = False
21
+ test_layerwise_casting = True
22
+ test_group_offloading = True
23
+
24
+ def get_dummy_components(self):
25
+ torch.manual_seed(0)
26
+ transformer = FluxTransformer2DModel(
27
+ patch_size=1,
28
+ in_channels=8,
29
+ out_channels=4,
30
+ num_layers=1,
31
+ num_single_layers=1,
32
+ attention_head_dim=16,
33
+ num_attention_heads=2,
34
+ joint_attention_dim=32,
35
+ pooled_projection_dim=32,
36
+ axes_dims_rope=[4, 4, 8],
37
+ )
38
+ clip_text_encoder_config = CLIPTextConfig(
39
+ bos_token_id=0,
40
+ eos_token_id=2,
41
+ hidden_size=32,
42
+ intermediate_size=37,
43
+ layer_norm_eps=1e-05,
44
+ num_attention_heads=4,
45
+ num_hidden_layers=5,
46
+ pad_token_id=1,
47
+ vocab_size=1000,
48
+ hidden_act="gelu",
49
+ projection_dim=32,
50
+ )
51
+
52
+ torch.manual_seed(0)
53
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
54
+
55
+ torch.manual_seed(0)
56
+ config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
57
+ text_encoder_2 = T5EncoderModel(config)
58
+
59
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
60
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
61
+
62
+ torch.manual_seed(0)
63
+ vae = AutoencoderKL(
64
+ sample_size=32,
65
+ in_channels=3,
66
+ out_channels=3,
67
+ block_out_channels=(4,),
68
+ layers_per_block=1,
69
+ latent_channels=1,
70
+ norm_num_groups=1,
71
+ use_quant_conv=False,
72
+ use_post_quant_conv=False,
73
+ shift_factor=0.0609,
74
+ scaling_factor=1.5035,
75
+ )
76
+
77
+ scheduler = FlowMatchEulerDiscreteScheduler()
78
+
79
+ return {
80
+ "scheduler": scheduler,
81
+ "text_encoder": text_encoder,
82
+ "text_encoder_2": text_encoder_2,
83
+ "tokenizer": tokenizer,
84
+ "tokenizer_2": tokenizer_2,
85
+ "transformer": transformer,
86
+ "vae": vae,
87
+ }
88
+
89
+ def get_dummy_inputs(self, device, seed=0):
90
+ if str(device).startswith("mps"):
91
+ generator = torch.manual_seed(seed)
92
+ else:
93
+ generator = torch.Generator(device="cpu").manual_seed(seed)
94
+
95
+ control_image = Image.new("RGB", (16, 16), 0)
96
+
97
+ inputs = {
98
+ "prompt": "A painting of a squirrel eating a burger",
99
+ "control_image": control_image,
100
+ "generator": generator,
101
+ "num_inference_steps": 2,
102
+ "guidance_scale": 5.0,
103
+ "height": 8,
104
+ "width": 8,
105
+ "max_sequence_length": 48,
106
+ "output_type": "np",
107
+ }
108
+ return inputs
109
+
110
+ def test_flux_different_prompts(self):
111
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
112
+
113
+ inputs = self.get_dummy_inputs(torch_device)
114
+ output_same_prompt = pipe(**inputs).images[0]
115
+
116
+ inputs = self.get_dummy_inputs(torch_device)
117
+ inputs["prompt_2"] = "a different prompt"
118
+ output_different_prompts = pipe(**inputs).images[0]
119
+
120
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
121
+
122
+ # Outputs should be different here
123
+ # For some reasons, they don't show large differences
124
+ assert max_diff > 1e-6
125
+
126
+ def test_fused_qkv_projections(self):
127
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
128
+ components = self.get_dummy_components()
129
+ pipe = self.pipeline_class(**components)
130
+ pipe = pipe.to(device)
131
+ pipe.set_progress_bar_config(disable=None)
132
+
133
+ inputs = self.get_dummy_inputs(device)
134
+ image = pipe(**inputs).images
135
+ original_image_slice = image[0, -3:, -3:, -1]
136
+
137
+ # TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
138
+ # to the pipeline level.
139
+ pipe.transformer.fuse_qkv_projections()
140
+ self.assertTrue(
141
+ check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
142
+ ("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
143
+ )
144
+
145
+ inputs = self.get_dummy_inputs(device)
146
+ image = pipe(**inputs).images
147
+ image_slice_fused = image[0, -3:, -3:, -1]
148
+
149
+ pipe.transformer.unfuse_qkv_projections()
150
+ inputs = self.get_dummy_inputs(device)
151
+ image = pipe(**inputs).images
152
+ image_slice_disabled = image[0, -3:, -3:, -1]
153
+
154
+ assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
155
+ "Fusion of QKV projections shouldn't affect the outputs."
156
+ )
157
+ assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
158
+ "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
159
+ )
160
+ assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
161
+ "Original outputs should match when fused QKV projections are disabled."
162
+ )
163
+
164
+ def test_flux_image_output_shape(self):
165
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
166
+ inputs = self.get_dummy_inputs(torch_device)
167
+
168
+ height_width_pairs = [(32, 32), (72, 57)]
169
+ for height, width in height_width_pairs:
170
+ expected_height = height - height % (pipe.vae_scale_factor * 2)
171
+ expected_width = width - width % (pipe.vae_scale_factor * 2)
172
+
173
+ inputs.update({"height": height, "width": width})
174
+ image = pipe(**inputs).images[0]
175
+ output_height, output_width, _ = image.shape
176
+ assert (output_height, output_width) == (expected_height, expected_width)