AdithyaSK HF Staff commited on
Commit
98702f1
·
verified ·
1 Parent(s): 9eeaf95

Stage Harbor release files 32001-32500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen/test_stable_diffusion_gligen.py +175 -0
  2. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen_text_image/__init__.py +0 -0
  3. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen_text_image/test_stable_diffusion_gligen_text_image.py +215 -0
  4. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_image_variation/__init__.py +0 -0
  5. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_image_variation/test_stable_diffusion_image_variation.py +345 -0
  6. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_k_diffusion/__init__.py +0 -0
  7. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_k_diffusion/test_stable_diffusion_k_diffusion.py +147 -0
  8. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_ldm3d/__init__.py +0 -0
  9. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_ldm3d/test_stable_diffusion_ldm3d.py +326 -0
  10. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_panorama/__init__.py +0 -0
  11. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_panorama/test_stable_diffusion_panorama.py +444 -0
  12. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_safe/__init__.py +0 -0
  13. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_safe/test_safe_diffusion.py +497 -0
  14. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_sag/__init__.py +0 -0
  15. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_sag/test_stable_diffusion_sag.py +245 -0
  16. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/__init__.py +0 -0
  17. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl.py +975 -0
  18. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_adapter.py +671 -0
  19. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_img2img.py +716 -0
  20. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_inpaint.py +826 -0
  21. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_instruction_pix2pix.py +189 -0
  22. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_k_diffusion.py +178 -0
  23. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/__init__.py +0 -0
  24. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/test_stable_unclip.py +257 -0
  25. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/test_stable_unclip_img2img.py +313 -0
  26. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_video_diffusion/__init__.py +0 -0
  27. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_video_diffusion/test_stable_video_diffusion.py +561 -0
  28. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipeline_utils.py +951 -0
  29. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines.py +0 -0
  30. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_auto.py +574 -0
  31. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_combined.py +128 -0
  32. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_common.py +0 -0
  33. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_flax.py +260 -0
  34. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_onnx_common.py +12 -0
  35. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/__init__.py +0 -0
  36. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video.py +231 -0
  37. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video_zero.py +62 -0
  38. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video_zero_sdxl.py +403 -0
  39. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_video_to_video.py +229 -0
  40. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/__init__.py +0 -0
  41. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/test_unclip.py +523 -0
  42. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/test_unclip_image_variation.py +540 -0
  43. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unidiffuser/__init__.py +0 -0
  44. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unidiffuser/test_unidiffuser.py +764 -0
  45. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/__init__.py +0 -0
  46. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/test_pipeline_visualcloze_combined.py +344 -0
  47. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/test_pipeline_visualcloze_generation.py +312 -0
  48. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/__init__.py +0 -0
  49. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/test_wan.py +156 -0
  50. tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/test_wan_image_to_video.py +249 -0
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen/test_stable_diffusion_gligen.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers import (
23
+ AutoencoderKL,
24
+ DDIMScheduler,
25
+ EulerAncestralDiscreteScheduler,
26
+ StableDiffusionGLIGENPipeline,
27
+ UNet2DConditionModel,
28
+ )
29
+ from diffusers.utils.testing_utils import enable_full_determinism
30
+
31
+ from ..pipeline_params import (
32
+ TEXT_TO_IMAGE_BATCH_PARAMS,
33
+ TEXT_TO_IMAGE_IMAGE_PARAMS,
34
+ TEXT_TO_IMAGE_PARAMS,
35
+ )
36
+ from ..test_pipelines_common import (
37
+ PipelineFromPipeTesterMixin,
38
+ PipelineKarrasSchedulerTesterMixin,
39
+ PipelineLatentTesterMixin,
40
+ PipelineTesterMixin,
41
+ )
42
+
43
+
44
+ enable_full_determinism()
45
+
46
+
47
+ class GligenPipelineFastTests(
48
+ PipelineLatentTesterMixin,
49
+ PipelineKarrasSchedulerTesterMixin,
50
+ PipelineTesterMixin,
51
+ PipelineFromPipeTesterMixin,
52
+ unittest.TestCase,
53
+ ):
54
+ pipeline_class = StableDiffusionGLIGENPipeline
55
+ params = TEXT_TO_IMAGE_PARAMS | {"gligen_phrases", "gligen_boxes"}
56
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
57
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
58
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
59
+
60
+ def get_dummy_components(self):
61
+ torch.manual_seed(0)
62
+ unet = UNet2DConditionModel(
63
+ block_out_channels=(32, 64),
64
+ layers_per_block=2,
65
+ sample_size=32,
66
+ in_channels=4,
67
+ out_channels=4,
68
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
69
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
70
+ cross_attention_dim=32,
71
+ attention_type="gated",
72
+ )
73
+ # unet.position_net = PositionNet(32,32)
74
+ scheduler = DDIMScheduler(
75
+ beta_start=0.00085,
76
+ beta_end=0.012,
77
+ beta_schedule="scaled_linear",
78
+ clip_sample=False,
79
+ set_alpha_to_one=False,
80
+ )
81
+ torch.manual_seed(0)
82
+ vae = AutoencoderKL(
83
+ block_out_channels=[32, 64],
84
+ in_channels=3,
85
+ out_channels=3,
86
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
87
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
88
+ latent_channels=4,
89
+ sample_size=128,
90
+ )
91
+ torch.manual_seed(0)
92
+ text_encoder_config = CLIPTextConfig(
93
+ bos_token_id=0,
94
+ eos_token_id=2,
95
+ hidden_size=32,
96
+ intermediate_size=37,
97
+ layer_norm_eps=1e-05,
98
+ num_attention_heads=4,
99
+ num_hidden_layers=5,
100
+ pad_token_id=1,
101
+ vocab_size=1000,
102
+ )
103
+ text_encoder = CLIPTextModel(text_encoder_config)
104
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
105
+
106
+ components = {
107
+ "unet": unet,
108
+ "scheduler": scheduler,
109
+ "vae": vae,
110
+ "text_encoder": text_encoder,
111
+ "tokenizer": tokenizer,
112
+ "safety_checker": None,
113
+ "feature_extractor": None,
114
+ }
115
+ return components
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=device).manual_seed(seed)
122
+ inputs = {
123
+ "prompt": "A modern livingroom",
124
+ "generator": generator,
125
+ "num_inference_steps": 2,
126
+ "guidance_scale": 6.0,
127
+ "gligen_phrases": ["a birthday cake"],
128
+ "gligen_boxes": [[0.2676, 0.6088, 0.4773, 0.7183]],
129
+ "output_type": "np",
130
+ }
131
+ return inputs
132
+
133
+ def test_stable_diffusion_gligen_default_case(self):
134
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
135
+ components = self.get_dummy_components()
136
+ sd_pipe = StableDiffusionGLIGENPipeline(**components)
137
+ sd_pipe = sd_pipe.to(device)
138
+ sd_pipe.set_progress_bar_config(disable=None)
139
+
140
+ inputs = self.get_dummy_inputs(device)
141
+ image = sd_pipe(**inputs).images
142
+ image_slice = image[0, -3:, -3:, -1]
143
+
144
+ assert image.shape == (1, 64, 64, 3)
145
+ expected_slice = np.array([0.5069, 0.5561, 0.4577, 0.4792, 0.5203, 0.4089, 0.5039, 0.4919, 0.4499])
146
+
147
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
148
+
149
+ def test_stable_diffusion_gligen_k_euler_ancestral(self):
150
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
151
+ components = self.get_dummy_components()
152
+ sd_pipe = StableDiffusionGLIGENPipeline(**components)
153
+ sd_pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(sd_pipe.scheduler.config)
154
+ sd_pipe = sd_pipe.to(device)
155
+ sd_pipe.set_progress_bar_config(disable=None)
156
+
157
+ inputs = self.get_dummy_inputs(device)
158
+ output = sd_pipe(**inputs)
159
+ image = output.images
160
+ image_slice = image[0, -3:, -3:, -1]
161
+
162
+ assert image.shape == (1, 64, 64, 3)
163
+ expected_slice = np.array([0.425, 0.494, 0.429, 0.469, 0.525, 0.417, 0.533, 0.5, 0.47])
164
+
165
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
166
+
167
+ def test_attention_slicing_forward_pass(self):
168
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
169
+
170
+ def test_inference_batch_single_identical(self):
171
+ super().test_inference_batch_single_identical(batch_size=3, expected_max_diff=3e-3)
172
+
173
+ @unittest.skip("Test not supported as tokenizer is used for parsing bounding boxes.")
174
+ def test_encode_prompt_works_in_isolation(self):
175
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen_text_image/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_gligen_text_image/test_stable_diffusion_gligen_text_image.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import (
21
+ CLIPProcessor,
22
+ CLIPTextConfig,
23
+ CLIPTextModel,
24
+ CLIPTokenizer,
25
+ CLIPVisionConfig,
26
+ CLIPVisionModelWithProjection,
27
+ )
28
+
29
+ from diffusers import (
30
+ AutoencoderKL,
31
+ DDIMScheduler,
32
+ EulerAncestralDiscreteScheduler,
33
+ StableDiffusionGLIGENTextImagePipeline,
34
+ UNet2DConditionModel,
35
+ )
36
+ from diffusers.pipelines.stable_diffusion import CLIPImageProjection
37
+ from diffusers.utils import load_image
38
+ from diffusers.utils.testing_utils import enable_full_determinism, torch_device
39
+
40
+ from ..pipeline_params import (
41
+ TEXT_TO_IMAGE_BATCH_PARAMS,
42
+ TEXT_TO_IMAGE_IMAGE_PARAMS,
43
+ TEXT_TO_IMAGE_PARAMS,
44
+ )
45
+ from ..test_pipelines_common import (
46
+ PipelineFromPipeTesterMixin,
47
+ PipelineKarrasSchedulerTesterMixin,
48
+ PipelineLatentTesterMixin,
49
+ PipelineTesterMixin,
50
+ )
51
+
52
+
53
+ enable_full_determinism()
54
+
55
+
56
+ class GligenTextImagePipelineFastTests(
57
+ PipelineLatentTesterMixin,
58
+ PipelineKarrasSchedulerTesterMixin,
59
+ PipelineTesterMixin,
60
+ PipelineFromPipeTesterMixin,
61
+ unittest.TestCase,
62
+ ):
63
+ pipeline_class = StableDiffusionGLIGENTextImagePipeline
64
+ params = TEXT_TO_IMAGE_PARAMS | {"gligen_phrases", "gligen_images", "gligen_boxes"}
65
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
66
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
67
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
68
+
69
+ supports_dduf = False
70
+
71
+ def get_dummy_components(self):
72
+ torch.manual_seed(0)
73
+ unet = UNet2DConditionModel(
74
+ block_out_channels=(32, 64),
75
+ layers_per_block=2,
76
+ sample_size=32,
77
+ in_channels=4,
78
+ out_channels=4,
79
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
80
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
81
+ cross_attention_dim=32,
82
+ attention_type="gated-text-image",
83
+ )
84
+ # unet.position_net = PositionNet(32,32)
85
+ scheduler = DDIMScheduler(
86
+ beta_start=0.00085,
87
+ beta_end=0.012,
88
+ beta_schedule="scaled_linear",
89
+ clip_sample=False,
90
+ set_alpha_to_one=False,
91
+ )
92
+ torch.manual_seed(0)
93
+ vae = AutoencoderKL(
94
+ block_out_channels=[32, 64],
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
+ sample_size=128,
101
+ )
102
+ torch.manual_seed(0)
103
+ text_encoder_config = CLIPTextConfig(
104
+ bos_token_id=0,
105
+ eos_token_id=2,
106
+ hidden_size=32,
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
+
117
+ image_encoder_config = CLIPVisionConfig(
118
+ hidden_size=32,
119
+ projection_dim=32,
120
+ intermediate_size=37,
121
+ layer_norm_eps=1e-05,
122
+ num_attention_heads=4,
123
+ num_hidden_layers=5,
124
+ )
125
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
126
+ processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
127
+
128
+ image_project = CLIPImageProjection(hidden_size=32)
129
+
130
+ components = {
131
+ "unet": unet,
132
+ "scheduler": scheduler,
133
+ "vae": vae,
134
+ "text_encoder": text_encoder,
135
+ "tokenizer": tokenizer,
136
+ "safety_checker": None,
137
+ "feature_extractor": None,
138
+ "image_encoder": image_encoder,
139
+ "image_project": image_project,
140
+ "processor": processor,
141
+ }
142
+ return components
143
+
144
+ def get_dummy_inputs(self, device, seed=0):
145
+ if str(device).startswith("mps"):
146
+ generator = torch.manual_seed(seed)
147
+ else:
148
+ generator = torch.Generator(device=device).manual_seed(seed)
149
+
150
+ gligen_images = load_image(
151
+ "https://hf.co/datasets/huggingface/documentation-images/resolve/main/diffusers/gligen/livingroom_modern.png"
152
+ )
153
+ inputs = {
154
+ "prompt": "A modern livingroom",
155
+ "generator": generator,
156
+ "num_inference_steps": 2,
157
+ "guidance_scale": 6.0,
158
+ "gligen_phrases": ["a birthday cake"],
159
+ "gligen_images": [gligen_images],
160
+ "gligen_boxes": [[0.2676, 0.6088, 0.4773, 0.7183]],
161
+ "output_type": "np",
162
+ }
163
+ return inputs
164
+
165
+ def test_dict_tuple_outputs_equivalent(self):
166
+ expected_slice = None
167
+ if torch_device == "cpu":
168
+ expected_slice = np.array([0.5052, 0.5546, 0.4567, 0.4770, 0.5195, 0.4085, 0.5026, 0.4909, 0.4495])
169
+ super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
170
+
171
+ def test_stable_diffusion_gligen_text_image_default_case(self):
172
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
173
+ components = self.get_dummy_components()
174
+ sd_pipe = StableDiffusionGLIGENTextImagePipeline(**components)
175
+ sd_pipe = sd_pipe.to(device)
176
+ sd_pipe.set_progress_bar_config(disable=None)
177
+
178
+ inputs = self.get_dummy_inputs(device)
179
+ image = sd_pipe(**inputs).images
180
+ image_slice = image[0, -3:, -3:, -1]
181
+
182
+ assert image.shape == (1, 64, 64, 3)
183
+ expected_slice = np.array([0.5069, 0.5561, 0.4577, 0.4792, 0.5203, 0.4089, 0.5039, 0.4919, 0.4499])
184
+
185
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
186
+
187
+ def test_stable_diffusion_gligen_k_euler_ancestral(self):
188
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
189
+ components = self.get_dummy_components()
190
+ sd_pipe = StableDiffusionGLIGENTextImagePipeline(**components)
191
+ sd_pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(sd_pipe.scheduler.config)
192
+ sd_pipe = sd_pipe.to(device)
193
+ sd_pipe.set_progress_bar_config(disable=None)
194
+
195
+ inputs = self.get_dummy_inputs(device)
196
+ image = sd_pipe(**inputs).images
197
+ image_slice = image[0, -3:, -3:, -1]
198
+
199
+ assert image.shape == (1, 64, 64, 3)
200
+
201
+ expected_slice = np.array([0.425, 0.494, 0.429, 0.469, 0.525, 0.417, 0.533, 0.5, 0.47])
202
+
203
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
204
+
205
+ def test_attention_slicing_forward_pass(self):
206
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
207
+
208
+ def test_inference_batch_single_identical(self):
209
+ super().test_inference_batch_single_identical(batch_size=3, expected_max_diff=3e-3)
210
+
211
+ @unittest.skip(
212
+ "Test not supported because of the use of `text_encoder` in `get_cross_attention_kwargs_with_grounded()`."
213
+ )
214
+ def test_encode_prompt_works_in_isolation(self):
215
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_image_variation/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_image_variation/test_stable_diffusion_image_variation.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import gc
17
+ import random
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import torch
22
+ from PIL import Image
23
+ from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection
24
+
25
+ from diffusers import (
26
+ AutoencoderKL,
27
+ DPMSolverMultistepScheduler,
28
+ PNDMScheduler,
29
+ StableDiffusionImageVariationPipeline,
30
+ UNet2DConditionModel,
31
+ )
32
+ from diffusers.utils.testing_utils import (
33
+ backend_empty_cache,
34
+ backend_max_memory_allocated,
35
+ backend_reset_max_memory_allocated,
36
+ backend_reset_peak_memory_stats,
37
+ enable_full_determinism,
38
+ floats_tensor,
39
+ load_image,
40
+ load_numpy,
41
+ nightly,
42
+ numpy_cosine_similarity_distance,
43
+ require_torch_accelerator,
44
+ slow,
45
+ torch_device,
46
+ )
47
+
48
+ from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
49
+ from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
50
+
51
+
52
+ enable_full_determinism()
53
+
54
+
55
+ class StableDiffusionImageVariationPipelineFastTests(
56
+ PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
57
+ ):
58
+ pipeline_class = StableDiffusionImageVariationPipeline
59
+ params = IMAGE_VARIATION_PARAMS
60
+ batch_params = IMAGE_VARIATION_BATCH_PARAMS
61
+ image_params = frozenset([])
62
+ # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
63
+ image_latents_params = frozenset([])
64
+
65
+ supports_dduf = False
66
+
67
+ def get_dummy_components(self):
68
+ torch.manual_seed(0)
69
+ unet = UNet2DConditionModel(
70
+ block_out_channels=(32, 64),
71
+ layers_per_block=2,
72
+ sample_size=32,
73
+ in_channels=4,
74
+ out_channels=4,
75
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
76
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
77
+ cross_attention_dim=32,
78
+ )
79
+ scheduler = PNDMScheduler(skip_prk_steps=True)
80
+ torch.manual_seed(0)
81
+ vae = AutoencoderKL(
82
+ block_out_channels=[32, 64],
83
+ in_channels=3,
84
+ out_channels=3,
85
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
86
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
87
+ latent_channels=4,
88
+ )
89
+ torch.manual_seed(0)
90
+ image_encoder_config = CLIPVisionConfig(
91
+ hidden_size=32,
92
+ projection_dim=32,
93
+ intermediate_size=37,
94
+ layer_norm_eps=1e-05,
95
+ num_attention_heads=4,
96
+ num_hidden_layers=5,
97
+ image_size=32,
98
+ patch_size=4,
99
+ )
100
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
101
+ feature_extractor = CLIPImageProcessor(crop_size=32, size=32)
102
+
103
+ components = {
104
+ "unet": unet,
105
+ "scheduler": scheduler,
106
+ "vae": vae,
107
+ "image_encoder": image_encoder,
108
+ "feature_extractor": feature_extractor,
109
+ "safety_checker": None,
110
+ }
111
+ return components
112
+
113
+ def get_dummy_inputs(self, device, seed=0):
114
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed))
115
+ image = image.cpu().permute(0, 2, 3, 1)[0]
116
+ image = Image.fromarray(np.uint8(image)).convert("RGB").resize((32, 32))
117
+ if str(device).startswith("mps"):
118
+ generator = torch.manual_seed(seed)
119
+ else:
120
+ generator = torch.Generator(device=device).manual_seed(seed)
121
+ inputs = {
122
+ "image": image,
123
+ "generator": generator,
124
+ "num_inference_steps": 2,
125
+ "guidance_scale": 6.0,
126
+ "output_type": "np",
127
+ }
128
+ return inputs
129
+
130
+ def test_stable_diffusion_img_variation_default_case(self):
131
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
132
+ components = self.get_dummy_components()
133
+ sd_pipe = StableDiffusionImageVariationPipeline(**components)
134
+ sd_pipe = sd_pipe.to(device)
135
+ sd_pipe.set_progress_bar_config(disable=None)
136
+
137
+ inputs = self.get_dummy_inputs(device)
138
+ image = sd_pipe(**inputs).images
139
+ image_slice = image[0, -3:, -3:, -1]
140
+
141
+ assert image.shape == (1, 64, 64, 3)
142
+ expected_slice = np.array([0.5348, 0.5924, 0.4798, 0.5237, 0.5741, 0.4651, 0.5344, 0.4942, 0.4851])
143
+
144
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
145
+
146
+ def test_stable_diffusion_img_variation_multiple_images(self):
147
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
148
+ components = self.get_dummy_components()
149
+ sd_pipe = StableDiffusionImageVariationPipeline(**components)
150
+ sd_pipe = sd_pipe.to(device)
151
+ sd_pipe.set_progress_bar_config(disable=None)
152
+
153
+ inputs = self.get_dummy_inputs(device)
154
+ inputs["image"] = 2 * [inputs["image"]]
155
+ output = sd_pipe(**inputs)
156
+
157
+ image = output.images
158
+
159
+ image_slice = image[-1, -3:, -3:, -1]
160
+
161
+ assert image.shape == (2, 64, 64, 3)
162
+ expected_slice = np.array([0.6647, 0.5557, 0.5723, 0.5567, 0.5869, 0.6044, 0.5502, 0.5439, 0.5189])
163
+
164
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
165
+
166
+ def test_inference_batch_single_identical(self):
167
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
168
+
169
+
170
+ @slow
171
+ @require_torch_accelerator
172
+ class StableDiffusionImageVariationPipelineSlowTests(unittest.TestCase):
173
+ def setUp(self):
174
+ super().setUp()
175
+ gc.collect()
176
+ backend_empty_cache(torch_device)
177
+
178
+ def tearDown(self):
179
+ super().tearDown()
180
+ gc.collect()
181
+ backend_empty_cache(torch_device)
182
+
183
+ def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
184
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
185
+ init_image = load_image(
186
+ "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
187
+ "/stable_diffusion_imgvar/input_image_vermeer.png"
188
+ )
189
+ latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
190
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
191
+ inputs = {
192
+ "image": init_image,
193
+ "latents": latents,
194
+ "generator": generator,
195
+ "num_inference_steps": 3,
196
+ "guidance_scale": 7.5,
197
+ "output_type": "np",
198
+ }
199
+ return inputs
200
+
201
+ def test_stable_diffusion_img_variation_pipeline_default(self):
202
+ sd_pipe = StableDiffusionImageVariationPipeline.from_pretrained(
203
+ "lambdalabs/sd-image-variations-diffusers", safety_checker=None
204
+ )
205
+ sd_pipe = sd_pipe.to(torch_device)
206
+ sd_pipe.set_progress_bar_config(disable=None)
207
+
208
+ generator_device = "cpu"
209
+ inputs = self.get_inputs(generator_device)
210
+ image = sd_pipe(**inputs).images
211
+ image_slice = image[0, -3:, -3:, -1].flatten()
212
+
213
+ assert image.shape == (1, 512, 512, 3)
214
+ expected_slice = np.array([0.5348, 0.5924, 0.4798, 0.5237, 0.5741, 0.4651, 0.5344, 0.4942, 0.4851])
215
+
216
+ max_diff = numpy_cosine_similarity_distance(image_slice, expected_slice)
217
+ assert max_diff < 1e-4
218
+
219
+ def test_stable_diffusion_img_variation_intermediate_state(self):
220
+ number_of_steps = 0
221
+
222
+ def callback_fn(step: int, timestep: int, latents: torch.Tensor) -> None:
223
+ callback_fn.has_been_called = True
224
+ nonlocal number_of_steps
225
+ number_of_steps += 1
226
+ if step == 1:
227
+ latents = latents.detach().cpu().numpy()
228
+ assert latents.shape == (1, 4, 64, 64)
229
+ latents_slice = latents[0, -3:, -3:, -1]
230
+ expected_slice = np.array([0.5348, 0.5924, 0.4798, 0.5237, 0.5741, 0.4651, 0.5344, 0.4942, 0.4851])
231
+ max_diff = numpy_cosine_similarity_distance(latents_slice.flatten(), expected_slice)
232
+
233
+ assert max_diff < 1e-3
234
+
235
+ elif step == 2:
236
+ latents = latents.detach().cpu().numpy()
237
+ assert latents.shape == (1, 4, 64, 64)
238
+ latents_slice = latents[0, -3:, -3:, -1]
239
+ expected_slice = np.array([0.5348, 0.5924, 0.4798, 0.5237, 0.5741, 0.4651, 0.5344, 0.4942, 0.4851])
240
+ max_diff = numpy_cosine_similarity_distance(latents_slice.flatten(), expected_slice)
241
+
242
+ assert max_diff < 1e-3
243
+
244
+ callback_fn.has_been_called = False
245
+
246
+ pipe = StableDiffusionImageVariationPipeline.from_pretrained(
247
+ "lambdalabs/sd-image-variations-diffusers",
248
+ safety_checker=None,
249
+ torch_dtype=torch.float16,
250
+ )
251
+
252
+ pipe.to(torch_device)
253
+ pipe.set_progress_bar_config(disable=None)
254
+ for component in pipe.components.values():
255
+ if hasattr(component, "set_default_attn_processor"):
256
+ component.set_default_attn_processor()
257
+
258
+ generator_device = "cpu"
259
+ inputs = self.get_inputs(generator_device, dtype=torch.float16)
260
+ pipe(**inputs, callback=callback_fn, callback_steps=1)
261
+ assert callback_fn.has_been_called
262
+ assert number_of_steps == inputs["num_inference_steps"]
263
+
264
+ def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self):
265
+ backend_empty_cache(torch_device)
266
+ backend_reset_max_memory_allocated(torch_device)
267
+ backend_reset_peak_memory_stats(torch_device)
268
+
269
+ pipe = StableDiffusionImageVariationPipeline.from_pretrained(
270
+ "lambdalabs/sd-image-variations-diffusers", safety_checker=None, torch_dtype=torch.float16
271
+ )
272
+ pipe.set_progress_bar_config(disable=None)
273
+ pipe.enable_attention_slicing(1)
274
+ pipe.enable_sequential_cpu_offload(device=torch_device)
275
+
276
+ inputs = self.get_inputs(torch_device, dtype=torch.float16)
277
+ _ = pipe(**inputs)
278
+
279
+ mem_bytes = backend_max_memory_allocated(torch_device)
280
+ # make sure that less than 2.6 GB is allocated
281
+ assert mem_bytes < 2.6 * 10**9
282
+
283
+
284
+ @nightly
285
+ @require_torch_accelerator
286
+ class StableDiffusionImageVariationPipelineNightlyTests(unittest.TestCase):
287
+ def setUp(self):
288
+ super().setUp()
289
+ gc.collect()
290
+ backend_empty_cache(torch_device)
291
+
292
+ def tearDown(self):
293
+ super().tearDown()
294
+ gc.collect()
295
+ backend_empty_cache(torch_device)
296
+
297
+ def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
298
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
299
+ init_image = load_image(
300
+ "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
301
+ "/stable_diffusion_imgvar/input_image_vermeer.png"
302
+ )
303
+ latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
304
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
305
+ inputs = {
306
+ "image": init_image,
307
+ "latents": latents,
308
+ "generator": generator,
309
+ "num_inference_steps": 50,
310
+ "guidance_scale": 7.5,
311
+ "output_type": "np",
312
+ }
313
+ return inputs
314
+
315
+ def test_img_variation_pndm(self):
316
+ sd_pipe = StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers")
317
+ sd_pipe.to(torch_device)
318
+ sd_pipe.set_progress_bar_config(disable=None)
319
+
320
+ inputs = self.get_inputs(torch_device)
321
+ image = sd_pipe(**inputs).images[0]
322
+
323
+ expected_image = load_numpy(
324
+ "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
325
+ "/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy"
326
+ )
327
+ max_diff = np.abs(expected_image - image).max()
328
+ assert max_diff < 1e-3
329
+
330
+ def test_img_variation_dpm(self):
331
+ sd_pipe = StableDiffusionImageVariationPipeline.from_pretrained("fusing/sd-image-variations-diffusers")
332
+ sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config)
333
+ sd_pipe.to(torch_device)
334
+ sd_pipe.set_progress_bar_config(disable=None)
335
+
336
+ inputs = self.get_inputs(torch_device)
337
+ inputs["num_inference_steps"] = 25
338
+ image = sd_pipe(**inputs).images[0]
339
+
340
+ expected_image = load_numpy(
341
+ "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
342
+ "/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy"
343
+ )
344
+ max_diff = np.abs(expected_image - image).max()
345
+ assert max_diff < 1e-3
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_k_diffusion/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_k_diffusion/test_stable_diffusion_k_diffusion.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 StableDiffusionKDiffusionPipeline
23
+ from diffusers.utils.testing_utils import (
24
+ backend_empty_cache,
25
+ enable_full_determinism,
26
+ nightly,
27
+ require_torch_accelerator,
28
+ torch_device,
29
+ )
30
+
31
+
32
+ enable_full_determinism()
33
+
34
+
35
+ @nightly
36
+ @require_torch_accelerator
37
+ class StableDiffusionPipelineIntegrationTests(unittest.TestCase):
38
+ def setUp(self):
39
+ # clean up the VRAM before each test
40
+ super().setUp()
41
+ gc.collect()
42
+ backend_empty_cache(torch_device)
43
+
44
+ def tearDown(self):
45
+ # clean up the VRAM after each test
46
+ super().tearDown()
47
+ gc.collect()
48
+ backend_empty_cache(torch_device)
49
+
50
+ def test_stable_diffusion_1(self):
51
+ sd_pipe = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
52
+ sd_pipe = sd_pipe.to(torch_device)
53
+ sd_pipe.set_progress_bar_config(disable=None)
54
+
55
+ sd_pipe.set_scheduler("sample_euler")
56
+
57
+ prompt = "A painting of a squirrel eating a burger"
58
+ generator = torch.manual_seed(0)
59
+ output = sd_pipe([prompt], generator=generator, guidance_scale=9.0, num_inference_steps=20, output_type="np")
60
+
61
+ image = output.images
62
+
63
+ image_slice = image[0, -3:, -3:, -1]
64
+
65
+ assert image.shape == (1, 512, 512, 3)
66
+ expected_slice = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339])
67
+
68
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
69
+
70
+ def test_stable_diffusion_2(self):
71
+ sd_pipe = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base")
72
+ sd_pipe = sd_pipe.to(torch_device)
73
+ sd_pipe.set_progress_bar_config(disable=None)
74
+
75
+ sd_pipe.set_scheduler("sample_euler")
76
+
77
+ prompt = "A painting of a squirrel eating a burger"
78
+ generator = torch.manual_seed(0)
79
+ output = sd_pipe([prompt], generator=generator, guidance_scale=9.0, num_inference_steps=20, output_type="np")
80
+
81
+ image = output.images
82
+
83
+ image_slice = image[0, -3:, -3:, -1]
84
+
85
+ assert image.shape == (1, 512, 512, 3)
86
+ expected_slice = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112])
87
+
88
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-1
89
+
90
+ def test_stable_diffusion_karras_sigmas(self):
91
+ sd_pipe = StableDiffusionKDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base")
92
+ sd_pipe = sd_pipe.to(torch_device)
93
+ sd_pipe.set_progress_bar_config(disable=None)
94
+
95
+ sd_pipe.set_scheduler("sample_dpmpp_2m")
96
+
97
+ prompt = "A painting of a squirrel eating a burger"
98
+ generator = torch.manual_seed(0)
99
+ output = sd_pipe(
100
+ [prompt],
101
+ generator=generator,
102
+ guidance_scale=7.5,
103
+ num_inference_steps=15,
104
+ output_type="np",
105
+ use_karras_sigmas=True,
106
+ )
107
+
108
+ image = output.images
109
+
110
+ image_slice = image[0, -3:, -3:, -1]
111
+
112
+ assert image.shape == (1, 512, 512, 3)
113
+ expected_slice = np.array(
114
+ [0.11381689, 0.12112921, 0.1389457, 0.12549606, 0.1244964, 0.10831517, 0.11562866, 0.10867816, 0.10499048]
115
+ )
116
+
117
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
118
+
119
+ def test_stable_diffusion_noise_sampler_seed(self):
120
+ sd_pipe = StableDiffusionKDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
121
+ sd_pipe = sd_pipe.to(torch_device)
122
+ sd_pipe.set_progress_bar_config(disable=None)
123
+
124
+ sd_pipe.set_scheduler("sample_dpmpp_sde")
125
+
126
+ prompt = "A painting of a squirrel eating a burger"
127
+ seed = 0
128
+ images1 = sd_pipe(
129
+ [prompt],
130
+ generator=torch.manual_seed(seed),
131
+ noise_sampler_seed=seed,
132
+ guidance_scale=9.0,
133
+ num_inference_steps=20,
134
+ output_type="np",
135
+ ).images
136
+ images2 = sd_pipe(
137
+ [prompt],
138
+ generator=torch.manual_seed(seed),
139
+ noise_sampler_seed=seed,
140
+ guidance_scale=9.0,
141
+ num_inference_steps=20,
142
+ output_type="np",
143
+ ).images
144
+
145
+ assert images1.shape == (1, 512, 512, 3)
146
+ assert images2.shape == (1, 512, 512, 3)
147
+ assert np.abs(images1.flatten() - images2.flatten()).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_ldm3d/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_ldm3d/test_stable_diffusion_ldm3d.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 torch
22
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
23
+
24
+ from diffusers import (
25
+ AutoencoderKL,
26
+ DDIMScheduler,
27
+ PNDMScheduler,
28
+ StableDiffusionLDM3DPipeline,
29
+ UNet2DConditionModel,
30
+ )
31
+ from diffusers.utils.testing_utils import (
32
+ backend_empty_cache,
33
+ enable_full_determinism,
34
+ nightly,
35
+ require_torch_accelerator,
36
+ torch_device,
37
+ )
38
+
39
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
40
+
41
+
42
+ enable_full_determinism()
43
+
44
+
45
+ class StableDiffusionLDM3DPipelineFastTests(unittest.TestCase):
46
+ pipeline_class = StableDiffusionLDM3DPipeline
47
+ params = TEXT_TO_IMAGE_PARAMS
48
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
49
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
50
+
51
+ def get_dummy_components(self):
52
+ torch.manual_seed(0)
53
+ unet = UNet2DConditionModel(
54
+ block_out_channels=(32, 64),
55
+ layers_per_block=2,
56
+ sample_size=32,
57
+ in_channels=4,
58
+ out_channels=4,
59
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
60
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
61
+ cross_attention_dim=32,
62
+ )
63
+ scheduler = DDIMScheduler(
64
+ beta_start=0.00085,
65
+ beta_end=0.012,
66
+ beta_schedule="scaled_linear",
67
+ clip_sample=False,
68
+ set_alpha_to_one=False,
69
+ )
70
+ torch.manual_seed(0)
71
+ vae = AutoencoderKL(
72
+ block_out_channels=[32, 64],
73
+ in_channels=6,
74
+ out_channels=6,
75
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
76
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
77
+ latent_channels=4,
78
+ )
79
+ torch.manual_seed(0)
80
+ text_encoder_config = CLIPTextConfig(
81
+ bos_token_id=0,
82
+ eos_token_id=2,
83
+ hidden_size=32,
84
+ intermediate_size=37,
85
+ layer_norm_eps=1e-05,
86
+ num_attention_heads=4,
87
+ num_hidden_layers=5,
88
+ pad_token_id=1,
89
+ vocab_size=1000,
90
+ )
91
+ text_encoder = CLIPTextModel(text_encoder_config)
92
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
93
+
94
+ components = {
95
+ "unet": unet,
96
+ "scheduler": scheduler,
97
+ "vae": vae,
98
+ "text_encoder": text_encoder,
99
+ "tokenizer": tokenizer,
100
+ "safety_checker": None,
101
+ "feature_extractor": None,
102
+ "image_encoder": None,
103
+ }
104
+ return components
105
+
106
+ def get_dummy_inputs(self, device, seed=0):
107
+ if str(device).startswith("mps"):
108
+ generator = torch.manual_seed(seed)
109
+ else:
110
+ generator = torch.Generator(device=device).manual_seed(seed)
111
+ inputs = {
112
+ "prompt": "A painting of a squirrel eating a burger",
113
+ "generator": generator,
114
+ "num_inference_steps": 2,
115
+ "guidance_scale": 6.0,
116
+ "output_type": "np",
117
+ }
118
+ return inputs
119
+
120
+ def test_stable_diffusion_ddim(self):
121
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
122
+
123
+ components = self.get_dummy_components()
124
+ ldm3d_pipe = StableDiffusionLDM3DPipeline(**components)
125
+ ldm3d_pipe = ldm3d_pipe.to(torch_device)
126
+ ldm3d_pipe.set_progress_bar_config(disable=None)
127
+
128
+ inputs = self.get_dummy_inputs(device)
129
+ output = ldm3d_pipe(**inputs)
130
+ rgb, depth = output.rgb, output.depth
131
+
132
+ image_slice_rgb = rgb[0, -3:, -3:, -1]
133
+ image_slice_depth = depth[0, -3:, -1]
134
+
135
+ assert rgb.shape == (1, 64, 64, 3)
136
+ assert depth.shape == (1, 64, 64)
137
+
138
+ expected_slice_rgb = np.array(
139
+ [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262]
140
+ )
141
+ expected_slice_depth = np.array([103.46727, 85.812004, 87.849236])
142
+
143
+ assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb).max() < 1e-2
144
+ assert np.abs(image_slice_depth.flatten() - expected_slice_depth).max() < 1e-2
145
+
146
+ def test_stable_diffusion_prompt_embeds(self):
147
+ components = self.get_dummy_components()
148
+ ldm3d_pipe = StableDiffusionLDM3DPipeline(**components)
149
+ ldm3d_pipe = ldm3d_pipe.to(torch_device)
150
+ ldm3d_pipe.set_progress_bar_config(disable=None)
151
+
152
+ inputs = self.get_dummy_inputs(torch_device)
153
+ inputs["prompt"] = 3 * [inputs["prompt"]]
154
+
155
+ # forward
156
+ output = ldm3d_pipe(**inputs)
157
+ rgb_slice_1, depth_slice_1 = output.rgb, output.depth
158
+ rgb_slice_1 = rgb_slice_1[0, -3:, -3:, -1]
159
+ depth_slice_1 = depth_slice_1[0, -3:, -1]
160
+
161
+ inputs = self.get_dummy_inputs(torch_device)
162
+ prompt = 3 * [inputs.pop("prompt")]
163
+
164
+ text_inputs = ldm3d_pipe.tokenizer(
165
+ prompt,
166
+ padding="max_length",
167
+ max_length=ldm3d_pipe.tokenizer.model_max_length,
168
+ truncation=True,
169
+ return_tensors="pt",
170
+ )
171
+ text_inputs = text_inputs["input_ids"].to(torch_device)
172
+
173
+ prompt_embeds = ldm3d_pipe.text_encoder(text_inputs)[0]
174
+
175
+ inputs["prompt_embeds"] = prompt_embeds
176
+
177
+ # forward
178
+ output = ldm3d_pipe(**inputs)
179
+ rgb_slice_2, depth_slice_2 = output.rgb, output.depth
180
+ rgb_slice_2 = rgb_slice_2[0, -3:, -3:, -1]
181
+ depth_slice_2 = depth_slice_2[0, -3:, -1]
182
+
183
+ assert np.abs(rgb_slice_1.flatten() - rgb_slice_2.flatten()).max() < 1e-4
184
+ assert np.abs(depth_slice_1.flatten() - depth_slice_2.flatten()).max() < 1e-4
185
+
186
+ def test_stable_diffusion_negative_prompt(self):
187
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
188
+ components = self.get_dummy_components()
189
+ components["scheduler"] = PNDMScheduler(skip_prk_steps=True)
190
+ ldm3d_pipe = StableDiffusionLDM3DPipeline(**components)
191
+ ldm3d_pipe = ldm3d_pipe.to(device)
192
+ ldm3d_pipe.set_progress_bar_config(disable=None)
193
+
194
+ inputs = self.get_dummy_inputs(device)
195
+ negative_prompt = "french fries"
196
+ output = ldm3d_pipe(**inputs, negative_prompt=negative_prompt)
197
+
198
+ rgb, depth = output.rgb, output.depth
199
+ rgb_slice = rgb[0, -3:, -3:, -1]
200
+ depth_slice = depth[0, -3:, -1]
201
+
202
+ assert rgb.shape == (1, 64, 64, 3)
203
+ assert depth.shape == (1, 64, 64)
204
+
205
+ expected_slice_rgb = np.array(
206
+ [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217]
207
+ )
208
+ expected_slice_depth = np.array([107.84738, 84.62802, 89.962135])
209
+ assert np.abs(rgb_slice.flatten() - expected_slice_rgb).max() < 1e-2
210
+ assert np.abs(depth_slice.flatten() - expected_slice_depth).max() < 1e-2
211
+
212
+
213
+ @nightly
214
+ @require_torch_accelerator
215
+ class StableDiffusionLDM3DPipelineSlowTests(unittest.TestCase):
216
+ def setUp(self):
217
+ super().setUp()
218
+ gc.collect()
219
+ backend_empty_cache(torch_device)
220
+
221
+ def tearDown(self):
222
+ super().tearDown()
223
+ gc.collect()
224
+ backend_empty_cache(torch_device)
225
+
226
+ def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
227
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
228
+ latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
229
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
230
+ inputs = {
231
+ "prompt": "a photograph of an astronaut riding a horse",
232
+ "latents": latents,
233
+ "generator": generator,
234
+ "num_inference_steps": 3,
235
+ "guidance_scale": 7.5,
236
+ "output_type": "np",
237
+ }
238
+ return inputs
239
+
240
+ def test_ldm3d_stable_diffusion(self):
241
+ ldm3d_pipe = StableDiffusionLDM3DPipeline.from_pretrained("Intel/ldm3d")
242
+ ldm3d_pipe = ldm3d_pipe.to(torch_device)
243
+ ldm3d_pipe.set_progress_bar_config(disable=None)
244
+
245
+ inputs = self.get_inputs(torch_device)
246
+ output = ldm3d_pipe(**inputs)
247
+ rgb, depth = output.rgb, output.depth
248
+ rgb_slice = rgb[0, -3:, -3:, -1].flatten()
249
+ depth_slice = rgb[0, -3:, -1].flatten()
250
+
251
+ assert rgb.shape == (1, 512, 512, 3)
252
+ assert depth.shape == (1, 512, 512)
253
+
254
+ expected_slice_rgb = np.array(
255
+ [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706]
256
+ )
257
+ expected_slice_depth = np.array(
258
+ [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706]
259
+ )
260
+ assert np.abs(rgb_slice - expected_slice_rgb).max() < 3e-3
261
+ assert np.abs(depth_slice - expected_slice_depth).max() < 3e-3
262
+
263
+
264
+ @nightly
265
+ @require_torch_accelerator
266
+ class StableDiffusionPipelineNightlyTests(unittest.TestCase):
267
+ def setUp(self):
268
+ super().setUp()
269
+ gc.collect()
270
+ backend_empty_cache(torch_device)
271
+
272
+ def tearDown(self):
273
+ super().tearDown()
274
+ gc.collect()
275
+ backend_empty_cache(torch_device)
276
+
277
+ def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
278
+ generator = torch.Generator(device=generator_device).manual_seed(seed)
279
+ latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
280
+ latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
281
+ inputs = {
282
+ "prompt": "a photograph of an astronaut riding a horse",
283
+ "latents": latents,
284
+ "generator": generator,
285
+ "num_inference_steps": 50,
286
+ "guidance_scale": 7.5,
287
+ "output_type": "np",
288
+ }
289
+ return inputs
290
+
291
+ def test_ldm3d(self):
292
+ ldm3d_pipe = StableDiffusionLDM3DPipeline.from_pretrained("Intel/ldm3d").to(torch_device)
293
+ ldm3d_pipe.set_progress_bar_config(disable=None)
294
+
295
+ inputs = self.get_inputs(torch_device)
296
+ output = ldm3d_pipe(**inputs)
297
+ rgb, depth = output.rgb, output.depth
298
+
299
+ expected_rgb_mean = 0.495586
300
+ expected_rgb_std = 0.33795515
301
+ expected_depth_mean = 112.48518
302
+ expected_depth_std = 98.489746
303
+ assert np.abs(expected_rgb_mean - rgb.mean()) < 1e-3
304
+ assert np.abs(expected_rgb_std - rgb.std()) < 1e-3
305
+ assert np.abs(expected_depth_mean - depth.mean()) < 1e-3
306
+ assert np.abs(expected_depth_std - depth.std()) < 1e-3
307
+
308
+ def test_ldm3d_v2(self):
309
+ ldm3d_pipe = StableDiffusionLDM3DPipeline.from_pretrained("Intel/ldm3d-4c").to(torch_device)
310
+ ldm3d_pipe.set_progress_bar_config(disable=None)
311
+
312
+ inputs = self.get_inputs(torch_device)
313
+ output = ldm3d_pipe(**inputs)
314
+ rgb, depth = output.rgb, output.depth
315
+
316
+ expected_rgb_mean = 0.4194127
317
+ expected_rgb_std = 0.35375586
318
+ expected_depth_mean = 0.5638502
319
+ expected_depth_std = 0.34686103
320
+
321
+ assert rgb.shape == (1, 512, 512, 3)
322
+ assert depth.shape == (1, 512, 512, 1)
323
+ assert np.abs(expected_rgb_mean - rgb.mean()) < 1e-3
324
+ assert np.abs(expected_rgb_std - rgb.std()) < 1e-3
325
+ assert np.abs(expected_depth_mean - depth.mean()) < 1e-3
326
+ assert np.abs(expected_depth_std - depth.std()) < 1e-3
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_panorama/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_panorama/test_stable_diffusion_panorama.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers import (
24
+ AutoencoderKL,
25
+ DDIMScheduler,
26
+ EulerAncestralDiscreteScheduler,
27
+ LMSDiscreteScheduler,
28
+ PNDMScheduler,
29
+ StableDiffusionPanoramaPipeline,
30
+ UNet2DConditionModel,
31
+ )
32
+ from diffusers.utils.testing_utils import (
33
+ backend_empty_cache,
34
+ backend_max_memory_allocated,
35
+ backend_reset_max_memory_allocated,
36
+ backend_reset_peak_memory_stats,
37
+ enable_full_determinism,
38
+ nightly,
39
+ require_torch_accelerator,
40
+ skip_mps,
41
+ torch_device,
42
+ )
43
+
44
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
45
+ from ..test_pipelines_common import (
46
+ IPAdapterTesterMixin,
47
+ PipelineFromPipeTesterMixin,
48
+ PipelineLatentTesterMixin,
49
+ PipelineTesterMixin,
50
+ )
51
+
52
+
53
+ enable_full_determinism()
54
+
55
+
56
+ @skip_mps
57
+ class StableDiffusionPanoramaPipelineFastTests(
58
+ IPAdapterTesterMixin,
59
+ PipelineLatentTesterMixin,
60
+ PipelineTesterMixin,
61
+ PipelineFromPipeTesterMixin,
62
+ unittest.TestCase,
63
+ ):
64
+ pipeline_class = StableDiffusionPanoramaPipeline
65
+ params = TEXT_TO_IMAGE_PARAMS
66
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
67
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
68
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
69
+
70
+ def get_dummy_components(self):
71
+ torch.manual_seed(0)
72
+ unet = UNet2DConditionModel(
73
+ block_out_channels=(32, 64),
74
+ layers_per_block=1,
75
+ sample_size=32,
76
+ in_channels=4,
77
+ out_channels=4,
78
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
79
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
80
+ cross_attention_dim=32,
81
+ )
82
+ scheduler = DDIMScheduler()
83
+ torch.manual_seed(0)
84
+ vae = AutoencoderKL(
85
+ block_out_channels=[32, 64],
86
+ in_channels=3,
87
+ out_channels=3,
88
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
89
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
90
+ latent_channels=4,
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
+ )
104
+ text_encoder = CLIPTextModel(text_encoder_config)
105
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
106
+
107
+ components = {
108
+ "unet": unet,
109
+ "scheduler": scheduler,
110
+ "vae": vae,
111
+ "text_encoder": text_encoder,
112
+ "tokenizer": tokenizer,
113
+ "safety_checker": None,
114
+ "feature_extractor": None,
115
+ "image_encoder": None,
116
+ }
117
+ return components
118
+
119
+ def get_dummy_inputs(self, device, seed=0):
120
+ generator = torch.Generator(device=device).manual_seed(seed)
121
+ inputs = {
122
+ "prompt": "a photo of the dolomites",
123
+ "generator": generator,
124
+ # Setting height and width to None to prevent OOMs on CPU.
125
+ "height": None,
126
+ "width": None,
127
+ "num_inference_steps": 1,
128
+ "guidance_scale": 6.0,
129
+ "output_type": "np",
130
+ }
131
+ return inputs
132
+
133
+ def test_stable_diffusion_panorama_default_case(self):
134
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
135
+ components = self.get_dummy_components()
136
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
137
+ sd_pipe = sd_pipe.to(device)
138
+ sd_pipe.set_progress_bar_config(disable=None)
139
+
140
+ inputs = self.get_dummy_inputs(device)
141
+ image = sd_pipe(**inputs).images
142
+ image_slice = image[0, -3:, -3:, -1]
143
+ assert image.shape == (1, 64, 64, 3)
144
+
145
+ expected_slice = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757])
146
+
147
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
148
+
149
+ def test_stable_diffusion_panorama_circular_padding_case(self):
150
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
151
+ components = self.get_dummy_components()
152
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
153
+ sd_pipe = sd_pipe.to(device)
154
+ sd_pipe.set_progress_bar_config(disable=None)
155
+
156
+ inputs = self.get_dummy_inputs(device)
157
+ image = sd_pipe(**inputs, circular_padding=True).images
158
+ image_slice = image[0, -3:, -3:, -1]
159
+ assert image.shape == (1, 64, 64, 3)
160
+
161
+ expected_slice = np.array([0.6127, 0.6299, 0.4595, 0.4051, 0.4543, 0.3925, 0.5510, 0.5693, 0.5031])
162
+
163
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
164
+
165
+ # override to speed the overall test timing up.
166
+ def test_inference_batch_consistent(self):
167
+ super().test_inference_batch_consistent(batch_sizes=[1, 2])
168
+
169
+ # override to speed the overall test timing up.
170
+ def test_inference_batch_single_identical(self):
171
+ super().test_inference_batch_single_identical(batch_size=2, expected_max_diff=5.0e-3)
172
+
173
+ def test_float16_inference(self):
174
+ super().test_float16_inference(expected_max_diff=1e-1)
175
+
176
+ def test_stable_diffusion_panorama_negative_prompt(self):
177
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
178
+ components = self.get_dummy_components()
179
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
180
+ sd_pipe = sd_pipe.to(device)
181
+ sd_pipe.set_progress_bar_config(disable=None)
182
+
183
+ inputs = self.get_dummy_inputs(device)
184
+ negative_prompt = "french fries"
185
+ output = sd_pipe(**inputs, negative_prompt=negative_prompt)
186
+ image = output.images
187
+ image_slice = image[0, -3:, -3:, -1]
188
+
189
+ assert image.shape == (1, 64, 64, 3)
190
+
191
+ expected_slice = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757])
192
+
193
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
194
+
195
+ def test_stable_diffusion_panorama_views_batch(self):
196
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
197
+ components = self.get_dummy_components()
198
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
199
+ sd_pipe = sd_pipe.to(device)
200
+ sd_pipe.set_progress_bar_config(disable=None)
201
+
202
+ inputs = self.get_dummy_inputs(device)
203
+ output = sd_pipe(**inputs, view_batch_size=2)
204
+ image = output.images
205
+ image_slice = image[0, -3:, -3:, -1]
206
+
207
+ assert image.shape == (1, 64, 64, 3)
208
+
209
+ expected_slice = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757])
210
+
211
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
212
+
213
+ def test_stable_diffusion_panorama_views_batch_circular_padding(self):
214
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
215
+ components = self.get_dummy_components()
216
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
217
+ sd_pipe = sd_pipe.to(device)
218
+ sd_pipe.set_progress_bar_config(disable=None)
219
+
220
+ inputs = self.get_dummy_inputs(device)
221
+ output = sd_pipe(**inputs, circular_padding=True, view_batch_size=2)
222
+ image = output.images
223
+ image_slice = image[0, -3:, -3:, -1]
224
+
225
+ assert image.shape == (1, 64, 64, 3)
226
+
227
+ expected_slice = np.array([0.6127, 0.6299, 0.4595, 0.4051, 0.4543, 0.3925, 0.5510, 0.5693, 0.5031])
228
+
229
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
230
+
231
+ def test_stable_diffusion_panorama_euler(self):
232
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
233
+ components = self.get_dummy_components()
234
+ components["scheduler"] = EulerAncestralDiscreteScheduler(
235
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear"
236
+ )
237
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
238
+ sd_pipe = sd_pipe.to(device)
239
+ sd_pipe.set_progress_bar_config(disable=None)
240
+
241
+ inputs = self.get_dummy_inputs(device)
242
+ image = sd_pipe(**inputs).images
243
+ image_slice = image[0, -3:, -3:, -1]
244
+
245
+ assert image.shape == (1, 64, 64, 3)
246
+
247
+ expected_slice = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952])
248
+
249
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
250
+
251
+ def test_stable_diffusion_panorama_pndm(self):
252
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
253
+ components = self.get_dummy_components()
254
+ components["scheduler"] = PNDMScheduler(
255
+ beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", skip_prk_steps=True
256
+ )
257
+ sd_pipe = StableDiffusionPanoramaPipeline(**components)
258
+ sd_pipe = sd_pipe.to(device)
259
+ sd_pipe.set_progress_bar_config(disable=None)
260
+
261
+ inputs = self.get_dummy_inputs(device)
262
+ image = sd_pipe(**inputs).images
263
+ image_slice = image[0, -3:, -3:, -1]
264
+
265
+ assert image.shape == (1, 64, 64, 3)
266
+
267
+ expected_slice = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539])
268
+
269
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
270
+
271
+ def test_encode_prompt_works_in_isolation(self):
272
+ extra_required_param_value_dict = {
273
+ "device": torch.device(torch_device).type,
274
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
275
+ }
276
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
277
+
278
+
279
+ @nightly
280
+ @require_torch_accelerator
281
+ class StableDiffusionPanoramaNightlyTests(unittest.TestCase):
282
+ def setUp(self):
283
+ super().setUp()
284
+ gc.collect()
285
+ backend_empty_cache(torch_device)
286
+
287
+ def tearDown(self):
288
+ super().tearDown()
289
+ gc.collect()
290
+ backend_empty_cache(torch_device)
291
+
292
+ def get_inputs(self, seed=0):
293
+ generator = torch.manual_seed(seed)
294
+ inputs = {
295
+ "prompt": "a photo of the dolomites",
296
+ "generator": generator,
297
+ "num_inference_steps": 3,
298
+ "guidance_scale": 7.5,
299
+ "output_type": "np",
300
+ }
301
+ return inputs
302
+
303
+ def test_stable_diffusion_panorama_default(self):
304
+ model_ckpt = "stabilityai/stable-diffusion-2-base"
305
+ scheduler = DDIMScheduler.from_pretrained(model_ckpt, subfolder="scheduler")
306
+ pipe = StableDiffusionPanoramaPipeline.from_pretrained(model_ckpt, scheduler=scheduler, safety_checker=None)
307
+ pipe.to(torch_device)
308
+ pipe.set_progress_bar_config(disable=None)
309
+ pipe.enable_attention_slicing()
310
+
311
+ inputs = self.get_inputs()
312
+ image = pipe(**inputs).images
313
+ image_slice = image[0, -3:, -3:, -1].flatten()
314
+
315
+ assert image.shape == (1, 512, 2048, 3)
316
+
317
+ expected_slice = np.array(
318
+ [
319
+ 0.36968392,
320
+ 0.27025372,
321
+ 0.32446766,
322
+ 0.28379387,
323
+ 0.36363274,
324
+ 0.30733347,
325
+ 0.27100027,
326
+ 0.27054125,
327
+ 0.25536096,
328
+ ]
329
+ )
330
+
331
+ assert np.abs(expected_slice - image_slice).max() < 1e-2
332
+
333
+ def test_stable_diffusion_panorama_k_lms(self):
334
+ pipe = StableDiffusionPanoramaPipeline.from_pretrained(
335
+ "stabilityai/stable-diffusion-2-base", safety_checker=None
336
+ )
337
+ pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
338
+ pipe.unet.set_default_attn_processor()
339
+ pipe.to(torch_device)
340
+ pipe.set_progress_bar_config(disable=None)
341
+ pipe.enable_attention_slicing()
342
+
343
+ inputs = self.get_inputs()
344
+ image = pipe(**inputs).images
345
+ image_slice = image[0, -3:, -3:, -1].flatten()
346
+ assert image.shape == (1, 512, 2048, 3)
347
+
348
+ expected_slice = np.array(
349
+ [
350
+ [
351
+ 0.0,
352
+ 0.0,
353
+ 0.0,
354
+ 0.0,
355
+ 0.0,
356
+ 0.0,
357
+ 0.0,
358
+ 0.0,
359
+ 0.0,
360
+ ]
361
+ ]
362
+ )
363
+
364
+ assert np.abs(expected_slice - image_slice).max() < 1e-2
365
+
366
+ def test_stable_diffusion_panorama_intermediate_state(self):
367
+ number_of_steps = 0
368
+
369
+ def callback_fn(step: int, timestep: int, latents: torch.Tensor) -> None:
370
+ callback_fn.has_been_called = True
371
+ nonlocal number_of_steps
372
+ number_of_steps += 1
373
+ if step == 1:
374
+ latents = latents.detach().cpu().numpy()
375
+ assert latents.shape == (1, 4, 64, 256)
376
+ latents_slice = latents[0, -3:, -3:, -1]
377
+
378
+ expected_slice = np.array(
379
+ [
380
+ 0.18681869,
381
+ 0.33907816,
382
+ 0.5361276,
383
+ 0.14432865,
384
+ -0.02856611,
385
+ -0.73941123,
386
+ 0.23397987,
387
+ 0.47322682,
388
+ -0.37823164,
389
+ ]
390
+ )
391
+ assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2
392
+ elif step == 2:
393
+ latents = latents.detach().cpu().numpy()
394
+ assert latents.shape == (1, 4, 64, 256)
395
+ latents_slice = latents[0, -3:, -3:, -1]
396
+
397
+ expected_slice = np.array(
398
+ [
399
+ 0.18539645,
400
+ 0.33987248,
401
+ 0.5378559,
402
+ 0.14437142,
403
+ -0.02455261,
404
+ -0.7338317,
405
+ 0.23990755,
406
+ 0.47356272,
407
+ -0.3786505,
408
+ ]
409
+ )
410
+
411
+ assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2
412
+
413
+ callback_fn.has_been_called = False
414
+
415
+ model_ckpt = "stabilityai/stable-diffusion-2-base"
416
+ scheduler = DDIMScheduler.from_pretrained(model_ckpt, subfolder="scheduler")
417
+ pipe = StableDiffusionPanoramaPipeline.from_pretrained(model_ckpt, scheduler=scheduler, safety_checker=None)
418
+ pipe = pipe.to(torch_device)
419
+ pipe.set_progress_bar_config(disable=None)
420
+ pipe.enable_attention_slicing()
421
+
422
+ inputs = self.get_inputs()
423
+ pipe(**inputs, callback=callback_fn, callback_steps=1)
424
+ assert callback_fn.has_been_called
425
+ assert number_of_steps == 3
426
+
427
+ def test_stable_diffusion_panorama_pipeline_with_sequential_cpu_offloading(self):
428
+ backend_empty_cache(torch_device)
429
+ backend_reset_max_memory_allocated(torch_device)
430
+ backend_reset_peak_memory_stats(torch_device)
431
+
432
+ model_ckpt = "stabilityai/stable-diffusion-2-base"
433
+ scheduler = DDIMScheduler.from_pretrained(model_ckpt, subfolder="scheduler")
434
+ pipe = StableDiffusionPanoramaPipeline.from_pretrained(model_ckpt, scheduler=scheduler, safety_checker=None)
435
+ pipe.set_progress_bar_config(disable=None)
436
+ pipe.enable_attention_slicing(1)
437
+ pipe.enable_sequential_cpu_offload()
438
+
439
+ inputs = self.get_inputs()
440
+ _ = pipe(**inputs)
441
+
442
+ mem_bytes = backend_max_memory_allocated(torch_device)
443
+ # make sure that less than 5.2 GB is allocated
444
+ assert mem_bytes < 5.5 * 10**9
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_safe/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_safe/test_safe_diffusion.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import gc
17
+ import random
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
24
+
25
+ from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNet2DConditionModel
26
+ from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
27
+ from diffusers.utils.testing_utils import (
28
+ Expectations,
29
+ backend_empty_cache,
30
+ floats_tensor,
31
+ nightly,
32
+ require_accelerator,
33
+ require_torch_accelerator,
34
+ torch_device,
35
+ )
36
+
37
+
38
+ class SafeDiffusionPipelineFastTests(unittest.TestCase):
39
+ def setUp(self):
40
+ # clean up the VRAM before each test
41
+ super().setUp()
42
+ gc.collect()
43
+ backend_empty_cache(torch_device)
44
+
45
+ def tearDown(self):
46
+ # clean up the VRAM after each test
47
+ super().tearDown()
48
+ gc.collect()
49
+ backend_empty_cache(torch_device)
50
+
51
+ @property
52
+ def dummy_image(self):
53
+ batch_size = 1
54
+ num_channels = 3
55
+ sizes = (32, 32)
56
+
57
+ image = floats_tensor((batch_size, num_channels) + sizes, rng=random.Random(0)).to(torch_device)
58
+ return image
59
+
60
+ @property
61
+ def dummy_cond_unet(self):
62
+ torch.manual_seed(0)
63
+ model = UNet2DConditionModel(
64
+ block_out_channels=(32, 64),
65
+ layers_per_block=2,
66
+ sample_size=32,
67
+ in_channels=4,
68
+ out_channels=4,
69
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
70
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
71
+ cross_attention_dim=32,
72
+ )
73
+ return model
74
+
75
+ @property
76
+ def dummy_vae(self):
77
+ torch.manual_seed(0)
78
+ model = AutoencoderKL(
79
+ block_out_channels=[32, 64],
80
+ in_channels=3,
81
+ out_channels=3,
82
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
83
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
84
+ latent_channels=4,
85
+ )
86
+ return model
87
+
88
+ @property
89
+ def dummy_text_encoder(self):
90
+ torch.manual_seed(0)
91
+ config = CLIPTextConfig(
92
+ bos_token_id=0,
93
+ eos_token_id=2,
94
+ hidden_size=32,
95
+ intermediate_size=37,
96
+ layer_norm_eps=1e-05,
97
+ num_attention_heads=4,
98
+ num_hidden_layers=5,
99
+ pad_token_id=1,
100
+ vocab_size=1000,
101
+ )
102
+ return CLIPTextModel(config)
103
+
104
+ @property
105
+ def dummy_extractor(self):
106
+ def extract(*args, **kwargs):
107
+ class Out:
108
+ def __init__(self):
109
+ self.pixel_values = torch.ones([0])
110
+
111
+ def to(self, device):
112
+ self.pixel_values.to(device)
113
+ return self
114
+
115
+ return Out()
116
+
117
+ return extract
118
+
119
+ def test_safe_diffusion_ddim(self):
120
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
121
+ unet = self.dummy_cond_unet
122
+ scheduler = DDIMScheduler(
123
+ beta_start=0.00085,
124
+ beta_end=0.012,
125
+ beta_schedule="scaled_linear",
126
+ clip_sample=False,
127
+ set_alpha_to_one=False,
128
+ )
129
+
130
+ vae = self.dummy_vae
131
+ bert = self.dummy_text_encoder
132
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
133
+
134
+ # make sure here that pndm scheduler skips prk
135
+ sd_pipe = StableDiffusionPipeline(
136
+ unet=unet,
137
+ scheduler=scheduler,
138
+ vae=vae,
139
+ text_encoder=bert,
140
+ tokenizer=tokenizer,
141
+ safety_checker=None,
142
+ feature_extractor=self.dummy_extractor,
143
+ )
144
+ sd_pipe = sd_pipe.to(device)
145
+ sd_pipe.set_progress_bar_config(disable=None)
146
+
147
+ prompt = "A painting of a squirrel eating a burger"
148
+
149
+ generator = torch.Generator(device=device).manual_seed(0)
150
+ output = sd_pipe([prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np")
151
+ image = output.images
152
+
153
+ generator = torch.Generator(device=device).manual_seed(0)
154
+ image_from_tuple = sd_pipe(
155
+ [prompt],
156
+ generator=generator,
157
+ guidance_scale=6.0,
158
+ num_inference_steps=2,
159
+ output_type="np",
160
+ return_dict=False,
161
+ )[0]
162
+
163
+ image_slice = image[0, -3:, -3:, -1]
164
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
165
+
166
+ assert image.shape == (1, 64, 64, 3)
167
+ expected_slice = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864])
168
+
169
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
170
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
171
+
172
+ def test_stable_diffusion_pndm(self):
173
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
174
+ unet = self.dummy_cond_unet
175
+ scheduler = PNDMScheduler(skip_prk_steps=True)
176
+ vae = self.dummy_vae
177
+ bert = self.dummy_text_encoder
178
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
179
+
180
+ # make sure here that pndm scheduler skips prk
181
+ sd_pipe = StableDiffusionPipeline(
182
+ unet=unet,
183
+ scheduler=scheduler,
184
+ vae=vae,
185
+ text_encoder=bert,
186
+ tokenizer=tokenizer,
187
+ safety_checker=None,
188
+ feature_extractor=self.dummy_extractor,
189
+ )
190
+ sd_pipe = sd_pipe.to(device)
191
+ sd_pipe.set_progress_bar_config(disable=None)
192
+
193
+ prompt = "A painting of a squirrel eating a burger"
194
+ generator = torch.Generator(device=device).manual_seed(0)
195
+ output = sd_pipe([prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np")
196
+
197
+ image = output.images
198
+
199
+ generator = torch.Generator(device=device).manual_seed(0)
200
+ image_from_tuple = sd_pipe(
201
+ [prompt],
202
+ generator=generator,
203
+ guidance_scale=6.0,
204
+ num_inference_steps=2,
205
+ output_type="np",
206
+ return_dict=False,
207
+ )[0]
208
+
209
+ image_slice = image[0, -3:, -3:, -1]
210
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
211
+
212
+ assert image.shape == (1, 64, 64, 3)
213
+ expected_slice = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993])
214
+
215
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
216
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
217
+
218
+ def test_stable_diffusion_no_safety_checker(self):
219
+ pipe = StableDiffusionPipeline.from_pretrained(
220
+ "hf-internal-testing/tiny-stable-diffusion-lms-pipe", safety_checker=None
221
+ )
222
+ assert isinstance(pipe, StableDiffusionPipeline)
223
+ assert isinstance(pipe.scheduler, LMSDiscreteScheduler)
224
+ assert pipe.safety_checker is None
225
+
226
+ image = pipe("example prompt", num_inference_steps=2).images[0]
227
+ assert image is not None
228
+
229
+ # check that there's no error when saving a pipeline with one of the models being None
230
+ with tempfile.TemporaryDirectory() as tmpdirname:
231
+ pipe.save_pretrained(tmpdirname)
232
+ pipe = StableDiffusionPipeline.from_pretrained(tmpdirname)
233
+
234
+ # sanity check that the pipeline still works
235
+ assert pipe.safety_checker is None
236
+ image = pipe("example prompt", num_inference_steps=2).images[0]
237
+ assert image is not None
238
+
239
+ @require_accelerator
240
+ def test_stable_diffusion_fp16(self):
241
+ """Test that stable diffusion works with fp16"""
242
+ unet = self.dummy_cond_unet
243
+ scheduler = PNDMScheduler(skip_prk_steps=True)
244
+ vae = self.dummy_vae
245
+ bert = self.dummy_text_encoder
246
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
247
+
248
+ # put models in fp16
249
+ unet = unet.half()
250
+ vae = vae.half()
251
+ bert = bert.half()
252
+
253
+ # make sure here that pndm scheduler skips prk
254
+ sd_pipe = StableDiffusionPipeline(
255
+ unet=unet,
256
+ scheduler=scheduler,
257
+ vae=vae,
258
+ text_encoder=bert,
259
+ tokenizer=tokenizer,
260
+ safety_checker=None,
261
+ feature_extractor=self.dummy_extractor,
262
+ )
263
+ sd_pipe = sd_pipe.to(torch_device)
264
+ sd_pipe.set_progress_bar_config(disable=None)
265
+
266
+ prompt = "A painting of a squirrel eating a burger"
267
+ image = sd_pipe([prompt], num_inference_steps=2, output_type="np").images
268
+
269
+ assert image.shape == (1, 64, 64, 3)
270
+
271
+
272
+ @nightly
273
+ @require_torch_accelerator
274
+ class SafeDiffusionPipelineIntegrationTests(unittest.TestCase):
275
+ def setUp(self):
276
+ # clean up the VRAM before each test
277
+ super().setUp()
278
+ gc.collect()
279
+ backend_empty_cache(torch_device)
280
+
281
+ def tearDown(self):
282
+ # clean up the VRAM after each test
283
+ super().tearDown()
284
+ gc.collect()
285
+ backend_empty_cache(torch_device)
286
+
287
+ def test_harm_safe_stable_diffusion(self):
288
+ sd_pipe = StableDiffusionPipeline.from_pretrained(
289
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None
290
+ )
291
+ sd_pipe.scheduler = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config)
292
+ sd_pipe = sd_pipe.to(torch_device)
293
+ sd_pipe.set_progress_bar_config(disable=None)
294
+
295
+ prompt = (
296
+ "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"
297
+ " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"
298
+ " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"
299
+ " children from bahnhof zoo, detailed "
300
+ )
301
+ seed = 4003660346
302
+ guidance_scale = 7
303
+
304
+ # without safety guidance (sld_guidance_scale = 0)
305
+ generator = torch.manual_seed(seed)
306
+ output = sd_pipe(
307
+ [prompt],
308
+ generator=generator,
309
+ guidance_scale=guidance_scale,
310
+ num_inference_steps=50,
311
+ output_type="np",
312
+ width=512,
313
+ height=512,
314
+ sld_guidance_scale=0,
315
+ )
316
+
317
+ image = output.images
318
+ image_slice = image[0, -3:, -3:, -1]
319
+ expected_slices = Expectations(
320
+ {
321
+ ("xpu", 3): [0.0076, 0.0058, 0.0012, 0, 0.0047, 0.0046, 0, 0, 0],
322
+ ("cuda", 7): [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176],
323
+ ("cuda", 8): [0.0076, 0.0058, 0.0012, 0, 0.0047, 0.0046, 0, 0, 0],
324
+ }
325
+ )
326
+ expected_slice = expected_slices.get_expectation()
327
+
328
+ assert image.shape == (1, 512, 512, 3)
329
+
330
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
331
+
332
+ # without safety guidance (strong configuration)
333
+ generator = torch.manual_seed(seed)
334
+ output = sd_pipe(
335
+ [prompt],
336
+ generator=generator,
337
+ guidance_scale=guidance_scale,
338
+ num_inference_steps=50,
339
+ output_type="np",
340
+ width=512,
341
+ height=512,
342
+ sld_guidance_scale=2000,
343
+ sld_warmup_steps=7,
344
+ sld_threshold=0.025,
345
+ sld_momentum_scale=0.5,
346
+ sld_mom_beta=0.7,
347
+ )
348
+
349
+ image = output.images
350
+ image_slice = image[0, -3:, -3:, -1]
351
+ expected_slice = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719]
352
+
353
+ expected_slices = Expectations(
354
+ {
355
+ ("xpu", 3): [0.0443, 0.0439, 0.0381, 0.0336, 0.0408, 0.0345, 0.0405, 0.0338, 0.0293],
356
+ ("cuda", 7): [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719],
357
+ ("cuda", 8): [0.0443, 0.0439, 0.0381, 0.0336, 0.0408, 0.0345, 0.0405, 0.0338, 0.0293],
358
+ }
359
+ )
360
+ expected_slice = expected_slices.get_expectation()
361
+
362
+ assert image.shape == (1, 512, 512, 3)
363
+
364
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
365
+
366
+ def test_nudity_safe_stable_diffusion(self):
367
+ sd_pipe = StableDiffusionPipeline.from_pretrained(
368
+ "stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None
369
+ )
370
+ sd_pipe.scheduler = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config)
371
+ sd_pipe = sd_pipe.to(torch_device)
372
+ sd_pipe.set_progress_bar_config(disable=None)
373
+
374
+ prompt = "padme amidala taking a bath artwork, safe for work, no nudity"
375
+ seed = 2734971755
376
+ guidance_scale = 7
377
+
378
+ generator = torch.manual_seed(seed)
379
+ output = sd_pipe(
380
+ [prompt],
381
+ generator=generator,
382
+ guidance_scale=guidance_scale,
383
+ num_inference_steps=50,
384
+ output_type="np",
385
+ width=512,
386
+ height=512,
387
+ sld_guidance_scale=0,
388
+ )
389
+
390
+ image = output.images
391
+ image_slice = image[0, -3:, -3:, -1]
392
+ expected_slices = Expectations(
393
+ {
394
+ ("xpu", 3): [0.3244, 0.3355, 0.3260, 0.3123, 0.3246, 0.3426, 0.3109, 0.3471, 0.4001],
395
+ ("cuda", 7): [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297],
396
+ ("cuda", 8): [0.3605, 0.3684, 0.3712, 0.3624, 0.3675, 0.3726, 0.3494, 0.3748, 0.4044],
397
+ }
398
+ )
399
+ expected_slice = expected_slices.get_expectation()
400
+ assert image.shape == (1, 512, 512, 3)
401
+
402
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
403
+
404
+ generator = torch.manual_seed(seed)
405
+ output = sd_pipe(
406
+ [prompt],
407
+ generator=generator,
408
+ guidance_scale=guidance_scale,
409
+ num_inference_steps=50,
410
+ output_type="np",
411
+ width=512,
412
+ height=512,
413
+ sld_guidance_scale=2000,
414
+ sld_warmup_steps=7,
415
+ sld_threshold=0.025,
416
+ sld_momentum_scale=0.5,
417
+ sld_mom_beta=0.7,
418
+ )
419
+
420
+ image = output.images
421
+ image_slice = image[0, -3:, -3:, -1]
422
+ expected_slices = Expectations(
423
+ {
424
+ ("xpu", 3): [0.6178, 0.6260, 0.6194, 0.6435, 0.6265, 0.6461, 0.6567, 0.6576, 0.6444],
425
+ ("cuda", 7): [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443],
426
+ ("cuda", 8): [0.5892, 0.5959, 0.5914, 0.6123, 0.5982, 0.6141, 0.6180, 0.6262, 0.6171],
427
+ }
428
+ )
429
+
430
+ print(f"image_slice: {image_slice.flatten()}")
431
+ expected_slice = expected_slices.get_expectation()
432
+
433
+ assert image.shape == (1, 512, 512, 3)
434
+
435
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
436
+
437
+ def test_nudity_safetychecker_safe_stable_diffusion(self):
438
+ sd_pipe = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")
439
+ sd_pipe = sd_pipe.to(torch_device)
440
+ sd_pipe.set_progress_bar_config(disable=None)
441
+
442
+ prompt = (
443
+ "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."
444
+ " leyendecker"
445
+ )
446
+ seed = 1044355234
447
+ guidance_scale = 12
448
+
449
+ generator = torch.manual_seed(seed)
450
+ output = sd_pipe(
451
+ [prompt],
452
+ generator=generator,
453
+ guidance_scale=guidance_scale,
454
+ num_inference_steps=50,
455
+ output_type="np",
456
+ width=512,
457
+ height=512,
458
+ sld_guidance_scale=0,
459
+ )
460
+
461
+ image = output.images
462
+ image_slice = image[0, -3:, -3:, -1]
463
+ expected_slice = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
464
+
465
+ assert image.shape == (1, 512, 512, 3)
466
+
467
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-7
468
+
469
+ generator = torch.manual_seed(seed)
470
+ output = sd_pipe(
471
+ [prompt],
472
+ generator=generator,
473
+ guidance_scale=guidance_scale,
474
+ num_inference_steps=50,
475
+ output_type="np",
476
+ width=512,
477
+ height=512,
478
+ sld_guidance_scale=2000,
479
+ sld_warmup_steps=7,
480
+ sld_threshold=0.025,
481
+ sld_momentum_scale=0.5,
482
+ sld_mom_beta=0.7,
483
+ )
484
+
485
+ image = output.images
486
+ image_slice = image[0, -3:, -3:, -1]
487
+ expected_slices = Expectations(
488
+ {
489
+ ("xpu", 3): np.array([0.0695, 0.1244, 0.1831, 0.0527, 0.0444, 0.1660, 0.0572, 0.0677, 0.1551]),
490
+ ("cuda", 7): np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561]),
491
+ ("cuda", 8): np.array([0.0695, 0.1244, 0.1831, 0.0527, 0.0444, 0.1660, 0.0572, 0.0677, 0.1551]),
492
+ }
493
+ )
494
+ expected_slice = expected_slices.get_expectation()
495
+
496
+ assert image.shape == (1, 512, 512, 3)
497
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_sag/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_sag/test_stable_diffusion_sag.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers import (
24
+ AutoencoderKL,
25
+ DDIMScheduler,
26
+ DEISMultistepScheduler,
27
+ DPMSolverMultistepScheduler,
28
+ EulerDiscreteScheduler,
29
+ StableDiffusionSAGPipeline,
30
+ UNet2DConditionModel,
31
+ )
32
+ from diffusers.utils.testing_utils import (
33
+ backend_empty_cache,
34
+ enable_full_determinism,
35
+ nightly,
36
+ require_torch_accelerator,
37
+ torch_device,
38
+ )
39
+
40
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
41
+ from ..test_pipelines_common import (
42
+ IPAdapterTesterMixin,
43
+ PipelineFromPipeTesterMixin,
44
+ PipelineLatentTesterMixin,
45
+ PipelineTesterMixin,
46
+ )
47
+
48
+
49
+ enable_full_determinism()
50
+
51
+
52
+ class StableDiffusionSAGPipelineFastTests(
53
+ IPAdapterTesterMixin,
54
+ PipelineLatentTesterMixin,
55
+ PipelineTesterMixin,
56
+ PipelineFromPipeTesterMixin,
57
+ unittest.TestCase,
58
+ ):
59
+ pipeline_class = StableDiffusionSAGPipeline
60
+ params = TEXT_TO_IMAGE_PARAMS
61
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
62
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
63
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
64
+
65
+ def get_dummy_components(self):
66
+ torch.manual_seed(0)
67
+ unet = UNet2DConditionModel(
68
+ block_out_channels=(4, 8),
69
+ layers_per_block=2,
70
+ sample_size=8,
71
+ norm_num_groups=1,
72
+ in_channels=4,
73
+ out_channels=4,
74
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
75
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
76
+ cross_attention_dim=8,
77
+ )
78
+ scheduler = DDIMScheduler(
79
+ beta_start=0.00085,
80
+ beta_end=0.012,
81
+ beta_schedule="scaled_linear",
82
+ clip_sample=False,
83
+ set_alpha_to_one=False,
84
+ )
85
+ torch.manual_seed(0)
86
+ vae = AutoencoderKL(
87
+ block_out_channels=[4, 8],
88
+ norm_num_groups=1,
89
+ in_channels=3,
90
+ out_channels=3,
91
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
92
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
93
+ latent_channels=4,
94
+ )
95
+ torch.manual_seed(0)
96
+ text_encoder_config = CLIPTextConfig(
97
+ bos_token_id=0,
98
+ eos_token_id=2,
99
+ hidden_size=8,
100
+ num_hidden_layers=2,
101
+ intermediate_size=37,
102
+ layer_norm_eps=1e-05,
103
+ num_attention_heads=4,
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
+
110
+ components = {
111
+ "unet": unet,
112
+ "scheduler": scheduler,
113
+ "vae": vae,
114
+ "text_encoder": text_encoder,
115
+ "tokenizer": tokenizer,
116
+ "safety_checker": None,
117
+ "feature_extractor": None,
118
+ "image_encoder": None,
119
+ }
120
+ return components
121
+
122
+ def get_dummy_inputs(self, device, seed=0):
123
+ if str(device).startswith("mps"):
124
+ generator = torch.manual_seed(seed)
125
+ else:
126
+ generator = torch.Generator(device=device).manual_seed(seed)
127
+ inputs = {
128
+ "prompt": ".",
129
+ "generator": generator,
130
+ "num_inference_steps": 2,
131
+ "guidance_scale": 1.0,
132
+ "sag_scale": 1.0,
133
+ "output_type": "np",
134
+ }
135
+ return inputs
136
+
137
+ def test_inference_batch_single_identical(self):
138
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
139
+
140
+ @unittest.skip("Not necessary to test here.")
141
+ def test_xformers_attention_forwardGenerator_pass(self):
142
+ pass
143
+
144
+ def test_pipeline_different_schedulers(self):
145
+ pipeline = self.pipeline_class(**self.get_dummy_components())
146
+ inputs = self.get_dummy_inputs("cpu")
147
+
148
+ expected_image_size = (16, 16, 3)
149
+ for scheduler_cls in [DDIMScheduler, DEISMultistepScheduler, DPMSolverMultistepScheduler]:
150
+ pipeline.scheduler = scheduler_cls.from_config(pipeline.scheduler.config)
151
+ image = pipeline(**inputs).images[0]
152
+
153
+ shape = image.shape
154
+ assert shape == expected_image_size
155
+
156
+ pipeline.scheduler = EulerDiscreteScheduler.from_config(pipeline.scheduler.config)
157
+
158
+ with self.assertRaises(ValueError):
159
+ # Karras schedulers are not supported
160
+ image = pipeline(**inputs).images[0]
161
+
162
+ def test_encode_prompt_works_in_isolation(self):
163
+ extra_required_param_value_dict = {
164
+ "device": torch.device(torch_device).type,
165
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
166
+ }
167
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
168
+
169
+
170
+ @nightly
171
+ @require_torch_accelerator
172
+ class StableDiffusionPipelineIntegrationTests(unittest.TestCase):
173
+ def setUp(self):
174
+ # clean up the VRAM before each test
175
+ super().setUp()
176
+ gc.collect()
177
+ backend_empty_cache(torch_device)
178
+
179
+ def tearDown(self):
180
+ # clean up the VRAM after each test
181
+ super().tearDown()
182
+ gc.collect()
183
+ backend_empty_cache(torch_device)
184
+
185
+ def test_stable_diffusion_1(self):
186
+ sag_pipe = StableDiffusionSAGPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
187
+ sag_pipe = sag_pipe.to(torch_device)
188
+ sag_pipe.set_progress_bar_config(disable=None)
189
+
190
+ prompt = "."
191
+ generator = torch.manual_seed(0)
192
+ output = sag_pipe(
193
+ [prompt], generator=generator, guidance_scale=7.5, sag_scale=1.0, num_inference_steps=20, output_type="np"
194
+ )
195
+
196
+ image = output.images
197
+
198
+ image_slice = image[0, -3:, -3:, -1]
199
+
200
+ assert image.shape == (1, 512, 512, 3)
201
+ expected_slice = np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949])
202
+
203
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2
204
+
205
+ def test_stable_diffusion_2(self):
206
+ sag_pipe = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base")
207
+ sag_pipe = sag_pipe.to(torch_device)
208
+ sag_pipe.set_progress_bar_config(disable=None)
209
+
210
+ prompt = "."
211
+ generator = torch.manual_seed(0)
212
+ output = sag_pipe(
213
+ [prompt], generator=generator, guidance_scale=7.5, sag_scale=1.0, num_inference_steps=20, output_type="np"
214
+ )
215
+
216
+ image = output.images
217
+
218
+ image_slice = image[0, -3:, -3:, -1]
219
+
220
+ assert image.shape == (1, 512, 512, 3)
221
+ expected_slice = np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371])
222
+
223
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-2
224
+
225
+ def test_stable_diffusion_2_non_square(self):
226
+ sag_pipe = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base")
227
+ sag_pipe = sag_pipe.to(torch_device)
228
+ sag_pipe.set_progress_bar_config(disable=None)
229
+
230
+ prompt = "."
231
+ generator = torch.manual_seed(0)
232
+ output = sag_pipe(
233
+ [prompt],
234
+ width=768,
235
+ height=512,
236
+ generator=generator,
237
+ guidance_scale=7.5,
238
+ sag_scale=1.0,
239
+ num_inference_steps=20,
240
+ output_type="np",
241
+ )
242
+
243
+ image = output.images
244
+
245
+ assert image.shape == (1, 512, 768, 3)
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl.py ADDED
@@ -0,0 +1,975 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 copy
17
+ import gc
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
24
+
25
+ from diffusers import (
26
+ AutoencoderKL,
27
+ DDIMScheduler,
28
+ DPMSolverMultistepScheduler,
29
+ EulerDiscreteScheduler,
30
+ HeunDiscreteScheduler,
31
+ LCMScheduler,
32
+ StableDiffusionXLImg2ImgPipeline,
33
+ StableDiffusionXLPipeline,
34
+ UNet2DConditionModel,
35
+ UniPCMultistepScheduler,
36
+ )
37
+ from diffusers.utils.testing_utils import (
38
+ enable_full_determinism,
39
+ load_image,
40
+ numpy_cosine_similarity_distance,
41
+ require_torch_accelerator,
42
+ slow,
43
+ torch_device,
44
+ )
45
+
46
+ from ..pipeline_params import (
47
+ TEXT_TO_IMAGE_BATCH_PARAMS,
48
+ TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
49
+ TEXT_TO_IMAGE_IMAGE_PARAMS,
50
+ TEXT_TO_IMAGE_PARAMS,
51
+ )
52
+ from ..test_pipelines_common import (
53
+ IPAdapterTesterMixin,
54
+ PipelineLatentTesterMixin,
55
+ PipelineTesterMixin,
56
+ SDFunctionTesterMixin,
57
+ )
58
+
59
+
60
+ enable_full_determinism()
61
+
62
+
63
+ class StableDiffusionXLPipelineFastTests(
64
+ SDFunctionTesterMixin,
65
+ IPAdapterTesterMixin,
66
+ PipelineLatentTesterMixin,
67
+ PipelineTesterMixin,
68
+ unittest.TestCase,
69
+ ):
70
+ pipeline_class = StableDiffusionXLPipeline
71
+ params = TEXT_TO_IMAGE_PARAMS
72
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
73
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
74
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
75
+ callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union({"add_text_embeds", "add_time_ids"})
76
+ test_layerwise_casting = True
77
+ test_group_offloading = True
78
+
79
+ def get_dummy_components(self, time_cond_proj_dim=None):
80
+ torch.manual_seed(0)
81
+ unet = UNet2DConditionModel(
82
+ block_out_channels=(2, 4),
83
+ layers_per_block=2,
84
+ time_cond_proj_dim=time_cond_proj_dim,
85
+ sample_size=32,
86
+ in_channels=4,
87
+ out_channels=4,
88
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
89
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
90
+ # SD2-specific config below
91
+ attention_head_dim=(2, 4),
92
+ use_linear_projection=True,
93
+ addition_embed_type="text_time",
94
+ addition_time_embed_dim=8,
95
+ transformer_layers_per_block=(1, 2),
96
+ projection_class_embeddings_input_dim=80, # 6 * 8 + 32
97
+ cross_attention_dim=64,
98
+ norm_num_groups=1,
99
+ )
100
+ scheduler = EulerDiscreteScheduler(
101
+ beta_start=0.00085,
102
+ beta_end=0.012,
103
+ steps_offset=1,
104
+ beta_schedule="scaled_linear",
105
+ timestep_spacing="leading",
106
+ )
107
+ torch.manual_seed(0)
108
+ vae = AutoencoderKL(
109
+ block_out_channels=[32, 64],
110
+ in_channels=3,
111
+ out_channels=3,
112
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
113
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
114
+ latent_channels=4,
115
+ sample_size=128,
116
+ )
117
+ torch.manual_seed(0)
118
+ text_encoder_config = CLIPTextConfig(
119
+ bos_token_id=0,
120
+ eos_token_id=2,
121
+ hidden_size=32,
122
+ intermediate_size=37,
123
+ layer_norm_eps=1e-05,
124
+ num_attention_heads=4,
125
+ num_hidden_layers=5,
126
+ pad_token_id=1,
127
+ vocab_size=1000,
128
+ # SD2-specific config below
129
+ hidden_act="gelu",
130
+ projection_dim=32,
131
+ )
132
+ text_encoder = CLIPTextModel(text_encoder_config)
133
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
134
+
135
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
136
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
137
+
138
+ components = {
139
+ "unet": unet,
140
+ "scheduler": scheduler,
141
+ "vae": vae,
142
+ "text_encoder": text_encoder,
143
+ "tokenizer": tokenizer,
144
+ "text_encoder_2": text_encoder_2,
145
+ "tokenizer_2": tokenizer_2,
146
+ "image_encoder": None,
147
+ "feature_extractor": None,
148
+ }
149
+ return components
150
+
151
+ def get_dummy_inputs(self, device, seed=0):
152
+ if str(device).startswith("mps"):
153
+ generator = torch.manual_seed(seed)
154
+ else:
155
+ generator = torch.Generator(device=device).manual_seed(seed)
156
+ inputs = {
157
+ "prompt": "A painting of a squirrel eating a burger",
158
+ "generator": generator,
159
+ "num_inference_steps": 2,
160
+ "guidance_scale": 5.0,
161
+ "output_type": "np",
162
+ }
163
+ return inputs
164
+
165
+ def test_stable_diffusion_xl_euler(self):
166
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
167
+ components = self.get_dummy_components()
168
+ sd_pipe = StableDiffusionXLPipeline(**components)
169
+ sd_pipe = sd_pipe.to(device)
170
+ sd_pipe.set_progress_bar_config(disable=None)
171
+
172
+ inputs = self.get_dummy_inputs(device)
173
+ image = sd_pipe(**inputs).images
174
+ image_slice = image[0, -3:, -3:, -1]
175
+
176
+ assert image.shape == (1, 64, 64, 3)
177
+ expected_slice = np.array([0.5388, 0.5452, 0.4694, 0.4583, 0.5253, 0.4832, 0.5288, 0.5035, 0.47])
178
+
179
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
180
+
181
+ def test_stable_diffusion_xl_euler_lcm(self):
182
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
183
+ components = self.get_dummy_components(time_cond_proj_dim=256)
184
+ sd_pipe = StableDiffusionXLPipeline(**components)
185
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
186
+ sd_pipe = sd_pipe.to(device)
187
+ sd_pipe.set_progress_bar_config(disable=None)
188
+
189
+ inputs = self.get_dummy_inputs(device)
190
+ image = sd_pipe(**inputs).images
191
+ image_slice = image[0, -3:, -3:, -1]
192
+
193
+ assert image.shape == (1, 64, 64, 3)
194
+ expected_slice = np.array([0.4917, 0.6555, 0.4348, 0.5219, 0.7324, 0.4855, 0.5168, 0.5447, 0.5156])
195
+
196
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
197
+
198
+ def test_stable_diffusion_xl_euler_lcm_custom_timesteps(self):
199
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
200
+ components = self.get_dummy_components(time_cond_proj_dim=256)
201
+ sd_pipe = StableDiffusionXLPipeline(**components)
202
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
203
+ sd_pipe = sd_pipe.to(device)
204
+ sd_pipe.set_progress_bar_config(disable=None)
205
+
206
+ inputs = self.get_dummy_inputs(device)
207
+ del inputs["num_inference_steps"]
208
+ inputs["timesteps"] = [999, 499]
209
+ image = sd_pipe(**inputs).images
210
+ image_slice = image[0, -3:, -3:, -1]
211
+
212
+ assert image.shape == (1, 64, 64, 3)
213
+ expected_slice = np.array([0.4917, 0.6555, 0.4348, 0.5219, 0.7324, 0.4855, 0.5168, 0.5447, 0.5156])
214
+
215
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
216
+
217
+ def test_stable_diffusion_ays(self):
218
+ from diffusers.schedulers import AysSchedules
219
+
220
+ timestep_schedule = AysSchedules["StableDiffusionXLTimesteps"]
221
+ sigma_schedule = AysSchedules["StableDiffusionXLSigmas"]
222
+
223
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
224
+
225
+ components = self.get_dummy_components(time_cond_proj_dim=256)
226
+ sd_pipe = StableDiffusionXLPipeline(**components)
227
+ sd_pipe.scheduler = EulerDiscreteScheduler.from_config(sd_pipe.scheduler.config)
228
+ sd_pipe = sd_pipe.to(torch_device)
229
+ sd_pipe.set_progress_bar_config(disable=None)
230
+
231
+ inputs = self.get_dummy_inputs(device)
232
+ inputs["num_inference_steps"] = 10
233
+ output = sd_pipe(**inputs).images
234
+
235
+ inputs = self.get_dummy_inputs(device)
236
+ inputs["num_inference_steps"] = None
237
+ inputs["timesteps"] = timestep_schedule
238
+ output_ts = sd_pipe(**inputs).images
239
+
240
+ inputs = self.get_dummy_inputs(device)
241
+ inputs["num_inference_steps"] = None
242
+ inputs["sigmas"] = sigma_schedule
243
+ output_sigmas = sd_pipe(**inputs).images
244
+
245
+ assert np.abs(output_sigmas.flatten() - output_ts.flatten()).max() < 1e-3, (
246
+ "ays timesteps and ays sigmas should have the same outputs"
247
+ )
248
+ assert np.abs(output.flatten() - output_ts.flatten()).max() > 1e-3, (
249
+ "use ays timesteps should have different outputs"
250
+ )
251
+ assert np.abs(output.flatten() - output_sigmas.flatten()).max() > 1e-3, (
252
+ "use ays sigmas should have different outputs"
253
+ )
254
+
255
+ def test_ip_adapter(self):
256
+ expected_pipe_slice = None
257
+ if torch_device == "cpu":
258
+ expected_pipe_slice = np.array([0.5388, 0.5452, 0.4694, 0.4583, 0.5253, 0.4832, 0.5288, 0.5035, 0.4766])
259
+
260
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
261
+
262
+ def test_attention_slicing_forward_pass(self):
263
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
264
+
265
+ def test_inference_batch_single_identical(self):
266
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
267
+
268
+ @require_torch_accelerator
269
+ def test_stable_diffusion_xl_offloads(self):
270
+ pipes = []
271
+ components = self.get_dummy_components()
272
+ sd_pipe = StableDiffusionXLPipeline(**components).to(torch_device)
273
+ pipes.append(sd_pipe)
274
+
275
+ components = self.get_dummy_components()
276
+ sd_pipe = StableDiffusionXLPipeline(**components)
277
+ sd_pipe.enable_model_cpu_offload(device=torch_device)
278
+ pipes.append(sd_pipe)
279
+
280
+ components = self.get_dummy_components()
281
+ sd_pipe = StableDiffusionXLPipeline(**components)
282
+ sd_pipe.enable_sequential_cpu_offload(device=torch_device)
283
+ pipes.append(sd_pipe)
284
+
285
+ image_slices = []
286
+ for pipe in pipes:
287
+ pipe.unet.set_default_attn_processor()
288
+
289
+ inputs = self.get_dummy_inputs(torch_device)
290
+ image = pipe(**inputs).images
291
+
292
+ image_slices.append(image[0, -3:, -3:, -1].flatten())
293
+
294
+ assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
295
+ assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
296
+
297
+ @unittest.skip("We test this functionality elsewhere already.")
298
+ def test_save_load_optional_components(self):
299
+ pass
300
+
301
+ def test_stable_diffusion_two_xl_mixture_of_denoiser_fast(self):
302
+ components = self.get_dummy_components()
303
+ pipe_1 = StableDiffusionXLPipeline(**components).to(torch_device)
304
+ pipe_1.unet.set_default_attn_processor()
305
+ pipe_2 = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
306
+ pipe_2.unet.set_default_attn_processor()
307
+
308
+ def assert_run_mixture(
309
+ num_steps,
310
+ split,
311
+ scheduler_cls_orig,
312
+ expected_tss,
313
+ num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps,
314
+ ):
315
+ inputs = self.get_dummy_inputs(torch_device)
316
+ inputs["num_inference_steps"] = num_steps
317
+
318
+ class scheduler_cls(scheduler_cls_orig):
319
+ pass
320
+
321
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
322
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
323
+
324
+ # Let's retrieve the number of timesteps we want to use
325
+ pipe_1.scheduler.set_timesteps(num_steps)
326
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
327
+
328
+ if pipe_1.scheduler.order == 2:
329
+ expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
330
+ expected_steps_2 = expected_steps_1[-1:] + list(filter(lambda ts: ts < split, expected_tss))
331
+ expected_steps = expected_steps_1 + expected_steps_2
332
+ else:
333
+ expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
334
+ expected_steps_2 = list(filter(lambda ts: ts < split, expected_tss))
335
+
336
+ # now we monkey patch step `done_steps`
337
+ # list into the step function for testing
338
+ done_steps = []
339
+ old_step = copy.copy(scheduler_cls.step)
340
+
341
+ def new_step(self, *args, **kwargs):
342
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
343
+ return old_step(self, *args, **kwargs)
344
+
345
+ scheduler_cls.step = new_step
346
+
347
+ inputs_1 = {
348
+ **inputs,
349
+ **{
350
+ "denoising_end": 1.0 - (split / num_train_timesteps),
351
+ "output_type": "latent",
352
+ },
353
+ }
354
+ latents = pipe_1(**inputs_1).images[0]
355
+
356
+ assert expected_steps_1 == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
357
+
358
+ inputs_2 = {
359
+ **inputs,
360
+ **{
361
+ "denoising_start": 1.0 - (split / num_train_timesteps),
362
+ "image": latents,
363
+ },
364
+ }
365
+ pipe_2(**inputs_2).images[0]
366
+
367
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
368
+ assert expected_steps == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
369
+
370
+ steps = 10
371
+ for split in [300, 700]:
372
+ for scheduler_cls_timesteps in [
373
+ (EulerDiscreteScheduler, [901, 801, 701, 601, 501, 401, 301, 201, 101, 1]),
374
+ (
375
+ HeunDiscreteScheduler,
376
+ [
377
+ 901.0,
378
+ 801.0,
379
+ 801.0,
380
+ 701.0,
381
+ 701.0,
382
+ 601.0,
383
+ 601.0,
384
+ 501.0,
385
+ 501.0,
386
+ 401.0,
387
+ 401.0,
388
+ 301.0,
389
+ 301.0,
390
+ 201.0,
391
+ 201.0,
392
+ 101.0,
393
+ 101.0,
394
+ 1.0,
395
+ 1.0,
396
+ ],
397
+ ),
398
+ ]:
399
+ assert_run_mixture(steps, split, scheduler_cls_timesteps[0], scheduler_cls_timesteps[1])
400
+
401
+ @slow
402
+ def test_stable_diffusion_two_xl_mixture_of_denoiser(self):
403
+ components = self.get_dummy_components()
404
+ pipe_1 = StableDiffusionXLPipeline(**components).to(torch_device)
405
+ pipe_1.unet.set_default_attn_processor()
406
+ pipe_2 = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
407
+ pipe_2.unet.set_default_attn_processor()
408
+
409
+ def assert_run_mixture(
410
+ num_steps,
411
+ split,
412
+ scheduler_cls_orig,
413
+ expected_tss,
414
+ num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps,
415
+ ):
416
+ inputs = self.get_dummy_inputs(torch_device)
417
+ inputs["num_inference_steps"] = num_steps
418
+
419
+ class scheduler_cls(scheduler_cls_orig):
420
+ pass
421
+
422
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
423
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
424
+
425
+ # Let's retrieve the number of timesteps we want to use
426
+ pipe_1.scheduler.set_timesteps(num_steps)
427
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
428
+
429
+ if pipe_1.scheduler.order == 2:
430
+ expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
431
+ expected_steps_2 = expected_steps_1[-1:] + list(filter(lambda ts: ts < split, expected_tss))
432
+ expected_steps = expected_steps_1 + expected_steps_2
433
+ else:
434
+ expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
435
+ expected_steps_2 = list(filter(lambda ts: ts < split, expected_tss))
436
+
437
+ # now we monkey patch step `done_steps`
438
+ # list into the step function for testing
439
+ done_steps = []
440
+ old_step = copy.copy(scheduler_cls.step)
441
+
442
+ def new_step(self, *args, **kwargs):
443
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
444
+ return old_step(self, *args, **kwargs)
445
+
446
+ scheduler_cls.step = new_step
447
+
448
+ inputs_1 = {
449
+ **inputs,
450
+ **{
451
+ "denoising_end": 1.0 - (split / num_train_timesteps),
452
+ "output_type": "latent",
453
+ },
454
+ }
455
+ latents = pipe_1(**inputs_1).images[0]
456
+
457
+ assert expected_steps_1 == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
458
+
459
+ inputs_2 = {
460
+ **inputs,
461
+ **{
462
+ "denoising_start": 1.0 - (split / num_train_timesteps),
463
+ "image": latents,
464
+ },
465
+ }
466
+ pipe_2(**inputs_2).images[0]
467
+
468
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
469
+ assert expected_steps == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
470
+
471
+ steps = 10
472
+ for split in [300, 500, 700]:
473
+ for scheduler_cls_timesteps in [
474
+ (DDIMScheduler, [901, 801, 701, 601, 501, 401, 301, 201, 101, 1]),
475
+ (EulerDiscreteScheduler, [901, 801, 701, 601, 501, 401, 301, 201, 101, 1]),
476
+ (DPMSolverMultistepScheduler, [901, 811, 721, 631, 541, 451, 361, 271, 181, 91]),
477
+ (UniPCMultistepScheduler, [901, 811, 721, 631, 541, 451, 361, 271, 181, 91]),
478
+ (
479
+ HeunDiscreteScheduler,
480
+ [
481
+ 901.0,
482
+ 801.0,
483
+ 801.0,
484
+ 701.0,
485
+ 701.0,
486
+ 601.0,
487
+ 601.0,
488
+ 501.0,
489
+ 501.0,
490
+ 401.0,
491
+ 401.0,
492
+ 301.0,
493
+ 301.0,
494
+ 201.0,
495
+ 201.0,
496
+ 101.0,
497
+ 101.0,
498
+ 1.0,
499
+ 1.0,
500
+ ],
501
+ ),
502
+ ]:
503
+ assert_run_mixture(steps, split, scheduler_cls_timesteps[0], scheduler_cls_timesteps[1])
504
+
505
+ steps = 25
506
+ for split in [300, 500, 700]:
507
+ for scheduler_cls_timesteps in [
508
+ (
509
+ DDIMScheduler,
510
+ [
511
+ 961,
512
+ 921,
513
+ 881,
514
+ 841,
515
+ 801,
516
+ 761,
517
+ 721,
518
+ 681,
519
+ 641,
520
+ 601,
521
+ 561,
522
+ 521,
523
+ 481,
524
+ 441,
525
+ 401,
526
+ 361,
527
+ 321,
528
+ 281,
529
+ 241,
530
+ 201,
531
+ 161,
532
+ 121,
533
+ 81,
534
+ 41,
535
+ 1,
536
+ ],
537
+ ),
538
+ (
539
+ EulerDiscreteScheduler,
540
+ [
541
+ 961.0,
542
+ 921.0,
543
+ 881.0,
544
+ 841.0,
545
+ 801.0,
546
+ 761.0,
547
+ 721.0,
548
+ 681.0,
549
+ 641.0,
550
+ 601.0,
551
+ 561.0,
552
+ 521.0,
553
+ 481.0,
554
+ 441.0,
555
+ 401.0,
556
+ 361.0,
557
+ 321.0,
558
+ 281.0,
559
+ 241.0,
560
+ 201.0,
561
+ 161.0,
562
+ 121.0,
563
+ 81.0,
564
+ 41.0,
565
+ 1.0,
566
+ ],
567
+ ),
568
+ (
569
+ DPMSolverMultistepScheduler,
570
+ [
571
+ 951,
572
+ 913,
573
+ 875,
574
+ 837,
575
+ 799,
576
+ 761,
577
+ 723,
578
+ 685,
579
+ 647,
580
+ 609,
581
+ 571,
582
+ 533,
583
+ 495,
584
+ 457,
585
+ 419,
586
+ 381,
587
+ 343,
588
+ 305,
589
+ 267,
590
+ 229,
591
+ 191,
592
+ 153,
593
+ 115,
594
+ 77,
595
+ 39,
596
+ ],
597
+ ),
598
+ (
599
+ UniPCMultistepScheduler,
600
+ [
601
+ 951,
602
+ 913,
603
+ 875,
604
+ 837,
605
+ 799,
606
+ 761,
607
+ 723,
608
+ 685,
609
+ 647,
610
+ 609,
611
+ 571,
612
+ 533,
613
+ 495,
614
+ 457,
615
+ 419,
616
+ 381,
617
+ 343,
618
+ 305,
619
+ 267,
620
+ 229,
621
+ 191,
622
+ 153,
623
+ 115,
624
+ 77,
625
+ 39,
626
+ ],
627
+ ),
628
+ (
629
+ HeunDiscreteScheduler,
630
+ [
631
+ 961.0,
632
+ 921.0,
633
+ 921.0,
634
+ 881.0,
635
+ 881.0,
636
+ 841.0,
637
+ 841.0,
638
+ 801.0,
639
+ 801.0,
640
+ 761.0,
641
+ 761.0,
642
+ 721.0,
643
+ 721.0,
644
+ 681.0,
645
+ 681.0,
646
+ 641.0,
647
+ 641.0,
648
+ 601.0,
649
+ 601.0,
650
+ 561.0,
651
+ 561.0,
652
+ 521.0,
653
+ 521.0,
654
+ 481.0,
655
+ 481.0,
656
+ 441.0,
657
+ 441.0,
658
+ 401.0,
659
+ 401.0,
660
+ 361.0,
661
+ 361.0,
662
+ 321.0,
663
+ 321.0,
664
+ 281.0,
665
+ 281.0,
666
+ 241.0,
667
+ 241.0,
668
+ 201.0,
669
+ 201.0,
670
+ 161.0,
671
+ 161.0,
672
+ 121.0,
673
+ 121.0,
674
+ 81.0,
675
+ 81.0,
676
+ 41.0,
677
+ 41.0,
678
+ 1.0,
679
+ 1.0,
680
+ ],
681
+ ),
682
+ ]:
683
+ assert_run_mixture(steps, split, scheduler_cls_timesteps[0], scheduler_cls_timesteps[1])
684
+
685
+ @slow
686
+ def test_stable_diffusion_three_xl_mixture_of_denoiser(self):
687
+ components = self.get_dummy_components()
688
+ pipe_1 = StableDiffusionXLPipeline(**components).to(torch_device)
689
+ pipe_1.unet.set_default_attn_processor()
690
+ pipe_2 = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
691
+ pipe_2.unet.set_default_attn_processor()
692
+ pipe_3 = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
693
+ pipe_3.unet.set_default_attn_processor()
694
+
695
+ def assert_run_mixture(
696
+ num_steps,
697
+ split_1,
698
+ split_2,
699
+ scheduler_cls_orig,
700
+ num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps,
701
+ ):
702
+ inputs = self.get_dummy_inputs(torch_device)
703
+ inputs["num_inference_steps"] = num_steps
704
+
705
+ class scheduler_cls(scheduler_cls_orig):
706
+ pass
707
+
708
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
709
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
710
+ pipe_3.scheduler = scheduler_cls.from_config(pipe_3.scheduler.config)
711
+
712
+ # Let's retrieve the number of timesteps we want to use
713
+ pipe_1.scheduler.set_timesteps(num_steps)
714
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
715
+
716
+ split_1_ts = num_train_timesteps - int(round(num_train_timesteps * split_1))
717
+ split_2_ts = num_train_timesteps - int(round(num_train_timesteps * split_2))
718
+
719
+ if pipe_1.scheduler.order == 2:
720
+ expected_steps_1 = list(filter(lambda ts: ts >= split_1_ts, expected_steps))
721
+ expected_steps_2 = expected_steps_1[-1:] + list(
722
+ filter(lambda ts: ts >= split_2_ts and ts < split_1_ts, expected_steps)
723
+ )
724
+ expected_steps_3 = expected_steps_2[-1:] + list(filter(lambda ts: ts < split_2_ts, expected_steps))
725
+ expected_steps = expected_steps_1 + expected_steps_2 + expected_steps_3
726
+ else:
727
+ expected_steps_1 = list(filter(lambda ts: ts >= split_1_ts, expected_steps))
728
+ expected_steps_2 = list(filter(lambda ts: ts >= split_2_ts and ts < split_1_ts, expected_steps))
729
+ expected_steps_3 = list(filter(lambda ts: ts < split_2_ts, expected_steps))
730
+
731
+ # now we monkey patch step `done_steps`
732
+ # list into the step function for testing
733
+ done_steps = []
734
+ old_step = copy.copy(scheduler_cls.step)
735
+
736
+ def new_step(self, *args, **kwargs):
737
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
738
+ return old_step(self, *args, **kwargs)
739
+
740
+ scheduler_cls.step = new_step
741
+
742
+ inputs_1 = {**inputs, **{"denoising_end": split_1, "output_type": "latent"}}
743
+ latents = pipe_1(**inputs_1).images[0]
744
+
745
+ assert expected_steps_1 == done_steps, (
746
+ f"Failure with {scheduler_cls.__name__} and {num_steps} and {split_1} and {split_2}"
747
+ )
748
+
749
+ with self.assertRaises(ValueError) as cm:
750
+ inputs_2 = {
751
+ **inputs,
752
+ **{
753
+ "denoising_start": split_2,
754
+ "denoising_end": split_1,
755
+ "image": latents,
756
+ "output_type": "latent",
757
+ },
758
+ }
759
+ pipe_2(**inputs_2).images[0]
760
+ assert "cannot be larger than or equal to `denoising_end`" in str(cm.exception)
761
+
762
+ inputs_2 = {
763
+ **inputs,
764
+ **{"denoising_start": split_1, "denoising_end": split_2, "image": latents, "output_type": "latent"},
765
+ }
766
+ pipe_2(**inputs_2).images[0]
767
+
768
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
769
+
770
+ inputs_3 = {**inputs, **{"denoising_start": split_2, "image": latents}}
771
+ pipe_3(**inputs_3).images[0]
772
+
773
+ assert expected_steps_3 == done_steps[len(expected_steps_1) + len(expected_steps_2) :]
774
+ assert expected_steps == done_steps, (
775
+ f"Failure with {scheduler_cls.__name__} and {num_steps} and {split_1} and {split_2}"
776
+ )
777
+
778
+ for steps in [7, 11, 20]:
779
+ for split_1, split_2 in zip([0.19, 0.32], [0.81, 0.68]):
780
+ for scheduler_cls in [
781
+ DDIMScheduler,
782
+ EulerDiscreteScheduler,
783
+ DPMSolverMultistepScheduler,
784
+ UniPCMultistepScheduler,
785
+ HeunDiscreteScheduler,
786
+ ]:
787
+ assert_run_mixture(steps, split_1, split_2, scheduler_cls)
788
+
789
+ def test_stable_diffusion_xl_multi_prompts(self):
790
+ components = self.get_dummy_components()
791
+ sd_pipe = self.pipeline_class(**components).to(torch_device)
792
+
793
+ # forward with single prompt
794
+ inputs = self.get_dummy_inputs(torch_device)
795
+ output = sd_pipe(**inputs)
796
+ image_slice_1 = output.images[0, -3:, -3:, -1]
797
+
798
+ # forward with same prompt duplicated
799
+ inputs = self.get_dummy_inputs(torch_device)
800
+ inputs["prompt_2"] = inputs["prompt"]
801
+ output = sd_pipe(**inputs)
802
+ image_slice_2 = output.images[0, -3:, -3:, -1]
803
+
804
+ # ensure the results are equal
805
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
806
+
807
+ # forward with different prompt
808
+ inputs = self.get_dummy_inputs(torch_device)
809
+ inputs["prompt_2"] = "different prompt"
810
+ output = sd_pipe(**inputs)
811
+ image_slice_3 = output.images[0, -3:, -3:, -1]
812
+
813
+ # ensure the results are not equal
814
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
815
+
816
+ # manually set a negative_prompt
817
+ inputs = self.get_dummy_inputs(torch_device)
818
+ inputs["negative_prompt"] = "negative prompt"
819
+ output = sd_pipe(**inputs)
820
+ image_slice_1 = output.images[0, -3:, -3:, -1]
821
+
822
+ # forward with same negative_prompt duplicated
823
+ inputs = self.get_dummy_inputs(torch_device)
824
+ inputs["negative_prompt"] = "negative prompt"
825
+ inputs["negative_prompt_2"] = inputs["negative_prompt"]
826
+ output = sd_pipe(**inputs)
827
+ image_slice_2 = output.images[0, -3:, -3:, -1]
828
+
829
+ # ensure the results are equal
830
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
831
+
832
+ # forward with different negative_prompt
833
+ inputs = self.get_dummy_inputs(torch_device)
834
+ inputs["negative_prompt"] = "negative prompt"
835
+ inputs["negative_prompt_2"] = "different negative prompt"
836
+ output = sd_pipe(**inputs)
837
+ image_slice_3 = output.images[0, -3:, -3:, -1]
838
+
839
+ # ensure the results are not equal
840
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
841
+
842
+ def test_stable_diffusion_xl_negative_conditions(self):
843
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
844
+ components = self.get_dummy_components()
845
+ sd_pipe = StableDiffusionXLPipeline(**components)
846
+ sd_pipe = sd_pipe.to(device)
847
+ sd_pipe.set_progress_bar_config(disable=None)
848
+
849
+ inputs = self.get_dummy_inputs(device)
850
+ image = sd_pipe(**inputs).images
851
+ image_slice_with_no_neg_cond = image[0, -3:, -3:, -1]
852
+
853
+ image = sd_pipe(
854
+ **inputs,
855
+ negative_original_size=(512, 512),
856
+ negative_crops_coords_top_left=(0, 0),
857
+ negative_target_size=(1024, 1024),
858
+ ).images
859
+ image_slice_with_neg_cond = image[0, -3:, -3:, -1]
860
+
861
+ self.assertTrue(np.abs(image_slice_with_no_neg_cond - image_slice_with_neg_cond).max() > 1e-2)
862
+
863
+ def test_stable_diffusion_xl_save_from_pretrained(self):
864
+ pipes = []
865
+ components = self.get_dummy_components()
866
+ sd_pipe = StableDiffusionXLPipeline(**components).to(torch_device)
867
+ pipes.append(sd_pipe)
868
+
869
+ with tempfile.TemporaryDirectory() as tmpdirname:
870
+ sd_pipe.save_pretrained(tmpdirname)
871
+ sd_pipe = StableDiffusionXLPipeline.from_pretrained(tmpdirname).to(torch_device)
872
+ pipes.append(sd_pipe)
873
+
874
+ image_slices = []
875
+ for pipe in pipes:
876
+ pipe.unet.set_default_attn_processor()
877
+
878
+ inputs = self.get_dummy_inputs(torch_device)
879
+ image = pipe(**inputs).images
880
+
881
+ image_slices.append(image[0, -3:, -3:, -1].flatten())
882
+
883
+ assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
884
+
885
+ def test_pipeline_interrupt(self):
886
+ components = self.get_dummy_components()
887
+ sd_pipe = StableDiffusionXLPipeline(**components)
888
+ sd_pipe = sd_pipe.to(torch_device)
889
+ sd_pipe.set_progress_bar_config(disable=None)
890
+
891
+ prompt = "hey"
892
+ num_inference_steps = 3
893
+
894
+ # store intermediate latents from the generation process
895
+ class PipelineState:
896
+ def __init__(self):
897
+ self.state = []
898
+
899
+ def apply(self, pipe, i, t, callback_kwargs):
900
+ self.state.append(callback_kwargs["latents"])
901
+ return callback_kwargs
902
+
903
+ pipe_state = PipelineState()
904
+ sd_pipe(
905
+ prompt,
906
+ num_inference_steps=num_inference_steps,
907
+ output_type="np",
908
+ generator=torch.Generator("cpu").manual_seed(0),
909
+ callback_on_step_end=pipe_state.apply,
910
+ ).images
911
+
912
+ # interrupt generation at step index
913
+ interrupt_step_idx = 1
914
+
915
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
916
+ if i == interrupt_step_idx:
917
+ pipe._interrupt = True
918
+
919
+ return callback_kwargs
920
+
921
+ output_interrupted = sd_pipe(
922
+ prompt,
923
+ num_inference_steps=num_inference_steps,
924
+ output_type="latent",
925
+ generator=torch.Generator("cpu").manual_seed(0),
926
+ callback_on_step_end=callback_on_step_end,
927
+ ).images
928
+
929
+ # fetch intermediate latents at the interrupted step
930
+ # from the completed generation process
931
+ intermediate_latent = pipe_state.state[interrupt_step_idx]
932
+
933
+ # compare the intermediate latent to the output of the interrupted process
934
+ # they should be the same
935
+ assert torch.allclose(intermediate_latent, output_interrupted, atol=1e-4)
936
+
937
+
938
+ @slow
939
+ class StableDiffusionXLPipelineIntegrationTests(unittest.TestCase):
940
+ def setUp(self):
941
+ super().setUp()
942
+ gc.collect()
943
+ torch.cuda.empty_cache()
944
+
945
+ def tearDown(self):
946
+ super().tearDown()
947
+ gc.collect()
948
+ torch.cuda.empty_cache()
949
+
950
+ def test_stable_diffusion_lcm(self):
951
+ torch.manual_seed(0)
952
+ unet = UNet2DConditionModel.from_pretrained(
953
+ "latent-consistency/lcm-ssd-1b", torch_dtype=torch.float16, variant="fp16"
954
+ )
955
+ sd_pipe = StableDiffusionXLPipeline.from_pretrained(
956
+ "segmind/SSD-1B", unet=unet, torch_dtype=torch.float16, variant="fp16"
957
+ ).to(torch_device)
958
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
959
+ sd_pipe.set_progress_bar_config(disable=None)
960
+
961
+ prompt = "a red car standing on the side of the street"
962
+
963
+ image = sd_pipe(
964
+ prompt, num_inference_steps=4, guidance_scale=8.0, generator=torch.Generator("cpu").manual_seed(0)
965
+ ).images[0]
966
+ expected_image = load_image(
967
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/lcm_full/stable_diffusion_ssd_1b_lcm.png"
968
+ )
969
+
970
+ image = sd_pipe.image_processor.pil_to_numpy(image)
971
+ expected_image = sd_pipe.image_processor.pil_to_numpy(expected_image)
972
+
973
+ max_diff = numpy_cosine_similarity_distance(image.flatten(), expected_image.flatten())
974
+
975
+ assert max_diff < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_adapter.py ADDED
@@ -0,0 +1,671 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 random
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from parameterized import parameterized
22
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
23
+
24
+ import diffusers
25
+ from diffusers import (
26
+ AutoencoderKL,
27
+ EulerDiscreteScheduler,
28
+ LCMScheduler,
29
+ MultiAdapter,
30
+ StableDiffusionXLAdapterPipeline,
31
+ T2IAdapter,
32
+ UNet2DConditionModel,
33
+ )
34
+ from diffusers.utils import logging
35
+ from diffusers.utils.testing_utils import (
36
+ enable_full_determinism,
37
+ floats_tensor,
38
+ torch_device,
39
+ )
40
+
41
+ from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
42
+ from ..test_pipelines_common import (
43
+ IPAdapterTesterMixin,
44
+ PipelineTesterMixin,
45
+ assert_mean_pixel_difference,
46
+ )
47
+
48
+
49
+ enable_full_determinism()
50
+
51
+
52
+ class StableDiffusionXLAdapterPipelineFastTests(IPAdapterTesterMixin, PipelineTesterMixin, unittest.TestCase):
53
+ pipeline_class = StableDiffusionXLAdapterPipeline
54
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS
55
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
56
+
57
+ def get_dummy_components(self, adapter_type="full_adapter_xl", time_cond_proj_dim=None):
58
+ torch.manual_seed(0)
59
+ unet = UNet2DConditionModel(
60
+ block_out_channels=(32, 64),
61
+ layers_per_block=2,
62
+ sample_size=32,
63
+ in_channels=4,
64
+ out_channels=4,
65
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
66
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
67
+ # SD2-specific config below
68
+ attention_head_dim=(2, 4),
69
+ use_linear_projection=True,
70
+ addition_embed_type="text_time",
71
+ addition_time_embed_dim=8,
72
+ transformer_layers_per_block=(1, 2),
73
+ projection_class_embeddings_input_dim=80, # 6 * 8 + 32
74
+ cross_attention_dim=64,
75
+ time_cond_proj_dim=time_cond_proj_dim,
76
+ )
77
+ scheduler = EulerDiscreteScheduler(
78
+ beta_start=0.00085,
79
+ beta_end=0.012,
80
+ steps_offset=1,
81
+ beta_schedule="scaled_linear",
82
+ timestep_spacing="leading",
83
+ )
84
+ torch.manual_seed(0)
85
+ vae = AutoencoderKL(
86
+ block_out_channels=[32, 64],
87
+ in_channels=3,
88
+ out_channels=3,
89
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
90
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
91
+ latent_channels=4,
92
+ sample_size=128,
93
+ )
94
+ torch.manual_seed(0)
95
+ text_encoder_config = CLIPTextConfig(
96
+ bos_token_id=0,
97
+ eos_token_id=2,
98
+ hidden_size=32,
99
+ intermediate_size=37,
100
+ layer_norm_eps=1e-05,
101
+ num_attention_heads=4,
102
+ num_hidden_layers=5,
103
+ pad_token_id=1,
104
+ vocab_size=1000,
105
+ # SD2-specific config below
106
+ hidden_act="gelu",
107
+ projection_dim=32,
108
+ )
109
+ text_encoder = CLIPTextModel(text_encoder_config)
110
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
111
+
112
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
113
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
114
+ if adapter_type == "full_adapter_xl":
115
+ adapter = T2IAdapter(
116
+ in_channels=3,
117
+ channels=[32, 64],
118
+ num_res_blocks=2,
119
+ downscale_factor=4,
120
+ adapter_type=adapter_type,
121
+ )
122
+ elif adapter_type == "multi_adapter":
123
+ adapter = MultiAdapter(
124
+ [
125
+ T2IAdapter(
126
+ in_channels=3,
127
+ channels=[32, 64],
128
+ num_res_blocks=2,
129
+ downscale_factor=4,
130
+ adapter_type="full_adapter_xl",
131
+ ),
132
+ T2IAdapter(
133
+ in_channels=3,
134
+ channels=[32, 64],
135
+ num_res_blocks=2,
136
+ downscale_factor=4,
137
+ adapter_type="full_adapter_xl",
138
+ ),
139
+ ]
140
+ )
141
+ else:
142
+ raise ValueError(
143
+ f"Unknown adapter type: {adapter_type}, must be one of 'full_adapter_xl', or 'multi_adapter''"
144
+ )
145
+
146
+ components = {
147
+ "adapter": adapter,
148
+ "unet": unet,
149
+ "scheduler": scheduler,
150
+ "vae": vae,
151
+ "text_encoder": text_encoder,
152
+ "tokenizer": tokenizer,
153
+ "text_encoder_2": text_encoder_2,
154
+ "tokenizer_2": tokenizer_2,
155
+ # "safety_checker": None,
156
+ "feature_extractor": None,
157
+ "image_encoder": None,
158
+ }
159
+ return components
160
+
161
+ def get_dummy_components_with_full_downscaling(self, adapter_type="full_adapter_xl"):
162
+ """Get dummy components with x8 VAE downscaling and 3 UNet down blocks.
163
+ These dummy components are intended to fully-exercise the T2I-Adapter
164
+ downscaling behavior.
165
+ """
166
+ torch.manual_seed(0)
167
+ unet = UNet2DConditionModel(
168
+ block_out_channels=(32, 32, 64),
169
+ layers_per_block=2,
170
+ sample_size=32,
171
+ in_channels=4,
172
+ out_channels=4,
173
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D"),
174
+ up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D"),
175
+ # SD2-specific config below
176
+ attention_head_dim=2,
177
+ use_linear_projection=True,
178
+ addition_embed_type="text_time",
179
+ addition_time_embed_dim=8,
180
+ transformer_layers_per_block=1,
181
+ projection_class_embeddings_input_dim=80, # 6 * 8 + 32
182
+ cross_attention_dim=64,
183
+ )
184
+ scheduler = EulerDiscreteScheduler(
185
+ beta_start=0.00085,
186
+ beta_end=0.012,
187
+ steps_offset=1,
188
+ beta_schedule="scaled_linear",
189
+ timestep_spacing="leading",
190
+ )
191
+ torch.manual_seed(0)
192
+ vae = AutoencoderKL(
193
+ block_out_channels=[32, 32, 32, 64],
194
+ in_channels=3,
195
+ out_channels=3,
196
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"],
197
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
198
+ latent_channels=4,
199
+ sample_size=128,
200
+ )
201
+ torch.manual_seed(0)
202
+ text_encoder_config = CLIPTextConfig(
203
+ bos_token_id=0,
204
+ eos_token_id=2,
205
+ hidden_size=32,
206
+ intermediate_size=37,
207
+ layer_norm_eps=1e-05,
208
+ num_attention_heads=4,
209
+ num_hidden_layers=5,
210
+ pad_token_id=1,
211
+ vocab_size=1000,
212
+ # SD2-specific config below
213
+ hidden_act="gelu",
214
+ projection_dim=32,
215
+ )
216
+ text_encoder = CLIPTextModel(text_encoder_config)
217
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
218
+
219
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
220
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
221
+ if adapter_type == "full_adapter_xl":
222
+ adapter = T2IAdapter(
223
+ in_channels=3,
224
+ channels=[32, 32, 64],
225
+ num_res_blocks=2,
226
+ downscale_factor=16,
227
+ adapter_type=adapter_type,
228
+ )
229
+ elif adapter_type == "multi_adapter":
230
+ adapter = MultiAdapter(
231
+ [
232
+ T2IAdapter(
233
+ in_channels=3,
234
+ channels=[32, 32, 64],
235
+ num_res_blocks=2,
236
+ downscale_factor=16,
237
+ adapter_type="full_adapter_xl",
238
+ ),
239
+ T2IAdapter(
240
+ in_channels=3,
241
+ channels=[32, 32, 64],
242
+ num_res_blocks=2,
243
+ downscale_factor=16,
244
+ adapter_type="full_adapter_xl",
245
+ ),
246
+ ]
247
+ )
248
+ else:
249
+ raise ValueError(
250
+ f"Unknown adapter type: {adapter_type}, must be one of 'full_adapter_xl', or 'multi_adapter''"
251
+ )
252
+
253
+ components = {
254
+ "adapter": adapter,
255
+ "unet": unet,
256
+ "scheduler": scheduler,
257
+ "vae": vae,
258
+ "text_encoder": text_encoder,
259
+ "tokenizer": tokenizer,
260
+ "text_encoder_2": text_encoder_2,
261
+ "tokenizer_2": tokenizer_2,
262
+ # "safety_checker": None,
263
+ "feature_extractor": None,
264
+ "image_encoder": None,
265
+ }
266
+ return components
267
+
268
+ def get_dummy_inputs(self, device, seed=0, height=64, width=64, num_images=1):
269
+ if num_images == 1:
270
+ image = floats_tensor((1, 3, height, width), rng=random.Random(seed)).to(device)
271
+ else:
272
+ image = [
273
+ floats_tensor((1, 3, height, width), rng=random.Random(seed)).to(device) for _ in range(num_images)
274
+ ]
275
+
276
+ if str(device).startswith("mps"):
277
+ generator = torch.manual_seed(seed)
278
+ else:
279
+ generator = torch.Generator(device=device).manual_seed(seed)
280
+ inputs = {
281
+ "prompt": "A painting of a squirrel eating a burger",
282
+ "image": image,
283
+ "generator": generator,
284
+ "num_inference_steps": 2,
285
+ "guidance_scale": 5.0,
286
+ "output_type": "np",
287
+ }
288
+ return inputs
289
+
290
+ def test_ip_adapter(self, from_multi=False, expected_pipe_slice=None):
291
+ if not from_multi:
292
+ expected_pipe_slice = None
293
+ if torch_device == "cpu":
294
+ expected_pipe_slice = np.array(
295
+ [0.5752, 0.6155, 0.4826, 0.5111, 0.5741, 0.4678, 0.5199, 0.5231, 0.4794]
296
+ )
297
+
298
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
299
+
300
+ @unittest.skip("We test this functionality elsewhere already.")
301
+ def test_save_load_optional_components(self):
302
+ pass
303
+
304
+ def test_stable_diffusion_adapter_default_case(self):
305
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
306
+ components = self.get_dummy_components()
307
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
308
+ sd_pipe = sd_pipe.to(device)
309
+ sd_pipe.set_progress_bar_config(disable=None)
310
+
311
+ inputs = self.get_dummy_inputs(device)
312
+ image = sd_pipe(**inputs).images
313
+ image_slice = image[0, -3:, -3:, -1]
314
+
315
+ assert image.shape == (1, 64, 64, 3)
316
+ expected_slice = np.array([00.5752, 0.6155, 0.4826, 0.5111, 0.5741, 0.4678, 0.5199, 0.5231, 0.4794])
317
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-3
318
+
319
+ @parameterized.expand(
320
+ [
321
+ # (dim=144) The internal feature map will be 9x9 after initial pixel unshuffling (downscaled x16).
322
+ (((4 * 2 + 1) * 16),),
323
+ # (dim=160) The internal feature map will be 5x5 after the first T2I down block (downscaled x32).
324
+ (((4 * 1 + 1) * 32),),
325
+ ]
326
+ )
327
+ def test_multiple_image_dimensions(self, dim):
328
+ """Test that the T2I-Adapter pipeline supports any input dimension that
329
+ is divisible by the adapter's `downscale_factor`. This test was added in
330
+ response to an issue where the T2I Adapter's downscaling padding
331
+ behavior did not match the UNet's behavior.
332
+
333
+ Note that we have selected `dim` values to produce odd resolutions at
334
+ each downscaling level.
335
+ """
336
+ components = self.get_dummy_components_with_full_downscaling()
337
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
338
+ sd_pipe = sd_pipe.to(torch_device)
339
+ sd_pipe.set_progress_bar_config(disable=None)
340
+
341
+ inputs = self.get_dummy_inputs(torch_device, height=dim, width=dim)
342
+ image = sd_pipe(**inputs).images
343
+
344
+ assert image.shape == (1, dim, dim, 3)
345
+
346
+ @parameterized.expand(["full_adapter", "full_adapter_xl", "light_adapter"])
347
+ def test_total_downscale_factor(self, adapter_type):
348
+ """Test that the T2IAdapter correctly reports its total_downscale_factor."""
349
+ batch_size = 1
350
+ in_channels = 3
351
+ out_channels = [320, 640, 1280, 1280]
352
+ in_image_size = 512
353
+
354
+ adapter = T2IAdapter(
355
+ in_channels=in_channels,
356
+ channels=out_channels,
357
+ num_res_blocks=2,
358
+ downscale_factor=8,
359
+ adapter_type=adapter_type,
360
+ )
361
+ adapter.to(torch_device)
362
+
363
+ in_image = floats_tensor((batch_size, in_channels, in_image_size, in_image_size)).to(torch_device)
364
+
365
+ adapter_state = adapter(in_image)
366
+
367
+ # Assume that the last element in `adapter_state` has been downsampled the most, and check
368
+ # that it matches the `total_downscale_factor`.
369
+ expected_out_image_size = in_image_size // adapter.total_downscale_factor
370
+ assert adapter_state[-1].shape == (
371
+ batch_size,
372
+ out_channels[-1],
373
+ expected_out_image_size,
374
+ expected_out_image_size,
375
+ )
376
+
377
+ def test_adapter_sdxl_lcm(self):
378
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
379
+
380
+ components = self.get_dummy_components(time_cond_proj_dim=256)
381
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
382
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
383
+ sd_pipe = sd_pipe.to(torch_device)
384
+ sd_pipe.set_progress_bar_config(disable=None)
385
+
386
+ inputs = self.get_dummy_inputs(device)
387
+ output = sd_pipe(**inputs)
388
+ image = output.images
389
+
390
+ image_slice = image[0, -3:, -3:, -1]
391
+
392
+ assert image.shape == (1, 64, 64, 3)
393
+ expected_slice = np.array([0.5425, 0.5385, 0.4964, 0.5045, 0.6149, 0.4974, 0.5469, 0.5332, 0.5426])
394
+
395
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
396
+
397
+ def test_adapter_sdxl_lcm_custom_timesteps(self):
398
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
399
+
400
+ components = self.get_dummy_components(time_cond_proj_dim=256)
401
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
402
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
403
+ sd_pipe = sd_pipe.to(torch_device)
404
+ sd_pipe.set_progress_bar_config(disable=None)
405
+
406
+ inputs = self.get_dummy_inputs(device)
407
+ del inputs["num_inference_steps"]
408
+ inputs["timesteps"] = [999, 499]
409
+ output = sd_pipe(**inputs)
410
+ image = output.images
411
+
412
+ image_slice = image[0, -3:, -3:, -1]
413
+
414
+ assert image.shape == (1, 64, 64, 3)
415
+ expected_slice = np.array([0.5425, 0.5385, 0.4964, 0.5045, 0.6149, 0.4974, 0.5469, 0.5332, 0.5426])
416
+
417
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
418
+
419
+
420
+ class StableDiffusionXLMultiAdapterPipelineFastTests(
421
+ StableDiffusionXLAdapterPipelineFastTests, PipelineTesterMixin, unittest.TestCase
422
+ ):
423
+ supports_dduf = False
424
+
425
+ def get_dummy_components(self, time_cond_proj_dim=None):
426
+ return super().get_dummy_components("multi_adapter", time_cond_proj_dim=time_cond_proj_dim)
427
+
428
+ def get_dummy_components_with_full_downscaling(self):
429
+ return super().get_dummy_components_with_full_downscaling("multi_adapter")
430
+
431
+ def get_dummy_inputs(self, device, seed=0, height=64, width=64):
432
+ inputs = super().get_dummy_inputs(device, seed, height, width, num_images=2)
433
+ inputs["adapter_conditioning_scale"] = [0.5, 0.5]
434
+ return inputs
435
+
436
+ def test_stable_diffusion_adapter_default_case(self):
437
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
438
+ components = self.get_dummy_components()
439
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
440
+ sd_pipe = sd_pipe.to(device)
441
+ sd_pipe.set_progress_bar_config(disable=None)
442
+
443
+ inputs = self.get_dummy_inputs(device)
444
+ image = sd_pipe(**inputs).images
445
+ image_slice = image[0, -3:, -3:, -1]
446
+
447
+ assert image.shape == (1, 64, 64, 3)
448
+ expected_slice = np.array([0.5617, 0.6081, 0.4807, 0.5071, 0.5665, 0.4614, 0.5165, 0.5164, 0.4786])
449
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-3
450
+
451
+ def test_ip_adapter(self):
452
+ expected_pipe_slice = None
453
+ if torch_device == "cpu":
454
+ expected_pipe_slice = np.array([0.5617, 0.6081, 0.4807, 0.5071, 0.5665, 0.4614, 0.5165, 0.5164, 0.4786])
455
+
456
+ return super().test_ip_adapter(from_multi=True, expected_pipe_slice=expected_pipe_slice)
457
+
458
+ def test_inference_batch_consistent(
459
+ self, batch_sizes=[2, 4, 13], additional_params_copy_to_batched_inputs=["num_inference_steps"]
460
+ ):
461
+ components = self.get_dummy_components()
462
+ pipe = self.pipeline_class(**components)
463
+ pipe.to(torch_device)
464
+ pipe.set_progress_bar_config(disable=None)
465
+
466
+ inputs = self.get_dummy_inputs(torch_device)
467
+
468
+ logger = logging.get_logger(pipe.__module__)
469
+ logger.setLevel(level=diffusers.logging.FATAL)
470
+
471
+ # batchify inputs
472
+ for batch_size in batch_sizes:
473
+ batched_inputs = {}
474
+ for name, value in inputs.items():
475
+ if name in self.batch_params:
476
+ # prompt is string
477
+ if name == "prompt":
478
+ len_prompt = len(value)
479
+ # make unequal batch sizes
480
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
481
+
482
+ # make last batch super long
483
+ batched_inputs[name][-1] = 100 * "very long"
484
+ elif name == "image":
485
+ batched_images = []
486
+
487
+ for image in value:
488
+ batched_images.append(batch_size * [image])
489
+
490
+ batched_inputs[name] = batched_images
491
+ else:
492
+ batched_inputs[name] = batch_size * [value]
493
+
494
+ elif name == "batch_size":
495
+ batched_inputs[name] = batch_size
496
+ else:
497
+ batched_inputs[name] = value
498
+
499
+ for arg in additional_params_copy_to_batched_inputs:
500
+ batched_inputs[arg] = inputs[arg]
501
+
502
+ batched_inputs["output_type"] = "np"
503
+
504
+ output = pipe(**batched_inputs)
505
+
506
+ assert len(output[0]) == batch_size
507
+
508
+ batched_inputs["output_type"] = "np"
509
+
510
+ output = pipe(**batched_inputs)[0]
511
+
512
+ assert output.shape[0] == batch_size
513
+
514
+ logger.setLevel(level=diffusers.logging.WARNING)
515
+
516
+ @unittest.skip("We test this functionality elsewhere already.")
517
+ def test_save_load_optional_components(self):
518
+ pass
519
+
520
+ def test_num_images_per_prompt(self):
521
+ components = self.get_dummy_components()
522
+ pipe = self.pipeline_class(**components)
523
+ pipe = pipe.to(torch_device)
524
+ pipe.set_progress_bar_config(disable=None)
525
+
526
+ batch_sizes = [1, 2]
527
+ num_images_per_prompts = [1, 2]
528
+
529
+ for batch_size in batch_sizes:
530
+ for num_images_per_prompt in num_images_per_prompts:
531
+ inputs = self.get_dummy_inputs(torch_device)
532
+
533
+ for key in inputs.keys():
534
+ if key in self.batch_params:
535
+ if key == "image":
536
+ batched_images = []
537
+
538
+ for image in inputs[key]:
539
+ batched_images.append(batch_size * [image])
540
+
541
+ inputs[key] = batched_images
542
+ else:
543
+ inputs[key] = batch_size * [inputs[key]]
544
+
545
+ images = pipe(**inputs, num_images_per_prompt=num_images_per_prompt)[0]
546
+
547
+ assert images.shape[0] == batch_size * num_images_per_prompt
548
+
549
+ def test_inference_batch_single_identical(
550
+ self,
551
+ batch_size=3,
552
+ test_max_difference=None,
553
+ test_mean_pixel_difference=None,
554
+ relax_max_difference=False,
555
+ expected_max_diff=2e-3,
556
+ additional_params_copy_to_batched_inputs=["num_inference_steps"],
557
+ ):
558
+ if test_max_difference is None:
559
+ # TODO(Pedro) - not sure why, but not at all reproducible at the moment it seems
560
+ # make sure that batched and non-batched is identical
561
+ test_max_difference = torch_device != "mps"
562
+
563
+ if test_mean_pixel_difference is None:
564
+ # TODO same as above
565
+ test_mean_pixel_difference = torch_device != "mps"
566
+
567
+ components = self.get_dummy_components()
568
+ pipe = self.pipeline_class(**components)
569
+ pipe.to(torch_device)
570
+ pipe.set_progress_bar_config(disable=None)
571
+
572
+ inputs = self.get_dummy_inputs(torch_device)
573
+
574
+ logger = logging.get_logger(pipe.__module__)
575
+ logger.setLevel(level=diffusers.logging.FATAL)
576
+
577
+ # batchify inputs
578
+ batched_inputs = {}
579
+ for name, value in inputs.items():
580
+ if name in self.batch_params:
581
+ # prompt is string
582
+ if name == "prompt":
583
+ len_prompt = len(value)
584
+ # make unequal batch sizes
585
+ batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
586
+
587
+ # make last batch super long
588
+ batched_inputs[name][-1] = 100 * "very long"
589
+ elif name == "image":
590
+ batched_images = []
591
+
592
+ for image in value:
593
+ batched_images.append(batch_size * [image])
594
+
595
+ batched_inputs[name] = batched_images
596
+ else:
597
+ batched_inputs[name] = batch_size * [value]
598
+ elif name == "batch_size":
599
+ batched_inputs[name] = batch_size
600
+ elif name == "generator":
601
+ batched_inputs[name] = [self.get_generator(i) for i in range(batch_size)]
602
+ else:
603
+ batched_inputs[name] = value
604
+
605
+ for arg in additional_params_copy_to_batched_inputs:
606
+ batched_inputs[arg] = inputs[arg]
607
+
608
+ output_batch = pipe(**batched_inputs)
609
+ assert output_batch[0].shape[0] == batch_size
610
+
611
+ inputs["generator"] = self.get_generator(0)
612
+
613
+ output = pipe(**inputs)
614
+
615
+ logger.setLevel(level=diffusers.logging.WARNING)
616
+ if test_max_difference:
617
+ if relax_max_difference:
618
+ # Taking the median of the largest <n> differences
619
+ # is resilient to outliers
620
+ diff = np.abs(output_batch[0][0] - output[0][0])
621
+ diff = diff.flatten()
622
+ diff.sort()
623
+ max_diff = np.median(diff[-5:])
624
+ else:
625
+ max_diff = np.abs(output_batch[0][0] - output[0][0]).max()
626
+ assert max_diff < expected_max_diff
627
+
628
+ if test_mean_pixel_difference:
629
+ assert_mean_pixel_difference(output_batch[0][0], output[0][0])
630
+
631
+ def test_adapter_sdxl_lcm(self):
632
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
633
+
634
+ components = self.get_dummy_components(time_cond_proj_dim=256)
635
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
636
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
637
+ sd_pipe = sd_pipe.to(torch_device)
638
+ sd_pipe.set_progress_bar_config(disable=None)
639
+
640
+ inputs = self.get_dummy_inputs(device)
641
+ output = sd_pipe(**inputs)
642
+ image = output.images
643
+
644
+ image_slice = image[0, -3:, -3:, -1]
645
+
646
+ assert image.shape == (1, 64, 64, 3)
647
+ expected_slice = np.array([0.5313, 0.5375, 0.4942, 0.5021, 0.6142, 0.4968, 0.5434, 0.5311, 0.5448])
648
+
649
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
650
+
651
+ def test_adapter_sdxl_lcm_custom_timesteps(self):
652
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
653
+
654
+ components = self.get_dummy_components(time_cond_proj_dim=256)
655
+ sd_pipe = StableDiffusionXLAdapterPipeline(**components)
656
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
657
+ sd_pipe = sd_pipe.to(torch_device)
658
+ sd_pipe.set_progress_bar_config(disable=None)
659
+
660
+ inputs = self.get_dummy_inputs(device)
661
+ del inputs["num_inference_steps"]
662
+ inputs["timesteps"] = [999, 499]
663
+ output = sd_pipe(**inputs)
664
+ image = output.images
665
+
666
+ image_slice = image[0, -3:, -3:, -1]
667
+
668
+ assert image.shape == (1, 64, 64, 3)
669
+ expected_slice = np.array([0.5313, 0.5375, 0.4942, 0.5021, 0.6142, 0.4968, 0.5434, 0.5311, 0.5448])
670
+
671
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_img2img.py ADDED
@@ -0,0 +1,716 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import gc
17
+ import random
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import torch
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextConfig,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionConfig,
29
+ CLIPVisionModelWithProjection,
30
+ )
31
+
32
+ from diffusers import (
33
+ AutoencoderKL,
34
+ AutoencoderTiny,
35
+ EDMDPMSolverMultistepScheduler,
36
+ EulerDiscreteScheduler,
37
+ LCMScheduler,
38
+ StableDiffusionXLImg2ImgPipeline,
39
+ UNet2DConditionModel,
40
+ )
41
+ from diffusers.utils.testing_utils import (
42
+ enable_full_determinism,
43
+ floats_tensor,
44
+ load_image,
45
+ require_torch_accelerator,
46
+ slow,
47
+ torch_device,
48
+ )
49
+
50
+ from ..pipeline_params import (
51
+ IMAGE_TO_IMAGE_IMAGE_PARAMS,
52
+ TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
53
+ TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
54
+ TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
55
+ )
56
+ from ..test_pipelines_common import (
57
+ IPAdapterTesterMixin,
58
+ PipelineLatentTesterMixin,
59
+ PipelineTesterMixin,
60
+ )
61
+
62
+
63
+ enable_full_determinism()
64
+
65
+
66
+ class StableDiffusionXLImg2ImgPipelineFastTests(
67
+ IPAdapterTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, unittest.TestCase
68
+ ):
69
+ pipeline_class = StableDiffusionXLImg2ImgPipeline
70
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
71
+ required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
72
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
73
+ image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
74
+ image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
75
+ callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union(
76
+ {"add_text_embeds", "add_time_ids", "add_neg_time_ids"}
77
+ )
78
+
79
+ supports_dduf = False
80
+
81
+ def get_dummy_components(self, skip_first_text_encoder=False, time_cond_proj_dim=None):
82
+ torch.manual_seed(0)
83
+ unet = UNet2DConditionModel(
84
+ block_out_channels=(32, 64),
85
+ layers_per_block=2,
86
+ sample_size=32,
87
+ in_channels=4,
88
+ out_channels=4,
89
+ time_cond_proj_dim=time_cond_proj_dim,
90
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
91
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
92
+ # SD2-specific config below
93
+ attention_head_dim=(2, 4),
94
+ use_linear_projection=True,
95
+ addition_embed_type="text_time",
96
+ addition_time_embed_dim=8,
97
+ transformer_layers_per_block=(1, 2),
98
+ projection_class_embeddings_input_dim=72, # 5 * 8 + 32
99
+ cross_attention_dim=64 if not skip_first_text_encoder else 32,
100
+ )
101
+ scheduler = EulerDiscreteScheduler(
102
+ beta_start=0.00085,
103
+ beta_end=0.012,
104
+ steps_offset=1,
105
+ beta_schedule="scaled_linear",
106
+ timestep_spacing="leading",
107
+ )
108
+ torch.manual_seed(0)
109
+ vae = AutoencoderKL(
110
+ block_out_channels=[32, 64],
111
+ in_channels=3,
112
+ out_channels=3,
113
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
114
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
115
+ latent_channels=4,
116
+ sample_size=128,
117
+ )
118
+ torch.manual_seed(0)
119
+ image_encoder_config = CLIPVisionConfig(
120
+ hidden_size=32,
121
+ image_size=224,
122
+ projection_dim=32,
123
+ intermediate_size=37,
124
+ num_attention_heads=4,
125
+ num_channels=3,
126
+ num_hidden_layers=5,
127
+ patch_size=14,
128
+ )
129
+
130
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
131
+
132
+ feature_extractor = CLIPImageProcessor(
133
+ crop_size=224,
134
+ do_center_crop=True,
135
+ do_normalize=True,
136
+ do_resize=True,
137
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
138
+ image_std=[0.26862954, 0.26130258, 0.27577711],
139
+ resample=3,
140
+ size=224,
141
+ )
142
+
143
+ torch.manual_seed(0)
144
+ text_encoder_config = CLIPTextConfig(
145
+ bos_token_id=0,
146
+ eos_token_id=2,
147
+ hidden_size=32,
148
+ intermediate_size=37,
149
+ layer_norm_eps=1e-05,
150
+ num_attention_heads=4,
151
+ num_hidden_layers=5,
152
+ pad_token_id=1,
153
+ vocab_size=1000,
154
+ # SD2-specific config below
155
+ hidden_act="gelu",
156
+ projection_dim=32,
157
+ )
158
+ text_encoder = CLIPTextModel(text_encoder_config)
159
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
160
+
161
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
162
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
163
+
164
+ components = {
165
+ "unet": unet,
166
+ "scheduler": scheduler,
167
+ "vae": vae,
168
+ "text_encoder": text_encoder if not skip_first_text_encoder else None,
169
+ "tokenizer": tokenizer if not skip_first_text_encoder else None,
170
+ "text_encoder_2": text_encoder_2,
171
+ "tokenizer_2": tokenizer_2,
172
+ "requires_aesthetics_score": True,
173
+ "image_encoder": image_encoder,
174
+ "feature_extractor": feature_extractor,
175
+ }
176
+ return components
177
+
178
+ def get_dummy_tiny_autoencoder(self):
179
+ return AutoencoderTiny(in_channels=3, out_channels=3, latent_channels=4)
180
+
181
+ def test_components_function(self):
182
+ init_components = self.get_dummy_components()
183
+ init_components.pop("requires_aesthetics_score")
184
+ pipe = self.pipeline_class(**init_components)
185
+
186
+ self.assertTrue(hasattr(pipe, "components"))
187
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
188
+
189
+ def get_dummy_inputs(self, device, seed=0):
190
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
191
+ image = image / 2 + 0.5
192
+ if str(device).startswith("mps"):
193
+ generator = torch.manual_seed(seed)
194
+ else:
195
+ generator = torch.Generator(device=device).manual_seed(seed)
196
+ inputs = {
197
+ "prompt": "A painting of a squirrel eating a burger",
198
+ "image": image,
199
+ "generator": generator,
200
+ "num_inference_steps": 2,
201
+ "guidance_scale": 5.0,
202
+ "output_type": "np",
203
+ "strength": 0.8,
204
+ }
205
+ return inputs
206
+
207
+ def test_stable_diffusion_xl_img2img_euler(self):
208
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
209
+ components = self.get_dummy_components()
210
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
211
+ sd_pipe = sd_pipe.to(device)
212
+ sd_pipe.set_progress_bar_config(disable=None)
213
+
214
+ inputs = self.get_dummy_inputs(device)
215
+ image = sd_pipe(**inputs).images
216
+ image_slice = image[0, -3:, -3:, -1]
217
+
218
+ assert image.shape == (1, 32, 32, 3)
219
+
220
+ expected_slice = np.array([0.4664, 0.4886, 0.4403, 0.6902, 0.5592, 0.4534, 0.5931, 0.5951, 0.5224])
221
+
222
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
223
+
224
+ def test_stable_diffusion_xl_img2img_euler_lcm(self):
225
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
226
+ components = self.get_dummy_components(time_cond_proj_dim=256)
227
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
228
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.config)
229
+ sd_pipe = sd_pipe.to(device)
230
+ sd_pipe.set_progress_bar_config(disable=None)
231
+
232
+ inputs = self.get_dummy_inputs(device)
233
+ image = sd_pipe(**inputs).images
234
+ image_slice = image[0, -3:, -3:, -1]
235
+
236
+ assert image.shape == (1, 32, 32, 3)
237
+
238
+ expected_slice = np.array([0.5604, 0.4352, 0.4717, 0.5844, 0.5101, 0.6704, 0.6290, 0.5460, 0.5286])
239
+
240
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
241
+
242
+ def test_stable_diffusion_xl_img2img_euler_lcm_custom_timesteps(self):
243
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
244
+ components = self.get_dummy_components(time_cond_proj_dim=256)
245
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
246
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.config)
247
+ sd_pipe = sd_pipe.to(device)
248
+ sd_pipe.set_progress_bar_config(disable=None)
249
+
250
+ inputs = self.get_dummy_inputs(device)
251
+ del inputs["num_inference_steps"]
252
+ inputs["timesteps"] = [999, 499]
253
+ image = sd_pipe(**inputs).images
254
+ image_slice = image[0, -3:, -3:, -1]
255
+
256
+ assert image.shape == (1, 32, 32, 3)
257
+
258
+ expected_slice = np.array([0.5604, 0.4352, 0.4717, 0.5844, 0.5101, 0.6704, 0.6290, 0.5460, 0.5286])
259
+
260
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
261
+
262
+ def test_attention_slicing_forward_pass(self):
263
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
264
+
265
+ def test_inference_batch_single_identical(self):
266
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
267
+
268
+ @unittest.skip("Skip for now.")
269
+ def test_save_load_optional_components(self):
270
+ pass
271
+
272
+ def test_ip_adapter(self):
273
+ expected_pipe_slice = None
274
+ if torch_device == "cpu":
275
+ expected_pipe_slice = np.array([0.5133, 0.4626, 0.4970, 0.6273, 0.5160, 0.6891, 0.6639, 0.5892, 0.5709])
276
+
277
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
278
+
279
+ def test_stable_diffusion_xl_img2img_tiny_autoencoder(self):
280
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
281
+ components = self.get_dummy_components()
282
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
283
+ sd_pipe.vae = self.get_dummy_tiny_autoencoder()
284
+ sd_pipe = sd_pipe.to(device)
285
+ sd_pipe.set_progress_bar_config(disable=None)
286
+
287
+ inputs = self.get_dummy_inputs(device)
288
+ image = sd_pipe(**inputs).images
289
+ image_slice = image[0, -3:, -3:, -1].flatten()
290
+
291
+ assert image.shape == (1, 32, 32, 3)
292
+ expected_slice = np.array([0.0, 0.0, 0.0106, 0.0, 0.0, 0.0087, 0.0052, 0.0062, 0.0177])
293
+
294
+ assert np.allclose(image_slice, expected_slice, atol=1e-4, rtol=1e-4)
295
+
296
+ @require_torch_accelerator
297
+ def test_stable_diffusion_xl_offloads(self):
298
+ pipes = []
299
+ components = self.get_dummy_components()
300
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
301
+ pipes.append(sd_pipe)
302
+
303
+ components = self.get_dummy_components()
304
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
305
+ sd_pipe.enable_model_cpu_offload(device=torch_device)
306
+ pipes.append(sd_pipe)
307
+
308
+ components = self.get_dummy_components()
309
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
310
+ sd_pipe.enable_sequential_cpu_offload(device=torch_device)
311
+ pipes.append(sd_pipe)
312
+
313
+ image_slices = []
314
+ for pipe in pipes:
315
+ pipe.unet.set_default_attn_processor()
316
+
317
+ generator_device = "cpu"
318
+ inputs = self.get_dummy_inputs(generator_device)
319
+ image = pipe(**inputs).images
320
+
321
+ image_slices.append(image[0, -3:, -3:, -1].flatten())
322
+
323
+ assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
324
+ assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
325
+
326
+ def test_stable_diffusion_xl_multi_prompts(self):
327
+ components = self.get_dummy_components()
328
+ sd_pipe = self.pipeline_class(**components).to(torch_device)
329
+
330
+ # forward with single prompt
331
+ generator_device = "cpu"
332
+ inputs = self.get_dummy_inputs(generator_device)
333
+ inputs["num_inference_steps"] = 5
334
+ output = sd_pipe(**inputs)
335
+ image_slice_1 = output.images[0, -3:, -3:, -1]
336
+
337
+ # forward with same prompt duplicated
338
+ generator_device = "cpu"
339
+ inputs = self.get_dummy_inputs(generator_device)
340
+ inputs["num_inference_steps"] = 5
341
+ inputs["prompt_2"] = inputs["prompt"]
342
+ output = sd_pipe(**inputs)
343
+ image_slice_2 = output.images[0, -3:, -3:, -1]
344
+
345
+ # ensure the results are equal
346
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
347
+
348
+ # forward with different prompt
349
+ generator_device = "cpu"
350
+ inputs = self.get_dummy_inputs(generator_device)
351
+ inputs["num_inference_steps"] = 5
352
+ inputs["prompt_2"] = "different prompt"
353
+ output = sd_pipe(**inputs)
354
+ image_slice_3 = output.images[0, -3:, -3:, -1]
355
+
356
+ # ensure the results are not equal
357
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
358
+
359
+ # manually set a negative_prompt
360
+ generator_device = "cpu"
361
+ inputs = self.get_dummy_inputs(generator_device)
362
+ inputs["num_inference_steps"] = 5
363
+ inputs["negative_prompt"] = "negative prompt"
364
+ output = sd_pipe(**inputs)
365
+ image_slice_1 = output.images[0, -3:, -3:, -1]
366
+
367
+ # forward with same negative_prompt duplicated
368
+ generator_device = "cpu"
369
+ inputs = self.get_dummy_inputs(generator_device)
370
+ inputs["num_inference_steps"] = 5
371
+ inputs["negative_prompt"] = "negative prompt"
372
+ inputs["negative_prompt_2"] = inputs["negative_prompt"]
373
+ output = sd_pipe(**inputs)
374
+ image_slice_2 = output.images[0, -3:, -3:, -1]
375
+
376
+ # ensure the results are equal
377
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
378
+
379
+ # forward with different negative_prompt
380
+ generator_device = "cpu"
381
+ inputs = self.get_dummy_inputs(generator_device)
382
+ inputs["num_inference_steps"] = 5
383
+ inputs["negative_prompt"] = "negative prompt"
384
+ inputs["negative_prompt_2"] = "different negative prompt"
385
+ output = sd_pipe(**inputs)
386
+ image_slice_3 = output.images[0, -3:, -3:, -1]
387
+
388
+ # ensure the results are not equal
389
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
390
+
391
+ def test_stable_diffusion_xl_img2img_negative_conditions(self):
392
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
393
+ components = self.get_dummy_components()
394
+
395
+ sd_pipe = self.pipeline_class(**components)
396
+ sd_pipe = sd_pipe.to(device)
397
+ sd_pipe.set_progress_bar_config(disable=None)
398
+
399
+ inputs = self.get_dummy_inputs(device)
400
+ image = sd_pipe(**inputs).images
401
+ image_slice_with_no_neg_conditions = image[0, -3:, -3:, -1]
402
+
403
+ image = sd_pipe(
404
+ **inputs,
405
+ negative_original_size=(512, 512),
406
+ negative_crops_coords_top_left=(
407
+ 0,
408
+ 0,
409
+ ),
410
+ negative_target_size=(1024, 1024),
411
+ ).images
412
+ image_slice_with_neg_conditions = image[0, -3:, -3:, -1]
413
+
414
+ assert (
415
+ np.abs(image_slice_with_no_neg_conditions.flatten() - image_slice_with_neg_conditions.flatten()).max()
416
+ > 1e-4
417
+ )
418
+
419
+ def test_pipeline_interrupt(self):
420
+ components = self.get_dummy_components()
421
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
422
+ sd_pipe = sd_pipe.to(torch_device)
423
+ sd_pipe.set_progress_bar_config(disable=None)
424
+
425
+ inputs = self.get_dummy_inputs(torch_device)
426
+
427
+ prompt = "hey"
428
+ num_inference_steps = 5
429
+
430
+ # store intermediate latents from the generation process
431
+ class PipelineState:
432
+ def __init__(self):
433
+ self.state = []
434
+
435
+ def apply(self, pipe, i, t, callback_kwargs):
436
+ self.state.append(callback_kwargs["latents"])
437
+ return callback_kwargs
438
+
439
+ pipe_state = PipelineState()
440
+ sd_pipe(
441
+ prompt,
442
+ image=inputs["image"],
443
+ strength=0.8,
444
+ num_inference_steps=num_inference_steps,
445
+ output_type="np",
446
+ generator=torch.Generator("cpu").manual_seed(0),
447
+ callback_on_step_end=pipe_state.apply,
448
+ ).images
449
+
450
+ # interrupt generation at step index
451
+ interrupt_step_idx = 1
452
+
453
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
454
+ if i == interrupt_step_idx:
455
+ pipe._interrupt = True
456
+
457
+ return callback_kwargs
458
+
459
+ output_interrupted = sd_pipe(
460
+ prompt,
461
+ image=inputs["image"],
462
+ strength=0.8,
463
+ num_inference_steps=num_inference_steps,
464
+ output_type="latent",
465
+ generator=torch.Generator("cpu").manual_seed(0),
466
+ callback_on_step_end=callback_on_step_end,
467
+ ).images
468
+
469
+ # fetch intermediate latents at the interrupted step
470
+ # from the completed generation process
471
+ intermediate_latent = pipe_state.state[interrupt_step_idx]
472
+
473
+ # compare the intermediate latent to the output of the interrupted process
474
+ # they should be the same
475
+ assert torch.allclose(intermediate_latent, output_interrupted, atol=1e-4)
476
+
477
+
478
+ class StableDiffusionXLImg2ImgRefinerOnlyPipelineFastTests(
479
+ PipelineLatentTesterMixin, PipelineTesterMixin, unittest.TestCase
480
+ ):
481
+ pipeline_class = StableDiffusionXLImg2ImgPipeline
482
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
483
+ required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
484
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
485
+ image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
486
+ image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
487
+
488
+ def get_dummy_components(self):
489
+ torch.manual_seed(0)
490
+ unet = UNet2DConditionModel(
491
+ block_out_channels=(32, 64),
492
+ layers_per_block=2,
493
+ sample_size=32,
494
+ in_channels=4,
495
+ out_channels=4,
496
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
497
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
498
+ # SD2-specific config below
499
+ attention_head_dim=(2, 4),
500
+ use_linear_projection=True,
501
+ addition_embed_type="text_time",
502
+ addition_time_embed_dim=8,
503
+ transformer_layers_per_block=(1, 2),
504
+ projection_class_embeddings_input_dim=72, # 5 * 8 + 32
505
+ cross_attention_dim=32,
506
+ )
507
+ scheduler = EulerDiscreteScheduler(
508
+ beta_start=0.00085,
509
+ beta_end=0.012,
510
+ steps_offset=1,
511
+ beta_schedule="scaled_linear",
512
+ timestep_spacing="leading",
513
+ )
514
+ torch.manual_seed(0)
515
+ vae = AutoencoderKL(
516
+ block_out_channels=[32, 64],
517
+ in_channels=3,
518
+ out_channels=3,
519
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
520
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
521
+ latent_channels=4,
522
+ sample_size=128,
523
+ )
524
+ torch.manual_seed(0)
525
+ text_encoder_config = CLIPTextConfig(
526
+ bos_token_id=0,
527
+ eos_token_id=2,
528
+ hidden_size=32,
529
+ intermediate_size=37,
530
+ layer_norm_eps=1e-05,
531
+ num_attention_heads=4,
532
+ num_hidden_layers=5,
533
+ pad_token_id=1,
534
+ vocab_size=1000,
535
+ # SD2-specific config below
536
+ hidden_act="gelu",
537
+ projection_dim=32,
538
+ )
539
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
540
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
541
+
542
+ components = {
543
+ "unet": unet,
544
+ "scheduler": scheduler,
545
+ "vae": vae,
546
+ "tokenizer": None,
547
+ "text_encoder": None,
548
+ "text_encoder_2": text_encoder_2,
549
+ "tokenizer_2": tokenizer_2,
550
+ "requires_aesthetics_score": True,
551
+ "image_encoder": None,
552
+ "feature_extractor": None,
553
+ }
554
+ return components
555
+
556
+ def test_components_function(self):
557
+ init_components = self.get_dummy_components()
558
+ init_components.pop("requires_aesthetics_score")
559
+ pipe = self.pipeline_class(**init_components)
560
+
561
+ self.assertTrue(hasattr(pipe, "components"))
562
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
563
+
564
+ def get_dummy_inputs(self, device, seed=0):
565
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
566
+ image = image / 2 + 0.5
567
+ if str(device).startswith("mps"):
568
+ generator = torch.manual_seed(seed)
569
+ else:
570
+ generator = torch.Generator(device=device).manual_seed(seed)
571
+ inputs = {
572
+ "prompt": "A painting of a squirrel eating a burger",
573
+ "image": image,
574
+ "generator": generator,
575
+ "num_inference_steps": 2,
576
+ "guidance_scale": 5.0,
577
+ "output_type": "np",
578
+ "strength": 0.8,
579
+ }
580
+ return inputs
581
+
582
+ def test_stable_diffusion_xl_img2img_euler(self):
583
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
584
+ components = self.get_dummy_components()
585
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
586
+ sd_pipe = sd_pipe.to(device)
587
+ sd_pipe.set_progress_bar_config(disable=None)
588
+
589
+ inputs = self.get_dummy_inputs(device)
590
+ image = sd_pipe(**inputs).images
591
+ image_slice = image[0, -3:, -3:, -1]
592
+
593
+ assert image.shape == (1, 32, 32, 3)
594
+
595
+ expected_slice = np.array([0.4745, 0.4924, 0.4338, 0.6468, 0.5547, 0.4419, 0.5646, 0.5897, 0.5146])
596
+
597
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
598
+
599
+ @require_torch_accelerator
600
+ def test_stable_diffusion_xl_offloads(self):
601
+ pipes = []
602
+ components = self.get_dummy_components()
603
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components).to(torch_device)
604
+ pipes.append(sd_pipe)
605
+
606
+ components = self.get_dummy_components()
607
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
608
+ sd_pipe.enable_model_cpu_offload(device=torch_device)
609
+ pipes.append(sd_pipe)
610
+
611
+ components = self.get_dummy_components()
612
+ sd_pipe = StableDiffusionXLImg2ImgPipeline(**components)
613
+ sd_pipe.enable_sequential_cpu_offload(device=torch_device)
614
+ pipes.append(sd_pipe)
615
+
616
+ image_slices = []
617
+ for pipe in pipes:
618
+ pipe.unet.set_default_attn_processor()
619
+
620
+ generator_device = "cpu"
621
+ inputs = self.get_dummy_inputs(generator_device)
622
+ image = pipe(**inputs).images
623
+
624
+ image_slices.append(image[0, -3:, -3:, -1].flatten())
625
+
626
+ assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
627
+ assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
628
+
629
+ def test_stable_diffusion_xl_img2img_negative_conditions(self):
630
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
631
+ components = self.get_dummy_components()
632
+
633
+ sd_pipe = self.pipeline_class(**components)
634
+ sd_pipe = sd_pipe.to(device)
635
+ sd_pipe.set_progress_bar_config(disable=None)
636
+
637
+ inputs = self.get_dummy_inputs(device)
638
+ image = sd_pipe(**inputs).images
639
+ image_slice_with_no_neg_conditions = image[0, -3:, -3:, -1]
640
+
641
+ image = sd_pipe(
642
+ **inputs,
643
+ negative_original_size=(512, 512),
644
+ negative_crops_coords_top_left=(
645
+ 0,
646
+ 0,
647
+ ),
648
+ negative_target_size=(1024, 1024),
649
+ ).images
650
+ image_slice_with_neg_conditions = image[0, -3:, -3:, -1]
651
+
652
+ assert (
653
+ np.abs(image_slice_with_no_neg_conditions.flatten() - image_slice_with_neg_conditions.flatten()).max()
654
+ > 1e-4
655
+ )
656
+
657
+ def test_attention_slicing_forward_pass(self):
658
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
659
+
660
+ def test_inference_batch_single_identical(self):
661
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
662
+
663
+ @unittest.skip("We test this functionality elsewhere already.")
664
+ def test_save_load_optional_components(self):
665
+ pass
666
+
667
+
668
+ @slow
669
+ class StableDiffusionXLImg2ImgPipelineIntegrationTests(unittest.TestCase):
670
+ def setUp(self):
671
+ super().setUp()
672
+ gc.collect()
673
+ torch.cuda.empty_cache()
674
+
675
+ def tearDown(self):
676
+ super().tearDown()
677
+ gc.collect()
678
+ torch.cuda.empty_cache()
679
+
680
+ def test_stable_diffusion_xl_img2img_playground(self):
681
+ torch.manual_seed(0)
682
+ model_path = "playgroundai/playground-v2.5-1024px-aesthetic"
683
+
684
+ sd_pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
685
+ model_path, torch_dtype=torch.float16, variant="fp16", add_watermarker=False
686
+ )
687
+
688
+ sd_pipe.enable_model_cpu_offload()
689
+ sd_pipe.scheduler = EDMDPMSolverMultistepScheduler.from_config(
690
+ sd_pipe.scheduler.config, use_karras_sigmas=True
691
+ )
692
+ sd_pipe.set_progress_bar_config(disable=None)
693
+
694
+ prompt = "a photo of an astronaut riding a horse on mars"
695
+
696
+ url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
697
+
698
+ init_image = load_image(url).convert("RGB")
699
+
700
+ image = sd_pipe(
701
+ prompt,
702
+ num_inference_steps=30,
703
+ guidance_scale=8.0,
704
+ image=init_image,
705
+ height=1024,
706
+ width=1024,
707
+ output_type="np",
708
+ ).images
709
+
710
+ image_slice = image[0, -3:, -3:, -1]
711
+
712
+ assert image.shape == (1, 1024, 1024, 3)
713
+
714
+ expected_slice = np.array([0.3519, 0.3149, 0.3364, 0.3505, 0.3402, 0.3371, 0.3554, 0.3495, 0.3333])
715
+
716
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_inpaint.py ADDED
@@ -0,0 +1,826 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 copy
17
+ import random
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import torch
22
+ from PIL import Image
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextConfig,
26
+ CLIPTextModel,
27
+ CLIPTextModelWithProjection,
28
+ CLIPTokenizer,
29
+ CLIPVisionConfig,
30
+ CLIPVisionModelWithProjection,
31
+ )
32
+
33
+ from diffusers import (
34
+ AutoencoderKL,
35
+ DDIMScheduler,
36
+ DPMSolverMultistepScheduler,
37
+ EulerDiscreteScheduler,
38
+ HeunDiscreteScheduler,
39
+ LCMScheduler,
40
+ StableDiffusionXLInpaintPipeline,
41
+ UNet2DConditionModel,
42
+ UniPCMultistepScheduler,
43
+ )
44
+ from diffusers.utils.testing_utils import (
45
+ enable_full_determinism,
46
+ floats_tensor,
47
+ require_torch_accelerator,
48
+ slow,
49
+ torch_device,
50
+ )
51
+
52
+ from ..pipeline_params import (
53
+ TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
54
+ TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
55
+ TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
56
+ )
57
+ from ..test_pipelines_common import IPAdapterTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
58
+
59
+
60
+ enable_full_determinism()
61
+
62
+
63
+ class StableDiffusionXLInpaintPipelineFastTests(
64
+ IPAdapterTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, unittest.TestCase
65
+ ):
66
+ pipeline_class = StableDiffusionXLInpaintPipeline
67
+ params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
68
+ batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
69
+ image_params = frozenset([])
70
+ # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
71
+ image_latents_params = frozenset([])
72
+ callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union(
73
+ {
74
+ "add_text_embeds",
75
+ "add_time_ids",
76
+ "mask",
77
+ "masked_image_latents",
78
+ }
79
+ )
80
+
81
+ supports_dduf = False
82
+
83
+ def get_dummy_components(self, skip_first_text_encoder=False, time_cond_proj_dim=None):
84
+ torch.manual_seed(0)
85
+ unet = UNet2DConditionModel(
86
+ block_out_channels=(32, 64),
87
+ layers_per_block=2,
88
+ sample_size=32,
89
+ in_channels=4,
90
+ out_channels=4,
91
+ time_cond_proj_dim=time_cond_proj_dim,
92
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
93
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
94
+ # SD2-specific config below
95
+ attention_head_dim=(2, 4),
96
+ use_linear_projection=True,
97
+ addition_embed_type="text_time",
98
+ addition_time_embed_dim=8,
99
+ transformer_layers_per_block=(1, 2),
100
+ projection_class_embeddings_input_dim=72, # 5 * 8 + 32
101
+ cross_attention_dim=64 if not skip_first_text_encoder else 32,
102
+ )
103
+ scheduler = EulerDiscreteScheduler(
104
+ beta_start=0.00085,
105
+ beta_end=0.012,
106
+ steps_offset=1,
107
+ beta_schedule="scaled_linear",
108
+ timestep_spacing="leading",
109
+ )
110
+ torch.manual_seed(0)
111
+ vae = AutoencoderKL(
112
+ block_out_channels=[32, 64],
113
+ in_channels=3,
114
+ out_channels=3,
115
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
116
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
117
+ latent_channels=4,
118
+ sample_size=128,
119
+ )
120
+ torch.manual_seed(0)
121
+ text_encoder_config = CLIPTextConfig(
122
+ bos_token_id=0,
123
+ eos_token_id=2,
124
+ hidden_size=32,
125
+ intermediate_size=37,
126
+ layer_norm_eps=1e-05,
127
+ num_attention_heads=4,
128
+ num_hidden_layers=5,
129
+ pad_token_id=1,
130
+ vocab_size=1000,
131
+ # SD2-specific config below
132
+ hidden_act="gelu",
133
+ projection_dim=32,
134
+ )
135
+ text_encoder = CLIPTextModel(text_encoder_config)
136
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
137
+
138
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
139
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
140
+
141
+ torch.manual_seed(0)
142
+ image_encoder_config = CLIPVisionConfig(
143
+ hidden_size=32,
144
+ image_size=224,
145
+ projection_dim=32,
146
+ intermediate_size=37,
147
+ num_attention_heads=4,
148
+ num_channels=3,
149
+ num_hidden_layers=5,
150
+ patch_size=14,
151
+ )
152
+
153
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
154
+
155
+ feature_extractor = CLIPImageProcessor(
156
+ crop_size=224,
157
+ do_center_crop=True,
158
+ do_normalize=True,
159
+ do_resize=True,
160
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
161
+ image_std=[0.26862954, 0.26130258, 0.27577711],
162
+ resample=3,
163
+ size=224,
164
+ )
165
+
166
+ components = {
167
+ "unet": unet,
168
+ "scheduler": scheduler,
169
+ "vae": vae,
170
+ "text_encoder": text_encoder if not skip_first_text_encoder else None,
171
+ "tokenizer": tokenizer if not skip_first_text_encoder else None,
172
+ "text_encoder_2": text_encoder_2,
173
+ "tokenizer_2": tokenizer_2,
174
+ "image_encoder": image_encoder,
175
+ "feature_extractor": feature_extractor,
176
+ "requires_aesthetics_score": True,
177
+ }
178
+ return components
179
+
180
+ def get_dummy_inputs(self, device, seed=0):
181
+ # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
182
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
183
+ image = image.cpu().permute(0, 2, 3, 1)[0]
184
+ init_image = Image.fromarray(np.uint8(image)).convert("RGB").resize((64, 64))
185
+ # create mask
186
+ image[8:, 8:, :] = 255
187
+ mask_image = Image.fromarray(np.uint8(image)).convert("L").resize((64, 64))
188
+
189
+ if str(device).startswith("mps"):
190
+ generator = torch.manual_seed(seed)
191
+ else:
192
+ generator = torch.Generator(device=device).manual_seed(seed)
193
+ inputs = {
194
+ "prompt": "A painting of a squirrel eating a burger",
195
+ "image": init_image,
196
+ "mask_image": mask_image,
197
+ "generator": generator,
198
+ "num_inference_steps": 2,
199
+ "guidance_scale": 6.0,
200
+ "strength": 1.0,
201
+ "output_type": "np",
202
+ }
203
+ return inputs
204
+
205
+ def get_dummy_inputs_2images(self, device, seed=0, img_res=64):
206
+ # Get random floats in [0, 1] as image with spatial size (img_res, img_res)
207
+ image1 = floats_tensor((1, 3, img_res, img_res), rng=random.Random(seed)).to(device)
208
+ image2 = floats_tensor((1, 3, img_res, img_res), rng=random.Random(seed + 22)).to(device)
209
+ # Convert images to [-1, 1]
210
+ init_image1 = 2.0 * image1 - 1.0
211
+ init_image2 = 2.0 * image2 - 1.0
212
+
213
+ # empty mask
214
+ mask_image = torch.zeros((1, 1, img_res, img_res), device=device)
215
+
216
+ if str(device).startswith("mps"):
217
+ generator1 = torch.manual_seed(seed)
218
+ generator2 = torch.manual_seed(seed)
219
+ else:
220
+ generator1 = torch.Generator(device=device).manual_seed(seed)
221
+ generator2 = torch.Generator(device=device).manual_seed(seed)
222
+
223
+ inputs = {
224
+ "prompt": ["A painting of a squirrel eating a burger"] * 2,
225
+ "image": [init_image1, init_image2],
226
+ "mask_image": [mask_image] * 2,
227
+ "generator": [generator1, generator2],
228
+ "num_inference_steps": 2,
229
+ "guidance_scale": 6.0,
230
+ "output_type": "np",
231
+ }
232
+ return inputs
233
+
234
+ def test_ip_adapter(self):
235
+ expected_pipe_slice = None
236
+ if torch_device == "cpu":
237
+ expected_pipe_slice = np.array([0.8274, 0.5538, 0.6141, 0.5843, 0.6865, 0.7082, 0.5861, 0.6123, 0.5344])
238
+
239
+ return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
240
+
241
+ def test_components_function(self):
242
+ init_components = self.get_dummy_components()
243
+ init_components.pop("requires_aesthetics_score")
244
+ pipe = self.pipeline_class(**init_components)
245
+
246
+ self.assertTrue(hasattr(pipe, "components"))
247
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
248
+
249
+ def test_stable_diffusion_xl_inpaint_euler(self):
250
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
251
+ components = self.get_dummy_components()
252
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
253
+ sd_pipe = sd_pipe.to(device)
254
+ sd_pipe.set_progress_bar_config(disable=None)
255
+
256
+ inputs = self.get_dummy_inputs(device)
257
+ image = sd_pipe(**inputs).images
258
+ image_slice = image[0, -3:, -3:, -1]
259
+
260
+ assert image.shape == (1, 64, 64, 3)
261
+
262
+ expected_slice = np.array([0.8279, 0.5673, 0.6088, 0.6156, 0.6923, 0.7347, 0.6547, 0.6108, 0.5198])
263
+
264
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
265
+
266
+ def test_stable_diffusion_xl_inpaint_euler_lcm(self):
267
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
268
+ components = self.get_dummy_components(time_cond_proj_dim=256)
269
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
270
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.config)
271
+ sd_pipe = sd_pipe.to(device)
272
+ sd_pipe.set_progress_bar_config(disable=None)
273
+
274
+ inputs = self.get_dummy_inputs(device)
275
+ image = sd_pipe(**inputs).images
276
+ image_slice = image[0, -3:, -3:, -1]
277
+
278
+ assert image.shape == (1, 64, 64, 3)
279
+
280
+ expected_slice = np.array([0.6611, 0.5569, 0.5531, 0.5471, 0.5918, 0.6393, 0.5074, 0.5468, 0.5185])
281
+
282
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
283
+
284
+ def test_stable_diffusion_xl_inpaint_euler_lcm_custom_timesteps(self):
285
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
286
+ components = self.get_dummy_components(time_cond_proj_dim=256)
287
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
288
+ sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.config)
289
+ sd_pipe = sd_pipe.to(device)
290
+ sd_pipe.set_progress_bar_config(disable=None)
291
+
292
+ inputs = self.get_dummy_inputs(device)
293
+ del inputs["num_inference_steps"]
294
+ inputs["timesteps"] = [999, 499]
295
+ image = sd_pipe(**inputs).images
296
+ image_slice = image[0, -3:, -3:, -1]
297
+
298
+ assert image.shape == (1, 64, 64, 3)
299
+
300
+ expected_slice = np.array([0.6611, 0.5569, 0.5531, 0.5471, 0.5918, 0.6393, 0.5074, 0.5468, 0.5185])
301
+
302
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
303
+
304
+ def test_attention_slicing_forward_pass(self):
305
+ super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
306
+
307
+ def test_inference_batch_single_identical(self):
308
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
309
+
310
+ @unittest.skip("Skip for now.")
311
+ def test_save_load_optional_components(self):
312
+ pass
313
+
314
+ @require_torch_accelerator
315
+ def test_stable_diffusion_xl_inpaint_negative_prompt_embeds(self):
316
+ components = self.get_dummy_components()
317
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
318
+ sd_pipe = sd_pipe.to(torch_device)
319
+ sd_pipe = sd_pipe.to(torch_device)
320
+ sd_pipe.set_progress_bar_config(disable=None)
321
+
322
+ # forward without prompt embeds
323
+ inputs = self.get_dummy_inputs(torch_device)
324
+ negative_prompt = 3 * ["this is a negative prompt"]
325
+ inputs["negative_prompt"] = negative_prompt
326
+ inputs["prompt"] = 3 * [inputs["prompt"]]
327
+
328
+ output = sd_pipe(**inputs)
329
+ image_slice_1 = output.images[0, -3:, -3:, -1]
330
+
331
+ # forward with prompt embeds
332
+ inputs = self.get_dummy_inputs(torch_device)
333
+ negative_prompt = 3 * ["this is a negative prompt"]
334
+ prompt = 3 * [inputs.pop("prompt")]
335
+
336
+ (
337
+ prompt_embeds,
338
+ negative_prompt_embeds,
339
+ pooled_prompt_embeds,
340
+ negative_pooled_prompt_embeds,
341
+ ) = sd_pipe.encode_prompt(prompt, negative_prompt=negative_prompt)
342
+
343
+ output = sd_pipe(
344
+ **inputs,
345
+ prompt_embeds=prompt_embeds,
346
+ negative_prompt_embeds=negative_prompt_embeds,
347
+ pooled_prompt_embeds=pooled_prompt_embeds,
348
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
349
+ )
350
+ image_slice_2 = output.images[0, -3:, -3:, -1]
351
+
352
+ # make sure that it's equal
353
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
354
+
355
+ @require_torch_accelerator
356
+ def test_stable_diffusion_xl_offloads(self):
357
+ pipes = []
358
+ components = self.get_dummy_components()
359
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
360
+ pipes.append(sd_pipe)
361
+
362
+ components = self.get_dummy_components()
363
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
364
+ sd_pipe.enable_model_cpu_offload(device=torch_device)
365
+ pipes.append(sd_pipe)
366
+
367
+ components = self.get_dummy_components()
368
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
369
+ sd_pipe.enable_sequential_cpu_offload(device=torch_device)
370
+ pipes.append(sd_pipe)
371
+
372
+ image_slices = []
373
+ for pipe in pipes:
374
+ pipe.unet.set_default_attn_processor()
375
+
376
+ inputs = self.get_dummy_inputs(torch_device)
377
+ image = pipe(**inputs).images
378
+
379
+ image_slices.append(image[0, -3:, -3:, -1].flatten())
380
+
381
+ assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
382
+ assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
383
+
384
+ def test_stable_diffusion_xl_refiner(self):
385
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
386
+ components = self.get_dummy_components(skip_first_text_encoder=True)
387
+
388
+ sd_pipe = self.pipeline_class(**components)
389
+ sd_pipe = sd_pipe.to(device)
390
+ sd_pipe.set_progress_bar_config(disable=None)
391
+
392
+ inputs = self.get_dummy_inputs(device)
393
+ image = sd_pipe(**inputs).images
394
+ image_slice = image[0, -3:, -3:, -1]
395
+
396
+ assert image.shape == (1, 64, 64, 3)
397
+
398
+ expected_slice = np.array([0.7540, 0.5231, 0.5833, 0.6217, 0.6339, 0.7067, 0.6507, 0.5672, 0.5030])
399
+
400
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
401
+
402
+ def test_stable_diffusion_two_xl_mixture_of_denoiser_fast(self):
403
+ components = self.get_dummy_components()
404
+ pipe_1 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
405
+ pipe_1.unet.set_default_attn_processor()
406
+ pipe_2 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
407
+ pipe_2.unet.set_default_attn_processor()
408
+
409
+ def assert_run_mixture(
410
+ num_steps, split, scheduler_cls_orig, num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps
411
+ ):
412
+ inputs = self.get_dummy_inputs(torch_device)
413
+ inputs["num_inference_steps"] = num_steps
414
+
415
+ class scheduler_cls(scheduler_cls_orig):
416
+ pass
417
+
418
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
419
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
420
+
421
+ # Let's retrieve the number of timesteps we want to use
422
+ pipe_1.scheduler.set_timesteps(num_steps)
423
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
424
+
425
+ split_ts = num_train_timesteps - int(round(num_train_timesteps * split))
426
+
427
+ if pipe_1.scheduler.order == 2:
428
+ expected_steps_1 = list(filter(lambda ts: ts >= split_ts, expected_steps))
429
+ expected_steps_2 = expected_steps_1[-1:] + list(filter(lambda ts: ts < split_ts, expected_steps))
430
+ expected_steps = expected_steps_1 + expected_steps_2
431
+ else:
432
+ expected_steps_1 = list(filter(lambda ts: ts >= split_ts, expected_steps))
433
+ expected_steps_2 = list(filter(lambda ts: ts < split_ts, expected_steps))
434
+
435
+ # now we monkey patch step `done_steps`
436
+ # list into the step function for testing
437
+ done_steps = []
438
+ old_step = copy.copy(scheduler_cls.step)
439
+
440
+ def new_step(self, *args, **kwargs):
441
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
442
+ return old_step(self, *args, **kwargs)
443
+
444
+ scheduler_cls.step = new_step
445
+
446
+ inputs_1 = {**inputs, **{"denoising_end": split, "output_type": "latent"}}
447
+ latents = pipe_1(**inputs_1).images[0]
448
+
449
+ assert expected_steps_1 == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
450
+
451
+ inputs_2 = {**inputs, **{"denoising_start": split, "image": latents}}
452
+ pipe_2(**inputs_2).images[0]
453
+
454
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
455
+ assert expected_steps == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
456
+
457
+ for steps in [7, 20]:
458
+ assert_run_mixture(steps, 0.33, EulerDiscreteScheduler)
459
+ assert_run_mixture(steps, 0.33, HeunDiscreteScheduler)
460
+
461
+ @slow
462
+ def test_stable_diffusion_two_xl_mixture_of_denoiser(self):
463
+ components = self.get_dummy_components()
464
+ pipe_1 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
465
+ pipe_1.unet.set_default_attn_processor()
466
+ pipe_2 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
467
+ pipe_2.unet.set_default_attn_processor()
468
+
469
+ def assert_run_mixture(
470
+ num_steps, split, scheduler_cls_orig, num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps
471
+ ):
472
+ inputs = self.get_dummy_inputs(torch_device)
473
+ inputs["num_inference_steps"] = num_steps
474
+
475
+ class scheduler_cls(scheduler_cls_orig):
476
+ pass
477
+
478
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
479
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
480
+
481
+ # Let's retrieve the number of timesteps we want to use
482
+ pipe_1.scheduler.set_timesteps(num_steps)
483
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
484
+
485
+ split_ts = num_train_timesteps - int(round(num_train_timesteps * split))
486
+
487
+ if pipe_1.scheduler.order == 2:
488
+ expected_steps_1 = list(filter(lambda ts: ts >= split_ts, expected_steps))
489
+ expected_steps_2 = expected_steps_1[-1:] + list(filter(lambda ts: ts < split_ts, expected_steps))
490
+ expected_steps = expected_steps_1 + expected_steps_2
491
+ else:
492
+ expected_steps_1 = list(filter(lambda ts: ts >= split_ts, expected_steps))
493
+ expected_steps_2 = list(filter(lambda ts: ts < split_ts, expected_steps))
494
+
495
+ # now we monkey patch step `done_steps`
496
+ # list into the step function for testing
497
+ done_steps = []
498
+ old_step = copy.copy(scheduler_cls.step)
499
+
500
+ def new_step(self, *args, **kwargs):
501
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
502
+ return old_step(self, *args, **kwargs)
503
+
504
+ scheduler_cls.step = new_step
505
+
506
+ inputs_1 = {**inputs, **{"denoising_end": split, "output_type": "latent"}}
507
+ latents = pipe_1(**inputs_1).images[0]
508
+
509
+ assert expected_steps_1 == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
510
+
511
+ inputs_2 = {**inputs, **{"denoising_start": split, "image": latents}}
512
+ pipe_2(**inputs_2).images[0]
513
+
514
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
515
+ assert expected_steps == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
516
+
517
+ for steps in [5, 8, 20]:
518
+ for split in [0.33, 0.49, 0.71]:
519
+ for scheduler_cls in [
520
+ DDIMScheduler,
521
+ EulerDiscreteScheduler,
522
+ DPMSolverMultistepScheduler,
523
+ UniPCMultistepScheduler,
524
+ HeunDiscreteScheduler,
525
+ ]:
526
+ assert_run_mixture(steps, split, scheduler_cls)
527
+
528
+ @slow
529
+ def test_stable_diffusion_three_xl_mixture_of_denoiser(self):
530
+ components = self.get_dummy_components()
531
+ pipe_1 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
532
+ pipe_1.unet.set_default_attn_processor()
533
+ pipe_2 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
534
+ pipe_2.unet.set_default_attn_processor()
535
+ pipe_3 = StableDiffusionXLInpaintPipeline(**components).to(torch_device)
536
+ pipe_3.unet.set_default_attn_processor()
537
+
538
+ def assert_run_mixture(
539
+ num_steps,
540
+ split_1,
541
+ split_2,
542
+ scheduler_cls_orig,
543
+ num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps,
544
+ ):
545
+ inputs = self.get_dummy_inputs(torch_device)
546
+ inputs["num_inference_steps"] = num_steps
547
+
548
+ class scheduler_cls(scheduler_cls_orig):
549
+ pass
550
+
551
+ pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
552
+ pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
553
+ pipe_3.scheduler = scheduler_cls.from_config(pipe_3.scheduler.config)
554
+
555
+ # Let's retrieve the number of timesteps we want to use
556
+ pipe_1.scheduler.set_timesteps(num_steps)
557
+ expected_steps = pipe_1.scheduler.timesteps.tolist()
558
+
559
+ split_1_ts = num_train_timesteps - int(round(num_train_timesteps * split_1))
560
+ split_2_ts = num_train_timesteps - int(round(num_train_timesteps * split_2))
561
+
562
+ if pipe_1.scheduler.order == 2:
563
+ expected_steps_1 = list(filter(lambda ts: ts >= split_1_ts, expected_steps))
564
+ expected_steps_2 = expected_steps_1[-1:] + list(
565
+ filter(lambda ts: ts >= split_2_ts and ts < split_1_ts, expected_steps)
566
+ )
567
+ expected_steps_3 = expected_steps_2[-1:] + list(filter(lambda ts: ts < split_2_ts, expected_steps))
568
+ expected_steps = expected_steps_1 + expected_steps_2 + expected_steps_3
569
+ else:
570
+ expected_steps_1 = list(filter(lambda ts: ts >= split_1_ts, expected_steps))
571
+ expected_steps_2 = list(filter(lambda ts: ts >= split_2_ts and ts < split_1_ts, expected_steps))
572
+ expected_steps_3 = list(filter(lambda ts: ts < split_2_ts, expected_steps))
573
+
574
+ # now we monkey patch step `done_steps`
575
+ # list into the step function for testing
576
+ done_steps = []
577
+ old_step = copy.copy(scheduler_cls.step)
578
+
579
+ def new_step(self, *args, **kwargs):
580
+ done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
581
+ return old_step(self, *args, **kwargs)
582
+
583
+ scheduler_cls.step = new_step
584
+
585
+ inputs_1 = {**inputs, **{"denoising_end": split_1, "output_type": "latent"}}
586
+ latents = pipe_1(**inputs_1).images[0]
587
+
588
+ assert expected_steps_1 == done_steps, (
589
+ f"Failure with {scheduler_cls.__name__} and {num_steps} and {split_1} and {split_2}"
590
+ )
591
+
592
+ inputs_2 = {
593
+ **inputs,
594
+ **{"denoising_start": split_1, "denoising_end": split_2, "image": latents, "output_type": "latent"},
595
+ }
596
+ pipe_2(**inputs_2).images[0]
597
+
598
+ assert expected_steps_2 == done_steps[len(expected_steps_1) :]
599
+
600
+ inputs_3 = {**inputs, **{"denoising_start": split_2, "image": latents}}
601
+ pipe_3(**inputs_3).images[0]
602
+
603
+ assert expected_steps_3 == done_steps[len(expected_steps_1) + len(expected_steps_2) :]
604
+ assert expected_steps == done_steps, (
605
+ f"Failure with {scheduler_cls.__name__} and {num_steps} and {split_1} and {split_2}"
606
+ )
607
+
608
+ for steps in [7, 11, 20]:
609
+ for split_1, split_2 in zip([0.19, 0.32], [0.81, 0.68]):
610
+ for scheduler_cls in [
611
+ DDIMScheduler,
612
+ EulerDiscreteScheduler,
613
+ DPMSolverMultistepScheduler,
614
+ UniPCMultistepScheduler,
615
+ HeunDiscreteScheduler,
616
+ ]:
617
+ assert_run_mixture(steps, split_1, split_2, scheduler_cls)
618
+
619
+ def test_stable_diffusion_xl_multi_prompts(self):
620
+ components = self.get_dummy_components()
621
+ sd_pipe = self.pipeline_class(**components).to(torch_device)
622
+
623
+ # forward with single prompt
624
+ inputs = self.get_dummy_inputs(torch_device)
625
+ inputs["num_inference_steps"] = 5
626
+ output = sd_pipe(**inputs)
627
+ image_slice_1 = output.images[0, -3:, -3:, -1]
628
+
629
+ # forward with same prompt duplicated
630
+ inputs = self.get_dummy_inputs(torch_device)
631
+ inputs["num_inference_steps"] = 5
632
+ inputs["prompt_2"] = inputs["prompt"]
633
+ output = sd_pipe(**inputs)
634
+ image_slice_2 = output.images[0, -3:, -3:, -1]
635
+
636
+ # ensure the results are equal
637
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
638
+
639
+ # forward with different prompt
640
+ inputs = self.get_dummy_inputs(torch_device)
641
+ inputs["num_inference_steps"] = 5
642
+ inputs["prompt_2"] = "different prompt"
643
+ output = sd_pipe(**inputs)
644
+ image_slice_3 = output.images[0, -3:, -3:, -1]
645
+
646
+ # ensure the results are not equal
647
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
648
+
649
+ # manually set a negative_prompt
650
+ inputs = self.get_dummy_inputs(torch_device)
651
+ inputs["num_inference_steps"] = 5
652
+ inputs["negative_prompt"] = "negative prompt"
653
+ output = sd_pipe(**inputs)
654
+ image_slice_1 = output.images[0, -3:, -3:, -1]
655
+
656
+ # forward with same negative_prompt duplicated
657
+ inputs = self.get_dummy_inputs(torch_device)
658
+ inputs["num_inference_steps"] = 5
659
+ inputs["negative_prompt"] = "negative prompt"
660
+ inputs["negative_prompt_2"] = inputs["negative_prompt"]
661
+ output = sd_pipe(**inputs)
662
+ image_slice_2 = output.images[0, -3:, -3:, -1]
663
+
664
+ # ensure the results are equal
665
+ assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
666
+
667
+ # forward with different negative_prompt
668
+ inputs = self.get_dummy_inputs(torch_device)
669
+ inputs["num_inference_steps"] = 5
670
+ inputs["negative_prompt"] = "negative prompt"
671
+ inputs["negative_prompt_2"] = "different negative prompt"
672
+ output = sd_pipe(**inputs)
673
+ image_slice_3 = output.images[0, -3:, -3:, -1]
674
+
675
+ # ensure the results are not equal
676
+ assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
677
+
678
+ def test_stable_diffusion_xl_img2img_negative_conditions(self):
679
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
680
+ components = self.get_dummy_components()
681
+ sd_pipe = self.pipeline_class(**components)
682
+ sd_pipe = sd_pipe.to(device)
683
+ sd_pipe.set_progress_bar_config(disable=None)
684
+
685
+ inputs = self.get_dummy_inputs(device)
686
+ image = sd_pipe(**inputs).images
687
+ image_slice_with_no_neg_conditions = image[0, -3:, -3:, -1]
688
+
689
+ image = sd_pipe(
690
+ **inputs,
691
+ negative_original_size=(512, 512),
692
+ negative_crops_coords_top_left=(
693
+ 0,
694
+ 0,
695
+ ),
696
+ negative_target_size=(1024, 1024),
697
+ ).images
698
+ image_slice_with_neg_conditions = image[0, -3:, -3:, -1]
699
+
700
+ assert (
701
+ np.abs(image_slice_with_no_neg_conditions.flatten() - image_slice_with_neg_conditions.flatten()).max()
702
+ > 1e-4
703
+ )
704
+
705
+ def test_stable_diffusion_xl_inpaint_mask_latents(self):
706
+ device = "cpu"
707
+ components = self.get_dummy_components()
708
+ sd_pipe = self.pipeline_class(**components).to(device)
709
+ sd_pipe.set_progress_bar_config(disable=None)
710
+
711
+ # normal mask + normal image
712
+ ## `image`: pil, `mask_image``: pil, `masked_image_latents``: None
713
+ inputs = self.get_dummy_inputs(device)
714
+ inputs["strength"] = 0.9
715
+ out_0 = sd_pipe(**inputs).images
716
+
717
+ # image latents + mask latents
718
+ inputs = self.get_dummy_inputs(device)
719
+ image = sd_pipe.image_processor.preprocess(inputs["image"]).to(sd_pipe.device)
720
+ mask = sd_pipe.mask_processor.preprocess(inputs["mask_image"]).to(sd_pipe.device)
721
+ masked_image = image * (mask < 0.5)
722
+
723
+ generator = torch.Generator(device=device).manual_seed(0)
724
+ image_latents = sd_pipe._encode_vae_image(image, generator=generator)
725
+ torch.randn((1, 4, 32, 32), generator=generator)
726
+ mask_latents = sd_pipe._encode_vae_image(masked_image, generator=generator)
727
+ inputs["image"] = image_latents
728
+ inputs["masked_image_latents"] = mask_latents
729
+ inputs["mask_image"] = mask
730
+ inputs["strength"] = 0.9
731
+ generator = torch.Generator(device=device).manual_seed(0)
732
+ torch.randn((1, 4, 32, 32), generator=generator)
733
+ inputs["generator"] = generator
734
+ out_1 = sd_pipe(**inputs).images
735
+ assert np.abs(out_0 - out_1).max() < 1e-2
736
+
737
+ def test_stable_diffusion_xl_inpaint_2_images(self):
738
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
739
+ components = self.get_dummy_components()
740
+ sd_pipe = self.pipeline_class(**components)
741
+ sd_pipe = sd_pipe.to(device)
742
+ sd_pipe.set_progress_bar_config(disable=None)
743
+
744
+ # test to confirm if we pass two same image, we will get same output
745
+ inputs = self.get_dummy_inputs(device)
746
+ gen1 = torch.Generator(device=device).manual_seed(0)
747
+ gen2 = torch.Generator(device=device).manual_seed(0)
748
+ for name in ["prompt", "image", "mask_image"]:
749
+ inputs[name] = [inputs[name]] * 2
750
+ inputs["generator"] = [gen1, gen2]
751
+ images = sd_pipe(**inputs).images
752
+
753
+ assert images.shape == (2, 64, 64, 3)
754
+
755
+ image_slice1 = images[0, -3:, -3:, -1]
756
+ image_slice2 = images[1, -3:, -3:, -1]
757
+ assert np.abs(image_slice1.flatten() - image_slice2.flatten()).max() < 1e-4
758
+
759
+ # test to confirm that if we pass two different images, we will get different output
760
+ inputs = self.get_dummy_inputs_2images(device)
761
+ images = sd_pipe(**inputs).images
762
+ assert images.shape == (2, 64, 64, 3)
763
+
764
+ image_slice1 = images[0, -3:, -3:, -1]
765
+ image_slice2 = images[1, -3:, -3:, -1]
766
+ assert np.abs(image_slice1.flatten() - image_slice2.flatten()).max() > 1e-2
767
+
768
+ def test_pipeline_interrupt(self):
769
+ components = self.get_dummy_components()
770
+ sd_pipe = StableDiffusionXLInpaintPipeline(**components)
771
+ sd_pipe = sd_pipe.to(torch_device)
772
+ sd_pipe.set_progress_bar_config(disable=None)
773
+
774
+ inputs = self.get_dummy_inputs(torch_device)
775
+
776
+ prompt = "hey"
777
+ num_inference_steps = 5
778
+
779
+ # store intermediate latents from the generation process
780
+ class PipelineState:
781
+ def __init__(self):
782
+ self.state = []
783
+
784
+ def apply(self, pipe, i, t, callback_kwargs):
785
+ self.state.append(callback_kwargs["latents"])
786
+ return callback_kwargs
787
+
788
+ pipe_state = PipelineState()
789
+ sd_pipe(
790
+ prompt,
791
+ image=inputs["image"],
792
+ mask_image=inputs["mask_image"],
793
+ strength=0.8,
794
+ num_inference_steps=num_inference_steps,
795
+ output_type="np",
796
+ generator=torch.Generator("cpu").manual_seed(0),
797
+ callback_on_step_end=pipe_state.apply,
798
+ ).images
799
+
800
+ # interrupt generation at step index
801
+ interrupt_step_idx = 1
802
+
803
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
804
+ if i == interrupt_step_idx:
805
+ pipe._interrupt = True
806
+
807
+ return callback_kwargs
808
+
809
+ output_interrupted = sd_pipe(
810
+ prompt,
811
+ image=inputs["image"],
812
+ mask_image=inputs["mask_image"],
813
+ strength=0.8,
814
+ num_inference_steps=num_inference_steps,
815
+ output_type="latent",
816
+ generator=torch.Generator("cpu").manual_seed(0),
817
+ callback_on_step_end=callback_on_step_end,
818
+ ).images
819
+
820
+ # fetch intermediate latents at the interrupted step
821
+ # from the completed generation process
822
+ intermediate_latent = pipe_state.state[interrupt_step_idx]
823
+
824
+ # compare the intermediate latent to the output of the interrupted process
825
+ # they should be the same
826
+ assert torch.allclose(intermediate_latent, output_interrupted, atol=1e-4)
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_instruction_pix2pix.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Harutatsu Akiyama and 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 random
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
22
+
23
+ from diffusers import (
24
+ AutoencoderKL,
25
+ EulerDiscreteScheduler,
26
+ UNet2DConditionModel,
27
+ )
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_instruct_pix2pix import (
30
+ StableDiffusionXLInstructPix2PixPipeline,
31
+ )
32
+ from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, torch_device
33
+
34
+ from ..pipeline_params import (
35
+ IMAGE_TO_IMAGE_IMAGE_PARAMS,
36
+ TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
37
+ TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
38
+ )
39
+ from ..test_pipelines_common import (
40
+ PipelineKarrasSchedulerTesterMixin,
41
+ PipelineLatentTesterMixin,
42
+ PipelineTesterMixin,
43
+ )
44
+
45
+
46
+ enable_full_determinism()
47
+
48
+
49
+ class StableDiffusionXLInstructPix2PixPipelineFastTests(
50
+ PipelineLatentTesterMixin,
51
+ PipelineKarrasSchedulerTesterMixin,
52
+ PipelineTesterMixin,
53
+ unittest.TestCase,
54
+ ):
55
+ pipeline_class = StableDiffusionXLInstructPix2PixPipeline
56
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width", "cross_attention_kwargs"}
57
+ batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
58
+ image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
59
+ image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
60
+
61
+ def get_dummy_components(self):
62
+ torch.manual_seed(0)
63
+ unet = UNet2DConditionModel(
64
+ block_out_channels=(32, 64),
65
+ layers_per_block=2,
66
+ sample_size=32,
67
+ in_channels=8,
68
+ out_channels=4,
69
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
70
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
71
+ # SD2-specific config below
72
+ attention_head_dim=(2, 4),
73
+ use_linear_projection=True,
74
+ addition_embed_type="text_time",
75
+ addition_time_embed_dim=8,
76
+ transformer_layers_per_block=(1, 2),
77
+ projection_class_embeddings_input_dim=80, # 5 * 8 + 32
78
+ cross_attention_dim=64,
79
+ )
80
+
81
+ scheduler = EulerDiscreteScheduler(
82
+ beta_start=0.00085,
83
+ beta_end=0.012,
84
+ steps_offset=1,
85
+ beta_schedule="scaled_linear",
86
+ timestep_spacing="leading",
87
+ )
88
+ torch.manual_seed(0)
89
+ vae = AutoencoderKL(
90
+ block_out_channels=[32, 64],
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
+ sample_size=128,
97
+ )
98
+ torch.manual_seed(0)
99
+ text_encoder_config = CLIPTextConfig(
100
+ bos_token_id=0,
101
+ eos_token_id=2,
102
+ hidden_size=32,
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
+ # SD2-specific config below
110
+ hidden_act="gelu",
111
+ projection_dim=32,
112
+ )
113
+ text_encoder = CLIPTextModel(text_encoder_config)
114
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
115
+
116
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
117
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
118
+
119
+ components = {
120
+ "unet": unet,
121
+ "scheduler": scheduler,
122
+ "vae": vae,
123
+ "text_encoder": text_encoder,
124
+ "tokenizer": tokenizer,
125
+ "text_encoder_2": text_encoder_2,
126
+ "tokenizer_2": tokenizer_2,
127
+ }
128
+ return components
129
+
130
+ def get_dummy_inputs(self, device, seed=0):
131
+ image = floats_tensor((1, 3, 64, 64), rng=random.Random(seed)).to(device)
132
+ image = image / 2 + 0.5
133
+ if str(device).startswith("mps"):
134
+ generator = torch.manual_seed(seed)
135
+ else:
136
+ generator = torch.Generator(device=device).manual_seed(seed)
137
+ inputs = {
138
+ "prompt": "A painting of a squirrel eating a burger",
139
+ "image": image,
140
+ "generator": generator,
141
+ "num_inference_steps": 2,
142
+ "guidance_scale": 6.0,
143
+ "image_guidance_scale": 1,
144
+ "output_type": "np",
145
+ }
146
+ return inputs
147
+
148
+ def test_components_function(self):
149
+ init_components = self.get_dummy_components()
150
+ pipe = self.pipeline_class(**init_components)
151
+
152
+ self.assertTrue(hasattr(pipe, "components"))
153
+ self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
154
+
155
+ def test_inference_batch_single_identical(self):
156
+ super().test_inference_batch_single_identical(expected_max_diff=3e-3)
157
+
158
+ def test_attention_slicing_forward_pass(self):
159
+ super().test_attention_slicing_forward_pass(expected_max_diff=2e-3)
160
+
161
+ # Overwrite the default test_latents_inputs because pix2pix encode the image differently
162
+ def test_latents_input(self):
163
+ components = self.get_dummy_components()
164
+ pipe = StableDiffusionXLInstructPix2PixPipeline(**components)
165
+ pipe.image_processor = VaeImageProcessor(do_resize=False, do_normalize=False)
166
+ pipe = pipe.to(torch_device)
167
+ pipe.set_progress_bar_config(disable=None)
168
+
169
+ out = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="pt"))[0]
170
+
171
+ vae = components["vae"]
172
+ inputs = self.get_dummy_inputs_by_type(torch_device, input_image_type="pt")
173
+
174
+ for image_param in self.image_latents_params:
175
+ if image_param in inputs.keys():
176
+ inputs[image_param] = vae.encode(inputs[image_param]).latent_dist.mode()
177
+
178
+ out_latents_inputs = pipe(**inputs)[0]
179
+
180
+ max_diff = np.abs(out - out_latents_inputs).max()
181
+ self.assertLess(max_diff, 1e-4, "passing latents as image input generate different result from passing image")
182
+
183
+ @unittest.skip("Test not supported at the moment.")
184
+ def test_cfg(self):
185
+ pass
186
+
187
+ @unittest.skip("Functionality is tested elsewhere.")
188
+ def test_save_load_optional_components(self):
189
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_diffusion_xl/test_stable_diffusion_xl_k_diffusion.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 StableDiffusionXLKDiffusionPipeline
23
+ from diffusers.utils.testing_utils import (
24
+ Expectations,
25
+ backend_empty_cache,
26
+ enable_full_determinism,
27
+ require_torch_accelerator,
28
+ slow,
29
+ torch_device,
30
+ )
31
+
32
+
33
+ enable_full_determinism()
34
+
35
+
36
+ @slow
37
+ @require_torch_accelerator
38
+ class StableDiffusionXLKPipelineIntegrationTests(unittest.TestCase):
39
+ dtype = torch.float16
40
+
41
+ def setUp(self):
42
+ # clean up the VRAM before each test
43
+ super().setUp()
44
+ gc.collect()
45
+ backend_empty_cache(torch_device)
46
+
47
+ def tearDown(self):
48
+ # clean up the VRAM after each test
49
+ super().tearDown()
50
+ gc.collect()
51
+ backend_empty_cache(torch_device)
52
+
53
+ def test_stable_diffusion_xl(self):
54
+ sd_pipe = StableDiffusionXLKDiffusionPipeline.from_pretrained(
55
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=self.dtype
56
+ )
57
+ sd_pipe = sd_pipe.to(torch_device)
58
+ sd_pipe.set_progress_bar_config(disable=None)
59
+
60
+ sd_pipe.set_scheduler("sample_euler")
61
+
62
+ prompt = "A painting of a squirrel eating a burger"
63
+ generator = torch.manual_seed(0)
64
+ output = sd_pipe(
65
+ [prompt],
66
+ generator=generator,
67
+ guidance_scale=9.0,
68
+ num_inference_steps=2,
69
+ height=512,
70
+ width=512,
71
+ output_type="np",
72
+ )
73
+
74
+ image = output.images
75
+
76
+ image_slice = image[0, -3:, -3:, -1]
77
+
78
+ assert image.shape == (1, 512, 512, 3)
79
+ expected_slice = np.array([0.5420, 0.5038, 0.2439, 0.5371, 0.4660, 0.1906, 0.5221, 0.4290, 0.2566])
80
+
81
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
82
+
83
+ def test_stable_diffusion_karras_sigmas(self):
84
+ sd_pipe = StableDiffusionXLKDiffusionPipeline.from_pretrained(
85
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=self.dtype
86
+ )
87
+ sd_pipe = sd_pipe.to(torch_device)
88
+ sd_pipe.set_progress_bar_config(disable=None)
89
+
90
+ sd_pipe.set_scheduler("sample_dpmpp_2m")
91
+
92
+ prompt = "A painting of a squirrel eating a burger"
93
+ generator = torch.manual_seed(0)
94
+ output = sd_pipe(
95
+ [prompt],
96
+ generator=generator,
97
+ guidance_scale=7.5,
98
+ num_inference_steps=2,
99
+ output_type="np",
100
+ use_karras_sigmas=True,
101
+ height=512,
102
+ width=512,
103
+ )
104
+
105
+ image = output.images
106
+
107
+ image_slice = image[0, -3:, -3:, -1]
108
+
109
+ assert image.shape == (1, 512, 512, 3)
110
+ expected_slices = Expectations(
111
+ {
112
+ ("xpu", 3): np.array(
113
+ [
114
+ 0.6128,
115
+ 0.6108,
116
+ 0.6109,
117
+ 0.5997,
118
+ 0.5988,
119
+ 0.5948,
120
+ 0.5903,
121
+ 0.597,
122
+ 0.5973,
123
+ ]
124
+ ),
125
+ ("cuda", 7): np.array(
126
+ [
127
+ 0.6418,
128
+ 0.6424,
129
+ 0.6462,
130
+ 0.6271,
131
+ 0.6314,
132
+ 0.6295,
133
+ 0.6249,
134
+ 0.6339,
135
+ 0.6335,
136
+ ]
137
+ ),
138
+ }
139
+ )
140
+
141
+ expected_slice = expected_slices.get_expectation()
142
+
143
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
144
+
145
+ def test_stable_diffusion_noise_sampler_seed(self):
146
+ sd_pipe = StableDiffusionXLKDiffusionPipeline.from_pretrained(
147
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=self.dtype
148
+ )
149
+ sd_pipe = sd_pipe.to(torch_device)
150
+ sd_pipe.set_progress_bar_config(disable=None)
151
+
152
+ sd_pipe.set_scheduler("sample_dpmpp_sde")
153
+
154
+ prompt = "A painting of a squirrel eating a burger"
155
+ seed = 0
156
+ images1 = sd_pipe(
157
+ [prompt],
158
+ generator=torch.manual_seed(seed),
159
+ noise_sampler_seed=seed,
160
+ guidance_scale=9.0,
161
+ num_inference_steps=2,
162
+ output_type="np",
163
+ height=512,
164
+ width=512,
165
+ ).images
166
+ images2 = sd_pipe(
167
+ [prompt],
168
+ generator=torch.manual_seed(seed),
169
+ noise_sampler_seed=seed,
170
+ guidance_scale=9.0,
171
+ num_inference_steps=2,
172
+ output_type="np",
173
+ height=512,
174
+ width=512,
175
+ ).images
176
+ assert images1.shape == (1, 512, 512, 3)
177
+ assert images2.shape == (1, 512, 512, 3)
178
+ assert np.abs(images1.flatten() - images2.flatten()).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/test_stable_unclip.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import unittest
3
+
4
+ import torch
5
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
6
+
7
+ from diffusers import (
8
+ AutoencoderKL,
9
+ DDIMScheduler,
10
+ DDPMScheduler,
11
+ PriorTransformer,
12
+ StableUnCLIPPipeline,
13
+ UNet2DConditionModel,
14
+ )
15
+ from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
16
+ from diffusers.utils.testing_utils import (
17
+ backend_empty_cache,
18
+ backend_max_memory_allocated,
19
+ backend_reset_max_memory_allocated,
20
+ backend_reset_peak_memory_stats,
21
+ enable_full_determinism,
22
+ load_numpy,
23
+ nightly,
24
+ require_torch_accelerator,
25
+ torch_device,
26
+ )
27
+
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 (
30
+ PipelineKarrasSchedulerTesterMixin,
31
+ PipelineLatentTesterMixin,
32
+ PipelineTesterMixin,
33
+ assert_mean_pixel_difference,
34
+ )
35
+
36
+
37
+ enable_full_determinism()
38
+
39
+
40
+ class StableUnCLIPPipelineFastTests(
41
+ PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
42
+ ):
43
+ pipeline_class = StableUnCLIPPipeline
44
+ params = TEXT_TO_IMAGE_PARAMS
45
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
46
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
47
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
48
+
49
+ # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
50
+ test_xformers_attention = False
51
+
52
+ def get_dummy_components(self):
53
+ embedder_hidden_size = 32
54
+ embedder_projection_dim = embedder_hidden_size
55
+
56
+ # prior components
57
+
58
+ torch.manual_seed(0)
59
+ prior_tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
60
+
61
+ torch.manual_seed(0)
62
+ prior_text_encoder = CLIPTextModelWithProjection(
63
+ CLIPTextConfig(
64
+ bos_token_id=0,
65
+ eos_token_id=2,
66
+ hidden_size=embedder_hidden_size,
67
+ projection_dim=embedder_projection_dim,
68
+ intermediate_size=37,
69
+ layer_norm_eps=1e-05,
70
+ num_attention_heads=4,
71
+ num_hidden_layers=5,
72
+ pad_token_id=1,
73
+ vocab_size=1000,
74
+ )
75
+ )
76
+
77
+ torch.manual_seed(0)
78
+ prior = PriorTransformer(
79
+ num_attention_heads=2,
80
+ attention_head_dim=12,
81
+ embedding_dim=embedder_projection_dim,
82
+ num_layers=1,
83
+ )
84
+
85
+ torch.manual_seed(0)
86
+ prior_scheduler = DDPMScheduler(
87
+ variance_type="fixed_small_log",
88
+ prediction_type="sample",
89
+ num_train_timesteps=1000,
90
+ clip_sample=True,
91
+ clip_sample_range=5.0,
92
+ beta_schedule="squaredcos_cap_v2",
93
+ )
94
+
95
+ # regular denoising components
96
+
97
+ torch.manual_seed(0)
98
+ image_normalizer = StableUnCLIPImageNormalizer(embedding_dim=embedder_hidden_size)
99
+ image_noising_scheduler = DDPMScheduler(beta_schedule="squaredcos_cap_v2")
100
+
101
+ torch.manual_seed(0)
102
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
103
+
104
+ torch.manual_seed(0)
105
+ text_encoder = CLIPTextModel(
106
+ CLIPTextConfig(
107
+ bos_token_id=0,
108
+ eos_token_id=2,
109
+ hidden_size=embedder_hidden_size,
110
+ projection_dim=32,
111
+ intermediate_size=37,
112
+ layer_norm_eps=1e-05,
113
+ num_attention_heads=4,
114
+ num_hidden_layers=5,
115
+ pad_token_id=1,
116
+ vocab_size=1000,
117
+ )
118
+ )
119
+
120
+ torch.manual_seed(0)
121
+ unet = UNet2DConditionModel(
122
+ sample_size=32,
123
+ in_channels=4,
124
+ out_channels=4,
125
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
126
+ up_block_types=("UpBlock2D", "CrossAttnUpBlock2D"),
127
+ block_out_channels=(32, 64),
128
+ attention_head_dim=(2, 4),
129
+ class_embed_type="projection",
130
+ # The class embeddings are the noise augmented image embeddings.
131
+ # I.e. the image embeddings concated with the noised embeddings of the same dimension
132
+ projection_class_embeddings_input_dim=embedder_projection_dim * 2,
133
+ cross_attention_dim=embedder_hidden_size,
134
+ layers_per_block=1,
135
+ upcast_attention=True,
136
+ use_linear_projection=True,
137
+ )
138
+
139
+ torch.manual_seed(0)
140
+ scheduler = DDIMScheduler(
141
+ beta_schedule="scaled_linear",
142
+ beta_start=0.00085,
143
+ beta_end=0.012,
144
+ prediction_type="v_prediction",
145
+ set_alpha_to_one=False,
146
+ steps_offset=1,
147
+ )
148
+
149
+ torch.manual_seed(0)
150
+ vae = AutoencoderKL()
151
+
152
+ components = {
153
+ # prior components
154
+ "prior_tokenizer": prior_tokenizer,
155
+ "prior_text_encoder": prior_text_encoder,
156
+ "prior": prior,
157
+ "prior_scheduler": prior_scheduler,
158
+ # image noising components
159
+ "image_normalizer": image_normalizer,
160
+ "image_noising_scheduler": image_noising_scheduler,
161
+ # regular denoising components
162
+ "tokenizer": tokenizer,
163
+ "text_encoder": text_encoder,
164
+ "unet": unet,
165
+ "scheduler": scheduler,
166
+ "vae": vae,
167
+ }
168
+
169
+ return components
170
+
171
+ def get_dummy_inputs(self, device, seed=0):
172
+ if str(device).startswith("mps"):
173
+ generator = torch.manual_seed(seed)
174
+ else:
175
+ generator = torch.Generator(device=device).manual_seed(seed)
176
+ inputs = {
177
+ "prompt": "A painting of a squirrel eating a burger",
178
+ "generator": generator,
179
+ "num_inference_steps": 2,
180
+ "prior_num_inference_steps": 2,
181
+ "output_type": "np",
182
+ }
183
+ return inputs
184
+
185
+ # Overriding PipelineTesterMixin::test_attention_slicing_forward_pass
186
+ # because UnCLIP GPU undeterminism requires a looser check.
187
+ def test_attention_slicing_forward_pass(self):
188
+ test_max_difference = torch_device == "cpu"
189
+
190
+ self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference)
191
+
192
+ # Overriding PipelineTesterMixin::test_inference_batch_single_identical
193
+ # because UnCLIP undeterminism requires a looser check.
194
+ def test_inference_batch_single_identical(self):
195
+ self._test_inference_batch_single_identical(expected_max_diff=1e-3)
196
+
197
+ @unittest.skip("Test not supported because of the use of `_encode_prior_prompt()`.")
198
+ def test_encode_prompt_works_in_isolation(self):
199
+ pass
200
+
201
+
202
+ @nightly
203
+ @require_torch_accelerator
204
+ class StableUnCLIPPipelineIntegrationTests(unittest.TestCase):
205
+ def setUp(self):
206
+ # clean up the VRAM before each test
207
+ super().setUp()
208
+ gc.collect()
209
+ backend_empty_cache(torch_device)
210
+
211
+ def tearDown(self):
212
+ # clean up the VRAM after each test
213
+ super().tearDown()
214
+ gc.collect()
215
+ backend_empty_cache(torch_device)
216
+
217
+ def test_stable_unclip(self):
218
+ expected_image = load_numpy(
219
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy"
220
+ )
221
+
222
+ pipe = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l", torch_dtype=torch.float16)
223
+ pipe.set_progress_bar_config(disable=None)
224
+ # stable unclip will oom when integration tests are run on a V100,
225
+ # so turn on memory savings
226
+ pipe.enable_attention_slicing()
227
+ pipe.enable_sequential_cpu_offload()
228
+
229
+ generator = torch.Generator(device="cpu").manual_seed(0)
230
+ output = pipe("anime turle", generator=generator, output_type="np")
231
+
232
+ image = output.images[0]
233
+
234
+ assert image.shape == (768, 768, 3)
235
+
236
+ assert_mean_pixel_difference(image, expected_image)
237
+
238
+ def test_stable_unclip_pipeline_with_sequential_cpu_offloading(self):
239
+ backend_empty_cache(torch_device)
240
+ backend_reset_max_memory_allocated(torch_device)
241
+ backend_reset_peak_memory_stats(torch_device)
242
+
243
+ pipe = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l", torch_dtype=torch.float16)
244
+ pipe.set_progress_bar_config(disable=None)
245
+ pipe.enable_attention_slicing()
246
+ pipe.enable_sequential_cpu_offload()
247
+
248
+ _ = pipe(
249
+ "anime turtle",
250
+ prior_num_inference_steps=2,
251
+ num_inference_steps=2,
252
+ output_type="np",
253
+ )
254
+
255
+ mem_bytes = backend_max_memory_allocated(torch_device)
256
+ # make sure that less than 7 GB is allocated
257
+ assert mem_bytes < 7 * 10**9
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_unclip/test_stable_unclip_img2img.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import random
3
+ import unittest
4
+
5
+ import numpy as np
6
+ import torch
7
+ from transformers import (
8
+ CLIPImageProcessor,
9
+ CLIPTextConfig,
10
+ CLIPTextModel,
11
+ CLIPTokenizer,
12
+ CLIPVisionConfig,
13
+ CLIPVisionModelWithProjection,
14
+ )
15
+
16
+ from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImg2ImgPipeline, UNet2DConditionModel
17
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
18
+ from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
19
+ from diffusers.utils.import_utils import is_xformers_available
20
+ from diffusers.utils.testing_utils import (
21
+ backend_empty_cache,
22
+ backend_max_memory_allocated,
23
+ backend_reset_max_memory_allocated,
24
+ backend_reset_peak_memory_stats,
25
+ enable_full_determinism,
26
+ floats_tensor,
27
+ load_image,
28
+ load_numpy,
29
+ nightly,
30
+ require_torch_accelerator,
31
+ skip_mps,
32
+ torch_device,
33
+ )
34
+
35
+ from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
36
+ from ..test_pipelines_common import (
37
+ PipelineKarrasSchedulerTesterMixin,
38
+ PipelineLatentTesterMixin,
39
+ PipelineTesterMixin,
40
+ assert_mean_pixel_difference,
41
+ )
42
+
43
+
44
+ enable_full_determinism()
45
+
46
+
47
+ class StableUnCLIPImg2ImgPipelineFastTests(
48
+ PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
49
+ ):
50
+ pipeline_class = StableUnCLIPImg2ImgPipeline
51
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS
52
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
53
+ image_params = frozenset(
54
+ []
55
+ ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
56
+ image_latents_params = frozenset([])
57
+
58
+ supports_dduf = False
59
+
60
+ def get_dummy_components(self):
61
+ embedder_hidden_size = 32
62
+ embedder_projection_dim = embedder_hidden_size
63
+
64
+ # image encoding components
65
+
66
+ feature_extractor = CLIPImageProcessor(crop_size=32, size=32)
67
+
68
+ torch.manual_seed(0)
69
+ image_encoder = CLIPVisionModelWithProjection(
70
+ CLIPVisionConfig(
71
+ hidden_size=embedder_hidden_size,
72
+ projection_dim=embedder_projection_dim,
73
+ num_hidden_layers=5,
74
+ num_attention_heads=4,
75
+ image_size=32,
76
+ intermediate_size=37,
77
+ patch_size=1,
78
+ )
79
+ )
80
+
81
+ # regular denoising components
82
+
83
+ torch.manual_seed(0)
84
+ image_normalizer = StableUnCLIPImageNormalizer(embedding_dim=embedder_hidden_size)
85
+ image_noising_scheduler = DDPMScheduler(beta_schedule="squaredcos_cap_v2")
86
+
87
+ torch.manual_seed(0)
88
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
89
+
90
+ torch.manual_seed(0)
91
+ text_encoder = CLIPTextModel(
92
+ CLIPTextConfig(
93
+ bos_token_id=0,
94
+ eos_token_id=2,
95
+ hidden_size=embedder_hidden_size,
96
+ projection_dim=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
+ )
104
+ )
105
+
106
+ torch.manual_seed(0)
107
+ unet = UNet2DConditionModel(
108
+ sample_size=32,
109
+ in_channels=4,
110
+ out_channels=4,
111
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
112
+ up_block_types=("UpBlock2D", "CrossAttnUpBlock2D"),
113
+ block_out_channels=(32, 64),
114
+ attention_head_dim=(2, 4),
115
+ class_embed_type="projection",
116
+ # The class embeddings are the noise augmented image embeddings.
117
+ # I.e. the image embeddings concated with the noised embeddings of the same dimension
118
+ projection_class_embeddings_input_dim=embedder_projection_dim * 2,
119
+ cross_attention_dim=embedder_hidden_size,
120
+ layers_per_block=1,
121
+ upcast_attention=True,
122
+ use_linear_projection=True,
123
+ )
124
+
125
+ torch.manual_seed(0)
126
+ scheduler = DDIMScheduler(
127
+ beta_schedule="scaled_linear",
128
+ beta_start=0.00085,
129
+ beta_end=0.012,
130
+ prediction_type="v_prediction",
131
+ set_alpha_to_one=False,
132
+ steps_offset=1,
133
+ )
134
+
135
+ torch.manual_seed(0)
136
+ vae = AutoencoderKL()
137
+
138
+ components = {
139
+ # image encoding components
140
+ "feature_extractor": feature_extractor,
141
+ "image_encoder": image_encoder.eval(),
142
+ # image noising components
143
+ "image_normalizer": image_normalizer.eval(),
144
+ "image_noising_scheduler": image_noising_scheduler,
145
+ # regular denoising components
146
+ "tokenizer": tokenizer,
147
+ "text_encoder": text_encoder.eval(),
148
+ "unet": unet.eval(),
149
+ "scheduler": scheduler,
150
+ "vae": vae.eval(),
151
+ }
152
+
153
+ return components
154
+
155
+ def get_dummy_inputs(self, device, seed=0, pil_image=True):
156
+ if str(device).startswith("mps"):
157
+ generator = torch.manual_seed(seed)
158
+ else:
159
+ generator = torch.Generator(device=device).manual_seed(seed)
160
+
161
+ input_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
162
+
163
+ if pil_image:
164
+ input_image = input_image * 0.5 + 0.5
165
+ input_image = input_image.clamp(0, 1)
166
+ input_image = input_image.cpu().permute(0, 2, 3, 1).float().numpy()
167
+ input_image = DiffusionPipeline.numpy_to_pil(input_image)[0]
168
+
169
+ return {
170
+ "prompt": "An anime racoon running a marathon",
171
+ "image": input_image,
172
+ "generator": generator,
173
+ "num_inference_steps": 2,
174
+ "output_type": "np",
175
+ }
176
+
177
+ @skip_mps
178
+ def test_image_embeds_none(self):
179
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
180
+ components = self.get_dummy_components()
181
+ sd_pipe = StableUnCLIPImg2ImgPipeline(**components)
182
+ sd_pipe = sd_pipe.to(device)
183
+ sd_pipe.set_progress_bar_config(disable=None)
184
+
185
+ inputs = self.get_dummy_inputs(device)
186
+ inputs.update({"image_embeds": None})
187
+ image = sd_pipe(**inputs).images
188
+ image_slice = image[0, -3:, -3:, -1]
189
+
190
+ assert image.shape == (1, 32, 32, 3)
191
+ expected_slice = np.array([0.4397, 0.7080, 0.5590, 0.4255, 0.7181, 0.5938, 0.4051, 0.3720, 0.5116])
192
+
193
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
194
+
195
+ # Overriding PipelineTesterMixin::test_attention_slicing_forward_pass
196
+ # because GPU undeterminism requires a looser check.
197
+ def test_attention_slicing_forward_pass(self):
198
+ test_max_difference = torch_device in ["cpu", "mps"]
199
+
200
+ self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference)
201
+
202
+ # Overriding PipelineTesterMixin::test_inference_batch_single_identical
203
+ # because undeterminism requires a looser check.
204
+ def test_inference_batch_single_identical(self):
205
+ self._test_inference_batch_single_identical(expected_max_diff=1e-3)
206
+
207
+ @unittest.skipIf(
208
+ torch_device != "cuda" or not is_xformers_available(),
209
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
210
+ )
211
+ def test_xformers_attention_forwardGenerator_pass(self):
212
+ self._test_xformers_attention_forwardGenerator_pass(test_max_difference=False)
213
+
214
+ @unittest.skip("Test not supported at the moment.")
215
+ def test_encode_prompt_works_in_isolation(self):
216
+ pass
217
+
218
+
219
+ @nightly
220
+ @require_torch_accelerator
221
+ class StableUnCLIPImg2ImgPipelineIntegrationTests(unittest.TestCase):
222
+ def setUp(self):
223
+ # clean up the VRAM before each test
224
+ super().setUp()
225
+ gc.collect()
226
+ backend_empty_cache(torch_device)
227
+
228
+ def tearDown(self):
229
+ # clean up the VRAM after each test
230
+ super().tearDown()
231
+ gc.collect()
232
+ backend_empty_cache(torch_device)
233
+
234
+ def test_stable_unclip_l_img2img(self):
235
+ input_image = load_image(
236
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"
237
+ )
238
+
239
+ expected_image = load_numpy(
240
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy"
241
+ )
242
+
243
+ pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
244
+ "fusing/stable-unclip-2-1-l-img2img", torch_dtype=torch.float16
245
+ )
246
+ pipe.set_progress_bar_config(disable=None)
247
+ # stable unclip will oom when integration tests are run on a V100,
248
+ # so turn on memory savings
249
+ pipe.enable_attention_slicing()
250
+ pipe.enable_sequential_cpu_offload()
251
+
252
+ generator = torch.Generator(device="cpu").manual_seed(0)
253
+ output = pipe(input_image, "anime turle", generator=generator, output_type="np")
254
+
255
+ image = output.images[0]
256
+
257
+ assert image.shape == (768, 768, 3)
258
+
259
+ assert_mean_pixel_difference(image, expected_image)
260
+
261
+ def test_stable_unclip_h_img2img(self):
262
+ input_image = load_image(
263
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"
264
+ )
265
+
266
+ expected_image = load_numpy(
267
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy"
268
+ )
269
+
270
+ pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
271
+ "fusing/stable-unclip-2-1-h-img2img", torch_dtype=torch.float16
272
+ )
273
+ pipe.set_progress_bar_config(disable=None)
274
+ # stable unclip will oom when integration tests are run on a V100,
275
+ # so turn on memory savings
276
+ pipe.enable_attention_slicing()
277
+ pipe.enable_sequential_cpu_offload()
278
+
279
+ generator = torch.Generator(device="cpu").manual_seed(0)
280
+ output = pipe(input_image, "anime turle", generator=generator, output_type="np")
281
+
282
+ image = output.images[0]
283
+
284
+ assert image.shape == (768, 768, 3)
285
+
286
+ assert_mean_pixel_difference(image, expected_image)
287
+
288
+ def test_stable_unclip_img2img_pipeline_with_sequential_cpu_offloading(self):
289
+ input_image = load_image(
290
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"
291
+ )
292
+
293
+ backend_empty_cache(torch_device)
294
+ backend_reset_max_memory_allocated(torch_device)
295
+ backend_reset_peak_memory_stats(torch_device)
296
+
297
+ pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
298
+ "fusing/stable-unclip-2-1-h-img2img", torch_dtype=torch.float16
299
+ )
300
+ pipe.set_progress_bar_config(disable=None)
301
+ pipe.enable_attention_slicing()
302
+ pipe.enable_sequential_cpu_offload()
303
+
304
+ _ = pipe(
305
+ input_image,
306
+ "anime turtle",
307
+ num_inference_steps=2,
308
+ output_type="np",
309
+ )
310
+
311
+ mem_bytes = backend_max_memory_allocated(torch_device)
312
+ # make sure that less than 7 GB is allocated
313
+ assert mem_bytes < 7 * 10**9
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_video_diffusion/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/stable_video_diffusion/test_stable_video_diffusion.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import random
3
+ import tempfile
4
+ import unittest
5
+
6
+ import numpy as np
7
+ import torch
8
+ from transformers import (
9
+ CLIPImageProcessor,
10
+ CLIPVisionConfig,
11
+ CLIPVisionModelWithProjection,
12
+ )
13
+
14
+ import diffusers
15
+ from diffusers import (
16
+ AutoencoderKLTemporalDecoder,
17
+ EulerDiscreteScheduler,
18
+ StableVideoDiffusionPipeline,
19
+ UNetSpatioTemporalConditionModel,
20
+ )
21
+ from diffusers.utils import load_image, logging
22
+ from diffusers.utils.import_utils import is_xformers_available
23
+ from diffusers.utils.testing_utils import (
24
+ CaptureLogger,
25
+ backend_empty_cache,
26
+ enable_full_determinism,
27
+ floats_tensor,
28
+ numpy_cosine_similarity_distance,
29
+ require_accelerate_version_greater,
30
+ require_accelerator,
31
+ require_torch_accelerator,
32
+ slow,
33
+ torch_device,
34
+ )
35
+
36
+ from ..test_pipelines_common import PipelineTesterMixin
37
+
38
+
39
+ enable_full_determinism()
40
+
41
+
42
+ def to_np(tensor):
43
+ if isinstance(tensor, torch.Tensor):
44
+ tensor = tensor.detach().cpu().numpy()
45
+
46
+ return tensor
47
+
48
+
49
+ class StableVideoDiffusionPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
50
+ pipeline_class = StableVideoDiffusionPipeline
51
+ params = frozenset(["image"])
52
+ batch_params = frozenset(["image", "generator"])
53
+ required_optional_params = frozenset(
54
+ [
55
+ "num_inference_steps",
56
+ "generator",
57
+ "latents",
58
+ "return_dict",
59
+ ]
60
+ )
61
+
62
+ supports_dduf = False
63
+
64
+ def get_dummy_components(self):
65
+ torch.manual_seed(0)
66
+ unet = UNetSpatioTemporalConditionModel(
67
+ block_out_channels=(32, 64),
68
+ layers_per_block=2,
69
+ sample_size=32,
70
+ in_channels=8,
71
+ out_channels=4,
72
+ down_block_types=(
73
+ "CrossAttnDownBlockSpatioTemporal",
74
+ "DownBlockSpatioTemporal",
75
+ ),
76
+ up_block_types=("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal"),
77
+ cross_attention_dim=32,
78
+ num_attention_heads=8,
79
+ projection_class_embeddings_input_dim=96,
80
+ addition_time_embed_dim=32,
81
+ )
82
+ scheduler = EulerDiscreteScheduler(
83
+ beta_start=0.00085,
84
+ beta_end=0.012,
85
+ beta_schedule="scaled_linear",
86
+ interpolation_type="linear",
87
+ num_train_timesteps=1000,
88
+ prediction_type="v_prediction",
89
+ sigma_max=700.0,
90
+ sigma_min=0.002,
91
+ steps_offset=1,
92
+ timestep_spacing="leading",
93
+ timestep_type="continuous",
94
+ trained_betas=None,
95
+ use_karras_sigmas=True,
96
+ )
97
+
98
+ torch.manual_seed(0)
99
+ vae = AutoencoderKLTemporalDecoder(
100
+ block_out_channels=[32, 64],
101
+ in_channels=3,
102
+ out_channels=3,
103
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
104
+ latent_channels=4,
105
+ )
106
+
107
+ torch.manual_seed(0)
108
+ config = CLIPVisionConfig(
109
+ hidden_size=32,
110
+ projection_dim=32,
111
+ num_hidden_layers=5,
112
+ num_attention_heads=4,
113
+ image_size=32,
114
+ intermediate_size=37,
115
+ patch_size=1,
116
+ )
117
+ image_encoder = CLIPVisionModelWithProjection(config)
118
+
119
+ torch.manual_seed(0)
120
+ feature_extractor = CLIPImageProcessor(crop_size=32, size=32)
121
+ components = {
122
+ "unet": unet,
123
+ "image_encoder": image_encoder,
124
+ "scheduler": scheduler,
125
+ "vae": vae,
126
+ "feature_extractor": feature_extractor,
127
+ }
128
+ return components
129
+
130
+ def get_dummy_inputs(self, device, seed=0):
131
+ if str(device).startswith("mps"):
132
+ generator = torch.manual_seed(seed)
133
+ else:
134
+ generator = torch.Generator(device="cpu").manual_seed(seed)
135
+
136
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(0)).to(device)
137
+ inputs = {
138
+ "generator": generator,
139
+ "image": image,
140
+ "num_inference_steps": 2,
141
+ "output_type": "pt",
142
+ "min_guidance_scale": 1.0,
143
+ "max_guidance_scale": 2.5,
144
+ "num_frames": 2,
145
+ "height": 32,
146
+ "width": 32,
147
+ }
148
+ return inputs
149
+
150
+ @unittest.skip("Deprecated functionality")
151
+ def test_attention_slicing_forward_pass(self):
152
+ pass
153
+
154
+ @unittest.skip("Batched inference works and outputs look correct, but the test is failing")
155
+ def test_inference_batch_single_identical(
156
+ self,
157
+ batch_size=2,
158
+ expected_max_diff=1e-4,
159
+ ):
160
+ components = self.get_dummy_components()
161
+ pipe = self.pipeline_class(**components)
162
+ for components in pipe.components.values():
163
+ if hasattr(components, "set_default_attn_processor"):
164
+ components.set_default_attn_processor()
165
+ pipe.to(torch_device)
166
+
167
+ pipe.set_progress_bar_config(disable=None)
168
+ inputs = self.get_dummy_inputs(torch_device)
169
+
170
+ # Reset generator in case it is has been used in self.get_dummy_inputs
171
+ inputs["generator"] = torch.Generator("cpu").manual_seed(0)
172
+
173
+ logger = logging.get_logger(pipe.__module__)
174
+ logger.setLevel(level=diffusers.logging.FATAL)
175
+
176
+ # batchify inputs
177
+ batched_inputs = {}
178
+ batched_inputs.update(inputs)
179
+
180
+ batched_inputs["generator"] = [torch.Generator("cpu").manual_seed(0) for i in range(batch_size)]
181
+ batched_inputs["image"] = torch.cat([inputs["image"]] * batch_size, dim=0)
182
+
183
+ output = pipe(**inputs).frames
184
+ output_batch = pipe(**batched_inputs).frames
185
+
186
+ assert len(output_batch) == batch_size
187
+
188
+ max_diff = np.abs(to_np(output_batch[0]) - to_np(output[0])).max()
189
+ assert max_diff < expected_max_diff
190
+
191
+ @unittest.skip("Test is similar to test_inference_batch_single_identical")
192
+ def test_inference_batch_consistent(self):
193
+ pass
194
+
195
+ def test_np_output_type(self):
196
+ components = self.get_dummy_components()
197
+ pipe = self.pipeline_class(**components)
198
+ for component in pipe.components.values():
199
+ if hasattr(component, "set_default_attn_processor"):
200
+ component.set_default_attn_processor()
201
+
202
+ pipe.to(torch_device)
203
+ pipe.set_progress_bar_config(disable=None)
204
+
205
+ generator_device = "cpu"
206
+ inputs = self.get_dummy_inputs(generator_device)
207
+ inputs["output_type"] = "np"
208
+ output = pipe(**inputs).frames
209
+ self.assertTrue(isinstance(output, np.ndarray))
210
+ self.assertEqual(len(output.shape), 5)
211
+
212
+ def test_dict_tuple_outputs_equivalent(self, expected_max_difference=1e-4):
213
+ components = self.get_dummy_components()
214
+ pipe = self.pipeline_class(**components)
215
+ for component in pipe.components.values():
216
+ if hasattr(component, "set_default_attn_processor"):
217
+ component.set_default_attn_processor()
218
+
219
+ pipe.to(torch_device)
220
+ pipe.set_progress_bar_config(disable=None)
221
+
222
+ generator_device = "cpu"
223
+ output = pipe(**self.get_dummy_inputs(generator_device)).frames[0]
224
+ output_tuple = pipe(**self.get_dummy_inputs(generator_device), return_dict=False)[0]
225
+
226
+ max_diff = np.abs(to_np(output) - to_np(output_tuple)).max()
227
+ self.assertLess(max_diff, expected_max_difference)
228
+
229
+ @unittest.skip("Test is currently failing")
230
+ def test_float16_inference(self, expected_max_diff=5e-2):
231
+ components = self.get_dummy_components()
232
+ pipe = self.pipeline_class(**components)
233
+ for component in pipe.components.values():
234
+ if hasattr(component, "set_default_attn_processor"):
235
+ component.set_default_attn_processor()
236
+
237
+ pipe.to(torch_device)
238
+ pipe.set_progress_bar_config(disable=None)
239
+
240
+ components = self.get_dummy_components()
241
+ pipe_fp16 = self.pipeline_class(**components)
242
+ for component in pipe_fp16.components.values():
243
+ if hasattr(component, "set_default_attn_processor"):
244
+ component.set_default_attn_processor()
245
+
246
+ pipe_fp16.to(torch_device, torch.float16)
247
+ pipe_fp16.set_progress_bar_config(disable=None)
248
+
249
+ inputs = self.get_dummy_inputs(torch_device)
250
+ output = pipe(**inputs).frames[0]
251
+
252
+ fp16_inputs = self.get_dummy_inputs(torch_device)
253
+ output_fp16 = pipe_fp16(**fp16_inputs).frames[0]
254
+
255
+ max_diff = np.abs(to_np(output) - to_np(output_fp16)).max()
256
+ self.assertLess(max_diff, expected_max_diff, "The outputs of the fp16 and fp32 pipelines are too different.")
257
+
258
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
259
+ @require_accelerator
260
+ def test_save_load_float16(self, expected_max_diff=1e-2):
261
+ components = self.get_dummy_components()
262
+ for name, module in components.items():
263
+ if hasattr(module, "half"):
264
+ components[name] = module.to(torch_device).half()
265
+
266
+ pipe = self.pipeline_class(**components)
267
+ for component in pipe.components.values():
268
+ if hasattr(component, "set_default_attn_processor"):
269
+ component.set_default_attn_processor()
270
+ pipe.to(torch_device)
271
+ pipe.set_progress_bar_config(disable=None)
272
+
273
+ inputs = self.get_dummy_inputs(torch_device)
274
+ output = pipe(**inputs).frames[0]
275
+
276
+ with tempfile.TemporaryDirectory() as tmpdir:
277
+ pipe.save_pretrained(tmpdir)
278
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16)
279
+ for component in pipe_loaded.components.values():
280
+ if hasattr(component, "set_default_attn_processor"):
281
+ component.set_default_attn_processor()
282
+ pipe_loaded.to(torch_device)
283
+ pipe_loaded.set_progress_bar_config(disable=None)
284
+
285
+ for name, component in pipe_loaded.components.items():
286
+ if hasattr(component, "dtype"):
287
+ self.assertTrue(
288
+ component.dtype == torch.float16,
289
+ f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
290
+ )
291
+
292
+ inputs = self.get_dummy_inputs(torch_device)
293
+ output_loaded = pipe_loaded(**inputs).frames[0]
294
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
295
+ self.assertLess(
296
+ max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
297
+ )
298
+
299
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
300
+ if not hasattr(self.pipeline_class, "_optional_components"):
301
+ return
302
+
303
+ components = self.get_dummy_components()
304
+ pipe = self.pipeline_class(**components)
305
+ for component in pipe.components.values():
306
+ if hasattr(component, "set_default_attn_processor"):
307
+ component.set_default_attn_processor()
308
+ pipe.to(torch_device)
309
+ pipe.set_progress_bar_config(disable=None)
310
+
311
+ # set all optional components to None
312
+ for optional_component in pipe._optional_components:
313
+ setattr(pipe, optional_component, None)
314
+
315
+ generator_device = "cpu"
316
+ inputs = self.get_dummy_inputs(generator_device)
317
+ output = pipe(**inputs).frames[0]
318
+
319
+ with tempfile.TemporaryDirectory() as tmpdir:
320
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
321
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
322
+ for component in pipe_loaded.components.values():
323
+ if hasattr(component, "set_default_attn_processor"):
324
+ component.set_default_attn_processor()
325
+ pipe_loaded.to(torch_device)
326
+ pipe_loaded.set_progress_bar_config(disable=None)
327
+
328
+ for optional_component in pipe._optional_components:
329
+ self.assertTrue(
330
+ getattr(pipe_loaded, optional_component) is None,
331
+ f"`{optional_component}` did not stay set to None after loading.",
332
+ )
333
+
334
+ inputs = self.get_dummy_inputs(generator_device)
335
+ output_loaded = pipe_loaded(**inputs).frames[0]
336
+
337
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
338
+ self.assertLess(max_diff, expected_max_difference)
339
+
340
+ def test_save_load_local(self, expected_max_difference=9e-4):
341
+ components = self.get_dummy_components()
342
+ pipe = self.pipeline_class(**components)
343
+ for component in pipe.components.values():
344
+ if hasattr(component, "set_default_attn_processor"):
345
+ component.set_default_attn_processor()
346
+
347
+ pipe.to(torch_device)
348
+ pipe.set_progress_bar_config(disable=None)
349
+
350
+ inputs = self.get_dummy_inputs(torch_device)
351
+ output = pipe(**inputs).frames[0]
352
+
353
+ logger = logging.get_logger("diffusers.pipelines.pipeline_utils")
354
+ logger.setLevel(diffusers.logging.INFO)
355
+
356
+ with tempfile.TemporaryDirectory() as tmpdir:
357
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
358
+
359
+ with CaptureLogger(logger) as cap_logger:
360
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
361
+
362
+ for name in pipe_loaded.components.keys():
363
+ if name not in pipe_loaded._optional_components:
364
+ assert name in str(cap_logger)
365
+
366
+ pipe_loaded.to(torch_device)
367
+ pipe_loaded.set_progress_bar_config(disable=None)
368
+
369
+ inputs = self.get_dummy_inputs(torch_device)
370
+ output_loaded = pipe_loaded(**inputs).frames[0]
371
+
372
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
373
+ self.assertLess(max_diff, expected_max_difference)
374
+
375
+ @require_accelerator
376
+ def test_to_device(self):
377
+ components = self.get_dummy_components()
378
+ pipe = self.pipeline_class(**components)
379
+ pipe.set_progress_bar_config(disable=None)
380
+
381
+ pipe.to("cpu")
382
+ model_devices = [
383
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
384
+ ]
385
+ self.assertTrue(all(device == "cpu" for device in model_devices))
386
+
387
+ output_cpu = pipe(**self.get_dummy_inputs("cpu")).frames[0]
388
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
389
+
390
+ pipe.to(torch_device)
391
+ model_devices = [
392
+ component.device.type for component in pipe.components.values() if hasattr(component, "device")
393
+ ]
394
+ self.assertTrue(all(device == torch_device for device in model_devices))
395
+
396
+ output_device = pipe(**self.get_dummy_inputs(torch_device)).frames[0]
397
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
398
+
399
+ def test_to_dtype(self):
400
+ components = self.get_dummy_components()
401
+ pipe = self.pipeline_class(**components)
402
+ pipe.set_progress_bar_config(disable=None)
403
+
404
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
405
+ self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
406
+
407
+ pipe.to(dtype=torch.float16)
408
+ model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
409
+ self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
410
+
411
+ @require_accelerator
412
+ @require_accelerate_version_greater("0.14.0")
413
+ def test_sequential_cpu_offload_forward_pass(self, expected_max_diff=1e-4):
414
+ components = self.get_dummy_components()
415
+ pipe = self.pipeline_class(**components)
416
+ for component in pipe.components.values():
417
+ if hasattr(component, "set_default_attn_processor"):
418
+ component.set_default_attn_processor()
419
+ pipe.to(torch_device)
420
+ pipe.set_progress_bar_config(disable=None)
421
+
422
+ generator_device = "cpu"
423
+ inputs = self.get_dummy_inputs(generator_device)
424
+ output_without_offload = pipe(**inputs).frames[0]
425
+
426
+ pipe.enable_sequential_cpu_offload(device=torch_device)
427
+
428
+ inputs = self.get_dummy_inputs(generator_device)
429
+ output_with_offload = pipe(**inputs).frames[0]
430
+
431
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
432
+ self.assertLess(max_diff, expected_max_diff, "CPU offloading should not affect the inference results")
433
+
434
+ @require_accelerator
435
+ @require_accelerate_version_greater("0.17.0")
436
+ def test_model_cpu_offload_forward_pass(self, expected_max_diff=2e-4):
437
+ generator_device = "cpu"
438
+ components = self.get_dummy_components()
439
+ pipe = self.pipeline_class(**components)
440
+
441
+ for component in pipe.components.values():
442
+ if hasattr(component, "set_default_attn_processor"):
443
+ component.set_default_attn_processor()
444
+
445
+ pipe = pipe.to(torch_device)
446
+ pipe.set_progress_bar_config(disable=None)
447
+
448
+ inputs = self.get_dummy_inputs(generator_device)
449
+ output_without_offload = pipe(**inputs).frames[0]
450
+
451
+ pipe.enable_model_cpu_offload(device=torch_device)
452
+ inputs = self.get_dummy_inputs(generator_device)
453
+ output_with_offload = pipe(**inputs).frames[0]
454
+
455
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
456
+ self.assertLess(max_diff, expected_max_diff, "CPU offloading should not affect the inference results")
457
+ offloaded_modules = [
458
+ v
459
+ for k, v in pipe.components.items()
460
+ if isinstance(v, torch.nn.Module) and k not in pipe._exclude_from_cpu_offload
461
+ ]
462
+ (
463
+ self.assertTrue(all(v.device.type == "cpu" for v in offloaded_modules)),
464
+ f"Not offloaded: {[v for v in offloaded_modules if v.device.type != 'cpu']}",
465
+ )
466
+
467
+ @unittest.skipIf(
468
+ torch_device != "cuda" or not is_xformers_available(),
469
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
470
+ )
471
+ def test_xformers_attention_forwardGenerator_pass(self):
472
+ expected_max_diff = 9e-4
473
+
474
+ if not self.test_xformers_attention:
475
+ return
476
+
477
+ components = self.get_dummy_components()
478
+ pipe = self.pipeline_class(**components)
479
+ for component in pipe.components.values():
480
+ if hasattr(component, "set_default_attn_processor"):
481
+ component.set_default_attn_processor()
482
+ pipe.to(torch_device)
483
+ pipe.set_progress_bar_config(disable=None)
484
+
485
+ inputs = self.get_dummy_inputs(torch_device)
486
+ output_without_offload = pipe(**inputs).frames[0]
487
+ output_without_offload = (
488
+ output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
489
+ )
490
+
491
+ pipe.enable_xformers_memory_efficient_attention()
492
+ inputs = self.get_dummy_inputs(torch_device)
493
+ output_with_offload = pipe(**inputs).frames[0]
494
+ output_with_offload = (
495
+ output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
496
+ )
497
+
498
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
499
+ self.assertLess(max_diff, expected_max_diff, "XFormers attention should not affect the inference results")
500
+
501
+ def test_disable_cfg(self):
502
+ components = self.get_dummy_components()
503
+ pipe = self.pipeline_class(**components)
504
+ for component in pipe.components.values():
505
+ if hasattr(component, "set_default_attn_processor"):
506
+ component.set_default_attn_processor()
507
+
508
+ pipe.to(torch_device)
509
+ pipe.set_progress_bar_config(disable=None)
510
+
511
+ generator_device = "cpu"
512
+ inputs = self.get_dummy_inputs(generator_device)
513
+ inputs["max_guidance_scale"] = 1.0
514
+ output = pipe(**inputs).frames
515
+ self.assertEqual(len(output.shape), 5)
516
+
517
+
518
+ @slow
519
+ @require_torch_accelerator
520
+ class StableVideoDiffusionPipelineSlowTests(unittest.TestCase):
521
+ def setUp(self):
522
+ # clean up the VRAM before each test
523
+ super().setUp()
524
+ gc.collect()
525
+ backend_empty_cache(torch_device)
526
+
527
+ def tearDown(self):
528
+ # clean up the VRAM after each test
529
+ super().tearDown()
530
+ gc.collect()
531
+ backend_empty_cache(torch_device)
532
+
533
+ def test_sd_video(self):
534
+ pipe = StableVideoDiffusionPipeline.from_pretrained(
535
+ "stabilityai/stable-video-diffusion-img2vid",
536
+ variant="fp16",
537
+ torch_dtype=torch.float16,
538
+ )
539
+ pipe.enable_model_cpu_offload(device=torch_device)
540
+ pipe.set_progress_bar_config(disable=None)
541
+ image = load_image(
542
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/cat_6.png?download=true"
543
+ )
544
+
545
+ generator = torch.Generator("cpu").manual_seed(0)
546
+ num_frames = 3
547
+
548
+ output = pipe(
549
+ image=image,
550
+ num_frames=num_frames,
551
+ generator=generator,
552
+ num_inference_steps=3,
553
+ output_type="np",
554
+ )
555
+
556
+ image = output.frames[0]
557
+ assert image.shape == (num_frames, 576, 1024, 3)
558
+
559
+ image_slice = image[0, -3:, -3:, -1]
560
+ expected_slice = np.array([0.8592, 0.8645, 0.8499, 0.8722, 0.8769, 0.8421, 0.8557, 0.8528, 0.8285])
561
+ assert numpy_cosine_similarity_distance(image_slice.flatten(), expected_slice.flatten()) < 1e-3
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipeline_utils.py ADDED
@@ -0,0 +1,951 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import io
3
+ import re
4
+ import unittest
5
+
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import (
11
+ AnimateDiffPipeline,
12
+ AnimateDiffVideoToVideoPipeline,
13
+ AutoencoderKL,
14
+ DDIMScheduler,
15
+ MotionAdapter,
16
+ StableDiffusionImg2ImgPipeline,
17
+ StableDiffusionInpaintPipeline,
18
+ StableDiffusionPipeline,
19
+ UNet2DConditionModel,
20
+ )
21
+ from diffusers.pipelines.pipeline_loading_utils import is_safetensors_compatible, variant_compatible_siblings
22
+ from diffusers.utils.testing_utils import require_torch_gpu, torch_device
23
+
24
+
25
+ class IsSafetensorsCompatibleTests(unittest.TestCase):
26
+ def test_all_is_compatible(self):
27
+ filenames = [
28
+ "safety_checker/pytorch_model.bin",
29
+ "safety_checker/model.safetensors",
30
+ "vae/diffusion_pytorch_model.bin",
31
+ "vae/diffusion_pytorch_model.safetensors",
32
+ "text_encoder/pytorch_model.bin",
33
+ "text_encoder/model.safetensors",
34
+ "unet/diffusion_pytorch_model.bin",
35
+ "unet/diffusion_pytorch_model.safetensors",
36
+ ]
37
+ self.assertTrue(is_safetensors_compatible(filenames))
38
+
39
+ def test_diffusers_model_is_compatible(self):
40
+ filenames = [
41
+ "unet/diffusion_pytorch_model.bin",
42
+ "unet/diffusion_pytorch_model.safetensors",
43
+ ]
44
+ self.assertTrue(is_safetensors_compatible(filenames))
45
+
46
+ def test_diffusers_model_is_not_compatible(self):
47
+ filenames = [
48
+ "safety_checker/pytorch_model.bin",
49
+ "safety_checker/model.safetensors",
50
+ "vae/diffusion_pytorch_model.bin",
51
+ "vae/diffusion_pytorch_model.safetensors",
52
+ "text_encoder/pytorch_model.bin",
53
+ "text_encoder/model.safetensors",
54
+ "unet/diffusion_pytorch_model.bin",
55
+ # Removed: 'unet/diffusion_pytorch_model.safetensors',
56
+ ]
57
+ self.assertFalse(is_safetensors_compatible(filenames))
58
+
59
+ def test_transformer_model_is_compatible(self):
60
+ filenames = [
61
+ "text_encoder/pytorch_model.bin",
62
+ "text_encoder/model.safetensors",
63
+ ]
64
+ self.assertTrue(is_safetensors_compatible(filenames))
65
+
66
+ def test_transformer_model_is_not_compatible(self):
67
+ filenames = [
68
+ "safety_checker/pytorch_model.bin",
69
+ "safety_checker/model.safetensors",
70
+ "vae/diffusion_pytorch_model.bin",
71
+ "vae/diffusion_pytorch_model.safetensors",
72
+ "text_encoder/pytorch_model.bin",
73
+ # Removed: 'text_encoder/model.safetensors',
74
+ "unet/diffusion_pytorch_model.bin",
75
+ "unet/diffusion_pytorch_model.safetensors",
76
+ ]
77
+ self.assertFalse(is_safetensors_compatible(filenames))
78
+
79
+ def test_all_is_compatible_variant(self):
80
+ filenames = [
81
+ "safety_checker/pytorch_model.fp16.bin",
82
+ "safety_checker/model.fp16.safetensors",
83
+ "vae/diffusion_pytorch_model.fp16.bin",
84
+ "vae/diffusion_pytorch_model.fp16.safetensors",
85
+ "text_encoder/pytorch_model.fp16.bin",
86
+ "text_encoder/model.fp16.safetensors",
87
+ "unet/diffusion_pytorch_model.fp16.bin",
88
+ "unet/diffusion_pytorch_model.fp16.safetensors",
89
+ ]
90
+ self.assertFalse(is_safetensors_compatible(filenames))
91
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
92
+
93
+ def test_diffusers_model_is_compatible_variant(self):
94
+ filenames = [
95
+ "unet/diffusion_pytorch_model.fp16.bin",
96
+ "unet/diffusion_pytorch_model.fp16.safetensors",
97
+ ]
98
+ self.assertFalse(is_safetensors_compatible(filenames))
99
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
100
+
101
+ def test_diffusers_model_is_compatible_variant_mixed(self):
102
+ filenames = [
103
+ "unet/diffusion_pytorch_model.bin",
104
+ "unet/diffusion_pytorch_model.fp16.safetensors",
105
+ ]
106
+ self.assertFalse(is_safetensors_compatible(filenames))
107
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
108
+
109
+ def test_diffusers_model_is_not_compatible_variant(self):
110
+ filenames = [
111
+ "safety_checker/pytorch_model.fp16.bin",
112
+ "safety_checker/model.fp16.safetensors",
113
+ "vae/diffusion_pytorch_model.fp16.bin",
114
+ "vae/diffusion_pytorch_model.fp16.safetensors",
115
+ "text_encoder/pytorch_model.fp16.bin",
116
+ "text_encoder/model.fp16.safetensors",
117
+ "unet/diffusion_pytorch_model.fp16.bin",
118
+ # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
119
+ ]
120
+ self.assertFalse(is_safetensors_compatible(filenames))
121
+
122
+ def test_transformer_model_is_compatible_variant(self):
123
+ filenames = [
124
+ "text_encoder/pytorch_model.fp16.bin",
125
+ "text_encoder/model.fp16.safetensors",
126
+ ]
127
+ self.assertFalse(is_safetensors_compatible(filenames))
128
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
129
+
130
+ def test_transformer_model_is_not_compatible_variant(self):
131
+ filenames = [
132
+ "safety_checker/pytorch_model.fp16.bin",
133
+ "safety_checker/model.fp16.safetensors",
134
+ "vae/diffusion_pytorch_model.fp16.bin",
135
+ "vae/diffusion_pytorch_model.fp16.safetensors",
136
+ "text_encoder/pytorch_model.fp16.bin",
137
+ "unet/diffusion_pytorch_model.fp16.bin",
138
+ "unet/diffusion_pytorch_model.fp16.safetensors",
139
+ ]
140
+ self.assertFalse(is_safetensors_compatible(filenames))
141
+
142
+ def test_transformer_model_is_compatible_variant_extra_folder(self):
143
+ filenames = [
144
+ "safety_checker/pytorch_model.fp16.bin",
145
+ "safety_checker/model.fp16.safetensors",
146
+ "vae/diffusion_pytorch_model.fp16.bin",
147
+ "vae/diffusion_pytorch_model.fp16.safetensors",
148
+ "text_encoder/pytorch_model.fp16.bin",
149
+ "unet/diffusion_pytorch_model.fp16.bin",
150
+ "unet/diffusion_pytorch_model.fp16.safetensors",
151
+ ]
152
+ self.assertFalse(is_safetensors_compatible(filenames, folder_names={"vae", "unet"}))
153
+ self.assertTrue(is_safetensors_compatible(filenames, folder_names={"vae", "unet"}, variant="fp16"))
154
+
155
+ def test_transformer_model_is_not_compatible_variant_extra_folder(self):
156
+ filenames = [
157
+ "safety_checker/pytorch_model.fp16.bin",
158
+ "safety_checker/model.fp16.safetensors",
159
+ "vae/diffusion_pytorch_model.fp16.bin",
160
+ "vae/diffusion_pytorch_model.fp16.safetensors",
161
+ "text_encoder/pytorch_model.fp16.bin",
162
+ "unet/diffusion_pytorch_model.fp16.bin",
163
+ "unet/diffusion_pytorch_model.fp16.safetensors",
164
+ ]
165
+ self.assertFalse(is_safetensors_compatible(filenames, folder_names={"text_encoder"}))
166
+
167
+ def test_transformers_is_compatible_sharded(self):
168
+ filenames = [
169
+ "text_encoder/pytorch_model.bin",
170
+ "text_encoder/model-00001-of-00002.safetensors",
171
+ "text_encoder/model-00002-of-00002.safetensors",
172
+ ]
173
+ self.assertTrue(is_safetensors_compatible(filenames))
174
+
175
+ def test_transformers_is_compatible_variant_sharded(self):
176
+ filenames = [
177
+ "text_encoder/pytorch_model.bin",
178
+ "text_encoder/model.fp16-00001-of-00002.safetensors",
179
+ "text_encoder/model.fp16-00001-of-00002.safetensors",
180
+ ]
181
+ self.assertFalse(is_safetensors_compatible(filenames))
182
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
183
+
184
+ def test_diffusers_is_compatible_sharded(self):
185
+ filenames = [
186
+ "unet/diffusion_pytorch_model.bin",
187
+ "unet/diffusion_pytorch_model-00001-of-00002.safetensors",
188
+ "unet/diffusion_pytorch_model-00002-of-00002.safetensors",
189
+ ]
190
+ self.assertTrue(is_safetensors_compatible(filenames))
191
+
192
+ def test_diffusers_is_compatible_variant_sharded(self):
193
+ filenames = [
194
+ "unet/diffusion_pytorch_model.bin",
195
+ "unet/diffusion_pytorch_model.fp16-00001-of-00002.safetensors",
196
+ "unet/diffusion_pytorch_model.fp16-00001-of-00002.safetensors",
197
+ ]
198
+ self.assertFalse(is_safetensors_compatible(filenames))
199
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
200
+
201
+ def test_diffusers_is_compatible_only_variants(self):
202
+ filenames = [
203
+ "unet/diffusion_pytorch_model.fp16.safetensors",
204
+ ]
205
+ self.assertFalse(is_safetensors_compatible(filenames))
206
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
207
+
208
+ def test_diffusers_is_compatible_no_components(self):
209
+ filenames = [
210
+ "diffusion_pytorch_model.bin",
211
+ ]
212
+ self.assertFalse(is_safetensors_compatible(filenames))
213
+
214
+ def test_diffusers_is_compatible_no_components_only_variants(self):
215
+ filenames = [
216
+ "diffusion_pytorch_model.fp16.bin",
217
+ ]
218
+ self.assertFalse(is_safetensors_compatible(filenames))
219
+
220
+ def test_is_compatible_mixed_variants(self):
221
+ filenames = [
222
+ "unet/diffusion_pytorch_model.fp16.safetensors",
223
+ "vae/diffusion_pytorch_model.safetensors",
224
+ ]
225
+ self.assertTrue(is_safetensors_compatible(filenames, variant="fp16"))
226
+
227
+ def test_is_compatible_variant_and_non_safetensors(self):
228
+ filenames = [
229
+ "unet/diffusion_pytorch_model.fp16.safetensors",
230
+ "vae/diffusion_pytorch_model.bin",
231
+ ]
232
+ self.assertFalse(is_safetensors_compatible(filenames, variant="fp16"))
233
+
234
+
235
+ class VariantCompatibleSiblingsTest(unittest.TestCase):
236
+ def test_only_non_variants_downloaded(self):
237
+ ignore_patterns = ["*.bin"]
238
+ variant = "fp16"
239
+ filenames = [
240
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
241
+ "vae/diffusion_pytorch_model.safetensors",
242
+ f"text_encoder/model.{variant}.safetensors",
243
+ "text_encoder/model.safetensors",
244
+ f"unet/diffusion_pytorch_model.{variant}.safetensors",
245
+ "unet/diffusion_pytorch_model.safetensors",
246
+ ]
247
+
248
+ model_filenames, variant_filenames = variant_compatible_siblings(
249
+ filenames, variant=None, ignore_patterns=ignore_patterns
250
+ )
251
+ assert all(variant not in f for f in model_filenames)
252
+
253
+ def test_only_variants_downloaded(self):
254
+ ignore_patterns = ["*.bin"]
255
+ variant = "fp16"
256
+ filenames = [
257
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
258
+ "vae/diffusion_pytorch_model.safetensors",
259
+ f"text_encoder/model.{variant}.safetensors",
260
+ "text_encoder/model.safetensors",
261
+ f"unet/diffusion_pytorch_model.{variant}.safetensors",
262
+ "unet/diffusion_pytorch_model.safetensors",
263
+ ]
264
+
265
+ model_filenames, variant_filenames = variant_compatible_siblings(
266
+ filenames, variant=variant, ignore_patterns=ignore_patterns
267
+ )
268
+ assert all(variant in f for f in model_filenames)
269
+
270
+ def test_mixed_variants_downloaded(self):
271
+ ignore_patterns = ["*.bin"]
272
+ variant = "fp16"
273
+ non_variant_file = "text_encoder/model.safetensors"
274
+ filenames = [
275
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
276
+ "vae/diffusion_pytorch_model.safetensors",
277
+ "text_encoder/model.safetensors",
278
+ f"unet/diffusion_pytorch_model.{variant}.safetensors",
279
+ "unet/diffusion_pytorch_model.safetensors",
280
+ ]
281
+ model_filenames, variant_filenames = variant_compatible_siblings(
282
+ filenames, variant=variant, ignore_patterns=ignore_patterns
283
+ )
284
+ assert all(variant in f if f != non_variant_file else variant not in f for f in model_filenames)
285
+
286
+ def test_non_variants_in_main_dir_downloaded(self):
287
+ ignore_patterns = ["*.bin"]
288
+ variant = "fp16"
289
+ filenames = [
290
+ f"diffusion_pytorch_model.{variant}.safetensors",
291
+ "diffusion_pytorch_model.safetensors",
292
+ "model.safetensors",
293
+ f"model.{variant}.safetensors",
294
+ ]
295
+ model_filenames, variant_filenames = variant_compatible_siblings(
296
+ filenames, variant=None, ignore_patterns=ignore_patterns
297
+ )
298
+ assert all(variant not in f for f in model_filenames)
299
+
300
+ def test_variants_in_main_dir_downloaded(self):
301
+ ignore_patterns = ["*.bin"]
302
+ variant = "fp16"
303
+ filenames = [
304
+ f"diffusion_pytorch_model.{variant}.safetensors",
305
+ "diffusion_pytorch_model.safetensors",
306
+ "model.safetensors",
307
+ f"model.{variant}.safetensors",
308
+ f"diffusion_pytorch_model.{variant}.safetensors",
309
+ "diffusion_pytorch_model.safetensors",
310
+ ]
311
+ model_filenames, variant_filenames = variant_compatible_siblings(
312
+ filenames, variant=variant, ignore_patterns=ignore_patterns
313
+ )
314
+ assert all(variant in f for f in model_filenames)
315
+
316
+ def test_mixed_variants_in_main_dir_downloaded(self):
317
+ ignore_patterns = ["*.bin"]
318
+ variant = "fp16"
319
+ non_variant_file = "model.safetensors"
320
+ filenames = [
321
+ f"diffusion_pytorch_model.{variant}.safetensors",
322
+ "diffusion_pytorch_model.safetensors",
323
+ "model.safetensors",
324
+ ]
325
+ model_filenames, variant_filenames = variant_compatible_siblings(
326
+ filenames, variant=variant, ignore_patterns=ignore_patterns
327
+ )
328
+ assert all(variant in f if f != non_variant_file else variant not in f for f in model_filenames)
329
+
330
+ def test_sharded_variants_in_main_dir_downloaded(self):
331
+ ignore_patterns = ["*.bin"]
332
+ variant = "fp16"
333
+ filenames = [
334
+ "diffusion_pytorch_model.safetensors.index.json",
335
+ "diffusion_pytorch_model-00001-of-00003.safetensors",
336
+ "diffusion_pytorch_model-00002-of-00003.safetensors",
337
+ "diffusion_pytorch_model-00003-of-00003.safetensors",
338
+ f"diffusion_pytorch_model.{variant}-00001-of-00002.safetensors",
339
+ f"diffusion_pytorch_model.{variant}-00002-of-00002.safetensors",
340
+ f"diffusion_pytorch_model.safetensors.index.{variant}.json",
341
+ ]
342
+ model_filenames, variant_filenames = variant_compatible_siblings(
343
+ filenames, variant=variant, ignore_patterns=ignore_patterns
344
+ )
345
+ assert all(variant in f for f in model_filenames)
346
+
347
+ def test_mixed_sharded_and_variant_in_main_dir_downloaded(self):
348
+ ignore_patterns = ["*.bin"]
349
+ variant = "fp16"
350
+ filenames = [
351
+ "diffusion_pytorch_model.safetensors.index.json",
352
+ "diffusion_pytorch_model-00001-of-00003.safetensors",
353
+ "diffusion_pytorch_model-00002-of-00003.safetensors",
354
+ "diffusion_pytorch_model-00003-of-00003.safetensors",
355
+ f"diffusion_pytorch_model.{variant}.safetensors",
356
+ ]
357
+ model_filenames, variant_filenames = variant_compatible_siblings(
358
+ filenames, variant=variant, ignore_patterns=ignore_patterns
359
+ )
360
+ assert all(variant in f for f in model_filenames)
361
+
362
+ def test_mixed_sharded_non_variants_in_main_dir_downloaded(self):
363
+ ignore_patterns = ["*.bin"]
364
+ variant = "fp16"
365
+ filenames = [
366
+ f"diffusion_pytorch_model.safetensors.index.{variant}.json",
367
+ "diffusion_pytorch_model.safetensors.index.json",
368
+ "diffusion_pytorch_model-00001-of-00003.safetensors",
369
+ "diffusion_pytorch_model-00002-of-00003.safetensors",
370
+ "diffusion_pytorch_model-00003-of-00003.safetensors",
371
+ f"diffusion_pytorch_model.{variant}-00001-of-00002.safetensors",
372
+ f"diffusion_pytorch_model.{variant}-00002-of-00002.safetensors",
373
+ ]
374
+ model_filenames, variant_filenames = variant_compatible_siblings(
375
+ filenames, variant=None, ignore_patterns=ignore_patterns
376
+ )
377
+ assert all(variant not in f for f in model_filenames)
378
+
379
+ def test_sharded_non_variants_downloaded(self):
380
+ ignore_patterns = ["*.bin"]
381
+ variant = "fp16"
382
+ filenames = [
383
+ f"unet/diffusion_pytorch_model.safetensors.index.{variant}.json",
384
+ "unet/diffusion_pytorch_model.safetensors.index.json",
385
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
386
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
387
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
388
+ f"unet/diffusion_pytorch_model.{variant}-00001-of-00002.safetensors",
389
+ f"unet/diffusion_pytorch_model.{variant}-00002-of-00002.safetensors",
390
+ ]
391
+ model_filenames, variant_filenames = variant_compatible_siblings(
392
+ filenames, variant=None, ignore_patterns=ignore_patterns
393
+ )
394
+ assert all(variant not in f for f in model_filenames)
395
+
396
+ def test_sharded_variants_downloaded(self):
397
+ ignore_patterns = ["*.bin"]
398
+ variant = "fp16"
399
+ filenames = [
400
+ f"unet/diffusion_pytorch_model.safetensors.index.{variant}.json",
401
+ "unet/diffusion_pytorch_model.safetensors.index.json",
402
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
403
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
404
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
405
+ f"unet/diffusion_pytorch_model.{variant}-00001-of-00002.safetensors",
406
+ f"unet/diffusion_pytorch_model.{variant}-00002-of-00002.safetensors",
407
+ ]
408
+ model_filenames, variant_filenames = variant_compatible_siblings(
409
+ filenames, variant=variant, ignore_patterns=ignore_patterns
410
+ )
411
+ assert all(variant in f for f in model_filenames)
412
+ assert model_filenames == variant_filenames
413
+
414
+ def test_single_variant_with_sharded_non_variant_downloaded(self):
415
+ ignore_patterns = ["*.bin"]
416
+ variant = "fp16"
417
+ filenames = [
418
+ "unet/diffusion_pytorch_model.safetensors.index.json",
419
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
420
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
421
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
422
+ f"unet/diffusion_pytorch_model.{variant}.safetensors",
423
+ ]
424
+ model_filenames, variant_filenames = variant_compatible_siblings(
425
+ filenames, variant=variant, ignore_patterns=ignore_patterns
426
+ )
427
+ assert all(variant in f for f in model_filenames)
428
+
429
+ def test_mixed_single_variant_with_sharded_non_variant_downloaded(self):
430
+ ignore_patterns = ["*.bin"]
431
+ variant = "fp16"
432
+ allowed_non_variant = "unet"
433
+ filenames = [
434
+ "vae/diffusion_pytorch_model.safetensors.index.json",
435
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
436
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
437
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
438
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
439
+ "unet/diffusion_pytorch_model.safetensors.index.json",
440
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
441
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
442
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
443
+ ]
444
+ model_filenames, variant_filenames = variant_compatible_siblings(
445
+ filenames, variant=variant, ignore_patterns=ignore_patterns
446
+ )
447
+ assert all(variant in f if allowed_non_variant not in f else variant not in f for f in model_filenames)
448
+
449
+ def test_sharded_mixed_variants_downloaded(self):
450
+ ignore_patterns = ["*.bin"]
451
+ variant = "fp16"
452
+ allowed_non_variant = "unet"
453
+ filenames = [
454
+ f"vae/diffusion_pytorch_model.safetensors.index.{variant}.json",
455
+ "vae/diffusion_pytorch_model.safetensors.index.json",
456
+ "unet/diffusion_pytorch_model.safetensors.index.json",
457
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
458
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
459
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
460
+ f"vae/diffusion_pytorch_model.{variant}-00001-of-00002.safetensors",
461
+ f"vae/diffusion_pytorch_model.{variant}-00002-of-00002.safetensors",
462
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
463
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
464
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
465
+ ]
466
+ model_filenames, variant_filenames = variant_compatible_siblings(
467
+ filenames, variant=variant, ignore_patterns=ignore_patterns
468
+ )
469
+ assert all(variant in f if allowed_non_variant not in f else variant not in f for f in model_filenames)
470
+
471
+ def test_downloading_when_no_variant_exists(self):
472
+ ignore_patterns = ["*.bin"]
473
+ variant = "fp16"
474
+ filenames = ["model.safetensors", "diffusion_pytorch_model.safetensors"]
475
+ with self.assertRaisesRegex(ValueError, "but no such modeling files are available. "):
476
+ model_filenames, variant_filenames = variant_compatible_siblings(
477
+ filenames, variant=variant, ignore_patterns=ignore_patterns
478
+ )
479
+
480
+ def test_downloading_use_safetensors_false(self):
481
+ ignore_patterns = ["*.safetensors"]
482
+ filenames = [
483
+ "text_encoder/model.bin",
484
+ "unet/diffusion_pytorch_model.bin",
485
+ "unet/diffusion_pytorch_model.safetensors",
486
+ ]
487
+ model_filenames, variant_filenames = variant_compatible_siblings(
488
+ filenames, variant=None, ignore_patterns=ignore_patterns
489
+ )
490
+
491
+ assert all(".safetensors" not in f for f in model_filenames)
492
+
493
+ def test_non_variant_in_main_dir_with_variant_in_subfolder(self):
494
+ ignore_patterns = ["*.bin"]
495
+ variant = "fp16"
496
+ allowed_non_variant = "diffusion_pytorch_model.safetensors"
497
+ filenames = [
498
+ f"unet/diffusion_pytorch_model.{variant}.safetensors",
499
+ "diffusion_pytorch_model.safetensors",
500
+ ]
501
+ model_filenames, variant_filenames = variant_compatible_siblings(
502
+ filenames, variant=variant, ignore_patterns=ignore_patterns
503
+ )
504
+ assert all(variant in f if allowed_non_variant not in f else variant not in f for f in model_filenames)
505
+
506
+ def test_download_variants_when_component_has_no_safetensors_variant(self):
507
+ ignore_patterns = None
508
+ variant = "fp16"
509
+ filenames = [
510
+ f"unet/diffusion_pytorch_model.{variant}.bin",
511
+ "vae/diffusion_pytorch_model.safetensors",
512
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
513
+ ]
514
+ model_filenames, variant_filenames = variant_compatible_siblings(
515
+ filenames, variant=variant, ignore_patterns=ignore_patterns
516
+ )
517
+ assert {
518
+ f"unet/diffusion_pytorch_model.{variant}.bin",
519
+ f"vae/diffusion_pytorch_model.{variant}.safetensors",
520
+ } == model_filenames
521
+
522
+ def test_error_when_download_sharded_variants_when_component_has_no_safetensors_variant(self):
523
+ ignore_patterns = ["*.bin"]
524
+ variant = "fp16"
525
+ filenames = [
526
+ f"vae/diffusion_pytorch_model.bin.index.{variant}.json",
527
+ "vae/diffusion_pytorch_model.safetensors.index.json",
528
+ f"vae/diffusion_pytorch_model.{variant}-00002-of-00002.bin",
529
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
530
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
531
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
532
+ "unet/diffusion_pytorch_model.safetensors.index.json",
533
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
534
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
535
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
536
+ f"vae/diffusion_pytorch_model.{variant}-00001-of-00002.bin",
537
+ ]
538
+ with self.assertRaisesRegex(ValueError, "but no such modeling files are available. "):
539
+ model_filenames, variant_filenames = variant_compatible_siblings(
540
+ filenames, variant=variant, ignore_patterns=ignore_patterns
541
+ )
542
+
543
+ def test_download_sharded_variants_when_component_has_no_safetensors_variant_and_safetensors_false(self):
544
+ ignore_patterns = ["*.safetensors"]
545
+ allowed_non_variant = "unet"
546
+ variant = "fp16"
547
+ filenames = [
548
+ f"vae/diffusion_pytorch_model.bin.index.{variant}.json",
549
+ "vae/diffusion_pytorch_model.safetensors.index.json",
550
+ f"vae/diffusion_pytorch_model.{variant}-00002-of-00002.bin",
551
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
552
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
553
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
554
+ "unet/diffusion_pytorch_model.safetensors.index.json",
555
+ "unet/diffusion_pytorch_model-00001-of-00003.safetensors",
556
+ "unet/diffusion_pytorch_model-00002-of-00003.safetensors",
557
+ "unet/diffusion_pytorch_model-00003-of-00003.safetensors",
558
+ f"vae/diffusion_pytorch_model.{variant}-00001-of-00002.bin",
559
+ ]
560
+ model_filenames, variant_filenames = variant_compatible_siblings(
561
+ filenames, variant=variant, ignore_patterns=ignore_patterns
562
+ )
563
+ assert all(variant in f if allowed_non_variant not in f else variant not in f for f in model_filenames)
564
+
565
+ def test_download_sharded_legacy_variants(self):
566
+ ignore_patterns = None
567
+ variant = "fp16"
568
+ filenames = [
569
+ f"vae/transformer/diffusion_pytorch_model.safetensors.{variant}.index.json",
570
+ "vae/diffusion_pytorch_model.safetensors.index.json",
571
+ f"vae/diffusion_pytorch_model-00002-of-00002.{variant}.safetensors",
572
+ "vae/diffusion_pytorch_model-00001-of-00003.safetensors",
573
+ "vae/diffusion_pytorch_model-00002-of-00003.safetensors",
574
+ "vae/diffusion_pytorch_model-00003-of-00003.safetensors",
575
+ f"vae/diffusion_pytorch_model-00001-of-00002.{variant}.safetensors",
576
+ ]
577
+ model_filenames, variant_filenames = variant_compatible_siblings(
578
+ filenames, variant=variant, ignore_patterns=ignore_patterns
579
+ )
580
+ assert all(variant in f for f in model_filenames)
581
+
582
+ def test_download_onnx_models(self):
583
+ ignore_patterns = ["*.safetensors"]
584
+ filenames = [
585
+ "vae/model.onnx",
586
+ "unet/model.onnx",
587
+ ]
588
+ model_filenames, variant_filenames = variant_compatible_siblings(
589
+ filenames, variant=None, ignore_patterns=ignore_patterns
590
+ )
591
+ assert model_filenames == set(filenames)
592
+
593
+ def test_download_flax_models(self):
594
+ ignore_patterns = ["*.safetensors", "*.bin"]
595
+ filenames = [
596
+ "vae/diffusion_flax_model.msgpack",
597
+ "unet/diffusion_flax_model.msgpack",
598
+ ]
599
+ model_filenames, variant_filenames = variant_compatible_siblings(
600
+ filenames, variant=None, ignore_patterns=ignore_patterns
601
+ )
602
+ assert model_filenames == set(filenames)
603
+
604
+
605
+ class ProgressBarTests(unittest.TestCase):
606
+ def get_dummy_components_image_generation(self):
607
+ cross_attention_dim = 8
608
+
609
+ torch.manual_seed(0)
610
+ unet = UNet2DConditionModel(
611
+ block_out_channels=(4, 8),
612
+ layers_per_block=1,
613
+ sample_size=32,
614
+ in_channels=4,
615
+ out_channels=4,
616
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
617
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
618
+ cross_attention_dim=cross_attention_dim,
619
+ norm_num_groups=2,
620
+ )
621
+ scheduler = DDIMScheduler(
622
+ beta_start=0.00085,
623
+ beta_end=0.012,
624
+ beta_schedule="scaled_linear",
625
+ clip_sample=False,
626
+ set_alpha_to_one=False,
627
+ )
628
+ torch.manual_seed(0)
629
+ vae = AutoencoderKL(
630
+ block_out_channels=[4, 8],
631
+ in_channels=3,
632
+ out_channels=3,
633
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
634
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
635
+ latent_channels=4,
636
+ norm_num_groups=2,
637
+ )
638
+ torch.manual_seed(0)
639
+ text_encoder_config = CLIPTextConfig(
640
+ bos_token_id=0,
641
+ eos_token_id=2,
642
+ hidden_size=cross_attention_dim,
643
+ intermediate_size=16,
644
+ layer_norm_eps=1e-05,
645
+ num_attention_heads=2,
646
+ num_hidden_layers=2,
647
+ pad_token_id=1,
648
+ vocab_size=1000,
649
+ )
650
+ text_encoder = CLIPTextModel(text_encoder_config)
651
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
652
+
653
+ components = {
654
+ "unet": unet,
655
+ "scheduler": scheduler,
656
+ "vae": vae,
657
+ "text_encoder": text_encoder,
658
+ "tokenizer": tokenizer,
659
+ "safety_checker": None,
660
+ "feature_extractor": None,
661
+ "image_encoder": None,
662
+ }
663
+ return components
664
+
665
+ def get_dummy_components_video_generation(self):
666
+ cross_attention_dim = 8
667
+ block_out_channels = (8, 8)
668
+
669
+ torch.manual_seed(0)
670
+ unet = UNet2DConditionModel(
671
+ block_out_channels=block_out_channels,
672
+ layers_per_block=2,
673
+ sample_size=8,
674
+ in_channels=4,
675
+ out_channels=4,
676
+ down_block_types=("CrossAttnDownBlock2D", "DownBlock2D"),
677
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
678
+ cross_attention_dim=cross_attention_dim,
679
+ norm_num_groups=2,
680
+ )
681
+ scheduler = DDIMScheduler(
682
+ beta_start=0.00085,
683
+ beta_end=0.012,
684
+ beta_schedule="linear",
685
+ clip_sample=False,
686
+ )
687
+ torch.manual_seed(0)
688
+ vae = AutoencoderKL(
689
+ block_out_channels=block_out_channels,
690
+ in_channels=3,
691
+ out_channels=3,
692
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
693
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
694
+ latent_channels=4,
695
+ norm_num_groups=2,
696
+ )
697
+ torch.manual_seed(0)
698
+ text_encoder_config = CLIPTextConfig(
699
+ bos_token_id=0,
700
+ eos_token_id=2,
701
+ hidden_size=cross_attention_dim,
702
+ intermediate_size=37,
703
+ layer_norm_eps=1e-05,
704
+ num_attention_heads=4,
705
+ num_hidden_layers=5,
706
+ pad_token_id=1,
707
+ vocab_size=1000,
708
+ )
709
+ text_encoder = CLIPTextModel(text_encoder_config)
710
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
711
+ torch.manual_seed(0)
712
+ motion_adapter = MotionAdapter(
713
+ block_out_channels=block_out_channels,
714
+ motion_layers_per_block=2,
715
+ motion_norm_num_groups=2,
716
+ motion_num_attention_heads=4,
717
+ )
718
+
719
+ components = {
720
+ "unet": unet,
721
+ "scheduler": scheduler,
722
+ "vae": vae,
723
+ "motion_adapter": motion_adapter,
724
+ "text_encoder": text_encoder,
725
+ "tokenizer": tokenizer,
726
+ "feature_extractor": None,
727
+ "image_encoder": None,
728
+ }
729
+ return components
730
+
731
+ def test_text_to_image(self):
732
+ components = self.get_dummy_components_image_generation()
733
+ pipe = StableDiffusionPipeline(**components)
734
+ pipe.to(torch_device)
735
+
736
+ inputs = {"prompt": "a cute cat", "num_inference_steps": 2}
737
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
738
+ _ = pipe(**inputs)
739
+ stderr = stderr.getvalue()
740
+ # we can't calculate the number of progress steps beforehand e.g. for strength-dependent img2img,
741
+ # so we just match "5" in "#####| 1/5 [00:01<00:00]"
742
+ max_steps = re.search("/(.*?) ", stderr).group(1)
743
+ self.assertTrue(max_steps is not None and len(max_steps) > 0)
744
+ self.assertTrue(
745
+ f"{max_steps}/{max_steps}" in stderr, "Progress bar should be enabled and stopped at the max step"
746
+ )
747
+
748
+ pipe.set_progress_bar_config(disable=True)
749
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
750
+ _ = pipe(**inputs)
751
+ self.assertTrue(stderr.getvalue() == "", "Progress bar should be disabled")
752
+
753
+ def test_image_to_image(self):
754
+ components = self.get_dummy_components_image_generation()
755
+ pipe = StableDiffusionImg2ImgPipeline(**components)
756
+ pipe.to(torch_device)
757
+
758
+ image = Image.new("RGB", (32, 32))
759
+ inputs = {"prompt": "a cute cat", "num_inference_steps": 2, "strength": 0.5, "image": image}
760
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
761
+ _ = pipe(**inputs)
762
+ stderr = stderr.getvalue()
763
+ # we can't calculate the number of progress steps beforehand e.g. for strength-dependent img2img,
764
+ # so we just match "5" in "#####| 1/5 [00:01<00:00]"
765
+ max_steps = re.search("/(.*?) ", stderr).group(1)
766
+ self.assertTrue(max_steps is not None and len(max_steps) > 0)
767
+ self.assertTrue(
768
+ f"{max_steps}/{max_steps}" in stderr, "Progress bar should be enabled and stopped at the max step"
769
+ )
770
+
771
+ pipe.set_progress_bar_config(disable=True)
772
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
773
+ _ = pipe(**inputs)
774
+ self.assertTrue(stderr.getvalue() == "", "Progress bar should be disabled")
775
+
776
+ def test_inpainting(self):
777
+ components = self.get_dummy_components_image_generation()
778
+ pipe = StableDiffusionInpaintPipeline(**components)
779
+ pipe.to(torch_device)
780
+
781
+ image = Image.new("RGB", (32, 32))
782
+ mask = Image.new("RGB", (32, 32))
783
+ inputs = {
784
+ "prompt": "a cute cat",
785
+ "num_inference_steps": 2,
786
+ "strength": 0.5,
787
+ "image": image,
788
+ "mask_image": mask,
789
+ }
790
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
791
+ _ = pipe(**inputs)
792
+ stderr = stderr.getvalue()
793
+ # we can't calculate the number of progress steps beforehand e.g. for strength-dependent img2img,
794
+ # so we just match "5" in "#####| 1/5 [00:01<00:00]"
795
+ max_steps = re.search("/(.*?) ", stderr).group(1)
796
+ self.assertTrue(max_steps is not None and len(max_steps) > 0)
797
+ self.assertTrue(
798
+ f"{max_steps}/{max_steps}" in stderr, "Progress bar should be enabled and stopped at the max step"
799
+ )
800
+
801
+ pipe.set_progress_bar_config(disable=True)
802
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
803
+ _ = pipe(**inputs)
804
+ self.assertTrue(stderr.getvalue() == "", "Progress bar should be disabled")
805
+
806
+ def test_text_to_video(self):
807
+ components = self.get_dummy_components_video_generation()
808
+ pipe = AnimateDiffPipeline(**components)
809
+ pipe.to(torch_device)
810
+
811
+ inputs = {"prompt": "a cute cat", "num_inference_steps": 2, "num_frames": 2}
812
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
813
+ _ = pipe(**inputs)
814
+ stderr = stderr.getvalue()
815
+ # we can't calculate the number of progress steps beforehand e.g. for strength-dependent img2img,
816
+ # so we just match "5" in "#####| 1/5 [00:01<00:00]"
817
+ max_steps = re.search("/(.*?) ", stderr).group(1)
818
+ self.assertTrue(max_steps is not None and len(max_steps) > 0)
819
+ self.assertTrue(
820
+ f"{max_steps}/{max_steps}" in stderr, "Progress bar should be enabled and stopped at the max step"
821
+ )
822
+
823
+ pipe.set_progress_bar_config(disable=True)
824
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
825
+ _ = pipe(**inputs)
826
+ self.assertTrue(stderr.getvalue() == "", "Progress bar should be disabled")
827
+
828
+ def test_video_to_video(self):
829
+ components = self.get_dummy_components_video_generation()
830
+ pipe = AnimateDiffVideoToVideoPipeline(**components)
831
+ pipe.to(torch_device)
832
+
833
+ num_frames = 2
834
+ video = [Image.new("RGB", (32, 32))] * num_frames
835
+ inputs = {"prompt": "a cute cat", "num_inference_steps": 2, "video": video}
836
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
837
+ _ = pipe(**inputs)
838
+ stderr = stderr.getvalue()
839
+ # we can't calculate the number of progress steps beforehand e.g. for strength-dependent img2img,
840
+ # so we just match "5" in "#####| 1/5 [00:01<00:00]"
841
+ max_steps = re.search("/(.*?) ", stderr).group(1)
842
+ self.assertTrue(max_steps is not None and len(max_steps) > 0)
843
+ self.assertTrue(
844
+ f"{max_steps}/{max_steps}" in stderr, "Progress bar should be enabled and stopped at the max step"
845
+ )
846
+
847
+ pipe.set_progress_bar_config(disable=True)
848
+ with io.StringIO() as stderr, contextlib.redirect_stderr(stderr):
849
+ _ = pipe(**inputs)
850
+ self.assertTrue(stderr.getvalue() == "", "Progress bar should be disabled")
851
+
852
+
853
+ @require_torch_gpu
854
+ class PipelineDeviceAndDtypeStabilityTests(unittest.TestCase):
855
+ expected_pipe_device = torch.device("cuda:0")
856
+ expected_pipe_dtype = torch.float64
857
+
858
+ def get_dummy_components_image_generation(self):
859
+ cross_attention_dim = 8
860
+
861
+ torch.manual_seed(0)
862
+ unet = UNet2DConditionModel(
863
+ block_out_channels=(4, 8),
864
+ layers_per_block=1,
865
+ sample_size=32,
866
+ in_channels=4,
867
+ out_channels=4,
868
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
869
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
870
+ cross_attention_dim=cross_attention_dim,
871
+ norm_num_groups=2,
872
+ )
873
+ scheduler = DDIMScheduler(
874
+ beta_start=0.00085,
875
+ beta_end=0.012,
876
+ beta_schedule="scaled_linear",
877
+ clip_sample=False,
878
+ set_alpha_to_one=False,
879
+ )
880
+ torch.manual_seed(0)
881
+ vae = AutoencoderKL(
882
+ block_out_channels=[4, 8],
883
+ in_channels=3,
884
+ out_channels=3,
885
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
886
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
887
+ latent_channels=4,
888
+ norm_num_groups=2,
889
+ )
890
+ torch.manual_seed(0)
891
+ text_encoder_config = CLIPTextConfig(
892
+ bos_token_id=0,
893
+ eos_token_id=2,
894
+ hidden_size=cross_attention_dim,
895
+ intermediate_size=16,
896
+ layer_norm_eps=1e-05,
897
+ num_attention_heads=2,
898
+ num_hidden_layers=2,
899
+ pad_token_id=1,
900
+ vocab_size=1000,
901
+ )
902
+ text_encoder = CLIPTextModel(text_encoder_config)
903
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
904
+
905
+ components = {
906
+ "unet": unet,
907
+ "scheduler": scheduler,
908
+ "vae": vae,
909
+ "text_encoder": text_encoder,
910
+ "tokenizer": tokenizer,
911
+ "safety_checker": None,
912
+ "feature_extractor": None,
913
+ "image_encoder": None,
914
+ }
915
+ return components
916
+
917
+ def test_deterministic_device(self):
918
+ components = self.get_dummy_components_image_generation()
919
+
920
+ pipe = StableDiffusionPipeline(**components)
921
+ pipe.to(device=torch_device, dtype=torch.float32)
922
+
923
+ pipe.unet.to(device="cpu")
924
+ pipe.vae.to(device="cuda")
925
+ pipe.text_encoder.to(device="cuda:0")
926
+
927
+ pipe_device = pipe.device
928
+
929
+ self.assertEqual(
930
+ self.expected_pipe_device,
931
+ pipe_device,
932
+ f"Wrong expected device. Expected {self.expected_pipe_device}. Got {pipe_device}.",
933
+ )
934
+
935
+ def test_deterministic_dtype(self):
936
+ components = self.get_dummy_components_image_generation()
937
+
938
+ pipe = StableDiffusionPipeline(**components)
939
+ pipe.to(device=torch_device, dtype=torch.float32)
940
+
941
+ pipe.unet.to(dtype=torch.float16)
942
+ pipe.vae.to(dtype=torch.float32)
943
+ pipe.text_encoder.to(dtype=torch.float64)
944
+
945
+ pipe_dtype = pipe.dtype
946
+
947
+ self.assertEqual(
948
+ self.expected_pipe_dtype,
949
+ pipe_dtype,
950
+ f"Wrong expected dtype. Expected {self.expected_pipe_dtype}. Got {pipe_dtype}.",
951
+ )
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_auto.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 os
18
+ import shutil
19
+ import unittest
20
+ from collections import OrderedDict
21
+ from pathlib import Path
22
+
23
+ import torch
24
+ from transformers import CLIPVisionConfig, CLIPVisionModelWithProjection
25
+
26
+ from diffusers import (
27
+ AutoPipelineForImage2Image,
28
+ AutoPipelineForInpainting,
29
+ AutoPipelineForText2Image,
30
+ ControlNetModel,
31
+ DiffusionPipeline,
32
+ )
33
+ from diffusers.pipelines.auto_pipeline import (
34
+ AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
35
+ AUTO_INPAINT_PIPELINES_MAPPING,
36
+ AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
37
+ )
38
+ from diffusers.utils.testing_utils import slow
39
+
40
+
41
+ PRETRAINED_MODEL_REPO_MAPPING = OrderedDict(
42
+ [
43
+ ("stable-diffusion", "stable-diffusion-v1-5/stable-diffusion-v1-5"),
44
+ ("if", "DeepFloyd/IF-I-XL-v1.0"),
45
+ ("kandinsky", "kandinsky-community/kandinsky-2-1"),
46
+ ("kandinsky22", "kandinsky-community/kandinsky-2-2-decoder"),
47
+ ]
48
+ )
49
+
50
+
51
+ class AutoPipelineFastTest(unittest.TestCase):
52
+ @property
53
+ def dummy_image_encoder(self):
54
+ torch.manual_seed(0)
55
+ config = CLIPVisionConfig(
56
+ hidden_size=1,
57
+ projection_dim=1,
58
+ num_hidden_layers=1,
59
+ num_attention_heads=1,
60
+ image_size=1,
61
+ intermediate_size=1,
62
+ patch_size=1,
63
+ )
64
+ return CLIPVisionModelWithProjection(config)
65
+
66
+ def test_from_pipe_consistent(self):
67
+ pipe = AutoPipelineForText2Image.from_pretrained(
68
+ "hf-internal-testing/tiny-stable-diffusion-pipe", requires_safety_checker=False
69
+ )
70
+ original_config = dict(pipe.config)
71
+
72
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe)
73
+ assert dict(pipe.config) == original_config
74
+
75
+ pipe = AutoPipelineForText2Image.from_pipe(pipe)
76
+ assert dict(pipe.config) == original_config
77
+
78
+ def test_from_pipe_override(self):
79
+ pipe = AutoPipelineForText2Image.from_pretrained(
80
+ "hf-internal-testing/tiny-stable-diffusion-pipe", requires_safety_checker=False
81
+ )
82
+
83
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe, requires_safety_checker=True)
84
+ assert pipe.config.requires_safety_checker is True
85
+
86
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, requires_safety_checker=True)
87
+ assert pipe.config.requires_safety_checker is True
88
+
89
+ def test_from_pipe_consistent_sdxl(self):
90
+ pipe = AutoPipelineForImage2Image.from_pretrained(
91
+ "hf-internal-testing/tiny-stable-diffusion-xl-pipe",
92
+ requires_aesthetics_score=True,
93
+ force_zeros_for_empty_prompt=False,
94
+ )
95
+
96
+ original_config = dict(pipe.config)
97
+
98
+ pipe = AutoPipelineForText2Image.from_pipe(pipe)
99
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe)
100
+
101
+ assert dict(pipe.config) == original_config
102
+
103
+ def test_kwargs_local_files_only(self):
104
+ repo = "hf-internal-testing/tiny-stable-diffusion-torch"
105
+ tmpdirname = DiffusionPipeline.download(repo)
106
+ tmpdirname = Path(tmpdirname)
107
+
108
+ # edit commit_id to so that it's not the latest commit
109
+ commit_id = tmpdirname.name
110
+ new_commit_id = commit_id + "hug"
111
+
112
+ ref_dir = tmpdirname.parent.parent / "refs/main"
113
+ with open(ref_dir, "w") as f:
114
+ f.write(new_commit_id)
115
+
116
+ new_tmpdirname = tmpdirname.parent / new_commit_id
117
+ os.rename(tmpdirname, new_tmpdirname)
118
+
119
+ try:
120
+ AutoPipelineForText2Image.from_pretrained(repo, local_files_only=True)
121
+ except OSError:
122
+ assert False, "not able to load local files"
123
+
124
+ shutil.rmtree(tmpdirname.parent.parent)
125
+
126
+ def test_from_pretrained_text2img(self):
127
+ repo = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
128
+ pipe = AutoPipelineForText2Image.from_pretrained(repo)
129
+ assert pipe.__class__.__name__ == "StableDiffusionXLPipeline"
130
+
131
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
132
+ pipe_control = AutoPipelineForText2Image.from_pretrained(repo, controlnet=controlnet)
133
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
134
+
135
+ pipe_pag = AutoPipelineForText2Image.from_pretrained(repo, enable_pag=True)
136
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGPipeline"
137
+
138
+ pipe_control_pag = AutoPipelineForText2Image.from_pretrained(repo, controlnet=controlnet, enable_pag=True)
139
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
140
+
141
+ def test_from_pipe_pag_text2img(self):
142
+ # test from StableDiffusionXLPipeline
143
+ pipe = AutoPipelineForText2Image.from_pretrained("hf-internal-testing/tiny-stable-diffusion-xl-pipe")
144
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
145
+
146
+ # - test `enable_pag` flag
147
+ pipe_pag = AutoPipelineForText2Image.from_pipe(pipe, enable_pag=True)
148
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGPipeline"
149
+ assert "controlnet" not in pipe_pag.components
150
+
151
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, enable_pag=False)
152
+ assert pipe.__class__.__name__ == "StableDiffusionXLPipeline"
153
+ assert "controlnet" not in pipe.components
154
+
155
+ # - test `enabe_pag` + `controlnet` flag
156
+ pipe_control_pag = AutoPipelineForText2Image.from_pipe(pipe, controlnet=controlnet, enable_pag=True)
157
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
158
+ assert "controlnet" in pipe_control_pag.components
159
+
160
+ pipe_control = AutoPipelineForText2Image.from_pipe(pipe, controlnet=controlnet, enable_pag=False)
161
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
162
+ assert "controlnet" in pipe_control.components
163
+
164
+ pipe_pag = AutoPipelineForText2Image.from_pipe(pipe, controlnet=None, enable_pag=True)
165
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGPipeline"
166
+ assert "controlnet" not in pipe_pag.components
167
+
168
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, controlnet=None, enable_pag=False)
169
+ assert pipe.__class__.__name__ == "StableDiffusionXLPipeline"
170
+ assert "controlnet" not in pipe.components
171
+
172
+ # test from StableDiffusionXLControlNetPipeline
173
+ # - test `enable_pag` flag
174
+ pipe_control_pag = AutoPipelineForText2Image.from_pipe(pipe_control, enable_pag=True)
175
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
176
+ assert "controlnet" in pipe_control_pag.components
177
+
178
+ pipe_control = AutoPipelineForText2Image.from_pipe(pipe_control, enable_pag=False)
179
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
180
+ assert "controlnet" in pipe_control.components
181
+
182
+ # - test `enable_pag` + `controlnet` flag
183
+ pipe_control_pag = AutoPipelineForText2Image.from_pipe(pipe_control, controlnet=controlnet, enable_pag=True)
184
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
185
+ assert "controlnet" in pipe_control_pag.components
186
+
187
+ pipe_control = AutoPipelineForText2Image.from_pipe(pipe_control, controlnet=controlnet, enable_pag=False)
188
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
189
+ assert "controlnet" in pipe_control.components
190
+
191
+ pipe_pag = AutoPipelineForText2Image.from_pipe(pipe_control, controlnet=None, enable_pag=True)
192
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGPipeline"
193
+ assert "controlnet" not in pipe_pag.components
194
+
195
+ pipe = AutoPipelineForText2Image.from_pipe(pipe_control, controlnet=None, enable_pag=False)
196
+ assert pipe.__class__.__name__ == "StableDiffusionXLPipeline"
197
+ assert "controlnet" not in pipe.components
198
+
199
+ # test from StableDiffusionXLControlNetPAGPipeline
200
+ # - test `enable_pag` flag
201
+ pipe_control_pag = AutoPipelineForText2Image.from_pipe(pipe_control_pag, enable_pag=True)
202
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
203
+ assert "controlnet" in pipe_control_pag.components
204
+
205
+ pipe_control = AutoPipelineForText2Image.from_pipe(pipe_control_pag, enable_pag=False)
206
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
207
+ assert "controlnet" in pipe_control.components
208
+
209
+ # - test `enable_pag` + `controlnet` flag
210
+ pipe_control_pag = AutoPipelineForText2Image.from_pipe(
211
+ pipe_control_pag, controlnet=controlnet, enable_pag=True
212
+ )
213
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGPipeline"
214
+ assert "controlnet" in pipe_control_pag.components
215
+
216
+ pipe_control = AutoPipelineForText2Image.from_pipe(pipe_control_pag, controlnet=controlnet, enable_pag=False)
217
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
218
+ assert "controlnet" in pipe_control.components
219
+
220
+ pipe_pag = AutoPipelineForText2Image.from_pipe(pipe_control_pag, controlnet=None, enable_pag=True)
221
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGPipeline"
222
+ assert "controlnet" not in pipe_pag.components
223
+
224
+ pipe = AutoPipelineForText2Image.from_pipe(pipe_control_pag, controlnet=None, enable_pag=False)
225
+ assert pipe.__class__.__name__ == "StableDiffusionXLPipeline"
226
+ assert "controlnet" not in pipe.components
227
+
228
+ pipe = AutoPipelineForText2Image.from_pipe(pipe_control_pag, enable_pag=False)
229
+ assert pipe.__class__.__name__ == "StableDiffusionXLControlNetPipeline"
230
+ assert "controlnet" in pipe.components
231
+
232
+ def test_from_pretrained_img2img(self):
233
+ repo = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
234
+
235
+ pipe = AutoPipelineForImage2Image.from_pretrained(repo)
236
+ assert pipe.__class__.__name__ == "StableDiffusionXLImg2ImgPipeline"
237
+
238
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
239
+ pipe_control = AutoPipelineForImage2Image.from_pretrained(repo, controlnet=controlnet)
240
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetImg2ImgPipeline"
241
+
242
+ pipe_pag = AutoPipelineForImage2Image.from_pretrained(repo, enable_pag=True)
243
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
244
+
245
+ pipe_control_pag = AutoPipelineForImage2Image.from_pretrained(repo, controlnet=controlnet, enable_pag=True)
246
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGImg2ImgPipeline"
247
+
248
+ def test_from_pretrained_img2img_refiner(self):
249
+ repo = "hf-internal-testing/tiny-stable-diffusion-xl-refiner-pipe"
250
+
251
+ pipe = AutoPipelineForImage2Image.from_pretrained(repo)
252
+ assert pipe.__class__.__name__ == "StableDiffusionXLImg2ImgPipeline"
253
+
254
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
255
+ pipe_control = AutoPipelineForImage2Image.from_pretrained(repo, controlnet=controlnet)
256
+ assert pipe_control.__class__.__name__ == "StableDiffusionXLControlNetImg2ImgPipeline"
257
+
258
+ pipe_pag = AutoPipelineForImage2Image.from_pretrained(repo, enable_pag=True)
259
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
260
+
261
+ pipe_control_pag = AutoPipelineForImage2Image.from_pretrained(repo, controlnet=controlnet, enable_pag=True)
262
+ assert pipe_control_pag.__class__.__name__ == "StableDiffusionXLControlNetPAGImg2ImgPipeline"
263
+
264
+ def test_from_pipe_pag_img2img(self):
265
+ # test from tableDiffusionXLPAGImg2ImgPipeline
266
+ pipe = AutoPipelineForImage2Image.from_pretrained("hf-internal-testing/tiny-stable-diffusion-xl-pipe")
267
+ # - test `enable_pag` flag
268
+ pipe_pag = AutoPipelineForImage2Image.from_pipe(pipe, enable_pag=True)
269
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
270
+
271
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe, enable_pag=False)
272
+ assert pipe.__class__.__name__ == "StableDiffusionXLImg2ImgPipeline"
273
+
274
+ # testing from StableDiffusionXLPAGImg2ImgPipeline
275
+ # - test `enable_pag` flag
276
+ pipe_pag = AutoPipelineForImage2Image.from_pipe(pipe_pag, enable_pag=True)
277
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
278
+
279
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe_pag, enable_pag=False)
280
+ assert pipe.__class__.__name__ == "StableDiffusionXLImg2ImgPipeline"
281
+
282
+ def test_from_pretrained_inpaint(self):
283
+ repo = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
284
+
285
+ pipe = AutoPipelineForInpainting.from_pretrained(repo)
286
+ assert pipe.__class__.__name__ == "StableDiffusionXLInpaintPipeline"
287
+
288
+ pipe_pag = AutoPipelineForInpainting.from_pretrained(repo, enable_pag=True)
289
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
290
+
291
+ def test_from_pretrained_inpaint_from_inpaint(self):
292
+ repo = "hf-internal-testing/tiny-stable-diffusion-xl-inpaint-pipe"
293
+
294
+ pipe = AutoPipelineForInpainting.from_pretrained(repo)
295
+ assert pipe.__class__.__name__ == "StableDiffusionXLInpaintPipeline"
296
+
297
+ # make sure you can use pag with inpaint-specific pipeline
298
+ pipe = AutoPipelineForInpainting.from_pretrained(repo, enable_pag=True)
299
+ assert pipe.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
300
+
301
+ def test_from_pipe_pag_inpaint(self):
302
+ # test from tableDiffusionXLPAGInpaintPipeline
303
+ pipe = AutoPipelineForInpainting.from_pretrained("hf-internal-testing/tiny-stable-diffusion-xl-pipe")
304
+ # - test `enable_pag` flag
305
+ pipe_pag = AutoPipelineForInpainting.from_pipe(pipe, enable_pag=True)
306
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
307
+
308
+ pipe = AutoPipelineForInpainting.from_pipe(pipe, enable_pag=False)
309
+ assert pipe.__class__.__name__ == "StableDiffusionXLInpaintPipeline"
310
+
311
+ # testing from StableDiffusionXLPAGInpaintPipeline
312
+ # - test `enable_pag` flag
313
+ pipe_pag = AutoPipelineForInpainting.from_pipe(pipe_pag, enable_pag=True)
314
+ assert pipe_pag.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
315
+
316
+ pipe = AutoPipelineForInpainting.from_pipe(pipe_pag, enable_pag=False)
317
+ assert pipe.__class__.__name__ == "StableDiffusionXLInpaintPipeline"
318
+
319
+ def test_from_pipe_pag_new_task(self):
320
+ # for from_pipe_new_task we only need to make sure it can map to the same pipeline from a different task,
321
+ # i.e. no need to test `enable_pag` + `controlnet` flag because it is already tested in `test_from_pipe_pag_text2img` and `test_from_pipe_pag_inpaint`etc
322
+ pipe_pag_text2img = AutoPipelineForText2Image.from_pretrained(
323
+ "hf-internal-testing/tiny-stable-diffusion-xl-pipe", enable_pag=True
324
+ )
325
+
326
+ # text2img pag -> inpaint pag
327
+ pipe_pag_inpaint = AutoPipelineForInpainting.from_pipe(pipe_pag_text2img)
328
+ assert pipe_pag_inpaint.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
329
+ # text2img pag -> img2img pag
330
+ pipe_pag_img2img = AutoPipelineForImage2Image.from_pipe(pipe_pag_text2img)
331
+ assert pipe_pag_img2img.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
332
+
333
+ # inpaint pag -> text2img pag
334
+ pipe_pag_text2img = AutoPipelineForText2Image.from_pipe(pipe_pag_inpaint)
335
+ assert pipe_pag_text2img.__class__.__name__ == "StableDiffusionXLPAGPipeline"
336
+ # inpaint pag -> img2img pag
337
+ pipe_pag_img2img = AutoPipelineForImage2Image.from_pipe(pipe_pag_inpaint)
338
+ assert pipe_pag_img2img.__class__.__name__ == "StableDiffusionXLPAGImg2ImgPipeline"
339
+
340
+ # img2img pag -> text2img pag
341
+ pipe_pag_text2img = AutoPipelineForText2Image.from_pipe(pipe_pag_img2img)
342
+ assert pipe_pag_text2img.__class__.__name__ == "StableDiffusionXLPAGPipeline"
343
+ # img2img pag -> inpaint pag
344
+ pipe_pag_inpaint = AutoPipelineForInpainting.from_pipe(pipe_pag_img2img)
345
+ assert pipe_pag_inpaint.__class__.__name__ == "StableDiffusionXLPAGInpaintPipeline"
346
+
347
+ def test_from_pipe_controlnet_text2img(self):
348
+ pipe = AutoPipelineForText2Image.from_pretrained("hf-internal-testing/tiny-stable-diffusion-pipe")
349
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
350
+
351
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, controlnet=controlnet)
352
+ assert pipe.__class__.__name__ == "StableDiffusionControlNetPipeline"
353
+ assert "controlnet" in pipe.components
354
+
355
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, controlnet=None)
356
+ assert pipe.__class__.__name__ == "StableDiffusionPipeline"
357
+ assert "controlnet" not in pipe.components
358
+
359
+ def test_from_pipe_controlnet_img2img(self):
360
+ pipe = AutoPipelineForImage2Image.from_pretrained("hf-internal-testing/tiny-stable-diffusion-pipe")
361
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
362
+
363
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe, controlnet=controlnet)
364
+ assert pipe.__class__.__name__ == "StableDiffusionControlNetImg2ImgPipeline"
365
+ assert "controlnet" in pipe.components
366
+
367
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe, controlnet=None)
368
+ assert pipe.__class__.__name__ == "StableDiffusionImg2ImgPipeline"
369
+ assert "controlnet" not in pipe.components
370
+
371
+ def test_from_pipe_controlnet_inpaint(self):
372
+ pipe = AutoPipelineForInpainting.from_pretrained("hf-internal-testing/tiny-stable-diffusion-torch")
373
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
374
+
375
+ pipe = AutoPipelineForInpainting.from_pipe(pipe, controlnet=controlnet)
376
+ assert pipe.__class__.__name__ == "StableDiffusionControlNetInpaintPipeline"
377
+ assert "controlnet" in pipe.components
378
+
379
+ pipe = AutoPipelineForInpainting.from_pipe(pipe, controlnet=None)
380
+ assert pipe.__class__.__name__ == "StableDiffusionInpaintPipeline"
381
+ assert "controlnet" not in pipe.components
382
+
383
+ def test_from_pipe_controlnet_new_task(self):
384
+ pipe_text2img = AutoPipelineForText2Image.from_pretrained("hf-internal-testing/tiny-stable-diffusion-torch")
385
+ controlnet = ControlNetModel.from_pretrained("hf-internal-testing/tiny-controlnet")
386
+
387
+ pipe_control_img2img = AutoPipelineForImage2Image.from_pipe(pipe_text2img, controlnet=controlnet)
388
+ assert pipe_control_img2img.__class__.__name__ == "StableDiffusionControlNetImg2ImgPipeline"
389
+ assert "controlnet" in pipe_control_img2img.components
390
+
391
+ pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_control_img2img, controlnet=None)
392
+ assert pipe_inpaint.__class__.__name__ == "StableDiffusionInpaintPipeline"
393
+ assert "controlnet" not in pipe_inpaint.components
394
+
395
+ # testing `from_pipe` for text2img controlnet
396
+ ## 1. from a different controlnet pipe, without controlnet argument
397
+ pipe_control_text2img = AutoPipelineForText2Image.from_pipe(pipe_control_img2img)
398
+ assert pipe_control_text2img.__class__.__name__ == "StableDiffusionControlNetPipeline"
399
+ assert "controlnet" in pipe_control_text2img.components
400
+
401
+ ## 2. from a different controlnet pipe, with controlnet argument
402
+ pipe_control_text2img = AutoPipelineForText2Image.from_pipe(pipe_control_img2img, controlnet=controlnet)
403
+ assert pipe_control_text2img.__class__.__name__ == "StableDiffusionControlNetPipeline"
404
+ assert "controlnet" in pipe_control_text2img.components
405
+
406
+ ## 3. from same controlnet pipeline class, with a different controlnet component
407
+ pipe_control_text2img = AutoPipelineForText2Image.from_pipe(pipe_control_text2img, controlnet=controlnet)
408
+ assert pipe_control_text2img.__class__.__name__ == "StableDiffusionControlNetPipeline"
409
+ assert "controlnet" in pipe_control_text2img.components
410
+
411
+ # testing from_pipe for inpainting
412
+ ## 1. from a different controlnet pipeline class
413
+ pipe_control_inpaint = AutoPipelineForInpainting.from_pipe(pipe_control_img2img)
414
+ assert pipe_control_inpaint.__class__.__name__ == "StableDiffusionControlNetInpaintPipeline"
415
+ assert "controlnet" in pipe_control_inpaint.components
416
+
417
+ ## from a different controlnet pipe, with a different controlnet
418
+ pipe_control_inpaint = AutoPipelineForInpainting.from_pipe(pipe_control_img2img, controlnet=controlnet)
419
+ assert pipe_control_inpaint.__class__.__name__ == "StableDiffusionControlNetInpaintPipeline"
420
+ assert "controlnet" in pipe_control_inpaint.components
421
+
422
+ ## from same controlnet pipe, with a different controlnet
423
+ pipe_control_inpaint = AutoPipelineForInpainting.from_pipe(pipe_control_inpaint, controlnet=controlnet)
424
+ assert pipe_control_inpaint.__class__.__name__ == "StableDiffusionControlNetInpaintPipeline"
425
+ assert "controlnet" in pipe_control_inpaint.components
426
+
427
+ # testing from_pipe from img2img controlnet
428
+ ## from a different controlnet pipe, without controlnet argument
429
+ pipe_control_img2img = AutoPipelineForImage2Image.from_pipe(pipe_control_text2img)
430
+ assert pipe_control_img2img.__class__.__name__ == "StableDiffusionControlNetImg2ImgPipeline"
431
+ assert "controlnet" in pipe_control_img2img.components
432
+
433
+ # from a different controlnet pipe, with a different controlnet component
434
+ pipe_control_img2img = AutoPipelineForImage2Image.from_pipe(pipe_control_text2img, controlnet=controlnet)
435
+ assert pipe_control_img2img.__class__.__name__ == "StableDiffusionControlNetImg2ImgPipeline"
436
+ assert "controlnet" in pipe_control_img2img.components
437
+
438
+ # from same controlnet pipeline class, with a different controlnet
439
+ pipe_control_img2img = AutoPipelineForImage2Image.from_pipe(pipe_control_img2img, controlnet=controlnet)
440
+ assert pipe_control_img2img.__class__.__name__ == "StableDiffusionControlNetImg2ImgPipeline"
441
+ assert "controlnet" in pipe_control_img2img.components
442
+
443
+ def test_from_pipe_optional_components(self):
444
+ image_encoder = self.dummy_image_encoder
445
+
446
+ pipe = AutoPipelineForText2Image.from_pretrained(
447
+ "hf-internal-testing/tiny-stable-diffusion-pipe",
448
+ image_encoder=image_encoder,
449
+ )
450
+
451
+ pipe = AutoPipelineForImage2Image.from_pipe(pipe)
452
+ assert pipe.image_encoder is not None
453
+
454
+ pipe = AutoPipelineForText2Image.from_pipe(pipe, image_encoder=None)
455
+ assert pipe.image_encoder is None
456
+
457
+
458
+ @slow
459
+ class AutoPipelineIntegrationTest(unittest.TestCase):
460
+ def test_pipe_auto(self):
461
+ for model_name, model_repo in PRETRAINED_MODEL_REPO_MAPPING.items():
462
+ # test txt2img
463
+ pipe_txt2img = AutoPipelineForText2Image.from_pretrained(
464
+ model_repo, variant="fp16", torch_dtype=torch.float16
465
+ )
466
+ self.assertIsInstance(pipe_txt2img, AUTO_TEXT2IMAGE_PIPELINES_MAPPING[model_name])
467
+
468
+ pipe_to = AutoPipelineForText2Image.from_pipe(pipe_txt2img)
469
+ self.assertIsInstance(pipe_to, AUTO_TEXT2IMAGE_PIPELINES_MAPPING[model_name])
470
+
471
+ pipe_to = AutoPipelineForImage2Image.from_pipe(pipe_txt2img)
472
+ self.assertIsInstance(pipe_to, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING[model_name])
473
+
474
+ if "kandinsky" not in model_name:
475
+ pipe_to = AutoPipelineForInpainting.from_pipe(pipe_txt2img)
476
+ self.assertIsInstance(pipe_to, AUTO_INPAINT_PIPELINES_MAPPING[model_name])
477
+
478
+ del pipe_txt2img, pipe_to
479
+ gc.collect()
480
+
481
+ # test img2img
482
+
483
+ pipe_img2img = AutoPipelineForImage2Image.from_pretrained(
484
+ model_repo, variant="fp16", torch_dtype=torch.float16
485
+ )
486
+ self.assertIsInstance(pipe_img2img, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING[model_name])
487
+
488
+ pipe_to = AutoPipelineForText2Image.from_pipe(pipe_img2img)
489
+ self.assertIsInstance(pipe_to, AUTO_TEXT2IMAGE_PIPELINES_MAPPING[model_name])
490
+
491
+ pipe_to = AutoPipelineForImage2Image.from_pipe(pipe_img2img)
492
+ self.assertIsInstance(pipe_to, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING[model_name])
493
+
494
+ if "kandinsky" not in model_name:
495
+ pipe_to = AutoPipelineForInpainting.from_pipe(pipe_img2img)
496
+ self.assertIsInstance(pipe_to, AUTO_INPAINT_PIPELINES_MAPPING[model_name])
497
+
498
+ del pipe_img2img, pipe_to
499
+ gc.collect()
500
+
501
+ # test inpaint
502
+
503
+ if "kandinsky" not in model_name:
504
+ pipe_inpaint = AutoPipelineForInpainting.from_pretrained(
505
+ model_repo, variant="fp16", torch_dtype=torch.float16
506
+ )
507
+ self.assertIsInstance(pipe_inpaint, AUTO_INPAINT_PIPELINES_MAPPING[model_name])
508
+
509
+ pipe_to = AutoPipelineForText2Image.from_pipe(pipe_inpaint)
510
+ self.assertIsInstance(pipe_to, AUTO_TEXT2IMAGE_PIPELINES_MAPPING[model_name])
511
+
512
+ pipe_to = AutoPipelineForImage2Image.from_pipe(pipe_inpaint)
513
+ self.assertIsInstance(pipe_to, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING[model_name])
514
+
515
+ pipe_to = AutoPipelineForInpainting.from_pipe(pipe_inpaint)
516
+ self.assertIsInstance(pipe_to, AUTO_INPAINT_PIPELINES_MAPPING[model_name])
517
+
518
+ del pipe_inpaint, pipe_to
519
+ gc.collect()
520
+
521
+ def test_from_pipe_consistent(self):
522
+ for model_name, model_repo in PRETRAINED_MODEL_REPO_MAPPING.items():
523
+ if model_name in ["kandinsky", "kandinsky22"]:
524
+ auto_pipes = [AutoPipelineForText2Image, AutoPipelineForImage2Image]
525
+ else:
526
+ auto_pipes = [AutoPipelineForText2Image, AutoPipelineForImage2Image, AutoPipelineForInpainting]
527
+
528
+ # test from_pretrained
529
+ for pipe_from_class in auto_pipes:
530
+ pipe_from = pipe_from_class.from_pretrained(model_repo, variant="fp16", torch_dtype=torch.float16)
531
+ pipe_from_config = dict(pipe_from.config)
532
+
533
+ for pipe_to_class in auto_pipes:
534
+ pipe_to = pipe_to_class.from_pipe(pipe_from)
535
+ self.assertEqual(dict(pipe_to.config), pipe_from_config)
536
+
537
+ del pipe_from, pipe_to
538
+ gc.collect()
539
+
540
+ def test_controlnet(self):
541
+ # test from_pretrained
542
+ model_repo = "stable-diffusion-v1-5/stable-diffusion-v1-5"
543
+ controlnet_repo = "lllyasviel/sd-controlnet-canny"
544
+
545
+ controlnet = ControlNetModel.from_pretrained(controlnet_repo, torch_dtype=torch.float16)
546
+
547
+ pipe_txt2img = AutoPipelineForText2Image.from_pretrained(
548
+ model_repo, controlnet=controlnet, torch_dtype=torch.float16
549
+ )
550
+ self.assertIsInstance(pipe_txt2img, AUTO_TEXT2IMAGE_PIPELINES_MAPPING["stable-diffusion-controlnet"])
551
+
552
+ pipe_img2img = AutoPipelineForImage2Image.from_pretrained(
553
+ model_repo, controlnet=controlnet, torch_dtype=torch.float16
554
+ )
555
+ self.assertIsInstance(pipe_img2img, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING["stable-diffusion-controlnet"])
556
+
557
+ pipe_inpaint = AutoPipelineForInpainting.from_pretrained(
558
+ model_repo, controlnet=controlnet, torch_dtype=torch.float16
559
+ )
560
+ self.assertIsInstance(pipe_inpaint, AUTO_INPAINT_PIPELINES_MAPPING["stable-diffusion-controlnet"])
561
+
562
+ # test from_pipe
563
+ for pipe_from in [pipe_txt2img, pipe_img2img, pipe_inpaint]:
564
+ pipe_to = AutoPipelineForText2Image.from_pipe(pipe_from)
565
+ self.assertIsInstance(pipe_to, AUTO_TEXT2IMAGE_PIPELINES_MAPPING["stable-diffusion-controlnet"])
566
+ self.assertEqual(dict(pipe_to.config), dict(pipe_txt2img.config))
567
+
568
+ pipe_to = AutoPipelineForImage2Image.from_pipe(pipe_from)
569
+ self.assertIsInstance(pipe_to, AUTO_IMAGE2IMAGE_PIPELINES_MAPPING["stable-diffusion-controlnet"])
570
+ self.assertEqual(dict(pipe_to.config), dict(pipe_img2img.config))
571
+
572
+ pipe_to = AutoPipelineForInpainting.from_pipe(pipe_from)
573
+ self.assertIsInstance(pipe_to, AUTO_INPAINT_PIPELINES_MAPPING["stable-diffusion-controlnet"])
574
+ self.assertEqual(dict(pipe_to.config), dict(pipe_inpaint.config))
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_combined.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 torch
19
+ from huggingface_hub import ModelCard
20
+
21
+ from diffusers import (
22
+ DDPMScheduler,
23
+ DiffusionPipeline,
24
+ KandinskyV22CombinedPipeline,
25
+ KandinskyV22Pipeline,
26
+ KandinskyV22PriorPipeline,
27
+ )
28
+ from diffusers.pipelines.pipeline_utils import CONNECTED_PIPES_KEYS
29
+
30
+
31
+ def state_dicts_almost_equal(sd1, sd2):
32
+ sd1 = dict(sorted(sd1.items()))
33
+ sd2 = dict(sorted(sd2.items()))
34
+
35
+ models_are_equal = True
36
+ for ten1, ten2 in zip(sd1.values(), sd2.values()):
37
+ if (ten1 - ten2).abs().sum() > 1e-3:
38
+ models_are_equal = False
39
+
40
+ return models_are_equal
41
+
42
+
43
+ class CombinedPipelineFastTest(unittest.TestCase):
44
+ def modelcard_has_connected_pipeline(self, model_id):
45
+ modelcard = ModelCard.load(model_id)
46
+ connected_pipes = {prefix: getattr(modelcard.data, prefix, [None])[0] for prefix in CONNECTED_PIPES_KEYS}
47
+ connected_pipes = {k: v for k, v in connected_pipes.items() if v is not None}
48
+
49
+ return len(connected_pipes) > 0
50
+
51
+ def test_correct_modelcard_format(self):
52
+ # hf-internal-testing/tiny-random-kandinsky-v22-prior has no metadata
53
+ assert not self.modelcard_has_connected_pipeline("hf-internal-testing/tiny-random-kandinsky-v22-prior")
54
+
55
+ # see https://huggingface.co/hf-internal-testing/tiny-random-kandinsky-v22-decoder/blob/8baff9897c6be017013e21b5c562e5a381646c7e/README.md?code=true#L2
56
+ assert self.modelcard_has_connected_pipeline("hf-internal-testing/tiny-random-kandinsky-v22-decoder")
57
+
58
+ def test_load_connected_checkpoint_when_specified(self):
59
+ pipeline_prior = DiffusionPipeline.from_pretrained("hf-internal-testing/tiny-random-kandinsky-v22-prior")
60
+ pipeline_prior_connected = DiffusionPipeline.from_pretrained(
61
+ "hf-internal-testing/tiny-random-kandinsky-v22-prior", load_connected_pipeline=True
62
+ )
63
+
64
+ # Passing `load_connected_pipeline` to prior is a no-op as the pipeline has no connected pipeline
65
+ assert pipeline_prior.__class__ == pipeline_prior_connected.__class__
66
+
67
+ pipeline = DiffusionPipeline.from_pretrained("hf-internal-testing/tiny-random-kandinsky-v22-decoder")
68
+ pipeline_connected = DiffusionPipeline.from_pretrained(
69
+ "hf-internal-testing/tiny-random-kandinsky-v22-decoder", load_connected_pipeline=True
70
+ )
71
+
72
+ # Passing `load_connected_pipeline` to decoder loads the combined pipeline
73
+ assert pipeline.__class__ != pipeline_connected.__class__
74
+ assert pipeline.__class__ == KandinskyV22Pipeline
75
+ assert pipeline_connected.__class__ == KandinskyV22CombinedPipeline
76
+
77
+ # check that loaded components match prior and decoder components
78
+ assert set(pipeline_connected.components.keys()) == set(
79
+ ["prior_" + k for k in pipeline_prior.components.keys()] + list(pipeline.components.keys())
80
+ )
81
+
82
+ def test_load_connected_checkpoint_default(self):
83
+ prior = KandinskyV22PriorPipeline.from_pretrained("hf-internal-testing/tiny-random-kandinsky-v22-prior")
84
+ decoder = KandinskyV22Pipeline.from_pretrained("hf-internal-testing/tiny-random-kandinsky-v22-decoder")
85
+
86
+ # check that combined pipeline loads both prior & decoder because of
87
+ # https://huggingface.co/hf-internal-testing/tiny-random-kandinsky-v22-decoder/blob/8baff9897c6be017013e21b5c562e5a381646c7e/README.md?code=true#L3
88
+ assert (
89
+ KandinskyV22CombinedPipeline._load_connected_pipes
90
+ ) # combined pipelines will download more checkpoints that just the one specified
91
+ pipeline = KandinskyV22CombinedPipeline.from_pretrained(
92
+ "hf-internal-testing/tiny-random-kandinsky-v22-decoder"
93
+ )
94
+
95
+ prior_comps = prior.components
96
+ decoder_comps = decoder.components
97
+ for k, component in pipeline.components.items():
98
+ if k.startswith("prior_"):
99
+ k = k[6:]
100
+ comp = prior_comps[k]
101
+ else:
102
+ comp = decoder_comps[k]
103
+
104
+ if isinstance(component, torch.nn.Module):
105
+ assert state_dicts_almost_equal(component.state_dict(), comp.state_dict())
106
+ elif hasattr(component, "config"):
107
+ assert dict(component.config) == dict(comp.config)
108
+ else:
109
+ assert component.__class__ == comp.__class__
110
+
111
+ def test_load_connected_checkpoint_with_passed_obj(self):
112
+ pipeline = KandinskyV22CombinedPipeline.from_pretrained(
113
+ "hf-internal-testing/tiny-random-kandinsky-v22-decoder"
114
+ )
115
+ prior_scheduler = DDPMScheduler.from_config(pipeline.prior_scheduler.config)
116
+ scheduler = DDPMScheduler.from_config(pipeline.scheduler.config)
117
+
118
+ # make sure we pass a different scheduler and prior_scheduler
119
+ assert pipeline.prior_scheduler.__class__ != prior_scheduler.__class__
120
+ assert pipeline.scheduler.__class__ != scheduler.__class__
121
+
122
+ pipeline_new = KandinskyV22CombinedPipeline.from_pretrained(
123
+ "hf-internal-testing/tiny-random-kandinsky-v22-decoder",
124
+ prior_scheduler=prior_scheduler,
125
+ scheduler=scheduler,
126
+ )
127
+ assert dict(pipeline_new.prior_scheduler.config) == dict(prior_scheduler.config)
128
+ assert dict(pipeline_new.scheduler.config) == dict(scheduler.config)
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_common.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_flax.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 os
17
+ import tempfile
18
+ import unittest
19
+
20
+ import numpy as np
21
+
22
+ from diffusers.utils import is_flax_available
23
+ from diffusers.utils.testing_utils import require_flax, slow
24
+
25
+
26
+ if is_flax_available():
27
+ import jax
28
+ import jax.numpy as jnp
29
+ from flax.jax_utils import replicate
30
+ from flax.training.common_utils import shard
31
+
32
+ from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline
33
+
34
+
35
+ @require_flax
36
+ class DownloadTests(unittest.TestCase):
37
+ def test_download_only_pytorch(self):
38
+ with tempfile.TemporaryDirectory() as tmpdirname:
39
+ # pipeline has Flax weights
40
+ _ = FlaxDiffusionPipeline.from_pretrained(
41
+ "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=None, cache_dir=tmpdirname
42
+ )
43
+
44
+ all_root_files = [t[-1] for t in os.walk(os.path.join(tmpdirname, os.listdir(tmpdirname)[0], "snapshots"))]
45
+ files = [item for sublist in all_root_files for item in sublist]
46
+
47
+ # None of the downloaded files should be a PyTorch file even if we have some here:
48
+ # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
49
+ assert not any(f.endswith(".bin") for f in files)
50
+
51
+
52
+ @slow
53
+ @require_flax
54
+ class FlaxPipelineTests(unittest.TestCase):
55
+ def test_dummy_all_tpus(self):
56
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
57
+ "hf-internal-testing/tiny-stable-diffusion-pipe", safety_checker=None
58
+ )
59
+
60
+ prompt = (
61
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
62
+ " field, close up, split lighting, cinematic"
63
+ )
64
+
65
+ prng_seed = jax.random.PRNGKey(0)
66
+ num_inference_steps = 4
67
+
68
+ num_samples = jax.device_count()
69
+ prompt = num_samples * [prompt]
70
+ prompt_ids = pipeline.prepare_inputs(prompt)
71
+
72
+ # shard inputs and rng
73
+ params = replicate(params)
74
+ prng_seed = jax.random.split(prng_seed, num_samples)
75
+ prompt_ids = shard(prompt_ids)
76
+
77
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
78
+
79
+ assert images.shape == (num_samples, 1, 64, 64, 3)
80
+ if jax.device_count() == 8:
81
+ assert np.abs(np.abs(images[0, 0, :2, :2, -2:], dtype=np.float32).sum() - 4.1514745) < 1e-3
82
+ assert np.abs(np.abs(images, dtype=np.float32).sum() - 49947.875) < 5e-1
83
+
84
+ images_pil = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:])))
85
+ assert len(images_pil) == num_samples
86
+
87
+ def test_stable_diffusion_v1_4(self):
88
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
89
+ "CompVis/stable-diffusion-v1-4", revision="flax", safety_checker=None
90
+ )
91
+
92
+ prompt = (
93
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
94
+ " field, close up, split lighting, cinematic"
95
+ )
96
+
97
+ prng_seed = jax.random.PRNGKey(0)
98
+ num_inference_steps = 50
99
+
100
+ num_samples = jax.device_count()
101
+ prompt = num_samples * [prompt]
102
+ prompt_ids = pipeline.prepare_inputs(prompt)
103
+
104
+ # shard inputs and rng
105
+ params = replicate(params)
106
+ prng_seed = jax.random.split(prng_seed, num_samples)
107
+ prompt_ids = shard(prompt_ids)
108
+
109
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
110
+
111
+ assert images.shape == (num_samples, 1, 512, 512, 3)
112
+ if jax.device_count() == 8:
113
+ assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.float32).sum() - 0.05652401)) < 1e-2
114
+ assert np.abs((np.abs(images, dtype=np.float32).sum() - 2383808.2)) < 5e-1
115
+
116
+ def test_stable_diffusion_v1_4_bfloat_16(self):
117
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
118
+ "CompVis/stable-diffusion-v1-4", variant="bf16", dtype=jnp.bfloat16, safety_checker=None
119
+ )
120
+
121
+ prompt = (
122
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
123
+ " field, close up, split lighting, cinematic"
124
+ )
125
+
126
+ prng_seed = jax.random.PRNGKey(0)
127
+ num_inference_steps = 50
128
+
129
+ num_samples = jax.device_count()
130
+ prompt = num_samples * [prompt]
131
+ prompt_ids = pipeline.prepare_inputs(prompt)
132
+
133
+ # shard inputs and rng
134
+ params = replicate(params)
135
+ prng_seed = jax.random.split(prng_seed, num_samples)
136
+ prompt_ids = shard(prompt_ids)
137
+
138
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
139
+
140
+ assert images.shape == (num_samples, 1, 512, 512, 3)
141
+ if jax.device_count() == 8:
142
+ assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.float32).sum() - 0.04003906)) < 5e-2
143
+ assert np.abs((np.abs(images, dtype=np.float32).sum() - 2373516.75)) < 5e-1
144
+
145
+ def test_stable_diffusion_v1_4_bfloat_16_with_safety(self):
146
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
147
+ "CompVis/stable-diffusion-v1-4", variant="bf16", dtype=jnp.bfloat16
148
+ )
149
+
150
+ prompt = (
151
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
152
+ " field, close up, split lighting, cinematic"
153
+ )
154
+
155
+ prng_seed = jax.random.PRNGKey(0)
156
+ num_inference_steps = 50
157
+
158
+ num_samples = jax.device_count()
159
+ prompt = num_samples * [prompt]
160
+ prompt_ids = pipeline.prepare_inputs(prompt)
161
+
162
+ # shard inputs and rng
163
+ params = replicate(params)
164
+ prng_seed = jax.random.split(prng_seed, num_samples)
165
+ prompt_ids = shard(prompt_ids)
166
+
167
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
168
+
169
+ assert images.shape == (num_samples, 1, 512, 512, 3)
170
+ if jax.device_count() == 8:
171
+ assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.float32).sum() - 0.04003906)) < 5e-2
172
+ assert np.abs((np.abs(images, dtype=np.float32).sum() - 2373516.75)) < 5e-1
173
+
174
+ def test_stable_diffusion_v1_4_bfloat_16_ddim(self):
175
+ scheduler = FlaxDDIMScheduler(
176
+ beta_start=0.00085,
177
+ beta_end=0.012,
178
+ beta_schedule="scaled_linear",
179
+ set_alpha_to_one=False,
180
+ steps_offset=1,
181
+ )
182
+
183
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
184
+ "CompVis/stable-diffusion-v1-4",
185
+ variant="bf16",
186
+ dtype=jnp.bfloat16,
187
+ scheduler=scheduler,
188
+ safety_checker=None,
189
+ )
190
+ scheduler_state = scheduler.create_state()
191
+
192
+ params["scheduler"] = scheduler_state
193
+
194
+ prompt = (
195
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
196
+ " field, close up, split lighting, cinematic"
197
+ )
198
+
199
+ prng_seed = jax.random.PRNGKey(0)
200
+ num_inference_steps = 50
201
+
202
+ num_samples = jax.device_count()
203
+ prompt = num_samples * [prompt]
204
+ prompt_ids = pipeline.prepare_inputs(prompt)
205
+
206
+ # shard inputs and rng
207
+ params = replicate(params)
208
+ prng_seed = jax.random.split(prng_seed, num_samples)
209
+ prompt_ids = shard(prompt_ids)
210
+
211
+ images = pipeline(prompt_ids, params, prng_seed, num_inference_steps, jit=True).images
212
+
213
+ assert images.shape == (num_samples, 1, 512, 512, 3)
214
+ if jax.device_count() == 8:
215
+ assert np.abs((np.abs(images[0, 0, :2, :2, -2:], dtype=np.float32).sum() - 0.045043945)) < 5e-2
216
+ assert np.abs((np.abs(images, dtype=np.float32).sum() - 2347693.5)) < 5e-1
217
+
218
+ def test_jax_memory_efficient_attention(self):
219
+ prompt = (
220
+ "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of"
221
+ " field, close up, split lighting, cinematic"
222
+ )
223
+
224
+ num_samples = jax.device_count()
225
+ prompt = num_samples * [prompt]
226
+ prng_seed = jax.random.split(jax.random.PRNGKey(0), num_samples)
227
+
228
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
229
+ "CompVis/stable-diffusion-v1-4",
230
+ variant="bf16",
231
+ dtype=jnp.bfloat16,
232
+ safety_checker=None,
233
+ )
234
+
235
+ params = replicate(params)
236
+ prompt_ids = pipeline.prepare_inputs(prompt)
237
+ prompt_ids = shard(prompt_ids)
238
+ images = pipeline(prompt_ids, params, prng_seed, jit=True).images
239
+ assert images.shape == (num_samples, 1, 512, 512, 3)
240
+ slice = images[2, 0, 256, 10:17, 1]
241
+
242
+ # With memory efficient attention
243
+ pipeline, params = FlaxStableDiffusionPipeline.from_pretrained(
244
+ "CompVis/stable-diffusion-v1-4",
245
+ variant="bf16",
246
+ dtype=jnp.bfloat16,
247
+ safety_checker=None,
248
+ use_memory_efficient_attention=True,
249
+ )
250
+
251
+ params = replicate(params)
252
+ prompt_ids = pipeline.prepare_inputs(prompt)
253
+ prompt_ids = shard(prompt_ids)
254
+ images_eff = pipeline(prompt_ids, params, prng_seed, jit=True).images
255
+ assert images_eff.shape == (num_samples, 1, 512, 512, 3)
256
+ slice_eff = images[2, 0, 256, 10:17, 1]
257
+
258
+ # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
259
+ # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
260
+ assert abs(slice_eff - slice).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/test_pipelines_onnx_common.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers.utils.testing_utils import require_onnxruntime
2
+
3
+
4
+ @require_onnxruntime
5
+ class OnnxPipelineTesterMixin:
6
+ """
7
+ This mixin is designed to be used with unittest.TestCase classes.
8
+ It provides a set of common tests for each ONNXRuntime pipeline, e.g. saving and loading the pipeline,
9
+ equivalence of dict and tuple outputs, etc.
10
+ """
11
+
12
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers import AutoencoderKL, DDIMScheduler, TextToVideoSDPipeline, UNet3DConditionModel
24
+ from diffusers.utils import is_xformers_available
25
+ from diffusers.utils.testing_utils import (
26
+ backend_empty_cache,
27
+ enable_full_determinism,
28
+ load_numpy,
29
+ numpy_cosine_similarity_distance,
30
+ require_torch_accelerator,
31
+ skip_mps,
32
+ slow,
33
+ torch_device,
34
+ )
35
+
36
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
37
+ from ..test_pipelines_common import PipelineTesterMixin, SDFunctionTesterMixin
38
+
39
+
40
+ enable_full_determinism()
41
+
42
+
43
+ @skip_mps
44
+ class TextToVideoSDPipelineFastTests(PipelineTesterMixin, SDFunctionTesterMixin, unittest.TestCase):
45
+ pipeline_class = TextToVideoSDPipeline
46
+ params = TEXT_TO_IMAGE_PARAMS
47
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
48
+ # No `output_type`.
49
+ required_optional_params = frozenset(
50
+ [
51
+ "num_inference_steps",
52
+ "generator",
53
+ "latents",
54
+ "return_dict",
55
+ "callback",
56
+ "callback_steps",
57
+ ]
58
+ )
59
+
60
+ def get_dummy_components(self):
61
+ torch.manual_seed(0)
62
+ unet = UNet3DConditionModel(
63
+ block_out_channels=(8, 8),
64
+ layers_per_block=1,
65
+ sample_size=32,
66
+ in_channels=4,
67
+ out_channels=4,
68
+ down_block_types=("CrossAttnDownBlock3D", "DownBlock3D"),
69
+ up_block_types=("UpBlock3D", "CrossAttnUpBlock3D"),
70
+ cross_attention_dim=4,
71
+ attention_head_dim=4,
72
+ norm_num_groups=2,
73
+ )
74
+ scheduler = DDIMScheduler(
75
+ beta_start=0.00085,
76
+ beta_end=0.012,
77
+ beta_schedule="scaled_linear",
78
+ clip_sample=False,
79
+ set_alpha_to_one=False,
80
+ )
81
+ torch.manual_seed(0)
82
+ vae = AutoencoderKL(
83
+ block_out_channels=(8,),
84
+ in_channels=3,
85
+ out_channels=3,
86
+ down_block_types=["DownEncoderBlock2D"],
87
+ up_block_types=["UpDecoderBlock2D"],
88
+ latent_channels=4,
89
+ sample_size=32,
90
+ norm_num_groups=2,
91
+ )
92
+ torch.manual_seed(0)
93
+ text_encoder_config = CLIPTextConfig(
94
+ bos_token_id=0,
95
+ eos_token_id=2,
96
+ hidden_size=4,
97
+ intermediate_size=16,
98
+ layer_norm_eps=1e-05,
99
+ num_attention_heads=2,
100
+ num_hidden_layers=2,
101
+ pad_token_id=1,
102
+ vocab_size=1000,
103
+ hidden_act="gelu",
104
+ projection_dim=32,
105
+ )
106
+ text_encoder = CLIPTextModel(text_encoder_config)
107
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
108
+
109
+ components = {
110
+ "unet": unet,
111
+ "scheduler": scheduler,
112
+ "vae": vae,
113
+ "text_encoder": text_encoder,
114
+ "tokenizer": tokenizer,
115
+ }
116
+ return components
117
+
118
+ def get_dummy_inputs(self, device, seed=0):
119
+ if str(device).startswith("mps"):
120
+ generator = torch.manual_seed(seed)
121
+ else:
122
+ generator = torch.Generator(device=device).manual_seed(seed)
123
+ inputs = {
124
+ "prompt": "A painting of a squirrel eating a burger",
125
+ "generator": generator,
126
+ "num_inference_steps": 2,
127
+ "guidance_scale": 6.0,
128
+ "output_type": "pt",
129
+ }
130
+ return inputs
131
+
132
+ def test_dict_tuple_outputs_equivalent(self):
133
+ return super().test_dict_tuple_outputs_equivalent()
134
+
135
+ def test_text_to_video_default_case(self):
136
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
137
+ components = self.get_dummy_components()
138
+ sd_pipe = TextToVideoSDPipeline(**components)
139
+ sd_pipe = sd_pipe.to(device)
140
+ sd_pipe.set_progress_bar_config(disable=None)
141
+
142
+ inputs = self.get_dummy_inputs(device)
143
+ inputs["output_type"] = "np"
144
+ frames = sd_pipe(**inputs).frames
145
+
146
+ image_slice = frames[0][0][-3:, -3:, -1]
147
+ assert frames[0][0].shape == (32, 32, 3)
148
+ expected_slice = np.array([0.8093, 0.2751, 0.6976, 0.5927, 0.4616, 0.4336, 0.5094, 0.5683, 0.4796])
149
+
150
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
151
+
152
+ @unittest.skipIf(torch_device != "cuda", reason="Feature isn't heavily used. Test in CUDA environment only.")
153
+ def test_attention_slicing_forward_pass(self):
154
+ self._test_attention_slicing_forward_pass(test_mean_pixel_difference=False, expected_max_diff=3e-3)
155
+
156
+ @unittest.skipIf(
157
+ torch_device != "cuda" or not is_xformers_available(),
158
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
159
+ )
160
+ def test_xformers_attention_forwardGenerator_pass(self):
161
+ self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=False, expected_max_diff=1e-2)
162
+
163
+ # (todo): sayakpaul
164
+ @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
165
+ def test_inference_batch_consistent(self):
166
+ pass
167
+
168
+ # (todo): sayakpaul
169
+ @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
170
+ def test_inference_batch_single_identical(self):
171
+ pass
172
+
173
+ @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline.")
174
+ def test_num_images_per_prompt(self):
175
+ pass
176
+
177
+ def test_encode_prompt_works_in_isolation(self):
178
+ extra_required_param_value_dict = {
179
+ "device": torch.device(torch_device).type,
180
+ "num_images_per_prompt": 1,
181
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
182
+ }
183
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
184
+
185
+
186
+ @slow
187
+ @skip_mps
188
+ @require_torch_accelerator
189
+ class TextToVideoSDPipelineSlowTests(unittest.TestCase):
190
+ def setUp(self):
191
+ # clean up the VRAM before each test
192
+ super().setUp()
193
+ gc.collect()
194
+ backend_empty_cache(torch_device)
195
+
196
+ def tearDown(self):
197
+ # clean up the VRAM after each test
198
+ super().tearDown()
199
+ gc.collect()
200
+ backend_empty_cache(torch_device)
201
+
202
+ def test_two_step_model(self):
203
+ expected_video = load_numpy(
204
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text-to-video/video_2step.npy"
205
+ )
206
+
207
+ pipe = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b")
208
+ pipe = pipe.to(torch_device)
209
+
210
+ prompt = "Spiderman is surfing"
211
+ generator = torch.Generator(device="cpu").manual_seed(0)
212
+
213
+ video_frames = pipe(prompt, generator=generator, num_inference_steps=2, output_type="np").frames
214
+ assert numpy_cosine_similarity_distance(expected_video.flatten(), video_frames.flatten()) < 1e-4
215
+
216
+ def test_two_step_model_with_freeu(self):
217
+ expected_video = []
218
+
219
+ pipe = TextToVideoSDPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b")
220
+ pipe = pipe.to(torch_device)
221
+
222
+ prompt = "Spiderman is surfing"
223
+ generator = torch.Generator(device="cpu").manual_seed(0)
224
+
225
+ pipe.enable_freeu(s1=0.9, s2=0.2, b1=1.2, b2=1.4)
226
+ video_frames = pipe(prompt, generator=generator, num_inference_steps=2, output_type="np").frames
227
+ video = video_frames[0, 0, -3:, -3:, -1].flatten()
228
+
229
+ expected_video = [0.3643, 0.3455, 0.3831, 0.3923, 0.2978, 0.3247, 0.3278, 0.3201, 0.3475]
230
+
231
+ assert np.abs(expected_video - video).mean() < 5e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video_zero.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 torch
20
+
21
+ from diffusers import DDIMScheduler, TextToVideoZeroPipeline
22
+ from diffusers.utils.testing_utils import (
23
+ backend_empty_cache,
24
+ load_pt,
25
+ nightly,
26
+ require_torch_accelerator,
27
+ torch_device,
28
+ )
29
+
30
+ from ..test_pipelines_common import assert_mean_pixel_difference
31
+
32
+
33
+ @nightly
34
+ @require_torch_accelerator
35
+ class TextToVideoZeroPipelineSlowTests(unittest.TestCase):
36
+ def setUp(self):
37
+ # clean up the VRAM before each test
38
+ super().setUp()
39
+ gc.collect()
40
+ backend_empty_cache(torch_device)
41
+
42
+ def tearDown(self):
43
+ # clean up the VRAM after each test
44
+ super().tearDown()
45
+ gc.collect()
46
+ backend_empty_cache(torch_device)
47
+
48
+ def test_full_model(self):
49
+ model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
50
+ pipe = TextToVideoZeroPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to(torch_device)
51
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
52
+ generator = torch.Generator(device="cpu").manual_seed(0)
53
+
54
+ prompt = "A bear is playing a guitar on Times Square"
55
+ result = pipe(prompt=prompt, generator=generator).images
56
+
57
+ expected_result = load_pt(
58
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text-to-video/A bear is playing a guitar on Times Square.pt",
59
+ weights_only=False,
60
+ )
61
+
62
+ assert_mean_pixel_difference(result, expected_result)
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_text_to_video_zero_sdxl.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 inspect
18
+ import tempfile
19
+ import unittest
20
+
21
+ import numpy as np
22
+ import torch
23
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
24
+
25
+ from diffusers import AutoencoderKL, DDIMScheduler, TextToVideoZeroSDXLPipeline, UNet2DConditionModel
26
+ from diffusers.utils.testing_utils import (
27
+ backend_empty_cache,
28
+ enable_full_determinism,
29
+ nightly,
30
+ require_accelerate_version_greater,
31
+ require_torch_accelerator,
32
+ torch_device,
33
+ )
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 PipelineFromPipeTesterMixin, PipelineTesterMixin
37
+
38
+
39
+ enable_full_determinism()
40
+
41
+
42
+ def to_np(tensor):
43
+ if isinstance(tensor, torch.Tensor):
44
+ tensor = tensor.detach().cpu().numpy()
45
+
46
+ return tensor
47
+
48
+
49
+ class TextToVideoZeroSDXLPipelineFastTests(PipelineTesterMixin, PipelineFromPipeTesterMixin, unittest.TestCase):
50
+ pipeline_class = TextToVideoZeroSDXLPipeline
51
+ params = TEXT_TO_IMAGE_PARAMS
52
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
53
+ image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
54
+ image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
55
+ generator_device = "cpu"
56
+
57
+ def get_dummy_components(self, seed=0):
58
+ torch.manual_seed(seed)
59
+ unet = UNet2DConditionModel(
60
+ block_out_channels=(2, 4),
61
+ layers_per_block=2,
62
+ sample_size=2,
63
+ norm_num_groups=2,
64
+ in_channels=4,
65
+ out_channels=4,
66
+ down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
67
+ up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
68
+ # SD2-specific config below
69
+ attention_head_dim=(2, 4),
70
+ use_linear_projection=True,
71
+ addition_embed_type="text_time",
72
+ addition_time_embed_dim=8,
73
+ transformer_layers_per_block=(1, 2),
74
+ projection_class_embeddings_input_dim=80, # 6 * 8 + 32
75
+ cross_attention_dim=64,
76
+ )
77
+ scheduler = DDIMScheduler(
78
+ num_train_timesteps=1000,
79
+ beta_start=0.0001,
80
+ beta_end=0.02,
81
+ beta_schedule="linear",
82
+ trained_betas=None,
83
+ clip_sample=True,
84
+ set_alpha_to_one=True,
85
+ steps_offset=0,
86
+ prediction_type="epsilon",
87
+ thresholding=False,
88
+ dynamic_thresholding_ratio=0.995,
89
+ clip_sample_range=1.0,
90
+ sample_max_value=1.0,
91
+ timestep_spacing="leading",
92
+ rescale_betas_zero_snr=False,
93
+ )
94
+ torch.manual_seed(seed)
95
+ vae = AutoencoderKL(
96
+ block_out_channels=[32, 64],
97
+ in_channels=3,
98
+ out_channels=3,
99
+ down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
100
+ up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
101
+ latent_channels=4,
102
+ sample_size=128,
103
+ )
104
+ torch.manual_seed(seed)
105
+ text_encoder_config = CLIPTextConfig(
106
+ bos_token_id=0,
107
+ eos_token_id=2,
108
+ hidden_size=32,
109
+ intermediate_size=37,
110
+ layer_norm_eps=1e-05,
111
+ num_attention_heads=4,
112
+ num_hidden_layers=5,
113
+ pad_token_id=1,
114
+ vocab_size=1000,
115
+ # SD2-specific config below
116
+ hidden_act="gelu",
117
+ projection_dim=32,
118
+ )
119
+ text_encoder = CLIPTextModel(text_encoder_config)
120
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
121
+
122
+ text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
123
+ tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
124
+
125
+ components = {
126
+ "unet": unet,
127
+ "scheduler": scheduler,
128
+ "vae": vae,
129
+ "text_encoder": text_encoder,
130
+ "tokenizer": tokenizer,
131
+ "text_encoder_2": text_encoder_2,
132
+ "tokenizer_2": tokenizer_2,
133
+ "image_encoder": None,
134
+ "feature_extractor": None,
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
+ inputs = {
144
+ "prompt": "A panda dancing in Antarctica",
145
+ "generator": generator,
146
+ "num_inference_steps": 5,
147
+ "t0": 1,
148
+ "t1": 3,
149
+ "height": 64,
150
+ "width": 64,
151
+ "video_length": 3,
152
+ "output_type": "np",
153
+ }
154
+ return inputs
155
+
156
+ def get_generator(self, device, seed=0):
157
+ if str(device).startswith("mps"):
158
+ generator = torch.manual_seed(seed)
159
+ else:
160
+ generator = torch.Generator(device=device).manual_seed(seed)
161
+ return generator
162
+
163
+ def test_text_to_video_zero_sdxl(self):
164
+ components = self.get_dummy_components()
165
+ pipe = self.pipeline_class(**components)
166
+ pipe = pipe.to(torch_device)
167
+
168
+ inputs = self.get_dummy_inputs(self.generator_device)
169
+ result = pipe(**inputs).images
170
+
171
+ first_frame_slice = result[0, -3:, -3:, -1]
172
+ last_frame_slice = result[-1, -3:, -3:, 0]
173
+
174
+ expected_slice1 = np.array(
175
+ [0.6008109, 0.73051643, 0.51778656, 0.55817354, 0.45222935, 0.45998418, 0.57017255, 0.54874814, 0.47078788]
176
+ )
177
+ expected_slice2 = np.array(
178
+ [0.6011751, 0.47420046, 0.41660714, 0.6472957, 0.41261768, 0.5438129, 0.7401535, 0.6756011, 0.53652245]
179
+ )
180
+
181
+ assert np.abs(first_frame_slice.flatten() - expected_slice1).max() < 1e-2
182
+ assert np.abs(last_frame_slice.flatten() - expected_slice2).max() < 1e-2
183
+
184
+ @unittest.skip(
185
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
186
+ )
187
+ def test_attention_slicing_forward_pass(self):
188
+ pass
189
+
190
+ def test_cfg(self):
191
+ sig = inspect.signature(self.pipeline_class.__call__)
192
+ if "guidance_scale" not in sig.parameters:
193
+ return
194
+ components = self.get_dummy_components()
195
+
196
+ pipe = self.pipeline_class(**components)
197
+ pipe = pipe.to(torch_device)
198
+ pipe.set_progress_bar_config(disable=None)
199
+
200
+ inputs = self.get_dummy_inputs(self.generator_device)
201
+
202
+ inputs["guidance_scale"] = 1.0
203
+ out_no_cfg = pipe(**inputs)[0]
204
+
205
+ inputs["guidance_scale"] = 7.5
206
+ out_cfg = pipe(**inputs)[0]
207
+
208
+ assert out_cfg.shape == out_no_cfg.shape
209
+
210
+ def test_dict_tuple_outputs_equivalent(self, expected_max_difference=1e-4):
211
+ components = self.get_dummy_components()
212
+ pipe = self.pipeline_class(**components)
213
+ pipe.to(torch_device)
214
+ pipe.set_progress_bar_config(disable=None)
215
+
216
+ output = pipe(**self.get_dummy_inputs(self.generator_device))[0]
217
+ output_tuple = pipe(**self.get_dummy_inputs(self.generator_device), return_dict=False)[0]
218
+
219
+ max_diff = np.abs(to_np(output) - to_np(output_tuple)).max()
220
+ self.assertLess(max_diff, expected_max_difference)
221
+
222
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
223
+ @require_torch_accelerator
224
+ def test_float16_inference(self, expected_max_diff=5e-2):
225
+ components = self.get_dummy_components()
226
+ for name, module in components.items():
227
+ if hasattr(module, "half"):
228
+ components[name] = module.to(torch_device).half()
229
+ pipe = self.pipeline_class(**components)
230
+ pipe.to(torch_device)
231
+ pipe.set_progress_bar_config(disable=None)
232
+
233
+ components = self.get_dummy_components()
234
+ pipe_fp16 = self.pipeline_class(**components)
235
+ pipe_fp16.to(torch_device, torch.float16)
236
+ pipe_fp16.set_progress_bar_config(disable=None)
237
+
238
+ inputs = self.get_dummy_inputs(self.generator_device)
239
+ # # Reset generator in case it is used inside dummy inputs
240
+ if "generator" in inputs:
241
+ inputs["generator"] = self.get_generator(self.generator_device)
242
+
243
+ output = pipe(**inputs)[0]
244
+
245
+ fp16_inputs = self.get_dummy_inputs(self.generator_device)
246
+ # Reset generator in case it is used inside dummy inputs
247
+ if "generator" in fp16_inputs:
248
+ fp16_inputs["generator"] = self.get_generator(self.generator_device)
249
+
250
+ output_fp16 = pipe_fp16(**fp16_inputs)[0]
251
+
252
+ max_diff = np.abs(to_np(output) - to_np(output_fp16)).max()
253
+ self.assertLess(max_diff, expected_max_diff, "The outputs of the fp16 and fp32 pipelines are too different.")
254
+
255
+ @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
256
+ def test_inference_batch_consistent(self):
257
+ pass
258
+
259
+ @unittest.skip(
260
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
261
+ )
262
+ def test_inference_batch_single_identical(self):
263
+ pass
264
+
265
+ @require_torch_accelerator
266
+ @require_accelerate_version_greater("0.17.0")
267
+ def test_model_cpu_offload_forward_pass(self, expected_max_diff=2e-4):
268
+ components = self.get_dummy_components()
269
+ pipe = self.pipeline_class(**components)
270
+ pipe = pipe.to(torch_device)
271
+ pipe.set_progress_bar_config(disable=None)
272
+
273
+ inputs = self.get_dummy_inputs(self.generator_device)
274
+ output_without_offload = pipe(**inputs)[0]
275
+
276
+ pipe.enable_model_cpu_offload(device=torch_device)
277
+ inputs = self.get_dummy_inputs(self.generator_device)
278
+ output_with_offload = pipe(**inputs)[0]
279
+
280
+ max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
281
+ self.assertLess(max_diff, expected_max_diff, "CPU offloading should not affect the inference results")
282
+
283
+ @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline.")
284
+ def test_pipeline_call_signature(self):
285
+ pass
286
+
287
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
288
+ @require_torch_accelerator
289
+ def test_save_load_float16(self, expected_max_diff=1e-2):
290
+ components = self.get_dummy_components()
291
+ for name, module in components.items():
292
+ if hasattr(module, "half"):
293
+ components[name] = module.to(torch_device).half()
294
+
295
+ pipe = self.pipeline_class(**components)
296
+ pipe.to(torch_device)
297
+ pipe.set_progress_bar_config(disable=None)
298
+
299
+ inputs = self.get_dummy_inputs(self.generator_device)
300
+ output = pipe(**inputs)[0]
301
+
302
+ with tempfile.TemporaryDirectory() as tmpdir:
303
+ pipe.save_pretrained(tmpdir)
304
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16)
305
+ pipe_loaded.to(torch_device)
306
+ pipe_loaded.set_progress_bar_config(disable=None)
307
+
308
+ for name, component in pipe_loaded.components.items():
309
+ if hasattr(component, "dtype"):
310
+ self.assertTrue(
311
+ component.dtype == torch.float16,
312
+ f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
313
+ )
314
+
315
+ inputs = self.get_dummy_inputs(self.generator_device)
316
+ output_loaded = pipe_loaded(**inputs)[0]
317
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
318
+ self.assertLess(
319
+ max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
320
+ )
321
+
322
+ @unittest.skip(
323
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
324
+ )
325
+ def test_save_load_local(self):
326
+ pass
327
+
328
+ @unittest.skip(
329
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
330
+ )
331
+ def test_save_load_optional_components(self):
332
+ pass
333
+
334
+ @unittest.skip(
335
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
336
+ )
337
+ def test_sequential_cpu_offload_forward_pass(self):
338
+ pass
339
+
340
+ @require_torch_accelerator
341
+ def test_to_device(self):
342
+ components = self.get_dummy_components()
343
+ pipe = self.pipeline_class(**components)
344
+ pipe.set_progress_bar_config(disable=None)
345
+
346
+ pipe.to("cpu")
347
+ model_devices = [component.device.type for component in components.values() if hasattr(component, "device")]
348
+ self.assertTrue(all(device == "cpu" for device in model_devices))
349
+
350
+ output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0] # generator set to cpu
351
+ self.assertTrue(np.isnan(output_cpu).sum() == 0)
352
+
353
+ pipe.to(torch_device)
354
+ model_devices = [component.device.type for component in components.values() if hasattr(component, "device")]
355
+ self.assertTrue(all(device == torch_device for device in model_devices))
356
+
357
+ output_device = pipe(**self.get_dummy_inputs("cpu"))[0] # generator set to cpu
358
+ self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
359
+
360
+ @unittest.skip(
361
+ reason="Cannot call `set_default_attn_processor` as this pipeline uses a specific attention processor."
362
+ )
363
+ def test_xformers_attention_forwardGenerator_pass(self):
364
+ pass
365
+
366
+
367
+ @nightly
368
+ @require_torch_accelerator
369
+ class TextToVideoZeroSDXLPipelineSlowTests(unittest.TestCase):
370
+ def setUp(self):
371
+ # clean up the VRAM before each test
372
+ super().setUp()
373
+ gc.collect()
374
+ backend_empty_cache(torch_device)
375
+
376
+ def tearDown(self):
377
+ # clean up the VRAM after each test
378
+ super().tearDown()
379
+ gc.collect()
380
+ backend_empty_cache(torch_device)
381
+
382
+ def test_full_model(self):
383
+ model_id = "stabilityai/stable-diffusion-xl-base-1.0"
384
+ pipe = TextToVideoZeroSDXLPipeline.from_pretrained(
385
+ model_id, torch_dtype=torch.float16, variant="fp16", use_safetensors=True
386
+ )
387
+ pipe.enable_model_cpu_offload()
388
+ pipe.enable_vae_slicing()
389
+
390
+ pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
391
+ generator = torch.Generator(device="cpu").manual_seed(0)
392
+
393
+ prompt = "A panda dancing in Antarctica"
394
+ result = pipe(prompt=prompt, generator=generator).images
395
+
396
+ first_frame_slice = result[0, -3:, -3:, -1]
397
+ last_frame_slice = result[-1, -3:, -3:, 0]
398
+
399
+ expected_slice1 = np.array([0.57, 0.57, 0.57, 0.57, 0.57, 0.56, 0.55, 0.56, 0.56])
400
+ expected_slice2 = np.array([0.54, 0.53, 0.53, 0.53, 0.53, 0.52, 0.53, 0.53, 0.53])
401
+
402
+ assert np.abs(first_frame_slice.flatten() - expected_slice1).max() < 1e-2
403
+ assert np.abs(last_frame_slice.flatten() - expected_slice2).max() < 1e-2
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/text_to_video_synthesis/test_video_to_video.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 random
17
+ import unittest
18
+
19
+ import numpy as np
20
+ import torch
21
+ from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers import (
24
+ AutoencoderKL,
25
+ DDIMScheduler,
26
+ UNet3DConditionModel,
27
+ VideoToVideoSDPipeline,
28
+ )
29
+ from diffusers.utils import is_xformers_available
30
+ from diffusers.utils.testing_utils import (
31
+ enable_full_determinism,
32
+ floats_tensor,
33
+ is_flaky,
34
+ nightly,
35
+ numpy_cosine_similarity_distance,
36
+ skip_mps,
37
+ torch_device,
38
+ )
39
+
40
+ from ..pipeline_params import (
41
+ TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
42
+ TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
43
+ )
44
+ from ..test_pipelines_common import PipelineTesterMixin
45
+
46
+
47
+ enable_full_determinism()
48
+
49
+
50
+ @skip_mps
51
+ class VideoToVideoSDPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
52
+ pipeline_class = VideoToVideoSDPipeline
53
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}) - {"image", "width", "height"}
54
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}) - {"image"}
55
+ required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
56
+ test_attention_slicing = False
57
+
58
+ # No `output_type`.
59
+ required_optional_params = frozenset(
60
+ [
61
+ "num_inference_steps",
62
+ "generator",
63
+ "latents",
64
+ "return_dict",
65
+ "callback",
66
+ "callback_steps",
67
+ ]
68
+ )
69
+
70
+ def get_dummy_components(self):
71
+ torch.manual_seed(0)
72
+ unet = UNet3DConditionModel(
73
+ block_out_channels=(4, 8),
74
+ layers_per_block=1,
75
+ sample_size=32,
76
+ in_channels=4,
77
+ out_channels=4,
78
+ down_block_types=("CrossAttnDownBlock3D", "DownBlock3D"),
79
+ up_block_types=("UpBlock3D", "CrossAttnUpBlock3D"),
80
+ cross_attention_dim=32,
81
+ attention_head_dim=4,
82
+ norm_num_groups=2,
83
+ )
84
+ scheduler = DDIMScheduler(
85
+ beta_start=0.00085,
86
+ beta_end=0.012,
87
+ beta_schedule="scaled_linear",
88
+ clip_sample=True,
89
+ set_alpha_to_one=False,
90
+ )
91
+ torch.manual_seed(0)
92
+ vae = AutoencoderKL(
93
+ block_out_channels=[
94
+ 8,
95
+ ],
96
+ in_channels=3,
97
+ out_channels=3,
98
+ down_block_types=[
99
+ "DownEncoderBlock2D",
100
+ ],
101
+ up_block_types=["UpDecoderBlock2D"],
102
+ latent_channels=4,
103
+ sample_size=32,
104
+ norm_num_groups=2,
105
+ )
106
+ torch.manual_seed(0)
107
+ text_encoder_config = CLIPTextConfig(
108
+ bos_token_id=0,
109
+ eos_token_id=2,
110
+ hidden_size=32,
111
+ intermediate_size=37,
112
+ layer_norm_eps=1e-05,
113
+ num_attention_heads=4,
114
+ num_hidden_layers=5,
115
+ pad_token_id=1,
116
+ vocab_size=1000,
117
+ hidden_act="gelu",
118
+ projection_dim=512,
119
+ )
120
+ text_encoder = CLIPTextModel(text_encoder_config)
121
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
122
+
123
+ components = {
124
+ "unet": unet,
125
+ "scheduler": scheduler,
126
+ "vae": vae,
127
+ "text_encoder": text_encoder,
128
+ "tokenizer": tokenizer,
129
+ }
130
+ return components
131
+
132
+ def get_dummy_inputs(self, device, seed=0):
133
+ # 3 frames
134
+ video = floats_tensor((1, 3, 3, 32, 32), rng=random.Random(seed)).to(device)
135
+
136
+ if str(device).startswith("mps"):
137
+ generator = torch.manual_seed(seed)
138
+ else:
139
+ generator = torch.Generator(device=device).manual_seed(seed)
140
+ inputs = {
141
+ "prompt": "A painting of a squirrel eating a burger",
142
+ "video": video,
143
+ "generator": generator,
144
+ "num_inference_steps": 2,
145
+ "guidance_scale": 6.0,
146
+ "output_type": "pt",
147
+ }
148
+ return inputs
149
+
150
+ def test_text_to_video_default_case(self):
151
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
152
+ components = self.get_dummy_components()
153
+ sd_pipe = VideoToVideoSDPipeline(**components)
154
+ sd_pipe = sd_pipe.to(device)
155
+ sd_pipe.set_progress_bar_config(disable=None)
156
+
157
+ inputs = self.get_dummy_inputs(device)
158
+ inputs["output_type"] = "np"
159
+ frames = sd_pipe(**inputs).frames
160
+ image_slice = frames[0][0][-3:, -3:, -1]
161
+
162
+ assert frames[0][0].shape == (32, 32, 3)
163
+ expected_slice = np.array([0.6391, 0.5350, 0.5202, 0.5521, 0.5453, 0.5393, 0.6652, 0.5270, 0.5185])
164
+
165
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
166
+
167
+ @is_flaky()
168
+ def test_save_load_optional_components(self):
169
+ super().test_save_load_optional_components(expected_max_difference=0.001)
170
+
171
+ @is_flaky()
172
+ def test_dict_tuple_outputs_equivalent(self):
173
+ super().test_dict_tuple_outputs_equivalent()
174
+
175
+ @is_flaky()
176
+ def test_save_load_local(self):
177
+ super().test_save_load_local()
178
+
179
+ @unittest.skipIf(
180
+ torch_device != "cuda" or not is_xformers_available(),
181
+ reason="XFormers attention is only available with CUDA and `xformers` installed",
182
+ )
183
+ def test_xformers_attention_forwardGenerator_pass(self):
184
+ self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=False, expected_max_diff=5e-3)
185
+
186
+ # (todo): sayakpaul
187
+ @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
188
+ def test_inference_batch_consistent(self):
189
+ pass
190
+
191
+ # (todo): sayakpaul
192
+ @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline.")
193
+ def test_inference_batch_single_identical(self):
194
+ pass
195
+
196
+ @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline.")
197
+ def test_num_images_per_prompt(self):
198
+ pass
199
+
200
+ def test_encode_prompt_works_in_isolation(self):
201
+ extra_required_param_value_dict = {
202
+ "device": torch.device(torch_device).type,
203
+ "num_images_per_prompt": 1,
204
+ "do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
205
+ }
206
+ return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
207
+
208
+
209
+ @nightly
210
+ @skip_mps
211
+ class VideoToVideoSDPipelineSlowTests(unittest.TestCase):
212
+ def test_two_step_model(self):
213
+ pipe = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_576w", torch_dtype=torch.float16)
214
+ pipe.enable_model_cpu_offload()
215
+
216
+ # 10 frames
217
+ generator = torch.Generator(device="cpu").manual_seed(0)
218
+ video = torch.randn((1, 10, 3, 320, 576), generator=generator)
219
+
220
+ prompt = "Spiderman is surfing"
221
+
222
+ generator = torch.Generator(device="cpu").manual_seed(0)
223
+ video_frames = pipe(prompt, video=video, generator=generator, num_inference_steps=3, output_type="np").frames
224
+
225
+ expected_array = np.array(
226
+ [0.17114258, 0.13720703, 0.08886719, 0.14819336, 0.1730957, 0.24584961, 0.22021484, 0.35180664, 0.2607422]
227
+ )
228
+ output_array = video_frames[0, 0, :3, :3, 0].flatten()
229
+ assert numpy_cosine_similarity_distance(expected_array, output_array) < 1e-3
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/test_unclip.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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
+ from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer
22
+
23
+ from diffusers import PriorTransformer, UnCLIPPipeline, UnCLIPScheduler, UNet2DConditionModel, UNet2DModel
24
+ from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
25
+ from diffusers.utils.testing_utils import (
26
+ backend_empty_cache,
27
+ backend_max_memory_allocated,
28
+ backend_reset_max_memory_allocated,
29
+ backend_reset_peak_memory_stats,
30
+ enable_full_determinism,
31
+ load_numpy,
32
+ nightly,
33
+ require_torch_accelerator,
34
+ skip_mps,
35
+ torch_device,
36
+ )
37
+
38
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
39
+ from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
40
+
41
+
42
+ enable_full_determinism()
43
+
44
+
45
+ class UnCLIPPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
46
+ pipeline_class = UnCLIPPipeline
47
+ params = TEXT_TO_IMAGE_PARAMS - {
48
+ "negative_prompt",
49
+ "height",
50
+ "width",
51
+ "negative_prompt_embeds",
52
+ "guidance_scale",
53
+ "prompt_embeds",
54
+ "cross_attention_kwargs",
55
+ }
56
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
57
+ required_optional_params = [
58
+ "generator",
59
+ "return_dict",
60
+ "prior_num_inference_steps",
61
+ "decoder_num_inference_steps",
62
+ "super_res_num_inference_steps",
63
+ ]
64
+ test_xformers_attention = False
65
+
66
+ @property
67
+ def text_embedder_hidden_size(self):
68
+ return 32
69
+
70
+ @property
71
+ def time_input_dim(self):
72
+ return 32
73
+
74
+ @property
75
+ def block_out_channels_0(self):
76
+ return self.time_input_dim
77
+
78
+ @property
79
+ def time_embed_dim(self):
80
+ return self.time_input_dim * 4
81
+
82
+ @property
83
+ def cross_attention_dim(self):
84
+ return 100
85
+
86
+ @property
87
+ def dummy_tokenizer(self):
88
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
89
+ return tokenizer
90
+
91
+ @property
92
+ def dummy_text_encoder(self):
93
+ torch.manual_seed(0)
94
+ config = CLIPTextConfig(
95
+ bos_token_id=0,
96
+ eos_token_id=2,
97
+ hidden_size=self.text_embedder_hidden_size,
98
+ projection_dim=self.text_embedder_hidden_size,
99
+ intermediate_size=37,
100
+ layer_norm_eps=1e-05,
101
+ num_attention_heads=4,
102
+ num_hidden_layers=5,
103
+ pad_token_id=1,
104
+ vocab_size=1000,
105
+ )
106
+ return CLIPTextModelWithProjection(config)
107
+
108
+ @property
109
+ def dummy_prior(self):
110
+ torch.manual_seed(0)
111
+
112
+ model_kwargs = {
113
+ "num_attention_heads": 2,
114
+ "attention_head_dim": 12,
115
+ "embedding_dim": self.text_embedder_hidden_size,
116
+ "num_layers": 1,
117
+ }
118
+
119
+ model = PriorTransformer(**model_kwargs)
120
+ return model
121
+
122
+ @property
123
+ def dummy_text_proj(self):
124
+ torch.manual_seed(0)
125
+
126
+ model_kwargs = {
127
+ "clip_embeddings_dim": self.text_embedder_hidden_size,
128
+ "time_embed_dim": self.time_embed_dim,
129
+ "cross_attention_dim": self.cross_attention_dim,
130
+ }
131
+
132
+ model = UnCLIPTextProjModel(**model_kwargs)
133
+ return model
134
+
135
+ @property
136
+ def dummy_decoder(self):
137
+ torch.manual_seed(0)
138
+
139
+ model_kwargs = {
140
+ "sample_size": 32,
141
+ # RGB in channels
142
+ "in_channels": 3,
143
+ # Out channels is double in channels because predicts mean and variance
144
+ "out_channels": 6,
145
+ "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
146
+ "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
147
+ "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
148
+ "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
149
+ "layers_per_block": 1,
150
+ "cross_attention_dim": self.cross_attention_dim,
151
+ "attention_head_dim": 4,
152
+ "resnet_time_scale_shift": "scale_shift",
153
+ "class_embed_type": "identity",
154
+ }
155
+
156
+ model = UNet2DConditionModel(**model_kwargs)
157
+ return model
158
+
159
+ @property
160
+ def dummy_super_res_kwargs(self):
161
+ return {
162
+ "sample_size": 64,
163
+ "layers_per_block": 1,
164
+ "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
165
+ "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
166
+ "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
167
+ "in_channels": 6,
168
+ "out_channels": 3,
169
+ }
170
+
171
+ @property
172
+ def dummy_super_res_first(self):
173
+ torch.manual_seed(0)
174
+
175
+ model = UNet2DModel(**self.dummy_super_res_kwargs)
176
+ return model
177
+
178
+ @property
179
+ def dummy_super_res_last(self):
180
+ # seeded differently to get different unet than `self.dummy_super_res_first`
181
+ torch.manual_seed(1)
182
+
183
+ model = UNet2DModel(**self.dummy_super_res_kwargs)
184
+ return model
185
+
186
+ def get_dummy_components(self):
187
+ prior = self.dummy_prior
188
+ decoder = self.dummy_decoder
189
+ text_proj = self.dummy_text_proj
190
+ text_encoder = self.dummy_text_encoder
191
+ tokenizer = self.dummy_tokenizer
192
+ super_res_first = self.dummy_super_res_first
193
+ super_res_last = self.dummy_super_res_last
194
+
195
+ prior_scheduler = UnCLIPScheduler(
196
+ variance_type="fixed_small_log",
197
+ prediction_type="sample",
198
+ num_train_timesteps=1000,
199
+ clip_sample_range=5.0,
200
+ )
201
+
202
+ decoder_scheduler = UnCLIPScheduler(
203
+ variance_type="learned_range",
204
+ prediction_type="epsilon",
205
+ num_train_timesteps=1000,
206
+ )
207
+
208
+ super_res_scheduler = UnCLIPScheduler(
209
+ variance_type="fixed_small_log",
210
+ prediction_type="epsilon",
211
+ num_train_timesteps=1000,
212
+ )
213
+
214
+ components = {
215
+ "prior": prior,
216
+ "decoder": decoder,
217
+ "text_proj": text_proj,
218
+ "text_encoder": text_encoder,
219
+ "tokenizer": tokenizer,
220
+ "super_res_first": super_res_first,
221
+ "super_res_last": super_res_last,
222
+ "prior_scheduler": prior_scheduler,
223
+ "decoder_scheduler": decoder_scheduler,
224
+ "super_res_scheduler": super_res_scheduler,
225
+ }
226
+
227
+ return components
228
+
229
+ def get_dummy_inputs(self, device, seed=0):
230
+ if str(device).startswith("mps"):
231
+ generator = torch.manual_seed(seed)
232
+ else:
233
+ generator = torch.Generator(device=device).manual_seed(seed)
234
+ inputs = {
235
+ "prompt": "horse",
236
+ "generator": generator,
237
+ "prior_num_inference_steps": 2,
238
+ "decoder_num_inference_steps": 2,
239
+ "super_res_num_inference_steps": 2,
240
+ "output_type": "np",
241
+ }
242
+ return inputs
243
+
244
+ def test_unclip(self):
245
+ device = "cpu"
246
+
247
+ components = self.get_dummy_components()
248
+
249
+ pipe = self.pipeline_class(**components)
250
+ pipe = pipe.to(device)
251
+
252
+ pipe.set_progress_bar_config(disable=None)
253
+
254
+ output = pipe(**self.get_dummy_inputs(device))
255
+ image = output.images
256
+
257
+ image_from_tuple = pipe(
258
+ **self.get_dummy_inputs(device),
259
+ return_dict=False,
260
+ )[0]
261
+
262
+ image_slice = image[0, -3:, -3:, -1]
263
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
264
+
265
+ assert image.shape == (1, 64, 64, 3)
266
+
267
+ expected_slice = np.array(
268
+ [
269
+ 0.9997,
270
+ 0.9988,
271
+ 0.0028,
272
+ 0.9997,
273
+ 0.9984,
274
+ 0.9965,
275
+ 0.0029,
276
+ 0.9986,
277
+ 0.0025,
278
+ ]
279
+ )
280
+
281
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
282
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
283
+
284
+ def test_unclip_passed_text_embed(self):
285
+ device = torch.device("cpu")
286
+
287
+ class DummyScheduler:
288
+ init_noise_sigma = 1
289
+
290
+ components = self.get_dummy_components()
291
+
292
+ pipe = self.pipeline_class(**components)
293
+ pipe = pipe.to(device)
294
+
295
+ prior = components["prior"]
296
+ decoder = components["decoder"]
297
+ super_res_first = components["super_res_first"]
298
+ tokenizer = components["tokenizer"]
299
+ text_encoder = components["text_encoder"]
300
+
301
+ generator = torch.Generator(device=device).manual_seed(0)
302
+ dtype = prior.dtype
303
+ batch_size = 1
304
+
305
+ shape = (batch_size, prior.config.embedding_dim)
306
+ prior_latents = pipe.prepare_latents(
307
+ shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
308
+ )
309
+ shape = (batch_size, decoder.config.in_channels, decoder.config.sample_size, decoder.config.sample_size)
310
+ generator = torch.Generator(device=device).manual_seed(0)
311
+ decoder_latents = pipe.prepare_latents(
312
+ shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
313
+ )
314
+
315
+ shape = (
316
+ batch_size,
317
+ super_res_first.config.in_channels // 2,
318
+ super_res_first.config.sample_size,
319
+ super_res_first.config.sample_size,
320
+ )
321
+ super_res_latents = pipe.prepare_latents(
322
+ shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
323
+ )
324
+
325
+ pipe.set_progress_bar_config(disable=None)
326
+
327
+ prompt = "this is a prompt example"
328
+
329
+ generator = torch.Generator(device=device).manual_seed(0)
330
+ output = pipe(
331
+ [prompt],
332
+ generator=generator,
333
+ prior_num_inference_steps=2,
334
+ decoder_num_inference_steps=2,
335
+ super_res_num_inference_steps=2,
336
+ prior_latents=prior_latents,
337
+ decoder_latents=decoder_latents,
338
+ super_res_latents=super_res_latents,
339
+ output_type="np",
340
+ )
341
+ image = output.images
342
+
343
+ text_inputs = tokenizer(
344
+ prompt,
345
+ padding="max_length",
346
+ max_length=tokenizer.model_max_length,
347
+ return_tensors="pt",
348
+ )
349
+ text_model_output = text_encoder(text_inputs.input_ids)
350
+ text_attention_mask = text_inputs.attention_mask
351
+
352
+ generator = torch.Generator(device=device).manual_seed(0)
353
+ image_from_text = pipe(
354
+ generator=generator,
355
+ prior_num_inference_steps=2,
356
+ decoder_num_inference_steps=2,
357
+ super_res_num_inference_steps=2,
358
+ prior_latents=prior_latents,
359
+ decoder_latents=decoder_latents,
360
+ super_res_latents=super_res_latents,
361
+ text_model_output=text_model_output,
362
+ text_attention_mask=text_attention_mask,
363
+ output_type="np",
364
+ )[0]
365
+
366
+ # make sure passing text embeddings manually is identical
367
+ assert np.abs(image - image_from_text).max() < 1e-4
368
+
369
+ # Overriding PipelineTesterMixin::test_attention_slicing_forward_pass
370
+ # because UnCLIP GPU undeterminism requires a looser check.
371
+ @skip_mps
372
+ def test_attention_slicing_forward_pass(self):
373
+ test_max_difference = torch_device == "cpu"
374
+
375
+ self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference, expected_max_diff=0.01)
376
+
377
+ # Overriding PipelineTesterMixin::test_inference_batch_single_identical
378
+ # because UnCLIP undeterminism requires a looser check.
379
+ @skip_mps
380
+ def test_inference_batch_single_identical(self):
381
+ additional_params_copy_to_batched_inputs = [
382
+ "prior_num_inference_steps",
383
+ "decoder_num_inference_steps",
384
+ "super_res_num_inference_steps",
385
+ ]
386
+
387
+ self._test_inference_batch_single_identical(
388
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs, expected_max_diff=9.8e-3
389
+ )
390
+
391
+ def test_inference_batch_consistent(self):
392
+ additional_params_copy_to_batched_inputs = [
393
+ "prior_num_inference_steps",
394
+ "decoder_num_inference_steps",
395
+ "super_res_num_inference_steps",
396
+ ]
397
+
398
+ if torch_device == "mps":
399
+ # TODO: MPS errors with larger batch sizes
400
+ batch_sizes = [2, 3]
401
+ self._test_inference_batch_consistent(
402
+ batch_sizes=batch_sizes,
403
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,
404
+ )
405
+ else:
406
+ self._test_inference_batch_consistent(
407
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs
408
+ )
409
+
410
+ @skip_mps
411
+ def test_dict_tuple_outputs_equivalent(self):
412
+ return super().test_dict_tuple_outputs_equivalent()
413
+
414
+ @skip_mps
415
+ def test_save_load_local(self):
416
+ return super().test_save_load_local(expected_max_difference=5e-3)
417
+
418
+ @skip_mps
419
+ def test_save_load_optional_components(self):
420
+ return super().test_save_load_optional_components()
421
+
422
+ @unittest.skip("UnCLIP produces very large differences in fp16 vs fp32. Test is not useful.")
423
+ def test_float16_inference(self):
424
+ super().test_float16_inference(expected_max_diff=1.0)
425
+
426
+
427
+ @nightly
428
+ class UnCLIPPipelineCPUIntegrationTests(unittest.TestCase):
429
+ def setUp(self):
430
+ # clean up the VRAM before each test
431
+ super().setUp()
432
+ gc.collect()
433
+ backend_empty_cache(torch_device)
434
+
435
+ def tearDown(self):
436
+ # clean up the VRAM after each test
437
+ super().tearDown()
438
+ gc.collect()
439
+ backend_empty_cache(torch_device)
440
+
441
+ def test_unclip_karlo_cpu_fp32(self):
442
+ expected_image = load_numpy(
443
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
444
+ "/unclip/karlo_v1_alpha_horse_cpu.npy"
445
+ )
446
+
447
+ pipeline = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha")
448
+ pipeline.set_progress_bar_config(disable=None)
449
+
450
+ generator = torch.manual_seed(0)
451
+ output = pipeline(
452
+ "horse",
453
+ num_images_per_prompt=1,
454
+ generator=generator,
455
+ output_type="np",
456
+ )
457
+
458
+ image = output.images[0]
459
+
460
+ assert image.shape == (256, 256, 3)
461
+ assert np.abs(expected_image - image).max() < 1e-1
462
+
463
+
464
+ @nightly
465
+ @require_torch_accelerator
466
+ class UnCLIPPipelineIntegrationTests(unittest.TestCase):
467
+ def setUp(self):
468
+ # clean up the VRAM before each test
469
+ super().setUp()
470
+ gc.collect()
471
+ backend_empty_cache(torch_device)
472
+
473
+ def tearDown(self):
474
+ # clean up the VRAM after each test
475
+ super().tearDown()
476
+ gc.collect()
477
+ backend_empty_cache(torch_device)
478
+
479
+ def test_unclip_karlo(self):
480
+ expected_image = load_numpy(
481
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
482
+ "/unclip/karlo_v1_alpha_horse_fp16.npy"
483
+ )
484
+
485
+ pipeline = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha", torch_dtype=torch.float16)
486
+ pipeline = pipeline.to(torch_device)
487
+ pipeline.set_progress_bar_config(disable=None)
488
+
489
+ generator = torch.Generator(device="cpu").manual_seed(0)
490
+ output = pipeline(
491
+ "horse",
492
+ generator=generator,
493
+ output_type="np",
494
+ )
495
+
496
+ image = output.images[0]
497
+
498
+ assert image.shape == (256, 256, 3)
499
+
500
+ assert_mean_pixel_difference(image, expected_image)
501
+
502
+ def test_unclip_pipeline_with_sequential_cpu_offloading(self):
503
+ backend_empty_cache(torch_device)
504
+ backend_reset_max_memory_allocated(torch_device)
505
+ backend_reset_peak_memory_stats(torch_device)
506
+
507
+ pipe = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha", torch_dtype=torch.float16)
508
+ pipe.set_progress_bar_config(disable=None)
509
+ pipe.enable_attention_slicing()
510
+ pipe.enable_sequential_cpu_offload()
511
+
512
+ _ = pipe(
513
+ "horse",
514
+ num_images_per_prompt=1,
515
+ prior_num_inference_steps=2,
516
+ decoder_num_inference_steps=2,
517
+ super_res_num_inference_steps=2,
518
+ output_type="np",
519
+ )
520
+
521
+ mem_bytes = backend_max_memory_allocated(torch_device)
522
+ # make sure that less than 7 GB is allocated
523
+ assert mem_bytes < 7 * 10**9
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unclip/test_unclip_image_variation.py ADDED
@@ -0,0 +1,540 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import gc
17
+ import random
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import torch
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextConfig,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ CLIPVisionConfig,
28
+ CLIPVisionModelWithProjection,
29
+ )
30
+
31
+ from diffusers import (
32
+ DiffusionPipeline,
33
+ UnCLIPImageVariationPipeline,
34
+ UnCLIPScheduler,
35
+ UNet2DConditionModel,
36
+ UNet2DModel,
37
+ )
38
+ from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
39
+ from diffusers.utils.testing_utils import (
40
+ backend_empty_cache,
41
+ enable_full_determinism,
42
+ floats_tensor,
43
+ load_image,
44
+ load_numpy,
45
+ nightly,
46
+ require_torch_accelerator,
47
+ skip_mps,
48
+ torch_device,
49
+ )
50
+
51
+ from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
52
+ from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
53
+
54
+
55
+ enable_full_determinism()
56
+
57
+
58
+ class UnCLIPImageVariationPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
59
+ pipeline_class = UnCLIPImageVariationPipeline
60
+ params = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"}
61
+ batch_params = IMAGE_VARIATION_BATCH_PARAMS
62
+
63
+ required_optional_params = [
64
+ "generator",
65
+ "return_dict",
66
+ "decoder_num_inference_steps",
67
+ "super_res_num_inference_steps",
68
+ ]
69
+ test_xformers_attention = False
70
+ supports_dduf = False
71
+
72
+ @property
73
+ def text_embedder_hidden_size(self):
74
+ return 32
75
+
76
+ @property
77
+ def time_input_dim(self):
78
+ return 32
79
+
80
+ @property
81
+ def block_out_channels_0(self):
82
+ return self.time_input_dim
83
+
84
+ @property
85
+ def time_embed_dim(self):
86
+ return self.time_input_dim * 4
87
+
88
+ @property
89
+ def cross_attention_dim(self):
90
+ return 100
91
+
92
+ @property
93
+ def dummy_tokenizer(self):
94
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
95
+ return tokenizer
96
+
97
+ @property
98
+ def dummy_text_encoder(self):
99
+ torch.manual_seed(0)
100
+ config = CLIPTextConfig(
101
+ bos_token_id=0,
102
+ eos_token_id=2,
103
+ hidden_size=self.text_embedder_hidden_size,
104
+ projection_dim=self.text_embedder_hidden_size,
105
+ intermediate_size=37,
106
+ layer_norm_eps=1e-05,
107
+ num_attention_heads=4,
108
+ num_hidden_layers=5,
109
+ pad_token_id=1,
110
+ vocab_size=1000,
111
+ )
112
+ return CLIPTextModelWithProjection(config)
113
+
114
+ @property
115
+ def dummy_image_encoder(self):
116
+ torch.manual_seed(0)
117
+ config = CLIPVisionConfig(
118
+ hidden_size=self.text_embedder_hidden_size,
119
+ projection_dim=self.text_embedder_hidden_size,
120
+ num_hidden_layers=5,
121
+ num_attention_heads=4,
122
+ image_size=32,
123
+ intermediate_size=37,
124
+ patch_size=1,
125
+ )
126
+ return CLIPVisionModelWithProjection(config)
127
+
128
+ @property
129
+ def dummy_text_proj(self):
130
+ torch.manual_seed(0)
131
+
132
+ model_kwargs = {
133
+ "clip_embeddings_dim": self.text_embedder_hidden_size,
134
+ "time_embed_dim": self.time_embed_dim,
135
+ "cross_attention_dim": self.cross_attention_dim,
136
+ }
137
+
138
+ model = UnCLIPTextProjModel(**model_kwargs)
139
+ return model
140
+
141
+ @property
142
+ def dummy_decoder(self):
143
+ torch.manual_seed(0)
144
+
145
+ model_kwargs = {
146
+ "sample_size": 32,
147
+ # RGB in channels
148
+ "in_channels": 3,
149
+ # Out channels is double in channels because predicts mean and variance
150
+ "out_channels": 6,
151
+ "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
152
+ "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
153
+ "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
154
+ "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
155
+ "layers_per_block": 1,
156
+ "cross_attention_dim": self.cross_attention_dim,
157
+ "attention_head_dim": 4,
158
+ "resnet_time_scale_shift": "scale_shift",
159
+ "class_embed_type": "identity",
160
+ }
161
+
162
+ model = UNet2DConditionModel(**model_kwargs)
163
+ return model
164
+
165
+ @property
166
+ def dummy_super_res_kwargs(self):
167
+ return {
168
+ "sample_size": 64,
169
+ "layers_per_block": 1,
170
+ "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
171
+ "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
172
+ "block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),
173
+ "in_channels": 6,
174
+ "out_channels": 3,
175
+ }
176
+
177
+ @property
178
+ def dummy_super_res_first(self):
179
+ torch.manual_seed(0)
180
+
181
+ model = UNet2DModel(**self.dummy_super_res_kwargs)
182
+ return model
183
+
184
+ @property
185
+ def dummy_super_res_last(self):
186
+ # seeded differently to get different unet than `self.dummy_super_res_first`
187
+ torch.manual_seed(1)
188
+
189
+ model = UNet2DModel(**self.dummy_super_res_kwargs)
190
+ return model
191
+
192
+ def get_dummy_components(self):
193
+ decoder = self.dummy_decoder
194
+ text_proj = self.dummy_text_proj
195
+ text_encoder = self.dummy_text_encoder
196
+ tokenizer = self.dummy_tokenizer
197
+ super_res_first = self.dummy_super_res_first
198
+ super_res_last = self.dummy_super_res_last
199
+
200
+ decoder_scheduler = UnCLIPScheduler(
201
+ variance_type="learned_range",
202
+ prediction_type="epsilon",
203
+ num_train_timesteps=1000,
204
+ )
205
+
206
+ super_res_scheduler = UnCLIPScheduler(
207
+ variance_type="fixed_small_log",
208
+ prediction_type="epsilon",
209
+ num_train_timesteps=1000,
210
+ )
211
+
212
+ feature_extractor = CLIPImageProcessor(crop_size=32, size=32)
213
+
214
+ image_encoder = self.dummy_image_encoder
215
+
216
+ return {
217
+ "decoder": decoder,
218
+ "text_encoder": text_encoder,
219
+ "tokenizer": tokenizer,
220
+ "text_proj": text_proj,
221
+ "feature_extractor": feature_extractor,
222
+ "image_encoder": image_encoder,
223
+ "super_res_first": super_res_first,
224
+ "super_res_last": super_res_last,
225
+ "decoder_scheduler": decoder_scheduler,
226
+ "super_res_scheduler": super_res_scheduler,
227
+ }
228
+
229
+ def get_dummy_inputs(self, device, seed=0, pil_image=True):
230
+ input_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
231
+ if str(device).startswith("mps"):
232
+ generator = torch.manual_seed(seed)
233
+ else:
234
+ generator = torch.Generator(device=device).manual_seed(seed)
235
+
236
+ if pil_image:
237
+ input_image = input_image * 0.5 + 0.5
238
+ input_image = input_image.clamp(0, 1)
239
+ input_image = input_image.cpu().permute(0, 2, 3, 1).float().numpy()
240
+ input_image = DiffusionPipeline.numpy_to_pil(input_image)[0]
241
+
242
+ return {
243
+ "image": input_image,
244
+ "generator": generator,
245
+ "decoder_num_inference_steps": 2,
246
+ "super_res_num_inference_steps": 2,
247
+ "output_type": "np",
248
+ }
249
+
250
+ def test_unclip_image_variation_input_tensor(self):
251
+ device = "cpu"
252
+
253
+ components = self.get_dummy_components()
254
+
255
+ pipe = self.pipeline_class(**components)
256
+ pipe = pipe.to(device)
257
+
258
+ pipe.set_progress_bar_config(disable=None)
259
+
260
+ pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
261
+
262
+ output = pipe(**pipeline_inputs)
263
+ image = output.images
264
+
265
+ tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
266
+
267
+ image_from_tuple = pipe(
268
+ **tuple_pipeline_inputs,
269
+ return_dict=False,
270
+ )[0]
271
+
272
+ image_slice = image[0, -3:, -3:, -1]
273
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
274
+
275
+ assert image.shape == (1, 64, 64, 3)
276
+
277
+ expected_slice = np.array(
278
+ [
279
+ 0.9997,
280
+ 0.0002,
281
+ 0.9997,
282
+ 0.9997,
283
+ 0.9969,
284
+ 0.0023,
285
+ 0.9997,
286
+ 0.9969,
287
+ 0.9970,
288
+ ]
289
+ )
290
+
291
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
292
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
293
+
294
+ def test_unclip_image_variation_input_image(self):
295
+ device = "cpu"
296
+
297
+ components = self.get_dummy_components()
298
+
299
+ pipe = self.pipeline_class(**components)
300
+ pipe = pipe.to(device)
301
+
302
+ pipe.set_progress_bar_config(disable=None)
303
+
304
+ pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
305
+
306
+ output = pipe(**pipeline_inputs)
307
+ image = output.images
308
+
309
+ tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
310
+
311
+ image_from_tuple = pipe(
312
+ **tuple_pipeline_inputs,
313
+ return_dict=False,
314
+ )[0]
315
+
316
+ image_slice = image[0, -3:, -3:, -1]
317
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
318
+
319
+ assert image.shape == (1, 64, 64, 3)
320
+
321
+ expected_slice = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971])
322
+
323
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
324
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
325
+
326
+ def test_unclip_image_variation_input_list_images(self):
327
+ device = "cpu"
328
+
329
+ components = self.get_dummy_components()
330
+
331
+ pipe = self.pipeline_class(**components)
332
+ pipe = pipe.to(device)
333
+
334
+ pipe.set_progress_bar_config(disable=None)
335
+
336
+ pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
337
+ pipeline_inputs["image"] = [
338
+ pipeline_inputs["image"],
339
+ pipeline_inputs["image"],
340
+ ]
341
+
342
+ output = pipe(**pipeline_inputs)
343
+ image = output.images
344
+
345
+ tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)
346
+ tuple_pipeline_inputs["image"] = [
347
+ tuple_pipeline_inputs["image"],
348
+ tuple_pipeline_inputs["image"],
349
+ ]
350
+
351
+ image_from_tuple = pipe(
352
+ **tuple_pipeline_inputs,
353
+ return_dict=False,
354
+ )[0]
355
+
356
+ image_slice = image[0, -3:, -3:, -1]
357
+ image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
358
+
359
+ assert image.shape == (2, 64, 64, 3)
360
+
361
+ expected_slice = np.array(
362
+ [
363
+ 0.9997,
364
+ 0.9989,
365
+ 0.0008,
366
+ 0.0021,
367
+ 0.9960,
368
+ 0.0018,
369
+ 0.0014,
370
+ 0.0002,
371
+ 0.9933,
372
+ ]
373
+ )
374
+
375
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
376
+ assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
377
+
378
+ def test_unclip_passed_image_embed(self):
379
+ device = torch.device("cpu")
380
+
381
+ class DummyScheduler:
382
+ init_noise_sigma = 1
383
+
384
+ components = self.get_dummy_components()
385
+
386
+ pipe = self.pipeline_class(**components)
387
+ pipe = pipe.to(device)
388
+
389
+ pipe.set_progress_bar_config(disable=None)
390
+
391
+ generator = torch.Generator(device=device).manual_seed(0)
392
+ dtype = pipe.decoder.dtype
393
+ batch_size = 1
394
+
395
+ shape = (
396
+ batch_size,
397
+ pipe.decoder.config.in_channels,
398
+ pipe.decoder.config.sample_size,
399
+ pipe.decoder.config.sample_size,
400
+ )
401
+ decoder_latents = pipe.prepare_latents(
402
+ shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
403
+ )
404
+
405
+ shape = (
406
+ batch_size,
407
+ pipe.super_res_first.config.in_channels // 2,
408
+ pipe.super_res_first.config.sample_size,
409
+ pipe.super_res_first.config.sample_size,
410
+ )
411
+ generator = torch.Generator(device=device).manual_seed(0)
412
+ super_res_latents = pipe.prepare_latents(
413
+ shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()
414
+ )
415
+
416
+ pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
417
+
418
+ img_out_1 = pipe(
419
+ **pipeline_inputs, decoder_latents=decoder_latents, super_res_latents=super_res_latents
420
+ ).images
421
+
422
+ pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)
423
+ # Don't pass image, instead pass embedding
424
+ image = pipeline_inputs.pop("image")
425
+ image_embeddings = pipe.image_encoder(image).image_embeds
426
+
427
+ img_out_2 = pipe(
428
+ **pipeline_inputs,
429
+ decoder_latents=decoder_latents,
430
+ super_res_latents=super_res_latents,
431
+ image_embeddings=image_embeddings,
432
+ ).images
433
+
434
+ # make sure passing text embeddings manually is identical
435
+ assert np.abs(img_out_1 - img_out_2).max() < 1e-4
436
+
437
+ # Overriding PipelineTesterMixin::test_attention_slicing_forward_pass
438
+ # because UnCLIP GPU undeterminism requires a looser check.
439
+ @skip_mps
440
+ def test_attention_slicing_forward_pass(self):
441
+ test_max_difference = torch_device == "cpu"
442
+
443
+ # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor
444
+ expected_max_diff = 1e-2
445
+
446
+ self._test_attention_slicing_forward_pass(
447
+ test_max_difference=test_max_difference, expected_max_diff=expected_max_diff
448
+ )
449
+
450
+ # Overriding PipelineTesterMixin::test_inference_batch_single_identical
451
+ # because UnCLIP undeterminism requires a looser check.
452
+ @unittest.skip("UnCLIP produces very large differences. Test is not useful.")
453
+ @skip_mps
454
+ def test_inference_batch_single_identical(self):
455
+ additional_params_copy_to_batched_inputs = [
456
+ "decoder_num_inference_steps",
457
+ "super_res_num_inference_steps",
458
+ ]
459
+ self._test_inference_batch_single_identical(
460
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs, expected_max_diff=5e-3
461
+ )
462
+
463
+ def test_inference_batch_consistent(self):
464
+ additional_params_copy_to_batched_inputs = [
465
+ "decoder_num_inference_steps",
466
+ "super_res_num_inference_steps",
467
+ ]
468
+
469
+ if torch_device == "mps":
470
+ # TODO: MPS errors with larger batch sizes
471
+ batch_sizes = [2, 3]
472
+ self._test_inference_batch_consistent(
473
+ batch_sizes=batch_sizes,
474
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,
475
+ )
476
+ else:
477
+ self._test_inference_batch_consistent(
478
+ additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs
479
+ )
480
+
481
+ @skip_mps
482
+ def test_dict_tuple_outputs_equivalent(self):
483
+ return super().test_dict_tuple_outputs_equivalent()
484
+
485
+ @unittest.skip("UnCLIP produces very large difference. Test is not useful.")
486
+ @skip_mps
487
+ def test_save_load_local(self):
488
+ return super().test_save_load_local(expected_max_difference=4e-3)
489
+
490
+ @skip_mps
491
+ def test_save_load_optional_components(self):
492
+ return super().test_save_load_optional_components()
493
+
494
+ @unittest.skip("UnCLIP produces very large difference in fp16 vs fp32. Test is not useful.")
495
+ def test_float16_inference(self):
496
+ super().test_float16_inference(expected_max_diff=1.0)
497
+
498
+
499
+ @nightly
500
+ @require_torch_accelerator
501
+ class UnCLIPImageVariationPipelineIntegrationTests(unittest.TestCase):
502
+ def setUp(self):
503
+ # clean up the VRAM before each test
504
+ super().setUp()
505
+ gc.collect()
506
+ backend_empty_cache(torch_device)
507
+
508
+ def tearDown(self):
509
+ # clean up the VRAM after each test
510
+ super().tearDown()
511
+ gc.collect()
512
+ backend_empty_cache(torch_device)
513
+
514
+ def test_unclip_image_variation_karlo(self):
515
+ input_image = load_image(
516
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png"
517
+ )
518
+ expected_image = load_numpy(
519
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
520
+ "/unclip/karlo_v1_alpha_cat_variation_fp16.npy"
521
+ )
522
+
523
+ pipeline = UnCLIPImageVariationPipeline.from_pretrained(
524
+ "kakaobrain/karlo-v1-alpha-image-variations", torch_dtype=torch.float16
525
+ )
526
+ pipeline = pipeline.to(torch_device)
527
+ pipeline.set_progress_bar_config(disable=None)
528
+
529
+ generator = torch.Generator(device="cpu").manual_seed(0)
530
+ output = pipeline(
531
+ input_image,
532
+ generator=generator,
533
+ output_type="np",
534
+ )
535
+
536
+ image = output.images[0]
537
+
538
+ assert image.shape == (256, 256, 3)
539
+
540
+ assert_mean_pixel_difference(image, expected_image, 15)
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unidiffuser/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/unidiffuser/test_unidiffuser.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import random
3
+ import unittest
4
+
5
+ import numpy as np
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import (
9
+ CLIPImageProcessor,
10
+ CLIPTextModel,
11
+ CLIPTokenizer,
12
+ CLIPVisionModelWithProjection,
13
+ GPT2Tokenizer,
14
+ )
15
+
16
+ from diffusers import (
17
+ AutoencoderKL,
18
+ DPMSolverMultistepScheduler,
19
+ UniDiffuserModel,
20
+ UniDiffuserPipeline,
21
+ UniDiffuserTextDecoder,
22
+ )
23
+ from diffusers.utils.testing_utils import (
24
+ backend_empty_cache,
25
+ enable_full_determinism,
26
+ floats_tensor,
27
+ load_image,
28
+ nightly,
29
+ require_torch_accelerator,
30
+ torch_device,
31
+ )
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+
34
+ from ..pipeline_params import (
35
+ IMAGE_TO_IMAGE_IMAGE_PARAMS,
36
+ TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
37
+ TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
38
+ )
39
+ from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
40
+
41
+
42
+ enable_full_determinism()
43
+
44
+
45
+ class UniDiffuserPipelineFastTests(
46
+ PipelineTesterMixin, PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
47
+ ):
48
+ pipeline_class = UniDiffuserPipeline
49
+ params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS
50
+ batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
51
+ image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
52
+ # vae_latents, not latents, is the argument that corresponds to VAE latent inputs
53
+ image_latents_params = frozenset(["vae_latents"])
54
+
55
+ supports_dduf = False
56
+
57
+ def get_dummy_components(self):
58
+ unet = UniDiffuserModel.from_pretrained(
59
+ "hf-internal-testing/unidiffuser-diffusers-test",
60
+ subfolder="unet",
61
+ )
62
+
63
+ scheduler = DPMSolverMultistepScheduler(
64
+ beta_start=0.00085,
65
+ beta_end=0.012,
66
+ beta_schedule="scaled_linear",
67
+ solver_order=3,
68
+ )
69
+
70
+ vae = AutoencoderKL.from_pretrained(
71
+ "hf-internal-testing/unidiffuser-diffusers-test",
72
+ subfolder="vae",
73
+ )
74
+
75
+ text_encoder = CLIPTextModel.from_pretrained(
76
+ "hf-internal-testing/unidiffuser-diffusers-test",
77
+ subfolder="text_encoder",
78
+ )
79
+ clip_tokenizer = CLIPTokenizer.from_pretrained(
80
+ "hf-internal-testing/unidiffuser-diffusers-test",
81
+ subfolder="clip_tokenizer",
82
+ )
83
+
84
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
85
+ "hf-internal-testing/unidiffuser-diffusers-test",
86
+ subfolder="image_encoder",
87
+ )
88
+ # From the Stable Diffusion Image Variation pipeline tests
89
+ clip_image_processor = CLIPImageProcessor(crop_size=32, size=32)
90
+ # image_processor = CLIPImageProcessor.from_pretrained("hf-internal-testing/tiny-random-clip")
91
+
92
+ text_tokenizer = GPT2Tokenizer.from_pretrained(
93
+ "hf-internal-testing/unidiffuser-diffusers-test",
94
+ subfolder="text_tokenizer",
95
+ )
96
+ text_decoder = UniDiffuserTextDecoder.from_pretrained(
97
+ "hf-internal-testing/unidiffuser-diffusers-test",
98
+ subfolder="text_decoder",
99
+ )
100
+
101
+ components = {
102
+ "vae": vae,
103
+ "text_encoder": text_encoder,
104
+ "image_encoder": image_encoder,
105
+ "clip_image_processor": clip_image_processor,
106
+ "clip_tokenizer": clip_tokenizer,
107
+ "text_decoder": text_decoder,
108
+ "text_tokenizer": text_tokenizer,
109
+ "unet": unet,
110
+ "scheduler": scheduler,
111
+ }
112
+
113
+ return components
114
+
115
+ def get_dummy_inputs(self, device, seed=0):
116
+ image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
117
+ image = image.cpu().permute(0, 2, 3, 1)[0]
118
+ image = Image.fromarray(np.uint8(image)).convert("RGB")
119
+ if str(device).startswith("mps"):
120
+ generator = torch.manual_seed(seed)
121
+ else:
122
+ generator = torch.Generator(device=device).manual_seed(seed)
123
+ inputs = {
124
+ "prompt": "an elephant under the sea",
125
+ "image": image,
126
+ "generator": generator,
127
+ "num_inference_steps": 2,
128
+ "guidance_scale": 6.0,
129
+ "output_type": "np",
130
+ }
131
+ return inputs
132
+
133
+ def get_fixed_latents(self, device, seed=0):
134
+ if isinstance(device, str):
135
+ device = torch.device(device)
136
+ generator = torch.Generator(device=device).manual_seed(seed)
137
+ # Hardcode the shapes for now.
138
+ prompt_latents = randn_tensor((1, 77, 32), generator=generator, device=device, dtype=torch.float32)
139
+ vae_latents = randn_tensor((1, 4, 16, 16), generator=generator, device=device, dtype=torch.float32)
140
+ clip_latents = randn_tensor((1, 1, 32), generator=generator, device=device, dtype=torch.float32)
141
+
142
+ latents = {
143
+ "prompt_latents": prompt_latents,
144
+ "vae_latents": vae_latents,
145
+ "clip_latents": clip_latents,
146
+ }
147
+ return latents
148
+
149
+ def get_dummy_inputs_with_latents(self, device, seed=0):
150
+ # image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
151
+ # image = image.cpu().permute(0, 2, 3, 1)[0]
152
+ # image = Image.fromarray(np.uint8(image)).convert("RGB")
153
+ image = load_image(
154
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg",
155
+ )
156
+ image = image.resize((32, 32))
157
+ latents = self.get_fixed_latents(device, seed=seed)
158
+
159
+ if str(device).startswith("mps"):
160
+ generator = torch.manual_seed(seed)
161
+ else:
162
+ generator = torch.Generator(device=device).manual_seed(seed)
163
+
164
+ inputs = {
165
+ "prompt": "an elephant under the sea",
166
+ "image": image,
167
+ "generator": generator,
168
+ "num_inference_steps": 2,
169
+ "guidance_scale": 6.0,
170
+ "output_type": "np",
171
+ "prompt_latents": latents.get("prompt_latents"),
172
+ "vae_latents": latents.get("vae_latents"),
173
+ "clip_latents": latents.get("clip_latents"),
174
+ }
175
+ return inputs
176
+
177
+ def test_dict_tuple_outputs_equivalent(self):
178
+ expected_slice = None
179
+ if torch_device == "cpu":
180
+ expected_slice = np.array([0.7489, 0.3722, 0.4475, 0.5630, 0.5923, 0.4992, 0.3936, 0.5844, 0.4975])
181
+ super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
182
+
183
+ def test_unidiffuser_default_joint_v0(self):
184
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
185
+ components = self.get_dummy_components()
186
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
187
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
188
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
189
+
190
+ # Set mode to 'joint'
191
+ unidiffuser_pipe.set_joint_mode()
192
+ assert unidiffuser_pipe.mode == "joint"
193
+
194
+ # inputs = self.get_dummy_inputs(device)
195
+ inputs = self.get_dummy_inputs_with_latents(device)
196
+ # Delete prompt and image for joint inference.
197
+ del inputs["prompt"]
198
+ del inputs["image"]
199
+ sample = unidiffuser_pipe(**inputs)
200
+ image = sample.images
201
+ text = sample.text
202
+ assert image.shape == (1, 32, 32, 3)
203
+
204
+ image_slice = image[0, -3:, -3:, -1]
205
+ expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716])
206
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3
207
+
208
+ expected_text_prefix = " no no no "
209
+ assert text[0][:10] == expected_text_prefix
210
+
211
+ def test_unidiffuser_default_joint_no_cfg_v0(self):
212
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
213
+ components = self.get_dummy_components()
214
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
215
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
216
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
217
+
218
+ # Set mode to 'joint'
219
+ unidiffuser_pipe.set_joint_mode()
220
+ assert unidiffuser_pipe.mode == "joint"
221
+
222
+ # inputs = self.get_dummy_inputs(device)
223
+ inputs = self.get_dummy_inputs_with_latents(device)
224
+ # Delete prompt and image for joint inference.
225
+ del inputs["prompt"]
226
+ del inputs["image"]
227
+ # Set guidance scale to 1.0 to turn off CFG
228
+ inputs["guidance_scale"] = 1.0
229
+ sample = unidiffuser_pipe(**inputs)
230
+ image = sample.images
231
+ text = sample.text
232
+ assert image.shape == (1, 32, 32, 3)
233
+
234
+ image_slice = image[0, -3:, -3:, -1]
235
+ expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716])
236
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3
237
+
238
+ expected_text_prefix = " no no no "
239
+ assert text[0][:10] == expected_text_prefix
240
+
241
+ def test_unidiffuser_default_text2img_v0(self):
242
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
243
+ components = self.get_dummy_components()
244
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
245
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
246
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
247
+
248
+ # Set mode to 'text2img'
249
+ unidiffuser_pipe.set_text_to_image_mode()
250
+ assert unidiffuser_pipe.mode == "text2img"
251
+
252
+ inputs = self.get_dummy_inputs_with_latents(device)
253
+ # Delete image for text-conditioned image generation
254
+ del inputs["image"]
255
+ image = unidiffuser_pipe(**inputs).images
256
+ assert image.shape == (1, 32, 32, 3)
257
+
258
+ image_slice = image[0, -3:, -3:, -1]
259
+ expected_slice = np.array([0.5758, 0.6269, 0.6570, 0.4967, 0.4639, 0.5664, 0.5257, 0.5067, 0.5715])
260
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
261
+
262
+ def test_unidiffuser_default_image_0(self):
263
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
264
+ components = self.get_dummy_components()
265
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
266
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
267
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
268
+
269
+ # Set mode to 'img'
270
+ unidiffuser_pipe.set_image_mode()
271
+ assert unidiffuser_pipe.mode == "img"
272
+
273
+ inputs = self.get_dummy_inputs(device)
274
+ # Delete prompt and image for unconditional ("marginal") text generation.
275
+ del inputs["prompt"]
276
+ del inputs["image"]
277
+ image = unidiffuser_pipe(**inputs).images
278
+ assert image.shape == (1, 32, 32, 3)
279
+
280
+ image_slice = image[0, -3:, -3:, -1]
281
+ expected_slice = np.array([0.5760, 0.6270, 0.6571, 0.4966, 0.4638, 0.5663, 0.5254, 0.5068, 0.5715])
282
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
283
+
284
+ def test_unidiffuser_default_text_v0(self):
285
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
286
+ components = self.get_dummy_components()
287
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
288
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
289
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
290
+
291
+ # Set mode to 'img'
292
+ unidiffuser_pipe.set_text_mode()
293
+ assert unidiffuser_pipe.mode == "text"
294
+
295
+ inputs = self.get_dummy_inputs(device)
296
+ # Delete prompt and image for unconditional ("marginal") text generation.
297
+ del inputs["prompt"]
298
+ del inputs["image"]
299
+ text = unidiffuser_pipe(**inputs).text
300
+
301
+ expected_text_prefix = " no no no "
302
+ assert text[0][:10] == expected_text_prefix
303
+
304
+ def test_unidiffuser_default_img2text_v0(self):
305
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
306
+ components = self.get_dummy_components()
307
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
308
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
309
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
310
+
311
+ # Set mode to 'img2text'
312
+ unidiffuser_pipe.set_image_to_text_mode()
313
+ assert unidiffuser_pipe.mode == "img2text"
314
+
315
+ inputs = self.get_dummy_inputs_with_latents(device)
316
+ # Delete text for image-conditioned text generation
317
+ del inputs["prompt"]
318
+ text = unidiffuser_pipe(**inputs).text
319
+
320
+ expected_text_prefix = " no no no "
321
+ assert text[0][:10] == expected_text_prefix
322
+
323
+ def test_unidiffuser_default_joint_v1(self):
324
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
325
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1")
326
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
327
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
328
+
329
+ # Set mode to 'joint'
330
+ unidiffuser_pipe.set_joint_mode()
331
+ assert unidiffuser_pipe.mode == "joint"
332
+
333
+ # inputs = self.get_dummy_inputs(device)
334
+ inputs = self.get_dummy_inputs_with_latents(device)
335
+ # Delete prompt and image for joint inference.
336
+ del inputs["prompt"]
337
+ del inputs["image"]
338
+ inputs["data_type"] = 1
339
+ sample = unidiffuser_pipe(**inputs)
340
+ image = sample.images
341
+ text = sample.text
342
+ assert image.shape == (1, 32, 32, 3)
343
+
344
+ image_slice = image[0, -3:, -3:, -1]
345
+ expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716])
346
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3
347
+
348
+ expected_text_prefix = " no no no "
349
+ assert text[0][:10] == expected_text_prefix
350
+
351
+ def test_unidiffuser_default_text2img_v1(self):
352
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
353
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1")
354
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
355
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
356
+
357
+ # Set mode to 'text2img'
358
+ unidiffuser_pipe.set_text_to_image_mode()
359
+ assert unidiffuser_pipe.mode == "text2img"
360
+
361
+ inputs = self.get_dummy_inputs_with_latents(device)
362
+ # Delete image for text-conditioned image generation
363
+ del inputs["image"]
364
+ image = unidiffuser_pipe(**inputs).images
365
+ assert image.shape == (1, 32, 32, 3)
366
+
367
+ image_slice = image[0, -3:, -3:, -1]
368
+ expected_slice = np.array([0.5758, 0.6269, 0.6570, 0.4967, 0.4639, 0.5664, 0.5257, 0.5067, 0.5715])
369
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
370
+
371
+ def test_unidiffuser_default_img2text_v1(self):
372
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
373
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1")
374
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
375
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
376
+
377
+ # Set mode to 'img2text'
378
+ unidiffuser_pipe.set_image_to_text_mode()
379
+ assert unidiffuser_pipe.mode == "img2text"
380
+
381
+ inputs = self.get_dummy_inputs_with_latents(device)
382
+ # Delete text for image-conditioned text generation
383
+ del inputs["prompt"]
384
+ text = unidiffuser_pipe(**inputs).text
385
+
386
+ expected_text_prefix = " no no no "
387
+ assert text[0][:10] == expected_text_prefix
388
+
389
+ def test_unidiffuser_text2img_multiple_images(self):
390
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
391
+ components = self.get_dummy_components()
392
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
393
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
394
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
395
+
396
+ # Set mode to 'text2img'
397
+ unidiffuser_pipe.set_text_to_image_mode()
398
+ assert unidiffuser_pipe.mode == "text2img"
399
+
400
+ inputs = self.get_dummy_inputs(device)
401
+ # Delete image for text-conditioned image generation
402
+ del inputs["image"]
403
+ inputs["num_images_per_prompt"] = 2
404
+ inputs["num_prompts_per_image"] = 3
405
+ image = unidiffuser_pipe(**inputs).images
406
+ assert image.shape == (2, 32, 32, 3)
407
+
408
+ def test_unidiffuser_img2text_multiple_prompts(self):
409
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
410
+ components = self.get_dummy_components()
411
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
412
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
413
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
414
+
415
+ # Set mode to 'img2text'
416
+ unidiffuser_pipe.set_image_to_text_mode()
417
+ assert unidiffuser_pipe.mode == "img2text"
418
+
419
+ inputs = self.get_dummy_inputs(device)
420
+ # Delete text for image-conditioned text generation
421
+ del inputs["prompt"]
422
+ inputs["num_images_per_prompt"] = 2
423
+ inputs["num_prompts_per_image"] = 3
424
+ text = unidiffuser_pipe(**inputs).text
425
+
426
+ assert len(text) == 3
427
+
428
+ def test_unidiffuser_text2img_multiple_images_with_latents(self):
429
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
430
+ components = self.get_dummy_components()
431
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
432
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
433
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
434
+
435
+ # Set mode to 'text2img'
436
+ unidiffuser_pipe.set_text_to_image_mode()
437
+ assert unidiffuser_pipe.mode == "text2img"
438
+
439
+ inputs = self.get_dummy_inputs_with_latents(device)
440
+ # Delete image for text-conditioned image generation
441
+ del inputs["image"]
442
+ inputs["num_images_per_prompt"] = 2
443
+ inputs["num_prompts_per_image"] = 3
444
+ image = unidiffuser_pipe(**inputs).images
445
+ assert image.shape == (2, 32, 32, 3)
446
+
447
+ def test_unidiffuser_img2text_multiple_prompts_with_latents(self):
448
+ device = "cpu" # ensure determinism for the device-dependent torch.Generator
449
+ components = self.get_dummy_components()
450
+ unidiffuser_pipe = UniDiffuserPipeline(**components)
451
+ unidiffuser_pipe = unidiffuser_pipe.to(device)
452
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
453
+
454
+ # Set mode to 'img2text'
455
+ unidiffuser_pipe.set_image_to_text_mode()
456
+ assert unidiffuser_pipe.mode == "img2text"
457
+
458
+ inputs = self.get_dummy_inputs_with_latents(device)
459
+ # Delete text for image-conditioned text generation
460
+ del inputs["prompt"]
461
+ inputs["num_images_per_prompt"] = 2
462
+ inputs["num_prompts_per_image"] = 3
463
+ text = unidiffuser_pipe(**inputs).text
464
+
465
+ assert len(text) == 3
466
+
467
+ def test_inference_batch_single_identical(self):
468
+ super().test_inference_batch_single_identical(expected_max_diff=2e-4)
469
+
470
+ @require_torch_accelerator
471
+ def test_unidiffuser_default_joint_v1_fp16(self):
472
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained(
473
+ "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16
474
+ )
475
+ unidiffuser_pipe = unidiffuser_pipe.to(torch_device)
476
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
477
+
478
+ # Set mode to 'joint'
479
+ unidiffuser_pipe.set_joint_mode()
480
+ assert unidiffuser_pipe.mode == "joint"
481
+
482
+ inputs = self.get_dummy_inputs_with_latents(torch_device)
483
+ # Delete prompt and image for joint inference.
484
+ del inputs["prompt"]
485
+ del inputs["image"]
486
+ inputs["data_type"] = 1
487
+ sample = unidiffuser_pipe(**inputs)
488
+ image = sample.images
489
+ text = sample.text
490
+ assert image.shape == (1, 32, 32, 3)
491
+
492
+ image_slice = image[0, -3:, -3:, -1]
493
+ expected_img_slice = np.array([0.5049, 0.5498, 0.5854, 0.3052, 0.4460, 0.6489, 0.5122, 0.4810, 0.6138])
494
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3
495
+
496
+ expected_text_prefix = '" This This'
497
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
498
+
499
+ @require_torch_accelerator
500
+ def test_unidiffuser_default_text2img_v1_fp16(self):
501
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained(
502
+ "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16
503
+ )
504
+ unidiffuser_pipe = unidiffuser_pipe.to(torch_device)
505
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
506
+
507
+ # Set mode to 'text2img'
508
+ unidiffuser_pipe.set_text_to_image_mode()
509
+ assert unidiffuser_pipe.mode == "text2img"
510
+
511
+ inputs = self.get_dummy_inputs_with_latents(torch_device)
512
+ # Delete prompt and image for joint inference.
513
+ del inputs["image"]
514
+ inputs["data_type"] = 1
515
+ sample = unidiffuser_pipe(**inputs)
516
+ image = sample.images
517
+ assert image.shape == (1, 32, 32, 3)
518
+
519
+ image_slice = image[0, -3:, -3:, -1]
520
+ expected_img_slice = np.array([0.5054, 0.5498, 0.5854, 0.3052, 0.4458, 0.6489, 0.5122, 0.4810, 0.6138])
521
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3
522
+
523
+ @require_torch_accelerator
524
+ def test_unidiffuser_default_img2text_v1_fp16(self):
525
+ unidiffuser_pipe = UniDiffuserPipeline.from_pretrained(
526
+ "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16
527
+ )
528
+ unidiffuser_pipe = unidiffuser_pipe.to(torch_device)
529
+ unidiffuser_pipe.set_progress_bar_config(disable=None)
530
+
531
+ # Set mode to 'img2text'
532
+ unidiffuser_pipe.set_image_to_text_mode()
533
+ assert unidiffuser_pipe.mode == "img2text"
534
+
535
+ inputs = self.get_dummy_inputs_with_latents(torch_device)
536
+ # Delete prompt and image for joint inference.
537
+ del inputs["prompt"]
538
+ inputs["data_type"] = 1
539
+ text = unidiffuser_pipe(**inputs).text
540
+
541
+ expected_text_prefix = '" This This'
542
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
543
+
544
+ @unittest.skip(
545
+ "Test not supported because it has a bunch of direct configs at init and also, this pipeline isn't used that much now."
546
+ )
547
+ def test_encode_prompt_works_in_isolation():
548
+ pass
549
+
550
+
551
+ @nightly
552
+ @require_torch_accelerator
553
+ class UniDiffuserPipelineSlowTests(unittest.TestCase):
554
+ def setUp(self):
555
+ super().setUp()
556
+ gc.collect()
557
+ backend_empty_cache(torch_device)
558
+
559
+ def tearDown(self):
560
+ super().tearDown()
561
+ gc.collect()
562
+ backend_empty_cache(torch_device)
563
+
564
+ def get_inputs(self, device, seed=0, generate_latents=False):
565
+ generator = torch.manual_seed(seed)
566
+ image = load_image(
567
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
568
+ )
569
+ inputs = {
570
+ "prompt": "an elephant under the sea",
571
+ "image": image,
572
+ "generator": generator,
573
+ "num_inference_steps": 3,
574
+ "guidance_scale": 8.0,
575
+ "output_type": "np",
576
+ }
577
+ if generate_latents:
578
+ latents = self.get_fixed_latents(device, seed=seed)
579
+ for latent_name, latent_tensor in latents.items():
580
+ inputs[latent_name] = latent_tensor
581
+ return inputs
582
+
583
+ def get_fixed_latents(self, device, seed=0):
584
+ if isinstance(device, str):
585
+ device = torch.device(device)
586
+ latent_device = torch.device("cpu")
587
+ generator = torch.Generator(device=latent_device).manual_seed(seed)
588
+ # Hardcode the shapes for now.
589
+ prompt_latents = randn_tensor((1, 77, 768), generator=generator, device=device, dtype=torch.float32)
590
+ vae_latents = randn_tensor((1, 4, 64, 64), generator=generator, device=device, dtype=torch.float32)
591
+ clip_latents = randn_tensor((1, 1, 512), generator=generator, device=device, dtype=torch.float32)
592
+
593
+ # Move latents onto desired device.
594
+ prompt_latents = prompt_latents.to(device)
595
+ vae_latents = vae_latents.to(device)
596
+ clip_latents = clip_latents.to(device)
597
+
598
+ latents = {
599
+ "prompt_latents": prompt_latents,
600
+ "vae_latents": vae_latents,
601
+ "clip_latents": clip_latents,
602
+ }
603
+ return latents
604
+
605
+ def test_unidiffuser_default_joint_v1(self):
606
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1")
607
+ pipe.to(torch_device)
608
+ pipe.set_progress_bar_config(disable=None)
609
+ pipe.enable_attention_slicing()
610
+
611
+ # inputs = self.get_dummy_inputs(device)
612
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
613
+ # Delete prompt and image for joint inference.
614
+ del inputs["prompt"]
615
+ del inputs["image"]
616
+ sample = pipe(**inputs)
617
+ image = sample.images
618
+ text = sample.text
619
+ assert image.shape == (1, 512, 512, 3)
620
+
621
+ image_slice = image[0, -3:, -3:, -1]
622
+ expected_img_slice = np.array([0.2402, 0.2375, 0.2285, 0.2378, 0.2407, 0.2263, 0.2354, 0.2307, 0.2520])
623
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-1
624
+
625
+ expected_text_prefix = "a living room"
626
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
627
+
628
+ def test_unidiffuser_default_text2img_v1(self):
629
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1")
630
+ pipe.to(torch_device)
631
+ pipe.set_progress_bar_config(disable=None)
632
+ pipe.enable_attention_slicing()
633
+
634
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
635
+ del inputs["image"]
636
+ sample = pipe(**inputs)
637
+ image = sample.images
638
+ assert image.shape == (1, 512, 512, 3)
639
+
640
+ image_slice = image[0, -3:, -3:, -1]
641
+ expected_slice = np.array([0.0242, 0.0103, 0.0022, 0.0129, 0.0000, 0.0090, 0.0376, 0.0508, 0.0005])
642
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1
643
+
644
+ def test_unidiffuser_default_img2text_v1(self):
645
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1")
646
+ pipe.to(torch_device)
647
+ pipe.set_progress_bar_config(disable=None)
648
+ pipe.enable_attention_slicing()
649
+
650
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
651
+ del inputs["prompt"]
652
+ sample = pipe(**inputs)
653
+ text = sample.text
654
+
655
+ expected_text_prefix = "An astronaut"
656
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
657
+
658
+
659
+ @nightly
660
+ @require_torch_accelerator
661
+ class UniDiffuserPipelineNightlyTests(unittest.TestCase):
662
+ def setUp(self):
663
+ super().setUp()
664
+ gc.collect()
665
+ backend_empty_cache(torch_device)
666
+
667
+ def tearDown(self):
668
+ super().tearDown()
669
+ gc.collect()
670
+ backend_empty_cache(torch_device)
671
+
672
+ def get_inputs(self, device, seed=0, generate_latents=False):
673
+ generator = torch.manual_seed(seed)
674
+ image = load_image(
675
+ "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg"
676
+ )
677
+ inputs = {
678
+ "prompt": "an elephant under the sea",
679
+ "image": image,
680
+ "generator": generator,
681
+ "num_inference_steps": 3,
682
+ "guidance_scale": 8.0,
683
+ "output_type": "np",
684
+ }
685
+ if generate_latents:
686
+ latents = self.get_fixed_latents(device, seed=seed)
687
+ for latent_name, latent_tensor in latents.items():
688
+ inputs[latent_name] = latent_tensor
689
+ return inputs
690
+
691
+ def get_fixed_latents(self, device, seed=0):
692
+ if isinstance(device, str):
693
+ device = torch.device(device)
694
+ latent_device = torch.device("cpu")
695
+ generator = torch.Generator(device=latent_device).manual_seed(seed)
696
+ # Hardcode the shapes for now.
697
+ prompt_latents = randn_tensor((1, 77, 768), generator=generator, device=device, dtype=torch.float32)
698
+ vae_latents = randn_tensor((1, 4, 64, 64), generator=generator, device=device, dtype=torch.float32)
699
+ clip_latents = randn_tensor((1, 1, 512), generator=generator, device=device, dtype=torch.float32)
700
+
701
+ # Move latents onto desired device.
702
+ prompt_latents = prompt_latents.to(device)
703
+ vae_latents = vae_latents.to(device)
704
+ clip_latents = clip_latents.to(device)
705
+
706
+ latents = {
707
+ "prompt_latents": prompt_latents,
708
+ "vae_latents": vae_latents,
709
+ "clip_latents": clip_latents,
710
+ }
711
+ return latents
712
+
713
+ def test_unidiffuser_default_joint_v1_fp16(self):
714
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16)
715
+ pipe.to(torch_device)
716
+ pipe.set_progress_bar_config(disable=None)
717
+ pipe.enable_attention_slicing()
718
+
719
+ # inputs = self.get_dummy_inputs(device)
720
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
721
+ # Delete prompt and image for joint inference.
722
+ del inputs["prompt"]
723
+ del inputs["image"]
724
+ sample = pipe(**inputs)
725
+ image = sample.images
726
+ text = sample.text
727
+ assert image.shape == (1, 512, 512, 3)
728
+
729
+ image_slice = image[0, -3:, -3:, -1]
730
+ expected_img_slice = np.array([0.2402, 0.2375, 0.2285, 0.2378, 0.2407, 0.2263, 0.2354, 0.2307, 0.2520])
731
+ assert np.abs(image_slice.flatten() - expected_img_slice).max() < 2e-1
732
+
733
+ expected_text_prefix = "a living room"
734
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
735
+
736
+ def test_unidiffuser_default_text2img_v1_fp16(self):
737
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16)
738
+ pipe.to(torch_device)
739
+ pipe.set_progress_bar_config(disable=None)
740
+ pipe.enable_attention_slicing()
741
+
742
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
743
+ del inputs["image"]
744
+ sample = pipe(**inputs)
745
+ image = sample.images
746
+ assert image.shape == (1, 512, 512, 3)
747
+
748
+ image_slice = image[0, -3:, -3:, -1]
749
+ expected_slice = np.array([0.0242, 0.0103, 0.0022, 0.0129, 0.0000, 0.0090, 0.0376, 0.0508, 0.0005])
750
+ assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1
751
+
752
+ def test_unidiffuser_default_img2text_v1_fp16(self):
753
+ pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16)
754
+ pipe.to(torch_device)
755
+ pipe.set_progress_bar_config(disable=None)
756
+ pipe.enable_attention_slicing()
757
+
758
+ inputs = self.get_inputs(device=torch_device, generate_latents=True)
759
+ del inputs["prompt"]
760
+ sample = pipe(**inputs)
761
+ text = sample.text
762
+
763
+ expected_text_prefix = "An astronaut"
764
+ assert text[0][: len(expected_text_prefix)] == expected_text_prefix
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/test_pipeline_visualcloze_combined.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import tempfile
3
+ import unittest
4
+
5
+ import numpy as np
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
9
+
10
+ import diffusers
11
+ from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxTransformer2DModel, VisualClozePipeline
12
+ from diffusers.utils import logging
13
+ from diffusers.utils.testing_utils import (
14
+ CaptureLogger,
15
+ enable_full_determinism,
16
+ floats_tensor,
17
+ require_accelerator,
18
+ torch_device,
19
+ )
20
+
21
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
22
+
23
+
24
+ enable_full_determinism()
25
+
26
+
27
+ class VisualClozePipelineFastTests(unittest.TestCase, PipelineTesterMixin):
28
+ pipeline_class = VisualClozePipeline
29
+ params = frozenset(
30
+ [
31
+ "task_prompt",
32
+ "content_prompt",
33
+ "upsampling_height",
34
+ "upsampling_width",
35
+ "guidance_scale",
36
+ "prompt_embeds",
37
+ "pooled_prompt_embeds",
38
+ "upsampling_strength",
39
+ ]
40
+ )
41
+ batch_params = frozenset(["task_prompt", "content_prompt", "image"])
42
+ test_xformers_attention = False
43
+ test_layerwise_casting = True
44
+ test_group_offloading = True
45
+
46
+ supports_dduf = False
47
+
48
+ def get_dummy_components(self):
49
+ torch.manual_seed(0)
50
+ transformer = FluxTransformer2DModel(
51
+ patch_size=1,
52
+ in_channels=12,
53
+ out_channels=4,
54
+ num_layers=1,
55
+ num_single_layers=1,
56
+ attention_head_dim=6,
57
+ num_attention_heads=2,
58
+ joint_attention_dim=32,
59
+ pooled_projection_dim=32,
60
+ axes_dims_rope=[2, 2, 2],
61
+ )
62
+ clip_text_encoder_config = CLIPTextConfig(
63
+ bos_token_id=0,
64
+ eos_token_id=2,
65
+ hidden_size=32,
66
+ intermediate_size=37,
67
+ layer_norm_eps=1e-05,
68
+ num_attention_heads=4,
69
+ num_hidden_layers=5,
70
+ pad_token_id=1,
71
+ vocab_size=1000,
72
+ hidden_act="gelu",
73
+ projection_dim=32,
74
+ )
75
+
76
+ torch.manual_seed(0)
77
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
78
+
79
+ torch.manual_seed(0)
80
+ text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
81
+
82
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
83
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
84
+
85
+ torch.manual_seed(0)
86
+ vae = AutoencoderKL(
87
+ sample_size=32,
88
+ in_channels=3,
89
+ out_channels=3,
90
+ block_out_channels=(4,),
91
+ layers_per_block=1,
92
+ latent_channels=1,
93
+ norm_num_groups=1,
94
+ use_quant_conv=False,
95
+ use_post_quant_conv=False,
96
+ shift_factor=0.0609,
97
+ scaling_factor=1.5035,
98
+ )
99
+
100
+ scheduler = FlowMatchEulerDiscreteScheduler()
101
+
102
+ return {
103
+ "scheduler": scheduler,
104
+ "text_encoder": text_encoder,
105
+ "text_encoder_2": text_encoder_2,
106
+ "tokenizer": tokenizer,
107
+ "tokenizer_2": tokenizer_2,
108
+ "transformer": transformer,
109
+ "vae": vae,
110
+ "resolution": 32,
111
+ }
112
+
113
+ def get_dummy_inputs(self, device, seed=0):
114
+ # Create example images to simulate the input format required by VisualCloze
115
+ context_image = [
116
+ Image.fromarray(floats_tensor((32, 32, 3), rng=random.Random(seed), scale=255).numpy().astype(np.uint8))
117
+ for _ in range(2)
118
+ ]
119
+ query_image = [
120
+ Image.fromarray(
121
+ floats_tensor((32, 32, 3), rng=random.Random(seed + 1), scale=255).numpy().astype(np.uint8)
122
+ ),
123
+ None,
124
+ ]
125
+
126
+ # Create an image list that conforms to the VisualCloze input format
127
+ image = [
128
+ context_image, # In-Context example
129
+ query_image, # Query image
130
+ ]
131
+
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
+ "task_prompt": "Each row outlines a logical process, starting from [IMAGE1] gray-based depth map with detailed object contours, to achieve [IMAGE2] an image with flawless clarity.",
139
+ "content_prompt": "A beautiful landscape with mountains and a lake",
140
+ "image": image,
141
+ "generator": generator,
142
+ "num_inference_steps": 2,
143
+ "guidance_scale": 5.0,
144
+ "upsampling_height": 32,
145
+ "upsampling_width": 32,
146
+ "max_sequence_length": 77,
147
+ "output_type": "np",
148
+ "upsampling_strength": 0.4,
149
+ }
150
+ return inputs
151
+
152
+ def test_visualcloze_different_prompts(self):
153
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
154
+
155
+ inputs = self.get_dummy_inputs(torch_device)
156
+ output_same_prompt = pipe(**inputs).images[0]
157
+
158
+ inputs = self.get_dummy_inputs(torch_device)
159
+ inputs["task_prompt"] = "A different task to perform."
160
+ output_different_prompts = pipe(**inputs).images[0]
161
+
162
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
163
+
164
+ # Outputs should be different
165
+ assert max_diff > 1e-6
166
+
167
+ def test_visualcloze_image_output_shape(self):
168
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
169
+ inputs = self.get_dummy_inputs(torch_device)
170
+
171
+ height_width_pairs = [(32, 32), (72, 57)]
172
+ for height, width in height_width_pairs:
173
+ expected_height = height - height % (pipe.generation_pipe.vae_scale_factor * 2)
174
+ expected_width = width - width % (pipe.generation_pipe.vae_scale_factor * 2)
175
+
176
+ inputs.update({"upsampling_height": height, "upsampling_width": width})
177
+ image = pipe(**inputs).images[0]
178
+ output_height, output_width, _ = image.shape
179
+ assert (output_height, output_width) == (expected_height, expected_width)
180
+
181
+ def test_inference_batch_single_identical(self):
182
+ self._test_inference_batch_single_identical(expected_max_diff=1e-3)
183
+
184
+ def test_upsampling_strength(self, expected_min_diff=1e-1):
185
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
186
+ inputs = self.get_dummy_inputs(torch_device)
187
+
188
+ # Test different upsampling strengths
189
+ inputs["upsampling_strength"] = 0.2
190
+ output_no_upsampling = pipe(**inputs).images[0]
191
+
192
+ inputs["upsampling_strength"] = 0.8
193
+ output_full_upsampling = pipe(**inputs).images[0]
194
+
195
+ # Different upsampling strengths should produce different outputs
196
+ max_diff = np.abs(output_no_upsampling - output_full_upsampling).max()
197
+ assert max_diff > expected_min_diff
198
+
199
+ def test_different_task_prompts(self, expected_min_diff=1e-1):
200
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
201
+ inputs = self.get_dummy_inputs(torch_device)
202
+
203
+ output_original = pipe(**inputs).images[0]
204
+
205
+ inputs["task_prompt"] = "A different task description for image generation"
206
+ output_different_task = pipe(**inputs).images[0]
207
+
208
+ # Different task prompts should produce different outputs
209
+ max_diff = np.abs(output_original - output_different_task).max()
210
+ assert max_diff > expected_min_diff
211
+
212
+ @unittest.skip(
213
+ "Test not applicable because the pipeline being tested is a wrapper pipeline. CFG tests should be done on the inner pipelines."
214
+ )
215
+ def test_callback_cfg(self):
216
+ pass
217
+
218
+ def test_save_load_local(self, expected_max_difference=5e-4):
219
+ components = self.get_dummy_components()
220
+ pipe = self.pipeline_class(**components)
221
+ for component in pipe.components.values():
222
+ if hasattr(component, "set_default_attn_processor"):
223
+ component.set_default_attn_processor()
224
+
225
+ pipe.to(torch_device)
226
+ pipe.set_progress_bar_config(disable=None)
227
+
228
+ inputs = self.get_dummy_inputs(torch_device)
229
+ output = pipe(**inputs)[0]
230
+
231
+ logger = logging.get_logger("diffusers.pipelines.pipeline_utils")
232
+ logger.setLevel(diffusers.logging.INFO)
233
+
234
+ with tempfile.TemporaryDirectory() as tmpdir:
235
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
236
+
237
+ with CaptureLogger(logger) as cap_logger:
238
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
239
+ # This attribute is not serialized in the config of the pipeline
240
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, resolution=32)
241
+
242
+ for component in pipe_loaded.components.values():
243
+ if hasattr(component, "set_default_attn_processor"):
244
+ component.set_default_attn_processor()
245
+
246
+ for name in pipe_loaded.components.keys():
247
+ if name not in pipe_loaded._optional_components:
248
+ assert name in str(cap_logger)
249
+
250
+ pipe_loaded.to(torch_device)
251
+ pipe_loaded.set_progress_bar_config(disable=None)
252
+
253
+ inputs = self.get_dummy_inputs(torch_device)
254
+ output_loaded = pipe_loaded(**inputs)[0]
255
+
256
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
257
+ self.assertLess(max_diff, expected_max_difference)
258
+
259
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
260
+ if not hasattr(self.pipeline_class, "_optional_components"):
261
+ return
262
+ components = self.get_dummy_components()
263
+ pipe = self.pipeline_class(**components)
264
+ for component in pipe.components.values():
265
+ if hasattr(component, "set_default_attn_processor"):
266
+ component.set_default_attn_processor()
267
+ pipe.to(torch_device)
268
+ pipe.set_progress_bar_config(disable=None)
269
+
270
+ # set all optional components to None
271
+ for optional_component in pipe._optional_components:
272
+ setattr(pipe, optional_component, None)
273
+
274
+ generator_device = "cpu"
275
+ inputs = self.get_dummy_inputs(generator_device)
276
+ torch.manual_seed(0)
277
+ output = pipe(**inputs)[0]
278
+
279
+ with tempfile.TemporaryDirectory() as tmpdir:
280
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
281
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
282
+ # This attribute is not serialized in the config of the pipeline
283
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, resolution=32)
284
+ for component in pipe_loaded.components.values():
285
+ if hasattr(component, "set_default_attn_processor"):
286
+ component.set_default_attn_processor()
287
+ pipe_loaded.to(torch_device)
288
+ pipe_loaded.set_progress_bar_config(disable=None)
289
+
290
+ for optional_component in pipe._optional_components:
291
+ self.assertTrue(
292
+ getattr(pipe_loaded, optional_component) is None,
293
+ f"`{optional_component}` did not stay set to None after loading.",
294
+ )
295
+
296
+ inputs = self.get_dummy_inputs(generator_device)
297
+ torch.manual_seed(0)
298
+ output_loaded = pipe_loaded(**inputs)[0]
299
+
300
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
301
+ self.assertLess(max_diff, expected_max_difference)
302
+
303
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
304
+ @require_accelerator
305
+ def test_save_load_float16(self, expected_max_diff=1e-2):
306
+ components = self.get_dummy_components()
307
+ for name, module in components.items():
308
+ if hasattr(module, "half"):
309
+ components[name] = module.to(torch_device).half()
310
+
311
+ pipe = self.pipeline_class(**components)
312
+ for component in pipe.components.values():
313
+ if hasattr(component, "set_default_attn_processor"):
314
+ component.set_default_attn_processor()
315
+ pipe.to(torch_device)
316
+ pipe.set_progress_bar_config(disable=None)
317
+
318
+ inputs = self.get_dummy_inputs(torch_device)
319
+ output = pipe(**inputs)[0]
320
+
321
+ with tempfile.TemporaryDirectory() as tmpdir:
322
+ pipe.save_pretrained(tmpdir)
323
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
324
+ # This attribute is not serialized in the config of the pipeline
325
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16, resolution=32)
326
+ for component in pipe_loaded.components.values():
327
+ if hasattr(component, "set_default_attn_processor"):
328
+ component.set_default_attn_processor()
329
+ pipe_loaded.to(torch_device)
330
+ pipe_loaded.set_progress_bar_config(disable=None)
331
+
332
+ for name, component in pipe_loaded.components.items():
333
+ if hasattr(component, "dtype"):
334
+ self.assertTrue(
335
+ component.dtype == torch.float16,
336
+ f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
337
+ )
338
+
339
+ inputs = self.get_dummy_inputs(torch_device)
340
+ output_loaded = pipe_loaded(**inputs)[0]
341
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
342
+ self.assertLess(
343
+ max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
344
+ )
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/visualcloze/test_pipeline_visualcloze_generation.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import tempfile
3
+ import unittest
4
+
5
+ import numpy as np
6
+ import torch
7
+ from PIL import Image
8
+ from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
9
+
10
+ import diffusers
11
+ from diffusers import (
12
+ AutoencoderKL,
13
+ FlowMatchEulerDiscreteScheduler,
14
+ FluxTransformer2DModel,
15
+ VisualClozeGenerationPipeline,
16
+ )
17
+ from diffusers.utils import logging
18
+ from diffusers.utils.testing_utils import (
19
+ CaptureLogger,
20
+ enable_full_determinism,
21
+ floats_tensor,
22
+ require_accelerator,
23
+ torch_device,
24
+ )
25
+
26
+ from ..test_pipelines_common import PipelineTesterMixin, to_np
27
+
28
+
29
+ enable_full_determinism()
30
+
31
+
32
+ class VisualClozeGenerationPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
33
+ pipeline_class = VisualClozeGenerationPipeline
34
+ params = frozenset(
35
+ [
36
+ "task_prompt",
37
+ "content_prompt",
38
+ "guidance_scale",
39
+ "prompt_embeds",
40
+ "pooled_prompt_embeds",
41
+ ]
42
+ )
43
+ batch_params = frozenset(["task_prompt", "content_prompt", "image"])
44
+ test_xformers_attention = False
45
+ test_layerwise_casting = True
46
+ test_group_offloading = True
47
+
48
+ supports_dduf = False
49
+
50
+ def get_dummy_components(self):
51
+ torch.manual_seed(0)
52
+ transformer = FluxTransformer2DModel(
53
+ patch_size=1,
54
+ in_channels=12,
55
+ out_channels=4,
56
+ num_layers=1,
57
+ num_single_layers=1,
58
+ attention_head_dim=6,
59
+ num_attention_heads=2,
60
+ joint_attention_dim=32,
61
+ pooled_projection_dim=32,
62
+ axes_dims_rope=[2, 2, 2],
63
+ )
64
+ clip_text_encoder_config = CLIPTextConfig(
65
+ bos_token_id=0,
66
+ eos_token_id=2,
67
+ hidden_size=32,
68
+ intermediate_size=37,
69
+ layer_norm_eps=1e-05,
70
+ num_attention_heads=4,
71
+ num_hidden_layers=5,
72
+ pad_token_id=1,
73
+ vocab_size=1000,
74
+ hidden_act="gelu",
75
+ projection_dim=32,
76
+ )
77
+
78
+ torch.manual_seed(0)
79
+ text_encoder = CLIPTextModel(clip_text_encoder_config)
80
+
81
+ torch.manual_seed(0)
82
+ text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
83
+
84
+ tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
85
+ tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
86
+
87
+ torch.manual_seed(0)
88
+ vae = AutoencoderKL(
89
+ sample_size=32,
90
+ in_channels=3,
91
+ out_channels=3,
92
+ block_out_channels=(4,),
93
+ layers_per_block=1,
94
+ latent_channels=1,
95
+ norm_num_groups=1,
96
+ use_quant_conv=False,
97
+ use_post_quant_conv=False,
98
+ shift_factor=0.0609,
99
+ scaling_factor=1.5035,
100
+ )
101
+
102
+ scheduler = FlowMatchEulerDiscreteScheduler()
103
+
104
+ return {
105
+ "scheduler": scheduler,
106
+ "text_encoder": text_encoder,
107
+ "text_encoder_2": text_encoder_2,
108
+ "tokenizer": tokenizer,
109
+ "tokenizer_2": tokenizer_2,
110
+ "transformer": transformer,
111
+ "vae": vae,
112
+ "resolution": 32,
113
+ }
114
+
115
+ def get_dummy_inputs(self, device, seed=0):
116
+ # Create example images to simulate the input format required by VisualCloze
117
+ context_image = [
118
+ Image.fromarray(floats_tensor((32, 32, 3), rng=random.Random(seed), scale=255).numpy().astype(np.uint8))
119
+ for _ in range(2)
120
+ ]
121
+ query_image = [
122
+ Image.fromarray(
123
+ floats_tensor((32, 32, 3), rng=random.Random(seed + 1), scale=255).numpy().astype(np.uint8)
124
+ ),
125
+ None,
126
+ ]
127
+
128
+ # Create an image list that conforms to the VisualCloze input format
129
+ image = [
130
+ context_image, # In-Context example
131
+ query_image, # Query image
132
+ ]
133
+
134
+ if str(device).startswith("mps"):
135
+ generator = torch.manual_seed(seed)
136
+ else:
137
+ generator = torch.Generator(device="cpu").manual_seed(seed)
138
+
139
+ inputs = {
140
+ "task_prompt": "Each row outlines a logical process, starting from [IMAGE1] gray-based depth map with detailed object contours, to achieve [IMAGE2] an image with flawless clarity.",
141
+ "content_prompt": "A beautiful landscape with mountains and a lake",
142
+ "image": image,
143
+ "generator": generator,
144
+ "num_inference_steps": 2,
145
+ "guidance_scale": 5.0,
146
+ "max_sequence_length": 77,
147
+ "output_type": "np",
148
+ }
149
+ return inputs
150
+
151
+ def test_visualcloze_different_prompts(self):
152
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
153
+
154
+ inputs = self.get_dummy_inputs(torch_device)
155
+ output_same_prompt = pipe(**inputs).images[0]
156
+
157
+ inputs = self.get_dummy_inputs(torch_device)
158
+ inputs["task_prompt"] = "A different task to perform."
159
+ output_different_prompts = pipe(**inputs).images[0]
160
+
161
+ max_diff = np.abs(output_same_prompt - output_different_prompts).max()
162
+
163
+ # Outputs should be different
164
+ assert max_diff > 1e-6
165
+
166
+ def test_inference_batch_single_identical(self):
167
+ self._test_inference_batch_single_identical(expected_max_diff=1e-3)
168
+
169
+ def test_different_task_prompts(self, expected_min_diff=1e-1):
170
+ pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
171
+ inputs = self.get_dummy_inputs(torch_device)
172
+
173
+ output_original = pipe(**inputs).images[0]
174
+
175
+ inputs["task_prompt"] = "A different task description for image generation"
176
+ output_different_task = pipe(**inputs).images[0]
177
+
178
+ # Different task prompts should produce different outputs
179
+ max_diff = np.abs(output_original - output_different_task).max()
180
+ assert max_diff > expected_min_diff
181
+
182
+ def test_save_load_local(self, expected_max_difference=5e-4):
183
+ components = self.get_dummy_components()
184
+ pipe = self.pipeline_class(**components)
185
+ for component in pipe.components.values():
186
+ if hasattr(component, "set_default_attn_processor"):
187
+ component.set_default_attn_processor()
188
+
189
+ pipe.to(torch_device)
190
+ pipe.set_progress_bar_config(disable=None)
191
+
192
+ inputs = self.get_dummy_inputs(torch_device)
193
+ output = pipe(**inputs)[0]
194
+
195
+ logger = logging.get_logger("diffusers.pipelines.pipeline_utils")
196
+ logger.setLevel(diffusers.logging.INFO)
197
+
198
+ with tempfile.TemporaryDirectory() as tmpdir:
199
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
200
+
201
+ with CaptureLogger(logger) as cap_logger:
202
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
203
+ # This attribute is not serialized in the config of the pipeline
204
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, resolution=32)
205
+
206
+ for component in pipe_loaded.components.values():
207
+ if hasattr(component, "set_default_attn_processor"):
208
+ component.set_default_attn_processor()
209
+
210
+ for name in pipe_loaded.components.keys():
211
+ if name not in pipe_loaded._optional_components:
212
+ assert name in str(cap_logger)
213
+
214
+ pipe_loaded.to(torch_device)
215
+ pipe_loaded.set_progress_bar_config(disable=None)
216
+
217
+ inputs = self.get_dummy_inputs(torch_device)
218
+ output_loaded = pipe_loaded(**inputs)[0]
219
+
220
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
221
+ self.assertLess(max_diff, expected_max_difference)
222
+
223
+ def test_save_load_optional_components(self, expected_max_difference=1e-4):
224
+ if not hasattr(self.pipeline_class, "_optional_components"):
225
+ return
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
+ # set all optional components to None
235
+ for optional_component in pipe._optional_components:
236
+ setattr(pipe, optional_component, None)
237
+
238
+ generator_device = "cpu"
239
+ inputs = self.get_dummy_inputs(generator_device)
240
+ torch.manual_seed(0)
241
+ output = pipe(**inputs)[0]
242
+
243
+ with tempfile.TemporaryDirectory() as tmpdir:
244
+ pipe.save_pretrained(tmpdir, safe_serialization=False)
245
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
246
+ # This attribute is not serialized in the config of the pipeline
247
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, resolution=32)
248
+ for component in pipe_loaded.components.values():
249
+ if hasattr(component, "set_default_attn_processor"):
250
+ component.set_default_attn_processor()
251
+ pipe_loaded.to(torch_device)
252
+ pipe_loaded.set_progress_bar_config(disable=None)
253
+
254
+ for optional_component in pipe._optional_components:
255
+ self.assertTrue(
256
+ getattr(pipe_loaded, optional_component) is None,
257
+ f"`{optional_component}` did not stay set to None after loading.",
258
+ )
259
+
260
+ inputs = self.get_dummy_inputs(generator_device)
261
+ torch.manual_seed(0)
262
+ output_loaded = pipe_loaded(**inputs)[0]
263
+
264
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
265
+ self.assertLess(max_diff, expected_max_difference)
266
+
267
+ @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
268
+ @require_accelerator
269
+ def test_save_load_float16(self, expected_max_diff=1e-2):
270
+ components = self.get_dummy_components()
271
+ for name, module in components.items():
272
+ if hasattr(module, "half"):
273
+ components[name] = module.to(torch_device).half()
274
+
275
+ pipe = self.pipeline_class(**components)
276
+ for component in pipe.components.values():
277
+ if hasattr(component, "set_default_attn_processor"):
278
+ component.set_default_attn_processor()
279
+ pipe.to(torch_device)
280
+ pipe.set_progress_bar_config(disable=None)
281
+
282
+ inputs = self.get_dummy_inputs(torch_device)
283
+ output = pipe(**inputs)[0]
284
+
285
+ with tempfile.TemporaryDirectory() as tmpdir:
286
+ pipe.save_pretrained(tmpdir)
287
+ # NOTE: Resolution must be set to 32 for loading otherwise will lead to OOM on CI hardware
288
+ # This attribute is not serialized in the config of the pipeline
289
+ pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16, resolution=32)
290
+ for component in pipe_loaded.components.values():
291
+ if hasattr(component, "set_default_attn_processor"):
292
+ component.set_default_attn_processor()
293
+ pipe_loaded.to(torch_device)
294
+ pipe_loaded.set_progress_bar_config(disable=None)
295
+
296
+ for name, component in pipe_loaded.components.items():
297
+ if hasattr(component, "dtype"):
298
+ self.assertTrue(
299
+ component.dtype == torch.float16,
300
+ f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
301
+ )
302
+
303
+ inputs = self.get_dummy_inputs(torch_device)
304
+ output_loaded = pipe_loaded(**inputs)[0]
305
+ max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
306
+ self.assertLess(
307
+ max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
308
+ )
309
+
310
+ @unittest.skip("Skipped due to missing layout_prompt. Needs further investigation.")
311
+ def test_encode_prompt_works_in_isolation(self, extra_required_param_value_dict=None, atol=0.0001, rtol=0.0001):
312
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/__init__.py ADDED
File without changes
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/test_wan.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 unittest
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import AutoTokenizer, T5EncoderModel
21
+
22
+ from diffusers import AutoencoderKLWan, FlowMatchEulerDiscreteScheduler, WanPipeline, WanTransformer3DModel
23
+ from diffusers.utils.testing_utils import (
24
+ enable_full_determinism,
25
+ require_torch_accelerator,
26
+ slow,
27
+ )
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
+ )
33
+
34
+
35
+ enable_full_determinism()
36
+
37
+
38
+ class WanPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
39
+ pipeline_class = WanPipeline
40
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
41
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
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
+ supports_dduf = False
56
+
57
+ def get_dummy_components(self):
58
+ torch.manual_seed(0)
59
+ vae = AutoencoderKLWan(
60
+ base_dim=3,
61
+ z_dim=16,
62
+ dim_mult=[1, 1, 1, 1],
63
+ num_res_blocks=1,
64
+ temperal_downsample=[False, True, True],
65
+ )
66
+
67
+ torch.manual_seed(0)
68
+ # TODO: impl FlowDPMSolverMultistepScheduler
69
+ scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
70
+ text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
71
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
72
+
73
+ torch.manual_seed(0)
74
+ transformer = WanTransformer3DModel(
75
+ patch_size=(1, 2, 2),
76
+ num_attention_heads=2,
77
+ attention_head_dim=12,
78
+ in_channels=16,
79
+ out_channels=16,
80
+ text_dim=32,
81
+ freq_dim=256,
82
+ ffn_dim=32,
83
+ num_layers=2,
84
+ cross_attn_norm=True,
85
+ qk_norm="rms_norm_across_heads",
86
+ rope_max_seq_len=32,
87
+ )
88
+
89
+ components = {
90
+ "transformer": transformer,
91
+ "vae": vae,
92
+ "scheduler": scheduler,
93
+ "text_encoder": text_encoder,
94
+ "tokenizer": tokenizer,
95
+ }
96
+ return components
97
+
98
+ def get_dummy_inputs(self, device, seed=0):
99
+ if str(device).startswith("mps"):
100
+ generator = torch.manual_seed(seed)
101
+ else:
102
+ generator = torch.Generator(device=device).manual_seed(seed)
103
+ inputs = {
104
+ "prompt": "dance monkey",
105
+ "negative_prompt": "negative", # TODO
106
+ "generator": generator,
107
+ "num_inference_steps": 2,
108
+ "guidance_scale": 6.0,
109
+ "height": 16,
110
+ "width": 16,
111
+ "num_frames": 9,
112
+ "max_sequence_length": 16,
113
+ "output_type": "pt",
114
+ }
115
+ return inputs
116
+
117
+ def test_inference(self):
118
+ device = "cpu"
119
+
120
+ components = self.get_dummy_components()
121
+ pipe = self.pipeline_class(**components)
122
+ pipe.to(device)
123
+ pipe.set_progress_bar_config(disable=None)
124
+
125
+ inputs = self.get_dummy_inputs(device)
126
+ video = pipe(**inputs).frames
127
+ generated_video = video[0]
128
+
129
+ self.assertEqual(generated_video.shape, (9, 3, 16, 16))
130
+ expected_video = torch.randn(9, 3, 16, 16)
131
+ max_diff = np.abs(generated_video - expected_video).max()
132
+ self.assertLessEqual(max_diff, 1e10)
133
+
134
+ @unittest.skip("Test not supported")
135
+ def test_attention_slicing_forward_pass(self):
136
+ pass
137
+
138
+
139
+ @slow
140
+ @require_torch_accelerator
141
+ class WanPipelineIntegrationTests(unittest.TestCase):
142
+ prompt = "A painting of a squirrel eating a burger."
143
+
144
+ def setUp(self):
145
+ super().setUp()
146
+ gc.collect()
147
+ torch.cuda.empty_cache()
148
+
149
+ def tearDown(self):
150
+ super().tearDown()
151
+ gc.collect()
152
+ torch.cuda.empty_cache()
153
+
154
+ @unittest.skip("TODO: test needs to be implemented")
155
+ def test_Wanx(self):
156
+ pass
tasks/tasksmith-48efdcc71e7d/tests/source/tests/pipelines/wan/test_wan_image_to_video.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 unittest
16
+
17
+ import numpy as np
18
+ import torch
19
+ from PIL import Image
20
+ from transformers import (
21
+ AutoTokenizer,
22
+ CLIPImageProcessor,
23
+ CLIPVisionConfig,
24
+ CLIPVisionModelWithProjection,
25
+ T5EncoderModel,
26
+ )
27
+
28
+ from diffusers import AutoencoderKLWan, FlowMatchEulerDiscreteScheduler, WanImageToVideoPipeline, WanTransformer3DModel
29
+ from diffusers.utils.testing_utils import enable_full_determinism
30
+
31
+ from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
32
+ from ..test_pipelines_common import PipelineTesterMixin
33
+
34
+
35
+ enable_full_determinism()
36
+
37
+
38
+ class WanImageToVideoPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
39
+ pipeline_class = WanImageToVideoPipeline
40
+ params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs", "height", "width"}
41
+ batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
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
+ supports_dduf = False
56
+
57
+ def get_dummy_components(self):
58
+ torch.manual_seed(0)
59
+ vae = AutoencoderKLWan(
60
+ base_dim=3,
61
+ z_dim=16,
62
+ dim_mult=[1, 1, 1, 1],
63
+ num_res_blocks=1,
64
+ temperal_downsample=[False, True, True],
65
+ )
66
+
67
+ torch.manual_seed(0)
68
+ # TODO: impl FlowDPMSolverMultistepScheduler
69
+ scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
70
+ text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
71
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
72
+
73
+ torch.manual_seed(0)
74
+ transformer = WanTransformer3DModel(
75
+ patch_size=(1, 2, 2),
76
+ num_attention_heads=2,
77
+ attention_head_dim=12,
78
+ in_channels=36,
79
+ out_channels=16,
80
+ text_dim=32,
81
+ freq_dim=256,
82
+ ffn_dim=32,
83
+ num_layers=2,
84
+ cross_attn_norm=True,
85
+ qk_norm="rms_norm_across_heads",
86
+ rope_max_seq_len=32,
87
+ image_dim=4,
88
+ )
89
+
90
+ torch.manual_seed(0)
91
+ image_encoder_config = CLIPVisionConfig(
92
+ hidden_size=4,
93
+ projection_dim=4,
94
+ num_hidden_layers=2,
95
+ num_attention_heads=2,
96
+ image_size=32,
97
+ intermediate_size=16,
98
+ patch_size=1,
99
+ )
100
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
101
+
102
+ torch.manual_seed(0)
103
+ image_processor = CLIPImageProcessor(crop_size=32, size=32)
104
+
105
+ components = {
106
+ "transformer": transformer,
107
+ "vae": vae,
108
+ "scheduler": scheduler,
109
+ "text_encoder": text_encoder,
110
+ "tokenizer": tokenizer,
111
+ "image_encoder": image_encoder,
112
+ "image_processor": image_processor,
113
+ }
114
+ return components
115
+
116
+ def get_dummy_inputs(self, device, seed=0):
117
+ if str(device).startswith("mps"):
118
+ generator = torch.manual_seed(seed)
119
+ else:
120
+ generator = torch.Generator(device=device).manual_seed(seed)
121
+ image_height = 16
122
+ image_width = 16
123
+ image = Image.new("RGB", (image_width, image_height))
124
+ inputs = {
125
+ "image": image,
126
+ "prompt": "dance monkey",
127
+ "negative_prompt": "negative", # TODO
128
+ "height": image_height,
129
+ "width": image_width,
130
+ "generator": generator,
131
+ "num_inference_steps": 2,
132
+ "guidance_scale": 6.0,
133
+ "num_frames": 9,
134
+ "max_sequence_length": 16,
135
+ "output_type": "pt",
136
+ }
137
+ return inputs
138
+
139
+ def test_inference(self):
140
+ device = "cpu"
141
+
142
+ components = self.get_dummy_components()
143
+ pipe = self.pipeline_class(**components)
144
+ pipe.to(device)
145
+ pipe.set_progress_bar_config(disable=None)
146
+
147
+ inputs = self.get_dummy_inputs(device)
148
+ video = pipe(**inputs).frames
149
+ generated_video = video[0]
150
+
151
+ self.assertEqual(generated_video.shape, (9, 3, 16, 16))
152
+ expected_video = torch.randn(9, 3, 16, 16)
153
+ max_diff = np.abs(generated_video - expected_video).max()
154
+ self.assertLessEqual(max_diff, 1e10)
155
+
156
+ @unittest.skip("Test not supported")
157
+ def test_attention_slicing_forward_pass(self):
158
+ pass
159
+
160
+ @unittest.skip("TODO: revisit failing as it requires a very high threshold to pass")
161
+ def test_inference_batch_single_identical(self):
162
+ pass
163
+
164
+
165
+ class WanFLFToVideoPipelineFastTests(WanImageToVideoPipelineFastTests):
166
+ def get_dummy_components(self):
167
+ torch.manual_seed(0)
168
+ vae = AutoencoderKLWan(
169
+ base_dim=3,
170
+ z_dim=16,
171
+ dim_mult=[1, 1, 1, 1],
172
+ num_res_blocks=1,
173
+ temperal_downsample=[False, True, True],
174
+ )
175
+
176
+ torch.manual_seed(0)
177
+ # TODO: impl FlowDPMSolverMultistepScheduler
178
+ scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
179
+ text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
180
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
181
+
182
+ torch.manual_seed(0)
183
+ transformer = WanTransformer3DModel(
184
+ patch_size=(1, 2, 2),
185
+ num_attention_heads=2,
186
+ attention_head_dim=12,
187
+ in_channels=36,
188
+ out_channels=16,
189
+ text_dim=32,
190
+ freq_dim=256,
191
+ ffn_dim=32,
192
+ num_layers=2,
193
+ cross_attn_norm=True,
194
+ qk_norm="rms_norm_across_heads",
195
+ rope_max_seq_len=32,
196
+ image_dim=4,
197
+ pos_embed_seq_len=2 * (4 * 4 + 1),
198
+ )
199
+
200
+ torch.manual_seed(0)
201
+ image_encoder_config = CLIPVisionConfig(
202
+ hidden_size=4,
203
+ projection_dim=4,
204
+ num_hidden_layers=2,
205
+ num_attention_heads=2,
206
+ image_size=4,
207
+ intermediate_size=16,
208
+ patch_size=1,
209
+ )
210
+ image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
211
+
212
+ torch.manual_seed(0)
213
+ image_processor = CLIPImageProcessor(crop_size=4, size=4)
214
+
215
+ components = {
216
+ "transformer": transformer,
217
+ "vae": vae,
218
+ "scheduler": scheduler,
219
+ "text_encoder": text_encoder,
220
+ "tokenizer": tokenizer,
221
+ "image_encoder": image_encoder,
222
+ "image_processor": image_processor,
223
+ }
224
+ return components
225
+
226
+ def get_dummy_inputs(self, device, seed=0):
227
+ if str(device).startswith("mps"):
228
+ generator = torch.manual_seed(seed)
229
+ else:
230
+ generator = torch.Generator(device=device).manual_seed(seed)
231
+ image_height = 16
232
+ image_width = 16
233
+ image = Image.new("RGB", (image_width, image_height))
234
+ last_image = Image.new("RGB", (image_width, image_height))
235
+ inputs = {
236
+ "image": image,
237
+ "last_image": last_image,
238
+ "prompt": "dance monkey",
239
+ "negative_prompt": "negative",
240
+ "height": image_height,
241
+ "width": image_width,
242
+ "generator": generator,
243
+ "num_inference_steps": 2,
244
+ "guidance_scale": 6.0,
245
+ "num_frames": 9,
246
+ "max_sequence_length": 16,
247
+ "output_type": "pt",
248
+ }
249
+ return inputs