Datasets:

ArXiv:
diffusers-benchmarking-bot commited on
Commit
c6d1527
·
verified ·
1 Parent(s): 03762ee

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. v0.32.0/README.md +0 -0
  2. v0.32.0/README_community_scripts.md +439 -0
  3. v0.32.0/adaptive_mask_inpainting.py +1465 -0
  4. v0.32.0/bit_diffusion.py +264 -0
  5. v0.32.0/checkpoint_merger.py +284 -0
  6. v0.32.0/clip_guided_images_mixing_stable_diffusion.py +445 -0
  7. v0.32.0/clip_guided_stable_diffusion.py +337 -0
  8. v0.32.0/clip_guided_stable_diffusion_img2img.py +490 -0
  9. v0.32.0/composable_stable_diffusion.py +532 -0
  10. v0.32.0/ddim_noise_comparative_analysis.py +190 -0
  11. v0.32.0/dps_pipeline.py +466 -0
  12. v0.32.0/edict_pipeline.py +264 -0
  13. v0.32.0/fresco_v2v.py +0 -0
  14. v0.32.0/gluegen.py +816 -0
  15. v0.32.0/hd_painter.py +1001 -0
  16. v0.32.0/iadb.py +149 -0
  17. v0.32.0/imagic_stable_diffusion.py +470 -0
  18. v0.32.0/img2img_inpainting.py +437 -0
  19. v0.32.0/instaflow_one_step.py +689 -0
  20. v0.32.0/interpolate_stable_diffusion.py +498 -0
  21. v0.32.0/ip_adapter_face_id.py +1128 -0
  22. v0.32.0/kohya_hires_fix.py +468 -0
  23. v0.32.0/latent_consistency_img2img.py +821 -0
  24. v0.32.0/latent_consistency_interpolate.py +999 -0
  25. v0.32.0/latent_consistency_txt2img.py +729 -0
  26. v0.32.0/llm_grounded_diffusion.py +1563 -0
  27. v0.32.0/lpw_stable_diffusion.py +1427 -0
  28. v0.32.0/lpw_stable_diffusion_onnx.py +1148 -0
  29. v0.32.0/lpw_stable_diffusion_xl.py +0 -0
  30. v0.32.0/magic_mix.py +152 -0
  31. v0.32.0/marigold_depth_estimation.py +673 -0
  32. v0.32.0/masked_stable_diffusion_img2img.py +262 -0
  33. v0.32.0/masked_stable_diffusion_xl_img2img.py +682 -0
  34. v0.32.0/matryoshka.py +0 -0
  35. v0.32.0/mixture_canvas.py +501 -0
  36. v0.32.0/mixture_tiling.py +405 -0
  37. v0.32.0/multilingual_stable_diffusion.py +410 -0
  38. v0.32.0/one_step_unet.py +24 -0
  39. v0.32.0/pipeline_animatediff_controlnet.py +1129 -0
  40. v0.32.0/pipeline_animatediff_img2video.py +984 -0
  41. v0.32.0/pipeline_animatediff_ipex.py +1002 -0
  42. v0.32.0/pipeline_demofusion_sdxl.py +1386 -0
  43. v0.32.0/pipeline_fabric.py +751 -0
  44. v0.32.0/pipeline_flux_differential_img2img.py +1024 -0
  45. v0.32.0/pipeline_flux_rf_inversion.py +1060 -0
  46. v0.32.0/pipeline_flux_with_cfg.py +850 -0
  47. v0.32.0/pipeline_hunyuandit_differential_img2img.py +1146 -0
  48. v0.32.0/pipeline_kolors_differential_img2img.py +1280 -0
  49. v0.32.0/pipeline_null_text_inversion.py +260 -0
  50. v0.32.0/pipeline_prompt2prompt.py +1422 -0
v0.32.0/README.md ADDED
The diff for this file is too large to render. See raw diff
 
v0.32.0/README_community_scripts.md ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Community Scripts
2
+
3
+ **Community scripts** consist of inference examples using Diffusers pipelines that have been added by the community.
4
+ Please have a look at the following table to get an overview of all community examples. Click on the **Code Example** to get a copy-and-paste code example that you can try out.
5
+ If a community script doesn't work as expected, please open an issue and ping the author on it.
6
+
7
+ | Example | Description | Code Example | Colab | Author |
8
+ |:--------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------:|
9
+ | Using IP-Adapter with Negative Noise | Using negative noise with IP-adapter to better control the generation (see the [original post](https://github.com/huggingface/diffusers/discussions/7167) on the forum for more details) | [IP-Adapter Negative Noise](#ip-adapter-negative-noise) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/ip_adapter_negative_noise.ipynb) | [Álvaro Somoza](https://github.com/asomoza)|
10
+ | Asymmetric Tiling |configure seamless image tiling independently for the X and Y axes | [Asymmetric Tiling](#Asymmetric-Tiling ) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/asymetric_tiling.ipynb) | [alexisrolland](https://github.com/alexisrolland)|
11
+ | Prompt Scheduling Callback |Allows changing prompts during a generation | [Prompt Scheduling-Callback](#Prompt-Scheduling-Callback ) |[Notebook](https://github.com/huggingface/notebooks/blob/main/diffusers/prompt_scheduling_callback.ipynb) | [hlky](https://github.com/hlky)|
12
+
13
+
14
+ ## Example usages
15
+
16
+ ### IP Adapter Negative Noise
17
+
18
+ Diffusers pipelines are fully integrated with IP-Adapter, which allows you to prompt the diffusion model with an image. However, it does not support negative image prompts (there is no `negative_ip_adapter_image` argument) the same way it supports negative text prompts. When you pass an `ip_adapter_image,` it will create a zero-filled tensor as a negative image. This script shows you how to create a negative noise from `ip_adapter_image` and use it to significantly improve the generation quality while preserving the composition of images.
19
+
20
+ [cubiq](https://github.com/cubiq) initially developed this feature in his [repository](https://github.com/cubiq/ComfyUI_IPAdapter_plus). The community script was contributed by [asomoza](https://github.com/Somoza). You can find more details about this experimentation [this discussion](https://github.com/huggingface/diffusers/discussions/7167)
21
+
22
+ IP-Adapter without negative noise
23
+ |source|result|
24
+ |---|---|
25
+ |![20240229150812](https://github.com/huggingface/diffusers/assets/5442875/901d8bd8-7a59-4fe7-bda1-a0e0d6c7dffd)|![20240229163923_normal](https://github.com/huggingface/diffusers/assets/5442875/3432e25a-ece6-45f4-a3f4-fca354f40b5b)|
26
+
27
+ IP-Adapter with negative noise
28
+ |source|result|
29
+ |---|---|
30
+ |![20240229150812](https://github.com/huggingface/diffusers/assets/5442875/901d8bd8-7a59-4fe7-bda1-a0e0d6c7dffd)|![20240229163923](https://github.com/huggingface/diffusers/assets/5442875/736fd15a-36ba-40c0-a7d8-6ec1ac26f788)|
31
+
32
+ ```python
33
+ import torch
34
+
35
+ from diffusers import AutoencoderKL, DPMSolverMultistepScheduler, StableDiffusionXLPipeline
36
+ from diffusers.models import ImageProjection
37
+ from diffusers.utils import load_image
38
+
39
+
40
+ def encode_image(
41
+ image_encoder,
42
+ feature_extractor,
43
+ image,
44
+ device,
45
+ num_images_per_prompt,
46
+ output_hidden_states=None,
47
+ negative_image=None,
48
+ ):
49
+ dtype = next(image_encoder.parameters()).dtype
50
+
51
+ if not isinstance(image, torch.Tensor):
52
+ image = feature_extractor(image, return_tensors="pt").pixel_values
53
+
54
+ image = image.to(device=device, dtype=dtype)
55
+ if output_hidden_states:
56
+ image_enc_hidden_states = image_encoder(image, output_hidden_states=True).hidden_states[-2]
57
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
58
+
59
+ if negative_image is None:
60
+ uncond_image_enc_hidden_states = image_encoder(
61
+ torch.zeros_like(image), output_hidden_states=True
62
+ ).hidden_states[-2]
63
+ else:
64
+ if not isinstance(negative_image, torch.Tensor):
65
+ negative_image = feature_extractor(negative_image, return_tensors="pt").pixel_values
66
+ negative_image = negative_image.to(device=device, dtype=dtype)
67
+ uncond_image_enc_hidden_states = image_encoder(negative_image, output_hidden_states=True).hidden_states[-2]
68
+
69
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
70
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
71
+ else:
72
+ image_embeds = image_encoder(image).image_embeds
73
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
74
+ uncond_image_embeds = torch.zeros_like(image_embeds)
75
+
76
+ return image_embeds, uncond_image_embeds
77
+
78
+
79
+ @torch.no_grad()
80
+ def prepare_ip_adapter_image_embeds(
81
+ unet,
82
+ image_encoder,
83
+ feature_extractor,
84
+ ip_adapter_image,
85
+ do_classifier_free_guidance,
86
+ device,
87
+ num_images_per_prompt,
88
+ ip_adapter_negative_image=None,
89
+ ):
90
+ if not isinstance(ip_adapter_image, list):
91
+ ip_adapter_image = [ip_adapter_image]
92
+
93
+ if len(ip_adapter_image) != len(unet.encoder_hid_proj.image_projection_layers):
94
+ raise ValueError(
95
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
96
+ )
97
+
98
+ image_embeds = []
99
+ for single_ip_adapter_image, image_proj_layer in zip(
100
+ ip_adapter_image, unet.encoder_hid_proj.image_projection_layers
101
+ ):
102
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
103
+ single_image_embeds, single_negative_image_embeds = encode_image(
104
+ image_encoder,
105
+ feature_extractor,
106
+ single_ip_adapter_image,
107
+ device,
108
+ 1,
109
+ output_hidden_state,
110
+ negative_image=ip_adapter_negative_image,
111
+ )
112
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
113
+ single_negative_image_embeds = torch.stack([single_negative_image_embeds] * num_images_per_prompt, dim=0)
114
+
115
+ if do_classifier_free_guidance:
116
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
117
+ single_image_embeds = single_image_embeds.to(device)
118
+
119
+ image_embeds.append(single_image_embeds)
120
+
121
+ return image_embeds
122
+
123
+
124
+ vae = AutoencoderKL.from_pretrained(
125
+ "madebyollin/sdxl-vae-fp16-fix",
126
+ torch_dtype=torch.float16,
127
+ ).to("cuda")
128
+
129
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
130
+ "RunDiffusion/Juggernaut-XL-v9",
131
+ torch_dtype=torch.float16,
132
+ vae=vae,
133
+ variant="fp16",
134
+ ).to("cuda")
135
+
136
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
137
+ pipeline.scheduler.config.use_karras_sigmas = True
138
+
139
+ pipeline.load_ip_adapter(
140
+ "h94/IP-Adapter",
141
+ subfolder="sdxl_models",
142
+ weight_name="ip-adapter-plus_sdxl_vit-h.safetensors",
143
+ image_encoder_folder="models/image_encoder",
144
+ )
145
+ pipeline.set_ip_adapter_scale(0.7)
146
+
147
+ ip_image = load_image("source.png")
148
+ negative_ip_image = load_image("noise.png")
149
+
150
+ image_embeds = prepare_ip_adapter_image_embeds(
151
+ unet=pipeline.unet,
152
+ image_encoder=pipeline.image_encoder,
153
+ feature_extractor=pipeline.feature_extractor,
154
+ ip_adapter_image=[[ip_image]],
155
+ do_classifier_free_guidance=True,
156
+ device="cuda",
157
+ num_images_per_prompt=1,
158
+ ip_adapter_negative_image=negative_ip_image,
159
+ )
160
+
161
+
162
+ prompt = "cinematic photo of a cyborg in the city, 4k, high quality, intricate, highly detailed"
163
+ negative_prompt = "blurry, smooth, plastic"
164
+
165
+ image = pipeline(
166
+ prompt=prompt,
167
+ negative_prompt=negative_prompt,
168
+ ip_adapter_image_embeds=image_embeds,
169
+ guidance_scale=6.0,
170
+ num_inference_steps=25,
171
+ generator=torch.Generator(device="cpu").manual_seed(1556265306),
172
+ ).images[0]
173
+
174
+ image.save("result.png")
175
+ ```
176
+
177
+ ### Asymmetric Tiling
178
+ Stable Diffusion is not trained to generate seamless textures. However, you can use this simple script to add tiling to your generation. This script is contributed by [alexisrolland](https://github.com/alexisrolland). See more details in the [this issue](https://github.com/huggingface/diffusers/issues/556)
179
+
180
+
181
+ |Generated|Tiled|
182
+ |---|---|
183
+ |![20240313003235_573631814](https://github.com/huggingface/diffusers/assets/5442875/eca174fb-06a4-464e-a3a7-00dbb024543e)|![wall](https://github.com/huggingface/diffusers/assets/5442875/b4aa774b-2a6a-4316-a8eb-8f30b5f4d024)|
184
+
185
+
186
+ ```py
187
+ import torch
188
+ from typing import Optional
189
+ from diffusers import StableDiffusionPipeline
190
+ from diffusers.models.lora import LoRACompatibleConv
191
+
192
+ def seamless_tiling(pipeline, x_axis, y_axis):
193
+ def asymmetric_conv2d_convforward(self, input: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None):
194
+ self.paddingX = (self._reversed_padding_repeated_twice[0], self._reversed_padding_repeated_twice[1], 0, 0)
195
+ self.paddingY = (0, 0, self._reversed_padding_repeated_twice[2], self._reversed_padding_repeated_twice[3])
196
+ working = torch.nn.functional.pad(input, self.paddingX, mode=x_mode)
197
+ working = torch.nn.functional.pad(working, self.paddingY, mode=y_mode)
198
+ return torch.nn.functional.conv2d(working, weight, bias, self.stride, torch.nn.modules.utils._pair(0), self.dilation, self.groups)
199
+ x_mode = 'circular' if x_axis else 'constant'
200
+ y_mode = 'circular' if y_axis else 'constant'
201
+ targets = [pipeline.vae, pipeline.text_encoder, pipeline.unet]
202
+ convolution_layers = []
203
+ for target in targets:
204
+ for module in target.modules():
205
+ if isinstance(module, torch.nn.Conv2d):
206
+ convolution_layers.append(module)
207
+ for layer in convolution_layers:
208
+ if isinstance(layer, LoRACompatibleConv) and layer.lora_layer is None:
209
+ layer.lora_layer = lambda * x: 0
210
+ layer._conv_forward = asymmetric_conv2d_convforward.__get__(layer, torch.nn.Conv2d)
211
+ return pipeline
212
+
213
+ pipeline = StableDiffusionPipeline.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True)
214
+ pipeline.enable_model_cpu_offload()
215
+ prompt = ["texture of a red brick wall"]
216
+ seed = 123456
217
+ generator = torch.Generator(device='cuda').manual_seed(seed)
218
+
219
+ pipeline = seamless_tiling(pipeline=pipeline, x_axis=True, y_axis=True)
220
+ image = pipeline(
221
+ prompt=prompt,
222
+ width=512,
223
+ height=512,
224
+ num_inference_steps=20,
225
+ guidance_scale=7,
226
+ num_images_per_prompt=1,
227
+ generator=generator
228
+ ).images[0]
229
+ seamless_tiling(pipeline=pipeline, x_axis=False, y_axis=False)
230
+
231
+ torch.cuda.empty_cache()
232
+ image.save('image.png')
233
+ ```
234
+
235
+ ### Prompt Scheduling callback
236
+
237
+ Prompt scheduling callback allows changing prompts during a generation, like [prompt editing in A1111](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Features#prompt-editing)
238
+
239
+ ```python
240
+ from diffusers import StableDiffusionPipeline
241
+ from diffusers.callbacks import PipelineCallback, MultiPipelineCallbacks
242
+ from diffusers.configuration_utils import register_to_config
243
+ import torch
244
+ from typing import Any, Dict, Tuple, Union
245
+
246
+
247
+ class SDPromptSchedulingCallback(PipelineCallback):
248
+ @register_to_config
249
+ def __init__(
250
+ self,
251
+ encoded_prompt: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
252
+ cutoff_step_ratio=None,
253
+ cutoff_step_index=None,
254
+ ):
255
+ super().__init__(
256
+ cutoff_step_ratio=cutoff_step_ratio, cutoff_step_index=cutoff_step_index
257
+ )
258
+
259
+ tensor_inputs = ["prompt_embeds"]
260
+
261
+ def callback_fn(
262
+ self, pipeline, step_index, timestep, callback_kwargs
263
+ ) -> Dict[str, Any]:
264
+ cutoff_step_ratio = self.config.cutoff_step_ratio
265
+ cutoff_step_index = self.config.cutoff_step_index
266
+ if isinstance(self.config.encoded_prompt, tuple):
267
+ prompt_embeds, negative_prompt_embeds = self.config.encoded_prompt
268
+ else:
269
+ prompt_embeds = self.config.encoded_prompt
270
+
271
+ # Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio
272
+ cutoff_step = (
273
+ cutoff_step_index
274
+ if cutoff_step_index is not None
275
+ else int(pipeline.num_timesteps * cutoff_step_ratio)
276
+ )
277
+
278
+ if step_index == cutoff_step:
279
+ if pipeline.do_classifier_free_guidance:
280
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
281
+ callback_kwargs[self.tensor_inputs[0]] = prompt_embeds
282
+ return callback_kwargs
283
+
284
+
285
+ pipeline: StableDiffusionPipeline = StableDiffusionPipeline.from_pretrained(
286
+ "stable-diffusion-v1-5/stable-diffusion-v1-5",
287
+ torch_dtype=torch.float16,
288
+ variant="fp16",
289
+ use_safetensors=True,
290
+ ).to("cuda")
291
+ pipeline.safety_checker = None
292
+ pipeline.requires_safety_checker = False
293
+
294
+ callback = MultiPipelineCallbacks(
295
+ [
296
+ SDPromptSchedulingCallback(
297
+ encoded_prompt=pipeline.encode_prompt(
298
+ prompt=f"prompt {index}",
299
+ negative_prompt=f"negative prompt {index}",
300
+ device=pipeline._execution_device,
301
+ num_images_per_prompt=1,
302
+ # pipeline.do_classifier_free_guidance can't be accessed until after pipeline is ran
303
+ do_classifier_free_guidance=True,
304
+ ),
305
+ cutoff_step_index=index,
306
+ ) for index in range(1, 20)
307
+ ]
308
+ )
309
+
310
+ image = pipeline(
311
+ prompt="prompt"
312
+ negative_prompt="negative prompt",
313
+ callback_on_step_end=callback,
314
+ callback_on_step_end_tensor_inputs=["prompt_embeds"],
315
+ ).images[0]
316
+ torch.cuda.empty_cache()
317
+ image.save('image.png')
318
+ ```
319
+
320
+ ```python
321
+ from diffusers import StableDiffusionXLPipeline
322
+ from diffusers.callbacks import PipelineCallback, MultiPipelineCallbacks
323
+ from diffusers.configuration_utils import register_to_config
324
+ import torch
325
+ from typing import Any, Dict, Tuple, Union
326
+
327
+
328
+ class SDXLPromptSchedulingCallback(PipelineCallback):
329
+ @register_to_config
330
+ def __init__(
331
+ self,
332
+ encoded_prompt: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
333
+ add_text_embeds: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
334
+ add_time_ids: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
335
+ cutoff_step_ratio=None,
336
+ cutoff_step_index=None,
337
+ ):
338
+ super().__init__(
339
+ cutoff_step_ratio=cutoff_step_ratio, cutoff_step_index=cutoff_step_index
340
+ )
341
+
342
+ tensor_inputs = ["prompt_embeds", "add_text_embeds", "add_time_ids"]
343
+
344
+ def callback_fn(
345
+ self, pipeline, step_index, timestep, callback_kwargs
346
+ ) -> Dict[str, Any]:
347
+ cutoff_step_ratio = self.config.cutoff_step_ratio
348
+ cutoff_step_index = self.config.cutoff_step_index
349
+ if isinstance(self.config.encoded_prompt, tuple):
350
+ prompt_embeds, negative_prompt_embeds = self.config.encoded_prompt
351
+ else:
352
+ prompt_embeds = self.config.encoded_prompt
353
+ if isinstance(self.config.add_text_embeds, tuple):
354
+ add_text_embeds, negative_add_text_embeds = self.config.add_text_embeds
355
+ else:
356
+ add_text_embeds = self.config.add_text_embeds
357
+ if isinstance(self.config.add_time_ids, tuple):
358
+ add_time_ids, negative_add_time_ids = self.config.add_time_ids
359
+ else:
360
+ add_time_ids = self.config.add_time_ids
361
+
362
+ # Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio
363
+ cutoff_step = (
364
+ cutoff_step_index
365
+ if cutoff_step_index is not None
366
+ else int(pipeline.num_timesteps * cutoff_step_ratio)
367
+ )
368
+
369
+ if step_index == cutoff_step:
370
+ if pipeline.do_classifier_free_guidance:
371
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
372
+ add_text_embeds = torch.cat([negative_add_text_embeds, add_text_embeds])
373
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids])
374
+ callback_kwargs[self.tensor_inputs[0]] = prompt_embeds
375
+ callback_kwargs[self.tensor_inputs[1]] = add_text_embeds
376
+ callback_kwargs[self.tensor_inputs[2]] = add_time_ids
377
+ return callback_kwargs
378
+
379
+
380
+ pipeline: StableDiffusionXLPipeline = StableDiffusionXLPipeline.from_pretrained(
381
+ "stabilityai/stable-diffusion-xl-base-1.0",
382
+ torch_dtype=torch.float16,
383
+ variant="fp16",
384
+ use_safetensors=True,
385
+ ).to("cuda")
386
+
387
+ callbacks = []
388
+ for index in range(1, 20):
389
+ (
390
+ prompt_embeds,
391
+ negative_prompt_embeds,
392
+ pooled_prompt_embeds,
393
+ negative_pooled_prompt_embeds,
394
+ ) = pipeline.encode_prompt(
395
+ prompt=f"prompt {index}",
396
+ negative_prompt=f"prompt {index}",
397
+ device=pipeline._execution_device,
398
+ num_images_per_prompt=1,
399
+ # pipeline.do_classifier_free_guidance can't be accessed until after pipeline is ran
400
+ do_classifier_free_guidance=True,
401
+ )
402
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
403
+ add_time_ids = pipeline._get_add_time_ids(
404
+ (1024, 1024),
405
+ (0, 0),
406
+ (1024, 1024),
407
+ dtype=prompt_embeds.dtype,
408
+ text_encoder_projection_dim=text_encoder_projection_dim,
409
+ )
410
+ negative_add_time_ids = pipeline._get_add_time_ids(
411
+ (1024, 1024),
412
+ (0, 0),
413
+ (1024, 1024),
414
+ dtype=prompt_embeds.dtype,
415
+ text_encoder_projection_dim=text_encoder_projection_dim,
416
+ )
417
+ callbacks.append(
418
+ SDXLPromptSchedulingCallback(
419
+ encoded_prompt=(prompt_embeds, negative_prompt_embeds),
420
+ add_text_embeds=(pooled_prompt_embeds, negative_pooled_prompt_embeds),
421
+ add_time_ids=(add_time_ids, negative_add_time_ids),
422
+ cutoff_step_index=index,
423
+ )
424
+ )
425
+
426
+
427
+ callback = MultiPipelineCallbacks(callbacks)
428
+
429
+ image = pipeline(
430
+ prompt="prompt",
431
+ negative_prompt="negative prompt",
432
+ callback_on_step_end=callback,
433
+ callback_on_step_end_tensor_inputs=[
434
+ "prompt_embeds",
435
+ "add_text_embeds",
436
+ "add_time_ids",
437
+ ],
438
+ ).images[0]
439
+ ```
v0.32.0/adaptive_mask_inpainting.py ADDED
@@ -0,0 +1,1465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/
16
+
17
+ import inspect
18
+ import os
19
+ import shutil
20
+ from glob import glob
21
+ from typing import Any, Callable, Dict, List, Optional, Union
22
+
23
+ import cv2
24
+ import numpy as np
25
+ import PIL.Image
26
+ import requests
27
+ import torch
28
+ from detectron2.config import get_cfg
29
+ from detectron2.data import MetadataCatalog
30
+ from detectron2.engine import DefaultPredictor
31
+ from detectron2.projects import point_rend
32
+ from detectron2.structures.instances import Instances
33
+ from detectron2.utils.visualizer import ColorMode, Visualizer
34
+ from packaging import version
35
+ from tqdm import tqdm
36
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
37
+
38
+ from diffusers.configuration_utils import FrozenDict
39
+ from diffusers.image_processor import VaeImageProcessor
40
+ from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
41
+ from diffusers.models import AsymmetricAutoencoderKL, AutoencoderKL, UNet2DConditionModel
42
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
43
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
44
+ from diffusers.schedulers import KarrasDiffusionSchedulers
45
+ from diffusers.utils import (
46
+ deprecate,
47
+ is_accelerate_available,
48
+ is_accelerate_version,
49
+ logging,
50
+ randn_tensor,
51
+ )
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+
57
+ AMI_INSTALL_MESSAGE = """
58
+
59
+ Example Demo of Adaptive Mask Inpainting
60
+
61
+ Beyond the Contact: Discovering Comprehensive Affordance for 3D Objects from Pre-trained 2D Diffusion Models
62
+ Kim et al.
63
+ ECCV-2024 (Oral)
64
+
65
+
66
+ Please prepare the environment via
67
+
68
+ ```
69
+ conda create --name ami python=3.9 -y
70
+ conda activate ami
71
+
72
+ conda install pytorch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 cudatoolkit=11.3 -c pytorch -c conda-forge -y
73
+ python -m pip install detectron2==0.6 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu113/torch1.10/index.html
74
+ pip install easydict
75
+ pip install diffusers==0.20.2 accelerate safetensors transformers
76
+ pip install setuptools==59.5.0
77
+ pip install opencv-python
78
+ pip install numpy==1.24.1
79
+ ```
80
+
81
+
82
+ Put the code inside the root of diffusers library (e.g., as '/home/username/diffusers/adaptive_mask_inpainting_example.py') and run the python code.
83
+
84
+
85
+
86
+
87
+ """
88
+
89
+
90
+ EXAMPLE_DOC_STRING = """
91
+ Examples:
92
+ ```py
93
+ >>> # !pip install transformers accelerate
94
+ >>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler
95
+ >>> from diffusers.utils import load_image
96
+ >>> import numpy as np
97
+ >>> import torch
98
+
99
+ >>> init_image = load_image(
100
+ ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
101
+ ... )
102
+ >>> init_image = init_image.resize((512, 512))
103
+
104
+ >>> generator = torch.Generator(device="cpu").manual_seed(1)
105
+
106
+ >>> mask_image = load_image(
107
+ ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
108
+ ... )
109
+ >>> mask_image = mask_image.resize((512, 512))
110
+
111
+
112
+ >>> def make_inpaint_condition(image, image_mask):
113
+ ... image = np.array(image.convert("RGB")).astype(np.float32) / 255.0
114
+ ... image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0
115
+
116
+ ... assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
117
+ ... image[image_mask > 0.5] = -1.0 # set as masked pixel
118
+ ... image = np.expand_dims(image, 0).transpose(0, 3, 1, 2)
119
+ ... image = torch.from_numpy(image)
120
+ ... return image
121
+
122
+
123
+ >>> control_image = make_inpaint_condition(init_image, mask_image)
124
+
125
+ >>> controlnet = ControlNetModel.from_pretrained(
126
+ ... "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16
127
+ ... )
128
+ >>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
129
+ ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
130
+ ... )
131
+
132
+ >>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
133
+ >>> pipe.enable_model_cpu_offload()
134
+
135
+ >>> # generate image
136
+ >>> image = pipe(
137
+ ... "a handsome man with ray-ban sunglasses",
138
+ ... num_inference_steps=20,
139
+ ... generator=generator,
140
+ ... eta=1.0,
141
+ ... image=init_image,
142
+ ... mask_image=mask_image,
143
+ ... control_image=control_image,
144
+ ... ).images[0]
145
+ ```
146
+ """
147
+
148
+
149
+ def download_file(url, output_file, exist_ok: bool):
150
+ if exist_ok and os.path.exists(output_file):
151
+ return
152
+
153
+ response = requests.get(url, stream=True)
154
+
155
+ with open(output_file, "wb") as file:
156
+ for chunk in tqdm(response.iter_content(chunk_size=8192), desc=f"Downloading '{output_file}'..."):
157
+ if chunk:
158
+ file.write(chunk)
159
+
160
+
161
+ def generate_video_from_imgs(images_save_directory, fps=15.0, delete_dir=True):
162
+ # delete videos if exists
163
+ if os.path.exists(f"{images_save_directory}.mp4"):
164
+ os.remove(f"{images_save_directory}.mp4")
165
+ if os.path.exists(f"{images_save_directory}_before_process.mp4"):
166
+ os.remove(f"{images_save_directory}_before_process.mp4")
167
+
168
+ # assume there are "enumerated" images under "images_save_directory"
169
+ assert os.path.isdir(images_save_directory)
170
+ ImgPaths = sorted(glob(f"{images_save_directory}/*"))
171
+
172
+ if len(ImgPaths) == 0:
173
+ print("\tSkipping, since there must be at least one image to create mp4\n")
174
+ else:
175
+ # mp4 configuration
176
+ video_path = images_save_directory + "_before_process.mp4"
177
+
178
+ # Get height and width config
179
+ images = sorted([ImgPath.split("/")[-1] for ImgPath in ImgPaths if ImgPath.endswith(".png")])
180
+ frame = cv2.imread(os.path.join(images_save_directory, images[0]))
181
+ height, width, channels = frame.shape
182
+
183
+ # create mp4 video writer
184
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
185
+ video = cv2.VideoWriter(video_path, fourcc, fps, (width, height))
186
+ for image in images:
187
+ video.write(cv2.imread(os.path.join(images_save_directory, image)))
188
+ cv2.destroyAllWindows()
189
+ video.release()
190
+
191
+ # generated video is not compatible with HTML5. Post-process and change codec of video, so that it is applicable to HTML.
192
+ os.system(
193
+ f'ffmpeg -i "{images_save_directory}_before_process.mp4" -vcodec libx264 -f mp4 "{images_save_directory}.mp4" '
194
+ )
195
+
196
+ # remove group of images, and remove video before post-process.
197
+ if delete_dir and os.path.exists(images_save_directory):
198
+ shutil.rmtree(images_save_directory)
199
+ # remove 'before-process' video
200
+ if os.path.exists(f"{images_save_directory}_before_process.mp4"):
201
+ os.remove(f"{images_save_directory}_before_process.mp4")
202
+
203
+
204
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.prepare_mask_and_masked_image
205
+ def prepare_mask_and_masked_image(image, mask, height, width, return_image=False):
206
+ """
207
+ Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
208
+ converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the
209
+ ``image`` and ``1`` for the ``mask``.
210
+
211
+ The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be
212
+ binarized (``mask > 0.5``) and cast to ``torch.float32`` too.
213
+
214
+ Args:
215
+ image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint.
216
+ It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width``
217
+ ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``.
218
+ mask (_type_): The mask to apply to the image, i.e. regions to inpaint.
219
+ It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width``
220
+ ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``.
221
+
222
+
223
+ Raises:
224
+ ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask
225
+ should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions.
226
+ TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not
227
+ (ot the other way around).
228
+
229
+ Returns:
230
+ tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4
231
+ dimensions: ``batch x channels x height x width``.
232
+ """
233
+
234
+ if image is None:
235
+ raise ValueError("`image` input cannot be undefined.")
236
+
237
+ if mask is None:
238
+ raise ValueError("`mask_image` input cannot be undefined.")
239
+
240
+ if isinstance(image, torch.Tensor):
241
+ if not isinstance(mask, torch.Tensor):
242
+ raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not")
243
+
244
+ # Batch single image
245
+ if image.ndim == 3:
246
+ assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)"
247
+ image = image.unsqueeze(0)
248
+
249
+ # Batch and add channel dim for single mask
250
+ if mask.ndim == 2:
251
+ mask = mask.unsqueeze(0).unsqueeze(0)
252
+
253
+ # Batch single mask or add channel dim
254
+ if mask.ndim == 3:
255
+ # Single batched mask, no channel dim or single mask not batched but channel dim
256
+ if mask.shape[0] == 1:
257
+ mask = mask.unsqueeze(0)
258
+
259
+ # Batched masks no channel dim
260
+ else:
261
+ mask = mask.unsqueeze(1)
262
+
263
+ assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions"
264
+ assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions"
265
+ assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size"
266
+
267
+ # Check image is in [-1, 1]
268
+ if image.min() < -1 or image.max() > 1:
269
+ raise ValueError("Image should be in [-1, 1] range")
270
+
271
+ # Check mask is in [0, 1]
272
+ if mask.min() < 0 or mask.max() > 1:
273
+ raise ValueError("Mask should be in [0, 1] range")
274
+
275
+ # Binarize mask
276
+ mask[mask < 0.5] = 0
277
+ mask[mask >= 0.5] = 1
278
+
279
+ # Image as float32
280
+ image = image.to(dtype=torch.float32)
281
+ elif isinstance(mask, torch.Tensor):
282
+ raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not")
283
+ else:
284
+ # preprocess image
285
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
286
+ image = [image]
287
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
288
+ # resize all images w.r.t passed height an width
289
+ image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image]
290
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
291
+ image = np.concatenate(image, axis=0)
292
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
293
+ image = np.concatenate([i[None, :] for i in image], axis=0)
294
+
295
+ image = image.transpose(0, 3, 1, 2)
296
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
297
+
298
+ # preprocess mask
299
+ if isinstance(mask, (PIL.Image.Image, np.ndarray)):
300
+ mask = [mask]
301
+
302
+ if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image):
303
+ mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask]
304
+ mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
305
+ mask = mask.astype(np.float32) / 255.0
306
+ elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
307
+ mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
308
+
309
+ mask[mask < 0.5] = 0
310
+ mask[mask >= 0.5] = 1
311
+ mask = torch.from_numpy(mask)
312
+
313
+ masked_image = image * (mask < 0.5)
314
+
315
+ # n.b. ensure backwards compatibility as old function does not return image
316
+ if return_image:
317
+ return mask, masked_image, image
318
+
319
+ return mask, masked_image
320
+
321
+
322
+ class AdaptiveMaskInpaintPipeline(
323
+ DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
324
+ ):
325
+ r"""
326
+ Pipeline for text-guided image inpainting using Stable Diffusion.
327
+
328
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
329
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
330
+
331
+ The pipeline also inherits the following loading methods:
332
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
333
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
334
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
335
+
336
+ Args:
337
+ vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]):
338
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
339
+ text_encoder ([`CLIPTextModel`]):
340
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
341
+ tokenizer ([`~transformers.CLIPTokenizer`]):
342
+ A `CLIPTokenizer` to tokenize text.
343
+ unet ([`UNet2DConditionModel`]):
344
+ A `UNet2DConditionModel` to denoise the encoded image latents.
345
+ scheduler ([`SchedulerMixin`]):
346
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
347
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
348
+ safety_checker ([`StableDiffusionSafetyChecker`]):
349
+ Classification module that estimates whether generated images could be considered offensive or harmful.
350
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
351
+ about a model's potential harms.
352
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
353
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
354
+ """
355
+
356
+ _optional_components = ["safety_checker", "feature_extractor"]
357
+
358
+ def __init__(
359
+ self,
360
+ vae: Union[AutoencoderKL, AsymmetricAutoencoderKL],
361
+ text_encoder: CLIPTextModel,
362
+ tokenizer: CLIPTokenizer,
363
+ unet: UNet2DConditionModel,
364
+ scheduler: KarrasDiffusionSchedulers,
365
+ # safety_checker: StableDiffusionSafetyChecker,
366
+ safety_checker,
367
+ feature_extractor: CLIPImageProcessor,
368
+ requires_safety_checker: bool = True,
369
+ ):
370
+ super().__init__()
371
+
372
+ self.register_adaptive_mask_model()
373
+ self.register_adaptive_mask_settings()
374
+
375
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
376
+ deprecation_message = (
377
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
378
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
379
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
380
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
381
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
382
+ " file"
383
+ )
384
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
385
+ new_config = dict(scheduler.config)
386
+ new_config["steps_offset"] = 1
387
+ scheduler._internal_dict = FrozenDict(new_config)
388
+
389
+ if hasattr(scheduler.config, "skip_prk_steps") and scheduler.config.skip_prk_steps is False:
390
+ deprecation_message = (
391
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration"
392
+ " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"
393
+ " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"
394
+ " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"
395
+ " Hub, it would be very nice if you could open a Pull request for the"
396
+ " `scheduler/scheduler_config.json` file"
397
+ )
398
+ deprecate("skip_prk_steps not set", "1.0.0", deprecation_message, standard_warn=False)
399
+ new_config = dict(scheduler.config)
400
+ new_config["skip_prk_steps"] = True
401
+ scheduler._internal_dict = FrozenDict(new_config)
402
+
403
+ if safety_checker is None and requires_safety_checker:
404
+ logger.warning(
405
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
406
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
407
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
408
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
409
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
410
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
411
+ )
412
+
413
+ if safety_checker is not None and feature_extractor is None:
414
+ raise ValueError(
415
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
416
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
417
+ )
418
+
419
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
420
+ version.parse(unet.config._diffusers_version).base_version
421
+ ) < version.parse("0.9.0.dev0")
422
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
423
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
424
+ deprecation_message = (
425
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
426
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
427
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
428
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
429
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
430
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
431
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
432
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
433
+ " the `unet/config.json` file"
434
+ )
435
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
436
+ new_config = dict(unet.config)
437
+ new_config["sample_size"] = 64
438
+ unet._internal_dict = FrozenDict(new_config)
439
+
440
+ # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4
441
+ if unet.config.in_channels != 9:
442
+ logger.info(f"You have loaded a UNet with {unet.config.in_channels} input channels which.")
443
+
444
+ self.register_modules(
445
+ vae=vae,
446
+ text_encoder=text_encoder,
447
+ tokenizer=tokenizer,
448
+ unet=unet,
449
+ scheduler=scheduler,
450
+ safety_checker=safety_checker,
451
+ feature_extractor=feature_extractor,
452
+ )
453
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
454
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
455
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
456
+
457
+ """ Preparation for Adaptive Mask inpainting """
458
+
459
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload
460
+ def enable_model_cpu_offload(self, gpu_id=0):
461
+ r"""
462
+ Offload all models to CPU to reduce memory usage with a low impact on performance. Moves one whole model at a
463
+ time to the GPU when its `forward` method is called, and the model remains in GPU until the next model runs.
464
+ Memory savings are lower than using `enable_sequential_cpu_offload`, but performance is much better due to the
465
+ iterative execution of the `unet`.
466
+ """
467
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
468
+ from accelerate import cpu_offload_with_hook
469
+ else:
470
+ raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
471
+
472
+ device = torch.device(f"cuda:{gpu_id}")
473
+
474
+ if self.device.type != "cpu":
475
+ self.to("cpu", silence_dtype_warnings=True)
476
+ torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
477
+
478
+ hook = None
479
+ for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]:
480
+ _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook)
481
+
482
+ if self.safety_checker is not None:
483
+ _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook)
484
+
485
+ # We'll offload the last model manually.
486
+ self.final_offload_hook = hook
487
+
488
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
489
+ def _encode_prompt(
490
+ self,
491
+ prompt,
492
+ device,
493
+ num_images_per_prompt,
494
+ do_classifier_free_guidance,
495
+ negative_prompt=None,
496
+ prompt_embeds: Optional[torch.FloatTensor] = None,
497
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
498
+ lora_scale: Optional[float] = None,
499
+ ):
500
+ r"""
501
+ Encodes the prompt into text encoder hidden states.
502
+
503
+ Args:
504
+ prompt (`str` or `List[str]`, *optional*):
505
+ prompt to be encoded
506
+ device: (`torch.device`):
507
+ torch device
508
+ num_images_per_prompt (`int`):
509
+ number of images that should be generated per prompt
510
+ do_classifier_free_guidance (`bool`):
511
+ whether to use classifier free guidance or not
512
+ negative_prompt (`str` or `List[str]`, *optional*):
513
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
514
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
515
+ less than `1`).
516
+ prompt_embeds (`torch.FloatTensor`, *optional*):
517
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
518
+ provided, text embeddings will be generated from `prompt` input argument.
519
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
520
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
521
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
522
+ argument.
523
+ lora_scale (`float`, *optional*):
524
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
525
+ """
526
+ # set lora scale so that monkey patched LoRA
527
+ # function of text encoder can correctly access it
528
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
529
+ self._lora_scale = lora_scale
530
+
531
+ if prompt is not None and isinstance(prompt, str):
532
+ batch_size = 1
533
+ elif prompt is not None and isinstance(prompt, list):
534
+ batch_size = len(prompt)
535
+ else:
536
+ batch_size = prompt_embeds.shape[0]
537
+
538
+ if prompt_embeds is None:
539
+ # textual inversion: procecss multi-vector tokens if necessary
540
+ if isinstance(self, TextualInversionLoaderMixin):
541
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
542
+
543
+ text_inputs = self.tokenizer(
544
+ prompt,
545
+ padding="max_length",
546
+ max_length=self.tokenizer.model_max_length,
547
+ truncation=True,
548
+ return_tensors="pt",
549
+ )
550
+ text_input_ids = text_inputs.input_ids
551
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
552
+
553
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
554
+ text_input_ids, untruncated_ids
555
+ ):
556
+ removed_text = self.tokenizer.batch_decode(
557
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
558
+ )
559
+ logger.warning(
560
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
561
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
562
+ )
563
+
564
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
565
+ attention_mask = text_inputs.attention_mask.to(device)
566
+ else:
567
+ attention_mask = None
568
+
569
+ prompt_embeds = self.text_encoder(
570
+ text_input_ids.to(device),
571
+ attention_mask=attention_mask,
572
+ )
573
+ prompt_embeds = prompt_embeds[0]
574
+
575
+ if self.text_encoder is not None:
576
+ prompt_embeds_dtype = self.text_encoder.dtype
577
+ elif self.unet is not None:
578
+ prompt_embeds_dtype = self.unet.dtype
579
+ else:
580
+ prompt_embeds_dtype = prompt_embeds.dtype
581
+
582
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
583
+
584
+ bs_embed, seq_len, _ = prompt_embeds.shape
585
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
586
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
587
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
588
+
589
+ # get unconditional embeddings for classifier free guidance
590
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
591
+ uncond_tokens: List[str]
592
+ if negative_prompt is None:
593
+ uncond_tokens = [""] * batch_size
594
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
595
+ raise TypeError(
596
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
597
+ f" {type(prompt)}."
598
+ )
599
+ elif isinstance(negative_prompt, str):
600
+ uncond_tokens = [negative_prompt]
601
+ elif batch_size != len(negative_prompt):
602
+ raise ValueError(
603
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
604
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
605
+ " the batch size of `prompt`."
606
+ )
607
+ else:
608
+ uncond_tokens = negative_prompt
609
+
610
+ # textual inversion: procecss multi-vector tokens if necessary
611
+ if isinstance(self, TextualInversionLoaderMixin):
612
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
613
+
614
+ max_length = prompt_embeds.shape[1]
615
+ uncond_input = self.tokenizer(
616
+ uncond_tokens,
617
+ padding="max_length",
618
+ max_length=max_length,
619
+ truncation=True,
620
+ return_tensors="pt",
621
+ )
622
+
623
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
624
+ attention_mask = uncond_input.attention_mask.to(device)
625
+ else:
626
+ attention_mask = None
627
+
628
+ negative_prompt_embeds = self.text_encoder(
629
+ uncond_input.input_ids.to(device),
630
+ attention_mask=attention_mask,
631
+ )
632
+ negative_prompt_embeds = negative_prompt_embeds[0]
633
+
634
+ if do_classifier_free_guidance:
635
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
636
+ seq_len = negative_prompt_embeds.shape[1]
637
+
638
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
639
+
640
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
641
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
642
+
643
+ # For classifier free guidance, we need to do two forward passes.
644
+ # Here we concatenate the unconditional and text embeddings into a single batch
645
+ # to avoid doing two forward passes
646
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
647
+
648
+ return prompt_embeds
649
+
650
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
651
+ def run_safety_checker(self, image, device, dtype):
652
+ if self.safety_checker is None:
653
+ has_nsfw_concept = None
654
+ else:
655
+ if torch.is_tensor(image):
656
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
657
+ else:
658
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
659
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
660
+ image, has_nsfw_concept = self.safety_checker(
661
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
662
+ )
663
+ return image, has_nsfw_concept
664
+
665
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
666
+ def prepare_extra_step_kwargs(self, generator, eta):
667
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
668
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
669
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
670
+ # and should be between [0, 1]
671
+
672
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
673
+ extra_step_kwargs = {}
674
+ if accepts_eta:
675
+ extra_step_kwargs["eta"] = eta
676
+
677
+ # check if the scheduler accepts generator
678
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
679
+ if accepts_generator:
680
+ extra_step_kwargs["generator"] = generator
681
+ return extra_step_kwargs
682
+
683
+ def check_inputs(
684
+ self,
685
+ prompt,
686
+ height,
687
+ width,
688
+ strength,
689
+ callback_steps,
690
+ negative_prompt=None,
691
+ prompt_embeds=None,
692
+ negative_prompt_embeds=None,
693
+ ):
694
+ if strength < 0 or strength > 1:
695
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
696
+
697
+ if height % 8 != 0 or width % 8 != 0:
698
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
699
+
700
+ if (callback_steps is None) or (
701
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
702
+ ):
703
+ raise ValueError(
704
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
705
+ f" {type(callback_steps)}."
706
+ )
707
+
708
+ if prompt is not None and prompt_embeds is not None:
709
+ raise ValueError(
710
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
711
+ " only forward one of the two."
712
+ )
713
+ elif prompt is None and prompt_embeds is None:
714
+ raise ValueError(
715
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
716
+ )
717
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
718
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
719
+
720
+ if negative_prompt is not None and negative_prompt_embeds is not None:
721
+ raise ValueError(
722
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
723
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
724
+ )
725
+
726
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
727
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
728
+ raise ValueError(
729
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
730
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
731
+ f" {negative_prompt_embeds.shape}."
732
+ )
733
+
734
+ def prepare_latents(
735
+ self,
736
+ batch_size,
737
+ num_channels_latents,
738
+ height,
739
+ width,
740
+ dtype,
741
+ device,
742
+ generator,
743
+ latents=None,
744
+ image=None,
745
+ timestep=None,
746
+ is_strength_max=True,
747
+ return_noise=False,
748
+ return_image_latents=False,
749
+ ):
750
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
751
+ if isinstance(generator, list) and len(generator) != batch_size:
752
+ raise ValueError(
753
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
754
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
755
+ )
756
+
757
+ if (image is None or timestep is None) and not is_strength_max:
758
+ raise ValueError(
759
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
760
+ "However, either the image or the noise timestep has not been provided."
761
+ )
762
+
763
+ if return_image_latents or (latents is None and not is_strength_max):
764
+ image = image.to(device=device, dtype=dtype)
765
+ image_latents = self._encode_vae_image(image=image, generator=generator)
766
+
767
+ if latents is None:
768
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
769
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
770
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
771
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
772
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
773
+ else:
774
+ noise = latents.to(device)
775
+ latents = noise * self.scheduler.init_noise_sigma
776
+
777
+ outputs = (latents,)
778
+
779
+ if return_noise:
780
+ outputs += (noise,)
781
+
782
+ if return_image_latents:
783
+ outputs += (image_latents,)
784
+
785
+ return outputs
786
+
787
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
788
+ if isinstance(generator, list):
789
+ image_latents = [
790
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator=generator[i])
791
+ for i in range(image.shape[0])
792
+ ]
793
+ image_latents = torch.cat(image_latents, dim=0)
794
+ else:
795
+ image_latents = self.vae.encode(image).latent_dist.sample(generator=generator)
796
+
797
+ image_latents = self.vae.config.scaling_factor * image_latents
798
+
799
+ return image_latents
800
+
801
+ def prepare_mask_latents(
802
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
803
+ ):
804
+ # resize the mask to latents shape as we concatenate the mask to the latents
805
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
806
+ # and half precision
807
+ mask = torch.nn.functional.interpolate(
808
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
809
+ )
810
+ mask = mask.to(device=device, dtype=dtype)
811
+
812
+ masked_image = masked_image.to(device=device, dtype=dtype)
813
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
814
+
815
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
816
+ if mask.shape[0] < batch_size:
817
+ if not batch_size % mask.shape[0] == 0:
818
+ raise ValueError(
819
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
820
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
821
+ " of masks that you pass is divisible by the total requested batch size."
822
+ )
823
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
824
+ if masked_image_latents.shape[0] < batch_size:
825
+ if not batch_size % masked_image_latents.shape[0] == 0:
826
+ raise ValueError(
827
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
828
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
829
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
830
+ )
831
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
832
+
833
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
834
+ masked_image_latents = (
835
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
836
+ )
837
+
838
+ # aligning device to prevent device errors when concating it with the latent model input
839
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
840
+ return mask, masked_image_latents
841
+
842
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
843
+ def get_timesteps(self, num_inference_steps, strength, device):
844
+ # get the original timestep using init_timestep
845
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
846
+
847
+ t_start = max(num_inference_steps - init_timestep, 0)
848
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
849
+
850
+ return timesteps, num_inference_steps - t_start
851
+
852
+ @torch.no_grad()
853
+ def __call__(
854
+ self,
855
+ prompt: Union[str, List[str]] = None,
856
+ image: Union[torch.FloatTensor, PIL.Image.Image] = None,
857
+ default_mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None,
858
+ height: Optional[int] = None,
859
+ width: Optional[int] = None,
860
+ strength: float = 1.0,
861
+ num_inference_steps: int = 50,
862
+ guidance_scale: float = 7.5,
863
+ negative_prompt: Optional[Union[str, List[str]]] = None,
864
+ num_images_per_prompt: Optional[int] = 1,
865
+ eta: float = 0.0,
866
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
867
+ latents: Optional[torch.FloatTensor] = None,
868
+ prompt_embeds: Optional[torch.FloatTensor] = None,
869
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
870
+ output_type: Optional[str] = "pil",
871
+ return_dict: bool = True,
872
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
873
+ callback_steps: int = 1,
874
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
875
+ use_adaptive_mask: bool = True,
876
+ enforce_full_mask_ratio: float = 0.5,
877
+ human_detection_thres: float = 0.008,
878
+ visualization_save_dir: str = None,
879
+ ):
880
+ r"""
881
+ The call function to the pipeline for generation.
882
+
883
+ Args:
884
+ prompt (`str` or `List[str]`, *optional*):
885
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
886
+ image (`PIL.Image.Image`):
887
+ `Image` or tensor representing an image batch to be inpainted (which parts of the image to be masked
888
+ out with `default_mask_image` and repainted according to `prompt`).
889
+ default_mask_image (`PIL.Image.Image`):
890
+ `Image` or tensor representing an image batch to mask `image`. White pixels in the mask are repainted
891
+ while black pixels are preserved. If `default_mask_image` is a PIL image, it is converted to a single channel
892
+ (luminance) before use. If it's a tensor, it should contain one color channel (L) instead of 3, so the
893
+ expected shape would be `(B, H, W, 1)`.
894
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
895
+ The height in pixels of the generated image.
896
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
897
+ The width in pixels of the generated image.
898
+ strength (`float`, *optional*, defaults to 1.0):
899
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
900
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
901
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
902
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
903
+ essentially ignores `image`.
904
+ num_inference_steps (`int`, *optional*, defaults to 50):
905
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
906
+ expense of slower inference. This parameter is modulated by `strength`.
907
+ guidance_scale (`float`, *optional*, defaults to 7.5):
908
+ A higher guidance scale value encourages the model to generate images closely linked to the text
909
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
910
+ negative_prompt (`str` or `List[str]`, *optional*):
911
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
912
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
913
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
914
+ The number of images to generate per prompt.
915
+ eta (`float`, *optional*, defaults to 0.0):
916
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
917
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
918
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
919
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
920
+ generation deterministic.
921
+ latents (`torch.FloatTensor`, *optional*):
922
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
923
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
924
+ tensor is generated by sampling using the supplied random `generator`.
925
+ prompt_embeds (`torch.FloatTensor`, *optional*):
926
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
927
+ provided, text embeddings are generated from the `prompt` input argument.
928
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
929
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
930
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
931
+ output_type (`str`, *optional*, defaults to `"pil"`):
932
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
933
+ return_dict (`bool`, *optional*, defaults to `True`):
934
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
935
+ plain tuple.
936
+ callback (`Callable`, *optional*):
937
+ A function that calls every `callback_steps` steps during inference. The function is called with the
938
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
939
+ callback_steps (`int`, *optional*, defaults to 1):
940
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
941
+ every step.
942
+ cross_attention_kwargs (`dict`, *optional*):
943
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
944
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
945
+
946
+ Examples:
947
+
948
+ ```py
949
+ >>> import PIL
950
+ >>> import requests
951
+ >>> import torch
952
+ >>> from io import BytesIO
953
+
954
+ >>> from diffusers import AdaptiveMaskInpaintPipeline
955
+
956
+
957
+ >>> def download_image(url):
958
+ ... response = requests.get(url)
959
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
960
+
961
+
962
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
963
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
964
+
965
+ >>> init_image = download_image(img_url).resize((512, 512))
966
+ >>> default_mask_image = download_image(mask_url).resize((512, 512))
967
+
968
+ >>> pipe = AdaptiveMaskInpaintPipeline.from_pretrained(
969
+ ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16
970
+ ... )
971
+ >>> pipe = pipe.to("cuda")
972
+
973
+ >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench"
974
+ >>> image = pipe(prompt=prompt, image=init_image, default_mask_image=default_mask_image).images[0]
975
+ ```
976
+
977
+ Returns:
978
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
979
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
980
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
981
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
982
+ "not-safe-for-work" (nsfw) content.
983
+ """
984
+ # 0. Default height and width to unet
985
+ width, height = image.size
986
+ # height = height or self.unet.config.sample_size * self.vae_scale_factor
987
+ # width = width or self.unet.config.sample_size * self.vae_scale_factor
988
+
989
+ # 1. Check inputs
990
+ self.check_inputs(
991
+ prompt,
992
+ height,
993
+ width,
994
+ strength,
995
+ callback_steps,
996
+ negative_prompt,
997
+ prompt_embeds,
998
+ negative_prompt_embeds,
999
+ )
1000
+
1001
+ # 2. Define call parameters
1002
+ if prompt is not None and isinstance(prompt, str):
1003
+ batch_size = 1
1004
+ elif prompt is not None and isinstance(prompt, list):
1005
+ batch_size = len(prompt)
1006
+ else:
1007
+ batch_size = prompt_embeds.shape[0]
1008
+
1009
+ device = self._execution_device
1010
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1011
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1012
+ # corresponds to doing no classifier free guidance.
1013
+ do_classifier_free_guidance = guidance_scale > 1.0
1014
+
1015
+ # 3. Encode input prompt
1016
+ text_encoder_lora_scale = (
1017
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1018
+ )
1019
+ prompt_embeds = self._encode_prompt(
1020
+ prompt,
1021
+ device,
1022
+ num_images_per_prompt,
1023
+ do_classifier_free_guidance,
1024
+ negative_prompt,
1025
+ prompt_embeds=prompt_embeds,
1026
+ negative_prompt_embeds=negative_prompt_embeds,
1027
+ lora_scale=text_encoder_lora_scale,
1028
+ )
1029
+
1030
+ # 4. set timesteps
1031
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1032
+ timesteps, num_inference_steps = self.get_timesteps(
1033
+ num_inference_steps=num_inference_steps, strength=strength, device=device
1034
+ )
1035
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1036
+ if num_inference_steps < 1:
1037
+ raise ValueError(
1038
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1039
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1040
+ )
1041
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1042
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1043
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1044
+ is_strength_max = strength == 1.0
1045
+
1046
+ # 5. Preprocess mask and image (will be used later, once again)
1047
+ mask, masked_image, init_image = prepare_mask_and_masked_image(
1048
+ image, default_mask_image, height, width, return_image=True
1049
+ )
1050
+ default_mask_image_np = np.array(default_mask_image).astype(np.uint8) / 255
1051
+ mask_condition = mask.clone()
1052
+
1053
+ # 6. Prepare latent variables
1054
+ num_channels_latents = self.vae.config.latent_channels
1055
+ num_channels_unet = self.unet.config.in_channels
1056
+ return_image_latents = num_channels_unet == 4
1057
+
1058
+ latents_outputs = self.prepare_latents(
1059
+ batch_size * num_images_per_prompt,
1060
+ num_channels_latents,
1061
+ height,
1062
+ width,
1063
+ prompt_embeds.dtype,
1064
+ device,
1065
+ generator,
1066
+ latents,
1067
+ image=init_image,
1068
+ timestep=latent_timestep,
1069
+ is_strength_max=is_strength_max,
1070
+ return_noise=True,
1071
+ return_image_latents=return_image_latents,
1072
+ )
1073
+
1074
+ if return_image_latents:
1075
+ latents, noise, image_latents = latents_outputs
1076
+ else:
1077
+ latents, noise = latents_outputs
1078
+
1079
+ # 7. Prepare mask latent variables
1080
+ mask, masked_image_latents = self.prepare_mask_latents(
1081
+ mask,
1082
+ masked_image,
1083
+ batch_size * num_images_per_prompt,
1084
+ height,
1085
+ width,
1086
+ prompt_embeds.dtype,
1087
+ device,
1088
+ generator,
1089
+ do_classifier_free_guidance,
1090
+ )
1091
+
1092
+ # 8. Check that sizes of mask, masked image and latents match
1093
+ if num_channels_unet == 9:
1094
+ # default case for runwayml/stable-diffusion-inpainting
1095
+ num_channels_mask = mask.shape[1]
1096
+ num_channels_masked_image = masked_image_latents.shape[1]
1097
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1098
+ raise ValueError(
1099
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1100
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1101
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1102
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1103
+ " `pipeline.unet` or your `default_mask_image` or `image` input."
1104
+ )
1105
+ elif num_channels_unet != 4:
1106
+ raise ValueError(
1107
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1108
+ )
1109
+
1110
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1111
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1112
+
1113
+ # 10. Denoising loop
1114
+ mask_image_np = default_mask_image_np
1115
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1116
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1117
+ for i, t in enumerate(timesteps):
1118
+ # expand the latents if we are doing classifier free guidance
1119
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1120
+
1121
+ # concat latents, mask, masked_image_latents in the channel dimension
1122
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1123
+
1124
+ if num_channels_unet == 9:
1125
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1126
+ else:
1127
+ raise NotImplementedError
1128
+
1129
+ # predict the noise residual
1130
+ noise_pred = self.unet(
1131
+ latent_model_input,
1132
+ t,
1133
+ encoder_hidden_states=prompt_embeds,
1134
+ cross_attention_kwargs=cross_attention_kwargs,
1135
+ return_dict=False,
1136
+ )[0]
1137
+
1138
+ # perform guidance
1139
+ if do_classifier_free_guidance:
1140
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1141
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1142
+
1143
+ # compute the previous noisy sample x_t -> x_t-1 & predicted original sample x_0
1144
+ outputs = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=True)
1145
+ latents = outputs["prev_sample"] # x_t-1
1146
+ pred_orig_latents = outputs["pred_original_sample"] # x_0
1147
+
1148
+ # run segmentation
1149
+ if use_adaptive_mask:
1150
+ if enforce_full_mask_ratio > 0.0:
1151
+ use_default_mask = t < self.scheduler.config.num_train_timesteps * enforce_full_mask_ratio
1152
+ elif enforce_full_mask_ratio == 0.0:
1153
+ use_default_mask = False
1154
+ else:
1155
+ raise NotImplementedError
1156
+
1157
+ pred_orig_image = self.decode_to_npuint8_image(pred_orig_latents)
1158
+ dilate_num = self.adaptive_mask_settings.dilate_scheduler(i)
1159
+ do_adapt_mask = self.adaptive_mask_settings.provoke_scheduler(i)
1160
+ if do_adapt_mask:
1161
+ mask, masked_image_latents, mask_image_np, vis_np = self.adapt_mask(
1162
+ init_image,
1163
+ pred_orig_image,
1164
+ default_mask_image_np,
1165
+ dilate_num=dilate_num,
1166
+ use_default_mask=use_default_mask,
1167
+ height=height,
1168
+ width=width,
1169
+ batch_size=batch_size,
1170
+ num_images_per_prompt=num_images_per_prompt,
1171
+ prompt_embeds=prompt_embeds,
1172
+ device=device,
1173
+ generator=generator,
1174
+ do_classifier_free_guidance=do_classifier_free_guidance,
1175
+ i=i,
1176
+ human_detection_thres=human_detection_thres,
1177
+ mask_image_np=mask_image_np,
1178
+ )
1179
+
1180
+ if self.adaptive_mask_model.use_visualizer:
1181
+ import matplotlib.pyplot as plt
1182
+
1183
+ # mask_image_new_colormap = np.clip(0.6 + (1.0 - mask_image_np), a_min=0.0, a_max=1.0) * 255
1184
+
1185
+ os.makedirs(visualization_save_dir, exist_ok=True)
1186
+
1187
+ # Image.fromarray(mask_image_new_colormap).convert("L").save(f"{visualization_save_dir}/masks/{i:05}.png")
1188
+ plt.axis("off")
1189
+ plt.subplot(1, 2, 1)
1190
+ plt.imshow(mask_image_np)
1191
+ plt.subplot(1, 2, 2)
1192
+ plt.imshow(pred_orig_image)
1193
+ plt.savefig(f"{visualization_save_dir}/{i:05}.png", bbox_inches="tight")
1194
+ plt.close("all")
1195
+
1196
+ if num_channels_unet == 4:
1197
+ init_latents_proper = image_latents[:1]
1198
+ init_mask = mask[:1]
1199
+
1200
+ if i < len(timesteps) - 1:
1201
+ noise_timestep = timesteps[i + 1]
1202
+ init_latents_proper = self.scheduler.add_noise(
1203
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1204
+ )
1205
+
1206
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1207
+
1208
+ # call the callback, if provided
1209
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1210
+ progress_bar.update()
1211
+ if callback is not None and i % callback_steps == 0:
1212
+ callback(i, t, latents)
1213
+
1214
+ if not output_type == "latent":
1215
+ condition_kwargs = {}
1216
+ if isinstance(self.vae, AsymmetricAutoencoderKL):
1217
+ init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)
1218
+ init_image_condition = init_image.clone()
1219
+ init_image = self._encode_vae_image(init_image, generator=generator)
1220
+ mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)
1221
+ condition_kwargs = {"image": init_image_condition, "mask": mask_condition}
1222
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, **condition_kwargs)[0]
1223
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1224
+ else:
1225
+ image = latents
1226
+ has_nsfw_concept = None
1227
+
1228
+ if has_nsfw_concept is None:
1229
+ do_denormalize = [True] * image.shape[0]
1230
+ else:
1231
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1232
+
1233
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1234
+
1235
+ # Offload last model to CPU
1236
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1237
+ self.final_offload_hook.offload()
1238
+
1239
+ if self.adaptive_mask_model.use_visualizer:
1240
+ generate_video_from_imgs(images_save_directory=visualization_save_dir, fps=10, delete_dir=True)
1241
+
1242
+ if not return_dict:
1243
+ return (image, has_nsfw_concept)
1244
+
1245
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1246
+
1247
+ def decode_to_npuint8_image(self, latents):
1248
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, **{})[
1249
+ 0
1250
+ ] # torch, float32, -1.~1.
1251
+ image = self.image_processor.postprocess(image, output_type="pt", do_denormalize=[True] * image.shape[0])
1252
+ image = (image.squeeze().permute(1, 2, 0).detach().cpu().numpy() * 255).astype(np.uint8) # np, uint8, 0~255
1253
+ return image
1254
+
1255
+ def register_adaptive_mask_settings(self):
1256
+ from easydict import EasyDict
1257
+
1258
+ num_steps = 50
1259
+
1260
+ step_num = int(num_steps * 0.1)
1261
+ final_step_num = num_steps - step_num * 7
1262
+ # adaptive mask settings
1263
+ self.adaptive_mask_settings = EasyDict(
1264
+ dilate_scheduler=MaskDilateScheduler(
1265
+ max_dilate_num=20,
1266
+ num_inference_steps=num_steps,
1267
+ schedule=[20] * step_num
1268
+ + [10] * step_num
1269
+ + [5] * step_num
1270
+ + [4] * step_num
1271
+ + [3] * step_num
1272
+ + [2] * step_num
1273
+ + [1] * step_num
1274
+ + [0] * final_step_num,
1275
+ ),
1276
+ dilate_kernel=np.ones((3, 3), dtype=np.uint8),
1277
+ provoke_scheduler=ProvokeScheduler(
1278
+ num_inference_steps=num_steps,
1279
+ schedule=list(range(2, 10 + 1, 2)) + list(range(12, 40 + 1, 2)) + [45],
1280
+ is_zero_indexing=False,
1281
+ ),
1282
+ )
1283
+
1284
+ def register_adaptive_mask_model(self):
1285
+ # declare segmentation model used for mask adaptation
1286
+ use_visualizer = True
1287
+ # assert not use_visualizer, \
1288
+ # """
1289
+ # If you plan to 'use_visualizer', USE WITH CAUTION.
1290
+ # It creates a directory of images and masks, which is used for merging into a video.
1291
+ # The procedure involves deleting the directory of images, which means that
1292
+ # if you set the directory wrong you can have other important files blown away.
1293
+ # """
1294
+
1295
+ self.adaptive_mask_model = PointRendPredictor(
1296
+ # pointrend_thres=0.2,
1297
+ pointrend_thres=0.9,
1298
+ device="cuda" if torch.cuda.is_available() else "cpu",
1299
+ use_visualizer=use_visualizer,
1300
+ config_pth="pointrend_rcnn_R_50_FPN_3x_coco.yaml",
1301
+ weights_pth="model_final_edd263.pkl",
1302
+ )
1303
+
1304
+ def adapt_mask(self, init_image, pred_orig_image, default_mask_image, dilate_num, use_default_mask, **kwargs):
1305
+ ## predict mask to use for adaptation
1306
+ adapt_output = self.adaptive_mask_model(pred_orig_image) # vis can be None if 'use_visualizer' is False
1307
+ mask = adapt_output["mask"]
1308
+ vis = adapt_output["vis"]
1309
+
1310
+ ## if mask is empty or too small, use default_mask_image. else, use dilate and intersect with default_mask_image
1311
+ if use_default_mask or mask.sum() < 512 * 512 * kwargs["human_detection_thres"]: # 0.005
1312
+ # set mask as default mask
1313
+ mask = default_mask_image # HxW
1314
+
1315
+ else:
1316
+ ## timestep-adaptive mask
1317
+ mask = cv2.dilate(
1318
+ mask, self.adaptive_mask_settings.dilate_kernel, iterations=dilate_num
1319
+ ) # dilate_kernel: np.ones((3,3), np.uint8)
1320
+ mask = np.logical_and(mask, default_mask_image) # HxW
1321
+
1322
+ ## prepare mask as pt tensor format
1323
+ mask = torch.tensor(mask, dtype=torch.float32).to(kwargs["device"])[None, None] # 1 x 1 x H x W
1324
+ mask, masked_image = prepare_mask_and_masked_image(
1325
+ init_image.to(kwargs["device"]), mask, kwargs["height"], kwargs["width"], return_image=False
1326
+ )
1327
+
1328
+ mask_image_np = mask.clone().squeeze().detach().cpu().numpy()
1329
+
1330
+ mask, masked_image_latents = self.prepare_mask_latents(
1331
+ mask,
1332
+ masked_image,
1333
+ kwargs["batch_size"] * kwargs["num_images_per_prompt"],
1334
+ kwargs["height"],
1335
+ kwargs["width"],
1336
+ kwargs["prompt_embeds"].dtype,
1337
+ kwargs["device"],
1338
+ kwargs["generator"],
1339
+ kwargs["do_classifier_free_guidance"],
1340
+ )
1341
+
1342
+ return mask, masked_image_latents, mask_image_np, vis
1343
+
1344
+
1345
+ def seg2bbox(seg_mask: np.ndarray):
1346
+ nonzero_i, nonzero_j = seg_mask.nonzero()
1347
+ min_i, max_i = nonzero_i.min(), nonzero_i.max()
1348
+ min_j, max_j = nonzero_j.min(), nonzero_j.max()
1349
+
1350
+ return np.array([min_j, min_i, max_j + 1, max_i + 1])
1351
+
1352
+
1353
+ def merge_bbox(bboxes: list):
1354
+ assert len(bboxes) > 0
1355
+
1356
+ all_bboxes = np.stack(bboxes, axis=0) # shape: N_bbox X 4
1357
+ merged_bbox = np.zeros_like(all_bboxes[0]) # shape: 4,
1358
+
1359
+ merged_bbox[0] = all_bboxes[:, 0].min()
1360
+ merged_bbox[1] = all_bboxes[:, 1].min()
1361
+ merged_bbox[2] = all_bboxes[:, 2].max()
1362
+ merged_bbox[3] = all_bboxes[:, 3].max()
1363
+
1364
+ return merged_bbox
1365
+
1366
+
1367
+ class PointRendPredictor:
1368
+ def __init__(
1369
+ self,
1370
+ cat_id_to_focus=0,
1371
+ pointrend_thres=0.9,
1372
+ device="cuda",
1373
+ use_visualizer=False,
1374
+ merge_mode="merge",
1375
+ config_pth=None,
1376
+ weights_pth=None,
1377
+ ):
1378
+ super().__init__()
1379
+
1380
+ # category id to focus (default: 0, which is human)
1381
+ self.cat_id_to_focus = cat_id_to_focus
1382
+
1383
+ # setup coco metadata
1384
+ self.coco_metadata = MetadataCatalog.get("coco_2017_val")
1385
+ self.cfg = get_cfg()
1386
+
1387
+ # get segmentation model config
1388
+ point_rend.add_pointrend_config(self.cfg) # --> Add PointRend-specific config
1389
+ self.cfg.merge_from_file(config_pth)
1390
+ self.cfg.MODEL.WEIGHTS = weights_pth
1391
+ self.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = pointrend_thres
1392
+ self.cfg.MODEL.DEVICE = device
1393
+
1394
+ # get segmentation model
1395
+ self.pointrend_seg_model = DefaultPredictor(self.cfg)
1396
+
1397
+ # settings for visualizer
1398
+ self.use_visualizer = use_visualizer
1399
+
1400
+ # mask-merge mode
1401
+ assert merge_mode in ["merge", "max-confidence"], f"'merge_mode': {merge_mode} not implemented."
1402
+ self.merge_mode = merge_mode
1403
+
1404
+ def merge_mask(self, masks, scores=None):
1405
+ if self.merge_mode == "merge":
1406
+ mask = np.any(masks, axis=0)
1407
+ elif self.merge_mode == "max-confidence":
1408
+ mask = masks[np.argmax(scores)]
1409
+ return mask
1410
+
1411
+ def vis_seg_on_img(self, image, mask):
1412
+ if type(mask) == np.ndarray:
1413
+ mask = torch.tensor(mask)
1414
+ v = Visualizer(image, self.coco_metadata, scale=0.5, instance_mode=ColorMode.IMAGE_BW)
1415
+ instances = Instances(image_size=image.shape[:2], pred_masks=mask if len(mask.shape) == 3 else mask[None])
1416
+ vis = v.draw_instance_predictions(instances.to("cpu")).get_image()
1417
+ return vis
1418
+
1419
+ def __call__(self, image):
1420
+ # run segmentation
1421
+ outputs = self.pointrend_seg_model(image)
1422
+ instances = outputs["instances"]
1423
+
1424
+ # merge instances for the category-id to focus
1425
+ is_class = instances.pred_classes == self.cat_id_to_focus
1426
+ masks = instances.pred_masks[is_class]
1427
+ masks = masks.detach().cpu().numpy() # [N, img_size, img_size]
1428
+ mask = self.merge_mask(masks, scores=instances.scores[is_class])
1429
+
1430
+ return {
1431
+ "asset_mask": None,
1432
+ "mask": mask.astype(np.uint8),
1433
+ "vis": self.vis_seg_on_img(image, mask) if self.use_visualizer else None,
1434
+ }
1435
+
1436
+
1437
+ class MaskDilateScheduler:
1438
+ def __init__(self, max_dilate_num=15, num_inference_steps=50, schedule=None):
1439
+ super().__init__()
1440
+ self.max_dilate_num = max_dilate_num
1441
+ self.schedule = [num_inference_steps - i for i in range(num_inference_steps)] if schedule is None else schedule
1442
+ assert len(self.schedule) == num_inference_steps
1443
+
1444
+ def __call__(self, i):
1445
+ return min(self.max_dilate_num, self.schedule[i])
1446
+
1447
+
1448
+ class ProvokeScheduler:
1449
+ def __init__(self, num_inference_steps=50, schedule=None, is_zero_indexing=False):
1450
+ super().__init__()
1451
+ if len(schedule) > 0:
1452
+ if is_zero_indexing:
1453
+ assert max(schedule) <= num_inference_steps - 1
1454
+ else:
1455
+ assert max(schedule) <= num_inference_steps
1456
+
1457
+ # register as self
1458
+ self.is_zero_indexing = is_zero_indexing
1459
+ self.schedule = schedule
1460
+
1461
+ def __call__(self, i):
1462
+ if self.is_zero_indexing:
1463
+ return i in self.schedule
1464
+ else:
1465
+ return i + 1 in self.schedule
v0.32.0/bit_diffusion.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Tuple, Union
2
+
3
+ import torch
4
+ from einops import rearrange, reduce
5
+
6
+ from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNet2DConditionModel
7
+ from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
8
+ from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
9
+
10
+
11
+ BITS = 8
12
+
13
+
14
+ # convert to bit representations and back taken from https://github.com/lucidrains/bit-diffusion/blob/main/bit_diffusion/bit_diffusion.py
15
+ def decimal_to_bits(x, bits=BITS):
16
+ """expects image tensor ranging from 0 to 1, outputs bit tensor ranging from -1 to 1"""
17
+ device = x.device
18
+
19
+ x = (x * 255).int().clamp(0, 255)
20
+
21
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device)
22
+ mask = rearrange(mask, "d -> d 1 1")
23
+ x = rearrange(x, "b c h w -> b c 1 h w")
24
+
25
+ bits = ((x & mask) != 0).float()
26
+ bits = rearrange(bits, "b c d h w -> b (c d) h w")
27
+ bits = bits * 2 - 1
28
+ return bits
29
+
30
+
31
+ def bits_to_decimal(x, bits=BITS):
32
+ """expects bits from -1 to 1, outputs image tensor from 0 to 1"""
33
+ device = x.device
34
+
35
+ x = (x > 0).int()
36
+ mask = 2 ** torch.arange(bits - 1, -1, -1, device=device, dtype=torch.int32)
37
+
38
+ mask = rearrange(mask, "d -> d 1 1")
39
+ x = rearrange(x, "b (c d) h w -> b c d h w", d=8)
40
+ dec = reduce(x * mask, "b c d h w -> b c h w", "sum")
41
+ return (dec / 255).clamp(0.0, 1.0)
42
+
43
+
44
+ # modified scheduler step functions for clamping the predicted x_0 between -bit_scale and +bit_scale
45
+ def ddim_bit_scheduler_step(
46
+ self,
47
+ model_output: torch.Tensor,
48
+ timestep: int,
49
+ sample: torch.Tensor,
50
+ eta: float = 0.0,
51
+ use_clipped_model_output: bool = True,
52
+ generator=None,
53
+ return_dict: bool = True,
54
+ ) -> Union[DDIMSchedulerOutput, Tuple]:
55
+ """
56
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
57
+ process from the learned model outputs (most often the predicted noise).
58
+ Args:
59
+ model_output (`torch.Tensor`): direct output from learned diffusion model.
60
+ timestep (`int`): current discrete timestep in the diffusion chain.
61
+ sample (`torch.Tensor`):
62
+ current instance of sample being created by diffusion process.
63
+ eta (`float`): weight of noise for added noise in diffusion step.
64
+ use_clipped_model_output (`bool`): TODO
65
+ generator: random number generator.
66
+ return_dict (`bool`): option for returning tuple rather than DDIMSchedulerOutput class
67
+ Returns:
68
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] or `tuple`:
69
+ [`~schedulers.scheduling_utils.DDIMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
70
+ returning a tuple, the first element is the sample tensor.
71
+ """
72
+ if self.num_inference_steps is None:
73
+ raise ValueError(
74
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
75
+ )
76
+
77
+ # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
78
+ # Ideally, read DDIM paper in-detail understanding
79
+
80
+ # Notation (<variable name> -> <name in paper>
81
+ # - pred_noise_t -> e_theta(x_t, t)
82
+ # - pred_original_sample -> f_theta(x_t, t) or x_0
83
+ # - std_dev_t -> sigma_t
84
+ # - eta -> η
85
+ # - pred_sample_direction -> "direction pointing to x_t"
86
+ # - pred_prev_sample -> "x_t-1"
87
+
88
+ # 1. get previous step value (=t-1)
89
+ prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps
90
+
91
+ # 2. compute alphas, betas
92
+ alpha_prod_t = self.alphas_cumprod[timestep]
93
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
94
+
95
+ beta_prod_t = 1 - alpha_prod_t
96
+
97
+ # 3. compute predicted original sample from predicted noise also called
98
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
99
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
100
+
101
+ # 4. Clip "predicted x_0"
102
+ scale = self.bit_scale
103
+ if self.config.clip_sample:
104
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
105
+
106
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
107
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
108
+ variance = self._get_variance(timestep, prev_timestep)
109
+ std_dev_t = eta * variance ** (0.5)
110
+
111
+ if use_clipped_model_output:
112
+ # the model_output is always re-derived from the clipped x_0 in Glide
113
+ model_output = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
114
+
115
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
116
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * model_output
117
+
118
+ # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
119
+ prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
120
+
121
+ if eta > 0:
122
+ # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
123
+ device = model_output.device if torch.is_tensor(model_output) else "cpu"
124
+ noise = torch.randn(model_output.shape, dtype=model_output.dtype, generator=generator).to(device)
125
+ variance = self._get_variance(timestep, prev_timestep) ** (0.5) * eta * noise
126
+
127
+ prev_sample = prev_sample + variance
128
+
129
+ if not return_dict:
130
+ return (prev_sample,)
131
+
132
+ return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
133
+
134
+
135
+ def ddpm_bit_scheduler_step(
136
+ self,
137
+ model_output: torch.Tensor,
138
+ timestep: int,
139
+ sample: torch.Tensor,
140
+ prediction_type="epsilon",
141
+ generator=None,
142
+ return_dict: bool = True,
143
+ ) -> Union[DDPMSchedulerOutput, Tuple]:
144
+ """
145
+ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
146
+ process from the learned model outputs (most often the predicted noise).
147
+ Args:
148
+ model_output (`torch.Tensor`): direct output from learned diffusion model.
149
+ timestep (`int`): current discrete timestep in the diffusion chain.
150
+ sample (`torch.Tensor`):
151
+ current instance of sample being created by diffusion process.
152
+ prediction_type (`str`, default `epsilon`):
153
+ indicates whether the model predicts the noise (epsilon), or the samples (`sample`).
154
+ generator: random number generator.
155
+ return_dict (`bool`): option for returning tuple rather than DDPMSchedulerOutput class
156
+ Returns:
157
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] or `tuple`:
158
+ [`~schedulers.scheduling_utils.DDPMSchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
159
+ returning a tuple, the first element is the sample tensor.
160
+ """
161
+ t = timestep
162
+
163
+ if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
164
+ model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1)
165
+ else:
166
+ predicted_variance = None
167
+
168
+ # 1. compute alphas, betas
169
+ alpha_prod_t = self.alphas_cumprod[t]
170
+ alpha_prod_t_prev = self.alphas_cumprod[t - 1] if t > 0 else self.one
171
+ beta_prod_t = 1 - alpha_prod_t
172
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
173
+
174
+ # 2. compute predicted original sample from predicted noise also called
175
+ # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
176
+ if prediction_type == "epsilon":
177
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
178
+ elif prediction_type == "sample":
179
+ pred_original_sample = model_output
180
+ else:
181
+ raise ValueError(f"Unsupported prediction_type {prediction_type}.")
182
+
183
+ # 3. Clip "predicted x_0"
184
+ scale = self.bit_scale
185
+ if self.config.clip_sample:
186
+ pred_original_sample = torch.clamp(pred_original_sample, -scale, scale)
187
+
188
+ # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
189
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
190
+ pred_original_sample_coeff = (alpha_prod_t_prev ** (0.5) * self.betas[t]) / beta_prod_t
191
+ current_sample_coeff = self.alphas[t] ** (0.5) * beta_prod_t_prev / beta_prod_t
192
+
193
+ # 5. Compute predicted previous sample µ_t
194
+ # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
195
+ pred_prev_sample = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
196
+
197
+ # 6. Add noise
198
+ variance = 0
199
+ if t > 0:
200
+ noise = torch.randn(
201
+ model_output.size(), dtype=model_output.dtype, layout=model_output.layout, generator=generator
202
+ ).to(model_output.device)
203
+ variance = (self._get_variance(t, predicted_variance=predicted_variance) ** 0.5) * noise
204
+
205
+ pred_prev_sample = pred_prev_sample + variance
206
+
207
+ if not return_dict:
208
+ return (pred_prev_sample,)
209
+
210
+ return DDPMSchedulerOutput(prev_sample=pred_prev_sample, pred_original_sample=pred_original_sample)
211
+
212
+
213
+ class BitDiffusion(DiffusionPipeline):
214
+ def __init__(
215
+ self,
216
+ unet: UNet2DConditionModel,
217
+ scheduler: Union[DDIMScheduler, DDPMScheduler],
218
+ bit_scale: Optional[float] = 1.0,
219
+ ):
220
+ super().__init__()
221
+ self.bit_scale = bit_scale
222
+ self.scheduler.step = (
223
+ ddim_bit_scheduler_step if isinstance(scheduler, DDIMScheduler) else ddpm_bit_scheduler_step
224
+ )
225
+
226
+ self.register_modules(unet=unet, scheduler=scheduler)
227
+
228
+ @torch.no_grad()
229
+ def __call__(
230
+ self,
231
+ height: Optional[int] = 256,
232
+ width: Optional[int] = 256,
233
+ num_inference_steps: Optional[int] = 50,
234
+ generator: Optional[torch.Generator] = None,
235
+ batch_size: Optional[int] = 1,
236
+ output_type: Optional[str] = "pil",
237
+ return_dict: bool = True,
238
+ **kwargs,
239
+ ) -> Union[Tuple, ImagePipelineOutput]:
240
+ latents = torch.randn(
241
+ (batch_size, self.unet.config.in_channels, height, width),
242
+ generator=generator,
243
+ )
244
+ latents = decimal_to_bits(latents) * self.bit_scale
245
+ latents = latents.to(self.device)
246
+
247
+ self.scheduler.set_timesteps(num_inference_steps)
248
+
249
+ for t in self.progress_bar(self.scheduler.timesteps):
250
+ # predict the noise residual
251
+ noise_pred = self.unet(latents, t).sample
252
+
253
+ # compute the previous noisy sample x_t -> x_t-1
254
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
255
+
256
+ image = bits_to_decimal(latents)
257
+
258
+ if output_type == "pil":
259
+ image = self.numpy_to_pil(image)
260
+
261
+ if not return_dict:
262
+ return (image,)
263
+
264
+ return ImagePipelineOutput(images=image)
v0.32.0/checkpoint_merger.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from typing import Dict, List, Union
4
+
5
+ import safetensors.torch
6
+ import torch
7
+ from huggingface_hub import snapshot_download
8
+ from huggingface_hub.utils import validate_hf_hub_args
9
+
10
+ from diffusers import DiffusionPipeline, __version__
11
+ from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
12
+ from diffusers.utils import CONFIG_NAME, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
13
+
14
+
15
+ class CheckpointMergerPipeline(DiffusionPipeline):
16
+ """
17
+ A class that supports merging diffusion models based on the discussion here:
18
+ https://github.com/huggingface/diffusers/issues/877
19
+
20
+ Example usage:-
21
+
22
+ pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", custom_pipeline="checkpoint_merger.py")
23
+
24
+ merged_pipe = pipe.merge(["CompVis/stable-diffusion-v1-4","prompthero/openjourney"], interp = 'inv_sigmoid', alpha = 0.8, force = True)
25
+
26
+ merged_pipe.to('cuda')
27
+
28
+ prompt = "An astronaut riding a unicycle on Mars"
29
+
30
+ results = merged_pipe(prompt)
31
+
32
+ ## For more details, see the docstring for the merge method.
33
+
34
+ """
35
+
36
+ def __init__(self):
37
+ self.register_to_config()
38
+ super().__init__()
39
+
40
+ def _compare_model_configs(self, dict0, dict1):
41
+ if dict0 == dict1:
42
+ return True
43
+ else:
44
+ config0, meta_keys0 = self._remove_meta_keys(dict0)
45
+ config1, meta_keys1 = self._remove_meta_keys(dict1)
46
+ if config0 == config1:
47
+ print(f"Warning !: Mismatch in keys {meta_keys0} and {meta_keys1}.")
48
+ return True
49
+ return False
50
+
51
+ def _remove_meta_keys(self, config_dict: Dict):
52
+ meta_keys = []
53
+ temp_dict = config_dict.copy()
54
+ for key in config_dict.keys():
55
+ if key.startswith("_"):
56
+ temp_dict.pop(key)
57
+ meta_keys.append(key)
58
+ return (temp_dict, meta_keys)
59
+
60
+ @torch.no_grad()
61
+ @validate_hf_hub_args
62
+ def merge(self, pretrained_model_name_or_path_list: List[Union[str, os.PathLike]], **kwargs):
63
+ """
64
+ Returns a new pipeline object of the class 'DiffusionPipeline' with the merged checkpoints(weights) of the models passed
65
+ in the argument 'pretrained_model_name_or_path_list' as a list.
66
+
67
+ Parameters:
68
+ -----------
69
+ pretrained_model_name_or_path_list : A list of valid pretrained model names in the HuggingFace hub or paths to locally stored models in the HuggingFace format.
70
+
71
+ **kwargs:
72
+ Supports all the default DiffusionPipeline.get_config_dict kwargs viz..
73
+
74
+ cache_dir, force_download, proxies, local_files_only, token, revision, torch_dtype, device_map.
75
+
76
+ alpha - The interpolation parameter. Ranges from 0 to 1. It affects the ratio in which the checkpoints are merged. A 0.8 alpha
77
+ would mean that the first model checkpoints would affect the final result far less than an alpha of 0.2
78
+
79
+ interp - The interpolation method to use for the merging. Supports "sigmoid", "inv_sigmoid", "add_diff" and None.
80
+ Passing None uses the default interpolation which is weighted sum interpolation. For merging three checkpoints, only "add_diff" is supported.
81
+
82
+ force - Whether to ignore mismatch in model_config.json for the current models. Defaults to False.
83
+
84
+ variant - which variant of a pretrained model to load, e.g. "fp16" (None)
85
+
86
+ """
87
+ # Default kwargs from DiffusionPipeline
88
+ cache_dir = kwargs.pop("cache_dir", None)
89
+ force_download = kwargs.pop("force_download", False)
90
+ proxies = kwargs.pop("proxies", None)
91
+ local_files_only = kwargs.pop("local_files_only", False)
92
+ token = kwargs.pop("token", None)
93
+ variant = kwargs.pop("variant", None)
94
+ revision = kwargs.pop("revision", None)
95
+ torch_dtype = kwargs.pop("torch_dtype", None)
96
+ device_map = kwargs.pop("device_map", None)
97
+
98
+ alpha = kwargs.pop("alpha", 0.5)
99
+ interp = kwargs.pop("interp", None)
100
+
101
+ print("Received list", pretrained_model_name_or_path_list)
102
+ print(f"Combining with alpha={alpha}, interpolation mode={interp}")
103
+
104
+ checkpoint_count = len(pretrained_model_name_or_path_list)
105
+ # Ignore result from model_index_json comparison of the two checkpoints
106
+ force = kwargs.pop("force", False)
107
+
108
+ # If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
109
+ if checkpoint_count > 3 or checkpoint_count < 2:
110
+ raise ValueError(
111
+ "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
112
+ " passed."
113
+ )
114
+
115
+ print("Received the right number of checkpoints")
116
+ # chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
117
+ # chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
118
+
119
+ # Validate that the checkpoints can be merged
120
+ # Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
121
+ config_dicts = []
122
+ for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
123
+ config_dict = DiffusionPipeline.load_config(
124
+ pretrained_model_name_or_path,
125
+ cache_dir=cache_dir,
126
+ force_download=force_download,
127
+ proxies=proxies,
128
+ local_files_only=local_files_only,
129
+ token=token,
130
+ revision=revision,
131
+ )
132
+ config_dicts.append(config_dict)
133
+
134
+ comparison_result = True
135
+ for idx in range(1, len(config_dicts)):
136
+ comparison_result &= self._compare_model_configs(config_dicts[idx - 1], config_dicts[idx])
137
+ if not force and comparison_result is False:
138
+ raise ValueError("Incompatible checkpoints. Please check model_index.json for the models.")
139
+ print("Compatible model_index.json files found")
140
+ # Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
141
+ cached_folders = []
142
+ for pretrained_model_name_or_path, config_dict in zip(pretrained_model_name_or_path_list, config_dicts):
143
+ folder_names = [k for k in config_dict.keys() if not k.startswith("_")]
144
+ allow_patterns = [os.path.join(k, "*") for k in folder_names]
145
+ allow_patterns += [
146
+ WEIGHTS_NAME,
147
+ SCHEDULER_CONFIG_NAME,
148
+ CONFIG_NAME,
149
+ ONNX_WEIGHTS_NAME,
150
+ DiffusionPipeline.config_name,
151
+ ]
152
+ requested_pipeline_class = config_dict.get("_class_name")
153
+ user_agent = {"diffusers": __version__, "pipeline_class": requested_pipeline_class}
154
+
155
+ cached_folder = (
156
+ pretrained_model_name_or_path
157
+ if os.path.isdir(pretrained_model_name_or_path)
158
+ else snapshot_download(
159
+ pretrained_model_name_or_path,
160
+ cache_dir=cache_dir,
161
+ proxies=proxies,
162
+ local_files_only=local_files_only,
163
+ token=token,
164
+ revision=revision,
165
+ allow_patterns=allow_patterns,
166
+ user_agent=user_agent,
167
+ )
168
+ )
169
+ print("Cached Folder", cached_folder)
170
+ cached_folders.append(cached_folder)
171
+
172
+ # Step 3:-
173
+ # Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
174
+ final_pipe = DiffusionPipeline.from_pretrained(
175
+ cached_folders[0],
176
+ torch_dtype=torch_dtype,
177
+ device_map=device_map,
178
+ variant=variant,
179
+ )
180
+ final_pipe.to(self.device)
181
+
182
+ checkpoint_path_2 = None
183
+ if len(cached_folders) > 2:
184
+ checkpoint_path_2 = os.path.join(cached_folders[2])
185
+
186
+ if interp == "sigmoid":
187
+ theta_func = CheckpointMergerPipeline.sigmoid
188
+ elif interp == "inv_sigmoid":
189
+ theta_func = CheckpointMergerPipeline.inv_sigmoid
190
+ elif interp == "add_diff":
191
+ theta_func = CheckpointMergerPipeline.add_difference
192
+ else:
193
+ theta_func = CheckpointMergerPipeline.weighted_sum
194
+
195
+ # Find each module's state dict.
196
+ for attr in final_pipe.config.keys():
197
+ if not attr.startswith("_"):
198
+ checkpoint_path_1 = os.path.join(cached_folders[1], attr)
199
+ if os.path.exists(checkpoint_path_1):
200
+ files = [
201
+ *glob.glob(os.path.join(checkpoint_path_1, "*.safetensors")),
202
+ *glob.glob(os.path.join(checkpoint_path_1, "*.bin")),
203
+ ]
204
+ checkpoint_path_1 = files[0] if len(files) > 0 else None
205
+ if len(cached_folders) < 3:
206
+ checkpoint_path_2 = None
207
+ else:
208
+ checkpoint_path_2 = os.path.join(cached_folders[2], attr)
209
+ if os.path.exists(checkpoint_path_2):
210
+ files = [
211
+ *glob.glob(os.path.join(checkpoint_path_2, "*.safetensors")),
212
+ *glob.glob(os.path.join(checkpoint_path_2, "*.bin")),
213
+ ]
214
+ checkpoint_path_2 = files[0] if len(files) > 0 else None
215
+ # For an attr if both checkpoint_path_1 and 2 are None, ignore.
216
+ # If at least one is present, deal with it according to interp method, of course only if the state_dict keys match.
217
+ if checkpoint_path_1 is None and checkpoint_path_2 is None:
218
+ print(f"Skipping {attr}: not present in 2nd or 3d model")
219
+ continue
220
+ try:
221
+ module = getattr(final_pipe, attr)
222
+ if isinstance(module, bool): # ignore requires_safety_checker boolean
223
+ continue
224
+ theta_0 = getattr(module, "state_dict")
225
+ theta_0 = theta_0()
226
+
227
+ update_theta_0 = getattr(module, "load_state_dict")
228
+ theta_1 = (
229
+ safetensors.torch.load_file(checkpoint_path_1)
230
+ if (checkpoint_path_1.endswith(".safetensors"))
231
+ else torch.load(checkpoint_path_1, map_location="cpu")
232
+ )
233
+ theta_2 = None
234
+ if checkpoint_path_2:
235
+ theta_2 = (
236
+ safetensors.torch.load_file(checkpoint_path_2)
237
+ if (checkpoint_path_2.endswith(".safetensors"))
238
+ else torch.load(checkpoint_path_2, map_location="cpu")
239
+ )
240
+
241
+ if not theta_0.keys() == theta_1.keys():
242
+ print(f"Skipping {attr}: key mismatch")
243
+ continue
244
+ if theta_2 and not theta_1.keys() == theta_2.keys():
245
+ print(f"Skipping {attr}:y mismatch")
246
+ except Exception as e:
247
+ print(f"Skipping {attr} do to an unexpected error: {str(e)}")
248
+ continue
249
+ print(f"MERGING {attr}")
250
+
251
+ for key in theta_0.keys():
252
+ if theta_2:
253
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], theta_2[key], alpha)
254
+ else:
255
+ theta_0[key] = theta_func(theta_0[key], theta_1[key], None, alpha)
256
+
257
+ del theta_1
258
+ del theta_2
259
+ update_theta_0(theta_0)
260
+
261
+ del theta_0
262
+ return final_pipe
263
+
264
+ @staticmethod
265
+ def weighted_sum(theta0, theta1, theta2, alpha):
266
+ return ((1 - alpha) * theta0) + (alpha * theta1)
267
+
268
+ # Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
269
+ @staticmethod
270
+ def sigmoid(theta0, theta1, theta2, alpha):
271
+ alpha = alpha * alpha * (3 - (2 * alpha))
272
+ return theta0 + ((theta1 - theta0) * alpha)
273
+
274
+ # Inverse Smoothstep (https://en.wikipedia.org/wiki/Smoothstep)
275
+ @staticmethod
276
+ def inv_sigmoid(theta0, theta1, theta2, alpha):
277
+ import math
278
+
279
+ alpha = 0.5 - math.sin(math.asin(1.0 - 2.0 * alpha) / 3.0)
280
+ return theta0 + ((theta1 - theta0) * alpha)
281
+
282
+ @staticmethod
283
+ def add_difference(theta0, theta1, theta2, alpha):
284
+ return theta0 + (theta1 - theta2) * (1.0 - alpha)
v0.32.0/clip_guided_images_mixing_stable_diffusion.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import inspect
3
+ from typing import Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from torch.nn import functional as F
9
+ from torchvision import transforms
10
+ from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import (
13
+ AutoencoderKL,
14
+ DDIMScheduler,
15
+ DPMSolverMultistepScheduler,
16
+ LMSDiscreteScheduler,
17
+ PNDMScheduler,
18
+ UNet2DConditionModel,
19
+ )
20
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.utils import PIL_INTERPOLATION
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ def preprocess(image, w, h):
27
+ if isinstance(image, torch.Tensor):
28
+ return image
29
+ elif isinstance(image, PIL.Image.Image):
30
+ image = [image]
31
+
32
+ if isinstance(image[0], PIL.Image.Image):
33
+ image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
34
+ image = np.concatenate(image, axis=0)
35
+ image = np.array(image).astype(np.float32) / 255.0
36
+ image = image.transpose(0, 3, 1, 2)
37
+ image = 2.0 * image - 1.0
38
+ image = torch.from_numpy(image)
39
+ elif isinstance(image[0], torch.Tensor):
40
+ image = torch.cat(image, dim=0)
41
+ return image
42
+
43
+
44
+ def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
45
+ if not isinstance(v0, np.ndarray):
46
+ inputs_are_torch = True
47
+ input_device = v0.device
48
+ v0 = v0.cpu().numpy()
49
+ v1 = v1.cpu().numpy()
50
+
51
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
52
+ if np.abs(dot) > DOT_THRESHOLD:
53
+ v2 = (1 - t) * v0 + t * v1
54
+ else:
55
+ theta_0 = np.arccos(dot)
56
+ sin_theta_0 = np.sin(theta_0)
57
+ theta_t = theta_0 * t
58
+ sin_theta_t = np.sin(theta_t)
59
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
60
+ s1 = sin_theta_t / sin_theta_0
61
+ v2 = s0 * v0 + s1 * v1
62
+
63
+ if inputs_are_torch:
64
+ v2 = torch.from_numpy(v2).to(input_device)
65
+
66
+ return v2
67
+
68
+
69
+ def spherical_dist_loss(x, y):
70
+ x = F.normalize(x, dim=-1)
71
+ y = F.normalize(y, dim=-1)
72
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
73
+
74
+
75
+ def set_requires_grad(model, value):
76
+ for param in model.parameters():
77
+ param.requires_grad = value
78
+
79
+
80
+ class CLIPGuidedImagesMixingStableDiffusion(DiffusionPipeline, StableDiffusionMixin):
81
+ def __init__(
82
+ self,
83
+ vae: AutoencoderKL,
84
+ text_encoder: CLIPTextModel,
85
+ clip_model: CLIPModel,
86
+ tokenizer: CLIPTokenizer,
87
+ unet: UNet2DConditionModel,
88
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
89
+ feature_extractor: CLIPImageProcessor,
90
+ coca_model=None,
91
+ coca_tokenizer=None,
92
+ coca_transform=None,
93
+ ):
94
+ super().__init__()
95
+ self.register_modules(
96
+ vae=vae,
97
+ text_encoder=text_encoder,
98
+ clip_model=clip_model,
99
+ tokenizer=tokenizer,
100
+ unet=unet,
101
+ scheduler=scheduler,
102
+ feature_extractor=feature_extractor,
103
+ coca_model=coca_model,
104
+ coca_tokenizer=coca_tokenizer,
105
+ coca_transform=coca_transform,
106
+ )
107
+ self.feature_extractor_size = (
108
+ feature_extractor.size
109
+ if isinstance(feature_extractor.size, int)
110
+ else feature_extractor.size["shortest_edge"]
111
+ )
112
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
113
+ set_requires_grad(self.text_encoder, False)
114
+ set_requires_grad(self.clip_model, False)
115
+
116
+ def freeze_vae(self):
117
+ set_requires_grad(self.vae, False)
118
+
119
+ def unfreeze_vae(self):
120
+ set_requires_grad(self.vae, True)
121
+
122
+ def freeze_unet(self):
123
+ set_requires_grad(self.unet, False)
124
+
125
+ def unfreeze_unet(self):
126
+ set_requires_grad(self.unet, True)
127
+
128
+ def get_timesteps(self, num_inference_steps, strength, device):
129
+ # get the original timestep using init_timestep
130
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
131
+
132
+ t_start = max(num_inference_steps - init_timestep, 0)
133
+ timesteps = self.scheduler.timesteps[t_start:]
134
+
135
+ return timesteps, num_inference_steps - t_start
136
+
137
+ def prepare_latents(self, image, timestep, batch_size, dtype, device, generator=None):
138
+ if not isinstance(image, torch.Tensor):
139
+ raise ValueError(f"`image` has to be of type `torch.Tensor` but is {type(image)}")
140
+
141
+ image = image.to(device=device, dtype=dtype)
142
+
143
+ if isinstance(generator, list):
144
+ init_latents = [
145
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
146
+ ]
147
+ init_latents = torch.cat(init_latents, dim=0)
148
+ else:
149
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
150
+
151
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
152
+ init_latents = 0.18215 * init_latents
153
+ init_latents = init_latents.repeat_interleave(batch_size, dim=0)
154
+
155
+ noise = randn_tensor(init_latents.shape, generator=generator, device=device, dtype=dtype)
156
+
157
+ # get latents
158
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
159
+ latents = init_latents
160
+
161
+ return latents
162
+
163
+ def get_image_description(self, image):
164
+ transformed_image = self.coca_transform(image).unsqueeze(0)
165
+ with torch.no_grad(), torch.cuda.amp.autocast():
166
+ generated = self.coca_model.generate(transformed_image.to(device=self.device, dtype=self.coca_model.dtype))
167
+ generated = self.coca_tokenizer.decode(generated[0].cpu().numpy())
168
+ return generated.split("<end_of_text>")[0].replace("<start_of_text>", "").rstrip(" .,")
169
+
170
+ def get_clip_image_embeddings(self, image, batch_size):
171
+ clip_image_input = self.feature_extractor.preprocess(image)
172
+ clip_image_features = torch.from_numpy(clip_image_input["pixel_values"][0]).unsqueeze(0).to(self.device).half()
173
+ image_embeddings_clip = self.clip_model.get_image_features(clip_image_features)
174
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
175
+ image_embeddings_clip = image_embeddings_clip.repeat_interleave(batch_size, dim=0)
176
+ return image_embeddings_clip
177
+
178
+ @torch.enable_grad()
179
+ def cond_fn(
180
+ self,
181
+ latents,
182
+ timestep,
183
+ index,
184
+ text_embeddings,
185
+ noise_pred_original,
186
+ original_image_embeddings_clip,
187
+ clip_guidance_scale,
188
+ ):
189
+ latents = latents.detach().requires_grad_()
190
+
191
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
192
+
193
+ # predict the noise residual
194
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
195
+
196
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
197
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
198
+ beta_prod_t = 1 - alpha_prod_t
199
+ # compute predicted original sample from predicted noise also called
200
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
201
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
202
+
203
+ fac = torch.sqrt(beta_prod_t)
204
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
205
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
206
+ sigma = self.scheduler.sigmas[index]
207
+ sample = latents - sigma * noise_pred
208
+ else:
209
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
210
+
211
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
212
+ sample = 1 / 0.18215 * sample
213
+ image = self.vae.decode(sample).sample
214
+ image = (image / 2 + 0.5).clamp(0, 1)
215
+
216
+ image = transforms.Resize(self.feature_extractor_size)(image)
217
+ image = self.normalize(image).to(latents.dtype)
218
+
219
+ image_embeddings_clip = self.clip_model.get_image_features(image)
220
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
221
+
222
+ loss = spherical_dist_loss(image_embeddings_clip, original_image_embeddings_clip).mean() * clip_guidance_scale
223
+
224
+ grads = -torch.autograd.grad(loss, latents)[0]
225
+
226
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
227
+ latents = latents.detach() + grads * (sigma**2)
228
+ noise_pred = noise_pred_original
229
+ else:
230
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
231
+ return noise_pred, latents
232
+
233
+ @torch.no_grad()
234
+ def __call__(
235
+ self,
236
+ style_image: Union[torch.Tensor, PIL.Image.Image],
237
+ content_image: Union[torch.Tensor, PIL.Image.Image],
238
+ style_prompt: Optional[str] = None,
239
+ content_prompt: Optional[str] = None,
240
+ height: Optional[int] = 512,
241
+ width: Optional[int] = 512,
242
+ noise_strength: float = 0.6,
243
+ num_inference_steps: Optional[int] = 50,
244
+ guidance_scale: Optional[float] = 7.5,
245
+ batch_size: Optional[int] = 1,
246
+ eta: float = 0.0,
247
+ clip_guidance_scale: Optional[float] = 100,
248
+ generator: Optional[torch.Generator] = None,
249
+ output_type: Optional[str] = "pil",
250
+ return_dict: bool = True,
251
+ slerp_latent_style_strength: float = 0.8,
252
+ slerp_prompt_style_strength: float = 0.1,
253
+ slerp_clip_image_style_strength: float = 0.1,
254
+ ):
255
+ if isinstance(generator, list) and len(generator) != batch_size:
256
+ raise ValueError(f"You have passed {batch_size} batch_size, but only {len(generator)} generators.")
257
+
258
+ if height % 8 != 0 or width % 8 != 0:
259
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
260
+
261
+ if isinstance(generator, torch.Generator) and batch_size > 1:
262
+ generator = [generator] + [None] * (batch_size - 1)
263
+
264
+ coca_is_none = [
265
+ ("model", self.coca_model is None),
266
+ ("tokenizer", self.coca_tokenizer is None),
267
+ ("transform", self.coca_transform is None),
268
+ ]
269
+ coca_is_none = [x[0] for x in coca_is_none if x[1]]
270
+ coca_is_none_str = ", ".join(coca_is_none)
271
+ # generate prompts with coca model if prompt is None
272
+ if content_prompt is None:
273
+ if len(coca_is_none):
274
+ raise ValueError(
275
+ f"Content prompt is None and CoCa [{coca_is_none_str}] is None."
276
+ f"Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."
277
+ )
278
+ content_prompt = self.get_image_description(content_image)
279
+ if style_prompt is None:
280
+ if len(coca_is_none):
281
+ raise ValueError(
282
+ f"Style prompt is None and CoCa [{coca_is_none_str}] is None."
283
+ f" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline."
284
+ )
285
+ style_prompt = self.get_image_description(style_image)
286
+
287
+ # get prompt text embeddings for content and style
288
+ content_text_input = self.tokenizer(
289
+ content_prompt,
290
+ padding="max_length",
291
+ max_length=self.tokenizer.model_max_length,
292
+ truncation=True,
293
+ return_tensors="pt",
294
+ )
295
+ content_text_embeddings = self.text_encoder(content_text_input.input_ids.to(self.device))[0]
296
+
297
+ style_text_input = self.tokenizer(
298
+ style_prompt,
299
+ padding="max_length",
300
+ max_length=self.tokenizer.model_max_length,
301
+ truncation=True,
302
+ return_tensors="pt",
303
+ )
304
+ style_text_embeddings = self.text_encoder(style_text_input.input_ids.to(self.device))[0]
305
+
306
+ text_embeddings = slerp(slerp_prompt_style_strength, content_text_embeddings, style_text_embeddings)
307
+
308
+ # duplicate text embeddings for each generation per prompt
309
+ text_embeddings = text_embeddings.repeat_interleave(batch_size, dim=0)
310
+
311
+ # set timesteps
312
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
313
+ extra_set_kwargs = {}
314
+ if accepts_offset:
315
+ extra_set_kwargs["offset"] = 1
316
+
317
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
318
+ # Some schedulers like PNDM have timesteps as arrays
319
+ # It's more optimized to move all timesteps to correct device beforehand
320
+ self.scheduler.timesteps.to(self.device)
321
+
322
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, noise_strength, self.device)
323
+ latent_timestep = timesteps[:1].repeat(batch_size)
324
+
325
+ # Preprocess image
326
+ preprocessed_content_image = preprocess(content_image, width, height)
327
+ content_latents = self.prepare_latents(
328
+ preprocessed_content_image, latent_timestep, batch_size, text_embeddings.dtype, self.device, generator
329
+ )
330
+
331
+ preprocessed_style_image = preprocess(style_image, width, height)
332
+ style_latents = self.prepare_latents(
333
+ preprocessed_style_image, latent_timestep, batch_size, text_embeddings.dtype, self.device, generator
334
+ )
335
+
336
+ latents = slerp(slerp_latent_style_strength, content_latents, style_latents)
337
+
338
+ if clip_guidance_scale > 0:
339
+ content_clip_image_embedding = self.get_clip_image_embeddings(content_image, batch_size)
340
+ style_clip_image_embedding = self.get_clip_image_embeddings(style_image, batch_size)
341
+ clip_image_embeddings = slerp(
342
+ slerp_clip_image_style_strength, content_clip_image_embedding, style_clip_image_embedding
343
+ )
344
+
345
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
346
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
347
+ # corresponds to doing no classifier free guidance.
348
+ do_classifier_free_guidance = guidance_scale > 1.0
349
+ # get unconditional embeddings for classifier free guidance
350
+ if do_classifier_free_guidance:
351
+ max_length = content_text_input.input_ids.shape[-1]
352
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
353
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
354
+ # duplicate unconditional embeddings for each generation per prompt
355
+ uncond_embeddings = uncond_embeddings.repeat_interleave(batch_size, dim=0)
356
+
357
+ # For classifier free guidance, we need to do two forward passes.
358
+ # Here we concatenate the unconditional and text embeddings into a single batch
359
+ # to avoid doing two forward passes
360
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
361
+
362
+ # get the initial random noise unless the user supplied it
363
+
364
+ # Unlike in other pipelines, latents need to be generated in the target device
365
+ # for 1-to-1 results reproducibility with the CompVis implementation.
366
+ # However this currently doesn't work in `mps`.
367
+ latents_shape = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
368
+ latents_dtype = text_embeddings.dtype
369
+ if latents is None:
370
+ if self.device.type == "mps":
371
+ # randn does not work reproducibly on mps
372
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
373
+ self.device
374
+ )
375
+ else:
376
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
377
+ else:
378
+ if latents.shape != latents_shape:
379
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
380
+ latents = latents.to(self.device)
381
+
382
+ # scale the initial noise by the standard deviation required by the scheduler
383
+ latents = latents * self.scheduler.init_noise_sigma
384
+
385
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
386
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
387
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
388
+ # and should be between [0, 1]
389
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
390
+ extra_step_kwargs = {}
391
+ if accepts_eta:
392
+ extra_step_kwargs["eta"] = eta
393
+
394
+ # check if the scheduler accepts generator
395
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
396
+ if accepts_generator:
397
+ extra_step_kwargs["generator"] = generator
398
+
399
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
400
+ for i, t in enumerate(timesteps):
401
+ # expand the latents if we are doing classifier free guidance
402
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
403
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
404
+
405
+ # predict the noise residual
406
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
407
+
408
+ # perform classifier free guidance
409
+ if do_classifier_free_guidance:
410
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
411
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
412
+
413
+ # perform clip guidance
414
+ if clip_guidance_scale > 0:
415
+ text_embeddings_for_guidance = (
416
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
417
+ )
418
+ noise_pred, latents = self.cond_fn(
419
+ latents,
420
+ t,
421
+ i,
422
+ text_embeddings_for_guidance,
423
+ noise_pred,
424
+ clip_image_embeddings,
425
+ clip_guidance_scale,
426
+ )
427
+
428
+ # compute the previous noisy sample x_t -> x_t-1
429
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
430
+
431
+ progress_bar.update()
432
+ # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor
433
+ latents = 1 / 0.18215 * latents
434
+ image = self.vae.decode(latents).sample
435
+
436
+ image = (image / 2 + 0.5).clamp(0, 1)
437
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
438
+
439
+ if output_type == "pil":
440
+ image = self.numpy_to_pil(image)
441
+
442
+ if not return_dict:
443
+ return (image, None)
444
+
445
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.32.0/clip_guided_stable_diffusion.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+ from torch.nn import functional as F
7
+ from torchvision import transforms
8
+ from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers import (
11
+ AutoencoderKL,
12
+ DDIMScheduler,
13
+ DPMSolverMultistepScheduler,
14
+ LMSDiscreteScheduler,
15
+ PNDMScheduler,
16
+ UNet2DConditionModel,
17
+ )
18
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
19
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
20
+
21
+
22
+ class MakeCutouts(nn.Module):
23
+ def __init__(self, cut_size, cut_power=1.0):
24
+ super().__init__()
25
+
26
+ self.cut_size = cut_size
27
+ self.cut_power = cut_power
28
+
29
+ def forward(self, pixel_values, num_cutouts):
30
+ sideY, sideX = pixel_values.shape[2:4]
31
+ max_size = min(sideX, sideY)
32
+ min_size = min(sideX, sideY, self.cut_size)
33
+ cutouts = []
34
+ for _ in range(num_cutouts):
35
+ size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
36
+ offsetx = torch.randint(0, sideX - size + 1, ())
37
+ offsety = torch.randint(0, sideY - size + 1, ())
38
+ cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
39
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
40
+ return torch.cat(cutouts)
41
+
42
+
43
+ def spherical_dist_loss(x, y):
44
+ x = F.normalize(x, dim=-1)
45
+ y = F.normalize(y, dim=-1)
46
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
47
+
48
+
49
+ def set_requires_grad(model, value):
50
+ for param in model.parameters():
51
+ param.requires_grad = value
52
+
53
+
54
+ class CLIPGuidedStableDiffusion(DiffusionPipeline, StableDiffusionMixin):
55
+ """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000
56
+ - https://github.com/Jack000/glid-3-xl
57
+ - https://github.dev/crowsonkb/k-diffusion
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ vae: AutoencoderKL,
63
+ text_encoder: CLIPTextModel,
64
+ clip_model: CLIPModel,
65
+ tokenizer: CLIPTokenizer,
66
+ unet: UNet2DConditionModel,
67
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
68
+ feature_extractor: CLIPImageProcessor,
69
+ ):
70
+ super().__init__()
71
+ self.register_modules(
72
+ vae=vae,
73
+ text_encoder=text_encoder,
74
+ clip_model=clip_model,
75
+ tokenizer=tokenizer,
76
+ unet=unet,
77
+ scheduler=scheduler,
78
+ feature_extractor=feature_extractor,
79
+ )
80
+
81
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
82
+ self.cut_out_size = (
83
+ feature_extractor.size
84
+ if isinstance(feature_extractor.size, int)
85
+ else feature_extractor.size["shortest_edge"]
86
+ )
87
+ self.make_cutouts = MakeCutouts(self.cut_out_size)
88
+
89
+ set_requires_grad(self.text_encoder, False)
90
+ set_requires_grad(self.clip_model, False)
91
+
92
+ def freeze_vae(self):
93
+ set_requires_grad(self.vae, False)
94
+
95
+ def unfreeze_vae(self):
96
+ set_requires_grad(self.vae, True)
97
+
98
+ def freeze_unet(self):
99
+ set_requires_grad(self.unet, False)
100
+
101
+ def unfreeze_unet(self):
102
+ set_requires_grad(self.unet, True)
103
+
104
+ @torch.enable_grad()
105
+ def cond_fn(
106
+ self,
107
+ latents,
108
+ timestep,
109
+ index,
110
+ text_embeddings,
111
+ noise_pred_original,
112
+ text_embeddings_clip,
113
+ clip_guidance_scale,
114
+ num_cutouts,
115
+ use_cutouts=True,
116
+ ):
117
+ latents = latents.detach().requires_grad_()
118
+
119
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
120
+
121
+ # predict the noise residual
122
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
123
+
124
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
125
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
126
+ beta_prod_t = 1 - alpha_prod_t
127
+ # compute predicted original sample from predicted noise also called
128
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
129
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
130
+
131
+ fac = torch.sqrt(beta_prod_t)
132
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
133
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
134
+ sigma = self.scheduler.sigmas[index]
135
+ sample = latents - sigma * noise_pred
136
+ else:
137
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
138
+
139
+ sample = 1 / self.vae.config.scaling_factor * sample
140
+ image = self.vae.decode(sample).sample
141
+ image = (image / 2 + 0.5).clamp(0, 1)
142
+
143
+ if use_cutouts:
144
+ image = self.make_cutouts(image, num_cutouts)
145
+ else:
146
+ image = transforms.Resize(self.cut_out_size)(image)
147
+ image = self.normalize(image).to(latents.dtype)
148
+
149
+ image_embeddings_clip = self.clip_model.get_image_features(image)
150
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
151
+
152
+ if use_cutouts:
153
+ dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip)
154
+ dists = dists.view([num_cutouts, sample.shape[0], -1])
155
+ loss = dists.sum(2).mean(0).sum() * clip_guidance_scale
156
+ else:
157
+ loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale
158
+
159
+ grads = -torch.autograd.grad(loss, latents)[0]
160
+
161
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
162
+ latents = latents.detach() + grads * (sigma**2)
163
+ noise_pred = noise_pred_original
164
+ else:
165
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
166
+ return noise_pred, latents
167
+
168
+ @torch.no_grad()
169
+ def __call__(
170
+ self,
171
+ prompt: Union[str, List[str]],
172
+ height: Optional[int] = 512,
173
+ width: Optional[int] = 512,
174
+ num_inference_steps: Optional[int] = 50,
175
+ guidance_scale: Optional[float] = 7.5,
176
+ num_images_per_prompt: Optional[int] = 1,
177
+ eta: float = 0.0,
178
+ clip_guidance_scale: Optional[float] = 100,
179
+ clip_prompt: Optional[Union[str, List[str]]] = None,
180
+ num_cutouts: Optional[int] = 4,
181
+ use_cutouts: Optional[bool] = True,
182
+ generator: Optional[torch.Generator] = None,
183
+ latents: Optional[torch.Tensor] = None,
184
+ output_type: Optional[str] = "pil",
185
+ return_dict: bool = True,
186
+ ):
187
+ if isinstance(prompt, str):
188
+ batch_size = 1
189
+ elif isinstance(prompt, list):
190
+ batch_size = len(prompt)
191
+ else:
192
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
193
+
194
+ if height % 8 != 0 or width % 8 != 0:
195
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
196
+
197
+ # get prompt text embeddings
198
+ text_input = self.tokenizer(
199
+ prompt,
200
+ padding="max_length",
201
+ max_length=self.tokenizer.model_max_length,
202
+ truncation=True,
203
+ return_tensors="pt",
204
+ )
205
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
206
+ # duplicate text embeddings for each generation per prompt
207
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
208
+
209
+ if clip_guidance_scale > 0:
210
+ if clip_prompt is not None:
211
+ clip_text_input = self.tokenizer(
212
+ clip_prompt,
213
+ padding="max_length",
214
+ max_length=self.tokenizer.model_max_length,
215
+ truncation=True,
216
+ return_tensors="pt",
217
+ ).input_ids.to(self.device)
218
+ else:
219
+ clip_text_input = text_input.input_ids.to(self.device)
220
+ text_embeddings_clip = self.clip_model.get_text_features(clip_text_input)
221
+ text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
222
+ # duplicate text embeddings clip for each generation per prompt
223
+ text_embeddings_clip = text_embeddings_clip.repeat_interleave(num_images_per_prompt, dim=0)
224
+
225
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
226
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
227
+ # corresponds to doing no classifier free guidance.
228
+ do_classifier_free_guidance = guidance_scale > 1.0
229
+ # get unconditional embeddings for classifier free guidance
230
+ if do_classifier_free_guidance:
231
+ max_length = text_input.input_ids.shape[-1]
232
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
233
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
234
+ # duplicate unconditional embeddings for each generation per prompt
235
+ uncond_embeddings = uncond_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
236
+
237
+ # For classifier free guidance, we need to do two forward passes.
238
+ # Here we concatenate the unconditional and text embeddings into a single batch
239
+ # to avoid doing two forward passes
240
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
241
+
242
+ # get the initial random noise unless the user supplied it
243
+
244
+ # Unlike in other pipelines, latents need to be generated in the target device
245
+ # for 1-to-1 results reproducibility with the CompVis implementation.
246
+ # However this currently doesn't work in `mps`.
247
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
248
+ latents_dtype = text_embeddings.dtype
249
+ if latents is None:
250
+ if self.device.type == "mps":
251
+ # randn does not work reproducibly on mps
252
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
253
+ self.device
254
+ )
255
+ else:
256
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
257
+ else:
258
+ if latents.shape != latents_shape:
259
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
260
+ latents = latents.to(self.device)
261
+
262
+ # set timesteps
263
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
264
+ extra_set_kwargs = {}
265
+ if accepts_offset:
266
+ extra_set_kwargs["offset"] = 1
267
+
268
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
269
+
270
+ # Some schedulers like PNDM have timesteps as arrays
271
+ # It's more optimized to move all timesteps to correct device beforehand
272
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
273
+
274
+ # scale the initial noise by the standard deviation required by the scheduler
275
+ latents = latents * self.scheduler.init_noise_sigma
276
+
277
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
278
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
279
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
280
+ # and should be between [0, 1]
281
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
282
+ extra_step_kwargs = {}
283
+ if accepts_eta:
284
+ extra_step_kwargs["eta"] = eta
285
+
286
+ # check if the scheduler accepts generator
287
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
288
+ if accepts_generator:
289
+ extra_step_kwargs["generator"] = generator
290
+
291
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
292
+ # expand the latents if we are doing classifier free guidance
293
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
294
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
295
+
296
+ # predict the noise residual
297
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
298
+
299
+ # perform classifier free guidance
300
+ if do_classifier_free_guidance:
301
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
302
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
303
+
304
+ # perform clip guidance
305
+ if clip_guidance_scale > 0:
306
+ text_embeddings_for_guidance = (
307
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
308
+ )
309
+ noise_pred, latents = self.cond_fn(
310
+ latents,
311
+ t,
312
+ i,
313
+ text_embeddings_for_guidance,
314
+ noise_pred,
315
+ text_embeddings_clip,
316
+ clip_guidance_scale,
317
+ num_cutouts,
318
+ use_cutouts,
319
+ )
320
+
321
+ # compute the previous noisy sample x_t -> x_t-1
322
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
323
+
324
+ # scale and decode the image latents with vae
325
+ latents = 1 / self.vae.config.scaling_factor * latents
326
+ image = self.vae.decode(latents).sample
327
+
328
+ image = (image / 2 + 0.5).clamp(0, 1)
329
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
330
+
331
+ if output_type == "pil":
332
+ image = self.numpy_to_pil(image)
333
+
334
+ if not return_dict:
335
+ return (image, None)
336
+
337
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.32.0/clip_guided_stable_diffusion_img2img.py ADDED
@@ -0,0 +1,490 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import List, Optional, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+ from torch import nn
8
+ from torch.nn import functional as F
9
+ from torchvision import transforms
10
+ from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer
11
+
12
+ from diffusers import (
13
+ AutoencoderKL,
14
+ DDIMScheduler,
15
+ DPMSolverMultistepScheduler,
16
+ LMSDiscreteScheduler,
17
+ PNDMScheduler,
18
+ UNet2DConditionModel,
19
+ )
20
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
21
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
22
+ from diffusers.utils import PIL_INTERPOLATION, deprecate
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ EXAMPLE_DOC_STRING = """
27
+ Examples:
28
+ ```py
29
+ from io import BytesIO
30
+
31
+ import requests
32
+ import torch
33
+ from diffusers import DiffusionPipeline
34
+ from PIL import Image
35
+ from transformers import CLIPImageProcessor, CLIPModel
36
+
37
+ feature_extractor = CLIPImageProcessor.from_pretrained(
38
+ "laion/CLIP-ViT-B-32-laion2B-s34B-b79K"
39
+ )
40
+ clip_model = CLIPModel.from_pretrained(
41
+ "laion/CLIP-ViT-B-32-laion2B-s34B-b79K", torch_dtype=torch.float16
42
+ )
43
+
44
+
45
+ guided_pipeline = DiffusionPipeline.from_pretrained(
46
+ "CompVis/stable-diffusion-v1-4",
47
+ # custom_pipeline="clip_guided_stable_diffusion",
48
+ custom_pipeline="/home/njindal/diffusers/examples/community/clip_guided_stable_diffusion.py",
49
+ clip_model=clip_model,
50
+ feature_extractor=feature_extractor,
51
+ torch_dtype=torch.float16,
52
+ )
53
+ guided_pipeline.enable_attention_slicing()
54
+ guided_pipeline = guided_pipeline.to("cuda")
55
+
56
+ prompt = "fantasy book cover, full moon, fantasy forest landscape, golden vector elements, fantasy magic, dark light night, intricate, elegant, sharp focus, illustration, highly detailed, digital painting, concept art, matte, art by WLOP and Artgerm and Albert Bierstadt, masterpiece"
57
+
58
+ url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
59
+
60
+ response = requests.get(url)
61
+ init_image = Image.open(BytesIO(response.content)).convert("RGB")
62
+
63
+ image = guided_pipeline(
64
+ prompt=prompt,
65
+ num_inference_steps=30,
66
+ image=init_image,
67
+ strength=0.75,
68
+ guidance_scale=7.5,
69
+ clip_guidance_scale=100,
70
+ num_cutouts=4,
71
+ use_cutouts=False,
72
+ ).images[0]
73
+ display(image)
74
+ ```
75
+ """
76
+
77
+
78
+ def preprocess(image, w, h):
79
+ if isinstance(image, torch.Tensor):
80
+ return image
81
+ elif isinstance(image, PIL.Image.Image):
82
+ image = [image]
83
+
84
+ if isinstance(image[0], PIL.Image.Image):
85
+ image = [np.array(i.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]))[None, :] for i in image]
86
+ image = np.concatenate(image, axis=0)
87
+ image = np.array(image).astype(np.float32) / 255.0
88
+ image = image.transpose(0, 3, 1, 2)
89
+ image = 2.0 * image - 1.0
90
+ image = torch.from_numpy(image)
91
+ elif isinstance(image[0], torch.Tensor):
92
+ image = torch.cat(image, dim=0)
93
+ return image
94
+
95
+
96
+ class MakeCutouts(nn.Module):
97
+ def __init__(self, cut_size, cut_power=1.0):
98
+ super().__init__()
99
+
100
+ self.cut_size = cut_size
101
+ self.cut_power = cut_power
102
+
103
+ def forward(self, pixel_values, num_cutouts):
104
+ sideY, sideX = pixel_values.shape[2:4]
105
+ max_size = min(sideX, sideY)
106
+ min_size = min(sideX, sideY, self.cut_size)
107
+ cutouts = []
108
+ for _ in range(num_cutouts):
109
+ size = int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
110
+ offsetx = torch.randint(0, sideX - size + 1, ())
111
+ offsety = torch.randint(0, sideY - size + 1, ())
112
+ cutout = pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
113
+ cutouts.append(F.adaptive_avg_pool2d(cutout, self.cut_size))
114
+ return torch.cat(cutouts)
115
+
116
+
117
+ def spherical_dist_loss(x, y):
118
+ x = F.normalize(x, dim=-1)
119
+ y = F.normalize(y, dim=-1)
120
+ return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2)
121
+
122
+
123
+ def set_requires_grad(model, value):
124
+ for param in model.parameters():
125
+ param.requires_grad = value
126
+
127
+
128
+ class CLIPGuidedStableDiffusion(DiffusionPipeline, StableDiffusionMixin):
129
+ """CLIP guided stable diffusion based on the amazing repo by @crowsonkb and @Jack000
130
+ - https://github.com/Jack000/glid-3-xl
131
+ - https://github.dev/crowsonkb/k-diffusion
132
+ """
133
+
134
+ def __init__(
135
+ self,
136
+ vae: AutoencoderKL,
137
+ text_encoder: CLIPTextModel,
138
+ clip_model: CLIPModel,
139
+ tokenizer: CLIPTokenizer,
140
+ unet: UNet2DConditionModel,
141
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler],
142
+ feature_extractor: CLIPImageProcessor,
143
+ ):
144
+ super().__init__()
145
+ self.register_modules(
146
+ vae=vae,
147
+ text_encoder=text_encoder,
148
+ clip_model=clip_model,
149
+ tokenizer=tokenizer,
150
+ unet=unet,
151
+ scheduler=scheduler,
152
+ feature_extractor=feature_extractor,
153
+ )
154
+
155
+ self.normalize = transforms.Normalize(mean=feature_extractor.image_mean, std=feature_extractor.image_std)
156
+ self.cut_out_size = (
157
+ feature_extractor.size
158
+ if isinstance(feature_extractor.size, int)
159
+ else feature_extractor.size["shortest_edge"]
160
+ )
161
+ self.make_cutouts = MakeCutouts(self.cut_out_size)
162
+
163
+ set_requires_grad(self.text_encoder, False)
164
+ set_requires_grad(self.clip_model, False)
165
+
166
+ def freeze_vae(self):
167
+ set_requires_grad(self.vae, False)
168
+
169
+ def unfreeze_vae(self):
170
+ set_requires_grad(self.vae, True)
171
+
172
+ def freeze_unet(self):
173
+ set_requires_grad(self.unet, False)
174
+
175
+ def unfreeze_unet(self):
176
+ set_requires_grad(self.unet, True)
177
+
178
+ def get_timesteps(self, num_inference_steps, strength, device):
179
+ # get the original timestep using init_timestep
180
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
181
+
182
+ t_start = max(num_inference_steps - init_timestep, 0)
183
+ timesteps = self.scheduler.timesteps[t_start:]
184
+
185
+ return timesteps, num_inference_steps - t_start
186
+
187
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
188
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
189
+ raise ValueError(
190
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
191
+ )
192
+
193
+ image = image.to(device=device, dtype=dtype)
194
+
195
+ batch_size = batch_size * num_images_per_prompt
196
+ if isinstance(generator, list) and len(generator) != batch_size:
197
+ raise ValueError(
198
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
199
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
200
+ )
201
+
202
+ if isinstance(generator, list):
203
+ init_latents = [
204
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
205
+ ]
206
+ init_latents = torch.cat(init_latents, dim=0)
207
+ else:
208
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
209
+
210
+ init_latents = self.vae.config.scaling_factor * init_latents
211
+
212
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
213
+ # expand init_latents for batch_size
214
+ deprecation_message = (
215
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
216
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
217
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
218
+ " your script to pass as many initial images as text prompts to suppress this warning."
219
+ )
220
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
221
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
222
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
223
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
224
+ raise ValueError(
225
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
226
+ )
227
+ else:
228
+ init_latents = torch.cat([init_latents], dim=0)
229
+
230
+ shape = init_latents.shape
231
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
232
+
233
+ # get latents
234
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
235
+ latents = init_latents
236
+
237
+ return latents
238
+
239
+ @torch.enable_grad()
240
+ def cond_fn(
241
+ self,
242
+ latents,
243
+ timestep,
244
+ index,
245
+ text_embeddings,
246
+ noise_pred_original,
247
+ text_embeddings_clip,
248
+ clip_guidance_scale,
249
+ num_cutouts,
250
+ use_cutouts=True,
251
+ ):
252
+ latents = latents.detach().requires_grad_()
253
+
254
+ latent_model_input = self.scheduler.scale_model_input(latents, timestep)
255
+
256
+ # predict the noise residual
257
+ noise_pred = self.unet(latent_model_input, timestep, encoder_hidden_states=text_embeddings).sample
258
+
259
+ if isinstance(self.scheduler, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
260
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
261
+ beta_prod_t = 1 - alpha_prod_t
262
+ # compute predicted original sample from predicted noise also called
263
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
264
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
265
+
266
+ fac = torch.sqrt(beta_prod_t)
267
+ sample = pred_original_sample * (fac) + latents * (1 - fac)
268
+ elif isinstance(self.scheduler, LMSDiscreteScheduler):
269
+ sigma = self.scheduler.sigmas[index]
270
+ sample = latents - sigma * noise_pred
271
+ else:
272
+ raise ValueError(f"scheduler type {type(self.scheduler)} not supported")
273
+
274
+ sample = 1 / self.vae.config.scaling_factor * sample
275
+ image = self.vae.decode(sample).sample
276
+ image = (image / 2 + 0.5).clamp(0, 1)
277
+
278
+ if use_cutouts:
279
+ image = self.make_cutouts(image, num_cutouts)
280
+ else:
281
+ image = transforms.Resize(self.cut_out_size)(image)
282
+ image = self.normalize(image).to(latents.dtype)
283
+
284
+ image_embeddings_clip = self.clip_model.get_image_features(image)
285
+ image_embeddings_clip = image_embeddings_clip / image_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
286
+
287
+ if use_cutouts:
288
+ dists = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip)
289
+ dists = dists.view([num_cutouts, sample.shape[0], -1])
290
+ loss = dists.sum(2).mean(0).sum() * clip_guidance_scale
291
+ else:
292
+ loss = spherical_dist_loss(image_embeddings_clip, text_embeddings_clip).mean() * clip_guidance_scale
293
+
294
+ grads = -torch.autograd.grad(loss, latents)[0]
295
+
296
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
297
+ latents = latents.detach() + grads * (sigma**2)
298
+ noise_pred = noise_pred_original
299
+ else:
300
+ noise_pred = noise_pred_original - torch.sqrt(beta_prod_t) * grads
301
+ return noise_pred, latents
302
+
303
+ @torch.no_grad()
304
+ def __call__(
305
+ self,
306
+ prompt: Union[str, List[str]],
307
+ height: Optional[int] = 512,
308
+ width: Optional[int] = 512,
309
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
310
+ strength: float = 0.8,
311
+ num_inference_steps: Optional[int] = 50,
312
+ guidance_scale: Optional[float] = 7.5,
313
+ num_images_per_prompt: Optional[int] = 1,
314
+ eta: float = 0.0,
315
+ clip_guidance_scale: Optional[float] = 100,
316
+ clip_prompt: Optional[Union[str, List[str]]] = None,
317
+ num_cutouts: Optional[int] = 4,
318
+ use_cutouts: Optional[bool] = True,
319
+ generator: Optional[torch.Generator] = None,
320
+ latents: Optional[torch.Tensor] = None,
321
+ output_type: Optional[str] = "pil",
322
+ return_dict: bool = True,
323
+ ):
324
+ if isinstance(prompt, str):
325
+ batch_size = 1
326
+ elif isinstance(prompt, list):
327
+ batch_size = len(prompt)
328
+ else:
329
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
330
+
331
+ if height % 8 != 0 or width % 8 != 0:
332
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
333
+
334
+ # get prompt text embeddings
335
+ text_input = self.tokenizer(
336
+ prompt,
337
+ padding="max_length",
338
+ max_length=self.tokenizer.model_max_length,
339
+ truncation=True,
340
+ return_tensors="pt",
341
+ )
342
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
343
+ # duplicate text embeddings for each generation per prompt
344
+ text_embeddings = text_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
345
+
346
+ # set timesteps
347
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
348
+ extra_set_kwargs = {}
349
+ if accepts_offset:
350
+ extra_set_kwargs["offset"] = 1
351
+
352
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
353
+ # Some schedulers like PNDM have timesteps as arrays
354
+ # It's more optimized to move all timesteps to correct device beforehand
355
+ self.scheduler.timesteps.to(self.device)
356
+
357
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)
358
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
359
+
360
+ # Preprocess image
361
+ image = preprocess(image, width, height)
362
+ if latents is None:
363
+ latents = self.prepare_latents(
364
+ image,
365
+ latent_timestep,
366
+ batch_size,
367
+ num_images_per_prompt,
368
+ text_embeddings.dtype,
369
+ self.device,
370
+ generator,
371
+ )
372
+
373
+ if clip_guidance_scale > 0:
374
+ if clip_prompt is not None:
375
+ clip_text_input = self.tokenizer(
376
+ clip_prompt,
377
+ padding="max_length",
378
+ max_length=self.tokenizer.model_max_length,
379
+ truncation=True,
380
+ return_tensors="pt",
381
+ ).input_ids.to(self.device)
382
+ else:
383
+ clip_text_input = text_input.input_ids.to(self.device)
384
+ text_embeddings_clip = self.clip_model.get_text_features(clip_text_input)
385
+ text_embeddings_clip = text_embeddings_clip / text_embeddings_clip.norm(p=2, dim=-1, keepdim=True)
386
+ # duplicate text embeddings clip for each generation per prompt
387
+ text_embeddings_clip = text_embeddings_clip.repeat_interleave(num_images_per_prompt, dim=0)
388
+
389
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
390
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
391
+ # corresponds to doing no classifier free guidance.
392
+ do_classifier_free_guidance = guidance_scale > 1.0
393
+ # get unconditional embeddings for classifier free guidance
394
+ if do_classifier_free_guidance:
395
+ max_length = text_input.input_ids.shape[-1]
396
+ uncond_input = self.tokenizer([""], padding="max_length", max_length=max_length, return_tensors="pt")
397
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
398
+ # duplicate unconditional embeddings for each generation per prompt
399
+ uncond_embeddings = uncond_embeddings.repeat_interleave(num_images_per_prompt, dim=0)
400
+
401
+ # For classifier free guidance, we need to do two forward passes.
402
+ # Here we concatenate the unconditional and text embeddings into a single batch
403
+ # to avoid doing two forward passes
404
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
405
+
406
+ # get the initial random noise unless the user supplied it
407
+
408
+ # Unlike in other pipelines, latents need to be generated in the target device
409
+ # for 1-to-1 results reproducibility with the CompVis implementation.
410
+ # However this currently doesn't work in `mps`.
411
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
412
+ latents_dtype = text_embeddings.dtype
413
+ if latents is None:
414
+ if self.device.type == "mps":
415
+ # randn does not work reproducibly on mps
416
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
417
+ self.device
418
+ )
419
+ else:
420
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
421
+ else:
422
+ if latents.shape != latents_shape:
423
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
424
+ latents = latents.to(self.device)
425
+
426
+ # scale the initial noise by the standard deviation required by the scheduler
427
+ latents = latents * self.scheduler.init_noise_sigma
428
+
429
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
430
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
431
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
432
+ # and should be between [0, 1]
433
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
434
+ extra_step_kwargs = {}
435
+ if accepts_eta:
436
+ extra_step_kwargs["eta"] = eta
437
+
438
+ # check if the scheduler accepts generator
439
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
440
+ if accepts_generator:
441
+ extra_step_kwargs["generator"] = generator
442
+
443
+ with self.progress_bar(total=num_inference_steps):
444
+ for i, t in enumerate(timesteps):
445
+ # expand the latents if we are doing classifier free guidance
446
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
447
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
448
+
449
+ # predict the noise residual
450
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
451
+
452
+ # perform classifier free guidance
453
+ if do_classifier_free_guidance:
454
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
455
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
456
+
457
+ # perform clip guidance
458
+ if clip_guidance_scale > 0:
459
+ text_embeddings_for_guidance = (
460
+ text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
461
+ )
462
+ noise_pred, latents = self.cond_fn(
463
+ latents,
464
+ t,
465
+ i,
466
+ text_embeddings_for_guidance,
467
+ noise_pred,
468
+ text_embeddings_clip,
469
+ clip_guidance_scale,
470
+ num_cutouts,
471
+ use_cutouts,
472
+ )
473
+
474
+ # compute the previous noisy sample x_t -> x_t-1
475
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
476
+
477
+ # scale and decode the image latents with vae
478
+ latents = 1 / self.vae.config.scaling_factor * latents
479
+ image = self.vae.decode(latents).sample
480
+
481
+ image = (image / 2 + 0.5).clamp(0, 1)
482
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
483
+
484
+ if output_type == "pil":
485
+ image = self.numpy_to_pil(image)
486
+
487
+ if not return_dict:
488
+ return (image, None)
489
+
490
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=None)
v0.32.0/composable_stable_diffusion.py ADDED
@@ -0,0 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers import DiffusionPipeline
23
+ from diffusers.configuration_utils import FrozenDict
24
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
25
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
26
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
27
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
28
+ from diffusers.schedulers import (
29
+ DDIMScheduler,
30
+ DPMSolverMultistepScheduler,
31
+ EulerAncestralDiscreteScheduler,
32
+ EulerDiscreteScheduler,
33
+ LMSDiscreteScheduler,
34
+ PNDMScheduler,
35
+ )
36
+ from diffusers.utils import deprecate, logging
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ class ComposableStableDiffusionPipeline(DiffusionPipeline, StableDiffusionMixin):
43
+ r"""
44
+ Pipeline for text-to-image generation using Stable Diffusion.
45
+
46
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
47
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
48
+
49
+ Args:
50
+ vae ([`AutoencoderKL`]):
51
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
52
+ text_encoder ([`CLIPTextModel`]):
53
+ Frozen text-encoder. Stable Diffusion uses the text portion of
54
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
55
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
56
+ tokenizer (`CLIPTokenizer`):
57
+ Tokenizer of class
58
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
59
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
60
+ scheduler ([`SchedulerMixin`]):
61
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
62
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
63
+ safety_checker ([`StableDiffusionSafetyChecker`]):
64
+ Classification module that estimates whether generated images could be considered offensive or harmful.
65
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
66
+ feature_extractor ([`CLIPImageProcessor`]):
67
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
68
+ """
69
+
70
+ _optional_components = ["safety_checker", "feature_extractor"]
71
+
72
+ def __init__(
73
+ self,
74
+ vae: AutoencoderKL,
75
+ text_encoder: CLIPTextModel,
76
+ tokenizer: CLIPTokenizer,
77
+ unet: UNet2DConditionModel,
78
+ scheduler: Union[
79
+ DDIMScheduler,
80
+ PNDMScheduler,
81
+ LMSDiscreteScheduler,
82
+ EulerDiscreteScheduler,
83
+ EulerAncestralDiscreteScheduler,
84
+ DPMSolverMultistepScheduler,
85
+ ],
86
+ safety_checker: StableDiffusionSafetyChecker,
87
+ feature_extractor: CLIPImageProcessor,
88
+ requires_safety_checker: bool = True,
89
+ ):
90
+ super().__init__()
91
+
92
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
93
+ deprecation_message = (
94
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
95
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
96
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
97
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
98
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
99
+ " file"
100
+ )
101
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
102
+ new_config = dict(scheduler.config)
103
+ new_config["steps_offset"] = 1
104
+ scheduler._internal_dict = FrozenDict(new_config)
105
+
106
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
107
+ deprecation_message = (
108
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
109
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
110
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
111
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
112
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
113
+ )
114
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
115
+ new_config = dict(scheduler.config)
116
+ new_config["clip_sample"] = False
117
+ scheduler._internal_dict = FrozenDict(new_config)
118
+
119
+ if safety_checker is None and requires_safety_checker:
120
+ logger.warning(
121
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
122
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
123
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
124
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
125
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
126
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
127
+ )
128
+
129
+ if safety_checker is not None and feature_extractor is None:
130
+ raise ValueError(
131
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
132
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
133
+ )
134
+
135
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
136
+ version.parse(unet.config._diffusers_version).base_version
137
+ ) < version.parse("0.9.0.dev0")
138
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
139
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
140
+ deprecation_message = (
141
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
142
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
143
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
144
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
145
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
146
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
147
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
148
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
149
+ " the `unet/config.json` file"
150
+ )
151
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
152
+ new_config = dict(unet.config)
153
+ new_config["sample_size"] = 64
154
+ unet._internal_dict = FrozenDict(new_config)
155
+
156
+ self.register_modules(
157
+ vae=vae,
158
+ text_encoder=text_encoder,
159
+ tokenizer=tokenizer,
160
+ unet=unet,
161
+ scheduler=scheduler,
162
+ safety_checker=safety_checker,
163
+ feature_extractor=feature_extractor,
164
+ )
165
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
166
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
167
+
168
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
169
+ r"""
170
+ Encodes the prompt into text encoder hidden states.
171
+
172
+ Args:
173
+ prompt (`str` or `list(int)`):
174
+ prompt to be encoded
175
+ device: (`torch.device`):
176
+ torch device
177
+ num_images_per_prompt (`int`):
178
+ number of images that should be generated per prompt
179
+ do_classifier_free_guidance (`bool`):
180
+ whether to use classifier free guidance or not
181
+ negative_prompt (`str` or `List[str]`):
182
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
183
+ if `guidance_scale` is less than `1`).
184
+ """
185
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
186
+
187
+ text_inputs = self.tokenizer(
188
+ prompt,
189
+ padding="max_length",
190
+ max_length=self.tokenizer.model_max_length,
191
+ truncation=True,
192
+ return_tensors="pt",
193
+ )
194
+ text_input_ids = text_inputs.input_ids
195
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
196
+
197
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
198
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
199
+ logger.warning(
200
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
201
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
202
+ )
203
+
204
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
205
+ attention_mask = text_inputs.attention_mask.to(device)
206
+ else:
207
+ attention_mask = None
208
+
209
+ text_embeddings = self.text_encoder(
210
+ text_input_ids.to(device),
211
+ attention_mask=attention_mask,
212
+ )
213
+ text_embeddings = text_embeddings[0]
214
+
215
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
216
+ bs_embed, seq_len, _ = text_embeddings.shape
217
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
218
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
219
+
220
+ # get unconditional embeddings for classifier free guidance
221
+ if do_classifier_free_guidance:
222
+ uncond_tokens: List[str]
223
+ if negative_prompt is None:
224
+ uncond_tokens = [""] * batch_size
225
+ elif type(prompt) is not type(negative_prompt):
226
+ raise TypeError(
227
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
228
+ f" {type(prompt)}."
229
+ )
230
+ elif isinstance(negative_prompt, str):
231
+ uncond_tokens = [negative_prompt]
232
+ elif batch_size != len(negative_prompt):
233
+ raise ValueError(
234
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
235
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
236
+ " the batch size of `prompt`."
237
+ )
238
+ else:
239
+ uncond_tokens = negative_prompt
240
+
241
+ max_length = text_input_ids.shape[-1]
242
+ uncond_input = self.tokenizer(
243
+ uncond_tokens,
244
+ padding="max_length",
245
+ max_length=max_length,
246
+ truncation=True,
247
+ return_tensors="pt",
248
+ )
249
+
250
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
251
+ attention_mask = uncond_input.attention_mask.to(device)
252
+ else:
253
+ attention_mask = None
254
+
255
+ uncond_embeddings = self.text_encoder(
256
+ uncond_input.input_ids.to(device),
257
+ attention_mask=attention_mask,
258
+ )
259
+ uncond_embeddings = uncond_embeddings[0]
260
+
261
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
262
+ seq_len = uncond_embeddings.shape[1]
263
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
264
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
265
+
266
+ # For classifier free guidance, we need to do two forward passes.
267
+ # Here we concatenate the unconditional and text embeddings into a single batch
268
+ # to avoid doing two forward passes
269
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
270
+
271
+ return text_embeddings
272
+
273
+ def run_safety_checker(self, image, device, dtype):
274
+ if self.safety_checker is not None:
275
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
276
+ image, has_nsfw_concept = self.safety_checker(
277
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
278
+ )
279
+ else:
280
+ has_nsfw_concept = None
281
+ return image, has_nsfw_concept
282
+
283
+ def decode_latents(self, latents):
284
+ latents = 1 / 0.18215 * latents
285
+ image = self.vae.decode(latents).sample
286
+ image = (image / 2 + 0.5).clamp(0, 1)
287
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
288
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
289
+ return image
290
+
291
+ def prepare_extra_step_kwargs(self, generator, eta):
292
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
293
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
294
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
295
+ # and should be between [0, 1]
296
+
297
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
298
+ extra_step_kwargs = {}
299
+ if accepts_eta:
300
+ extra_step_kwargs["eta"] = eta
301
+
302
+ # check if the scheduler accepts generator
303
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
304
+ if accepts_generator:
305
+ extra_step_kwargs["generator"] = generator
306
+ return extra_step_kwargs
307
+
308
+ def check_inputs(self, prompt, height, width, callback_steps):
309
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
310
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
311
+
312
+ if height % 8 != 0 or width % 8 != 0:
313
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
314
+
315
+ if (callback_steps is None) or (
316
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
317
+ ):
318
+ raise ValueError(
319
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
320
+ f" {type(callback_steps)}."
321
+ )
322
+
323
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
324
+ shape = (
325
+ batch_size,
326
+ num_channels_latents,
327
+ int(height) // self.vae_scale_factor,
328
+ int(width) // self.vae_scale_factor,
329
+ )
330
+ if latents is None:
331
+ if device.type == "mps":
332
+ # randn does not work reproducibly on mps
333
+ latents = torch.randn(shape, generator=generator, device="cpu", dtype=dtype).to(device)
334
+ else:
335
+ latents = torch.randn(shape, generator=generator, device=device, dtype=dtype)
336
+ else:
337
+ if latents.shape != shape:
338
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
339
+ latents = latents.to(device)
340
+
341
+ # scale the initial noise by the standard deviation required by the scheduler
342
+ latents = latents * self.scheduler.init_noise_sigma
343
+ return latents
344
+
345
+ @torch.no_grad()
346
+ def __call__(
347
+ self,
348
+ prompt: Union[str, List[str]],
349
+ height: Optional[int] = None,
350
+ width: Optional[int] = None,
351
+ num_inference_steps: int = 50,
352
+ guidance_scale: float = 7.5,
353
+ negative_prompt: Optional[Union[str, List[str]]] = None,
354
+ num_images_per_prompt: Optional[int] = 1,
355
+ eta: float = 0.0,
356
+ generator: Optional[torch.Generator] = None,
357
+ latents: Optional[torch.Tensor] = None,
358
+ output_type: Optional[str] = "pil",
359
+ return_dict: bool = True,
360
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
361
+ callback_steps: int = 1,
362
+ weights: Optional[str] = "",
363
+ ):
364
+ r"""
365
+ Function invoked when calling the pipeline for generation.
366
+
367
+ Args:
368
+ prompt (`str` or `List[str]`):
369
+ The prompt or prompts to guide the image generation.
370
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
371
+ The height in pixels of the generated image.
372
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
373
+ The width in pixels of the generated image.
374
+ num_inference_steps (`int`, *optional*, defaults to 50):
375
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
376
+ expense of slower inference.
377
+ guidance_scale (`float`, *optional*, defaults to 5.0):
378
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
379
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
380
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
381
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
382
+ usually at the expense of lower image quality.
383
+ negative_prompt (`str` or `List[str]`, *optional*):
384
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
385
+ if `guidance_scale` is less than `1`).
386
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
387
+ The number of images to generate per prompt.
388
+ eta (`float`, *optional*, defaults to 0.0):
389
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
390
+ [`schedulers.DDIMScheduler`], will be ignored for others.
391
+ generator (`torch.Generator`, *optional*):
392
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
393
+ deterministic.
394
+ latents (`torch.Tensor`, *optional*):
395
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
396
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
397
+ tensor will ge generated by sampling using the supplied random `generator`.
398
+ output_type (`str`, *optional*, defaults to `"pil"`):
399
+ The output format of the generate image. Choose between
400
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
401
+ return_dict (`bool`, *optional*, defaults to `True`):
402
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
403
+ plain tuple.
404
+ callback (`Callable`, *optional*):
405
+ A function that will be called every `callback_steps` steps during inference. The function will be
406
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
407
+ callback_steps (`int`, *optional*, defaults to 1):
408
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
409
+ called at every step.
410
+
411
+ Returns:
412
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
413
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
414
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
415
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
416
+ (nsfw) content, according to the `safety_checker`.
417
+ """
418
+ # 0. Default height and width to unet
419
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
420
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
421
+
422
+ # 1. Check inputs. Raise error if not correct
423
+ self.check_inputs(prompt, height, width, callback_steps)
424
+
425
+ # 2. Define call parameters
426
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
427
+ device = self._execution_device
428
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
429
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
430
+ # corresponds to doing no classifier free guidance.
431
+ do_classifier_free_guidance = guidance_scale > 1.0
432
+
433
+ if "|" in prompt:
434
+ prompt = [x.strip() for x in prompt.split("|")]
435
+ print(f"composing {prompt}...")
436
+
437
+ if not weights:
438
+ # specify weights for prompts (excluding the unconditional score)
439
+ print("using equal positive weights (conjunction) for all prompts...")
440
+ weights = torch.tensor([guidance_scale] * len(prompt), device=self.device).reshape(-1, 1, 1, 1)
441
+ else:
442
+ # set prompt weight for each
443
+ num_prompts = len(prompt) if isinstance(prompt, list) else 1
444
+ weights = [float(w.strip()) for w in weights.split("|")]
445
+ # guidance scale as the default
446
+ if len(weights) < num_prompts:
447
+ weights.append(guidance_scale)
448
+ else:
449
+ weights = weights[:num_prompts]
450
+ assert len(weights) == len(prompt), "weights specified are not equal to the number of prompts"
451
+ weights = torch.tensor(weights, device=self.device).reshape(-1, 1, 1, 1)
452
+ else:
453
+ weights = guidance_scale
454
+
455
+ # 3. Encode input prompt
456
+ text_embeddings = self._encode_prompt(
457
+ prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
458
+ )
459
+
460
+ # 4. Prepare timesteps
461
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
462
+ timesteps = self.scheduler.timesteps
463
+
464
+ # 5. Prepare latent variables
465
+ num_channels_latents = self.unet.config.in_channels
466
+ latents = self.prepare_latents(
467
+ batch_size * num_images_per_prompt,
468
+ num_channels_latents,
469
+ height,
470
+ width,
471
+ text_embeddings.dtype,
472
+ device,
473
+ generator,
474
+ latents,
475
+ )
476
+
477
+ # composable diffusion
478
+ if isinstance(prompt, list) and batch_size == 1:
479
+ # remove extra unconditional embedding
480
+ # N = one unconditional embed + conditional embeds
481
+ text_embeddings = text_embeddings[len(prompt) - 1 :]
482
+
483
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
484
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
485
+
486
+ # 7. Denoising loop
487
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
488
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
489
+ for i, t in enumerate(timesteps):
490
+ # expand the latents if we are doing classifier free guidance
491
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
492
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
493
+
494
+ # predict the noise residual
495
+ noise_pred = []
496
+ for j in range(text_embeddings.shape[0]):
497
+ noise_pred.append(
498
+ self.unet(latent_model_input[:1], t, encoder_hidden_states=text_embeddings[j : j + 1]).sample
499
+ )
500
+ noise_pred = torch.cat(noise_pred, dim=0)
501
+
502
+ # perform guidance
503
+ if do_classifier_free_guidance:
504
+ noise_pred_uncond, noise_pred_text = noise_pred[:1], noise_pred[1:]
505
+ noise_pred = noise_pred_uncond + (weights * (noise_pred_text - noise_pred_uncond)).sum(
506
+ dim=0, keepdims=True
507
+ )
508
+
509
+ # compute the previous noisy sample x_t -> x_t-1
510
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
511
+
512
+ # call the callback, if provided
513
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
514
+ progress_bar.update()
515
+ if callback is not None and i % callback_steps == 0:
516
+ step_idx = i // getattr(self.scheduler, "order", 1)
517
+ callback(step_idx, t, latents)
518
+
519
+ # 8. Post-processing
520
+ image = self.decode_latents(latents)
521
+
522
+ # 9. Run safety checker
523
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
524
+
525
+ # 10. Convert to PIL
526
+ if output_type == "pil":
527
+ image = self.numpy_to_pil(image)
528
+
529
+ if not return_dict:
530
+ return (image, has_nsfw_concept)
531
+
532
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/ddim_noise_comparative_analysis.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import List, Optional, Tuple, Union
16
+
17
+ import PIL.Image
18
+ import torch
19
+ from torchvision import transforms
20
+
21
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
22
+ from diffusers.schedulers import DDIMScheduler
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ trans = transforms.Compose(
27
+ [
28
+ transforms.Resize((256, 256)),
29
+ transforms.ToTensor(),
30
+ transforms.Normalize([0.5], [0.5]),
31
+ ]
32
+ )
33
+
34
+
35
+ def preprocess(image):
36
+ if isinstance(image, torch.Tensor):
37
+ return image
38
+ elif isinstance(image, PIL.Image.Image):
39
+ image = [image]
40
+
41
+ image = [trans(img.convert("RGB")) for img in image]
42
+ image = torch.stack(image)
43
+ return image
44
+
45
+
46
+ class DDIMNoiseComparativeAnalysisPipeline(DiffusionPipeline):
47
+ r"""
48
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
+
51
+ Parameters:
52
+ unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
53
+ scheduler ([`SchedulerMixin`]):
54
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
55
+ [`DDPMScheduler`], or [`DDIMScheduler`].
56
+ """
57
+
58
+ def __init__(self, unet, scheduler):
59
+ super().__init__()
60
+
61
+ # make sure scheduler can always be converted to DDIM
62
+ scheduler = DDIMScheduler.from_config(scheduler.config)
63
+
64
+ self.register_modules(unet=unet, scheduler=scheduler)
65
+
66
+ def check_inputs(self, strength):
67
+ if strength < 0 or strength > 1:
68
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
69
+
70
+ def get_timesteps(self, num_inference_steps, strength, device):
71
+ # get the original timestep using init_timestep
72
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
73
+
74
+ t_start = max(num_inference_steps - init_timestep, 0)
75
+ timesteps = self.scheduler.timesteps[t_start:]
76
+
77
+ return timesteps, num_inference_steps - t_start
78
+
79
+ def prepare_latents(self, image, timestep, batch_size, dtype, device, generator=None):
80
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
81
+ raise ValueError(
82
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
83
+ )
84
+
85
+ init_latents = image.to(device=device, dtype=dtype)
86
+
87
+ if isinstance(generator, list) and len(generator) != batch_size:
88
+ raise ValueError(
89
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
90
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
91
+ )
92
+
93
+ shape = init_latents.shape
94
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
95
+
96
+ # get latents
97
+ print("add noise to latents at timestep", timestep)
98
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
99
+ latents = init_latents
100
+
101
+ return latents
102
+
103
+ @torch.no_grad()
104
+ def __call__(
105
+ self,
106
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
107
+ strength: float = 0.8,
108
+ batch_size: int = 1,
109
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
110
+ eta: float = 0.0,
111
+ num_inference_steps: int = 50,
112
+ use_clipped_model_output: Optional[bool] = None,
113
+ output_type: Optional[str] = "pil",
114
+ return_dict: bool = True,
115
+ ) -> Union[ImagePipelineOutput, Tuple]:
116
+ r"""
117
+ Args:
118
+ image (`torch.Tensor` or `PIL.Image.Image`):
119
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
120
+ process.
121
+ strength (`float`, *optional*, defaults to 0.8):
122
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
123
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
124
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
125
+ be maximum and the denoising process will run for the full number of iterations specified in
126
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
127
+ batch_size (`int`, *optional*, defaults to 1):
128
+ The number of images to generate.
129
+ generator (`torch.Generator`, *optional*):
130
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
131
+ to make generation deterministic.
132
+ eta (`float`, *optional*, defaults to 0.0):
133
+ The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).
134
+ num_inference_steps (`int`, *optional*, defaults to 50):
135
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
136
+ expense of slower inference.
137
+ use_clipped_model_output (`bool`, *optional*, defaults to `None`):
138
+ if `True` or `False`, see documentation for `DDIMScheduler.step`. If `None`, nothing is passed
139
+ downstream to the scheduler. So use `None` for schedulers which don't support this argument.
140
+ output_type (`str`, *optional*, defaults to `"pil"`):
141
+ The output format of the generate image. Choose between
142
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
143
+ return_dict (`bool`, *optional*, defaults to `True`):
144
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
145
+
146
+ Returns:
147
+ [`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is
148
+ True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.
149
+ """
150
+ # 1. Check inputs. Raise error if not correct
151
+ self.check_inputs(strength)
152
+
153
+ # 2. Preprocess image
154
+ image = preprocess(image)
155
+
156
+ # 3. set timesteps
157
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
158
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, self.device)
159
+ latent_timestep = timesteps[:1].repeat(batch_size)
160
+
161
+ # 4. Prepare latent variables
162
+ latents = self.prepare_latents(image, latent_timestep, batch_size, self.unet.dtype, self.device, generator)
163
+ image = latents
164
+
165
+ # 5. Denoising loop
166
+ for t in self.progress_bar(timesteps):
167
+ # 1. predict noise model_output
168
+ model_output = self.unet(image, t).sample
169
+
170
+ # 2. predict previous mean of image x_t-1 and add variance depending on eta
171
+ # eta corresponds to η in paper and should be between [0, 1]
172
+ # do x_t -> x_t-1
173
+ image = self.scheduler.step(
174
+ model_output,
175
+ t,
176
+ image,
177
+ eta=eta,
178
+ use_clipped_model_output=use_clipped_model_output,
179
+ generator=generator,
180
+ ).prev_sample
181
+
182
+ image = (image / 2 + 0.5).clamp(0, 1)
183
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
184
+ if output_type == "pil":
185
+ image = self.numpy_to_pil(image)
186
+
187
+ if not return_dict:
188
+ return (image, latent_timestep.item())
189
+
190
+ return ImagePipelineOutput(images=image)
v0.32.0/dps_pipeline.py ADDED
@@ -0,0 +1,466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from math import pi
17
+ from typing import Callable, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import torch
21
+ from PIL import Image
22
+
23
+ from diffusers import DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNet2DModel
24
+ from diffusers.utils.torch_utils import randn_tensor
25
+
26
+
27
+ class DPSPipeline(DiffusionPipeline):
28
+ r"""
29
+ Pipeline for Diffusion Posterior Sampling.
30
+
31
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
32
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
33
+
34
+ Parameters:
35
+ unet ([`UNet2DModel`]):
36
+ A `UNet2DModel` to denoise the encoded image latents.
37
+ scheduler ([`SchedulerMixin`]):
38
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
39
+ [`DDPMScheduler`], or [`DDIMScheduler`].
40
+ """
41
+
42
+ model_cpu_offload_seq = "unet"
43
+
44
+ def __init__(self, unet, scheduler):
45
+ super().__init__()
46
+ self.register_modules(unet=unet, scheduler=scheduler)
47
+
48
+ @torch.no_grad()
49
+ def __call__(
50
+ self,
51
+ measurement: torch.Tensor,
52
+ operator: torch.nn.Module,
53
+ loss_fn: Callable[[torch.Tensor, torch.Tensor], torch.Tensor],
54
+ batch_size: int = 1,
55
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
56
+ num_inference_steps: int = 1000,
57
+ output_type: Optional[str] = "pil",
58
+ return_dict: bool = True,
59
+ zeta: float = 0.3,
60
+ ) -> Union[ImagePipelineOutput, Tuple]:
61
+ r"""
62
+ The call function to the pipeline for generation.
63
+
64
+ Args:
65
+ measurement (`torch.Tensor`, *required*):
66
+ A 'torch.Tensor', the corrupted image
67
+ operator (`torch.nn.Module`, *required*):
68
+ A 'torch.nn.Module', the operator generating the corrupted image
69
+ loss_fn (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`, *required*):
70
+ A 'Callable[[torch.Tensor, torch.Tensor], torch.Tensor]', the loss function used
71
+ between the measurements, for most of the cases using RMSE is fine.
72
+ batch_size (`int`, *optional*, defaults to 1):
73
+ The number of images to generate.
74
+ generator (`torch.Generator`, *optional*):
75
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
76
+ generation deterministic.
77
+ num_inference_steps (`int`, *optional*, defaults to 1000):
78
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
79
+ expense of slower inference.
80
+ output_type (`str`, *optional*, defaults to `"pil"`):
81
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
82
+ return_dict (`bool`, *optional*, defaults to `True`):
83
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
84
+
85
+ Example:
86
+
87
+ ```py
88
+ >>> from diffusers import DDPMPipeline
89
+
90
+ >>> # load model and scheduler
91
+ >>> pipe = DDPMPipeline.from_pretrained("google/ddpm-cat-256")
92
+
93
+ >>> # run pipeline in inference (sample random noise and denoise)
94
+ >>> image = pipe().images[0]
95
+
96
+ >>> # save image
97
+ >>> image.save("ddpm_generated_image.png")
98
+ ```
99
+
100
+ Returns:
101
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
102
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
103
+ returned where the first element is a list with the generated images
104
+ """
105
+ # Sample gaussian noise to begin loop
106
+ if isinstance(self.unet.config.sample_size, int):
107
+ image_shape = (
108
+ batch_size,
109
+ self.unet.config.in_channels,
110
+ self.unet.config.sample_size,
111
+ self.unet.config.sample_size,
112
+ )
113
+ else:
114
+ image_shape = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
115
+
116
+ if self.device.type == "mps":
117
+ # randn does not work reproducibly on mps
118
+ image = randn_tensor(image_shape, generator=generator)
119
+ image = image.to(self.device)
120
+ else:
121
+ image = randn_tensor(image_shape, generator=generator, device=self.device)
122
+
123
+ # set step values
124
+ self.scheduler.set_timesteps(num_inference_steps)
125
+
126
+ for t in self.progress_bar(self.scheduler.timesteps):
127
+ with torch.enable_grad():
128
+ # 1. predict noise model_output
129
+ image = image.requires_grad_()
130
+ model_output = self.unet(image, t).sample
131
+
132
+ # 2. compute previous image x'_{t-1} and original prediction x0_{t}
133
+ scheduler_out = self.scheduler.step(model_output, t, image, generator=generator)
134
+ image_pred, origi_pred = scheduler_out.prev_sample, scheduler_out.pred_original_sample
135
+
136
+ # 3. compute y'_t = f(x0_{t})
137
+ measurement_pred = operator(origi_pred)
138
+
139
+ # 4. compute loss = d(y, y'_t-1)
140
+ loss = loss_fn(measurement, measurement_pred)
141
+ loss.backward()
142
+
143
+ print("distance: {0:.4f}".format(loss.item()))
144
+
145
+ with torch.no_grad():
146
+ image_pred = image_pred - zeta * image.grad
147
+ image = image_pred.detach()
148
+
149
+ image = (image / 2 + 0.5).clamp(0, 1)
150
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
151
+ if output_type == "pil":
152
+ image = self.numpy_to_pil(image)
153
+
154
+ if not return_dict:
155
+ return (image,)
156
+
157
+ return ImagePipelineOutput(images=image)
158
+
159
+
160
+ if __name__ == "__main__":
161
+ import scipy
162
+ from torch import nn
163
+ from torchvision.utils import save_image
164
+
165
+ # defining the operators f(.) of y = f(x)
166
+ # super-resolution operator
167
+ class SuperResolutionOperator(nn.Module):
168
+ def __init__(self, in_shape, scale_factor):
169
+ super().__init__()
170
+
171
+ # Resizer local class, do not use outiside the SR operator class
172
+ class Resizer(nn.Module):
173
+ def __init__(self, in_shape, scale_factor=None, output_shape=None, kernel=None, antialiasing=True):
174
+ super(Resizer, self).__init__()
175
+
176
+ # First standardize values and fill missing arguments (if needed) by deriving scale from output shape or vice versa
177
+ scale_factor, output_shape = self.fix_scale_and_size(in_shape, output_shape, scale_factor)
178
+
179
+ # Choose interpolation method, each method has the matching kernel size
180
+ def cubic(x):
181
+ absx = np.abs(x)
182
+ absx2 = absx**2
183
+ absx3 = absx**3
184
+ return (1.5 * absx3 - 2.5 * absx2 + 1) * (absx <= 1) + (
185
+ -0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2
186
+ ) * ((1 < absx) & (absx <= 2))
187
+
188
+ def lanczos2(x):
189
+ return (
190
+ (np.sin(pi * x) * np.sin(pi * x / 2) + np.finfo(np.float32).eps)
191
+ / ((pi**2 * x**2 / 2) + np.finfo(np.float32).eps)
192
+ ) * (abs(x) < 2)
193
+
194
+ def box(x):
195
+ return ((-0.5 <= x) & (x < 0.5)) * 1.0
196
+
197
+ def lanczos3(x):
198
+ return (
199
+ (np.sin(pi * x) * np.sin(pi * x / 3) + np.finfo(np.float32).eps)
200
+ / ((pi**2 * x**2 / 3) + np.finfo(np.float32).eps)
201
+ ) * (abs(x) < 3)
202
+
203
+ def linear(x):
204
+ return (x + 1) * ((-1 <= x) & (x < 0)) + (1 - x) * ((0 <= x) & (x <= 1))
205
+
206
+ method, kernel_width = {
207
+ "cubic": (cubic, 4.0),
208
+ "lanczos2": (lanczos2, 4.0),
209
+ "lanczos3": (lanczos3, 6.0),
210
+ "box": (box, 1.0),
211
+ "linear": (linear, 2.0),
212
+ None: (cubic, 4.0), # set default interpolation method as cubic
213
+ }.get(kernel)
214
+
215
+ # Antialiasing is only used when downscaling
216
+ antialiasing *= np.any(np.array(scale_factor) < 1)
217
+
218
+ # Sort indices of dimensions according to scale of each dimension. since we are going dim by dim this is efficient
219
+ sorted_dims = np.argsort(np.array(scale_factor))
220
+ self.sorted_dims = [int(dim) for dim in sorted_dims if scale_factor[dim] != 1]
221
+
222
+ # Iterate over dimensions to calculate local weights for resizing and resize each time in one direction
223
+ field_of_view_list = []
224
+ weights_list = []
225
+ for dim in self.sorted_dims:
226
+ # for each coordinate (along 1 dim), calculate which coordinates in the input image affect its result and the
227
+ # weights that multiply the values there to get its result.
228
+ weights, field_of_view = self.contributions(
229
+ in_shape[dim], output_shape[dim], scale_factor[dim], method, kernel_width, antialiasing
230
+ )
231
+
232
+ # convert to torch tensor
233
+ weights = torch.tensor(weights.T, dtype=torch.float32)
234
+
235
+ # We add singleton dimensions to the weight matrix so we can multiply it with the big tensor we get for
236
+ # tmp_im[field_of_view.T], (bsxfun style)
237
+ weights_list.append(
238
+ nn.Parameter(
239
+ torch.reshape(weights, list(weights.shape) + (len(scale_factor) - 1) * [1]),
240
+ requires_grad=False,
241
+ )
242
+ )
243
+ field_of_view_list.append(
244
+ nn.Parameter(
245
+ torch.tensor(field_of_view.T.astype(np.int32), dtype=torch.long), requires_grad=False
246
+ )
247
+ )
248
+
249
+ self.field_of_view = nn.ParameterList(field_of_view_list)
250
+ self.weights = nn.ParameterList(weights_list)
251
+
252
+ def forward(self, in_tensor):
253
+ x = in_tensor
254
+
255
+ # Use the affecting position values and the set of weights to calculate the result of resizing along this 1 dim
256
+ for dim, fov, w in zip(self.sorted_dims, self.field_of_view, self.weights):
257
+ # To be able to act on each dim, we swap so that dim 0 is the wanted dim to resize
258
+ x = torch.transpose(x, dim, 0)
259
+
260
+ # This is a bit of a complicated multiplication: x[field_of_view.T] is a tensor of order image_dims+1.
261
+ # for each pixel in the output-image it matches the positions the influence it from the input image (along 1 dim
262
+ # only, this is why it only adds 1 dim to 5the shape). We then multiply, for each pixel, its set of positions with
263
+ # the matching set of weights. we do this by this big tensor element-wise multiplication (MATLAB bsxfun style:
264
+ # matching dims are multiplied element-wise while singletons mean that the matching dim is all multiplied by the
265
+ # same number
266
+ x = torch.sum(x[fov] * w, dim=0)
267
+
268
+ # Finally we swap back the axes to the original order
269
+ x = torch.transpose(x, dim, 0)
270
+
271
+ return x
272
+
273
+ def fix_scale_and_size(self, input_shape, output_shape, scale_factor):
274
+ # First fixing the scale-factor (if given) to be standardized the function expects (a list of scale factors in the
275
+ # same size as the number of input dimensions)
276
+ if scale_factor is not None:
277
+ # By default, if scale-factor is a scalar we assume 2d resizing and duplicate it.
278
+ if np.isscalar(scale_factor) and len(input_shape) > 1:
279
+ scale_factor = [scale_factor, scale_factor]
280
+
281
+ # We extend the size of scale-factor list to the size of the input by assigning 1 to all the unspecified scales
282
+ scale_factor = list(scale_factor)
283
+ scale_factor = [1] * (len(input_shape) - len(scale_factor)) + scale_factor
284
+
285
+ # Fixing output-shape (if given): extending it to the size of the input-shape, by assigning the original input-size
286
+ # to all the unspecified dimensions
287
+ if output_shape is not None:
288
+ output_shape = list(input_shape[len(output_shape) :]) + list(np.uint(np.array(output_shape)))
289
+
290
+ # Dealing with the case of non-give scale-factor, calculating according to output-shape. note that this is
291
+ # sub-optimal, because there can be different scales to the same output-shape.
292
+ if scale_factor is None:
293
+ scale_factor = 1.0 * np.array(output_shape) / np.array(input_shape)
294
+
295
+ # Dealing with missing output-shape. calculating according to scale-factor
296
+ if output_shape is None:
297
+ output_shape = np.uint(np.ceil(np.array(input_shape) * np.array(scale_factor)))
298
+
299
+ return scale_factor, output_shape
300
+
301
+ def contributions(self, in_length, out_length, scale, kernel, kernel_width, antialiasing):
302
+ # This function calculates a set of 'filters' and a set of field_of_view that will later on be applied
303
+ # such that each position from the field_of_view will be multiplied with a matching filter from the
304
+ # 'weights' based on the interpolation method and the distance of the sub-pixel location from the pixel centers
305
+ # around it. This is only done for one dimension of the image.
306
+
307
+ # When anti-aliasing is activated (default and only for downscaling) the receptive field is stretched to size of
308
+ # 1/sf. this means filtering is more 'low-pass filter'.
309
+ fixed_kernel = (lambda arg: scale * kernel(scale * arg)) if antialiasing else kernel
310
+ kernel_width *= 1.0 / scale if antialiasing else 1.0
311
+
312
+ # These are the coordinates of the output image
313
+ out_coordinates = np.arange(1, out_length + 1)
314
+
315
+ # since both scale-factor and output size can be provided simulatneously, perserving the center of the image requires shifting
316
+ # the output coordinates. the deviation is because out_length doesn't necesary equal in_length*scale.
317
+ # to keep the center we need to subtract half of this deivation so that we get equal margins for boths sides and center is preserved.
318
+ shifted_out_coordinates = out_coordinates - (out_length - in_length * scale) / 2
319
+
320
+ # These are the matching positions of the output-coordinates on the input image coordinates.
321
+ # Best explained by example: say we have 4 horizontal pixels for HR and we downscale by SF=2 and get 2 pixels:
322
+ # [1,2,3,4] -> [1,2]. Remember each pixel number is the middle of the pixel.
323
+ # The scaling is done between the distances and not pixel numbers (the right boundary of pixel 4 is transformed to
324
+ # the right boundary of pixel 2. pixel 1 in the small image matches the boundary between pixels 1 and 2 in the big
325
+ # one and not to pixel 2. This means the position is not just multiplication of the old pos by scale-factor).
326
+ # So if we measure distance from the left border, middle of pixel 1 is at distance d=0.5, border between 1 and 2 is
327
+ # at d=1, and so on (d = p - 0.5). we calculate (d_new = d_old / sf) which means:
328
+ # (p_new-0.5 = (p_old-0.5) / sf) -> p_new = p_old/sf + 0.5 * (1-1/sf)
329
+ match_coordinates = shifted_out_coordinates / scale + 0.5 * (1 - 1 / scale)
330
+
331
+ # This is the left boundary to start multiplying the filter from, it depends on the size of the filter
332
+ left_boundary = np.floor(match_coordinates - kernel_width / 2)
333
+
334
+ # Kernel width needs to be enlarged because when covering has sub-pixel borders, it must 'see' the pixel centers
335
+ # of the pixels it only covered a part from. So we add one pixel at each side to consider (weights can zeroize them)
336
+ expanded_kernel_width = np.ceil(kernel_width) + 2
337
+
338
+ # Determine a set of field_of_view for each each output position, these are the pixels in the input image
339
+ # that the pixel in the output image 'sees'. We get a matrix whos horizontal dim is the output pixels (big) and the
340
+ # vertical dim is the pixels it 'sees' (kernel_size + 2)
341
+ field_of_view = np.squeeze(
342
+ np.int16(np.expand_dims(left_boundary, axis=1) + np.arange(expanded_kernel_width) - 1)
343
+ )
344
+
345
+ # Assign weight to each pixel in the field of view. A matrix whos horizontal dim is the output pixels and the
346
+ # vertical dim is a list of weights matching to the pixel in the field of view (that are specified in
347
+ # 'field_of_view')
348
+ weights = fixed_kernel(1.0 * np.expand_dims(match_coordinates, axis=1) - field_of_view - 1)
349
+
350
+ # Normalize weights to sum up to 1. be careful from dividing by 0
351
+ sum_weights = np.sum(weights, axis=1)
352
+ sum_weights[sum_weights == 0] = 1.0
353
+ weights = 1.0 * weights / np.expand_dims(sum_weights, axis=1)
354
+
355
+ # We use this mirror structure as a trick for reflection padding at the boundaries
356
+ mirror = np.uint(np.concatenate((np.arange(in_length), np.arange(in_length - 1, -1, step=-1))))
357
+ field_of_view = mirror[np.mod(field_of_view, mirror.shape[0])]
358
+
359
+ # Get rid of weights and pixel positions that are of zero weight
360
+ non_zero_out_pixels = np.nonzero(np.any(weights, axis=0))
361
+ weights = np.squeeze(weights[:, non_zero_out_pixels])
362
+ field_of_view = np.squeeze(field_of_view[:, non_zero_out_pixels])
363
+
364
+ # Final products are the relative positions and the matching weights, both are output_size X fixed_kernel_size
365
+ return weights, field_of_view
366
+
367
+ self.down_sample = Resizer(in_shape, 1 / scale_factor)
368
+ for param in self.parameters():
369
+ param.requires_grad = False
370
+
371
+ def forward(self, data, **kwargs):
372
+ return self.down_sample(data)
373
+
374
+ # Gaussian blurring operator
375
+ class GaussialBlurOperator(nn.Module):
376
+ def __init__(self, kernel_size, intensity):
377
+ super().__init__()
378
+
379
+ class Blurkernel(nn.Module):
380
+ def __init__(self, blur_type="gaussian", kernel_size=31, std=3.0):
381
+ super().__init__()
382
+ self.blur_type = blur_type
383
+ self.kernel_size = kernel_size
384
+ self.std = std
385
+ self.seq = nn.Sequential(
386
+ nn.ReflectionPad2d(self.kernel_size // 2),
387
+ nn.Conv2d(3, 3, self.kernel_size, stride=1, padding=0, bias=False, groups=3),
388
+ )
389
+ self.weights_init()
390
+
391
+ def forward(self, x):
392
+ return self.seq(x)
393
+
394
+ def weights_init(self):
395
+ if self.blur_type == "gaussian":
396
+ n = np.zeros((self.kernel_size, self.kernel_size))
397
+ n[self.kernel_size // 2, self.kernel_size // 2] = 1
398
+ k = scipy.ndimage.gaussian_filter(n, sigma=self.std)
399
+ k = torch.from_numpy(k)
400
+ self.k = k
401
+ for name, f in self.named_parameters():
402
+ f.data.copy_(k)
403
+
404
+ def update_weights(self, k):
405
+ if not torch.is_tensor(k):
406
+ k = torch.from_numpy(k)
407
+ for name, f in self.named_parameters():
408
+ f.data.copy_(k)
409
+
410
+ def get_kernel(self):
411
+ return self.k
412
+
413
+ self.kernel_size = kernel_size
414
+ self.conv = Blurkernel(blur_type="gaussian", kernel_size=kernel_size, std=intensity)
415
+ self.kernel = self.conv.get_kernel()
416
+ self.conv.update_weights(self.kernel.type(torch.float32))
417
+
418
+ for param in self.parameters():
419
+ param.requires_grad = False
420
+
421
+ def forward(self, data, **kwargs):
422
+ return self.conv(data)
423
+
424
+ def transpose(self, data, **kwargs):
425
+ return data
426
+
427
+ def get_kernel(self):
428
+ return self.kernel.view(1, 1, self.kernel_size, self.kernel_size)
429
+
430
+ # assuming the forward process y = f(x) is polluted by Gaussian noise, use l2 norm
431
+ def RMSELoss(yhat, y):
432
+ return torch.sqrt(torch.sum((yhat - y) ** 2))
433
+
434
+ # set up source image
435
+ src = Image.open("sample.png")
436
+ # read image into [1,3,H,W]
437
+ src = torch.from_numpy(np.array(src, dtype=np.float32)).permute(2, 0, 1)[None]
438
+ # normalize image to [-1,1]
439
+ src = (src / 127.5) - 1.0
440
+ src = src.to("cuda")
441
+
442
+ # set up operator and measurement
443
+ # operator = SuperResolutionOperator(in_shape=src.shape, scale_factor=4).to("cuda")
444
+ operator = GaussialBlurOperator(kernel_size=61, intensity=3.0).to("cuda")
445
+ measurement = operator(src)
446
+
447
+ # set up scheduler
448
+ scheduler = DDPMScheduler.from_pretrained("google/ddpm-celebahq-256")
449
+ scheduler.set_timesteps(1000)
450
+
451
+ # set up model
452
+ model = UNet2DModel.from_pretrained("google/ddpm-celebahq-256").to("cuda")
453
+
454
+ save_image((src + 1.0) / 2.0, "dps_src.png")
455
+ save_image((measurement + 1.0) / 2.0, "dps_mea.png")
456
+
457
+ # finally, the pipeline
458
+ dpspipe = DPSPipeline(model, scheduler)
459
+ image = dpspipe(
460
+ measurement=measurement,
461
+ operator=operator,
462
+ loss_fn=RMSELoss,
463
+ zeta=1.0,
464
+ ).images[0]
465
+
466
+ image.save("dps_generated_image.png")
v0.32.0/edict_pipeline.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from tqdm.auto import tqdm
6
+ from transformers import CLIPTextModel, CLIPTokenizer
7
+
8
+ from diffusers import AutoencoderKL, DDIMScheduler, DiffusionPipeline, UNet2DConditionModel
9
+ from diffusers.image_processor import VaeImageProcessor
10
+ from diffusers.utils import (
11
+ deprecate,
12
+ )
13
+
14
+
15
+ class EDICTPipeline(DiffusionPipeline):
16
+ def __init__(
17
+ self,
18
+ vae: AutoencoderKL,
19
+ text_encoder: CLIPTextModel,
20
+ tokenizer: CLIPTokenizer,
21
+ unet: UNet2DConditionModel,
22
+ scheduler: DDIMScheduler,
23
+ mixing_coeff: float = 0.93,
24
+ leapfrog_steps: bool = True,
25
+ ):
26
+ self.mixing_coeff = mixing_coeff
27
+ self.leapfrog_steps = leapfrog_steps
28
+
29
+ super().__init__()
30
+ self.register_modules(
31
+ vae=vae,
32
+ text_encoder=text_encoder,
33
+ tokenizer=tokenizer,
34
+ unet=unet,
35
+ scheduler=scheduler,
36
+ )
37
+
38
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
39
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
40
+
41
+ def _encode_prompt(
42
+ self, prompt: str, negative_prompt: Optional[str] = None, do_classifier_free_guidance: bool = False
43
+ ):
44
+ text_inputs = self.tokenizer(
45
+ prompt,
46
+ padding="max_length",
47
+ max_length=self.tokenizer.model_max_length,
48
+ truncation=True,
49
+ return_tensors="pt",
50
+ )
51
+
52
+ prompt_embeds = self.text_encoder(text_inputs.input_ids.to(self.device)).last_hidden_state
53
+
54
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=self.device)
55
+
56
+ if do_classifier_free_guidance:
57
+ uncond_tokens = "" if negative_prompt is None else negative_prompt
58
+
59
+ uncond_input = self.tokenizer(
60
+ uncond_tokens,
61
+ padding="max_length",
62
+ max_length=self.tokenizer.model_max_length,
63
+ truncation=True,
64
+ return_tensors="pt",
65
+ )
66
+
67
+ negative_prompt_embeds = self.text_encoder(uncond_input.input_ids.to(self.device)).last_hidden_state
68
+
69
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
70
+
71
+ return prompt_embeds
72
+
73
+ def denoise_mixing_layer(self, x: torch.Tensor, y: torch.Tensor):
74
+ x = self.mixing_coeff * x + (1 - self.mixing_coeff) * y
75
+ y = self.mixing_coeff * y + (1 - self.mixing_coeff) * x
76
+
77
+ return [x, y]
78
+
79
+ def noise_mixing_layer(self, x: torch.Tensor, y: torch.Tensor):
80
+ y = (y - (1 - self.mixing_coeff) * x) / self.mixing_coeff
81
+ x = (x - (1 - self.mixing_coeff) * y) / self.mixing_coeff
82
+
83
+ return [x, y]
84
+
85
+ def _get_alpha_and_beta(self, t: torch.Tensor):
86
+ # as self.alphas_cumprod is always in cpu
87
+ t = int(t)
88
+
89
+ alpha_prod = self.scheduler.alphas_cumprod[t] if t >= 0 else self.scheduler.final_alpha_cumprod
90
+
91
+ return alpha_prod, 1 - alpha_prod
92
+
93
+ def noise_step(
94
+ self,
95
+ base: torch.Tensor,
96
+ model_input: torch.Tensor,
97
+ model_output: torch.Tensor,
98
+ timestep: torch.Tensor,
99
+ ):
100
+ prev_timestep = timestep - self.scheduler.config.num_train_timesteps / self.scheduler.num_inference_steps
101
+
102
+ alpha_prod_t, beta_prod_t = self._get_alpha_and_beta(timestep)
103
+ alpha_prod_t_prev, beta_prod_t_prev = self._get_alpha_and_beta(prev_timestep)
104
+
105
+ a_t = (alpha_prod_t_prev / alpha_prod_t) ** 0.5
106
+ b_t = -a_t * (beta_prod_t**0.5) + beta_prod_t_prev**0.5
107
+
108
+ next_model_input = (base - b_t * model_output) / a_t
109
+
110
+ return model_input, next_model_input.to(base.dtype)
111
+
112
+ def denoise_step(
113
+ self,
114
+ base: torch.Tensor,
115
+ model_input: torch.Tensor,
116
+ model_output: torch.Tensor,
117
+ timestep: torch.Tensor,
118
+ ):
119
+ prev_timestep = timestep - self.scheduler.config.num_train_timesteps / self.scheduler.num_inference_steps
120
+
121
+ alpha_prod_t, beta_prod_t = self._get_alpha_and_beta(timestep)
122
+ alpha_prod_t_prev, beta_prod_t_prev = self._get_alpha_and_beta(prev_timestep)
123
+
124
+ a_t = (alpha_prod_t_prev / alpha_prod_t) ** 0.5
125
+ b_t = -a_t * (beta_prod_t**0.5) + beta_prod_t_prev**0.5
126
+ next_model_input = a_t * base + b_t * model_output
127
+
128
+ return model_input, next_model_input.to(base.dtype)
129
+
130
+ @torch.no_grad()
131
+ def decode_latents(self, latents: torch.Tensor):
132
+ latents = 1 / self.vae.config.scaling_factor * latents
133
+ image = self.vae.decode(latents).sample
134
+ image = (image / 2 + 0.5).clamp(0, 1)
135
+ return image
136
+
137
+ @torch.no_grad()
138
+ def prepare_latents(
139
+ self,
140
+ image: Image.Image,
141
+ text_embeds: torch.Tensor,
142
+ timesteps: torch.Tensor,
143
+ guidance_scale: float,
144
+ generator: Optional[torch.Generator] = None,
145
+ ):
146
+ do_classifier_free_guidance = guidance_scale > 1.0
147
+
148
+ image = image.to(device=self.device, dtype=text_embeds.dtype)
149
+ latent = self.vae.encode(image).latent_dist.sample(generator)
150
+
151
+ latent = self.vae.config.scaling_factor * latent
152
+
153
+ coupled_latents = [latent.clone(), latent.clone()]
154
+
155
+ for i, t in tqdm(enumerate(timesteps), total=len(timesteps)):
156
+ coupled_latents = self.noise_mixing_layer(x=coupled_latents[0], y=coupled_latents[1])
157
+
158
+ # j - model_input index, k - base index
159
+ for j in range(2):
160
+ k = j ^ 1
161
+
162
+ if self.leapfrog_steps:
163
+ if i % 2 == 0:
164
+ k, j = j, k
165
+
166
+ model_input = coupled_latents[j]
167
+ base = coupled_latents[k]
168
+
169
+ latent_model_input = torch.cat([model_input] * 2) if do_classifier_free_guidance else model_input
170
+
171
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeds).sample
172
+
173
+ if do_classifier_free_guidance:
174
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
175
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
176
+
177
+ base, model_input = self.noise_step(
178
+ base=base,
179
+ model_input=model_input,
180
+ model_output=noise_pred,
181
+ timestep=t,
182
+ )
183
+
184
+ coupled_latents[k] = model_input
185
+
186
+ return coupled_latents
187
+
188
+ @torch.no_grad()
189
+ def __call__(
190
+ self,
191
+ base_prompt: str,
192
+ target_prompt: str,
193
+ image: Image.Image,
194
+ guidance_scale: float = 3.0,
195
+ num_inference_steps: int = 50,
196
+ strength: float = 0.8,
197
+ negative_prompt: Optional[str] = None,
198
+ generator: Optional[torch.Generator] = None,
199
+ output_type: Optional[str] = "pil",
200
+ ):
201
+ do_classifier_free_guidance = guidance_scale > 1.0
202
+
203
+ image = self.image_processor.preprocess(image)
204
+
205
+ base_embeds = self._encode_prompt(base_prompt, negative_prompt, do_classifier_free_guidance)
206
+ target_embeds = self._encode_prompt(target_prompt, negative_prompt, do_classifier_free_guidance)
207
+
208
+ self.scheduler.set_timesteps(num_inference_steps, self.device)
209
+
210
+ t_limit = num_inference_steps - int(num_inference_steps * strength)
211
+ fwd_timesteps = self.scheduler.timesteps[t_limit:]
212
+ bwd_timesteps = fwd_timesteps.flip(0)
213
+
214
+ coupled_latents = self.prepare_latents(image, base_embeds, bwd_timesteps, guidance_scale, generator)
215
+
216
+ for i, t in tqdm(enumerate(fwd_timesteps), total=len(fwd_timesteps)):
217
+ # j - model_input index, k - base index
218
+ for k in range(2):
219
+ j = k ^ 1
220
+
221
+ if self.leapfrog_steps:
222
+ if i % 2 == 1:
223
+ k, j = j, k
224
+
225
+ model_input = coupled_latents[j]
226
+ base = coupled_latents[k]
227
+
228
+ latent_model_input = torch.cat([model_input] * 2) if do_classifier_free_guidance else model_input
229
+
230
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=target_embeds).sample
231
+
232
+ if do_classifier_free_guidance:
233
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
234
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
235
+
236
+ base, model_input = self.denoise_step(
237
+ base=base,
238
+ model_input=model_input,
239
+ model_output=noise_pred,
240
+ timestep=t,
241
+ )
242
+
243
+ coupled_latents[k] = model_input
244
+
245
+ coupled_latents = self.denoise_mixing_layer(x=coupled_latents[0], y=coupled_latents[1])
246
+
247
+ # either one is fine
248
+ final_latent = coupled_latents[0]
249
+
250
+ if output_type not in ["latent", "pt", "np", "pil"]:
251
+ deprecation_message = (
252
+ f"the output_type {output_type} is outdated. Please make sure to set it to one of these instead: "
253
+ "`pil`, `np`, `pt`, `latent`"
254
+ )
255
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
256
+ output_type = "np"
257
+
258
+ if output_type == "latent":
259
+ image = final_latent
260
+ else:
261
+ image = self.decode_latents(final_latent)
262
+ image = self.image_processor.postprocess(image, output_type=output_type)
263
+
264
+ return image
v0.32.0/fresco_v2v.py ADDED
The diff for this file is too large to render. See raw diff
 
v0.32.0/gluegen.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import AutoModel, AutoTokenizer, CLIPImageProcessor
7
+
8
+ from diffusers import DiffusionPipeline
9
+ from diffusers.image_processor import VaeImageProcessor
10
+ from diffusers.loaders import StableDiffusionLoraLoaderMixin
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
13
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
14
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
15
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
16
+ from diffusers.schedulers import KarrasDiffusionSchedulers
17
+ from diffusers.utils import (
18
+ USE_PEFT_BACKEND,
19
+ logging,
20
+ scale_lora_layers,
21
+ unscale_lora_layers,
22
+ )
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+
29
+ class TranslatorBase(nn.Module):
30
+ def __init__(self, num_tok, dim, dim_out, mult=2):
31
+ super().__init__()
32
+
33
+ self.dim_in = dim
34
+ self.dim_out = dim_out
35
+
36
+ self.net_tok = nn.Sequential(
37
+ nn.Linear(num_tok, int(num_tok * mult)),
38
+ nn.LayerNorm(int(num_tok * mult)),
39
+ nn.GELU(),
40
+ nn.Linear(int(num_tok * mult), int(num_tok * mult)),
41
+ nn.LayerNorm(int(num_tok * mult)),
42
+ nn.GELU(),
43
+ nn.Linear(int(num_tok * mult), num_tok),
44
+ nn.LayerNorm(num_tok),
45
+ )
46
+
47
+ self.net_sen = nn.Sequential(
48
+ nn.Linear(dim, int(dim * mult)),
49
+ nn.LayerNorm(int(dim * mult)),
50
+ nn.GELU(),
51
+ nn.Linear(int(dim * mult), int(dim * mult)),
52
+ nn.LayerNorm(int(dim * mult)),
53
+ nn.GELU(),
54
+ nn.Linear(int(dim * mult), dim_out),
55
+ nn.LayerNorm(dim_out),
56
+ )
57
+
58
+ def forward(self, x):
59
+ if self.dim_in == self.dim_out:
60
+ indentity_0 = x
61
+ x = self.net_sen(x)
62
+ x += indentity_0
63
+ x = x.transpose(1, 2)
64
+
65
+ indentity_1 = x
66
+ x = self.net_tok(x)
67
+ x += indentity_1
68
+ x = x.transpose(1, 2)
69
+ else:
70
+ x = self.net_sen(x)
71
+ x = x.transpose(1, 2)
72
+
73
+ x = self.net_tok(x)
74
+ x = x.transpose(1, 2)
75
+ return x
76
+
77
+
78
+ class TranslatorBaseNoLN(nn.Module):
79
+ def __init__(self, num_tok, dim, dim_out, mult=2):
80
+ super().__init__()
81
+
82
+ self.dim_in = dim
83
+ self.dim_out = dim_out
84
+
85
+ self.net_tok = nn.Sequential(
86
+ nn.Linear(num_tok, int(num_tok * mult)),
87
+ nn.GELU(),
88
+ nn.Linear(int(num_tok * mult), int(num_tok * mult)),
89
+ nn.GELU(),
90
+ nn.Linear(int(num_tok * mult), num_tok),
91
+ )
92
+
93
+ self.net_sen = nn.Sequential(
94
+ nn.Linear(dim, int(dim * mult)),
95
+ nn.GELU(),
96
+ nn.Linear(int(dim * mult), int(dim * mult)),
97
+ nn.GELU(),
98
+ nn.Linear(int(dim * mult), dim_out),
99
+ )
100
+
101
+ def forward(self, x):
102
+ if self.dim_in == self.dim_out:
103
+ indentity_0 = x
104
+ x = self.net_sen(x)
105
+ x += indentity_0
106
+ x = x.transpose(1, 2)
107
+
108
+ indentity_1 = x
109
+ x = self.net_tok(x)
110
+ x += indentity_1
111
+ x = x.transpose(1, 2)
112
+ else:
113
+ x = self.net_sen(x)
114
+ x = x.transpose(1, 2)
115
+
116
+ x = self.net_tok(x)
117
+ x = x.transpose(1, 2)
118
+ return x
119
+
120
+
121
+ class TranslatorNoLN(nn.Module):
122
+ def __init__(self, num_tok, dim, dim_out, mult=2, depth=5):
123
+ super().__init__()
124
+
125
+ self.blocks = nn.ModuleList([TranslatorBase(num_tok, dim, dim, mult=2) for d in range(depth)])
126
+ self.gelu = nn.GELU()
127
+
128
+ self.tail = TranslatorBaseNoLN(num_tok, dim, dim_out, mult=2)
129
+
130
+ def forward(self, x):
131
+ for block in self.blocks:
132
+ x = block(x) + x
133
+ x = self.gelu(x)
134
+
135
+ x = self.tail(x)
136
+ return x
137
+
138
+
139
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
140
+ """
141
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
142
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
143
+ """
144
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
145
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
146
+ # rescale the results from guidance (fixes overexposure)
147
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
148
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
149
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
150
+ return noise_cfg
151
+
152
+
153
+ def retrieve_timesteps(
154
+ scheduler,
155
+ num_inference_steps: Optional[int] = None,
156
+ device: Optional[Union[str, torch.device]] = None,
157
+ timesteps: Optional[List[int]] = None,
158
+ **kwargs,
159
+ ):
160
+ """
161
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
162
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
163
+
164
+ Args:
165
+ scheduler (`SchedulerMixin`):
166
+ The scheduler to get timesteps from.
167
+ num_inference_steps (`int`):
168
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
169
+ `timesteps` must be `None`.
170
+ device (`str` or `torch.device`, *optional*):
171
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
172
+ timesteps (`List[int]`, *optional*):
173
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
174
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
175
+ must be `None`.
176
+
177
+ Returns:
178
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
179
+ second element is the number of inference steps.
180
+ """
181
+ if timesteps is not None:
182
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
183
+ if not accepts_timesteps:
184
+ raise ValueError(
185
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
186
+ f" timestep schedules. Please check whether you are using the correct scheduler."
187
+ )
188
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
189
+ timesteps = scheduler.timesteps
190
+ num_inference_steps = len(timesteps)
191
+ else:
192
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
193
+ timesteps = scheduler.timesteps
194
+ return timesteps, num_inference_steps
195
+
196
+
197
+ class GlueGenStableDiffusionPipeline(DiffusionPipeline, StableDiffusionMixin, StableDiffusionLoraLoaderMixin):
198
+ def __init__(
199
+ self,
200
+ vae: AutoencoderKL,
201
+ text_encoder: AutoModel,
202
+ tokenizer: AutoTokenizer,
203
+ unet: UNet2DConditionModel,
204
+ scheduler: KarrasDiffusionSchedulers,
205
+ safety_checker: StableDiffusionSafetyChecker,
206
+ feature_extractor: CLIPImageProcessor,
207
+ language_adapter: TranslatorNoLN = None,
208
+ tensor_norm: torch.Tensor = None,
209
+ requires_safety_checker: bool = True,
210
+ ):
211
+ super().__init__()
212
+
213
+ self.register_modules(
214
+ vae=vae,
215
+ text_encoder=text_encoder,
216
+ tokenizer=tokenizer,
217
+ unet=unet,
218
+ scheduler=scheduler,
219
+ safety_checker=safety_checker,
220
+ feature_extractor=feature_extractor,
221
+ language_adapter=language_adapter,
222
+ tensor_norm=tensor_norm,
223
+ )
224
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
225
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
226
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
227
+
228
+ def load_language_adapter(
229
+ self,
230
+ model_path: str,
231
+ num_token: int,
232
+ dim: int,
233
+ dim_out: int,
234
+ tensor_norm: torch.Tensor,
235
+ mult: int = 2,
236
+ depth: int = 5,
237
+ ):
238
+ device = self._execution_device
239
+ self.tensor_norm = tensor_norm.to(device)
240
+ self.language_adapter = TranslatorNoLN(num_tok=num_token, dim=dim, dim_out=dim_out, mult=mult, depth=depth).to(
241
+ device
242
+ )
243
+ self.language_adapter.load_state_dict(torch.load(model_path))
244
+
245
+ def _adapt_language(self, prompt_embeds: torch.Tensor):
246
+ prompt_embeds = prompt_embeds / 3
247
+ prompt_embeds = self.language_adapter(prompt_embeds) * (self.tensor_norm / 2)
248
+ return prompt_embeds
249
+
250
+ def encode_prompt(
251
+ self,
252
+ prompt,
253
+ device,
254
+ num_images_per_prompt,
255
+ do_classifier_free_guidance,
256
+ negative_prompt=None,
257
+ prompt_embeds: Optional[torch.Tensor] = None,
258
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
259
+ lora_scale: Optional[float] = None,
260
+ clip_skip: Optional[int] = None,
261
+ ):
262
+ r"""
263
+ Encodes the prompt into text encoder hidden states.
264
+
265
+ Args:
266
+ prompt (`str` or `List[str]`, *optional*):
267
+ prompt to be encoded
268
+ device: (`torch.device`):
269
+ torch device
270
+ num_images_per_prompt (`int`):
271
+ number of images that should be generated per prompt
272
+ do_classifier_free_guidance (`bool`):
273
+ whether to use classifier free guidance or not
274
+ negative_prompt (`str` or `List[str]`, *optional*):
275
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
276
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
277
+ less than `1`).
278
+ prompt_embeds (`torch.Tensor`, *optional*):
279
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
280
+ provided, text embeddings will be generated from `prompt` input argument.
281
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
282
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
283
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
284
+ argument.
285
+ lora_scale (`float`, *optional*):
286
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
287
+ clip_skip (`int`, *optional*):
288
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
289
+ the output of the pre-final layer will be used for computing the prompt embeddings.
290
+ """
291
+ # set lora scale so that monkey patched LoRA
292
+ # function of text encoder can correctly access it
293
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
294
+ self._lora_scale = lora_scale
295
+
296
+ # dynamically adjust the LoRA scale
297
+ if not USE_PEFT_BACKEND:
298
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
299
+ else:
300
+ scale_lora_layers(self.text_encoder, lora_scale)
301
+
302
+ if prompt is not None and isinstance(prompt, str):
303
+ batch_size = 1
304
+ elif prompt is not None and isinstance(prompt, list):
305
+ batch_size = len(prompt)
306
+ else:
307
+ batch_size = prompt_embeds.shape[0]
308
+
309
+ if prompt_embeds is None:
310
+ text_inputs = self.tokenizer(
311
+ prompt,
312
+ padding="max_length",
313
+ max_length=self.tokenizer.model_max_length,
314
+ truncation=True,
315
+ return_tensors="pt",
316
+ )
317
+ text_input_ids = text_inputs.input_ids
318
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
319
+
320
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
321
+ text_input_ids, untruncated_ids
322
+ ):
323
+ removed_text = self.tokenizer.batch_decode(
324
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
325
+ )
326
+ logger.warning(
327
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
328
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
329
+ )
330
+
331
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
332
+ attention_mask = text_inputs.attention_mask.to(device)
333
+ elif self.language_adapter is not None:
334
+ attention_mask = text_inputs.attention_mask.to(device)
335
+ else:
336
+ attention_mask = None
337
+
338
+ if clip_skip is None:
339
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
340
+ prompt_embeds = prompt_embeds[0]
341
+
342
+ else:
343
+ prompt_embeds = self.text_encoder(
344
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
345
+ )
346
+ # Access the `hidden_states` first, that contains a tuple of
347
+ # all the hidden states from the encoder layers. Then index into
348
+ # the tuple to access the hidden states from the desired layer.
349
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
350
+ # We also need to apply the final LayerNorm here to not mess with the
351
+ # representations. The `last_hidden_states` that we typically use for
352
+ # obtaining the final prompt representations passes through the LayerNorm
353
+ # layer.
354
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
355
+
356
+ # Run prompt language adapter
357
+ if self.language_adapter is not None:
358
+ prompt_embeds = self._adapt_language(prompt_embeds)
359
+
360
+ if self.text_encoder is not None:
361
+ prompt_embeds_dtype = self.text_encoder.dtype
362
+ elif self.unet is not None:
363
+ prompt_embeds_dtype = self.unet.dtype
364
+ else:
365
+ prompt_embeds_dtype = prompt_embeds.dtype
366
+
367
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
368
+
369
+ bs_embed, seq_len, _ = prompt_embeds.shape
370
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
371
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
372
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
373
+
374
+ # get unconditional embeddings for classifier free guidance
375
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
376
+ uncond_tokens: List[str]
377
+ if negative_prompt is None:
378
+ uncond_tokens = [""] * batch_size
379
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
380
+ raise TypeError(
381
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
382
+ f" {type(prompt)}."
383
+ )
384
+ elif isinstance(negative_prompt, str):
385
+ uncond_tokens = [negative_prompt]
386
+ elif batch_size != len(negative_prompt):
387
+ raise ValueError(
388
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
389
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
390
+ " the batch size of `prompt`."
391
+ )
392
+ else:
393
+ uncond_tokens = negative_prompt
394
+
395
+ max_length = prompt_embeds.shape[1]
396
+ uncond_input = self.tokenizer(
397
+ uncond_tokens,
398
+ padding="max_length",
399
+ max_length=max_length,
400
+ truncation=True,
401
+ return_tensors="pt",
402
+ )
403
+
404
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
405
+ attention_mask = uncond_input.attention_mask.to(device)
406
+ else:
407
+ attention_mask = None
408
+
409
+ negative_prompt_embeds = self.text_encoder(
410
+ uncond_input.input_ids.to(device),
411
+ attention_mask=attention_mask,
412
+ )
413
+ negative_prompt_embeds = negative_prompt_embeds[0]
414
+ # Run negative prompt language adapter
415
+ if self.language_adapter is not None:
416
+ negative_prompt_embeds = self._adapt_language(negative_prompt_embeds)
417
+
418
+ if do_classifier_free_guidance:
419
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
420
+ seq_len = negative_prompt_embeds.shape[1]
421
+
422
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
423
+
424
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
425
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
426
+
427
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
428
+ # Retrieve the original scale by scaling back the LoRA layers
429
+ unscale_lora_layers(self.text_encoder, lora_scale)
430
+
431
+ return prompt_embeds, negative_prompt_embeds
432
+
433
+ def run_safety_checker(self, image, device, dtype):
434
+ if self.safety_checker is None:
435
+ has_nsfw_concept = None
436
+ else:
437
+ if torch.is_tensor(image):
438
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
439
+ else:
440
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
441
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
442
+ image, has_nsfw_concept = self.safety_checker(
443
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
444
+ )
445
+ return image, has_nsfw_concept
446
+
447
+ def prepare_extra_step_kwargs(self, generator, eta):
448
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
449
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
450
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
451
+ # and should be between [0, 1]
452
+
453
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
454
+ extra_step_kwargs = {}
455
+ if accepts_eta:
456
+ extra_step_kwargs["eta"] = eta
457
+
458
+ # check if the scheduler accepts generator
459
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
460
+ if accepts_generator:
461
+ extra_step_kwargs["generator"] = generator
462
+ return extra_step_kwargs
463
+
464
+ def check_inputs(
465
+ self,
466
+ prompt,
467
+ height,
468
+ width,
469
+ negative_prompt=None,
470
+ prompt_embeds=None,
471
+ negative_prompt_embeds=None,
472
+ ):
473
+ if height % 8 != 0 or width % 8 != 0:
474
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
475
+
476
+ if prompt is not None and prompt_embeds is not None:
477
+ raise ValueError(
478
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
479
+ " only forward one of the two."
480
+ )
481
+ elif prompt is None and prompt_embeds is None:
482
+ raise ValueError(
483
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
484
+ )
485
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
486
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
487
+
488
+ if negative_prompt is not None and negative_prompt_embeds is not None:
489
+ raise ValueError(
490
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
491
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
492
+ )
493
+
494
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
495
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
496
+ raise ValueError(
497
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
498
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
499
+ f" {negative_prompt_embeds.shape}."
500
+ )
501
+
502
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
503
+ shape = (
504
+ batch_size,
505
+ num_channels_latents,
506
+ int(height) // self.vae_scale_factor,
507
+ int(width) // self.vae_scale_factor,
508
+ )
509
+ if isinstance(generator, list) and len(generator) != batch_size:
510
+ raise ValueError(
511
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
512
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
513
+ )
514
+
515
+ if latents is None:
516
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
517
+ else:
518
+ latents = latents.to(device)
519
+
520
+ # scale the initial noise by the standard deviation required by the scheduler
521
+ latents = latents * self.scheduler.init_noise_sigma
522
+ return latents
523
+
524
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
525
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
526
+ """
527
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
528
+
529
+ Args:
530
+ timesteps (`torch.Tensor`):
531
+ generate embedding vectors at these timesteps
532
+ embedding_dim (`int`, *optional*, defaults to 512):
533
+ dimension of the embeddings to generate
534
+ dtype:
535
+ data type of the generated embeddings
536
+
537
+ Returns:
538
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
539
+ """
540
+ assert len(w.shape) == 1
541
+ w = w * 1000.0
542
+
543
+ half_dim = embedding_dim // 2
544
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
545
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
546
+ emb = w.to(dtype)[:, None] * emb[None, :]
547
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
548
+ if embedding_dim % 2 == 1: # zero pad
549
+ emb = torch.nn.functional.pad(emb, (0, 1))
550
+ assert emb.shape == (w.shape[0], embedding_dim)
551
+ return emb
552
+
553
+ @property
554
+ def guidance_scale(self):
555
+ return self._guidance_scale
556
+
557
+ @property
558
+ def guidance_rescale(self):
559
+ return self._guidance_rescale
560
+
561
+ @property
562
+ def clip_skip(self):
563
+ return self._clip_skip
564
+
565
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
566
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
567
+ # corresponds to doing no classifier free guidance.
568
+ @property
569
+ def do_classifier_free_guidance(self):
570
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
571
+
572
+ @property
573
+ def cross_attention_kwargs(self):
574
+ return self._cross_attention_kwargs
575
+
576
+ @property
577
+ def num_timesteps(self):
578
+ return self._num_timesteps
579
+
580
+ @property
581
+ def interrupt(self):
582
+ return self._interrupt
583
+
584
+ @torch.no_grad()
585
+ def __call__(
586
+ self,
587
+ prompt: Union[str, List[str]] = None,
588
+ height: Optional[int] = None,
589
+ width: Optional[int] = None,
590
+ num_inference_steps: int = 50,
591
+ timesteps: List[int] = None,
592
+ guidance_scale: float = 7.5,
593
+ negative_prompt: Optional[Union[str, List[str]]] = None,
594
+ num_images_per_prompt: Optional[int] = 1,
595
+ eta: float = 0.0,
596
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
597
+ latents: Optional[torch.Tensor] = None,
598
+ prompt_embeds: Optional[torch.Tensor] = None,
599
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
600
+ output_type: Optional[str] = "pil",
601
+ return_dict: bool = True,
602
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
603
+ guidance_rescale: float = 0.0,
604
+ clip_skip: Optional[int] = None,
605
+ **kwargs,
606
+ ):
607
+ r"""
608
+ The call function to the pipeline for generation.
609
+
610
+ Args:
611
+ prompt (`str` or `List[str]`, *optional*):
612
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
613
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
614
+ The height in pixels of the generated image.
615
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
616
+ The width in pixels of the generated image.
617
+ num_inference_steps (`int`, *optional*, defaults to 50):
618
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
619
+ expense of slower inference.
620
+ timesteps (`List[int]`, *optional*):
621
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
622
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
623
+ passed will be used. Must be in descending order.
624
+ guidance_scale (`float`, *optional*, defaults to 7.5):
625
+ A higher guidance scale value encourages the model to generate images closely linked to the text
626
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
627
+ negative_prompt (`str` or `List[str]`, *optional*):
628
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
629
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
630
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
631
+ The number of images to generate per prompt.
632
+ eta (`float`, *optional*, defaults to 0.0):
633
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
634
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
635
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
636
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
637
+ generation deterministic.
638
+ latents (`torch.Tensor`, *optional*):
639
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
640
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
641
+ tensor is generated by sampling using the supplied random `generator`.
642
+ prompt_embeds (`torch.Tensor`, *optional*):
643
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
644
+ provided, text embeddings are generated from the `prompt` input argument.
645
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
646
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
647
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
648
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
649
+ output_type (`str`, *optional*, defaults to `"pil"`):
650
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
651
+ return_dict (`bool`, *optional*, defaults to `True`):
652
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
653
+ plain tuple.
654
+ cross_attention_kwargs (`dict`, *optional*):
655
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
656
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
657
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
658
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
659
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
660
+ using zero terminal SNR.
661
+ clip_skip (`int`, *optional*):
662
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
663
+ the output of the pre-final layer will be used for computing the prompt embeddings.
664
+
665
+ Examples:
666
+
667
+ Returns:
668
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
669
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
670
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
671
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
672
+ "not-safe-for-work" (nsfw) content.
673
+ """
674
+
675
+ # 0. Default height and width to unet
676
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
677
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
678
+ # to deal with lora scaling and other possible forward hooks
679
+
680
+ # 1. Check inputs. Raise error if not correct
681
+ self.check_inputs(
682
+ prompt,
683
+ height,
684
+ width,
685
+ negative_prompt,
686
+ prompt_embeds,
687
+ negative_prompt_embeds,
688
+ )
689
+
690
+ self._guidance_scale = guidance_scale
691
+ self._guidance_rescale = guidance_rescale
692
+ self._clip_skip = clip_skip
693
+ self._cross_attention_kwargs = cross_attention_kwargs
694
+ self._interrupt = False
695
+
696
+ # 2. Define call parameters
697
+ if prompt is not None and isinstance(prompt, str):
698
+ batch_size = 1
699
+ elif prompt is not None and isinstance(prompt, list):
700
+ batch_size = len(prompt)
701
+ else:
702
+ batch_size = prompt_embeds.shape[0]
703
+
704
+ device = self._execution_device
705
+
706
+ # 3. Encode input prompt
707
+ lora_scale = (
708
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
709
+ )
710
+
711
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
712
+ prompt,
713
+ device,
714
+ num_images_per_prompt,
715
+ self.do_classifier_free_guidance,
716
+ negative_prompt,
717
+ prompt_embeds=prompt_embeds,
718
+ negative_prompt_embeds=negative_prompt_embeds,
719
+ lora_scale=lora_scale,
720
+ clip_skip=self.clip_skip,
721
+ )
722
+
723
+ # For classifier free guidance, we need to do two forward passes.
724
+ # Here we concatenate the unconditional and text embeddings into a single batch
725
+ # to avoid doing two forward passes
726
+ if self.do_classifier_free_guidance:
727
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
728
+
729
+ # 4. Prepare timesteps
730
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
731
+
732
+ # 5. Prepare latent variables
733
+ num_channels_latents = self.unet.config.in_channels
734
+ latents = self.prepare_latents(
735
+ batch_size * num_images_per_prompt,
736
+ num_channels_latents,
737
+ height,
738
+ width,
739
+ prompt_embeds.dtype,
740
+ device,
741
+ generator,
742
+ latents,
743
+ )
744
+
745
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
746
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
747
+
748
+ # 6.2 Optionally get Guidance Scale Embedding
749
+ timestep_cond = None
750
+ if self.unet.config.time_cond_proj_dim is not None:
751
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
752
+ timestep_cond = self.get_guidance_scale_embedding(
753
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
754
+ ).to(device=device, dtype=latents.dtype)
755
+
756
+ # 7. Denoising loop
757
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
758
+ self._num_timesteps = len(timesteps)
759
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
760
+ for i, t in enumerate(timesteps):
761
+ if self.interrupt:
762
+ continue
763
+
764
+ # expand the latents if we are doing classifier free guidance
765
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
766
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
767
+
768
+ # predict the noise residual
769
+ noise_pred = self.unet(
770
+ latent_model_input,
771
+ t,
772
+ encoder_hidden_states=prompt_embeds,
773
+ timestep_cond=timestep_cond,
774
+ cross_attention_kwargs=self.cross_attention_kwargs,
775
+ return_dict=False,
776
+ )[0]
777
+
778
+ # perform guidance
779
+ if self.do_classifier_free_guidance:
780
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
781
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
782
+
783
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
784
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
785
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
786
+
787
+ # compute the previous noisy sample x_t -> x_t-1
788
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
789
+
790
+ # call the callback, if provided
791
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
792
+ progress_bar.update()
793
+
794
+ if not output_type == "latent":
795
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
796
+ 0
797
+ ]
798
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
799
+ else:
800
+ image = latents
801
+ has_nsfw_concept = None
802
+
803
+ if has_nsfw_concept is None:
804
+ do_denormalize = [True] * image.shape[0]
805
+ else:
806
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
807
+
808
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
809
+
810
+ # Offload all models
811
+ self.maybe_free_model_hooks()
812
+
813
+ if not return_dict:
814
+ return (image, has_nsfw_concept)
815
+
816
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/hd_painter.py ADDED
@@ -0,0 +1,1001 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ from typing import Any, Callable, Dict, List, Optional, Union
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ from diffusers.image_processor import PipelineImageInput
10
+ from diffusers.models import AsymmetricAutoencoderKL, ImageProjection
11
+ from diffusers.models.attention_processor import Attention, AttnProcessor
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint import (
14
+ StableDiffusionInpaintPipeline,
15
+ retrieve_timesteps,
16
+ )
17
+ from diffusers.utils import deprecate
18
+
19
+
20
+ class RASGAttnProcessor:
21
+ def __init__(self, mask, token_idx, scale_factor):
22
+ self.attention_scores = None # Stores the last output of the similarity matrix here. Each layer will get its own RASGAttnProcessor assigned
23
+ self.mask = mask
24
+ self.token_idx = token_idx
25
+ self.scale_factor = scale_factor
26
+ self.mask_resoltuion = mask.shape[-1] * mask.shape[-2] # 64 x 64 if the image is 512x512
27
+
28
+ def __call__(
29
+ self,
30
+ attn: Attention,
31
+ hidden_states: torch.Tensor,
32
+ encoder_hidden_states: Optional[torch.Tensor] = None,
33
+ attention_mask: Optional[torch.Tensor] = None,
34
+ temb: Optional[torch.Tensor] = None,
35
+ scale: float = 1.0,
36
+ ) -> torch.Tensor:
37
+ # Same as the default AttnProcessor up untill the part where similarity matrix gets saved
38
+ downscale_factor = self.mask_resoltuion // hidden_states.shape[1]
39
+ residual = hidden_states
40
+
41
+ if attn.spatial_norm is not None:
42
+ hidden_states = attn.spatial_norm(hidden_states, temb)
43
+
44
+ input_ndim = hidden_states.ndim
45
+
46
+ if input_ndim == 4:
47
+ batch_size, channel, height, width = hidden_states.shape
48
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
49
+
50
+ batch_size, sequence_length, _ = (
51
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
52
+ )
53
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
54
+
55
+ if attn.group_norm is not None:
56
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
57
+
58
+ query = attn.to_q(hidden_states)
59
+
60
+ if encoder_hidden_states is None:
61
+ encoder_hidden_states = hidden_states
62
+ elif attn.norm_cross:
63
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
64
+
65
+ key = attn.to_k(encoder_hidden_states)
66
+ value = attn.to_v(encoder_hidden_states)
67
+
68
+ query = attn.head_to_batch_dim(query)
69
+ key = attn.head_to_batch_dim(key)
70
+ value = attn.head_to_batch_dim(value)
71
+
72
+ # Automatically recognize the resolution and save the attention similarity values
73
+ # We need to use the values before the softmax function, hence the rewritten get_attention_scores function.
74
+ if downscale_factor == self.scale_factor**2:
75
+ self.attention_scores = get_attention_scores(attn, query, key, attention_mask)
76
+ attention_probs = self.attention_scores.softmax(dim=-1)
77
+ attention_probs = attention_probs.to(query.dtype)
78
+ else:
79
+ attention_probs = attn.get_attention_scores(query, key, attention_mask) # Original code
80
+
81
+ hidden_states = torch.bmm(attention_probs, value)
82
+ hidden_states = attn.batch_to_head_dim(hidden_states)
83
+
84
+ # linear proj
85
+ hidden_states = attn.to_out[0](hidden_states)
86
+ # dropout
87
+ hidden_states = attn.to_out[1](hidden_states)
88
+
89
+ if input_ndim == 4:
90
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
91
+
92
+ if attn.residual_connection:
93
+ hidden_states = hidden_states + residual
94
+
95
+ hidden_states = hidden_states / attn.rescale_output_factor
96
+
97
+ return hidden_states
98
+
99
+
100
+ class PAIntAAttnProcessor:
101
+ def __init__(self, transformer_block, mask, token_idx, do_classifier_free_guidance, scale_factors):
102
+ self.transformer_block = transformer_block # Stores the parent transformer block.
103
+ self.mask = mask
104
+ self.scale_factors = scale_factors
105
+ self.do_classifier_free_guidance = do_classifier_free_guidance
106
+ self.token_idx = token_idx
107
+ self.shape = mask.shape[2:]
108
+ self.mask_resoltuion = mask.shape[-1] * mask.shape[-2] # 64 x 64
109
+ self.default_processor = AttnProcessor()
110
+
111
+ def __call__(
112
+ self,
113
+ attn: Attention,
114
+ hidden_states: torch.Tensor,
115
+ encoder_hidden_states: Optional[torch.Tensor] = None,
116
+ attention_mask: Optional[torch.Tensor] = None,
117
+ temb: Optional[torch.Tensor] = None,
118
+ scale: float = 1.0,
119
+ ) -> torch.Tensor:
120
+ # Automatically recognize the resolution of the current attention layer and resize the masks accordingly
121
+ downscale_factor = self.mask_resoltuion // hidden_states.shape[1]
122
+
123
+ mask = None
124
+ for factor in self.scale_factors:
125
+ if downscale_factor == factor**2:
126
+ shape = (self.shape[0] // factor, self.shape[1] // factor)
127
+ mask = F.interpolate(self.mask, shape, mode="bicubic") # B, 1, H, W
128
+ break
129
+ if mask is None:
130
+ return self.default_processor(attn, hidden_states, encoder_hidden_states, attention_mask, temb, scale)
131
+
132
+ # STARTS HERE
133
+ residual = hidden_states
134
+ # Save the input hidden_states for later use
135
+ input_hidden_states = hidden_states
136
+
137
+ # ================================================== #
138
+ # =============== SELF ATTENTION 1 ================= #
139
+ # ================================================== #
140
+
141
+ if attn.spatial_norm is not None:
142
+ hidden_states = attn.spatial_norm(hidden_states, temb)
143
+
144
+ input_ndim = hidden_states.ndim
145
+
146
+ if input_ndim == 4:
147
+ batch_size, channel, height, width = hidden_states.shape
148
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
149
+
150
+ batch_size, sequence_length, _ = (
151
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
152
+ )
153
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
154
+
155
+ if attn.group_norm is not None:
156
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
157
+
158
+ query = attn.to_q(hidden_states)
159
+
160
+ if encoder_hidden_states is None:
161
+ encoder_hidden_states = hidden_states
162
+ elif attn.norm_cross:
163
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
164
+
165
+ key = attn.to_k(encoder_hidden_states)
166
+ value = attn.to_v(encoder_hidden_states)
167
+
168
+ query = attn.head_to_batch_dim(query)
169
+ key = attn.head_to_batch_dim(key)
170
+ value = attn.head_to_batch_dim(value)
171
+
172
+ # self_attention_probs = attn.get_attention_scores(query, key, attention_mask) # We can't use post-softmax attention scores in this case
173
+ self_attention_scores = get_attention_scores(
174
+ attn, query, key, attention_mask
175
+ ) # The custom function returns pre-softmax probabilities
176
+ self_attention_probs = self_attention_scores.softmax(
177
+ dim=-1
178
+ ) # Manually compute the probabilities here, the scores will be reused in the second part of PAIntA
179
+ self_attention_probs = self_attention_probs.to(query.dtype)
180
+
181
+ hidden_states = torch.bmm(self_attention_probs, value)
182
+ hidden_states = attn.batch_to_head_dim(hidden_states)
183
+
184
+ # linear proj
185
+ hidden_states = attn.to_out[0](hidden_states)
186
+ # dropout
187
+ hidden_states = attn.to_out[1](hidden_states)
188
+
189
+ # x = x + self.attn1(self.norm1(x))
190
+
191
+ if input_ndim == 4:
192
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
193
+
194
+ if attn.residual_connection: # So many residuals everywhere
195
+ hidden_states = hidden_states + residual
196
+
197
+ self_attention_output_hidden_states = hidden_states / attn.rescale_output_factor
198
+
199
+ # ================================================== #
200
+ # ============ BasicTransformerBlock =============== #
201
+ # ================================================== #
202
+ # We use a hack by running the code from the BasicTransformerBlock that is between Self and Cross attentions here
203
+ # The other option would've been modifying the BasicTransformerBlock and adding this functionality here.
204
+ # I assumed that changing the BasicTransformerBlock would have been a bigger deal and decided to use this hack isntead.
205
+
206
+ # The SelfAttention block recieves the normalized latents from the BasicTransformerBlock,
207
+ # But the residual of the output is the non-normalized version.
208
+ # Therefore we unnormalize the input hidden state here
209
+ unnormalized_input_hidden_states = (
210
+ input_hidden_states + self.transformer_block.norm1.bias
211
+ ) * self.transformer_block.norm1.weight
212
+
213
+ # TODO: return if neccessary
214
+ # if self.use_ada_layer_norm_zero:
215
+ # attn_output = gate_msa.unsqueeze(1) * attn_output
216
+ # elif self.use_ada_layer_norm_single:
217
+ # attn_output = gate_msa * attn_output
218
+
219
+ transformer_hidden_states = self_attention_output_hidden_states + unnormalized_input_hidden_states
220
+ if transformer_hidden_states.ndim == 4:
221
+ transformer_hidden_states = transformer_hidden_states.squeeze(1)
222
+
223
+ # TODO: return if neccessary
224
+ # 2.5 GLIGEN Control
225
+ # if gligen_kwargs is not None:
226
+ # transformer_hidden_states = self.fuser(transformer_hidden_states, gligen_kwargs["objs"])
227
+ # NOTE: we experimented with using GLIGEN and HDPainter together, the results were not that great
228
+
229
+ # 3. Cross-Attention
230
+ if self.transformer_block.use_ada_layer_norm:
231
+ # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, timestep)
232
+ raise NotImplementedError()
233
+ elif self.transformer_block.use_ada_layer_norm_zero or self.transformer_block.use_layer_norm:
234
+ transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states)
235
+ elif self.transformer_block.use_ada_layer_norm_single:
236
+ # For PixArt norm2 isn't applied here:
237
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
238
+ transformer_norm_hidden_states = transformer_hidden_states
239
+ elif self.transformer_block.use_ada_layer_norm_continuous:
240
+ # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, added_cond_kwargs["pooled_text_emb"])
241
+ raise NotImplementedError()
242
+ else:
243
+ raise ValueError("Incorrect norm")
244
+
245
+ if self.transformer_block.pos_embed is not None and self.transformer_block.use_ada_layer_norm_single is False:
246
+ transformer_norm_hidden_states = self.transformer_block.pos_embed(transformer_norm_hidden_states)
247
+
248
+ # ================================================== #
249
+ # ================= CROSS ATTENTION ================ #
250
+ # ================================================== #
251
+
252
+ # We do an initial pass of the CrossAttention up to obtaining the similarity matrix here.
253
+ # The similarity matrix is used to obtain scaling coefficients for the attention matrix of the self attention
254
+ # We reuse the previously computed self-attention matrix, and only repeat the steps after the softmax
255
+
256
+ cross_attention_input_hidden_states = (
257
+ transformer_norm_hidden_states # Renaming the variable for the sake of readability
258
+ )
259
+
260
+ # TODO: check if classifier_free_guidance is being used before splitting here
261
+ if self.do_classifier_free_guidance:
262
+ # Our scaling coefficients depend only on the conditional part, so we split the inputs
263
+ (
264
+ _cross_attention_input_hidden_states_unconditional,
265
+ cross_attention_input_hidden_states_conditional,
266
+ ) = cross_attention_input_hidden_states.chunk(2)
267
+
268
+ # Same split for the encoder_hidden_states i.e. the tokens
269
+ # Since the SelfAttention processors don't get the encoder states as input, we inject them into the processor in the begining.
270
+ _encoder_hidden_states_unconditional, encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(
271
+ 2
272
+ )
273
+ else:
274
+ cross_attention_input_hidden_states_conditional = cross_attention_input_hidden_states
275
+ encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(2)
276
+
277
+ # Rename the variables for the sake of readability
278
+ # The part below is the beginning of the __call__ function of the following CrossAttention layer
279
+ cross_attention_hidden_states = cross_attention_input_hidden_states_conditional
280
+ cross_attention_encoder_hidden_states = encoder_hidden_states_conditional
281
+
282
+ attn2 = self.transformer_block.attn2
283
+
284
+ if attn2.spatial_norm is not None:
285
+ cross_attention_hidden_states = attn2.spatial_norm(cross_attention_hidden_states, temb)
286
+
287
+ input_ndim = cross_attention_hidden_states.ndim
288
+
289
+ if input_ndim == 4:
290
+ batch_size, channel, height, width = cross_attention_hidden_states.shape
291
+ cross_attention_hidden_states = cross_attention_hidden_states.view(
292
+ batch_size, channel, height * width
293
+ ).transpose(1, 2)
294
+
295
+ (
296
+ batch_size,
297
+ sequence_length,
298
+ _,
299
+ ) = cross_attention_hidden_states.shape # It is definitely a cross attention, so no need for an if block
300
+ # TODO: change the attention_mask here
301
+ attention_mask = attn2.prepare_attention_mask(
302
+ None, sequence_length, batch_size
303
+ ) # I assume the attention mask is the same...
304
+
305
+ if attn2.group_norm is not None:
306
+ cross_attention_hidden_states = attn2.group_norm(cross_attention_hidden_states.transpose(1, 2)).transpose(
307
+ 1, 2
308
+ )
309
+
310
+ query2 = attn2.to_q(cross_attention_hidden_states)
311
+
312
+ if attn2.norm_cross:
313
+ cross_attention_encoder_hidden_states = attn2.norm_encoder_hidden_states(
314
+ cross_attention_encoder_hidden_states
315
+ )
316
+
317
+ key2 = attn2.to_k(cross_attention_encoder_hidden_states)
318
+ query2 = attn2.head_to_batch_dim(query2)
319
+ key2 = attn2.head_to_batch_dim(key2)
320
+
321
+ cross_attention_probs = attn2.get_attention_scores(query2, key2, attention_mask)
322
+
323
+ # CrossAttention ends here, the remaining part is not used
324
+
325
+ # ================================================== #
326
+ # ================ SELF ATTENTION 2 ================ #
327
+ # ================================================== #
328
+ # DEJA VU!
329
+
330
+ mask = (mask > 0.5).to(self_attention_output_hidden_states.dtype)
331
+ m = mask.to(self_attention_output_hidden_states.device)
332
+ # m = rearrange(m, 'b c h w -> b (h w) c').contiguous()
333
+ m = m.permute(0, 2, 3, 1).reshape((m.shape[0], -1, m.shape[1])).contiguous() # B HW 1
334
+ m = torch.matmul(m, m.permute(0, 2, 1)) + (1 - m)
335
+
336
+ # # Compute scaling coefficients for the similarity matrix
337
+ # # Select the cross attention values for the correct tokens only!
338
+ # cross_attention_probs = cross_attention_probs.mean(dim = 0)
339
+ # cross_attention_probs = cross_attention_probs[:, self.token_idx].sum(dim=1)
340
+
341
+ # cross_attention_probs = cross_attention_probs.reshape(shape)
342
+ # gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(self_attention_output_hidden_states.device)
343
+ # cross_attention_probs = gaussian_smoothing(cross_attention_probs.unsqueeze(0))[0] # optional smoothing
344
+ # cross_attention_probs = cross_attention_probs.reshape(-1)
345
+ # cross_attention_probs = ((cross_attention_probs - torch.median(cross_attention_probs.ravel())) / torch.max(cross_attention_probs.ravel())).clip(0, 1)
346
+
347
+ # c = (1 - m) * cross_attention_probs.reshape(1, 1, -1) + m # PAIntA scaling coefficients
348
+
349
+ # Compute scaling coefficients for the similarity matrix
350
+ # Select the cross attention values for the correct tokens only!
351
+
352
+ batch_size, dims, channels = cross_attention_probs.shape
353
+ batch_size = batch_size // attn.heads
354
+ cross_attention_probs = cross_attention_probs.reshape((batch_size, attn.heads, dims, channels)) # B, D, HW, T
355
+
356
+ cross_attention_probs = cross_attention_probs.mean(dim=1) # B, HW, T
357
+ cross_attention_probs = cross_attention_probs[..., self.token_idx].sum(dim=-1) # B, HW
358
+ cross_attention_probs = cross_attention_probs.reshape((batch_size,) + shape) # , B, H, W
359
+
360
+ gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(
361
+ self_attention_output_hidden_states.device
362
+ )
363
+ cross_attention_probs = gaussian_smoothing(cross_attention_probs[:, None])[:, 0] # optional smoothing B, H, W
364
+
365
+ # Median normalization
366
+ cross_attention_probs = cross_attention_probs.reshape(batch_size, -1) # B, HW
367
+ cross_attention_probs = (
368
+ cross_attention_probs - cross_attention_probs.median(dim=-1, keepdim=True).values
369
+ ) / cross_attention_probs.max(dim=-1, keepdim=True).values
370
+ cross_attention_probs = cross_attention_probs.clip(0, 1)
371
+
372
+ c = (1 - m) * cross_attention_probs.reshape(batch_size, 1, -1) + m
373
+ c = c.repeat_interleave(attn.heads, 0) # BD, HW
374
+ if self.do_classifier_free_guidance:
375
+ c = torch.cat([c, c]) # 2BD, HW
376
+
377
+ # Rescaling the original self-attention matrix
378
+ self_attention_scores_rescaled = self_attention_scores * c
379
+ self_attention_probs_rescaled = self_attention_scores_rescaled.softmax(dim=-1)
380
+
381
+ # Continuing the self attention normally using the new matrix
382
+ hidden_states = torch.bmm(self_attention_probs_rescaled, value)
383
+ hidden_states = attn.batch_to_head_dim(hidden_states)
384
+
385
+ # linear proj
386
+ hidden_states = attn.to_out[0](hidden_states)
387
+ # dropout
388
+ hidden_states = attn.to_out[1](hidden_states)
389
+
390
+ if input_ndim == 4:
391
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
392
+
393
+ if attn.residual_connection:
394
+ hidden_states = hidden_states + input_hidden_states
395
+
396
+ hidden_states = hidden_states / attn.rescale_output_factor
397
+
398
+ return hidden_states
399
+
400
+
401
+ class StableDiffusionHDPainterPipeline(StableDiffusionInpaintPipeline):
402
+ def get_tokenized_prompt(self, prompt):
403
+ out = self.tokenizer(prompt)
404
+ return [self.tokenizer.decode(x) for x in out["input_ids"]]
405
+
406
+ def init_attn_processors(
407
+ self,
408
+ mask,
409
+ token_idx,
410
+ use_painta=True,
411
+ use_rasg=True,
412
+ painta_scale_factors=[2, 4], # 64x64 -> [16x16, 32x32]
413
+ rasg_scale_factor=4, # 64x64 -> 16x16
414
+ self_attention_layer_name="attn1",
415
+ cross_attention_layer_name="attn2",
416
+ list_of_painta_layer_names=None,
417
+ list_of_rasg_layer_names=None,
418
+ ):
419
+ default_processor = AttnProcessor()
420
+ width, height = mask.shape[-2:]
421
+ width, height = width // self.vae_scale_factor, height // self.vae_scale_factor
422
+
423
+ painta_scale_factors = [x * self.vae_scale_factor for x in painta_scale_factors]
424
+ rasg_scale_factor = self.vae_scale_factor * rasg_scale_factor
425
+
426
+ attn_processors = {}
427
+ for x in self.unet.attn_processors:
428
+ if (list_of_painta_layer_names is None and self_attention_layer_name in x) or (
429
+ list_of_painta_layer_names is not None and x in list_of_painta_layer_names
430
+ ):
431
+ if use_painta:
432
+ transformer_block = self.unet.get_submodule(x.replace(".attn1.processor", ""))
433
+ attn_processors[x] = PAIntAAttnProcessor(
434
+ transformer_block, mask, token_idx, self.do_classifier_free_guidance, painta_scale_factors
435
+ )
436
+ else:
437
+ attn_processors[x] = default_processor
438
+ elif (list_of_rasg_layer_names is None and cross_attention_layer_name in x) or (
439
+ list_of_rasg_layer_names is not None and x in list_of_rasg_layer_names
440
+ ):
441
+ if use_rasg:
442
+ attn_processors[x] = RASGAttnProcessor(mask, token_idx, rasg_scale_factor)
443
+ else:
444
+ attn_processors[x] = default_processor
445
+
446
+ self.unet.set_attn_processor(attn_processors)
447
+ # import json
448
+ # with open('/home/hayk.manukyan/repos/diffusers/debug.txt', 'a') as f:
449
+ # json.dump({x:str(y) for x,y in self.unet.attn_processors.items()}, f, indent=4)
450
+
451
+ @torch.no_grad()
452
+ def __call__(
453
+ self,
454
+ prompt: Union[str, List[str]] = None,
455
+ image: PipelineImageInput = None,
456
+ mask_image: PipelineImageInput = None,
457
+ masked_image_latents: torch.Tensor = None,
458
+ height: Optional[int] = None,
459
+ width: Optional[int] = None,
460
+ padding_mask_crop: Optional[int] = None,
461
+ strength: float = 1.0,
462
+ num_inference_steps: int = 50,
463
+ timesteps: List[int] = None,
464
+ guidance_scale: float = 7.5,
465
+ positive_prompt: Optional[str] = "",
466
+ negative_prompt: Optional[Union[str, List[str]]] = None,
467
+ num_images_per_prompt: Optional[int] = 1,
468
+ eta: float = 0.01,
469
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
470
+ latents: Optional[torch.Tensor] = None,
471
+ prompt_embeds: Optional[torch.Tensor] = None,
472
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
473
+ ip_adapter_image: Optional[PipelineImageInput] = None,
474
+ output_type: Optional[str] = "pil",
475
+ return_dict: bool = True,
476
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
477
+ clip_skip: int = None,
478
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
479
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
480
+ use_painta=True,
481
+ use_rasg=True,
482
+ self_attention_layer_name=".attn1",
483
+ cross_attention_layer_name=".attn2",
484
+ painta_scale_factors=[2, 4], # 16 x 16 and 32 x 32
485
+ rasg_scale_factor=4, # 16x16 by default
486
+ list_of_painta_layer_names=None,
487
+ list_of_rasg_layer_names=None,
488
+ **kwargs,
489
+ ):
490
+ callback = kwargs.pop("callback", None)
491
+ callback_steps = kwargs.pop("callback_steps", None)
492
+
493
+ if callback is not None:
494
+ deprecate(
495
+ "callback",
496
+ "1.0.0",
497
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
498
+ )
499
+ if callback_steps is not None:
500
+ deprecate(
501
+ "callback_steps",
502
+ "1.0.0",
503
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
504
+ )
505
+
506
+ # 0. Default height and width to unet
507
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
508
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
509
+
510
+ #
511
+ prompt_no_positives = prompt
512
+ if isinstance(prompt, list):
513
+ prompt = [x + positive_prompt for x in prompt]
514
+ else:
515
+ prompt = prompt + positive_prompt
516
+
517
+ # 1. Check inputs
518
+ self.check_inputs(
519
+ prompt,
520
+ image,
521
+ mask_image,
522
+ height,
523
+ width,
524
+ strength,
525
+ callback_steps,
526
+ negative_prompt,
527
+ prompt_embeds,
528
+ negative_prompt_embeds,
529
+ callback_on_step_end_tensor_inputs,
530
+ padding_mask_crop,
531
+ )
532
+
533
+ self._guidance_scale = guidance_scale
534
+ self._clip_skip = clip_skip
535
+ self._cross_attention_kwargs = cross_attention_kwargs
536
+ self._interrupt = False
537
+
538
+ # 2. Define call parameters
539
+ if prompt is not None and isinstance(prompt, str):
540
+ batch_size = 1
541
+ elif prompt is not None and isinstance(prompt, list):
542
+ batch_size = len(prompt)
543
+ else:
544
+ batch_size = prompt_embeds.shape[0]
545
+
546
+ # assert batch_size == 1, "Does not work with batch size > 1 currently"
547
+
548
+ device = self._execution_device
549
+
550
+ # 3. Encode input prompt
551
+ text_encoder_lora_scale = (
552
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
553
+ )
554
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
555
+ prompt,
556
+ device,
557
+ num_images_per_prompt,
558
+ self.do_classifier_free_guidance,
559
+ negative_prompt,
560
+ prompt_embeds=prompt_embeds,
561
+ negative_prompt_embeds=negative_prompt_embeds,
562
+ lora_scale=text_encoder_lora_scale,
563
+ clip_skip=self.clip_skip,
564
+ )
565
+ # For classifier free guidance, we need to do two forward passes.
566
+ # Here we concatenate the unconditional and text embeddings into a single batch
567
+ # to avoid doing two forward passes
568
+ if self.do_classifier_free_guidance:
569
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
570
+
571
+ if ip_adapter_image is not None:
572
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
573
+ image_embeds, negative_image_embeds = self.encode_image(
574
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
575
+ )
576
+ if self.do_classifier_free_guidance:
577
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
578
+
579
+ # 4. set timesteps
580
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
581
+ timesteps, num_inference_steps = self.get_timesteps(
582
+ num_inference_steps=num_inference_steps, strength=strength, device=device
583
+ )
584
+ # check that number of inference steps is not < 1 - as this doesn't make sense
585
+ if num_inference_steps < 1:
586
+ raise ValueError(
587
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
588
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
589
+ )
590
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
591
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
592
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
593
+ is_strength_max = strength == 1.0
594
+
595
+ # 5. Preprocess mask and image
596
+
597
+ if padding_mask_crop is not None:
598
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
599
+ resize_mode = "fill"
600
+ else:
601
+ crops_coords = None
602
+ resize_mode = "default"
603
+
604
+ original_image = image
605
+ init_image = self.image_processor.preprocess(
606
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
607
+ )
608
+ init_image = init_image.to(dtype=torch.float32)
609
+
610
+ # 6. Prepare latent variables
611
+ num_channels_latents = self.vae.config.latent_channels
612
+ num_channels_unet = self.unet.config.in_channels
613
+ return_image_latents = num_channels_unet == 4
614
+
615
+ latents_outputs = self.prepare_latents(
616
+ batch_size * num_images_per_prompt,
617
+ num_channels_latents,
618
+ height,
619
+ width,
620
+ prompt_embeds.dtype,
621
+ device,
622
+ generator,
623
+ latents,
624
+ image=init_image,
625
+ timestep=latent_timestep,
626
+ is_strength_max=is_strength_max,
627
+ return_noise=True,
628
+ return_image_latents=return_image_latents,
629
+ )
630
+
631
+ if return_image_latents:
632
+ latents, noise, image_latents = latents_outputs
633
+ else:
634
+ latents, noise = latents_outputs
635
+
636
+ # 7. Prepare mask latent variables
637
+ mask_condition = self.mask_processor.preprocess(
638
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
639
+ )
640
+
641
+ if masked_image_latents is None:
642
+ masked_image = init_image * (mask_condition < 0.5)
643
+ else:
644
+ masked_image = masked_image_latents
645
+
646
+ mask, masked_image_latents = self.prepare_mask_latents(
647
+ mask_condition,
648
+ masked_image,
649
+ batch_size * num_images_per_prompt,
650
+ height,
651
+ width,
652
+ prompt_embeds.dtype,
653
+ device,
654
+ generator,
655
+ self.do_classifier_free_guidance,
656
+ )
657
+
658
+ # 7.5 Setting up HD-Painter
659
+
660
+ # Get the indices of the tokens to be modified by both RASG and PAIntA
661
+ token_idx = list(range(1, self.get_tokenized_prompt(prompt_no_positives).index("<|endoftext|>"))) + [
662
+ self.get_tokenized_prompt(prompt).index("<|endoftext|>")
663
+ ]
664
+
665
+ # Setting up the attention processors
666
+ self.init_attn_processors(
667
+ mask_condition,
668
+ token_idx,
669
+ use_painta,
670
+ use_rasg,
671
+ painta_scale_factors=painta_scale_factors,
672
+ rasg_scale_factor=rasg_scale_factor,
673
+ self_attention_layer_name=self_attention_layer_name,
674
+ cross_attention_layer_name=cross_attention_layer_name,
675
+ list_of_painta_layer_names=list_of_painta_layer_names,
676
+ list_of_rasg_layer_names=list_of_rasg_layer_names,
677
+ )
678
+
679
+ # 8. Check that sizes of mask, masked image and latents match
680
+ if num_channels_unet == 9:
681
+ # default case for runwayml/stable-diffusion-inpainting
682
+ num_channels_mask = mask.shape[1]
683
+ num_channels_masked_image = masked_image_latents.shape[1]
684
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
685
+ raise ValueError(
686
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
687
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
688
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
689
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
690
+ " `pipeline.unet` or your `mask_image` or `image` input."
691
+ )
692
+ elif num_channels_unet != 4:
693
+ raise ValueError(
694
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
695
+ )
696
+
697
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
698
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
699
+
700
+ if use_rasg:
701
+ extra_step_kwargs["generator"] = None
702
+
703
+ # 9.1 Add image embeds for IP-Adapter
704
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
705
+
706
+ # 9.2 Optionally get Guidance Scale Embedding
707
+ timestep_cond = None
708
+ if self.unet.config.time_cond_proj_dim is not None:
709
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
710
+ timestep_cond = self.get_guidance_scale_embedding(
711
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
712
+ ).to(device=device, dtype=latents.dtype)
713
+
714
+ # 10. Denoising loop
715
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
716
+ self._num_timesteps = len(timesteps)
717
+ painta_active = True
718
+
719
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
720
+ for i, t in enumerate(timesteps):
721
+ if self.interrupt:
722
+ continue
723
+
724
+ if t < 500 and painta_active:
725
+ self.init_attn_processors(
726
+ mask_condition,
727
+ token_idx,
728
+ False,
729
+ use_rasg,
730
+ painta_scale_factors=painta_scale_factors,
731
+ rasg_scale_factor=rasg_scale_factor,
732
+ self_attention_layer_name=self_attention_layer_name,
733
+ cross_attention_layer_name=cross_attention_layer_name,
734
+ list_of_painta_layer_names=list_of_painta_layer_names,
735
+ list_of_rasg_layer_names=list_of_rasg_layer_names,
736
+ )
737
+ painta_active = False
738
+
739
+ with torch.enable_grad():
740
+ self.unet.zero_grad()
741
+ latents = latents.detach()
742
+ latents.requires_grad = True
743
+
744
+ # expand the latents if we are doing classifier free guidance
745
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
746
+
747
+ # concat latents, mask, masked_image_latents in the channel dimension
748
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
749
+
750
+ if num_channels_unet == 9:
751
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
752
+
753
+ self.scheduler.latents = latents
754
+ self.encoder_hidden_states = prompt_embeds
755
+ for attn_processor in self.unet.attn_processors.values():
756
+ attn_processor.encoder_hidden_states = prompt_embeds
757
+
758
+ # predict the noise residual
759
+ noise_pred = self.unet(
760
+ latent_model_input,
761
+ t,
762
+ encoder_hidden_states=prompt_embeds,
763
+ timestep_cond=timestep_cond,
764
+ cross_attention_kwargs=self.cross_attention_kwargs,
765
+ added_cond_kwargs=added_cond_kwargs,
766
+ return_dict=False,
767
+ )[0]
768
+
769
+ # perform guidance
770
+ if self.do_classifier_free_guidance:
771
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
772
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
773
+
774
+ if use_rasg:
775
+ # Perform RASG
776
+ _, _, height, width = mask_condition.shape # 512 x 512
777
+ scale_factor = self.vae_scale_factor * rasg_scale_factor # 8 * 4 = 32
778
+
779
+ # TODO: Fix for > 1 batch_size
780
+ rasg_mask = F.interpolate(
781
+ mask_condition, (height // scale_factor, width // scale_factor), mode="bicubic"
782
+ )[0, 0] # mode is nearest by default, B, H, W
783
+
784
+ # Aggregate the saved attention maps
785
+ attn_map = []
786
+ for processor in self.unet.attn_processors.values():
787
+ if hasattr(processor, "attention_scores") and processor.attention_scores is not None:
788
+ if self.do_classifier_free_guidance:
789
+ attn_map.append(processor.attention_scores.chunk(2)[1]) # (B/2) x H, 256, 77
790
+ else:
791
+ attn_map.append(processor.attention_scores) # B x H, 256, 77 ?
792
+
793
+ attn_map = (
794
+ torch.cat(attn_map)
795
+ .mean(0)
796
+ .permute(1, 0)
797
+ .reshape((-1, height // scale_factor, width // scale_factor))
798
+ ) # 77, 16, 16
799
+
800
+ # Compute the attention score
801
+ attn_score = -sum(
802
+ [
803
+ F.binary_cross_entropy_with_logits(x - 1.0, rasg_mask.to(device))
804
+ for x in attn_map[token_idx]
805
+ ]
806
+ )
807
+
808
+ # Backward the score and compute the gradients
809
+ attn_score.backward()
810
+
811
+ # Normalzie the gradients and compute the noise component
812
+ variance_noise = latents.grad.detach()
813
+ # print("VARIANCE SHAPE", variance_noise.shape)
814
+ variance_noise -= torch.mean(variance_noise, [1, 2, 3], keepdim=True)
815
+ variance_noise /= torch.std(variance_noise, [1, 2, 3], keepdim=True)
816
+ else:
817
+ variance_noise = None
818
+
819
+ # compute the previous noisy sample x_t -> x_t-1
820
+ latents = self.scheduler.step(
821
+ noise_pred, t, latents, **extra_step_kwargs, return_dict=False, variance_noise=variance_noise
822
+ )[0]
823
+
824
+ if num_channels_unet == 4:
825
+ init_latents_proper = image_latents
826
+ if self.do_classifier_free_guidance:
827
+ init_mask, _ = mask.chunk(2)
828
+ else:
829
+ init_mask = mask
830
+
831
+ if i < len(timesteps) - 1:
832
+ noise_timestep = timesteps[i + 1]
833
+ init_latents_proper = self.scheduler.add_noise(
834
+ init_latents_proper, noise, torch.tensor([noise_timestep])
835
+ )
836
+
837
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
838
+
839
+ if callback_on_step_end is not None:
840
+ callback_kwargs = {}
841
+ for k in callback_on_step_end_tensor_inputs:
842
+ callback_kwargs[k] = locals()[k]
843
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
844
+
845
+ latents = callback_outputs.pop("latents", latents)
846
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
847
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
848
+ mask = callback_outputs.pop("mask", mask)
849
+ masked_image_latents = callback_outputs.pop("masked_image_latents", masked_image_latents)
850
+
851
+ # call the callback, if provided
852
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
853
+ progress_bar.update()
854
+ if callback is not None and i % callback_steps == 0:
855
+ step_idx = i // getattr(self.scheduler, "order", 1)
856
+ callback(step_idx, t, latents)
857
+
858
+ if not output_type == "latent":
859
+ condition_kwargs = {}
860
+ if isinstance(self.vae, AsymmetricAutoencoderKL):
861
+ init_image = init_image.to(device=device, dtype=masked_image_latents.dtype)
862
+ init_image_condition = init_image.clone()
863
+ init_image = self._encode_vae_image(init_image, generator=generator)
864
+ mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype)
865
+ condition_kwargs = {"image": init_image_condition, "mask": mask_condition}
866
+ image = self.vae.decode(
867
+ latents / self.vae.config.scaling_factor, return_dict=False, generator=generator, **condition_kwargs
868
+ )[0]
869
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
870
+ else:
871
+ image = latents
872
+ has_nsfw_concept = None
873
+
874
+ if has_nsfw_concept is None:
875
+ do_denormalize = [True] * image.shape[0]
876
+ else:
877
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
878
+
879
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
880
+
881
+ if padding_mask_crop is not None:
882
+ image = [self.image_processor.apply_overlay(mask_image, original_image, i, crops_coords) for i in image]
883
+
884
+ # Offload all models
885
+ self.maybe_free_model_hooks()
886
+
887
+ if not return_dict:
888
+ return (image, has_nsfw_concept)
889
+
890
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
891
+
892
+
893
+ # ============= Utility Functions ============== #
894
+
895
+
896
+ class GaussianSmoothing(nn.Module):
897
+ """
898
+ Apply gaussian smoothing on a
899
+ 1d, 2d or 3d tensor. Filtering is performed seperately for each channel
900
+ in the input using a depthwise convolution.
901
+
902
+ Args:
903
+ channels (`int` or `sequence`):
904
+ Number of channels of the input tensors. The output will have this number of channels as well.
905
+ kernel_size (`int` or `sequence`):
906
+ Size of the Gaussian kernel.
907
+ sigma (`float` or `sequence`):
908
+ Standard deviation of the Gaussian kernel.
909
+ dim (`int`, *optional*, defaults to `2`):
910
+ The number of dimensions of the data. Default is 2 (spatial dimensions).
911
+ """
912
+
913
+ def __init__(self, channels, kernel_size, sigma, dim=2):
914
+ super(GaussianSmoothing, self).__init__()
915
+ if isinstance(kernel_size, numbers.Number):
916
+ kernel_size = [kernel_size] * dim
917
+ if isinstance(sigma, numbers.Number):
918
+ sigma = [sigma] * dim
919
+
920
+ # The gaussian kernel is the product of the
921
+ # gaussian function of each dimension.
922
+ kernel = 1
923
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
924
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
925
+ mean = (size - 1) / 2
926
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
927
+
928
+ # Make sure sum of values in gaussian kernel equals 1.
929
+ kernel = kernel / torch.sum(kernel)
930
+
931
+ # Reshape to depthwise convolutional weight
932
+ kernel = kernel.view(1, 1, *kernel.size())
933
+ kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
934
+
935
+ self.register_buffer("weight", kernel)
936
+ self.groups = channels
937
+
938
+ if dim == 1:
939
+ self.conv = F.conv1d
940
+ elif dim == 2:
941
+ self.conv = F.conv2d
942
+ elif dim == 3:
943
+ self.conv = F.conv3d
944
+ else:
945
+ raise RuntimeError("Only 1, 2 and 3 dimensions are supported. Received {}.".format(dim))
946
+
947
+ def forward(self, input):
948
+ """
949
+ Apply gaussian filter to input.
950
+
951
+ Args:
952
+ input (`torch.Tensor` of shape `(N, C, H, W)`):
953
+ Input to apply Gaussian filter on.
954
+
955
+ Returns:
956
+ `torch.Tensor`:
957
+ The filtered output tensor with the same shape as the input.
958
+ """
959
+ return self.conv(input, weight=self.weight.to(input.dtype), groups=self.groups, padding="same")
960
+
961
+
962
+ def get_attention_scores(
963
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None
964
+ ) -> torch.Tensor:
965
+ r"""
966
+ Compute the attention scores.
967
+
968
+ Args:
969
+ query (`torch.Tensor`): The query tensor.
970
+ key (`torch.Tensor`): The key tensor.
971
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
972
+
973
+ Returns:
974
+ `torch.Tensor`: The attention probabilities/scores.
975
+ """
976
+ if self.upcast_attention:
977
+ query = query.float()
978
+ key = key.float()
979
+
980
+ if attention_mask is None:
981
+ baddbmm_input = torch.empty(
982
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
983
+ )
984
+ beta = 0
985
+ else:
986
+ baddbmm_input = attention_mask
987
+ beta = 1
988
+
989
+ attention_scores = torch.baddbmm(
990
+ baddbmm_input,
991
+ query,
992
+ key.transpose(-1, -2),
993
+ beta=beta,
994
+ alpha=self.scale,
995
+ )
996
+ del baddbmm_input
997
+
998
+ if self.upcast_softmax:
999
+ attention_scores = attention_scores.float()
1000
+
1001
+ return attention_scores
v0.32.0/iadb.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Optional, Tuple, Union
2
+
3
+ import torch
4
+
5
+ from diffusers import DiffusionPipeline
6
+ from diffusers.configuration_utils import ConfigMixin
7
+ from diffusers.pipelines.pipeline_utils import ImagePipelineOutput
8
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
+
10
+
11
+ class IADBScheduler(SchedulerMixin, ConfigMixin):
12
+ """
13
+ IADBScheduler is a scheduler for the Iterative α-(de)Blending denoising method. It is simple and minimalist.
14
+
15
+ For more details, see the original paper: https://arxiv.org/abs/2305.03486 and the blog post: https://ggx-research.github.io/publication/2023/05/10/publication-iadb.html
16
+ """
17
+
18
+ def step(
19
+ self,
20
+ model_output: torch.Tensor,
21
+ timestep: int,
22
+ x_alpha: torch.Tensor,
23
+ ) -> torch.Tensor:
24
+ """
25
+ Predict the sample at the previous timestep by reversing the ODE. Core function to propagate the diffusion
26
+ process from the learned model outputs (most often the predicted noise).
27
+
28
+ Args:
29
+ model_output (`torch.Tensor`): direct output from learned diffusion model. It is the direction from x0 to x1.
30
+ timestep (`float`): current timestep in the diffusion chain.
31
+ x_alpha (`torch.Tensor`): x_alpha sample for the current timestep
32
+
33
+ Returns:
34
+ `torch.Tensor`: the sample at the previous timestep
35
+
36
+ """
37
+ if self.num_inference_steps is None:
38
+ raise ValueError(
39
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
40
+ )
41
+
42
+ alpha = timestep / self.num_inference_steps
43
+ alpha_next = (timestep + 1) / self.num_inference_steps
44
+
45
+ d = model_output
46
+
47
+ x_alpha = x_alpha + (alpha_next - alpha) * d
48
+
49
+ return x_alpha
50
+
51
+ def set_timesteps(self, num_inference_steps: int):
52
+ self.num_inference_steps = num_inference_steps
53
+
54
+ def add_noise(
55
+ self,
56
+ original_samples: torch.Tensor,
57
+ noise: torch.Tensor,
58
+ alpha: torch.Tensor,
59
+ ) -> torch.Tensor:
60
+ return original_samples * alpha + noise * (1 - alpha)
61
+
62
+ def __len__(self):
63
+ return self.config.num_train_timesteps
64
+
65
+
66
+ class IADBPipeline(DiffusionPipeline):
67
+ r"""
68
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
69
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
70
+
71
+ Parameters:
72
+ unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
73
+ scheduler ([`SchedulerMixin`]):
74
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
75
+ [`DDPMScheduler`], or [`DDIMScheduler`].
76
+ """
77
+
78
+ def __init__(self, unet, scheduler):
79
+ super().__init__()
80
+
81
+ self.register_modules(unet=unet, scheduler=scheduler)
82
+
83
+ @torch.no_grad()
84
+ def __call__(
85
+ self,
86
+ batch_size: int = 1,
87
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
88
+ num_inference_steps: int = 50,
89
+ output_type: Optional[str] = "pil",
90
+ return_dict: bool = True,
91
+ ) -> Union[ImagePipelineOutput, Tuple]:
92
+ r"""
93
+ Args:
94
+ batch_size (`int`, *optional*, defaults to 1):
95
+ The number of images to generate.
96
+ num_inference_steps (`int`, *optional*, defaults to 50):
97
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
98
+ expense of slower inference.
99
+ output_type (`str`, *optional*, defaults to `"pil"`):
100
+ The output format of the generate image. Choose between
101
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
102
+ return_dict (`bool`, *optional*, defaults to `True`):
103
+ Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
104
+
105
+ Returns:
106
+ [`~pipelines.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if `return_dict` is
107
+ True, otherwise a `tuple. When returning a tuple, the first element is a list with the generated images.
108
+ """
109
+
110
+ # Sample gaussian noise to begin loop
111
+ if isinstance(self.unet.config.sample_size, int):
112
+ image_shape = (
113
+ batch_size,
114
+ self.unet.config.in_channels,
115
+ self.unet.config.sample_size,
116
+ self.unet.config.sample_size,
117
+ )
118
+ else:
119
+ image_shape = (batch_size, self.unet.config.in_channels, *self.unet.config.sample_size)
120
+
121
+ if isinstance(generator, list) and len(generator) != batch_size:
122
+ raise ValueError(
123
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
124
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
125
+ )
126
+
127
+ image = torch.randn(image_shape, generator=generator, device=self.device, dtype=self.unet.dtype)
128
+
129
+ # set step values
130
+ self.scheduler.set_timesteps(num_inference_steps)
131
+ x_alpha = image.clone()
132
+ for t in self.progress_bar(range(num_inference_steps)):
133
+ alpha = t / num_inference_steps
134
+
135
+ # 1. predict noise model_output
136
+ model_output = self.unet(x_alpha, torch.tensor(alpha, device=x_alpha.device)).sample
137
+
138
+ # 2. step
139
+ x_alpha = self.scheduler.step(model_output, t, x_alpha)
140
+
141
+ image = (x_alpha * 0.5 + 0.5).clamp(0, 1)
142
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
143
+ if output_type == "pil":
144
+ image = self.numpy_to_pil(image)
145
+
146
+ if not return_dict:
147
+ return (image,)
148
+
149
+ return ImagePipelineOutput(images=image)
v0.32.0/imagic_stable_diffusion.py ADDED
@@ -0,0 +1,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ modeled after the textual_inversion.py / train_dreambooth.py and the work
3
+ of justinpinkney here: https://github.com/justinpinkney/stable-diffusion/blob/main/notebooks/imagic.ipynb
4
+ """
5
+
6
+ import inspect
7
+ import warnings
8
+ from typing import List, Optional, Union
9
+
10
+ import numpy as np
11
+ import PIL.Image
12
+ import torch
13
+ import torch.nn.functional as F
14
+ from accelerate import Accelerator
15
+
16
+ # TODO: remove and import from diffusers.utils when the new version of diffusers is released
17
+ from packaging import version
18
+ from tqdm.auto import tqdm
19
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
20
+
21
+ from diffusers import DiffusionPipeline
22
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
23
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
24
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
25
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
26
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
27
+ from diffusers.utils import logging
28
+
29
+
30
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
31
+ PIL_INTERPOLATION = {
32
+ "linear": PIL.Image.Resampling.BILINEAR,
33
+ "bilinear": PIL.Image.Resampling.BILINEAR,
34
+ "bicubic": PIL.Image.Resampling.BICUBIC,
35
+ "lanczos": PIL.Image.Resampling.LANCZOS,
36
+ "nearest": PIL.Image.Resampling.NEAREST,
37
+ }
38
+ else:
39
+ PIL_INTERPOLATION = {
40
+ "linear": PIL.Image.LINEAR,
41
+ "bilinear": PIL.Image.BILINEAR,
42
+ "bicubic": PIL.Image.BICUBIC,
43
+ "lanczos": PIL.Image.LANCZOS,
44
+ "nearest": PIL.Image.NEAREST,
45
+ }
46
+ # ------------------------------------------------------------------------------
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+
51
+ def preprocess(image):
52
+ w, h = image.size
53
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
54
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
55
+ image = np.array(image).astype(np.float32) / 255.0
56
+ image = image[None].transpose(0, 3, 1, 2)
57
+ image = torch.from_numpy(image)
58
+ return 2.0 * image - 1.0
59
+
60
+
61
+ class ImagicStableDiffusionPipeline(DiffusionPipeline, StableDiffusionMixin):
62
+ r"""
63
+ Pipeline for imagic image editing.
64
+ See paper here: https://arxiv.org/pdf/2210.09276.pdf
65
+
66
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
67
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
68
+ Args:
69
+ vae ([`AutoencoderKL`]):
70
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
71
+ text_encoder ([`CLIPTextModel`]):
72
+ Frozen text-encoder. Stable Diffusion uses the text portion of
73
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
74
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
75
+ tokenizer (`CLIPTokenizer`):
76
+ Tokenizer of class
77
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
78
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
79
+ scheduler ([`SchedulerMixin`]):
80
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
81
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
82
+ safety_checker ([`StableDiffusionSafetyChecker`]):
83
+ Classification module that estimates whether generated images could be considered offsensive or harmful.
84
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
85
+ feature_extractor ([`CLIPImageProcessor`]):
86
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ vae: AutoencoderKL,
92
+ text_encoder: CLIPTextModel,
93
+ tokenizer: CLIPTokenizer,
94
+ unet: UNet2DConditionModel,
95
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
96
+ safety_checker: StableDiffusionSafetyChecker,
97
+ feature_extractor: CLIPImageProcessor,
98
+ ):
99
+ super().__init__()
100
+ self.register_modules(
101
+ vae=vae,
102
+ text_encoder=text_encoder,
103
+ tokenizer=tokenizer,
104
+ unet=unet,
105
+ scheduler=scheduler,
106
+ safety_checker=safety_checker,
107
+ feature_extractor=feature_extractor,
108
+ )
109
+
110
+ def train(
111
+ self,
112
+ prompt: Union[str, List[str]],
113
+ image: Union[torch.Tensor, PIL.Image.Image],
114
+ height: Optional[int] = 512,
115
+ width: Optional[int] = 512,
116
+ generator: Optional[torch.Generator] = None,
117
+ embedding_learning_rate: float = 0.001,
118
+ diffusion_model_learning_rate: float = 2e-6,
119
+ text_embedding_optimization_steps: int = 500,
120
+ model_fine_tuning_optimization_steps: int = 1000,
121
+ **kwargs,
122
+ ):
123
+ r"""
124
+ Function invoked when calling the pipeline for generation.
125
+ Args:
126
+ prompt (`str` or `List[str]`):
127
+ The prompt or prompts to guide the image generation.
128
+ height (`int`, *optional*, defaults to 512):
129
+ The height in pixels of the generated image.
130
+ width (`int`, *optional*, defaults to 512):
131
+ The width in pixels of the generated image.
132
+ num_inference_steps (`int`, *optional*, defaults to 50):
133
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
134
+ expense of slower inference.
135
+ guidance_scale (`float`, *optional*, defaults to 7.5):
136
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
137
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
138
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
139
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
140
+ usually at the expense of lower image quality.
141
+ eta (`float`, *optional*, defaults to 0.0):
142
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
143
+ [`schedulers.DDIMScheduler`], will be ignored for others.
144
+ generator (`torch.Generator`, *optional*):
145
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
146
+ deterministic.
147
+ latents (`torch.Tensor`, *optional*):
148
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
149
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
150
+ tensor will ge generated by sampling using the supplied random `generator`.
151
+ output_type (`str`, *optional*, defaults to `"pil"`):
152
+ The output format of the generate image. Choose between
153
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
154
+ return_dict (`bool`, *optional*, defaults to `True`):
155
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
156
+ plain tuple.
157
+ Returns:
158
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
159
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
160
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
161
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
162
+ (nsfw) content, according to the `safety_checker`.
163
+ """
164
+ accelerator = Accelerator(
165
+ gradient_accumulation_steps=1,
166
+ mixed_precision="fp16",
167
+ )
168
+
169
+ if "torch_device" in kwargs:
170
+ device = kwargs.pop("torch_device")
171
+ warnings.warn(
172
+ "`torch_device` is deprecated as an input argument to `__call__` and will be removed in v0.3.0."
173
+ " Consider using `pipe.to(torch_device)` instead."
174
+ )
175
+
176
+ if device is None:
177
+ device = "cuda" if torch.cuda.is_available() else "cpu"
178
+ self.to(device)
179
+
180
+ if height % 8 != 0 or width % 8 != 0:
181
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
182
+
183
+ # Freeze vae and unet
184
+ self.vae.requires_grad_(False)
185
+ self.unet.requires_grad_(False)
186
+ self.text_encoder.requires_grad_(False)
187
+ self.unet.eval()
188
+ self.vae.eval()
189
+ self.text_encoder.eval()
190
+
191
+ if accelerator.is_main_process:
192
+ accelerator.init_trackers(
193
+ "imagic",
194
+ config={
195
+ "embedding_learning_rate": embedding_learning_rate,
196
+ "text_embedding_optimization_steps": text_embedding_optimization_steps,
197
+ },
198
+ )
199
+
200
+ # get text embeddings for prompt
201
+ text_input = self.tokenizer(
202
+ prompt,
203
+ padding="max_length",
204
+ max_length=self.tokenizer.model_max_length,
205
+ truncation=True,
206
+ return_tensors="pt",
207
+ )
208
+ text_embeddings = torch.nn.Parameter(
209
+ self.text_encoder(text_input.input_ids.to(self.device))[0], requires_grad=True
210
+ )
211
+ text_embeddings = text_embeddings.detach()
212
+ text_embeddings.requires_grad_()
213
+ text_embeddings_orig = text_embeddings.clone()
214
+
215
+ # Initialize the optimizer
216
+ optimizer = torch.optim.Adam(
217
+ [text_embeddings], # only optimize the embeddings
218
+ lr=embedding_learning_rate,
219
+ )
220
+
221
+ if isinstance(image, PIL.Image.Image):
222
+ image = preprocess(image)
223
+
224
+ latents_dtype = text_embeddings.dtype
225
+ image = image.to(device=self.device, dtype=latents_dtype)
226
+ init_latent_image_dist = self.vae.encode(image).latent_dist
227
+ image_latents = init_latent_image_dist.sample(generator=generator)
228
+ image_latents = 0.18215 * image_latents
229
+
230
+ progress_bar = tqdm(range(text_embedding_optimization_steps), disable=not accelerator.is_local_main_process)
231
+ progress_bar.set_description("Steps")
232
+
233
+ global_step = 0
234
+
235
+ logger.info("First optimizing the text embedding to better reconstruct the init image")
236
+ for _ in range(text_embedding_optimization_steps):
237
+ with accelerator.accumulate(text_embeddings):
238
+ # Sample noise that we'll add to the latents
239
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
240
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
241
+
242
+ # Add noise to the latents according to the noise magnitude at each timestep
243
+ # (this is the forward diffusion process)
244
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
245
+
246
+ # Predict the noise residual
247
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
248
+
249
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
250
+ accelerator.backward(loss)
251
+
252
+ optimizer.step()
253
+ optimizer.zero_grad()
254
+
255
+ # Checks if the accelerator has performed an optimization step behind the scenes
256
+ if accelerator.sync_gradients:
257
+ progress_bar.update(1)
258
+ global_step += 1
259
+
260
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
261
+ progress_bar.set_postfix(**logs)
262
+ accelerator.log(logs, step=global_step)
263
+
264
+ accelerator.wait_for_everyone()
265
+
266
+ text_embeddings.requires_grad_(False)
267
+
268
+ # Now we fine tune the unet to better reconstruct the image
269
+ self.unet.requires_grad_(True)
270
+ self.unet.train()
271
+ optimizer = torch.optim.Adam(
272
+ self.unet.parameters(), # only optimize unet
273
+ lr=diffusion_model_learning_rate,
274
+ )
275
+ progress_bar = tqdm(range(model_fine_tuning_optimization_steps), disable=not accelerator.is_local_main_process)
276
+
277
+ logger.info("Next fine tuning the entire model to better reconstruct the init image")
278
+ for _ in range(model_fine_tuning_optimization_steps):
279
+ with accelerator.accumulate(self.unet.parameters()):
280
+ # Sample noise that we'll add to the latents
281
+ noise = torch.randn(image_latents.shape).to(image_latents.device)
282
+ timesteps = torch.randint(1000, (1,), device=image_latents.device)
283
+
284
+ # Add noise to the latents according to the noise magnitude at each timestep
285
+ # (this is the forward diffusion process)
286
+ noisy_latents = self.scheduler.add_noise(image_latents, noise, timesteps)
287
+
288
+ # Predict the noise residual
289
+ noise_pred = self.unet(noisy_latents, timesteps, text_embeddings).sample
290
+
291
+ loss = F.mse_loss(noise_pred, noise, reduction="none").mean([1, 2, 3]).mean()
292
+ accelerator.backward(loss)
293
+
294
+ optimizer.step()
295
+ optimizer.zero_grad()
296
+
297
+ # Checks if the accelerator has performed an optimization step behind the scenes
298
+ if accelerator.sync_gradients:
299
+ progress_bar.update(1)
300
+ global_step += 1
301
+
302
+ logs = {"loss": loss.detach().item()} # , "lr": lr_scheduler.get_last_lr()[0]}
303
+ progress_bar.set_postfix(**logs)
304
+ accelerator.log(logs, step=global_step)
305
+
306
+ accelerator.wait_for_everyone()
307
+ self.text_embeddings_orig = text_embeddings_orig
308
+ self.text_embeddings = text_embeddings
309
+
310
+ @torch.no_grad()
311
+ def __call__(
312
+ self,
313
+ alpha: float = 1.2,
314
+ height: Optional[int] = 512,
315
+ width: Optional[int] = 512,
316
+ num_inference_steps: Optional[int] = 50,
317
+ generator: Optional[torch.Generator] = None,
318
+ output_type: Optional[str] = "pil",
319
+ return_dict: bool = True,
320
+ guidance_scale: float = 7.5,
321
+ eta: float = 0.0,
322
+ ):
323
+ r"""
324
+ Function invoked when calling the pipeline for generation.
325
+ Args:
326
+ alpha (`float`, *optional*, defaults to 1.2):
327
+ The interpolation factor between the original and optimized text embeddings. A value closer to 0
328
+ will resemble the original input image.
329
+ height (`int`, *optional*, defaults to 512):
330
+ The height in pixels of the generated image.
331
+ width (`int`, *optional*, defaults to 512):
332
+ The width in pixels of the generated image.
333
+ num_inference_steps (`int`, *optional*, defaults to 50):
334
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
335
+ expense of slower inference.
336
+ guidance_scale (`float`, *optional*, defaults to 7.5):
337
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
338
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
339
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
340
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
341
+ usually at the expense of lower image quality.
342
+ generator (`torch.Generator`, *optional*):
343
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
344
+ deterministic.
345
+ output_type (`str`, *optional*, defaults to `"pil"`):
346
+ The output format of the generate image. Choose between
347
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `nd.array`.
348
+ return_dict (`bool`, *optional*, defaults to `True`):
349
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
350
+ plain tuple.
351
+ eta (`float`, *optional*, defaults to 0.0):
352
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
353
+ [`schedulers.DDIMScheduler`], will be ignored for others.
354
+ Returns:
355
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
356
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
357
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
358
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
359
+ (nsfw) content, according to the `safety_checker`.
360
+ """
361
+ if height % 8 != 0 or width % 8 != 0:
362
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
363
+ if self.text_embeddings is None:
364
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
365
+ if self.text_embeddings_orig is None:
366
+ raise ValueError("Please run the pipe.train() before trying to generate an image.")
367
+
368
+ text_embeddings = alpha * self.text_embeddings_orig + (1 - alpha) * self.text_embeddings
369
+
370
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
371
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
372
+ # corresponds to doing no classifier free guidance.
373
+ do_classifier_free_guidance = guidance_scale > 1.0
374
+ # get unconditional embeddings for classifier free guidance
375
+ if do_classifier_free_guidance:
376
+ uncond_tokens = [""]
377
+ max_length = self.tokenizer.model_max_length
378
+ uncond_input = self.tokenizer(
379
+ uncond_tokens,
380
+ padding="max_length",
381
+ max_length=max_length,
382
+ truncation=True,
383
+ return_tensors="pt",
384
+ )
385
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
386
+
387
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
388
+ seq_len = uncond_embeddings.shape[1]
389
+ uncond_embeddings = uncond_embeddings.view(1, seq_len, -1)
390
+
391
+ # For classifier free guidance, we need to do two forward passes.
392
+ # Here we concatenate the unconditional and text embeddings into a single batch
393
+ # to avoid doing two forward passes
394
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
395
+
396
+ # get the initial random noise unless the user supplied it
397
+
398
+ # Unlike in other pipelines, latents need to be generated in the target device
399
+ # for 1-to-1 results reproducibility with the CompVis implementation.
400
+ # However this currently doesn't work in `mps`.
401
+ latents_shape = (1, self.unet.config.in_channels, height // 8, width // 8)
402
+ latents_dtype = text_embeddings.dtype
403
+ if self.device.type == "mps":
404
+ # randn does not exist on mps
405
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
406
+ self.device
407
+ )
408
+ else:
409
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
410
+
411
+ # set timesteps
412
+ self.scheduler.set_timesteps(num_inference_steps)
413
+
414
+ # Some schedulers like PNDM have timesteps as arrays
415
+ # It's more optimized to move all timesteps to correct device beforehand
416
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
417
+
418
+ # scale the initial noise by the standard deviation required by the scheduler
419
+ latents = latents * self.scheduler.init_noise_sigma
420
+
421
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
422
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
423
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
424
+ # and should be between [0, 1]
425
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
426
+ extra_step_kwargs = {}
427
+ if accepts_eta:
428
+ extra_step_kwargs["eta"] = eta
429
+
430
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
431
+ # expand the latents if we are doing classifier free guidance
432
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
433
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
434
+
435
+ # predict the noise residual
436
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
437
+
438
+ # perform guidance
439
+ if do_classifier_free_guidance:
440
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
441
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
442
+
443
+ # compute the previous noisy sample x_t -> x_t-1
444
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
445
+
446
+ latents = 1 / 0.18215 * latents
447
+ image = self.vae.decode(latents).sample
448
+
449
+ image = (image / 2 + 0.5).clamp(0, 1)
450
+
451
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
452
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
453
+
454
+ if self.safety_checker is not None:
455
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
456
+ self.device
457
+ )
458
+ image, has_nsfw_concept = self.safety_checker(
459
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
460
+ )
461
+ else:
462
+ has_nsfw_concept = None
463
+
464
+ if output_type == "pil":
465
+ image = self.numpy_to_pil(image)
466
+
467
+ if not return_dict:
468
+ return (image, has_nsfw_concept)
469
+
470
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/img2img_inpainting.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import DiffusionPipeline
10
+ from diffusers.configuration_utils import FrozenDict
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
15
+ from diffusers.utils import deprecate, logging
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ def prepare_mask_and_masked_image(image, mask):
22
+ image = np.array(image.convert("RGB"))
23
+ image = image[None].transpose(0, 3, 1, 2)
24
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
25
+
26
+ mask = np.array(mask.convert("L"))
27
+ mask = mask.astype(np.float32) / 255.0
28
+ mask = mask[None, None]
29
+ mask[mask < 0.5] = 0
30
+ mask[mask >= 0.5] = 1
31
+ mask = torch.from_numpy(mask)
32
+
33
+ masked_image = image * (mask < 0.5)
34
+
35
+ return mask, masked_image
36
+
37
+
38
+ def check_size(image, height, width):
39
+ if isinstance(image, PIL.Image.Image):
40
+ w, h = image.size
41
+ elif isinstance(image, torch.Tensor):
42
+ *_, h, w = image.shape
43
+
44
+ if h != height or w != width:
45
+ raise ValueError(f"Image size should be {height}x{width}, but got {h}x{w}")
46
+
47
+
48
+ def overlay_inner_image(image, inner_image, paste_offset: Tuple[int] = (0, 0)):
49
+ inner_image = inner_image.convert("RGBA")
50
+ image = image.convert("RGB")
51
+
52
+ image.paste(inner_image, paste_offset, inner_image)
53
+ image = image.convert("RGB")
54
+
55
+ return image
56
+
57
+
58
+ class ImageToImageInpaintingPipeline(DiffusionPipeline):
59
+ r"""
60
+ Pipeline for text-guided image-to-image inpainting using Stable Diffusion. *This is an experimental feature*.
61
+
62
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
63
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
64
+
65
+ Args:
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPImageProcessor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ vae: AutoencoderKL,
89
+ text_encoder: CLIPTextModel,
90
+ tokenizer: CLIPTokenizer,
91
+ unet: UNet2DConditionModel,
92
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
93
+ safety_checker: StableDiffusionSafetyChecker,
94
+ feature_extractor: CLIPImageProcessor,
95
+ ):
96
+ super().__init__()
97
+
98
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
99
+ deprecation_message = (
100
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
101
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
102
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
103
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
104
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
105
+ " file"
106
+ )
107
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
108
+ new_config = dict(scheduler.config)
109
+ new_config["steps_offset"] = 1
110
+ scheduler._internal_dict = FrozenDict(new_config)
111
+
112
+ if safety_checker is None:
113
+ logger.warning(
114
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
115
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
116
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
117
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
118
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
119
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
120
+ )
121
+
122
+ self.register_modules(
123
+ vae=vae,
124
+ text_encoder=text_encoder,
125
+ tokenizer=tokenizer,
126
+ unet=unet,
127
+ scheduler=scheduler,
128
+ safety_checker=safety_checker,
129
+ feature_extractor=feature_extractor,
130
+ )
131
+
132
+ @torch.no_grad()
133
+ def __call__(
134
+ self,
135
+ prompt: Union[str, List[str]],
136
+ image: Union[torch.Tensor, PIL.Image.Image],
137
+ inner_image: Union[torch.Tensor, PIL.Image.Image],
138
+ mask_image: Union[torch.Tensor, PIL.Image.Image],
139
+ height: int = 512,
140
+ width: int = 512,
141
+ num_inference_steps: int = 50,
142
+ guidance_scale: float = 7.5,
143
+ negative_prompt: Optional[Union[str, List[str]]] = None,
144
+ num_images_per_prompt: Optional[int] = 1,
145
+ eta: float = 0.0,
146
+ generator: Optional[torch.Generator] = None,
147
+ latents: Optional[torch.Tensor] = None,
148
+ output_type: Optional[str] = "pil",
149
+ return_dict: bool = True,
150
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
151
+ callback_steps: int = 1,
152
+ **kwargs,
153
+ ):
154
+ r"""
155
+ Function invoked when calling the pipeline for generation.
156
+
157
+ Args:
158
+ prompt (`str` or `List[str]`):
159
+ The prompt or prompts to guide the image generation.
160
+ image (`torch.Tensor` or `PIL.Image.Image`):
161
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
162
+ be masked out with `mask_image` and repainted according to `prompt`.
163
+ inner_image (`torch.Tensor` or `PIL.Image.Image`):
164
+ `Image`, or tensor representing an image batch which will be overlayed onto `image`. Non-transparent
165
+ regions of `inner_image` must fit inside white pixels in `mask_image`. Expects four channels, with
166
+ the last channel representing the alpha channel, which will be used to blend `inner_image` with
167
+ `image`. If not provided, it will be forcibly cast to RGBA.
168
+ mask_image (`PIL.Image.Image`):
169
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
170
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
171
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
172
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
173
+ height (`int`, *optional*, defaults to 512):
174
+ The height in pixels of the generated image.
175
+ width (`int`, *optional*, defaults to 512):
176
+ The width in pixels of the generated image.
177
+ num_inference_steps (`int`, *optional*, defaults to 50):
178
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
179
+ expense of slower inference.
180
+ guidance_scale (`float`, *optional*, defaults to 7.5):
181
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
182
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
183
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
184
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
185
+ usually at the expense of lower image quality.
186
+ negative_prompt (`str` or `List[str]`, *optional*):
187
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
188
+ if `guidance_scale` is less than `1`).
189
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
190
+ The number of images to generate per prompt.
191
+ eta (`float`, *optional*, defaults to 0.0):
192
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
193
+ [`schedulers.DDIMScheduler`], will be ignored for others.
194
+ generator (`torch.Generator`, *optional*):
195
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
196
+ deterministic.
197
+ latents (`torch.Tensor`, *optional*):
198
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
199
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
200
+ tensor will ge generated by sampling using the supplied random `generator`.
201
+ output_type (`str`, *optional*, defaults to `"pil"`):
202
+ The output format of the generate image. Choose between
203
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
204
+ return_dict (`bool`, *optional*, defaults to `True`):
205
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
206
+ plain tuple.
207
+ callback (`Callable`, *optional*):
208
+ A function that will be called every `callback_steps` steps during inference. The function will be
209
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
210
+ callback_steps (`int`, *optional*, defaults to 1):
211
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
212
+ called at every step.
213
+
214
+ Returns:
215
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
216
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
217
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
218
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
219
+ (nsfw) content, according to the `safety_checker`.
220
+ """
221
+
222
+ if isinstance(prompt, str):
223
+ batch_size = 1
224
+ elif isinstance(prompt, list):
225
+ batch_size = len(prompt)
226
+ else:
227
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
228
+
229
+ if height % 8 != 0 or width % 8 != 0:
230
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
231
+
232
+ if (callback_steps is None) or (
233
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
234
+ ):
235
+ raise ValueError(
236
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
237
+ f" {type(callback_steps)}."
238
+ )
239
+
240
+ # check if input sizes are correct
241
+ check_size(image, height, width)
242
+ check_size(inner_image, height, width)
243
+ check_size(mask_image, height, width)
244
+
245
+ # get prompt text embeddings
246
+ text_inputs = self.tokenizer(
247
+ prompt,
248
+ padding="max_length",
249
+ max_length=self.tokenizer.model_max_length,
250
+ return_tensors="pt",
251
+ )
252
+ text_input_ids = text_inputs.input_ids
253
+
254
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
255
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
256
+ logger.warning(
257
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
258
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
259
+ )
260
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
261
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
262
+
263
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
264
+ bs_embed, seq_len, _ = text_embeddings.shape
265
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
266
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
267
+
268
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
269
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
270
+ # corresponds to doing no classifier free guidance.
271
+ do_classifier_free_guidance = guidance_scale > 1.0
272
+ # get unconditional embeddings for classifier free guidance
273
+ if do_classifier_free_guidance:
274
+ uncond_tokens: List[str]
275
+ if negative_prompt is None:
276
+ uncond_tokens = [""]
277
+ elif type(prompt) is not type(negative_prompt):
278
+ raise TypeError(
279
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
280
+ f" {type(prompt)}."
281
+ )
282
+ elif isinstance(negative_prompt, str):
283
+ uncond_tokens = [negative_prompt]
284
+ elif batch_size != len(negative_prompt):
285
+ raise ValueError(
286
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
287
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
288
+ " the batch size of `prompt`."
289
+ )
290
+ else:
291
+ uncond_tokens = negative_prompt
292
+
293
+ max_length = text_input_ids.shape[-1]
294
+ uncond_input = self.tokenizer(
295
+ uncond_tokens,
296
+ padding="max_length",
297
+ max_length=max_length,
298
+ truncation=True,
299
+ return_tensors="pt",
300
+ )
301
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
302
+
303
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
304
+ seq_len = uncond_embeddings.shape[1]
305
+ uncond_embeddings = uncond_embeddings.repeat(batch_size, num_images_per_prompt, 1)
306
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
307
+
308
+ # For classifier free guidance, we need to do two forward passes.
309
+ # Here we concatenate the unconditional and text embeddings into a single batch
310
+ # to avoid doing two forward passes
311
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
312
+
313
+ # get the initial random noise unless the user supplied it
314
+ # Unlike in other pipelines, latents need to be generated in the target device
315
+ # for 1-to-1 results reproducibility with the CompVis implementation.
316
+ # However this currently doesn't work in `mps`.
317
+ num_channels_latents = self.vae.config.latent_channels
318
+ latents_shape = (batch_size * num_images_per_prompt, num_channels_latents, height // 8, width // 8)
319
+ latents_dtype = text_embeddings.dtype
320
+ if latents is None:
321
+ if self.device.type == "mps":
322
+ # randn does not exist on mps
323
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
324
+ self.device
325
+ )
326
+ else:
327
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
328
+ else:
329
+ if latents.shape != latents_shape:
330
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
331
+ latents = latents.to(self.device)
332
+
333
+ # overlay the inner image
334
+ image = overlay_inner_image(image, inner_image)
335
+
336
+ # prepare mask and masked_image
337
+ mask, masked_image = prepare_mask_and_masked_image(image, mask_image)
338
+ mask = mask.to(device=self.device, dtype=text_embeddings.dtype)
339
+ masked_image = masked_image.to(device=self.device, dtype=text_embeddings.dtype)
340
+
341
+ # resize the mask to latents shape as we concatenate the mask to the latents
342
+ mask = torch.nn.functional.interpolate(mask, size=(height // 8, width // 8))
343
+
344
+ # encode the mask image into latents space so we can concatenate it to the latents
345
+ masked_image_latents = self.vae.encode(masked_image).latent_dist.sample(generator=generator)
346
+ masked_image_latents = 0.18215 * masked_image_latents
347
+
348
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
349
+ mask = mask.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
350
+ masked_image_latents = masked_image_latents.repeat(batch_size * num_images_per_prompt, 1, 1, 1)
351
+
352
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
353
+ masked_image_latents = (
354
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
355
+ )
356
+
357
+ num_channels_mask = mask.shape[1]
358
+ num_channels_masked_image = masked_image_latents.shape[1]
359
+
360
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
361
+ raise ValueError(
362
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
363
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
364
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
365
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
366
+ " `pipeline.unet` or your `mask_image` or `image` input."
367
+ )
368
+
369
+ # set timesteps
370
+ self.scheduler.set_timesteps(num_inference_steps)
371
+
372
+ # Some schedulers like PNDM have timesteps as arrays
373
+ # It's more optimized to move all timesteps to correct device beforehand
374
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
375
+
376
+ # scale the initial noise by the standard deviation required by the scheduler
377
+ latents = latents * self.scheduler.init_noise_sigma
378
+
379
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
380
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
381
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
382
+ # and should be between [0, 1]
383
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
384
+ extra_step_kwargs = {}
385
+ if accepts_eta:
386
+ extra_step_kwargs["eta"] = eta
387
+
388
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
389
+ # expand the latents if we are doing classifier free guidance
390
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
391
+
392
+ # concat latents, mask, masked_image_latents in the channel dimension
393
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
394
+
395
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
396
+
397
+ # predict the noise residual
398
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
399
+
400
+ # perform guidance
401
+ if do_classifier_free_guidance:
402
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
403
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
404
+
405
+ # compute the previous noisy sample x_t -> x_t-1
406
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
407
+
408
+ # call the callback, if provided
409
+ if callback is not None and i % callback_steps == 0:
410
+ step_idx = i // getattr(self.scheduler, "order", 1)
411
+ callback(step_idx, t, latents)
412
+
413
+ latents = 1 / 0.18215 * latents
414
+ image = self.vae.decode(latents).sample
415
+
416
+ image = (image / 2 + 0.5).clamp(0, 1)
417
+
418
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
419
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
420
+
421
+ if self.safety_checker is not None:
422
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
423
+ self.device
424
+ )
425
+ image, has_nsfw_concept = self.safety_checker(
426
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
427
+ )
428
+ else:
429
+ has_nsfw_concept = None
430
+
431
+ if output_type == "pil":
432
+ image = self.numpy_to_pil(image)
433
+
434
+ if not return_dict:
435
+ return (image, has_nsfw_concept)
436
+
437
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/instaflow_one_step.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from packaging import version
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
21
+
22
+ from diffusers.configuration_utils import FrozenDict
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
25
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
26
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
28
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
29
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
30
+ from diffusers.schedulers import KarrasDiffusionSchedulers
31
+ from diffusers.utils import (
32
+ deprecate,
33
+ logging,
34
+ )
35
+ from diffusers.utils.torch_utils import randn_tensor
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
42
+ """
43
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
44
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
45
+ """
46
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
47
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
48
+ # rescale the results from guidance (fixes overexposure)
49
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
50
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
51
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
52
+ return noise_cfg
53
+
54
+
55
+ class InstaFlowPipeline(
56
+ DiffusionPipeline,
57
+ StableDiffusionMixin,
58
+ TextualInversionLoaderMixin,
59
+ StableDiffusionLoraLoaderMixin,
60
+ FromSingleFileMixin,
61
+ ):
62
+ r"""
63
+ Pipeline for text-to-image generation using Rectified Flow and Euler discretization.
64
+ This customized pipeline is based on StableDiffusionPipeline from the official Diffusers library (0.21.4)
65
+
66
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
67
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
68
+
69
+ The pipeline also inherits the following loading methods:
70
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
71
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
72
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
73
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
74
+
75
+ Args:
76
+ vae ([`AutoencoderKL`]):
77
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
78
+ text_encoder ([`~transformers.CLIPTextModel`]):
79
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
80
+ tokenizer ([`~transformers.CLIPTokenizer`]):
81
+ A `CLIPTokenizer` to tokenize text.
82
+ unet ([`UNet2DConditionModel`]):
83
+ A `UNet2DConditionModel` to denoise the encoded image latents.
84
+ scheduler ([`SchedulerMixin`]):
85
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
86
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
87
+ safety_checker ([`StableDiffusionSafetyChecker`]):
88
+ Classification module that estimates whether generated images could be considered offensive or harmful.
89
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
90
+ about a model's potential harms.
91
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
92
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
93
+ """
94
+
95
+ model_cpu_offload_seq = "text_encoder->unet->vae"
96
+ _optional_components = ["safety_checker", "feature_extractor"]
97
+ _exclude_from_cpu_offload = ["safety_checker"]
98
+
99
+ def __init__(
100
+ self,
101
+ vae: AutoencoderKL,
102
+ text_encoder: CLIPTextModel,
103
+ tokenizer: CLIPTokenizer,
104
+ unet: UNet2DConditionModel,
105
+ scheduler: KarrasDiffusionSchedulers,
106
+ safety_checker: StableDiffusionSafetyChecker,
107
+ feature_extractor: CLIPImageProcessor,
108
+ requires_safety_checker: bool = True,
109
+ ):
110
+ super().__init__()
111
+
112
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
113
+ deprecation_message = (
114
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
115
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
116
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
117
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
118
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
119
+ " file"
120
+ )
121
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
122
+ new_config = dict(scheduler.config)
123
+ new_config["steps_offset"] = 1
124
+ scheduler._internal_dict = FrozenDict(new_config)
125
+
126
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
127
+ deprecation_message = (
128
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
129
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
130
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
131
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
132
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
133
+ )
134
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
135
+ new_config = dict(scheduler.config)
136
+ new_config["clip_sample"] = False
137
+ scheduler._internal_dict = FrozenDict(new_config)
138
+
139
+ if safety_checker is None and requires_safety_checker:
140
+ logger.warning(
141
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
142
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
143
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
144
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
145
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
146
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
147
+ )
148
+
149
+ if safety_checker is not None and feature_extractor is None:
150
+ raise ValueError(
151
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
152
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
153
+ )
154
+
155
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
156
+ version.parse(unet.config._diffusers_version).base_version
157
+ ) < version.parse("0.9.0.dev0")
158
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
159
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
160
+ deprecation_message = (
161
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
162
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
163
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
164
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
165
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
166
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
167
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
168
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
169
+ " the `unet/config.json` file"
170
+ )
171
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
172
+ new_config = dict(unet.config)
173
+ new_config["sample_size"] = 64
174
+ unet._internal_dict = FrozenDict(new_config)
175
+
176
+ self.register_modules(
177
+ vae=vae,
178
+ text_encoder=text_encoder,
179
+ tokenizer=tokenizer,
180
+ unet=unet,
181
+ scheduler=scheduler,
182
+ safety_checker=safety_checker,
183
+ feature_extractor=feature_extractor,
184
+ )
185
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
186
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
187
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
188
+
189
+ def _encode_prompt(
190
+ self,
191
+ prompt,
192
+ device,
193
+ num_images_per_prompt,
194
+ do_classifier_free_guidance,
195
+ negative_prompt=None,
196
+ prompt_embeds: Optional[torch.Tensor] = None,
197
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
198
+ lora_scale: Optional[float] = None,
199
+ ):
200
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
201
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
202
+
203
+ prompt_embeds_tuple = self.encode_prompt(
204
+ prompt=prompt,
205
+ device=device,
206
+ num_images_per_prompt=num_images_per_prompt,
207
+ do_classifier_free_guidance=do_classifier_free_guidance,
208
+ negative_prompt=negative_prompt,
209
+ prompt_embeds=prompt_embeds,
210
+ negative_prompt_embeds=negative_prompt_embeds,
211
+ lora_scale=lora_scale,
212
+ )
213
+
214
+ # concatenate for backwards comp
215
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
216
+
217
+ return prompt_embeds
218
+
219
+ def encode_prompt(
220
+ self,
221
+ prompt,
222
+ device,
223
+ num_images_per_prompt,
224
+ do_classifier_free_guidance,
225
+ negative_prompt=None,
226
+ prompt_embeds: Optional[torch.Tensor] = None,
227
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
228
+ lora_scale: Optional[float] = None,
229
+ ):
230
+ r"""
231
+ Encodes the prompt into text encoder hidden states.
232
+
233
+ Args:
234
+ prompt (`str` or `List[str]`, *optional*):
235
+ prompt to be encoded
236
+ device: (`torch.device`):
237
+ torch device
238
+ num_images_per_prompt (`int`):
239
+ number of images that should be generated per prompt
240
+ do_classifier_free_guidance (`bool`):
241
+ whether to use classifier free guidance or not
242
+ negative_prompt (`str` or `List[str]`, *optional*):
243
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
244
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
245
+ less than `1`).
246
+ prompt_embeds (`torch.Tensor`, *optional*):
247
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
248
+ provided, text embeddings will be generated from `prompt` input argument.
249
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
250
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
251
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
252
+ argument.
253
+ lora_scale (`float`, *optional*):
254
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
255
+ """
256
+ # set lora scale so that monkey patched LoRA
257
+ # function of text encoder can correctly access it
258
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
259
+ self._lora_scale = lora_scale
260
+
261
+ # dynamically adjust the LoRA scale
262
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
263
+
264
+ if prompt is not None and isinstance(prompt, str):
265
+ batch_size = 1
266
+ elif prompt is not None and isinstance(prompt, list):
267
+ batch_size = len(prompt)
268
+ else:
269
+ batch_size = prompt_embeds.shape[0]
270
+
271
+ if prompt_embeds is None:
272
+ # textual inversion: procecss multi-vector tokens if necessary
273
+ if isinstance(self, TextualInversionLoaderMixin):
274
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
275
+
276
+ text_inputs = self.tokenizer(
277
+ prompt,
278
+ padding="max_length",
279
+ max_length=self.tokenizer.model_max_length,
280
+ truncation=True,
281
+ return_tensors="pt",
282
+ )
283
+ text_input_ids = text_inputs.input_ids
284
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
285
+
286
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
287
+ text_input_ids, untruncated_ids
288
+ ):
289
+ removed_text = self.tokenizer.batch_decode(
290
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
291
+ )
292
+ logger.warning(
293
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
294
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
295
+ )
296
+
297
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
298
+ attention_mask = text_inputs.attention_mask.to(device)
299
+ else:
300
+ attention_mask = None
301
+
302
+ prompt_embeds = self.text_encoder(
303
+ text_input_ids.to(device),
304
+ attention_mask=attention_mask,
305
+ )
306
+ prompt_embeds = prompt_embeds[0]
307
+
308
+ if self.text_encoder is not None:
309
+ prompt_embeds_dtype = self.text_encoder.dtype
310
+ elif self.unet is not None:
311
+ prompt_embeds_dtype = self.unet.dtype
312
+ else:
313
+ prompt_embeds_dtype = prompt_embeds.dtype
314
+
315
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
316
+
317
+ bs_embed, seq_len, _ = prompt_embeds.shape
318
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
319
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
320
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
321
+
322
+ # get unconditional embeddings for classifier free guidance
323
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
324
+ uncond_tokens: List[str]
325
+ if negative_prompt is None:
326
+ uncond_tokens = [""] * batch_size
327
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
328
+ raise TypeError(
329
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
330
+ f" {type(prompt)}."
331
+ )
332
+ elif isinstance(negative_prompt, str):
333
+ uncond_tokens = [negative_prompt]
334
+ elif batch_size != len(negative_prompt):
335
+ raise ValueError(
336
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
337
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
338
+ " the batch size of `prompt`."
339
+ )
340
+ else:
341
+ uncond_tokens = negative_prompt
342
+
343
+ # textual inversion: procecss multi-vector tokens if necessary
344
+ if isinstance(self, TextualInversionLoaderMixin):
345
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
346
+
347
+ max_length = prompt_embeds.shape[1]
348
+ uncond_input = self.tokenizer(
349
+ uncond_tokens,
350
+ padding="max_length",
351
+ max_length=max_length,
352
+ truncation=True,
353
+ return_tensors="pt",
354
+ )
355
+
356
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
357
+ attention_mask = uncond_input.attention_mask.to(device)
358
+ else:
359
+ attention_mask = None
360
+
361
+ negative_prompt_embeds = self.text_encoder(
362
+ uncond_input.input_ids.to(device),
363
+ attention_mask=attention_mask,
364
+ )
365
+ negative_prompt_embeds = negative_prompt_embeds[0]
366
+
367
+ if do_classifier_free_guidance:
368
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
369
+ seq_len = negative_prompt_embeds.shape[1]
370
+
371
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
372
+
373
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
374
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
375
+
376
+ return prompt_embeds, negative_prompt_embeds
377
+
378
+ def run_safety_checker(self, image, device, dtype):
379
+ if self.safety_checker is None:
380
+ has_nsfw_concept = None
381
+ else:
382
+ if torch.is_tensor(image):
383
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
384
+ else:
385
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
386
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
387
+ image, has_nsfw_concept = self.safety_checker(
388
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
389
+ )
390
+ return image, has_nsfw_concept
391
+
392
+ def decode_latents(self, latents):
393
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
394
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
395
+
396
+ latents = 1 / self.vae.config.scaling_factor * latents
397
+ image = self.vae.decode(latents, return_dict=False)[0]
398
+ image = (image / 2 + 0.5).clamp(0, 1)
399
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
400
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
401
+ return image
402
+
403
+ def merge_dW_to_unet(pipe, dW_dict, alpha=1.0):
404
+ _tmp_sd = pipe.unet.state_dict()
405
+ for key in dW_dict.keys():
406
+ _tmp_sd[key] += dW_dict[key] * alpha
407
+ pipe.unet.load_state_dict(_tmp_sd, strict=False)
408
+ return pipe
409
+
410
+ def prepare_extra_step_kwargs(self, generator, eta):
411
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
412
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
413
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
414
+ # and should be between [0, 1]
415
+
416
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
417
+ extra_step_kwargs = {}
418
+ if accepts_eta:
419
+ extra_step_kwargs["eta"] = eta
420
+
421
+ # check if the scheduler accepts generator
422
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
423
+ if accepts_generator:
424
+ extra_step_kwargs["generator"] = generator
425
+ return extra_step_kwargs
426
+
427
+ def check_inputs(
428
+ self,
429
+ prompt,
430
+ height,
431
+ width,
432
+ callback_steps,
433
+ negative_prompt=None,
434
+ prompt_embeds=None,
435
+ negative_prompt_embeds=None,
436
+ ):
437
+ if height % 8 != 0 or width % 8 != 0:
438
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
439
+
440
+ if (callback_steps is None) or (
441
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
442
+ ):
443
+ raise ValueError(
444
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
445
+ f" {type(callback_steps)}."
446
+ )
447
+
448
+ if prompt is not None and prompt_embeds is not None:
449
+ raise ValueError(
450
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
451
+ " only forward one of the two."
452
+ )
453
+ elif prompt is None and prompt_embeds is None:
454
+ raise ValueError(
455
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
456
+ )
457
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
458
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
459
+
460
+ if negative_prompt is not None and negative_prompt_embeds is not None:
461
+ raise ValueError(
462
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
463
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
464
+ )
465
+
466
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
467
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
468
+ raise ValueError(
469
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
470
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
471
+ f" {negative_prompt_embeds.shape}."
472
+ )
473
+
474
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
475
+ shape = (
476
+ batch_size,
477
+ num_channels_latents,
478
+ int(height) // self.vae_scale_factor,
479
+ int(width) // self.vae_scale_factor,
480
+ )
481
+ if isinstance(generator, list) and len(generator) != batch_size:
482
+ raise ValueError(
483
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
484
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
485
+ )
486
+
487
+ if latents is None:
488
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
489
+ else:
490
+ latents = latents.to(device)
491
+
492
+ # scale the initial noise by the standard deviation required by the scheduler
493
+ latents = latents * self.scheduler.init_noise_sigma
494
+ return latents
495
+
496
+ @torch.no_grad()
497
+ def __call__(
498
+ self,
499
+ prompt: Union[str, List[str]] = None,
500
+ height: Optional[int] = None,
501
+ width: Optional[int] = None,
502
+ num_inference_steps: int = 50,
503
+ guidance_scale: float = 7.5,
504
+ negative_prompt: Optional[Union[str, List[str]]] = None,
505
+ num_images_per_prompt: Optional[int] = 1,
506
+ eta: float = 0.0,
507
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
508
+ latents: Optional[torch.Tensor] = None,
509
+ prompt_embeds: Optional[torch.Tensor] = None,
510
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
511
+ output_type: Optional[str] = "pil",
512
+ return_dict: bool = True,
513
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
514
+ callback_steps: int = 1,
515
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
516
+ guidance_rescale: float = 0.0,
517
+ ):
518
+ r"""
519
+ The call function to the pipeline for generation.
520
+
521
+ Args:
522
+ prompt (`str` or `List[str]`, *optional*):
523
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
524
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
525
+ The height in pixels of the generated image.
526
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
527
+ The width in pixels of the generated image.
528
+ num_inference_steps (`int`, *optional*, defaults to 50):
529
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
530
+ expense of slower inference.
531
+ guidance_scale (`float`, *optional*, defaults to 7.5):
532
+ A higher guidance scale value encourages the model to generate images closely linked to the text
533
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
534
+ negative_prompt (`str` or `List[str]`, *optional*):
535
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
536
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
537
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
538
+ The number of images to generate per prompt.
539
+ eta (`float`, *optional*, defaults to 0.0):
540
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
541
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
542
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
543
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
544
+ generation deterministic.
545
+ latents (`torch.Tensor`, *optional*):
546
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
547
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
548
+ tensor is generated by sampling using the supplied random `generator`.
549
+ prompt_embeds (`torch.Tensor`, *optional*):
550
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
551
+ provided, text embeddings are generated from the `prompt` input argument.
552
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
553
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
554
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
555
+ output_type (`str`, *optional*, defaults to `"pil"`):
556
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
557
+ return_dict (`bool`, *optional*, defaults to `True`):
558
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
559
+ plain tuple.
560
+ callback (`Callable`, *optional*):
561
+ A function that calls every `callback_steps` steps during inference. The function is called with the
562
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
563
+ callback_steps (`int`, *optional*, defaults to 1):
564
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
565
+ every step.
566
+ cross_attention_kwargs (`dict`, *optional*):
567
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
568
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
569
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
570
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
571
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
572
+ using zero terminal SNR.
573
+
574
+ Examples:
575
+
576
+ Returns:
577
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
578
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
579
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
580
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
581
+ "not-safe-for-work" (nsfw) content.
582
+ """
583
+ # 0. Default height and width to unet
584
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
585
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
586
+
587
+ # 1. Check inputs. Raise error if not correct
588
+ self.check_inputs(
589
+ prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
590
+ )
591
+
592
+ # 2. Define call parameters
593
+ if prompt is not None and isinstance(prompt, str):
594
+ batch_size = 1
595
+ elif prompt is not None and isinstance(prompt, list):
596
+ batch_size = len(prompt)
597
+ else:
598
+ batch_size = prompt_embeds.shape[0]
599
+
600
+ device = self._execution_device
601
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
602
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
603
+ # corresponds to doing no classifier free guidance.
604
+ do_classifier_free_guidance = guidance_scale > 1.0
605
+
606
+ # 3. Encode input prompt
607
+ text_encoder_lora_scale = (
608
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
609
+ )
610
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
611
+ prompt,
612
+ device,
613
+ num_images_per_prompt,
614
+ do_classifier_free_guidance,
615
+ negative_prompt,
616
+ prompt_embeds=prompt_embeds,
617
+ negative_prompt_embeds=negative_prompt_embeds,
618
+ lora_scale=text_encoder_lora_scale,
619
+ )
620
+ # For classifier free guidance, we need to do two forward passes.
621
+ # Here we concatenate the unconditional and text embeddings into a single batch
622
+ # to avoid doing two forward passes
623
+ if do_classifier_free_guidance:
624
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
625
+
626
+ # 4. Prepare timesteps
627
+ timesteps = [(1.0 - i / num_inference_steps) * 1000.0 for i in range(num_inference_steps)]
628
+
629
+ # 5. Prepare latent variables
630
+ num_channels_latents = self.unet.config.in_channels
631
+ latents = self.prepare_latents(
632
+ batch_size * num_images_per_prompt,
633
+ num_channels_latents,
634
+ height,
635
+ width,
636
+ prompt_embeds.dtype,
637
+ device,
638
+ generator,
639
+ latents,
640
+ )
641
+
642
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
643
+ dt = 1.0 / num_inference_steps
644
+
645
+ # 7. Denoising loop of Euler discretization from t = 0 to t = 1
646
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
647
+ for i, t in enumerate(timesteps):
648
+ # expand the latents if we are doing classifier free guidance
649
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
650
+
651
+ vec_t = torch.ones((latent_model_input.shape[0],), device=latents.device) * t
652
+
653
+ v_pred = self.unet(latent_model_input, vec_t, encoder_hidden_states=prompt_embeds).sample
654
+
655
+ # perform guidance
656
+ if do_classifier_free_guidance:
657
+ v_pred_neg, v_pred_text = v_pred.chunk(2)
658
+ v_pred = v_pred_neg + guidance_scale * (v_pred_text - v_pred_neg)
659
+
660
+ latents = latents + dt * v_pred
661
+
662
+ # call the callback, if provided
663
+ if i == len(timesteps) - 1 or ((i + 1) % self.scheduler.order == 0):
664
+ progress_bar.update()
665
+ if callback is not None and i % callback_steps == 0:
666
+ step_idx = i // getattr(self.scheduler, "order", 1)
667
+ callback(step_idx, t, latents)
668
+
669
+ if not output_type == "latent":
670
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
671
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
672
+ else:
673
+ image = latents
674
+ has_nsfw_concept = None
675
+
676
+ if has_nsfw_concept is None:
677
+ do_denormalize = [True] * image.shape[0]
678
+ else:
679
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
680
+
681
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
682
+
683
+ # Offload all models
684
+ self.maybe_free_model_hooks()
685
+
686
+ if not return_dict:
687
+ return (image, has_nsfw_concept)
688
+
689
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/interpolate_stable_diffusion.py ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import time
3
+ from pathlib import Path
4
+ from typing import Callable, List, Optional, Union
5
+
6
+ import numpy as np
7
+ import torch
8
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
9
+
10
+ from diffusers.configuration_utils import FrozenDict
11
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
12
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
15
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
16
+ from diffusers.utils import deprecate, logging
17
+
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+
22
+ def slerp(t, v0, v1, DOT_THRESHOLD=0.9995):
23
+ """helper function to spherically interpolate two arrays v1 v2"""
24
+
25
+ if not isinstance(v0, np.ndarray):
26
+ inputs_are_torch = True
27
+ input_device = v0.device
28
+ v0 = v0.cpu().numpy()
29
+ v1 = v1.cpu().numpy()
30
+
31
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
32
+ if np.abs(dot) > DOT_THRESHOLD:
33
+ v2 = (1 - t) * v0 + t * v1
34
+ else:
35
+ theta_0 = np.arccos(dot)
36
+ sin_theta_0 = np.sin(theta_0)
37
+ theta_t = theta_0 * t
38
+ sin_theta_t = np.sin(theta_t)
39
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
40
+ s1 = sin_theta_t / sin_theta_0
41
+ v2 = s0 * v0 + s1 * v1
42
+
43
+ if inputs_are_torch:
44
+ v2 = torch.from_numpy(v2).to(input_device)
45
+
46
+ return v2
47
+
48
+
49
+ class StableDiffusionWalkPipeline(DiffusionPipeline, StableDiffusionMixin):
50
+ r"""
51
+ Pipeline for text-to-image generation using Stable Diffusion.
52
+
53
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
54
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
55
+
56
+ Args:
57
+ vae ([`AutoencoderKL`]):
58
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
59
+ text_encoder ([`CLIPTextModel`]):
60
+ Frozen text-encoder. Stable Diffusion uses the text portion of
61
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
62
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
63
+ tokenizer (`CLIPTokenizer`):
64
+ Tokenizer of class
65
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
66
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
67
+ scheduler ([`SchedulerMixin`]):
68
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
69
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
70
+ safety_checker ([`StableDiffusionSafetyChecker`]):
71
+ Classification module that estimates whether generated images could be considered offensive or harmful.
72
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
73
+ feature_extractor ([`CLIPImageProcessor`]):
74
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ vae: AutoencoderKL,
80
+ text_encoder: CLIPTextModel,
81
+ tokenizer: CLIPTokenizer,
82
+ unet: UNet2DConditionModel,
83
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
84
+ safety_checker: StableDiffusionSafetyChecker,
85
+ feature_extractor: CLIPImageProcessor,
86
+ ):
87
+ super().__init__()
88
+
89
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
90
+ deprecation_message = (
91
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
92
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
93
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
94
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
95
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
96
+ " file"
97
+ )
98
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
99
+ new_config = dict(scheduler.config)
100
+ new_config["steps_offset"] = 1
101
+ scheduler._internal_dict = FrozenDict(new_config)
102
+
103
+ if safety_checker is None:
104
+ logger.warning(
105
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
106
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
107
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
108
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
109
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
110
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
111
+ )
112
+
113
+ self.register_modules(
114
+ vae=vae,
115
+ text_encoder=text_encoder,
116
+ tokenizer=tokenizer,
117
+ unet=unet,
118
+ scheduler=scheduler,
119
+ safety_checker=safety_checker,
120
+ feature_extractor=feature_extractor,
121
+ )
122
+
123
+ @torch.no_grad()
124
+ def __call__(
125
+ self,
126
+ prompt: Optional[Union[str, List[str]]] = None,
127
+ height: int = 512,
128
+ width: int = 512,
129
+ num_inference_steps: int = 50,
130
+ guidance_scale: float = 7.5,
131
+ negative_prompt: Optional[Union[str, List[str]]] = None,
132
+ num_images_per_prompt: Optional[int] = 1,
133
+ eta: float = 0.0,
134
+ generator: Optional[torch.Generator] = None,
135
+ latents: Optional[torch.Tensor] = None,
136
+ output_type: Optional[str] = "pil",
137
+ return_dict: bool = True,
138
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
139
+ callback_steps: int = 1,
140
+ text_embeddings: Optional[torch.Tensor] = None,
141
+ **kwargs,
142
+ ):
143
+ r"""
144
+ Function invoked when calling the pipeline for generation.
145
+
146
+ Args:
147
+ prompt (`str` or `List[str]`, *optional*, defaults to `None`):
148
+ The prompt or prompts to guide the image generation. If not provided, `text_embeddings` is required.
149
+ height (`int`, *optional*, defaults to 512):
150
+ The height in pixels of the generated image.
151
+ width (`int`, *optional*, defaults to 512):
152
+ The width in pixels of the generated image.
153
+ num_inference_steps (`int`, *optional*, defaults to 50):
154
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
155
+ expense of slower inference.
156
+ guidance_scale (`float`, *optional*, defaults to 7.5):
157
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
158
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
159
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
160
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
161
+ usually at the expense of lower image quality.
162
+ negative_prompt (`str` or `List[str]`, *optional*):
163
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
164
+ if `guidance_scale` is less than `1`).
165
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
166
+ The number of images to generate per prompt.
167
+ eta (`float`, *optional*, defaults to 0.0):
168
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
169
+ [`schedulers.DDIMScheduler`], will be ignored for others.
170
+ generator (`torch.Generator`, *optional*):
171
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
172
+ deterministic.
173
+ latents (`torch.Tensor`, *optional*):
174
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
175
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
176
+ tensor will ge generated by sampling using the supplied random `generator`.
177
+ output_type (`str`, *optional*, defaults to `"pil"`):
178
+ The output format of the generate image. Choose between
179
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
180
+ return_dict (`bool`, *optional*, defaults to `True`):
181
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
182
+ plain tuple.
183
+ callback (`Callable`, *optional*):
184
+ A function that will be called every `callback_steps` steps during inference. The function will be
185
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
186
+ callback_steps (`int`, *optional*, defaults to 1):
187
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
188
+ called at every step.
189
+ text_embeddings (`torch.Tensor`, *optional*, defaults to `None`):
190
+ Pre-generated text embeddings to be used as inputs for image generation. Can be used in place of
191
+ `prompt` to avoid re-computing the embeddings. If not provided, the embeddings will be generated from
192
+ the supplied `prompt`.
193
+
194
+ Returns:
195
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
196
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
197
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
198
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
199
+ (nsfw) content, according to the `safety_checker`.
200
+ """
201
+
202
+ if height % 8 != 0 or width % 8 != 0:
203
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
204
+
205
+ if (callback_steps is None) or (
206
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
207
+ ):
208
+ raise ValueError(
209
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
210
+ f" {type(callback_steps)}."
211
+ )
212
+
213
+ if text_embeddings is None:
214
+ if isinstance(prompt, str):
215
+ batch_size = 1
216
+ elif isinstance(prompt, list):
217
+ batch_size = len(prompt)
218
+ else:
219
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
220
+
221
+ # get prompt text embeddings
222
+ text_inputs = self.tokenizer(
223
+ prompt,
224
+ padding="max_length",
225
+ max_length=self.tokenizer.model_max_length,
226
+ return_tensors="pt",
227
+ )
228
+ text_input_ids = text_inputs.input_ids
229
+
230
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
231
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
232
+ print(
233
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
234
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
235
+ )
236
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
237
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
238
+ else:
239
+ batch_size = text_embeddings.shape[0]
240
+
241
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
242
+ bs_embed, seq_len, _ = text_embeddings.shape
243
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
244
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
245
+
246
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
247
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
248
+ # corresponds to doing no classifier free guidance.
249
+ do_classifier_free_guidance = guidance_scale > 1.0
250
+ # get unconditional embeddings for classifier free guidance
251
+ if do_classifier_free_guidance:
252
+ uncond_tokens: List[str]
253
+ if negative_prompt is None:
254
+ uncond_tokens = [""] * batch_size
255
+ elif type(prompt) is not type(negative_prompt):
256
+ raise TypeError(
257
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
258
+ f" {type(prompt)}."
259
+ )
260
+ elif isinstance(negative_prompt, str):
261
+ uncond_tokens = [negative_prompt]
262
+ elif batch_size != len(negative_prompt):
263
+ raise ValueError(
264
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
265
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
266
+ " the batch size of `prompt`."
267
+ )
268
+ else:
269
+ uncond_tokens = negative_prompt
270
+
271
+ max_length = self.tokenizer.model_max_length
272
+ uncond_input = self.tokenizer(
273
+ uncond_tokens,
274
+ padding="max_length",
275
+ max_length=max_length,
276
+ truncation=True,
277
+ return_tensors="pt",
278
+ )
279
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
280
+
281
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
282
+ seq_len = uncond_embeddings.shape[1]
283
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
284
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
285
+
286
+ # For classifier free guidance, we need to do two forward passes.
287
+ # Here we concatenate the unconditional and text embeddings into a single batch
288
+ # to avoid doing two forward passes
289
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
290
+
291
+ # get the initial random noise unless the user supplied it
292
+
293
+ # Unlike in other pipelines, latents need to be generated in the target device
294
+ # for 1-to-1 results reproducibility with the CompVis implementation.
295
+ # However this currently doesn't work in `mps`.
296
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
297
+ latents_dtype = text_embeddings.dtype
298
+ if latents is None:
299
+ if self.device.type == "mps":
300
+ # randn does not work reproducibly on mps
301
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
302
+ self.device
303
+ )
304
+ else:
305
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
306
+ else:
307
+ if latents.shape != latents_shape:
308
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
309
+ latents = latents.to(self.device)
310
+
311
+ # set timesteps
312
+ self.scheduler.set_timesteps(num_inference_steps)
313
+
314
+ # Some schedulers like PNDM have timesteps as arrays
315
+ # It's more optimized to move all timesteps to correct device beforehand
316
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
317
+
318
+ # scale the initial noise by the standard deviation required by the scheduler
319
+ latents = latents * self.scheduler.init_noise_sigma
320
+
321
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
322
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
323
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
324
+ # and should be between [0, 1]
325
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
326
+ extra_step_kwargs = {}
327
+ if accepts_eta:
328
+ extra_step_kwargs["eta"] = eta
329
+
330
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
331
+ # expand the latents if we are doing classifier free guidance
332
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
333
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
334
+
335
+ # predict the noise residual
336
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
337
+
338
+ # perform guidance
339
+ if do_classifier_free_guidance:
340
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
341
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
342
+
343
+ # compute the previous noisy sample x_t -> x_t-1
344
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
345
+
346
+ # call the callback, if provided
347
+ if callback is not None and i % callback_steps == 0:
348
+ step_idx = i // getattr(self.scheduler, "order", 1)
349
+ callback(step_idx, t, latents)
350
+
351
+ latents = 1 / 0.18215 * latents
352
+ image = self.vae.decode(latents).sample
353
+
354
+ image = (image / 2 + 0.5).clamp(0, 1)
355
+
356
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
357
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
358
+
359
+ if self.safety_checker is not None:
360
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
361
+ self.device
362
+ )
363
+ image, has_nsfw_concept = self.safety_checker(
364
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
365
+ )
366
+ else:
367
+ has_nsfw_concept = None
368
+
369
+ if output_type == "pil":
370
+ image = self.numpy_to_pil(image)
371
+
372
+ if not return_dict:
373
+ return (image, has_nsfw_concept)
374
+
375
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
376
+
377
+ def embed_text(self, text):
378
+ """takes in text and turns it into text embeddings"""
379
+ text_input = self.tokenizer(
380
+ text,
381
+ padding="max_length",
382
+ max_length=self.tokenizer.model_max_length,
383
+ truncation=True,
384
+ return_tensors="pt",
385
+ )
386
+ with torch.no_grad():
387
+ embed = self.text_encoder(text_input.input_ids.to(self.device))[0]
388
+ return embed
389
+
390
+ def get_noise(self, seed, dtype=torch.float32, height=512, width=512):
391
+ """Takes in random seed and returns corresponding noise vector"""
392
+ return torch.randn(
393
+ (1, self.unet.config.in_channels, height // 8, width // 8),
394
+ generator=torch.Generator(device=self.device).manual_seed(seed),
395
+ device=self.device,
396
+ dtype=dtype,
397
+ )
398
+
399
+ def walk(
400
+ self,
401
+ prompts: List[str],
402
+ seeds: List[int],
403
+ num_interpolation_steps: Optional[int] = 6,
404
+ output_dir: Optional[str] = "./dreams",
405
+ name: Optional[str] = None,
406
+ batch_size: Optional[int] = 1,
407
+ height: Optional[int] = 512,
408
+ width: Optional[int] = 512,
409
+ guidance_scale: Optional[float] = 7.5,
410
+ num_inference_steps: Optional[int] = 50,
411
+ eta: Optional[float] = 0.0,
412
+ ) -> List[str]:
413
+ """
414
+ Walks through a series of prompts and seeds, interpolating between them and saving the results to disk.
415
+
416
+ Args:
417
+ prompts (`List[str]`):
418
+ List of prompts to generate images for.
419
+ seeds (`List[int]`):
420
+ List of seeds corresponding to provided prompts. Must be the same length as prompts.
421
+ num_interpolation_steps (`int`, *optional*, defaults to 6):
422
+ Number of interpolation steps to take between prompts.
423
+ output_dir (`str`, *optional*, defaults to `./dreams`):
424
+ Directory to save the generated images to.
425
+ name (`str`, *optional*, defaults to `None`):
426
+ Subdirectory of `output_dir` to save the generated images to. If `None`, the name will
427
+ be the current time.
428
+ batch_size (`int`, *optional*, defaults to 1):
429
+ Number of images to generate at once.
430
+ height (`int`, *optional*, defaults to 512):
431
+ Height of the generated images.
432
+ width (`int`, *optional*, defaults to 512):
433
+ Width of the generated images.
434
+ guidance_scale (`float`, *optional*, defaults to 7.5):
435
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
436
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
437
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
438
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
439
+ usually at the expense of lower image quality.
440
+ num_inference_steps (`int`, *optional*, defaults to 50):
441
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
442
+ expense of slower inference.
443
+ eta (`float`, *optional*, defaults to 0.0):
444
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
445
+ [`schedulers.DDIMScheduler`], will be ignored for others.
446
+
447
+ Returns:
448
+ `List[str]`: List of paths to the generated images.
449
+ """
450
+ if not len(prompts) == len(seeds):
451
+ raise ValueError(
452
+ f"Number of prompts and seeds must be equalGot {len(prompts)} prompts and {len(seeds)} seeds"
453
+ )
454
+
455
+ name = name or time.strftime("%Y%m%d-%H%M%S")
456
+ save_path = Path(output_dir) / name
457
+ save_path.mkdir(exist_ok=True, parents=True)
458
+
459
+ frame_idx = 0
460
+ frame_filepaths = []
461
+ for prompt_a, prompt_b, seed_a, seed_b in zip(prompts, prompts[1:], seeds, seeds[1:]):
462
+ # Embed Text
463
+ embed_a = self.embed_text(prompt_a)
464
+ embed_b = self.embed_text(prompt_b)
465
+
466
+ # Get Noise
467
+ noise_dtype = embed_a.dtype
468
+ noise_a = self.get_noise(seed_a, noise_dtype, height, width)
469
+ noise_b = self.get_noise(seed_b, noise_dtype, height, width)
470
+
471
+ noise_batch, embeds_batch = None, None
472
+ T = np.linspace(0.0, 1.0, num_interpolation_steps)
473
+ for i, t in enumerate(T):
474
+ noise = slerp(float(t), noise_a, noise_b)
475
+ embed = torch.lerp(embed_a, embed_b, t)
476
+
477
+ noise_batch = noise if noise_batch is None else torch.cat([noise_batch, noise], dim=0)
478
+ embeds_batch = embed if embeds_batch is None else torch.cat([embeds_batch, embed], dim=0)
479
+
480
+ batch_is_ready = embeds_batch.shape[0] == batch_size or i + 1 == T.shape[0]
481
+ if batch_is_ready:
482
+ outputs = self(
483
+ latents=noise_batch,
484
+ text_embeddings=embeds_batch,
485
+ height=height,
486
+ width=width,
487
+ guidance_scale=guidance_scale,
488
+ eta=eta,
489
+ num_inference_steps=num_inference_steps,
490
+ )
491
+ noise_batch, embeds_batch = None, None
492
+
493
+ for image in outputs["images"]:
494
+ frame_filepath = str(save_path / f"frame_{frame_idx:06d}.png")
495
+ image.save(frame_filepath)
496
+ frame_filepaths.append(frame_filepath)
497
+ frame_idx += 1
498
+ return frame_filepaths
v0.32.0/ip_adapter_face_id.py ADDED
@@ -0,0 +1,1128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from packaging import version
22
+ from safetensors import safe_open
23
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
24
+
25
+ from diffusers.configuration_utils import FrozenDict
26
+ from diffusers.image_processor import VaeImageProcessor
27
+ from diffusers.loaders import (
28
+ FromSingleFileMixin,
29
+ IPAdapterMixin,
30
+ StableDiffusionLoraLoaderMixin,
31
+ TextualInversionLoaderMixin,
32
+ )
33
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
34
+ from diffusers.models.attention_processor import (
35
+ AttnProcessor,
36
+ AttnProcessor2_0,
37
+ IPAdapterAttnProcessor,
38
+ IPAdapterAttnProcessor2_0,
39
+ )
40
+ from diffusers.models.embeddings import MultiIPAdapterImageProjection
41
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
42
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
43
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
44
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
45
+ from diffusers.schedulers import KarrasDiffusionSchedulers
46
+ from diffusers.utils import (
47
+ USE_PEFT_BACKEND,
48
+ _get_model_file,
49
+ deprecate,
50
+ logging,
51
+ scale_lora_layers,
52
+ unscale_lora_layers,
53
+ )
54
+ from diffusers.utils.torch_utils import randn_tensor
55
+
56
+
57
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
58
+
59
+
60
+ class IPAdapterFullImageProjection(nn.Module):
61
+ def __init__(self, image_embed_dim=1024, cross_attention_dim=1024, mult=1, num_tokens=1):
62
+ super().__init__()
63
+ from diffusers.models.attention import FeedForward
64
+
65
+ self.num_tokens = num_tokens
66
+ self.cross_attention_dim = cross_attention_dim
67
+ self.ff = FeedForward(image_embed_dim, cross_attention_dim * num_tokens, mult=mult, activation_fn="gelu")
68
+ self.norm = nn.LayerNorm(cross_attention_dim)
69
+
70
+ def forward(self, image_embeds: torch.Tensor):
71
+ x = self.ff(image_embeds)
72
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
73
+ return self.norm(x)
74
+
75
+
76
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
77
+ """
78
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
79
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
80
+ """
81
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
82
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
83
+ # rescale the results from guidance (fixes overexposure)
84
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
85
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
86
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
87
+ return noise_cfg
88
+
89
+
90
+ def retrieve_timesteps(
91
+ scheduler,
92
+ num_inference_steps: Optional[int] = None,
93
+ device: Optional[Union[str, torch.device]] = None,
94
+ timesteps: Optional[List[int]] = None,
95
+ **kwargs,
96
+ ):
97
+ """
98
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
99
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
100
+
101
+ Args:
102
+ scheduler (`SchedulerMixin`):
103
+ The scheduler to get timesteps from.
104
+ num_inference_steps (`int`):
105
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
106
+ `timesteps` must be `None`.
107
+ device (`str` or `torch.device`, *optional*):
108
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
109
+ timesteps (`List[int]`, *optional*):
110
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
111
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
112
+ must be `None`.
113
+
114
+ Returns:
115
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
116
+ second element is the number of inference steps.
117
+ """
118
+ if timesteps is not None:
119
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
120
+ if not accepts_timesteps:
121
+ raise ValueError(
122
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
123
+ f" timestep schedules. Please check whether you are using the correct scheduler."
124
+ )
125
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
126
+ timesteps = scheduler.timesteps
127
+ num_inference_steps = len(timesteps)
128
+ else:
129
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
130
+ timesteps = scheduler.timesteps
131
+ return timesteps, num_inference_steps
132
+
133
+
134
+ class IPAdapterFaceIDStableDiffusionPipeline(
135
+ DiffusionPipeline,
136
+ StableDiffusionMixin,
137
+ TextualInversionLoaderMixin,
138
+ StableDiffusionLoraLoaderMixin,
139
+ IPAdapterMixin,
140
+ FromSingleFileMixin,
141
+ ):
142
+ r"""
143
+ Pipeline for text-to-image generation using Stable Diffusion.
144
+
145
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
146
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
147
+
148
+ The pipeline also inherits the following loading methods:
149
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
150
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
151
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
152
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
153
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
154
+
155
+ Args:
156
+ vae ([`AutoencoderKL`]):
157
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
158
+ text_encoder ([`~transformers.CLIPTextModel`]):
159
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
160
+ tokenizer ([`~transformers.CLIPTokenizer`]):
161
+ A `CLIPTokenizer` to tokenize text.
162
+ unet ([`UNet2DConditionModel`]):
163
+ A `UNet2DConditionModel` to denoise the encoded image latents.
164
+ scheduler ([`SchedulerMixin`]):
165
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
166
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
167
+ safety_checker ([`StableDiffusionSafetyChecker`]):
168
+ Classification module that estimates whether generated images could be considered offensive or harmful.
169
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
170
+ about a model's potential harms.
171
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
172
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
173
+ """
174
+
175
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
176
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
177
+ _exclude_from_cpu_offload = ["safety_checker"]
178
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
179
+
180
+ def __init__(
181
+ self,
182
+ vae: AutoencoderKL,
183
+ text_encoder: CLIPTextModel,
184
+ tokenizer: CLIPTokenizer,
185
+ unet: UNet2DConditionModel,
186
+ scheduler: KarrasDiffusionSchedulers,
187
+ safety_checker: StableDiffusionSafetyChecker,
188
+ feature_extractor: CLIPImageProcessor,
189
+ image_encoder: CLIPVisionModelWithProjection = None,
190
+ requires_safety_checker: bool = True,
191
+ ):
192
+ super().__init__()
193
+
194
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
195
+ deprecation_message = (
196
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
197
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
198
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
199
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
200
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
201
+ " file"
202
+ )
203
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
204
+ new_config = dict(scheduler.config)
205
+ new_config["steps_offset"] = 1
206
+ scheduler._internal_dict = FrozenDict(new_config)
207
+
208
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
209
+ deprecation_message = (
210
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
211
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
212
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
213
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
214
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
215
+ )
216
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
217
+ new_config = dict(scheduler.config)
218
+ new_config["clip_sample"] = False
219
+ scheduler._internal_dict = FrozenDict(new_config)
220
+
221
+ if safety_checker is None and requires_safety_checker:
222
+ logger.warning(
223
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
224
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
225
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
226
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
227
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
228
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
229
+ )
230
+
231
+ if safety_checker is not None and feature_extractor is None:
232
+ raise ValueError(
233
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
234
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
235
+ )
236
+
237
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
238
+ version.parse(unet.config._diffusers_version).base_version
239
+ ) < version.parse("0.9.0.dev0")
240
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
241
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
242
+ deprecation_message = (
243
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
244
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
245
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
246
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
247
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
248
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
249
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
250
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
251
+ " the `unet/config.json` file"
252
+ )
253
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
254
+ new_config = dict(unet.config)
255
+ new_config["sample_size"] = 64
256
+ unet._internal_dict = FrozenDict(new_config)
257
+
258
+ self.register_modules(
259
+ vae=vae,
260
+ text_encoder=text_encoder,
261
+ tokenizer=tokenizer,
262
+ unet=unet,
263
+ scheduler=scheduler,
264
+ safety_checker=safety_checker,
265
+ feature_extractor=feature_extractor,
266
+ image_encoder=image_encoder,
267
+ )
268
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
269
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
270
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
271
+
272
+ def load_ip_adapter_face_id(self, pretrained_model_name_or_path_or_dict, weight_name, **kwargs):
273
+ cache_dir = kwargs.pop("cache_dir", None)
274
+ force_download = kwargs.pop("force_download", False)
275
+ proxies = kwargs.pop("proxies", None)
276
+ local_files_only = kwargs.pop("local_files_only", None)
277
+ token = kwargs.pop("token", None)
278
+ revision = kwargs.pop("revision", None)
279
+ subfolder = kwargs.pop("subfolder", None)
280
+
281
+ user_agent = {
282
+ "file_type": "attn_procs_weights",
283
+ "framework": "pytorch",
284
+ }
285
+ model_file = _get_model_file(
286
+ pretrained_model_name_or_path_or_dict,
287
+ weights_name=weight_name,
288
+ cache_dir=cache_dir,
289
+ force_download=force_download,
290
+ proxies=proxies,
291
+ local_files_only=local_files_only,
292
+ token=token,
293
+ revision=revision,
294
+ subfolder=subfolder,
295
+ user_agent=user_agent,
296
+ )
297
+ if weight_name.endswith(".safetensors"):
298
+ state_dict = {"image_proj": {}, "ip_adapter": {}}
299
+ with safe_open(model_file, framework="pt", device="cpu") as f:
300
+ for key in f.keys():
301
+ if key.startswith("image_proj."):
302
+ state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
303
+ elif key.startswith("ip_adapter."):
304
+ state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
305
+ else:
306
+ state_dict = torch.load(model_file, map_location="cpu")
307
+ self._load_ip_adapter_weights(state_dict)
308
+
309
+ def convert_ip_adapter_image_proj_to_diffusers(self, state_dict):
310
+ updated_state_dict = {}
311
+ clip_embeddings_dim_in = state_dict["proj.0.weight"].shape[1]
312
+ clip_embeddings_dim_out = state_dict["proj.0.weight"].shape[0]
313
+ multiplier = clip_embeddings_dim_out // clip_embeddings_dim_in
314
+ norm_layer = "norm.weight"
315
+ cross_attention_dim = state_dict[norm_layer].shape[0]
316
+ num_tokens = state_dict["proj.2.weight"].shape[0] // cross_attention_dim
317
+
318
+ image_projection = IPAdapterFullImageProjection(
319
+ cross_attention_dim=cross_attention_dim,
320
+ image_embed_dim=clip_embeddings_dim_in,
321
+ mult=multiplier,
322
+ num_tokens=num_tokens,
323
+ )
324
+
325
+ for key, value in state_dict.items():
326
+ diffusers_name = key.replace("proj.0", "ff.net.0.proj")
327
+ diffusers_name = diffusers_name.replace("proj.2", "ff.net.2")
328
+ updated_state_dict[diffusers_name] = value
329
+
330
+ image_projection.load_state_dict(updated_state_dict)
331
+ return image_projection
332
+
333
+ def _load_ip_adapter_weights(self, state_dict):
334
+ num_image_text_embeds = 4
335
+
336
+ self.unet.encoder_hid_proj = None
337
+
338
+ # set ip-adapter cross-attention processors & load state_dict
339
+ attn_procs = {}
340
+ lora_dict = {}
341
+ key_id = 0
342
+ for name in self.unet.attn_processors.keys():
343
+ cross_attention_dim = None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
344
+ if name.startswith("mid_block"):
345
+ hidden_size = self.unet.config.block_out_channels[-1]
346
+ elif name.startswith("up_blocks"):
347
+ block_id = int(name[len("up_blocks.")])
348
+ hidden_size = list(reversed(self.unet.config.block_out_channels))[block_id]
349
+ elif name.startswith("down_blocks"):
350
+ block_id = int(name[len("down_blocks.")])
351
+ hidden_size = self.unet.config.block_out_channels[block_id]
352
+ if cross_attention_dim is None or "motion_modules" in name:
353
+ attn_processor_class = (
354
+ AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
355
+ )
356
+ attn_procs[name] = attn_processor_class()
357
+
358
+ lora_dict.update(
359
+ {f"unet.{name}.to_k_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.down.weight"]}
360
+ )
361
+ lora_dict.update(
362
+ {f"unet.{name}.to_q_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.down.weight"]}
363
+ )
364
+ lora_dict.update(
365
+ {f"unet.{name}.to_v_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.down.weight"]}
366
+ )
367
+ lora_dict.update(
368
+ {
369
+ f"unet.{name}.to_out_lora.down.weight": state_dict["ip_adapter"][
370
+ f"{key_id}.to_out_lora.down.weight"
371
+ ]
372
+ }
373
+ )
374
+ lora_dict.update(
375
+ {f"unet.{name}.to_k_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.up.weight"]}
376
+ )
377
+ lora_dict.update(
378
+ {f"unet.{name}.to_q_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.up.weight"]}
379
+ )
380
+ lora_dict.update(
381
+ {f"unet.{name}.to_v_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.up.weight"]}
382
+ )
383
+ lora_dict.update(
384
+ {f"unet.{name}.to_out_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_out_lora.up.weight"]}
385
+ )
386
+ key_id += 1
387
+ else:
388
+ attn_processor_class = (
389
+ IPAdapterAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else IPAdapterAttnProcessor
390
+ )
391
+ attn_procs[name] = attn_processor_class(
392
+ hidden_size=hidden_size,
393
+ cross_attention_dim=cross_attention_dim,
394
+ scale=1.0,
395
+ num_tokens=num_image_text_embeds,
396
+ ).to(dtype=self.dtype, device=self.device)
397
+
398
+ lora_dict.update(
399
+ {f"unet.{name}.to_k_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.down.weight"]}
400
+ )
401
+ lora_dict.update(
402
+ {f"unet.{name}.to_q_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.down.weight"]}
403
+ )
404
+ lora_dict.update(
405
+ {f"unet.{name}.to_v_lora.down.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.down.weight"]}
406
+ )
407
+ lora_dict.update(
408
+ {
409
+ f"unet.{name}.to_out_lora.down.weight": state_dict["ip_adapter"][
410
+ f"{key_id}.to_out_lora.down.weight"
411
+ ]
412
+ }
413
+ )
414
+ lora_dict.update(
415
+ {f"unet.{name}.to_k_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.up.weight"]}
416
+ )
417
+ lora_dict.update(
418
+ {f"unet.{name}.to_q_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.up.weight"]}
419
+ )
420
+ lora_dict.update(
421
+ {f"unet.{name}.to_v_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.up.weight"]}
422
+ )
423
+ lora_dict.update(
424
+ {f"unet.{name}.to_out_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_out_lora.up.weight"]}
425
+ )
426
+
427
+ value_dict = {}
428
+ value_dict.update({"to_k_ip.0.weight": state_dict["ip_adapter"][f"{key_id}.to_k_ip.weight"]})
429
+ value_dict.update({"to_v_ip.0.weight": state_dict["ip_adapter"][f"{key_id}.to_v_ip.weight"]})
430
+ attn_procs[name].load_state_dict(value_dict)
431
+ key_id += 1
432
+
433
+ self.unet.set_attn_processor(attn_procs)
434
+
435
+ self.load_lora_weights(lora_dict, adapter_name="faceid")
436
+ self.set_adapters(["faceid"], adapter_weights=[1.0])
437
+
438
+ # convert IP-Adapter Image Projection layers to diffusers
439
+ image_projection = self.convert_ip_adapter_image_proj_to_diffusers(state_dict["image_proj"])
440
+ image_projection_layers = [image_projection.to(device=self.device, dtype=self.dtype)]
441
+
442
+ self.unet.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
443
+ self.unet.config.encoder_hid_dim_type = "ip_image_proj"
444
+
445
+ def set_ip_adapter_scale(self, scale):
446
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
447
+ for attn_processor in unet.attn_processors.values():
448
+ if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
449
+ attn_processor.scale = [scale]
450
+
451
+ def _encode_prompt(
452
+ self,
453
+ prompt,
454
+ device,
455
+ num_images_per_prompt,
456
+ do_classifier_free_guidance,
457
+ negative_prompt=None,
458
+ prompt_embeds: Optional[torch.Tensor] = None,
459
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
460
+ lora_scale: Optional[float] = None,
461
+ **kwargs,
462
+ ):
463
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
464
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
465
+
466
+ prompt_embeds_tuple = self.encode_prompt(
467
+ prompt=prompt,
468
+ device=device,
469
+ num_images_per_prompt=num_images_per_prompt,
470
+ do_classifier_free_guidance=do_classifier_free_guidance,
471
+ negative_prompt=negative_prompt,
472
+ prompt_embeds=prompt_embeds,
473
+ negative_prompt_embeds=negative_prompt_embeds,
474
+ lora_scale=lora_scale,
475
+ **kwargs,
476
+ )
477
+
478
+ # concatenate for backwards comp
479
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
480
+
481
+ return prompt_embeds
482
+
483
+ def encode_prompt(
484
+ self,
485
+ prompt,
486
+ device,
487
+ num_images_per_prompt,
488
+ do_classifier_free_guidance,
489
+ negative_prompt=None,
490
+ prompt_embeds: Optional[torch.Tensor] = None,
491
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
492
+ lora_scale: Optional[float] = None,
493
+ clip_skip: Optional[int] = None,
494
+ ):
495
+ r"""
496
+ Encodes the prompt into text encoder hidden states.
497
+
498
+ Args:
499
+ prompt (`str` or `List[str]`, *optional*):
500
+ prompt to be encoded
501
+ device: (`torch.device`):
502
+ torch device
503
+ num_images_per_prompt (`int`):
504
+ number of images that should be generated per prompt
505
+ do_classifier_free_guidance (`bool`):
506
+ whether to use classifier free guidance or not
507
+ negative_prompt (`str` or `List[str]`, *optional*):
508
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
509
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
510
+ less than `1`).
511
+ prompt_embeds (`torch.Tensor`, *optional*):
512
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
513
+ provided, text embeddings will be generated from `prompt` input argument.
514
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
515
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
516
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
517
+ argument.
518
+ lora_scale (`float`, *optional*):
519
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
520
+ clip_skip (`int`, *optional*):
521
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
522
+ the output of the pre-final layer will be used for computing the prompt embeddings.
523
+ """
524
+ # set lora scale so that monkey patched LoRA
525
+ # function of text encoder can correctly access it
526
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
527
+ self._lora_scale = lora_scale
528
+
529
+ # dynamically adjust the LoRA scale
530
+ if not USE_PEFT_BACKEND:
531
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
532
+ else:
533
+ scale_lora_layers(self.text_encoder, lora_scale)
534
+
535
+ if prompt is not None and isinstance(prompt, str):
536
+ batch_size = 1
537
+ elif prompt is not None and isinstance(prompt, list):
538
+ batch_size = len(prompt)
539
+ else:
540
+ batch_size = prompt_embeds.shape[0]
541
+
542
+ if prompt_embeds is None:
543
+ # textual inversion: process multi-vector tokens if necessary
544
+ if isinstance(self, TextualInversionLoaderMixin):
545
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
546
+
547
+ text_inputs = self.tokenizer(
548
+ prompt,
549
+ padding="max_length",
550
+ max_length=self.tokenizer.model_max_length,
551
+ truncation=True,
552
+ return_tensors="pt",
553
+ )
554
+ text_input_ids = text_inputs.input_ids
555
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
556
+
557
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
558
+ text_input_ids, untruncated_ids
559
+ ):
560
+ removed_text = self.tokenizer.batch_decode(
561
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
562
+ )
563
+ logger.warning(
564
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
565
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
566
+ )
567
+
568
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
569
+ attention_mask = text_inputs.attention_mask.to(device)
570
+ else:
571
+ attention_mask = None
572
+
573
+ if clip_skip is None:
574
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
575
+ prompt_embeds = prompt_embeds[0]
576
+ else:
577
+ prompt_embeds = self.text_encoder(
578
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
579
+ )
580
+ # Access the `hidden_states` first, that contains a tuple of
581
+ # all the hidden states from the encoder layers. Then index into
582
+ # the tuple to access the hidden states from the desired layer.
583
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
584
+ # We also need to apply the final LayerNorm here to not mess with the
585
+ # representations. The `last_hidden_states` that we typically use for
586
+ # obtaining the final prompt representations passes through the LayerNorm
587
+ # layer.
588
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
589
+
590
+ if self.text_encoder is not None:
591
+ prompt_embeds_dtype = self.text_encoder.dtype
592
+ elif self.unet is not None:
593
+ prompt_embeds_dtype = self.unet.dtype
594
+ else:
595
+ prompt_embeds_dtype = prompt_embeds.dtype
596
+
597
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
598
+
599
+ bs_embed, seq_len, _ = prompt_embeds.shape
600
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
601
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
602
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
603
+
604
+ # get unconditional embeddings for classifier free guidance
605
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
606
+ uncond_tokens: List[str]
607
+ if negative_prompt is None:
608
+ uncond_tokens = [""] * batch_size
609
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
610
+ raise TypeError(
611
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
612
+ f" {type(prompt)}."
613
+ )
614
+ elif isinstance(negative_prompt, str):
615
+ uncond_tokens = [negative_prompt]
616
+ elif batch_size != len(negative_prompt):
617
+ raise ValueError(
618
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
619
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
620
+ " the batch size of `prompt`."
621
+ )
622
+ else:
623
+ uncond_tokens = negative_prompt
624
+
625
+ # textual inversion: process multi-vector tokens if necessary
626
+ if isinstance(self, TextualInversionLoaderMixin):
627
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
628
+
629
+ max_length = prompt_embeds.shape[1]
630
+ uncond_input = self.tokenizer(
631
+ uncond_tokens,
632
+ padding="max_length",
633
+ max_length=max_length,
634
+ truncation=True,
635
+ return_tensors="pt",
636
+ )
637
+
638
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
639
+ attention_mask = uncond_input.attention_mask.to(device)
640
+ else:
641
+ attention_mask = None
642
+
643
+ negative_prompt_embeds = self.text_encoder(
644
+ uncond_input.input_ids.to(device),
645
+ attention_mask=attention_mask,
646
+ )
647
+ negative_prompt_embeds = negative_prompt_embeds[0]
648
+
649
+ if do_classifier_free_guidance:
650
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
651
+ seq_len = negative_prompt_embeds.shape[1]
652
+
653
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
654
+
655
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
656
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
657
+
658
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
659
+ # Retrieve the original scale by scaling back the LoRA layers
660
+ unscale_lora_layers(self.text_encoder, lora_scale)
661
+
662
+ return prompt_embeds, negative_prompt_embeds
663
+
664
+ def run_safety_checker(self, image, device, dtype):
665
+ if self.safety_checker is None:
666
+ has_nsfw_concept = None
667
+ else:
668
+ if torch.is_tensor(image):
669
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
670
+ else:
671
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
672
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
673
+ image, has_nsfw_concept = self.safety_checker(
674
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
675
+ )
676
+ return image, has_nsfw_concept
677
+
678
+ def decode_latents(self, latents):
679
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
680
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
681
+
682
+ latents = 1 / self.vae.config.scaling_factor * latents
683
+ image = self.vae.decode(latents, return_dict=False)[0]
684
+ image = (image / 2 + 0.5).clamp(0, 1)
685
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
686
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
687
+ return image
688
+
689
+ def prepare_extra_step_kwargs(self, generator, eta):
690
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
691
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
692
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
693
+ # and should be between [0, 1]
694
+
695
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
696
+ extra_step_kwargs = {}
697
+ if accepts_eta:
698
+ extra_step_kwargs["eta"] = eta
699
+
700
+ # check if the scheduler accepts generator
701
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
702
+ if accepts_generator:
703
+ extra_step_kwargs["generator"] = generator
704
+ return extra_step_kwargs
705
+
706
+ def check_inputs(
707
+ self,
708
+ prompt,
709
+ height,
710
+ width,
711
+ callback_steps,
712
+ negative_prompt=None,
713
+ prompt_embeds=None,
714
+ negative_prompt_embeds=None,
715
+ callback_on_step_end_tensor_inputs=None,
716
+ ):
717
+ if height % 8 != 0 or width % 8 != 0:
718
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
719
+
720
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
721
+ raise ValueError(
722
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
723
+ f" {type(callback_steps)}."
724
+ )
725
+ if callback_on_step_end_tensor_inputs is not None and not all(
726
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
727
+ ):
728
+ raise ValueError(
729
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
730
+ )
731
+
732
+ if prompt is not None and prompt_embeds is not None:
733
+ raise ValueError(
734
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
735
+ " only forward one of the two."
736
+ )
737
+ elif prompt is None and prompt_embeds is None:
738
+ raise ValueError(
739
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
740
+ )
741
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
742
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
743
+
744
+ if negative_prompt is not None and negative_prompt_embeds is not None:
745
+ raise ValueError(
746
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
747
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
748
+ )
749
+
750
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
751
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
752
+ raise ValueError(
753
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
754
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
755
+ f" {negative_prompt_embeds.shape}."
756
+ )
757
+
758
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
759
+ shape = (
760
+ batch_size,
761
+ num_channels_latents,
762
+ int(height) // self.vae_scale_factor,
763
+ int(width) // self.vae_scale_factor,
764
+ )
765
+ if isinstance(generator, list) and len(generator) != batch_size:
766
+ raise ValueError(
767
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
768
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
769
+ )
770
+
771
+ if latents is None:
772
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
773
+ else:
774
+ latents = latents.to(device)
775
+
776
+ # scale the initial noise by the standard deviation required by the scheduler
777
+ latents = latents * self.scheduler.init_noise_sigma
778
+ return latents
779
+
780
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
781
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
782
+ """
783
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
784
+
785
+ Args:
786
+ timesteps (`torch.Tensor`):
787
+ generate embedding vectors at these timesteps
788
+ embedding_dim (`int`, *optional*, defaults to 512):
789
+ dimension of the embeddings to generate
790
+ dtype:
791
+ data type of the generated embeddings
792
+
793
+ Returns:
794
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
795
+ """
796
+ assert len(w.shape) == 1
797
+ w = w * 1000.0
798
+
799
+ half_dim = embedding_dim // 2
800
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
801
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
802
+ emb = w.to(dtype)[:, None] * emb[None, :]
803
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
804
+ if embedding_dim % 2 == 1: # zero pad
805
+ emb = torch.nn.functional.pad(emb, (0, 1))
806
+ assert emb.shape == (w.shape[0], embedding_dim)
807
+ return emb
808
+
809
+ @property
810
+ def guidance_scale(self):
811
+ return self._guidance_scale
812
+
813
+ @property
814
+ def guidance_rescale(self):
815
+ return self._guidance_rescale
816
+
817
+ @property
818
+ def clip_skip(self):
819
+ return self._clip_skip
820
+
821
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
822
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
823
+ # corresponds to doing no classifier free guidance.
824
+ @property
825
+ def do_classifier_free_guidance(self):
826
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
827
+
828
+ @property
829
+ def cross_attention_kwargs(self):
830
+ return self._cross_attention_kwargs
831
+
832
+ @property
833
+ def num_timesteps(self):
834
+ return self._num_timesteps
835
+
836
+ @property
837
+ def interrupt(self):
838
+ return self._interrupt
839
+
840
+ @torch.no_grad()
841
+ def __call__(
842
+ self,
843
+ prompt: Union[str, List[str]] = None,
844
+ height: Optional[int] = None,
845
+ width: Optional[int] = None,
846
+ num_inference_steps: int = 50,
847
+ timesteps: List[int] = None,
848
+ guidance_scale: float = 7.5,
849
+ negative_prompt: Optional[Union[str, List[str]]] = None,
850
+ num_images_per_prompt: Optional[int] = 1,
851
+ eta: float = 0.0,
852
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
853
+ latents: Optional[torch.Tensor] = None,
854
+ prompt_embeds: Optional[torch.Tensor] = None,
855
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
856
+ image_embeds: Optional[torch.Tensor] = None,
857
+ output_type: Optional[str] = "pil",
858
+ return_dict: bool = True,
859
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
860
+ guidance_rescale: float = 0.0,
861
+ clip_skip: Optional[int] = None,
862
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
863
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
864
+ **kwargs,
865
+ ):
866
+ r"""
867
+ The call function to the pipeline for generation.
868
+
869
+ Args:
870
+ prompt (`str` or `List[str]`, *optional*):
871
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
872
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
873
+ The height in pixels of the generated image.
874
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
875
+ The width in pixels of the generated image.
876
+ num_inference_steps (`int`, *optional*, defaults to 50):
877
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
878
+ expense of slower inference.
879
+ timesteps (`List[int]`, *optional*):
880
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
881
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
882
+ passed will be used. Must be in descending order.
883
+ guidance_scale (`float`, *optional*, defaults to 7.5):
884
+ A higher guidance scale value encourages the model to generate images closely linked to the text
885
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
886
+ negative_prompt (`str` or `List[str]`, *optional*):
887
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
888
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
889
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
890
+ The number of images to generate per prompt.
891
+ eta (`float`, *optional*, defaults to 0.0):
892
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
893
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
894
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
895
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
896
+ generation deterministic.
897
+ latents (`torch.Tensor`, *optional*):
898
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
899
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
900
+ tensor is generated by sampling using the supplied random `generator`.
901
+ prompt_embeds (`torch.Tensor`, *optional*):
902
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
903
+ provided, text embeddings are generated from the `prompt` input argument.
904
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
905
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
906
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
907
+ image_embeds (`torch.Tensor`, *optional*):
908
+ Pre-generated image embeddings.
909
+ output_type (`str`, *optional*, defaults to `"pil"`):
910
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
911
+ return_dict (`bool`, *optional*, defaults to `True`):
912
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
913
+ plain tuple.
914
+ cross_attention_kwargs (`dict`, *optional*):
915
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
916
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
917
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
918
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
919
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
920
+ using zero terminal SNR.
921
+ clip_skip (`int`, *optional*):
922
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
923
+ the output of the pre-final layer will be used for computing the prompt embeddings.
924
+ callback_on_step_end (`Callable`, *optional*):
925
+ A function that calls at the end of each denoising steps during the inference. The function is called
926
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
927
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
928
+ `callback_on_step_end_tensor_inputs`.
929
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
930
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
931
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
932
+ `._callback_tensor_inputs` attribute of your pipeline class.
933
+
934
+ Examples:
935
+
936
+ Returns:
937
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
938
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
939
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
940
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
941
+ "not-safe-for-work" (nsfw) content.
942
+ """
943
+
944
+ callback = kwargs.pop("callback", None)
945
+ callback_steps = kwargs.pop("callback_steps", None)
946
+
947
+ if callback is not None:
948
+ deprecate(
949
+ "callback",
950
+ "1.0.0",
951
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
952
+ )
953
+ if callback_steps is not None:
954
+ deprecate(
955
+ "callback_steps",
956
+ "1.0.0",
957
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
958
+ )
959
+
960
+ # 0. Default height and width to unet
961
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
962
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
963
+ # to deal with lora scaling and other possible forward hooks
964
+
965
+ # 1. Check inputs. Raise error if not correct
966
+ self.check_inputs(
967
+ prompt,
968
+ height,
969
+ width,
970
+ callback_steps,
971
+ negative_prompt,
972
+ prompt_embeds,
973
+ negative_prompt_embeds,
974
+ callback_on_step_end_tensor_inputs,
975
+ )
976
+
977
+ self._guidance_scale = guidance_scale
978
+ self._guidance_rescale = guidance_rescale
979
+ self._clip_skip = clip_skip
980
+ self._cross_attention_kwargs = cross_attention_kwargs
981
+ self._interrupt = False
982
+
983
+ # 2. Define call parameters
984
+ if prompt is not None and isinstance(prompt, str):
985
+ batch_size = 1
986
+ elif prompt is not None and isinstance(prompt, list):
987
+ batch_size = len(prompt)
988
+ else:
989
+ batch_size = prompt_embeds.shape[0]
990
+
991
+ device = self._execution_device
992
+
993
+ # 3. Encode input prompt
994
+ lora_scale = (
995
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
996
+ )
997
+
998
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
999
+ prompt,
1000
+ device,
1001
+ num_images_per_prompt,
1002
+ self.do_classifier_free_guidance,
1003
+ negative_prompt,
1004
+ prompt_embeds=prompt_embeds,
1005
+ negative_prompt_embeds=negative_prompt_embeds,
1006
+ lora_scale=lora_scale,
1007
+ clip_skip=self.clip_skip,
1008
+ )
1009
+
1010
+ # For classifier free guidance, we need to do two forward passes.
1011
+ # Here we concatenate the unconditional and text embeddings into a single batch
1012
+ # to avoid doing two forward passes
1013
+ if self.do_classifier_free_guidance:
1014
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1015
+
1016
+ if image_embeds is not None:
1017
+ image_embeds = torch.stack([image_embeds] * num_images_per_prompt, dim=0).to(
1018
+ device=device, dtype=prompt_embeds.dtype
1019
+ )
1020
+ negative_image_embeds = torch.zeros_like(image_embeds)
1021
+ if self.do_classifier_free_guidance:
1022
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1023
+ image_embeds = [image_embeds]
1024
+ # 4. Prepare timesteps
1025
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1026
+
1027
+ # 5. Prepare latent variables
1028
+ num_channels_latents = self.unet.config.in_channels
1029
+ latents = self.prepare_latents(
1030
+ batch_size * num_images_per_prompt,
1031
+ num_channels_latents,
1032
+ height,
1033
+ width,
1034
+ prompt_embeds.dtype,
1035
+ device,
1036
+ generator,
1037
+ latents,
1038
+ )
1039
+
1040
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1041
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1042
+
1043
+ # 6.1 Add image embeds for IP-Adapter
1044
+ added_cond_kwargs = {"image_embeds": image_embeds} if image_embeds is not None else {}
1045
+
1046
+ # 6.2 Optionally get Guidance Scale Embedding
1047
+ timestep_cond = None
1048
+ if self.unet.config.time_cond_proj_dim is not None:
1049
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1050
+ timestep_cond = self.get_guidance_scale_embedding(
1051
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1052
+ ).to(device=device, dtype=latents.dtype)
1053
+
1054
+ # 7. Denoising loop
1055
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1056
+ self._num_timesteps = len(timesteps)
1057
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1058
+ for i, t in enumerate(timesteps):
1059
+ if self.interrupt:
1060
+ continue
1061
+
1062
+ # expand the latents if we are doing classifier free guidance
1063
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1064
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1065
+
1066
+ # predict the noise residual
1067
+ noise_pred = self.unet(
1068
+ latent_model_input,
1069
+ t,
1070
+ encoder_hidden_states=prompt_embeds,
1071
+ timestep_cond=timestep_cond,
1072
+ cross_attention_kwargs=self.cross_attention_kwargs,
1073
+ added_cond_kwargs=added_cond_kwargs,
1074
+ return_dict=False,
1075
+ )[0]
1076
+
1077
+ # perform guidance
1078
+ if self.do_classifier_free_guidance:
1079
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1080
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1081
+
1082
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1083
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1084
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1085
+
1086
+ # compute the previous noisy sample x_t -> x_t-1
1087
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1088
+
1089
+ if callback_on_step_end is not None:
1090
+ callback_kwargs = {}
1091
+ for k in callback_on_step_end_tensor_inputs:
1092
+ callback_kwargs[k] = locals()[k]
1093
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1094
+
1095
+ latents = callback_outputs.pop("latents", latents)
1096
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1097
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1098
+
1099
+ # call the callback, if provided
1100
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1101
+ progress_bar.update()
1102
+ if callback is not None and i % callback_steps == 0:
1103
+ step_idx = i // getattr(self.scheduler, "order", 1)
1104
+ callback(step_idx, t, latents)
1105
+
1106
+ if not output_type == "latent":
1107
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1108
+ 0
1109
+ ]
1110
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1111
+ else:
1112
+ image = latents
1113
+ has_nsfw_concept = None
1114
+
1115
+ if has_nsfw_concept is None:
1116
+ do_denormalize = [True] * image.shape[0]
1117
+ else:
1118
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1119
+
1120
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1121
+
1122
+ # Offload all models
1123
+ self.maybe_free_model_hooks()
1124
+
1125
+ if not return_dict:
1126
+ return (image, has_nsfw_concept)
1127
+
1128
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/kohya_hires_fix.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.utils.checkpoint
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
21
+
22
+ from diffusers.configuration_utils import register_to_config
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from diffusers.models.autoencoders import AutoencoderKL
25
+ from diffusers.models.unets.unet_2d_condition import UNet2DConditionModel, UNet2DConditionOutput
26
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline
27
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
28
+ from diffusers.schedulers import KarrasDiffusionSchedulers
29
+ from diffusers.utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ class UNet2DConditionModelHighResFix(UNet2DConditionModel):
36
+ r"""
37
+ A conditional 2D UNet model that applies Kohya fix proposed for high resolution image generation.
38
+
39
+ This model inherits from [`UNet2DConditionModel`]. Check the superclass documentation for learning about all the parameters.
40
+
41
+ Parameters:
42
+ high_res_fix (`List[Dict]`, *optional*, defaults to `[{'timestep': 600, 'scale_factor': 0.5, 'block_num': 1}]`):
43
+ Enables Kohya fix for high resolution generation. The activation maps are scaled based on the scale_factor up to the timestep at specified block_num.
44
+ """
45
+
46
+ _supports_gradient_checkpointing = True
47
+
48
+ @register_to_config
49
+ def __init__(self, high_res_fix: List[Dict] = [{"timestep": 600, "scale_factor": 0.5, "block_num": 1}], **kwargs):
50
+ super().__init__(**kwargs)
51
+ if high_res_fix:
52
+ self.config.high_res_fix = sorted(high_res_fix, key=lambda x: x["timestep"], reverse=True)
53
+
54
+ @classmethod
55
+ def _resize(cls, sample, target=None, scale_factor=1, mode="bicubic"):
56
+ dtype = sample.dtype
57
+ if dtype == torch.bfloat16:
58
+ sample = sample.to(torch.float32)
59
+
60
+ if target is not None:
61
+ if sample.shape[-2:] != target.shape[-2:]:
62
+ sample = nn.functional.interpolate(sample, size=target.shape[-2:], mode=mode, align_corners=False)
63
+ elif scale_factor != 1:
64
+ sample = nn.functional.interpolate(sample, scale_factor=scale_factor, mode=mode, align_corners=False)
65
+
66
+ return sample.to(dtype)
67
+
68
+ def forward(
69
+ self,
70
+ sample: torch.FloatTensor,
71
+ timestep: Union[torch.Tensor, float, int],
72
+ encoder_hidden_states: torch.Tensor,
73
+ class_labels: Optional[torch.Tensor] = None,
74
+ timestep_cond: Optional[torch.Tensor] = None,
75
+ attention_mask: Optional[torch.Tensor] = None,
76
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
77
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
78
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
79
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
80
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
81
+ encoder_attention_mask: Optional[torch.Tensor] = None,
82
+ return_dict: bool = True,
83
+ ) -> Union[UNet2DConditionOutput, Tuple]:
84
+ r"""
85
+ The [`UNet2DConditionModel`] forward method.
86
+
87
+ Args:
88
+ sample (`torch.FloatTensor`):
89
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
90
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
91
+ encoder_hidden_states (`torch.FloatTensor`):
92
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
93
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
94
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
95
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
96
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
97
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
98
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
99
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
100
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
101
+ negative values to the attention scores corresponding to "discard" tokens.
102
+ cross_attention_kwargs (`dict`, *optional*):
103
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
104
+ `self.processor` in
105
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
106
+ added_cond_kwargs: (`dict`, *optional*):
107
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
108
+ are passed along to the UNet blocks.
109
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
110
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
111
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
112
+ A tensor that if specified is added to the residual of the middle unet block.
113
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
114
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
115
+ encoder_attention_mask (`torch.Tensor`):
116
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
117
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
118
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
119
+ return_dict (`bool`, *optional*, defaults to `True`):
120
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
121
+ tuple.
122
+
123
+ Returns:
124
+ [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
125
+ If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,
126
+ otherwise a `tuple` is returned where the first element is the sample tensor.
127
+ """
128
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
129
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
130
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
131
+ # on the fly if necessary.
132
+ default_overall_up_factor = 2**self.num_upsamplers
133
+
134
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
135
+ forward_upsample_size = False
136
+ upsample_size = None
137
+
138
+ for dim in sample.shape[-2:]:
139
+ if dim % default_overall_up_factor != 0:
140
+ # Forward upsample size to force interpolation output size.
141
+ forward_upsample_size = True
142
+ break
143
+
144
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
145
+ # expects mask of shape:
146
+ # [batch, key_tokens]
147
+ # adds singleton query_tokens dimension:
148
+ # [batch, 1, key_tokens]
149
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
150
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
151
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
152
+ if attention_mask is not None:
153
+ # assume that mask is expressed as:
154
+ # (1 = keep, 0 = discard)
155
+ # convert mask into a bias that can be added to attention scores:
156
+ # (keep = +0, discard = -10000.0)
157
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
158
+ attention_mask = attention_mask.unsqueeze(1)
159
+
160
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
161
+ if encoder_attention_mask is not None:
162
+ encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0
163
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
164
+
165
+ # 0. center input if necessary
166
+ if self.config.center_input_sample:
167
+ sample = 2 * sample - 1.0
168
+
169
+ # 1. time
170
+ t_emb = self.get_time_embed(sample=sample, timestep=timestep)
171
+ emb = self.time_embedding(t_emb, timestep_cond)
172
+ aug_emb = None
173
+
174
+ class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)
175
+ if class_emb is not None:
176
+ if self.config.class_embeddings_concat:
177
+ emb = torch.cat([emb, class_emb], dim=-1)
178
+ else:
179
+ emb = emb + class_emb
180
+
181
+ aug_emb = self.get_aug_embed(
182
+ emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
183
+ )
184
+ if self.config.addition_embed_type == "image_hint":
185
+ aug_emb, hint = aug_emb
186
+ sample = torch.cat([sample, hint], dim=1)
187
+
188
+ emb = emb + aug_emb if aug_emb is not None else emb
189
+
190
+ if self.time_embed_act is not None:
191
+ emb = self.time_embed_act(emb)
192
+
193
+ encoder_hidden_states = self.process_encoder_hidden_states(
194
+ encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
195
+ )
196
+
197
+ # 2. pre-process
198
+ sample = self.conv_in(sample)
199
+
200
+ # 2.5 GLIGEN position net
201
+ if cross_attention_kwargs is not None and cross_attention_kwargs.get("gligen", None) is not None:
202
+ cross_attention_kwargs = cross_attention_kwargs.copy()
203
+ gligen_args = cross_attention_kwargs.pop("gligen")
204
+ cross_attention_kwargs["gligen"] = {"objs": self.position_net(**gligen_args)}
205
+
206
+ # 3. down
207
+ # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated
208
+ # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.
209
+ if cross_attention_kwargs is not None:
210
+ cross_attention_kwargs = cross_attention_kwargs.copy()
211
+ lora_scale = cross_attention_kwargs.pop("scale", 1.0)
212
+ else:
213
+ lora_scale = 1.0
214
+
215
+ if USE_PEFT_BACKEND:
216
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
217
+ scale_lora_layers(self, lora_scale)
218
+
219
+ is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None
220
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
221
+ is_adapter = down_intrablock_additional_residuals is not None
222
+ # maintain backward compatibility for legacy usage, where
223
+ # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
224
+ # but can only use one or the other
225
+ if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:
226
+ deprecate(
227
+ "T2I should not use down_block_additional_residuals",
228
+ "1.3.0",
229
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
230
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
231
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
232
+ standard_warn=False,
233
+ )
234
+ down_intrablock_additional_residuals = down_block_additional_residuals
235
+ is_adapter = True
236
+
237
+ down_block_res_samples = (sample,)
238
+ for down_i, downsample_block in enumerate(self.down_blocks):
239
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
240
+ # For t2i-adapter CrossAttnDownBlock2D
241
+ additional_residuals = {}
242
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
243
+ additional_residuals["additional_residuals"] = down_intrablock_additional_residuals.pop(0)
244
+
245
+ sample, res_samples = downsample_block(
246
+ hidden_states=sample,
247
+ temb=emb,
248
+ encoder_hidden_states=encoder_hidden_states,
249
+ attention_mask=attention_mask,
250
+ cross_attention_kwargs=cross_attention_kwargs,
251
+ encoder_attention_mask=encoder_attention_mask,
252
+ **additional_residuals,
253
+ )
254
+
255
+ else:
256
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
257
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
258
+ sample += down_intrablock_additional_residuals.pop(0)
259
+
260
+ down_block_res_samples += res_samples
261
+
262
+ # kohya high res fix
263
+ if self.config.high_res_fix:
264
+ for high_res_fix in self.config.high_res_fix:
265
+ if timestep > high_res_fix["timestep"] and down_i == high_res_fix["block_num"]:
266
+ sample = self.__class__._resize(sample, scale_factor=high_res_fix["scale_factor"])
267
+ break
268
+
269
+ if is_controlnet:
270
+ new_down_block_res_samples = ()
271
+
272
+ for down_block_res_sample, down_block_additional_residual in zip(
273
+ down_block_res_samples, down_block_additional_residuals
274
+ ):
275
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
276
+ new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
277
+
278
+ down_block_res_samples = new_down_block_res_samples
279
+
280
+ # 4. mid
281
+ if self.mid_block is not None:
282
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
283
+ sample = self.mid_block(
284
+ sample,
285
+ emb,
286
+ encoder_hidden_states=encoder_hidden_states,
287
+ attention_mask=attention_mask,
288
+ cross_attention_kwargs=cross_attention_kwargs,
289
+ encoder_attention_mask=encoder_attention_mask,
290
+ )
291
+ else:
292
+ sample = self.mid_block(sample, emb)
293
+
294
+ # To support T2I-Adapter-XL
295
+ if (
296
+ is_adapter
297
+ and len(down_intrablock_additional_residuals) > 0
298
+ and sample.shape == down_intrablock_additional_residuals[0].shape
299
+ ):
300
+ sample += down_intrablock_additional_residuals.pop(0)
301
+
302
+ if is_controlnet:
303
+ sample = sample + mid_block_additional_residual
304
+
305
+ # 5. up
306
+ for i, upsample_block in enumerate(self.up_blocks):
307
+ is_final_block = i == len(self.up_blocks) - 1
308
+
309
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
310
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
311
+
312
+ # up scaling of kohya high res fix
313
+ if self.config.high_res_fix is not None:
314
+ if res_samples[0].shape[-2:] != sample.shape[-2:]:
315
+ sample = self.__class__._resize(sample, target=res_samples[0])
316
+ res_samples_up_sampled = (res_samples[0],)
317
+ for res_sample in res_samples[1:]:
318
+ res_samples_up_sampled += (self.__class__._resize(res_sample, target=res_samples[0]),)
319
+ res_samples = res_samples_up_sampled
320
+
321
+ # if we have not reached the final block and need to forward the
322
+ # upsample size, we do it here
323
+ if not is_final_block and forward_upsample_size:
324
+ upsample_size = down_block_res_samples[-1].shape[2:]
325
+
326
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
327
+ sample = upsample_block(
328
+ hidden_states=sample,
329
+ temb=emb,
330
+ res_hidden_states_tuple=res_samples,
331
+ encoder_hidden_states=encoder_hidden_states,
332
+ cross_attention_kwargs=cross_attention_kwargs,
333
+ upsample_size=upsample_size,
334
+ attention_mask=attention_mask,
335
+ encoder_attention_mask=encoder_attention_mask,
336
+ )
337
+ else:
338
+ sample = upsample_block(
339
+ hidden_states=sample,
340
+ temb=emb,
341
+ res_hidden_states_tuple=res_samples,
342
+ upsample_size=upsample_size,
343
+ )
344
+
345
+ # 6. post-process
346
+ if self.conv_norm_out:
347
+ sample = self.conv_norm_out(sample)
348
+ sample = self.conv_act(sample)
349
+ sample = self.conv_out(sample)
350
+
351
+ if USE_PEFT_BACKEND:
352
+ # remove `lora_scale` from each PEFT layer
353
+ unscale_lora_layers(self, lora_scale)
354
+
355
+ if not return_dict:
356
+ return (sample,)
357
+
358
+ return UNet2DConditionOutput(sample=sample)
359
+
360
+ @classmethod
361
+ def from_unet(cls, unet: UNet2DConditionModel, high_res_fix: list):
362
+ config = dict((unet.config))
363
+ config["high_res_fix"] = high_res_fix
364
+ unet_high_res = cls(**config)
365
+ unet_high_res.load_state_dict(unet.state_dict())
366
+ unet_high_res.to(unet.dtype)
367
+ return unet_high_res
368
+
369
+
370
+ EXAMPLE_DOC_STRING = """
371
+ Examples:
372
+ ```py
373
+ >>> import torch
374
+ >>> from diffusers import DiffusionPipeline
375
+
376
+ >>> pipe = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4",
377
+ custom_pipeline="kohya_hires_fix",
378
+ torch_dtype=torch.float16,
379
+ high_res_fix=[{'timestep': 600,
380
+ 'scale_factor': 0.5,
381
+ 'block_num': 1}])
382
+ >>> pipe = pipe.to("cuda")
383
+
384
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
385
+ >>> image = pipe(prompt, height=1000, width=1600).images[0]
386
+ ```
387
+ """
388
+
389
+
390
+ class StableDiffusionHighResFixPipeline(StableDiffusionPipeline):
391
+ r"""
392
+ Pipeline for text-to-image generation using Stable Diffusion with Kohya fix for high resolution generation.
393
+
394
+ This model inherits from [`StableDiffusionPipeline`]. Check the superclass documentation for the generic methods.
395
+
396
+ The pipeline also inherits the following loading methods:
397
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
398
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
399
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
400
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
401
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
402
+
403
+ Args:
404
+ vae ([`AutoencoderKL`]):
405
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
406
+ text_encoder ([`~transformers.CLIPTextModel`]):
407
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
408
+ tokenizer ([`~transformers.CLIPTokenizer`]):
409
+ A `CLIPTokenizer` to tokenize text.
410
+ unet ([`UNet2DConditionModel`]):
411
+ A `UNet2DConditionModel` to denoise the encoded image latents.
412
+ scheduler ([`SchedulerMixin`]):
413
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
414
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
415
+ safety_checker ([`StableDiffusionSafetyChecker`]):
416
+ Classification module that estimates whether generated images could be considered offensive or harmful.
417
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
418
+ about a model's potential harms.
419
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
420
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
421
+ high_res_fix (`List[Dict]`, *optional*, defaults to `[{'timestep': 600, 'scale_factor': 0.5, 'block_num': 1}]`):
422
+ Enables Kohya fix for high resolution generation. The activation maps are scaled based on the scale_factor up to the timestep at specified block_num.
423
+ """
424
+
425
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
426
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
427
+ _exclude_from_cpu_offload = ["safety_checker"]
428
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
429
+
430
+ def __init__(
431
+ self,
432
+ vae: AutoencoderKL,
433
+ text_encoder: CLIPTextModel,
434
+ tokenizer: CLIPTokenizer,
435
+ unet: UNet2DConditionModel,
436
+ scheduler: KarrasDiffusionSchedulers,
437
+ safety_checker: StableDiffusionSafetyChecker,
438
+ feature_extractor: CLIPImageProcessor,
439
+ image_encoder: CLIPVisionModelWithProjection = None,
440
+ requires_safety_checker: bool = True,
441
+ high_res_fix: List[Dict] = [{"timestep": 600, "scale_factor": 0.5, "block_num": 1}],
442
+ ):
443
+ super().__init__(
444
+ vae=vae,
445
+ text_encoder=text_encoder,
446
+ tokenizer=tokenizer,
447
+ unet=unet,
448
+ scheduler=scheduler,
449
+ safety_checker=safety_checker,
450
+ feature_extractor=feature_extractor,
451
+ image_encoder=image_encoder,
452
+ requires_safety_checker=requires_safety_checker,
453
+ )
454
+
455
+ unet = UNet2DConditionModelHighResFix.from_unet(unet=unet, high_res_fix=high_res_fix)
456
+ self.register_modules(
457
+ vae=vae,
458
+ text_encoder=text_encoder,
459
+ tokenizer=tokenizer,
460
+ unet=unet,
461
+ scheduler=scheduler,
462
+ safety_checker=safety_checker,
463
+ feature_extractor=feature_extractor,
464
+ image_encoder=image_encoder,
465
+ )
466
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
467
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
468
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
v0.32.0/latent_consistency_img2img.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stanford University Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import PIL.Image
24
+ import torch
25
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
26
+
27
+ from diffusers import AutoencoderKL, ConfigMixin, DiffusionPipeline, SchedulerMixin, UNet2DConditionModel, logging
28
+ from diffusers.configuration_utils import register_to_config
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
31
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
32
+ from diffusers.utils import BaseOutput
33
+ from diffusers.utils.torch_utils import randn_tensor
34
+
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+
39
+ class LatentConsistencyModelImg2ImgPipeline(DiffusionPipeline):
40
+ _optional_components = ["scheduler"]
41
+
42
+ def __init__(
43
+ self,
44
+ vae: AutoencoderKL,
45
+ text_encoder: CLIPTextModel,
46
+ tokenizer: CLIPTokenizer,
47
+ unet: UNet2DConditionModel,
48
+ scheduler: "LCMSchedulerWithTimestamp",
49
+ safety_checker: StableDiffusionSafetyChecker,
50
+ feature_extractor: CLIPImageProcessor,
51
+ requires_safety_checker: bool = True,
52
+ ):
53
+ super().__init__()
54
+
55
+ scheduler = (
56
+ scheduler
57
+ if scheduler is not None
58
+ else LCMSchedulerWithTimestamp(
59
+ beta_start=0.00085, beta_end=0.0120, beta_schedule="scaled_linear", prediction_type="epsilon"
60
+ )
61
+ )
62
+
63
+ self.register_modules(
64
+ vae=vae,
65
+ text_encoder=text_encoder,
66
+ tokenizer=tokenizer,
67
+ unet=unet,
68
+ scheduler=scheduler,
69
+ safety_checker=safety_checker,
70
+ feature_extractor=feature_extractor,
71
+ )
72
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
73
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
74
+
75
+ def _encode_prompt(
76
+ self,
77
+ prompt,
78
+ device,
79
+ num_images_per_prompt,
80
+ prompt_embeds: None,
81
+ ):
82
+ r"""
83
+ Encodes the prompt into text encoder hidden states.
84
+ Args:
85
+ prompt (`str` or `List[str]`, *optional*):
86
+ prompt to be encoded
87
+ device: (`torch.device`):
88
+ torch device
89
+ num_images_per_prompt (`int`):
90
+ number of images that should be generated per prompt
91
+ prompt_embeds (`torch.Tensor`, *optional*):
92
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
93
+ provided, text embeddings will be generated from `prompt` input argument.
94
+ """
95
+
96
+ if prompt is not None and isinstance(prompt, str):
97
+ pass
98
+ elif prompt is not None and isinstance(prompt, list):
99
+ len(prompt)
100
+ else:
101
+ prompt_embeds.shape[0]
102
+
103
+ if prompt_embeds is None:
104
+ text_inputs = self.tokenizer(
105
+ prompt,
106
+ padding="max_length",
107
+ max_length=self.tokenizer.model_max_length,
108
+ truncation=True,
109
+ return_tensors="pt",
110
+ )
111
+ text_input_ids = text_inputs.input_ids
112
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
113
+
114
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
115
+ text_input_ids, untruncated_ids
116
+ ):
117
+ removed_text = self.tokenizer.batch_decode(
118
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
119
+ )
120
+ logger.warning(
121
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
122
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
123
+ )
124
+
125
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
126
+ attention_mask = text_inputs.attention_mask.to(device)
127
+ else:
128
+ attention_mask = None
129
+
130
+ prompt_embeds = self.text_encoder(
131
+ text_input_ids.to(device),
132
+ attention_mask=attention_mask,
133
+ )
134
+ prompt_embeds = prompt_embeds[0]
135
+
136
+ if self.text_encoder is not None:
137
+ prompt_embeds_dtype = self.text_encoder.dtype
138
+ elif self.unet is not None:
139
+ prompt_embeds_dtype = self.unet.dtype
140
+ else:
141
+ prompt_embeds_dtype = prompt_embeds.dtype
142
+
143
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
144
+
145
+ bs_embed, seq_len, _ = prompt_embeds.shape
146
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
147
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
148
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
149
+
150
+ # Don't need to get uncond prompt embedding because of LCM Guided Distillation
151
+ return prompt_embeds
152
+
153
+ def run_safety_checker(self, image, device, dtype):
154
+ if self.safety_checker is None:
155
+ has_nsfw_concept = None
156
+ else:
157
+ if torch.is_tensor(image):
158
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
159
+ else:
160
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
161
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
162
+ image, has_nsfw_concept = self.safety_checker(
163
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
164
+ )
165
+ return image, has_nsfw_concept
166
+
167
+ def prepare_latents(
168
+ self,
169
+ image,
170
+ timestep,
171
+ batch_size,
172
+ num_channels_latents,
173
+ height,
174
+ width,
175
+ dtype,
176
+ device,
177
+ latents=None,
178
+ generator=None,
179
+ ):
180
+ shape = (
181
+ batch_size,
182
+ num_channels_latents,
183
+ int(height) // self.vae_scale_factor,
184
+ int(width) // self.vae_scale_factor,
185
+ )
186
+
187
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
188
+ raise ValueError(
189
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
190
+ )
191
+
192
+ image = image.to(device=device, dtype=dtype)
193
+
194
+ # batch_size = batch_size * num_images_per_prompt
195
+
196
+ if image.shape[1] == 4:
197
+ init_latents = image
198
+
199
+ else:
200
+ if isinstance(generator, list) and len(generator) != batch_size:
201
+ raise ValueError(
202
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
203
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
204
+ )
205
+
206
+ elif isinstance(generator, list):
207
+ init_latents = [
208
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator[i]) for i in range(batch_size)
209
+ ]
210
+ init_latents = torch.cat(init_latents, dim=0)
211
+ else:
212
+ init_latents = self.vae.encode(image).latent_dist.sample(generator)
213
+
214
+ init_latents = self.vae.config.scaling_factor * init_latents
215
+
216
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
217
+ # expand init_latents for batch_size
218
+ (
219
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
220
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
221
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
222
+ " your script to pass as many initial images as text prompts to suppress this warning."
223
+ )
224
+ # deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
225
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
226
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
227
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
228
+ raise ValueError(
229
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
230
+ )
231
+ else:
232
+ init_latents = torch.cat([init_latents], dim=0)
233
+
234
+ shape = init_latents.shape
235
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
236
+
237
+ # get latents
238
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
239
+ latents = init_latents
240
+
241
+ return latents
242
+
243
+ def get_w_embedding(self, w, embedding_dim=512, dtype=torch.float32):
244
+ """
245
+ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
246
+ Args:
247
+ timesteps: torch.Tensor: generate embedding vectors at these timesteps
248
+ embedding_dim: int: dimension of the embeddings to generate
249
+ dtype: data type of the generated embeddings
250
+ Returns:
251
+ embedding vectors with shape `(len(timesteps), embedding_dim)`
252
+ """
253
+ assert len(w.shape) == 1
254
+ w = w * 1000.0
255
+
256
+ half_dim = embedding_dim // 2
257
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
258
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
259
+ emb = w.to(dtype)[:, None] * emb[None, :]
260
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
261
+ if embedding_dim % 2 == 1: # zero pad
262
+ emb = torch.nn.functional.pad(emb, (0, 1))
263
+ assert emb.shape == (w.shape[0], embedding_dim)
264
+ return emb
265
+
266
+ def get_timesteps(self, num_inference_steps, strength, device):
267
+ # get the original timestep using init_timestep
268
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
269
+
270
+ t_start = max(num_inference_steps - init_timestep, 0)
271
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
272
+
273
+ return timesteps, num_inference_steps - t_start
274
+
275
+ @torch.no_grad()
276
+ def __call__(
277
+ self,
278
+ prompt: Union[str, List[str]] = None,
279
+ image: PipelineImageInput = None,
280
+ strength: float = 0.8,
281
+ height: Optional[int] = 768,
282
+ width: Optional[int] = 768,
283
+ guidance_scale: float = 7.5,
284
+ num_images_per_prompt: Optional[int] = 1,
285
+ latents: Optional[torch.Tensor] = None,
286
+ num_inference_steps: int = 4,
287
+ lcm_origin_steps: int = 50,
288
+ prompt_embeds: Optional[torch.Tensor] = None,
289
+ output_type: Optional[str] = "pil",
290
+ return_dict: bool = True,
291
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
292
+ ):
293
+ # 0. Default height and width to unet
294
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
295
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
296
+
297
+ # 2. Define call parameters
298
+ if prompt is not None and isinstance(prompt, str):
299
+ batch_size = 1
300
+ elif prompt is not None and isinstance(prompt, list):
301
+ batch_size = len(prompt)
302
+ else:
303
+ batch_size = prompt_embeds.shape[0]
304
+
305
+ device = self._execution_device
306
+ # do_classifier_free_guidance = guidance_scale > 0.0 # In LCM Implementation: cfg_noise = noise_cond + cfg_scale * (noise_cond - noise_uncond) , (cfg_scale > 0.0 using CFG)
307
+
308
+ # 3. Encode input prompt
309
+ prompt_embeds = self._encode_prompt(
310
+ prompt,
311
+ device,
312
+ num_images_per_prompt,
313
+ prompt_embeds=prompt_embeds,
314
+ )
315
+
316
+ # 3.5 encode image
317
+ image = self.image_processor.preprocess(image)
318
+
319
+ # 4. Prepare timesteps
320
+ self.scheduler.set_timesteps(strength, num_inference_steps, lcm_origin_steps)
321
+ # timesteps = self.scheduler.timesteps
322
+ # timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, 1.0, device)
323
+ timesteps = self.scheduler.timesteps
324
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
325
+
326
+ print("timesteps: ", timesteps)
327
+
328
+ # 5. Prepare latent variable
329
+ num_channels_latents = self.unet.config.in_channels
330
+ if latents is None:
331
+ latents = self.prepare_latents(
332
+ image,
333
+ latent_timestep,
334
+ batch_size * num_images_per_prompt,
335
+ num_channels_latents,
336
+ height,
337
+ width,
338
+ prompt_embeds.dtype,
339
+ device,
340
+ latents,
341
+ )
342
+ bs = batch_size * num_images_per_prompt
343
+
344
+ # 6. Get Guidance Scale Embedding
345
+ w = torch.tensor(guidance_scale).repeat(bs)
346
+ w_embedding = self.get_w_embedding(w, embedding_dim=256).to(device=device, dtype=latents.dtype)
347
+
348
+ # 7. LCM MultiStep Sampling Loop:
349
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
350
+ for i, t in enumerate(timesteps):
351
+ ts = torch.full((bs,), t, device=device, dtype=torch.long)
352
+ latents = latents.to(prompt_embeds.dtype)
353
+
354
+ # model prediction (v-prediction, eps, x)
355
+ model_pred = self.unet(
356
+ latents,
357
+ ts,
358
+ timestep_cond=w_embedding,
359
+ encoder_hidden_states=prompt_embeds,
360
+ cross_attention_kwargs=cross_attention_kwargs,
361
+ return_dict=False,
362
+ )[0]
363
+
364
+ # compute the previous noisy sample x_t -> x_t-1
365
+ latents, denoised = self.scheduler.step(model_pred, i, t, latents, return_dict=False)
366
+
367
+ # # call the callback, if provided
368
+ # if i == len(timesteps) - 1:
369
+ progress_bar.update()
370
+
371
+ denoised = denoised.to(prompt_embeds.dtype)
372
+ if not output_type == "latent":
373
+ image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
374
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
375
+ else:
376
+ image = denoised
377
+ has_nsfw_concept = None
378
+
379
+ if has_nsfw_concept is None:
380
+ do_denormalize = [True] * image.shape[0]
381
+ else:
382
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
383
+
384
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
385
+
386
+ if not return_dict:
387
+ return (image, has_nsfw_concept)
388
+
389
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
390
+
391
+
392
+ @dataclass
393
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
394
+ class LCMSchedulerOutput(BaseOutput):
395
+ """
396
+ Output class for the scheduler's `step` function output.
397
+ Args:
398
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
399
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
400
+ denoising loop.
401
+ pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
402
+ The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
403
+ `pred_original_sample` can be used to preview progress or for guidance.
404
+ """
405
+
406
+ prev_sample: torch.Tensor
407
+ denoised: Optional[torch.Tensor] = None
408
+
409
+
410
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
411
+ def betas_for_alpha_bar(
412
+ num_diffusion_timesteps,
413
+ max_beta=0.999,
414
+ alpha_transform_type="cosine",
415
+ ):
416
+ """
417
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
418
+ (1-beta) over time from t = [0,1].
419
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
420
+ to that part of the diffusion process.
421
+ Args:
422
+ num_diffusion_timesteps (`int`): the number of betas to produce.
423
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
424
+ prevent singularities.
425
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
426
+ Choose from `cosine` or `exp`
427
+ Returns:
428
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
429
+ """
430
+ if alpha_transform_type == "cosine":
431
+
432
+ def alpha_bar_fn(t):
433
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
434
+
435
+ elif alpha_transform_type == "exp":
436
+
437
+ def alpha_bar_fn(t):
438
+ return math.exp(t * -12.0)
439
+
440
+ else:
441
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
442
+
443
+ betas = []
444
+ for i in range(num_diffusion_timesteps):
445
+ t1 = i / num_diffusion_timesteps
446
+ t2 = (i + 1) / num_diffusion_timesteps
447
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
448
+ return torch.tensor(betas, dtype=torch.float32)
449
+
450
+
451
+ def rescale_zero_terminal_snr(betas):
452
+ """
453
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
454
+ Args:
455
+ betas (`torch.Tensor`):
456
+ the betas that the scheduler is being initialized with.
457
+ Returns:
458
+ `torch.Tensor`: rescaled betas with zero terminal SNR
459
+ """
460
+ # Convert betas to alphas_bar_sqrt
461
+ alphas = 1.0 - betas
462
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
463
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
464
+
465
+ # Store old values.
466
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
467
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
468
+
469
+ # Shift so the last timestep is zero.
470
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
471
+
472
+ # Scale so the first timestep is back to the old value.
473
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
474
+
475
+ # Convert alphas_bar_sqrt to betas
476
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
477
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
478
+ alphas = torch.cat([alphas_bar[0:1], alphas])
479
+ betas = 1 - alphas
480
+
481
+ return betas
482
+
483
+
484
+ class LCMSchedulerWithTimestamp(SchedulerMixin, ConfigMixin):
485
+ """
486
+ This class modifies LCMScheduler to add a timestamp argument to set_timesteps
487
+
488
+
489
+ `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
490
+ non-Markovian guidance.
491
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
492
+ methods the library implements for all schedulers such as loading and saving.
493
+ Args:
494
+ num_train_timesteps (`int`, defaults to 1000):
495
+ The number of diffusion steps to train the model.
496
+ beta_start (`float`, defaults to 0.0001):
497
+ The starting `beta` value of inference.
498
+ beta_end (`float`, defaults to 0.02):
499
+ The final `beta` value.
500
+ beta_schedule (`str`, defaults to `"linear"`):
501
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
502
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
503
+ trained_betas (`np.ndarray`, *optional*):
504
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
505
+ clip_sample (`bool`, defaults to `True`):
506
+ Clip the predicted sample for numerical stability.
507
+ clip_sample_range (`float`, defaults to 1.0):
508
+ The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
509
+ set_alpha_to_one (`bool`, defaults to `True`):
510
+ Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
511
+ there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
512
+ otherwise it uses the alpha value at step 0.
513
+ steps_offset (`int`, defaults to 0):
514
+ An offset added to the inference steps, as required by some model families.
515
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
516
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
517
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
518
+ Video](https://imagen.research.google/video/paper.pdf) paper).
519
+ thresholding (`bool`, defaults to `False`):
520
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
521
+ as Stable Diffusion.
522
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
523
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
524
+ sample_max_value (`float`, defaults to 1.0):
525
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
526
+ timestep_spacing (`str`, defaults to `"leading"`):
527
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
528
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
529
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
530
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
531
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
532
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
533
+ """
534
+
535
+ # _compatibles = [e.name for e in KarrasDiffusionSchedulers]
536
+ order = 1
537
+
538
+ @register_to_config
539
+ def __init__(
540
+ self,
541
+ num_train_timesteps: int = 1000,
542
+ beta_start: float = 0.0001,
543
+ beta_end: float = 0.02,
544
+ beta_schedule: str = "linear",
545
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
546
+ clip_sample: bool = True,
547
+ set_alpha_to_one: bool = True,
548
+ steps_offset: int = 0,
549
+ prediction_type: str = "epsilon",
550
+ thresholding: bool = False,
551
+ dynamic_thresholding_ratio: float = 0.995,
552
+ clip_sample_range: float = 1.0,
553
+ sample_max_value: float = 1.0,
554
+ timestep_spacing: str = "leading",
555
+ rescale_betas_zero_snr: bool = False,
556
+ ):
557
+ if trained_betas is not None:
558
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
559
+ elif beta_schedule == "linear":
560
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
561
+ elif beta_schedule == "scaled_linear":
562
+ # this schedule is very specific to the latent diffusion model.
563
+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
564
+ elif beta_schedule == "squaredcos_cap_v2":
565
+ # Glide cosine schedule
566
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
567
+ else:
568
+ raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
569
+
570
+ # Rescale for zero SNR
571
+ if rescale_betas_zero_snr:
572
+ self.betas = rescale_zero_terminal_snr(self.betas)
573
+
574
+ self.alphas = 1.0 - self.betas
575
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
576
+
577
+ # At every step in ddim, we are looking into the previous alphas_cumprod
578
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
579
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
580
+ # whether we use the final alpha of the "non-previous" one.
581
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
582
+
583
+ # standard deviation of the initial noise distribution
584
+ self.init_noise_sigma = 1.0
585
+
586
+ # setable values
587
+ self.num_inference_steps = None
588
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
589
+
590
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
591
+ """
592
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
593
+ current timestep.
594
+ Args:
595
+ sample (`torch.Tensor`):
596
+ The input sample.
597
+ timestep (`int`, *optional*):
598
+ The current timestep in the diffusion chain.
599
+ Returns:
600
+ `torch.Tensor`:
601
+ A scaled input sample.
602
+ """
603
+ return sample
604
+
605
+ def _get_variance(self, timestep, prev_timestep):
606
+ alpha_prod_t = self.alphas_cumprod[timestep]
607
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
608
+ beta_prod_t = 1 - alpha_prod_t
609
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
610
+
611
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
612
+
613
+ return variance
614
+
615
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
616
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
617
+ """
618
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
619
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
620
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
621
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
622
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
623
+ https://arxiv.org/abs/2205.11487
624
+ """
625
+ dtype = sample.dtype
626
+ batch_size, channels, height, width = sample.shape
627
+
628
+ if dtype not in (torch.float32, torch.float64):
629
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
630
+
631
+ # Flatten sample for doing quantile calculation along each image
632
+ sample = sample.reshape(batch_size, channels * height * width)
633
+
634
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
635
+
636
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
637
+ s = torch.clamp(
638
+ s, min=1, max=self.config.sample_max_value
639
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
640
+
641
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
642
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
643
+
644
+ sample = sample.reshape(batch_size, channels, height, width)
645
+ sample = sample.to(dtype)
646
+
647
+ return sample
648
+
649
+ def set_timesteps(
650
+ self, stength, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None
651
+ ):
652
+ """
653
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
654
+ Args:
655
+ num_inference_steps (`int`):
656
+ The number of diffusion steps used when generating samples with a pre-trained model.
657
+ """
658
+
659
+ if num_inference_steps > self.config.num_train_timesteps:
660
+ raise ValueError(
661
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
662
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
663
+ f" maximal {self.config.num_train_timesteps} timesteps."
664
+ )
665
+
666
+ self.num_inference_steps = num_inference_steps
667
+
668
+ # LCM Timesteps Setting: # Linear Spacing
669
+ c = self.config.num_train_timesteps // lcm_origin_steps
670
+ lcm_origin_timesteps = (
671
+ np.asarray(list(range(1, int(lcm_origin_steps * stength) + 1))) * c - 1
672
+ ) # LCM Training Steps Schedule
673
+ skipping_step = len(lcm_origin_timesteps) // num_inference_steps
674
+ timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule
675
+
676
+ self.timesteps = torch.from_numpy(timesteps.copy()).to(device)
677
+
678
+ def get_scalings_for_boundary_condition_discrete(self, t):
679
+ self.sigma_data = 0.5 # Default: 0.5
680
+
681
+ # By dividing 0.1: This is almost a delta function at t=0.
682
+ c_skip = self.sigma_data**2 / ((t / 0.1) ** 2 + self.sigma_data**2)
683
+ c_out = (t / 0.1) / ((t / 0.1) ** 2 + self.sigma_data**2) ** 0.5
684
+ return c_skip, c_out
685
+
686
+ def step(
687
+ self,
688
+ model_output: torch.Tensor,
689
+ timeindex: int,
690
+ timestep: int,
691
+ sample: torch.Tensor,
692
+ eta: float = 0.0,
693
+ use_clipped_model_output: bool = False,
694
+ generator=None,
695
+ variance_noise: Optional[torch.Tensor] = None,
696
+ return_dict: bool = True,
697
+ ) -> Union[LCMSchedulerOutput, Tuple]:
698
+ """
699
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
700
+ process from the learned model outputs (most often the predicted noise).
701
+ Args:
702
+ model_output (`torch.Tensor`):
703
+ The direct output from learned diffusion model.
704
+ timestep (`float`):
705
+ The current discrete timestep in the diffusion chain.
706
+ sample (`torch.Tensor`):
707
+ A current instance of a sample created by the diffusion process.
708
+ eta (`float`):
709
+ The weight of noise for added noise in diffusion step.
710
+ use_clipped_model_output (`bool`, defaults to `False`):
711
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
712
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
713
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
714
+ `use_clipped_model_output` has no effect.
715
+ generator (`torch.Generator`, *optional*):
716
+ A random number generator.
717
+ variance_noise (`torch.Tensor`):
718
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
719
+ itself. Useful for methods such as [`CycleDiffusion`].
720
+ return_dict (`bool`, *optional*, defaults to `True`):
721
+ Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
722
+ Returns:
723
+ [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
724
+ If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
725
+ tuple is returned where the first element is the sample tensor.
726
+ """
727
+ if self.num_inference_steps is None:
728
+ raise ValueError(
729
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
730
+ )
731
+
732
+ # 1. get previous step value
733
+ prev_timeindex = timeindex + 1
734
+ if prev_timeindex < len(self.timesteps):
735
+ prev_timestep = self.timesteps[prev_timeindex]
736
+ else:
737
+ prev_timestep = timestep
738
+
739
+ # 2. compute alphas, betas
740
+ alpha_prod_t = self.alphas_cumprod[timestep]
741
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
742
+
743
+ beta_prod_t = 1 - alpha_prod_t
744
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
745
+
746
+ # 3. Get scalings for boundary conditions
747
+ c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
748
+
749
+ # 4. Different Parameterization:
750
+ parameterization = self.config.prediction_type
751
+
752
+ if parameterization == "epsilon": # noise-prediction
753
+ pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()
754
+
755
+ elif parameterization == "sample": # x-prediction
756
+ pred_x0 = model_output
757
+
758
+ elif parameterization == "v_prediction": # v-prediction
759
+ pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output
760
+
761
+ # 4. Denoise model output using boundary conditions
762
+ denoised = c_out * pred_x0 + c_skip * sample
763
+
764
+ # 5. Sample z ~ N(0, I), For MultiStep Inference
765
+ # Noise is not used for one-step sampling.
766
+ if len(self.timesteps) > 1:
767
+ noise = torch.randn(model_output.shape).to(model_output.device)
768
+ prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise
769
+ else:
770
+ prev_sample = denoised
771
+
772
+ if not return_dict:
773
+ return (prev_sample, denoised)
774
+
775
+ return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)
776
+
777
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
778
+ def add_noise(
779
+ self,
780
+ original_samples: torch.Tensor,
781
+ noise: torch.Tensor,
782
+ timesteps: torch.IntTensor,
783
+ ) -> torch.Tensor:
784
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
785
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
786
+ timesteps = timesteps.to(original_samples.device)
787
+
788
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
789
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
790
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
791
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
792
+
793
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
794
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
795
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
796
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
797
+
798
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
799
+ return noisy_samples
800
+
801
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
802
+ def get_velocity(self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.IntTensor) -> torch.Tensor:
803
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
804
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
805
+ timesteps = timesteps.to(sample.device)
806
+
807
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
808
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
809
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
810
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
811
+
812
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
813
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
814
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
815
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
816
+
817
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
818
+ return velocity
819
+
820
+ def __len__(self):
821
+ return self.config.num_train_timesteps
v0.32.0/latent_consistency_interpolate.py ADDED
@@ -0,0 +1,999 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
7
+
8
+ from diffusers.image_processor import VaeImageProcessor
9
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
10
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
11
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
12
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
14
+ from diffusers.schedulers import LCMScheduler
15
+ from diffusers.utils import (
16
+ USE_PEFT_BACKEND,
17
+ deprecate,
18
+ logging,
19
+ replace_example_docstring,
20
+ scale_lora_layers,
21
+ unscale_lora_layers,
22
+ )
23
+ from diffusers.utils.torch_utils import randn_tensor
24
+
25
+
26
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
27
+
28
+ EXAMPLE_DOC_STRING = """
29
+ Examples:
30
+ ```py
31
+ >>> import torch
32
+ >>> import numpy as np
33
+
34
+ >>> from diffusers import DiffusionPipeline
35
+
36
+ >>> pipe = DiffusionPipeline.from_pretrained("SimianLuo/LCM_Dreamshaper_v7", custom_pipeline="latent_consistency_interpolate")
37
+ >>> # To save GPU memory, torch.float16 can be used, but it may compromise image quality.
38
+ >>> pipe.to(torch_device="cuda", torch_dtype=torch.float32)
39
+
40
+ >>> prompts = ["A cat", "A dog", "A horse"]
41
+ >>> num_inference_steps = 4
42
+ >>> num_interpolation_steps = 24
43
+ >>> seed = 1337
44
+
45
+ >>> torch.manual_seed(seed)
46
+ >>> np.random.seed(seed)
47
+
48
+ >>> images = pipe(
49
+ prompt=prompts,
50
+ height=512,
51
+ width=512,
52
+ num_inference_steps=num_inference_steps,
53
+ num_interpolation_steps=num_interpolation_steps,
54
+ guidance_scale=8.0,
55
+ embedding_interpolation_type="lerp",
56
+ latent_interpolation_type="slerp",
57
+ process_batch_size=4, # Make it higher or lower based on your GPU memory
58
+ generator=torch.Generator(seed),
59
+ )
60
+
61
+ >>> # Save the images as a video
62
+ >>> import imageio
63
+ >>> from PIL import Image
64
+
65
+ >>> def pil_to_video(images: List[Image.Image], filename: str, fps: int = 60) -> None:
66
+ frames = [np.array(image) for image in images]
67
+ with imageio.get_writer(filename, fps=fps) as video_writer:
68
+ for frame in frames:
69
+ video_writer.append_data(frame)
70
+
71
+ >>> pil_to_video(images, "lcm_interpolate.mp4", fps=24)
72
+ ```
73
+ """
74
+
75
+
76
+ def lerp(
77
+ v0: Union[torch.Tensor, np.ndarray],
78
+ v1: Union[torch.Tensor, np.ndarray],
79
+ t: Union[float, torch.Tensor, np.ndarray],
80
+ ) -> Union[torch.Tensor, np.ndarray]:
81
+ """
82
+ Linearly interpolate between two vectors/tensors.
83
+
84
+ Args:
85
+ v0 (`torch.Tensor` or `np.ndarray`): First vector/tensor.
86
+ v1 (`torch.Tensor` or `np.ndarray`): Second vector/tensor.
87
+ t: (`float`, `torch.Tensor`, or `np.ndarray`):
88
+ Interpolation factor. If float, must be between 0 and 1. If np.ndarray or
89
+ torch.Tensor, must be one dimensional with values between 0 and 1.
90
+
91
+ Returns:
92
+ Union[torch.Tensor, np.ndarray]
93
+ Interpolated vector/tensor between v0 and v1.
94
+ """
95
+ inputs_are_torch = False
96
+ t_is_float = False
97
+
98
+ if isinstance(v0, torch.Tensor):
99
+ inputs_are_torch = True
100
+ input_device = v0.device
101
+ v0 = v0.cpu().numpy()
102
+ v1 = v1.cpu().numpy()
103
+
104
+ if isinstance(t, torch.Tensor):
105
+ inputs_are_torch = True
106
+ input_device = t.device
107
+ t = t.cpu().numpy()
108
+ elif isinstance(t, float):
109
+ t_is_float = True
110
+ t = np.array([t])
111
+
112
+ t = t[..., None]
113
+ v0 = v0[None, ...]
114
+ v1 = v1[None, ...]
115
+ v2 = (1 - t) * v0 + t * v1
116
+
117
+ if t_is_float and v0.ndim > 1:
118
+ assert v2.shape[0] == 1
119
+ v2 = np.squeeze(v2, axis=0)
120
+ if inputs_are_torch:
121
+ v2 = torch.from_numpy(v2).to(input_device)
122
+
123
+ return v2
124
+
125
+
126
+ def slerp(
127
+ v0: Union[torch.Tensor, np.ndarray],
128
+ v1: Union[torch.Tensor, np.ndarray],
129
+ t: Union[float, torch.Tensor, np.ndarray],
130
+ DOT_THRESHOLD=0.9995,
131
+ ) -> Union[torch.Tensor, np.ndarray]:
132
+ """
133
+ Spherical linear interpolation between two vectors/tensors.
134
+
135
+ Args:
136
+ v0 (`torch.Tensor` or `np.ndarray`): First vector/tensor.
137
+ v1 (`torch.Tensor` or `np.ndarray`): Second vector/tensor.
138
+ t: (`float`, `torch.Tensor`, or `np.ndarray`):
139
+ Interpolation factor. If float, must be between 0 and 1. If np.ndarray or
140
+ torch.Tensor, must be one dimensional with values between 0 and 1.
141
+ DOT_THRESHOLD (`float`, *optional*, default=0.9995):
142
+ Threshold for when to use linear interpolation instead of spherical interpolation.
143
+
144
+ Returns:
145
+ `torch.Tensor` or `np.ndarray`:
146
+ Interpolated vector/tensor between v0 and v1.
147
+ """
148
+ inputs_are_torch = False
149
+ t_is_float = False
150
+
151
+ if isinstance(v0, torch.Tensor):
152
+ inputs_are_torch = True
153
+ input_device = v0.device
154
+ v0 = v0.cpu().numpy()
155
+ v1 = v1.cpu().numpy()
156
+
157
+ if isinstance(t, torch.Tensor):
158
+ inputs_are_torch = True
159
+ input_device = t.device
160
+ t = t.cpu().numpy()
161
+ elif isinstance(t, float):
162
+ t_is_float = True
163
+ t = np.array([t], dtype=v0.dtype)
164
+
165
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
166
+ if np.abs(dot) > DOT_THRESHOLD:
167
+ # v1 and v2 are close to parallel
168
+ # Use linear interpolation instead
169
+ v2 = lerp(v0, v1, t)
170
+ else:
171
+ theta_0 = np.arccos(dot)
172
+ sin_theta_0 = np.sin(theta_0)
173
+ theta_t = theta_0 * t
174
+ sin_theta_t = np.sin(theta_t)
175
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
176
+ s1 = sin_theta_t / sin_theta_0
177
+ s0 = s0[..., None]
178
+ s1 = s1[..., None]
179
+ v0 = v0[None, ...]
180
+ v1 = v1[None, ...]
181
+ v2 = s0 * v0 + s1 * v1
182
+
183
+ if t_is_float and v0.ndim > 1:
184
+ assert v2.shape[0] == 1
185
+ v2 = np.squeeze(v2, axis=0)
186
+ if inputs_are_torch:
187
+ v2 = torch.from_numpy(v2).to(input_device)
188
+
189
+ return v2
190
+
191
+
192
+ class LatentConsistencyModelWalkPipeline(
193
+ DiffusionPipeline,
194
+ StableDiffusionMixin,
195
+ TextualInversionLoaderMixin,
196
+ StableDiffusionLoraLoaderMixin,
197
+ FromSingleFileMixin,
198
+ ):
199
+ r"""
200
+ Pipeline for text-to-image generation using a latent consistency model.
201
+
202
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
203
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
204
+
205
+ The pipeline also inherits the following loading methods:
206
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
207
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
208
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
209
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
210
+
211
+ Args:
212
+ vae ([`AutoencoderKL`]):
213
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
214
+ text_encoder ([`~transformers.CLIPTextModel`]):
215
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
216
+ tokenizer ([`~transformers.CLIPTokenizer`]):
217
+ A `CLIPTokenizer` to tokenize text.
218
+ unet ([`UNet2DConditionModel`]):
219
+ A `UNet2DConditionModel` to denoise the encoded image latents.
220
+ scheduler ([`SchedulerMixin`]):
221
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Currently only
222
+ supports [`LCMScheduler`].
223
+ safety_checker ([`StableDiffusionSafetyChecker`]):
224
+ Classification module that estimates whether generated images could be considered offensive or harmful.
225
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
226
+ about a model's potential harms.
227
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
228
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
229
+ requires_safety_checker (`bool`, *optional*, defaults to `True`):
230
+ Whether the pipeline requires a safety checker component.
231
+ """
232
+
233
+ model_cpu_offload_seq = "text_encoder->unet->vae"
234
+ _optional_components = ["safety_checker", "feature_extractor"]
235
+ _exclude_from_cpu_offload = ["safety_checker"]
236
+ _callback_tensor_inputs = ["latents", "denoised", "prompt_embeds", "w_embedding"]
237
+
238
+ def __init__(
239
+ self,
240
+ vae: AutoencoderKL,
241
+ text_encoder: CLIPTextModel,
242
+ tokenizer: CLIPTokenizer,
243
+ unet: UNet2DConditionModel,
244
+ scheduler: LCMScheduler,
245
+ safety_checker: StableDiffusionSafetyChecker,
246
+ feature_extractor: CLIPImageProcessor,
247
+ requires_safety_checker: bool = True,
248
+ ):
249
+ super().__init__()
250
+
251
+ if safety_checker is None and requires_safety_checker:
252
+ logger.warning(
253
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
254
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
255
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
256
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
257
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
258
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
259
+ )
260
+
261
+ if safety_checker is not None and feature_extractor is None:
262
+ raise ValueError(
263
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
264
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
265
+ )
266
+
267
+ self.register_modules(
268
+ vae=vae,
269
+ text_encoder=text_encoder,
270
+ tokenizer=tokenizer,
271
+ unet=unet,
272
+ scheduler=scheduler,
273
+ safety_checker=safety_checker,
274
+ feature_extractor=feature_extractor,
275
+ )
276
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
277
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
278
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
279
+
280
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
281
+ def encode_prompt(
282
+ self,
283
+ prompt,
284
+ device,
285
+ num_images_per_prompt,
286
+ do_classifier_free_guidance,
287
+ negative_prompt=None,
288
+ prompt_embeds: Optional[torch.Tensor] = None,
289
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
290
+ lora_scale: Optional[float] = None,
291
+ clip_skip: Optional[int] = None,
292
+ ):
293
+ r"""
294
+ Encodes the prompt into text encoder hidden states.
295
+
296
+ Args:
297
+ prompt (`str` or `List[str]`, *optional*):
298
+ prompt to be encoded
299
+ device: (`torch.device`):
300
+ torch device
301
+ num_images_per_prompt (`int`):
302
+ number of images that should be generated per prompt
303
+ do_classifier_free_guidance (`bool`):
304
+ whether to use classifier free guidance or not
305
+ negative_prompt (`str` or `List[str]`, *optional*):
306
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
307
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
308
+ less than `1`).
309
+ prompt_embeds (`torch.Tensor`, *optional*):
310
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
311
+ provided, text embeddings will be generated from `prompt` input argument.
312
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
313
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
314
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
315
+ argument.
316
+ lora_scale (`float`, *optional*):
317
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
318
+ clip_skip (`int`, *optional*):
319
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
320
+ the output of the pre-final layer will be used for computing the prompt embeddings.
321
+ """
322
+ # set lora scale so that monkey patched LoRA
323
+ # function of text encoder can correctly access it
324
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
325
+ self._lora_scale = lora_scale
326
+
327
+ # dynamically adjust the LoRA scale
328
+ if not USE_PEFT_BACKEND:
329
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
330
+ else:
331
+ scale_lora_layers(self.text_encoder, lora_scale)
332
+
333
+ if prompt is not None and isinstance(prompt, str):
334
+ batch_size = 1
335
+ elif prompt is not None and isinstance(prompt, list):
336
+ batch_size = len(prompt)
337
+ else:
338
+ batch_size = prompt_embeds.shape[0]
339
+
340
+ if prompt_embeds is None:
341
+ # textual inversion: process multi-vector tokens if necessary
342
+ if isinstance(self, TextualInversionLoaderMixin):
343
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
344
+
345
+ text_inputs = self.tokenizer(
346
+ prompt,
347
+ padding="max_length",
348
+ max_length=self.tokenizer.model_max_length,
349
+ truncation=True,
350
+ return_tensors="pt",
351
+ )
352
+ text_input_ids = text_inputs.input_ids
353
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
354
+
355
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
356
+ text_input_ids, untruncated_ids
357
+ ):
358
+ removed_text = self.tokenizer.batch_decode(
359
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
360
+ )
361
+ logger.warning(
362
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
363
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
364
+ )
365
+
366
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
367
+ attention_mask = text_inputs.attention_mask.to(device)
368
+ else:
369
+ attention_mask = None
370
+
371
+ if clip_skip is None:
372
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
373
+ prompt_embeds = prompt_embeds[0]
374
+ else:
375
+ prompt_embeds = self.text_encoder(
376
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
377
+ )
378
+ # Access the `hidden_states` first, that contains a tuple of
379
+ # all the hidden states from the encoder layers. Then index into
380
+ # the tuple to access the hidden states from the desired layer.
381
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
382
+ # We also need to apply the final LayerNorm here to not mess with the
383
+ # representations. The `last_hidden_states` that we typically use for
384
+ # obtaining the final prompt representations passes through the LayerNorm
385
+ # layer.
386
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
387
+
388
+ if self.text_encoder is not None:
389
+ prompt_embeds_dtype = self.text_encoder.dtype
390
+ elif self.unet is not None:
391
+ prompt_embeds_dtype = self.unet.dtype
392
+ else:
393
+ prompt_embeds_dtype = prompt_embeds.dtype
394
+
395
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
396
+
397
+ bs_embed, seq_len, _ = prompt_embeds.shape
398
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
399
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
400
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
401
+
402
+ # get unconditional embeddings for classifier free guidance
403
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
404
+ uncond_tokens: List[str]
405
+ if negative_prompt is None:
406
+ uncond_tokens = [""] * batch_size
407
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
408
+ raise TypeError(
409
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
410
+ f" {type(prompt)}."
411
+ )
412
+ elif isinstance(negative_prompt, str):
413
+ uncond_tokens = [negative_prompt]
414
+ elif batch_size != len(negative_prompt):
415
+ raise ValueError(
416
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
417
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
418
+ " the batch size of `prompt`."
419
+ )
420
+ else:
421
+ uncond_tokens = negative_prompt
422
+
423
+ # textual inversion: process multi-vector tokens if necessary
424
+ if isinstance(self, TextualInversionLoaderMixin):
425
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
426
+
427
+ max_length = prompt_embeds.shape[1]
428
+ uncond_input = self.tokenizer(
429
+ uncond_tokens,
430
+ padding="max_length",
431
+ max_length=max_length,
432
+ truncation=True,
433
+ return_tensors="pt",
434
+ )
435
+
436
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
437
+ attention_mask = uncond_input.attention_mask.to(device)
438
+ else:
439
+ attention_mask = None
440
+
441
+ negative_prompt_embeds = self.text_encoder(
442
+ uncond_input.input_ids.to(device),
443
+ attention_mask=attention_mask,
444
+ )
445
+ negative_prompt_embeds = negative_prompt_embeds[0]
446
+
447
+ if do_classifier_free_guidance:
448
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
449
+ seq_len = negative_prompt_embeds.shape[1]
450
+
451
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
452
+
453
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
454
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
455
+
456
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
457
+ # Retrieve the original scale by scaling back the LoRA layers
458
+ unscale_lora_layers(self.text_encoder, lora_scale)
459
+
460
+ return prompt_embeds, negative_prompt_embeds
461
+
462
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
463
+ def run_safety_checker(self, image, device, dtype):
464
+ if self.safety_checker is None:
465
+ has_nsfw_concept = None
466
+ else:
467
+ if torch.is_tensor(image):
468
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
469
+ else:
470
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
471
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
472
+ image, has_nsfw_concept = self.safety_checker(
473
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
474
+ )
475
+ return image, has_nsfw_concept
476
+
477
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
478
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
479
+ shape = (
480
+ batch_size,
481
+ num_channels_latents,
482
+ int(height) // self.vae_scale_factor,
483
+ int(width) // self.vae_scale_factor,
484
+ )
485
+ if isinstance(generator, list) and len(generator) != batch_size:
486
+ raise ValueError(
487
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
488
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
489
+ )
490
+
491
+ if latents is None:
492
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
493
+ else:
494
+ latents = latents.to(device)
495
+
496
+ # scale the initial noise by the standard deviation required by the scheduler
497
+ latents = latents * self.scheduler.init_noise_sigma
498
+ return latents
499
+
500
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
501
+ """
502
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
503
+
504
+ Args:
505
+ timesteps (`torch.Tensor`):
506
+ generate embedding vectors at these timesteps
507
+ embedding_dim (`int`, *optional*, defaults to 512):
508
+ dimension of the embeddings to generate
509
+ dtype:
510
+ data type of the generated embeddings
511
+
512
+ Returns:
513
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
514
+ """
515
+ assert len(w.shape) == 1
516
+ w = w * 1000.0
517
+
518
+ half_dim = embedding_dim // 2
519
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
520
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
521
+ emb = w.to(dtype)[:, None] * emb[None, :]
522
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
523
+ if embedding_dim % 2 == 1: # zero pad
524
+ emb = torch.nn.functional.pad(emb, (0, 1))
525
+ assert emb.shape == (w.shape[0], embedding_dim)
526
+ return emb
527
+
528
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
529
+ def prepare_extra_step_kwargs(self, generator, eta):
530
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
531
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
532
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
533
+ # and should be between [0, 1]
534
+
535
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
536
+ extra_step_kwargs = {}
537
+ if accepts_eta:
538
+ extra_step_kwargs["eta"] = eta
539
+
540
+ # check if the scheduler accepts generator
541
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
542
+ if accepts_generator:
543
+ extra_step_kwargs["generator"] = generator
544
+ return extra_step_kwargs
545
+
546
+ # Currently StableDiffusionPipeline.check_inputs with negative prompt stuff removed
547
+ def check_inputs(
548
+ self,
549
+ prompt: Union[str, List[str]],
550
+ height: int,
551
+ width: int,
552
+ callback_steps: int,
553
+ prompt_embeds: Optional[torch.Tensor] = None,
554
+ callback_on_step_end_tensor_inputs=None,
555
+ ):
556
+ if height % 8 != 0 or width % 8 != 0:
557
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
558
+
559
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
560
+ raise ValueError(
561
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
562
+ f" {type(callback_steps)}."
563
+ )
564
+
565
+ if callback_on_step_end_tensor_inputs is not None and not all(
566
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
567
+ ):
568
+ raise ValueError(
569
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
570
+ )
571
+
572
+ if prompt is not None and prompt_embeds is not None:
573
+ raise ValueError(
574
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
575
+ " only forward one of the two."
576
+ )
577
+ elif prompt is None and prompt_embeds is None:
578
+ raise ValueError(
579
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
580
+ )
581
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
582
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
583
+
584
+ @torch.no_grad()
585
+ def interpolate_embedding(
586
+ self,
587
+ start_embedding: torch.Tensor,
588
+ end_embedding: torch.Tensor,
589
+ num_interpolation_steps: Union[int, List[int]],
590
+ interpolation_type: str,
591
+ ) -> torch.Tensor:
592
+ if interpolation_type == "lerp":
593
+ interpolation_fn = lerp
594
+ elif interpolation_type == "slerp":
595
+ interpolation_fn = slerp
596
+ else:
597
+ raise ValueError(
598
+ f"embedding_interpolation_type must be one of ['lerp', 'slerp'], got {interpolation_type}."
599
+ )
600
+
601
+ embedding = torch.cat([start_embedding, end_embedding])
602
+ steps = torch.linspace(0, 1, num_interpolation_steps, dtype=embedding.dtype).cpu().numpy()
603
+ steps = np.expand_dims(steps, axis=tuple(range(1, embedding.ndim)))
604
+ interpolations = []
605
+
606
+ # Interpolate between text embeddings
607
+ # TODO(aryan): Think of a better way of doing this
608
+ # See if it can be done parallelly instead
609
+ for i in range(embedding.shape[0] - 1):
610
+ interpolations.append(interpolation_fn(embedding[i], embedding[i + 1], steps).squeeze(dim=1))
611
+
612
+ interpolations = torch.cat(interpolations)
613
+ return interpolations
614
+
615
+ @torch.no_grad()
616
+ def interpolate_latent(
617
+ self,
618
+ start_latent: torch.Tensor,
619
+ end_latent: torch.Tensor,
620
+ num_interpolation_steps: Union[int, List[int]],
621
+ interpolation_type: str,
622
+ ) -> torch.Tensor:
623
+ if interpolation_type == "lerp":
624
+ interpolation_fn = lerp
625
+ elif interpolation_type == "slerp":
626
+ interpolation_fn = slerp
627
+
628
+ latent = torch.cat([start_latent, end_latent])
629
+ steps = torch.linspace(0, 1, num_interpolation_steps, dtype=latent.dtype).cpu().numpy()
630
+ steps = np.expand_dims(steps, axis=tuple(range(1, latent.ndim)))
631
+ interpolations = []
632
+
633
+ # Interpolate between latents
634
+ # TODO: Think of a better way of doing this
635
+ # See if it can be done parallelly instead
636
+ for i in range(latent.shape[0] - 1):
637
+ interpolations.append(interpolation_fn(latent[i], latent[i + 1], steps).squeeze(dim=1))
638
+
639
+ return torch.cat(interpolations)
640
+
641
+ @property
642
+ def guidance_scale(self):
643
+ return self._guidance_scale
644
+
645
+ @property
646
+ def cross_attention_kwargs(self):
647
+ return self._cross_attention_kwargs
648
+
649
+ @property
650
+ def clip_skip(self):
651
+ return self._clip_skip
652
+
653
+ @property
654
+ def num_timesteps(self):
655
+ return self._num_timesteps
656
+
657
+ @torch.no_grad()
658
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
659
+ def __call__(
660
+ self,
661
+ prompt: Union[str, List[str]] = None,
662
+ height: Optional[int] = None,
663
+ width: Optional[int] = None,
664
+ num_inference_steps: int = 4,
665
+ num_interpolation_steps: int = 8,
666
+ original_inference_steps: int = None,
667
+ guidance_scale: float = 8.5,
668
+ num_images_per_prompt: Optional[int] = 1,
669
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
670
+ latents: Optional[torch.Tensor] = None,
671
+ prompt_embeds: Optional[torch.Tensor] = None,
672
+ output_type: Optional[str] = "pil",
673
+ return_dict: bool = True,
674
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
675
+ clip_skip: Optional[int] = None,
676
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
677
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
678
+ embedding_interpolation_type: str = "lerp",
679
+ latent_interpolation_type: str = "slerp",
680
+ process_batch_size: int = 4,
681
+ **kwargs,
682
+ ):
683
+ r"""
684
+ The call function to the pipeline for generation.
685
+
686
+ Args:
687
+ prompt (`str` or `List[str]`, *optional*):
688
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
689
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
690
+ The height in pixels of the generated image.
691
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
692
+ The width in pixels of the generated image.
693
+ num_inference_steps (`int`, *optional*, defaults to 50):
694
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
695
+ expense of slower inference.
696
+ original_inference_steps (`int`, *optional*):
697
+ The original number of inference steps use to generate a linearly-spaced timestep schedule, from which
698
+ we will draw `num_inference_steps` evenly spaced timesteps from as our final timestep schedule,
699
+ following the Skipping-Step method in the paper (see Section 4.3). If not set this will default to the
700
+ scheduler's `original_inference_steps` attribute.
701
+ guidance_scale (`float`, *optional*, defaults to 7.5):
702
+ A higher guidance scale value encourages the model to generate images closely linked to the text
703
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
704
+ Note that the original latent consistency models paper uses a different CFG formulation where the
705
+ guidance scales are decreased by 1 (so in the paper formulation CFG is enabled when `guidance_scale >
706
+ 0`).
707
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
708
+ The number of images to generate per prompt.
709
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
710
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
711
+ generation deterministic.
712
+ latents (`torch.Tensor`, *optional*):
713
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
714
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
715
+ tensor is generated by sampling using the supplied random `generator`.
716
+ prompt_embeds (`torch.Tensor`, *optional*):
717
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
718
+ provided, text embeddings are generated from the `prompt` input argument.
719
+ output_type (`str`, *optional*, defaults to `"pil"`):
720
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
721
+ return_dict (`bool`, *optional*, defaults to `True`):
722
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
723
+ plain tuple.
724
+ cross_attention_kwargs (`dict`, *optional*):
725
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
726
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
727
+ clip_skip (`int`, *optional*):
728
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
729
+ the output of the pre-final layer will be used for computing the prompt embeddings.
730
+ callback_on_step_end (`Callable`, *optional*):
731
+ A function that calls at the end of each denoising steps during the inference. The function is called
732
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
733
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
734
+ `callback_on_step_end_tensor_inputs`.
735
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
736
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
737
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
738
+ `._callback_tensor_inputs` attribute of your pipeline class.
739
+ embedding_interpolation_type (`str`, *optional*, defaults to `"lerp"`):
740
+ The type of interpolation to use for interpolating between text embeddings. Choose between `"lerp"` and `"slerp"`.
741
+ latent_interpolation_type (`str`, *optional*, defaults to `"slerp"`):
742
+ The type of interpolation to use for interpolating between latents. Choose between `"lerp"` and `"slerp"`.
743
+ process_batch_size (`int`, *optional*, defaults to 4):
744
+ The batch size to use for processing the images. This is useful when generating a large number of images
745
+ and you want to avoid running out of memory.
746
+
747
+ Examples:
748
+
749
+ Returns:
750
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
751
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
752
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
753
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
754
+ "not-safe-for-work" (nsfw) content.
755
+ """
756
+
757
+ callback = kwargs.pop("callback", None)
758
+ callback_steps = kwargs.pop("callback_steps", None)
759
+
760
+ if callback is not None:
761
+ deprecate(
762
+ "callback",
763
+ "1.0.0",
764
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
765
+ )
766
+ if callback_steps is not None:
767
+ deprecate(
768
+ "callback_steps",
769
+ "1.0.0",
770
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
771
+ )
772
+
773
+ # 0. Default height and width to unet
774
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
775
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
776
+
777
+ # 1. Check inputs. Raise error if not correct
778
+ self.check_inputs(prompt, height, width, callback_steps, prompt_embeds, callback_on_step_end_tensor_inputs)
779
+ self._guidance_scale = guidance_scale
780
+ self._clip_skip = clip_skip
781
+ self._cross_attention_kwargs = cross_attention_kwargs
782
+
783
+ # 2. Define call parameters
784
+ if prompt is not None and isinstance(prompt, str):
785
+ batch_size = 1
786
+ elif prompt is not None and isinstance(prompt, list):
787
+ batch_size = len(prompt)
788
+ else:
789
+ batch_size = prompt_embeds.shape[0]
790
+ if batch_size < 2:
791
+ raise ValueError(f"`prompt` must have length of at least 2 but found {batch_size}")
792
+ if num_images_per_prompt != 1:
793
+ raise ValueError("`num_images_per_prompt` must be `1` as no other value is supported yet")
794
+ if prompt_embeds is not None:
795
+ raise ValueError("`prompt_embeds` must be None since it is not supported yet")
796
+ if latents is not None:
797
+ raise ValueError("`latents` must be None since it is not supported yet")
798
+
799
+ device = self._execution_device
800
+ # do_classifier_free_guidance = guidance_scale > 1.0
801
+
802
+ lora_scale = (
803
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
804
+ )
805
+
806
+ self.scheduler.set_timesteps(num_inference_steps, device, original_inference_steps=original_inference_steps)
807
+ timesteps = self.scheduler.timesteps
808
+ num_channels_latents = self.unet.config.in_channels
809
+ # bs = batch_size * num_images_per_prompt
810
+
811
+ # 3. Encode initial input prompt
812
+ prompt_embeds_1, _ = self.encode_prompt(
813
+ prompt[:1],
814
+ device,
815
+ num_images_per_prompt=num_images_per_prompt,
816
+ do_classifier_free_guidance=False,
817
+ negative_prompt=None,
818
+ prompt_embeds=prompt_embeds,
819
+ negative_prompt_embeds=None,
820
+ lora_scale=lora_scale,
821
+ clip_skip=self.clip_skip,
822
+ )
823
+
824
+ # 4. Prepare initial latent variables
825
+ latents_1 = self.prepare_latents(
826
+ 1,
827
+ num_channels_latents,
828
+ height,
829
+ width,
830
+ prompt_embeds_1.dtype,
831
+ device,
832
+ generator,
833
+ latents,
834
+ )
835
+
836
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, None)
837
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
838
+ self._num_timesteps = len(timesteps)
839
+ images = []
840
+
841
+ # 5. Iterate over prompts and perform latent walk. Note that we do this two prompts at a time
842
+ # otherwise the memory usage ends up being too high.
843
+ with self.progress_bar(total=batch_size - 1) as prompt_progress_bar:
844
+ for i in range(1, batch_size):
845
+ # 6. Encode current prompt
846
+ prompt_embeds_2, _ = self.encode_prompt(
847
+ prompt[i : i + 1],
848
+ device,
849
+ num_images_per_prompt=num_images_per_prompt,
850
+ do_classifier_free_guidance=False,
851
+ negative_prompt=None,
852
+ prompt_embeds=prompt_embeds,
853
+ negative_prompt_embeds=None,
854
+ lora_scale=lora_scale,
855
+ clip_skip=self.clip_skip,
856
+ )
857
+
858
+ # 7. Prepare current latent variables
859
+ latents_2 = self.prepare_latents(
860
+ 1,
861
+ num_channels_latents,
862
+ height,
863
+ width,
864
+ prompt_embeds_2.dtype,
865
+ device,
866
+ generator,
867
+ latents,
868
+ )
869
+
870
+ # 8. Interpolate between previous and current prompt embeddings and latents
871
+ inference_embeddings = self.interpolate_embedding(
872
+ start_embedding=prompt_embeds_1,
873
+ end_embedding=prompt_embeds_2,
874
+ num_interpolation_steps=num_interpolation_steps,
875
+ interpolation_type=embedding_interpolation_type,
876
+ )
877
+ inference_latents = self.interpolate_latent(
878
+ start_latent=latents_1,
879
+ end_latent=latents_2,
880
+ num_interpolation_steps=num_interpolation_steps,
881
+ interpolation_type=latent_interpolation_type,
882
+ )
883
+ next_prompt_embeds = inference_embeddings[-1:].detach().clone()
884
+ next_latents = inference_latents[-1:].detach().clone()
885
+ bs = num_interpolation_steps
886
+
887
+ # 9. Perform inference in batches. Note the use of `process_batch_size` to control the batch size
888
+ # of the inference. This is useful for reducing memory usage and can be configured based on the
889
+ # available GPU memory.
890
+ with self.progress_bar(
891
+ total=(bs + process_batch_size - 1) // process_batch_size
892
+ ) as batch_progress_bar:
893
+ for batch_index in range(0, bs, process_batch_size):
894
+ batch_inference_latents = inference_latents[batch_index : batch_index + process_batch_size]
895
+ batch_inference_embeddings = inference_embeddings[
896
+ batch_index : batch_index + process_batch_size
897
+ ]
898
+
899
+ self.scheduler.set_timesteps(
900
+ num_inference_steps, device, original_inference_steps=original_inference_steps
901
+ )
902
+ timesteps = self.scheduler.timesteps
903
+
904
+ current_bs = batch_inference_embeddings.shape[0]
905
+ w = torch.tensor(self.guidance_scale - 1).repeat(current_bs)
906
+ w_embedding = self.get_guidance_scale_embedding(
907
+ w, embedding_dim=self.unet.config.time_cond_proj_dim
908
+ ).to(device=device, dtype=latents_1.dtype)
909
+
910
+ # 10. Perform inference for current batch
911
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
912
+ for index, t in enumerate(timesteps):
913
+ batch_inference_latents = batch_inference_latents.to(batch_inference_embeddings.dtype)
914
+
915
+ # model prediction (v-prediction, eps, x)
916
+ model_pred = self.unet(
917
+ batch_inference_latents,
918
+ t,
919
+ timestep_cond=w_embedding,
920
+ encoder_hidden_states=batch_inference_embeddings,
921
+ cross_attention_kwargs=self.cross_attention_kwargs,
922
+ return_dict=False,
923
+ )[0]
924
+
925
+ # compute the previous noisy sample x_t -> x_t-1
926
+ batch_inference_latents, denoised = self.scheduler.step(
927
+ model_pred, t, batch_inference_latents, **extra_step_kwargs, return_dict=False
928
+ )
929
+ if callback_on_step_end is not None:
930
+ callback_kwargs = {}
931
+ for k in callback_on_step_end_tensor_inputs:
932
+ callback_kwargs[k] = locals()[k]
933
+ callback_outputs = callback_on_step_end(self, index, t, callback_kwargs)
934
+
935
+ batch_inference_latents = callback_outputs.pop("latents", batch_inference_latents)
936
+ batch_inference_embeddings = callback_outputs.pop(
937
+ "prompt_embeds", batch_inference_embeddings
938
+ )
939
+ w_embedding = callback_outputs.pop("w_embedding", w_embedding)
940
+ denoised = callback_outputs.pop("denoised", denoised)
941
+
942
+ # call the callback, if provided
943
+ if index == len(timesteps) - 1 or (
944
+ (index + 1) > num_warmup_steps and (index + 1) % self.scheduler.order == 0
945
+ ):
946
+ progress_bar.update()
947
+ if callback is not None and index % callback_steps == 0:
948
+ step_idx = index // getattr(self.scheduler, "order", 1)
949
+ callback(step_idx, t, batch_inference_latents)
950
+
951
+ denoised = denoised.to(batch_inference_embeddings.dtype)
952
+
953
+ # Note: This is not supported because you would get black images in your latent walk if
954
+ # NSFW concept is detected
955
+ # if not output_type == "latent":
956
+ # image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
957
+ # image, has_nsfw_concept = self.run_safety_checker(image, device, inference_embeddings.dtype)
958
+ # else:
959
+ # image = denoised
960
+ # has_nsfw_concept = None
961
+
962
+ # if has_nsfw_concept is None:
963
+ # do_denormalize = [True] * image.shape[0]
964
+ # else:
965
+ # do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
966
+
967
+ image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
968
+ do_denormalize = [True] * image.shape[0]
969
+ has_nsfw_concept = None
970
+
971
+ image = self.image_processor.postprocess(
972
+ image, output_type=output_type, do_denormalize=do_denormalize
973
+ )
974
+ images.append(image)
975
+
976
+ batch_progress_bar.update()
977
+
978
+ prompt_embeds_1 = next_prompt_embeds
979
+ latents_1 = next_latents
980
+
981
+ prompt_progress_bar.update()
982
+
983
+ # 11. Determine what should be returned
984
+ if output_type == "pil":
985
+ images = [image for image_list in images for image in image_list]
986
+ elif output_type == "np":
987
+ images = np.concatenate(images)
988
+ elif output_type == "pt":
989
+ images = torch.cat(images)
990
+ else:
991
+ raise ValueError("`output_type` must be one of 'pil', 'np' or 'pt'.")
992
+
993
+ # Offload all models
994
+ self.maybe_free_model_hooks()
995
+
996
+ if not return_dict:
997
+ return (images, has_nsfw_concept)
998
+
999
+ return StableDiffusionPipelineOutput(images=images, nsfw_content_detected=has_nsfw_concept)
v0.32.0/latent_consistency_txt2img.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stanford University Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
16
+ # and https://github.com/hojonathanho/diffusion
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import torch
24
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
25
+
26
+ from diffusers import AutoencoderKL, ConfigMixin, DiffusionPipeline, SchedulerMixin, UNet2DConditionModel, logging
27
+ from diffusers.configuration_utils import register_to_config
28
+ from diffusers.image_processor import VaeImageProcessor
29
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
30
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
31
+ from diffusers.utils import BaseOutput
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ class LatentConsistencyModelPipeline(DiffusionPipeline):
38
+ _optional_components = ["scheduler"]
39
+
40
+ def __init__(
41
+ self,
42
+ vae: AutoencoderKL,
43
+ text_encoder: CLIPTextModel,
44
+ tokenizer: CLIPTokenizer,
45
+ unet: UNet2DConditionModel,
46
+ scheduler: "LCMScheduler",
47
+ safety_checker: StableDiffusionSafetyChecker,
48
+ feature_extractor: CLIPImageProcessor,
49
+ requires_safety_checker: bool = True,
50
+ ):
51
+ super().__init__()
52
+
53
+ scheduler = (
54
+ scheduler
55
+ if scheduler is not None
56
+ else LCMScheduler(
57
+ beta_start=0.00085, beta_end=0.0120, beta_schedule="scaled_linear", prediction_type="epsilon"
58
+ )
59
+ )
60
+
61
+ self.register_modules(
62
+ vae=vae,
63
+ text_encoder=text_encoder,
64
+ tokenizer=tokenizer,
65
+ unet=unet,
66
+ scheduler=scheduler,
67
+ safety_checker=safety_checker,
68
+ feature_extractor=feature_extractor,
69
+ )
70
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
71
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
72
+
73
+ def _encode_prompt(
74
+ self,
75
+ prompt,
76
+ device,
77
+ num_images_per_prompt,
78
+ prompt_embeds: None,
79
+ ):
80
+ r"""
81
+ Encodes the prompt into text encoder hidden states.
82
+ Args:
83
+ prompt (`str` or `List[str]`, *optional*):
84
+ prompt to be encoded
85
+ device: (`torch.device`):
86
+ torch device
87
+ num_images_per_prompt (`int`):
88
+ number of images that should be generated per prompt
89
+ prompt_embeds (`torch.Tensor`, *optional*):
90
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
91
+ provided, text embeddings will be generated from `prompt` input argument.
92
+ """
93
+
94
+ if prompt is not None and isinstance(prompt, str):
95
+ pass
96
+ elif prompt is not None and isinstance(prompt, list):
97
+ len(prompt)
98
+ else:
99
+ prompt_embeds.shape[0]
100
+
101
+ if prompt_embeds is None:
102
+ text_inputs = self.tokenizer(
103
+ prompt,
104
+ padding="max_length",
105
+ max_length=self.tokenizer.model_max_length,
106
+ truncation=True,
107
+ return_tensors="pt",
108
+ )
109
+ text_input_ids = text_inputs.input_ids
110
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
111
+
112
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
113
+ text_input_ids, untruncated_ids
114
+ ):
115
+ removed_text = self.tokenizer.batch_decode(
116
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
117
+ )
118
+ logger.warning(
119
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
120
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
121
+ )
122
+
123
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
124
+ attention_mask = text_inputs.attention_mask.to(device)
125
+ else:
126
+ attention_mask = None
127
+
128
+ prompt_embeds = self.text_encoder(
129
+ text_input_ids.to(device),
130
+ attention_mask=attention_mask,
131
+ )
132
+ prompt_embeds = prompt_embeds[0]
133
+
134
+ if self.text_encoder is not None:
135
+ prompt_embeds_dtype = self.text_encoder.dtype
136
+ elif self.unet is not None:
137
+ prompt_embeds_dtype = self.unet.dtype
138
+ else:
139
+ prompt_embeds_dtype = prompt_embeds.dtype
140
+
141
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
142
+
143
+ bs_embed, seq_len, _ = prompt_embeds.shape
144
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
145
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
146
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
147
+
148
+ # Don't need to get uncond prompt embedding because of LCM Guided Distillation
149
+ return prompt_embeds
150
+
151
+ def run_safety_checker(self, image, device, dtype):
152
+ if self.safety_checker is None:
153
+ has_nsfw_concept = None
154
+ else:
155
+ if torch.is_tensor(image):
156
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
157
+ else:
158
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
159
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
160
+ image, has_nsfw_concept = self.safety_checker(
161
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
162
+ )
163
+ return image, has_nsfw_concept
164
+
165
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, latents=None):
166
+ shape = (
167
+ batch_size,
168
+ num_channels_latents,
169
+ int(height) // self.vae_scale_factor,
170
+ int(width) // self.vae_scale_factor,
171
+ )
172
+ if latents is None:
173
+ latents = torch.randn(shape, dtype=dtype).to(device)
174
+ else:
175
+ latents = latents.to(device)
176
+ # scale the initial noise by the standard deviation required by the scheduler
177
+ latents = latents * self.scheduler.init_noise_sigma
178
+ return latents
179
+
180
+ def get_w_embedding(self, w, embedding_dim=512, dtype=torch.float32):
181
+ """
182
+ see https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
183
+ Args:
184
+ timesteps: torch.Tensor: generate embedding vectors at these timesteps
185
+ embedding_dim: int: dimension of the embeddings to generate
186
+ dtype: data type of the generated embeddings
187
+ Returns:
188
+ embedding vectors with shape `(len(timesteps), embedding_dim)`
189
+ """
190
+ assert len(w.shape) == 1
191
+ w = w * 1000.0
192
+
193
+ half_dim = embedding_dim // 2
194
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
195
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
196
+ emb = w.to(dtype)[:, None] * emb[None, :]
197
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
198
+ if embedding_dim % 2 == 1: # zero pad
199
+ emb = torch.nn.functional.pad(emb, (0, 1))
200
+ assert emb.shape == (w.shape[0], embedding_dim)
201
+ return emb
202
+
203
+ @torch.no_grad()
204
+ def __call__(
205
+ self,
206
+ prompt: Union[str, List[str]] = None,
207
+ height: Optional[int] = 768,
208
+ width: Optional[int] = 768,
209
+ guidance_scale: float = 7.5,
210
+ num_images_per_prompt: Optional[int] = 1,
211
+ latents: Optional[torch.Tensor] = None,
212
+ num_inference_steps: int = 4,
213
+ lcm_origin_steps: int = 50,
214
+ prompt_embeds: Optional[torch.Tensor] = None,
215
+ output_type: Optional[str] = "pil",
216
+ return_dict: bool = True,
217
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
218
+ ):
219
+ # 0. Default height and width to unet
220
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
221
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
222
+
223
+ # 2. Define call parameters
224
+ if prompt is not None and isinstance(prompt, str):
225
+ batch_size = 1
226
+ elif prompt is not None and isinstance(prompt, list):
227
+ batch_size = len(prompt)
228
+ else:
229
+ batch_size = prompt_embeds.shape[0]
230
+
231
+ device = self._execution_device
232
+ # do_classifier_free_guidance = guidance_scale > 0.0 # In LCM Implementation: cfg_noise = noise_cond + cfg_scale * (noise_cond - noise_uncond) , (cfg_scale > 0.0 using CFG)
233
+
234
+ # 3. Encode input prompt
235
+ prompt_embeds = self._encode_prompt(
236
+ prompt,
237
+ device,
238
+ num_images_per_prompt,
239
+ prompt_embeds=prompt_embeds,
240
+ )
241
+
242
+ # 4. Prepare timesteps
243
+ self.scheduler.set_timesteps(num_inference_steps, lcm_origin_steps)
244
+ timesteps = self.scheduler.timesteps
245
+
246
+ # 5. Prepare latent variable
247
+ num_channels_latents = self.unet.config.in_channels
248
+ latents = self.prepare_latents(
249
+ batch_size * num_images_per_prompt,
250
+ num_channels_latents,
251
+ height,
252
+ width,
253
+ prompt_embeds.dtype,
254
+ device,
255
+ latents,
256
+ )
257
+ bs = batch_size * num_images_per_prompt
258
+
259
+ # 6. Get Guidance Scale Embedding
260
+ w = torch.tensor(guidance_scale).repeat(bs)
261
+ w_embedding = self.get_w_embedding(w, embedding_dim=256).to(device=device, dtype=latents.dtype)
262
+
263
+ # 7. LCM MultiStep Sampling Loop:
264
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
265
+ for i, t in enumerate(timesteps):
266
+ ts = torch.full((bs,), t, device=device, dtype=torch.long)
267
+ latents = latents.to(prompt_embeds.dtype)
268
+
269
+ # model prediction (v-prediction, eps, x)
270
+ model_pred = self.unet(
271
+ latents,
272
+ ts,
273
+ timestep_cond=w_embedding,
274
+ encoder_hidden_states=prompt_embeds,
275
+ cross_attention_kwargs=cross_attention_kwargs,
276
+ return_dict=False,
277
+ )[0]
278
+
279
+ # compute the previous noisy sample x_t -> x_t-1
280
+ latents, denoised = self.scheduler.step(model_pred, i, t, latents, return_dict=False)
281
+
282
+ # # call the callback, if provided
283
+ # if i == len(timesteps) - 1:
284
+ progress_bar.update()
285
+
286
+ denoised = denoised.to(prompt_embeds.dtype)
287
+ if not output_type == "latent":
288
+ image = self.vae.decode(denoised / self.vae.config.scaling_factor, return_dict=False)[0]
289
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
290
+ else:
291
+ image = denoised
292
+ has_nsfw_concept = None
293
+
294
+ if has_nsfw_concept is None:
295
+ do_denormalize = [True] * image.shape[0]
296
+ else:
297
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
298
+
299
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
300
+
301
+ if not return_dict:
302
+ return (image, has_nsfw_concept)
303
+
304
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
305
+
306
+
307
+ @dataclass
308
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
309
+ class LCMSchedulerOutput(BaseOutput):
310
+ """
311
+ Output class for the scheduler's `step` function output.
312
+ Args:
313
+ prev_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
314
+ Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
315
+ denoising loop.
316
+ pred_original_sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` for images):
317
+ The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
318
+ `pred_original_sample` can be used to preview progress or for guidance.
319
+ """
320
+
321
+ prev_sample: torch.Tensor
322
+ denoised: Optional[torch.Tensor] = None
323
+
324
+
325
+ # Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
326
+ def betas_for_alpha_bar(
327
+ num_diffusion_timesteps,
328
+ max_beta=0.999,
329
+ alpha_transform_type="cosine",
330
+ ):
331
+ """
332
+ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
333
+ (1-beta) over time from t = [0,1].
334
+ Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
335
+ to that part of the diffusion process.
336
+ Args:
337
+ num_diffusion_timesteps (`int`): the number of betas to produce.
338
+ max_beta (`float`): the maximum beta to use; use values lower than 1 to
339
+ prevent singularities.
340
+ alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
341
+ Choose from `cosine` or `exp`
342
+ Returns:
343
+ betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
344
+ """
345
+ if alpha_transform_type == "cosine":
346
+
347
+ def alpha_bar_fn(t):
348
+ return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
349
+
350
+ elif alpha_transform_type == "exp":
351
+
352
+ def alpha_bar_fn(t):
353
+ return math.exp(t * -12.0)
354
+
355
+ else:
356
+ raise ValueError(f"Unsupported alpha_transform_type: {alpha_transform_type}")
357
+
358
+ betas = []
359
+ for i in range(num_diffusion_timesteps):
360
+ t1 = i / num_diffusion_timesteps
361
+ t2 = (i + 1) / num_diffusion_timesteps
362
+ betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
363
+ return torch.tensor(betas, dtype=torch.float32)
364
+
365
+
366
+ def rescale_zero_terminal_snr(betas):
367
+ """
368
+ Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
369
+ Args:
370
+ betas (`torch.Tensor`):
371
+ the betas that the scheduler is being initialized with.
372
+ Returns:
373
+ `torch.Tensor`: rescaled betas with zero terminal SNR
374
+ """
375
+ # Convert betas to alphas_bar_sqrt
376
+ alphas = 1.0 - betas
377
+ alphas_cumprod = torch.cumprod(alphas, dim=0)
378
+ alphas_bar_sqrt = alphas_cumprod.sqrt()
379
+
380
+ # Store old values.
381
+ alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
382
+ alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
383
+
384
+ # Shift so the last timestep is zero.
385
+ alphas_bar_sqrt -= alphas_bar_sqrt_T
386
+
387
+ # Scale so the first timestep is back to the old value.
388
+ alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
389
+
390
+ # Convert alphas_bar_sqrt to betas
391
+ alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
392
+ alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
393
+ alphas = torch.cat([alphas_bar[0:1], alphas])
394
+ betas = 1 - alphas
395
+
396
+ return betas
397
+
398
+
399
+ class LCMScheduler(SchedulerMixin, ConfigMixin):
400
+ """
401
+ `LCMScheduler` extends the denoising procedure introduced in denoising diffusion probabilistic models (DDPMs) with
402
+ non-Markovian guidance.
403
+ This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
404
+ methods the library implements for all schedulers such as loading and saving.
405
+ Args:
406
+ num_train_timesteps (`int`, defaults to 1000):
407
+ The number of diffusion steps to train the model.
408
+ beta_start (`float`, defaults to 0.0001):
409
+ The starting `beta` value of inference.
410
+ beta_end (`float`, defaults to 0.02):
411
+ The final `beta` value.
412
+ beta_schedule (`str`, defaults to `"linear"`):
413
+ The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
414
+ `linear`, `scaled_linear`, or `squaredcos_cap_v2`.
415
+ trained_betas (`np.ndarray`, *optional*):
416
+ Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
417
+ clip_sample (`bool`, defaults to `True`):
418
+ Clip the predicted sample for numerical stability.
419
+ clip_sample_range (`float`, defaults to 1.0):
420
+ The maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
421
+ set_alpha_to_one (`bool`, defaults to `True`):
422
+ Each diffusion step uses the alphas product value at that step and at the previous one. For the final step
423
+ there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
424
+ otherwise it uses the alpha value at step 0.
425
+ steps_offset (`int`, defaults to 0):
426
+ An offset added to the inference steps, as required by some model families.
427
+ prediction_type (`str`, defaults to `epsilon`, *optional*):
428
+ Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
429
+ `sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
430
+ Video](https://imagen.research.google/video/paper.pdf) paper).
431
+ thresholding (`bool`, defaults to `False`):
432
+ Whether to use the "dynamic thresholding" method. This is unsuitable for latent-space diffusion models such
433
+ as Stable Diffusion.
434
+ dynamic_thresholding_ratio (`float`, defaults to 0.995):
435
+ The ratio for the dynamic thresholding method. Valid only when `thresholding=True`.
436
+ sample_max_value (`float`, defaults to 1.0):
437
+ The threshold value for dynamic thresholding. Valid only when `thresholding=True`.
438
+ timestep_spacing (`str`, defaults to `"leading"`):
439
+ The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
440
+ Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
441
+ rescale_betas_zero_snr (`bool`, defaults to `False`):
442
+ Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
443
+ dark samples instead of limiting it to samples with medium brightness. Loosely related to
444
+ [`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
445
+ """
446
+
447
+ # _compatibles = [e.name for e in KarrasDiffusionSchedulers]
448
+ order = 1
449
+
450
+ @register_to_config
451
+ def __init__(
452
+ self,
453
+ num_train_timesteps: int = 1000,
454
+ beta_start: float = 0.0001,
455
+ beta_end: float = 0.02,
456
+ beta_schedule: str = "linear",
457
+ trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
458
+ clip_sample: bool = True,
459
+ set_alpha_to_one: bool = True,
460
+ steps_offset: int = 0,
461
+ prediction_type: str = "epsilon",
462
+ thresholding: bool = False,
463
+ dynamic_thresholding_ratio: float = 0.995,
464
+ clip_sample_range: float = 1.0,
465
+ sample_max_value: float = 1.0,
466
+ timestep_spacing: str = "leading",
467
+ rescale_betas_zero_snr: bool = False,
468
+ ):
469
+ if trained_betas is not None:
470
+ self.betas = torch.tensor(trained_betas, dtype=torch.float32)
471
+ elif beta_schedule == "linear":
472
+ self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
473
+ elif beta_schedule == "scaled_linear":
474
+ # this schedule is very specific to the latent diffusion model.
475
+ self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
476
+ elif beta_schedule == "squaredcos_cap_v2":
477
+ # Glide cosine schedule
478
+ self.betas = betas_for_alpha_bar(num_train_timesteps)
479
+ else:
480
+ raise NotImplementedError(f"{beta_schedule} is not implemented for {self.__class__}")
481
+
482
+ # Rescale for zero SNR
483
+ if rescale_betas_zero_snr:
484
+ self.betas = rescale_zero_terminal_snr(self.betas)
485
+
486
+ self.alphas = 1.0 - self.betas
487
+ self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
488
+
489
+ # At every step in ddim, we are looking into the previous alphas_cumprod
490
+ # For the final step, there is no previous alphas_cumprod because we are already at 0
491
+ # `set_alpha_to_one` decides whether we set this parameter simply to one or
492
+ # whether we use the final alpha of the "non-previous" one.
493
+ self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
494
+
495
+ # standard deviation of the initial noise distribution
496
+ self.init_noise_sigma = 1.0
497
+
498
+ # setable values
499
+ self.num_inference_steps = None
500
+ self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps)[::-1].copy().astype(np.int64))
501
+
502
+ def scale_model_input(self, sample: torch.Tensor, timestep: Optional[int] = None) -> torch.Tensor:
503
+ """
504
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
505
+ current timestep.
506
+ Args:
507
+ sample (`torch.Tensor`):
508
+ The input sample.
509
+ timestep (`int`, *optional*):
510
+ The current timestep in the diffusion chain.
511
+ Returns:
512
+ `torch.Tensor`:
513
+ A scaled input sample.
514
+ """
515
+ return sample
516
+
517
+ def _get_variance(self, timestep, prev_timestep):
518
+ alpha_prod_t = self.alphas_cumprod[timestep]
519
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
520
+ beta_prod_t = 1 - alpha_prod_t
521
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
522
+
523
+ variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)
524
+
525
+ return variance
526
+
527
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler._threshold_sample
528
+ def _threshold_sample(self, sample: torch.Tensor) -> torch.Tensor:
529
+ """
530
+ "Dynamic thresholding: At each sampling step we set s to a certain percentile absolute pixel value in xt0 (the
531
+ prediction of x_0 at timestep t), and if s > 1, then we threshold xt0 to the range [-s, s] and then divide by
532
+ s. Dynamic thresholding pushes saturated pixels (those near -1 and 1) inwards, thereby actively preventing
533
+ pixels from saturation at each step. We find that dynamic thresholding results in significantly better
534
+ photorealism as well as better image-text alignment, especially when using very large guidance weights."
535
+ https://arxiv.org/abs/2205.11487
536
+ """
537
+ dtype = sample.dtype
538
+ batch_size, channels, height, width = sample.shape
539
+
540
+ if dtype not in (torch.float32, torch.float64):
541
+ sample = sample.float() # upcast for quantile calculation, and clamp not implemented for cpu half
542
+
543
+ # Flatten sample for doing quantile calculation along each image
544
+ sample = sample.reshape(batch_size, channels * height * width)
545
+
546
+ abs_sample = sample.abs() # "a certain percentile absolute pixel value"
547
+
548
+ s = torch.quantile(abs_sample, self.config.dynamic_thresholding_ratio, dim=1)
549
+ s = torch.clamp(
550
+ s, min=1, max=self.config.sample_max_value
551
+ ) # When clamped to min=1, equivalent to standard clipping to [-1, 1]
552
+
553
+ s = s.unsqueeze(1) # (batch_size, 1) because clamp will broadcast along dim=0
554
+ sample = torch.clamp(sample, -s, s) / s # "we threshold xt0 to the range [-s, s] and then divide by s"
555
+
556
+ sample = sample.reshape(batch_size, channels, height, width)
557
+ sample = sample.to(dtype)
558
+
559
+ return sample
560
+
561
+ def set_timesteps(self, num_inference_steps: int, lcm_origin_steps: int, device: Union[str, torch.device] = None):
562
+ """
563
+ Sets the discrete timesteps used for the diffusion chain (to be run before inference).
564
+ Args:
565
+ num_inference_steps (`int`):
566
+ The number of diffusion steps used when generating samples with a pre-trained model.
567
+ """
568
+
569
+ if num_inference_steps > self.config.num_train_timesteps:
570
+ raise ValueError(
571
+ f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"
572
+ f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"
573
+ f" maximal {self.config.num_train_timesteps} timesteps."
574
+ )
575
+
576
+ self.num_inference_steps = num_inference_steps
577
+
578
+ # LCM Timesteps Setting: # Linear Spacing
579
+ c = self.config.num_train_timesteps // lcm_origin_steps
580
+ lcm_origin_timesteps = np.asarray(list(range(1, lcm_origin_steps + 1))) * c - 1 # LCM Training Steps Schedule
581
+ skipping_step = len(lcm_origin_timesteps) // num_inference_steps
582
+ timesteps = lcm_origin_timesteps[::-skipping_step][:num_inference_steps] # LCM Inference Steps Schedule
583
+
584
+ self.timesteps = torch.from_numpy(timesteps.copy()).to(device)
585
+
586
+ def get_scalings_for_boundary_condition_discrete(self, t):
587
+ self.sigma_data = 0.5 # Default: 0.5
588
+
589
+ # By dividing 0.1: This is almost a delta function at t=0.
590
+ c_skip = self.sigma_data**2 / ((t / 0.1) ** 2 + self.sigma_data**2)
591
+ c_out = (t / 0.1) / ((t / 0.1) ** 2 + self.sigma_data**2) ** 0.5
592
+ return c_skip, c_out
593
+
594
+ def step(
595
+ self,
596
+ model_output: torch.Tensor,
597
+ timeindex: int,
598
+ timestep: int,
599
+ sample: torch.Tensor,
600
+ eta: float = 0.0,
601
+ use_clipped_model_output: bool = False,
602
+ generator=None,
603
+ variance_noise: Optional[torch.Tensor] = None,
604
+ return_dict: bool = True,
605
+ ) -> Union[LCMSchedulerOutput, Tuple]:
606
+ """
607
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
608
+ process from the learned model outputs (most often the predicted noise).
609
+ Args:
610
+ model_output (`torch.Tensor`):
611
+ The direct output from learned diffusion model.
612
+ timestep (`float`):
613
+ The current discrete timestep in the diffusion chain.
614
+ sample (`torch.Tensor`):
615
+ A current instance of a sample created by the diffusion process.
616
+ eta (`float`):
617
+ The weight of noise for added noise in diffusion step.
618
+ use_clipped_model_output (`bool`, defaults to `False`):
619
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
620
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
621
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
622
+ `use_clipped_model_output` has no effect.
623
+ generator (`torch.Generator`, *optional*):
624
+ A random number generator.
625
+ variance_noise (`torch.Tensor`):
626
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
627
+ itself. Useful for methods such as [`CycleDiffusion`].
628
+ return_dict (`bool`, *optional*, defaults to `True`):
629
+ Whether or not to return a [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] or `tuple`.
630
+ Returns:
631
+ [`~schedulers.scheduling_utils.LCMSchedulerOutput`] or `tuple`:
632
+ If return_dict is `True`, [`~schedulers.scheduling_lcm.LCMSchedulerOutput`] is returned, otherwise a
633
+ tuple is returned where the first element is the sample tensor.
634
+ """
635
+ if self.num_inference_steps is None:
636
+ raise ValueError(
637
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
638
+ )
639
+
640
+ # 1. get previous step value
641
+ prev_timeindex = timeindex + 1
642
+ if prev_timeindex < len(self.timesteps):
643
+ prev_timestep = self.timesteps[prev_timeindex]
644
+ else:
645
+ prev_timestep = timestep
646
+
647
+ # 2. compute alphas, betas
648
+ alpha_prod_t = self.alphas_cumprod[timestep]
649
+ alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
650
+
651
+ beta_prod_t = 1 - alpha_prod_t
652
+ beta_prod_t_prev = 1 - alpha_prod_t_prev
653
+
654
+ # 3. Get scalings for boundary conditions
655
+ c_skip, c_out = self.get_scalings_for_boundary_condition_discrete(timestep)
656
+
657
+ # 4. Different Parameterization:
658
+ parameterization = self.config.prediction_type
659
+
660
+ if parameterization == "epsilon": # noise-prediction
661
+ pred_x0 = (sample - beta_prod_t.sqrt() * model_output) / alpha_prod_t.sqrt()
662
+
663
+ elif parameterization == "sample": # x-prediction
664
+ pred_x0 = model_output
665
+
666
+ elif parameterization == "v_prediction": # v-prediction
667
+ pred_x0 = alpha_prod_t.sqrt() * sample - beta_prod_t.sqrt() * model_output
668
+
669
+ # 4. Denoise model output using boundary conditions
670
+ denoised = c_out * pred_x0 + c_skip * sample
671
+
672
+ # 5. Sample z ~ N(0, I), For MultiStep Inference
673
+ # Noise is not used for one-step sampling.
674
+ if len(self.timesteps) > 1:
675
+ noise = torch.randn(model_output.shape).to(model_output.device)
676
+ prev_sample = alpha_prod_t_prev.sqrt() * denoised + beta_prod_t_prev.sqrt() * noise
677
+ else:
678
+ prev_sample = denoised
679
+
680
+ if not return_dict:
681
+ return (prev_sample, denoised)
682
+
683
+ return LCMSchedulerOutput(prev_sample=prev_sample, denoised=denoised)
684
+
685
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.add_noise
686
+ def add_noise(
687
+ self,
688
+ original_samples: torch.Tensor,
689
+ noise: torch.Tensor,
690
+ timesteps: torch.IntTensor,
691
+ ) -> torch.Tensor:
692
+ # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
693
+ alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
694
+ timesteps = timesteps.to(original_samples.device)
695
+
696
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
697
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
698
+ while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
699
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
700
+
701
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
702
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
703
+ while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
704
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
705
+
706
+ noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
707
+ return noisy_samples
708
+
709
+ # Copied from diffusers.schedulers.scheduling_ddpm.DDPMScheduler.get_velocity
710
+ def get_velocity(self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.IntTensor) -> torch.Tensor:
711
+ # Make sure alphas_cumprod and timestep have same device and dtype as sample
712
+ alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype)
713
+ timesteps = timesteps.to(sample.device)
714
+
715
+ sqrt_alpha_prod = alphas_cumprod[timesteps] ** 0.5
716
+ sqrt_alpha_prod = sqrt_alpha_prod.flatten()
717
+ while len(sqrt_alpha_prod.shape) < len(sample.shape):
718
+ sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
719
+
720
+ sqrt_one_minus_alpha_prod = (1 - alphas_cumprod[timesteps]) ** 0.5
721
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
722
+ while len(sqrt_one_minus_alpha_prod.shape) < len(sample.shape):
723
+ sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
724
+
725
+ velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample
726
+ return velocity
727
+
728
+ def __len__(self):
729
+ return self.config.num_train_timesteps
v0.32.0/llm_grounded_diffusion.py ADDED
@@ -0,0 +1,1563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Long Lian, the GLIGEN Authors, and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This is a single file implementation of LMD+. See README.md for examples.
16
+
17
+ import ast
18
+ import gc
19
+ import inspect
20
+ import math
21
+ import warnings
22
+ from collections.abc import Iterable
23
+ from typing import Any, Callable, Dict, List, Optional, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ from packaging import version
28
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
29
+
30
+ from diffusers.configuration_utils import FrozenDict
31
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
32
+ from diffusers.loaders import (
33
+ FromSingleFileMixin,
34
+ IPAdapterMixin,
35
+ StableDiffusionLoraLoaderMixin,
36
+ TextualInversionLoaderMixin,
37
+ )
38
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
39
+ from diffusers.models.attention import Attention, GatedSelfAttentionDense
40
+ from diffusers.models.attention_processor import AttnProcessor2_0
41
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
42
+ from diffusers.pipelines import DiffusionPipeline
43
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
44
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
45
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
46
+ from diffusers.schedulers import KarrasDiffusionSchedulers
47
+ from diffusers.utils import (
48
+ USE_PEFT_BACKEND,
49
+ deprecate,
50
+ logging,
51
+ replace_example_docstring,
52
+ scale_lora_layers,
53
+ unscale_lora_layers,
54
+ )
55
+ from diffusers.utils.torch_utils import randn_tensor
56
+
57
+
58
+ EXAMPLE_DOC_STRING = """
59
+ Examples:
60
+ ```py
61
+ >>> import torch
62
+ >>> from diffusers import DiffusionPipeline
63
+
64
+ >>> pipe = DiffusionPipeline.from_pretrained(
65
+ ... "longlian/lmd_plus",
66
+ ... custom_pipeline="llm_grounded_diffusion",
67
+ ... custom_revision="main",
68
+ ... variant="fp16", torch_dtype=torch.float16
69
+ ... )
70
+ >>> pipe.enable_model_cpu_offload()
71
+
72
+ >>> # Generate an image described by the prompt and
73
+ >>> # insert objects described by text at the region defined by bounding boxes
74
+ >>> prompt = "a waterfall and a modern high speed train in a beautiful forest with fall foliage"
75
+ >>> boxes = [[0.1387, 0.2051, 0.4277, 0.7090], [0.4980, 0.4355, 0.8516, 0.7266]]
76
+ >>> phrases = ["a waterfall", "a modern high speed train"]
77
+
78
+ >>> images = pipe(
79
+ ... prompt=prompt,
80
+ ... phrases=phrases,
81
+ ... boxes=boxes,
82
+ ... gligen_scheduled_sampling_beta=0.4,
83
+ ... output_type="pil",
84
+ ... num_inference_steps=50,
85
+ ... lmd_guidance_kwargs={}
86
+ ... ).images
87
+
88
+ >>> images[0].save("./lmd_plus_generation.jpg")
89
+
90
+ >>> # Generate directly from a text prompt and an LLM response
91
+ >>> prompt = "a waterfall and a modern high speed train in a beautiful forest with fall foliage"
92
+ >>> phrases, boxes, bg_prompt, neg_prompt = pipe.parse_llm_response(\"""
93
+ [('a waterfall', [71, 105, 148, 258]), ('a modern high speed train', [255, 223, 181, 149])]
94
+ Background prompt: A beautiful forest with fall foliage
95
+ Negative prompt:
96
+ \""")
97
+
98
+ >> images = pipe(
99
+ ... prompt=prompt,
100
+ ... negative_prompt=neg_prompt,
101
+ ... phrases=phrases,
102
+ ... boxes=boxes,
103
+ ... gligen_scheduled_sampling_beta=0.4,
104
+ ... output_type="pil",
105
+ ... num_inference_steps=50,
106
+ ... lmd_guidance_kwargs={}
107
+ ... ).images
108
+
109
+ >>> images[0].save("./lmd_plus_generation.jpg")
110
+
111
+ images[0]
112
+
113
+ ```
114
+ """
115
+
116
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
117
+
118
+ # All keys in Stable Diffusion models: [('down', 0, 0, 0), ('down', 0, 1, 0), ('down', 1, 0, 0), ('down', 1, 1, 0), ('down', 2, 0, 0), ('down', 2, 1, 0), ('mid', 0, 0, 0), ('up', 1, 0, 0), ('up', 1, 1, 0), ('up', 1, 2, 0), ('up', 2, 0, 0), ('up', 2, 1, 0), ('up', 2, 2, 0), ('up', 3, 0, 0), ('up', 3, 1, 0), ('up', 3, 2, 0)]
119
+ # Note that the first up block is `UpBlock2D` rather than `CrossAttnUpBlock2D` and does not have attention. The last index is always 0 in our case since we have one `BasicTransformerBlock` in each `Transformer2DModel`.
120
+ DEFAULT_GUIDANCE_ATTN_KEYS = [
121
+ ("mid", 0, 0, 0),
122
+ ("up", 1, 0, 0),
123
+ ("up", 1, 1, 0),
124
+ ("up", 1, 2, 0),
125
+ ]
126
+
127
+
128
+ def convert_attn_keys(key):
129
+ """Convert the attention key from tuple format to the torch state format"""
130
+
131
+ if key[0] == "mid":
132
+ assert key[1] == 0, f"mid block only has one block but the index is {key[1]}"
133
+ return f"{key[0]}_block.attentions.{key[2]}.transformer_blocks.{key[3]}.attn2.processor"
134
+
135
+ return f"{key[0]}_blocks.{key[1]}.attentions.{key[2]}.transformer_blocks.{key[3]}.attn2.processor"
136
+
137
+
138
+ DEFAULT_GUIDANCE_ATTN_KEYS = [convert_attn_keys(key) for key in DEFAULT_GUIDANCE_ATTN_KEYS]
139
+
140
+
141
+ def scale_proportion(obj_box, H, W):
142
+ # Separately rounding box_w and box_h to allow shift invariant box sizes. Otherwise box sizes may change when both coordinates being rounded end with ".5".
143
+ x_min, y_min = round(obj_box[0] * W), round(obj_box[1] * H)
144
+ box_w, box_h = round((obj_box[2] - obj_box[0]) * W), round((obj_box[3] - obj_box[1]) * H)
145
+ x_max, y_max = x_min + box_w, y_min + box_h
146
+
147
+ x_min, y_min = max(x_min, 0), max(y_min, 0)
148
+ x_max, y_max = min(x_max, W), min(y_max, H)
149
+
150
+ return x_min, y_min, x_max, y_max
151
+
152
+
153
+ # Adapted from the parent class `AttnProcessor2_0`
154
+ class AttnProcessorWithHook(AttnProcessor2_0):
155
+ def __init__(
156
+ self,
157
+ attn_processor_key,
158
+ hidden_size,
159
+ cross_attention_dim,
160
+ hook=None,
161
+ fast_attn=True,
162
+ enabled=True,
163
+ ):
164
+ super().__init__()
165
+ self.attn_processor_key = attn_processor_key
166
+ self.hidden_size = hidden_size
167
+ self.cross_attention_dim = cross_attention_dim
168
+ self.hook = hook
169
+ self.fast_attn = fast_attn
170
+ self.enabled = enabled
171
+
172
+ def __call__(
173
+ self,
174
+ attn: Attention,
175
+ hidden_states,
176
+ encoder_hidden_states=None,
177
+ attention_mask=None,
178
+ temb=None,
179
+ scale: float = 1.0,
180
+ ):
181
+ residual = hidden_states
182
+
183
+ if attn.spatial_norm is not None:
184
+ hidden_states = attn.spatial_norm(hidden_states, temb)
185
+
186
+ input_ndim = hidden_states.ndim
187
+
188
+ if input_ndim == 4:
189
+ batch_size, channel, height, width = hidden_states.shape
190
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
191
+
192
+ batch_size, sequence_length, _ = (
193
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
194
+ )
195
+
196
+ if attention_mask is not None:
197
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
198
+
199
+ if attn.group_norm is not None:
200
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
201
+
202
+ args = () if USE_PEFT_BACKEND else (scale,)
203
+ query = attn.to_q(hidden_states, *args)
204
+
205
+ if encoder_hidden_states is None:
206
+ encoder_hidden_states = hidden_states
207
+ elif attn.norm_cross:
208
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
209
+
210
+ key = attn.to_k(encoder_hidden_states, *args)
211
+ value = attn.to_v(encoder_hidden_states, *args)
212
+
213
+ inner_dim = key.shape[-1]
214
+ head_dim = inner_dim // attn.heads
215
+
216
+ if (self.hook is not None and self.enabled) or not self.fast_attn:
217
+ query_batch_dim = attn.head_to_batch_dim(query)
218
+ key_batch_dim = attn.head_to_batch_dim(key)
219
+ value_batch_dim = attn.head_to_batch_dim(value)
220
+ attention_probs = attn.get_attention_scores(query_batch_dim, key_batch_dim, attention_mask)
221
+
222
+ if self.hook is not None and self.enabled:
223
+ # Call the hook with query, key, value, and attention maps
224
+ self.hook(
225
+ self.attn_processor_key,
226
+ query_batch_dim,
227
+ key_batch_dim,
228
+ value_batch_dim,
229
+ attention_probs,
230
+ )
231
+
232
+ if self.fast_attn:
233
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
234
+
235
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
236
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
237
+
238
+ if attention_mask is not None:
239
+ # scaled_dot_product_attention expects attention_mask shape to be
240
+ # (batch, heads, source_length, target_length)
241
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
242
+
243
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
244
+ # TODO: add support for attn.scale when we move to Torch 2.1
245
+ hidden_states = F.scaled_dot_product_attention(
246
+ query,
247
+ key,
248
+ value,
249
+ attn_mask=attention_mask,
250
+ dropout_p=0.0,
251
+ is_causal=False,
252
+ )
253
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
254
+ hidden_states = hidden_states.to(query.dtype)
255
+ else:
256
+ hidden_states = torch.bmm(attention_probs, value)
257
+ hidden_states = attn.batch_to_head_dim(hidden_states)
258
+
259
+ # linear proj
260
+ hidden_states = attn.to_out[0](hidden_states, *args)
261
+ # dropout
262
+ hidden_states = attn.to_out[1](hidden_states)
263
+
264
+ if input_ndim == 4:
265
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
266
+
267
+ if attn.residual_connection:
268
+ hidden_states = hidden_states + residual
269
+
270
+ hidden_states = hidden_states / attn.rescale_output_factor
271
+
272
+ return hidden_states
273
+
274
+
275
+ class LLMGroundedDiffusionPipeline(
276
+ DiffusionPipeline,
277
+ StableDiffusionMixin,
278
+ TextualInversionLoaderMixin,
279
+ StableDiffusionLoraLoaderMixin,
280
+ IPAdapterMixin,
281
+ FromSingleFileMixin,
282
+ ):
283
+ r"""
284
+ Pipeline for layout-grounded text-to-image generation using LLM-grounded Diffusion (LMD+): https://arxiv.org/pdf/2305.13655.pdf.
285
+
286
+ This model inherits from [`StableDiffusionPipeline`] and aims at implementing the pipeline with minimal modifications. Check the superclass documentation for the generic methods
287
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
288
+
289
+ This is a simplified implementation that does not perform latent or attention transfer from single object generation to overall generation. The final image is generated directly with attention and adapters control.
290
+
291
+ Args:
292
+ vae ([`AutoencoderKL`]):
293
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
294
+ text_encoder ([`~transformers.CLIPTextModel`]):
295
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
296
+ tokenizer ([`~transformers.CLIPTokenizer`]):
297
+ A `CLIPTokenizer` to tokenize text.
298
+ unet ([`UNet2DConditionModel`]):
299
+ A `UNet2DConditionModel` to denoise the encoded image latents.
300
+ scheduler ([`SchedulerMixin`]):
301
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
302
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
303
+ safety_checker ([`StableDiffusionSafetyChecker`]):
304
+ Classification module that estimates whether generated images could be considered offensive or harmful.
305
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
306
+ about a model's potential harms.
307
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
308
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
309
+ requires_safety_checker (bool):
310
+ Whether a safety checker is needed for this pipeline.
311
+ """
312
+
313
+ model_cpu_offload_seq = "text_encoder->unet->vae"
314
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
315
+ _exclude_from_cpu_offload = ["safety_checker"]
316
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
317
+
318
+ objects_text = "Objects: "
319
+ bg_prompt_text = "Background prompt: "
320
+ bg_prompt_text_no_trailing_space = bg_prompt_text.rstrip()
321
+ neg_prompt_text = "Negative prompt: "
322
+ neg_prompt_text_no_trailing_space = neg_prompt_text.rstrip()
323
+
324
+ def __init__(
325
+ self,
326
+ vae: AutoencoderKL,
327
+ text_encoder: CLIPTextModel,
328
+ tokenizer: CLIPTokenizer,
329
+ unet: UNet2DConditionModel,
330
+ scheduler: KarrasDiffusionSchedulers,
331
+ safety_checker: StableDiffusionSafetyChecker,
332
+ feature_extractor: CLIPImageProcessor,
333
+ image_encoder: CLIPVisionModelWithProjection = None,
334
+ requires_safety_checker: bool = True,
335
+ ):
336
+ # This is copied from StableDiffusionPipeline, with hook initizations for LMD+.
337
+ super().__init__()
338
+
339
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
340
+ deprecation_message = (
341
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
342
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
343
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
344
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
345
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
346
+ " file"
347
+ )
348
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
349
+ new_config = dict(scheduler.config)
350
+ new_config["steps_offset"] = 1
351
+ scheduler._internal_dict = FrozenDict(new_config)
352
+
353
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
354
+ deprecation_message = (
355
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
356
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
357
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
358
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
359
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
360
+ )
361
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
362
+ new_config = dict(scheduler.config)
363
+ new_config["clip_sample"] = False
364
+ scheduler._internal_dict = FrozenDict(new_config)
365
+
366
+ if safety_checker is None and requires_safety_checker:
367
+ logger.warning(
368
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
369
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
370
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
371
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
372
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
373
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
374
+ )
375
+
376
+ if safety_checker is not None and feature_extractor is None:
377
+ raise ValueError(
378
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
379
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
380
+ )
381
+
382
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
383
+ version.parse(unet.config._diffusers_version).base_version
384
+ ) < version.parse("0.9.0.dev0")
385
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
386
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
387
+ deprecation_message = (
388
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
389
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
390
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
391
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
392
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
393
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
394
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
395
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
396
+ " the `unet/config.json` file"
397
+ )
398
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
399
+ new_config = dict(unet.config)
400
+ new_config["sample_size"] = 64
401
+ unet._internal_dict = FrozenDict(new_config)
402
+
403
+ self.register_modules(
404
+ vae=vae,
405
+ text_encoder=text_encoder,
406
+ tokenizer=tokenizer,
407
+ unet=unet,
408
+ scheduler=scheduler,
409
+ safety_checker=safety_checker,
410
+ feature_extractor=feature_extractor,
411
+ image_encoder=image_encoder,
412
+ )
413
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
414
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
415
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
416
+
417
+ # Initialize the attention hooks for LLM-grounded Diffusion
418
+ self.register_attn_hooks(unet)
419
+ self._saved_attn = None
420
+
421
+ def attn_hook(self, name, query, key, value, attention_probs):
422
+ if name in DEFAULT_GUIDANCE_ATTN_KEYS:
423
+ self._saved_attn[name] = attention_probs
424
+
425
+ @classmethod
426
+ def convert_box(cls, box, height, width):
427
+ # box: x, y, w, h (in 512 format) -> x_min, y_min, x_max, y_max
428
+ x_min, y_min = box[0] / width, box[1] / height
429
+ w_box, h_box = box[2] / width, box[3] / height
430
+
431
+ x_max, y_max = x_min + w_box, y_min + h_box
432
+
433
+ return x_min, y_min, x_max, y_max
434
+
435
+ @classmethod
436
+ def _parse_response_with_negative(cls, text):
437
+ if not text:
438
+ raise ValueError("LLM response is empty")
439
+
440
+ if cls.objects_text in text:
441
+ text = text.split(cls.objects_text)[1]
442
+
443
+ text_split = text.split(cls.bg_prompt_text_no_trailing_space)
444
+ if len(text_split) == 2:
445
+ gen_boxes, text_rem = text_split
446
+ else:
447
+ raise ValueError(f"LLM response is incomplete: {text}")
448
+
449
+ text_split = text_rem.split(cls.neg_prompt_text_no_trailing_space)
450
+
451
+ if len(text_split) == 2:
452
+ bg_prompt, neg_prompt = text_split
453
+ else:
454
+ raise ValueError(f"LLM response is incomplete: {text}")
455
+
456
+ try:
457
+ gen_boxes = ast.literal_eval(gen_boxes)
458
+ except SyntaxError as e:
459
+ # Sometimes the response is in plain text
460
+ if "No objects" in gen_boxes or gen_boxes.strip() == "":
461
+ gen_boxes = []
462
+ else:
463
+ raise e
464
+ bg_prompt = bg_prompt.strip()
465
+ neg_prompt = neg_prompt.strip()
466
+
467
+ # LLM may return "None" to mean no negative prompt provided.
468
+ if neg_prompt == "None":
469
+ neg_prompt = ""
470
+
471
+ return gen_boxes, bg_prompt, neg_prompt
472
+
473
+ @classmethod
474
+ def parse_llm_response(cls, response, canvas_height=512, canvas_width=512):
475
+ # Infer from spec
476
+ gen_boxes, bg_prompt, neg_prompt = cls._parse_response_with_negative(text=response)
477
+
478
+ gen_boxes = sorted(gen_boxes, key=lambda gen_box: gen_box[0])
479
+
480
+ phrases = [name for name, _ in gen_boxes]
481
+ boxes = [cls.convert_box(box, height=canvas_height, width=canvas_width) for _, box in gen_boxes]
482
+
483
+ return phrases, boxes, bg_prompt, neg_prompt
484
+
485
+ def check_inputs(
486
+ self,
487
+ prompt,
488
+ height,
489
+ width,
490
+ callback_steps,
491
+ phrases,
492
+ boxes,
493
+ negative_prompt=None,
494
+ prompt_embeds=None,
495
+ negative_prompt_embeds=None,
496
+ phrase_indices=None,
497
+ ):
498
+ if height % 8 != 0 or width % 8 != 0:
499
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
500
+
501
+ if (callback_steps is None) or (
502
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
503
+ ):
504
+ raise ValueError(
505
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
506
+ f" {type(callback_steps)}."
507
+ )
508
+
509
+ if prompt is not None and prompt_embeds is not None:
510
+ raise ValueError(
511
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
512
+ " only forward one of the two."
513
+ )
514
+ elif prompt is None and prompt_embeds is None:
515
+ raise ValueError(
516
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
517
+ )
518
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
519
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
520
+ elif prompt is None and phrase_indices is None:
521
+ raise ValueError("If the prompt is None, the phrase_indices cannot be None")
522
+
523
+ if negative_prompt is not None and negative_prompt_embeds is not None:
524
+ raise ValueError(
525
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
526
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
527
+ )
528
+
529
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
530
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
531
+ raise ValueError(
532
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
533
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
534
+ f" {negative_prompt_embeds.shape}."
535
+ )
536
+
537
+ if len(phrases) != len(boxes):
538
+ raise ValueError(
539
+ "length of `phrases` and `boxes` has to be same, but"
540
+ f" got: `phrases` {len(phrases)} != `boxes` {len(boxes)}"
541
+ )
542
+
543
+ def register_attn_hooks(self, unet):
544
+ """Registering hooks to obtain the attention maps for guidance"""
545
+
546
+ attn_procs = {}
547
+
548
+ for name in unet.attn_processors.keys():
549
+ # Only obtain the queries and keys from cross-attention
550
+ if name.endswith("attn1.processor") or name.endswith("fuser.attn.processor"):
551
+ # Keep the same attn_processors for self-attention (no hooks for self-attention)
552
+ attn_procs[name] = unet.attn_processors[name]
553
+ continue
554
+
555
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
556
+
557
+ if name.startswith("mid_block"):
558
+ hidden_size = unet.config.block_out_channels[-1]
559
+ elif name.startswith("up_blocks"):
560
+ block_id = int(name[len("up_blocks.")])
561
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
562
+ elif name.startswith("down_blocks"):
563
+ block_id = int(name[len("down_blocks.")])
564
+ hidden_size = unet.config.block_out_channels[block_id]
565
+
566
+ attn_procs[name] = AttnProcessorWithHook(
567
+ attn_processor_key=name,
568
+ hidden_size=hidden_size,
569
+ cross_attention_dim=cross_attention_dim,
570
+ hook=self.attn_hook,
571
+ fast_attn=True,
572
+ # Not enabled by default
573
+ enabled=False,
574
+ )
575
+
576
+ unet.set_attn_processor(attn_procs)
577
+
578
+ def enable_fuser(self, enabled=True):
579
+ for module in self.unet.modules():
580
+ if isinstance(module, GatedSelfAttentionDense):
581
+ module.enabled = enabled
582
+
583
+ def enable_attn_hook(self, enabled=True):
584
+ for module in self.unet.attn_processors.values():
585
+ if isinstance(module, AttnProcessorWithHook):
586
+ module.enabled = enabled
587
+
588
+ def get_token_map(self, prompt, padding="do_not_pad", verbose=False):
589
+ """Get a list of mapping: prompt index to str (prompt in a list of token str)"""
590
+ fg_prompt_tokens = self.tokenizer([prompt], padding=padding, max_length=77, return_tensors="np")
591
+ input_ids = fg_prompt_tokens["input_ids"][0]
592
+
593
+ token_map = []
594
+ for ind, item in enumerate(input_ids.tolist()):
595
+ token = self.tokenizer._convert_id_to_token(item)
596
+
597
+ if verbose:
598
+ logger.info(f"{ind}, {token} ({item})")
599
+
600
+ token_map.append(token)
601
+
602
+ return token_map
603
+
604
+ def get_phrase_indices(
605
+ self,
606
+ prompt,
607
+ phrases,
608
+ token_map=None,
609
+ add_suffix_if_not_found=False,
610
+ verbose=False,
611
+ ):
612
+ for obj in phrases:
613
+ # Suffix the prompt with object name for attention guidance if object is not in the prompt, using "|" to separate the prompt and the suffix
614
+ if obj not in prompt:
615
+ prompt += "| " + obj
616
+
617
+ if token_map is None:
618
+ # We allow using a pre-computed token map.
619
+ token_map = self.get_token_map(prompt=prompt, padding="do_not_pad", verbose=verbose)
620
+ token_map_str = " ".join(token_map)
621
+
622
+ phrase_indices = []
623
+
624
+ for obj in phrases:
625
+ phrase_token_map = self.get_token_map(prompt=obj, padding="do_not_pad", verbose=verbose)
626
+ # Remove <bos> and <eos> in substr
627
+ phrase_token_map = phrase_token_map[1:-1]
628
+ phrase_token_map_len = len(phrase_token_map)
629
+ phrase_token_map_str = " ".join(phrase_token_map)
630
+
631
+ if verbose:
632
+ logger.info(
633
+ "Full str:",
634
+ token_map_str,
635
+ "Substr:",
636
+ phrase_token_map_str,
637
+ "Phrase:",
638
+ phrases,
639
+ )
640
+
641
+ # Count the number of token before substr
642
+ # The substring comes with a trailing space that needs to be removed by minus one in the index.
643
+ obj_first_index = len(token_map_str[: token_map_str.index(phrase_token_map_str) - 1].split(" "))
644
+
645
+ obj_position = list(range(obj_first_index, obj_first_index + phrase_token_map_len))
646
+ phrase_indices.append(obj_position)
647
+
648
+ if add_suffix_if_not_found:
649
+ return phrase_indices, prompt
650
+
651
+ return phrase_indices
652
+
653
+ def add_ca_loss_per_attn_map_to_loss(
654
+ self,
655
+ loss,
656
+ attn_map,
657
+ object_number,
658
+ bboxes,
659
+ phrase_indices,
660
+ fg_top_p=0.2,
661
+ bg_top_p=0.2,
662
+ fg_weight=1.0,
663
+ bg_weight=1.0,
664
+ ):
665
+ # b is the number of heads, not batch
666
+ b, i, j = attn_map.shape
667
+ H = W = int(math.sqrt(i))
668
+ for obj_idx in range(object_number):
669
+ obj_loss = 0
670
+ mask = torch.zeros(size=(H, W), device="cuda")
671
+ obj_boxes = bboxes[obj_idx]
672
+
673
+ # We support two level (one box per phrase) and three level (multiple boxes per phrase)
674
+ if not isinstance(obj_boxes[0], Iterable):
675
+ obj_boxes = [obj_boxes]
676
+
677
+ for obj_box in obj_boxes:
678
+ # x_min, y_min, x_max, y_max = int(obj_box[0] * W), int(obj_box[1] * H), int(obj_box[2] * W), int(obj_box[3] * H)
679
+ x_min, y_min, x_max, y_max = scale_proportion(obj_box, H=H, W=W)
680
+ mask[y_min:y_max, x_min:x_max] = 1
681
+
682
+ for obj_position in phrase_indices[obj_idx]:
683
+ # Could potentially optimize to compute this for loop in batch.
684
+ # Could crop the ref cross attention before saving to save memory.
685
+
686
+ ca_map_obj = attn_map[:, :, obj_position].reshape(b, H, W)
687
+
688
+ # shape: (b, H * W)
689
+ ca_map_obj = attn_map[:, :, obj_position] # .reshape(b, H, W)
690
+ k_fg = (mask.sum() * fg_top_p).long().clamp_(min=1)
691
+ k_bg = ((1 - mask).sum() * bg_top_p).long().clamp_(min=1)
692
+
693
+ mask_1d = mask.view(1, -1)
694
+
695
+ # Max-based loss function
696
+
697
+ # Take the topk over spatial dimension, and then take the sum over heads dim
698
+ # The mean is over k_fg and k_bg dimension, so we don't need to sum and divide on our own.
699
+ obj_loss += (1 - (ca_map_obj * mask_1d).topk(k=k_fg).values.mean(dim=1)).sum(dim=0) * fg_weight
700
+ obj_loss += ((ca_map_obj * (1 - mask_1d)).topk(k=k_bg).values.mean(dim=1)).sum(dim=0) * bg_weight
701
+
702
+ loss += obj_loss / len(phrase_indices[obj_idx])
703
+
704
+ return loss
705
+
706
+ def compute_ca_loss(
707
+ self,
708
+ saved_attn,
709
+ bboxes,
710
+ phrase_indices,
711
+ guidance_attn_keys,
712
+ verbose=False,
713
+ **kwargs,
714
+ ):
715
+ """
716
+ The `saved_attn` is supposed to be passed to `save_attn_to_dict` in `cross_attention_kwargs` prior to computing ths loss.
717
+ `AttnProcessor` will put attention maps into the `save_attn_to_dict`.
718
+
719
+ `index` is the timestep.
720
+ `ref_ca_word_token_only`: This has precedence over `ref_ca_last_token_only` (i.e., if both are enabled, we take the token from word rather than the last token).
721
+ `ref_ca_last_token_only`: `ref_ca_saved_attn` comes from the attention map of the last token of the phrase in single object generation, so we apply it only to the last token of the phrase in overall generation if this is set to True. If set to False, `ref_ca_saved_attn` will be applied to all the text tokens.
722
+ """
723
+ loss = torch.tensor(0).float().cuda()
724
+ object_number = len(bboxes)
725
+ if object_number == 0:
726
+ return loss
727
+
728
+ for attn_key in guidance_attn_keys:
729
+ # We only have 1 cross attention for mid.
730
+
731
+ attn_map_integrated = saved_attn[attn_key]
732
+ if not attn_map_integrated.is_cuda:
733
+ attn_map_integrated = attn_map_integrated.cuda()
734
+ # Example dimension: [20, 64, 77]
735
+ attn_map = attn_map_integrated.squeeze(dim=0)
736
+
737
+ loss = self.add_ca_loss_per_attn_map_to_loss(
738
+ loss, attn_map, object_number, bboxes, phrase_indices, **kwargs
739
+ )
740
+
741
+ num_attn = len(guidance_attn_keys)
742
+
743
+ if num_attn > 0:
744
+ loss = loss / (object_number * num_attn)
745
+
746
+ return loss
747
+
748
+ @torch.no_grad()
749
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
750
+ def __call__(
751
+ self,
752
+ prompt: Union[str, List[str]] = None,
753
+ height: Optional[int] = None,
754
+ width: Optional[int] = None,
755
+ num_inference_steps: int = 50,
756
+ guidance_scale: float = 7.5,
757
+ gligen_scheduled_sampling_beta: float = 0.3,
758
+ phrases: List[str] = None,
759
+ boxes: List[List[float]] = None,
760
+ negative_prompt: Optional[Union[str, List[str]]] = None,
761
+ num_images_per_prompt: Optional[int] = 1,
762
+ eta: float = 0.0,
763
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
764
+ latents: Optional[torch.Tensor] = None,
765
+ prompt_embeds: Optional[torch.Tensor] = None,
766
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
767
+ ip_adapter_image: Optional[PipelineImageInput] = None,
768
+ output_type: Optional[str] = "pil",
769
+ return_dict: bool = True,
770
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
771
+ callback_steps: int = 1,
772
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
773
+ clip_skip: Optional[int] = None,
774
+ lmd_guidance_kwargs: Optional[Dict[str, Any]] = {},
775
+ phrase_indices: Optional[List[int]] = None,
776
+ ):
777
+ r"""
778
+ The call function to the pipeline for generation.
779
+
780
+ Args:
781
+ prompt (`str` or `List[str]`, *optional*):
782
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
783
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
784
+ The height in pixels of the generated image.
785
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
786
+ The width in pixels of the generated image.
787
+ num_inference_steps (`int`, *optional*, defaults to 50):
788
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
789
+ expense of slower inference.
790
+ guidance_scale (`float`, *optional*, defaults to 7.5):
791
+ A higher guidance scale value encourages the model to generate images closely linked to the text
792
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
793
+ phrases (`List[str]`):
794
+ The phrases to guide what to include in each of the regions defined by the corresponding
795
+ `boxes`. There should only be one phrase per bounding box.
796
+ boxes (`List[List[float]]`):
797
+ The bounding boxes that identify rectangular regions of the image that are going to be filled with the
798
+ content described by the corresponding `phrases`. Each rectangular box is defined as a
799
+ `List[float]` of 4 elements `[xmin, ymin, xmax, ymax]` where each value is between [0,1].
800
+ gligen_scheduled_sampling_beta (`float`, defaults to 0.3):
801
+ Scheduled Sampling factor from [GLIGEN: Open-Set Grounded Text-to-Image
802
+ Generation](https://arxiv.org/pdf/2301.07093.pdf). Scheduled Sampling factor is only varied for
803
+ scheduled sampling during inference for improved quality and controllability.
804
+ negative_prompt (`str` or `List[str]`, *optional*):
805
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
806
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
807
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
808
+ The number of images to generate per prompt.
809
+ eta (`float`, *optional*, defaults to 0.0):
810
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
811
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
812
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
813
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
814
+ generation deterministic.
815
+ latents (`torch.Tensor`, *optional*):
816
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
817
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
818
+ tensor is generated by sampling using the supplied random `generator`.
819
+ prompt_embeds (`torch.Tensor`, *optional*):
820
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
821
+ provided, text embeddings are generated from the `prompt` input argument.
822
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
823
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
824
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
825
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
826
+ output_type (`str`, *optional*, defaults to `"pil"`):
827
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
828
+ return_dict (`bool`, *optional*, defaults to `True`):
829
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
830
+ plain tuple.
831
+ callback (`Callable`, *optional*):
832
+ A function that calls every `callback_steps` steps during inference. The function is called with the
833
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
834
+ callback_steps (`int`, *optional*, defaults to 1):
835
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
836
+ every step.
837
+ cross_attention_kwargs (`dict`, *optional*):
838
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
839
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
840
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
841
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
842
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
843
+ using zero terminal SNR.
844
+ clip_skip (`int`, *optional*):
845
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
846
+ the output of the pre-final layer will be used for computing the prompt embeddings.
847
+ lmd_guidance_kwargs (`dict`, *optional*):
848
+ A kwargs dictionary that if specified is passed along to `latent_lmd_guidance` function. Useful keys include `loss_scale` (the guidance strength), `loss_threshold` (when loss is lower than this value, the guidance is not applied anymore), `max_iter` (the number of iterations of guidance for each step), and `guidance_timesteps` (the number of diffusion timesteps to apply guidance on). See `latent_lmd_guidance` for implementation details.
849
+ phrase_indices (`list` of `list`, *optional*): The indices of the tokens of each phrase in the overall prompt. If omitted, the pipeline will match the first token subsequence. The pipeline will append the missing phrases to the end of the prompt by default.
850
+ Examples:
851
+
852
+ Returns:
853
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
854
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
855
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
856
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
857
+ "not-safe-for-work" (nsfw) content.
858
+ """
859
+ # 0. Default height and width to unet
860
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
861
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
862
+
863
+ # 1. Check inputs. Raise error if not correct
864
+ self.check_inputs(
865
+ prompt,
866
+ height,
867
+ width,
868
+ callback_steps,
869
+ phrases,
870
+ boxes,
871
+ negative_prompt,
872
+ prompt_embeds,
873
+ negative_prompt_embeds,
874
+ phrase_indices,
875
+ )
876
+
877
+ # 2. Define call parameters
878
+ if prompt is not None and isinstance(prompt, str):
879
+ batch_size = 1
880
+ if phrase_indices is None:
881
+ phrase_indices, prompt = self.get_phrase_indices(prompt, phrases, add_suffix_if_not_found=True)
882
+ elif prompt is not None and isinstance(prompt, list):
883
+ batch_size = len(prompt)
884
+ if phrase_indices is None:
885
+ phrase_indices = []
886
+ prompt_parsed = []
887
+ for prompt_item in prompt:
888
+ (
889
+ phrase_indices_parsed_item,
890
+ prompt_parsed_item,
891
+ ) = self.get_phrase_indices(prompt_item, add_suffix_if_not_found=True)
892
+ phrase_indices.append(phrase_indices_parsed_item)
893
+ prompt_parsed.append(prompt_parsed_item)
894
+ prompt = prompt_parsed
895
+ else:
896
+ batch_size = prompt_embeds.shape[0]
897
+
898
+ device = self._execution_device
899
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
900
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
901
+ # corresponds to doing no classifier free guidance.
902
+ do_classifier_free_guidance = guidance_scale > 1.0
903
+
904
+ # 3. Encode input prompt
905
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
906
+ prompt,
907
+ device,
908
+ num_images_per_prompt,
909
+ do_classifier_free_guidance,
910
+ negative_prompt,
911
+ prompt_embeds=prompt_embeds,
912
+ negative_prompt_embeds=negative_prompt_embeds,
913
+ clip_skip=clip_skip,
914
+ )
915
+
916
+ cond_prompt_embeds = prompt_embeds
917
+
918
+ # For classifier free guidance, we need to do two forward passes.
919
+ # Here we concatenate the unconditional and text embeddings into a single batch
920
+ # to avoid doing two forward passes
921
+ if do_classifier_free_guidance:
922
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
923
+
924
+ if ip_adapter_image is not None:
925
+ image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_images_per_prompt)
926
+ if self.do_classifier_free_guidance:
927
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
928
+
929
+ # 4. Prepare timesteps
930
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
931
+ timesteps = self.scheduler.timesteps
932
+
933
+ # 5. Prepare latent variables
934
+ num_channels_latents = self.unet.config.in_channels
935
+ latents = self.prepare_latents(
936
+ batch_size * num_images_per_prompt,
937
+ num_channels_latents,
938
+ height,
939
+ width,
940
+ prompt_embeds.dtype,
941
+ device,
942
+ generator,
943
+ latents,
944
+ )
945
+
946
+ # 5.1 Prepare GLIGEN variables
947
+ max_objs = 30
948
+ if len(boxes) > max_objs:
949
+ warnings.warn(
950
+ f"More that {max_objs} objects found. Only first {max_objs} objects will be processed.",
951
+ FutureWarning,
952
+ )
953
+ phrases = phrases[:max_objs]
954
+ boxes = boxes[:max_objs]
955
+
956
+ n_objs = len(boxes)
957
+ if n_objs:
958
+ # prepare batched input to the PositionNet (boxes, phrases, mask)
959
+ # Get tokens for phrases from pre-trained CLIPTokenizer
960
+ tokenizer_inputs = self.tokenizer(phrases, padding=True, return_tensors="pt").to(device)
961
+ # For the token, we use the same pre-trained text encoder
962
+ # to obtain its text feature
963
+ _text_embeddings = self.text_encoder(**tokenizer_inputs).pooler_output
964
+
965
+ # For each entity, described in phrases, is denoted with a bounding box,
966
+ # we represent the location information as (xmin,ymin,xmax,ymax)
967
+ cond_boxes = torch.zeros(max_objs, 4, device=device, dtype=self.text_encoder.dtype)
968
+ if n_objs:
969
+ cond_boxes[:n_objs] = torch.tensor(boxes)
970
+ text_embeddings = torch.zeros(
971
+ max_objs,
972
+ self.unet.config.cross_attention_dim,
973
+ device=device,
974
+ dtype=self.text_encoder.dtype,
975
+ )
976
+ if n_objs:
977
+ text_embeddings[:n_objs] = _text_embeddings
978
+ # Generate a mask for each object that is entity described by phrases
979
+ masks = torch.zeros(max_objs, device=device, dtype=self.text_encoder.dtype)
980
+ masks[:n_objs] = 1
981
+
982
+ repeat_batch = batch_size * num_images_per_prompt
983
+ cond_boxes = cond_boxes.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
984
+ text_embeddings = text_embeddings.unsqueeze(0).expand(repeat_batch, -1, -1).clone()
985
+ masks = masks.unsqueeze(0).expand(repeat_batch, -1).clone()
986
+ if do_classifier_free_guidance:
987
+ repeat_batch = repeat_batch * 2
988
+ cond_boxes = torch.cat([cond_boxes] * 2)
989
+ text_embeddings = torch.cat([text_embeddings] * 2)
990
+ masks = torch.cat([masks] * 2)
991
+ masks[: repeat_batch // 2] = 0
992
+ if cross_attention_kwargs is None:
993
+ cross_attention_kwargs = {}
994
+ cross_attention_kwargs["gligen"] = {
995
+ "boxes": cond_boxes,
996
+ "positive_embeddings": text_embeddings,
997
+ "masks": masks,
998
+ }
999
+
1000
+ num_grounding_steps = int(gligen_scheduled_sampling_beta * len(timesteps))
1001
+ self.enable_fuser(True)
1002
+
1003
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1004
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1005
+
1006
+ # 6.1 Add image embeds for IP-Adapter
1007
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1008
+
1009
+ loss_attn = torch.tensor(10000.0)
1010
+
1011
+ # 7. Denoising loop
1012
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1013
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1014
+ for i, t in enumerate(timesteps):
1015
+ # Scheduled sampling
1016
+ if i == num_grounding_steps:
1017
+ self.enable_fuser(False)
1018
+
1019
+ if latents.shape[1] != 4:
1020
+ latents = torch.randn_like(latents[:, :4])
1021
+
1022
+ # 7.1 Perform LMD guidance
1023
+ if boxes:
1024
+ latents, loss_attn = self.latent_lmd_guidance(
1025
+ cond_prompt_embeds,
1026
+ index=i,
1027
+ boxes=boxes,
1028
+ phrase_indices=phrase_indices,
1029
+ t=t,
1030
+ latents=latents,
1031
+ loss=loss_attn,
1032
+ **lmd_guidance_kwargs,
1033
+ )
1034
+
1035
+ # expand the latents if we are doing classifier free guidance
1036
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1037
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1038
+
1039
+ # predict the noise residual
1040
+ noise_pred = self.unet(
1041
+ latent_model_input,
1042
+ t,
1043
+ encoder_hidden_states=prompt_embeds,
1044
+ cross_attention_kwargs=cross_attention_kwargs,
1045
+ added_cond_kwargs=added_cond_kwargs,
1046
+ ).sample
1047
+
1048
+ # perform guidance
1049
+ if do_classifier_free_guidance:
1050
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1051
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1052
+
1053
+ # compute the previous noisy sample x_t -> x_t-1
1054
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1055
+
1056
+ # call the callback, if provided
1057
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1058
+ progress_bar.update()
1059
+ if callback is not None and i % callback_steps == 0:
1060
+ step_idx = i // getattr(self.scheduler, "order", 1)
1061
+ callback(step_idx, t, latents)
1062
+
1063
+ if not output_type == "latent":
1064
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1065
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1066
+ else:
1067
+ image = latents
1068
+ has_nsfw_concept = None
1069
+
1070
+ if has_nsfw_concept is None:
1071
+ do_denormalize = [True] * image.shape[0]
1072
+ else:
1073
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1074
+
1075
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1076
+
1077
+ # Offload last model to CPU
1078
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1079
+ self.final_offload_hook.offload()
1080
+
1081
+ if not return_dict:
1082
+ return (image, has_nsfw_concept)
1083
+
1084
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1085
+
1086
+ @torch.set_grad_enabled(True)
1087
+ def latent_lmd_guidance(
1088
+ self,
1089
+ cond_embeddings,
1090
+ index,
1091
+ boxes,
1092
+ phrase_indices,
1093
+ t,
1094
+ latents,
1095
+ loss,
1096
+ *,
1097
+ loss_scale=20,
1098
+ loss_threshold=5.0,
1099
+ max_iter=[3] * 5 + [2] * 5 + [1] * 5,
1100
+ guidance_timesteps=15,
1101
+ cross_attention_kwargs=None,
1102
+ guidance_attn_keys=DEFAULT_GUIDANCE_ATTN_KEYS,
1103
+ verbose=False,
1104
+ clear_cache=False,
1105
+ unet_additional_kwargs={},
1106
+ guidance_callback=None,
1107
+ **kwargs,
1108
+ ):
1109
+ scheduler, unet = self.scheduler, self.unet
1110
+
1111
+ iteration = 0
1112
+
1113
+ if index < guidance_timesteps:
1114
+ if isinstance(max_iter, list):
1115
+ max_iter = max_iter[index]
1116
+
1117
+ if verbose:
1118
+ logger.info(
1119
+ f"time index {index}, loss: {loss.item()/loss_scale:.3f} (de-scaled with scale {loss_scale:.1f}), loss threshold: {loss_threshold:.3f}"
1120
+ )
1121
+
1122
+ try:
1123
+ self.enable_attn_hook(enabled=True)
1124
+
1125
+ while (
1126
+ loss.item() / loss_scale > loss_threshold and iteration < max_iter and index < guidance_timesteps
1127
+ ):
1128
+ self._saved_attn = {}
1129
+
1130
+ latents.requires_grad_(True)
1131
+ latent_model_input = latents
1132
+ latent_model_input = scheduler.scale_model_input(latent_model_input, t)
1133
+
1134
+ unet(
1135
+ latent_model_input,
1136
+ t,
1137
+ encoder_hidden_states=cond_embeddings,
1138
+ cross_attention_kwargs=cross_attention_kwargs,
1139
+ **unet_additional_kwargs,
1140
+ )
1141
+
1142
+ # update latents with guidance
1143
+ loss = (
1144
+ self.compute_ca_loss(
1145
+ saved_attn=self._saved_attn,
1146
+ bboxes=boxes,
1147
+ phrase_indices=phrase_indices,
1148
+ guidance_attn_keys=guidance_attn_keys,
1149
+ verbose=verbose,
1150
+ **kwargs,
1151
+ )
1152
+ * loss_scale
1153
+ )
1154
+
1155
+ if torch.isnan(loss):
1156
+ raise RuntimeError("**Loss is NaN**")
1157
+
1158
+ # This callback allows visualizations.
1159
+ if guidance_callback is not None:
1160
+ guidance_callback(self, latents, loss, iteration, index)
1161
+
1162
+ self._saved_attn = None
1163
+
1164
+ grad_cond = torch.autograd.grad(loss.requires_grad_(True), [latents])[0]
1165
+
1166
+ latents.requires_grad_(False)
1167
+
1168
+ # Scaling with classifier guidance
1169
+ alpha_prod_t = scheduler.alphas_cumprod[t]
1170
+ # Classifier guidance: https://arxiv.org/pdf/2105.05233.pdf
1171
+ # DDIM: https://arxiv.org/pdf/2010.02502.pdf
1172
+ scale = (1 - alpha_prod_t) ** (0.5)
1173
+ latents = latents - scale * grad_cond
1174
+
1175
+ iteration += 1
1176
+
1177
+ if clear_cache:
1178
+ gc.collect()
1179
+ torch.cuda.empty_cache()
1180
+
1181
+ if verbose:
1182
+ logger.info(
1183
+ f"time index {index}, loss: {loss.item()/loss_scale:.3f}, loss threshold: {loss_threshold:.3f}, iteration: {iteration}"
1184
+ )
1185
+
1186
+ finally:
1187
+ self.enable_attn_hook(enabled=False)
1188
+
1189
+ return latents, loss
1190
+
1191
+ # Below are methods copied from StableDiffusionPipeline
1192
+ # The design choice of not inheriting from StableDiffusionPipeline is discussed here: https://github.com/huggingface/diffusers/pull/5993#issuecomment-1834258517
1193
+
1194
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
1195
+ def _encode_prompt(
1196
+ self,
1197
+ prompt,
1198
+ device,
1199
+ num_images_per_prompt,
1200
+ do_classifier_free_guidance,
1201
+ negative_prompt=None,
1202
+ prompt_embeds: Optional[torch.Tensor] = None,
1203
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1204
+ lora_scale: Optional[float] = None,
1205
+ **kwargs,
1206
+ ):
1207
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
1208
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
1209
+
1210
+ prompt_embeds_tuple = self.encode_prompt(
1211
+ prompt=prompt,
1212
+ device=device,
1213
+ num_images_per_prompt=num_images_per_prompt,
1214
+ do_classifier_free_guidance=do_classifier_free_guidance,
1215
+ negative_prompt=negative_prompt,
1216
+ prompt_embeds=prompt_embeds,
1217
+ negative_prompt_embeds=negative_prompt_embeds,
1218
+ lora_scale=lora_scale,
1219
+ **kwargs,
1220
+ )
1221
+
1222
+ # concatenate for backwards comp
1223
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
1224
+
1225
+ return prompt_embeds
1226
+
1227
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
1228
+ def encode_prompt(
1229
+ self,
1230
+ prompt,
1231
+ device,
1232
+ num_images_per_prompt,
1233
+ do_classifier_free_guidance,
1234
+ negative_prompt=None,
1235
+ prompt_embeds: Optional[torch.Tensor] = None,
1236
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1237
+ lora_scale: Optional[float] = None,
1238
+ clip_skip: Optional[int] = None,
1239
+ ):
1240
+ r"""
1241
+ Encodes the prompt into text encoder hidden states.
1242
+
1243
+ Args:
1244
+ prompt (`str` or `List[str]`, *optional*):
1245
+ prompt to be encoded
1246
+ device: (`torch.device`):
1247
+ torch device
1248
+ num_images_per_prompt (`int`):
1249
+ number of images that should be generated per prompt
1250
+ do_classifier_free_guidance (`bool`):
1251
+ whether to use classifier free guidance or not
1252
+ negative_prompt (`str` or `List[str]`, *optional*):
1253
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1254
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1255
+ less than `1`).
1256
+ prompt_embeds (`torch.Tensor`, *optional*):
1257
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1258
+ provided, text embeddings will be generated from `prompt` input argument.
1259
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1260
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1261
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1262
+ argument.
1263
+ lora_scale (`float`, *optional*):
1264
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
1265
+ clip_skip (`int`, *optional*):
1266
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1267
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1268
+ """
1269
+ # set lora scale so that monkey patched LoRA
1270
+ # function of text encoder can correctly access it
1271
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
1272
+ self._lora_scale = lora_scale
1273
+
1274
+ # dynamically adjust the LoRA scale
1275
+ if not USE_PEFT_BACKEND:
1276
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
1277
+ else:
1278
+ scale_lora_layers(self.text_encoder, lora_scale)
1279
+
1280
+ if prompt is not None and isinstance(prompt, str):
1281
+ batch_size = 1
1282
+ elif prompt is not None and isinstance(prompt, list):
1283
+ batch_size = len(prompt)
1284
+ else:
1285
+ batch_size = prompt_embeds.shape[0]
1286
+
1287
+ if prompt_embeds is None:
1288
+ # textual inversion: process multi-vector tokens if necessary
1289
+ if isinstance(self, TextualInversionLoaderMixin):
1290
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
1291
+
1292
+ text_inputs = self.tokenizer(
1293
+ prompt,
1294
+ padding="max_length",
1295
+ max_length=self.tokenizer.model_max_length,
1296
+ truncation=True,
1297
+ return_tensors="pt",
1298
+ )
1299
+ text_input_ids = text_inputs.input_ids
1300
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
1301
+
1302
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
1303
+ text_input_ids, untruncated_ids
1304
+ ):
1305
+ removed_text = self.tokenizer.batch_decode(
1306
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
1307
+ )
1308
+ logger.warning(
1309
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
1310
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
1311
+ )
1312
+
1313
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
1314
+ attention_mask = text_inputs.attention_mask.to(device)
1315
+ else:
1316
+ attention_mask = None
1317
+
1318
+ if clip_skip is None:
1319
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
1320
+ prompt_embeds = prompt_embeds[0]
1321
+ else:
1322
+ prompt_embeds = self.text_encoder(
1323
+ text_input_ids.to(device),
1324
+ attention_mask=attention_mask,
1325
+ output_hidden_states=True,
1326
+ )
1327
+ # Access the `hidden_states` first, that contains a tuple of
1328
+ # all the hidden states from the encoder layers. Then index into
1329
+ # the tuple to access the hidden states from the desired layer.
1330
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
1331
+ # We also need to apply the final LayerNorm here to not mess with the
1332
+ # representations. The `last_hidden_states` that we typically use for
1333
+ # obtaining the final prompt representations passes through the LayerNorm
1334
+ # layer.
1335
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
1336
+
1337
+ if self.text_encoder is not None:
1338
+ prompt_embeds_dtype = self.text_encoder.dtype
1339
+ elif self.unet is not None:
1340
+ prompt_embeds_dtype = self.unet.dtype
1341
+ else:
1342
+ prompt_embeds_dtype = prompt_embeds.dtype
1343
+
1344
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
1345
+
1346
+ bs_embed, seq_len, _ = prompt_embeds.shape
1347
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
1348
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
1349
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
1350
+
1351
+ # get unconditional embeddings for classifier free guidance
1352
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
1353
+ uncond_tokens: List[str]
1354
+ if negative_prompt is None:
1355
+ uncond_tokens = [""] * batch_size
1356
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
1357
+ raise TypeError(
1358
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
1359
+ f" {type(prompt)}."
1360
+ )
1361
+ elif isinstance(negative_prompt, str):
1362
+ uncond_tokens = [negative_prompt]
1363
+ elif batch_size != len(negative_prompt):
1364
+ raise ValueError(
1365
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
1366
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
1367
+ " the batch size of `prompt`."
1368
+ )
1369
+ else:
1370
+ uncond_tokens = negative_prompt
1371
+
1372
+ # textual inversion: process multi-vector tokens if necessary
1373
+ if isinstance(self, TextualInversionLoaderMixin):
1374
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
1375
+
1376
+ max_length = prompt_embeds.shape[1]
1377
+ uncond_input = self.tokenizer(
1378
+ uncond_tokens,
1379
+ padding="max_length",
1380
+ max_length=max_length,
1381
+ truncation=True,
1382
+ return_tensors="pt",
1383
+ )
1384
+
1385
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
1386
+ attention_mask = uncond_input.attention_mask.to(device)
1387
+ else:
1388
+ attention_mask = None
1389
+
1390
+ negative_prompt_embeds = self.text_encoder(
1391
+ uncond_input.input_ids.to(device),
1392
+ attention_mask=attention_mask,
1393
+ )
1394
+ negative_prompt_embeds = negative_prompt_embeds[0]
1395
+
1396
+ if do_classifier_free_guidance:
1397
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
1398
+ seq_len = negative_prompt_embeds.shape[1]
1399
+
1400
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
1401
+
1402
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
1403
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
1404
+
1405
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
1406
+ # Retrieve the original scale by scaling back the LoRA layers
1407
+ unscale_lora_layers(self.text_encoder, lora_scale)
1408
+
1409
+ return prompt_embeds, negative_prompt_embeds
1410
+
1411
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
1412
+ def encode_image(self, image, device, num_images_per_prompt):
1413
+ dtype = next(self.image_encoder.parameters()).dtype
1414
+
1415
+ if not isinstance(image, torch.Tensor):
1416
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
1417
+
1418
+ image = image.to(device=device, dtype=dtype)
1419
+ image_embeds = self.image_encoder(image).image_embeds
1420
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
1421
+
1422
+ uncond_image_embeds = torch.zeros_like(image_embeds)
1423
+ return image_embeds, uncond_image_embeds
1424
+
1425
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
1426
+ def run_safety_checker(self, image, device, dtype):
1427
+ if self.safety_checker is None:
1428
+ has_nsfw_concept = None
1429
+ else:
1430
+ if torch.is_tensor(image):
1431
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
1432
+ else:
1433
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
1434
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
1435
+ image, has_nsfw_concept = self.safety_checker(
1436
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
1437
+ )
1438
+ return image, has_nsfw_concept
1439
+
1440
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
1441
+ def decode_latents(self, latents):
1442
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
1443
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
1444
+
1445
+ latents = 1 / self.vae.config.scaling_factor * latents
1446
+ image = self.vae.decode(latents, return_dict=False)[0]
1447
+ image = (image / 2 + 0.5).clamp(0, 1)
1448
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
1449
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
1450
+ return image
1451
+
1452
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
1453
+ def prepare_extra_step_kwargs(self, generator, eta):
1454
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
1455
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
1456
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
1457
+ # and should be between [0, 1]
1458
+
1459
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
1460
+ extra_step_kwargs = {}
1461
+ if accepts_eta:
1462
+ extra_step_kwargs["eta"] = eta
1463
+
1464
+ # check if the scheduler accepts generator
1465
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
1466
+ if accepts_generator:
1467
+ extra_step_kwargs["generator"] = generator
1468
+ return extra_step_kwargs
1469
+
1470
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
1471
+ def prepare_latents(
1472
+ self,
1473
+ batch_size,
1474
+ num_channels_latents,
1475
+ height,
1476
+ width,
1477
+ dtype,
1478
+ device,
1479
+ generator,
1480
+ latents=None,
1481
+ ):
1482
+ shape = (
1483
+ batch_size,
1484
+ num_channels_latents,
1485
+ height // self.vae_scale_factor,
1486
+ width // self.vae_scale_factor,
1487
+ )
1488
+ if isinstance(generator, list) and len(generator) != batch_size:
1489
+ raise ValueError(
1490
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
1491
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
1492
+ )
1493
+
1494
+ if latents is None:
1495
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
1496
+ else:
1497
+ latents = latents.to(device)
1498
+
1499
+ # scale the initial noise by the standard deviation required by the scheduler
1500
+ latents = latents * self.scheduler.init_noise_sigma
1501
+ return latents
1502
+
1503
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1504
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
1505
+ """
1506
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1507
+
1508
+ Args:
1509
+ timesteps (`torch.Tensor`):
1510
+ generate embedding vectors at these timesteps
1511
+ embedding_dim (`int`, *optional*, defaults to 512):
1512
+ dimension of the embeddings to generate
1513
+ dtype:
1514
+ data type of the generated embeddings
1515
+
1516
+ Returns:
1517
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
1518
+ """
1519
+ assert len(w.shape) == 1
1520
+ w = w * 1000.0
1521
+
1522
+ half_dim = embedding_dim // 2
1523
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1524
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1525
+ emb = w.to(dtype)[:, None] * emb[None, :]
1526
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1527
+ if embedding_dim % 2 == 1: # zero pad
1528
+ emb = torch.nn.functional.pad(emb, (0, 1))
1529
+ assert emb.shape == (w.shape[0], embedding_dim)
1530
+ return emb
1531
+
1532
+ @property
1533
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_scale
1534
+ def guidance_scale(self):
1535
+ return self._guidance_scale
1536
+
1537
+ @property
1538
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_rescale
1539
+ def guidance_rescale(self):
1540
+ return self._guidance_rescale
1541
+
1542
+ @property
1543
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.clip_skip
1544
+ def clip_skip(self):
1545
+ return self._clip_skip
1546
+
1547
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1548
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1549
+ # corresponds to doing no classifier free guidance.
1550
+ @property
1551
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.do_classifier_free_guidance
1552
+ def do_classifier_free_guidance(self):
1553
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1554
+
1555
+ @property
1556
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.cross_attention_kwargs
1557
+ def cross_attention_kwargs(self):
1558
+ return self._cross_attention_kwargs
1559
+
1560
+ @property
1561
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.num_timesteps
1562
+ def num_timesteps(self):
1563
+ return self._num_timesteps
v0.32.0/lpw_stable_diffusion.py ADDED
@@ -0,0 +1,1427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Any, Callable, Dict, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
10
+
11
+ from diffusers import DiffusionPipeline
12
+ from diffusers.configuration_utils import FrozenDict
13
+ from diffusers.image_processor import VaeImageProcessor
14
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
17
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
18
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput, StableDiffusionSafetyChecker
19
+ from diffusers.schedulers import KarrasDiffusionSchedulers
20
+ from diffusers.utils import (
21
+ PIL_INTERPOLATION,
22
+ USE_PEFT_BACKEND,
23
+ deprecate,
24
+ logging,
25
+ scale_lora_layers,
26
+ unscale_lora_layers,
27
+ )
28
+ from diffusers.utils.torch_utils import randn_tensor
29
+
30
+
31
+ # ------------------------------------------------------------------------------
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+ re_attention = re.compile(
36
+ r"""
37
+ \\\(|
38
+ \\\)|
39
+ \\\[|
40
+ \\]|
41
+ \\\\|
42
+ \\|
43
+ \(|
44
+ \[|
45
+ :([+-]?[.\d]+)\)|
46
+ \)|
47
+ ]|
48
+ [^\\()\[\]:]+|
49
+ :
50
+ """,
51
+ re.X,
52
+ )
53
+
54
+
55
+ def parse_prompt_attention(text):
56
+ """
57
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
58
+ Accepted tokens are:
59
+ (abc) - increases attention to abc by a multiplier of 1.1
60
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
61
+ [abc] - decreases attention to abc by a multiplier of 1.1
62
+ \\( - literal character '('
63
+ \\[ - literal character '['
64
+ \\) - literal character ')'
65
+ \\] - literal character ']'
66
+ \\ - literal character '\'
67
+ anything else - just text
68
+ >>> parse_prompt_attention('normal text')
69
+ [['normal text', 1.0]]
70
+ >>> parse_prompt_attention('an (important) word')
71
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
72
+ >>> parse_prompt_attention('(unbalanced')
73
+ [['unbalanced', 1.1]]
74
+ >>> parse_prompt_attention('\\(literal\\]')
75
+ [['(literal]', 1.0]]
76
+ >>> parse_prompt_attention('(unnecessary)(parens)')
77
+ [['unnecessaryparens', 1.1]]
78
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
79
+ [['a ', 1.0],
80
+ ['house', 1.5730000000000004],
81
+ [' ', 1.1],
82
+ ['on', 1.0],
83
+ [' a ', 1.1],
84
+ ['hill', 0.55],
85
+ [', sun, ', 1.1],
86
+ ['sky', 1.4641000000000006],
87
+ ['.', 1.1]]
88
+ """
89
+
90
+ res = []
91
+ round_brackets = []
92
+ square_brackets = []
93
+
94
+ round_bracket_multiplier = 1.1
95
+ square_bracket_multiplier = 1 / 1.1
96
+
97
+ def multiply_range(start_position, multiplier):
98
+ for p in range(start_position, len(res)):
99
+ res[p][1] *= multiplier
100
+
101
+ for m in re_attention.finditer(text):
102
+ text = m.group(0)
103
+ weight = m.group(1)
104
+
105
+ if text.startswith("\\"):
106
+ res.append([text[1:], 1.0])
107
+ elif text == "(":
108
+ round_brackets.append(len(res))
109
+ elif text == "[":
110
+ square_brackets.append(len(res))
111
+ elif weight is not None and len(round_brackets) > 0:
112
+ multiply_range(round_brackets.pop(), float(weight))
113
+ elif text == ")" and len(round_brackets) > 0:
114
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
115
+ elif text == "]" and len(square_brackets) > 0:
116
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
117
+ else:
118
+ res.append([text, 1.0])
119
+
120
+ for pos in round_brackets:
121
+ multiply_range(pos, round_bracket_multiplier)
122
+
123
+ for pos in square_brackets:
124
+ multiply_range(pos, square_bracket_multiplier)
125
+
126
+ if len(res) == 0:
127
+ res = [["", 1.0]]
128
+
129
+ # merge runs of identical weights
130
+ i = 0
131
+ while i + 1 < len(res):
132
+ if res[i][1] == res[i + 1][1]:
133
+ res[i][0] += res[i + 1][0]
134
+ res.pop(i + 1)
135
+ else:
136
+ i += 1
137
+
138
+ return res
139
+
140
+
141
+ def get_prompts_with_weights(pipe: DiffusionPipeline, prompt: List[str], max_length: int):
142
+ r"""
143
+ Tokenize a list of prompts and return its tokens with weights of each token.
144
+
145
+ No padding, starting or ending token is included.
146
+ """
147
+ tokens = []
148
+ weights = []
149
+ truncated = False
150
+ for text in prompt:
151
+ texts_and_weights = parse_prompt_attention(text)
152
+ text_token = []
153
+ text_weight = []
154
+ for word, weight in texts_and_weights:
155
+ # tokenize and discard the starting and the ending token
156
+ token = pipe.tokenizer(word).input_ids[1:-1]
157
+ text_token += token
158
+ # copy the weight by length of token
159
+ text_weight += [weight] * len(token)
160
+ # stop if the text is too long (longer than truncation limit)
161
+ if len(text_token) > max_length:
162
+ truncated = True
163
+ break
164
+ # truncate
165
+ if len(text_token) > max_length:
166
+ truncated = True
167
+ text_token = text_token[:max_length]
168
+ text_weight = text_weight[:max_length]
169
+ tokens.append(text_token)
170
+ weights.append(text_weight)
171
+ if truncated:
172
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
173
+ return tokens, weights
174
+
175
+
176
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, pad, no_boseos_middle=True, chunk_length=77):
177
+ r"""
178
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
179
+ """
180
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
181
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
182
+ for i in range(len(tokens)):
183
+ tokens[i] = [bos] + tokens[i] + [pad] * (max_length - 1 - len(tokens[i]) - 1) + [eos]
184
+ if no_boseos_middle:
185
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
186
+ else:
187
+ w = []
188
+ if len(weights[i]) == 0:
189
+ w = [1.0] * weights_length
190
+ else:
191
+ for j in range(max_embeddings_multiples):
192
+ w.append(1.0) # weight for starting token in this chunk
193
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
194
+ w.append(1.0) # weight for ending token in this chunk
195
+ w += [1.0] * (weights_length - len(w))
196
+ weights[i] = w[:]
197
+
198
+ return tokens, weights
199
+
200
+
201
+ def get_unweighted_text_embeddings(
202
+ pipe: DiffusionPipeline,
203
+ text_input: torch.Tensor,
204
+ chunk_length: int,
205
+ no_boseos_middle: Optional[bool] = True,
206
+ clip_skip: Optional[int] = None,
207
+ ):
208
+ """
209
+ When the length of tokens is a multiple of the capacity of the text encoder,
210
+ it should be split into chunks and sent to the text encoder individually.
211
+ """
212
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
213
+ if max_embeddings_multiples > 1:
214
+ text_embeddings = []
215
+ for i in range(max_embeddings_multiples):
216
+ # extract the i-th chunk
217
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].clone()
218
+
219
+ # cover the head and the tail by the starting and the ending tokens
220
+ text_input_chunk[:, 0] = text_input[0, 0]
221
+ text_input_chunk[:, -1] = text_input[0, -1]
222
+ if clip_skip is None:
223
+ prompt_embeds = pipe.text_encoder(text_input_chunk.to(pipe.device))
224
+ text_embedding = prompt_embeds[0]
225
+ else:
226
+ prompt_embeds = pipe.text_encoder(text_input_chunk.to(pipe.device), output_hidden_states=True)
227
+ # Access the `hidden_states` first, that contains a tuple of
228
+ # all the hidden states from the encoder layers. Then index into
229
+ # the tuple to access the hidden states from the desired layer.
230
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
231
+ # We also need to apply the final LayerNorm here to not mess with the
232
+ # representations. The `last_hidden_states` that we typically use for
233
+ # obtaining the final prompt representations passes through the LayerNorm
234
+ # layer.
235
+ text_embedding = pipe.text_encoder.text_model.final_layer_norm(prompt_embeds)
236
+
237
+ if no_boseos_middle:
238
+ if i == 0:
239
+ # discard the ending token
240
+ text_embedding = text_embedding[:, :-1]
241
+ elif i == max_embeddings_multiples - 1:
242
+ # discard the starting token
243
+ text_embedding = text_embedding[:, 1:]
244
+ else:
245
+ # discard both starting and ending tokens
246
+ text_embedding = text_embedding[:, 1:-1]
247
+
248
+ text_embeddings.append(text_embedding)
249
+ text_embeddings = torch.concat(text_embeddings, axis=1)
250
+ else:
251
+ if clip_skip is None:
252
+ clip_skip = 0
253
+ prompt_embeds = pipe.text_encoder(text_input, output_hidden_states=True)[-1][-(clip_skip + 1)]
254
+ text_embeddings = pipe.text_encoder.text_model.final_layer_norm(prompt_embeds)
255
+ return text_embeddings
256
+
257
+
258
+ def get_weighted_text_embeddings(
259
+ pipe: DiffusionPipeline,
260
+ prompt: Union[str, List[str]],
261
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
262
+ max_embeddings_multiples: Optional[int] = 3,
263
+ no_boseos_middle: Optional[bool] = False,
264
+ skip_parsing: Optional[bool] = False,
265
+ skip_weighting: Optional[bool] = False,
266
+ clip_skip=None,
267
+ lora_scale=None,
268
+ ):
269
+ r"""
270
+ Prompts can be assigned with local weights using brackets. For example,
271
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
272
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
273
+
274
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
275
+
276
+ Args:
277
+ pipe (`DiffusionPipeline`):
278
+ Pipe to provide access to the tokenizer and the text encoder.
279
+ prompt (`str` or `List[str]`):
280
+ The prompt or prompts to guide the image generation.
281
+ uncond_prompt (`str` or `List[str]`):
282
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
283
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
284
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
285
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
286
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
287
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
288
+ ending token in each of the chunk in the middle.
289
+ skip_parsing (`bool`, *optional*, defaults to `False`):
290
+ Skip the parsing of brackets.
291
+ skip_weighting (`bool`, *optional*, defaults to `False`):
292
+ Skip the weighting. When the parsing is skipped, it is forced True.
293
+ """
294
+ # set lora scale so that monkey patched LoRA
295
+ # function of text encoder can correctly access it
296
+ if lora_scale is not None and isinstance(pipe, StableDiffusionLoraLoaderMixin):
297
+ pipe._lora_scale = lora_scale
298
+
299
+ # dynamically adjust the LoRA scale
300
+ if not USE_PEFT_BACKEND:
301
+ adjust_lora_scale_text_encoder(pipe.text_encoder, lora_scale)
302
+ else:
303
+ scale_lora_layers(pipe.text_encoder, lora_scale)
304
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
305
+ if isinstance(prompt, str):
306
+ prompt = [prompt]
307
+
308
+ if not skip_parsing:
309
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
310
+ if uncond_prompt is not None:
311
+ if isinstance(uncond_prompt, str):
312
+ uncond_prompt = [uncond_prompt]
313
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
314
+ else:
315
+ prompt_tokens = [
316
+ token[1:-1] for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True).input_ids
317
+ ]
318
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
319
+ if uncond_prompt is not None:
320
+ if isinstance(uncond_prompt, str):
321
+ uncond_prompt = [uncond_prompt]
322
+ uncond_tokens = [
323
+ token[1:-1]
324
+ for token in pipe.tokenizer(uncond_prompt, max_length=max_length, truncation=True).input_ids
325
+ ]
326
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
327
+
328
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
329
+ max_length = max([len(token) for token in prompt_tokens])
330
+ if uncond_prompt is not None:
331
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
332
+
333
+ max_embeddings_multiples = min(
334
+ max_embeddings_multiples,
335
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
336
+ )
337
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
338
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
339
+
340
+ # pad the length of tokens and weights
341
+ bos = pipe.tokenizer.bos_token_id
342
+ eos = pipe.tokenizer.eos_token_id
343
+ pad = getattr(pipe.tokenizer, "pad_token_id", eos)
344
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
345
+ prompt_tokens,
346
+ prompt_weights,
347
+ max_length,
348
+ bos,
349
+ eos,
350
+ pad,
351
+ no_boseos_middle=no_boseos_middle,
352
+ chunk_length=pipe.tokenizer.model_max_length,
353
+ )
354
+ prompt_tokens = torch.tensor(prompt_tokens, dtype=torch.long, device=pipe.device)
355
+ if uncond_prompt is not None:
356
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
357
+ uncond_tokens,
358
+ uncond_weights,
359
+ max_length,
360
+ bos,
361
+ eos,
362
+ pad,
363
+ no_boseos_middle=no_boseos_middle,
364
+ chunk_length=pipe.tokenizer.model_max_length,
365
+ )
366
+ uncond_tokens = torch.tensor(uncond_tokens, dtype=torch.long, device=pipe.device)
367
+
368
+ # get the embeddings
369
+ text_embeddings = get_unweighted_text_embeddings(
370
+ pipe, prompt_tokens, pipe.tokenizer.model_max_length, no_boseos_middle=no_boseos_middle, clip_skip=clip_skip
371
+ )
372
+ prompt_weights = torch.tensor(prompt_weights, dtype=text_embeddings.dtype, device=text_embeddings.device)
373
+ if uncond_prompt is not None:
374
+ uncond_embeddings = get_unweighted_text_embeddings(
375
+ pipe,
376
+ uncond_tokens,
377
+ pipe.tokenizer.model_max_length,
378
+ no_boseos_middle=no_boseos_middle,
379
+ clip_skip=clip_skip,
380
+ )
381
+ uncond_weights = torch.tensor(uncond_weights, dtype=uncond_embeddings.dtype, device=uncond_embeddings.device)
382
+
383
+ # assign weights to the prompts and normalize in the sense of mean
384
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
385
+ if (not skip_parsing) and (not skip_weighting):
386
+ previous_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
387
+ text_embeddings *= prompt_weights.unsqueeze(-1)
388
+ current_mean = text_embeddings.float().mean(axis=[-2, -1]).to(text_embeddings.dtype)
389
+ text_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
390
+ if uncond_prompt is not None:
391
+ previous_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
392
+ uncond_embeddings *= uncond_weights.unsqueeze(-1)
393
+ current_mean = uncond_embeddings.float().mean(axis=[-2, -1]).to(uncond_embeddings.dtype)
394
+ uncond_embeddings *= (previous_mean / current_mean).unsqueeze(-1).unsqueeze(-1)
395
+
396
+ if pipe.text_encoder is not None:
397
+ if isinstance(pipe, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
398
+ # Retrieve the original scale by scaling back the LoRA layers
399
+ unscale_lora_layers(pipe.text_encoder, lora_scale)
400
+
401
+ if uncond_prompt is not None:
402
+ return text_embeddings, uncond_embeddings
403
+ return text_embeddings, None
404
+
405
+
406
+ def preprocess_image(image, batch_size):
407
+ w, h = image.size
408
+ w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
409
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
410
+ image = np.array(image).astype(np.float32) / 255.0
411
+ image = np.vstack([image[None].transpose(0, 3, 1, 2)] * batch_size)
412
+ image = torch.from_numpy(image)
413
+ return 2.0 * image - 1.0
414
+
415
+
416
+ def preprocess_mask(mask, batch_size, scale_factor=8):
417
+ if not isinstance(mask, torch.Tensor):
418
+ mask = mask.convert("L")
419
+ w, h = mask.size
420
+ w, h = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8
421
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
422
+ mask = np.array(mask).astype(np.float32) / 255.0
423
+ mask = np.tile(mask, (4, 1, 1))
424
+ mask = np.vstack([mask[None]] * batch_size)
425
+ mask = 1 - mask # repaint white, keep black
426
+ mask = torch.from_numpy(mask)
427
+ return mask
428
+
429
+ else:
430
+ valid_mask_channel_sizes = [1, 3]
431
+ # if mask channel is fourth tensor dimension, permute dimensions to pytorch standard (B, C, H, W)
432
+ if mask.shape[3] in valid_mask_channel_sizes:
433
+ mask = mask.permute(0, 3, 1, 2)
434
+ elif mask.shape[1] not in valid_mask_channel_sizes:
435
+ raise ValueError(
436
+ f"Mask channel dimension of size in {valid_mask_channel_sizes} should be second or fourth dimension,"
437
+ f" but received mask of shape {tuple(mask.shape)}"
438
+ )
439
+ # (potentially) reduce mask channel dimension from 3 to 1 for broadcasting to latent shape
440
+ mask = mask.mean(dim=1, keepdim=True)
441
+ h, w = mask.shape[-2:]
442
+ h, w = (x - x % 8 for x in (h, w)) # resize to integer multiple of 8
443
+ mask = torch.nn.functional.interpolate(mask, (h // scale_factor, w // scale_factor))
444
+ return mask
445
+
446
+
447
+ class StableDiffusionLongPromptWeightingPipeline(
448
+ DiffusionPipeline,
449
+ StableDiffusionMixin,
450
+ TextualInversionLoaderMixin,
451
+ StableDiffusionLoraLoaderMixin,
452
+ FromSingleFileMixin,
453
+ ):
454
+ r"""
455
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
456
+ weighting in prompt.
457
+
458
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
459
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
460
+
461
+ Args:
462
+ vae ([`AutoencoderKL`]):
463
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
464
+ text_encoder ([`CLIPTextModel`]):
465
+ Frozen text-encoder. Stable Diffusion uses the text portion of
466
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
467
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
468
+ tokenizer (`CLIPTokenizer`):
469
+ Tokenizer of class
470
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
471
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
472
+ scheduler ([`SchedulerMixin`]):
473
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
474
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
475
+ safety_checker ([`StableDiffusionSafetyChecker`]):
476
+ Classification module that estimates whether generated images could be considered offensive or harmful.
477
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
478
+ feature_extractor ([`CLIPImageProcessor`]):
479
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
480
+ """
481
+
482
+ model_cpu_offload_seq = "text_encoder-->unet->vae"
483
+ _optional_components = ["safety_checker", "feature_extractor"]
484
+ _exclude_from_cpu_offload = ["safety_checker"]
485
+
486
+ def __init__(
487
+ self,
488
+ vae: AutoencoderKL,
489
+ text_encoder: CLIPTextModel,
490
+ tokenizer: CLIPTokenizer,
491
+ unet: UNet2DConditionModel,
492
+ scheduler: KarrasDiffusionSchedulers,
493
+ safety_checker: StableDiffusionSafetyChecker,
494
+ feature_extractor: CLIPImageProcessor,
495
+ requires_safety_checker: bool = True,
496
+ ):
497
+ super().__init__()
498
+
499
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
500
+ deprecation_message = (
501
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
502
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
503
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
504
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
505
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
506
+ " file"
507
+ )
508
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
509
+ new_config = dict(scheduler.config)
510
+ new_config["steps_offset"] = 1
511
+ scheduler._internal_dict = FrozenDict(new_config)
512
+
513
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
514
+ deprecation_message = (
515
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
516
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
517
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
518
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
519
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
520
+ )
521
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
522
+ new_config = dict(scheduler.config)
523
+ new_config["clip_sample"] = False
524
+ scheduler._internal_dict = FrozenDict(new_config)
525
+
526
+ if safety_checker is None and requires_safety_checker:
527
+ logger.warning(
528
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
529
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
530
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
531
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
532
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
533
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
534
+ )
535
+
536
+ if safety_checker is not None and feature_extractor is None:
537
+ raise ValueError(
538
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
539
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
540
+ )
541
+
542
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
543
+ version.parse(unet.config._diffusers_version).base_version
544
+ ) < version.parse("0.9.0.dev0")
545
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
546
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
547
+ deprecation_message = (
548
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
549
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
550
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
551
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
552
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
553
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
554
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
555
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
556
+ " the `unet/config.json` file"
557
+ )
558
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
559
+ new_config = dict(unet.config)
560
+ new_config["sample_size"] = 64
561
+ unet._internal_dict = FrozenDict(new_config)
562
+ self.register_modules(
563
+ vae=vae,
564
+ text_encoder=text_encoder,
565
+ tokenizer=tokenizer,
566
+ unet=unet,
567
+ scheduler=scheduler,
568
+ safety_checker=safety_checker,
569
+ feature_extractor=feature_extractor,
570
+ )
571
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
572
+
573
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
574
+ self.register_to_config(
575
+ requires_safety_checker=requires_safety_checker,
576
+ )
577
+
578
+ def _encode_prompt(
579
+ self,
580
+ prompt,
581
+ device,
582
+ num_images_per_prompt,
583
+ do_classifier_free_guidance,
584
+ negative_prompt=None,
585
+ max_embeddings_multiples=3,
586
+ prompt_embeds: Optional[torch.Tensor] = None,
587
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
588
+ clip_skip: Optional[int] = None,
589
+ lora_scale: Optional[float] = None,
590
+ ):
591
+ r"""
592
+ Encodes the prompt into text encoder hidden states.
593
+
594
+ Args:
595
+ prompt (`str` or `list(int)`):
596
+ prompt to be encoded
597
+ device: (`torch.device`):
598
+ torch device
599
+ num_images_per_prompt (`int`):
600
+ number of images that should be generated per prompt
601
+ do_classifier_free_guidance (`bool`):
602
+ whether to use classifier free guidance or not
603
+ negative_prompt (`str` or `List[str]`):
604
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
605
+ if `guidance_scale` is less than `1`).
606
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
607
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
608
+ """
609
+ if prompt is not None and isinstance(prompt, str):
610
+ batch_size = 1
611
+ elif prompt is not None and isinstance(prompt, list):
612
+ batch_size = len(prompt)
613
+ else:
614
+ batch_size = prompt_embeds.shape[0]
615
+
616
+ if negative_prompt_embeds is None:
617
+ if negative_prompt is None:
618
+ negative_prompt = [""] * batch_size
619
+ elif isinstance(negative_prompt, str):
620
+ negative_prompt = [negative_prompt] * batch_size
621
+ if batch_size != len(negative_prompt):
622
+ raise ValueError(
623
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
624
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
625
+ " the batch size of `prompt`."
626
+ )
627
+ if prompt_embeds is None or negative_prompt_embeds is None:
628
+ if isinstance(self, TextualInversionLoaderMixin):
629
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
630
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
631
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, self.tokenizer)
632
+
633
+ prompt_embeds1, negative_prompt_embeds1 = get_weighted_text_embeddings(
634
+ pipe=self,
635
+ prompt=prompt,
636
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
637
+ max_embeddings_multiples=max_embeddings_multiples,
638
+ clip_skip=clip_skip,
639
+ lora_scale=lora_scale,
640
+ )
641
+ if prompt_embeds is None:
642
+ prompt_embeds = prompt_embeds1
643
+ if negative_prompt_embeds is None:
644
+ negative_prompt_embeds = negative_prompt_embeds1
645
+
646
+ bs_embed, seq_len, _ = prompt_embeds.shape
647
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
648
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
649
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
650
+
651
+ if do_classifier_free_guidance:
652
+ bs_embed, seq_len, _ = negative_prompt_embeds.shape
653
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
654
+ negative_prompt_embeds = negative_prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
655
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
656
+
657
+ return prompt_embeds
658
+
659
+ def check_inputs(
660
+ self,
661
+ prompt,
662
+ height,
663
+ width,
664
+ strength,
665
+ callback_steps,
666
+ negative_prompt=None,
667
+ prompt_embeds=None,
668
+ negative_prompt_embeds=None,
669
+ ):
670
+ if height % 8 != 0 or width % 8 != 0:
671
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
672
+
673
+ if strength < 0 or strength > 1:
674
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
675
+
676
+ if (callback_steps is None) or (
677
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
678
+ ):
679
+ raise ValueError(
680
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
681
+ f" {type(callback_steps)}."
682
+ )
683
+
684
+ if prompt is not None and prompt_embeds is not None:
685
+ raise ValueError(
686
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
687
+ " only forward one of the two."
688
+ )
689
+ elif prompt is None and prompt_embeds is None:
690
+ raise ValueError(
691
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
692
+ )
693
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
694
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
695
+
696
+ if negative_prompt is not None and negative_prompt_embeds is not None:
697
+ raise ValueError(
698
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
699
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
700
+ )
701
+
702
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
703
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
704
+ raise ValueError(
705
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
706
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
707
+ f" {negative_prompt_embeds.shape}."
708
+ )
709
+
710
+ def get_timesteps(self, num_inference_steps, strength, device, is_text2img):
711
+ if is_text2img:
712
+ return self.scheduler.timesteps.to(device), num_inference_steps
713
+ else:
714
+ # get the original timestep using init_timestep
715
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
716
+
717
+ t_start = max(num_inference_steps - init_timestep, 0)
718
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
719
+
720
+ return timesteps, num_inference_steps - t_start
721
+
722
+ def run_safety_checker(self, image, device, dtype):
723
+ if self.safety_checker is not None:
724
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
725
+ image, has_nsfw_concept = self.safety_checker(
726
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
727
+ )
728
+ else:
729
+ has_nsfw_concept = None
730
+ return image, has_nsfw_concept
731
+
732
+ def decode_latents(self, latents):
733
+ latents = 1 / self.vae.config.scaling_factor * latents
734
+ image = self.vae.decode(latents).sample
735
+ image = (image / 2 + 0.5).clamp(0, 1)
736
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
737
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
738
+ return image
739
+
740
+ def prepare_extra_step_kwargs(self, generator, eta):
741
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
742
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
743
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
744
+ # and should be between [0, 1]
745
+
746
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
747
+ extra_step_kwargs = {}
748
+ if accepts_eta:
749
+ extra_step_kwargs["eta"] = eta
750
+
751
+ # check if the scheduler accepts generator
752
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
753
+ if accepts_generator:
754
+ extra_step_kwargs["generator"] = generator
755
+ return extra_step_kwargs
756
+
757
+ def prepare_latents(
758
+ self,
759
+ image,
760
+ timestep,
761
+ num_images_per_prompt,
762
+ batch_size,
763
+ num_channels_latents,
764
+ height,
765
+ width,
766
+ dtype,
767
+ device,
768
+ generator,
769
+ latents=None,
770
+ ):
771
+ if image is None:
772
+ batch_size = batch_size * num_images_per_prompt
773
+ shape = (
774
+ batch_size,
775
+ num_channels_latents,
776
+ int(height) // self.vae_scale_factor,
777
+ int(width) // self.vae_scale_factor,
778
+ )
779
+ if isinstance(generator, list) and len(generator) != batch_size:
780
+ raise ValueError(
781
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
782
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
783
+ )
784
+
785
+ if latents is None:
786
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
787
+ else:
788
+ latents = latents.to(device)
789
+
790
+ # scale the initial noise by the standard deviation required by the scheduler
791
+ latents = latents * self.scheduler.init_noise_sigma
792
+ return latents, None, None
793
+ else:
794
+ image = image.to(device=self.device, dtype=dtype)
795
+ init_latent_dist = self.vae.encode(image).latent_dist
796
+ init_latents = init_latent_dist.sample(generator=generator)
797
+ init_latents = self.vae.config.scaling_factor * init_latents
798
+
799
+ # Expand init_latents for batch_size and num_images_per_prompt
800
+ init_latents = torch.cat([init_latents] * num_images_per_prompt, dim=0)
801
+ init_latents_orig = init_latents
802
+
803
+ # add noise to latents using the timesteps
804
+ noise = randn_tensor(init_latents.shape, generator=generator, device=self.device, dtype=dtype)
805
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
806
+ latents = init_latents
807
+ return latents, init_latents_orig, noise
808
+
809
+ @torch.no_grad()
810
+ def __call__(
811
+ self,
812
+ prompt: Union[str, List[str]],
813
+ negative_prompt: Optional[Union[str, List[str]]] = None,
814
+ image: Union[torch.Tensor, PIL.Image.Image] = None,
815
+ mask_image: Union[torch.Tensor, PIL.Image.Image] = None,
816
+ height: int = 512,
817
+ width: int = 512,
818
+ num_inference_steps: int = 50,
819
+ guidance_scale: float = 7.5,
820
+ strength: float = 0.8,
821
+ num_images_per_prompt: Optional[int] = 1,
822
+ add_predicted_noise: Optional[bool] = False,
823
+ eta: float = 0.0,
824
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
825
+ latents: Optional[torch.Tensor] = None,
826
+ prompt_embeds: Optional[torch.Tensor] = None,
827
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
828
+ max_embeddings_multiples: Optional[int] = 3,
829
+ output_type: Optional[str] = "pil",
830
+ return_dict: bool = True,
831
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
832
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
833
+ clip_skip: Optional[int] = None,
834
+ callback_steps: int = 1,
835
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
836
+ ):
837
+ r"""
838
+ Function invoked when calling the pipeline for generation.
839
+
840
+ Args:
841
+ prompt (`str` or `List[str]`):
842
+ The prompt or prompts to guide the image generation.
843
+ negative_prompt (`str` or `List[str]`, *optional*):
844
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
845
+ if `guidance_scale` is less than `1`).
846
+ image (`torch.Tensor` or `PIL.Image.Image`):
847
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
848
+ process.
849
+ mask_image (`torch.Tensor` or `PIL.Image.Image`):
850
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
851
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
852
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
853
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
854
+ height (`int`, *optional*, defaults to 512):
855
+ The height in pixels of the generated image.
856
+ width (`int`, *optional*, defaults to 512):
857
+ The width in pixels of the generated image.
858
+ num_inference_steps (`int`, *optional*, defaults to 50):
859
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
860
+ expense of slower inference.
861
+ guidance_scale (`float`, *optional*, defaults to 7.5):
862
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
863
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
864
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
865
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
866
+ usually at the expense of lower image quality.
867
+ strength (`float`, *optional*, defaults to 0.8):
868
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
869
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
870
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
871
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
872
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
873
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
874
+ The number of images to generate per prompt.
875
+ add_predicted_noise (`bool`, *optional*, defaults to True):
876
+ Use predicted noise instead of random noise when constructing noisy versions of the original image in
877
+ the reverse diffusion process
878
+ eta (`float`, *optional*, defaults to 0.0):
879
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
880
+ [`schedulers.DDIMScheduler`], will be ignored for others.
881
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
882
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
883
+ to make generation deterministic.
884
+ latents (`torch.Tensor`, *optional*):
885
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
886
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
887
+ tensor will ge generated by sampling using the supplied random `generator`.
888
+ prompt_embeds (`torch.Tensor`, *optional*):
889
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
890
+ provided, text embeddings will be generated from `prompt` input argument.
891
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
892
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
893
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
894
+ argument.
895
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
896
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
897
+ output_type (`str`, *optional*, defaults to `"pil"`):
898
+ The output format of the generate image. Choose between
899
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
900
+ return_dict (`bool`, *optional*, defaults to `True`):
901
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
902
+ plain tuple.
903
+ callback (`Callable`, *optional*):
904
+ A function that will be called every `callback_steps` steps during inference. The function will be
905
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
906
+ is_cancelled_callback (`Callable`, *optional*):
907
+ A function that will be called every `callback_steps` steps during inference. If the function returns
908
+ `True`, the inference will be cancelled.
909
+ clip_skip (`int`, *optional*):
910
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
911
+ the output of the pre-final layer will be used for computing the prompt embeddings.
912
+ callback_steps (`int`, *optional*, defaults to 1):
913
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
914
+ called at every step.
915
+ cross_attention_kwargs (`dict`, *optional*):
916
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
917
+ `self.processor` in
918
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
919
+
920
+ Returns:
921
+ `None` if cancelled by `is_cancelled_callback`,
922
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
923
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
924
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
925
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
926
+ (nsfw) content, according to the `safety_checker`.
927
+ """
928
+ # 0. Default height and width to unet
929
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
930
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
931
+
932
+ # 1. Check inputs. Raise error if not correct
933
+ self.check_inputs(
934
+ prompt, height, width, strength, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds
935
+ )
936
+
937
+ # 2. Define call parameters
938
+ if prompt is not None and isinstance(prompt, str):
939
+ batch_size = 1
940
+ elif prompt is not None and isinstance(prompt, list):
941
+ batch_size = len(prompt)
942
+ else:
943
+ batch_size = prompt_embeds.shape[0]
944
+
945
+ device = self._execution_device
946
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
947
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
948
+ # corresponds to doing no classifier free guidance.
949
+ do_classifier_free_guidance = guidance_scale > 1.0
950
+ lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
951
+
952
+ # 3. Encode input prompt
953
+ prompt_embeds = self._encode_prompt(
954
+ prompt,
955
+ device,
956
+ num_images_per_prompt,
957
+ do_classifier_free_guidance,
958
+ negative_prompt,
959
+ max_embeddings_multiples,
960
+ prompt_embeds=prompt_embeds,
961
+ negative_prompt_embeds=negative_prompt_embeds,
962
+ clip_skip=clip_skip,
963
+ lora_scale=lora_scale,
964
+ )
965
+ dtype = prompt_embeds.dtype
966
+
967
+ # 4. Preprocess image and mask
968
+ if isinstance(image, PIL.Image.Image):
969
+ image = preprocess_image(image, batch_size)
970
+ if image is not None:
971
+ image = image.to(device=self.device, dtype=dtype)
972
+ if isinstance(mask_image, PIL.Image.Image):
973
+ mask_image = preprocess_mask(mask_image, batch_size, self.vae_scale_factor)
974
+ if mask_image is not None:
975
+ mask = mask_image.to(device=self.device, dtype=dtype)
976
+ mask = torch.cat([mask] * num_images_per_prompt)
977
+ else:
978
+ mask = None
979
+
980
+ # 5. set timesteps
981
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
982
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device, image is None)
983
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
984
+
985
+ # 6. Prepare latent variables
986
+ latents, init_latents_orig, noise = self.prepare_latents(
987
+ image,
988
+ latent_timestep,
989
+ num_images_per_prompt,
990
+ batch_size,
991
+ self.unet.config.in_channels,
992
+ height,
993
+ width,
994
+ dtype,
995
+ device,
996
+ generator,
997
+ latents,
998
+ )
999
+
1000
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1001
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1002
+
1003
+ # 8. Denoising loop
1004
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1005
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1006
+ for i, t in enumerate(timesteps):
1007
+ # expand the latents if we are doing classifier free guidance
1008
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1009
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1010
+
1011
+ # predict the noise residual
1012
+ noise_pred = self.unet(
1013
+ latent_model_input,
1014
+ t,
1015
+ encoder_hidden_states=prompt_embeds,
1016
+ cross_attention_kwargs=cross_attention_kwargs,
1017
+ ).sample
1018
+
1019
+ # perform guidance
1020
+ if do_classifier_free_guidance:
1021
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1022
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1023
+
1024
+ # compute the previous noisy sample x_t -> x_t-1
1025
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1026
+
1027
+ if mask is not None:
1028
+ # masking
1029
+ if add_predicted_noise:
1030
+ init_latents_proper = self.scheduler.add_noise(
1031
+ init_latents_orig, noise_pred_uncond, torch.tensor([t])
1032
+ )
1033
+ else:
1034
+ init_latents_proper = self.scheduler.add_noise(init_latents_orig, noise, torch.tensor([t]))
1035
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
1036
+
1037
+ # call the callback, if provided
1038
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1039
+ progress_bar.update()
1040
+ if i % callback_steps == 0:
1041
+ if callback is not None:
1042
+ step_idx = i // getattr(self.scheduler, "order", 1)
1043
+ callback(step_idx, t, latents)
1044
+ if is_cancelled_callback is not None and is_cancelled_callback():
1045
+ return None
1046
+
1047
+ if output_type == "latent":
1048
+ image = latents
1049
+ has_nsfw_concept = None
1050
+ elif output_type == "pil":
1051
+ # 9. Post-processing
1052
+ image = self.decode_latents(latents)
1053
+
1054
+ # 10. Run safety checker
1055
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1056
+
1057
+ # 11. Convert to PIL
1058
+ image = self.numpy_to_pil(image)
1059
+ else:
1060
+ # 9. Post-processing
1061
+ image = self.decode_latents(latents)
1062
+
1063
+ # 10. Run safety checker
1064
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1065
+
1066
+ # Offload last model to CPU
1067
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1068
+ self.final_offload_hook.offload()
1069
+
1070
+ if not return_dict:
1071
+ return image, has_nsfw_concept
1072
+
1073
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
1074
+
1075
+ def text2img(
1076
+ self,
1077
+ prompt: Union[str, List[str]],
1078
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1079
+ height: int = 512,
1080
+ width: int = 512,
1081
+ num_inference_steps: int = 50,
1082
+ guidance_scale: float = 7.5,
1083
+ num_images_per_prompt: Optional[int] = 1,
1084
+ eta: float = 0.0,
1085
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1086
+ latents: Optional[torch.Tensor] = None,
1087
+ prompt_embeds: Optional[torch.Tensor] = None,
1088
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1089
+ max_embeddings_multiples: Optional[int] = 3,
1090
+ output_type: Optional[str] = "pil",
1091
+ return_dict: bool = True,
1092
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
1093
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1094
+ clip_skip=None,
1095
+ callback_steps: int = 1,
1096
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1097
+ ):
1098
+ r"""
1099
+ Function for text-to-image generation.
1100
+ Args:
1101
+ prompt (`str` or `List[str]`):
1102
+ The prompt or prompts to guide the image generation.
1103
+ negative_prompt (`str` or `List[str]`, *optional*):
1104
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1105
+ if `guidance_scale` is less than `1`).
1106
+ height (`int`, *optional*, defaults to 512):
1107
+ The height in pixels of the generated image.
1108
+ width (`int`, *optional*, defaults to 512):
1109
+ The width in pixels of the generated image.
1110
+ num_inference_steps (`int`, *optional*, defaults to 50):
1111
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1112
+ expense of slower inference.
1113
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1114
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1115
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1116
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1117
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1118
+ usually at the expense of lower image quality.
1119
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1120
+ The number of images to generate per prompt.
1121
+ eta (`float`, *optional*, defaults to 0.0):
1122
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1123
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1124
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1125
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1126
+ to make generation deterministic.
1127
+ latents (`torch.Tensor`, *optional*):
1128
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1129
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1130
+ tensor will ge generated by sampling using the supplied random `generator`.
1131
+ prompt_embeds (`torch.Tensor`, *optional*):
1132
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1133
+ provided, text embeddings will be generated from `prompt` input argument.
1134
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1135
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1136
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1137
+ argument.
1138
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1139
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1140
+ output_type (`str`, *optional*, defaults to `"pil"`):
1141
+ The output format of the generate image. Choose between
1142
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1143
+ return_dict (`bool`, *optional*, defaults to `True`):
1144
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1145
+ plain tuple.
1146
+ callback (`Callable`, *optional*):
1147
+ A function that will be called every `callback_steps` steps during inference. The function will be
1148
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1149
+ is_cancelled_callback (`Callable`, *optional*):
1150
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1151
+ `True`, the inference will be cancelled.
1152
+ clip_skip (`int`, *optional*):
1153
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1154
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1155
+ callback_steps (`int`, *optional*, defaults to 1):
1156
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1157
+ called at every step.
1158
+ cross_attention_kwargs (`dict`, *optional*):
1159
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1160
+ `self.processor` in
1161
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1162
+
1163
+ Returns:
1164
+ `None` if cancelled by `is_cancelled_callback`,
1165
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1166
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1167
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1168
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1169
+ (nsfw) content, according to the `safety_checker`.
1170
+ """
1171
+ return self.__call__(
1172
+ prompt=prompt,
1173
+ negative_prompt=negative_prompt,
1174
+ height=height,
1175
+ width=width,
1176
+ num_inference_steps=num_inference_steps,
1177
+ guidance_scale=guidance_scale,
1178
+ num_images_per_prompt=num_images_per_prompt,
1179
+ eta=eta,
1180
+ generator=generator,
1181
+ latents=latents,
1182
+ prompt_embeds=prompt_embeds,
1183
+ negative_prompt_embeds=negative_prompt_embeds,
1184
+ max_embeddings_multiples=max_embeddings_multiples,
1185
+ output_type=output_type,
1186
+ return_dict=return_dict,
1187
+ callback=callback,
1188
+ is_cancelled_callback=is_cancelled_callback,
1189
+ clip_skip=clip_skip,
1190
+ callback_steps=callback_steps,
1191
+ cross_attention_kwargs=cross_attention_kwargs,
1192
+ )
1193
+
1194
+ def img2img(
1195
+ self,
1196
+ image: Union[torch.Tensor, PIL.Image.Image],
1197
+ prompt: Union[str, List[str]],
1198
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1199
+ strength: float = 0.8,
1200
+ num_inference_steps: Optional[int] = 50,
1201
+ guidance_scale: Optional[float] = 7.5,
1202
+ num_images_per_prompt: Optional[int] = 1,
1203
+ eta: Optional[float] = 0.0,
1204
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1205
+ prompt_embeds: Optional[torch.Tensor] = None,
1206
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1207
+ max_embeddings_multiples: Optional[int] = 3,
1208
+ output_type: Optional[str] = "pil",
1209
+ return_dict: bool = True,
1210
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
1211
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1212
+ callback_steps: int = 1,
1213
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1214
+ ):
1215
+ r"""
1216
+ Function for image-to-image generation.
1217
+ Args:
1218
+ image (`torch.Tensor` or `PIL.Image.Image`):
1219
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1220
+ process.
1221
+ prompt (`str` or `List[str]`):
1222
+ The prompt or prompts to guide the image generation.
1223
+ negative_prompt (`str` or `List[str]`, *optional*):
1224
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1225
+ if `guidance_scale` is less than `1`).
1226
+ strength (`float`, *optional*, defaults to 0.8):
1227
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
1228
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
1229
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
1230
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
1231
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
1232
+ num_inference_steps (`int`, *optional*, defaults to 50):
1233
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1234
+ expense of slower inference. This parameter will be modulated by `strength`.
1235
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1236
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1237
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1238
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1239
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1240
+ usually at the expense of lower image quality.
1241
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1242
+ The number of images to generate per prompt.
1243
+ eta (`float`, *optional*, defaults to 0.0):
1244
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1245
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1246
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1247
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1248
+ to make generation deterministic.
1249
+ prompt_embeds (`torch.Tensor`, *optional*):
1250
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1251
+ provided, text embeddings will be generated from `prompt` input argument.
1252
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1253
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1254
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1255
+ argument.
1256
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1257
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1258
+ output_type (`str`, *optional*, defaults to `"pil"`):
1259
+ The output format of the generate image. Choose between
1260
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1261
+ return_dict (`bool`, *optional*, defaults to `True`):
1262
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1263
+ plain tuple.
1264
+ callback (`Callable`, *optional*):
1265
+ A function that will be called every `callback_steps` steps during inference. The function will be
1266
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1267
+ is_cancelled_callback (`Callable`, *optional*):
1268
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1269
+ `True`, the inference will be cancelled.
1270
+ callback_steps (`int`, *optional*, defaults to 1):
1271
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1272
+ called at every step.
1273
+ cross_attention_kwargs (`dict`, *optional*):
1274
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1275
+ `self.processor` in
1276
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1277
+
1278
+ Returns:
1279
+ `None` if cancelled by `is_cancelled_callback`,
1280
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1281
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1282
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1283
+ (nsfw) content, according to the `safety_checker`.
1284
+ """
1285
+ return self.__call__(
1286
+ prompt=prompt,
1287
+ negative_prompt=negative_prompt,
1288
+ image=image,
1289
+ num_inference_steps=num_inference_steps,
1290
+ guidance_scale=guidance_scale,
1291
+ strength=strength,
1292
+ num_images_per_prompt=num_images_per_prompt,
1293
+ eta=eta,
1294
+ generator=generator,
1295
+ prompt_embeds=prompt_embeds,
1296
+ negative_prompt_embeds=negative_prompt_embeds,
1297
+ max_embeddings_multiples=max_embeddings_multiples,
1298
+ output_type=output_type,
1299
+ return_dict=return_dict,
1300
+ callback=callback,
1301
+ is_cancelled_callback=is_cancelled_callback,
1302
+ callback_steps=callback_steps,
1303
+ cross_attention_kwargs=cross_attention_kwargs,
1304
+ )
1305
+
1306
+ def inpaint(
1307
+ self,
1308
+ image: Union[torch.Tensor, PIL.Image.Image],
1309
+ mask_image: Union[torch.Tensor, PIL.Image.Image],
1310
+ prompt: Union[str, List[str]],
1311
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1312
+ strength: float = 0.8,
1313
+ num_inference_steps: Optional[int] = 50,
1314
+ guidance_scale: Optional[float] = 7.5,
1315
+ num_images_per_prompt: Optional[int] = 1,
1316
+ add_predicted_noise: Optional[bool] = False,
1317
+ eta: Optional[float] = 0.0,
1318
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1319
+ prompt_embeds: Optional[torch.Tensor] = None,
1320
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1321
+ max_embeddings_multiples: Optional[int] = 3,
1322
+ output_type: Optional[str] = "pil",
1323
+ return_dict: bool = True,
1324
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
1325
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
1326
+ callback_steps: int = 1,
1327
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1328
+ ):
1329
+ r"""
1330
+ Function for inpaint.
1331
+ Args:
1332
+ image (`torch.Tensor` or `PIL.Image.Image`):
1333
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1334
+ process. This is the image whose masked region will be inpainted.
1335
+ mask_image (`torch.Tensor` or `PIL.Image.Image`):
1336
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1337
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1338
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1339
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1340
+ prompt (`str` or `List[str]`):
1341
+ The prompt or prompts to guide the image generation.
1342
+ negative_prompt (`str` or `List[str]`, *optional*):
1343
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1344
+ if `guidance_scale` is less than `1`).
1345
+ strength (`float`, *optional*, defaults to 0.8):
1346
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1347
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1348
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1349
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1350
+ num_inference_steps (`int`, *optional*, defaults to 50):
1351
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1352
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1353
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1354
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1355
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1356
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1357
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1358
+ usually at the expense of lower image quality.
1359
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1360
+ The number of images to generate per prompt.
1361
+ add_predicted_noise (`bool`, *optional*, defaults to True):
1362
+ Use predicted noise instead of random noise when constructing noisy versions of the original image in
1363
+ the reverse diffusion process
1364
+ eta (`float`, *optional*, defaults to 0.0):
1365
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1366
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1367
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1368
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1369
+ to make generation deterministic.
1370
+ prompt_embeds (`torch.Tensor`, *optional*):
1371
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1372
+ provided, text embeddings will be generated from `prompt` input argument.
1373
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1374
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1375
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1376
+ argument.
1377
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1378
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1379
+ output_type (`str`, *optional*, defaults to `"pil"`):
1380
+ The output format of the generate image. Choose between
1381
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1382
+ return_dict (`bool`, *optional*, defaults to `True`):
1383
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1384
+ plain tuple.
1385
+ callback (`Callable`, *optional*):
1386
+ A function that will be called every `callback_steps` steps during inference. The function will be
1387
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1388
+ is_cancelled_callback (`Callable`, *optional*):
1389
+ A function that will be called every `callback_steps` steps during inference. If the function returns
1390
+ `True`, the inference will be cancelled.
1391
+ callback_steps (`int`, *optional*, defaults to 1):
1392
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1393
+ called at every step.
1394
+ cross_attention_kwargs (`dict`, *optional*):
1395
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1396
+ `self.processor` in
1397
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1398
+
1399
+ Returns:
1400
+ `None` if cancelled by `is_cancelled_callback`,
1401
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1402
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1403
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1404
+ (nsfw) content, according to the `safety_checker`.
1405
+ """
1406
+ return self.__call__(
1407
+ prompt=prompt,
1408
+ negative_prompt=negative_prompt,
1409
+ image=image,
1410
+ mask_image=mask_image,
1411
+ num_inference_steps=num_inference_steps,
1412
+ guidance_scale=guidance_scale,
1413
+ strength=strength,
1414
+ num_images_per_prompt=num_images_per_prompt,
1415
+ add_predicted_noise=add_predicted_noise,
1416
+ eta=eta,
1417
+ generator=generator,
1418
+ prompt_embeds=prompt_embeds,
1419
+ negative_prompt_embeds=negative_prompt_embeds,
1420
+ max_embeddings_multiples=max_embeddings_multiples,
1421
+ output_type=output_type,
1422
+ return_dict=return_dict,
1423
+ callback=callback,
1424
+ is_cancelled_callback=is_cancelled_callback,
1425
+ callback_steps=callback_steps,
1426
+ cross_attention_kwargs=cross_attention_kwargs,
1427
+ )
v0.32.0/lpw_stable_diffusion_onnx.py ADDED
@@ -0,0 +1,1148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import re
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import PIL.Image
7
+ import torch
8
+ from packaging import version
9
+ from transformers import CLIPImageProcessor, CLIPTokenizer
10
+
11
+ import diffusers
12
+ from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, SchedulerMixin
13
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
14
+ from diffusers.utils import logging
15
+
16
+
17
+ try:
18
+ from diffusers.pipelines.onnx_utils import ORT_TO_NP_TYPE
19
+ except ImportError:
20
+ ORT_TO_NP_TYPE = {
21
+ "tensor(bool)": np.bool_,
22
+ "tensor(int8)": np.int8,
23
+ "tensor(uint8)": np.uint8,
24
+ "tensor(int16)": np.int16,
25
+ "tensor(uint16)": np.uint16,
26
+ "tensor(int32)": np.int32,
27
+ "tensor(uint32)": np.uint32,
28
+ "tensor(int64)": np.int64,
29
+ "tensor(uint64)": np.uint64,
30
+ "tensor(float16)": np.float16,
31
+ "tensor(float)": np.float32,
32
+ "tensor(double)": np.float64,
33
+ }
34
+
35
+ try:
36
+ from diffusers.utils import PIL_INTERPOLATION
37
+ except ImportError:
38
+ if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("9.1.0"):
39
+ PIL_INTERPOLATION = {
40
+ "linear": PIL.Image.Resampling.BILINEAR,
41
+ "bilinear": PIL.Image.Resampling.BILINEAR,
42
+ "bicubic": PIL.Image.Resampling.BICUBIC,
43
+ "lanczos": PIL.Image.Resampling.LANCZOS,
44
+ "nearest": PIL.Image.Resampling.NEAREST,
45
+ }
46
+ else:
47
+ PIL_INTERPOLATION = {
48
+ "linear": PIL.Image.LINEAR,
49
+ "bilinear": PIL.Image.BILINEAR,
50
+ "bicubic": PIL.Image.BICUBIC,
51
+ "lanczos": PIL.Image.LANCZOS,
52
+ "nearest": PIL.Image.NEAREST,
53
+ }
54
+ # ------------------------------------------------------------------------------
55
+
56
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
57
+
58
+ re_attention = re.compile(
59
+ r"""
60
+ \\\(|
61
+ \\\)|
62
+ \\\[|
63
+ \\]|
64
+ \\\\|
65
+ \\|
66
+ \(|
67
+ \[|
68
+ :([+-]?[.\d]+)\)|
69
+ \)|
70
+ ]|
71
+ [^\\()\[\]:]+|
72
+ :
73
+ """,
74
+ re.X,
75
+ )
76
+
77
+
78
+ def parse_prompt_attention(text):
79
+ """
80
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
81
+ Accepted tokens are:
82
+ (abc) - increases attention to abc by a multiplier of 1.1
83
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
84
+ [abc] - decreases attention to abc by a multiplier of 1.1
85
+ \\( - literal character '('
86
+ \\[ - literal character '['
87
+ \\) - literal character ')'
88
+ \\] - literal character ']'
89
+ \\ - literal character '\'
90
+ anything else - just text
91
+ >>> parse_prompt_attention('normal text')
92
+ [['normal text', 1.0]]
93
+ >>> parse_prompt_attention('an (important) word')
94
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
95
+ >>> parse_prompt_attention('(unbalanced')
96
+ [['unbalanced', 1.1]]
97
+ >>> parse_prompt_attention('\\(literal\\]')
98
+ [['(literal]', 1.0]]
99
+ >>> parse_prompt_attention('(unnecessary)(parens)')
100
+ [['unnecessaryparens', 1.1]]
101
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
102
+ [['a ', 1.0],
103
+ ['house', 1.5730000000000004],
104
+ [' ', 1.1],
105
+ ['on', 1.0],
106
+ [' a ', 1.1],
107
+ ['hill', 0.55],
108
+ [', sun, ', 1.1],
109
+ ['sky', 1.4641000000000006],
110
+ ['.', 1.1]]
111
+ """
112
+
113
+ res = []
114
+ round_brackets = []
115
+ square_brackets = []
116
+
117
+ round_bracket_multiplier = 1.1
118
+ square_bracket_multiplier = 1 / 1.1
119
+
120
+ def multiply_range(start_position, multiplier):
121
+ for p in range(start_position, len(res)):
122
+ res[p][1] *= multiplier
123
+
124
+ for m in re_attention.finditer(text):
125
+ text = m.group(0)
126
+ weight = m.group(1)
127
+
128
+ if text.startswith("\\"):
129
+ res.append([text[1:], 1.0])
130
+ elif text == "(":
131
+ round_brackets.append(len(res))
132
+ elif text == "[":
133
+ square_brackets.append(len(res))
134
+ elif weight is not None and len(round_brackets) > 0:
135
+ multiply_range(round_brackets.pop(), float(weight))
136
+ elif text == ")" and len(round_brackets) > 0:
137
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
138
+ elif text == "]" and len(square_brackets) > 0:
139
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
140
+ else:
141
+ res.append([text, 1.0])
142
+
143
+ for pos in round_brackets:
144
+ multiply_range(pos, round_bracket_multiplier)
145
+
146
+ for pos in square_brackets:
147
+ multiply_range(pos, square_bracket_multiplier)
148
+
149
+ if len(res) == 0:
150
+ res = [["", 1.0]]
151
+
152
+ # merge runs of identical weights
153
+ i = 0
154
+ while i + 1 < len(res):
155
+ if res[i][1] == res[i + 1][1]:
156
+ res[i][0] += res[i + 1][0]
157
+ res.pop(i + 1)
158
+ else:
159
+ i += 1
160
+
161
+ return res
162
+
163
+
164
+ def get_prompts_with_weights(pipe, prompt: List[str], max_length: int):
165
+ r"""
166
+ Tokenize a list of prompts and return its tokens with weights of each token.
167
+
168
+ No padding, starting or ending token is included.
169
+ """
170
+ tokens = []
171
+ weights = []
172
+ truncated = False
173
+ for text in prompt:
174
+ texts_and_weights = parse_prompt_attention(text)
175
+ text_token = []
176
+ text_weight = []
177
+ for word, weight in texts_and_weights:
178
+ # tokenize and discard the starting and the ending token
179
+ token = pipe.tokenizer(word, return_tensors="np").input_ids[0, 1:-1]
180
+ text_token += list(token)
181
+ # copy the weight by length of token
182
+ text_weight += [weight] * len(token)
183
+ # stop if the text is too long (longer than truncation limit)
184
+ if len(text_token) > max_length:
185
+ truncated = True
186
+ break
187
+ # truncate
188
+ if len(text_token) > max_length:
189
+ truncated = True
190
+ text_token = text_token[:max_length]
191
+ text_weight = text_weight[:max_length]
192
+ tokens.append(text_token)
193
+ weights.append(text_weight)
194
+ if truncated:
195
+ logger.warning("Prompt was truncated. Try to shorten the prompt or increase max_embeddings_multiples")
196
+ return tokens, weights
197
+
198
+
199
+ def pad_tokens_and_weights(tokens, weights, max_length, bos, eos, pad, no_boseos_middle=True, chunk_length=77):
200
+ r"""
201
+ Pad the tokens (with starting and ending tokens) and weights (with 1.0) to max_length.
202
+ """
203
+ max_embeddings_multiples = (max_length - 2) // (chunk_length - 2)
204
+ weights_length = max_length if no_boseos_middle else max_embeddings_multiples * chunk_length
205
+ for i in range(len(tokens)):
206
+ tokens[i] = [bos] + tokens[i] + [pad] * (max_length - 1 - len(tokens[i]) - 1) + [eos]
207
+ if no_boseos_middle:
208
+ weights[i] = [1.0] + weights[i] + [1.0] * (max_length - 1 - len(weights[i]))
209
+ else:
210
+ w = []
211
+ if len(weights[i]) == 0:
212
+ w = [1.0] * weights_length
213
+ else:
214
+ for j in range(max_embeddings_multiples):
215
+ w.append(1.0) # weight for starting token in this chunk
216
+ w += weights[i][j * (chunk_length - 2) : min(len(weights[i]), (j + 1) * (chunk_length - 2))]
217
+ w.append(1.0) # weight for ending token in this chunk
218
+ w += [1.0] * (weights_length - len(w))
219
+ weights[i] = w[:]
220
+
221
+ return tokens, weights
222
+
223
+
224
+ def get_unweighted_text_embeddings(
225
+ pipe,
226
+ text_input: np.array,
227
+ chunk_length: int,
228
+ no_boseos_middle: Optional[bool] = True,
229
+ ):
230
+ """
231
+ When the length of tokens is a multiple of the capacity of the text encoder,
232
+ it should be split into chunks and sent to the text encoder individually.
233
+ """
234
+ max_embeddings_multiples = (text_input.shape[1] - 2) // (chunk_length - 2)
235
+ if max_embeddings_multiples > 1:
236
+ text_embeddings = []
237
+ for i in range(max_embeddings_multiples):
238
+ # extract the i-th chunk
239
+ text_input_chunk = text_input[:, i * (chunk_length - 2) : (i + 1) * (chunk_length - 2) + 2].copy()
240
+
241
+ # cover the head and the tail by the starting and the ending tokens
242
+ text_input_chunk[:, 0] = text_input[0, 0]
243
+ text_input_chunk[:, -1] = text_input[0, -1]
244
+
245
+ text_embedding = pipe.text_encoder(input_ids=text_input_chunk)[0]
246
+
247
+ if no_boseos_middle:
248
+ if i == 0:
249
+ # discard the ending token
250
+ text_embedding = text_embedding[:, :-1]
251
+ elif i == max_embeddings_multiples - 1:
252
+ # discard the starting token
253
+ text_embedding = text_embedding[:, 1:]
254
+ else:
255
+ # discard both starting and ending tokens
256
+ text_embedding = text_embedding[:, 1:-1]
257
+
258
+ text_embeddings.append(text_embedding)
259
+ text_embeddings = np.concatenate(text_embeddings, axis=1)
260
+ else:
261
+ text_embeddings = pipe.text_encoder(input_ids=text_input)[0]
262
+ return text_embeddings
263
+
264
+
265
+ def get_weighted_text_embeddings(
266
+ pipe,
267
+ prompt: Union[str, List[str]],
268
+ uncond_prompt: Optional[Union[str, List[str]]] = None,
269
+ max_embeddings_multiples: Optional[int] = 4,
270
+ no_boseos_middle: Optional[bool] = False,
271
+ skip_parsing: Optional[bool] = False,
272
+ skip_weighting: Optional[bool] = False,
273
+ **kwargs,
274
+ ):
275
+ r"""
276
+ Prompts can be assigned with local weights using brackets. For example,
277
+ prompt 'A (very beautiful) masterpiece' highlights the words 'very beautiful',
278
+ and the embedding tokens corresponding to the words get multiplied by a constant, 1.1.
279
+
280
+ Also, to regularize of the embedding, the weighted embedding would be scaled to preserve the original mean.
281
+
282
+ Args:
283
+ pipe (`OnnxStableDiffusionPipeline`):
284
+ Pipe to provide access to the tokenizer and the text encoder.
285
+ prompt (`str` or `List[str]`):
286
+ The prompt or prompts to guide the image generation.
287
+ uncond_prompt (`str` or `List[str]`):
288
+ The unconditional prompt or prompts for guide the image generation. If unconditional prompt
289
+ is provided, the embeddings of prompt and uncond_prompt are concatenated.
290
+ max_embeddings_multiples (`int`, *optional*, defaults to `1`):
291
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
292
+ no_boseos_middle (`bool`, *optional*, defaults to `False`):
293
+ If the length of text token is multiples of the capacity of text encoder, whether reserve the starting and
294
+ ending token in each of the chunk in the middle.
295
+ skip_parsing (`bool`, *optional*, defaults to `False`):
296
+ Skip the parsing of brackets.
297
+ skip_weighting (`bool`, *optional*, defaults to `False`):
298
+ Skip the weighting. When the parsing is skipped, it is forced True.
299
+ """
300
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
301
+ if isinstance(prompt, str):
302
+ prompt = [prompt]
303
+
304
+ if not skip_parsing:
305
+ prompt_tokens, prompt_weights = get_prompts_with_weights(pipe, prompt, max_length - 2)
306
+ if uncond_prompt is not None:
307
+ if isinstance(uncond_prompt, str):
308
+ uncond_prompt = [uncond_prompt]
309
+ uncond_tokens, uncond_weights = get_prompts_with_weights(pipe, uncond_prompt, max_length - 2)
310
+ else:
311
+ prompt_tokens = [
312
+ token[1:-1]
313
+ for token in pipe.tokenizer(prompt, max_length=max_length, truncation=True, return_tensors="np").input_ids
314
+ ]
315
+ prompt_weights = [[1.0] * len(token) for token in prompt_tokens]
316
+ if uncond_prompt is not None:
317
+ if isinstance(uncond_prompt, str):
318
+ uncond_prompt = [uncond_prompt]
319
+ uncond_tokens = [
320
+ token[1:-1]
321
+ for token in pipe.tokenizer(
322
+ uncond_prompt,
323
+ max_length=max_length,
324
+ truncation=True,
325
+ return_tensors="np",
326
+ ).input_ids
327
+ ]
328
+ uncond_weights = [[1.0] * len(token) for token in uncond_tokens]
329
+
330
+ # round up the longest length of tokens to a multiple of (model_max_length - 2)
331
+ max_length = max([len(token) for token in prompt_tokens])
332
+ if uncond_prompt is not None:
333
+ max_length = max(max_length, max([len(token) for token in uncond_tokens]))
334
+
335
+ max_embeddings_multiples = min(
336
+ max_embeddings_multiples,
337
+ (max_length - 1) // (pipe.tokenizer.model_max_length - 2) + 1,
338
+ )
339
+ max_embeddings_multiples = max(1, max_embeddings_multiples)
340
+ max_length = (pipe.tokenizer.model_max_length - 2) * max_embeddings_multiples + 2
341
+
342
+ # pad the length of tokens and weights
343
+ bos = pipe.tokenizer.bos_token_id
344
+ eos = pipe.tokenizer.eos_token_id
345
+ pad = getattr(pipe.tokenizer, "pad_token_id", eos)
346
+ prompt_tokens, prompt_weights = pad_tokens_and_weights(
347
+ prompt_tokens,
348
+ prompt_weights,
349
+ max_length,
350
+ bos,
351
+ eos,
352
+ pad,
353
+ no_boseos_middle=no_boseos_middle,
354
+ chunk_length=pipe.tokenizer.model_max_length,
355
+ )
356
+ prompt_tokens = np.array(prompt_tokens, dtype=np.int32)
357
+ if uncond_prompt is not None:
358
+ uncond_tokens, uncond_weights = pad_tokens_and_weights(
359
+ uncond_tokens,
360
+ uncond_weights,
361
+ max_length,
362
+ bos,
363
+ eos,
364
+ pad,
365
+ no_boseos_middle=no_boseos_middle,
366
+ chunk_length=pipe.tokenizer.model_max_length,
367
+ )
368
+ uncond_tokens = np.array(uncond_tokens, dtype=np.int32)
369
+
370
+ # get the embeddings
371
+ text_embeddings = get_unweighted_text_embeddings(
372
+ pipe,
373
+ prompt_tokens,
374
+ pipe.tokenizer.model_max_length,
375
+ no_boseos_middle=no_boseos_middle,
376
+ )
377
+ prompt_weights = np.array(prompt_weights, dtype=text_embeddings.dtype)
378
+ if uncond_prompt is not None:
379
+ uncond_embeddings = get_unweighted_text_embeddings(
380
+ pipe,
381
+ uncond_tokens,
382
+ pipe.tokenizer.model_max_length,
383
+ no_boseos_middle=no_boseos_middle,
384
+ )
385
+ uncond_weights = np.array(uncond_weights, dtype=uncond_embeddings.dtype)
386
+
387
+ # assign weights to the prompts and normalize in the sense of mean
388
+ # TODO: should we normalize by chunk or in a whole (current implementation)?
389
+ if (not skip_parsing) and (not skip_weighting):
390
+ previous_mean = text_embeddings.mean(axis=(-2, -1))
391
+ text_embeddings *= prompt_weights[:, :, None]
392
+ text_embeddings *= (previous_mean / text_embeddings.mean(axis=(-2, -1)))[:, None, None]
393
+ if uncond_prompt is not None:
394
+ previous_mean = uncond_embeddings.mean(axis=(-2, -1))
395
+ uncond_embeddings *= uncond_weights[:, :, None]
396
+ uncond_embeddings *= (previous_mean / uncond_embeddings.mean(axis=(-2, -1)))[:, None, None]
397
+
398
+ # For classifier free guidance, we need to do two forward passes.
399
+ # Here we concatenate the unconditional and text embeddings into a single batch
400
+ # to avoid doing two forward passes
401
+ if uncond_prompt is not None:
402
+ return text_embeddings, uncond_embeddings
403
+
404
+ return text_embeddings
405
+
406
+
407
+ def preprocess_image(image):
408
+ w, h = image.size
409
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
410
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
411
+ image = np.array(image).astype(np.float32) / 255.0
412
+ image = image[None].transpose(0, 3, 1, 2)
413
+ return 2.0 * image - 1.0
414
+
415
+
416
+ def preprocess_mask(mask, scale_factor=8):
417
+ mask = mask.convert("L")
418
+ w, h = mask.size
419
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
420
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"])
421
+ mask = np.array(mask).astype(np.float32) / 255.0
422
+ mask = np.tile(mask, (4, 1, 1))
423
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
424
+ mask = 1 - mask # repaint white, keep black
425
+ return mask
426
+
427
+
428
+ class OnnxStableDiffusionLongPromptWeightingPipeline(OnnxStableDiffusionPipeline):
429
+ r"""
430
+ Pipeline for text-to-image generation using Stable Diffusion without tokens length limit, and support parsing
431
+ weighting in prompt.
432
+
433
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
434
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
435
+ """
436
+
437
+ if version.parse(version.parse(diffusers.__version__).base_version) >= version.parse("0.9.0"):
438
+
439
+ def __init__(
440
+ self,
441
+ vae_encoder: OnnxRuntimeModel,
442
+ vae_decoder: OnnxRuntimeModel,
443
+ text_encoder: OnnxRuntimeModel,
444
+ tokenizer: CLIPTokenizer,
445
+ unet: OnnxRuntimeModel,
446
+ scheduler: SchedulerMixin,
447
+ safety_checker: OnnxRuntimeModel,
448
+ feature_extractor: CLIPImageProcessor,
449
+ requires_safety_checker: bool = True,
450
+ ):
451
+ super().__init__(
452
+ vae_encoder=vae_encoder,
453
+ vae_decoder=vae_decoder,
454
+ text_encoder=text_encoder,
455
+ tokenizer=tokenizer,
456
+ unet=unet,
457
+ scheduler=scheduler,
458
+ safety_checker=safety_checker,
459
+ feature_extractor=feature_extractor,
460
+ requires_safety_checker=requires_safety_checker,
461
+ )
462
+ self.__init__additional__()
463
+
464
+ else:
465
+
466
+ def __init__(
467
+ self,
468
+ vae_encoder: OnnxRuntimeModel,
469
+ vae_decoder: OnnxRuntimeModel,
470
+ text_encoder: OnnxRuntimeModel,
471
+ tokenizer: CLIPTokenizer,
472
+ unet: OnnxRuntimeModel,
473
+ scheduler: SchedulerMixin,
474
+ safety_checker: OnnxRuntimeModel,
475
+ feature_extractor: CLIPImageProcessor,
476
+ ):
477
+ super().__init__(
478
+ vae_encoder=vae_encoder,
479
+ vae_decoder=vae_decoder,
480
+ text_encoder=text_encoder,
481
+ tokenizer=tokenizer,
482
+ unet=unet,
483
+ scheduler=scheduler,
484
+ safety_checker=safety_checker,
485
+ feature_extractor=feature_extractor,
486
+ )
487
+ self.__init__additional__()
488
+
489
+ def __init__additional__(self):
490
+ self.unet.config.in_channels = 4
491
+ self.vae_scale_factor = 8
492
+
493
+ def _encode_prompt(
494
+ self,
495
+ prompt,
496
+ num_images_per_prompt,
497
+ do_classifier_free_guidance,
498
+ negative_prompt,
499
+ max_embeddings_multiples,
500
+ ):
501
+ r"""
502
+ Encodes the prompt into text encoder hidden states.
503
+
504
+ Args:
505
+ prompt (`str` or `list(int)`):
506
+ prompt to be encoded
507
+ num_images_per_prompt (`int`):
508
+ number of images that should be generated per prompt
509
+ do_classifier_free_guidance (`bool`):
510
+ whether to use classifier free guidance or not
511
+ negative_prompt (`str` or `List[str]`):
512
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
513
+ if `guidance_scale` is less than `1`).
514
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
515
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
516
+ """
517
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
518
+
519
+ if negative_prompt is None:
520
+ negative_prompt = [""] * batch_size
521
+ elif isinstance(negative_prompt, str):
522
+ negative_prompt = [negative_prompt] * batch_size
523
+ if batch_size != len(negative_prompt):
524
+ raise ValueError(
525
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
526
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
527
+ " the batch size of `prompt`."
528
+ )
529
+
530
+ text_embeddings, uncond_embeddings = get_weighted_text_embeddings(
531
+ pipe=self,
532
+ prompt=prompt,
533
+ uncond_prompt=negative_prompt if do_classifier_free_guidance else None,
534
+ max_embeddings_multiples=max_embeddings_multiples,
535
+ )
536
+
537
+ text_embeddings = text_embeddings.repeat(num_images_per_prompt, 0)
538
+ if do_classifier_free_guidance:
539
+ uncond_embeddings = uncond_embeddings.repeat(num_images_per_prompt, 0)
540
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
541
+
542
+ return text_embeddings
543
+
544
+ def check_inputs(self, prompt, height, width, strength, callback_steps):
545
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
546
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
547
+
548
+ if strength < 0 or strength > 1:
549
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
550
+
551
+ if height % 8 != 0 or width % 8 != 0:
552
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
553
+
554
+ if (callback_steps is None) or (
555
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
556
+ ):
557
+ raise ValueError(
558
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
559
+ f" {type(callback_steps)}."
560
+ )
561
+
562
+ def get_timesteps(self, num_inference_steps, strength, is_text2img):
563
+ if is_text2img:
564
+ return self.scheduler.timesteps, num_inference_steps
565
+ else:
566
+ # get the original timestep using init_timestep
567
+ offset = self.scheduler.config.get("steps_offset", 0)
568
+ init_timestep = int(num_inference_steps * strength) + offset
569
+ init_timestep = min(init_timestep, num_inference_steps)
570
+
571
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
572
+ timesteps = self.scheduler.timesteps[t_start:]
573
+ return timesteps, num_inference_steps - t_start
574
+
575
+ def run_safety_checker(self, image):
576
+ if self.safety_checker is not None:
577
+ safety_checker_input = self.feature_extractor(
578
+ self.numpy_to_pil(image), return_tensors="np"
579
+ ).pixel_values.astype(image.dtype)
580
+ # There will throw an error if use safety_checker directly and batchsize>1
581
+ images, has_nsfw_concept = [], []
582
+ for i in range(image.shape[0]):
583
+ image_i, has_nsfw_concept_i = self.safety_checker(
584
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
585
+ )
586
+ images.append(image_i)
587
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
588
+ image = np.concatenate(images)
589
+ else:
590
+ has_nsfw_concept = None
591
+ return image, has_nsfw_concept
592
+
593
+ def decode_latents(self, latents):
594
+ latents = 1 / 0.18215 * latents
595
+ # image = self.vae_decoder(latent_sample=latents)[0]
596
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
597
+ image = np.concatenate(
598
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
599
+ )
600
+ image = np.clip(image / 2 + 0.5, 0, 1)
601
+ image = image.transpose((0, 2, 3, 1))
602
+ return image
603
+
604
+ def prepare_extra_step_kwargs(self, generator, eta):
605
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
606
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
607
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
608
+ # and should be between [0, 1]
609
+
610
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
611
+ extra_step_kwargs = {}
612
+ if accepts_eta:
613
+ extra_step_kwargs["eta"] = eta
614
+
615
+ # check if the scheduler accepts generator
616
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
617
+ if accepts_generator:
618
+ extra_step_kwargs["generator"] = generator
619
+ return extra_step_kwargs
620
+
621
+ def prepare_latents(self, image, timestep, batch_size, height, width, dtype, generator, latents=None):
622
+ if image is None:
623
+ shape = (
624
+ batch_size,
625
+ self.unet.config.in_channels,
626
+ height // self.vae_scale_factor,
627
+ width // self.vae_scale_factor,
628
+ )
629
+
630
+ if latents is None:
631
+ latents = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
632
+ else:
633
+ if latents.shape != shape:
634
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
635
+
636
+ # scale the initial noise by the standard deviation required by the scheduler
637
+ latents = (torch.from_numpy(latents) * self.scheduler.init_noise_sigma).numpy()
638
+ return latents, None, None
639
+ else:
640
+ init_latents = self.vae_encoder(sample=image)[0]
641
+ init_latents = 0.18215 * init_latents
642
+ init_latents = np.concatenate([init_latents] * batch_size, axis=0)
643
+ init_latents_orig = init_latents
644
+ shape = init_latents.shape
645
+
646
+ # add noise to latents using the timesteps
647
+ noise = torch.randn(shape, generator=generator, device="cpu").numpy().astype(dtype)
648
+ latents = self.scheduler.add_noise(
649
+ torch.from_numpy(init_latents), torch.from_numpy(noise), timestep
650
+ ).numpy()
651
+ return latents, init_latents_orig, noise
652
+
653
+ @torch.no_grad()
654
+ def __call__(
655
+ self,
656
+ prompt: Union[str, List[str]],
657
+ negative_prompt: Optional[Union[str, List[str]]] = None,
658
+ image: Union[np.ndarray, PIL.Image.Image] = None,
659
+ mask_image: Union[np.ndarray, PIL.Image.Image] = None,
660
+ height: int = 512,
661
+ width: int = 512,
662
+ num_inference_steps: int = 50,
663
+ guidance_scale: float = 7.5,
664
+ strength: float = 0.8,
665
+ num_images_per_prompt: Optional[int] = 1,
666
+ eta: float = 0.0,
667
+ generator: Optional[torch.Generator] = None,
668
+ latents: Optional[np.ndarray] = None,
669
+ max_embeddings_multiples: Optional[int] = 3,
670
+ output_type: Optional[str] = "pil",
671
+ return_dict: bool = True,
672
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
673
+ is_cancelled_callback: Optional[Callable[[], bool]] = None,
674
+ callback_steps: int = 1,
675
+ **kwargs,
676
+ ):
677
+ r"""
678
+ Function invoked when calling the pipeline for generation.
679
+
680
+ Args:
681
+ prompt (`str` or `List[str]`):
682
+ The prompt or prompts to guide the image generation.
683
+ negative_prompt (`str` or `List[str]`, *optional*):
684
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
685
+ if `guidance_scale` is less than `1`).
686
+ image (`np.ndarray` or `PIL.Image.Image`):
687
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
688
+ process.
689
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
690
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
691
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
692
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
693
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
694
+ height (`int`, *optional*, defaults to 512):
695
+ The height in pixels of the generated image.
696
+ width (`int`, *optional*, defaults to 512):
697
+ The width in pixels of the generated image.
698
+ num_inference_steps (`int`, *optional*, defaults to 50):
699
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
700
+ expense of slower inference.
701
+ guidance_scale (`float`, *optional*, defaults to 7.5):
702
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
703
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
704
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
705
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
706
+ usually at the expense of lower image quality.
707
+ strength (`float`, *optional*, defaults to 0.8):
708
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
709
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
710
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
711
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
712
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
713
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
714
+ The number of images to generate per prompt.
715
+ eta (`float`, *optional*, defaults to 0.0):
716
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
717
+ [`schedulers.DDIMScheduler`], will be ignored for others.
718
+ generator (`torch.Generator`, *optional*):
719
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
720
+ deterministic.
721
+ latents (`np.ndarray`, *optional*):
722
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
723
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
724
+ tensor will ge generated by sampling using the supplied random `generator`.
725
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
726
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
727
+ output_type (`str`, *optional*, defaults to `"pil"`):
728
+ The output format of the generate image. Choose between
729
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
730
+ return_dict (`bool`, *optional*, defaults to `True`):
731
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
732
+ plain tuple.
733
+ callback (`Callable`, *optional*):
734
+ A function that will be called every `callback_steps` steps during inference. The function will be
735
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
736
+ is_cancelled_callback (`Callable`, *optional*):
737
+ A function that will be called every `callback_steps` steps during inference. If the function returns
738
+ `True`, the inference will be cancelled.
739
+ callback_steps (`int`, *optional*, defaults to 1):
740
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
741
+ called at every step.
742
+
743
+ Returns:
744
+ `None` if cancelled by `is_cancelled_callback`,
745
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
746
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
747
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
748
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
749
+ (nsfw) content, according to the `safety_checker`.
750
+ """
751
+ # 0. Default height and width to unet
752
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
753
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
754
+
755
+ # 1. Check inputs. Raise error if not correct
756
+ self.check_inputs(prompt, height, width, strength, callback_steps)
757
+
758
+ # 2. Define call parameters
759
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
760
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
761
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
762
+ # corresponds to doing no classifier free guidance.
763
+ do_classifier_free_guidance = guidance_scale > 1.0
764
+
765
+ # 3. Encode input prompt
766
+ text_embeddings = self._encode_prompt(
767
+ prompt,
768
+ num_images_per_prompt,
769
+ do_classifier_free_guidance,
770
+ negative_prompt,
771
+ max_embeddings_multiples,
772
+ )
773
+ dtype = text_embeddings.dtype
774
+
775
+ # 4. Preprocess image and mask
776
+ if isinstance(image, PIL.Image.Image):
777
+ image = preprocess_image(image)
778
+ if image is not None:
779
+ image = image.astype(dtype)
780
+ if isinstance(mask_image, PIL.Image.Image):
781
+ mask_image = preprocess_mask(mask_image, self.vae_scale_factor)
782
+ if mask_image is not None:
783
+ mask = mask_image.astype(dtype)
784
+ mask = np.concatenate([mask] * batch_size * num_images_per_prompt)
785
+ else:
786
+ mask = None
787
+
788
+ # 5. set timesteps
789
+ self.scheduler.set_timesteps(num_inference_steps)
790
+ timestep_dtype = next(
791
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
792
+ )
793
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
794
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, image is None)
795
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
796
+
797
+ # 6. Prepare latent variables
798
+ latents, init_latents_orig, noise = self.prepare_latents(
799
+ image,
800
+ latent_timestep,
801
+ batch_size * num_images_per_prompt,
802
+ height,
803
+ width,
804
+ dtype,
805
+ generator,
806
+ latents,
807
+ )
808
+
809
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
810
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
811
+
812
+ # 8. Denoising loop
813
+ for i, t in enumerate(self.progress_bar(timesteps)):
814
+ # expand the latents if we are doing classifier free guidance
815
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
816
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
817
+ latent_model_input = latent_model_input.numpy()
818
+
819
+ # predict the noise residual
820
+ noise_pred = self.unet(
821
+ sample=latent_model_input,
822
+ timestep=np.array([t], dtype=timestep_dtype),
823
+ encoder_hidden_states=text_embeddings,
824
+ )
825
+ noise_pred = noise_pred[0]
826
+
827
+ # perform guidance
828
+ if do_classifier_free_guidance:
829
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
830
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
831
+
832
+ # compute the previous noisy sample x_t -> x_t-1
833
+ scheduler_output = self.scheduler.step(
834
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
835
+ )
836
+ latents = scheduler_output.prev_sample.numpy()
837
+
838
+ if mask is not None:
839
+ # masking
840
+ init_latents_proper = self.scheduler.add_noise(
841
+ torch.from_numpy(init_latents_orig),
842
+ torch.from_numpy(noise),
843
+ t,
844
+ ).numpy()
845
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
846
+
847
+ # call the callback, if provided
848
+ if i % callback_steps == 0:
849
+ if callback is not None:
850
+ step_idx = i // getattr(self.scheduler, "order", 1)
851
+ callback(step_idx, t, latents)
852
+ if is_cancelled_callback is not None and is_cancelled_callback():
853
+ return None
854
+
855
+ # 9. Post-processing
856
+ image = self.decode_latents(latents)
857
+
858
+ # 10. Run safety checker
859
+ image, has_nsfw_concept = self.run_safety_checker(image)
860
+
861
+ # 11. Convert to PIL
862
+ if output_type == "pil":
863
+ image = self.numpy_to_pil(image)
864
+
865
+ if not return_dict:
866
+ return image, has_nsfw_concept
867
+
868
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
869
+
870
+ def text2img(
871
+ self,
872
+ prompt: Union[str, List[str]],
873
+ negative_prompt: Optional[Union[str, List[str]]] = None,
874
+ height: int = 512,
875
+ width: int = 512,
876
+ num_inference_steps: int = 50,
877
+ guidance_scale: float = 7.5,
878
+ num_images_per_prompt: Optional[int] = 1,
879
+ eta: float = 0.0,
880
+ generator: Optional[torch.Generator] = None,
881
+ latents: Optional[np.ndarray] = None,
882
+ max_embeddings_multiples: Optional[int] = 3,
883
+ output_type: Optional[str] = "pil",
884
+ return_dict: bool = True,
885
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
886
+ callback_steps: int = 1,
887
+ **kwargs,
888
+ ):
889
+ r"""
890
+ Function for text-to-image generation.
891
+ Args:
892
+ prompt (`str` or `List[str]`):
893
+ The prompt or prompts to guide the image generation.
894
+ negative_prompt (`str` or `List[str]`, *optional*):
895
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
896
+ if `guidance_scale` is less than `1`).
897
+ height (`int`, *optional*, defaults to 512):
898
+ The height in pixels of the generated image.
899
+ width (`int`, *optional*, defaults to 512):
900
+ The width in pixels of the generated image.
901
+ num_inference_steps (`int`, *optional*, defaults to 50):
902
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
903
+ expense of slower inference.
904
+ guidance_scale (`float`, *optional*, defaults to 7.5):
905
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
906
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
907
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
908
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
909
+ usually at the expense of lower image quality.
910
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
911
+ The number of images to generate per prompt.
912
+ eta (`float`, *optional*, defaults to 0.0):
913
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
914
+ [`schedulers.DDIMScheduler`], will be ignored for others.
915
+ generator (`torch.Generator`, *optional*):
916
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
917
+ deterministic.
918
+ latents (`np.ndarray`, *optional*):
919
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
920
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
921
+ tensor will ge generated by sampling using the supplied random `generator`.
922
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
923
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
924
+ output_type (`str`, *optional*, defaults to `"pil"`):
925
+ The output format of the generate image. Choose between
926
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
927
+ return_dict (`bool`, *optional*, defaults to `True`):
928
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
929
+ plain tuple.
930
+ callback (`Callable`, *optional*):
931
+ A function that will be called every `callback_steps` steps during inference. The function will be
932
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
933
+ callback_steps (`int`, *optional*, defaults to 1):
934
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
935
+ called at every step.
936
+ Returns:
937
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
938
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
939
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
940
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
941
+ (nsfw) content, according to the `safety_checker`.
942
+ """
943
+ return self.__call__(
944
+ prompt=prompt,
945
+ negative_prompt=negative_prompt,
946
+ height=height,
947
+ width=width,
948
+ num_inference_steps=num_inference_steps,
949
+ guidance_scale=guidance_scale,
950
+ num_images_per_prompt=num_images_per_prompt,
951
+ eta=eta,
952
+ generator=generator,
953
+ latents=latents,
954
+ max_embeddings_multiples=max_embeddings_multiples,
955
+ output_type=output_type,
956
+ return_dict=return_dict,
957
+ callback=callback,
958
+ callback_steps=callback_steps,
959
+ **kwargs,
960
+ )
961
+
962
+ def img2img(
963
+ self,
964
+ image: Union[np.ndarray, PIL.Image.Image],
965
+ prompt: Union[str, List[str]],
966
+ negative_prompt: Optional[Union[str, List[str]]] = None,
967
+ strength: float = 0.8,
968
+ num_inference_steps: Optional[int] = 50,
969
+ guidance_scale: Optional[float] = 7.5,
970
+ num_images_per_prompt: Optional[int] = 1,
971
+ eta: Optional[float] = 0.0,
972
+ generator: Optional[torch.Generator] = None,
973
+ max_embeddings_multiples: Optional[int] = 3,
974
+ output_type: Optional[str] = "pil",
975
+ return_dict: bool = True,
976
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
977
+ callback_steps: int = 1,
978
+ **kwargs,
979
+ ):
980
+ r"""
981
+ Function for image-to-image generation.
982
+ Args:
983
+ image (`np.ndarray` or `PIL.Image.Image`):
984
+ `Image`, or ndarray representing an image batch, that will be used as the starting point for the
985
+ process.
986
+ prompt (`str` or `List[str]`):
987
+ The prompt or prompts to guide the image generation.
988
+ negative_prompt (`str` or `List[str]`, *optional*):
989
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
990
+ if `guidance_scale` is less than `1`).
991
+ strength (`float`, *optional*, defaults to 0.8):
992
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
993
+ `image` will be used as a starting point, adding more noise to it the larger the `strength`. The
994
+ number of denoising steps depends on the amount of noise initially added. When `strength` is 1, added
995
+ noise will be maximum and the denoising process will run for the full number of iterations specified in
996
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
997
+ num_inference_steps (`int`, *optional*, defaults to 50):
998
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
999
+ expense of slower inference. This parameter will be modulated by `strength`.
1000
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1001
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1002
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1003
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1004
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1005
+ usually at the expense of lower image quality.
1006
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1007
+ The number of images to generate per prompt.
1008
+ eta (`float`, *optional*, defaults to 0.0):
1009
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1010
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1011
+ generator (`torch.Generator`, *optional*):
1012
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1013
+ deterministic.
1014
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1015
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1016
+ output_type (`str`, *optional*, defaults to `"pil"`):
1017
+ The output format of the generate image. Choose between
1018
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1019
+ return_dict (`bool`, *optional*, defaults to `True`):
1020
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1021
+ plain tuple.
1022
+ callback (`Callable`, *optional*):
1023
+ A function that will be called every `callback_steps` steps during inference. The function will be
1024
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1025
+ callback_steps (`int`, *optional*, defaults to 1):
1026
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1027
+ called at every step.
1028
+ Returns:
1029
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1030
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1031
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1032
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1033
+ (nsfw) content, according to the `safety_checker`.
1034
+ """
1035
+ return self.__call__(
1036
+ prompt=prompt,
1037
+ negative_prompt=negative_prompt,
1038
+ image=image,
1039
+ num_inference_steps=num_inference_steps,
1040
+ guidance_scale=guidance_scale,
1041
+ strength=strength,
1042
+ num_images_per_prompt=num_images_per_prompt,
1043
+ eta=eta,
1044
+ generator=generator,
1045
+ max_embeddings_multiples=max_embeddings_multiples,
1046
+ output_type=output_type,
1047
+ return_dict=return_dict,
1048
+ callback=callback,
1049
+ callback_steps=callback_steps,
1050
+ **kwargs,
1051
+ )
1052
+
1053
+ def inpaint(
1054
+ self,
1055
+ image: Union[np.ndarray, PIL.Image.Image],
1056
+ mask_image: Union[np.ndarray, PIL.Image.Image],
1057
+ prompt: Union[str, List[str]],
1058
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1059
+ strength: float = 0.8,
1060
+ num_inference_steps: Optional[int] = 50,
1061
+ guidance_scale: Optional[float] = 7.5,
1062
+ num_images_per_prompt: Optional[int] = 1,
1063
+ eta: Optional[float] = 0.0,
1064
+ generator: Optional[torch.Generator] = None,
1065
+ max_embeddings_multiples: Optional[int] = 3,
1066
+ output_type: Optional[str] = "pil",
1067
+ return_dict: bool = True,
1068
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
1069
+ callback_steps: int = 1,
1070
+ **kwargs,
1071
+ ):
1072
+ r"""
1073
+ Function for inpaint.
1074
+ Args:
1075
+ image (`np.ndarray` or `PIL.Image.Image`):
1076
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
1077
+ process. This is the image whose masked region will be inpainted.
1078
+ mask_image (`np.ndarray` or `PIL.Image.Image`):
1079
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1080
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
1081
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
1082
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.
1083
+ prompt (`str` or `List[str]`):
1084
+ The prompt or prompts to guide the image generation.
1085
+ negative_prompt (`str` or `List[str]`, *optional*):
1086
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
1087
+ if `guidance_scale` is less than `1`).
1088
+ strength (`float`, *optional*, defaults to 0.8):
1089
+ Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength`
1090
+ is 1, the denoising process will be run on the masked area for the full number of iterations specified
1091
+ in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more
1092
+ noise to that region the larger the `strength`. If `strength` is 0, no inpainting will occur.
1093
+ num_inference_steps (`int`, *optional*, defaults to 50):
1094
+ The reference number of denoising steps. More denoising steps usually lead to a higher quality image at
1095
+ the expense of slower inference. This parameter will be modulated by `strength`, as explained above.
1096
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1097
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1098
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1099
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1100
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1101
+ usually at the expense of lower image quality.
1102
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1103
+ The number of images to generate per prompt.
1104
+ eta (`float`, *optional*, defaults to 0.0):
1105
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1106
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1107
+ generator (`torch.Generator`, *optional*):
1108
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
1109
+ deterministic.
1110
+ max_embeddings_multiples (`int`, *optional*, defaults to `3`):
1111
+ The max multiple length of prompt embeddings compared to the max output length of text encoder.
1112
+ output_type (`str`, *optional*, defaults to `"pil"`):
1113
+ The output format of the generate image. Choose between
1114
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1115
+ return_dict (`bool`, *optional*, defaults to `True`):
1116
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1117
+ plain tuple.
1118
+ callback (`Callable`, *optional*):
1119
+ A function that will be called every `callback_steps` steps during inference. The function will be
1120
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
1121
+ callback_steps (`int`, *optional*, defaults to 1):
1122
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1123
+ called at every step.
1124
+ Returns:
1125
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1126
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
1127
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
1128
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
1129
+ (nsfw) content, according to the `safety_checker`.
1130
+ """
1131
+ return self.__call__(
1132
+ prompt=prompt,
1133
+ negative_prompt=negative_prompt,
1134
+ image=image,
1135
+ mask_image=mask_image,
1136
+ num_inference_steps=num_inference_steps,
1137
+ guidance_scale=guidance_scale,
1138
+ strength=strength,
1139
+ num_images_per_prompt=num_images_per_prompt,
1140
+ eta=eta,
1141
+ generator=generator,
1142
+ max_embeddings_multiples=max_embeddings_multiples,
1143
+ output_type=output_type,
1144
+ return_dict=return_dict,
1145
+ callback=callback,
1146
+ callback_steps=callback_steps,
1147
+ **kwargs,
1148
+ )
v0.32.0/lpw_stable_diffusion_xl.py ADDED
The diff for this file is too large to render. See raw diff
 
v0.32.0/magic_mix.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+
3
+ import torch
4
+ from PIL import Image
5
+ from torchvision import transforms as tfms
6
+ from tqdm.auto import tqdm
7
+ from transformers import CLIPTextModel, CLIPTokenizer
8
+
9
+ from diffusers import (
10
+ AutoencoderKL,
11
+ DDIMScheduler,
12
+ DiffusionPipeline,
13
+ LMSDiscreteScheduler,
14
+ PNDMScheduler,
15
+ UNet2DConditionModel,
16
+ )
17
+
18
+
19
+ class MagicMixPipeline(DiffusionPipeline):
20
+ def __init__(
21
+ self,
22
+ vae: AutoencoderKL,
23
+ text_encoder: CLIPTextModel,
24
+ tokenizer: CLIPTokenizer,
25
+ unet: UNet2DConditionModel,
26
+ scheduler: Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler],
27
+ ):
28
+ super().__init__()
29
+
30
+ self.register_modules(vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, unet=unet, scheduler=scheduler)
31
+
32
+ # convert PIL image to latents
33
+ def encode(self, img):
34
+ with torch.no_grad():
35
+ latent = self.vae.encode(tfms.ToTensor()(img).unsqueeze(0).to(self.device) * 2 - 1)
36
+ latent = 0.18215 * latent.latent_dist.sample()
37
+ return latent
38
+
39
+ # convert latents to PIL image
40
+ def decode(self, latent):
41
+ latent = (1 / 0.18215) * latent
42
+ with torch.no_grad():
43
+ img = self.vae.decode(latent).sample
44
+ img = (img / 2 + 0.5).clamp(0, 1)
45
+ img = img.detach().cpu().permute(0, 2, 3, 1).numpy()
46
+ img = (img * 255).round().astype("uint8")
47
+ return Image.fromarray(img[0])
48
+
49
+ # convert prompt into text embeddings, also unconditional embeddings
50
+ def prep_text(self, prompt):
51
+ text_input = self.tokenizer(
52
+ prompt,
53
+ padding="max_length",
54
+ max_length=self.tokenizer.model_max_length,
55
+ truncation=True,
56
+ return_tensors="pt",
57
+ )
58
+
59
+ text_embedding = self.text_encoder(text_input.input_ids.to(self.device))[0]
60
+
61
+ uncond_input = self.tokenizer(
62
+ "",
63
+ padding="max_length",
64
+ max_length=self.tokenizer.model_max_length,
65
+ truncation=True,
66
+ return_tensors="pt",
67
+ )
68
+
69
+ uncond_embedding = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
70
+
71
+ return torch.cat([uncond_embedding, text_embedding])
72
+
73
+ def __call__(
74
+ self,
75
+ img: Image.Image,
76
+ prompt: str,
77
+ kmin: float = 0.3,
78
+ kmax: float = 0.6,
79
+ mix_factor: float = 0.5,
80
+ seed: int = 42,
81
+ steps: int = 50,
82
+ guidance_scale: float = 7.5,
83
+ ) -> Image.Image:
84
+ tmin = steps - int(kmin * steps)
85
+ tmax = steps - int(kmax * steps)
86
+
87
+ text_embeddings = self.prep_text(prompt)
88
+
89
+ self.scheduler.set_timesteps(steps)
90
+
91
+ width, height = img.size
92
+ encoded = self.encode(img)
93
+
94
+ torch.manual_seed(seed)
95
+ noise = torch.randn(
96
+ (1, self.unet.config.in_channels, height // 8, width // 8),
97
+ ).to(self.device)
98
+
99
+ latents = self.scheduler.add_noise(
100
+ encoded,
101
+ noise,
102
+ timesteps=self.scheduler.timesteps[tmax],
103
+ )
104
+
105
+ input = torch.cat([latents] * 2)
106
+
107
+ input = self.scheduler.scale_model_input(input, self.scheduler.timesteps[tmax])
108
+
109
+ with torch.no_grad():
110
+ pred = self.unet(
111
+ input,
112
+ self.scheduler.timesteps[tmax],
113
+ encoder_hidden_states=text_embeddings,
114
+ ).sample
115
+
116
+ pred_uncond, pred_text = pred.chunk(2)
117
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
118
+
119
+ latents = self.scheduler.step(pred, self.scheduler.timesteps[tmax], latents).prev_sample
120
+
121
+ for i, t in enumerate(tqdm(self.scheduler.timesteps)):
122
+ if i > tmax:
123
+ if i < tmin: # layout generation phase
124
+ orig_latents = self.scheduler.add_noise(
125
+ encoded,
126
+ noise,
127
+ timesteps=t,
128
+ )
129
+
130
+ input = (
131
+ (mix_factor * latents) + (1 - mix_factor) * orig_latents
132
+ ) # interpolating between layout noise and conditionally generated noise to preserve layout sematics
133
+ input = torch.cat([input] * 2)
134
+
135
+ else: # content generation phase
136
+ input = torch.cat([latents] * 2)
137
+
138
+ input = self.scheduler.scale_model_input(input, t)
139
+
140
+ with torch.no_grad():
141
+ pred = self.unet(
142
+ input,
143
+ t,
144
+ encoder_hidden_states=text_embeddings,
145
+ ).sample
146
+
147
+ pred_uncond, pred_text = pred.chunk(2)
148
+ pred = pred_uncond + guidance_scale * (pred_text - pred_uncond)
149
+
150
+ latents = self.scheduler.step(pred, t, latents).prev_sample
151
+
152
+ return self.decode(latents)
v0.32.0/marigold_depth_estimation.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Bingxin Ke, ETH Zurich and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # --------------------------------------------------------------------------
15
+ # If you find this code useful, we kindly ask you to cite our paper in your work.
16
+ # Please find bibtex at: https://github.com/prs-eth/Marigold#-citation
17
+ # More information about the method can be found at https://marigoldmonodepth.github.io
18
+ # --------------------------------------------------------------------------
19
+
20
+
21
+ import logging
22
+ import math
23
+ from typing import Dict, Union
24
+
25
+ import matplotlib
26
+ import numpy as np
27
+ import torch
28
+ from PIL import Image
29
+ from PIL.Image import Resampling
30
+ from scipy.optimize import minimize
31
+ from torch.utils.data import DataLoader, TensorDataset
32
+ from tqdm.auto import tqdm
33
+ from transformers import CLIPTextModel, CLIPTokenizer
34
+
35
+ from diffusers import (
36
+ AutoencoderKL,
37
+ DDIMScheduler,
38
+ DiffusionPipeline,
39
+ LCMScheduler,
40
+ UNet2DConditionModel,
41
+ )
42
+ from diffusers.utils import BaseOutput, check_min_version
43
+
44
+
45
+ # Will error if the minimal version of diffusers is not installed. Remove at your own risks.
46
+ check_min_version("0.32.0")
47
+
48
+ class MarigoldDepthOutput(BaseOutput):
49
+ """
50
+ Output class for Marigold monocular depth prediction pipeline.
51
+
52
+ Args:
53
+ depth_np (`np.ndarray`):
54
+ Predicted depth map, with depth values in the range of [0, 1].
55
+ depth_colored (`None` or `PIL.Image.Image`):
56
+ Colorized depth map, with the shape of [3, H, W] and values in [0, 1].
57
+ uncertainty (`None` or `np.ndarray`):
58
+ Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling.
59
+ """
60
+
61
+ depth_np: np.ndarray
62
+ depth_colored: Union[None, Image.Image]
63
+ uncertainty: Union[None, np.ndarray]
64
+
65
+
66
+ def get_pil_resample_method(method_str: str) -> Resampling:
67
+ resample_method_dic = {
68
+ "bilinear": Resampling.BILINEAR,
69
+ "bicubic": Resampling.BICUBIC,
70
+ "nearest": Resampling.NEAREST,
71
+ }
72
+ resample_method = resample_method_dic.get(method_str, None)
73
+ if resample_method is None:
74
+ raise ValueError(f"Unknown resampling method: {resample_method}")
75
+ else:
76
+ return resample_method
77
+
78
+
79
+ class MarigoldPipeline(DiffusionPipeline):
80
+ """
81
+ Pipeline for monocular depth estimation using Marigold: https://marigoldmonodepth.github.io.
82
+
83
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
84
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
85
+
86
+ Args:
87
+ unet (`UNet2DConditionModel`):
88
+ Conditional U-Net to denoise the depth latent, conditioned on image latent.
89
+ vae (`AutoencoderKL`):
90
+ Variational Auto-Encoder (VAE) Model to encode and decode images and depth maps
91
+ to and from latent representations.
92
+ scheduler (`DDIMScheduler`):
93
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents.
94
+ text_encoder (`CLIPTextModel`):
95
+ Text-encoder, for empty text embedding.
96
+ tokenizer (`CLIPTokenizer`):
97
+ CLIP tokenizer.
98
+ """
99
+
100
+ rgb_latent_scale_factor = 0.18215
101
+ depth_latent_scale_factor = 0.18215
102
+
103
+ def __init__(
104
+ self,
105
+ unet: UNet2DConditionModel,
106
+ vae: AutoencoderKL,
107
+ scheduler: DDIMScheduler,
108
+ text_encoder: CLIPTextModel,
109
+ tokenizer: CLIPTokenizer,
110
+ ):
111
+ super().__init__()
112
+
113
+ self.register_modules(
114
+ unet=unet,
115
+ vae=vae,
116
+ scheduler=scheduler,
117
+ text_encoder=text_encoder,
118
+ tokenizer=tokenizer,
119
+ )
120
+
121
+ self.empty_text_embed = None
122
+
123
+ @torch.no_grad()
124
+ def __call__(
125
+ self,
126
+ input_image: Image,
127
+ denoising_steps: int = 10,
128
+ ensemble_size: int = 10,
129
+ processing_res: int = 768,
130
+ match_input_res: bool = True,
131
+ resample_method: str = "bilinear",
132
+ batch_size: int = 0,
133
+ seed: Union[int, None] = None,
134
+ color_map: str = "Spectral",
135
+ show_progress_bar: bool = True,
136
+ ensemble_kwargs: Dict = None,
137
+ ) -> MarigoldDepthOutput:
138
+ """
139
+ Function invoked when calling the pipeline.
140
+
141
+ Args:
142
+ input_image (`Image`):
143
+ Input RGB (or gray-scale) image.
144
+ processing_res (`int`, *optional*, defaults to `768`):
145
+ Maximum resolution of processing.
146
+ If set to 0: will not resize at all.
147
+ match_input_res (`bool`, *optional*, defaults to `True`):
148
+ Resize depth prediction to match input resolution.
149
+ Only valid if `processing_res` > 0.
150
+ resample_method: (`str`, *optional*, defaults to `bilinear`):
151
+ Resampling method used to resize images and depth predictions. This can be one of `bilinear`, `bicubic` or `nearest`, defaults to: `bilinear`.
152
+ denoising_steps (`int`, *optional*, defaults to `10`):
153
+ Number of diffusion denoising steps (DDIM) during inference.
154
+ ensemble_size (`int`, *optional*, defaults to `10`):
155
+ Number of predictions to be ensembled.
156
+ batch_size (`int`, *optional*, defaults to `0`):
157
+ Inference batch size, no bigger than `num_ensemble`.
158
+ If set to 0, the script will automatically decide the proper batch size.
159
+ seed (`int`, *optional*, defaults to `None`)
160
+ Reproducibility seed.
161
+ show_progress_bar (`bool`, *optional*, defaults to `True`):
162
+ Display a progress bar of diffusion denoising.
163
+ color_map (`str`, *optional*, defaults to `"Spectral"`, pass `None` to skip colorized depth map generation):
164
+ Colormap used to colorize the depth map.
165
+ ensemble_kwargs (`dict`, *optional*, defaults to `None`):
166
+ Arguments for detailed ensembling settings.
167
+ Returns:
168
+ `MarigoldDepthOutput`: Output class for Marigold monocular depth prediction pipeline, including:
169
+ - **depth_np** (`np.ndarray`) Predicted depth map, with depth values in the range of [0, 1]
170
+ - **depth_colored** (`PIL.Image.Image`) Colorized depth map, with the shape of [3, H, W] and values in [0, 1], None if `color_map` is `None`
171
+ - **uncertainty** (`None` or `np.ndarray`) Uncalibrated uncertainty(MAD, median absolute deviation)
172
+ coming from ensembling. None if `ensemble_size = 1`
173
+ """
174
+
175
+ device = self.device
176
+ input_size = input_image.size
177
+
178
+ if not match_input_res:
179
+ assert processing_res is not None, "Value error: `resize_output_back` is only valid with "
180
+ assert processing_res >= 0
181
+ assert ensemble_size >= 1
182
+
183
+ # Check if denoising step is reasonable
184
+ self._check_inference_step(denoising_steps)
185
+
186
+ resample_method: Resampling = get_pil_resample_method(resample_method)
187
+
188
+ # ----------------- Image Preprocess -----------------
189
+ # Resize image
190
+ if processing_res > 0:
191
+ input_image = self.resize_max_res(
192
+ input_image,
193
+ max_edge_resolution=processing_res,
194
+ resample_method=resample_method,
195
+ )
196
+ # Convert the image to RGB, to 1.remove the alpha channel 2.convert B&W to 3-channel
197
+ input_image = input_image.convert("RGB")
198
+ image = np.asarray(input_image)
199
+
200
+ # Normalize rgb values
201
+ rgb = np.transpose(image, (2, 0, 1)) # [H, W, rgb] -> [rgb, H, W]
202
+ rgb_norm = rgb / 255.0 * 2.0 - 1.0 # [0, 255] -> [-1, 1]
203
+ rgb_norm = torch.from_numpy(rgb_norm).to(self.dtype)
204
+ rgb_norm = rgb_norm.to(device)
205
+ assert rgb_norm.min() >= -1.0 and rgb_norm.max() <= 1.0
206
+
207
+ # ----------------- Predicting depth -----------------
208
+ # Batch repeated input image
209
+ duplicated_rgb = torch.stack([rgb_norm] * ensemble_size)
210
+ single_rgb_dataset = TensorDataset(duplicated_rgb)
211
+ if batch_size > 0:
212
+ _bs = batch_size
213
+ else:
214
+ _bs = self._find_batch_size(
215
+ ensemble_size=ensemble_size,
216
+ input_res=max(rgb_norm.shape[1:]),
217
+ dtype=self.dtype,
218
+ )
219
+
220
+ single_rgb_loader = DataLoader(single_rgb_dataset, batch_size=_bs, shuffle=False)
221
+
222
+ # Predict depth maps (batched)
223
+ depth_pred_ls = []
224
+ if show_progress_bar:
225
+ iterable = tqdm(single_rgb_loader, desc=" " * 2 + "Inference batches", leave=False)
226
+ else:
227
+ iterable = single_rgb_loader
228
+ for batch in iterable:
229
+ (batched_img,) = batch
230
+ depth_pred_raw = self.single_infer(
231
+ rgb_in=batched_img,
232
+ num_inference_steps=denoising_steps,
233
+ show_pbar=show_progress_bar,
234
+ seed=seed,
235
+ )
236
+ depth_pred_ls.append(depth_pred_raw.detach())
237
+ depth_preds = torch.concat(depth_pred_ls, dim=0).squeeze()
238
+ torch.cuda.empty_cache() # clear vram cache for ensembling
239
+
240
+ # ----------------- Test-time ensembling -----------------
241
+ if ensemble_size > 1:
242
+ depth_pred, pred_uncert = self.ensemble_depths(depth_preds, **(ensemble_kwargs or {}))
243
+ else:
244
+ depth_pred = depth_preds
245
+ pred_uncert = None
246
+
247
+ # ----------------- Post processing -----------------
248
+ # Scale prediction to [0, 1]
249
+ min_d = torch.min(depth_pred)
250
+ max_d = torch.max(depth_pred)
251
+ depth_pred = (depth_pred - min_d) / (max_d - min_d)
252
+
253
+ # Convert to numpy
254
+ depth_pred = depth_pred.cpu().numpy().astype(np.float32)
255
+
256
+ # Resize back to original resolution
257
+ if match_input_res:
258
+ pred_img = Image.fromarray(depth_pred)
259
+ pred_img = pred_img.resize(input_size, resample=resample_method)
260
+ depth_pred = np.asarray(pred_img)
261
+
262
+ # Clip output range
263
+ depth_pred = depth_pred.clip(0, 1)
264
+
265
+ # Colorize
266
+ if color_map is not None:
267
+ depth_colored = self.colorize_depth_maps(
268
+ depth_pred, 0, 1, cmap=color_map
269
+ ).squeeze() # [3, H, W], value in (0, 1)
270
+ depth_colored = (depth_colored * 255).astype(np.uint8)
271
+ depth_colored_hwc = self.chw2hwc(depth_colored)
272
+ depth_colored_img = Image.fromarray(depth_colored_hwc)
273
+ else:
274
+ depth_colored_img = None
275
+
276
+ return MarigoldDepthOutput(
277
+ depth_np=depth_pred,
278
+ depth_colored=depth_colored_img,
279
+ uncertainty=pred_uncert,
280
+ )
281
+
282
+ def _check_inference_step(self, n_step: int):
283
+ """
284
+ Check if denoising step is reasonable
285
+ Args:
286
+ n_step (`int`): denoising steps
287
+ """
288
+ assert n_step >= 1
289
+
290
+ if isinstance(self.scheduler, DDIMScheduler):
291
+ if n_step < 10:
292
+ logging.warning(
293
+ f"Too few denoising steps: {n_step}. Recommended to use the LCM checkpoint for few-step inference."
294
+ )
295
+ elif isinstance(self.scheduler, LCMScheduler):
296
+ if not 1 <= n_step <= 4:
297
+ logging.warning(f"Non-optimal setting of denoising steps: {n_step}. Recommended setting is 1-4 steps.")
298
+ else:
299
+ raise RuntimeError(f"Unsupported scheduler type: {type(self.scheduler)}")
300
+
301
+ def _encode_empty_text(self):
302
+ """
303
+ Encode text embedding for empty prompt.
304
+ """
305
+ prompt = ""
306
+ text_inputs = self.tokenizer(
307
+ prompt,
308
+ padding="do_not_pad",
309
+ max_length=self.tokenizer.model_max_length,
310
+ truncation=True,
311
+ return_tensors="pt",
312
+ )
313
+ text_input_ids = text_inputs.input_ids.to(self.text_encoder.device)
314
+ self.empty_text_embed = self.text_encoder(text_input_ids)[0].to(self.dtype)
315
+
316
+ @torch.no_grad()
317
+ def single_infer(
318
+ self,
319
+ rgb_in: torch.Tensor,
320
+ num_inference_steps: int,
321
+ seed: Union[int, None],
322
+ show_pbar: bool,
323
+ ) -> torch.Tensor:
324
+ """
325
+ Perform an individual depth prediction without ensembling.
326
+
327
+ Args:
328
+ rgb_in (`torch.Tensor`):
329
+ Input RGB image.
330
+ num_inference_steps (`int`):
331
+ Number of diffusion denoisign steps (DDIM) during inference.
332
+ show_pbar (`bool`):
333
+ Display a progress bar of diffusion denoising.
334
+ Returns:
335
+ `torch.Tensor`: Predicted depth map.
336
+ """
337
+ device = rgb_in.device
338
+
339
+ # Set timesteps
340
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
341
+ timesteps = self.scheduler.timesteps # [T]
342
+
343
+ # Encode image
344
+ rgb_latent = self.encode_rgb(rgb_in)
345
+
346
+ # Initial depth map (noise)
347
+ if seed is None:
348
+ rand_num_generator = None
349
+ else:
350
+ rand_num_generator = torch.Generator(device=device)
351
+ rand_num_generator.manual_seed(seed)
352
+ depth_latent = torch.randn(
353
+ rgb_latent.shape,
354
+ device=device,
355
+ dtype=self.dtype,
356
+ generator=rand_num_generator,
357
+ ) # [B, 4, h, w]
358
+
359
+ # Batched empty text embedding
360
+ if self.empty_text_embed is None:
361
+ self._encode_empty_text()
362
+ batch_empty_text_embed = self.empty_text_embed.repeat((rgb_latent.shape[0], 1, 1)) # [B, 2, 1024]
363
+
364
+ # Denoising loop
365
+ if show_pbar:
366
+ iterable = tqdm(
367
+ enumerate(timesteps),
368
+ total=len(timesteps),
369
+ leave=False,
370
+ desc=" " * 4 + "Diffusion denoising",
371
+ )
372
+ else:
373
+ iterable = enumerate(timesteps)
374
+
375
+ for i, t in iterable:
376
+ unet_input = torch.cat([rgb_latent, depth_latent], dim=1) # this order is important
377
+
378
+ # predict the noise residual
379
+ noise_pred = self.unet(unet_input, t, encoder_hidden_states=batch_empty_text_embed).sample # [B, 4, h, w]
380
+
381
+ # compute the previous noisy sample x_t -> x_t-1
382
+ depth_latent = self.scheduler.step(noise_pred, t, depth_latent, generator=rand_num_generator).prev_sample
383
+
384
+ depth = self.decode_depth(depth_latent)
385
+
386
+ # clip prediction
387
+ depth = torch.clip(depth, -1.0, 1.0)
388
+ # shift to [0, 1]
389
+ depth = (depth + 1.0) / 2.0
390
+
391
+ return depth
392
+
393
+ def encode_rgb(self, rgb_in: torch.Tensor) -> torch.Tensor:
394
+ """
395
+ Encode RGB image into latent.
396
+
397
+ Args:
398
+ rgb_in (`torch.Tensor`):
399
+ Input RGB image to be encoded.
400
+
401
+ Returns:
402
+ `torch.Tensor`: Image latent.
403
+ """
404
+ # encode
405
+ h = self.vae.encoder(rgb_in)
406
+ moments = self.vae.quant_conv(h)
407
+ mean, logvar = torch.chunk(moments, 2, dim=1)
408
+ # scale latent
409
+ rgb_latent = mean * self.rgb_latent_scale_factor
410
+ return rgb_latent
411
+
412
+ def decode_depth(self, depth_latent: torch.Tensor) -> torch.Tensor:
413
+ """
414
+ Decode depth latent into depth map.
415
+
416
+ Args:
417
+ depth_latent (`torch.Tensor`):
418
+ Depth latent to be decoded.
419
+
420
+ Returns:
421
+ `torch.Tensor`: Decoded depth map.
422
+ """
423
+ # scale latent
424
+ depth_latent = depth_latent / self.depth_latent_scale_factor
425
+ # decode
426
+ z = self.vae.post_quant_conv(depth_latent)
427
+ stacked = self.vae.decoder(z)
428
+ # mean of output channels
429
+ depth_mean = stacked.mean(dim=1, keepdim=True)
430
+ return depth_mean
431
+
432
+ @staticmethod
433
+ def resize_max_res(img: Image.Image, max_edge_resolution: int, resample_method=Resampling.BILINEAR) -> Image.Image:
434
+ """
435
+ Resize image to limit maximum edge length while keeping aspect ratio.
436
+
437
+ Args:
438
+ img (`Image.Image`):
439
+ Image to be resized.
440
+ max_edge_resolution (`int`):
441
+ Maximum edge length (pixel).
442
+ resample_method (`PIL.Image.Resampling`):
443
+ Resampling method used to resize images.
444
+
445
+ Returns:
446
+ `Image.Image`: Resized image.
447
+ """
448
+ original_width, original_height = img.size
449
+ downscale_factor = min(max_edge_resolution / original_width, max_edge_resolution / original_height)
450
+
451
+ new_width = int(original_width * downscale_factor)
452
+ new_height = int(original_height * downscale_factor)
453
+
454
+ resized_img = img.resize((new_width, new_height), resample=resample_method)
455
+ return resized_img
456
+
457
+ @staticmethod
458
+ def colorize_depth_maps(depth_map, min_depth, max_depth, cmap="Spectral", valid_mask=None):
459
+ """
460
+ Colorize depth maps.
461
+ """
462
+ assert len(depth_map.shape) >= 2, "Invalid dimension"
463
+
464
+ if isinstance(depth_map, torch.Tensor):
465
+ depth = depth_map.detach().clone().squeeze().numpy()
466
+ elif isinstance(depth_map, np.ndarray):
467
+ depth = depth_map.copy().squeeze()
468
+ # reshape to [ (B,) H, W ]
469
+ if depth.ndim < 3:
470
+ depth = depth[np.newaxis, :, :]
471
+
472
+ # colorize
473
+ cm = matplotlib.colormaps[cmap]
474
+ depth = ((depth - min_depth) / (max_depth - min_depth)).clip(0, 1)
475
+ img_colored_np = cm(depth, bytes=False)[:, :, :, 0:3] # value from 0 to 1
476
+ img_colored_np = np.rollaxis(img_colored_np, 3, 1)
477
+
478
+ if valid_mask is not None:
479
+ if isinstance(depth_map, torch.Tensor):
480
+ valid_mask = valid_mask.detach().numpy()
481
+ valid_mask = valid_mask.squeeze() # [H, W] or [B, H, W]
482
+ if valid_mask.ndim < 3:
483
+ valid_mask = valid_mask[np.newaxis, np.newaxis, :, :]
484
+ else:
485
+ valid_mask = valid_mask[:, np.newaxis, :, :]
486
+ valid_mask = np.repeat(valid_mask, 3, axis=1)
487
+ img_colored_np[~valid_mask] = 0
488
+
489
+ if isinstance(depth_map, torch.Tensor):
490
+ img_colored = torch.from_numpy(img_colored_np).float()
491
+ elif isinstance(depth_map, np.ndarray):
492
+ img_colored = img_colored_np
493
+
494
+ return img_colored
495
+
496
+ @staticmethod
497
+ def chw2hwc(chw):
498
+ assert 3 == len(chw.shape)
499
+ if isinstance(chw, torch.Tensor):
500
+ hwc = torch.permute(chw, (1, 2, 0))
501
+ elif isinstance(chw, np.ndarray):
502
+ hwc = np.moveaxis(chw, 0, -1)
503
+ return hwc
504
+
505
+ @staticmethod
506
+ def _find_batch_size(ensemble_size: int, input_res: int, dtype: torch.dtype) -> int:
507
+ """
508
+ Automatically search for suitable operating batch size.
509
+
510
+ Args:
511
+ ensemble_size (`int`):
512
+ Number of predictions to be ensembled.
513
+ input_res (`int`):
514
+ Operating resolution of the input image.
515
+
516
+ Returns:
517
+ `int`: Operating batch size.
518
+ """
519
+ # Search table for suggested max. inference batch size
520
+ bs_search_table = [
521
+ # tested on A100-PCIE-80GB
522
+ {"res": 768, "total_vram": 79, "bs": 35, "dtype": torch.float32},
523
+ {"res": 1024, "total_vram": 79, "bs": 20, "dtype": torch.float32},
524
+ # tested on A100-PCIE-40GB
525
+ {"res": 768, "total_vram": 39, "bs": 15, "dtype": torch.float32},
526
+ {"res": 1024, "total_vram": 39, "bs": 8, "dtype": torch.float32},
527
+ {"res": 768, "total_vram": 39, "bs": 30, "dtype": torch.float16},
528
+ {"res": 1024, "total_vram": 39, "bs": 15, "dtype": torch.float16},
529
+ # tested on RTX3090, RTX4090
530
+ {"res": 512, "total_vram": 23, "bs": 20, "dtype": torch.float32},
531
+ {"res": 768, "total_vram": 23, "bs": 7, "dtype": torch.float32},
532
+ {"res": 1024, "total_vram": 23, "bs": 3, "dtype": torch.float32},
533
+ {"res": 512, "total_vram": 23, "bs": 40, "dtype": torch.float16},
534
+ {"res": 768, "total_vram": 23, "bs": 18, "dtype": torch.float16},
535
+ {"res": 1024, "total_vram": 23, "bs": 10, "dtype": torch.float16},
536
+ # tested on GTX1080Ti
537
+ {"res": 512, "total_vram": 10, "bs": 5, "dtype": torch.float32},
538
+ {"res": 768, "total_vram": 10, "bs": 2, "dtype": torch.float32},
539
+ {"res": 512, "total_vram": 10, "bs": 10, "dtype": torch.float16},
540
+ {"res": 768, "total_vram": 10, "bs": 5, "dtype": torch.float16},
541
+ {"res": 1024, "total_vram": 10, "bs": 3, "dtype": torch.float16},
542
+ ]
543
+
544
+ if not torch.cuda.is_available():
545
+ return 1
546
+
547
+ total_vram = torch.cuda.mem_get_info()[1] / 1024.0**3
548
+ filtered_bs_search_table = [s for s in bs_search_table if s["dtype"] == dtype]
549
+ for settings in sorted(
550
+ filtered_bs_search_table,
551
+ key=lambda k: (k["res"], -k["total_vram"]),
552
+ ):
553
+ if input_res <= settings["res"] and total_vram >= settings["total_vram"]:
554
+ bs = settings["bs"]
555
+ if bs > ensemble_size:
556
+ bs = ensemble_size
557
+ elif bs > math.ceil(ensemble_size / 2) and bs < ensemble_size:
558
+ bs = math.ceil(ensemble_size / 2)
559
+ return bs
560
+
561
+ return 1
562
+
563
+ @staticmethod
564
+ def ensemble_depths(
565
+ input_images: torch.Tensor,
566
+ regularizer_strength: float = 0.02,
567
+ max_iter: int = 2,
568
+ tol: float = 1e-3,
569
+ reduction: str = "median",
570
+ max_res: int = None,
571
+ ):
572
+ """
573
+ To ensemble multiple affine-invariant depth images (up to scale and shift),
574
+ by aligning estimating the scale and shift
575
+ """
576
+
577
+ def inter_distances(tensors: torch.Tensor):
578
+ """
579
+ To calculate the distance between each two depth maps.
580
+ """
581
+ distances = []
582
+ for i, j in torch.combinations(torch.arange(tensors.shape[0])):
583
+ arr1 = tensors[i : i + 1]
584
+ arr2 = tensors[j : j + 1]
585
+ distances.append(arr1 - arr2)
586
+ dist = torch.concatenate(distances, dim=0)
587
+ return dist
588
+
589
+ device = input_images.device
590
+ dtype = input_images.dtype
591
+ np_dtype = np.float32
592
+
593
+ original_input = input_images.clone()
594
+ n_img = input_images.shape[0]
595
+ ori_shape = input_images.shape
596
+
597
+ if max_res is not None:
598
+ scale_factor = torch.min(max_res / torch.tensor(ori_shape[-2:]))
599
+ if scale_factor < 1:
600
+ downscaler = torch.nn.Upsample(scale_factor=scale_factor, mode="nearest")
601
+ input_images = downscaler(torch.from_numpy(input_images)).numpy()
602
+
603
+ # init guess
604
+ _min = np.min(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1)
605
+ _max = np.max(input_images.reshape((n_img, -1)).cpu().numpy(), axis=1)
606
+ s_init = 1.0 / (_max - _min).reshape((-1, 1, 1))
607
+ t_init = (-1 * s_init.flatten() * _min.flatten()).reshape((-1, 1, 1))
608
+ x = np.concatenate([s_init, t_init]).reshape(-1).astype(np_dtype)
609
+
610
+ input_images = input_images.to(device)
611
+
612
+ # objective function
613
+ def closure(x):
614
+ l = len(x)
615
+ s = x[: int(l / 2)]
616
+ t = x[int(l / 2) :]
617
+ s = torch.from_numpy(s).to(dtype=dtype).to(device)
618
+ t = torch.from_numpy(t).to(dtype=dtype).to(device)
619
+
620
+ transformed_arrays = input_images * s.view((-1, 1, 1)) + t.view((-1, 1, 1))
621
+ dists = inter_distances(transformed_arrays)
622
+ sqrt_dist = torch.sqrt(torch.mean(dists**2))
623
+
624
+ if "mean" == reduction:
625
+ pred = torch.mean(transformed_arrays, dim=0)
626
+ elif "median" == reduction:
627
+ pred = torch.median(transformed_arrays, dim=0).values
628
+ else:
629
+ raise ValueError
630
+
631
+ near_err = torch.sqrt((0 - torch.min(pred)) ** 2)
632
+ far_err = torch.sqrt((1 - torch.max(pred)) ** 2)
633
+
634
+ err = sqrt_dist + (near_err + far_err) * regularizer_strength
635
+ err = err.detach().cpu().numpy().astype(np_dtype)
636
+ return err
637
+
638
+ res = minimize(
639
+ closure,
640
+ x,
641
+ method="BFGS",
642
+ tol=tol,
643
+ options={"maxiter": max_iter, "disp": False},
644
+ )
645
+ x = res.x
646
+ l = len(x)
647
+ s = x[: int(l / 2)]
648
+ t = x[int(l / 2) :]
649
+
650
+ # Prediction
651
+ s = torch.from_numpy(s).to(dtype=dtype).to(device)
652
+ t = torch.from_numpy(t).to(dtype=dtype).to(device)
653
+ transformed_arrays = original_input * s.view(-1, 1, 1) + t.view(-1, 1, 1)
654
+ if "mean" == reduction:
655
+ aligned_images = torch.mean(transformed_arrays, dim=0)
656
+ std = torch.std(transformed_arrays, dim=0)
657
+ uncertainty = std
658
+ elif "median" == reduction:
659
+ aligned_images = torch.median(transformed_arrays, dim=0).values
660
+ # MAD (median absolute deviation) as uncertainty indicator
661
+ abs_dev = torch.abs(transformed_arrays - aligned_images)
662
+ mad = torch.median(abs_dev, dim=0).values
663
+ uncertainty = mad
664
+ else:
665
+ raise ValueError(f"Unknown reduction method: {reduction}")
666
+
667
+ # Scale and shift to [0, 1]
668
+ _min = torch.min(aligned_images)
669
+ _max = torch.max(aligned_images)
670
+ aligned_images = (aligned_images - _min) / (_max - _min)
671
+ uncertainty /= _max - _min
672
+
673
+ return aligned_images, uncertainty
v0.32.0/masked_stable_diffusion_img2img.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Union
2
+
3
+ import numpy as np
4
+ import PIL.Image
5
+ import torch
6
+
7
+ from diffusers import StableDiffusionImg2ImgPipeline
8
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
9
+
10
+
11
+ class MaskedStableDiffusionImg2ImgPipeline(StableDiffusionImg2ImgPipeline):
12
+ debug_save = False
13
+
14
+ @torch.no_grad()
15
+ def __call__(
16
+ self,
17
+ prompt: Union[str, List[str]] = None,
18
+ image: Union[
19
+ torch.Tensor,
20
+ PIL.Image.Image,
21
+ np.ndarray,
22
+ List[torch.Tensor],
23
+ List[PIL.Image.Image],
24
+ List[np.ndarray],
25
+ ] = None,
26
+ strength: float = 0.8,
27
+ num_inference_steps: Optional[int] = 50,
28
+ guidance_scale: Optional[float] = 7.5,
29
+ negative_prompt: Optional[Union[str, List[str]]] = None,
30
+ num_images_per_prompt: Optional[int] = 1,
31
+ eta: Optional[float] = 0.0,
32
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
33
+ prompt_embeds: Optional[torch.Tensor] = None,
34
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
35
+ output_type: Optional[str] = "pil",
36
+ return_dict: bool = True,
37
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
38
+ callback_steps: int = 1,
39
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
40
+ mask: Union[
41
+ torch.Tensor,
42
+ PIL.Image.Image,
43
+ np.ndarray,
44
+ List[torch.Tensor],
45
+ List[PIL.Image.Image],
46
+ List[np.ndarray],
47
+ ] = None,
48
+ ):
49
+ r"""
50
+ The call function to the pipeline for generation.
51
+
52
+ Args:
53
+ prompt (`str` or `List[str]`, *optional*):
54
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
55
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
56
+ `Image` or tensor representing an image batch to be used as the starting point. Can also accept image
57
+ latents as `image`, but if passing latents directly it is not encoded again.
58
+ strength (`float`, *optional*, defaults to 0.8):
59
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
60
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
61
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
62
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
63
+ essentially ignores `image`.
64
+ num_inference_steps (`int`, *optional*, defaults to 50):
65
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
66
+ expense of slower inference. This parameter is modulated by `strength`.
67
+ guidance_scale (`float`, *optional*, defaults to 7.5):
68
+ A higher guidance scale value encourages the model to generate images closely linked to the text
69
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
70
+ negative_prompt (`str` or `List[str]`, *optional*):
71
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
72
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
73
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
74
+ The number of images to generate per prompt.
75
+ eta (`float`, *optional*, defaults to 0.0):
76
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
77
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
78
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
79
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
80
+ generation deterministic.
81
+ prompt_embeds (`torch.Tensor`, *optional*):
82
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
83
+ provided, text embeddings are generated from the `prompt` input argument.
84
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
85
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
86
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
87
+ output_type (`str`, *optional*, defaults to `"pil"`):
88
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
89
+ return_dict (`bool`, *optional*, defaults to `True`):
90
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
91
+ plain tuple.
92
+ callback (`Callable`, *optional*):
93
+ A function that calls every `callback_steps` steps during inference. The function is called with the
94
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
95
+ callback_steps (`int`, *optional*, defaults to 1):
96
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
97
+ every step.
98
+ cross_attention_kwargs (`dict`, *optional*):
99
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
100
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
101
+ mask (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
102
+ A mask with non-zero elements for the area to be inpainted. If not specified, no mask is applied.
103
+ Examples:
104
+
105
+ Returns:
106
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
107
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
108
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
109
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
110
+ "not-safe-for-work" (nsfw) content.
111
+ """
112
+ # code adapted from parent class StableDiffusionImg2ImgPipeline
113
+
114
+ # 0. Check inputs. Raise error if not correct
115
+ self.check_inputs(prompt, strength, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
116
+
117
+ # 1. Define call parameters
118
+ if prompt is not None and isinstance(prompt, str):
119
+ batch_size = 1
120
+ elif prompt is not None and isinstance(prompt, list):
121
+ batch_size = len(prompt)
122
+ else:
123
+ batch_size = prompt_embeds.shape[0]
124
+ device = self._execution_device
125
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
126
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
127
+ # corresponds to doing no classifier free guidance.
128
+ do_classifier_free_guidance = guidance_scale > 1.0
129
+
130
+ # 2. Encode input prompt
131
+ text_encoder_lora_scale = (
132
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
133
+ )
134
+ prompt_embeds = self._encode_prompt(
135
+ prompt,
136
+ device,
137
+ num_images_per_prompt,
138
+ do_classifier_free_guidance,
139
+ negative_prompt,
140
+ prompt_embeds=prompt_embeds,
141
+ negative_prompt_embeds=negative_prompt_embeds,
142
+ lora_scale=text_encoder_lora_scale,
143
+ )
144
+
145
+ # 3. Preprocess image
146
+ image = self.image_processor.preprocess(image)
147
+
148
+ # 4. set timesteps
149
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
150
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
151
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
152
+
153
+ # 5. Prepare latent variables
154
+ # it is sampled from the latent distribution of the VAE
155
+ latents = self.prepare_latents(
156
+ image, latent_timestep, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
157
+ )
158
+
159
+ # mean of the latent distribution
160
+ init_latents = [
161
+ self.vae.encode(image.to(device=device, dtype=prompt_embeds.dtype)[i : i + 1]).latent_dist.mean
162
+ for i in range(batch_size)
163
+ ]
164
+ init_latents = torch.cat(init_latents, dim=0)
165
+
166
+ # 6. create latent mask
167
+ latent_mask = self._make_latent_mask(latents, mask)
168
+
169
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
170
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
171
+
172
+ # 8. Denoising loop
173
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
174
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
175
+ for i, t in enumerate(timesteps):
176
+ # expand the latents if we are doing classifier free guidance
177
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
178
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
179
+
180
+ # predict the noise residual
181
+ noise_pred = self.unet(
182
+ latent_model_input,
183
+ t,
184
+ encoder_hidden_states=prompt_embeds,
185
+ cross_attention_kwargs=cross_attention_kwargs,
186
+ return_dict=False,
187
+ )[0]
188
+
189
+ # perform guidance
190
+ if do_classifier_free_guidance:
191
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
192
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
193
+
194
+ if latent_mask is not None:
195
+ latents = torch.lerp(init_latents * self.vae.config.scaling_factor, latents, latent_mask)
196
+ noise_pred = torch.lerp(torch.zeros_like(noise_pred), noise_pred, latent_mask)
197
+
198
+ # compute the previous noisy sample x_t -> x_t-1
199
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
200
+
201
+ # call the callback, if provided
202
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
203
+ progress_bar.update()
204
+ if callback is not None and i % callback_steps == 0:
205
+ step_idx = i // getattr(self.scheduler, "order", 1)
206
+ callback(step_idx, t, latents)
207
+
208
+ if not output_type == "latent":
209
+ scaled = latents / self.vae.config.scaling_factor
210
+ if latent_mask is not None:
211
+ # scaled = latents / self.vae.config.scaling_factor * latent_mask + init_latents * (1 - latent_mask)
212
+ scaled = torch.lerp(init_latents, scaled, latent_mask)
213
+ image = self.vae.decode(scaled, return_dict=False)[0]
214
+ if self.debug_save:
215
+ image_gen = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
216
+ image_gen = self.image_processor.postprocess(image_gen, output_type=output_type, do_denormalize=[True])
217
+ image_gen[0].save("from_latent.png")
218
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
219
+ else:
220
+ image = latents
221
+ has_nsfw_concept = None
222
+
223
+ if has_nsfw_concept is None:
224
+ do_denormalize = [True] * image.shape[0]
225
+ else:
226
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
227
+
228
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
229
+
230
+ # Offload last model to CPU
231
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
232
+ self.final_offload_hook.offload()
233
+
234
+ if not return_dict:
235
+ return (image, has_nsfw_concept)
236
+
237
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
238
+
239
+ def _make_latent_mask(self, latents, mask):
240
+ if mask is not None:
241
+ latent_mask = []
242
+ if not isinstance(mask, list):
243
+ tmp_mask = [mask]
244
+ else:
245
+ tmp_mask = mask
246
+ _, l_channels, l_height, l_width = latents.shape
247
+ for m in tmp_mask:
248
+ if not isinstance(m, PIL.Image.Image):
249
+ if len(m.shape) == 2:
250
+ m = m[..., np.newaxis]
251
+ if m.max() > 1:
252
+ m = m / 255.0
253
+ m = self.image_processor.numpy_to_pil(m)[0]
254
+ if m.mode != "L":
255
+ m = m.convert("L")
256
+ resized = self.image_processor.resize(m, l_height, l_width)
257
+ if self.debug_save:
258
+ resized.save("latent_mask.png")
259
+ latent_mask.append(np.repeat(np.array(resized)[np.newaxis, :, :], l_channels, axis=0))
260
+ latent_mask = torch.as_tensor(np.stack(latent_mask)).to(latents)
261
+ latent_mask = latent_mask / latent_mask.max()
262
+ return latent_mask
v0.32.0/masked_stable_diffusion_xl_img2img.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
2
+
3
+ import numpy as np
4
+ import torch
5
+ from PIL import Image, ImageFilter
6
+
7
+ from diffusers.image_processor import PipelineImageInput
8
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
9
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img import (
10
+ StableDiffusionXLImg2ImgPipeline,
11
+ rescale_noise_cfg,
12
+ retrieve_latents,
13
+ retrieve_timesteps,
14
+ )
15
+ from diffusers.utils import (
16
+ deprecate,
17
+ is_torch_xla_available,
18
+ logging,
19
+ )
20
+ from diffusers.utils.torch_utils import randn_tensor
21
+
22
+
23
+ if is_torch_xla_available():
24
+ import torch_xla.core.xla_model as xm
25
+
26
+ XLA_AVAILABLE = True
27
+ else:
28
+ XLA_AVAILABLE = False
29
+
30
+
31
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
+
33
+
34
+ class MaskedStableDiffusionXLImg2ImgPipeline(StableDiffusionXLImg2ImgPipeline):
35
+ debug_save = 0
36
+
37
+ @torch.no_grad()
38
+ def __call__(
39
+ self,
40
+ prompt: Union[str, List[str]] = None,
41
+ prompt_2: Optional[Union[str, List[str]]] = None,
42
+ image: PipelineImageInput = None,
43
+ original_image: PipelineImageInput = None,
44
+ strength: float = 0.3,
45
+ num_inference_steps: Optional[int] = 50,
46
+ timesteps: List[int] = None,
47
+ denoising_start: Optional[float] = None,
48
+ denoising_end: Optional[float] = None,
49
+ guidance_scale: Optional[float] = 5.0,
50
+ negative_prompt: Optional[Union[str, List[str]]] = None,
51
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
52
+ num_images_per_prompt: Optional[int] = 1,
53
+ eta: Optional[float] = 0.0,
54
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
55
+ latents: Optional[torch.FloatTensor] = None,
56
+ prompt_embeds: Optional[torch.FloatTensor] = None,
57
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
58
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
59
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
60
+ ip_adapter_image: Optional[PipelineImageInput] = None,
61
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
62
+ output_type: Optional[str] = "pil",
63
+ return_dict: bool = True,
64
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
65
+ guidance_rescale: float = 0.0,
66
+ original_size: Tuple[int, int] = None,
67
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
68
+ target_size: Tuple[int, int] = None,
69
+ negative_original_size: Optional[Tuple[int, int]] = None,
70
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
71
+ negative_target_size: Optional[Tuple[int, int]] = None,
72
+ aesthetic_score: float = 6.0,
73
+ negative_aesthetic_score: float = 2.5,
74
+ clip_skip: Optional[int] = None,
75
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
76
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
77
+ mask: Union[
78
+ torch.FloatTensor,
79
+ Image.Image,
80
+ np.ndarray,
81
+ List[torch.FloatTensor],
82
+ List[Image.Image],
83
+ List[np.ndarray],
84
+ ] = None,
85
+ blur=24,
86
+ blur_compose=4,
87
+ sample_mode="sample",
88
+ **kwargs,
89
+ ):
90
+ r"""
91
+ The call function to the pipeline for generation.
92
+
93
+ Args:
94
+ prompt (`str` or `List[str]`, *optional*):
95
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
96
+ image (`PipelineImageInput`):
97
+ `Image` or tensor representing an image batch to be used as the starting point. This image might have mask painted on it.
98
+ original_image (`PipelineImageInput`, *optional*):
99
+ `Image` or tensor representing an image batch to be used for blending with the result.
100
+ strength (`float`, *optional*, defaults to 0.8):
101
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
102
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
103
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
104
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
105
+ essentially ignores `image`.
106
+ num_inference_steps (`int`, *optional*, defaults to 50):
107
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
108
+ expense of slower inference. This parameter is modulated by `strength`.
109
+ guidance_scale (`float`, *optional*, defaults to 7.5):
110
+ A higher guidance scale value encourages the model to generate images closely linked to the text
111
+ ,`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
112
+ negative_prompt (`str` or `List[str]`, *optional*):
113
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
114
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
115
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
116
+ The number of images to generate per prompt.
117
+ eta (`float`, *optional*, defaults to 0.0):
118
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
119
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
120
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
121
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
122
+ generation deterministic.
123
+ prompt_embeds (`torch.FloatTensor`, *optional*):
124
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
125
+ provided, text embeddings are generated from the `prompt` input argument.
126
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
127
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
128
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
129
+ output_type (`str`, *optional*, defaults to `"pil"`):
130
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
131
+ return_dict (`bool`, *optional*, defaults to `True`):
132
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
133
+ plain tuple.
134
+ callback (`Callable`, *optional*):
135
+ A function that calls every `callback_steps` steps during inference. The function is called with the
136
+ following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
137
+ callback_steps (`int`, *optional*, defaults to 1):
138
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
139
+ every step.
140
+ cross_attention_kwargs (`dict`, *optional*):
141
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
142
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
143
+ blur (`int`, *optional*):
144
+ blur to apply to mask
145
+ blur_compose (`int`, *optional*):
146
+ blur to apply for composition of original a
147
+ mask (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`, *optional*):
148
+ A mask with non-zero elements for the area to be inpainted. If not specified, no mask is applied.
149
+ sample_mode (`str`, *optional*):
150
+ control latents initialisation for the inpaint area, can be one of sample, argmax, random
151
+ Examples:
152
+
153
+ Returns:
154
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
155
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
156
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
157
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
158
+ "not-safe-for-work" (nsfw) content.
159
+ """
160
+ # code adapted from parent class StableDiffusionXLImg2ImgPipeline
161
+ callback = kwargs.pop("callback", None)
162
+ callback_steps = kwargs.pop("callback_steps", None)
163
+
164
+ if callback is not None:
165
+ deprecate(
166
+ "callback",
167
+ "1.0.0",
168
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
169
+ )
170
+ if callback_steps is not None:
171
+ deprecate(
172
+ "callback_steps",
173
+ "1.0.0",
174
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
175
+ )
176
+
177
+ # 0. Check inputs. Raise error if not correct
178
+ self.check_inputs(
179
+ prompt,
180
+ prompt_2,
181
+ strength,
182
+ num_inference_steps,
183
+ callback_steps,
184
+ negative_prompt,
185
+ negative_prompt_2,
186
+ prompt_embeds,
187
+ negative_prompt_embeds,
188
+ ip_adapter_image,
189
+ ip_adapter_image_embeds,
190
+ callback_on_step_end_tensor_inputs,
191
+ )
192
+
193
+ self._guidance_scale = guidance_scale
194
+ self._guidance_rescale = guidance_rescale
195
+ self._clip_skip = clip_skip
196
+ self._cross_attention_kwargs = cross_attention_kwargs
197
+ self._denoising_end = denoising_end
198
+ self._denoising_start = denoising_start
199
+ self._interrupt = False
200
+
201
+ # 1. Define call parameters
202
+ # mask is computed from difference between image and original_image
203
+ if image is not None:
204
+ neq = np.any(np.array(original_image) != np.array(image), axis=-1)
205
+ mask = neq.astype(np.uint8) * 255
206
+ else:
207
+ assert mask is not None
208
+
209
+ if not isinstance(mask, Image.Image):
210
+ pil_mask = Image.fromarray(mask)
211
+ if pil_mask.mode != "L":
212
+ pil_mask = pil_mask.convert("L")
213
+ mask_blur = self.blur_mask(pil_mask, blur)
214
+ mask_compose = self.blur_mask(pil_mask, blur_compose)
215
+ if original_image is None:
216
+ original_image = image
217
+ if prompt is not None and isinstance(prompt, str):
218
+ batch_size = 1
219
+ elif prompt is not None and isinstance(prompt, list):
220
+ batch_size = len(prompt)
221
+ else:
222
+ batch_size = prompt_embeds.shape[0]
223
+
224
+ device = self._execution_device
225
+
226
+ # 2. Encode input prompt
227
+ text_encoder_lora_scale = (
228
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
229
+ )
230
+ (
231
+ prompt_embeds,
232
+ negative_prompt_embeds,
233
+ pooled_prompt_embeds,
234
+ negative_pooled_prompt_embeds,
235
+ ) = self.encode_prompt(
236
+ prompt=prompt,
237
+ prompt_2=prompt_2,
238
+ device=device,
239
+ num_images_per_prompt=num_images_per_prompt,
240
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
241
+ negative_prompt=negative_prompt,
242
+ negative_prompt_2=negative_prompt_2,
243
+ prompt_embeds=prompt_embeds,
244
+ negative_prompt_embeds=negative_prompt_embeds,
245
+ pooled_prompt_embeds=pooled_prompt_embeds,
246
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
247
+ lora_scale=text_encoder_lora_scale,
248
+ clip_skip=self.clip_skip,
249
+ )
250
+
251
+ # 3. Preprocess image
252
+ input_image = image if image is not None else original_image
253
+ image = self.image_processor.preprocess(input_image)
254
+ original_image = self.image_processor.preprocess(original_image)
255
+
256
+ # 4. set timesteps
257
+ def denoising_value_valid(dnv):
258
+ return isinstance(dnv, float) and 0 < dnv < 1
259
+
260
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
261
+ timesteps, num_inference_steps = self.get_timesteps(
262
+ num_inference_steps,
263
+ strength,
264
+ device,
265
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
266
+ )
267
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
268
+
269
+ add_noise = True if self.denoising_start is None else False
270
+
271
+ # 5. Prepare latent variables
272
+ # It is sampled from the latent distribution of the VAE
273
+ # that's what we repaint
274
+ latents = self.prepare_latents(
275
+ image,
276
+ latent_timestep,
277
+ batch_size,
278
+ num_images_per_prompt,
279
+ prompt_embeds.dtype,
280
+ device,
281
+ generator,
282
+ add_noise,
283
+ sample_mode=sample_mode,
284
+ )
285
+
286
+ # mean of the latent distribution
287
+ # it is multiplied by self.vae.config.scaling_factor
288
+ non_paint_latents = self.prepare_latents(
289
+ original_image,
290
+ latent_timestep,
291
+ batch_size,
292
+ num_images_per_prompt,
293
+ prompt_embeds.dtype,
294
+ device,
295
+ generator,
296
+ add_noise=False,
297
+ sample_mode="argmax",
298
+ )
299
+
300
+ if self.debug_save:
301
+ init_img_from_latents = self.latents_to_img(non_paint_latents)
302
+ init_img_from_latents[0].save("non_paint_latents.png")
303
+ # 6. create latent mask
304
+ latent_mask = self._make_latent_mask(latents, mask)
305
+
306
+ # 7. Prepare extra step kwargs.
307
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
308
+
309
+ height, width = latents.shape[-2:]
310
+ height = height * self.vae_scale_factor
311
+ width = width * self.vae_scale_factor
312
+
313
+ original_size = original_size or (height, width)
314
+ target_size = target_size or (height, width)
315
+
316
+ # 8. Prepare added time ids & embeddings
317
+ if negative_original_size is None:
318
+ negative_original_size = original_size
319
+ if negative_target_size is None:
320
+ negative_target_size = target_size
321
+
322
+ add_text_embeds = pooled_prompt_embeds
323
+ if self.text_encoder_2 is None:
324
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
325
+ else:
326
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
327
+
328
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
329
+ original_size,
330
+ crops_coords_top_left,
331
+ target_size,
332
+ aesthetic_score,
333
+ negative_aesthetic_score,
334
+ negative_original_size,
335
+ negative_crops_coords_top_left,
336
+ negative_target_size,
337
+ dtype=prompt_embeds.dtype,
338
+ text_encoder_projection_dim=text_encoder_projection_dim,
339
+ )
340
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
341
+
342
+ if self.do_classifier_free_guidance:
343
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
344
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
345
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
346
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
347
+
348
+ prompt_embeds = prompt_embeds.to(device)
349
+ add_text_embeds = add_text_embeds.to(device)
350
+ add_time_ids = add_time_ids.to(device)
351
+
352
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
353
+ image_embeds = self.prepare_ip_adapter_image_embeds(
354
+ ip_adapter_image,
355
+ ip_adapter_image_embeds,
356
+ device,
357
+ batch_size * num_images_per_prompt,
358
+ self.do_classifier_free_guidance,
359
+ )
360
+
361
+ # 10. Denoising loop
362
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
363
+
364
+ # 10.1 Apply denoising_end
365
+ if (
366
+ self.denoising_end is not None
367
+ and self.denoising_start is not None
368
+ and denoising_value_valid(self.denoising_end)
369
+ and denoising_value_valid(self.denoising_start)
370
+ and self.denoising_start >= self.denoising_end
371
+ ):
372
+ raise ValueError(
373
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
374
+ + f" {self.denoising_end} when using type float."
375
+ )
376
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
377
+ discrete_timestep_cutoff = int(
378
+ round(
379
+ self.scheduler.config.num_train_timesteps
380
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
381
+ )
382
+ )
383
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
384
+ timesteps = timesteps[:num_inference_steps]
385
+
386
+ # 10.2 Optionally get Guidance Scale Embedding
387
+ timestep_cond = None
388
+ if self.unet.config.time_cond_proj_dim is not None:
389
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
390
+ timestep_cond = self.get_guidance_scale_embedding(
391
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
392
+ ).to(device=device, dtype=latents.dtype)
393
+
394
+ self._num_timesteps = len(timesteps)
395
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
396
+ for i, t in enumerate(timesteps):
397
+ if self.interrupt:
398
+ continue
399
+
400
+ shape = non_paint_latents.shape
401
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=latents.dtype)
402
+ # noisy latent code of input image at current step
403
+ orig_latents_t = non_paint_latents
404
+ orig_latents_t = self.scheduler.add_noise(non_paint_latents, noise, t.unsqueeze(0))
405
+
406
+ # orig_latents_t (1 - latent_mask) + latents * latent_mask
407
+ latents = torch.lerp(orig_latents_t, latents, latent_mask)
408
+
409
+ if self.debug_save:
410
+ img1 = self.latents_to_img(latents)
411
+ t_str = str(t.int().item())
412
+ for i in range(3 - len(t_str)):
413
+ t_str = "0" + t_str
414
+ img1[0].save(f"step{t_str}.png")
415
+
416
+ # expand the latents if we are doing classifier free guidance
417
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
418
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
419
+
420
+ # predict the noise residual
421
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
422
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
423
+ added_cond_kwargs["image_embeds"] = image_embeds
424
+
425
+ noise_pred = self.unet(
426
+ latent_model_input,
427
+ t,
428
+ encoder_hidden_states=prompt_embeds,
429
+ timestep_cond=timestep_cond,
430
+ cross_attention_kwargs=self.cross_attention_kwargs,
431
+ added_cond_kwargs=added_cond_kwargs,
432
+ return_dict=False,
433
+ )[0]
434
+
435
+ # perform guidance
436
+ if self.do_classifier_free_guidance:
437
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
438
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
439
+
440
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
441
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
442
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
443
+
444
+ # compute the previous noisy sample x_t -> x_t-1
445
+ latents_dtype = latents.dtype
446
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
447
+
448
+ if latents.dtype != latents_dtype:
449
+ if torch.backends.mps.is_available():
450
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
451
+ latents = latents.to(latents_dtype)
452
+
453
+ if callback_on_step_end is not None:
454
+ callback_kwargs = {}
455
+ for k in callback_on_step_end_tensor_inputs:
456
+ callback_kwargs[k] = locals()[k]
457
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
458
+
459
+ latents = callback_outputs.pop("latents", latents)
460
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
461
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
462
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
463
+ negative_pooled_prompt_embeds = callback_outputs.pop(
464
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
465
+ )
466
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
467
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
468
+
469
+ # call the callback, if provided
470
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
471
+ progress_bar.update()
472
+ if callback is not None and i % callback_steps == 0:
473
+ step_idx = i // getattr(self.scheduler, "order", 1)
474
+ callback(step_idx, t, latents)
475
+
476
+ if XLA_AVAILABLE:
477
+ xm.mark_step()
478
+
479
+ if not output_type == "latent":
480
+ # make sure the VAE is in float32 mode, as it overflows in float16
481
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
482
+
483
+ if needs_upcasting:
484
+ self.upcast_vae()
485
+ elif latents.dtype != self.vae.dtype:
486
+ if torch.backends.mps.is_available():
487
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
488
+ self.vae = self.vae.to(latents.dtype)
489
+
490
+ if self.debug_save:
491
+ image_gen = self.latents_to_img(latents)
492
+ image_gen[0].save("from_latent.png")
493
+
494
+ if latent_mask is not None:
495
+ # interpolate with latent mask
496
+ latents = torch.lerp(non_paint_latents, latents, latent_mask)
497
+
498
+ latents = self.denormalize(latents)
499
+ image = self.vae.decode(latents, return_dict=False)[0]
500
+ m = mask_compose.permute(2, 0, 1).unsqueeze(0).to(image)
501
+ img_compose = m * image + (1 - m) * original_image.to(image)
502
+ image = img_compose
503
+ # cast back to fp16 if needed
504
+ if needs_upcasting:
505
+ self.vae.to(dtype=torch.float16)
506
+ else:
507
+ image = latents
508
+
509
+ # apply watermark if available
510
+ if self.watermark is not None:
511
+ image = self.watermark.apply_watermark(image)
512
+
513
+ image = self.image_processor.postprocess(image, output_type=output_type)
514
+
515
+ # Offload all models
516
+ self.maybe_free_model_hooks()
517
+
518
+ if not return_dict:
519
+ return (image,)
520
+
521
+ return StableDiffusionXLPipelineOutput(images=image)
522
+
523
+ def _make_latent_mask(self, latents, mask):
524
+ if mask is not None:
525
+ latent_mask = []
526
+ if not isinstance(mask, list):
527
+ tmp_mask = [mask]
528
+ else:
529
+ tmp_mask = mask
530
+ _, l_channels, l_height, l_width = latents.shape
531
+ for m in tmp_mask:
532
+ if not isinstance(m, Image.Image):
533
+ if len(m.shape) == 2:
534
+ m = m[..., np.newaxis]
535
+ if m.max() > 1:
536
+ m = m / 255.0
537
+ m = self.image_processor.numpy_to_pil(m)[0]
538
+ if m.mode != "L":
539
+ m = m.convert("L")
540
+ resized = self.image_processor.resize(m, l_height, l_width)
541
+ if self.debug_save:
542
+ resized.save("latent_mask.png")
543
+ latent_mask.append(np.repeat(np.array(resized)[np.newaxis, :, :], l_channels, axis=0))
544
+ latent_mask = torch.as_tensor(np.stack(latent_mask)).to(latents)
545
+ latent_mask = latent_mask / max(latent_mask.max(), 1)
546
+ return latent_mask
547
+
548
+ def prepare_latents(
549
+ self,
550
+ image,
551
+ timestep,
552
+ batch_size,
553
+ num_images_per_prompt,
554
+ dtype,
555
+ device,
556
+ generator=None,
557
+ add_noise=True,
558
+ sample_mode: str = "sample",
559
+ ):
560
+ if not isinstance(image, (torch.Tensor, Image.Image, list)):
561
+ raise ValueError(
562
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
563
+ )
564
+
565
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
566
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
567
+ self.text_encoder_2.to("cpu")
568
+ torch.cuda.empty_cache()
569
+
570
+ image = image.to(device=device, dtype=dtype)
571
+
572
+ batch_size = batch_size * num_images_per_prompt
573
+
574
+ if image.shape[1] == 4:
575
+ init_latents = image
576
+ elif sample_mode == "random":
577
+ height, width = image.shape[-2:]
578
+ num_channels_latents = self.unet.config.in_channels
579
+ latents = self.random_latents(
580
+ batch_size,
581
+ num_channels_latents,
582
+ height,
583
+ width,
584
+ dtype,
585
+ device,
586
+ generator,
587
+ )
588
+ return self.vae.config.scaling_factor * latents
589
+ else:
590
+ # make sure the VAE is in float32 mode, as it overflows in float16
591
+ if self.vae.config.force_upcast:
592
+ image = image.float()
593
+ self.vae.to(dtype=torch.float32)
594
+
595
+ if isinstance(generator, list) and len(generator) != batch_size:
596
+ raise ValueError(
597
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
598
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
599
+ )
600
+
601
+ elif isinstance(generator, list):
602
+ init_latents = [
603
+ retrieve_latents(
604
+ self.vae.encode(image[i : i + 1]), generator=generator[i], sample_mode=sample_mode
605
+ )
606
+ for i in range(batch_size)
607
+ ]
608
+ init_latents = torch.cat(init_latents, dim=0)
609
+ else:
610
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator, sample_mode=sample_mode)
611
+
612
+ if self.vae.config.force_upcast:
613
+ self.vae.to(dtype)
614
+
615
+ init_latents = init_latents.to(dtype)
616
+ init_latents = self.vae.config.scaling_factor * init_latents
617
+
618
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
619
+ # expand init_latents for batch_size
620
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
621
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
622
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
623
+ raise ValueError(
624
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
625
+ )
626
+ else:
627
+ init_latents = torch.cat([init_latents], dim=0)
628
+
629
+ if add_noise:
630
+ shape = init_latents.shape
631
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
632
+ # get latents
633
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
634
+
635
+ latents = init_latents
636
+
637
+ return latents
638
+
639
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
640
+ def random_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
641
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
642
+ if isinstance(generator, list) and len(generator) != batch_size:
643
+ raise ValueError(
644
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
645
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
646
+ )
647
+
648
+ if latents is None:
649
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
650
+ else:
651
+ latents = latents.to(device)
652
+
653
+ # scale the initial noise by the standard deviation required by the scheduler
654
+ latents = latents * self.scheduler.init_noise_sigma
655
+ return latents
656
+
657
+ def denormalize(self, latents):
658
+ # unscale/denormalize the latents
659
+ # denormalize with the mean and std if available and not None
660
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
661
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
662
+ if has_latents_mean and has_latents_std:
663
+ latents_mean = (
664
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
665
+ )
666
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
667
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
668
+ else:
669
+ latents = latents / self.vae.config.scaling_factor
670
+
671
+ return latents
672
+
673
+ def latents_to_img(self, latents):
674
+ l1 = self.denormalize(latents)
675
+ img1 = self.vae.decode(l1, return_dict=False)[0]
676
+ img1 = self.image_processor.postprocess(img1, output_type="pil", do_denormalize=[True])
677
+ return img1
678
+
679
+ def blur_mask(self, pil_mask, blur):
680
+ mask_blur = pil_mask.filter(ImageFilter.GaussianBlur(radius=blur))
681
+ mask_blur = np.array(mask_blur)
682
+ return torch.from_numpy(np.tile(mask_blur / mask_blur.max(), (3, 1, 1)).transpose(1, 2, 0))
v0.32.0/matryoshka.py ADDED
The diff for this file is too large to render. See raw diff
 
v0.32.0/mixture_canvas.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from copy import deepcopy
3
+ from dataclasses import asdict, dataclass
4
+ from enum import Enum
5
+ from typing import List, Optional, Union
6
+
7
+ import numpy as np
8
+ import torch
9
+ from numpy import exp, pi, sqrt
10
+ from torchvision.transforms.functional import resize
11
+ from tqdm.auto import tqdm
12
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
13
+
14
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
16
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
17
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
18
+
19
+
20
+ def preprocess_image(image):
21
+ from PIL import Image
22
+
23
+ """Preprocess an input image
24
+
25
+ Same as
26
+ https://github.com/huggingface/diffusers/blob/1138d63b519e37f0ce04e027b9f4a3261d27c628/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py#L44
27
+ """
28
+ w, h = image.size
29
+ w, h = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32
30
+ image = image.resize((w, h), resample=Image.LANCZOS)
31
+ image = np.array(image).astype(np.float32) / 255.0
32
+ image = image[None].transpose(0, 3, 1, 2)
33
+ image = torch.from_numpy(image)
34
+ return 2.0 * image - 1.0
35
+
36
+
37
+ @dataclass
38
+ class CanvasRegion:
39
+ """Class defining a rectangular region in the canvas"""
40
+
41
+ row_init: int # Region starting row in pixel space (included)
42
+ row_end: int # Region end row in pixel space (not included)
43
+ col_init: int # Region starting column in pixel space (included)
44
+ col_end: int # Region end column in pixel space (not included)
45
+ region_seed: int = None # Seed for random operations in this region
46
+ noise_eps: float = 0.0 # Deviation of a zero-mean gaussian noise to be applied over the latents in this region. Useful for slightly "rerolling" latents
47
+
48
+ def __post_init__(self):
49
+ # Initialize arguments if not specified
50
+ if self.region_seed is None:
51
+ self.region_seed = np.random.randint(9999999999)
52
+ # Check coordinates are non-negative
53
+ for coord in [self.row_init, self.row_end, self.col_init, self.col_end]:
54
+ if coord < 0:
55
+ raise ValueError(
56
+ f"A CanvasRegion must be defined with non-negative indices, found ({self.row_init}, {self.row_end}, {self.col_init}, {self.col_end})"
57
+ )
58
+ # Check coordinates are divisible by 8, else we end up with nasty rounding error when mapping to latent space
59
+ for coord in [self.row_init, self.row_end, self.col_init, self.col_end]:
60
+ if coord // 8 != coord / 8:
61
+ raise ValueError(
62
+ f"A CanvasRegion must be defined with locations divisible by 8, found ({self.row_init}-{self.row_end}, {self.col_init}-{self.col_end})"
63
+ )
64
+ # Check noise eps is non-negative
65
+ if self.noise_eps < 0:
66
+ raise ValueError(f"A CanvasRegion must be defined noises eps non-negative, found {self.noise_eps}")
67
+ # Compute coordinates for this region in latent space
68
+ self.latent_row_init = self.row_init // 8
69
+ self.latent_row_end = self.row_end // 8
70
+ self.latent_col_init = self.col_init // 8
71
+ self.latent_col_end = self.col_end // 8
72
+
73
+ @property
74
+ def width(self):
75
+ return self.col_end - self.col_init
76
+
77
+ @property
78
+ def height(self):
79
+ return self.row_end - self.row_init
80
+
81
+ def get_region_generator(self, device="cpu"):
82
+ """Creates a torch.Generator based on the random seed of this region"""
83
+ # Initialize region generator
84
+ return torch.Generator(device).manual_seed(self.region_seed)
85
+
86
+ @property
87
+ def __dict__(self):
88
+ return asdict(self)
89
+
90
+
91
+ class MaskModes(Enum):
92
+ """Modes in which the influence of diffuser is masked"""
93
+
94
+ CONSTANT = "constant"
95
+ GAUSSIAN = "gaussian"
96
+ QUARTIC = "quartic" # See https://en.wikipedia.org/wiki/Kernel_(statistics)
97
+
98
+
99
+ @dataclass
100
+ class DiffusionRegion(CanvasRegion):
101
+ """Abstract class defining a region where some class of diffusion process is acting"""
102
+
103
+ pass
104
+
105
+
106
+ @dataclass
107
+ class Text2ImageRegion(DiffusionRegion):
108
+ """Class defining a region where a text guided diffusion process is acting"""
109
+
110
+ prompt: str = "" # Text prompt guiding the diffuser in this region
111
+ guidance_scale: float = 7.5 # Guidance scale of the diffuser in this region. If None, randomize
112
+ mask_type: MaskModes = MaskModes.GAUSSIAN.value # Kind of weight mask applied to this region
113
+ mask_weight: float = 1.0 # Global weights multiplier of the mask
114
+ tokenized_prompt = None # Tokenized prompt
115
+ encoded_prompt = None # Encoded prompt
116
+
117
+ def __post_init__(self):
118
+ super().__post_init__()
119
+ # Mask weight cannot be negative
120
+ if self.mask_weight < 0:
121
+ raise ValueError(
122
+ f"A Text2ImageRegion must be defined with non-negative mask weight, found {self.mask_weight}"
123
+ )
124
+ # Mask type must be an actual known mask
125
+ if self.mask_type not in [e.value for e in MaskModes]:
126
+ raise ValueError(
127
+ f"A Text2ImageRegion was defined with mask {self.mask_type}, which is not an accepted mask ({[e.value for e in MaskModes]})"
128
+ )
129
+ # Randomize arguments if given as None
130
+ if self.guidance_scale is None:
131
+ self.guidance_scale = np.random.randint(5, 30)
132
+ # Clean prompt
133
+ self.prompt = re.sub(" +", " ", self.prompt).replace("\n", " ")
134
+
135
+ def tokenize_prompt(self, tokenizer):
136
+ """Tokenizes the prompt for this diffusion region using a given tokenizer"""
137
+ self.tokenized_prompt = tokenizer(
138
+ self.prompt,
139
+ padding="max_length",
140
+ max_length=tokenizer.model_max_length,
141
+ truncation=True,
142
+ return_tensors="pt",
143
+ )
144
+
145
+ def encode_prompt(self, text_encoder, device):
146
+ """Encodes the previously tokenized prompt for this diffusion region using a given encoder"""
147
+ assert self.tokenized_prompt is not None, ValueError(
148
+ "Prompt in diffusion region must be tokenized before encoding"
149
+ )
150
+ self.encoded_prompt = text_encoder(self.tokenized_prompt.input_ids.to(device))[0]
151
+
152
+
153
+ @dataclass
154
+ class Image2ImageRegion(DiffusionRegion):
155
+ """Class defining a region where an image guided diffusion process is acting"""
156
+
157
+ reference_image: torch.Tensor = None
158
+ strength: float = 0.8 # Strength of the image
159
+
160
+ def __post_init__(self):
161
+ super().__post_init__()
162
+ if self.reference_image is None:
163
+ raise ValueError("Must provide a reference image when creating an Image2ImageRegion")
164
+ if self.strength < 0 or self.strength > 1:
165
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {self.strength}")
166
+ # Rescale image to region shape
167
+ self.reference_image = resize(self.reference_image, size=[self.height, self.width])
168
+
169
+ def encode_reference_image(self, encoder, device, generator, cpu_vae=False):
170
+ """Encodes the reference image for this Image2Image region into the latent space"""
171
+ # Place encoder in CPU or not following the parameter cpu_vae
172
+ if cpu_vae:
173
+ # Note here we use mean instead of sample, to avoid moving also generator to CPU, which is troublesome
174
+ self.reference_latents = encoder.cpu().encode(self.reference_image).latent_dist.mean.to(device)
175
+ else:
176
+ self.reference_latents = encoder.encode(self.reference_image.to(device)).latent_dist.sample(
177
+ generator=generator
178
+ )
179
+ self.reference_latents = 0.18215 * self.reference_latents
180
+
181
+ @property
182
+ def __dict__(self):
183
+ # This class requires special casting to dict because of the reference_image tensor. Otherwise it cannot be casted to JSON
184
+
185
+ # Get all basic fields from parent class
186
+ super_fields = {key: getattr(self, key) for key in DiffusionRegion.__dataclass_fields__.keys()}
187
+ # Pack other fields
188
+ return {**super_fields, "reference_image": self.reference_image.cpu().tolist(), "strength": self.strength}
189
+
190
+
191
+ class RerollModes(Enum):
192
+ """Modes in which the reroll regions operate"""
193
+
194
+ RESET = "reset" # Completely reset the random noise in the region
195
+ EPSILON = "epsilon" # Alter slightly the latents in the region
196
+
197
+
198
+ @dataclass
199
+ class RerollRegion(CanvasRegion):
200
+ """Class defining a rectangular canvas region in which initial latent noise will be rerolled"""
201
+
202
+ reroll_mode: RerollModes = RerollModes.RESET.value
203
+
204
+
205
+ @dataclass
206
+ class MaskWeightsBuilder:
207
+ """Auxiliary class to compute a tensor of weights for a given diffusion region"""
208
+
209
+ latent_space_dim: int # Size of the U-net latent space
210
+ nbatch: int = 1 # Batch size in the U-net
211
+
212
+ def compute_mask_weights(self, region: DiffusionRegion) -> torch.tensor:
213
+ """Computes a tensor of weights for a given diffusion region"""
214
+ MASK_BUILDERS = {
215
+ MaskModes.CONSTANT.value: self._constant_weights,
216
+ MaskModes.GAUSSIAN.value: self._gaussian_weights,
217
+ MaskModes.QUARTIC.value: self._quartic_weights,
218
+ }
219
+ return MASK_BUILDERS[region.mask_type](region)
220
+
221
+ def _constant_weights(self, region: DiffusionRegion) -> torch.tensor:
222
+ """Computes a tensor of constant for a given diffusion region"""
223
+ latent_width = region.latent_col_end - region.latent_col_init
224
+ latent_height = region.latent_row_end - region.latent_row_init
225
+ return torch.ones(self.nbatch, self.latent_space_dim, latent_height, latent_width) * region.mask_weight
226
+
227
+ def _gaussian_weights(self, region: DiffusionRegion) -> torch.tensor:
228
+ """Generates a gaussian mask of weights for tile contributions"""
229
+ latent_width = region.latent_col_end - region.latent_col_init
230
+ latent_height = region.latent_row_end - region.latent_row_init
231
+
232
+ var = 0.01
233
+ midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1
234
+ x_probs = [
235
+ exp(-(x - midpoint) * (x - midpoint) / (latent_width * latent_width) / (2 * var)) / sqrt(2 * pi * var)
236
+ for x in range(latent_width)
237
+ ]
238
+ midpoint = (latent_height - 1) / 2
239
+ y_probs = [
240
+ exp(-(y - midpoint) * (y - midpoint) / (latent_height * latent_height) / (2 * var)) / sqrt(2 * pi * var)
241
+ for y in range(latent_height)
242
+ ]
243
+
244
+ weights = np.outer(y_probs, x_probs) * region.mask_weight
245
+ return torch.tile(torch.tensor(weights), (self.nbatch, self.latent_space_dim, 1, 1))
246
+
247
+ def _quartic_weights(self, region: DiffusionRegion) -> torch.tensor:
248
+ """Generates a quartic mask of weights for tile contributions
249
+
250
+ The quartic kernel has bounded support over the diffusion region, and a smooth decay to the region limits.
251
+ """
252
+ quartic_constant = 15.0 / 16.0
253
+
254
+ support = (np.array(range(region.latent_col_init, region.latent_col_end)) - region.latent_col_init) / (
255
+ region.latent_col_end - region.latent_col_init - 1
256
+ ) * 1.99 - (1.99 / 2.0)
257
+ x_probs = quartic_constant * np.square(1 - np.square(support))
258
+ support = (np.array(range(region.latent_row_init, region.latent_row_end)) - region.latent_row_init) / (
259
+ region.latent_row_end - region.latent_row_init - 1
260
+ ) * 1.99 - (1.99 / 2.0)
261
+ y_probs = quartic_constant * np.square(1 - np.square(support))
262
+
263
+ weights = np.outer(y_probs, x_probs) * region.mask_weight
264
+ return torch.tile(torch.tensor(weights), (self.nbatch, self.latent_space_dim, 1, 1))
265
+
266
+
267
+ class StableDiffusionCanvasPipeline(DiffusionPipeline, StableDiffusionMixin):
268
+ """Stable Diffusion pipeline that mixes several diffusers in the same canvas"""
269
+
270
+ def __init__(
271
+ self,
272
+ vae: AutoencoderKL,
273
+ text_encoder: CLIPTextModel,
274
+ tokenizer: CLIPTokenizer,
275
+ unet: UNet2DConditionModel,
276
+ scheduler: Union[DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler],
277
+ safety_checker: StableDiffusionSafetyChecker,
278
+ feature_extractor: CLIPImageProcessor,
279
+ ):
280
+ super().__init__()
281
+ self.register_modules(
282
+ vae=vae,
283
+ text_encoder=text_encoder,
284
+ tokenizer=tokenizer,
285
+ unet=unet,
286
+ scheduler=scheduler,
287
+ safety_checker=safety_checker,
288
+ feature_extractor=feature_extractor,
289
+ )
290
+
291
+ def decode_latents(self, latents, cpu_vae=False):
292
+ """Decodes a given array of latents into pixel space"""
293
+ # scale and decode the image latents with vae
294
+ if cpu_vae:
295
+ lat = deepcopy(latents).cpu()
296
+ vae = deepcopy(self.vae).cpu()
297
+ else:
298
+ lat = latents
299
+ vae = self.vae
300
+
301
+ lat = 1 / 0.18215 * lat
302
+ image = vae.decode(lat).sample
303
+
304
+ image = (image / 2 + 0.5).clamp(0, 1)
305
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
306
+
307
+ return self.numpy_to_pil(image)
308
+
309
+ def get_latest_timestep_img2img(self, num_inference_steps, strength):
310
+ """Finds the latest timesteps where an img2img strength does not impose latents anymore"""
311
+ # get the original timestep using init_timestep
312
+ offset = self.scheduler.config.get("steps_offset", 0)
313
+ init_timestep = int(num_inference_steps * (1 - strength)) + offset
314
+ init_timestep = min(init_timestep, num_inference_steps)
315
+
316
+ t_start = min(max(num_inference_steps - init_timestep + offset, 0), num_inference_steps - 1)
317
+ latest_timestep = self.scheduler.timesteps[t_start]
318
+
319
+ return latest_timestep
320
+
321
+ @torch.no_grad()
322
+ def __call__(
323
+ self,
324
+ canvas_height: int,
325
+ canvas_width: int,
326
+ regions: List[DiffusionRegion],
327
+ num_inference_steps: Optional[int] = 50,
328
+ seed: Optional[int] = 12345,
329
+ reroll_regions: Optional[List[RerollRegion]] = None,
330
+ cpu_vae: Optional[bool] = False,
331
+ decode_steps: Optional[bool] = False,
332
+ ):
333
+ if reroll_regions is None:
334
+ reroll_regions = []
335
+ batch_size = 1
336
+
337
+ if decode_steps:
338
+ steps_images = []
339
+
340
+ # Prepare scheduler
341
+ self.scheduler.set_timesteps(num_inference_steps, device=self.device)
342
+
343
+ # Split diffusion regions by their kind
344
+ text2image_regions = [region for region in regions if isinstance(region, Text2ImageRegion)]
345
+ image2image_regions = [region for region in regions if isinstance(region, Image2ImageRegion)]
346
+
347
+ # Prepare text embeddings
348
+ for region in text2image_regions:
349
+ region.tokenize_prompt(self.tokenizer)
350
+ region.encode_prompt(self.text_encoder, self.device)
351
+
352
+ # Create original noisy latents using the timesteps
353
+ latents_shape = (batch_size, self.unet.config.in_channels, canvas_height // 8, canvas_width // 8)
354
+ generator = torch.Generator(self.device).manual_seed(seed)
355
+ init_noise = torch.randn(latents_shape, generator=generator, device=self.device)
356
+
357
+ # Reset latents in seed reroll regions, if requested
358
+ for region in reroll_regions:
359
+ if region.reroll_mode == RerollModes.RESET.value:
360
+ region_shape = (
361
+ latents_shape[0],
362
+ latents_shape[1],
363
+ region.latent_row_end - region.latent_row_init,
364
+ region.latent_col_end - region.latent_col_init,
365
+ )
366
+ init_noise[
367
+ :,
368
+ :,
369
+ region.latent_row_init : region.latent_row_end,
370
+ region.latent_col_init : region.latent_col_end,
371
+ ] = torch.randn(region_shape, generator=region.get_region_generator(self.device), device=self.device)
372
+
373
+ # Apply epsilon noise to regions: first diffusion regions, then reroll regions
374
+ all_eps_rerolls = regions + [r for r in reroll_regions if r.reroll_mode == RerollModes.EPSILON.value]
375
+ for region in all_eps_rerolls:
376
+ if region.noise_eps > 0:
377
+ region_noise = init_noise[
378
+ :,
379
+ :,
380
+ region.latent_row_init : region.latent_row_end,
381
+ region.latent_col_init : region.latent_col_end,
382
+ ]
383
+ eps_noise = (
384
+ torch.randn(
385
+ region_noise.shape, generator=region.get_region_generator(self.device), device=self.device
386
+ )
387
+ * region.noise_eps
388
+ )
389
+ init_noise[
390
+ :,
391
+ :,
392
+ region.latent_row_init : region.latent_row_end,
393
+ region.latent_col_init : region.latent_col_end,
394
+ ] += eps_noise
395
+
396
+ # scale the initial noise by the standard deviation required by the scheduler
397
+ latents = init_noise * self.scheduler.init_noise_sigma
398
+
399
+ # Get unconditional embeddings for classifier free guidance in text2image regions
400
+ for region in text2image_regions:
401
+ max_length = region.tokenized_prompt.input_ids.shape[-1]
402
+ uncond_input = self.tokenizer(
403
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
404
+ )
405
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
406
+
407
+ # For classifier free guidance, we need to do two forward passes.
408
+ # Here we concatenate the unconditional and text embeddings into a single batch
409
+ # to avoid doing two forward passes
410
+ region.encoded_prompt = torch.cat([uncond_embeddings, region.encoded_prompt])
411
+
412
+ # Prepare image latents
413
+ for region in image2image_regions:
414
+ region.encode_reference_image(self.vae, device=self.device, generator=generator)
415
+
416
+ # Prepare mask of weights for each region
417
+ mask_builder = MaskWeightsBuilder(latent_space_dim=self.unet.config.in_channels, nbatch=batch_size)
418
+ mask_weights = [mask_builder.compute_mask_weights(region).to(self.device) for region in text2image_regions]
419
+
420
+ # Diffusion timesteps
421
+ for i, t in tqdm(enumerate(self.scheduler.timesteps)):
422
+ # Diffuse each region
423
+ noise_preds_regions = []
424
+
425
+ # text2image regions
426
+ for region in text2image_regions:
427
+ region_latents = latents[
428
+ :,
429
+ :,
430
+ region.latent_row_init : region.latent_row_end,
431
+ region.latent_col_init : region.latent_col_end,
432
+ ]
433
+ # expand the latents if we are doing classifier free guidance
434
+ latent_model_input = torch.cat([region_latents] * 2)
435
+ # scale model input following scheduler rules
436
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
437
+ # predict the noise residual
438
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=region.encoded_prompt)["sample"]
439
+ # perform guidance
440
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
441
+ noise_pred_region = noise_pred_uncond + region.guidance_scale * (noise_pred_text - noise_pred_uncond)
442
+ noise_preds_regions.append(noise_pred_region)
443
+
444
+ # Merge noise predictions for all tiles
445
+ noise_pred = torch.zeros(latents.shape, device=self.device)
446
+ contributors = torch.zeros(latents.shape, device=self.device)
447
+ # Add each tile contribution to overall latents
448
+ for region, noise_pred_region, mask_weights_region in zip(
449
+ text2image_regions, noise_preds_regions, mask_weights
450
+ ):
451
+ noise_pred[
452
+ :,
453
+ :,
454
+ region.latent_row_init : region.latent_row_end,
455
+ region.latent_col_init : region.latent_col_end,
456
+ ] += noise_pred_region * mask_weights_region
457
+ contributors[
458
+ :,
459
+ :,
460
+ region.latent_row_init : region.latent_row_end,
461
+ region.latent_col_init : region.latent_col_end,
462
+ ] += mask_weights_region
463
+ # Average overlapping areas with more than 1 contributor
464
+ noise_pred /= contributors
465
+ noise_pred = torch.nan_to_num(
466
+ noise_pred
467
+ ) # Replace NaNs by zeros: NaN can appear if a position is not covered by any DiffusionRegion
468
+
469
+ # compute the previous noisy sample x_t -> x_t-1
470
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
471
+
472
+ # Image2Image regions: override latents generated by the scheduler
473
+ for region in image2image_regions:
474
+ influence_step = self.get_latest_timestep_img2img(num_inference_steps, region.strength)
475
+ # Only override in the timesteps before the last influence step of the image (given by its strength)
476
+ if t > influence_step:
477
+ timestep = t.repeat(batch_size)
478
+ region_init_noise = init_noise[
479
+ :,
480
+ :,
481
+ region.latent_row_init : region.latent_row_end,
482
+ region.latent_col_init : region.latent_col_end,
483
+ ]
484
+ region_latents = self.scheduler.add_noise(region.reference_latents, region_init_noise, timestep)
485
+ latents[
486
+ :,
487
+ :,
488
+ region.latent_row_init : region.latent_row_end,
489
+ region.latent_col_init : region.latent_col_end,
490
+ ] = region_latents
491
+
492
+ if decode_steps:
493
+ steps_images.append(self.decode_latents(latents, cpu_vae))
494
+
495
+ # scale and decode the image latents with vae
496
+ image = self.decode_latents(latents, cpu_vae)
497
+
498
+ output = {"images": image}
499
+ if decode_steps:
500
+ output = {**output, "steps_images": steps_images}
501
+ return output
v0.32.0/mixture_tiling.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from copy import deepcopy
3
+ from enum import Enum
4
+ from typing import List, Optional, Tuple, Union
5
+
6
+ import torch
7
+ from tqdm.auto import tqdm
8
+
9
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
10
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
11
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
12
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
13
+ from diffusers.utils import logging
14
+
15
+
16
+ try:
17
+ from ligo.segments import segment
18
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
19
+ except ImportError:
20
+ raise ImportError("Please install transformers and ligo-segments to use the mixture pipeline")
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+ EXAMPLE_DOC_STRING = """
25
+ Examples:
26
+ ```py
27
+ >>> from diffusers import LMSDiscreteScheduler, DiffusionPipeline
28
+
29
+ >>> scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
30
+ >>> pipeline = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", scheduler=scheduler, custom_pipeline="mixture_tiling")
31
+ >>> pipeline.to("cuda")
32
+
33
+ >>> image = pipeline(
34
+ >>> prompt=[[
35
+ >>> "A charming house in the countryside, by jakub rozalski, sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece",
36
+ >>> "A dirt road in the countryside crossing pastures, by jakub rozalski, sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece",
37
+ >>> "An old and rusty giant robot lying on a dirt road, by jakub rozalski, dark sunset lighting, elegant, highly detailed, smooth, sharp focus, artstation, stunning masterpiece"
38
+ >>> ]],
39
+ >>> tile_height=640,
40
+ >>> tile_width=640,
41
+ >>> tile_row_overlap=0,
42
+ >>> tile_col_overlap=256,
43
+ >>> guidance_scale=8,
44
+ >>> seed=7178915308,
45
+ >>> num_inference_steps=50,
46
+ >>> )["images"][0]
47
+ ```
48
+ """
49
+
50
+
51
+ def _tile2pixel_indices(tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap):
52
+ """Given a tile row and column numbers returns the range of pixels affected by that tiles in the overall image
53
+
54
+ Returns a tuple with:
55
+ - Starting coordinates of rows in pixel space
56
+ - Ending coordinates of rows in pixel space
57
+ - Starting coordinates of columns in pixel space
58
+ - Ending coordinates of columns in pixel space
59
+ """
60
+ px_row_init = 0 if tile_row == 0 else tile_row * (tile_height - tile_row_overlap)
61
+ px_row_end = px_row_init + tile_height
62
+ px_col_init = 0 if tile_col == 0 else tile_col * (tile_width - tile_col_overlap)
63
+ px_col_end = px_col_init + tile_width
64
+ return px_row_init, px_row_end, px_col_init, px_col_end
65
+
66
+
67
+ def _pixel2latent_indices(px_row_init, px_row_end, px_col_init, px_col_end):
68
+ """Translates coordinates in pixel space to coordinates in latent space"""
69
+ return px_row_init // 8, px_row_end // 8, px_col_init // 8, px_col_end // 8
70
+
71
+
72
+ def _tile2latent_indices(tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap):
73
+ """Given a tile row and column numbers returns the range of latents affected by that tiles in the overall image
74
+
75
+ Returns a tuple with:
76
+ - Starting coordinates of rows in latent space
77
+ - Ending coordinates of rows in latent space
78
+ - Starting coordinates of columns in latent space
79
+ - Ending coordinates of columns in latent space
80
+ """
81
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2pixel_indices(
82
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
83
+ )
84
+ return _pixel2latent_indices(px_row_init, px_row_end, px_col_init, px_col_end)
85
+
86
+
87
+ def _tile2latent_exclusive_indices(
88
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap, rows, columns
89
+ ):
90
+ """Given a tile row and column numbers returns the range of latents affected only by that tile in the overall image
91
+
92
+ Returns a tuple with:
93
+ - Starting coordinates of rows in latent space
94
+ - Ending coordinates of rows in latent space
95
+ - Starting coordinates of columns in latent space
96
+ - Ending coordinates of columns in latent space
97
+ """
98
+ row_init, row_end, col_init, col_end = _tile2latent_indices(
99
+ tile_row, tile_col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
100
+ )
101
+ row_segment = segment(row_init, row_end)
102
+ col_segment = segment(col_init, col_end)
103
+ # Iterate over the rest of tiles, clipping the region for the current tile
104
+ for row in range(rows):
105
+ for column in range(columns):
106
+ if row != tile_row and column != tile_col:
107
+ clip_row_init, clip_row_end, clip_col_init, clip_col_end = _tile2latent_indices(
108
+ row, column, tile_width, tile_height, tile_row_overlap, tile_col_overlap
109
+ )
110
+ row_segment = row_segment - segment(clip_row_init, clip_row_end)
111
+ col_segment = col_segment - segment(clip_col_init, clip_col_end)
112
+ # return row_init, row_end, col_init, col_end
113
+ return row_segment[0], row_segment[1], col_segment[0], col_segment[1]
114
+
115
+
116
+ class StableDiffusionExtrasMixin:
117
+ """Mixin providing additional convenience method to Stable Diffusion pipelines"""
118
+
119
+ def decode_latents(self, latents, cpu_vae=False):
120
+ """Decodes a given array of latents into pixel space"""
121
+ # scale and decode the image latents with vae
122
+ if cpu_vae:
123
+ lat = deepcopy(latents).cpu()
124
+ vae = deepcopy(self.vae).cpu()
125
+ else:
126
+ lat = latents
127
+ vae = self.vae
128
+
129
+ lat = 1 / 0.18215 * lat
130
+ image = vae.decode(lat).sample
131
+
132
+ image = (image / 2 + 0.5).clamp(0, 1)
133
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
134
+
135
+ return self.numpy_to_pil(image)
136
+
137
+
138
+ class StableDiffusionTilingPipeline(DiffusionPipeline, StableDiffusionExtrasMixin):
139
+ def __init__(
140
+ self,
141
+ vae: AutoencoderKL,
142
+ text_encoder: CLIPTextModel,
143
+ tokenizer: CLIPTokenizer,
144
+ unet: UNet2DConditionModel,
145
+ scheduler: Union[DDIMScheduler, PNDMScheduler],
146
+ safety_checker: StableDiffusionSafetyChecker,
147
+ feature_extractor: CLIPImageProcessor,
148
+ ):
149
+ super().__init__()
150
+ self.register_modules(
151
+ vae=vae,
152
+ text_encoder=text_encoder,
153
+ tokenizer=tokenizer,
154
+ unet=unet,
155
+ scheduler=scheduler,
156
+ safety_checker=safety_checker,
157
+ feature_extractor=feature_extractor,
158
+ )
159
+
160
+ class SeedTilesMode(Enum):
161
+ """Modes in which the latents of a particular tile can be re-seeded"""
162
+
163
+ FULL = "full"
164
+ EXCLUSIVE = "exclusive"
165
+
166
+ @torch.no_grad()
167
+ def __call__(
168
+ self,
169
+ prompt: Union[str, List[List[str]]],
170
+ num_inference_steps: Optional[int] = 50,
171
+ guidance_scale: Optional[float] = 7.5,
172
+ eta: Optional[float] = 0.0,
173
+ seed: Optional[int] = None,
174
+ tile_height: Optional[int] = 512,
175
+ tile_width: Optional[int] = 512,
176
+ tile_row_overlap: Optional[int] = 256,
177
+ tile_col_overlap: Optional[int] = 256,
178
+ guidance_scale_tiles: Optional[List[List[float]]] = None,
179
+ seed_tiles: Optional[List[List[int]]] = None,
180
+ seed_tiles_mode: Optional[Union[str, List[List[str]]]] = "full",
181
+ seed_reroll_regions: Optional[List[Tuple[int, int, int, int, int]]] = None,
182
+ cpu_vae: Optional[bool] = False,
183
+ ):
184
+ r"""
185
+ Function to run the diffusion pipeline with tiling support.
186
+
187
+ Args:
188
+ prompt: either a single string (no tiling) or a list of lists with all the prompts to use (one list for each row of tiles). This will also define the tiling structure.
189
+ num_inference_steps: number of diffusions steps.
190
+ guidance_scale: classifier-free guidance.
191
+ seed: general random seed to initialize latents.
192
+ tile_height: height in pixels of each grid tile.
193
+ tile_width: width in pixels of each grid tile.
194
+ tile_row_overlap: number of overlap pixels between tiles in consecutive rows.
195
+ tile_col_overlap: number of overlap pixels between tiles in consecutive columns.
196
+ guidance_scale_tiles: specific weights for classifier-free guidance in each tile.
197
+ guidance_scale_tiles: specific weights for classifier-free guidance in each tile. If None, the value provided in guidance_scale will be used.
198
+ seed_tiles: specific seeds for the initialization latents in each tile. These will override the latents generated for the whole canvas using the standard seed parameter.
199
+ seed_tiles_mode: either "full" "exclusive". If "full", all the latents affected by the tile be overriden. If "exclusive", only the latents that are affected exclusively by this tile (and no other tiles) will be overriden.
200
+ seed_reroll_regions: a list of tuples in the form (start row, end row, start column, end column, seed) defining regions in pixel space for which the latents will be overriden using the given seed. Takes priority over seed_tiles.
201
+ cpu_vae: the decoder from latent space to pixel space can require too mucho GPU RAM for large images. If you find out of memory errors at the end of the generation process, try setting this parameter to True to run the decoder in CPU. Slower, but should run without memory issues.
202
+
203
+ Examples:
204
+
205
+ Returns:
206
+ A PIL image with the generated image.
207
+
208
+ """
209
+ if not isinstance(prompt, list) or not all(isinstance(row, list) for row in prompt):
210
+ raise ValueError(f"`prompt` has to be a list of lists but is {type(prompt)}")
211
+ grid_rows = len(prompt)
212
+ grid_cols = len(prompt[0])
213
+ if not all(len(row) == grid_cols for row in prompt):
214
+ raise ValueError("All prompt rows must have the same number of prompt columns")
215
+ if not isinstance(seed_tiles_mode, str) and (
216
+ not isinstance(seed_tiles_mode, list) or not all(isinstance(row, list) for row in seed_tiles_mode)
217
+ ):
218
+ raise ValueError(f"`seed_tiles_mode` has to be a string or list of lists but is {type(prompt)}")
219
+ if isinstance(seed_tiles_mode, str):
220
+ seed_tiles_mode = [[seed_tiles_mode for _ in range(len(row))] for row in prompt]
221
+
222
+ modes = [mode.value for mode in self.SeedTilesMode]
223
+ if any(mode not in modes for row in seed_tiles_mode for mode in row):
224
+ raise ValueError(f"Seed tiles mode must be one of {modes}")
225
+ if seed_reroll_regions is None:
226
+ seed_reroll_regions = []
227
+ batch_size = 1
228
+
229
+ # create original noisy latents using the timesteps
230
+ height = tile_height + (grid_rows - 1) * (tile_height - tile_row_overlap)
231
+ width = tile_width + (grid_cols - 1) * (tile_width - tile_col_overlap)
232
+ latents_shape = (batch_size, self.unet.config.in_channels, height // 8, width // 8)
233
+ generator = torch.Generator("cuda").manual_seed(seed)
234
+ latents = torch.randn(latents_shape, generator=generator, device=self.device)
235
+
236
+ # overwrite latents for specific tiles if provided
237
+ if seed_tiles is not None:
238
+ for row in range(grid_rows):
239
+ for col in range(grid_cols):
240
+ if (seed_tile := seed_tiles[row][col]) is not None:
241
+ mode = seed_tiles_mode[row][col]
242
+ if mode == self.SeedTilesMode.FULL.value:
243
+ row_init, row_end, col_init, col_end = _tile2latent_indices(
244
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
245
+ )
246
+ else:
247
+ row_init, row_end, col_init, col_end = _tile2latent_exclusive_indices(
248
+ row,
249
+ col,
250
+ tile_width,
251
+ tile_height,
252
+ tile_row_overlap,
253
+ tile_col_overlap,
254
+ grid_rows,
255
+ grid_cols,
256
+ )
257
+ tile_generator = torch.Generator("cuda").manual_seed(seed_tile)
258
+ tile_shape = (latents_shape[0], latents_shape[1], row_end - row_init, col_end - col_init)
259
+ latents[:, :, row_init:row_end, col_init:col_end] = torch.randn(
260
+ tile_shape, generator=tile_generator, device=self.device
261
+ )
262
+
263
+ # overwrite again for seed reroll regions
264
+ for row_init, row_end, col_init, col_end, seed_reroll in seed_reroll_regions:
265
+ row_init, row_end, col_init, col_end = _pixel2latent_indices(
266
+ row_init, row_end, col_init, col_end
267
+ ) # to latent space coordinates
268
+ reroll_generator = torch.Generator("cuda").manual_seed(seed_reroll)
269
+ region_shape = (latents_shape[0], latents_shape[1], row_end - row_init, col_end - col_init)
270
+ latents[:, :, row_init:row_end, col_init:col_end] = torch.randn(
271
+ region_shape, generator=reroll_generator, device=self.device
272
+ )
273
+
274
+ # Prepare scheduler
275
+ accepts_offset = "offset" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
276
+ extra_set_kwargs = {}
277
+ if accepts_offset:
278
+ extra_set_kwargs["offset"] = 1
279
+ self.scheduler.set_timesteps(num_inference_steps, **extra_set_kwargs)
280
+ # if we use LMSDiscreteScheduler, let's make sure latents are multiplied by sigmas
281
+ if isinstance(self.scheduler, LMSDiscreteScheduler):
282
+ latents = latents * self.scheduler.sigmas[0]
283
+
284
+ # get prompts text embeddings
285
+ text_input = [
286
+ [
287
+ self.tokenizer(
288
+ col,
289
+ padding="max_length",
290
+ max_length=self.tokenizer.model_max_length,
291
+ truncation=True,
292
+ return_tensors="pt",
293
+ )
294
+ for col in row
295
+ ]
296
+ for row in prompt
297
+ ]
298
+ text_embeddings = [[self.text_encoder(col.input_ids.to(self.device))[0] for col in row] for row in text_input]
299
+
300
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
301
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
302
+ # corresponds to doing no classifier free guidance.
303
+ do_classifier_free_guidance = guidance_scale > 1.0 # TODO: also active if any tile has guidance scale
304
+ # get unconditional embeddings for classifier free guidance
305
+ if do_classifier_free_guidance:
306
+ for i in range(grid_rows):
307
+ for j in range(grid_cols):
308
+ max_length = text_input[i][j].input_ids.shape[-1]
309
+ uncond_input = self.tokenizer(
310
+ [""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
311
+ )
312
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
313
+
314
+ # For classifier free guidance, we need to do two forward passes.
315
+ # Here we concatenate the unconditional and text embeddings into a single batch
316
+ # to avoid doing two forward passes
317
+ text_embeddings[i][j] = torch.cat([uncond_embeddings, text_embeddings[i][j]])
318
+
319
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
320
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
321
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
322
+ # and should be between [0, 1]
323
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
324
+ extra_step_kwargs = {}
325
+ if accepts_eta:
326
+ extra_step_kwargs["eta"] = eta
327
+
328
+ # Mask for tile weights strength
329
+ tile_weights = self._gaussian_weights(tile_width, tile_height, batch_size)
330
+
331
+ # Diffusion timesteps
332
+ for i, t in tqdm(enumerate(self.scheduler.timesteps)):
333
+ # Diffuse each tile
334
+ noise_preds = []
335
+ for row in range(grid_rows):
336
+ noise_preds_row = []
337
+ for col in range(grid_cols):
338
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
339
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
340
+ )
341
+ tile_latents = latents[:, :, px_row_init:px_row_end, px_col_init:px_col_end]
342
+ # expand the latents if we are doing classifier free guidance
343
+ latent_model_input = torch.cat([tile_latents] * 2) if do_classifier_free_guidance else tile_latents
344
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
345
+ # predict the noise residual
346
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings[row][col])[
347
+ "sample"
348
+ ]
349
+ # perform guidance
350
+ if do_classifier_free_guidance:
351
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
352
+ guidance = (
353
+ guidance_scale
354
+ if guidance_scale_tiles is None or guidance_scale_tiles[row][col] is None
355
+ else guidance_scale_tiles[row][col]
356
+ )
357
+ noise_pred_tile = noise_pred_uncond + guidance * (noise_pred_text - noise_pred_uncond)
358
+ noise_preds_row.append(noise_pred_tile)
359
+ noise_preds.append(noise_preds_row)
360
+ # Stitch noise predictions for all tiles
361
+ noise_pred = torch.zeros(latents.shape, device=self.device)
362
+ contributors = torch.zeros(latents.shape, device=self.device)
363
+ # Add each tile contribution to overall latents
364
+ for row in range(grid_rows):
365
+ for col in range(grid_cols):
366
+ px_row_init, px_row_end, px_col_init, px_col_end = _tile2latent_indices(
367
+ row, col, tile_width, tile_height, tile_row_overlap, tile_col_overlap
368
+ )
369
+ noise_pred[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += (
370
+ noise_preds[row][col] * tile_weights
371
+ )
372
+ contributors[:, :, px_row_init:px_row_end, px_col_init:px_col_end] += tile_weights
373
+ # Average overlapping areas with more than 1 contributor
374
+ noise_pred /= contributors
375
+
376
+ # compute the previous noisy sample x_t -> x_t-1
377
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
378
+
379
+ # scale and decode the image latents with vae
380
+ image = self.decode_latents(latents, cpu_vae)
381
+
382
+ return {"images": image}
383
+
384
+ def _gaussian_weights(self, tile_width, tile_height, nbatches):
385
+ """Generates a gaussian mask of weights for tile contributions"""
386
+ import numpy as np
387
+ from numpy import exp, pi, sqrt
388
+
389
+ latent_width = tile_width // 8
390
+ latent_height = tile_height // 8
391
+
392
+ var = 0.01
393
+ midpoint = (latent_width - 1) / 2 # -1 because index goes from 0 to latent_width - 1
394
+ x_probs = [
395
+ exp(-(x - midpoint) * (x - midpoint) / (latent_width * latent_width) / (2 * var)) / sqrt(2 * pi * var)
396
+ for x in range(latent_width)
397
+ ]
398
+ midpoint = latent_height / 2
399
+ y_probs = [
400
+ exp(-(y - midpoint) * (y - midpoint) / (latent_height * latent_height) / (2 * var)) / sqrt(2 * pi * var)
401
+ for y in range(latent_height)
402
+ ]
403
+
404
+ weights = np.outer(y_probs, x_probs)
405
+ return torch.tile(torch.tensor(weights, device=self.device), (nbatches, self.unet.config.in_channels, 1, 1))
v0.32.0/multilingual_stable_diffusion.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import torch
5
+ from transformers import (
6
+ CLIPImageProcessor,
7
+ CLIPTextModel,
8
+ CLIPTokenizer,
9
+ MBart50TokenizerFast,
10
+ MBartForConditionalGeneration,
11
+ pipeline,
12
+ )
13
+
14
+ from diffusers.configuration_utils import FrozenDict
15
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
16
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
17
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
18
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
19
+ from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
20
+ from diffusers.utils import deprecate, logging
21
+
22
+
23
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
24
+
25
+
26
+ def detect_language(pipe, prompt, batch_size):
27
+ """helper function to detect language(s) of prompt"""
28
+
29
+ if batch_size == 1:
30
+ preds = pipe(prompt, top_k=1, truncation=True, max_length=128)
31
+ return preds[0]["label"]
32
+ else:
33
+ detected_languages = []
34
+ for p in prompt:
35
+ preds = pipe(p, top_k=1, truncation=True, max_length=128)
36
+ detected_languages.append(preds[0]["label"])
37
+
38
+ return detected_languages
39
+
40
+
41
+ def translate_prompt(prompt, translation_tokenizer, translation_model, device):
42
+ """helper function to translate prompt to English"""
43
+
44
+ encoded_prompt = translation_tokenizer(prompt, return_tensors="pt").to(device)
45
+ generated_tokens = translation_model.generate(**encoded_prompt, max_new_tokens=1000)
46
+ en_trans = translation_tokenizer.batch_decode(generated_tokens, skip_special_tokens=True)
47
+
48
+ return en_trans[0]
49
+
50
+
51
+ class MultilingualStableDiffusion(DiffusionPipeline, StableDiffusionMixin):
52
+ r"""
53
+ Pipeline for text-to-image generation using Stable Diffusion in different languages.
54
+
55
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
56
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
57
+
58
+ Args:
59
+ detection_pipeline ([`pipeline`]):
60
+ Transformers pipeline to detect prompt's language.
61
+ translation_model ([`MBartForConditionalGeneration`]):
62
+ Model to translate prompt to English, if necessary. Please refer to the
63
+ [model card](https://huggingface.co/docs/transformers/model_doc/mbart) for details.
64
+ translation_tokenizer ([`MBart50TokenizerFast`]):
65
+ Tokenizer of the translation model.
66
+ vae ([`AutoencoderKL`]):
67
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
68
+ text_encoder ([`CLIPTextModel`]):
69
+ Frozen text-encoder. Stable Diffusion uses the text portion of
70
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
71
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
72
+ tokenizer (`CLIPTokenizer`):
73
+ Tokenizer of class
74
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
75
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
76
+ scheduler ([`SchedulerMixin`]):
77
+ A scheduler to be used in combination with `unet` to denoise the encoded image latens. Can be one of
78
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
79
+ safety_checker ([`StableDiffusionSafetyChecker`]):
80
+ Classification module that estimates whether generated images could be considered offensive or harmful.
81
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
82
+ feature_extractor ([`CLIPImageProcessor`]):
83
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
84
+ """
85
+
86
+ def __init__(
87
+ self,
88
+ detection_pipeline: pipeline,
89
+ translation_model: MBartForConditionalGeneration,
90
+ translation_tokenizer: MBart50TokenizerFast,
91
+ vae: AutoencoderKL,
92
+ text_encoder: CLIPTextModel,
93
+ tokenizer: CLIPTokenizer,
94
+ unet: UNet2DConditionModel,
95
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
96
+ safety_checker: StableDiffusionSafetyChecker,
97
+ feature_extractor: CLIPImageProcessor,
98
+ ):
99
+ super().__init__()
100
+
101
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
102
+ deprecation_message = (
103
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
104
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
105
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
106
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
107
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
108
+ " file"
109
+ )
110
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
111
+ new_config = dict(scheduler.config)
112
+ new_config["steps_offset"] = 1
113
+ scheduler._internal_dict = FrozenDict(new_config)
114
+
115
+ if safety_checker is None:
116
+ logger.warning(
117
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
118
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
119
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
120
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
121
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
122
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
123
+ )
124
+
125
+ self.register_modules(
126
+ detection_pipeline=detection_pipeline,
127
+ translation_model=translation_model,
128
+ translation_tokenizer=translation_tokenizer,
129
+ vae=vae,
130
+ text_encoder=text_encoder,
131
+ tokenizer=tokenizer,
132
+ unet=unet,
133
+ scheduler=scheduler,
134
+ safety_checker=safety_checker,
135
+ feature_extractor=feature_extractor,
136
+ )
137
+
138
+ @torch.no_grad()
139
+ def __call__(
140
+ self,
141
+ prompt: Union[str, List[str]],
142
+ height: int = 512,
143
+ width: int = 512,
144
+ num_inference_steps: int = 50,
145
+ guidance_scale: float = 7.5,
146
+ negative_prompt: Optional[Union[str, List[str]]] = None,
147
+ num_images_per_prompt: Optional[int] = 1,
148
+ eta: float = 0.0,
149
+ generator: Optional[torch.Generator] = None,
150
+ latents: Optional[torch.Tensor] = None,
151
+ output_type: Optional[str] = "pil",
152
+ return_dict: bool = True,
153
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
154
+ callback_steps: int = 1,
155
+ **kwargs,
156
+ ):
157
+ r"""
158
+ Function invoked when calling the pipeline for generation.
159
+
160
+ Args:
161
+ prompt (`str` or `List[str]`):
162
+ The prompt or prompts to guide the image generation. Can be in different languages.
163
+ height (`int`, *optional*, defaults to 512):
164
+ The height in pixels of the generated image.
165
+ width (`int`, *optional*, defaults to 512):
166
+ The width in pixels of the generated image.
167
+ num_inference_steps (`int`, *optional*, defaults to 50):
168
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
169
+ expense of slower inference.
170
+ guidance_scale (`float`, *optional*, defaults to 7.5):
171
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
172
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
173
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
174
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
175
+ usually at the expense of lower image quality.
176
+ negative_prompt (`str` or `List[str]`, *optional*):
177
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
178
+ if `guidance_scale` is less than `1`).
179
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
180
+ The number of images to generate per prompt.
181
+ eta (`float`, *optional*, defaults to 0.0):
182
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
183
+ [`schedulers.DDIMScheduler`], will be ignored for others.
184
+ generator (`torch.Generator`, *optional*):
185
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
186
+ deterministic.
187
+ latents (`torch.Tensor`, *optional*):
188
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
189
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
190
+ tensor will ge generated by sampling using the supplied random `generator`.
191
+ output_type (`str`, *optional*, defaults to `"pil"`):
192
+ The output format of the generate image. Choose between
193
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
194
+ return_dict (`bool`, *optional*, defaults to `True`):
195
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
196
+ plain tuple.
197
+ callback (`Callable`, *optional*):
198
+ A function that will be called every `callback_steps` steps during inference. The function will be
199
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
200
+ callback_steps (`int`, *optional*, defaults to 1):
201
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
202
+ called at every step.
203
+
204
+ Returns:
205
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
206
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
207
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
208
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
209
+ (nsfw) content, according to the `safety_checker`.
210
+ """
211
+ if isinstance(prompt, str):
212
+ batch_size = 1
213
+ elif isinstance(prompt, list):
214
+ batch_size = len(prompt)
215
+ else:
216
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
217
+
218
+ if height % 8 != 0 or width % 8 != 0:
219
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
220
+
221
+ if (callback_steps is None) or (
222
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
223
+ ):
224
+ raise ValueError(
225
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
226
+ f" {type(callback_steps)}."
227
+ )
228
+
229
+ # detect language and translate if necessary
230
+ prompt_language = detect_language(self.detection_pipeline, prompt, batch_size)
231
+ if batch_size == 1 and prompt_language != "en":
232
+ prompt = translate_prompt(prompt, self.translation_tokenizer, self.translation_model, self.device)
233
+
234
+ if isinstance(prompt, list):
235
+ for index in range(batch_size):
236
+ if prompt_language[index] != "en":
237
+ p = translate_prompt(
238
+ prompt[index], self.translation_tokenizer, self.translation_model, self.device
239
+ )
240
+ prompt[index] = p
241
+
242
+ # get prompt text embeddings
243
+ text_inputs = self.tokenizer(
244
+ prompt,
245
+ padding="max_length",
246
+ max_length=self.tokenizer.model_max_length,
247
+ return_tensors="pt",
248
+ )
249
+ text_input_ids = text_inputs.input_ids
250
+
251
+ if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
252
+ removed_text = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
253
+ logger.warning(
254
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
255
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
256
+ )
257
+ text_input_ids = text_input_ids[:, : self.tokenizer.model_max_length]
258
+ text_embeddings = self.text_encoder(text_input_ids.to(self.device))[0]
259
+
260
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
261
+ bs_embed, seq_len, _ = text_embeddings.shape
262
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
263
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
264
+
265
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
266
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
267
+ # corresponds to doing no classifier free guidance.
268
+ do_classifier_free_guidance = guidance_scale > 1.0
269
+ # get unconditional embeddings for classifier free guidance
270
+ if do_classifier_free_guidance:
271
+ uncond_tokens: List[str]
272
+ if negative_prompt is None:
273
+ uncond_tokens = [""] * batch_size
274
+ elif type(prompt) is not type(negative_prompt):
275
+ raise TypeError(
276
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
277
+ f" {type(prompt)}."
278
+ )
279
+ elif isinstance(negative_prompt, str):
280
+ # detect language and translate it if necessary
281
+ negative_prompt_language = detect_language(self.detection_pipeline, negative_prompt, batch_size)
282
+ if negative_prompt_language != "en":
283
+ negative_prompt = translate_prompt(
284
+ negative_prompt, self.translation_tokenizer, self.translation_model, self.device
285
+ )
286
+ if isinstance(negative_prompt, str):
287
+ uncond_tokens = [negative_prompt]
288
+ elif batch_size != len(negative_prompt):
289
+ raise ValueError(
290
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
291
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
292
+ " the batch size of `prompt`."
293
+ )
294
+ else:
295
+ # detect language and translate it if necessary
296
+ if isinstance(negative_prompt, list):
297
+ negative_prompt_languages = detect_language(self.detection_pipeline, negative_prompt, batch_size)
298
+ for index in range(batch_size):
299
+ if negative_prompt_languages[index] != "en":
300
+ p = translate_prompt(
301
+ negative_prompt[index], self.translation_tokenizer, self.translation_model, self.device
302
+ )
303
+ negative_prompt[index] = p
304
+ uncond_tokens = negative_prompt
305
+
306
+ max_length = text_input_ids.shape[-1]
307
+ uncond_input = self.tokenizer(
308
+ uncond_tokens,
309
+ padding="max_length",
310
+ max_length=max_length,
311
+ truncation=True,
312
+ return_tensors="pt",
313
+ )
314
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
315
+
316
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
317
+ seq_len = uncond_embeddings.shape[1]
318
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
319
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
320
+
321
+ # For classifier free guidance, we need to do two forward passes.
322
+ # Here we concatenate the unconditional and text embeddings into a single batch
323
+ # to avoid doing two forward passes
324
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
325
+
326
+ # get the initial random noise unless the user supplied it
327
+
328
+ # Unlike in other pipelines, latents need to be generated in the target device
329
+ # for 1-to-1 results reproducibility with the CompVis implementation.
330
+ # However this currently doesn't work in `mps`.
331
+ latents_shape = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
332
+ latents_dtype = text_embeddings.dtype
333
+ if latents is None:
334
+ if self.device.type == "mps":
335
+ # randn does not work reproducibly on mps
336
+ latents = torch.randn(latents_shape, generator=generator, device="cpu", dtype=latents_dtype).to(
337
+ self.device
338
+ )
339
+ else:
340
+ latents = torch.randn(latents_shape, generator=generator, device=self.device, dtype=latents_dtype)
341
+ else:
342
+ if latents.shape != latents_shape:
343
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
344
+ latents = latents.to(self.device)
345
+
346
+ # set timesteps
347
+ self.scheduler.set_timesteps(num_inference_steps)
348
+
349
+ # Some schedulers like PNDM have timesteps as arrays
350
+ # It's more optimized to move all timesteps to correct device beforehand
351
+ timesteps_tensor = self.scheduler.timesteps.to(self.device)
352
+
353
+ # scale the initial noise by the standard deviation required by the scheduler
354
+ latents = latents * self.scheduler.init_noise_sigma
355
+
356
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
357
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
358
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
359
+ # and should be between [0, 1]
360
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
361
+ extra_step_kwargs = {}
362
+ if accepts_eta:
363
+ extra_step_kwargs["eta"] = eta
364
+
365
+ for i, t in enumerate(self.progress_bar(timesteps_tensor)):
366
+ # expand the latents if we are doing classifier free guidance
367
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
368
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
369
+
370
+ # predict the noise residual
371
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
372
+
373
+ # perform guidance
374
+ if do_classifier_free_guidance:
375
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
376
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
377
+
378
+ # compute the previous noisy sample x_t -> x_t-1
379
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
380
+
381
+ # call the callback, if provided
382
+ if callback is not None and i % callback_steps == 0:
383
+ step_idx = i // getattr(self.scheduler, "order", 1)
384
+ callback(step_idx, t, latents)
385
+
386
+ latents = 1 / 0.18215 * latents
387
+ image = self.vae.decode(latents).sample
388
+
389
+ image = (image / 2 + 0.5).clamp(0, 1)
390
+
391
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
392
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
393
+
394
+ if self.safety_checker is not None:
395
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(
396
+ self.device
397
+ )
398
+ image, has_nsfw_concept = self.safety_checker(
399
+ images=image, clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype)
400
+ )
401
+ else:
402
+ has_nsfw_concept = None
403
+
404
+ if output_type == "pil":
405
+ image = self.numpy_to_pil(image)
406
+
407
+ if not return_dict:
408
+ return (image, has_nsfw_concept)
409
+
410
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/one_step_unet.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import torch
3
+
4
+ from diffusers import DiffusionPipeline
5
+
6
+
7
+ class UnetSchedulerOneForwardPipeline(DiffusionPipeline):
8
+ def __init__(self, unet, scheduler):
9
+ super().__init__()
10
+
11
+ self.register_modules(unet=unet, scheduler=scheduler)
12
+
13
+ def __call__(self):
14
+ image = torch.randn(
15
+ (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size),
16
+ )
17
+ timestep = 1
18
+
19
+ model_output = self.unet(image, timestep).sample
20
+ scheduler_output = self.scheduler.step(model_output, timestep, image).prev_sample
21
+
22
+ result = scheduler_output - scheduler_output + torch.ones_like(scheduler_output)
23
+
24
+ return result
v0.32.0/pipeline_animatediff_controlnet.py ADDED
@@ -0,0 +1,1129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn.functional as F
21
+ from PIL import Image
22
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
23
+
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel, UNetMotionModel
27
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
28
+ from diffusers.models.unets.unet_motion_model import MotionAdapter
29
+ from diffusers.pipelines.animatediff.pipeline_output import AnimateDiffPipelineOutput
30
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
31
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
32
+ from diffusers.schedulers import (
33
+ DDIMScheduler,
34
+ DPMSolverMultistepScheduler,
35
+ EulerAncestralDiscreteScheduler,
36
+ EulerDiscreteScheduler,
37
+ LMSDiscreteScheduler,
38
+ PNDMScheduler,
39
+ )
40
+ from diffusers.utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
41
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
42
+
43
+
44
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```py
49
+ >>> import torch
50
+ >>> from diffusers import AutoencoderKL, ControlNetModel, MotionAdapter
51
+ >>> from diffusers.pipelines import DiffusionPipeline
52
+ >>> from diffusers.schedulers import DPMSolverMultistepScheduler
53
+ >>> from PIL import Image
54
+
55
+ >>> motion_id = "guoyww/animatediff-motion-adapter-v1-5-2"
56
+ >>> adapter = MotionAdapter.from_pretrained(motion_id)
57
+ >>> controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_openpose", torch_dtype=torch.float16)
58
+ >>> vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=torch.float16)
59
+
60
+ >>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
61
+ >>> pipe = DiffusionPipeline.from_pretrained(
62
+ ... model_id,
63
+ ... motion_adapter=adapter,
64
+ ... controlnet=controlnet,
65
+ ... vae=vae,
66
+ ... custom_pipeline="pipeline_animatediff_controlnet",
67
+ ... ).to(device="cuda", dtype=torch.float16)
68
+ >>> pipe.scheduler = DPMSolverMultistepScheduler.from_pretrained(
69
+ ... model_id, subfolder="scheduler", clip_sample=False, timestep_spacing="linspace", steps_offset=1, beta_schedule="linear",
70
+ ... )
71
+ >>> pipe.enable_vae_slicing()
72
+
73
+ >>> conditioning_frames = []
74
+ >>> for i in range(1, 16 + 1):
75
+ ... conditioning_frames.append(Image.open(f"frame_{i}.png"))
76
+
77
+ >>> prompt = "astronaut in space, dancing"
78
+ >>> negative_prompt = "bad quality, worst quality, jpeg artifacts, ugly"
79
+ >>> result = pipe(
80
+ ... prompt=prompt,
81
+ ... negative_prompt=negative_prompt,
82
+ ... width=512,
83
+ ... height=768,
84
+ ... conditioning_frames=conditioning_frames,
85
+ ... num_inference_steps=12,
86
+ ... )
87
+
88
+ >>> from diffusers.utils import export_to_gif
89
+ >>> export_to_gif(result.frames[0], "result.gif")
90
+ ```
91
+ """
92
+
93
+
94
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff.tensor2vid
95
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
96
+ batch_size, channels, num_frames, height, width = video.shape
97
+ outputs = []
98
+ for batch_idx in range(batch_size):
99
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
100
+ batch_output = processor.postprocess(batch_vid, output_type)
101
+
102
+ outputs.append(batch_output)
103
+
104
+ if output_type == "np":
105
+ outputs = np.stack(outputs)
106
+
107
+ elif output_type == "pt":
108
+ outputs = torch.stack(outputs)
109
+
110
+ elif not output_type == "pil":
111
+ raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
112
+
113
+ return outputs
114
+
115
+
116
+ class AnimateDiffControlNetPipeline(
117
+ DiffusionPipeline,
118
+ StableDiffusionMixin,
119
+ TextualInversionLoaderMixin,
120
+ IPAdapterMixin,
121
+ StableDiffusionLoraLoaderMixin,
122
+ ):
123
+ r"""
124
+ Pipeline for text-to-video generation.
125
+
126
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
127
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
128
+
129
+ The pipeline also inherits the following loading methods:
130
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
131
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
132
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
133
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
134
+
135
+ Args:
136
+ vae ([`AutoencoderKL`]):
137
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
138
+ text_encoder ([`CLIPTextModel`]):
139
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
140
+ tokenizer (`CLIPTokenizer`):
141
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
142
+ unet ([`UNet2DConditionModel`]):
143
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
144
+ motion_adapter ([`MotionAdapter`]):
145
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
146
+ scheduler ([`SchedulerMixin`]):
147
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
148
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
149
+ """
150
+
151
+ model_cpu_offload_seq = "text_encoder->unet->vae"
152
+ _optional_components = ["feature_extractor", "image_encoder"]
153
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
154
+
155
+ def __init__(
156
+ self,
157
+ vae: AutoencoderKL,
158
+ text_encoder: CLIPTextModel,
159
+ tokenizer: CLIPTokenizer,
160
+ unet: UNet2DConditionModel,
161
+ motion_adapter: MotionAdapter,
162
+ controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
163
+ scheduler: Union[
164
+ DDIMScheduler,
165
+ PNDMScheduler,
166
+ LMSDiscreteScheduler,
167
+ EulerDiscreteScheduler,
168
+ EulerAncestralDiscreteScheduler,
169
+ DPMSolverMultistepScheduler,
170
+ ],
171
+ feature_extractor: Optional[CLIPImageProcessor] = None,
172
+ image_encoder: Optional[CLIPVisionModelWithProjection] = None,
173
+ ):
174
+ super().__init__()
175
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
176
+
177
+ if isinstance(controlnet, (list, tuple)):
178
+ controlnet = MultiControlNetModel(controlnet)
179
+
180
+ self.register_modules(
181
+ vae=vae,
182
+ text_encoder=text_encoder,
183
+ tokenizer=tokenizer,
184
+ unet=unet,
185
+ motion_adapter=motion_adapter,
186
+ controlnet=controlnet,
187
+ scheduler=scheduler,
188
+ feature_extractor=feature_extractor,
189
+ image_encoder=image_encoder,
190
+ )
191
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
192
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
193
+ self.control_image_processor = VaeImageProcessor(
194
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
195
+ )
196
+
197
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
198
+ def encode_prompt(
199
+ self,
200
+ prompt,
201
+ device,
202
+ num_images_per_prompt,
203
+ do_classifier_free_guidance,
204
+ negative_prompt=None,
205
+ prompt_embeds: Optional[torch.Tensor] = None,
206
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
207
+ lora_scale: Optional[float] = None,
208
+ clip_skip: Optional[int] = None,
209
+ ):
210
+ r"""
211
+ Encodes the prompt into text encoder hidden states.
212
+
213
+ Args:
214
+ prompt (`str` or `List[str]`, *optional*):
215
+ prompt to be encoded
216
+ device: (`torch.device`):
217
+ torch device
218
+ num_images_per_prompt (`int`):
219
+ number of images that should be generated per prompt
220
+ do_classifier_free_guidance (`bool`):
221
+ whether to use classifier free guidance or not
222
+ negative_prompt (`str` or `List[str]`, *optional*):
223
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
224
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
225
+ less than `1`).
226
+ prompt_embeds (`torch.Tensor`, *optional*):
227
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
228
+ provided, text embeddings will be generated from `prompt` input argument.
229
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
230
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
231
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
232
+ argument.
233
+ lora_scale (`float`, *optional*):
234
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
235
+ clip_skip (`int`, *optional*):
236
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
237
+ the output of the pre-final layer will be used for computing the prompt embeddings.
238
+ """
239
+ # set lora scale so that monkey patched LoRA
240
+ # function of text encoder can correctly access it
241
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
242
+ self._lora_scale = lora_scale
243
+
244
+ # dynamically adjust the LoRA scale
245
+ if not USE_PEFT_BACKEND:
246
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
247
+ else:
248
+ scale_lora_layers(self.text_encoder, lora_scale)
249
+
250
+ if prompt is not None and isinstance(prompt, str):
251
+ batch_size = 1
252
+ elif prompt is not None and isinstance(prompt, list):
253
+ batch_size = len(prompt)
254
+ else:
255
+ batch_size = prompt_embeds.shape[0]
256
+
257
+ if prompt_embeds is None:
258
+ # textual inversion: process multi-vector tokens if necessary
259
+ if isinstance(self, TextualInversionLoaderMixin):
260
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
261
+
262
+ text_inputs = self.tokenizer(
263
+ prompt,
264
+ padding="max_length",
265
+ max_length=self.tokenizer.model_max_length,
266
+ truncation=True,
267
+ return_tensors="pt",
268
+ )
269
+ text_input_ids = text_inputs.input_ids
270
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
271
+
272
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
273
+ text_input_ids, untruncated_ids
274
+ ):
275
+ removed_text = self.tokenizer.batch_decode(
276
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
277
+ )
278
+ logger.warning(
279
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
280
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
281
+ )
282
+
283
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
284
+ attention_mask = text_inputs.attention_mask.to(device)
285
+ else:
286
+ attention_mask = None
287
+
288
+ if clip_skip is None:
289
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
290
+ prompt_embeds = prompt_embeds[0]
291
+ else:
292
+ prompt_embeds = self.text_encoder(
293
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
294
+ )
295
+ # Access the `hidden_states` first, that contains a tuple of
296
+ # all the hidden states from the encoder layers. Then index into
297
+ # the tuple to access the hidden states from the desired layer.
298
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
299
+ # We also need to apply the final LayerNorm here to not mess with the
300
+ # representations. The `last_hidden_states` that we typically use for
301
+ # obtaining the final prompt representations passes through the LayerNorm
302
+ # layer.
303
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
304
+
305
+ if self.text_encoder is not None:
306
+ prompt_embeds_dtype = self.text_encoder.dtype
307
+ elif self.unet is not None:
308
+ prompt_embeds_dtype = self.unet.dtype
309
+ else:
310
+ prompt_embeds_dtype = prompt_embeds.dtype
311
+
312
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
313
+
314
+ bs_embed, seq_len, _ = prompt_embeds.shape
315
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
316
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
317
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
318
+
319
+ # get unconditional embeddings for classifier free guidance
320
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
321
+ uncond_tokens: List[str]
322
+ if negative_prompt is None:
323
+ uncond_tokens = [""] * batch_size
324
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
325
+ raise TypeError(
326
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
327
+ f" {type(prompt)}."
328
+ )
329
+ elif isinstance(negative_prompt, str):
330
+ uncond_tokens = [negative_prompt]
331
+ elif batch_size != len(negative_prompt):
332
+ raise ValueError(
333
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
334
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
335
+ " the batch size of `prompt`."
336
+ )
337
+ else:
338
+ uncond_tokens = negative_prompt
339
+
340
+ # textual inversion: process multi-vector tokens if necessary
341
+ if isinstance(self, TextualInversionLoaderMixin):
342
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
343
+
344
+ max_length = prompt_embeds.shape[1]
345
+ uncond_input = self.tokenizer(
346
+ uncond_tokens,
347
+ padding="max_length",
348
+ max_length=max_length,
349
+ truncation=True,
350
+ return_tensors="pt",
351
+ )
352
+
353
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
354
+ attention_mask = uncond_input.attention_mask.to(device)
355
+ else:
356
+ attention_mask = None
357
+
358
+ negative_prompt_embeds = self.text_encoder(
359
+ uncond_input.input_ids.to(device),
360
+ attention_mask=attention_mask,
361
+ )
362
+ negative_prompt_embeds = negative_prompt_embeds[0]
363
+
364
+ if do_classifier_free_guidance:
365
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
366
+ seq_len = negative_prompt_embeds.shape[1]
367
+
368
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
369
+
370
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
371
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
372
+
373
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
374
+ # Retrieve the original scale by scaling back the LoRA layers
375
+ unscale_lora_layers(self.text_encoder, lora_scale)
376
+
377
+ return prompt_embeds, negative_prompt_embeds
378
+
379
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
380
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
381
+ dtype = next(self.image_encoder.parameters()).dtype
382
+
383
+ if not isinstance(image, torch.Tensor):
384
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
385
+
386
+ image = image.to(device=device, dtype=dtype)
387
+ if output_hidden_states:
388
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
389
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
390
+ uncond_image_enc_hidden_states = self.image_encoder(
391
+ torch.zeros_like(image), output_hidden_states=True
392
+ ).hidden_states[-2]
393
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
394
+ num_images_per_prompt, dim=0
395
+ )
396
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
397
+ else:
398
+ image_embeds = self.image_encoder(image).image_embeds
399
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
400
+ uncond_image_embeds = torch.zeros_like(image_embeds)
401
+
402
+ return image_embeds, uncond_image_embeds
403
+
404
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
405
+ def prepare_ip_adapter_image_embeds(
406
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
407
+ ):
408
+ if ip_adapter_image_embeds is None:
409
+ if not isinstance(ip_adapter_image, list):
410
+ ip_adapter_image = [ip_adapter_image]
411
+
412
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
413
+ raise ValueError(
414
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
415
+ )
416
+
417
+ image_embeds = []
418
+ for single_ip_adapter_image, image_proj_layer in zip(
419
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
420
+ ):
421
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
422
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
423
+ single_ip_adapter_image, device, 1, output_hidden_state
424
+ )
425
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
426
+ single_negative_image_embeds = torch.stack(
427
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
428
+ )
429
+
430
+ if self.do_classifier_free_guidance:
431
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
432
+ single_image_embeds = single_image_embeds.to(device)
433
+
434
+ image_embeds.append(single_image_embeds)
435
+ else:
436
+ image_embeds = ip_adapter_image_embeds
437
+ return image_embeds
438
+
439
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
440
+ def decode_latents(self, latents):
441
+ latents = 1 / self.vae.config.scaling_factor * latents
442
+
443
+ batch_size, channels, num_frames, height, width = latents.shape
444
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
445
+
446
+ image = self.vae.decode(latents).sample
447
+ video = (
448
+ image[None, :]
449
+ .reshape(
450
+ (
451
+ batch_size,
452
+ num_frames,
453
+ -1,
454
+ )
455
+ + image.shape[2:]
456
+ )
457
+ .permute(0, 2, 1, 3, 4)
458
+ )
459
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
460
+ video = video.float()
461
+ return video
462
+
463
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
464
+ def prepare_extra_step_kwargs(self, generator, eta):
465
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
466
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
467
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
468
+ # and should be between [0, 1]
469
+
470
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
471
+ extra_step_kwargs = {}
472
+ if accepts_eta:
473
+ extra_step_kwargs["eta"] = eta
474
+
475
+ # check if the scheduler accepts generator
476
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
477
+ if accepts_generator:
478
+ extra_step_kwargs["generator"] = generator
479
+ return extra_step_kwargs
480
+
481
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
482
+ def check_inputs(
483
+ self,
484
+ prompt,
485
+ height,
486
+ width,
487
+ num_frames,
488
+ callback_steps,
489
+ negative_prompt=None,
490
+ prompt_embeds=None,
491
+ negative_prompt_embeds=None,
492
+ callback_on_step_end_tensor_inputs=None,
493
+ image=None,
494
+ controlnet_conditioning_scale=1.0,
495
+ control_guidance_start=0.0,
496
+ control_guidance_end=1.0,
497
+ ):
498
+ if height % 8 != 0 or width % 8 != 0:
499
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
500
+
501
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
502
+ raise ValueError(
503
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
504
+ f" {type(callback_steps)}."
505
+ )
506
+ if callback_on_step_end_tensor_inputs is not None and not all(
507
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
508
+ ):
509
+ raise ValueError(
510
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
511
+ )
512
+
513
+ if prompt is not None and prompt_embeds is not None:
514
+ raise ValueError(
515
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
516
+ " only forward one of the two."
517
+ )
518
+ elif prompt is None and prompt_embeds is None:
519
+ raise ValueError(
520
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
521
+ )
522
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
523
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
524
+
525
+ if negative_prompt is not None and negative_prompt_embeds is not None:
526
+ raise ValueError(
527
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
528
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
529
+ )
530
+
531
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
532
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
533
+ raise ValueError(
534
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
535
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
536
+ f" {negative_prompt_embeds.shape}."
537
+ )
538
+
539
+ # `prompt` needs more sophisticated handling when there are multiple
540
+ # conditionings.
541
+ if isinstance(self.controlnet, MultiControlNetModel):
542
+ if isinstance(prompt, list):
543
+ logger.warning(
544
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
545
+ " prompts. The conditionings will be fixed across the prompts."
546
+ )
547
+
548
+ # Check `image`
549
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
550
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
551
+ )
552
+ if (
553
+ isinstance(self.controlnet, ControlNetModel)
554
+ or is_compiled
555
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
556
+ ):
557
+ if not isinstance(image, list):
558
+ raise TypeError(f"For single controlnet, `image` must be of type `list` but got {type(image)}")
559
+ if len(image) != num_frames:
560
+ raise ValueError(f"Excepted image to have length {num_frames} but got {len(image)=}")
561
+ elif (
562
+ isinstance(self.controlnet, MultiControlNetModel)
563
+ or is_compiled
564
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
565
+ ):
566
+ if not isinstance(image, list) or not isinstance(image[0], list):
567
+ raise TypeError(f"For multiple controlnets: `image` must be type list of lists but got {type(image)=}")
568
+ if len(image[0]) != num_frames:
569
+ raise ValueError(f"Expected length of image sublist as {num_frames} but got {len(image[0])=}")
570
+ if any(len(img) != len(image[0]) for img in image):
571
+ raise ValueError("All conditioning frame batches for multicontrolnet must be same size")
572
+ else:
573
+ assert False
574
+
575
+ # Check `controlnet_conditioning_scale`
576
+ if (
577
+ isinstance(self.controlnet, ControlNetModel)
578
+ or is_compiled
579
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
580
+ ):
581
+ if not isinstance(controlnet_conditioning_scale, float):
582
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
583
+ elif (
584
+ isinstance(self.controlnet, MultiControlNetModel)
585
+ or is_compiled
586
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
587
+ ):
588
+ if isinstance(controlnet_conditioning_scale, list):
589
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
590
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
591
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
592
+ self.controlnet.nets
593
+ ):
594
+ raise ValueError(
595
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
596
+ " the same length as the number of controlnets"
597
+ )
598
+ else:
599
+ assert False
600
+
601
+ if not isinstance(control_guidance_start, (tuple, list)):
602
+ control_guidance_start = [control_guidance_start]
603
+
604
+ if not isinstance(control_guidance_end, (tuple, list)):
605
+ control_guidance_end = [control_guidance_end]
606
+
607
+ if len(control_guidance_start) != len(control_guidance_end):
608
+ raise ValueError(
609
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
610
+ )
611
+
612
+ if isinstance(self.controlnet, MultiControlNetModel):
613
+ if len(control_guidance_start) != len(self.controlnet.nets):
614
+ raise ValueError(
615
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
616
+ )
617
+
618
+ for start, end in zip(control_guidance_start, control_guidance_end):
619
+ if start >= end:
620
+ raise ValueError(
621
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
622
+ )
623
+ if start < 0.0:
624
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
625
+ if end > 1.0:
626
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
627
+
628
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
629
+ def check_image(self, image, prompt, prompt_embeds):
630
+ image_is_pil = isinstance(image, Image.Image)
631
+ image_is_tensor = isinstance(image, torch.Tensor)
632
+ image_is_np = isinstance(image, np.ndarray)
633
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], Image.Image)
634
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
635
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
636
+
637
+ if (
638
+ not image_is_pil
639
+ and not image_is_tensor
640
+ and not image_is_np
641
+ and not image_is_pil_list
642
+ and not image_is_tensor_list
643
+ and not image_is_np_list
644
+ ):
645
+ raise TypeError(
646
+ f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
647
+ )
648
+
649
+ if image_is_pil:
650
+ image_batch_size = 1
651
+ else:
652
+ image_batch_size = len(image)
653
+
654
+ if prompt is not None and isinstance(prompt, str):
655
+ prompt_batch_size = 1
656
+ elif prompt is not None and isinstance(prompt, list):
657
+ prompt_batch_size = len(prompt)
658
+ elif prompt_embeds is not None:
659
+ prompt_batch_size = prompt_embeds.shape[0]
660
+
661
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
662
+ raise ValueError(
663
+ f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
664
+ )
665
+
666
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
667
+ def prepare_latents(
668
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
669
+ ):
670
+ shape = (
671
+ batch_size,
672
+ num_channels_latents,
673
+ num_frames,
674
+ height // self.vae_scale_factor,
675
+ width // self.vae_scale_factor,
676
+ )
677
+ if isinstance(generator, list) and len(generator) != batch_size:
678
+ raise ValueError(
679
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
680
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
681
+ )
682
+
683
+ if latents is None:
684
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
685
+ else:
686
+ latents = latents.to(device)
687
+
688
+ # scale the initial noise by the standard deviation required by the scheduler
689
+ latents = latents * self.scheduler.init_noise_sigma
690
+ return latents
691
+
692
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
693
+ def prepare_image(
694
+ self,
695
+ image,
696
+ width,
697
+ height,
698
+ batch_size,
699
+ num_images_per_prompt,
700
+ device,
701
+ dtype,
702
+ do_classifier_free_guidance=False,
703
+ guess_mode=False,
704
+ ):
705
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
706
+ image_batch_size = image.shape[0]
707
+
708
+ if image_batch_size == 1:
709
+ repeat_by = batch_size
710
+ else:
711
+ # image batch size is the same as prompt batch size
712
+ repeat_by = num_images_per_prompt
713
+
714
+ image = image.repeat_interleave(repeat_by, dim=0)
715
+
716
+ image = image.to(device=device, dtype=dtype)
717
+
718
+ if do_classifier_free_guidance and not guess_mode:
719
+ image = torch.cat([image] * 2)
720
+
721
+ return image
722
+
723
+ @property
724
+ def guidance_scale(self):
725
+ return self._guidance_scale
726
+
727
+ @property
728
+ def clip_skip(self):
729
+ return self._clip_skip
730
+
731
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
732
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
733
+ # corresponds to doing no classifier free guidance.
734
+ @property
735
+ def do_classifier_free_guidance(self):
736
+ return self._guidance_scale > 1
737
+
738
+ @property
739
+ def cross_attention_kwargs(self):
740
+ return self._cross_attention_kwargs
741
+
742
+ @property
743
+ def num_timesteps(self):
744
+ return self._num_timesteps
745
+
746
+ @torch.no_grad()
747
+ def __call__(
748
+ self,
749
+ prompt: Union[str, List[str]] = None,
750
+ num_frames: Optional[int] = 16,
751
+ height: Optional[int] = None,
752
+ width: Optional[int] = None,
753
+ num_inference_steps: int = 50,
754
+ guidance_scale: float = 7.5,
755
+ negative_prompt: Optional[Union[str, List[str]]] = None,
756
+ num_videos_per_prompt: Optional[int] = 1,
757
+ eta: float = 0.0,
758
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
759
+ latents: Optional[torch.Tensor] = None,
760
+ prompt_embeds: Optional[torch.Tensor] = None,
761
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
762
+ ip_adapter_image: Optional[PipelineImageInput] = None,
763
+ ip_adapter_image_embeds: Optional[PipelineImageInput] = None,
764
+ conditioning_frames: Optional[List[PipelineImageInput]] = None,
765
+ output_type: Optional[str] = "pil",
766
+ return_dict: bool = True,
767
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
768
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
769
+ guess_mode: bool = False,
770
+ control_guidance_start: Union[float, List[float]] = 0.0,
771
+ control_guidance_end: Union[float, List[float]] = 1.0,
772
+ clip_skip: Optional[int] = None,
773
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
774
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
775
+ **kwargs,
776
+ ):
777
+ r"""
778
+ The call function to the pipeline for generation.
779
+
780
+ Args:
781
+ prompt (`str` or `List[str]`, *optional*):
782
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
783
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
784
+ The height in pixels of the generated video.
785
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
786
+ The width in pixels of the generated video.
787
+ num_frames (`int`, *optional*, defaults to 16):
788
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
789
+ amounts to 2 seconds of video.
790
+ num_inference_steps (`int`, *optional*, defaults to 50):
791
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
792
+ expense of slower inference.
793
+ guidance_scale (`float`, *optional*, defaults to 7.5):
794
+ A higher guidance scale value encourages the model to generate images closely linked to the text
795
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
796
+ negative_prompt (`str` or `List[str]`, *optional*):
797
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
798
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
799
+ eta (`float`, *optional*, defaults to 0.0):
800
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
801
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
802
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
803
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
804
+ generation deterministic.
805
+ latents (`torch.Tensor`, *optional*):
806
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
807
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
808
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
809
+ `(batch_size, num_channel, num_frames, height, width)`.
810
+ prompt_embeds (`torch.Tensor`, *optional*):
811
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
812
+ provided, text embeddings are generated from the `prompt` input argument.
813
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
814
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
815
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
816
+ ip_adapter_image (`PipelineImageInput`, *optional*):
817
+ Optional image input to work with IP Adapters.
818
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
819
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
820
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
821
+ if `do_classifier_free_guidance` is set to `True`.
822
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
823
+ conditioning_frames (`List[PipelineImageInput]`, *optional*):
824
+ The ControlNet input condition to provide guidance to the `unet` for generation. If multiple ControlNets
825
+ are specified, images must be passed as a list such that each element of the list can be correctly
826
+ batched for input to a single ControlNet.
827
+ output_type (`str`, *optional*, defaults to `"pil"`):
828
+ The output format of the generated video. Choose between `torch.Tensor`, `PIL.Image` or
829
+ `np.array`.
830
+ return_dict (`bool`, *optional*, defaults to `True`):
831
+ Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
832
+ of a plain tuple.
833
+ cross_attention_kwargs (`dict`, *optional*):
834
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
835
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
836
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
837
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
838
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
839
+ the corresponding scale as a list.
840
+ guess_mode (`bool`, *optional*, defaults to `False`):
841
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
842
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
843
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
844
+ The percentage of total steps at which the ControlNet starts applying.
845
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
846
+ The percentage of total steps at which the ControlNet stops applying.
847
+ clip_skip (`int`, *optional*):
848
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
849
+ the output of the pre-final layer will be used for computing the prompt embeddings.
850
+ callback_on_step_end (`Callable`, *optional*):
851
+ A function that calls at the end of each denoising steps during the inference. The function is called
852
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
853
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
854
+ `callback_on_step_end_tensor_inputs`.
855
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
856
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
857
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
858
+ `._callback_tensor_inputs` attribute of your pipeline class.
859
+
860
+ Examples:
861
+
862
+ Returns:
863
+ [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
864
+ If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
865
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
866
+ """
867
+
868
+ callback = kwargs.pop("callback", None)
869
+ callback_steps = kwargs.pop("callback_steps", None)
870
+
871
+ if callback is not None:
872
+ deprecate(
873
+ "callback",
874
+ "1.0.0",
875
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
876
+ )
877
+ if callback_steps is not None:
878
+ deprecate(
879
+ "callback_steps",
880
+ "1.0.0",
881
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
882
+ )
883
+
884
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
885
+
886
+ # align format for control guidance
887
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
888
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
889
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
890
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
891
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
892
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
893
+ control_guidance_start, control_guidance_end = (
894
+ mult * [control_guidance_start],
895
+ mult * [control_guidance_end],
896
+ )
897
+
898
+ # 0. Default height and width to unet
899
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
900
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
901
+
902
+ num_videos_per_prompt = 1
903
+
904
+ # 1. Check inputs. Raise error if not correct
905
+ self.check_inputs(
906
+ prompt=prompt,
907
+ height=height,
908
+ width=width,
909
+ num_frames=num_frames,
910
+ callback_steps=callback_steps,
911
+ negative_prompt=negative_prompt,
912
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
913
+ prompt_embeds=prompt_embeds,
914
+ negative_prompt_embeds=negative_prompt_embeds,
915
+ image=conditioning_frames,
916
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
917
+ control_guidance_start=control_guidance_start,
918
+ control_guidance_end=control_guidance_end,
919
+ )
920
+
921
+ self._guidance_scale = guidance_scale
922
+ self._clip_skip = clip_skip
923
+ self._cross_attention_kwargs = cross_attention_kwargs
924
+
925
+ # 2. Define call parameters
926
+ if prompt is not None and isinstance(prompt, str):
927
+ batch_size = 1
928
+ elif prompt is not None and isinstance(prompt, list):
929
+ batch_size = len(prompt)
930
+ else:
931
+ batch_size = prompt_embeds.shape[0]
932
+
933
+ device = self._execution_device
934
+
935
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
936
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
937
+
938
+ global_pool_conditions = (
939
+ controlnet.config.global_pool_conditions
940
+ if isinstance(controlnet, ControlNetModel)
941
+ else controlnet.nets[0].config.global_pool_conditions
942
+ )
943
+ guess_mode = guess_mode or global_pool_conditions
944
+
945
+ # 3. Encode input prompt
946
+ text_encoder_lora_scale = (
947
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
948
+ )
949
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
950
+ prompt,
951
+ device,
952
+ num_videos_per_prompt,
953
+ self.do_classifier_free_guidance,
954
+ negative_prompt,
955
+ prompt_embeds=prompt_embeds,
956
+ negative_prompt_embeds=negative_prompt_embeds,
957
+ lora_scale=text_encoder_lora_scale,
958
+ clip_skip=self.clip_skip,
959
+ )
960
+ # For classifier free guidance, we need to do two forward passes.
961
+ # Here we concatenate the unconditional and text embeddings into a single batch
962
+ # to avoid doing two forward passes
963
+ if self.do_classifier_free_guidance:
964
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
965
+
966
+ if ip_adapter_image is not None:
967
+ image_embeds = self.prepare_ip_adapter_image_embeds(
968
+ ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_videos_per_prompt
969
+ )
970
+
971
+ if isinstance(controlnet, ControlNetModel):
972
+ conditioning_frames = self.prepare_image(
973
+ image=conditioning_frames,
974
+ width=width,
975
+ height=height,
976
+ batch_size=batch_size * num_videos_per_prompt * num_frames,
977
+ num_images_per_prompt=num_videos_per_prompt,
978
+ device=device,
979
+ dtype=controlnet.dtype,
980
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
981
+ guess_mode=guess_mode,
982
+ )
983
+ elif isinstance(controlnet, MultiControlNetModel):
984
+ cond_prepared_frames = []
985
+ for frame_ in conditioning_frames:
986
+ prepared_frame = self.prepare_image(
987
+ image=frame_,
988
+ width=width,
989
+ height=height,
990
+ batch_size=batch_size * num_videos_per_prompt * num_frames,
991
+ num_images_per_prompt=num_videos_per_prompt,
992
+ device=device,
993
+ dtype=controlnet.dtype,
994
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
995
+ guess_mode=guess_mode,
996
+ )
997
+ cond_prepared_frames.append(prepared_frame)
998
+ conditioning_frames = cond_prepared_frames
999
+ else:
1000
+ assert False
1001
+
1002
+ # 4. Prepare timesteps
1003
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1004
+ timesteps = self.scheduler.timesteps
1005
+ self._num_timesteps = len(timesteps)
1006
+
1007
+ # 5. Prepare latent variables
1008
+ num_channels_latents = self.unet.config.in_channels
1009
+ latents = self.prepare_latents(
1010
+ batch_size * num_videos_per_prompt,
1011
+ num_channels_latents,
1012
+ num_frames,
1013
+ height,
1014
+ width,
1015
+ prompt_embeds.dtype,
1016
+ device,
1017
+ generator,
1018
+ latents,
1019
+ )
1020
+
1021
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1022
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1023
+
1024
+ # 7. Add image embeds for IP-Adapter
1025
+ added_cond_kwargs = (
1026
+ {"image_embeds": image_embeds}
1027
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
1028
+ else None
1029
+ )
1030
+
1031
+ # 7.1 Create tensor stating which controlnets to keep
1032
+ controlnet_keep = []
1033
+ for i in range(len(timesteps)):
1034
+ keeps = [
1035
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1036
+ for s, e in zip(control_guidance_start, control_guidance_end)
1037
+ ]
1038
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1039
+
1040
+ # 8. Denoising loop
1041
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1042
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1043
+ for i, t in enumerate(timesteps):
1044
+ # expand the latents if we are doing classifier free guidance
1045
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1046
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1047
+
1048
+ if guess_mode and self.do_classifier_free_guidance:
1049
+ # Infer ControlNet only for the conditional batch.
1050
+ control_model_input = latents
1051
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1052
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1053
+ else:
1054
+ control_model_input = latent_model_input
1055
+ controlnet_prompt_embeds = prompt_embeds
1056
+ controlnet_prompt_embeds = controlnet_prompt_embeds.repeat_interleave(num_frames, dim=0)
1057
+
1058
+ if isinstance(controlnet_keep[i], list):
1059
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1060
+ else:
1061
+ controlnet_cond_scale = controlnet_conditioning_scale
1062
+ if isinstance(controlnet_cond_scale, list):
1063
+ controlnet_cond_scale = controlnet_cond_scale[0]
1064
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1065
+
1066
+ control_model_input = torch.transpose(control_model_input, 1, 2)
1067
+ control_model_input = control_model_input.reshape(
1068
+ (-1, control_model_input.shape[2], control_model_input.shape[3], control_model_input.shape[4])
1069
+ )
1070
+
1071
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1072
+ control_model_input,
1073
+ t,
1074
+ encoder_hidden_states=controlnet_prompt_embeds,
1075
+ controlnet_cond=conditioning_frames,
1076
+ conditioning_scale=cond_scale,
1077
+ guess_mode=guess_mode,
1078
+ return_dict=False,
1079
+ )
1080
+
1081
+ # predict the noise residual
1082
+ noise_pred = self.unet(
1083
+ latent_model_input,
1084
+ t,
1085
+ encoder_hidden_states=prompt_embeds,
1086
+ cross_attention_kwargs=self.cross_attention_kwargs,
1087
+ added_cond_kwargs=added_cond_kwargs,
1088
+ down_block_additional_residuals=down_block_res_samples,
1089
+ mid_block_additional_residual=mid_block_res_sample,
1090
+ ).sample
1091
+
1092
+ # perform guidance
1093
+ if self.do_classifier_free_guidance:
1094
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1095
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1096
+
1097
+ # compute the previous noisy sample x_t -> x_t-1
1098
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
1099
+
1100
+ if callback_on_step_end is not None:
1101
+ callback_kwargs = {}
1102
+ for k in callback_on_step_end_tensor_inputs:
1103
+ callback_kwargs[k] = locals()[k]
1104
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1105
+
1106
+ latents = callback_outputs.pop("latents", latents)
1107
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1108
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1109
+
1110
+ # call the callback, if provided
1111
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1112
+ progress_bar.update()
1113
+ if callback is not None and i % callback_steps == 0:
1114
+ callback(i, t, latents)
1115
+
1116
+ # 9. Post processing
1117
+ if output_type == "latent":
1118
+ video = latents
1119
+ else:
1120
+ video_tensor = self.decode_latents(latents)
1121
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
1122
+
1123
+ # 10. Offload all models
1124
+ self.maybe_free_model_hooks()
1125
+
1126
+ if not return_dict:
1127
+ return (video,)
1128
+
1129
+ return AnimateDiffPipelineOutput(frames=video)
v0.32.0/pipeline_animatediff_img2video.py ADDED
@@ -0,0 +1,984 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # Note:
16
+ # This pipeline relies on a "hack" discovered by the community that allows
17
+ # the generation of videos given an input image with AnimateDiff. It works
18
+ # by creating a copy of the image `num_frames` times and progressively adding
19
+ # more noise to the image based on the strength and latent interpolation method.
20
+
21
+ import inspect
22
+ from types import FunctionType
23
+ from typing import Any, Callable, Dict, List, Optional, Union
24
+
25
+ import numpy as np
26
+ import torch
27
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
28
+
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.loaders import IPAdapterMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
31
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
32
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
33
+ from diffusers.models.unet_motion_model import MotionAdapter
34
+ from diffusers.pipelines.animatediff.pipeline_output import AnimateDiffPipelineOutput
35
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
36
+ from diffusers.schedulers import (
37
+ DDIMScheduler,
38
+ DPMSolverMultistepScheduler,
39
+ EulerAncestralDiscreteScheduler,
40
+ EulerDiscreteScheduler,
41
+ LMSDiscreteScheduler,
42
+ PNDMScheduler,
43
+ )
44
+ from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
45
+ from diffusers.utils.torch_utils import randn_tensor
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```py
53
+ >>> import torch
54
+ >>> from diffusers import MotionAdapter, DiffusionPipeline, DDIMScheduler
55
+ >>> from diffusers.utils import export_to_gif, load_image
56
+
57
+ >>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
58
+ >>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
59
+ >>> pipe = DiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE", motion_adapter=adapter, custom_pipeline="pipeline_animatediff_img2video").to("cuda")
60
+ >>> pipe.scheduler = pipe.scheduler = DDIMScheduler.from_pretrained(model_id, subfolder="scheduler", clip_sample=False, timestep_spacing="linspace", beta_schedule="linear", steps_offset=1)
61
+
62
+ >>> image = load_image("snail.png")
63
+ >>> output = pipe(image=image, prompt="A snail moving on the ground", strength=0.8, latent_interpolation_method="slerp")
64
+ >>> frames = output.frames[0]
65
+ >>> export_to_gif(frames, "animation.gif")
66
+ ```
67
+ """
68
+
69
+
70
+ def lerp(
71
+ v0: torch.Tensor,
72
+ v1: torch.Tensor,
73
+ t: Union[float, torch.Tensor],
74
+ ) -> torch.Tensor:
75
+ r"""
76
+ Linear Interpolation between two tensors.
77
+
78
+ Args:
79
+ v0 (`torch.Tensor`): First tensor.
80
+ v1 (`torch.Tensor`): Second tensor.
81
+ t: (`float` or `torch.Tensor`): Interpolation factor.
82
+ """
83
+ t_is_float = False
84
+ input_device = v0.device
85
+ v0 = v0.cpu().numpy()
86
+ v1 = v1.cpu().numpy()
87
+
88
+ if isinstance(t, torch.Tensor):
89
+ t = t.cpu().numpy()
90
+ else:
91
+ t_is_float = True
92
+ t = np.array([t], dtype=v0.dtype)
93
+
94
+ t = t[..., None]
95
+ v0 = v0[None, ...]
96
+ v1 = v1[None, ...]
97
+ v2 = (1 - t) * v0 + t * v1
98
+
99
+ if t_is_float and v0.ndim > 1:
100
+ assert v2.shape[0] == 1
101
+ v2 = np.squeeze(v2, axis=0)
102
+
103
+ v2 = torch.from_numpy(v2).to(input_device)
104
+ return v2
105
+
106
+
107
+ def slerp(
108
+ v0: torch.Tensor,
109
+ v1: torch.Tensor,
110
+ t: Union[float, torch.Tensor],
111
+ DOT_THRESHOLD: float = 0.9995,
112
+ ) -> torch.Tensor:
113
+ r"""
114
+ Spherical Linear Interpolation between two tensors.
115
+
116
+ Args:
117
+ v0 (`torch.Tensor`): First tensor.
118
+ v1 (`torch.Tensor`): Second tensor.
119
+ t: (`float` or `torch.Tensor`): Interpolation factor.
120
+ DOT_THRESHOLD (`float`):
121
+ Dot product threshold exceeding which linear interpolation will be used
122
+ because input tensors are close to parallel.
123
+ """
124
+ t_is_float = False
125
+ input_device = v0.device
126
+ v0 = v0.cpu().numpy()
127
+ v1 = v1.cpu().numpy()
128
+
129
+ if isinstance(t, torch.Tensor):
130
+ t = t.cpu().numpy()
131
+ else:
132
+ t_is_float = True
133
+ t = np.array([t], dtype=v0.dtype)
134
+
135
+ dot = np.sum(v0 * v1 / (np.linalg.norm(v0) * np.linalg.norm(v1)))
136
+
137
+ if np.abs(dot) > DOT_THRESHOLD:
138
+ # v0 and v1 are close to parallel, so use linear interpolation instead
139
+ v2 = lerp(v0, v1, t)
140
+ else:
141
+ theta_0 = np.arccos(dot)
142
+ sin_theta_0 = np.sin(theta_0)
143
+ theta_t = theta_0 * t
144
+ sin_theta_t = np.sin(theta_t)
145
+ s0 = np.sin(theta_0 - theta_t) / sin_theta_0
146
+ s1 = sin_theta_t / sin_theta_0
147
+ s0 = s0[..., None]
148
+ s1 = s1[..., None]
149
+ v0 = v0[None, ...]
150
+ v1 = v1[None, ...]
151
+ v2 = s0 * v0 + s1 * v1
152
+
153
+ if t_is_float and v0.ndim > 1:
154
+ assert v2.shape[0] == 1
155
+ v2 = np.squeeze(v2, axis=0)
156
+
157
+ v2 = torch.from_numpy(v2).to(input_device)
158
+ return v2
159
+
160
+
161
+ # Copied from diffusers.pipelines.animatediff.pipeline_animatediff.tensor2vid
162
+ def tensor2vid(video: torch.Tensor, processor, output_type="np"):
163
+ batch_size, channels, num_frames, height, width = video.shape
164
+ outputs = []
165
+ for batch_idx in range(batch_size):
166
+ batch_vid = video[batch_idx].permute(1, 0, 2, 3)
167
+ batch_output = processor.postprocess(batch_vid, output_type)
168
+
169
+ outputs.append(batch_output)
170
+
171
+ if output_type == "np":
172
+ outputs = np.stack(outputs)
173
+
174
+ elif output_type == "pt":
175
+ outputs = torch.stack(outputs)
176
+
177
+ elif not output_type == "pil":
178
+ raise ValueError(f"{output_type} does not exist. Please choose one of ['np', 'pt', 'pil']")
179
+
180
+ return outputs
181
+
182
+
183
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
184
+ def retrieve_latents(
185
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
186
+ ):
187
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
188
+ return encoder_output.latent_dist.sample(generator)
189
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
190
+ return encoder_output.latent_dist.mode()
191
+ elif hasattr(encoder_output, "latents"):
192
+ return encoder_output.latents
193
+ else:
194
+ raise AttributeError("Could not access latents of provided encoder_output")
195
+
196
+
197
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
198
+ def retrieve_timesteps(
199
+ scheduler,
200
+ num_inference_steps: Optional[int] = None,
201
+ device: Optional[Union[str, torch.device]] = None,
202
+ timesteps: Optional[List[int]] = None,
203
+ **kwargs,
204
+ ):
205
+ """
206
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
207
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
208
+
209
+ Args:
210
+ scheduler (`SchedulerMixin`):
211
+ The scheduler to get timesteps from.
212
+ num_inference_steps (`int`):
213
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
214
+ `timesteps` must be `None`.
215
+ device (`str` or `torch.device`, *optional*):
216
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
217
+ timesteps (`List[int]`, *optional*):
218
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
219
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
220
+ must be `None`.
221
+
222
+ Returns:
223
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
224
+ second element is the number of inference steps.
225
+ """
226
+ if timesteps is not None:
227
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
228
+ if not accepts_timesteps:
229
+ raise ValueError(
230
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
231
+ f" timestep schedules. Please check whether you are using the correct scheduler."
232
+ )
233
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
234
+ timesteps = scheduler.timesteps
235
+ num_inference_steps = len(timesteps)
236
+ else:
237
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
238
+ timesteps = scheduler.timesteps
239
+ return timesteps, num_inference_steps
240
+
241
+
242
+ class AnimateDiffImgToVideoPipeline(
243
+ DiffusionPipeline,
244
+ StableDiffusionMixin,
245
+ TextualInversionLoaderMixin,
246
+ IPAdapterMixin,
247
+ StableDiffusionLoraLoaderMixin,
248
+ ):
249
+ r"""
250
+ Pipeline for image-to-video generation.
251
+
252
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
253
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
254
+
255
+ The pipeline also inherits the following loading methods:
256
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
257
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
258
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
259
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
260
+
261
+ Args:
262
+ vae ([`AutoencoderKL`]):
263
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
264
+ text_encoder ([`CLIPTextModel`]):
265
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
266
+ tokenizer (`CLIPTokenizer`):
267
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
268
+ unet ([`UNet2DConditionModel`]):
269
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
270
+ motion_adapter ([`MotionAdapter`]):
271
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
272
+ scheduler ([`SchedulerMixin`]):
273
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
274
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
275
+ """
276
+
277
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
278
+ _optional_components = ["feature_extractor", "image_encoder"]
279
+
280
+ def __init__(
281
+ self,
282
+ vae: AutoencoderKL,
283
+ text_encoder: CLIPTextModel,
284
+ tokenizer: CLIPTokenizer,
285
+ unet: UNet2DConditionModel,
286
+ motion_adapter: MotionAdapter,
287
+ scheduler: Union[
288
+ DDIMScheduler,
289
+ PNDMScheduler,
290
+ LMSDiscreteScheduler,
291
+ EulerDiscreteScheduler,
292
+ EulerAncestralDiscreteScheduler,
293
+ DPMSolverMultistepScheduler,
294
+ ],
295
+ feature_extractor: CLIPImageProcessor = None,
296
+ image_encoder: CLIPVisionModelWithProjection = None,
297
+ ):
298
+ super().__init__()
299
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
300
+
301
+ self.register_modules(
302
+ vae=vae,
303
+ text_encoder=text_encoder,
304
+ tokenizer=tokenizer,
305
+ unet=unet,
306
+ motion_adapter=motion_adapter,
307
+ scheduler=scheduler,
308
+ feature_extractor=feature_extractor,
309
+ image_encoder=image_encoder,
310
+ )
311
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
312
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
313
+
314
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
315
+ def encode_prompt(
316
+ self,
317
+ prompt,
318
+ device,
319
+ num_images_per_prompt,
320
+ do_classifier_free_guidance,
321
+ negative_prompt=None,
322
+ prompt_embeds: Optional[torch.Tensor] = None,
323
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
324
+ lora_scale: Optional[float] = None,
325
+ clip_skip: Optional[int] = None,
326
+ ):
327
+ r"""
328
+ Encodes the prompt into text encoder hidden states.
329
+
330
+ Args:
331
+ prompt (`str` or `List[str]`, *optional*):
332
+ prompt to be encoded
333
+ device: (`torch.device`):
334
+ torch device
335
+ num_images_per_prompt (`int`):
336
+ number of images that should be generated per prompt
337
+ do_classifier_free_guidance (`bool`):
338
+ whether to use classifier free guidance or not
339
+ negative_prompt (`str` or `List[str]`, *optional*):
340
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
341
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
342
+ less than `1`).
343
+ prompt_embeds (`torch.Tensor`, *optional*):
344
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
345
+ provided, text embeddings will be generated from `prompt` input argument.
346
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
347
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
348
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
349
+ argument.
350
+ lora_scale (`float`, *optional*):
351
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
352
+ clip_skip (`int`, *optional*):
353
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
354
+ the output of the pre-final layer will be used for computing the prompt embeddings.
355
+ """
356
+ # set lora scale so that monkey patched LoRA
357
+ # function of text encoder can correctly access it
358
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
359
+ self._lora_scale = lora_scale
360
+
361
+ # dynamically adjust the LoRA scale
362
+ if not USE_PEFT_BACKEND:
363
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
364
+ else:
365
+ scale_lora_layers(self.text_encoder, lora_scale)
366
+
367
+ if prompt is not None and isinstance(prompt, str):
368
+ batch_size = 1
369
+ elif prompt is not None and isinstance(prompt, list):
370
+ batch_size = len(prompt)
371
+ else:
372
+ batch_size = prompt_embeds.shape[0]
373
+
374
+ if prompt_embeds is None:
375
+ # textual inversion: procecss multi-vector tokens if necessary
376
+ if isinstance(self, TextualInversionLoaderMixin):
377
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
378
+
379
+ text_inputs = self.tokenizer(
380
+ prompt,
381
+ padding="max_length",
382
+ max_length=self.tokenizer.model_max_length,
383
+ truncation=True,
384
+ return_tensors="pt",
385
+ )
386
+ text_input_ids = text_inputs.input_ids
387
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
388
+
389
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
390
+ text_input_ids, untruncated_ids
391
+ ):
392
+ removed_text = self.tokenizer.batch_decode(
393
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
394
+ )
395
+ logger.warning(
396
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
397
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
398
+ )
399
+
400
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
401
+ attention_mask = text_inputs.attention_mask.to(device)
402
+ else:
403
+ attention_mask = None
404
+
405
+ if clip_skip is None:
406
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
407
+ prompt_embeds = prompt_embeds[0]
408
+ else:
409
+ prompt_embeds = self.text_encoder(
410
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
411
+ )
412
+ # Access the `hidden_states` first, that contains a tuple of
413
+ # all the hidden states from the encoder layers. Then index into
414
+ # the tuple to access the hidden states from the desired layer.
415
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
416
+ # We also need to apply the final LayerNorm here to not mess with the
417
+ # representations. The `last_hidden_states` that we typically use for
418
+ # obtaining the final prompt representations passes through the LayerNorm
419
+ # layer.
420
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
421
+
422
+ if self.text_encoder is not None:
423
+ prompt_embeds_dtype = self.text_encoder.dtype
424
+ elif self.unet is not None:
425
+ prompt_embeds_dtype = self.unet.dtype
426
+ else:
427
+ prompt_embeds_dtype = prompt_embeds.dtype
428
+
429
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
430
+
431
+ bs_embed, seq_len, _ = prompt_embeds.shape
432
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
433
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
434
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
435
+
436
+ # get unconditional embeddings for classifier free guidance
437
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
438
+ uncond_tokens: List[str]
439
+ if negative_prompt is None:
440
+ uncond_tokens = [""] * batch_size
441
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
442
+ raise TypeError(
443
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
444
+ f" {type(prompt)}."
445
+ )
446
+ elif isinstance(negative_prompt, str):
447
+ uncond_tokens = [negative_prompt]
448
+ elif batch_size != len(negative_prompt):
449
+ raise ValueError(
450
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
451
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
452
+ " the batch size of `prompt`."
453
+ )
454
+ else:
455
+ uncond_tokens = negative_prompt
456
+
457
+ # textual inversion: procecss multi-vector tokens if necessary
458
+ if isinstance(self, TextualInversionLoaderMixin):
459
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
460
+
461
+ max_length = prompt_embeds.shape[1]
462
+ uncond_input = self.tokenizer(
463
+ uncond_tokens,
464
+ padding="max_length",
465
+ max_length=max_length,
466
+ truncation=True,
467
+ return_tensors="pt",
468
+ )
469
+
470
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
471
+ attention_mask = uncond_input.attention_mask.to(device)
472
+ else:
473
+ attention_mask = None
474
+
475
+ negative_prompt_embeds = self.text_encoder(
476
+ uncond_input.input_ids.to(device),
477
+ attention_mask=attention_mask,
478
+ )
479
+ negative_prompt_embeds = negative_prompt_embeds[0]
480
+
481
+ if do_classifier_free_guidance:
482
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
483
+ seq_len = negative_prompt_embeds.shape[1]
484
+
485
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
486
+
487
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
488
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
489
+
490
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
491
+ # Retrieve the original scale by scaling back the LoRA layers
492
+ unscale_lora_layers(self.text_encoder, lora_scale)
493
+
494
+ return prompt_embeds, negative_prompt_embeds
495
+
496
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
497
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
498
+ dtype = next(self.image_encoder.parameters()).dtype
499
+
500
+ if not isinstance(image, torch.Tensor):
501
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
502
+
503
+ image = image.to(device=device, dtype=dtype)
504
+ if output_hidden_states:
505
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
506
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
507
+ uncond_image_enc_hidden_states = self.image_encoder(
508
+ torch.zeros_like(image), output_hidden_states=True
509
+ ).hidden_states[-2]
510
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
511
+ num_images_per_prompt, dim=0
512
+ )
513
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
514
+ else:
515
+ image_embeds = self.image_encoder(image).image_embeds
516
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
517
+ uncond_image_embeds = torch.zeros_like(image_embeds)
518
+
519
+ return image_embeds, uncond_image_embeds
520
+
521
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
522
+ def prepare_ip_adapter_image_embeds(
523
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
524
+ ):
525
+ if ip_adapter_image_embeds is None:
526
+ if not isinstance(ip_adapter_image, list):
527
+ ip_adapter_image = [ip_adapter_image]
528
+
529
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
530
+ raise ValueError(
531
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
532
+ )
533
+
534
+ image_embeds = []
535
+ for single_ip_adapter_image, image_proj_layer in zip(
536
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
537
+ ):
538
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
539
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
540
+ single_ip_adapter_image, device, 1, output_hidden_state
541
+ )
542
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
543
+ single_negative_image_embeds = torch.stack(
544
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
545
+ )
546
+
547
+ if self.do_classifier_free_guidance:
548
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
549
+ single_image_embeds = single_image_embeds.to(device)
550
+
551
+ image_embeds.append(single_image_embeds)
552
+ else:
553
+ image_embeds = ip_adapter_image_embeds
554
+ return image_embeds
555
+
556
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
557
+ def decode_latents(self, latents):
558
+ latents = 1 / self.vae.config.scaling_factor * latents
559
+
560
+ batch_size, channels, num_frames, height, width = latents.shape
561
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
562
+
563
+ image = self.vae.decode(latents).sample
564
+ video = (
565
+ image[None, :]
566
+ .reshape(
567
+ (
568
+ batch_size,
569
+ num_frames,
570
+ -1,
571
+ )
572
+ + image.shape[2:]
573
+ )
574
+ .permute(0, 2, 1, 3, 4)
575
+ )
576
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
577
+ video = video.float()
578
+ return video
579
+
580
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
581
+ def prepare_extra_step_kwargs(self, generator, eta):
582
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
583
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
584
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
585
+ # and should be between [0, 1]
586
+
587
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
588
+ extra_step_kwargs = {}
589
+ if accepts_eta:
590
+ extra_step_kwargs["eta"] = eta
591
+
592
+ # check if the scheduler accepts generator
593
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
594
+ if accepts_generator:
595
+ extra_step_kwargs["generator"] = generator
596
+ return extra_step_kwargs
597
+
598
+ def check_inputs(
599
+ self,
600
+ prompt,
601
+ height,
602
+ width,
603
+ callback_steps,
604
+ negative_prompt=None,
605
+ prompt_embeds=None,
606
+ negative_prompt_embeds=None,
607
+ callback_on_step_end_tensor_inputs=None,
608
+ latent_interpolation_method=None,
609
+ ):
610
+ if height % 8 != 0 or width % 8 != 0:
611
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
612
+
613
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
614
+ raise ValueError(
615
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
616
+ f" {type(callback_steps)}."
617
+ )
618
+ if callback_on_step_end_tensor_inputs is not None and not all(
619
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
620
+ ):
621
+ raise ValueError(
622
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
623
+ )
624
+
625
+ if prompt is not None and prompt_embeds is not None:
626
+ raise ValueError(
627
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
628
+ " only forward one of the two."
629
+ )
630
+ elif prompt is None and prompt_embeds is None:
631
+ raise ValueError(
632
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
633
+ )
634
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
635
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
636
+
637
+ if negative_prompt is not None and negative_prompt_embeds is not None:
638
+ raise ValueError(
639
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
640
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
641
+ )
642
+
643
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
644
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
645
+ raise ValueError(
646
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
647
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
648
+ f" {negative_prompt_embeds.shape}."
649
+ )
650
+
651
+ if latent_interpolation_method is not None:
652
+ if latent_interpolation_method not in ["lerp", "slerp"] and not isinstance(
653
+ latent_interpolation_method, FunctionType
654
+ ):
655
+ raise ValueError(
656
+ "`latent_interpolation_method` must be one of `lerp`, `slerp` or a Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]"
657
+ )
658
+
659
+ def prepare_latents(
660
+ self,
661
+ image,
662
+ strength,
663
+ batch_size,
664
+ num_channels_latents,
665
+ num_frames,
666
+ height,
667
+ width,
668
+ dtype,
669
+ device,
670
+ generator,
671
+ latents=None,
672
+ latent_interpolation_method="slerp",
673
+ ):
674
+ shape = (
675
+ batch_size,
676
+ num_channels_latents,
677
+ num_frames,
678
+ height // self.vae_scale_factor,
679
+ width // self.vae_scale_factor,
680
+ )
681
+
682
+ if latents is None:
683
+ image = image.to(device=device, dtype=dtype)
684
+
685
+ if image.shape[1] == 4:
686
+ latents = image
687
+ else:
688
+ # make sure the VAE is in float32 mode, as it overflows in float16
689
+ if self.vae.config.force_upcast:
690
+ image = image.float()
691
+ self.vae.to(dtype=torch.float32)
692
+
693
+ if isinstance(generator, list):
694
+ if len(generator) != batch_size:
695
+ raise ValueError(
696
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
697
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
698
+ )
699
+
700
+ init_latents = [
701
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
702
+ for i in range(batch_size)
703
+ ]
704
+ init_latents = torch.cat(init_latents, dim=0)
705
+ else:
706
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
707
+
708
+ if self.vae.config.force_upcast:
709
+ self.vae.to(dtype)
710
+
711
+ init_latents = init_latents.to(dtype)
712
+ init_latents = self.vae.config.scaling_factor * init_latents
713
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
714
+ latents = latents * self.scheduler.init_noise_sigma
715
+
716
+ if latent_interpolation_method == "lerp":
717
+
718
+ def latent_cls(v0, v1, index):
719
+ return lerp(v0, v1, index / num_frames * (1 - strength))
720
+ elif latent_interpolation_method == "slerp":
721
+
722
+ def latent_cls(v0, v1, index):
723
+ return slerp(v0, v1, index / num_frames * (1 - strength))
724
+ else:
725
+ latent_cls = latent_interpolation_method
726
+
727
+ for i in range(num_frames):
728
+ latents[:, :, i, :, :] = latent_cls(latents[:, :, i, :, :], init_latents, i)
729
+ else:
730
+ if shape != latents.shape:
731
+ # [B, C, F, H, W]
732
+ raise ValueError(f"`latents` expected to have {shape=}, but found {latents.shape=}")
733
+ latents = latents.to(device, dtype=dtype)
734
+
735
+ return latents
736
+
737
+ @torch.no_grad()
738
+ def __call__(
739
+ self,
740
+ image: PipelineImageInput,
741
+ prompt: Optional[Union[str, List[str]]] = None,
742
+ height: Optional[int] = None,
743
+ width: Optional[int] = None,
744
+ num_frames: int = 16,
745
+ num_inference_steps: int = 50,
746
+ timesteps: Optional[List[int]] = None,
747
+ guidance_scale: float = 7.5,
748
+ strength: float = 0.8,
749
+ negative_prompt: Optional[Union[str, List[str]]] = None,
750
+ num_videos_per_prompt: Optional[int] = 1,
751
+ eta: float = 0.0,
752
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
753
+ latents: Optional[torch.Tensor] = None,
754
+ prompt_embeds: Optional[torch.Tensor] = None,
755
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
756
+ ip_adapter_image: Optional[PipelineImageInput] = None,
757
+ ip_adapter_image_embeds: Optional[PipelineImageInput] = None,
758
+ output_type: Optional[str] = "pil",
759
+ return_dict: bool = True,
760
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
761
+ callback_steps: Optional[int] = 1,
762
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
763
+ clip_skip: Optional[int] = None,
764
+ latent_interpolation_method: Union[str, Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]] = "slerp",
765
+ ):
766
+ r"""
767
+ The call function to the pipeline for generation.
768
+
769
+ Args:
770
+ image (`PipelineImageInput`):
771
+ The input image to condition the generation on.
772
+ prompt (`str` or `List[str]`, *optional*):
773
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
774
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
775
+ The height in pixels of the generated video.
776
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
777
+ The width in pixels of the generated video.
778
+ num_frames (`int`, *optional*, defaults to 16):
779
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
780
+ amounts to 2 seconds of video.
781
+ num_inference_steps (`int`, *optional*, defaults to 50):
782
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
783
+ expense of slower inference.
784
+ strength (`float`, *optional*, defaults to 0.8):
785
+ Higher strength leads to more differences between original image and generated video.
786
+ guidance_scale (`float`, *optional*, defaults to 7.5):
787
+ A higher guidance scale value encourages the model to generate images closely linked to the text
788
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
789
+ negative_prompt (`str` or `List[str]`, *optional*):
790
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
791
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
792
+ eta (`float`, *optional*, defaults to 0.0):
793
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
794
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
795
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
796
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
797
+ generation deterministic.
798
+ latents (`torch.Tensor`, *optional*):
799
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
800
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
801
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
802
+ `(batch_size, num_channel, num_frames, height, width)`.
803
+ prompt_embeds (`torch.Tensor`, *optional*):
804
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
805
+ provided, text embeddings are generated from the `prompt` input argument.
806
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
807
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
808
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
809
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
810
+ Optional image input to work with IP Adapters.
811
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
812
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
813
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
814
+ if `do_classifier_free_guidance` is set to `True`.
815
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
816
+ output_type (`str`, *optional*, defaults to `"pil"`):
817
+ The output format of the generated video. Choose between `torch.Tensor`, `PIL.Image` or
818
+ `np.array`.
819
+ return_dict (`bool`, *optional*, defaults to `True`):
820
+ Whether or not to return a [`AnimateDiffImgToVideoPipelineOutput`] instead
821
+ of a plain tuple.
822
+ callback (`Callable`, *optional*):
823
+ A function that calls every `callback_steps` steps during inference. The function is called with the
824
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
825
+ callback_steps (`int`, *optional*, defaults to 1):
826
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
827
+ every step.
828
+ cross_attention_kwargs (`dict`, *optional*):
829
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
830
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
831
+ clip_skip (`int`, *optional*):
832
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
833
+ the output of the pre-final layer will be used for computing the prompt embeddings.
834
+ latent_interpolation_method (`str` or `Callable[[torch.Tensor, torch.Tensor, int], torch.Tensor]]`, *optional*):
835
+ Must be one of "lerp", "slerp" or a callable that takes in a random noisy latent, image latent and a frame index
836
+ as input and returns an initial latent for sampling.
837
+ Examples:
838
+
839
+ Returns:
840
+ [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
841
+ If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
842
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
843
+ """
844
+ # 0. Default height and width to unet
845
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
846
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
847
+
848
+ num_videos_per_prompt = 1
849
+
850
+ # 1. Check inputs. Raise error if not correct
851
+ self.check_inputs(
852
+ prompt=prompt,
853
+ height=height,
854
+ width=width,
855
+ callback_steps=callback_steps,
856
+ negative_prompt=negative_prompt,
857
+ prompt_embeds=prompt_embeds,
858
+ negative_prompt_embeds=negative_prompt_embeds,
859
+ latent_interpolation_method=latent_interpolation_method,
860
+ )
861
+
862
+ # 2. Define call parameters
863
+ if prompt is not None and isinstance(prompt, str):
864
+ batch_size = 1
865
+ elif prompt is not None and isinstance(prompt, list):
866
+ batch_size = len(prompt)
867
+ else:
868
+ batch_size = prompt_embeds.shape[0]
869
+
870
+ device = self._execution_device
871
+
872
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
873
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
874
+ # corresponds to doing no classifier free guidance.
875
+ do_classifier_free_guidance = guidance_scale > 1.0
876
+
877
+ # 3. Encode input prompt
878
+ text_encoder_lora_scale = (
879
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
880
+ )
881
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
882
+ prompt,
883
+ device,
884
+ num_videos_per_prompt,
885
+ do_classifier_free_guidance,
886
+ negative_prompt,
887
+ prompt_embeds=prompt_embeds,
888
+ negative_prompt_embeds=negative_prompt_embeds,
889
+ lora_scale=text_encoder_lora_scale,
890
+ clip_skip=clip_skip,
891
+ )
892
+
893
+ # For classifier free guidance, we need to do two forward passes.
894
+ # Here we concatenate the unconditional and text embeddings into a single batch
895
+ # to avoid doing two forward passes
896
+ if do_classifier_free_guidance:
897
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
898
+
899
+ if ip_adapter_image is not None:
900
+ image_embeds = self.prepare_ip_adapter_image_embeds(
901
+ ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_videos_per_prompt
902
+ )
903
+
904
+ # 4. Preprocess image
905
+ image = self.image_processor.preprocess(image, height=height, width=width)
906
+
907
+ # 5. Prepare timesteps
908
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
909
+
910
+ # 6. Prepare latent variables
911
+ num_channels_latents = self.unet.config.in_channels
912
+ latents = self.prepare_latents(
913
+ image=image,
914
+ strength=strength,
915
+ batch_size=batch_size * num_videos_per_prompt,
916
+ num_channels_latents=num_channels_latents,
917
+ num_frames=num_frames,
918
+ height=height,
919
+ width=width,
920
+ dtype=prompt_embeds.dtype,
921
+ device=device,
922
+ generator=generator,
923
+ latents=latents,
924
+ latent_interpolation_method=latent_interpolation_method,
925
+ )
926
+
927
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
928
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
929
+
930
+ # 8. Add image embeds for IP-Adapter
931
+ added_cond_kwargs = (
932
+ {"image_embeds": image_embeds}
933
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
934
+ else None
935
+ )
936
+
937
+ # 9. Denoising loop
938
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
939
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
940
+ for i, t in enumerate(timesteps):
941
+ # expand the latents if we are doing classifier free guidance
942
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
943
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
944
+
945
+ # predict the noise residual
946
+ noise_pred = self.unet(
947
+ latent_model_input,
948
+ t,
949
+ encoder_hidden_states=prompt_embeds,
950
+ cross_attention_kwargs=cross_attention_kwargs,
951
+ added_cond_kwargs=added_cond_kwargs,
952
+ ).sample
953
+
954
+ # perform guidance
955
+ if do_classifier_free_guidance:
956
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
957
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
958
+
959
+ # compute the previous noisy sample x_t -> x_t-1
960
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
961
+
962
+ # call the callback, if provided
963
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
964
+ progress_bar.update()
965
+ if callback is not None and i % callback_steps == 0:
966
+ callback(i, t, latents)
967
+
968
+ if output_type == "latent":
969
+ return AnimateDiffPipelineOutput(frames=latents)
970
+
971
+ # 10. Post-processing
972
+ if output_type == "latent":
973
+ video = latents
974
+ else:
975
+ video_tensor = self.decode_latents(latents)
976
+ video = tensor2vid(video_tensor, self.image_processor, output_type=output_type)
977
+
978
+ # 11. Offload all models
979
+ self.maybe_free_model_hooks()
980
+
981
+ if not return_dict:
982
+ return (video,)
983
+
984
+ return AnimateDiffPipelineOutput(frames=video)
v0.32.0/pipeline_animatediff_ipex.py ADDED
@@ -0,0 +1,1002 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import intel_extension_for_pytorch as ipex
19
+ import torch
20
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
21
+
22
+ from diffusers.image_processor import PipelineImageInput
23
+ from diffusers.loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
24
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel, UNetMotionModel
25
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
26
+ from diffusers.models.unets.unet_motion_model import MotionAdapter
27
+ from diffusers.pipelines.animatediff.pipeline_output import AnimateDiffPipelineOutput
28
+ from diffusers.pipelines.free_init_utils import FreeInitMixin
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
30
+ from diffusers.schedulers import (
31
+ DDIMScheduler,
32
+ DPMSolverMultistepScheduler,
33
+ EulerAncestralDiscreteScheduler,
34
+ EulerDiscreteScheduler,
35
+ LMSDiscreteScheduler,
36
+ PNDMScheduler,
37
+ )
38
+ from diffusers.utils import (
39
+ USE_PEFT_BACKEND,
40
+ logging,
41
+ replace_example_docstring,
42
+ scale_lora_layers,
43
+ unscale_lora_layers,
44
+ )
45
+ from diffusers.utils.torch_utils import randn_tensor
46
+ from diffusers.video_processor import VideoProcessor
47
+
48
+
49
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
50
+
51
+ EXAMPLE_DOC_STRING = """
52
+ Examples:
53
+ ```py
54
+ >>> import torch
55
+ >>> from diffusers import MotionAdapter, AnimateDiffPipelineIpex, EulerDiscreteScheduler
56
+ >>> from diffusers.utils import export_to_gif
57
+ >>> from safetensors.torch import load_file
58
+
59
+ >>> device = "cpu"
60
+ >>> dtype = torch.float32
61
+
62
+ >>> # ByteDance/AnimateDiff-Lightning, a distilled version of AnimateDiff SD1.5 v2,
63
+ >>> # a lightning-fast text-to-video generation model which can generate videos
64
+ >>> # more than ten times faster than the original AnimateDiff.
65
+ >>> step = 8 # Options: [1,2,4,8]
66
+ >>> repo = "ByteDance/AnimateDiff-Lightning"
67
+ >>> ckpt = f"animatediff_lightning_{step}step_diffusers.safetensors"
68
+ >>> base = "emilianJR/epiCRealism" # Choose to your favorite base model.
69
+
70
+ >>> adapter = MotionAdapter().to(device, dtype)
71
+ >>> adapter.load_state_dict(load_file(hf_hub_download(repo ,ckpt), device=device))
72
+
73
+ >>> pipe = AnimateDiffPipelineIpex.from_pretrained(base, motion_adapter=adapter, torch_dtype=dtype).to(device)
74
+ >>> pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config, timestep_spacing="trailing", beta_schedule="linear")
75
+
76
+ >>> # For Float32
77
+ >>> pipe.prepare_for_ipex(torch.float32, prompt = "A girl smiling")
78
+ >>> # For BFloat16
79
+ >>> pipe.prepare_for_ipex(torch.bfloat16, prompt = "A girl smiling")
80
+
81
+ >>> # For Float32
82
+ >>> output = pipe(prompt = "A girl smiling", guidance_scale=1.0, num_inference_steps = step)
83
+ >>> # For BFloat16
84
+ >>> with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloat16):
85
+ >>> output = pipe(prompt = "A girl smiling", guidance_scale=1.0, num_inference_steps = step)
86
+
87
+ >>> frames = output.frames[0]
88
+ >>> export_to_gif(frames, "animation.gif")
89
+ ```
90
+ """
91
+
92
+
93
+ class AnimateDiffPipelineIpex(
94
+ DiffusionPipeline,
95
+ StableDiffusionMixin,
96
+ TextualInversionLoaderMixin,
97
+ IPAdapterMixin,
98
+ LoraLoaderMixin,
99
+ FreeInitMixin,
100
+ ):
101
+ r"""
102
+ Pipeline for text-to-video generation.
103
+
104
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
105
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
106
+
107
+ The pipeline also inherits the following loading methods:
108
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
109
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
110
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
111
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
112
+
113
+ Args:
114
+ vae ([`AutoencoderKL`]):
115
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
116
+ text_encoder ([`CLIPTextModel`]):
117
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
118
+ tokenizer (`CLIPTokenizer`):
119
+ A [`~transformers.CLIPTokenizer`] to tokenize text.
120
+ unet ([`UNet2DConditionModel`]):
121
+ A [`UNet2DConditionModel`] used to create a UNetMotionModel to denoise the encoded video latents.
122
+ motion_adapter ([`MotionAdapter`]):
123
+ A [`MotionAdapter`] to be used in combination with `unet` to denoise the encoded video latents.
124
+ scheduler ([`SchedulerMixin`]):
125
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
126
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
127
+ """
128
+
129
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
130
+ _optional_components = ["feature_extractor", "image_encoder", "motion_adapter"]
131
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
132
+
133
+ def __init__(
134
+ self,
135
+ vae: AutoencoderKL,
136
+ text_encoder: CLIPTextModel,
137
+ tokenizer: CLIPTokenizer,
138
+ unet: Union[UNet2DConditionModel, UNetMotionModel],
139
+ motion_adapter: MotionAdapter,
140
+ scheduler: Union[
141
+ DDIMScheduler,
142
+ PNDMScheduler,
143
+ LMSDiscreteScheduler,
144
+ EulerDiscreteScheduler,
145
+ EulerAncestralDiscreteScheduler,
146
+ DPMSolverMultistepScheduler,
147
+ ],
148
+ feature_extractor: CLIPImageProcessor = None,
149
+ image_encoder: CLIPVisionModelWithProjection = None,
150
+ ):
151
+ super().__init__()
152
+ if isinstance(unet, UNet2DConditionModel):
153
+ unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
154
+
155
+ self.register_modules(
156
+ vae=vae,
157
+ text_encoder=text_encoder,
158
+ tokenizer=tokenizer,
159
+ unet=unet,
160
+ motion_adapter=motion_adapter,
161
+ scheduler=scheduler,
162
+ feature_extractor=feature_extractor,
163
+ image_encoder=image_encoder,
164
+ )
165
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
166
+ self.video_processor = VideoProcessor(do_resize=False, vae_scale_factor=self.vae_scale_factor)
167
+
168
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt with num_images_per_prompt -> num_videos_per_prompt
169
+ def encode_prompt(
170
+ self,
171
+ prompt,
172
+ device,
173
+ num_images_per_prompt,
174
+ do_classifier_free_guidance,
175
+ negative_prompt=None,
176
+ prompt_embeds: Optional[torch.Tensor] = None,
177
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
178
+ lora_scale: Optional[float] = None,
179
+ clip_skip: Optional[int] = None,
180
+ ):
181
+ r"""
182
+ Encodes the prompt into text encoder hidden states.
183
+
184
+ Args:
185
+ prompt (`str` or `List[str]`, *optional*):
186
+ prompt to be encoded
187
+ device: (`torch.device`):
188
+ torch device
189
+ num_images_per_prompt (`int`):
190
+ number of images that should be generated per prompt
191
+ do_classifier_free_guidance (`bool`):
192
+ whether to use classifier free guidance or not
193
+ negative_prompt (`str` or `List[str]`, *optional*):
194
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
195
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
196
+ less than `1`).
197
+ prompt_embeds (`torch.Tensor`, *optional*):
198
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
199
+ provided, text embeddings will be generated from `prompt` input argument.
200
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
201
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
202
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
203
+ argument.
204
+ lora_scale (`float`, *optional*):
205
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
206
+ clip_skip (`int`, *optional*):
207
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
208
+ the output of the pre-final layer will be used for computing the prompt embeddings.
209
+ """
210
+ # set lora scale so that monkey patched LoRA
211
+ # function of text encoder can correctly access it
212
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
213
+ self._lora_scale = lora_scale
214
+
215
+ # dynamically adjust the LoRA scale
216
+ if not USE_PEFT_BACKEND:
217
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
218
+ else:
219
+ scale_lora_layers(self.text_encoder, lora_scale)
220
+
221
+ if prompt is not None and isinstance(prompt, str):
222
+ batch_size = 1
223
+ elif prompt is not None and isinstance(prompt, list):
224
+ batch_size = len(prompt)
225
+ else:
226
+ batch_size = prompt_embeds.shape[0]
227
+
228
+ if prompt_embeds is None:
229
+ # textual inversion: process multi-vector tokens if necessary
230
+ if isinstance(self, TextualInversionLoaderMixin):
231
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
232
+
233
+ text_inputs = self.tokenizer(
234
+ prompt,
235
+ padding="max_length",
236
+ max_length=self.tokenizer.model_max_length,
237
+ truncation=True,
238
+ return_tensors="pt",
239
+ )
240
+ text_input_ids = text_inputs.input_ids
241
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
242
+
243
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
244
+ text_input_ids, untruncated_ids
245
+ ):
246
+ removed_text = self.tokenizer.batch_decode(
247
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
248
+ )
249
+ logger.warning(
250
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
251
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
252
+ )
253
+
254
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
255
+ attention_mask = text_inputs.attention_mask.to(device)
256
+ else:
257
+ attention_mask = None
258
+
259
+ if clip_skip is None:
260
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
261
+ prompt_embeds = prompt_embeds[0]
262
+ else:
263
+ prompt_embeds = self.text_encoder(
264
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
265
+ )
266
+ # Access the `hidden_states` first, that contains a tuple of
267
+ # all the hidden states from the encoder layers. Then index into
268
+ # the tuple to access the hidden states from the desired layer.
269
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
270
+ # We also need to apply the final LayerNorm here to not mess with the
271
+ # representations. The `last_hidden_states` that we typically use for
272
+ # obtaining the final prompt representations passes through the LayerNorm
273
+ # layer.
274
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
275
+
276
+ if self.text_encoder is not None:
277
+ prompt_embeds_dtype = self.text_encoder.dtype
278
+ elif self.unet is not None:
279
+ prompt_embeds_dtype = self.unet.dtype
280
+ else:
281
+ prompt_embeds_dtype = prompt_embeds.dtype
282
+
283
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
284
+
285
+ bs_embed, seq_len, _ = prompt_embeds.shape
286
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
287
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
288
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
289
+
290
+ # get unconditional embeddings for classifier free guidance
291
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
292
+ uncond_tokens: List[str]
293
+ if negative_prompt is None:
294
+ uncond_tokens = [""] * batch_size
295
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
296
+ raise TypeError(
297
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
298
+ f" {type(prompt)}."
299
+ )
300
+ elif isinstance(negative_prompt, str):
301
+ uncond_tokens = [negative_prompt]
302
+ elif batch_size != len(negative_prompt):
303
+ raise ValueError(
304
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
305
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
306
+ " the batch size of `prompt`."
307
+ )
308
+ else:
309
+ uncond_tokens = negative_prompt
310
+
311
+ # textual inversion: process multi-vector tokens if necessary
312
+ if isinstance(self, TextualInversionLoaderMixin):
313
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
314
+
315
+ max_length = prompt_embeds.shape[1]
316
+ uncond_input = self.tokenizer(
317
+ uncond_tokens,
318
+ padding="max_length",
319
+ max_length=max_length,
320
+ truncation=True,
321
+ return_tensors="pt",
322
+ )
323
+
324
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
325
+ attention_mask = uncond_input.attention_mask.to(device)
326
+ else:
327
+ attention_mask = None
328
+
329
+ negative_prompt_embeds = self.text_encoder(
330
+ uncond_input.input_ids.to(device),
331
+ attention_mask=attention_mask,
332
+ )
333
+ negative_prompt_embeds = negative_prompt_embeds[0]
334
+
335
+ if do_classifier_free_guidance:
336
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
337
+ seq_len = negative_prompt_embeds.shape[1]
338
+
339
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
340
+
341
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
342
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
343
+
344
+ if self.text_encoder is not None:
345
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
346
+ # Retrieve the original scale by scaling back the LoRA layers
347
+ unscale_lora_layers(self.text_encoder, lora_scale)
348
+
349
+ return prompt_embeds, negative_prompt_embeds
350
+
351
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
352
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
353
+ dtype = next(self.image_encoder.parameters()).dtype
354
+
355
+ if not isinstance(image, torch.Tensor):
356
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
357
+
358
+ image = image.to(device=device, dtype=dtype)
359
+ if output_hidden_states:
360
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
361
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
362
+ uncond_image_enc_hidden_states = self.image_encoder(
363
+ torch.zeros_like(image), output_hidden_states=True
364
+ ).hidden_states[-2]
365
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
366
+ num_images_per_prompt, dim=0
367
+ )
368
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
369
+ else:
370
+ image_embeds = self.image_encoder(image).image_embeds
371
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
372
+ uncond_image_embeds = torch.zeros_like(image_embeds)
373
+
374
+ return image_embeds, uncond_image_embeds
375
+
376
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
377
+ def prepare_ip_adapter_image_embeds(
378
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
379
+ ):
380
+ if ip_adapter_image_embeds is None:
381
+ if not isinstance(ip_adapter_image, list):
382
+ ip_adapter_image = [ip_adapter_image]
383
+
384
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
385
+ raise ValueError(
386
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
387
+ )
388
+
389
+ image_embeds = []
390
+ for single_ip_adapter_image, image_proj_layer in zip(
391
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
392
+ ):
393
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
394
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
395
+ single_ip_adapter_image, device, 1, output_hidden_state
396
+ )
397
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
398
+ single_negative_image_embeds = torch.stack(
399
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
400
+ )
401
+
402
+ if do_classifier_free_guidance:
403
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
404
+ single_image_embeds = single_image_embeds.to(device)
405
+
406
+ image_embeds.append(single_image_embeds)
407
+ else:
408
+ repeat_dims = [1]
409
+ image_embeds = []
410
+ for single_image_embeds in ip_adapter_image_embeds:
411
+ if do_classifier_free_guidance:
412
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
413
+ single_image_embeds = single_image_embeds.repeat(
414
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
415
+ )
416
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
417
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
418
+ )
419
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
420
+ else:
421
+ single_image_embeds = single_image_embeds.repeat(
422
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
423
+ )
424
+ image_embeds.append(single_image_embeds)
425
+
426
+ return image_embeds
427
+
428
+ # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
429
+ def decode_latents(self, latents):
430
+ latents = 1 / self.vae.config.scaling_factor * latents
431
+
432
+ batch_size, channels, num_frames, height, width = latents.shape
433
+ latents = latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
434
+
435
+ image = self.vae.decode(latents).sample
436
+ video = image[None, :].reshape((batch_size, num_frames, -1) + image.shape[2:]).permute(0, 2, 1, 3, 4)
437
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
438
+ video = video.float()
439
+ return video
440
+
441
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
442
+ def prepare_extra_step_kwargs(self, generator, eta):
443
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
444
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
445
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
446
+ # and should be between [0, 1]
447
+
448
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
449
+ extra_step_kwargs = {}
450
+ if accepts_eta:
451
+ extra_step_kwargs["eta"] = eta
452
+
453
+ # check if the scheduler accepts generator
454
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
455
+ if accepts_generator:
456
+ extra_step_kwargs["generator"] = generator
457
+ return extra_step_kwargs
458
+
459
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
460
+ def check_inputs(
461
+ self,
462
+ prompt,
463
+ height,
464
+ width,
465
+ negative_prompt=None,
466
+ prompt_embeds=None,
467
+ negative_prompt_embeds=None,
468
+ ip_adapter_image=None,
469
+ ip_adapter_image_embeds=None,
470
+ callback_on_step_end_tensor_inputs=None,
471
+ ):
472
+ if height % 8 != 0 or width % 8 != 0:
473
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
474
+
475
+ if callback_on_step_end_tensor_inputs is not None and not all(
476
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
477
+ ):
478
+ raise ValueError(
479
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
480
+ )
481
+
482
+ if prompt is not None and prompt_embeds is not None:
483
+ raise ValueError(
484
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
485
+ " only forward one of the two."
486
+ )
487
+ elif prompt is None and prompt_embeds is None:
488
+ raise ValueError(
489
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
490
+ )
491
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
492
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
493
+
494
+ if negative_prompt is not None and negative_prompt_embeds is not None:
495
+ raise ValueError(
496
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
497
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
498
+ )
499
+
500
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
501
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
502
+ raise ValueError(
503
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
504
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
505
+ f" {negative_prompt_embeds.shape}."
506
+ )
507
+
508
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
509
+ raise ValueError(
510
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
511
+ )
512
+
513
+ if ip_adapter_image_embeds is not None:
514
+ if not isinstance(ip_adapter_image_embeds, list):
515
+ raise ValueError(
516
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
517
+ )
518
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
519
+ raise ValueError(
520
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
521
+ )
522
+
523
+ # Copied from diffusers.pipelines.text_to_video_synthesis.pipeline_text_to_video_synth.TextToVideoSDPipeline.prepare_latents
524
+ def prepare_latents(
525
+ self, batch_size, num_channels_latents, num_frames, height, width, dtype, device, generator, latents=None
526
+ ):
527
+ shape = (
528
+ batch_size,
529
+ num_channels_latents,
530
+ num_frames,
531
+ height // self.vae_scale_factor,
532
+ width // self.vae_scale_factor,
533
+ )
534
+ if isinstance(generator, list) and len(generator) != batch_size:
535
+ raise ValueError(
536
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
537
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
538
+ )
539
+
540
+ if latents is None:
541
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=torch.float32)
542
+ else:
543
+ latents = latents.to(device)
544
+
545
+ # scale the initial noise by the standard deviation required by the scheduler
546
+ latents = latents * self.scheduler.init_noise_sigma
547
+ return latents
548
+
549
+ @property
550
+ def guidance_scale(self):
551
+ return self._guidance_scale
552
+
553
+ @property
554
+ def clip_skip(self):
555
+ return self._clip_skip
556
+
557
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
558
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
559
+ # corresponds to doing no classifier free guidance.
560
+ @property
561
+ def do_classifier_free_guidance(self):
562
+ return self._guidance_scale > 1
563
+
564
+ @property
565
+ def cross_attention_kwargs(self):
566
+ return self._cross_attention_kwargs
567
+
568
+ @property
569
+ def num_timesteps(self):
570
+ return self._num_timesteps
571
+
572
+ @torch.no_grad()
573
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
574
+ def __call__(
575
+ self,
576
+ prompt: Union[str, List[str]] = None,
577
+ num_frames: Optional[int] = 16,
578
+ height: Optional[int] = None,
579
+ width: Optional[int] = None,
580
+ num_inference_steps: int = 50,
581
+ guidance_scale: float = 7.5,
582
+ negative_prompt: Optional[Union[str, List[str]]] = None,
583
+ num_videos_per_prompt: Optional[int] = 1,
584
+ eta: float = 0.0,
585
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
586
+ latents: Optional[torch.Tensor] = None,
587
+ prompt_embeds: Optional[torch.Tensor] = None,
588
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
589
+ ip_adapter_image: Optional[PipelineImageInput] = None,
590
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
591
+ output_type: Optional[str] = "pil",
592
+ return_dict: bool = True,
593
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
594
+ clip_skip: Optional[int] = None,
595
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
596
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
597
+ ):
598
+ r"""
599
+ The call function to the pipeline for generation.
600
+
601
+ Args:
602
+ prompt (`str` or `List[str]`, *optional*):
603
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
604
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
605
+ The height in pixels of the generated video.
606
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
607
+ The width in pixels of the generated video.
608
+ num_frames (`int`, *optional*, defaults to 16):
609
+ The number of video frames that are generated. Defaults to 16 frames which at 8 frames per seconds
610
+ amounts to 2 seconds of video.
611
+ num_inference_steps (`int`, *optional*, defaults to 50):
612
+ The number of denoising steps. More denoising steps usually lead to a higher quality videos at the
613
+ expense of slower inference.
614
+ guidance_scale (`float`, *optional*, defaults to 7.5):
615
+ A higher guidance scale value encourages the model to generate images closely linked to the text
616
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
617
+ negative_prompt (`str` or `List[str]`, *optional*):
618
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
619
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
620
+ eta (`float`, *optional*, defaults to 0.0):
621
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
622
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
623
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
624
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
625
+ generation deterministic.
626
+ latents (`torch.Tensor`, *optional*):
627
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for video
628
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
629
+ tensor is generated by sampling using the supplied random `generator`. Latents should be of shape
630
+ `(batch_size, num_channel, num_frames, height, width)`.
631
+ prompt_embeds (`torch.Tensor`, *optional*):
632
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
633
+ provided, text embeddings are generated from the `prompt` input argument.
634
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
635
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
636
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
637
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
638
+ Optional image input to work with IP Adapters.
639
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
640
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
641
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
642
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
643
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
644
+ output_type (`str`, *optional*, defaults to `"pil"`):
645
+ The output format of the generated video. Choose between `torch.Tensor`, `PIL.Image` or `np.array`.
646
+ return_dict (`bool`, *optional*, defaults to `True`):
647
+ Whether or not to return a [`~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput`] instead
648
+ of a plain tuple.
649
+ cross_attention_kwargs (`dict`, *optional*):
650
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
651
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
652
+ clip_skip (`int`, *optional*):
653
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
654
+ the output of the pre-final layer will be used for computing the prompt embeddings.
655
+ callback_on_step_end (`Callable`, *optional*):
656
+ A function that calls at the end of each denoising steps during the inference. The function is called
657
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
658
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
659
+ `callback_on_step_end_tensor_inputs`.
660
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
661
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
662
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
663
+ `._callback_tensor_inputs` attribute of your pipeline class.
664
+
665
+ Examples:
666
+
667
+ Returns:
668
+ [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] or `tuple`:
669
+ If `return_dict` is `True`, [`~pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput`] is
670
+ returned, otherwise a `tuple` is returned where the first element is a list with the generated frames.
671
+ """
672
+
673
+ # 0. Default height and width to unet
674
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
675
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
676
+
677
+ num_videos_per_prompt = 1
678
+
679
+ # 1. Check inputs. Raise error if not correct
680
+ self.check_inputs(
681
+ prompt,
682
+ height,
683
+ width,
684
+ negative_prompt,
685
+ prompt_embeds,
686
+ negative_prompt_embeds,
687
+ ip_adapter_image,
688
+ ip_adapter_image_embeds,
689
+ callback_on_step_end_tensor_inputs,
690
+ )
691
+
692
+ self._guidance_scale = guidance_scale
693
+ self._clip_skip = clip_skip
694
+ self._cross_attention_kwargs = cross_attention_kwargs
695
+
696
+ # 2. Define call parameters
697
+ if prompt is not None and isinstance(prompt, str):
698
+ batch_size = 1
699
+ elif prompt is not None and isinstance(prompt, list):
700
+ batch_size = len(prompt)
701
+ else:
702
+ batch_size = prompt_embeds.shape[0]
703
+
704
+ device = self._execution_device
705
+
706
+ # 3. Encode input prompt
707
+ text_encoder_lora_scale = (
708
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
709
+ )
710
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
711
+ prompt,
712
+ device,
713
+ num_videos_per_prompt,
714
+ self.do_classifier_free_guidance,
715
+ negative_prompt,
716
+ prompt_embeds=prompt_embeds,
717
+ negative_prompt_embeds=negative_prompt_embeds,
718
+ lora_scale=text_encoder_lora_scale,
719
+ clip_skip=self.clip_skip,
720
+ )
721
+ # For classifier free guidance, we need to do two forward passes.
722
+ # Here we concatenate the unconditional and text embeddings into a single batch
723
+ # to avoid doing two forward passes
724
+ if self.do_classifier_free_guidance:
725
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
726
+
727
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
728
+ image_embeds = self.prepare_ip_adapter_image_embeds(
729
+ ip_adapter_image,
730
+ ip_adapter_image_embeds,
731
+ device,
732
+ batch_size * num_videos_per_prompt,
733
+ self.do_classifier_free_guidance,
734
+ )
735
+
736
+ # 4. Prepare timesteps
737
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
738
+ timesteps = self.scheduler.timesteps
739
+
740
+ # 5. Prepare latent variables
741
+ num_channels_latents = self.unet.config.in_channels
742
+ latents = self.prepare_latents(
743
+ batch_size * num_videos_per_prompt,
744
+ num_channels_latents,
745
+ num_frames,
746
+ height,
747
+ width,
748
+ prompt_embeds.dtype,
749
+ device,
750
+ generator,
751
+ latents,
752
+ )
753
+
754
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
755
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
756
+
757
+ # 7. Add image embeds for IP-Adapter
758
+ added_cond_kwargs = (
759
+ {"image_embeds": image_embeds}
760
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
761
+ else None
762
+ )
763
+
764
+ num_free_init_iters = self._free_init_num_iters if self.free_init_enabled else 1
765
+ for free_init_iter in range(num_free_init_iters):
766
+ if self.free_init_enabled:
767
+ latents, timesteps = self._apply_free_init(
768
+ latents, free_init_iter, num_inference_steps, device, latents.dtype, generator
769
+ )
770
+
771
+ self._num_timesteps = len(timesteps)
772
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
773
+
774
+ # 8. Denoising loop
775
+ with self.progress_bar(total=self._num_timesteps) as progress_bar:
776
+ for i, t in enumerate(timesteps):
777
+ # expand the latents if we are doing classifier free guidance
778
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
779
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
780
+
781
+ # predict the noise residual
782
+ noise_pred = self.unet(
783
+ latent_model_input,
784
+ t,
785
+ encoder_hidden_states=prompt_embeds,
786
+ # cross_attention_kwargs=cross_attention_kwargs,
787
+ # added_cond_kwargs=added_cond_kwargs,
788
+ # ).sample
789
+ )["sample"]
790
+
791
+ # perform guidance
792
+ if self.do_classifier_free_guidance:
793
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
794
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
795
+
796
+ # compute the previous noisy sample x_t -> x_t-1
797
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
798
+
799
+ if callback_on_step_end is not None:
800
+ callback_kwargs = {}
801
+ for k in callback_on_step_end_tensor_inputs:
802
+ callback_kwargs[k] = locals()[k]
803
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
804
+
805
+ latents = callback_outputs.pop("latents", latents)
806
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
807
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
808
+
809
+ # call the callback, if provided
810
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
811
+ progress_bar.update()
812
+
813
+ # 9. Post processing
814
+ if output_type == "latent":
815
+ video = latents
816
+ else:
817
+ video_tensor = self.decode_latents(latents)
818
+ video = self.video_processor.postprocess_video(video=video_tensor, output_type=output_type)
819
+
820
+ # 10. Offload all models
821
+ self.maybe_free_model_hooks()
822
+
823
+ if not return_dict:
824
+ return (video,)
825
+
826
+ return AnimateDiffPipelineOutput(frames=video)
827
+
828
+ @torch.no_grad()
829
+ def prepare_for_ipex(
830
+ self,
831
+ dtype=torch.float32,
832
+ prompt: Union[str, List[str]] = None,
833
+ num_frames: Optional[int] = 16,
834
+ height: Optional[int] = None,
835
+ width: Optional[int] = None,
836
+ num_inference_steps: int = 50,
837
+ guidance_scale: float = 7.5,
838
+ negative_prompt: Optional[Union[str, List[str]]] = None,
839
+ num_videos_per_prompt: Optional[int] = 1,
840
+ eta: float = 0.0,
841
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
842
+ latents: Optional[torch.Tensor] = None,
843
+ prompt_embeds: Optional[torch.Tensor] = None,
844
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
845
+ ip_adapter_image: Optional[PipelineImageInput] = None,
846
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
847
+ output_type: Optional[str] = "pil",
848
+ return_dict: bool = True,
849
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
850
+ clip_skip: Optional[int] = None,
851
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
852
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
853
+ ):
854
+ # 0. Default height and width to unet
855
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
856
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
857
+
858
+ num_videos_per_prompt = 1
859
+
860
+ # 1. Check inputs. Raise error if not correct
861
+ self.check_inputs(
862
+ prompt,
863
+ height,
864
+ width,
865
+ negative_prompt,
866
+ prompt_embeds,
867
+ negative_prompt_embeds,
868
+ ip_adapter_image,
869
+ ip_adapter_image_embeds,
870
+ callback_on_step_end_tensor_inputs,
871
+ )
872
+
873
+ self._guidance_scale = guidance_scale
874
+ self._clip_skip = clip_skip
875
+ self._cross_attention_kwargs = cross_attention_kwargs
876
+
877
+ # 2. Define call parameters
878
+ if prompt is not None and isinstance(prompt, str):
879
+ batch_size = 1
880
+ elif prompt is not None and isinstance(prompt, list):
881
+ batch_size = len(prompt)
882
+ else:
883
+ batch_size = prompt_embeds.shape[0]
884
+
885
+ device = self._execution_device
886
+
887
+ # 3. Encode input prompt
888
+ text_encoder_lora_scale = (
889
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
890
+ )
891
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
892
+ prompt,
893
+ device,
894
+ num_videos_per_prompt,
895
+ self.do_classifier_free_guidance,
896
+ negative_prompt,
897
+ prompt_embeds=prompt_embeds,
898
+ negative_prompt_embeds=negative_prompt_embeds,
899
+ lora_scale=text_encoder_lora_scale,
900
+ clip_skip=self.clip_skip,
901
+ )
902
+ # For classifier free guidance, we need to do two forward passes.
903
+ # Here we concatenate the unconditional and text embeddings into a single batch
904
+ # to avoid doing two forward passes
905
+ if self.do_classifier_free_guidance:
906
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
907
+
908
+ # 4. Prepare timesteps
909
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
910
+ timesteps = self.scheduler.timesteps
911
+
912
+ # 5. Prepare latent variables
913
+ num_channels_latents = self.unet.config.in_channels
914
+ latents = self.prepare_latents(
915
+ batch_size * num_videos_per_prompt,
916
+ num_channels_latents,
917
+ num_frames,
918
+ height,
919
+ width,
920
+ prompt_embeds.dtype,
921
+ device,
922
+ generator,
923
+ latents,
924
+ )
925
+
926
+ num_free_init_iters = self._free_init_num_iters if self.free_init_enabled else 1
927
+ for free_init_iter in range(num_free_init_iters):
928
+ if self.free_init_enabled:
929
+ latents, timesteps = self._apply_free_init(
930
+ latents, free_init_iter, num_inference_steps, device, latents.dtype, generator
931
+ )
932
+
933
+ self._num_timesteps = len(timesteps)
934
+
935
+ dummy = timesteps[0]
936
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
937
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, dummy)
938
+
939
+ self.unet = self.unet.to(memory_format=torch.channels_last)
940
+ self.vae.decoder = self.vae.decoder.to(memory_format=torch.channels_last)
941
+ self.text_encoder = self.text_encoder.to(memory_format=torch.channels_last)
942
+
943
+ unet_input_example = {
944
+ "sample": latent_model_input,
945
+ "timestep": dummy,
946
+ "encoder_hidden_states": prompt_embeds,
947
+ }
948
+
949
+ fake_latents = 1 / self.vae.config.scaling_factor * latents
950
+ batch_size, channels, num_frames, height, width = fake_latents.shape
951
+ fake_latents = fake_latents.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
952
+ vae_decoder_input_example = fake_latents
953
+
954
+ # optimize with ipex
955
+ if dtype == torch.bfloat16:
956
+ self.unet = ipex.optimize(self.unet.eval(), dtype=torch.bfloat16, inplace=True)
957
+ self.vae.decoder = ipex.optimize(self.vae.decoder.eval(), dtype=torch.bfloat16, inplace=True)
958
+ self.text_encoder = ipex.optimize(self.text_encoder.eval(), dtype=torch.bfloat16, inplace=True)
959
+ elif dtype == torch.float32:
960
+ self.unet = ipex.optimize(
961
+ self.unet.eval(),
962
+ dtype=torch.float32,
963
+ inplace=True,
964
+ # sample_input=unet_input_example,
965
+ level="O1",
966
+ weights_prepack=True,
967
+ auto_kernel_selection=False,
968
+ )
969
+ self.vae.decoder = ipex.optimize(
970
+ self.vae.decoder.eval(),
971
+ dtype=torch.float32,
972
+ inplace=True,
973
+ level="O1",
974
+ weights_prepack=True,
975
+ auto_kernel_selection=False,
976
+ )
977
+ self.text_encoder = ipex.optimize(
978
+ self.text_encoder.eval(),
979
+ dtype=torch.float32,
980
+ inplace=True,
981
+ level="O1",
982
+ weights_prepack=True,
983
+ auto_kernel_selection=False,
984
+ )
985
+ else:
986
+ raise ValueError(" The value of 'dtype' should be 'torch.bfloat16' or 'torch.float32' !")
987
+
988
+ # trace unet model to get better performance on IPEX
989
+ with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():
990
+ unet_trace_model = torch.jit.trace(
991
+ self.unet, example_kwarg_inputs=unet_input_example, check_trace=False, strict=False
992
+ )
993
+ unet_trace_model = torch.jit.freeze(unet_trace_model)
994
+ self.unet.forward = unet_trace_model.forward
995
+
996
+ # trace vae.decoder model to get better performance on IPEX
997
+ with torch.cpu.amp.autocast(enabled=dtype == torch.bfloat16), torch.no_grad():
998
+ vae_decoder_trace_model = torch.jit.trace(
999
+ self.vae.decoder, vae_decoder_input_example, check_trace=False, strict=False
1000
+ )
1001
+ vae_decoder_trace_model = torch.jit.freeze(vae_decoder_trace_model)
1002
+ self.vae.decoder.forward = vae_decoder_trace_model.forward
v0.32.0/pipeline_demofusion_sdxl.py ADDED
@@ -0,0 +1,1386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+ import random
4
+ import warnings
5
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
6
+
7
+ import matplotlib.pyplot as plt
8
+ import torch
9
+ import torch.nn.functional as F
10
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
11
+
12
+ from diffusers.image_processor import VaeImageProcessor
13
+ from diffusers.loaders import (
14
+ FromSingleFileMixin,
15
+ StableDiffusionLoraLoaderMixin,
16
+ TextualInversionLoaderMixin,
17
+ )
18
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
19
+ from diffusers.models.attention_processor import AttnProcessor2_0, XFormersAttnProcessor
20
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
21
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
22
+ from diffusers.schedulers import KarrasDiffusionSchedulers
23
+ from diffusers.utils import (
24
+ is_accelerate_available,
25
+ is_accelerate_version,
26
+ is_invisible_watermark_available,
27
+ logging,
28
+ replace_example_docstring,
29
+ )
30
+ from diffusers.utils.torch_utils import randn_tensor
31
+
32
+
33
+ if is_invisible_watermark_available():
34
+ from diffusers.pipelines.stable_diffusion_xl.watermark import (
35
+ StableDiffusionXLWatermarker,
36
+ )
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+ EXAMPLE_DOC_STRING = """
42
+ Examples:
43
+ ```py
44
+ >>> import torch
45
+ >>> from diffusers import StableDiffusionXLPipeline
46
+
47
+ >>> pipe = StableDiffusionXLPipeline.from_pretrained(
48
+ ... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
49
+ ... )
50
+ >>> pipe = pipe.to("cuda")
51
+
52
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
53
+ >>> image = pipe(prompt).images[0]
54
+ ```
55
+ """
56
+
57
+
58
+ def gaussian_kernel(kernel_size=3, sigma=1.0, channels=3):
59
+ x_coord = torch.arange(kernel_size)
60
+ gaussian_1d = torch.exp(-((x_coord - (kernel_size - 1) / 2) ** 2) / (2 * sigma**2))
61
+ gaussian_1d = gaussian_1d / gaussian_1d.sum()
62
+ gaussian_2d = gaussian_1d[:, None] * gaussian_1d[None, :]
63
+ kernel = gaussian_2d[None, None, :, :].repeat(channels, 1, 1, 1)
64
+
65
+ return kernel
66
+
67
+
68
+ def gaussian_filter(latents, kernel_size=3, sigma=1.0):
69
+ channels = latents.shape[1]
70
+ kernel = gaussian_kernel(kernel_size, sigma, channels).to(latents.device, latents.dtype)
71
+ blurred_latents = F.conv2d(latents, kernel, padding=kernel_size // 2, groups=channels)
72
+
73
+ return blurred_latents
74
+
75
+
76
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
77
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
78
+ """
79
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
80
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
81
+ """
82
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
83
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
84
+ # rescale the results from guidance (fixes overexposure)
85
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
86
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
87
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
88
+ return noise_cfg
89
+
90
+
91
+ class DemoFusionSDXLPipeline(
92
+ DiffusionPipeline,
93
+ StableDiffusionMixin,
94
+ FromSingleFileMixin,
95
+ StableDiffusionLoraLoaderMixin,
96
+ TextualInversionLoaderMixin,
97
+ ):
98
+ r"""
99
+ Pipeline for text-to-image generation using Stable Diffusion XL.
100
+
101
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
102
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
103
+
104
+ In addition the pipeline inherits the following loading methods:
105
+ - *LoRA*: [`StableDiffusionXLPipeline.load_lora_weights`]
106
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
107
+
108
+ as well as the following saving methods:
109
+ - *LoRA*: [`loaders.StableDiffusionXLPipeline.save_lora_weights`]
110
+
111
+ Args:
112
+ vae ([`AutoencoderKL`]):
113
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
114
+ text_encoder ([`CLIPTextModel`]):
115
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
116
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
117
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
118
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
119
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
120
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
121
+ specifically the
122
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
123
+ variant.
124
+ tokenizer (`CLIPTokenizer`):
125
+ Tokenizer of class
126
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
127
+ tokenizer_2 (`CLIPTokenizer`):
128
+ Second Tokenizer of class
129
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
130
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
131
+ scheduler ([`SchedulerMixin`]):
132
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
133
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
134
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
135
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
136
+ `stabilityai/stable-diffusion-xl-base-1-0`.
137
+ add_watermarker (`bool`, *optional*):
138
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
139
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
140
+ watermarker will be used.
141
+ """
142
+
143
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
144
+
145
+ def __init__(
146
+ self,
147
+ vae: AutoencoderKL,
148
+ text_encoder: CLIPTextModel,
149
+ text_encoder_2: CLIPTextModelWithProjection,
150
+ tokenizer: CLIPTokenizer,
151
+ tokenizer_2: CLIPTokenizer,
152
+ unet: UNet2DConditionModel,
153
+ scheduler: KarrasDiffusionSchedulers,
154
+ force_zeros_for_empty_prompt: bool = True,
155
+ add_watermarker: Optional[bool] = None,
156
+ ):
157
+ super().__init__()
158
+
159
+ self.register_modules(
160
+ vae=vae,
161
+ text_encoder=text_encoder,
162
+ text_encoder_2=text_encoder_2,
163
+ tokenizer=tokenizer,
164
+ tokenizer_2=tokenizer_2,
165
+ unet=unet,
166
+ scheduler=scheduler,
167
+ )
168
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
169
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
170
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
171
+ self.default_sample_size = self.unet.config.sample_size
172
+
173
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
174
+
175
+ if add_watermarker:
176
+ self.watermark = StableDiffusionXLWatermarker()
177
+ else:
178
+ self.watermark = None
179
+
180
+ def encode_prompt(
181
+ self,
182
+ prompt: str,
183
+ prompt_2: Optional[str] = None,
184
+ device: Optional[torch.device] = None,
185
+ num_images_per_prompt: int = 1,
186
+ do_classifier_free_guidance: bool = True,
187
+ negative_prompt: Optional[str] = None,
188
+ negative_prompt_2: Optional[str] = None,
189
+ prompt_embeds: Optional[torch.Tensor] = None,
190
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
191
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
192
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
193
+ lora_scale: Optional[float] = None,
194
+ ):
195
+ r"""
196
+ Encodes the prompt into text encoder hidden states.
197
+
198
+ Args:
199
+ prompt (`str` or `List[str]`, *optional*):
200
+ prompt to be encoded
201
+ prompt_2 (`str` or `List[str]`, *optional*):
202
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
203
+ used in both text-encoders
204
+ device: (`torch.device`):
205
+ torch device
206
+ num_images_per_prompt (`int`):
207
+ number of images that should be generated per prompt
208
+ do_classifier_free_guidance (`bool`):
209
+ whether to use classifier free guidance or not
210
+ negative_prompt (`str` or `List[str]`, *optional*):
211
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
212
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
213
+ less than `1`).
214
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
215
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
216
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
217
+ prompt_embeds (`torch.Tensor`, *optional*):
218
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
219
+ provided, text embeddings will be generated from `prompt` input argument.
220
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
221
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
222
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
223
+ argument.
224
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
225
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
226
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
227
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
228
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
229
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
230
+ input argument.
231
+ lora_scale (`float`, *optional*):
232
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
233
+ """
234
+ device = device or self._execution_device
235
+
236
+ # set lora scale so that monkey patched LoRA
237
+ # function of text encoder can correctly access it
238
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
239
+ self._lora_scale = lora_scale
240
+
241
+ # dynamically adjust the LoRA scale
242
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
243
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
244
+
245
+ if prompt is not None and isinstance(prompt, str):
246
+ batch_size = 1
247
+ elif prompt is not None and isinstance(prompt, list):
248
+ batch_size = len(prompt)
249
+ else:
250
+ batch_size = prompt_embeds.shape[0]
251
+
252
+ # Define tokenizers and text encoders
253
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
254
+ text_encoders = (
255
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
256
+ )
257
+
258
+ if prompt_embeds is None:
259
+ prompt_2 = prompt_2 or prompt
260
+ # textual inversion: process multi-vector tokens if necessary
261
+ prompt_embeds_list = []
262
+ prompts = [prompt, prompt_2]
263
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
264
+ if isinstance(self, TextualInversionLoaderMixin):
265
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
266
+
267
+ text_inputs = tokenizer(
268
+ prompt,
269
+ padding="max_length",
270
+ max_length=tokenizer.model_max_length,
271
+ truncation=True,
272
+ return_tensors="pt",
273
+ )
274
+
275
+ text_input_ids = text_inputs.input_ids
276
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
277
+
278
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
279
+ text_input_ids, untruncated_ids
280
+ ):
281
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
282
+ logger.warning(
283
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
284
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
285
+ )
286
+
287
+ prompt_embeds = text_encoder(
288
+ text_input_ids.to(device),
289
+ output_hidden_states=True,
290
+ )
291
+
292
+ # We are only ALWAYS interested in the pooled output of the final text encoder
293
+ pooled_prompt_embeds = prompt_embeds[0]
294
+ prompt_embeds = prompt_embeds.hidden_states[-2]
295
+
296
+ prompt_embeds_list.append(prompt_embeds)
297
+
298
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
299
+
300
+ # get unconditional embeddings for classifier free guidance
301
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
302
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
303
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
304
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
305
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
306
+ negative_prompt = negative_prompt or ""
307
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
308
+
309
+ uncond_tokens: List[str]
310
+ if prompt is not None and type(prompt) is not type(negative_prompt):
311
+ raise TypeError(
312
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
313
+ f" {type(prompt)}."
314
+ )
315
+ elif isinstance(negative_prompt, str):
316
+ uncond_tokens = [negative_prompt, negative_prompt_2]
317
+ elif batch_size != len(negative_prompt):
318
+ raise ValueError(
319
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
320
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
321
+ " the batch size of `prompt`."
322
+ )
323
+ else:
324
+ uncond_tokens = [negative_prompt, negative_prompt_2]
325
+
326
+ negative_prompt_embeds_list = []
327
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
328
+ if isinstance(self, TextualInversionLoaderMixin):
329
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
330
+
331
+ max_length = prompt_embeds.shape[1]
332
+ uncond_input = tokenizer(
333
+ negative_prompt,
334
+ padding="max_length",
335
+ max_length=max_length,
336
+ truncation=True,
337
+ return_tensors="pt",
338
+ )
339
+
340
+ negative_prompt_embeds = text_encoder(
341
+ uncond_input.input_ids.to(device),
342
+ output_hidden_states=True,
343
+ )
344
+ # We are only ALWAYS interested in the pooled output of the final text encoder
345
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
346
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
347
+
348
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
349
+
350
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
351
+
352
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
353
+ bs_embed, seq_len, _ = prompt_embeds.shape
354
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
355
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
356
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
357
+
358
+ if do_classifier_free_guidance:
359
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
360
+ seq_len = negative_prompt_embeds.shape[1]
361
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
362
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
363
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
364
+
365
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
366
+ bs_embed * num_images_per_prompt, -1
367
+ )
368
+ if do_classifier_free_guidance:
369
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
370
+ bs_embed * num_images_per_prompt, -1
371
+ )
372
+
373
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
374
+
375
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
376
+ def prepare_extra_step_kwargs(self, generator, eta):
377
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
378
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
379
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
380
+ # and should be between [0, 1]
381
+
382
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
383
+ extra_step_kwargs = {}
384
+ if accepts_eta:
385
+ extra_step_kwargs["eta"] = eta
386
+
387
+ # check if the scheduler accepts generator
388
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
389
+ if accepts_generator:
390
+ extra_step_kwargs["generator"] = generator
391
+ return extra_step_kwargs
392
+
393
+ def check_inputs(
394
+ self,
395
+ prompt,
396
+ prompt_2,
397
+ height,
398
+ width,
399
+ callback_steps,
400
+ negative_prompt=None,
401
+ negative_prompt_2=None,
402
+ prompt_embeds=None,
403
+ negative_prompt_embeds=None,
404
+ pooled_prompt_embeds=None,
405
+ negative_pooled_prompt_embeds=None,
406
+ num_images_per_prompt=None,
407
+ ):
408
+ if height % 8 != 0 or width % 8 != 0:
409
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
410
+
411
+ if (callback_steps is None) or (
412
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
413
+ ):
414
+ raise ValueError(
415
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
416
+ f" {type(callback_steps)}."
417
+ )
418
+
419
+ if prompt is not None and prompt_embeds is not None:
420
+ raise ValueError(
421
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
422
+ " only forward one of the two."
423
+ )
424
+ elif prompt_2 is not None and prompt_embeds is not None:
425
+ raise ValueError(
426
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
427
+ " only forward one of the two."
428
+ )
429
+ elif prompt is None and prompt_embeds is None:
430
+ raise ValueError(
431
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
432
+ )
433
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
434
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
435
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
436
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
437
+
438
+ if negative_prompt is not None and negative_prompt_embeds is not None:
439
+ raise ValueError(
440
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
441
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
442
+ )
443
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
444
+ raise ValueError(
445
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
446
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
447
+ )
448
+
449
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
450
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
451
+ raise ValueError(
452
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
453
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
454
+ f" {negative_prompt_embeds.shape}."
455
+ )
456
+
457
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
458
+ raise ValueError(
459
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
460
+ )
461
+
462
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
463
+ raise ValueError(
464
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
465
+ )
466
+
467
+ # DemoFusion specific checks
468
+ if max(height, width) % 1024 != 0:
469
+ raise ValueError(
470
+ f"the larger one of `height` and `width` has to be divisible by 1024 but are {height} and {width}."
471
+ )
472
+
473
+ if num_images_per_prompt != 1:
474
+ warnings.warn("num_images_per_prompt != 1 is not supported by DemoFusion and will be ignored.")
475
+ num_images_per_prompt = 1
476
+
477
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
478
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
479
+ shape = (
480
+ batch_size,
481
+ num_channels_latents,
482
+ int(height) // self.vae_scale_factor,
483
+ int(width) // self.vae_scale_factor,
484
+ )
485
+ if isinstance(generator, list) and len(generator) != batch_size:
486
+ raise ValueError(
487
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
488
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
489
+ )
490
+
491
+ if latents is None:
492
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
493
+ else:
494
+ latents = latents.to(device)
495
+
496
+ # scale the initial noise by the standard deviation required by the scheduler
497
+ latents = latents * self.scheduler.init_noise_sigma
498
+ return latents
499
+
500
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
501
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
502
+
503
+ passed_add_embed_dim = (
504
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
505
+ )
506
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
507
+
508
+ if expected_add_embed_dim != passed_add_embed_dim:
509
+ raise ValueError(
510
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
511
+ )
512
+
513
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
514
+ return add_time_ids
515
+
516
+ def get_views(self, height, width, window_size=128, stride=64, random_jitter=False):
517
+ height //= self.vae_scale_factor
518
+ width //= self.vae_scale_factor
519
+ num_blocks_height = int((height - window_size) / stride - 1e-6) + 2 if height > window_size else 1
520
+ num_blocks_width = int((width - window_size) / stride - 1e-6) + 2 if width > window_size else 1
521
+ total_num_blocks = int(num_blocks_height * num_blocks_width)
522
+ views = []
523
+ for i in range(total_num_blocks):
524
+ h_start = int((i // num_blocks_width) * stride)
525
+ h_end = h_start + window_size
526
+ w_start = int((i % num_blocks_width) * stride)
527
+ w_end = w_start + window_size
528
+
529
+ if h_end > height:
530
+ h_start = int(h_start + height - h_end)
531
+ h_end = int(height)
532
+ if w_end > width:
533
+ w_start = int(w_start + width - w_end)
534
+ w_end = int(width)
535
+ if h_start < 0:
536
+ h_end = int(h_end - h_start)
537
+ h_start = 0
538
+ if w_start < 0:
539
+ w_end = int(w_end - w_start)
540
+ w_start = 0
541
+
542
+ if random_jitter:
543
+ jitter_range = (window_size - stride) // 4
544
+ w_jitter = 0
545
+ h_jitter = 0
546
+ if (w_start != 0) and (w_end != width):
547
+ w_jitter = random.randint(-jitter_range, jitter_range)
548
+ elif (w_start == 0) and (w_end != width):
549
+ w_jitter = random.randint(-jitter_range, 0)
550
+ elif (w_start != 0) and (w_end == width):
551
+ w_jitter = random.randint(0, jitter_range)
552
+ if (h_start != 0) and (h_end != height):
553
+ h_jitter = random.randint(-jitter_range, jitter_range)
554
+ elif (h_start == 0) and (h_end != height):
555
+ h_jitter = random.randint(-jitter_range, 0)
556
+ elif (h_start != 0) and (h_end == height):
557
+ h_jitter = random.randint(0, jitter_range)
558
+ h_start += h_jitter + jitter_range
559
+ h_end += h_jitter + jitter_range
560
+ w_start += w_jitter + jitter_range
561
+ w_end += w_jitter + jitter_range
562
+
563
+ views.append((h_start, h_end, w_start, w_end))
564
+ return views
565
+
566
+ def tiled_decode(self, latents, current_height, current_width):
567
+ core_size = self.unet.config.sample_size // 4
568
+ core_stride = core_size
569
+ pad_size = self.unet.config.sample_size // 4 * 3
570
+ decoder_view_batch_size = 1
571
+
572
+ views = self.get_views(current_height, current_width, stride=core_stride, window_size=core_size)
573
+ views_batch = [views[i : i + decoder_view_batch_size] for i in range(0, len(views), decoder_view_batch_size)]
574
+ latents_ = F.pad(latents, (pad_size, pad_size, pad_size, pad_size), "constant", 0)
575
+ image = torch.zeros(latents.size(0), 3, current_height, current_width).to(latents.device)
576
+ count = torch.zeros_like(image).to(latents.device)
577
+ # get the latents corresponding to the current view coordinates
578
+ with self.progress_bar(total=len(views_batch)) as progress_bar:
579
+ for j, batch_view in enumerate(views_batch):
580
+ len(batch_view)
581
+ latents_for_view = torch.cat(
582
+ [
583
+ latents_[:, :, h_start : h_end + pad_size * 2, w_start : w_end + pad_size * 2]
584
+ for h_start, h_end, w_start, w_end in batch_view
585
+ ]
586
+ )
587
+ image_patch = self.vae.decode(latents_for_view / self.vae.config.scaling_factor, return_dict=False)[0]
588
+ h_start, h_end, w_start, w_end = views[j]
589
+ h_start, h_end, w_start, w_end = (
590
+ h_start * self.vae_scale_factor,
591
+ h_end * self.vae_scale_factor,
592
+ w_start * self.vae_scale_factor,
593
+ w_end * self.vae_scale_factor,
594
+ )
595
+ p_h_start, p_h_end, p_w_start, p_w_end = (
596
+ pad_size * self.vae_scale_factor,
597
+ image_patch.size(2) - pad_size * self.vae_scale_factor,
598
+ pad_size * self.vae_scale_factor,
599
+ image_patch.size(3) - pad_size * self.vae_scale_factor,
600
+ )
601
+ image[:, :, h_start:h_end, w_start:w_end] += image_patch[:, :, p_h_start:p_h_end, p_w_start:p_w_end]
602
+ count[:, :, h_start:h_end, w_start:w_end] += 1
603
+ progress_bar.update()
604
+ image = image / count
605
+
606
+ return image
607
+
608
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
609
+ def upcast_vae(self):
610
+ dtype = self.vae.dtype
611
+ self.vae.to(dtype=torch.float32)
612
+ use_torch_2_0_or_xformers = isinstance(
613
+ self.vae.decoder.mid_block.attentions[0].processor,
614
+ (AttnProcessor2_0, XFormersAttnProcessor),
615
+ )
616
+ # if xformers or torch_2_0 is used attention block does not need
617
+ # to be in float32 which can save lots of memory
618
+ if use_torch_2_0_or_xformers:
619
+ self.vae.post_quant_conv.to(dtype)
620
+ self.vae.decoder.conv_in.to(dtype)
621
+ self.vae.decoder.mid_block.to(dtype)
622
+
623
+ @torch.no_grad()
624
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
625
+ def __call__(
626
+ self,
627
+ prompt: Union[str, List[str]] = None,
628
+ prompt_2: Optional[Union[str, List[str]]] = None,
629
+ height: Optional[int] = None,
630
+ width: Optional[int] = None,
631
+ num_inference_steps: int = 50,
632
+ denoising_end: Optional[float] = None,
633
+ guidance_scale: float = 5.0,
634
+ negative_prompt: Optional[Union[str, List[str]]] = None,
635
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
636
+ num_images_per_prompt: Optional[int] = 1,
637
+ eta: float = 0.0,
638
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
639
+ latents: Optional[torch.Tensor] = None,
640
+ prompt_embeds: Optional[torch.Tensor] = None,
641
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
642
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
643
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
644
+ output_type: Optional[str] = "pil",
645
+ return_dict: bool = False,
646
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
647
+ callback_steps: int = 1,
648
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
649
+ guidance_rescale: float = 0.0,
650
+ original_size: Optional[Tuple[int, int]] = None,
651
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
652
+ target_size: Optional[Tuple[int, int]] = None,
653
+ negative_original_size: Optional[Tuple[int, int]] = None,
654
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
655
+ negative_target_size: Optional[Tuple[int, int]] = None,
656
+ ################### DemoFusion specific parameters ####################
657
+ view_batch_size: int = 16,
658
+ multi_decoder: bool = True,
659
+ stride: Optional[int] = 64,
660
+ cosine_scale_1: Optional[float] = 3.0,
661
+ cosine_scale_2: Optional[float] = 1.0,
662
+ cosine_scale_3: Optional[float] = 1.0,
663
+ sigma: Optional[float] = 0.8,
664
+ show_image: bool = False,
665
+ ):
666
+ r"""
667
+ Function invoked when calling the pipeline for generation.
668
+
669
+ Args:
670
+ prompt (`str` or `List[str]`, *optional*):
671
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
672
+ instead.
673
+ prompt_2 (`str` or `List[str]`, *optional*):
674
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
675
+ used in both text-encoders
676
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
677
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
678
+ Anything below 512 pixels won't work well for
679
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
680
+ and checkpoints that are not specifically fine-tuned on low resolutions.
681
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
682
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
683
+ Anything below 512 pixels won't work well for
684
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
685
+ and checkpoints that are not specifically fine-tuned on low resolutions.
686
+ num_inference_steps (`int`, *optional*, defaults to 50):
687
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
688
+ expense of slower inference.
689
+ denoising_end (`float`, *optional*):
690
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
691
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
692
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
693
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
694
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
695
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
696
+ guidance_scale (`float`, *optional*, defaults to 5.0):
697
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
698
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
699
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
700
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
701
+ usually at the expense of lower image quality.
702
+ negative_prompt (`str` or `List[str]`, *optional*):
703
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
704
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
705
+ less than `1`).
706
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
707
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
708
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
709
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
710
+ The number of images to generate per prompt.
711
+ eta (`float`, *optional*, defaults to 0.0):
712
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
713
+ [`schedulers.DDIMScheduler`], will be ignored for others.
714
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
715
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
716
+ to make generation deterministic.
717
+ latents (`torch.Tensor`, *optional*):
718
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
719
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
720
+ tensor will ge generated by sampling using the supplied random `generator`.
721
+ prompt_embeds (`torch.Tensor`, *optional*):
722
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
723
+ provided, text embeddings will be generated from `prompt` input argument.
724
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
725
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
726
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
727
+ argument.
728
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
729
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
730
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
731
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
732
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
733
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
734
+ input argument.
735
+ output_type (`str`, *optional*, defaults to `"pil"`):
736
+ The output format of the generate image. Choose between
737
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
738
+ return_dict (`bool`, *optional*, defaults to `True`):
739
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
740
+ of a plain tuple.
741
+ callback (`Callable`, *optional*):
742
+ A function that will be called every `callback_steps` steps during inference. The function will be
743
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
744
+ callback_steps (`int`, *optional*, defaults to 1):
745
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
746
+ called at every step.
747
+ cross_attention_kwargs (`dict`, *optional*):
748
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
749
+ `self.processor` in
750
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
751
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
752
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
753
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
754
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
755
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
756
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
757
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
758
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
759
+ explained in section 2.2 of
760
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
761
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
762
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
763
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
764
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
765
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
766
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
767
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
768
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
769
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
770
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
771
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
772
+ micro-conditioning as explained in section 2.2 of
773
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
774
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
775
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
776
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
777
+ micro-conditioning as explained in section 2.2 of
778
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
779
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
780
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
781
+ To negatively condition the generation process based on a target image resolution. It should be as same
782
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
783
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
784
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
785
+ ################### DemoFusion specific parameters ####################
786
+ view_batch_size (`int`, defaults to 16):
787
+ The batch size for multiple denoising paths. Typically, a larger batch size can result in higher
788
+ efficiency but comes with increased GPU memory requirements.
789
+ multi_decoder (`bool`, defaults to True):
790
+ Determine whether to use a tiled decoder. Generally, when the resolution exceeds 3072x3072,
791
+ a tiled decoder becomes necessary.
792
+ stride (`int`, defaults to 64):
793
+ The stride of moving local patches. A smaller stride is better for alleviating seam issues,
794
+ but it also introduces additional computational overhead and inference time.
795
+ cosine_scale_1 (`float`, defaults to 3):
796
+ Control the strength of skip-residual. For specific impacts, please refer to Appendix C
797
+ in the DemoFusion paper.
798
+ cosine_scale_2 (`float`, defaults to 1):
799
+ Control the strength of dilated sampling. For specific impacts, please refer to Appendix C
800
+ in the DemoFusion paper.
801
+ cosine_scale_3 (`float`, defaults to 1):
802
+ Control the strength of the gaussian filter. For specific impacts, please refer to Appendix C
803
+ in the DemoFusion paper.
804
+ sigma (`float`, defaults to 1):
805
+ The standard value of the gaussian filter.
806
+ show_image (`bool`, defaults to False):
807
+ Determine whether to show intermediate results during generation.
808
+
809
+ Examples:
810
+
811
+ Returns:
812
+ a `list` with the generated images at each phase.
813
+ """
814
+
815
+ # 0. Default height and width to unet
816
+ height = height or self.default_sample_size * self.vae_scale_factor
817
+ width = width or self.default_sample_size * self.vae_scale_factor
818
+
819
+ x1_size = self.default_sample_size * self.vae_scale_factor
820
+
821
+ height_scale = height / x1_size
822
+ width_scale = width / x1_size
823
+ scale_num = int(max(height_scale, width_scale))
824
+ aspect_ratio = min(height_scale, width_scale) / max(height_scale, width_scale)
825
+
826
+ original_size = original_size or (height, width)
827
+ target_size = target_size or (height, width)
828
+
829
+ # 1. Check inputs. Raise error if not correct
830
+ self.check_inputs(
831
+ prompt,
832
+ prompt_2,
833
+ height,
834
+ width,
835
+ callback_steps,
836
+ negative_prompt,
837
+ negative_prompt_2,
838
+ prompt_embeds,
839
+ negative_prompt_embeds,
840
+ pooled_prompt_embeds,
841
+ negative_pooled_prompt_embeds,
842
+ num_images_per_prompt,
843
+ )
844
+
845
+ # 2. Define call parameters
846
+ if prompt is not None and isinstance(prompt, str):
847
+ batch_size = 1
848
+ elif prompt is not None and isinstance(prompt, list):
849
+ batch_size = len(prompt)
850
+ else:
851
+ batch_size = prompt_embeds.shape[0]
852
+
853
+ device = self._execution_device
854
+
855
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
856
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
857
+ # corresponds to doing no classifier free guidance.
858
+ do_classifier_free_guidance = guidance_scale > 1.0
859
+
860
+ # 3. Encode input prompt
861
+ text_encoder_lora_scale = (
862
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
863
+ )
864
+ (
865
+ prompt_embeds,
866
+ negative_prompt_embeds,
867
+ pooled_prompt_embeds,
868
+ negative_pooled_prompt_embeds,
869
+ ) = self.encode_prompt(
870
+ prompt=prompt,
871
+ prompt_2=prompt_2,
872
+ device=device,
873
+ num_images_per_prompt=num_images_per_prompt,
874
+ do_classifier_free_guidance=do_classifier_free_guidance,
875
+ negative_prompt=negative_prompt,
876
+ negative_prompt_2=negative_prompt_2,
877
+ prompt_embeds=prompt_embeds,
878
+ negative_prompt_embeds=negative_prompt_embeds,
879
+ pooled_prompt_embeds=pooled_prompt_embeds,
880
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
881
+ lora_scale=text_encoder_lora_scale,
882
+ )
883
+
884
+ # 4. Prepare timesteps
885
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
886
+
887
+ timesteps = self.scheduler.timesteps
888
+
889
+ # 5. Prepare latent variables
890
+ num_channels_latents = self.unet.config.in_channels
891
+ latents = self.prepare_latents(
892
+ batch_size * num_images_per_prompt,
893
+ num_channels_latents,
894
+ height // scale_num,
895
+ width // scale_num,
896
+ prompt_embeds.dtype,
897
+ device,
898
+ generator,
899
+ latents,
900
+ )
901
+
902
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
903
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
904
+
905
+ # 7. Prepare added time ids & embeddings
906
+ add_text_embeds = pooled_prompt_embeds
907
+ add_time_ids = self._get_add_time_ids(
908
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
909
+ )
910
+ if negative_original_size is not None and negative_target_size is not None:
911
+ negative_add_time_ids = self._get_add_time_ids(
912
+ negative_original_size,
913
+ negative_crops_coords_top_left,
914
+ negative_target_size,
915
+ dtype=prompt_embeds.dtype,
916
+ )
917
+ else:
918
+ negative_add_time_ids = add_time_ids
919
+
920
+ if do_classifier_free_guidance:
921
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
922
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
923
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
924
+
925
+ prompt_embeds = prompt_embeds.to(device)
926
+ add_text_embeds = add_text_embeds.to(device)
927
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
928
+
929
+ # 8. Denoising loop
930
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
931
+
932
+ # 7.1 Apply denoising_end
933
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
934
+ discrete_timestep_cutoff = int(
935
+ round(
936
+ self.scheduler.config.num_train_timesteps
937
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
938
+ )
939
+ )
940
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
941
+ timesteps = timesteps[:num_inference_steps]
942
+
943
+ output_images = []
944
+
945
+ ############################################################### Phase 1 #################################################################
946
+
947
+ print("### Phase 1 Denoising ###")
948
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
949
+ for i, t in enumerate(timesteps):
950
+ latents_for_view = latents
951
+
952
+ # expand the latents if we are doing classifier free guidance
953
+ latent_model_input = latents.repeat_interleave(2, dim=0) if do_classifier_free_guidance else latents
954
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
955
+
956
+ # predict the noise residual
957
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
958
+ noise_pred = self.unet(
959
+ latent_model_input,
960
+ t,
961
+ encoder_hidden_states=prompt_embeds,
962
+ cross_attention_kwargs=cross_attention_kwargs,
963
+ added_cond_kwargs=added_cond_kwargs,
964
+ return_dict=False,
965
+ )[0]
966
+
967
+ # perform guidance
968
+ if do_classifier_free_guidance:
969
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
970
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
971
+
972
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
973
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
974
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
975
+
976
+ # compute the previous noisy sample x_t -> x_t-1
977
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
978
+
979
+ # call the callback, if provided
980
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
981
+ progress_bar.update()
982
+ if callback is not None and i % callback_steps == 0:
983
+ step_idx = i // getattr(self.scheduler, "order", 1)
984
+ callback(step_idx, t, latents)
985
+
986
+ anchor_mean = latents.mean()
987
+ anchor_std = latents.std()
988
+ if not output_type == "latent":
989
+ # make sure the VAE is in float32 mode, as it overflows in float16
990
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
991
+
992
+ if needs_upcasting:
993
+ self.upcast_vae()
994
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
995
+ print("### Phase 1 Decoding ###")
996
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
997
+ # cast back to fp16 if needed
998
+ if needs_upcasting:
999
+ self.vae.to(dtype=torch.float16)
1000
+
1001
+ image = self.image_processor.postprocess(image, output_type=output_type)
1002
+ if show_image:
1003
+ plt.figure(figsize=(10, 10))
1004
+ plt.imshow(image[0])
1005
+ plt.axis("off") # Turn off axis numbers and ticks
1006
+ plt.show()
1007
+ output_images.append(image[0])
1008
+
1009
+ ####################################################### Phase 2+ #####################################################
1010
+
1011
+ for current_scale_num in range(2, scale_num + 1):
1012
+ print("### Phase {} Denoising ###".format(current_scale_num))
1013
+ current_height = self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
1014
+ current_width = self.unet.config.sample_size * self.vae_scale_factor * current_scale_num
1015
+ if height > width:
1016
+ current_width = int(current_width * aspect_ratio)
1017
+ else:
1018
+ current_height = int(current_height * aspect_ratio)
1019
+
1020
+ latents = F.interpolate(
1021
+ latents,
1022
+ size=(int(current_height / self.vae_scale_factor), int(current_width / self.vae_scale_factor)),
1023
+ mode="bicubic",
1024
+ )
1025
+
1026
+ noise_latents = []
1027
+ noise = torch.randn_like(latents)
1028
+ for timestep in timesteps:
1029
+ noise_latent = self.scheduler.add_noise(latents, noise, timestep.unsqueeze(0))
1030
+ noise_latents.append(noise_latent)
1031
+ latents = noise_latents[0]
1032
+
1033
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1034
+ for i, t in enumerate(timesteps):
1035
+ count = torch.zeros_like(latents)
1036
+ value = torch.zeros_like(latents)
1037
+ cosine_factor = (
1038
+ 0.5
1039
+ * (
1040
+ 1
1041
+ + torch.cos(
1042
+ torch.pi
1043
+ * (self.scheduler.config.num_train_timesteps - t)
1044
+ / self.scheduler.config.num_train_timesteps
1045
+ )
1046
+ ).cpu()
1047
+ )
1048
+
1049
+ c1 = cosine_factor**cosine_scale_1
1050
+ latents = latents * (1 - c1) + noise_latents[i] * c1
1051
+
1052
+ ############################################# MultiDiffusion #############################################
1053
+
1054
+ views = self.get_views(
1055
+ current_height,
1056
+ current_width,
1057
+ stride=stride,
1058
+ window_size=self.unet.config.sample_size,
1059
+ random_jitter=True,
1060
+ )
1061
+ views_batch = [views[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1062
+
1063
+ jitter_range = (self.unet.config.sample_size - stride) // 4
1064
+ latents_ = F.pad(latents, (jitter_range, jitter_range, jitter_range, jitter_range), "constant", 0)
1065
+
1066
+ count_local = torch.zeros_like(latents_)
1067
+ value_local = torch.zeros_like(latents_)
1068
+
1069
+ for j, batch_view in enumerate(views_batch):
1070
+ vb_size = len(batch_view)
1071
+
1072
+ # get the latents corresponding to the current view coordinates
1073
+ latents_for_view = torch.cat(
1074
+ [
1075
+ latents_[:, :, h_start:h_end, w_start:w_end]
1076
+ for h_start, h_end, w_start, w_end in batch_view
1077
+ ]
1078
+ )
1079
+
1080
+ # expand the latents if we are doing classifier free guidance
1081
+ latent_model_input = latents_for_view
1082
+ latent_model_input = (
1083
+ latent_model_input.repeat_interleave(2, dim=0)
1084
+ if do_classifier_free_guidance
1085
+ else latent_model_input
1086
+ )
1087
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1088
+
1089
+ prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
1090
+ add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
1091
+ add_time_ids_input = []
1092
+ for h_start, h_end, w_start, w_end in batch_view:
1093
+ add_time_ids_ = add_time_ids.clone()
1094
+ add_time_ids_[:, 2] = h_start * self.vae_scale_factor
1095
+ add_time_ids_[:, 3] = w_start * self.vae_scale_factor
1096
+ add_time_ids_input.append(add_time_ids_)
1097
+ add_time_ids_input = torch.cat(add_time_ids_input)
1098
+
1099
+ # predict the noise residual
1100
+ added_cond_kwargs = {"text_embeds": add_text_embeds_input, "time_ids": add_time_ids_input}
1101
+ noise_pred = self.unet(
1102
+ latent_model_input,
1103
+ t,
1104
+ encoder_hidden_states=prompt_embeds_input,
1105
+ cross_attention_kwargs=cross_attention_kwargs,
1106
+ added_cond_kwargs=added_cond_kwargs,
1107
+ return_dict=False,
1108
+ )[0]
1109
+
1110
+ if do_classifier_free_guidance:
1111
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
1112
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1113
+
1114
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1115
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1116
+ noise_pred = rescale_noise_cfg(
1117
+ noise_pred, noise_pred_text, guidance_rescale=guidance_rescale
1118
+ )
1119
+
1120
+ # compute the previous noisy sample x_t -> x_t-1
1121
+ self.scheduler._init_step_index(t)
1122
+ latents_denoised_batch = self.scheduler.step(
1123
+ noise_pred, t, latents_for_view, **extra_step_kwargs, return_dict=False
1124
+ )[0]
1125
+
1126
+ # extract value from batch
1127
+ for latents_view_denoised, (h_start, h_end, w_start, w_end) in zip(
1128
+ latents_denoised_batch.chunk(vb_size), batch_view
1129
+ ):
1130
+ value_local[:, :, h_start:h_end, w_start:w_end] += latents_view_denoised
1131
+ count_local[:, :, h_start:h_end, w_start:w_end] += 1
1132
+
1133
+ value_local = value_local[
1134
+ :,
1135
+ :,
1136
+ jitter_range : jitter_range + current_height // self.vae_scale_factor,
1137
+ jitter_range : jitter_range + current_width // self.vae_scale_factor,
1138
+ ]
1139
+ count_local = count_local[
1140
+ :,
1141
+ :,
1142
+ jitter_range : jitter_range + current_height // self.vae_scale_factor,
1143
+ jitter_range : jitter_range + current_width // self.vae_scale_factor,
1144
+ ]
1145
+
1146
+ c2 = cosine_factor**cosine_scale_2
1147
+
1148
+ value += value_local / count_local * (1 - c2)
1149
+ count += torch.ones_like(value_local) * (1 - c2)
1150
+
1151
+ ############################################# Dilated Sampling #############################################
1152
+
1153
+ views = [[h, w] for h in range(current_scale_num) for w in range(current_scale_num)]
1154
+ views_batch = [views[i : i + view_batch_size] for i in range(0, len(views), view_batch_size)]
1155
+
1156
+ h_pad = (current_scale_num - (latents.size(2) % current_scale_num)) % current_scale_num
1157
+ w_pad = (current_scale_num - (latents.size(3) % current_scale_num)) % current_scale_num
1158
+ latents_ = F.pad(latents, (w_pad, 0, h_pad, 0), "constant", 0)
1159
+
1160
+ count_global = torch.zeros_like(latents_)
1161
+ value_global = torch.zeros_like(latents_)
1162
+
1163
+ c3 = 0.99 * cosine_factor**cosine_scale_3 + 1e-2
1164
+ std_, mean_ = latents_.std(), latents_.mean()
1165
+ latents_gaussian = gaussian_filter(
1166
+ latents_, kernel_size=(2 * current_scale_num - 1), sigma=sigma * c3
1167
+ )
1168
+ latents_gaussian = (
1169
+ latents_gaussian - latents_gaussian.mean()
1170
+ ) / latents_gaussian.std() * std_ + mean_
1171
+
1172
+ for j, batch_view in enumerate(views_batch):
1173
+ latents_for_view = torch.cat(
1174
+ [latents_[:, :, h::current_scale_num, w::current_scale_num] for h, w in batch_view]
1175
+ )
1176
+ latents_for_view_gaussian = torch.cat(
1177
+ [latents_gaussian[:, :, h::current_scale_num, w::current_scale_num] for h, w in batch_view]
1178
+ )
1179
+
1180
+ vb_size = latents_for_view.size(0)
1181
+
1182
+ # expand the latents if we are doing classifier free guidance
1183
+ latent_model_input = latents_for_view_gaussian
1184
+ latent_model_input = (
1185
+ latent_model_input.repeat_interleave(2, dim=0)
1186
+ if do_classifier_free_guidance
1187
+ else latent_model_input
1188
+ )
1189
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1190
+
1191
+ prompt_embeds_input = torch.cat([prompt_embeds] * vb_size)
1192
+ add_text_embeds_input = torch.cat([add_text_embeds] * vb_size)
1193
+ add_time_ids_input = torch.cat([add_time_ids] * vb_size)
1194
+
1195
+ # predict the noise residual
1196
+ added_cond_kwargs = {"text_embeds": add_text_embeds_input, "time_ids": add_time_ids_input}
1197
+ noise_pred = self.unet(
1198
+ latent_model_input,
1199
+ t,
1200
+ encoder_hidden_states=prompt_embeds_input,
1201
+ cross_attention_kwargs=cross_attention_kwargs,
1202
+ added_cond_kwargs=added_cond_kwargs,
1203
+ return_dict=False,
1204
+ )[0]
1205
+
1206
+ if do_classifier_free_guidance:
1207
+ noise_pred_uncond, noise_pred_text = noise_pred[::2], noise_pred[1::2]
1208
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1209
+
1210
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1211
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1212
+ noise_pred = rescale_noise_cfg(
1213
+ noise_pred, noise_pred_text, guidance_rescale=guidance_rescale
1214
+ )
1215
+
1216
+ # compute the previous noisy sample x_t -> x_t-1
1217
+ self.scheduler._init_step_index(t)
1218
+ latents_denoised_batch = self.scheduler.step(
1219
+ noise_pred, t, latents_for_view, **extra_step_kwargs, return_dict=False
1220
+ )[0]
1221
+
1222
+ # extract value from batch
1223
+ for latents_view_denoised, (h, w) in zip(latents_denoised_batch.chunk(vb_size), batch_view):
1224
+ value_global[:, :, h::current_scale_num, w::current_scale_num] += latents_view_denoised
1225
+ count_global[:, :, h::current_scale_num, w::current_scale_num] += 1
1226
+
1227
+ c2 = cosine_factor**cosine_scale_2
1228
+
1229
+ value_global = value_global[:, :, h_pad:, w_pad:]
1230
+
1231
+ value += value_global * c2
1232
+ count += torch.ones_like(value_global) * c2
1233
+
1234
+ ###########################################################
1235
+
1236
+ latents = torch.where(count > 0, value / count, value)
1237
+
1238
+ # call the callback, if provided
1239
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1240
+ progress_bar.update()
1241
+ if callback is not None and i % callback_steps == 0:
1242
+ step_idx = i // getattr(self.scheduler, "order", 1)
1243
+ callback(step_idx, t, latents)
1244
+
1245
+ #########################################################################################################################################
1246
+
1247
+ latents = (latents - latents.mean()) / latents.std() * anchor_std + anchor_mean
1248
+ if not output_type == "latent":
1249
+ # make sure the VAE is in float32 mode, as it overflows in float16
1250
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1251
+
1252
+ if needs_upcasting:
1253
+ self.upcast_vae()
1254
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1255
+
1256
+ print("### Phase {} Decoding ###".format(current_scale_num))
1257
+ if multi_decoder:
1258
+ image = self.tiled_decode(latents, current_height, current_width)
1259
+ else:
1260
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1261
+
1262
+ # cast back to fp16 if needed
1263
+ if needs_upcasting:
1264
+ self.vae.to(dtype=torch.float16)
1265
+ else:
1266
+ image = latents
1267
+
1268
+ if not output_type == "latent":
1269
+ image = self.image_processor.postprocess(image, output_type=output_type)
1270
+ if show_image:
1271
+ plt.figure(figsize=(10, 10))
1272
+ plt.imshow(image[0])
1273
+ plt.axis("off") # Turn off axis numbers and ticks
1274
+ plt.show()
1275
+ output_images.append(image[0])
1276
+
1277
+ # Offload all models
1278
+ self.maybe_free_model_hooks()
1279
+
1280
+ return output_images
1281
+
1282
+ # Override to properly handle the loading and unloading of the additional text encoder.
1283
+ def load_lora_weights(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
1284
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1285
+ # it here explicitly to be able to tell that it's coming from an SDXL
1286
+ # pipeline.
1287
+
1288
+ # Remove any existing hooks.
1289
+ if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
1290
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
1291
+ else:
1292
+ raise ImportError("Offloading requires `accelerate v0.17.0` or higher.")
1293
+
1294
+ is_model_cpu_offload = False
1295
+ is_sequential_cpu_offload = False
1296
+ recursive = False
1297
+ for _, component in self.components.items():
1298
+ if isinstance(component, torch.nn.Module):
1299
+ if hasattr(component, "_hf_hook"):
1300
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
1301
+ is_sequential_cpu_offload = (
1302
+ isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
1303
+ or hasattr(component._hf_hook, "hooks")
1304
+ and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
1305
+ )
1306
+ logger.info(
1307
+ "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
1308
+ )
1309
+ recursive = is_sequential_cpu_offload
1310
+ remove_hook_from_module(component, recurse=recursive)
1311
+ state_dict, network_alphas = self.lora_state_dict(
1312
+ pretrained_model_name_or_path_or_dict,
1313
+ unet_config=self.unet.config,
1314
+ **kwargs,
1315
+ )
1316
+ self.load_lora_into_unet(state_dict, network_alphas=network_alphas, unet=self.unet)
1317
+
1318
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1319
+ if len(text_encoder_state_dict) > 0:
1320
+ self.load_lora_into_text_encoder(
1321
+ text_encoder_state_dict,
1322
+ network_alphas=network_alphas,
1323
+ text_encoder=self.text_encoder,
1324
+ prefix="text_encoder",
1325
+ lora_scale=self.lora_scale,
1326
+ )
1327
+
1328
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1329
+ if len(text_encoder_2_state_dict) > 0:
1330
+ self.load_lora_into_text_encoder(
1331
+ text_encoder_2_state_dict,
1332
+ network_alphas=network_alphas,
1333
+ text_encoder=self.text_encoder_2,
1334
+ prefix="text_encoder_2",
1335
+ lora_scale=self.lora_scale,
1336
+ )
1337
+
1338
+ # Offload back.
1339
+ if is_model_cpu_offload:
1340
+ self.enable_model_cpu_offload()
1341
+ elif is_sequential_cpu_offload:
1342
+ self.enable_sequential_cpu_offload()
1343
+
1344
+ @classmethod
1345
+ def save_lora_weights(
1346
+ cls,
1347
+ save_directory: Union[str, os.PathLike],
1348
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1349
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1350
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1351
+ is_main_process: bool = True,
1352
+ weight_name: str = None,
1353
+ save_function: Callable = None,
1354
+ safe_serialization: bool = True,
1355
+ ):
1356
+ state_dict = {}
1357
+
1358
+ def pack_weights(layers, prefix):
1359
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1360
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1361
+ return layers_state_dict
1362
+
1363
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1364
+ raise ValueError(
1365
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1366
+ )
1367
+
1368
+ if unet_lora_layers:
1369
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1370
+
1371
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1372
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1373
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1374
+
1375
+ cls.write_lora_layers(
1376
+ state_dict=state_dict,
1377
+ save_directory=save_directory,
1378
+ is_main_process=is_main_process,
1379
+ weight_name=weight_name,
1380
+ save_function=save_function,
1381
+ safe_serialization=safe_serialization,
1382
+ )
1383
+
1384
+ def _remove_text_encoder_monkey_patch(self):
1385
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1386
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
v0.32.0/pipeline_fabric.py ADDED
@@ -0,0 +1,751 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 FABRIC authors and the HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import List, Optional, Union
15
+
16
+ import torch
17
+ from packaging import version
18
+ from PIL import Image
19
+ from transformers import CLIPTextModel, CLIPTokenizer
20
+
21
+ from diffusers import AutoencoderKL, UNet2DConditionModel
22
+ from diffusers.configuration_utils import FrozenDict
23
+ from diffusers.image_processor import VaeImageProcessor
24
+ from diffusers.loaders import StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
25
+ from diffusers.models.attention import BasicTransformerBlock
26
+ from diffusers.models.attention_processor import LoRAAttnProcessor
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
29
+ from diffusers.schedulers import EulerAncestralDiscreteScheduler, KarrasDiffusionSchedulers
30
+ from diffusers.utils import (
31
+ deprecate,
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from diffusers.utils.torch_utils import randn_tensor
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+ EXAMPLE_DOC_STRING = """
41
+ Examples:
42
+ ```py
43
+ >>> from diffusers import DiffusionPipeline
44
+ >>> import torch
45
+
46
+ >>> model_id = "dreamlike-art/dreamlike-photoreal-2.0"
47
+ >>> pipe = DiffusionPipeline(model_id, torch_dtype=torch.float16, custom_pipeline="pipeline_fabric")
48
+ >>> pipe = pipe.to("cuda")
49
+ >>> prompt = "a giant standing in a fantasy landscape best quality"
50
+ >>> liked = [] # list of images for positive feedback
51
+ >>> disliked = [] # list of images for negative feedback
52
+ >>> image = pipe(prompt, num_images=4, liked=liked, disliked=disliked).images[0]
53
+ ```
54
+ """
55
+
56
+
57
+ class FabricCrossAttnProcessor:
58
+ def __init__(self):
59
+ self.attntion_probs = None
60
+
61
+ def __call__(
62
+ self,
63
+ attn,
64
+ hidden_states,
65
+ encoder_hidden_states=None,
66
+ attention_mask=None,
67
+ weights=None,
68
+ lora_scale=1.0,
69
+ ):
70
+ batch_size, sequence_length, _ = (
71
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
72
+ )
73
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
74
+
75
+ if isinstance(attn.processor, LoRAAttnProcessor):
76
+ query = attn.to_q(hidden_states) + lora_scale * attn.processor.to_q_lora(hidden_states)
77
+ else:
78
+ query = attn.to_q(hidden_states)
79
+
80
+ if encoder_hidden_states is None:
81
+ encoder_hidden_states = hidden_states
82
+ elif attn.norm_cross:
83
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
84
+
85
+ if isinstance(attn.processor, LoRAAttnProcessor):
86
+ key = attn.to_k(encoder_hidden_states) + lora_scale * attn.processor.to_k_lora(encoder_hidden_states)
87
+ value = attn.to_v(encoder_hidden_states) + lora_scale * attn.processor.to_v_lora(encoder_hidden_states)
88
+ else:
89
+ key = attn.to_k(encoder_hidden_states)
90
+ value = attn.to_v(encoder_hidden_states)
91
+
92
+ query = attn.head_to_batch_dim(query)
93
+ key = attn.head_to_batch_dim(key)
94
+ value = attn.head_to_batch_dim(value)
95
+
96
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
97
+
98
+ if weights is not None:
99
+ if weights.shape[0] != 1:
100
+ weights = weights.repeat_interleave(attn.heads, dim=0)
101
+ attention_probs = attention_probs * weights[:, None]
102
+ attention_probs = attention_probs / attention_probs.sum(dim=-1, keepdim=True)
103
+
104
+ hidden_states = torch.bmm(attention_probs, value)
105
+ hidden_states = attn.batch_to_head_dim(hidden_states)
106
+
107
+ # linear proj
108
+ if isinstance(attn.processor, LoRAAttnProcessor):
109
+ hidden_states = attn.to_out[0](hidden_states) + lora_scale * attn.processor.to_out_lora(hidden_states)
110
+ else:
111
+ hidden_states = attn.to_out[0](hidden_states)
112
+ # dropout
113
+ hidden_states = attn.to_out[1](hidden_states)
114
+
115
+ return hidden_states
116
+
117
+
118
+ class FabricPipeline(DiffusionPipeline):
119
+ r"""
120
+ Pipeline for text-to-image generation using Stable Diffusion and conditioning the results using feedback images.
121
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
122
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
123
+
124
+ Args:
125
+ vae ([`AutoencoderKL`]):
126
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
127
+ text_encoder ([`~transformers.CLIPTextModel`]):
128
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
129
+ tokenizer ([`~transformers.CLIPTokenizer`]):
130
+ A `CLIPTokenizer` to tokenize text.
131
+ unet ([`UNet2DConditionModel`]):
132
+ A `UNet2DConditionModel` to denoise the encoded image latents.
133
+ scheduler ([`EulerAncestralDiscreteScheduler`]):
134
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
135
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
136
+ safety_checker ([`StableDiffusionSafetyChecker`]):
137
+ Classification module that estimates whether generated images could be considered offensive or harmful.
138
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
139
+ about a model's potential harms.
140
+ """
141
+
142
+ def __init__(
143
+ self,
144
+ vae: AutoencoderKL,
145
+ text_encoder: CLIPTextModel,
146
+ tokenizer: CLIPTokenizer,
147
+ unet: UNet2DConditionModel,
148
+ scheduler: KarrasDiffusionSchedulers,
149
+ requires_safety_checker: bool = True,
150
+ ):
151
+ super().__init__()
152
+
153
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
154
+ version.parse(unet.config._diffusers_version).base_version
155
+ ) < version.parse("0.9.0.dev0")
156
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
157
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
158
+ deprecation_message = (
159
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
160
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
161
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
162
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
163
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
164
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
165
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
166
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
167
+ " the `unet/config.json` file"
168
+ )
169
+
170
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
171
+ new_config = dict(unet.config)
172
+ new_config["sample_size"] = 64
173
+ unet._internal_dict = FrozenDict(new_config)
174
+
175
+ self.register_modules(
176
+ unet=unet,
177
+ vae=vae,
178
+ text_encoder=text_encoder,
179
+ tokenizer=tokenizer,
180
+ scheduler=scheduler,
181
+ )
182
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
183
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
184
+
185
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
186
+ def _encode_prompt(
187
+ self,
188
+ prompt,
189
+ device,
190
+ num_images_per_prompt,
191
+ do_classifier_free_guidance,
192
+ negative_prompt=None,
193
+ prompt_embeds: Optional[torch.Tensor] = None,
194
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
195
+ lora_scale: Optional[float] = None,
196
+ ):
197
+ r"""
198
+ Encodes the prompt into text encoder hidden states.
199
+
200
+ Args:
201
+ prompt (`str` or `List[str]`, *optional*):
202
+ prompt to be encoded
203
+ device: (`torch.device`):
204
+ torch device
205
+ num_images_per_prompt (`int`):
206
+ number of images that should be generated per prompt
207
+ do_classifier_free_guidance (`bool`):
208
+ whether to use classifier free guidance or not
209
+ negative_prompt (`str` or `List[str]`, *optional*):
210
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
211
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
212
+ less than `1`).
213
+ prompt_embeds (`torch.Tensor`, *optional*):
214
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
215
+ provided, text embeddings will be generated from `prompt` input argument.
216
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
217
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
218
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
219
+ argument.
220
+ lora_scale (`float`, *optional*):
221
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
222
+ """
223
+ # set lora scale so that monkey patched LoRA
224
+ # function of text encoder can correctly access it
225
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
226
+ self._lora_scale = lora_scale
227
+
228
+ if prompt is not None and isinstance(prompt, str):
229
+ batch_size = 1
230
+ elif prompt is not None and isinstance(prompt, list):
231
+ batch_size = len(prompt)
232
+ else:
233
+ batch_size = prompt_embeds.shape[0]
234
+
235
+ if prompt_embeds is None:
236
+ # textual inversion: process multi-vector tokens if necessary
237
+ if isinstance(self, TextualInversionLoaderMixin):
238
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
239
+
240
+ text_inputs = self.tokenizer(
241
+ prompt,
242
+ padding="max_length",
243
+ max_length=self.tokenizer.model_max_length,
244
+ truncation=True,
245
+ return_tensors="pt",
246
+ )
247
+ text_input_ids = text_inputs.input_ids
248
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
249
+
250
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
251
+ text_input_ids, untruncated_ids
252
+ ):
253
+ removed_text = self.tokenizer.batch_decode(
254
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
255
+ )
256
+ logger.warning(
257
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
258
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
259
+ )
260
+
261
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
262
+ attention_mask = text_inputs.attention_mask.to(device)
263
+ else:
264
+ attention_mask = None
265
+
266
+ prompt_embeds = self.text_encoder(
267
+ text_input_ids.to(device),
268
+ attention_mask=attention_mask,
269
+ )
270
+ prompt_embeds = prompt_embeds[0]
271
+
272
+ if self.text_encoder is not None:
273
+ prompt_embeds_dtype = self.text_encoder.dtype
274
+ elif self.unet is not None:
275
+ prompt_embeds_dtype = self.unet.dtype
276
+ else:
277
+ prompt_embeds_dtype = prompt_embeds.dtype
278
+
279
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
280
+
281
+ bs_embed, seq_len, _ = prompt_embeds.shape
282
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
283
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
284
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
285
+
286
+ # get unconditional embeddings for classifier free guidance
287
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
288
+ uncond_tokens: List[str]
289
+ if negative_prompt is None:
290
+ uncond_tokens = [""] * batch_size
291
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
292
+ raise TypeError(
293
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
294
+ f" {type(prompt)}."
295
+ )
296
+ elif isinstance(negative_prompt, str):
297
+ uncond_tokens = [negative_prompt]
298
+ elif batch_size != len(negative_prompt):
299
+ raise ValueError(
300
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
301
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
302
+ " the batch size of `prompt`."
303
+ )
304
+ else:
305
+ uncond_tokens = negative_prompt
306
+
307
+ # textual inversion: process multi-vector tokens if necessary
308
+ if isinstance(self, TextualInversionLoaderMixin):
309
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
310
+
311
+ max_length = prompt_embeds.shape[1]
312
+ uncond_input = self.tokenizer(
313
+ uncond_tokens,
314
+ padding="max_length",
315
+ max_length=max_length,
316
+ truncation=True,
317
+ return_tensors="pt",
318
+ )
319
+
320
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
321
+ attention_mask = uncond_input.attention_mask.to(device)
322
+ else:
323
+ attention_mask = None
324
+
325
+ negative_prompt_embeds = self.text_encoder(
326
+ uncond_input.input_ids.to(device),
327
+ attention_mask=attention_mask,
328
+ )
329
+ negative_prompt_embeds = negative_prompt_embeds[0]
330
+
331
+ if do_classifier_free_guidance:
332
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
333
+ seq_len = negative_prompt_embeds.shape[1]
334
+
335
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
336
+
337
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
338
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
339
+
340
+ # For classifier free guidance, we need to do two forward passes.
341
+ # Here we concatenate the unconditional and text embeddings into a single batch
342
+ # to avoid doing two forward passes
343
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
344
+
345
+ return prompt_embeds
346
+
347
+ def get_unet_hidden_states(self, z_all, t, prompt_embd):
348
+ cached_hidden_states = []
349
+ for module in self.unet.modules():
350
+ if isinstance(module, BasicTransformerBlock):
351
+
352
+ def new_forward(self, hidden_states, *args, **kwargs):
353
+ cached_hidden_states.append(hidden_states.clone().detach().cpu())
354
+ return self.old_forward(hidden_states, *args, **kwargs)
355
+
356
+ module.attn1.old_forward = module.attn1.forward
357
+ module.attn1.forward = new_forward.__get__(module.attn1)
358
+
359
+ # run forward pass to cache hidden states, output can be discarded
360
+ _ = self.unet(z_all, t, encoder_hidden_states=prompt_embd)
361
+
362
+ # restore original forward pass
363
+ for module in self.unet.modules():
364
+ if isinstance(module, BasicTransformerBlock):
365
+ module.attn1.forward = module.attn1.old_forward
366
+ del module.attn1.old_forward
367
+
368
+ return cached_hidden_states
369
+
370
+ def unet_forward_with_cached_hidden_states(
371
+ self,
372
+ z_all,
373
+ t,
374
+ prompt_embd,
375
+ cached_pos_hiddens: Optional[List[torch.Tensor]] = None,
376
+ cached_neg_hiddens: Optional[List[torch.Tensor]] = None,
377
+ pos_weights=(0.8, 0.8),
378
+ neg_weights=(0.5, 0.5),
379
+ ):
380
+ if cached_pos_hiddens is None and cached_neg_hiddens is None:
381
+ return self.unet(z_all, t, encoder_hidden_states=prompt_embd)
382
+
383
+ local_pos_weights = torch.linspace(*pos_weights, steps=len(self.unet.down_blocks) + 1)[:-1].tolist()
384
+ local_neg_weights = torch.linspace(*neg_weights, steps=len(self.unet.down_blocks) + 1)[:-1].tolist()
385
+ for block, pos_weight, neg_weight in zip(
386
+ self.unet.down_blocks + [self.unet.mid_block] + self.unet.up_blocks,
387
+ local_pos_weights + [pos_weights[1]] + local_pos_weights[::-1],
388
+ local_neg_weights + [neg_weights[1]] + local_neg_weights[::-1],
389
+ ):
390
+ for module in block.modules():
391
+ if isinstance(module, BasicTransformerBlock):
392
+
393
+ def new_forward(
394
+ self,
395
+ hidden_states,
396
+ pos_weight=pos_weight,
397
+ neg_weight=neg_weight,
398
+ **kwargs,
399
+ ):
400
+ cond_hiddens, uncond_hiddens = hidden_states.chunk(2, dim=0)
401
+ batch_size, d_model = cond_hiddens.shape[:2]
402
+ device, dtype = hidden_states.device, hidden_states.dtype
403
+
404
+ weights = torch.ones(batch_size, d_model, device=device, dtype=dtype)
405
+ out_pos = self.old_forward(hidden_states)
406
+ out_neg = self.old_forward(hidden_states)
407
+
408
+ if cached_pos_hiddens is not None:
409
+ cached_pos_hs = cached_pos_hiddens.pop(0).to(hidden_states.device)
410
+ cond_pos_hs = torch.cat([cond_hiddens, cached_pos_hs], dim=1)
411
+ pos_weights = weights.clone().repeat(1, 1 + cached_pos_hs.shape[1] // d_model)
412
+ pos_weights[:, d_model:] = pos_weight
413
+ attn_with_weights = FabricCrossAttnProcessor()
414
+ out_pos = attn_with_weights(
415
+ self,
416
+ cond_hiddens,
417
+ encoder_hidden_states=cond_pos_hs,
418
+ weights=pos_weights,
419
+ )
420
+ else:
421
+ out_pos = self.old_forward(cond_hiddens)
422
+
423
+ if cached_neg_hiddens is not None:
424
+ cached_neg_hs = cached_neg_hiddens.pop(0).to(hidden_states.device)
425
+ uncond_neg_hs = torch.cat([uncond_hiddens, cached_neg_hs], dim=1)
426
+ neg_weights = weights.clone().repeat(1, 1 + cached_neg_hs.shape[1] // d_model)
427
+ neg_weights[:, d_model:] = neg_weight
428
+ attn_with_weights = FabricCrossAttnProcessor()
429
+ out_neg = attn_with_weights(
430
+ self,
431
+ uncond_hiddens,
432
+ encoder_hidden_states=uncond_neg_hs,
433
+ weights=neg_weights,
434
+ )
435
+ else:
436
+ out_neg = self.old_forward(uncond_hiddens)
437
+
438
+ out = torch.cat([out_pos, out_neg], dim=0)
439
+ return out
440
+
441
+ module.attn1.old_forward = module.attn1.forward
442
+ module.attn1.forward = new_forward.__get__(module.attn1)
443
+
444
+ out = self.unet(z_all, t, encoder_hidden_states=prompt_embd)
445
+
446
+ # restore original forward pass
447
+ for module in self.unet.modules():
448
+ if isinstance(module, BasicTransformerBlock):
449
+ module.attn1.forward = module.attn1.old_forward
450
+ del module.attn1.old_forward
451
+
452
+ return out
453
+
454
+ def preprocess_feedback_images(self, images, vae, dim, device, dtype, generator) -> torch.tensor:
455
+ images_t = [self.image_to_tensor(img, dim, dtype) for img in images]
456
+ images_t = torch.stack(images_t).to(device)
457
+ latents = vae.config.scaling_factor * vae.encode(images_t).latent_dist.sample(generator)
458
+
459
+ return torch.cat([latents], dim=0)
460
+
461
+ def check_inputs(
462
+ self,
463
+ prompt,
464
+ negative_prompt=None,
465
+ liked=None,
466
+ disliked=None,
467
+ height=None,
468
+ width=None,
469
+ ):
470
+ if prompt is None:
471
+ raise ValueError("Provide `prompt`. Cannot leave both `prompt` undefined.")
472
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
473
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
474
+
475
+ if negative_prompt is not None and (
476
+ not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
477
+ ):
478
+ raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
479
+
480
+ if liked is not None and not isinstance(liked, list):
481
+ raise ValueError(f"`liked` has to be of type `list` but is {type(liked)}")
482
+
483
+ if disliked is not None and not isinstance(disliked, list):
484
+ raise ValueError(f"`disliked` has to be of type `list` but is {type(disliked)}")
485
+
486
+ if height is not None and not isinstance(height, int):
487
+ raise ValueError(f"`height` has to be of type `int` but is {type(height)}")
488
+
489
+ if width is not None and not isinstance(width, int):
490
+ raise ValueError(f"`width` has to be of type `int` but is {type(width)}")
491
+
492
+ @torch.no_grad()
493
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
494
+ def __call__(
495
+ self,
496
+ prompt: Optional[Union[str, List[str]]] = "",
497
+ negative_prompt: Optional[Union[str, List[str]]] = "lowres, bad anatomy, bad hands, cropped, worst quality",
498
+ liked: Optional[Union[List[str], List[Image.Image]]] = [],
499
+ disliked: Optional[Union[List[str], List[Image.Image]]] = [],
500
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
501
+ height: int = 512,
502
+ width: int = 512,
503
+ return_dict: bool = True,
504
+ num_images: int = 4,
505
+ guidance_scale: float = 7.0,
506
+ num_inference_steps: int = 20,
507
+ output_type: Optional[str] = "pil",
508
+ feedback_start_ratio: float = 0.33,
509
+ feedback_end_ratio: float = 0.66,
510
+ min_weight: float = 0.05,
511
+ max_weight: float = 0.8,
512
+ neg_scale: float = 0.5,
513
+ pos_bottleneck_scale: float = 1.0,
514
+ neg_bottleneck_scale: float = 1.0,
515
+ latents: Optional[torch.Tensor] = None,
516
+ ):
517
+ r"""
518
+ The call function to the pipeline for generation. Generate a trajectory of images with binary feedback. The
519
+ feedback can be given as a list of liked and disliked images.
520
+
521
+ Args:
522
+ prompt (`str` or `List[str]`, *optional*):
523
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`
524
+ instead.
525
+ negative_prompt (`str` or `List[str]`, *optional*):
526
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
527
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
528
+ liked (`List[Image.Image]` or `List[str]`, *optional*):
529
+ Encourages images with liked features.
530
+ disliked (`List[Image.Image]` or `List[str]`, *optional*):
531
+ Discourages images with disliked features.
532
+ generator (`torch.Generator` or `List[torch.Generator]` or `int`, *optional*):
533
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) or an `int` to
534
+ make generation deterministic.
535
+ height (`int`, *optional*, defaults to 512):
536
+ Height of the generated image.
537
+ width (`int`, *optional*, defaults to 512):
538
+ Width of the generated image.
539
+ num_images (`int`, *optional*, defaults to 4):
540
+ The number of images to generate per prompt.
541
+ guidance_scale (`float`, *optional*, defaults to 7.0):
542
+ A higher guidance scale value encourages the model to generate images closely linked to the text
543
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
544
+ num_inference_steps (`int`, *optional*, defaults to 20):
545
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
546
+ expense of slower inference.
547
+ output_type (`str`, *optional*, defaults to `"pil"`):
548
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
549
+ return_dict (`bool`, *optional*, defaults to `True`):
550
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
551
+ plain tuple.
552
+ feedback_start_ratio (`float`, *optional*, defaults to `.33`):
553
+ Start point for providing feedback (between 0 and 1).
554
+ feedback_end_ratio (`float`, *optional*, defaults to `.66`):
555
+ End point for providing feedback (between 0 and 1).
556
+ min_weight (`float`, *optional*, defaults to `.05`):
557
+ Minimum weight for feedback.
558
+ max_weight (`float`, *optional*, defults tp `1.0`):
559
+ Maximum weight for feedback.
560
+ neg_scale (`float`, *optional*, defaults to `.5`):
561
+ Scale factor for negative feedback.
562
+
563
+ Examples:
564
+
565
+ Returns:
566
+ [`~pipelines.fabric.FabricPipelineOutput`] or `tuple`:
567
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
568
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
569
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
570
+ "not-safe-for-work" (nsfw) content.
571
+
572
+ """
573
+
574
+ self.check_inputs(prompt, negative_prompt, liked, disliked)
575
+
576
+ device = self._execution_device
577
+ dtype = self.unet.dtype
578
+
579
+ if isinstance(prompt, str) and prompt is not None:
580
+ batch_size = 1
581
+ elif isinstance(prompt, list) and prompt is not None:
582
+ batch_size = len(prompt)
583
+ else:
584
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
585
+
586
+ if isinstance(negative_prompt, str):
587
+ negative_prompt = negative_prompt
588
+ elif isinstance(negative_prompt, list):
589
+ negative_prompt = negative_prompt
590
+ else:
591
+ assert len(negative_prompt) == batch_size
592
+
593
+ shape = (
594
+ batch_size * num_images,
595
+ self.unet.config.in_channels,
596
+ height // self.vae_scale_factor,
597
+ width // self.vae_scale_factor,
598
+ )
599
+ latent_noise = randn_tensor(
600
+ shape,
601
+ device=device,
602
+ dtype=dtype,
603
+ generator=generator,
604
+ )
605
+
606
+ positive_latents = (
607
+ self.preprocess_feedback_images(liked, self.vae, (height, width), device, dtype, generator)
608
+ if liked and len(liked) > 0
609
+ else torch.tensor(
610
+ [],
611
+ device=device,
612
+ dtype=dtype,
613
+ )
614
+ )
615
+ negative_latents = (
616
+ self.preprocess_feedback_images(disliked, self.vae, (height, width), device, dtype, generator)
617
+ if disliked and len(disliked) > 0
618
+ else torch.tensor(
619
+ [],
620
+ device=device,
621
+ dtype=dtype,
622
+ )
623
+ )
624
+
625
+ do_classifier_free_guidance = guidance_scale > 0.1
626
+
627
+ (prompt_neg_embs, prompt_pos_embs) = self._encode_prompt(
628
+ prompt,
629
+ device,
630
+ num_images,
631
+ do_classifier_free_guidance,
632
+ negative_prompt,
633
+ ).split([num_images * batch_size, num_images * batch_size])
634
+
635
+ batched_prompt_embd = torch.cat([prompt_pos_embs, prompt_neg_embs], dim=0)
636
+
637
+ null_tokens = self.tokenizer(
638
+ [""],
639
+ return_tensors="pt",
640
+ max_length=self.tokenizer.model_max_length,
641
+ padding="max_length",
642
+ truncation=True,
643
+ )
644
+
645
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
646
+ attention_mask = null_tokens.attention_mask.to(device)
647
+ else:
648
+ attention_mask = None
649
+
650
+ null_prompt_emb = self.text_encoder(
651
+ input_ids=null_tokens.input_ids.to(device),
652
+ attention_mask=attention_mask,
653
+ ).last_hidden_state
654
+
655
+ null_prompt_emb = null_prompt_emb.to(device=device, dtype=dtype)
656
+
657
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
658
+ timesteps = self.scheduler.timesteps
659
+ latent_noise = latent_noise * self.scheduler.init_noise_sigma
660
+
661
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
662
+
663
+ ref_start_idx = round(len(timesteps) * feedback_start_ratio)
664
+ ref_end_idx = round(len(timesteps) * feedback_end_ratio)
665
+
666
+ with self.progress_bar(total=num_inference_steps) as pbar:
667
+ for i, t in enumerate(timesteps):
668
+ sigma = self.scheduler.sigma_t[t] if hasattr(self.scheduler, "sigma_t") else 0
669
+ if hasattr(self.scheduler, "sigmas"):
670
+ sigma = self.scheduler.sigmas[i]
671
+
672
+ alpha_hat = 1 / (sigma**2 + 1)
673
+
674
+ z_single = self.scheduler.scale_model_input(latent_noise, t)
675
+ z_all = torch.cat([z_single] * 2, dim=0)
676
+ z_ref = torch.cat([positive_latents, negative_latents], dim=0)
677
+
678
+ if i >= ref_start_idx and i <= ref_end_idx:
679
+ weight_factor = max_weight
680
+ else:
681
+ weight_factor = min_weight
682
+
683
+ pos_ws = (weight_factor, weight_factor * pos_bottleneck_scale)
684
+ neg_ws = (weight_factor * neg_scale, weight_factor * neg_scale * neg_bottleneck_scale)
685
+
686
+ if z_ref.size(0) > 0 and weight_factor > 0:
687
+ noise = torch.randn_like(z_ref)
688
+ if isinstance(self.scheduler, EulerAncestralDiscreteScheduler):
689
+ z_ref_noised = (alpha_hat**0.5 * z_ref + (1 - alpha_hat) ** 0.5 * noise).type(dtype)
690
+ else:
691
+ z_ref_noised = self.scheduler.add_noise(z_ref, noise, t)
692
+
693
+ ref_prompt_embd = torch.cat(
694
+ [null_prompt_emb] * (len(positive_latents) + len(negative_latents)), dim=0
695
+ )
696
+ cached_hidden_states = self.get_unet_hidden_states(z_ref_noised, t, ref_prompt_embd)
697
+
698
+ n_pos, n_neg = positive_latents.shape[0], negative_latents.shape[0]
699
+ cached_pos_hs, cached_neg_hs = [], []
700
+ for hs in cached_hidden_states:
701
+ cached_pos, cached_neg = hs.split([n_pos, n_neg], dim=0)
702
+ cached_pos = cached_pos.view(1, -1, *cached_pos.shape[2:]).expand(num_images, -1, -1)
703
+ cached_neg = cached_neg.view(1, -1, *cached_neg.shape[2:]).expand(num_images, -1, -1)
704
+ cached_pos_hs.append(cached_pos)
705
+ cached_neg_hs.append(cached_neg)
706
+
707
+ if n_pos == 0:
708
+ cached_pos_hs = None
709
+ if n_neg == 0:
710
+ cached_neg_hs = None
711
+ else:
712
+ cached_pos_hs, cached_neg_hs = None, None
713
+ unet_out = self.unet_forward_with_cached_hidden_states(
714
+ z_all,
715
+ t,
716
+ prompt_embd=batched_prompt_embd,
717
+ cached_pos_hiddens=cached_pos_hs,
718
+ cached_neg_hiddens=cached_neg_hs,
719
+ pos_weights=pos_ws,
720
+ neg_weights=neg_ws,
721
+ )[0]
722
+
723
+ noise_cond, noise_uncond = unet_out.chunk(2)
724
+ guidance = noise_cond - noise_uncond
725
+ noise_pred = noise_uncond + guidance_scale * guidance
726
+ latent_noise = self.scheduler.step(noise_pred, t, latent_noise)[0]
727
+
728
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
729
+ pbar.update()
730
+
731
+ y = self.vae.decode(latent_noise / self.vae.config.scaling_factor, return_dict=False)[0]
732
+ imgs = self.image_processor.postprocess(
733
+ y,
734
+ output_type=output_type,
735
+ )
736
+
737
+ if not return_dict:
738
+ return imgs
739
+
740
+ return StableDiffusionPipelineOutput(imgs, False)
741
+
742
+ def image_to_tensor(self, image: Union[str, Image.Image], dim: tuple, dtype):
743
+ """
744
+ Convert latent PIL image to a torch tensor for further processing.
745
+ """
746
+ if isinstance(image, str):
747
+ image = Image.open(image)
748
+ if not image.mode == "RGB":
749
+ image = image.convert("RGB")
750
+ image = self.image_processor.preprocess(image, height=dim[0], width=dim[1])[0]
751
+ return image.type(dtype)
v0.32.0/pipeline_flux_differential_img2img.py ADDED
@@ -0,0 +1,1024 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
22
+
23
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
24
+ from diffusers.loaders import FluxLoraLoaderMixin
25
+ from diffusers.models.autoencoders import AutoencoderKL
26
+ from diffusers.models.transformers import FluxTransformer2DModel
27
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
28
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
29
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
30
+ from diffusers.utils import (
31
+ USE_PEFT_BACKEND,
32
+ is_torch_xla_available,
33
+ logging,
34
+ replace_example_docstring,
35
+ scale_lora_layers,
36
+ unscale_lora_layers,
37
+ )
38
+ from diffusers.utils.torch_utils import randn_tensor
39
+
40
+
41
+ if is_torch_xla_available():
42
+ import torch_xla.core.xla_model as xm
43
+
44
+ XLA_AVAILABLE = True
45
+ else:
46
+ XLA_AVAILABLE = False
47
+
48
+
49
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
50
+
51
+ EXAMPLE_DOC_STRING = """
52
+ Examples:
53
+ ```py
54
+ >>> import torch
55
+ >>> from diffusers.utils import load_image
56
+ >>> from pipeline import FluxDifferentialImg2ImgPipeline
57
+
58
+ >>> image = load_image(
59
+ >>> "https://github.com/exx8/differential-diffusion/blob/main/assets/input.jpg?raw=true",
60
+ >>> )
61
+
62
+ >>> mask = load_image(
63
+ >>> "https://github.com/exx8/differential-diffusion/blob/main/assets/map.jpg?raw=true",
64
+ >>> )
65
+
66
+ >>> pipe = FluxDifferentialImg2ImgPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
67
+ >>> pipe.enable_model_cpu_offload()
68
+
69
+ >>> prompt = "painting of a mountain landscape with a meadow and a forest, meadow background, anime countryside landscape, anime nature wallpap, anime landscape wallpaper, studio ghibli landscape, anime landscape, mountain behind meadow, anime background art, studio ghibli environment, background of flowery hill, anime beautiful peace scene, forrest background, anime scenery, landscape background, background art, anime scenery concept art"
70
+ >>> out = pipe(
71
+ >>> prompt=prompt,
72
+ >>> num_inference_steps=20,
73
+ >>> guidance_scale=7.5,
74
+ >>> image=image,
75
+ >>> mask_image=mask,
76
+ >>> strength=1.0,
77
+ >>> ).images[0]
78
+
79
+ >>> out.save("image.png")
80
+ ```
81
+ """
82
+
83
+
84
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
85
+ def calculate_shift(
86
+ image_seq_len,
87
+ base_seq_len: int = 256,
88
+ max_seq_len: int = 4096,
89
+ base_shift: float = 0.5,
90
+ max_shift: float = 1.16,
91
+ ):
92
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
93
+ b = base_shift - m * base_seq_len
94
+ mu = image_seq_len * m + b
95
+ return mu
96
+
97
+
98
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
99
+ def retrieve_latents(
100
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
101
+ ):
102
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
103
+ return encoder_output.latent_dist.sample(generator)
104
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
105
+ return encoder_output.latent_dist.mode()
106
+ elif hasattr(encoder_output, "latents"):
107
+ return encoder_output.latents
108
+ else:
109
+ raise AttributeError("Could not access latents of provided encoder_output")
110
+
111
+
112
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
113
+ def retrieve_timesteps(
114
+ scheduler,
115
+ num_inference_steps: Optional[int] = None,
116
+ device: Optional[Union[str, torch.device]] = None,
117
+ timesteps: Optional[List[int]] = None,
118
+ sigmas: Optional[List[float]] = None,
119
+ **kwargs,
120
+ ):
121
+ """
122
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
123
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
124
+
125
+ Args:
126
+ scheduler (`SchedulerMixin`):
127
+ The scheduler to get timesteps from.
128
+ num_inference_steps (`int`):
129
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
130
+ must be `None`.
131
+ device (`str` or `torch.device`, *optional*):
132
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
133
+ timesteps (`List[int]`, *optional*):
134
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
135
+ `num_inference_steps` and `sigmas` must be `None`.
136
+ sigmas (`List[float]`, *optional*):
137
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
138
+ `num_inference_steps` and `timesteps` must be `None`.
139
+
140
+ Returns:
141
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
142
+ second element is the number of inference steps.
143
+ """
144
+ if timesteps is not None and sigmas is not None:
145
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
146
+ if timesteps is not None:
147
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
148
+ if not accepts_timesteps:
149
+ raise ValueError(
150
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
151
+ f" timestep schedules. Please check whether you are using the correct scheduler."
152
+ )
153
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
154
+ timesteps = scheduler.timesteps
155
+ num_inference_steps = len(timesteps)
156
+ elif sigmas is not None:
157
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
158
+ if not accept_sigmas:
159
+ raise ValueError(
160
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
161
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
162
+ )
163
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
164
+ timesteps = scheduler.timesteps
165
+ num_inference_steps = len(timesteps)
166
+ else:
167
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
168
+ timesteps = scheduler.timesteps
169
+ return timesteps, num_inference_steps
170
+
171
+
172
+ class FluxDifferentialImg2ImgPipeline(DiffusionPipeline, FluxLoraLoaderMixin):
173
+ r"""
174
+ Differential Image to Image pipeline for the Flux family of models.
175
+
176
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
177
+
178
+ Args:
179
+ transformer ([`FluxTransformer2DModel`]):
180
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
181
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
182
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
183
+ vae ([`AutoencoderKL`]):
184
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
185
+ text_encoder ([`CLIPTextModel`]):
186
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
187
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
188
+ text_encoder_2 ([`T5EncoderModel`]):
189
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
190
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
191
+ tokenizer (`CLIPTokenizer`):
192
+ Tokenizer of class
193
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
194
+ tokenizer_2 (`T5TokenizerFast`):
195
+ Second Tokenizer of class
196
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
197
+ """
198
+
199
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
200
+ _optional_components = []
201
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
202
+
203
+ def __init__(
204
+ self,
205
+ scheduler: FlowMatchEulerDiscreteScheduler,
206
+ vae: AutoencoderKL,
207
+ text_encoder: CLIPTextModel,
208
+ tokenizer: CLIPTokenizer,
209
+ text_encoder_2: T5EncoderModel,
210
+ tokenizer_2: T5TokenizerFast,
211
+ transformer: FluxTransformer2DModel,
212
+ ):
213
+ super().__init__()
214
+
215
+ self.register_modules(
216
+ vae=vae,
217
+ text_encoder=text_encoder,
218
+ text_encoder_2=text_encoder_2,
219
+ tokenizer=tokenizer,
220
+ tokenizer_2=tokenizer_2,
221
+ transformer=transformer,
222
+ scheduler=scheduler,
223
+ )
224
+ self.vae_scale_factor = (
225
+ 2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
226
+ )
227
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
228
+ self.mask_processor = VaeImageProcessor(
229
+ vae_scale_factor=self.vae_scale_factor,
230
+ vae_latent_channels=self.vae.config.latent_channels,
231
+ do_normalize=False,
232
+ do_binarize=False,
233
+ do_convert_grayscale=True,
234
+ )
235
+ self.tokenizer_max_length = (
236
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
237
+ )
238
+ self.default_sample_size = 64
239
+
240
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
241
+ def _get_t5_prompt_embeds(
242
+ self,
243
+ prompt: Union[str, List[str]] = None,
244
+ num_images_per_prompt: int = 1,
245
+ max_sequence_length: int = 512,
246
+ device: Optional[torch.device] = None,
247
+ dtype: Optional[torch.dtype] = None,
248
+ ):
249
+ device = device or self._execution_device
250
+ dtype = dtype or self.text_encoder.dtype
251
+
252
+ prompt = [prompt] if isinstance(prompt, str) else prompt
253
+ batch_size = len(prompt)
254
+
255
+ text_inputs = self.tokenizer_2(
256
+ prompt,
257
+ padding="max_length",
258
+ max_length=max_sequence_length,
259
+ truncation=True,
260
+ return_length=False,
261
+ return_overflowing_tokens=False,
262
+ return_tensors="pt",
263
+ )
264
+ text_input_ids = text_inputs.input_ids
265
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
266
+
267
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
268
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
269
+ logger.warning(
270
+ "The following part of your input was truncated because `max_sequence_length` is set to "
271
+ f" {max_sequence_length} tokens: {removed_text}"
272
+ )
273
+
274
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
275
+
276
+ dtype = self.text_encoder_2.dtype
277
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
278
+
279
+ _, seq_len, _ = prompt_embeds.shape
280
+
281
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
282
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
283
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
284
+
285
+ return prompt_embeds
286
+
287
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
288
+ def _get_clip_prompt_embeds(
289
+ self,
290
+ prompt: Union[str, List[str]],
291
+ num_images_per_prompt: int = 1,
292
+ device: Optional[torch.device] = None,
293
+ ):
294
+ device = device or self._execution_device
295
+
296
+ prompt = [prompt] if isinstance(prompt, str) else prompt
297
+ batch_size = len(prompt)
298
+
299
+ text_inputs = self.tokenizer(
300
+ prompt,
301
+ padding="max_length",
302
+ max_length=self.tokenizer_max_length,
303
+ truncation=True,
304
+ return_overflowing_tokens=False,
305
+ return_length=False,
306
+ return_tensors="pt",
307
+ )
308
+
309
+ text_input_ids = text_inputs.input_ids
310
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
311
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
312
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
313
+ logger.warning(
314
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
315
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
316
+ )
317
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
318
+
319
+ # Use pooled output of CLIPTextModel
320
+ prompt_embeds = prompt_embeds.pooler_output
321
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
322
+
323
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
324
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
325
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
326
+
327
+ return prompt_embeds
328
+
329
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
330
+ def encode_prompt(
331
+ self,
332
+ prompt: Union[str, List[str]],
333
+ prompt_2: Union[str, List[str]],
334
+ device: Optional[torch.device] = None,
335
+ num_images_per_prompt: int = 1,
336
+ prompt_embeds: Optional[torch.FloatTensor] = None,
337
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
338
+ max_sequence_length: int = 512,
339
+ lora_scale: Optional[float] = None,
340
+ ):
341
+ r"""
342
+
343
+ Args:
344
+ prompt (`str` or `List[str]`, *optional*):
345
+ prompt to be encoded
346
+ prompt_2 (`str` or `List[str]`, *optional*):
347
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
348
+ used in all text-encoders
349
+ device: (`torch.device`):
350
+ torch device
351
+ num_images_per_prompt (`int`):
352
+ number of images that should be generated per prompt
353
+ prompt_embeds (`torch.FloatTensor`, *optional*):
354
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
355
+ provided, text embeddings will be generated from `prompt` input argument.
356
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
357
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
358
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
359
+ lora_scale (`float`, *optional*):
360
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
361
+ """
362
+ device = device or self._execution_device
363
+
364
+ # set lora scale so that monkey patched LoRA
365
+ # function of text encoder can correctly access it
366
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
367
+ self._lora_scale = lora_scale
368
+
369
+ # dynamically adjust the LoRA scale
370
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
371
+ scale_lora_layers(self.text_encoder, lora_scale)
372
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
373
+ scale_lora_layers(self.text_encoder_2, lora_scale)
374
+
375
+ prompt = [prompt] if isinstance(prompt, str) else prompt
376
+
377
+ if prompt_embeds is None:
378
+ prompt_2 = prompt_2 or prompt
379
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
380
+
381
+ # We only use the pooled prompt output from the CLIPTextModel
382
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
383
+ prompt=prompt,
384
+ device=device,
385
+ num_images_per_prompt=num_images_per_prompt,
386
+ )
387
+ prompt_embeds = self._get_t5_prompt_embeds(
388
+ prompt=prompt_2,
389
+ num_images_per_prompt=num_images_per_prompt,
390
+ max_sequence_length=max_sequence_length,
391
+ device=device,
392
+ )
393
+
394
+ if self.text_encoder is not None:
395
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
396
+ # Retrieve the original scale by scaling back the LoRA layers
397
+ unscale_lora_layers(self.text_encoder, lora_scale)
398
+
399
+ if self.text_encoder_2 is not None:
400
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
401
+ # Retrieve the original scale by scaling back the LoRA layers
402
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
403
+
404
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
405
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
406
+
407
+ return prompt_embeds, pooled_prompt_embeds, text_ids
408
+
409
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
410
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
411
+ if isinstance(generator, list):
412
+ image_latents = [
413
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
414
+ for i in range(image.shape[0])
415
+ ]
416
+ image_latents = torch.cat(image_latents, dim=0)
417
+ else:
418
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
419
+
420
+ image_latents = (image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
421
+
422
+ return image_latents
423
+
424
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
425
+ def get_timesteps(self, num_inference_steps, strength, device):
426
+ # get the original timestep using init_timestep
427
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
428
+
429
+ t_start = int(max(num_inference_steps - init_timestep, 0))
430
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
431
+ if hasattr(self.scheduler, "set_begin_index"):
432
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
433
+
434
+ return timesteps, num_inference_steps - t_start
435
+
436
+ def check_inputs(
437
+ self,
438
+ prompt,
439
+ prompt_2,
440
+ image,
441
+ mask_image,
442
+ strength,
443
+ height,
444
+ width,
445
+ output_type,
446
+ prompt_embeds=None,
447
+ pooled_prompt_embeds=None,
448
+ callback_on_step_end_tensor_inputs=None,
449
+ padding_mask_crop=None,
450
+ max_sequence_length=None,
451
+ ):
452
+ if strength < 0 or strength > 1:
453
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
454
+
455
+ if height % 8 != 0 or width % 8 != 0:
456
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
457
+
458
+ if callback_on_step_end_tensor_inputs is not None and not all(
459
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
460
+ ):
461
+ raise ValueError(
462
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
463
+ )
464
+
465
+ if prompt is not None and prompt_embeds is not None:
466
+ raise ValueError(
467
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
468
+ " only forward one of the two."
469
+ )
470
+ elif prompt_2 is not None and prompt_embeds is not None:
471
+ raise ValueError(
472
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
473
+ " only forward one of the two."
474
+ )
475
+ elif prompt is None and prompt_embeds is None:
476
+ raise ValueError(
477
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
478
+ )
479
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
480
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
481
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
482
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
483
+
484
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
485
+ raise ValueError(
486
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
487
+ )
488
+
489
+ if padding_mask_crop is not None:
490
+ if not isinstance(image, PIL.Image.Image):
491
+ raise ValueError(
492
+ f"The image should be a PIL image when inpainting mask crop, but is of type" f" {type(image)}."
493
+ )
494
+ if not isinstance(mask_image, PIL.Image.Image):
495
+ raise ValueError(
496
+ f"The mask image should be a PIL image when inpainting mask crop, but is of type"
497
+ f" {type(mask_image)}."
498
+ )
499
+ if output_type != "pil":
500
+ raise ValueError(f"The output type should be PIL when inpainting mask crop, but is" f" {output_type}.")
501
+
502
+ if max_sequence_length is not None and max_sequence_length > 512:
503
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
504
+
505
+ @staticmethod
506
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._prepare_latent_image_ids
507
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
508
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
509
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
510
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
511
+
512
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
513
+
514
+ latent_image_ids = latent_image_ids.reshape(
515
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
516
+ )
517
+
518
+ return latent_image_ids.to(device=device, dtype=dtype)
519
+
520
+ @staticmethod
521
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._pack_latents
522
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
523
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
524
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
525
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
526
+
527
+ return latents
528
+
529
+ @staticmethod
530
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._unpack_latents
531
+ def _unpack_latents(latents, height, width, vae_scale_factor):
532
+ batch_size, num_patches, channels = latents.shape
533
+
534
+ height = height // vae_scale_factor
535
+ width = width // vae_scale_factor
536
+
537
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
538
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
539
+
540
+ latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
541
+
542
+ return latents
543
+
544
+ def prepare_latents(
545
+ self,
546
+ image,
547
+ timestep,
548
+ batch_size,
549
+ num_channels_latents,
550
+ height,
551
+ width,
552
+ dtype,
553
+ device,
554
+ generator,
555
+ latents=None,
556
+ ):
557
+ if isinstance(generator, list) and len(generator) != batch_size:
558
+ raise ValueError(
559
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
560
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
561
+ )
562
+
563
+ height = 2 * (int(height) // self.vae_scale_factor)
564
+ width = 2 * (int(width) // self.vae_scale_factor)
565
+
566
+ shape = (batch_size, num_channels_latents, height, width)
567
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
568
+
569
+ image = image.to(device=device, dtype=dtype)
570
+ image_latents = self._encode_vae_image(image=image, generator=generator)
571
+
572
+ if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
573
+ # expand init_latents for batch_size
574
+ additional_image_per_prompt = batch_size // image_latents.shape[0]
575
+ image_latents = torch.cat([image_latents] * additional_image_per_prompt, dim=0)
576
+ elif batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] != 0:
577
+ raise ValueError(
578
+ f"Cannot duplicate `image` of batch size {image_latents.shape[0]} to {batch_size} text prompts."
579
+ )
580
+ else:
581
+ image_latents = torch.cat([image_latents], dim=0)
582
+
583
+ if latents is None:
584
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
585
+ latents = self.scheduler.scale_noise(image_latents, timestep, noise)
586
+ else:
587
+ noise = latents.to(device)
588
+ latents = noise
589
+
590
+ noise = self._pack_latents(noise, batch_size, num_channels_latents, height, width)
591
+ image_latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height, width)
592
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
593
+ return latents, noise, image_latents, latent_image_ids
594
+
595
+ def prepare_mask_latents(
596
+ self,
597
+ mask,
598
+ masked_image,
599
+ batch_size,
600
+ num_channels_latents,
601
+ num_images_per_prompt,
602
+ height,
603
+ width,
604
+ dtype,
605
+ device,
606
+ generator,
607
+ ):
608
+ height = 2 * (int(height) // self.vae_scale_factor)
609
+ width = 2 * (int(width) // self.vae_scale_factor)
610
+ # resize the mask to latents shape as we concatenate the mask to the latents
611
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
612
+ # and half precision
613
+ mask = torch.nn.functional.interpolate(mask, size=(height, width))
614
+ mask = mask.to(device=device, dtype=dtype)
615
+
616
+ batch_size = batch_size * num_images_per_prompt
617
+
618
+ masked_image = masked_image.to(device=device, dtype=dtype)
619
+
620
+ if masked_image.shape[1] == 16:
621
+ masked_image_latents = masked_image
622
+ else:
623
+ masked_image_latents = retrieve_latents(self.vae.encode(masked_image), generator=generator)
624
+
625
+ masked_image_latents = (masked_image_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
626
+
627
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
628
+ if mask.shape[0] < batch_size:
629
+ if not batch_size % mask.shape[0] == 0:
630
+ raise ValueError(
631
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
632
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
633
+ " of masks that you pass is divisible by the total requested batch size."
634
+ )
635
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
636
+ if masked_image_latents.shape[0] < batch_size:
637
+ if not batch_size % masked_image_latents.shape[0] == 0:
638
+ raise ValueError(
639
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
640
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
641
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
642
+ )
643
+ masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1)
644
+
645
+ # aligning device to prevent device errors when concating it with the latent model input
646
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
647
+
648
+ masked_image_latents = self._pack_latents(
649
+ masked_image_latents,
650
+ batch_size,
651
+ num_channels_latents,
652
+ height,
653
+ width,
654
+ )
655
+ mask = self._pack_latents(
656
+ mask.repeat(1, num_channels_latents, 1, 1),
657
+ batch_size,
658
+ num_channels_latents,
659
+ height,
660
+ width,
661
+ )
662
+
663
+ return mask, masked_image_latents
664
+
665
+ @property
666
+ def guidance_scale(self):
667
+ return self._guidance_scale
668
+
669
+ @property
670
+ def joint_attention_kwargs(self):
671
+ return self._joint_attention_kwargs
672
+
673
+ @property
674
+ def num_timesteps(self):
675
+ return self._num_timesteps
676
+
677
+ @property
678
+ def interrupt(self):
679
+ return self._interrupt
680
+
681
+ @torch.no_grad()
682
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
683
+ def __call__(
684
+ self,
685
+ prompt: Union[str, List[str]] = None,
686
+ prompt_2: Optional[Union[str, List[str]]] = None,
687
+ image: PipelineImageInput = None,
688
+ mask_image: PipelineImageInput = None,
689
+ masked_image_latents: PipelineImageInput = None,
690
+ height: Optional[int] = None,
691
+ width: Optional[int] = None,
692
+ padding_mask_crop: Optional[int] = None,
693
+ strength: float = 0.6,
694
+ num_inference_steps: int = 28,
695
+ timesteps: List[int] = None,
696
+ guidance_scale: float = 7.0,
697
+ num_images_per_prompt: Optional[int] = 1,
698
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
699
+ latents: Optional[torch.FloatTensor] = None,
700
+ prompt_embeds: Optional[torch.FloatTensor] = None,
701
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
702
+ output_type: Optional[str] = "pil",
703
+ return_dict: bool = True,
704
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
705
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
706
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
707
+ max_sequence_length: int = 512,
708
+ ):
709
+ r"""
710
+ Function invoked when calling the pipeline for generation.
711
+
712
+ Args:
713
+ prompt (`str` or `List[str]`, *optional*):
714
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
715
+ instead.
716
+ prompt_2 (`str` or `List[str]`, *optional*):
717
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
718
+ will be used instead
719
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
720
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
721
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
722
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
723
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
724
+ latents as `image`, but if passing latents directly it is not encoded again.
725
+ mask_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
726
+ `Image`, numpy array or tensor representing an image batch to mask `image`. White pixels in the mask
727
+ are repainted while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a
728
+ single channel (luminance) before use. If it's a numpy array or pytorch tensor, it should contain one
729
+ color channel (L) instead of 3, so the expected shape for pytorch tensor would be `(B, 1, H, W)`, `(B,
730
+ H, W)`, `(1, H, W)`, `(H, W)`. And for numpy array would be for `(B, H, W, 1)`, `(B, H, W)`, `(H, W,
731
+ 1)`, or `(H, W)`.
732
+ mask_image_latent (`torch.Tensor`, `List[torch.Tensor]`):
733
+ `Tensor` representing an image batch to mask `image` generated by VAE. If not provided, the mask
734
+ latents tensor will ge generated by `mask_image`.
735
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
736
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
737
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
738
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
739
+ padding_mask_crop (`int`, *optional*, defaults to `None`):
740
+ The size of margin in the crop to be applied to the image and masking. If `None`, no crop is applied to
741
+ image and mask_image. If `padding_mask_crop` is not `None`, it will first find a rectangular region
742
+ with the same aspect ration of the image and contains all masked area, and then expand that area based
743
+ on `padding_mask_crop`. The image and mask_image will then be cropped based on the expanded area before
744
+ resizing to the original image size for inpainting. This is useful when the masked area is small while
745
+ the image is large and contain information irrelevant for inpainting, such as background.
746
+ strength (`float`, *optional*, defaults to 1.0):
747
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
748
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
749
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
750
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
751
+ essentially ignores `image`.
752
+ num_inference_steps (`int`, *optional*, defaults to 50):
753
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
754
+ expense of slower inference.
755
+ timesteps (`List[int]`, *optional*):
756
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
757
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
758
+ passed will be used. Must be in descending order.
759
+ guidance_scale (`float`, *optional*, defaults to 7.0):
760
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
761
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
762
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
763
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
764
+ usually at the expense of lower image quality.
765
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
766
+ The number of images to generate per prompt.
767
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
768
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
769
+ to make generation deterministic.
770
+ latents (`torch.FloatTensor`, *optional*):
771
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
772
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
773
+ tensor will ge generated by sampling using the supplied random `generator`.
774
+ prompt_embeds (`torch.FloatTensor`, *optional*):
775
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
776
+ provided, text embeddings will be generated from `prompt` input argument.
777
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
778
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
779
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
780
+ output_type (`str`, *optional*, defaults to `"pil"`):
781
+ The output format of the generate image. Choose between
782
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
783
+ return_dict (`bool`, *optional*, defaults to `True`):
784
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
785
+ joint_attention_kwargs (`dict`, *optional*):
786
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
787
+ `self.processor` in
788
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
789
+ callback_on_step_end (`Callable`, *optional*):
790
+ A function that calls at the end of each denoising steps during the inference. The function is called
791
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
792
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
793
+ `callback_on_step_end_tensor_inputs`.
794
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
795
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
796
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
797
+ `._callback_tensor_inputs` attribute of your pipeline class.
798
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
799
+
800
+ Examples:
801
+
802
+ Returns:
803
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
804
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
805
+ images.
806
+ """
807
+
808
+ height = height or self.default_sample_size * self.vae_scale_factor
809
+ width = width or self.default_sample_size * self.vae_scale_factor
810
+
811
+ # 1. Check inputs. Raise error if not correct
812
+ self.check_inputs(
813
+ prompt,
814
+ prompt_2,
815
+ image,
816
+ mask_image,
817
+ strength,
818
+ height,
819
+ width,
820
+ output_type=output_type,
821
+ prompt_embeds=prompt_embeds,
822
+ pooled_prompt_embeds=pooled_prompt_embeds,
823
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
824
+ padding_mask_crop=padding_mask_crop,
825
+ max_sequence_length=max_sequence_length,
826
+ )
827
+
828
+ self._guidance_scale = guidance_scale
829
+ self._joint_attention_kwargs = joint_attention_kwargs
830
+ self._interrupt = False
831
+
832
+ # 2. Preprocess mask and image
833
+ if padding_mask_crop is not None:
834
+ crops_coords = self.mask_processor.get_crop_region(mask_image, width, height, pad=padding_mask_crop)
835
+ resize_mode = "fill"
836
+ else:
837
+ crops_coords = None
838
+ resize_mode = "default"
839
+
840
+ original_image = image
841
+ init_image = self.image_processor.preprocess(
842
+ image, height=height, width=width, crops_coords=crops_coords, resize_mode=resize_mode
843
+ )
844
+ init_image = init_image.to(dtype=torch.float32)
845
+
846
+ # 3. Define call parameters
847
+ if prompt is not None and isinstance(prompt, str):
848
+ batch_size = 1
849
+ elif prompt is not None and isinstance(prompt, list):
850
+ batch_size = len(prompt)
851
+ else:
852
+ batch_size = prompt_embeds.shape[0]
853
+
854
+ device = self._execution_device
855
+
856
+ lora_scale = (
857
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
858
+ )
859
+ (
860
+ prompt_embeds,
861
+ pooled_prompt_embeds,
862
+ text_ids,
863
+ ) = self.encode_prompt(
864
+ prompt=prompt,
865
+ prompt_2=prompt_2,
866
+ prompt_embeds=prompt_embeds,
867
+ pooled_prompt_embeds=pooled_prompt_embeds,
868
+ device=device,
869
+ num_images_per_prompt=num_images_per_prompt,
870
+ max_sequence_length=max_sequence_length,
871
+ lora_scale=lora_scale,
872
+ )
873
+
874
+ # 4.Prepare timesteps
875
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
876
+ image_seq_len = (int(height) // self.vae_scale_factor) * (int(width) // self.vae_scale_factor)
877
+ mu = calculate_shift(
878
+ image_seq_len,
879
+ self.scheduler.config.base_image_seq_len,
880
+ self.scheduler.config.max_image_seq_len,
881
+ self.scheduler.config.base_shift,
882
+ self.scheduler.config.max_shift,
883
+ )
884
+ timesteps, num_inference_steps = retrieve_timesteps(
885
+ self.scheduler,
886
+ num_inference_steps,
887
+ device,
888
+ timesteps,
889
+ sigmas,
890
+ mu=mu,
891
+ )
892
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
893
+
894
+ if num_inference_steps < 1:
895
+ raise ValueError(
896
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
897
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
898
+ )
899
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
900
+
901
+ # 5. Prepare latent variables
902
+ num_channels_latents = self.transformer.config.in_channels // 4
903
+
904
+ latents, noise, original_image_latents, latent_image_ids = self.prepare_latents(
905
+ init_image,
906
+ latent_timestep,
907
+ batch_size * num_images_per_prompt,
908
+ num_channels_latents,
909
+ height,
910
+ width,
911
+ prompt_embeds.dtype,
912
+ device,
913
+ generator,
914
+ latents,
915
+ )
916
+
917
+ # start diff diff preparation
918
+ original_mask = self.mask_processor.preprocess(
919
+ mask_image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
920
+ )
921
+
922
+ masked_image = init_image * original_mask
923
+ original_mask, _ = self.prepare_mask_latents(
924
+ original_mask,
925
+ masked_image,
926
+ batch_size,
927
+ num_channels_latents,
928
+ num_images_per_prompt,
929
+ height,
930
+ width,
931
+ prompt_embeds.dtype,
932
+ device,
933
+ generator,
934
+ )
935
+
936
+ mask_thresholds = torch.arange(num_inference_steps, dtype=original_mask.dtype) / num_inference_steps
937
+ mask_thresholds = mask_thresholds.reshape(-1, 1, 1, 1).to(device)
938
+ masks = original_mask > mask_thresholds
939
+ # end diff diff preparation
940
+
941
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
942
+
943
+ # handle guidance
944
+ if self.transformer.config.guidance_embeds:
945
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
946
+ guidance = guidance.expand(latents.shape[0])
947
+ else:
948
+ guidance = None
949
+
950
+ # 6. Denoising loop
951
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
952
+ for i, t in enumerate(timesteps):
953
+ if self.interrupt:
954
+ continue
955
+
956
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
957
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
958
+ noise_pred = self.transformer(
959
+ hidden_states=latents,
960
+ timestep=timestep / 1000,
961
+ guidance=guidance,
962
+ pooled_projections=pooled_prompt_embeds,
963
+ encoder_hidden_states=prompt_embeds,
964
+ txt_ids=text_ids,
965
+ img_ids=latent_image_ids,
966
+ joint_attention_kwargs=self.joint_attention_kwargs,
967
+ return_dict=False,
968
+ )[0]
969
+
970
+ # compute the previous noisy sample x_t -> x_t-1
971
+ latents_dtype = latents.dtype
972
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
973
+
974
+ # for 64 channel transformer only.
975
+ image_latent = original_image_latents
976
+
977
+ if i < len(timesteps) - 1:
978
+ noise_timestep = timesteps[i + 1]
979
+ image_latent = self.scheduler.scale_noise(
980
+ original_image_latents, torch.tensor([noise_timestep]), noise
981
+ )
982
+
983
+ # start diff diff
984
+ mask = masks[i].to(latents_dtype)
985
+ latents = image_latent * mask + latents * (1 - mask)
986
+ # end diff diff
987
+
988
+ if latents.dtype != latents_dtype:
989
+ if torch.backends.mps.is_available():
990
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
991
+ latents = latents.to(latents_dtype)
992
+
993
+ if callback_on_step_end is not None:
994
+ callback_kwargs = {}
995
+ for k in callback_on_step_end_tensor_inputs:
996
+ callback_kwargs[k] = locals()[k]
997
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
998
+
999
+ latents = callback_outputs.pop("latents", latents)
1000
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1001
+
1002
+ # call the callback, if provided
1003
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1004
+ progress_bar.update()
1005
+
1006
+ if XLA_AVAILABLE:
1007
+ xm.mark_step()
1008
+
1009
+ if output_type == "latent":
1010
+ image = latents
1011
+
1012
+ else:
1013
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
1014
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
1015
+ image = self.vae.decode(latents, return_dict=False)[0]
1016
+ image = self.image_processor.postprocess(image, output_type=output_type)
1017
+
1018
+ # Offload all models
1019
+ self.maybe_free_model_hooks()
1020
+
1021
+ if not return_dict:
1022
+ return (image,)
1023
+
1024
+ return FluxPipelineOutput(images=image)
v0.32.0/pipeline_flux_rf_inversion.py ADDED
@@ -0,0 +1,1060 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ # modeled after RF Inversion: https://rf-inversion.github.io/, authored by Litu Rout, Yujia Chen, Nataniel Ruiz,
3
+ # Constantine Caramanis, Sanjay Shakkottai and Wen-Sheng Chu.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import inspect
18
+ from typing import Any, Callable, Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+ import torch
22
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
23
+
24
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
25
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin, TextualInversionLoaderMixin
26
+ from diffusers.models.autoencoders import AutoencoderKL
27
+ from diffusers.models.transformers import FluxTransformer2DModel
28
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
31
+ from diffusers.utils import (
32
+ USE_PEFT_BACKEND,
33
+ is_torch_xla_available,
34
+ logging,
35
+ replace_example_docstring,
36
+ scale_lora_layers,
37
+ unscale_lora_layers,
38
+ )
39
+ from diffusers.utils.torch_utils import randn_tensor
40
+
41
+
42
+ if is_torch_xla_available():
43
+ import torch_xla.core.xla_model as xm
44
+
45
+ XLA_AVAILABLE = True
46
+ else:
47
+ XLA_AVAILABLE = False
48
+
49
+
50
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
51
+
52
+ EXAMPLE_DOC_STRING = """
53
+ Examples:
54
+ ```py
55
+ >>> import torch
56
+ >>> import requests
57
+ >>> import PIL
58
+ >>> from io import BytesIO
59
+ >>> from diffusers import DiffusionPipeline
60
+
61
+ >>> pipe = DiffusionPipeline.from_pretrained(
62
+ ... "black-forest-labs/FLUX.1-dev",
63
+ ... torch_dtype=torch.bfloat16,
64
+ ... custom_pipeline="pipeline_flux_rf_inversion")
65
+ >>> pipe.to("cuda")
66
+
67
+ >>> def download_image(url):
68
+ ... response = requests.get(url)
69
+ ... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
70
+
71
+
72
+ >>> img_url = "https://www.aiml.informatik.tu-darmstadt.de/people/mbrack/tennis.jpg"
73
+ >>> image = download_image(img_url)
74
+
75
+ >>> inverted_latents, image_latents, latent_image_ids = pipe.invert(image=image, num_inversion_steps=28, gamma=0.5)
76
+
77
+ >>> edited_image = pipe(
78
+ ... prompt="a tomato",
79
+ ... inverted_latents=inverted_latents,
80
+ ... image_latents=image_latents,
81
+ ... latent_image_ids=latent_image_ids,
82
+ ... start_timestep=0,
83
+ ... stop_timestep=.25,
84
+ ... num_inference_steps=28,
85
+ ... eta=0.9,
86
+ ... ).images[0]
87
+ ```
88
+ """
89
+
90
+
91
+ # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
92
+ def calculate_shift(
93
+ image_seq_len,
94
+ base_seq_len: int = 256,
95
+ max_seq_len: int = 4096,
96
+ base_shift: float = 0.5,
97
+ max_shift: float = 1.16,
98
+ ):
99
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
100
+ b = base_shift - m * base_seq_len
101
+ mu = image_seq_len * m + b
102
+ return mu
103
+
104
+
105
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
106
+ def retrieve_timesteps(
107
+ scheduler,
108
+ num_inference_steps: Optional[int] = None,
109
+ device: Optional[Union[str, torch.device]] = None,
110
+ timesteps: Optional[List[int]] = None,
111
+ sigmas: Optional[List[float]] = None,
112
+ **kwargs,
113
+ ):
114
+ r"""
115
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
116
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
117
+
118
+ Args:
119
+ scheduler (`SchedulerMixin`):
120
+ The scheduler to get timesteps from.
121
+ num_inference_steps (`int`):
122
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
123
+ must be `None`.
124
+ device (`str` or `torch.device`, *optional*):
125
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
126
+ timesteps (`List[int]`, *optional*):
127
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
128
+ `num_inference_steps` and `sigmas` must be `None`.
129
+ sigmas (`List[float]`, *optional*):
130
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
131
+ `num_inference_steps` and `timesteps` must be `None`.
132
+
133
+ Returns:
134
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
135
+ second element is the number of inference steps.
136
+ """
137
+ if timesteps is not None and sigmas is not None:
138
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
139
+ if timesteps is not None:
140
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
141
+ if not accepts_timesteps:
142
+ raise ValueError(
143
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
144
+ f" timestep schedules. Please check whether you are using the correct scheduler."
145
+ )
146
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
147
+ timesteps = scheduler.timesteps
148
+ num_inference_steps = len(timesteps)
149
+ elif sigmas is not None:
150
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
151
+ if not accept_sigmas:
152
+ raise ValueError(
153
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
154
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
155
+ )
156
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
157
+ timesteps = scheduler.timesteps
158
+ num_inference_steps = len(timesteps)
159
+ else:
160
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
161
+ timesteps = scheduler.timesteps
162
+ return timesteps, num_inference_steps
163
+
164
+
165
+ class RFInversionFluxPipeline(
166
+ DiffusionPipeline,
167
+ FluxLoraLoaderMixin,
168
+ FromSingleFileMixin,
169
+ TextualInversionLoaderMixin,
170
+ ):
171
+ r"""
172
+ The Flux pipeline for text-to-image generation.
173
+
174
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
175
+
176
+ Args:
177
+ transformer ([`FluxTransformer2DModel`]):
178
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
179
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
180
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
181
+ vae ([`AutoencoderKL`]):
182
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
183
+ text_encoder ([`CLIPTextModel`]):
184
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
185
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
186
+ text_encoder_2 ([`T5EncoderModel`]):
187
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
188
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
189
+ tokenizer (`CLIPTokenizer`):
190
+ Tokenizer of class
191
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
192
+ tokenizer_2 (`T5TokenizerFast`):
193
+ Second Tokenizer of class
194
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
195
+ """
196
+
197
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
198
+ _optional_components = []
199
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
200
+
201
+ def __init__(
202
+ self,
203
+ scheduler: FlowMatchEulerDiscreteScheduler,
204
+ vae: AutoencoderKL,
205
+ text_encoder: CLIPTextModel,
206
+ tokenizer: CLIPTokenizer,
207
+ text_encoder_2: T5EncoderModel,
208
+ tokenizer_2: T5TokenizerFast,
209
+ transformer: FluxTransformer2DModel,
210
+ ):
211
+ super().__init__()
212
+
213
+ self.register_modules(
214
+ vae=vae,
215
+ text_encoder=text_encoder,
216
+ text_encoder_2=text_encoder_2,
217
+ tokenizer=tokenizer,
218
+ tokenizer_2=tokenizer_2,
219
+ transformer=transformer,
220
+ scheduler=scheduler,
221
+ )
222
+ self.vae_scale_factor = (
223
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
224
+ )
225
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
226
+ self.tokenizer_max_length = (
227
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
228
+ )
229
+ self.default_sample_size = 128
230
+
231
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
232
+ def _get_t5_prompt_embeds(
233
+ self,
234
+ prompt: Union[str, List[str]] = None,
235
+ num_images_per_prompt: int = 1,
236
+ max_sequence_length: int = 512,
237
+ device: Optional[torch.device] = None,
238
+ dtype: Optional[torch.dtype] = None,
239
+ ):
240
+ device = device or self._execution_device
241
+ dtype = dtype or self.text_encoder.dtype
242
+
243
+ prompt = [prompt] if isinstance(prompt, str) else prompt
244
+ batch_size = len(prompt)
245
+
246
+ if isinstance(self, TextualInversionLoaderMixin):
247
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer_2)
248
+
249
+ text_inputs = self.tokenizer_2(
250
+ prompt,
251
+ padding="max_length",
252
+ max_length=max_sequence_length,
253
+ truncation=True,
254
+ return_length=False,
255
+ return_overflowing_tokens=False,
256
+ return_tensors="pt",
257
+ )
258
+ text_input_ids = text_inputs.input_ids
259
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
260
+
261
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
262
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
263
+ logger.warning(
264
+ "The following part of your input was truncated because `max_sequence_length` is set to "
265
+ f" {max_sequence_length} tokens: {removed_text}"
266
+ )
267
+
268
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
269
+
270
+ dtype = self.text_encoder_2.dtype
271
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
272
+
273
+ _, seq_len, _ = prompt_embeds.shape
274
+
275
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
276
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
277
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
278
+
279
+ return prompt_embeds
280
+
281
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_clip_prompt_embeds
282
+ def _get_clip_prompt_embeds(
283
+ self,
284
+ prompt: Union[str, List[str]],
285
+ num_images_per_prompt: int = 1,
286
+ device: Optional[torch.device] = None,
287
+ ):
288
+ device = device or self._execution_device
289
+
290
+ prompt = [prompt] if isinstance(prompt, str) else prompt
291
+ batch_size = len(prompt)
292
+
293
+ if isinstance(self, TextualInversionLoaderMixin):
294
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
295
+
296
+ text_inputs = self.tokenizer(
297
+ prompt,
298
+ padding="max_length",
299
+ max_length=self.tokenizer_max_length,
300
+ truncation=True,
301
+ return_overflowing_tokens=False,
302
+ return_length=False,
303
+ return_tensors="pt",
304
+ )
305
+
306
+ text_input_ids = text_inputs.input_ids
307
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
308
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
309
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
310
+ logger.warning(
311
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
312
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
313
+ )
314
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
315
+
316
+ # Use pooled output of CLIPTextModel
317
+ prompt_embeds = prompt_embeds.pooler_output
318
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
319
+
320
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
321
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
322
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
323
+
324
+ return prompt_embeds
325
+
326
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.encode_prompt
327
+ def encode_prompt(
328
+ self,
329
+ prompt: Union[str, List[str]],
330
+ prompt_2: Union[str, List[str]],
331
+ device: Optional[torch.device] = None,
332
+ num_images_per_prompt: int = 1,
333
+ prompt_embeds: Optional[torch.FloatTensor] = None,
334
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
335
+ max_sequence_length: int = 512,
336
+ lora_scale: Optional[float] = None,
337
+ ):
338
+ r"""
339
+
340
+ Args:
341
+ prompt (`str` or `List[str]`, *optional*):
342
+ prompt to be encoded
343
+ prompt_2 (`str` or `List[str]`, *optional*):
344
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
345
+ used in all text-encoders
346
+ device: (`torch.device`):
347
+ torch device
348
+ num_images_per_prompt (`int`):
349
+ number of images that should be generated per prompt
350
+ prompt_embeds (`torch.FloatTensor`, *optional*):
351
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
352
+ provided, text embeddings will be generated from `prompt` input argument.
353
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
354
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
355
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
356
+ lora_scale (`float`, *optional*):
357
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
358
+ """
359
+ device = device or self._execution_device
360
+
361
+ # set lora scale so that monkey patched LoRA
362
+ # function of text encoder can correctly access it
363
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
364
+ self._lora_scale = lora_scale
365
+
366
+ # dynamically adjust the LoRA scale
367
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
368
+ scale_lora_layers(self.text_encoder, lora_scale)
369
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
370
+ scale_lora_layers(self.text_encoder_2, lora_scale)
371
+
372
+ prompt = [prompt] if isinstance(prompt, str) else prompt
373
+
374
+ if prompt_embeds is None:
375
+ prompt_2 = prompt_2 or prompt
376
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
377
+
378
+ # We only use the pooled prompt output from the CLIPTextModel
379
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
380
+ prompt=prompt,
381
+ device=device,
382
+ num_images_per_prompt=num_images_per_prompt,
383
+ )
384
+ prompt_embeds = self._get_t5_prompt_embeds(
385
+ prompt=prompt_2,
386
+ num_images_per_prompt=num_images_per_prompt,
387
+ max_sequence_length=max_sequence_length,
388
+ device=device,
389
+ )
390
+
391
+ if self.text_encoder is not None:
392
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
393
+ # Retrieve the original scale by scaling back the LoRA layers
394
+ unscale_lora_layers(self.text_encoder, lora_scale)
395
+
396
+ if self.text_encoder_2 is not None:
397
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
398
+ # Retrieve the original scale by scaling back the LoRA layers
399
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
400
+
401
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
402
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
403
+
404
+ return prompt_embeds, pooled_prompt_embeds, text_ids
405
+
406
+ @torch.no_grad()
407
+ # Modified from diffusers.pipelines.ledits_pp.pipeline_leditspp_stable_diffusion.LEditsPPPipelineStableDiffusion.encode_image
408
+ def encode_image(self, image, dtype=None, height=None, width=None, resize_mode="default", crops_coords=None):
409
+ image = self.image_processor.preprocess(
410
+ image=image, height=height, width=width, resize_mode=resize_mode, crops_coords=crops_coords
411
+ )
412
+ resized = self.image_processor.postprocess(image=image, output_type="pil")
413
+
414
+ if max(image.shape[-2:]) > self.vae.config["sample_size"] * 1.5:
415
+ logger.warning(
416
+ "Your input images far exceed the default resolution of the underlying diffusion model. "
417
+ "The output images may contain severe artifacts! "
418
+ "Consider down-sampling the input using the `height` and `width` parameters"
419
+ )
420
+ image = image.to(dtype)
421
+
422
+ x0 = self.vae.encode(image.to(self.device)).latent_dist.sample()
423
+ x0 = (x0 - self.vae.config.shift_factor) * self.vae.config.scaling_factor
424
+ x0 = x0.to(dtype)
425
+ return x0, resized
426
+
427
+ def check_inputs(
428
+ self,
429
+ prompt,
430
+ prompt_2,
431
+ inverted_latents,
432
+ image_latents,
433
+ latent_image_ids,
434
+ height,
435
+ width,
436
+ start_timestep,
437
+ stop_timestep,
438
+ prompt_embeds=None,
439
+ pooled_prompt_embeds=None,
440
+ callback_on_step_end_tensor_inputs=None,
441
+ max_sequence_length=None,
442
+ ):
443
+ if height % self.vae_scale_factor != 0 or width % self.vae_scale_factor != 0:
444
+ raise ValueError(
445
+ f"`height` and `width` have to be divisible by {self.vae_scale_factor} but are {height} and {width}."
446
+ )
447
+
448
+ if callback_on_step_end_tensor_inputs is not None and not all(
449
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
450
+ ):
451
+ raise ValueError(
452
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
453
+ )
454
+
455
+ if prompt is not None and prompt_embeds is not None:
456
+ raise ValueError(
457
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
458
+ " only forward one of the two."
459
+ )
460
+ elif prompt_2 is not None and prompt_embeds is not None:
461
+ raise ValueError(
462
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
463
+ " only forward one of the two."
464
+ )
465
+ elif prompt is None and prompt_embeds is None:
466
+ raise ValueError(
467
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
468
+ )
469
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
470
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
471
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
472
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
473
+
474
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
475
+ raise ValueError(
476
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
477
+ )
478
+
479
+ if max_sequence_length is not None and max_sequence_length > 512:
480
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
481
+
482
+ if inverted_latents is not None and (image_latents is None or latent_image_ids is None):
483
+ raise ValueError(
484
+ "If `inverted_latents` are provided, `image_latents` and `latent_image_ids` also have to be passed. "
485
+ )
486
+ # check start_timestep and stop_timestep
487
+ if start_timestep < 0 or start_timestep > stop_timestep:
488
+ raise ValueError(f"`start_timestep` should be in [0, stop_timestep] but is {start_timestep}")
489
+
490
+ @staticmethod
491
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
492
+ latent_image_ids = torch.zeros(height, width, 3)
493
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height)[:, None]
494
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width)[None, :]
495
+
496
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
497
+
498
+ latent_image_ids = latent_image_ids.reshape(
499
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
500
+ )
501
+
502
+ return latent_image_ids.to(device=device, dtype=dtype)
503
+
504
+ @staticmethod
505
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
506
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
507
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
508
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
509
+
510
+ return latents
511
+
512
+ @staticmethod
513
+ def _unpack_latents(latents, height, width, vae_scale_factor):
514
+ batch_size, num_patches, channels = latents.shape
515
+
516
+ height = height // vae_scale_factor
517
+ width = width // vae_scale_factor
518
+
519
+ latents = latents.view(batch_size, height // 2, width // 2, channels // 4, 2, 2)
520
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
521
+
522
+ latents = latents.reshape(batch_size, channels // (2 * 2), height, width)
523
+
524
+ return latents
525
+
526
+ def enable_vae_slicing(self):
527
+ r"""
528
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
529
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
530
+ """
531
+ self.vae.enable_slicing()
532
+
533
+ def disable_vae_slicing(self):
534
+ r"""
535
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
536
+ computing decoding in one step.
537
+ """
538
+ self.vae.disable_slicing()
539
+
540
+ def enable_vae_tiling(self):
541
+ r"""
542
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
543
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
544
+ processing larger images.
545
+ """
546
+ self.vae.enable_tiling()
547
+
548
+ def disable_vae_tiling(self):
549
+ r"""
550
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
551
+ computing decoding in one step.
552
+ """
553
+ self.vae.disable_tiling()
554
+
555
+ def prepare_latents_inversion(
556
+ self,
557
+ batch_size,
558
+ num_channels_latents,
559
+ height,
560
+ width,
561
+ dtype,
562
+ device,
563
+ image_latents,
564
+ ):
565
+ height = int(height) // self.vae_scale_factor
566
+ width = int(width) // self.vae_scale_factor
567
+
568
+ latents = self._pack_latents(image_latents, batch_size, num_channels_latents, height, width)
569
+
570
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
571
+
572
+ return latents, latent_image_ids
573
+
574
+ # Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline.prepare_latents
575
+ def prepare_latents(
576
+ self,
577
+ batch_size,
578
+ num_channels_latents,
579
+ height,
580
+ width,
581
+ dtype,
582
+ device,
583
+ generator,
584
+ latents=None,
585
+ ):
586
+ # VAE applies 8x compression on images but we must also account for packing which requires
587
+ # latent height and width to be divisible by 2.
588
+ height = 2 * (int(height) // (self.vae_scale_factor * 2))
589
+ width = 2 * (int(width) // (self.vae_scale_factor * 2))
590
+
591
+ shape = (batch_size, num_channels_latents, height, width)
592
+
593
+ if latents is not None:
594
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
595
+ return latents.to(device=device, dtype=dtype), latent_image_ids
596
+
597
+ if isinstance(generator, list) and len(generator) != batch_size:
598
+ raise ValueError(
599
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
600
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
601
+ )
602
+
603
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
604
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
605
+
606
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height // 2, width // 2, device, dtype)
607
+
608
+ return latents, latent_image_ids
609
+
610
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
611
+ def get_timesteps(self, num_inference_steps, strength=1.0):
612
+ # get the original timestep using init_timestep
613
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
614
+
615
+ t_start = int(max(num_inference_steps - init_timestep, 0))
616
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
617
+ sigmas = self.scheduler.sigmas[t_start * self.scheduler.order :]
618
+ if hasattr(self.scheduler, "set_begin_index"):
619
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
620
+
621
+ return timesteps, sigmas, num_inference_steps - t_start
622
+
623
+ @property
624
+ def guidance_scale(self):
625
+ return self._guidance_scale
626
+
627
+ @property
628
+ def joint_attention_kwargs(self):
629
+ return self._joint_attention_kwargs
630
+
631
+ @property
632
+ def num_timesteps(self):
633
+ return self._num_timesteps
634
+
635
+ @property
636
+ def interrupt(self):
637
+ return self._interrupt
638
+
639
+ @torch.no_grad()
640
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
641
+ def __call__(
642
+ self,
643
+ prompt: Union[str, List[str]] = None,
644
+ prompt_2: Optional[Union[str, List[str]]] = None,
645
+ inverted_latents: Optional[torch.FloatTensor] = None,
646
+ image_latents: Optional[torch.FloatTensor] = None,
647
+ latent_image_ids: Optional[torch.FloatTensor] = None,
648
+ height: Optional[int] = None,
649
+ width: Optional[int] = None,
650
+ eta: float = 1.0,
651
+ decay_eta: Optional[bool] = False,
652
+ eta_decay_power: Optional[float] = 1.0,
653
+ strength: float = 1.0,
654
+ start_timestep: float = 0,
655
+ stop_timestep: float = 0.25,
656
+ num_inference_steps: int = 28,
657
+ sigmas: Optional[List[float]] = None,
658
+ timesteps: List[int] = None,
659
+ guidance_scale: float = 3.5,
660
+ num_images_per_prompt: Optional[int] = 1,
661
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
662
+ latents: Optional[torch.FloatTensor] = None,
663
+ prompt_embeds: Optional[torch.FloatTensor] = None,
664
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
665
+ output_type: Optional[str] = "pil",
666
+ return_dict: bool = True,
667
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
668
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
669
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
670
+ max_sequence_length: int = 512,
671
+ ):
672
+ r"""
673
+ Function invoked when calling the pipeline for generation.
674
+
675
+ Args:
676
+ prompt (`str` or `List[str]`, *optional*):
677
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
678
+ instead.
679
+ prompt_2 (`str` or `List[str]`, *optional*):
680
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
681
+ will be used instead
682
+ inverted_latents (`torch.Tensor`, *optional*):
683
+ The inverted latents from `pipe.invert`.
684
+ image_latents (`torch.Tensor`, *optional*):
685
+ The image latents from `pipe.invert`.
686
+ latent_image_ids (`torch.Tensor`, *optional*):
687
+ The latent image ids from `pipe.invert`.
688
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
689
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
690
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
691
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
692
+ eta (`float`, *optional*, defaults to 1.0):
693
+ The controller guidance, balancing faithfulness & editability:
694
+ higher eta - better faithfullness, less editability. For more significant edits, lower the value of eta.
695
+ num_inference_steps (`int`, *optional*, defaults to 50):
696
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
697
+ expense of slower inference.
698
+ timesteps (`List[int]`, *optional*):
699
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
700
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
701
+ passed will be used. Must be in descending order.
702
+ guidance_scale (`float`, *optional*, defaults to 7.0):
703
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
704
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
705
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
706
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
707
+ usually at the expense of lower image quality.
708
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
709
+ The number of images to generate per prompt.
710
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
711
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
712
+ to make generation deterministic.
713
+ latents (`torch.FloatTensor`, *optional*):
714
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
715
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
716
+ tensor will ge generated by sampling using the supplied random `generator`.
717
+ prompt_embeds (`torch.FloatTensor`, *optional*):
718
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
719
+ provided, text embeddings will be generated from `prompt` input argument.
720
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
721
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
722
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
723
+ output_type (`str`, *optional*, defaults to `"pil"`):
724
+ The output format of the generate image. Choose between
725
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
726
+ return_dict (`bool`, *optional*, defaults to `True`):
727
+ Whether to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
728
+ joint_attention_kwargs (`dict`, *optional*):
729
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
730
+ `self.processor` in
731
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
732
+ callback_on_step_end (`Callable`, *optional*):
733
+ A function that calls at the end of each denoising steps during the inference. The function is called
734
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
735
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
736
+ `callback_on_step_end_tensor_inputs`.
737
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
738
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
739
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
740
+ `._callback_tensor_inputs` attribute of your pipeline class.
741
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
742
+
743
+ Examples:
744
+
745
+ Returns:
746
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
747
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
748
+ images.
749
+ """
750
+
751
+ height = height or self.default_sample_size * self.vae_scale_factor
752
+ width = width or self.default_sample_size * self.vae_scale_factor
753
+
754
+ # 1. Check inputs. Raise error if not correct
755
+ self.check_inputs(
756
+ prompt,
757
+ prompt_2,
758
+ inverted_latents,
759
+ image_latents,
760
+ latent_image_ids,
761
+ height,
762
+ width,
763
+ start_timestep,
764
+ stop_timestep,
765
+ prompt_embeds=prompt_embeds,
766
+ pooled_prompt_embeds=pooled_prompt_embeds,
767
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
768
+ max_sequence_length=max_sequence_length,
769
+ )
770
+
771
+ self._guidance_scale = guidance_scale
772
+ self._joint_attention_kwargs = joint_attention_kwargs
773
+ self._interrupt = False
774
+ do_rf_inversion = inverted_latents is not None
775
+
776
+ # 2. Define call parameters
777
+ if prompt is not None and isinstance(prompt, str):
778
+ batch_size = 1
779
+ elif prompt is not None and isinstance(prompt, list):
780
+ batch_size = len(prompt)
781
+ else:
782
+ batch_size = prompt_embeds.shape[0]
783
+
784
+ device = self._execution_device
785
+
786
+ lora_scale = (
787
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
788
+ )
789
+ (
790
+ prompt_embeds,
791
+ pooled_prompt_embeds,
792
+ text_ids,
793
+ ) = self.encode_prompt(
794
+ prompt=prompt,
795
+ prompt_2=prompt_2,
796
+ prompt_embeds=prompt_embeds,
797
+ pooled_prompt_embeds=pooled_prompt_embeds,
798
+ device=device,
799
+ num_images_per_prompt=num_images_per_prompt,
800
+ max_sequence_length=max_sequence_length,
801
+ lora_scale=lora_scale,
802
+ )
803
+
804
+ # 4. Prepare latent variables
805
+ num_channels_latents = self.transformer.config.in_channels // 4
806
+ if do_rf_inversion:
807
+ latents = inverted_latents
808
+ else:
809
+ latents, latent_image_ids = self.prepare_latents(
810
+ batch_size * num_images_per_prompt,
811
+ num_channels_latents,
812
+ height,
813
+ width,
814
+ prompt_embeds.dtype,
815
+ device,
816
+ generator,
817
+ latents,
818
+ )
819
+
820
+ # 5. Prepare timesteps
821
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
822
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
823
+ mu = calculate_shift(
824
+ image_seq_len,
825
+ self.scheduler.config.base_image_seq_len,
826
+ self.scheduler.config.max_image_seq_len,
827
+ self.scheduler.config.base_shift,
828
+ self.scheduler.config.max_shift,
829
+ )
830
+ timesteps, num_inference_steps = retrieve_timesteps(
831
+ self.scheduler,
832
+ num_inference_steps,
833
+ device,
834
+ timesteps,
835
+ sigmas,
836
+ mu=mu,
837
+ )
838
+ if do_rf_inversion:
839
+ start_timestep = int(start_timestep * num_inference_steps)
840
+ stop_timestep = min(int(stop_timestep * num_inference_steps), num_inference_steps)
841
+ timesteps, sigmas, num_inference_steps = self.get_timesteps(num_inference_steps, strength)
842
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
843
+ self._num_timesteps = len(timesteps)
844
+
845
+ # handle guidance
846
+ if self.transformer.config.guidance_embeds:
847
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
848
+ guidance = guidance.expand(latents.shape[0])
849
+ else:
850
+ guidance = None
851
+
852
+ if do_rf_inversion:
853
+ y_0 = image_latents.clone()
854
+ # 6. Denoising loop / Controlled Reverse ODE, Algorithm 2 from: https://arxiv.org/pdf/2410.10792
855
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
856
+ for i, t in enumerate(timesteps):
857
+ if do_rf_inversion:
858
+ # ti (current timestep) as annotated in algorithm 2 - i/num_inference_steps.
859
+ t_i = 1 - t / 1000
860
+ dt = torch.tensor(1 / (len(timesteps) - 1), device=device)
861
+
862
+ if self.interrupt:
863
+ continue
864
+
865
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
866
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
867
+
868
+ noise_pred = self.transformer(
869
+ hidden_states=latents,
870
+ timestep=timestep / 1000,
871
+ guidance=guidance,
872
+ pooled_projections=pooled_prompt_embeds,
873
+ encoder_hidden_states=prompt_embeds,
874
+ txt_ids=text_ids,
875
+ img_ids=latent_image_ids,
876
+ joint_attention_kwargs=self.joint_attention_kwargs,
877
+ return_dict=False,
878
+ )[0]
879
+
880
+ latents_dtype = latents.dtype
881
+ if do_rf_inversion:
882
+ v_t = -noise_pred
883
+ v_t_cond = (y_0 - latents) / (1 - t_i)
884
+ eta_t = eta if start_timestep <= i < stop_timestep else 0.0
885
+ if decay_eta:
886
+ eta_t = eta_t * (1 - i / num_inference_steps) ** eta_decay_power # Decay eta over the loop
887
+ v_hat_t = v_t + eta_t * (v_t_cond - v_t)
888
+
889
+ # SDE Eq: 17 from https://arxiv.org/pdf/2410.10792
890
+ latents = latents + v_hat_t * (sigmas[i] - sigmas[i + 1])
891
+ else:
892
+ # compute the previous noisy sample x_t -> x_t-1
893
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
894
+
895
+ if latents.dtype != latents_dtype:
896
+ if torch.backends.mps.is_available():
897
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
898
+ latents = latents.to(latents_dtype)
899
+
900
+ if callback_on_step_end is not None:
901
+ callback_kwargs = {}
902
+ for k in callback_on_step_end_tensor_inputs:
903
+ callback_kwargs[k] = locals()[k]
904
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
905
+
906
+ latents = callback_outputs.pop("latents", latents)
907
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
908
+
909
+ # call the callback, if provided
910
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
911
+ progress_bar.update()
912
+
913
+ if XLA_AVAILABLE:
914
+ xm.mark_step()
915
+
916
+ if output_type == "latent":
917
+ image = latents
918
+
919
+ else:
920
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
921
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
922
+ image = self.vae.decode(latents, return_dict=False)[0]
923
+ image = self.image_processor.postprocess(image, output_type=output_type)
924
+
925
+ # Offload all models
926
+ self.maybe_free_model_hooks()
927
+
928
+ if not return_dict:
929
+ return (image,)
930
+
931
+ return FluxPipelineOutput(images=image)
932
+
933
+ @torch.no_grad()
934
+ def invert(
935
+ self,
936
+ image: PipelineImageInput,
937
+ source_prompt: str = "",
938
+ source_guidance_scale=0.0,
939
+ num_inversion_steps: int = 28,
940
+ strength: float = 1.0,
941
+ gamma: float = 0.5,
942
+ height: Optional[int] = None,
943
+ width: Optional[int] = None,
944
+ timesteps: List[int] = None,
945
+ dtype: Optional[torch.dtype] = None,
946
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
947
+ ):
948
+ r"""
949
+ Performs Algorithm 1: Controlled Forward ODE from https://arxiv.org/pdf/2410.10792
950
+ Args:
951
+ image (`PipelineImageInput`):
952
+ Input for the image(s) that are to be edited. Multiple input images have to default to the same aspect
953
+ ratio.
954
+ source_prompt (`str` or `List[str]`, *optional* defaults to an empty prompt as done in the original paper):
955
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
956
+ instead.
957
+ source_guidance_scale (`float`, *optional*, defaults to 0.0):
958
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
959
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
960
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). For this algorithm, it's better to keep it 0.
961
+ num_inversion_steps (`int`, *optional*, defaults to 28):
962
+ The number of discretization steps.
963
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
964
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
965
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
966
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
967
+ gamma (`float`, *optional*, defaults to 0.5):
968
+ The controller guidance for the forward ODE, balancing faithfulness & editability:
969
+ higher eta - better faithfullness, less editability. For more significant edits, lower the value of eta.
970
+ timesteps (`List[int]`, *optional*):
971
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
972
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
973
+ passed will be used. Must be in descending order.
974
+ """
975
+ dtype = dtype or self.text_encoder.dtype
976
+ batch_size = 1
977
+ self._joint_attention_kwargs = joint_attention_kwargs
978
+ num_channels_latents = self.transformer.config.in_channels // 4
979
+
980
+ height = height or self.default_sample_size * self.vae_scale_factor
981
+ width = width or self.default_sample_size * self.vae_scale_factor
982
+ device = self._execution_device
983
+
984
+ # 1. prepare image
985
+ image_latents, _ = self.encode_image(image, height=height, width=width, dtype=dtype)
986
+ image_latents, latent_image_ids = self.prepare_latents_inversion(
987
+ batch_size, num_channels_latents, height, width, dtype, device, image_latents
988
+ )
989
+
990
+ # 2. prepare timesteps
991
+ sigmas = np.linspace(1.0, 1 / num_inversion_steps, num_inversion_steps)
992
+ image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
993
+ mu = calculate_shift(
994
+ image_seq_len,
995
+ self.scheduler.config.base_image_seq_len,
996
+ self.scheduler.config.max_image_seq_len,
997
+ self.scheduler.config.base_shift,
998
+ self.scheduler.config.max_shift,
999
+ )
1000
+ timesteps, num_inversion_steps = retrieve_timesteps(
1001
+ self.scheduler,
1002
+ num_inversion_steps,
1003
+ device,
1004
+ timesteps,
1005
+ sigmas,
1006
+ mu=mu,
1007
+ )
1008
+ timesteps, sigmas, num_inversion_steps = self.get_timesteps(num_inversion_steps, strength)
1009
+
1010
+ # 3. prepare text embeddings
1011
+ (
1012
+ prompt_embeds,
1013
+ pooled_prompt_embeds,
1014
+ text_ids,
1015
+ ) = self.encode_prompt(
1016
+ prompt=source_prompt,
1017
+ prompt_2=source_prompt,
1018
+ device=device,
1019
+ )
1020
+ # 4. handle guidance
1021
+ if self.transformer.config.guidance_embeds:
1022
+ guidance = torch.full([1], source_guidance_scale, device=device, dtype=torch.float32)
1023
+ else:
1024
+ guidance = None
1025
+
1026
+ # Eq 8 dY_t = [u_t(Y_t) + γ(u_t(Y_t|y_1) - u_t(Y_t))]dt
1027
+ Y_t = image_latents
1028
+ y_1 = torch.randn_like(Y_t)
1029
+ N = len(sigmas)
1030
+
1031
+ # forward ODE loop
1032
+ with self.progress_bar(total=N - 1) as progress_bar:
1033
+ for i in range(N - 1):
1034
+ t_i = torch.tensor(i / (N), dtype=Y_t.dtype, device=device)
1035
+ timestep = torch.tensor(t_i, dtype=Y_t.dtype, device=device).repeat(batch_size)
1036
+
1037
+ # get the unconditional vector field
1038
+ u_t_i = self.transformer(
1039
+ hidden_states=Y_t,
1040
+ timestep=timestep,
1041
+ guidance=guidance,
1042
+ pooled_projections=pooled_prompt_embeds,
1043
+ encoder_hidden_states=prompt_embeds,
1044
+ txt_ids=text_ids,
1045
+ img_ids=latent_image_ids,
1046
+ joint_attention_kwargs=self.joint_attention_kwargs,
1047
+ return_dict=False,
1048
+ )[0]
1049
+
1050
+ # get the conditional vector field
1051
+ u_t_i_cond = (y_1 - Y_t) / (1 - t_i)
1052
+
1053
+ # controlled vector field
1054
+ # Eq 8 dY_t = [u_t(Y_t) + γ(u_t(Y_t|y_1) - u_t(Y_t))]dt
1055
+ u_hat_t_i = u_t_i + gamma * (u_t_i_cond - u_t_i)
1056
+ Y_t = Y_t + u_hat_t_i * (sigmas[i] - sigmas[i + 1])
1057
+ progress_bar.update()
1058
+
1059
+ # return the inverted latents (start point for the denoising loop), encoded image & latent image ids
1060
+ return Y_t, image_latents, latent_image_ids
v0.32.0/pipeline_flux_with_cfg.py ADDED
@@ -0,0 +1,850 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
21
+
22
+ from diffusers.image_processor import VaeImageProcessor
23
+ from diffusers.loaders import FluxLoraLoaderMixin, FromSingleFileMixin
24
+ from diffusers.models.autoencoders import AutoencoderKL
25
+ from diffusers.models.transformers import FluxTransformer2DModel
26
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
27
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
29
+ from diffusers.utils import (
30
+ USE_PEFT_BACKEND,
31
+ is_torch_xla_available,
32
+ logging,
33
+ replace_example_docstring,
34
+ scale_lora_layers,
35
+ unscale_lora_layers,
36
+ )
37
+ from diffusers.utils.torch_utils import randn_tensor
38
+
39
+
40
+ if is_torch_xla_available():
41
+ import torch_xla.core.xla_model as xm
42
+
43
+ XLA_AVAILABLE = True
44
+ else:
45
+ XLA_AVAILABLE = False
46
+
47
+
48
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
+
50
+ EXAMPLE_DOC_STRING = """
51
+ Examples:
52
+ ```py
53
+ >>> import torch
54
+ >>> from diffusers import FluxPipeline
55
+
56
+ >>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
57
+ >>> pipe.to("cuda")
58
+ >>> prompt = "A cat holding a sign that says hello world"
59
+ >>> # Depending on the variant being used, the pipeline call will slightly vary.
60
+ >>> # Refer to the pipeline documentation for more details.
61
+ >>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
62
+ >>> image.save("flux.png")
63
+ ```
64
+ """
65
+
66
+
67
+ def calculate_shift(
68
+ image_seq_len,
69
+ base_seq_len: int = 256,
70
+ max_seq_len: int = 4096,
71
+ base_shift: float = 0.5,
72
+ max_shift: float = 1.16,
73
+ ):
74
+ m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
75
+ b = base_shift - m * base_seq_len
76
+ mu = image_seq_len * m + b
77
+ return mu
78
+
79
+
80
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
81
+ def retrieve_timesteps(
82
+ scheduler,
83
+ num_inference_steps: Optional[int] = None,
84
+ device: Optional[Union[str, torch.device]] = None,
85
+ timesteps: Optional[List[int]] = None,
86
+ sigmas: Optional[List[float]] = None,
87
+ **kwargs,
88
+ ):
89
+ """
90
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
91
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
92
+
93
+ Args:
94
+ scheduler (`SchedulerMixin`):
95
+ The scheduler to get timesteps from.
96
+ num_inference_steps (`int`):
97
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
98
+ must be `None`.
99
+ device (`str` or `torch.device`, *optional*):
100
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
101
+ timesteps (`List[int]`, *optional*):
102
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
103
+ `num_inference_steps` and `sigmas` must be `None`.
104
+ sigmas (`List[float]`, *optional*):
105
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
106
+ `num_inference_steps` and `timesteps` must be `None`.
107
+
108
+ Returns:
109
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
110
+ second element is the number of inference steps.
111
+ """
112
+ if timesteps is not None and sigmas is not None:
113
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
114
+ if timesteps is not None:
115
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
116
+ if not accepts_timesteps:
117
+ raise ValueError(
118
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
119
+ f" timestep schedules. Please check whether you are using the correct scheduler."
120
+ )
121
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
122
+ timesteps = scheduler.timesteps
123
+ num_inference_steps = len(timesteps)
124
+ elif sigmas is not None:
125
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
126
+ if not accept_sigmas:
127
+ raise ValueError(
128
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
129
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
130
+ )
131
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
132
+ timesteps = scheduler.timesteps
133
+ num_inference_steps = len(timesteps)
134
+ else:
135
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
136
+ timesteps = scheduler.timesteps
137
+ return timesteps, num_inference_steps
138
+
139
+
140
+ class FluxCFGPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
141
+ r"""
142
+ The Flux pipeline for text-to-image generation.
143
+
144
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
145
+
146
+ Args:
147
+ transformer ([`FluxTransformer2DModel`]):
148
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
149
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
150
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
151
+ vae ([`AutoencoderKL`]):
152
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
153
+ text_encoder ([`CLIPTextModel`]):
154
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
155
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
156
+ text_encoder_2 ([`T5EncoderModel`]):
157
+ [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
158
+ the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
159
+ tokenizer (`CLIPTokenizer`):
160
+ Tokenizer of class
161
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
162
+ tokenizer_2 (`T5TokenizerFast`):
163
+ Second Tokenizer of class
164
+ [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
165
+ """
166
+
167
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
168
+ _optional_components = []
169
+ _callback_tensor_inputs = ["latents", "prompt_embeds"]
170
+
171
+ def __init__(
172
+ self,
173
+ scheduler: FlowMatchEulerDiscreteScheduler,
174
+ vae: AutoencoderKL,
175
+ text_encoder: CLIPTextModel,
176
+ tokenizer: CLIPTokenizer,
177
+ text_encoder_2: T5EncoderModel,
178
+ tokenizer_2: T5TokenizerFast,
179
+ transformer: FluxTransformer2DModel,
180
+ ):
181
+ super().__init__()
182
+
183
+ self.register_modules(
184
+ vae=vae,
185
+ text_encoder=text_encoder,
186
+ text_encoder_2=text_encoder_2,
187
+ tokenizer=tokenizer,
188
+ tokenizer_2=tokenizer_2,
189
+ transformer=transformer,
190
+ scheduler=scheduler,
191
+ )
192
+ self.vae_scale_factor = (
193
+ 2 ** (len(self.vae.config.block_out_channels)) if hasattr(self, "vae") and self.vae is not None else 16
194
+ )
195
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
196
+ self.tokenizer_max_length = (
197
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
198
+ )
199
+ self.default_sample_size = 64
200
+
201
+ def _get_t5_prompt_embeds(
202
+ self,
203
+ prompt: Union[str, List[str]] = None,
204
+ num_images_per_prompt: int = 1,
205
+ max_sequence_length: int = 512,
206
+ device: Optional[torch.device] = None,
207
+ dtype: Optional[torch.dtype] = None,
208
+ ):
209
+ device = device or self._execution_device
210
+ dtype = dtype or self.text_encoder.dtype
211
+
212
+ prompt = [prompt] if isinstance(prompt, str) else prompt
213
+ batch_size = len(prompt)
214
+
215
+ text_inputs = self.tokenizer_2(
216
+ prompt,
217
+ padding="max_length",
218
+ max_length=max_sequence_length,
219
+ truncation=True,
220
+ return_length=False,
221
+ return_overflowing_tokens=False,
222
+ return_tensors="pt",
223
+ )
224
+ text_input_ids = text_inputs.input_ids
225
+ untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
226
+
227
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
228
+ removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
229
+ logger.warning(
230
+ "The following part of your input was truncated because `max_sequence_length` is set to "
231
+ f" {max_sequence_length} tokens: {removed_text}"
232
+ )
233
+
234
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False)[0]
235
+
236
+ dtype = self.text_encoder_2.dtype
237
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
238
+
239
+ _, seq_len, _ = prompt_embeds.shape
240
+
241
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
242
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
243
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
244
+
245
+ return prompt_embeds
246
+
247
+ def _get_clip_prompt_embeds(
248
+ self,
249
+ prompt: Union[str, List[str]],
250
+ num_images_per_prompt: int = 1,
251
+ device: Optional[torch.device] = None,
252
+ ):
253
+ device = device or self._execution_device
254
+
255
+ prompt = [prompt] if isinstance(prompt, str) else prompt
256
+ batch_size = len(prompt)
257
+
258
+ text_inputs = self.tokenizer(
259
+ prompt,
260
+ padding="max_length",
261
+ max_length=self.tokenizer_max_length,
262
+ truncation=True,
263
+ return_overflowing_tokens=False,
264
+ return_length=False,
265
+ return_tensors="pt",
266
+ )
267
+
268
+ text_input_ids = text_inputs.input_ids
269
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
270
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
271
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
272
+ logger.warning(
273
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
274
+ f" {self.tokenizer_max_length} tokens: {removed_text}"
275
+ )
276
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
277
+
278
+ # Use pooled output of CLIPTextModel
279
+ prompt_embeds = prompt_embeds.pooler_output
280
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
281
+
282
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
283
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
284
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
285
+
286
+ return prompt_embeds
287
+
288
+ def encode_prompt(
289
+ self,
290
+ prompt: Union[str, List[str]],
291
+ prompt_2: Union[str, List[str]],
292
+ negative_prompt: Union[str, List[str]] = None,
293
+ negative_prompt_2: Union[str, List[str]] = None,
294
+ device: Optional[torch.device] = None,
295
+ num_images_per_prompt: int = 1,
296
+ prompt_embeds: Optional[torch.FloatTensor] = None,
297
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
298
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
299
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
300
+ max_sequence_length: int = 512,
301
+ lora_scale: Optional[float] = None,
302
+ do_true_cfg: bool = False,
303
+ ):
304
+ device = device or self._execution_device
305
+
306
+ # Set LoRA scale if applicable
307
+ if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
308
+ self._lora_scale = lora_scale
309
+
310
+ if self.text_encoder is not None and USE_PEFT_BACKEND:
311
+ scale_lora_layers(self.text_encoder, lora_scale)
312
+ if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
313
+ scale_lora_layers(self.text_encoder_2, lora_scale)
314
+
315
+ prompt = [prompt] if isinstance(prompt, str) else prompt
316
+ batch_size = len(prompt)
317
+
318
+ if do_true_cfg and negative_prompt is not None:
319
+ negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
320
+ negative_batch_size = len(negative_prompt)
321
+
322
+ if negative_batch_size != batch_size:
323
+ raise ValueError(
324
+ f"Negative prompt batch size ({negative_batch_size}) does not match prompt batch size ({batch_size})"
325
+ )
326
+
327
+ # Concatenate prompts
328
+ prompts = prompt + negative_prompt
329
+ prompts_2 = (
330
+ prompt_2 + negative_prompt_2 if prompt_2 is not None and negative_prompt_2 is not None else None
331
+ )
332
+ else:
333
+ prompts = prompt
334
+ prompts_2 = prompt_2
335
+
336
+ if prompt_embeds is None:
337
+ if prompts_2 is None:
338
+ prompts_2 = prompts
339
+
340
+ # Get pooled prompt embeddings from CLIPTextModel
341
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
342
+ prompt=prompts,
343
+ device=device,
344
+ num_images_per_prompt=num_images_per_prompt,
345
+ )
346
+ prompt_embeds = self._get_t5_prompt_embeds(
347
+ prompt=prompts_2,
348
+ num_images_per_prompt=num_images_per_prompt,
349
+ max_sequence_length=max_sequence_length,
350
+ device=device,
351
+ )
352
+
353
+ if do_true_cfg and negative_prompt is not None:
354
+ # Split embeddings back into positive and negative parts
355
+ total_batch_size = batch_size * num_images_per_prompt
356
+ positive_indices = slice(0, total_batch_size)
357
+ negative_indices = slice(total_batch_size, 2 * total_batch_size)
358
+
359
+ positive_pooled_prompt_embeds = pooled_prompt_embeds[positive_indices]
360
+ negative_pooled_prompt_embeds = pooled_prompt_embeds[negative_indices]
361
+
362
+ positive_prompt_embeds = prompt_embeds[positive_indices]
363
+ negative_prompt_embeds = prompt_embeds[negative_indices]
364
+
365
+ pooled_prompt_embeds = positive_pooled_prompt_embeds
366
+ prompt_embeds = positive_prompt_embeds
367
+
368
+ # Unscale LoRA layers
369
+ if self.text_encoder is not None:
370
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
371
+ unscale_lora_layers(self.text_encoder, lora_scale)
372
+
373
+ if self.text_encoder_2 is not None:
374
+ if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
375
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
376
+
377
+ dtype = self.text_encoder.dtype if self.text_encoder is not None else self.transformer.dtype
378
+ text_ids = torch.zeros(prompt_embeds.shape[1], 3).to(device=device, dtype=dtype)
379
+
380
+ if do_true_cfg and negative_prompt is not None:
381
+ return (
382
+ prompt_embeds,
383
+ pooled_prompt_embeds,
384
+ text_ids,
385
+ negative_prompt_embeds,
386
+ negative_pooled_prompt_embeds,
387
+ )
388
+ else:
389
+ return prompt_embeds, pooled_prompt_embeds, text_ids, None, None
390
+
391
+ def check_inputs(
392
+ self,
393
+ prompt,
394
+ prompt_2,
395
+ height,
396
+ width,
397
+ negative_prompt=None,
398
+ negative_prompt_2=None,
399
+ prompt_embeds=None,
400
+ negative_prompt_embeds=None,
401
+ pooled_prompt_embeds=None,
402
+ negative_pooled_prompt_embeds=None,
403
+ callback_on_step_end_tensor_inputs=None,
404
+ max_sequence_length=None,
405
+ ):
406
+ if height % 8 != 0 or width % 8 != 0:
407
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
408
+
409
+ if callback_on_step_end_tensor_inputs is not None and not all(
410
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
411
+ ):
412
+ raise ValueError(
413
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
414
+ )
415
+
416
+ if prompt is not None and prompt_embeds is not None:
417
+ raise ValueError(
418
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
419
+ " only forward one of the two."
420
+ )
421
+ elif prompt_2 is not None and prompt_embeds is not None:
422
+ raise ValueError(
423
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
424
+ " only forward one of the two."
425
+ )
426
+ elif prompt is None and prompt_embeds is None:
427
+ raise ValueError(
428
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
429
+ )
430
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
431
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
432
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
433
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
434
+
435
+ if negative_prompt is not None and negative_prompt_embeds is not None:
436
+ raise ValueError(
437
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
438
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
439
+ )
440
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
441
+ raise ValueError(
442
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
443
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
444
+ )
445
+
446
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
447
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
448
+ raise ValueError(
449
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
450
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
451
+ f" {negative_prompt_embeds.shape}."
452
+ )
453
+
454
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
455
+ raise ValueError(
456
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
457
+ )
458
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
459
+ raise ValueError(
460
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
461
+ )
462
+
463
+ if max_sequence_length is not None and max_sequence_length > 512:
464
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
465
+
466
+ @staticmethod
467
+ def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
468
+ latent_image_ids = torch.zeros(height // 2, width // 2, 3)
469
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
470
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
471
+
472
+ latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
473
+
474
+ latent_image_ids = latent_image_ids.reshape(
475
+ latent_image_id_height * latent_image_id_width, latent_image_id_channels
476
+ )
477
+
478
+ return latent_image_ids.to(device=device, dtype=dtype)
479
+
480
+ @staticmethod
481
+ def _pack_latents(latents, batch_size, num_channels_latents, height, width):
482
+ latents = latents.view(batch_size, num_channels_latents, height // 2, 2, width // 2, 2)
483
+ latents = latents.permute(0, 2, 4, 1, 3, 5)
484
+ latents = latents.reshape(batch_size, (height // 2) * (width // 2), num_channels_latents * 4)
485
+
486
+ return latents
487
+
488
+ @staticmethod
489
+ def _unpack_latents(latents, height, width, vae_scale_factor):
490
+ batch_size, num_patches, channels = latents.shape
491
+
492
+ height = height // vae_scale_factor
493
+ width = width // vae_scale_factor
494
+
495
+ latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
496
+ latents = latents.permute(0, 3, 1, 4, 2, 5)
497
+
498
+ latents = latents.reshape(batch_size, channels // (2 * 2), height * 2, width * 2)
499
+
500
+ return latents
501
+
502
+ def enable_vae_slicing(self):
503
+ r"""
504
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
505
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
506
+ """
507
+ self.vae.enable_slicing()
508
+
509
+ def disable_vae_slicing(self):
510
+ r"""
511
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
512
+ computing decoding in one step.
513
+ """
514
+ self.vae.disable_slicing()
515
+
516
+ def enable_vae_tiling(self):
517
+ r"""
518
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
519
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
520
+ processing larger images.
521
+ """
522
+ self.vae.enable_tiling()
523
+
524
+ def disable_vae_tiling(self):
525
+ r"""
526
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
527
+ computing decoding in one step.
528
+ """
529
+ self.vae.disable_tiling()
530
+
531
+ def prepare_latents(
532
+ self,
533
+ batch_size,
534
+ num_channels_latents,
535
+ height,
536
+ width,
537
+ dtype,
538
+ device,
539
+ generator,
540
+ latents=None,
541
+ ):
542
+ height = 2 * (int(height) // self.vae_scale_factor)
543
+ width = 2 * (int(width) // self.vae_scale_factor)
544
+
545
+ shape = (batch_size, num_channels_latents, height, width)
546
+
547
+ if latents is not None:
548
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
549
+ return latents.to(device=device, dtype=dtype), latent_image_ids
550
+
551
+ if isinstance(generator, list) and len(generator) != batch_size:
552
+ raise ValueError(
553
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
554
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
555
+ )
556
+
557
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
558
+ latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
559
+
560
+ latent_image_ids = self._prepare_latent_image_ids(batch_size, height, width, device, dtype)
561
+
562
+ return latents, latent_image_ids
563
+
564
+ @property
565
+ def guidance_scale(self):
566
+ return self._guidance_scale
567
+
568
+ @property
569
+ def joint_attention_kwargs(self):
570
+ return self._joint_attention_kwargs
571
+
572
+ @property
573
+ def num_timesteps(self):
574
+ return self._num_timesteps
575
+
576
+ @property
577
+ def interrupt(self):
578
+ return self._interrupt
579
+
580
+ @torch.no_grad()
581
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
582
+ def __call__(
583
+ self,
584
+ prompt: Union[str, List[str]] = None,
585
+ prompt_2: Optional[Union[str, List[str]]] = None,
586
+ negative_prompt: Union[str, List[str]] = None, #
587
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
588
+ true_cfg: float = 1.0, #
589
+ height: Optional[int] = None,
590
+ width: Optional[int] = None,
591
+ num_inference_steps: int = 28,
592
+ timesteps: List[int] = None,
593
+ guidance_scale: float = 3.5,
594
+ num_images_per_prompt: Optional[int] = 1,
595
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
596
+ latents: Optional[torch.FloatTensor] = None,
597
+ prompt_embeds: Optional[torch.FloatTensor] = None,
598
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
599
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
600
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
601
+ output_type: Optional[str] = "pil",
602
+ return_dict: bool = True,
603
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
604
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
605
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
606
+ max_sequence_length: int = 512,
607
+ ):
608
+ r"""
609
+ Function invoked when calling the pipeline for generation.
610
+
611
+ Args:
612
+ prompt (`str` or `List[str]`, *optional*):
613
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
614
+ instead.
615
+ prompt_2 (`str` or `List[str]`, *optional*):
616
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
617
+ will be used instead
618
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
619
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
620
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
621
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
622
+ num_inference_steps (`int`, *optional*, defaults to 50):
623
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
624
+ expense of slower inference.
625
+ timesteps (`List[int]`, *optional*):
626
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
627
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
628
+ passed will be used. Must be in descending order.
629
+ guidance_scale (`float`, *optional*, defaults to 7.0):
630
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
631
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
632
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
633
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
634
+ usually at the expense of lower image quality.
635
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
636
+ The number of images to generate per prompt.
637
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
638
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
639
+ to make generation deterministic.
640
+ latents (`torch.FloatTensor`, *optional*):
641
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
642
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
643
+ tensor will ge generated by sampling using the supplied random `generator`.
644
+ prompt_embeds (`torch.FloatTensor`, *optional*):
645
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
646
+ provided, text embeddings will be generated from `prompt` input argument.
647
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
648
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
649
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
650
+ output_type (`str`, *optional*, defaults to `"pil"`):
651
+ The output format of the generate image. Choose between
652
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
653
+ return_dict (`bool`, *optional*, defaults to `True`):
654
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
655
+ joint_attention_kwargs (`dict`, *optional*):
656
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
657
+ `self.processor` in
658
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
659
+ callback_on_step_end (`Callable`, *optional*):
660
+ A function that calls at the end of each denoising steps during the inference. The function is called
661
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
662
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
663
+ `callback_on_step_end_tensor_inputs`.
664
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
665
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
666
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
667
+ `._callback_tensor_inputs` attribute of your pipeline class.
668
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
669
+
670
+ Examples:
671
+
672
+ Returns:
673
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
674
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
675
+ images.
676
+ """
677
+
678
+ height = height or self.default_sample_size * self.vae_scale_factor
679
+ width = width or self.default_sample_size * self.vae_scale_factor
680
+
681
+ # 1. Check inputs. Raise error if not correct
682
+ self.check_inputs(
683
+ prompt,
684
+ prompt_2,
685
+ height,
686
+ width,
687
+ negative_prompt=negative_prompt,
688
+ negative_prompt_2=negative_prompt_2,
689
+ prompt_embeds=prompt_embeds,
690
+ negative_prompt_embeds=negative_prompt_embeds,
691
+ pooled_prompt_embeds=pooled_prompt_embeds,
692
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
693
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
694
+ max_sequence_length=max_sequence_length,
695
+ )
696
+
697
+ self._guidance_scale = guidance_scale
698
+ self._joint_attention_kwargs = joint_attention_kwargs
699
+ self._interrupt = False
700
+
701
+ # 2. Define call parameters
702
+ if prompt is not None and isinstance(prompt, str):
703
+ batch_size = 1
704
+ elif prompt is not None and isinstance(prompt, list):
705
+ batch_size = len(prompt)
706
+ else:
707
+ batch_size = prompt_embeds.shape[0]
708
+
709
+ device = self._execution_device
710
+
711
+ lora_scale = (
712
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
713
+ )
714
+ do_true_cfg = true_cfg > 1 and negative_prompt is not None
715
+ (
716
+ prompt_embeds,
717
+ pooled_prompt_embeds,
718
+ text_ids,
719
+ negative_prompt_embeds,
720
+ negative_pooled_prompt_embeds,
721
+ ) = self.encode_prompt(
722
+ prompt=prompt,
723
+ prompt_2=prompt_2,
724
+ negative_prompt=negative_prompt,
725
+ negative_prompt_2=negative_prompt_2,
726
+ prompt_embeds=prompt_embeds,
727
+ pooled_prompt_embeds=pooled_prompt_embeds,
728
+ negative_prompt_embeds=negative_prompt_embeds,
729
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
730
+ device=device,
731
+ num_images_per_prompt=num_images_per_prompt,
732
+ max_sequence_length=max_sequence_length,
733
+ lora_scale=lora_scale,
734
+ do_true_cfg=do_true_cfg,
735
+ )
736
+
737
+ if do_true_cfg:
738
+ # Concatenate embeddings
739
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
740
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
741
+
742
+ # 4. Prepare latent variables
743
+ num_channels_latents = self.transformer.config.in_channels // 4
744
+ latents, latent_image_ids = self.prepare_latents(
745
+ batch_size * num_images_per_prompt,
746
+ num_channels_latents,
747
+ height,
748
+ width,
749
+ prompt_embeds.dtype,
750
+ device,
751
+ generator,
752
+ latents,
753
+ )
754
+
755
+ # 5. Prepare timesteps
756
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
757
+ image_seq_len = latents.shape[1]
758
+ mu = calculate_shift(
759
+ image_seq_len,
760
+ self.scheduler.config.base_image_seq_len,
761
+ self.scheduler.config.max_image_seq_len,
762
+ self.scheduler.config.base_shift,
763
+ self.scheduler.config.max_shift,
764
+ )
765
+ timesteps, num_inference_steps = retrieve_timesteps(
766
+ self.scheduler,
767
+ num_inference_steps,
768
+ device,
769
+ timesteps,
770
+ sigmas,
771
+ mu=mu,
772
+ )
773
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
774
+ self._num_timesteps = len(timesteps)
775
+
776
+ # 6. Denoising loop
777
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
778
+ for i, t in enumerate(timesteps):
779
+ if self.interrupt:
780
+ continue
781
+
782
+ latent_model_input = torch.cat([latents] * 2) if do_true_cfg else latents
783
+
784
+ # handle guidance
785
+ if self.transformer.config.guidance_embeds:
786
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
787
+ guidance = guidance.expand(latent_model_input.shape[0])
788
+ else:
789
+ guidance = None
790
+
791
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
792
+ timestep = t.expand(latent_model_input.shape[0]).to(latent_model_input.dtype)
793
+
794
+ noise_pred = self.transformer(
795
+ hidden_states=latent_model_input,
796
+ timestep=timestep / 1000,
797
+ guidance=guidance,
798
+ pooled_projections=pooled_prompt_embeds,
799
+ encoder_hidden_states=prompt_embeds,
800
+ txt_ids=text_ids,
801
+ img_ids=latent_image_ids,
802
+ joint_attention_kwargs=self.joint_attention_kwargs,
803
+ return_dict=False,
804
+ )[0]
805
+
806
+ if do_true_cfg:
807
+ neg_noise_pred, noise_pred = noise_pred.chunk(2)
808
+ noise_pred = neg_noise_pred + true_cfg * (noise_pred - neg_noise_pred)
809
+
810
+ # compute the previous noisy sample x_t -> x_t-1
811
+ latents_dtype = latents.dtype
812
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
813
+
814
+ if latents.dtype != latents_dtype:
815
+ if torch.backends.mps.is_available():
816
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
817
+ latents = latents.to(latents_dtype)
818
+
819
+ if callback_on_step_end is not None:
820
+ callback_kwargs = {}
821
+ for k in callback_on_step_end_tensor_inputs:
822
+ callback_kwargs[k] = locals()[k]
823
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
824
+
825
+ latents = callback_outputs.pop("latents", latents)
826
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
827
+
828
+ # call the callback, if provided
829
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
830
+ progress_bar.update()
831
+
832
+ if XLA_AVAILABLE:
833
+ xm.mark_step()
834
+
835
+ if output_type == "latent":
836
+ image = latents
837
+
838
+ else:
839
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
840
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
841
+ image = self.vae.decode(latents, return_dict=False)[0]
842
+ image = self.image_processor.postprocess(image, output_type=output_type)
843
+
844
+ # Offload all models
845
+ self.maybe_free_model_hooks()
846
+
847
+ if not return_dict:
848
+ return (image,)
849
+
850
+ return FluxPipelineOutput(images=image)
v0.32.0/pipeline_hunyuandit_differential_img2img.py ADDED
@@ -0,0 +1,1146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HunyuanDiT Authors and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, Dict, List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ from transformers import (
21
+ BertModel,
22
+ BertTokenizer,
23
+ CLIPImageProcessor,
24
+ MT5Tokenizer,
25
+ T5EncoderModel,
26
+ )
27
+
28
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.models import AutoencoderKL, HunyuanDiT2DModel
31
+ from diffusers.models.embeddings import get_2d_rotary_pos_embed
32
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
33
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
34
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
35
+ StableDiffusionSafetyChecker,
36
+ )
37
+ from diffusers.schedulers import DDPMScheduler
38
+ from diffusers.utils import (
39
+ deprecate,
40
+ is_torch_xla_available,
41
+ logging,
42
+ replace_example_docstring,
43
+ )
44
+ from diffusers.utils.torch_utils import randn_tensor
45
+
46
+
47
+ if is_torch_xla_available():
48
+ import torch_xla.core.xla_model as xm
49
+
50
+ XLA_AVAILABLE = True
51
+ else:
52
+ XLA_AVAILABLE = False
53
+
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+ EXAMPLE_DOC_STRING = """
58
+ Examples:
59
+ ```py
60
+ >>> import torch
61
+ >>> from diffusers import FlowMatchEulerDiscreteScheduler
62
+ >>> from diffusers.utils import load_image
63
+ >>> from PIL import Image
64
+ >>> from torchvision import transforms
65
+ >>> from pipeline_hunyuandit_differential_img2img import HunyuanDiTDifferentialImg2ImgPipeline
66
+ >>> pipe = HunyuanDiTDifferentialImg2ImgPipeline.from_pretrained(
67
+ >>> "Tencent-Hunyuan/HunyuanDiT-Diffusers", torch_dtype=torch.float16
68
+ >>> ).to("cuda")
69
+ >>> source_image = load_image(
70
+ >>> "https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/20240329211129_4024911930.png"
71
+ >>> )
72
+ >>> map = load_image(
73
+ >>> "https://huggingface.co/datasets/OzzyGT/testing-resources/resolve/main/differential/gradient_mask_2.png"
74
+ >>> )
75
+ >>> prompt = "a green pear"
76
+ >>> negative_prompt = "blurry"
77
+ >>> image = pipe(
78
+ >>> prompt=prompt,
79
+ >>> negative_prompt=negative_prompt,
80
+ >>> image=source_image,
81
+ >>> num_inference_steps=28,
82
+ >>> guidance_scale=4.5,
83
+ >>> strength=1.0,
84
+ >>> map=map,
85
+ >>> ).images[0]
86
+
87
+ ```
88
+ """
89
+
90
+ STANDARD_RATIO = np.array(
91
+ [
92
+ 1.0, # 1:1
93
+ 4.0 / 3.0, # 4:3
94
+ 3.0 / 4.0, # 3:4
95
+ 16.0 / 9.0, # 16:9
96
+ 9.0 / 16.0, # 9:16
97
+ ]
98
+ )
99
+ STANDARD_SHAPE = [
100
+ [(1024, 1024), (1280, 1280)], # 1:1
101
+ [(1024, 768), (1152, 864), (1280, 960)], # 4:3
102
+ [(768, 1024), (864, 1152), (960, 1280)], # 3:4
103
+ [(1280, 768)], # 16:9
104
+ [(768, 1280)], # 9:16
105
+ ]
106
+ STANDARD_AREA = [np.array([w * h for w, h in shapes]) for shapes in STANDARD_SHAPE]
107
+ SUPPORTED_SHAPE = [
108
+ (1024, 1024),
109
+ (1280, 1280), # 1:1
110
+ (1024, 768),
111
+ (1152, 864),
112
+ (1280, 960), # 4:3
113
+ (768, 1024),
114
+ (864, 1152),
115
+ (960, 1280), # 3:4
116
+ (1280, 768), # 16:9
117
+ (768, 1280), # 9:16
118
+ ]
119
+
120
+
121
+ def map_to_standard_shapes(target_width, target_height):
122
+ target_ratio = target_width / target_height
123
+ closest_ratio_idx = np.argmin(np.abs(STANDARD_RATIO - target_ratio))
124
+ closest_area_idx = np.argmin(np.abs(STANDARD_AREA[closest_ratio_idx] - target_width * target_height))
125
+ width, height = STANDARD_SHAPE[closest_ratio_idx][closest_area_idx]
126
+ return width, height
127
+
128
+
129
+ def get_resize_crop_region_for_grid(src, tgt_size):
130
+ th = tw = tgt_size
131
+ h, w = src
132
+
133
+ r = h / w
134
+
135
+ # resize
136
+ if r > 1:
137
+ resize_height = th
138
+ resize_width = int(round(th / h * w))
139
+ else:
140
+ resize_width = tw
141
+ resize_height = int(round(tw / w * h))
142
+
143
+ crop_top = int(round((th - resize_height) / 2.0))
144
+ crop_left = int(round((tw - resize_width) / 2.0))
145
+
146
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
147
+
148
+
149
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
150
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
151
+ """
152
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
153
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
154
+ """
155
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
156
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
157
+ # rescale the results from guidance (fixes overexposure)
158
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
159
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
160
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
161
+ return noise_cfg
162
+
163
+
164
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
165
+ def retrieve_latents(
166
+ encoder_output: torch.Tensor,
167
+ generator: Optional[torch.Generator] = None,
168
+ sample_mode: str = "sample",
169
+ ):
170
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
171
+ return encoder_output.latent_dist.sample(generator)
172
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
173
+ return encoder_output.latent_dist.mode()
174
+ elif hasattr(encoder_output, "latents"):
175
+ return encoder_output.latents
176
+ else:
177
+ raise AttributeError("Could not access latents of provided encoder_output")
178
+
179
+
180
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
181
+ def retrieve_timesteps(
182
+ scheduler,
183
+ num_inference_steps: Optional[int] = None,
184
+ device: Optional[Union[str, torch.device]] = None,
185
+ timesteps: Optional[List[int]] = None,
186
+ sigmas: Optional[List[float]] = None,
187
+ **kwargs,
188
+ ):
189
+ """
190
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
191
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
192
+
193
+ Args:
194
+ scheduler (`SchedulerMixin`):
195
+ The scheduler to get timesteps from.
196
+ num_inference_steps (`int`):
197
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
198
+ must be `None`.
199
+ device (`str` or `torch.device`, *optional*):
200
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
201
+ timesteps (`List[int]`, *optional*):
202
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
203
+ `num_inference_steps` and `sigmas` must be `None`.
204
+ sigmas (`List[float]`, *optional*):
205
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
206
+ `num_inference_steps` and `timesteps` must be `None`.
207
+
208
+ Returns:
209
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
210
+ second element is the number of inference steps.
211
+ """
212
+ if timesteps is not None and sigmas is not None:
213
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
214
+ if timesteps is not None:
215
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
216
+ if not accepts_timesteps:
217
+ raise ValueError(
218
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
219
+ f" timestep schedules. Please check whether you are using the correct scheduler."
220
+ )
221
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
222
+ timesteps = scheduler.timesteps
223
+ num_inference_steps = len(timesteps)
224
+ elif sigmas is not None:
225
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
226
+ if not accept_sigmas:
227
+ raise ValueError(
228
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
229
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
230
+ )
231
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
232
+ timesteps = scheduler.timesteps
233
+ num_inference_steps = len(timesteps)
234
+ else:
235
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
236
+ timesteps = scheduler.timesteps
237
+ return timesteps, num_inference_steps
238
+
239
+
240
+ class HunyuanDiTDifferentialImg2ImgPipeline(DiffusionPipeline):
241
+ r"""
242
+ Differential Pipeline for English/Chinese-to-image generation using HunyuanDiT.
243
+
244
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
245
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
246
+
247
+ HunyuanDiT uses two text encoders: [mT5](https://huggingface.co/google/mt5-base) and [bilingual CLIP](fine-tuned by
248
+ ourselves)
249
+
250
+ Args:
251
+ vae ([`AutoencoderKL`]):
252
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. We use
253
+ `sdxl-vae-fp16-fix`.
254
+ text_encoder (Optional[`~transformers.BertModel`, `~transformers.CLIPTextModel`]):
255
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
256
+ HunyuanDiT uses a fine-tuned [bilingual CLIP].
257
+ tokenizer (Optional[`~transformers.BertTokenizer`, `~transformers.CLIPTokenizer`]):
258
+ A `BertTokenizer` or `CLIPTokenizer` to tokenize text.
259
+ transformer ([`HunyuanDiT2DModel`]):
260
+ The HunyuanDiT model designed by Tencent Hunyuan.
261
+ text_encoder_2 (`T5EncoderModel`):
262
+ The mT5 embedder. Specifically, it is 't5-v1_1-xxl'.
263
+ tokenizer_2 (`MT5Tokenizer`):
264
+ The tokenizer for the mT5 embedder.
265
+ scheduler ([`DDPMScheduler`]):
266
+ A scheduler to be used in combination with HunyuanDiT to denoise the encoded image latents.
267
+ """
268
+
269
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
270
+ _optional_components = [
271
+ "safety_checker",
272
+ "feature_extractor",
273
+ "text_encoder_2",
274
+ "tokenizer_2",
275
+ "text_encoder",
276
+ "tokenizer",
277
+ ]
278
+ _exclude_from_cpu_offload = ["safety_checker"]
279
+ _callback_tensor_inputs = [
280
+ "latents",
281
+ "prompt_embeds",
282
+ "negative_prompt_embeds",
283
+ "prompt_embeds_2",
284
+ "negative_prompt_embeds_2",
285
+ ]
286
+
287
+ def __init__(
288
+ self,
289
+ vae: AutoencoderKL,
290
+ text_encoder: BertModel,
291
+ tokenizer: BertTokenizer,
292
+ transformer: HunyuanDiT2DModel,
293
+ scheduler: DDPMScheduler,
294
+ safety_checker: StableDiffusionSafetyChecker,
295
+ feature_extractor: CLIPImageProcessor,
296
+ requires_safety_checker: bool = True,
297
+ text_encoder_2=T5EncoderModel,
298
+ tokenizer_2=MT5Tokenizer,
299
+ ):
300
+ super().__init__()
301
+
302
+ self.register_modules(
303
+ vae=vae,
304
+ text_encoder=text_encoder,
305
+ tokenizer=tokenizer,
306
+ tokenizer_2=tokenizer_2,
307
+ transformer=transformer,
308
+ scheduler=scheduler,
309
+ safety_checker=safety_checker,
310
+ feature_extractor=feature_extractor,
311
+ text_encoder_2=text_encoder_2,
312
+ )
313
+
314
+ if safety_checker is None and requires_safety_checker:
315
+ logger.warning(
316
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
317
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
318
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
319
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
320
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
321
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
322
+ )
323
+
324
+ if safety_checker is not None and feature_extractor is None:
325
+ raise ValueError(
326
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
327
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
328
+ )
329
+
330
+ self.vae_scale_factor = (
331
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
332
+ )
333
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
334
+ self.mask_processor = VaeImageProcessor(
335
+ vae_scale_factor=self.vae_scale_factor,
336
+ do_normalize=False,
337
+ do_convert_grayscale=True,
338
+ )
339
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
340
+ self.default_sample_size = (
341
+ self.transformer.config.sample_size
342
+ if hasattr(self, "transformer") and self.transformer is not None
343
+ else 128
344
+ )
345
+
346
+ # copied from diffusers.pipelines.huanyuandit.pipeline_huanyuandit.HunyuanDiTPipeline.encode_prompt
347
+ def encode_prompt(
348
+ self,
349
+ prompt: str,
350
+ device: torch.device = None,
351
+ dtype: torch.dtype = None,
352
+ num_images_per_prompt: int = 1,
353
+ do_classifier_free_guidance: bool = True,
354
+ negative_prompt: Optional[str] = None,
355
+ prompt_embeds: Optional[torch.Tensor] = None,
356
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
357
+ prompt_attention_mask: Optional[torch.Tensor] = None,
358
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
359
+ max_sequence_length: Optional[int] = None,
360
+ text_encoder_index: int = 0,
361
+ ):
362
+ r"""
363
+ Encodes the prompt into text encoder hidden states.
364
+
365
+ Args:
366
+ prompt (`str` or `List[str]`, *optional*):
367
+ prompt to be encoded
368
+ device: (`torch.device`):
369
+ torch device
370
+ dtype (`torch.dtype`):
371
+ torch dtype
372
+ num_images_per_prompt (`int`):
373
+ number of images that should be generated per prompt
374
+ do_classifier_free_guidance (`bool`):
375
+ whether to use classifier free guidance or not
376
+ negative_prompt (`str` or `List[str]`, *optional*):
377
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
378
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
379
+ less than `1`).
380
+ prompt_embeds (`torch.Tensor`, *optional*):
381
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
382
+ provided, text embeddings will be generated from `prompt` input argument.
383
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
384
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
385
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
386
+ argument.
387
+ prompt_attention_mask (`torch.Tensor`, *optional*):
388
+ Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
389
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
390
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
391
+ max_sequence_length (`int`, *optional*): maximum sequence length to use for the prompt.
392
+ text_encoder_index (`int`, *optional*):
393
+ Index of the text encoder to use. `0` for clip and `1` for T5.
394
+ """
395
+ if dtype is None:
396
+ if self.text_encoder_2 is not None:
397
+ dtype = self.text_encoder_2.dtype
398
+ elif self.transformer is not None:
399
+ dtype = self.transformer.dtype
400
+ else:
401
+ dtype = None
402
+
403
+ if device is None:
404
+ device = self._execution_device
405
+
406
+ tokenizers = [self.tokenizer, self.tokenizer_2]
407
+ text_encoders = [self.text_encoder, self.text_encoder_2]
408
+
409
+ tokenizer = tokenizers[text_encoder_index]
410
+ text_encoder = text_encoders[text_encoder_index]
411
+
412
+ if max_sequence_length is None:
413
+ if text_encoder_index == 0:
414
+ max_length = 77
415
+ if text_encoder_index == 1:
416
+ max_length = 256
417
+ else:
418
+ max_length = max_sequence_length
419
+
420
+ if prompt is not None and isinstance(prompt, str):
421
+ batch_size = 1
422
+ elif prompt is not None and isinstance(prompt, list):
423
+ batch_size = len(prompt)
424
+ else:
425
+ batch_size = prompt_embeds.shape[0]
426
+
427
+ if prompt_embeds is None:
428
+ text_inputs = tokenizer(
429
+ prompt,
430
+ padding="max_length",
431
+ max_length=max_length,
432
+ truncation=True,
433
+ return_attention_mask=True,
434
+ return_tensors="pt",
435
+ )
436
+ text_input_ids = text_inputs.input_ids
437
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
438
+
439
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
440
+ text_input_ids, untruncated_ids
441
+ ):
442
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
443
+ logger.warning(
444
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
445
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
446
+ )
447
+
448
+ prompt_attention_mask = text_inputs.attention_mask.to(device)
449
+ prompt_embeds = text_encoder(
450
+ text_input_ids.to(device),
451
+ attention_mask=prompt_attention_mask,
452
+ )
453
+ prompt_embeds = prompt_embeds[0]
454
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
455
+
456
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
457
+
458
+ bs_embed, seq_len, _ = prompt_embeds.shape
459
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
460
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
461
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
462
+
463
+ # get unconditional embeddings for classifier free guidance
464
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
465
+ uncond_tokens: List[str]
466
+ if negative_prompt is None:
467
+ uncond_tokens = [""] * batch_size
468
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
469
+ raise TypeError(
470
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
471
+ f" {type(prompt)}."
472
+ )
473
+ elif isinstance(negative_prompt, str):
474
+ uncond_tokens = [negative_prompt]
475
+ elif batch_size != len(negative_prompt):
476
+ raise ValueError(
477
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
478
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
479
+ " the batch size of `prompt`."
480
+ )
481
+ else:
482
+ uncond_tokens = negative_prompt
483
+
484
+ max_length = prompt_embeds.shape[1]
485
+ uncond_input = tokenizer(
486
+ uncond_tokens,
487
+ padding="max_length",
488
+ max_length=max_length,
489
+ truncation=True,
490
+ return_tensors="pt",
491
+ )
492
+
493
+ negative_prompt_attention_mask = uncond_input.attention_mask.to(device)
494
+ negative_prompt_embeds = text_encoder(
495
+ uncond_input.input_ids.to(device),
496
+ attention_mask=negative_prompt_attention_mask,
497
+ )
498
+ negative_prompt_embeds = negative_prompt_embeds[0]
499
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(num_images_per_prompt, 1)
500
+
501
+ if do_classifier_free_guidance:
502
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
503
+ seq_len = negative_prompt_embeds.shape[1]
504
+
505
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
506
+
507
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
508
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
509
+
510
+ return (
511
+ prompt_embeds,
512
+ negative_prompt_embeds,
513
+ prompt_attention_mask,
514
+ negative_prompt_attention_mask,
515
+ )
516
+
517
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
518
+ def run_safety_checker(self, image, device, dtype):
519
+ if self.safety_checker is None:
520
+ has_nsfw_concept = None
521
+ else:
522
+ if torch.is_tensor(image):
523
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
524
+ else:
525
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
526
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
527
+ image, has_nsfw_concept = self.safety_checker(
528
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
529
+ )
530
+ return image, has_nsfw_concept
531
+
532
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
533
+ def prepare_extra_step_kwargs(self, generator, eta):
534
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
535
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
536
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
537
+ # and should be between [0, 1]
538
+
539
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
540
+ extra_step_kwargs = {}
541
+ if accepts_eta:
542
+ extra_step_kwargs["eta"] = eta
543
+
544
+ # check if the scheduler accepts generator
545
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
546
+ if accepts_generator:
547
+ extra_step_kwargs["generator"] = generator
548
+ return extra_step_kwargs
549
+
550
+ def check_inputs(
551
+ self,
552
+ prompt,
553
+ height,
554
+ width,
555
+ negative_prompt=None,
556
+ prompt_embeds=None,
557
+ negative_prompt_embeds=None,
558
+ prompt_attention_mask=None,
559
+ negative_prompt_attention_mask=None,
560
+ prompt_embeds_2=None,
561
+ negative_prompt_embeds_2=None,
562
+ prompt_attention_mask_2=None,
563
+ negative_prompt_attention_mask_2=None,
564
+ callback_on_step_end_tensor_inputs=None,
565
+ ):
566
+ if height % 8 != 0 or width % 8 != 0:
567
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
568
+ if callback_on_step_end_tensor_inputs is not None and not all(
569
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
570
+ ):
571
+ raise ValueError(
572
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
573
+ )
574
+
575
+ if prompt is not None and prompt_embeds is not None:
576
+ raise ValueError(
577
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
578
+ " only forward one of the two."
579
+ )
580
+ elif prompt is None and prompt_embeds is None:
581
+ raise ValueError(
582
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
583
+ )
584
+ elif prompt is None and prompt_embeds_2 is None:
585
+ raise ValueError(
586
+ "Provide either `prompt` or `prompt_embeds_2`. Cannot leave both `prompt` and `prompt_embeds_2` undefined."
587
+ )
588
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
589
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
590
+
591
+ if prompt_embeds is not None and prompt_attention_mask is None:
592
+ raise ValueError("Must provide `prompt_attention_mask` when specifying `prompt_embeds`.")
593
+
594
+ if prompt_embeds_2 is not None and prompt_attention_mask_2 is None:
595
+ raise ValueError("Must provide `prompt_attention_mask_2` when specifying `prompt_embeds_2`.")
596
+
597
+ if negative_prompt is not None and negative_prompt_embeds is not None:
598
+ raise ValueError(
599
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
600
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
601
+ )
602
+
603
+ if negative_prompt_embeds is not None and negative_prompt_attention_mask is None:
604
+ raise ValueError("Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`.")
605
+
606
+ if negative_prompt_embeds_2 is not None and negative_prompt_attention_mask_2 is None:
607
+ raise ValueError(
608
+ "Must provide `negative_prompt_attention_mask_2` when specifying `negative_prompt_embeds_2`."
609
+ )
610
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
611
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
612
+ raise ValueError(
613
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
614
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
615
+ f" {negative_prompt_embeds.shape}."
616
+ )
617
+ if prompt_embeds_2 is not None and negative_prompt_embeds_2 is not None:
618
+ if prompt_embeds_2.shape != negative_prompt_embeds_2.shape:
619
+ raise ValueError(
620
+ "`prompt_embeds_2` and `negative_prompt_embeds_2` must have the same shape when passed directly, but"
621
+ f" got: `prompt_embeds_2` {prompt_embeds_2.shape} != `negative_prompt_embeds_2`"
622
+ f" {negative_prompt_embeds_2.shape}."
623
+ )
624
+
625
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
626
+ def get_timesteps(self, num_inference_steps, strength, device):
627
+ # get the original timestep using init_timestep
628
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
629
+
630
+ t_start = max(num_inference_steps - init_timestep, 0)
631
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
632
+ if hasattr(self.scheduler, "set_begin_index"):
633
+ self.scheduler.set_begin_index(t_start * self.scheduler.order)
634
+
635
+ return timesteps, num_inference_steps - t_start
636
+
637
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.prepare_latents
638
+ def prepare_latents(
639
+ self,
640
+ batch_size,
641
+ num_channels_latents,
642
+ height,
643
+ width,
644
+ image,
645
+ timestep,
646
+ dtype,
647
+ device,
648
+ generator=None,
649
+ ):
650
+ shape = (
651
+ batch_size,
652
+ num_channels_latents,
653
+ int(height) // self.vae_scale_factor,
654
+ int(width) // self.vae_scale_factor,
655
+ )
656
+
657
+ image = image.to(device=device, dtype=dtype)
658
+ if isinstance(generator, list) and len(generator) != batch_size:
659
+ raise ValueError(
660
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
661
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
662
+ )
663
+ elif isinstance(generator, list):
664
+ init_latents = [
665
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i]) for i in range(batch_size)
666
+ ]
667
+ init_latents = torch.cat(init_latents, dim=0)
668
+
669
+ else:
670
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
671
+
672
+ init_latents = init_latents * self.vae.config.scaling_factor
673
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
674
+ # expand init_latents for batch_size
675
+ deprecation_message = (
676
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
677
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
678
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
679
+ " your script to pass as many initial images as text prompts to suppress this warning."
680
+ )
681
+ deprecate(
682
+ "len(prompt) != len(image)",
683
+ "1.0.0",
684
+ deprecation_message,
685
+ standard_warn=False,
686
+ )
687
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
688
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
689
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
690
+ raise ValueError(
691
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
692
+ )
693
+ else:
694
+ init_latents = torch.cat([init_latents], dim=0)
695
+
696
+ shape = init_latents.shape
697
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
698
+
699
+ # get latents
700
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
701
+ latents = init_latents
702
+
703
+ return latents
704
+
705
+ @property
706
+ def guidance_scale(self):
707
+ return self._guidance_scale
708
+
709
+ @property
710
+ def guidance_rescale(self):
711
+ return self._guidance_rescale
712
+
713
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
714
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
715
+ # corresponds to doing no classifier free guidance.
716
+ @property
717
+ def do_classifier_free_guidance(self):
718
+ return self._guidance_scale > 1
719
+
720
+ @property
721
+ def num_timesteps(self):
722
+ return self._num_timesteps
723
+
724
+ @property
725
+ def interrupt(self):
726
+ return self._interrupt
727
+
728
+ @torch.no_grad()
729
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
730
+ def __call__(
731
+ self,
732
+ prompt: Union[str, List[str]] = None,
733
+ image: PipelineImageInput = None,
734
+ strength: float = 0.8,
735
+ height: Optional[int] = None,
736
+ width: Optional[int] = None,
737
+ num_inference_steps: Optional[int] = 50,
738
+ timesteps: List[int] = None,
739
+ sigmas: List[float] = None,
740
+ guidance_scale: Optional[float] = 5.0,
741
+ negative_prompt: Optional[Union[str, List[str]]] = None,
742
+ num_images_per_prompt: Optional[int] = 1,
743
+ eta: Optional[float] = 0.0,
744
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
745
+ latents: Optional[torch.Tensor] = None,
746
+ prompt_embeds: Optional[torch.Tensor] = None,
747
+ prompt_embeds_2: Optional[torch.Tensor] = None,
748
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
749
+ negative_prompt_embeds_2: Optional[torch.Tensor] = None,
750
+ prompt_attention_mask: Optional[torch.Tensor] = None,
751
+ prompt_attention_mask_2: Optional[torch.Tensor] = None,
752
+ negative_prompt_attention_mask: Optional[torch.Tensor] = None,
753
+ negative_prompt_attention_mask_2: Optional[torch.Tensor] = None,
754
+ output_type: Optional[str] = "pil",
755
+ return_dict: bool = True,
756
+ callback_on_step_end: Optional[
757
+ Union[
758
+ Callable[[int, int, Dict], None],
759
+ PipelineCallback,
760
+ MultiPipelineCallbacks,
761
+ ]
762
+ ] = None,
763
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
764
+ guidance_rescale: float = 0.0,
765
+ original_size: Optional[Tuple[int, int]] = (1024, 1024),
766
+ target_size: Optional[Tuple[int, int]] = None,
767
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
768
+ use_resolution_binning: bool = True,
769
+ map: PipelineImageInput = None,
770
+ denoising_start: Optional[float] = None,
771
+ ):
772
+ r"""
773
+ The call function to the pipeline for generation with HunyuanDiT.
774
+
775
+ Args:
776
+ prompt (`str` or `List[str]`, *optional*):
777
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
778
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
779
+ `Image`, numpy array or tensor representing an image batch to be used as the starting point. For both
780
+ numpy array and pytorch tensor, the expected value range is between `[0, 1]` If it's a tensor or a list
781
+ or tensors, the expected shape should be `(B, C, H, W)` or `(C, H, W)`. If it is a numpy array or a
782
+ list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
783
+ latents as `image`, but if passing latents directly it is not encoded again.
784
+ strength (`float`, *optional*, defaults to 0.8):
785
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
786
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
787
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
788
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
789
+ essentially ignores `image`.
790
+ height (`int`):
791
+ The height in pixels of the generated image.
792
+ width (`int`):
793
+ The width in pixels of the generated image.
794
+ num_inference_steps (`int`, *optional*, defaults to 50):
795
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
796
+ expense of slower inference. This parameter is modulated by `strength`.
797
+ timesteps (`List[int]`, *optional*):
798
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
799
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
800
+ passed will be used. Must be in descending order.
801
+ sigmas (`List[float]`, *optional*):
802
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
803
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
804
+ will be used.
805
+ guidance_scale (`float`, *optional*, defaults to 7.5):
806
+ A higher guidance scale value encourages the model to generate images closely linked to the text
807
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
808
+ negative_prompt (`str` or `List[str]`, *optional*):
809
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
810
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
811
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
812
+ The number of images to generate per prompt.
813
+ eta (`float`, *optional*, defaults to 0.0):
814
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
815
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
816
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
817
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
818
+ generation deterministic.
819
+ prompt_embeds (`torch.Tensor`, *optional*):
820
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
821
+ provided, text embeddings are generated from the `prompt` input argument.
822
+ prompt_embeds_2 (`torch.Tensor`, *optional*):
823
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
824
+ provided, text embeddings are generated from the `prompt` input argument.
825
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
826
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
827
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
828
+ negative_prompt_embeds_2 (`torch.Tensor`, *optional*):
829
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
830
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
831
+ prompt_attention_mask (`torch.Tensor`, *optional*):
832
+ Attention mask for the prompt. Required when `prompt_embeds` is passed directly.
833
+ prompt_attention_mask_2 (`torch.Tensor`, *optional*):
834
+ Attention mask for the prompt. Required when `prompt_embeds_2` is passed directly.
835
+ negative_prompt_attention_mask (`torch.Tensor`, *optional*):
836
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds` is passed directly.
837
+ negative_prompt_attention_mask_2 (`torch.Tensor`, *optional*):
838
+ Attention mask for the negative prompt. Required when `negative_prompt_embeds_2` is passed directly.
839
+ output_type (`str`, *optional*, defaults to `"pil"`):
840
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
841
+ return_dict (`bool`, *optional*, defaults to `True`):
842
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
843
+ plain tuple.
844
+ callback_on_step_end (`Callable[[int, int, Dict], None]`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
845
+ A callback function or a list of callback functions to be called at the end of each denoising step.
846
+ callback_on_step_end_tensor_inputs (`List[str]`, *optional*):
847
+ A list of tensor inputs that should be passed to the callback function. If not defined, all tensor
848
+ inputs will be passed.
849
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
850
+ Rescale the noise_cfg according to `guidance_rescale`. Based on findings of [Common Diffusion Noise
851
+ Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
852
+ original_size (`Tuple[int, int]`, *optional*, defaults to `(1024, 1024)`):
853
+ The original size of the image. Used to calculate the time ids.
854
+ target_size (`Tuple[int, int]`, *optional*):
855
+ The target size of the image. Used to calculate the time ids.
856
+ crops_coords_top_left (`Tuple[int, int]`, *optional*, defaults to `(0, 0)`):
857
+ The top left coordinates of the crop. Used to calculate the time ids.
858
+ use_resolution_binning (`bool`, *optional*, defaults to `True`):
859
+ Whether to use resolution binning or not. If `True`, the input resolution will be mapped to the closest
860
+ standard resolution. Supported resolutions are 1024x1024, 1280x1280, 1024x768, 1152x864, 1280x960,
861
+ 768x1024, 864x1152, 960x1280, 1280x768, and 768x1280. It is recommended to set this to `True`.
862
+ denoising_start (`float`, *optional*):
863
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
864
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
865
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
866
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
867
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
868
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
869
+ Examples:
870
+
871
+ Returns:
872
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
873
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
874
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
875
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
876
+ "not-safe-for-work" (nsfw) content.
877
+ """
878
+
879
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
880
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
881
+
882
+ # 0. default height and width
883
+ height = height or self.default_sample_size * self.vae_scale_factor
884
+ width = width or self.default_sample_size * self.vae_scale_factor
885
+ height = int((height // 16) * 16)
886
+ width = int((width // 16) * 16)
887
+
888
+ if use_resolution_binning and (height, width) not in SUPPORTED_SHAPE:
889
+ width, height = map_to_standard_shapes(width, height)
890
+ height = int(height)
891
+ width = int(width)
892
+ logger.warning(f"Reshaped to (height, width)=({height}, {width}), Supported shapes are {SUPPORTED_SHAPE}")
893
+
894
+ # 1. Check inputs. Raise error if not correct
895
+ self.check_inputs(
896
+ prompt,
897
+ height,
898
+ width,
899
+ negative_prompt,
900
+ prompt_embeds,
901
+ negative_prompt_embeds,
902
+ prompt_attention_mask,
903
+ negative_prompt_attention_mask,
904
+ prompt_embeds_2,
905
+ negative_prompt_embeds_2,
906
+ prompt_attention_mask_2,
907
+ negative_prompt_attention_mask_2,
908
+ callback_on_step_end_tensor_inputs,
909
+ )
910
+ self._guidance_scale = guidance_scale
911
+ self._guidance_rescale = guidance_rescale
912
+ self._interrupt = False
913
+
914
+ # 2. Define call parameters
915
+ if prompt is not None and isinstance(prompt, str):
916
+ batch_size = 1
917
+ elif prompt is not None and isinstance(prompt, list):
918
+ batch_size = len(prompt)
919
+ else:
920
+ batch_size = prompt_embeds.shape[0]
921
+
922
+ device = self._execution_device
923
+
924
+ # 3. Encode input prompt
925
+
926
+ (
927
+ prompt_embeds,
928
+ negative_prompt_embeds,
929
+ prompt_attention_mask,
930
+ negative_prompt_attention_mask,
931
+ ) = self.encode_prompt(
932
+ prompt=prompt,
933
+ device=device,
934
+ dtype=self.transformer.dtype,
935
+ num_images_per_prompt=num_images_per_prompt,
936
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
937
+ negative_prompt=negative_prompt,
938
+ prompt_embeds=prompt_embeds,
939
+ negative_prompt_embeds=negative_prompt_embeds,
940
+ prompt_attention_mask=prompt_attention_mask,
941
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
942
+ max_sequence_length=77,
943
+ text_encoder_index=0,
944
+ )
945
+ (
946
+ prompt_embeds_2,
947
+ negative_prompt_embeds_2,
948
+ prompt_attention_mask_2,
949
+ negative_prompt_attention_mask_2,
950
+ ) = self.encode_prompt(
951
+ prompt=prompt,
952
+ device=device,
953
+ dtype=self.transformer.dtype,
954
+ num_images_per_prompt=num_images_per_prompt,
955
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
956
+ negative_prompt=negative_prompt,
957
+ prompt_embeds=prompt_embeds_2,
958
+ negative_prompt_embeds=negative_prompt_embeds_2,
959
+ prompt_attention_mask=prompt_attention_mask_2,
960
+ negative_prompt_attention_mask=negative_prompt_attention_mask_2,
961
+ max_sequence_length=256,
962
+ text_encoder_index=1,
963
+ )
964
+
965
+ # 4. Preprocess image
966
+ init_image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
967
+ map = self.mask_processor.preprocess(
968
+ map,
969
+ height=height // self.vae_scale_factor,
970
+ width=width // self.vae_scale_factor,
971
+ ).to(device)
972
+
973
+ # 5. Prepare timesteps
974
+ timesteps, num_inference_steps = retrieve_timesteps(
975
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
976
+ )
977
+
978
+ # begin diff diff change
979
+ total_time_steps = num_inference_steps
980
+ # end diff diff change
981
+
982
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
983
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
984
+
985
+ # 6. Prepare latent variables
986
+ num_channels_latents = self.transformer.config.in_channels
987
+ latents = self.prepare_latents(
988
+ batch_size * num_images_per_prompt,
989
+ num_channels_latents,
990
+ height,
991
+ width,
992
+ init_image,
993
+ latent_timestep,
994
+ prompt_embeds.dtype,
995
+ device,
996
+ generator,
997
+ )
998
+
999
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1000
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1001
+
1002
+ # 8. create image_rotary_emb, style embedding & time ids
1003
+ grid_height = height // 8 // self.transformer.config.patch_size
1004
+ grid_width = width // 8 // self.transformer.config.patch_size
1005
+ base_size = 512 // 8 // self.transformer.config.patch_size
1006
+ grid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size)
1007
+ image_rotary_emb = get_2d_rotary_pos_embed(
1008
+ self.transformer.inner_dim // self.transformer.num_heads,
1009
+ grid_crops_coords,
1010
+ (grid_height, grid_width),
1011
+ device=device,
1012
+ output_type="pt",
1013
+ )
1014
+
1015
+ style = torch.tensor([0], device=device)
1016
+
1017
+ target_size = target_size or (height, width)
1018
+ add_time_ids = list(original_size + target_size + crops_coords_top_left)
1019
+ add_time_ids = torch.tensor([add_time_ids], dtype=prompt_embeds.dtype)
1020
+
1021
+ if self.do_classifier_free_guidance:
1022
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1023
+ prompt_attention_mask = torch.cat([negative_prompt_attention_mask, prompt_attention_mask])
1024
+ prompt_embeds_2 = torch.cat([negative_prompt_embeds_2, prompt_embeds_2])
1025
+ prompt_attention_mask_2 = torch.cat([negative_prompt_attention_mask_2, prompt_attention_mask_2])
1026
+ add_time_ids = torch.cat([add_time_ids] * 2, dim=0)
1027
+ style = torch.cat([style] * 2, dim=0)
1028
+
1029
+ prompt_embeds = prompt_embeds.to(device=device)
1030
+ prompt_attention_mask = prompt_attention_mask.to(device=device)
1031
+ prompt_embeds_2 = prompt_embeds_2.to(device=device)
1032
+ prompt_attention_mask_2 = prompt_attention_mask_2.to(device=device)
1033
+ add_time_ids = add_time_ids.to(dtype=prompt_embeds.dtype, device=device).repeat(
1034
+ batch_size * num_images_per_prompt, 1
1035
+ )
1036
+ style = style.to(device=device).repeat(batch_size * num_images_per_prompt)
1037
+ # 9. Denoising loop
1038
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1039
+ # preparations for diff diff
1040
+ original_with_noise = self.prepare_latents(
1041
+ batch_size * num_images_per_prompt,
1042
+ num_channels_latents,
1043
+ height,
1044
+ width,
1045
+ init_image,
1046
+ timesteps,
1047
+ prompt_embeds.dtype,
1048
+ device,
1049
+ generator,
1050
+ )
1051
+ thresholds = torch.arange(total_time_steps, dtype=map.dtype) / total_time_steps
1052
+ thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(device)
1053
+ masks = map.squeeze() > (thresholds + (denoising_start or 0))
1054
+ # end diff diff preparations
1055
+ self._num_timesteps = len(timesteps)
1056
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1057
+ for i, t in enumerate(timesteps):
1058
+ if self.interrupt:
1059
+ continue
1060
+ # diff diff
1061
+ if i == 0 and denoising_start is None:
1062
+ latents = original_with_noise[:1]
1063
+ else:
1064
+ mask = masks[i].unsqueeze(0).to(latents.dtype)
1065
+ mask = mask.unsqueeze(1) # fit shape
1066
+ latents = original_with_noise[i] * mask + latents * (1 - mask)
1067
+ # end diff diff
1068
+
1069
+ # expand the latents if we are doing classifier free guidance
1070
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1071
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1072
+
1073
+ # expand scalar t to 1-D tensor to match the 1st dim of latent_model_input
1074
+ t_expand = torch.tensor([t] * latent_model_input.shape[0], device=device).to(
1075
+ dtype=latent_model_input.dtype
1076
+ )
1077
+
1078
+ # predict the noise residual
1079
+ noise_pred = self.transformer(
1080
+ latent_model_input,
1081
+ t_expand,
1082
+ encoder_hidden_states=prompt_embeds,
1083
+ text_embedding_mask=prompt_attention_mask,
1084
+ encoder_hidden_states_t5=prompt_embeds_2,
1085
+ text_embedding_mask_t5=prompt_attention_mask_2,
1086
+ image_meta_size=add_time_ids,
1087
+ style=style,
1088
+ image_rotary_emb=image_rotary_emb,
1089
+ return_dict=False,
1090
+ )[0]
1091
+
1092
+ noise_pred, _ = noise_pred.chunk(2, dim=1)
1093
+
1094
+ # perform guidance
1095
+ if self.do_classifier_free_guidance:
1096
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1097
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1098
+
1099
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
1100
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1101
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1102
+
1103
+ # compute the previous noisy sample x_t -> x_t-1
1104
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1105
+
1106
+ if callback_on_step_end is not None:
1107
+ callback_kwargs = {}
1108
+ for k in callback_on_step_end_tensor_inputs:
1109
+ callback_kwargs[k] = locals()[k]
1110
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1111
+
1112
+ latents = callback_outputs.pop("latents", latents)
1113
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1114
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1115
+ prompt_embeds_2 = callback_outputs.pop("prompt_embeds_2", prompt_embeds_2)
1116
+ negative_prompt_embeds_2 = callback_outputs.pop(
1117
+ "negative_prompt_embeds_2", negative_prompt_embeds_2
1118
+ )
1119
+
1120
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1121
+ progress_bar.update()
1122
+
1123
+ if XLA_AVAILABLE:
1124
+ xm.mark_step()
1125
+
1126
+ if not output_type == "latent":
1127
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1128
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1129
+ else:
1130
+ image = latents
1131
+ has_nsfw_concept = None
1132
+
1133
+ if has_nsfw_concept is None:
1134
+ do_denormalize = [True] * image.shape[0]
1135
+ else:
1136
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1137
+
1138
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1139
+
1140
+ # Offload all models
1141
+ self.maybe_free_model_hooks()
1142
+
1143
+ if not return_dict:
1144
+ return (image, has_nsfw_concept)
1145
+
1146
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.32.0/pipeline_kolors_differential_img2img.py ADDED
@@ -0,0 +1,1280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI, Kwai-Kolors Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import inspect
15
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
16
+
17
+ import PIL.Image
18
+ import torch
19
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
20
+
21
+ from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
22
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
23
+ from diffusers.loaders import IPAdapterMixin, StableDiffusionXLLoraLoaderMixin
24
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
25
+ from diffusers.models.attention_processor import AttnProcessor2_0, FusedAttnProcessor2_0, XFormersAttnProcessor
26
+ from diffusers.pipelines.kolors.pipeline_output import KolorsPipelineOutput
27
+ from diffusers.pipelines.kolors.text_encoder import ChatGLMModel
28
+ from diffusers.pipelines.kolors.tokenizer import ChatGLMTokenizer
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
30
+ from diffusers.schedulers import KarrasDiffusionSchedulers
31
+ from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
32
+ from diffusers.utils.torch_utils import randn_tensor
33
+
34
+
35
+ if is_torch_xla_available():
36
+ import torch_xla.core.xla_model as xm
37
+
38
+ XLA_AVAILABLE = True
39
+ else:
40
+ XLA_AVAILABLE = False
41
+
42
+
43
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
+
45
+
46
+ EXAMPLE_DOC_STRING = """
47
+ Examples:
48
+ ```py
49
+ >>> import torch
50
+ >>> from diffusers import KolorsDifferentialImg2ImgPipeline
51
+ >>> from diffusers.utils import load_image
52
+
53
+ >>> pipe = KolorsDifferentialImg2ImgPipeline.from_pretrained(
54
+ ... "Kwai-Kolors/Kolors-diffusers", variant="fp16", torch_dtype=torch.float16
55
+ ... )
56
+ >>> pipe = pipe.to("cuda")
57
+ >>> url = (
58
+ ... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/kolors/bunny_source.png"
59
+ ... )
60
+
61
+
62
+ >>> init_image = load_image(url)
63
+ >>> prompt = "high quality image of a capybara wearing sunglasses. In the background of the image there are trees, poles, grass and other objects. At the bottom of the object there is the road., 8k, highly detailed."
64
+ >>> image = pipe(prompt, image=init_image).images[0]
65
+ ```
66
+ """
67
+
68
+
69
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
70
+ def retrieve_latents(
71
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
72
+ ):
73
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
74
+ return encoder_output.latent_dist.sample(generator)
75
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
76
+ return encoder_output.latent_dist.mode()
77
+ elif hasattr(encoder_output, "latents"):
78
+ return encoder_output.latents
79
+ else:
80
+ raise AttributeError("Could not access latents of provided encoder_output")
81
+
82
+
83
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
84
+ def retrieve_timesteps(
85
+ scheduler,
86
+ num_inference_steps: Optional[int] = None,
87
+ device: Optional[Union[str, torch.device]] = None,
88
+ timesteps: Optional[List[int]] = None,
89
+ sigmas: Optional[List[float]] = None,
90
+ **kwargs,
91
+ ):
92
+ """
93
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
94
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
95
+
96
+ Args:
97
+ scheduler (`SchedulerMixin`):
98
+ The scheduler to get timesteps from.
99
+ num_inference_steps (`int`):
100
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
101
+ must be `None`.
102
+ device (`str` or `torch.device`, *optional*):
103
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
104
+ timesteps (`List[int]`, *optional*):
105
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
106
+ `num_inference_steps` and `sigmas` must be `None`.
107
+ sigmas (`List[float]`, *optional*):
108
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
109
+ `num_inference_steps` and `timesteps` must be `None`.
110
+
111
+ Returns:
112
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
113
+ second element is the number of inference steps.
114
+ """
115
+ if timesteps is not None and sigmas is not None:
116
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
117
+ if timesteps is not None:
118
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
119
+ if not accepts_timesteps:
120
+ raise ValueError(
121
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
122
+ f" timestep schedules. Please check whether you are using the correct scheduler."
123
+ )
124
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
125
+ timesteps = scheduler.timesteps
126
+ num_inference_steps = len(timesteps)
127
+ elif sigmas is not None:
128
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
129
+ if not accept_sigmas:
130
+ raise ValueError(
131
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
132
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
133
+ )
134
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
135
+ timesteps = scheduler.timesteps
136
+ num_inference_steps = len(timesteps)
137
+ else:
138
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
139
+ timesteps = scheduler.timesteps
140
+ return timesteps, num_inference_steps
141
+
142
+
143
+ class KolorsDifferentialImg2ImgPipeline(
144
+ DiffusionPipeline, StableDiffusionMixin, StableDiffusionXLLoraLoaderMixin, IPAdapterMixin
145
+ ):
146
+ r"""
147
+ Pipeline for text-to-image generation using Kolors.
148
+
149
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
150
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
151
+
152
+ The pipeline also inherits the following loading methods:
153
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
154
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
155
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
156
+
157
+ Args:
158
+ vae ([`AutoencoderKL`]):
159
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
160
+ text_encoder ([`ChatGLMModel`]):
161
+ Frozen text-encoder. Kolors uses [ChatGLM3-6B](https://huggingface.co/THUDM/chatglm3-6b).
162
+ tokenizer (`ChatGLMTokenizer`):
163
+ Tokenizer of class
164
+ [ChatGLMTokenizer](https://huggingface.co/THUDM/chatglm3-6b/blob/main/tokenization_chatglm.py).
165
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
166
+ scheduler ([`SchedulerMixin`]):
167
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
168
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
169
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"False"`):
170
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
171
+ `Kwai-Kolors/Kolors-diffusers`.
172
+ """
173
+
174
+ model_cpu_offload_seq = "text_encoder->image_encoder-unet->vae"
175
+ _optional_components = [
176
+ "image_encoder",
177
+ "feature_extractor",
178
+ ]
179
+ _callback_tensor_inputs = [
180
+ "latents",
181
+ "prompt_embeds",
182
+ "negative_prompt_embeds",
183
+ "add_text_embeds",
184
+ "add_time_ids",
185
+ "negative_pooled_prompt_embeds",
186
+ "negative_add_time_ids",
187
+ ]
188
+
189
+ def __init__(
190
+ self,
191
+ vae: AutoencoderKL,
192
+ text_encoder: ChatGLMModel,
193
+ tokenizer: ChatGLMTokenizer,
194
+ unet: UNet2DConditionModel,
195
+ scheduler: KarrasDiffusionSchedulers,
196
+ image_encoder: CLIPVisionModelWithProjection = None,
197
+ feature_extractor: CLIPImageProcessor = None,
198
+ force_zeros_for_empty_prompt: bool = False,
199
+ ):
200
+ super().__init__()
201
+
202
+ self.register_modules(
203
+ vae=vae,
204
+ text_encoder=text_encoder,
205
+ tokenizer=tokenizer,
206
+ unet=unet,
207
+ scheduler=scheduler,
208
+ image_encoder=image_encoder,
209
+ feature_extractor=feature_extractor,
210
+ )
211
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
212
+ self.vae_scale_factor = (
213
+ 2 ** (len(self.vae.config.block_out_channels) - 1) if hasattr(self, "vae") and self.vae is not None else 8
214
+ )
215
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
216
+
217
+ self.mask_processor = VaeImageProcessor(
218
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_convert_grayscale=True
219
+ )
220
+
221
+ self.default_sample_size = self.unet.config.sample_size
222
+
223
+ # Copied from diffusers.pipelines.kolors.pipeline_kolors.KolorsPipeline.encode_prompt
224
+ def encode_prompt(
225
+ self,
226
+ prompt,
227
+ device: Optional[torch.device] = None,
228
+ num_images_per_prompt: int = 1,
229
+ do_classifier_free_guidance: bool = True,
230
+ negative_prompt=None,
231
+ prompt_embeds: Optional[torch.FloatTensor] = None,
232
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
233
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
234
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
235
+ max_sequence_length: int = 256,
236
+ ):
237
+ r"""
238
+ Encodes the prompt into text encoder hidden states.
239
+
240
+ Args:
241
+ prompt (`str` or `List[str]`, *optional*):
242
+ prompt to be encoded
243
+ device: (`torch.device`):
244
+ torch device
245
+ num_images_per_prompt (`int`):
246
+ number of images that should be generated per prompt
247
+ do_classifier_free_guidance (`bool`):
248
+ whether to use classifier free guidance or not
249
+ negative_prompt (`str` or `List[str]`, *optional*):
250
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
251
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
252
+ less than `1`).
253
+ prompt_embeds (`torch.FloatTensor`, *optional*):
254
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
255
+ provided, text embeddings will be generated from `prompt` input argument.
256
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
257
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
258
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
259
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
260
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
261
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
262
+ argument.
263
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
264
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
265
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
266
+ input argument.
267
+ max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
268
+ """
269
+ # from IPython import embed; embed(); exit()
270
+ device = device or self._execution_device
271
+
272
+ if prompt is not None and isinstance(prompt, str):
273
+ batch_size = 1
274
+ elif prompt is not None and isinstance(prompt, list):
275
+ batch_size = len(prompt)
276
+ else:
277
+ batch_size = prompt_embeds.shape[0]
278
+
279
+ # Define tokenizers and text encoders
280
+ tokenizers = [self.tokenizer]
281
+ text_encoders = [self.text_encoder]
282
+
283
+ if prompt_embeds is None:
284
+ prompt_embeds_list = []
285
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
286
+ text_inputs = tokenizer(
287
+ prompt,
288
+ padding="max_length",
289
+ max_length=max_sequence_length,
290
+ truncation=True,
291
+ return_tensors="pt",
292
+ ).to(device)
293
+ output = text_encoder(
294
+ input_ids=text_inputs["input_ids"],
295
+ attention_mask=text_inputs["attention_mask"],
296
+ position_ids=text_inputs["position_ids"],
297
+ output_hidden_states=True,
298
+ )
299
+
300
+ # [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
301
+ # clone to have a contiguous tensor
302
+ prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
303
+ # [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
304
+ pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
305
+ bs_embed, seq_len, _ = prompt_embeds.shape
306
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
307
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
308
+
309
+ prompt_embeds_list.append(prompt_embeds)
310
+
311
+ prompt_embeds = prompt_embeds_list[0]
312
+
313
+ # get unconditional embeddings for classifier free guidance
314
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
315
+
316
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
317
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
318
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
319
+ uncond_tokens: List[str]
320
+ if negative_prompt is None:
321
+ uncond_tokens = [""] * batch_size
322
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
323
+ raise TypeError(
324
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
325
+ f" {type(prompt)}."
326
+ )
327
+ elif isinstance(negative_prompt, str):
328
+ uncond_tokens = [negative_prompt]
329
+ elif batch_size != len(negative_prompt):
330
+ raise ValueError(
331
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
332
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
333
+ " the batch size of `prompt`."
334
+ )
335
+ else:
336
+ uncond_tokens = negative_prompt
337
+
338
+ negative_prompt_embeds_list = []
339
+
340
+ for tokenizer, text_encoder in zip(tokenizers, text_encoders):
341
+ uncond_input = tokenizer(
342
+ uncond_tokens,
343
+ padding="max_length",
344
+ max_length=max_sequence_length,
345
+ truncation=True,
346
+ return_tensors="pt",
347
+ ).to(device)
348
+ output = text_encoder(
349
+ input_ids=uncond_input["input_ids"],
350
+ attention_mask=uncond_input["attention_mask"],
351
+ position_ids=uncond_input["position_ids"],
352
+ output_hidden_states=True,
353
+ )
354
+
355
+ # [max_sequence_length, batch, hidden_size] -> [batch, max_sequence_length, hidden_size]
356
+ # clone to have a contiguous tensor
357
+ negative_prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
358
+ # [max_sequence_length, batch, hidden_size] -> [batch, hidden_size]
359
+ negative_pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone()
360
+
361
+ if do_classifier_free_guidance:
362
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
363
+ seq_len = negative_prompt_embeds.shape[1]
364
+
365
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
366
+
367
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
368
+ negative_prompt_embeds = negative_prompt_embeds.view(
369
+ batch_size * num_images_per_prompt, seq_len, -1
370
+ )
371
+
372
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
373
+
374
+ negative_prompt_embeds = negative_prompt_embeds_list[0]
375
+
376
+ bs_embed = pooled_prompt_embeds.shape[0]
377
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
378
+ bs_embed * num_images_per_prompt, -1
379
+ )
380
+
381
+ if do_classifier_free_guidance:
382
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
383
+ bs_embed * num_images_per_prompt, -1
384
+ )
385
+
386
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
387
+
388
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
389
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
390
+ dtype = next(self.image_encoder.parameters()).dtype
391
+
392
+ if not isinstance(image, torch.Tensor):
393
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
394
+
395
+ image = image.to(device=device, dtype=dtype)
396
+ if output_hidden_states:
397
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
398
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
399
+ uncond_image_enc_hidden_states = self.image_encoder(
400
+ torch.zeros_like(image), output_hidden_states=True
401
+ ).hidden_states[-2]
402
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
403
+ num_images_per_prompt, dim=0
404
+ )
405
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
406
+ else:
407
+ image_embeds = self.image_encoder(image).image_embeds
408
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
409
+ uncond_image_embeds = torch.zeros_like(image_embeds)
410
+
411
+ return image_embeds, uncond_image_embeds
412
+
413
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
414
+ def prepare_ip_adapter_image_embeds(
415
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
416
+ ):
417
+ image_embeds = []
418
+ if do_classifier_free_guidance:
419
+ negative_image_embeds = []
420
+ if ip_adapter_image_embeds is None:
421
+ if not isinstance(ip_adapter_image, list):
422
+ ip_adapter_image = [ip_adapter_image]
423
+
424
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
425
+ raise ValueError(
426
+ f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
427
+ )
428
+
429
+ for single_ip_adapter_image, image_proj_layer in zip(
430
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
431
+ ):
432
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
433
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
434
+ single_ip_adapter_image, device, 1, output_hidden_state
435
+ )
436
+
437
+ image_embeds.append(single_image_embeds[None, :])
438
+ if do_classifier_free_guidance:
439
+ negative_image_embeds.append(single_negative_image_embeds[None, :])
440
+ else:
441
+ for single_image_embeds in ip_adapter_image_embeds:
442
+ if do_classifier_free_guidance:
443
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
444
+ negative_image_embeds.append(single_negative_image_embeds)
445
+ image_embeds.append(single_image_embeds)
446
+
447
+ ip_adapter_image_embeds = []
448
+ for i, single_image_embeds in enumerate(image_embeds):
449
+ single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
450
+ if do_classifier_free_guidance:
451
+ single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
452
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
453
+
454
+ single_image_embeds = single_image_embeds.to(device=device)
455
+ ip_adapter_image_embeds.append(single_image_embeds)
456
+
457
+ return ip_adapter_image_embeds
458
+
459
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
460
+ def prepare_extra_step_kwargs(self, generator, eta):
461
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
462
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
463
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
464
+ # and should be between [0, 1]
465
+
466
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
467
+ extra_step_kwargs = {}
468
+ if accepts_eta:
469
+ extra_step_kwargs["eta"] = eta
470
+
471
+ # check if the scheduler accepts generator
472
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
473
+ if accepts_generator:
474
+ extra_step_kwargs["generator"] = generator
475
+ return extra_step_kwargs
476
+
477
+ def check_inputs(
478
+ self,
479
+ prompt,
480
+ strength,
481
+ num_inference_steps,
482
+ height,
483
+ width,
484
+ negative_prompt=None,
485
+ prompt_embeds=None,
486
+ pooled_prompt_embeds=None,
487
+ negative_prompt_embeds=None,
488
+ negative_pooled_prompt_embeds=None,
489
+ ip_adapter_image=None,
490
+ ip_adapter_image_embeds=None,
491
+ callback_on_step_end_tensor_inputs=None,
492
+ max_sequence_length=None,
493
+ ):
494
+ if strength < 0 or strength > 1:
495
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
496
+
497
+ if not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
498
+ raise ValueError(
499
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
500
+ f" {type(num_inference_steps)}."
501
+ )
502
+
503
+ if height % 8 != 0 or width % 8 != 0:
504
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
505
+
506
+ if callback_on_step_end_tensor_inputs is not None and not all(
507
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
508
+ ):
509
+ raise ValueError(
510
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
511
+ )
512
+
513
+ if prompt is not None and prompt_embeds is not None:
514
+ raise ValueError(
515
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
516
+ " only forward one of the two."
517
+ )
518
+ elif prompt is None and prompt_embeds is None:
519
+ raise ValueError(
520
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
521
+ )
522
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
523
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
524
+
525
+ if negative_prompt is not None and negative_prompt_embeds is not None:
526
+ raise ValueError(
527
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
528
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
529
+ )
530
+
531
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
532
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
533
+ raise ValueError(
534
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
535
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
536
+ f" {negative_prompt_embeds.shape}."
537
+ )
538
+
539
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
540
+ raise ValueError(
541
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
542
+ )
543
+
544
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
545
+ raise ValueError(
546
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
547
+ )
548
+
549
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
550
+ raise ValueError(
551
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
552
+ )
553
+
554
+ if ip_adapter_image_embeds is not None:
555
+ if not isinstance(ip_adapter_image_embeds, list):
556
+ raise ValueError(
557
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
558
+ )
559
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
560
+ raise ValueError(
561
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
562
+ )
563
+
564
+ if max_sequence_length is not None and max_sequence_length > 256:
565
+ raise ValueError(f"`max_sequence_length` cannot be greater than 256 but is {max_sequence_length}")
566
+
567
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
568
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
569
+ # get the original timestep using init_timestep
570
+ if denoising_start is None:
571
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
572
+ t_start = max(num_inference_steps - init_timestep, 0)
573
+ else:
574
+ t_start = 0
575
+
576
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
577
+
578
+ # Strength is irrelevant if we directly request a timestep to start at;
579
+ # that is, strength is determined by the denoising_start instead.
580
+ if denoising_start is not None:
581
+ discrete_timestep_cutoff = int(
582
+ round(
583
+ self.scheduler.config.num_train_timesteps
584
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
585
+ )
586
+ )
587
+
588
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
589
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
590
+ # if the scheduler is a 2nd order scheduler we might have to do +1
591
+ # because `num_inference_steps` might be even given that every timestep
592
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
593
+ # mean that we cut the timesteps in the middle of the denoising step
594
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
595
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
596
+ num_inference_steps = num_inference_steps + 1
597
+
598
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
599
+ timesteps = timesteps[-num_inference_steps:]
600
+ return timesteps, num_inference_steps
601
+
602
+ return timesteps, num_inference_steps - t_start
603
+
604
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
605
+ def prepare_latents(
606
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
607
+ ):
608
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
609
+ raise ValueError(
610
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
611
+ )
612
+
613
+ latents_mean = latents_std = None
614
+ if hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None:
615
+ latents_mean = torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1)
616
+ if hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None:
617
+ latents_std = torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1)
618
+
619
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
620
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
621
+ self.text_encoder_2.to("cpu")
622
+ torch.cuda.empty_cache()
623
+
624
+ image = image.to(device=device, dtype=dtype)
625
+
626
+ batch_size = batch_size * num_images_per_prompt
627
+
628
+ if image.shape[1] == 4:
629
+ init_latents = image
630
+
631
+ else:
632
+ # make sure the VAE is in float32 mode, as it overflows in float16
633
+ if self.vae.config.force_upcast:
634
+ image = image.float()
635
+ self.vae.to(dtype=torch.float32)
636
+
637
+ if isinstance(generator, list) and len(generator) != batch_size:
638
+ raise ValueError(
639
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
640
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
641
+ )
642
+
643
+ elif isinstance(generator, list):
644
+ if image.shape[0] < batch_size and batch_size % image.shape[0] == 0:
645
+ image = torch.cat([image] * (batch_size // image.shape[0]), dim=0)
646
+ elif image.shape[0] < batch_size and batch_size % image.shape[0] != 0:
647
+ raise ValueError(
648
+ f"Cannot duplicate `image` of batch size {image.shape[0]} to effective batch_size {batch_size} "
649
+ )
650
+
651
+ init_latents = [
652
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
653
+ for i in range(batch_size)
654
+ ]
655
+ init_latents = torch.cat(init_latents, dim=0)
656
+ else:
657
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
658
+
659
+ if self.vae.config.force_upcast:
660
+ self.vae.to(dtype)
661
+
662
+ init_latents = init_latents.to(dtype)
663
+ if latents_mean is not None and latents_std is not None:
664
+ latents_mean = latents_mean.to(device=device, dtype=dtype)
665
+ latents_std = latents_std.to(device=device, dtype=dtype)
666
+ init_latents = (init_latents - latents_mean) * self.vae.config.scaling_factor / latents_std
667
+ else:
668
+ init_latents = self.vae.config.scaling_factor * init_latents
669
+
670
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
671
+ # expand init_latents for batch_size
672
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
673
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
674
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
675
+ raise ValueError(
676
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
677
+ )
678
+ else:
679
+ init_latents = torch.cat([init_latents], dim=0)
680
+
681
+ if add_noise:
682
+ shape = init_latents.shape
683
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
684
+ # get latents
685
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
686
+
687
+ latents = init_latents
688
+
689
+ return latents
690
+
691
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
692
+ def _get_add_time_ids(
693
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
694
+ ):
695
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
696
+
697
+ passed_add_embed_dim = (
698
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
699
+ )
700
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
701
+
702
+ if expected_add_embed_dim != passed_add_embed_dim:
703
+ raise ValueError(
704
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
705
+ )
706
+
707
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
708
+ return add_time_ids
709
+
710
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.upcast_vae
711
+ def upcast_vae(self):
712
+ dtype = self.vae.dtype
713
+ self.vae.to(dtype=torch.float32)
714
+ use_torch_2_0_or_xformers = isinstance(
715
+ self.vae.decoder.mid_block.attentions[0].processor,
716
+ (
717
+ AttnProcessor2_0,
718
+ XFormersAttnProcessor,
719
+ FusedAttnProcessor2_0,
720
+ ),
721
+ )
722
+ # if xformers or torch_2_0 is used attention block does not need
723
+ # to be in float32 which can save lots of memory
724
+ if use_torch_2_0_or_xformers:
725
+ self.vae.post_quant_conv.to(dtype)
726
+ self.vae.decoder.conv_in.to(dtype)
727
+ self.vae.decoder.mid_block.to(dtype)
728
+
729
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
730
+ def get_guidance_scale_embedding(
731
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
732
+ ) -> torch.Tensor:
733
+ """
734
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
735
+
736
+ Args:
737
+ w (`torch.Tensor`):
738
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
739
+ embedding_dim (`int`, *optional*, defaults to 512):
740
+ Dimension of the embeddings to generate.
741
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
742
+ Data type of the generated embeddings.
743
+
744
+ Returns:
745
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
746
+ """
747
+ assert len(w.shape) == 1
748
+ w = w * 1000.0
749
+
750
+ half_dim = embedding_dim // 2
751
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
752
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
753
+ emb = w.to(dtype)[:, None] * emb[None, :]
754
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
755
+ if embedding_dim % 2 == 1: # zero pad
756
+ emb = torch.nn.functional.pad(emb, (0, 1))
757
+ assert emb.shape == (w.shape[0], embedding_dim)
758
+ return emb
759
+
760
+ @property
761
+ def guidance_scale(self):
762
+ return self._guidance_scale
763
+
764
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
765
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
766
+ # corresponds to doing no classifier free guidance.
767
+ @property
768
+ def do_classifier_free_guidance(self):
769
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
770
+
771
+ @property
772
+ def cross_attention_kwargs(self):
773
+ return self._cross_attention_kwargs
774
+
775
+ @property
776
+ def denoising_start(self):
777
+ return self._denoising_start
778
+
779
+ @property
780
+ def denoising_end(self):
781
+ return self._denoising_end
782
+
783
+ @property
784
+ def num_timesteps(self):
785
+ return self._num_timesteps
786
+
787
+ @property
788
+ def interrupt(self):
789
+ return self._interrupt
790
+
791
+ @torch.no_grad()
792
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
793
+ def __call__(
794
+ self,
795
+ prompt: Union[str, List[str]] = None,
796
+ image: PipelineImageInput = None,
797
+ strength: float = 0.3,
798
+ height: Optional[int] = None,
799
+ width: Optional[int] = None,
800
+ num_inference_steps: int = 50,
801
+ timesteps: List[int] = None,
802
+ sigmas: List[float] = None,
803
+ denoising_start: Optional[float] = None,
804
+ denoising_end: Optional[float] = None,
805
+ guidance_scale: float = 5.0,
806
+ negative_prompt: Optional[Union[str, List[str]]] = None,
807
+ num_images_per_prompt: Optional[int] = 1,
808
+ eta: float = 0.0,
809
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
810
+ latents: Optional[torch.Tensor] = None,
811
+ prompt_embeds: Optional[torch.Tensor] = None,
812
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
813
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
814
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
815
+ ip_adapter_image: Optional[PipelineImageInput] = None,
816
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
817
+ output_type: Optional[str] = "pil",
818
+ return_dict: bool = True,
819
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
820
+ original_size: Optional[Tuple[int, int]] = None,
821
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
822
+ target_size: Optional[Tuple[int, int]] = None,
823
+ negative_original_size: Optional[Tuple[int, int]] = None,
824
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
825
+ negative_target_size: Optional[Tuple[int, int]] = None,
826
+ callback_on_step_end: Optional[
827
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
828
+ ] = None,
829
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
830
+ max_sequence_length: int = 256,
831
+ map: PipelineImageInput = None,
832
+ ):
833
+ r"""
834
+ Function invoked when calling the pipeline for generation.
835
+
836
+ Args:
837
+ prompt (`str` or `List[str]`, *optional*):
838
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
839
+ instead.
840
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
841
+ The image(s) to modify with the pipeline.
842
+ strength (`float`, *optional*, defaults to 0.3):
843
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
844
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
845
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
846
+ be maximum and the denoising process will run for the full number of iterations specified in
847
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
848
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
849
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
850
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
851
+ Anything below 512 pixels won't work well for
852
+ [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
853
+ that are not specifically fine-tuned on low resolutions.
854
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
855
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
856
+ Anything below 512 pixels won't work well for
857
+ [Kwai-Kolors/Kolors-diffusers](https://huggingface.co/Kwai-Kolors/Kolors-diffusers) and checkpoints
858
+ that are not specifically fine-tuned on low resolutions.
859
+ num_inference_steps (`int`, *optional*, defaults to 50):
860
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
861
+ expense of slower inference.
862
+ timesteps (`List[int]`, *optional*):
863
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
864
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
865
+ passed will be used. Must be in descending order.
866
+ sigmas (`List[float]`, *optional*):
867
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
868
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
869
+ will be used.
870
+ denoising_start (`float`, *optional*):
871
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
872
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
873
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
874
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
875
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refine Image
876
+ Quality**](https://huggingface.co/docs/diffusers/using-diffusers/sdxl#refine-image-quality).
877
+ denoising_end (`float`, *optional*):
878
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
879
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
880
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
881
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
882
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
883
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
884
+ guidance_scale (`float`, *optional*, defaults to 5.0):
885
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
886
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
887
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
888
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
889
+ usually at the expense of lower image quality.
890
+ negative_prompt (`str` or `List[str]`, *optional*):
891
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
892
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
893
+ less than `1`).
894
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
895
+ The number of images to generate per prompt.
896
+ eta (`float`, *optional*, defaults to 0.0):
897
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
898
+ [`schedulers.DDIMScheduler`], will be ignored for others.
899
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
900
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
901
+ to make generation deterministic.
902
+ latents (`torch.Tensor`, *optional*):
903
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
904
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
905
+ tensor will ge generated by sampling using the supplied random `generator`.
906
+ prompt_embeds (`torch.Tensor`, *optional*):
907
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
908
+ provided, text embeddings will be generated from `prompt` input argument.
909
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
910
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
911
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
912
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
913
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
914
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
915
+ argument.
916
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
917
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
918
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
919
+ input argument.
920
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
921
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
922
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
923
+ IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
924
+ contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
925
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
926
+ output_type (`str`, *optional*, defaults to `"pil"`):
927
+ The output format of the generate image. Choose between
928
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
929
+ return_dict (`bool`, *optional*, defaults to `True`):
930
+ Whether or not to return a [`~pipelines.kolors.KolorsPipelineOutput`] instead of a plain tuple.
931
+ cross_attention_kwargs (`dict`, *optional*):
932
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
933
+ `self.processor` in
934
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
935
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
936
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
937
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
938
+ explained in section 2.2 of
939
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
940
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
941
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
942
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
943
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
944
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
945
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
946
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
947
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
948
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
949
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
950
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
951
+ micro-conditioning as explained in section 2.2 of
952
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
953
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
954
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
955
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
956
+ micro-conditioning as explained in section 2.2 of
957
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
958
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
959
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
960
+ To negatively condition the generation process based on a target image resolution. It should be as same
961
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
962
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
963
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
964
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
965
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
966
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
967
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
968
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
969
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
970
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
971
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
972
+ `._callback_tensor_inputs` attribute of your pipeline class.
973
+ max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
974
+
975
+ Examples:
976
+
977
+ Returns:
978
+ [`~pipelines.kolors.KolorsPipelineOutput`] or `tuple`: [`~pipelines.kolors.KolorsPipelineOutput`] if
979
+ `return_dict` is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the
980
+ generated images.
981
+ """
982
+
983
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
984
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
985
+
986
+ # 0. Default height and width to unet
987
+ height = height or self.default_sample_size * self.vae_scale_factor
988
+ width = width or self.default_sample_size * self.vae_scale_factor
989
+
990
+ original_size = original_size or (height, width)
991
+ target_size = target_size or (height, width)
992
+
993
+ # 1. Check inputs. Raise error if not correct
994
+ self.check_inputs(
995
+ prompt,
996
+ strength,
997
+ num_inference_steps,
998
+ height,
999
+ width,
1000
+ negative_prompt,
1001
+ prompt_embeds,
1002
+ pooled_prompt_embeds,
1003
+ negative_prompt_embeds,
1004
+ negative_pooled_prompt_embeds,
1005
+ ip_adapter_image,
1006
+ ip_adapter_image_embeds,
1007
+ callback_on_step_end_tensor_inputs,
1008
+ max_sequence_length=max_sequence_length,
1009
+ )
1010
+
1011
+ self._guidance_scale = guidance_scale
1012
+ self._cross_attention_kwargs = cross_attention_kwargs
1013
+ self._denoising_end = denoising_end
1014
+ self._denoising_start = denoising_start
1015
+ self._interrupt = False
1016
+
1017
+ # 2. Define call parameters
1018
+ if prompt is not None and isinstance(prompt, str):
1019
+ batch_size = 1
1020
+ elif prompt is not None and isinstance(prompt, list):
1021
+ batch_size = len(prompt)
1022
+ else:
1023
+ batch_size = prompt_embeds.shape[0]
1024
+
1025
+ device = self._execution_device
1026
+
1027
+ # 3. Encode input prompt
1028
+ (
1029
+ prompt_embeds,
1030
+ negative_prompt_embeds,
1031
+ pooled_prompt_embeds,
1032
+ negative_pooled_prompt_embeds,
1033
+ ) = self.encode_prompt(
1034
+ prompt=prompt,
1035
+ device=device,
1036
+ num_images_per_prompt=num_images_per_prompt,
1037
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1038
+ negative_prompt=negative_prompt,
1039
+ prompt_embeds=prompt_embeds,
1040
+ negative_prompt_embeds=negative_prompt_embeds,
1041
+ )
1042
+
1043
+ # 4. Preprocess image
1044
+ init_image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1045
+
1046
+ map = self.mask_processor.preprocess(
1047
+ map, height=height // self.vae_scale_factor, width=width // self.vae_scale_factor
1048
+ ).to(device)
1049
+
1050
+ # 5. Prepare timesteps
1051
+ def denoising_value_valid(dnv):
1052
+ return isinstance(dnv, float) and 0 < dnv < 1
1053
+
1054
+ timesteps, num_inference_steps = retrieve_timesteps(
1055
+ self.scheduler, num_inference_steps, device, timesteps, sigmas
1056
+ )
1057
+
1058
+ # begin diff diff change
1059
+ total_time_steps = num_inference_steps
1060
+ # end diff diff change
1061
+
1062
+ timesteps, num_inference_steps = self.get_timesteps(
1063
+ num_inference_steps,
1064
+ strength,
1065
+ device,
1066
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1067
+ )
1068
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1069
+
1070
+ add_noise = True if self.denoising_start is None else False
1071
+
1072
+ # 6. Prepare latent variables
1073
+ if latents is None:
1074
+ latents = self.prepare_latents(
1075
+ init_image,
1076
+ latent_timestep,
1077
+ batch_size,
1078
+ num_images_per_prompt,
1079
+ prompt_embeds.dtype,
1080
+ device,
1081
+ generator,
1082
+ add_noise,
1083
+ )
1084
+
1085
+ # 7. Prepare extra step kwargs.
1086
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1087
+
1088
+ height, width = latents.shape[-2:]
1089
+ height = height * self.vae_scale_factor
1090
+ width = width * self.vae_scale_factor
1091
+
1092
+ original_size = original_size or (height, width)
1093
+ target_size = target_size or (height, width)
1094
+
1095
+ # 8. Prepare added time ids & embeddings
1096
+ add_text_embeds = pooled_prompt_embeds
1097
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1098
+
1099
+ add_time_ids = self._get_add_time_ids(
1100
+ original_size,
1101
+ crops_coords_top_left,
1102
+ target_size,
1103
+ dtype=prompt_embeds.dtype,
1104
+ text_encoder_projection_dim=text_encoder_projection_dim,
1105
+ )
1106
+ if negative_original_size is not None and negative_target_size is not None:
1107
+ negative_add_time_ids = self._get_add_time_ids(
1108
+ negative_original_size,
1109
+ negative_crops_coords_top_left,
1110
+ negative_target_size,
1111
+ dtype=prompt_embeds.dtype,
1112
+ text_encoder_projection_dim=text_encoder_projection_dim,
1113
+ )
1114
+ else:
1115
+ negative_add_time_ids = add_time_ids
1116
+
1117
+ if self.do_classifier_free_guidance:
1118
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1119
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1120
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1121
+
1122
+ prompt_embeds = prompt_embeds.to(device)
1123
+ add_text_embeds = add_text_embeds.to(device)
1124
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1125
+
1126
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1127
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1128
+ ip_adapter_image,
1129
+ ip_adapter_image_embeds,
1130
+ device,
1131
+ batch_size * num_images_per_prompt,
1132
+ self.do_classifier_free_guidance,
1133
+ )
1134
+
1135
+ # 9. Denoising loop
1136
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1137
+
1138
+ # preparations for diff diff
1139
+ original_with_noise = self.prepare_latents(
1140
+ init_image, timesteps, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
1141
+ )
1142
+ thresholds = torch.arange(total_time_steps, dtype=map.dtype) / total_time_steps
1143
+ thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(device)
1144
+ masks = map.squeeze() > thresholds
1145
+ # end diff diff preparations
1146
+
1147
+ # 9.1 Apply denoising_end
1148
+ if (
1149
+ self.denoising_end is not None
1150
+ and self.denoising_start is not None
1151
+ and denoising_value_valid(self.denoising_end)
1152
+ and denoising_value_valid(self.denoising_start)
1153
+ and self.denoising_start >= self.denoising_end
1154
+ ):
1155
+ raise ValueError(
1156
+ f"`denoising_start`: {self.denoising_start} cannot be larger than or equal to `denoising_end`: "
1157
+ + f" {self.denoising_end} when using type float."
1158
+ )
1159
+ elif self.denoising_end is not None and denoising_value_valid(self.denoising_end):
1160
+ discrete_timestep_cutoff = int(
1161
+ round(
1162
+ self.scheduler.config.num_train_timesteps
1163
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1164
+ )
1165
+ )
1166
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1167
+ timesteps = timesteps[:num_inference_steps]
1168
+
1169
+ # 9.2 Optionally get Guidance Scale Embedding
1170
+ timestep_cond = None
1171
+ if self.unet.config.time_cond_proj_dim is not None:
1172
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1173
+ timestep_cond = self.get_guidance_scale_embedding(
1174
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1175
+ ).to(device=device, dtype=latents.dtype)
1176
+
1177
+ self._num_timesteps = len(timesteps)
1178
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1179
+ for i, t in enumerate(timesteps):
1180
+ if self.interrupt:
1181
+ continue
1182
+
1183
+ # diff diff
1184
+ if i == 0:
1185
+ latents = original_with_noise[:1]
1186
+ else:
1187
+ mask = masks[i].unsqueeze(0).to(latents.dtype)
1188
+ mask = mask.unsqueeze(1) # fit shape
1189
+ latents = original_with_noise[i] * mask + latents * (1 - mask)
1190
+ # end diff diff
1191
+
1192
+ # expand the latents if we are doing classifier free guidance
1193
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1194
+
1195
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1196
+
1197
+ # predict the noise residual
1198
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1199
+
1200
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1201
+ added_cond_kwargs["image_embeds"] = image_embeds
1202
+
1203
+ noise_pred = self.unet(
1204
+ latent_model_input,
1205
+ t,
1206
+ encoder_hidden_states=prompt_embeds,
1207
+ timestep_cond=timestep_cond,
1208
+ cross_attention_kwargs=self.cross_attention_kwargs,
1209
+ added_cond_kwargs=added_cond_kwargs,
1210
+ return_dict=False,
1211
+ )[0]
1212
+
1213
+ # perform guidance
1214
+ if self.do_classifier_free_guidance:
1215
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1216
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1217
+
1218
+ # compute the previous noisy sample x_t -> x_t-1
1219
+ latents_dtype = latents.dtype
1220
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1221
+ if latents.dtype != latents_dtype:
1222
+ if torch.backends.mps.is_available():
1223
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1224
+ latents = latents.to(latents_dtype)
1225
+
1226
+ if callback_on_step_end is not None:
1227
+ callback_kwargs = {}
1228
+ for k in callback_on_step_end_tensor_inputs:
1229
+ callback_kwargs[k] = locals()[k]
1230
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1231
+
1232
+ latents = callback_outputs.pop("latents", latents)
1233
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1234
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1235
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1236
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1237
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1238
+ )
1239
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1240
+ negative_add_time_ids = callback_outputs.pop("negative_add_time_ids", negative_add_time_ids)
1241
+
1242
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1243
+ progress_bar.update()
1244
+
1245
+ if XLA_AVAILABLE:
1246
+ xm.mark_step()
1247
+
1248
+ if not output_type == "latent":
1249
+ # make sure the VAE is in float32 mode, as it overflows in float16
1250
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1251
+
1252
+ if needs_upcasting:
1253
+ self.upcast_vae()
1254
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1255
+ elif latents.dtype != self.vae.dtype:
1256
+ if torch.backends.mps.is_available():
1257
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1258
+ self.vae = self.vae.to(latents.dtype)
1259
+
1260
+ # unscale/denormalize the latents
1261
+ latents = latents / self.vae.config.scaling_factor
1262
+
1263
+ image = self.vae.decode(latents, return_dict=False)[0]
1264
+
1265
+ # cast back to fp16 if needed
1266
+ if needs_upcasting:
1267
+ self.vae.to(dtype=torch.float16)
1268
+ else:
1269
+ image = latents
1270
+
1271
+ if not output_type == "latent":
1272
+ image = self.image_processor.postprocess(image, output_type=output_type)
1273
+
1274
+ # Offload all models
1275
+ self.maybe_free_model_hooks()
1276
+
1277
+ if not return_dict:
1278
+ return (image,)
1279
+
1280
+ return KolorsPipelineOutput(images=image)
v0.32.0/pipeline_null_text_inversion.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as nnf
7
+ from PIL import Image
8
+ from torch.optim.adam import Adam
9
+ from tqdm import tqdm
10
+
11
+ from diffusers import StableDiffusionPipeline
12
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
13
+
14
+
15
+ def retrieve_timesteps(
16
+ scheduler,
17
+ num_inference_steps=None,
18
+ device=None,
19
+ timesteps=None,
20
+ **kwargs,
21
+ ):
22
+ """
23
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
24
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
25
+ Args:
26
+ scheduler (`SchedulerMixin`):
27
+ The scheduler to get timesteps from.
28
+ num_inference_steps (`int`):
29
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
30
+ `timesteps` must be `None`.
31
+ device (`str` or `torch.device`, *optional*):
32
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
33
+ timesteps (`List[int]`, *optional*):
34
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
35
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
36
+ must be `None`.
37
+
38
+ Returns:
39
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
40
+ second element is the number of inference steps.
41
+ """
42
+ if timesteps is not None:
43
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
44
+ if not accepts_timesteps:
45
+ raise ValueError(
46
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
47
+ f" timestep schedules. Please check whether you are using the correct scheduler."
48
+ )
49
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
50
+ timesteps = scheduler.timesteps
51
+ num_inference_steps = len(timesteps)
52
+ else:
53
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
54
+ timesteps = scheduler.timesteps
55
+ return timesteps, num_inference_steps
56
+
57
+
58
+ class NullTextPipeline(StableDiffusionPipeline):
59
+ def get_noise_pred(self, latents, t, context):
60
+ latents_input = torch.cat([latents] * 2)
61
+ guidance_scale = 7.5
62
+ noise_pred = self.unet(latents_input, t, encoder_hidden_states=context)["sample"]
63
+ noise_pred_uncond, noise_prediction_text = noise_pred.chunk(2)
64
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_prediction_text - noise_pred_uncond)
65
+ latents = self.prev_step(noise_pred, t, latents)
66
+ return latents
67
+
68
+ def get_noise_pred_single(self, latents, t, context):
69
+ noise_pred = self.unet(latents, t, encoder_hidden_states=context)["sample"]
70
+ return noise_pred
71
+
72
+ @torch.no_grad()
73
+ def image2latent(self, image_path):
74
+ image = Image.open(image_path).convert("RGB")
75
+ image = np.array(image)
76
+ image = torch.from_numpy(image).float() / 127.5 - 1
77
+ image = image.permute(2, 0, 1).unsqueeze(0).to(self.device)
78
+ latents = self.vae.encode(image)["latent_dist"].mean
79
+ latents = latents * 0.18215
80
+ return latents
81
+
82
+ @torch.no_grad()
83
+ def latent2image(self, latents):
84
+ latents = 1 / 0.18215 * latents.detach()
85
+ image = self.vae.decode(latents)["sample"].detach()
86
+ image = self.processor.postprocess(image, output_type="pil")[0]
87
+ return image
88
+
89
+ def prev_step(self, model_output, timestep, sample):
90
+ prev_timestep = timestep - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
91
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
92
+ alpha_prod_t_prev = (
93
+ self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod
94
+ )
95
+ beta_prod_t = 1 - alpha_prod_t
96
+ pred_original_sample = (sample - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
97
+ pred_sample_direction = (1 - alpha_prod_t_prev) ** 0.5 * model_output
98
+ prev_sample = alpha_prod_t_prev**0.5 * pred_original_sample + pred_sample_direction
99
+ return prev_sample
100
+
101
+ def next_step(self, model_output, timestep, sample):
102
+ timestep, next_timestep = (
103
+ min(timestep - self.scheduler.config.num_train_timesteps // self.num_inference_steps, 999),
104
+ timestep,
105
+ )
106
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod
107
+ alpha_prod_t_next = self.scheduler.alphas_cumprod[next_timestep]
108
+ beta_prod_t = 1 - alpha_prod_t
109
+ next_original_sample = (sample - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
110
+ next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
111
+ next_sample = alpha_prod_t_next**0.5 * next_original_sample + next_sample_direction
112
+ return next_sample
113
+
114
+ def null_optimization(self, latents, context, num_inner_steps, epsilon):
115
+ uncond_embeddings, cond_embeddings = context.chunk(2)
116
+ uncond_embeddings_list = []
117
+ latent_cur = latents[-1]
118
+ bar = tqdm(total=num_inner_steps * self.num_inference_steps)
119
+ for i in range(self.num_inference_steps):
120
+ uncond_embeddings = uncond_embeddings.clone().detach()
121
+ uncond_embeddings.requires_grad = True
122
+ optimizer = Adam([uncond_embeddings], lr=1e-2 * (1.0 - i / 100.0))
123
+ latent_prev = latents[len(latents) - i - 2]
124
+ t = self.scheduler.timesteps[i]
125
+ with torch.no_grad():
126
+ noise_pred_cond = self.get_noise_pred_single(latent_cur, t, cond_embeddings)
127
+ for j in range(num_inner_steps):
128
+ noise_pred_uncond = self.get_noise_pred_single(latent_cur, t, uncond_embeddings)
129
+ noise_pred = noise_pred_uncond + 7.5 * (noise_pred_cond - noise_pred_uncond)
130
+ latents_prev_rec = self.prev_step(noise_pred, t, latent_cur)
131
+ loss = nnf.mse_loss(latents_prev_rec, latent_prev)
132
+ optimizer.zero_grad()
133
+ loss.backward()
134
+ optimizer.step()
135
+ loss_item = loss.item()
136
+ bar.update()
137
+ if loss_item < epsilon + i * 2e-5:
138
+ break
139
+ for j in range(j + 1, num_inner_steps):
140
+ bar.update()
141
+ uncond_embeddings_list.append(uncond_embeddings[:1].detach())
142
+ with torch.no_grad():
143
+ context = torch.cat([uncond_embeddings, cond_embeddings])
144
+ latent_cur = self.get_noise_pred(latent_cur, t, context)
145
+ bar.close()
146
+ return uncond_embeddings_list
147
+
148
+ @torch.no_grad()
149
+ def ddim_inversion_loop(self, latent, context):
150
+ self.scheduler.set_timesteps(self.num_inference_steps)
151
+ _, cond_embeddings = context.chunk(2)
152
+ all_latent = [latent]
153
+ latent = latent.clone().detach()
154
+ with torch.no_grad():
155
+ for i in range(0, self.num_inference_steps):
156
+ t = self.scheduler.timesteps[len(self.scheduler.timesteps) - i - 1]
157
+ noise_pred = self.unet(latent, t, encoder_hidden_states=cond_embeddings)["sample"]
158
+ latent = self.next_step(noise_pred, t, latent)
159
+ all_latent.append(latent)
160
+ return all_latent
161
+
162
+ def get_context(self, prompt):
163
+ uncond_input = self.tokenizer(
164
+ [""], padding="max_length", max_length=self.tokenizer.model_max_length, return_tensors="pt"
165
+ )
166
+ uncond_embeddings = self.text_encoder(uncond_input.input_ids.to(self.device))[0]
167
+ text_input = self.tokenizer(
168
+ [prompt],
169
+ padding="max_length",
170
+ max_length=self.tokenizer.model_max_length,
171
+ truncation=True,
172
+ return_tensors="pt",
173
+ )
174
+ text_embeddings = self.text_encoder(text_input.input_ids.to(self.device))[0]
175
+ context = torch.cat([uncond_embeddings, text_embeddings])
176
+ return context
177
+
178
+ def invert(
179
+ self, image_path: str, prompt: str, num_inner_steps=10, early_stop_epsilon=1e-6, num_inference_steps=50
180
+ ):
181
+ self.num_inference_steps = num_inference_steps
182
+ context = self.get_context(prompt)
183
+ latent = self.image2latent(image_path)
184
+ ddim_latents = self.ddim_inversion_loop(latent, context)
185
+ if os.path.exists(image_path + ".pt"):
186
+ uncond_embeddings = torch.load(image_path + ".pt")
187
+ else:
188
+ uncond_embeddings = self.null_optimization(ddim_latents, context, num_inner_steps, early_stop_epsilon)
189
+ uncond_embeddings = torch.stack(uncond_embeddings, 0)
190
+ torch.save(uncond_embeddings, image_path + ".pt")
191
+ return ddim_latents[-1], uncond_embeddings
192
+
193
+ @torch.no_grad()
194
+ def __call__(
195
+ self,
196
+ prompt,
197
+ uncond_embeddings,
198
+ inverted_latent,
199
+ num_inference_steps: int = 50,
200
+ timesteps=None,
201
+ guidance_scale=7.5,
202
+ negative_prompt=None,
203
+ num_images_per_prompt=1,
204
+ generator=None,
205
+ latents=None,
206
+ prompt_embeds=None,
207
+ negative_prompt_embeds=None,
208
+ output_type="pil",
209
+ ):
210
+ self._guidance_scale = guidance_scale
211
+ # 0. Default height and width to unet
212
+ height = self.unet.config.sample_size * self.vae_scale_factor
213
+ width = self.unet.config.sample_size * self.vae_scale_factor
214
+ # to deal with lora scaling and other possible forward hook
215
+ callback_steps = None
216
+ # 1. Check inputs. Raise error if not correct
217
+ self.check_inputs(
218
+ prompt,
219
+ height,
220
+ width,
221
+ callback_steps,
222
+ negative_prompt,
223
+ prompt_embeds,
224
+ negative_prompt_embeds,
225
+ )
226
+ # 2. Define call parameter
227
+ device = self._execution_device
228
+ # 3. Encode input prompt
229
+ prompt_embeds, _ = self.encode_prompt(
230
+ prompt,
231
+ device,
232
+ num_images_per_prompt,
233
+ self.do_classifier_free_guidance,
234
+ negative_prompt,
235
+ prompt_embeds=prompt_embeds,
236
+ negative_prompt_embeds=negative_prompt_embeds,
237
+ )
238
+ # 4. Prepare timesteps
239
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
240
+ latents = inverted_latent
241
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
242
+ for i, t in enumerate(timesteps):
243
+ noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=uncond_embeddings[i])["sample"]
244
+ noise_pred = self.unet(latents, t, encoder_hidden_states=prompt_embeds)["sample"]
245
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
246
+ # compute the previous noisy sample x_t -> x_t-1
247
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
248
+ progress_bar.update()
249
+ if not output_type == "latent":
250
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
251
+ 0
252
+ ]
253
+ else:
254
+ image = latents
255
+ image = self.image_processor.postprocess(
256
+ image, output_type=output_type, do_denormalize=[True] * image.shape[0]
257
+ )
258
+ # Offload all models
259
+ self.maybe_free_model_hooks()
260
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=False)
v0.32.0/pipeline_prompt2prompt.py ADDED
@@ -0,0 +1,1422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from __future__ import annotations
16
+
17
+ import abc
18
+ import inspect
19
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn.functional as F
24
+ from packaging import version
25
+ from transformers import (
26
+ CLIPImageProcessor,
27
+ CLIPTextModel,
28
+ CLIPTokenizer,
29
+ CLIPVisionModelWithProjection,
30
+ )
31
+
32
+ from diffusers import AutoencoderKL, DiffusionPipeline, UNet2DConditionModel
33
+ from diffusers.configuration_utils import FrozenDict, deprecate
34
+ from diffusers.image_processor import VaeImageProcessor
35
+ from diffusers.loaders import (
36
+ FromSingleFileMixin,
37
+ IPAdapterMixin,
38
+ StableDiffusionLoraLoaderMixin,
39
+ TextualInversionLoaderMixin,
40
+ )
41
+ from diffusers.models.attention import Attention
42
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
43
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
44
+ from diffusers.pipelines.stable_diffusion.safety_checker import (
45
+ StableDiffusionSafetyChecker,
46
+ )
47
+ from diffusers.schedulers import KarrasDiffusionSchedulers
48
+ from diffusers.utils import (
49
+ USE_PEFT_BACKEND,
50
+ logging,
51
+ scale_lora_layers,
52
+ unscale_lora_layers,
53
+ )
54
+ from diffusers.utils.torch_utils import randn_tensor
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+
60
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
61
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
62
+ """
63
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
64
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
65
+ """
66
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
67
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
68
+ # rescale the results from guidance (fixes overexposure)
69
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
70
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
71
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
72
+ return noise_cfg
73
+
74
+
75
+ class Prompt2PromptPipeline(
76
+ DiffusionPipeline,
77
+ TextualInversionLoaderMixin,
78
+ StableDiffusionLoraLoaderMixin,
79
+ IPAdapterMixin,
80
+ FromSingleFileMixin,
81
+ ):
82
+ r"""
83
+ Pipeline for text-to-image generation using Stable Diffusion.
84
+
85
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
86
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
87
+
88
+ The pipeline also inherits the following loading methods:
89
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
90
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
91
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
92
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
93
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
94
+
95
+ Args:
96
+ vae ([`AutoencoderKL`]):
97
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
98
+ text_encoder ([`~transformers.CLIPTextModel`]):
99
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
100
+ tokenizer ([`~transformers.CLIPTokenizer`]):
101
+ A `CLIPTokenizer` to tokenize text.
102
+ unet ([`UNet2DConditionModel`]):
103
+ A `UNet2DConditionModel` to denoise the encoded image latents.
104
+ scheduler ([`SchedulerMixin`]):
105
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
106
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
107
+ safety_checker ([`StableDiffusionSafetyChecker`]):
108
+ Classification module that estimates whether generated images could be considered offensive or harmful.
109
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
110
+ about a model's potential harms.
111
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
112
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
113
+ """
114
+
115
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
116
+ _exclude_from_cpu_offload = ["safety_checker"]
117
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
118
+ _optional_components = ["safety_checker", "feature_extractor"]
119
+
120
+ def __init__(
121
+ self,
122
+ vae: AutoencoderKL,
123
+ text_encoder: CLIPTextModel,
124
+ tokenizer: CLIPTokenizer,
125
+ unet: UNet2DConditionModel,
126
+ scheduler: KarrasDiffusionSchedulers,
127
+ safety_checker: StableDiffusionSafetyChecker,
128
+ feature_extractor: CLIPImageProcessor,
129
+ image_encoder: CLIPVisionModelWithProjection = None,
130
+ requires_safety_checker: bool = True,
131
+ ):
132
+ super().__init__()
133
+
134
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
135
+ deprecation_message = (
136
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
137
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
138
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
139
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
140
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
141
+ " file"
142
+ )
143
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
144
+ new_config = dict(scheduler.config)
145
+ new_config["steps_offset"] = 1
146
+ scheduler._internal_dict = FrozenDict(new_config)
147
+
148
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
149
+ deprecation_message = (
150
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
151
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
152
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
153
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
154
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
155
+ )
156
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
157
+ new_config = dict(scheduler.config)
158
+ new_config["clip_sample"] = False
159
+ scheduler._internal_dict = FrozenDict(new_config)
160
+
161
+ if safety_checker is None and requires_safety_checker:
162
+ logger.warning(
163
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
164
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
165
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
166
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
167
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
168
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
169
+ )
170
+
171
+ if safety_checker is not None and feature_extractor is None:
172
+ raise ValueError(
173
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
174
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
175
+ )
176
+
177
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
178
+ version.parse(unet.config._diffusers_version).base_version
179
+ ) < version.parse("0.9.0.dev0")
180
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
181
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
182
+ deprecation_message = (
183
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
184
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
185
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
186
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
187
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
188
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
189
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
190
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
191
+ " the `unet/config.json` file"
192
+ )
193
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
194
+ new_config = dict(unet.config)
195
+ new_config["sample_size"] = 64
196
+ unet._internal_dict = FrozenDict(new_config)
197
+
198
+ self.register_modules(
199
+ vae=vae,
200
+ text_encoder=text_encoder,
201
+ tokenizer=tokenizer,
202
+ unet=unet,
203
+ scheduler=scheduler,
204
+ safety_checker=safety_checker,
205
+ feature_extractor=feature_extractor,
206
+ image_encoder=image_encoder,
207
+ )
208
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
209
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
210
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
211
+
212
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
213
+ def _encode_prompt(
214
+ self,
215
+ prompt,
216
+ device,
217
+ num_images_per_prompt,
218
+ do_classifier_free_guidance,
219
+ negative_prompt=None,
220
+ prompt_embeds: Optional[torch.Tensor] = None,
221
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
222
+ lora_scale: Optional[float] = None,
223
+ **kwargs,
224
+ ):
225
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
226
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
227
+
228
+ prompt_embeds_tuple = self.encode_prompt(
229
+ prompt=prompt,
230
+ device=device,
231
+ num_images_per_prompt=num_images_per_prompt,
232
+ do_classifier_free_guidance=do_classifier_free_guidance,
233
+ negative_prompt=negative_prompt,
234
+ prompt_embeds=prompt_embeds,
235
+ negative_prompt_embeds=negative_prompt_embeds,
236
+ lora_scale=lora_scale,
237
+ **kwargs,
238
+ )
239
+
240
+ # concatenate for backwards comp
241
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
242
+
243
+ return prompt_embeds
244
+
245
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
246
+ def encode_prompt(
247
+ self,
248
+ prompt,
249
+ device,
250
+ num_images_per_prompt,
251
+ do_classifier_free_guidance,
252
+ negative_prompt=None,
253
+ prompt_embeds: Optional[torch.Tensor] = None,
254
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
255
+ lora_scale: Optional[float] = None,
256
+ clip_skip: Optional[int] = None,
257
+ ):
258
+ r"""
259
+ Encodes the prompt into text encoder hidden states.
260
+
261
+ Args:
262
+ prompt (`str` or `List[str]`, *optional*):
263
+ prompt to be encoded
264
+ device: (`torch.device`):
265
+ torch device
266
+ num_images_per_prompt (`int`):
267
+ number of images that should be generated per prompt
268
+ do_classifier_free_guidance (`bool`):
269
+ whether to use classifier free guidance or not
270
+ negative_prompt (`str` or `List[str]`, *optional*):
271
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
272
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
273
+ less than `1`).
274
+ prompt_embeds (`torch.Tensor`, *optional*):
275
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
276
+ provided, text embeddings will be generated from `prompt` input argument.
277
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
278
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
279
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
280
+ argument.
281
+ lora_scale (`float`, *optional*):
282
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
283
+ clip_skip (`int`, *optional*):
284
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
285
+ the output of the pre-final layer will be used for computing the prompt embeddings.
286
+ """
287
+ # set lora scale so that monkey patched LoRA
288
+ # function of text encoder can correctly access it
289
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
290
+ self._lora_scale = lora_scale
291
+
292
+ # dynamically adjust the LoRA scale
293
+ if not USE_PEFT_BACKEND:
294
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
295
+ else:
296
+ scale_lora_layers(self.text_encoder, lora_scale)
297
+
298
+ if prompt is not None and isinstance(prompt, str):
299
+ batch_size = 1
300
+ elif prompt is not None and isinstance(prompt, list):
301
+ batch_size = len(prompt)
302
+ else:
303
+ batch_size = prompt_embeds.shape[0]
304
+
305
+ if prompt_embeds is None:
306
+ # textual inversion: process multi-vector tokens if necessary
307
+ if isinstance(self, TextualInversionLoaderMixin):
308
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
309
+
310
+ text_inputs = self.tokenizer(
311
+ prompt,
312
+ padding="max_length",
313
+ max_length=self.tokenizer.model_max_length,
314
+ truncation=True,
315
+ return_tensors="pt",
316
+ )
317
+ text_input_ids = text_inputs.input_ids
318
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
319
+
320
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
321
+ text_input_ids, untruncated_ids
322
+ ):
323
+ removed_text = self.tokenizer.batch_decode(
324
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
325
+ )
326
+ logger.warning(
327
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
328
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
329
+ )
330
+
331
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
332
+ attention_mask = text_inputs.attention_mask.to(device)
333
+ else:
334
+ attention_mask = None
335
+
336
+ if clip_skip is None:
337
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
338
+ prompt_embeds = prompt_embeds[0]
339
+ else:
340
+ prompt_embeds = self.text_encoder(
341
+ text_input_ids.to(device),
342
+ attention_mask=attention_mask,
343
+ output_hidden_states=True,
344
+ )
345
+ # Access the `hidden_states` first, that contains a tuple of
346
+ # all the hidden states from the encoder layers. Then index into
347
+ # the tuple to access the hidden states from the desired layer.
348
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
349
+ # We also need to apply the final LayerNorm here to not mess with the
350
+ # representations. The `last_hidden_states` that we typically use for
351
+ # obtaining the final prompt representations passes through the LayerNorm
352
+ # layer.
353
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
354
+
355
+ if self.text_encoder is not None:
356
+ prompt_embeds_dtype = self.text_encoder.dtype
357
+ elif self.unet is not None:
358
+ prompt_embeds_dtype = self.unet.dtype
359
+ else:
360
+ prompt_embeds_dtype = prompt_embeds.dtype
361
+
362
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
363
+
364
+ bs_embed, seq_len, _ = prompt_embeds.shape
365
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
366
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
367
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
368
+
369
+ # get unconditional embeddings for classifier free guidance
370
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
371
+ uncond_tokens: List[str]
372
+ if negative_prompt is None:
373
+ uncond_tokens = [""] * batch_size
374
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
375
+ raise TypeError(
376
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
377
+ f" {type(prompt)}."
378
+ )
379
+ elif isinstance(negative_prompt, str):
380
+ uncond_tokens = [negative_prompt]
381
+ elif batch_size != len(negative_prompt):
382
+ raise ValueError(
383
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
384
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
385
+ " the batch size of `prompt`."
386
+ )
387
+ else:
388
+ uncond_tokens = negative_prompt
389
+
390
+ # textual inversion: process multi-vector tokens if necessary
391
+ if isinstance(self, TextualInversionLoaderMixin):
392
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
393
+
394
+ max_length = prompt_embeds.shape[1]
395
+ uncond_input = self.tokenizer(
396
+ uncond_tokens,
397
+ padding="max_length",
398
+ max_length=max_length,
399
+ truncation=True,
400
+ return_tensors="pt",
401
+ )
402
+
403
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
404
+ attention_mask = uncond_input.attention_mask.to(device)
405
+ else:
406
+ attention_mask = None
407
+
408
+ negative_prompt_embeds = self.text_encoder(
409
+ uncond_input.input_ids.to(device),
410
+ attention_mask=attention_mask,
411
+ )
412
+ negative_prompt_embeds = negative_prompt_embeds[0]
413
+
414
+ if do_classifier_free_guidance:
415
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
416
+ seq_len = negative_prompt_embeds.shape[1]
417
+
418
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
419
+
420
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
421
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
422
+
423
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
424
+ # Retrieve the original scale by scaling back the LoRA layers
425
+ unscale_lora_layers(self.text_encoder, lora_scale)
426
+
427
+ return prompt_embeds, negative_prompt_embeds
428
+
429
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
430
+ def run_safety_checker(self, image, device, dtype):
431
+ if self.safety_checker is None:
432
+ has_nsfw_concept = None
433
+ else:
434
+ if torch.is_tensor(image):
435
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
436
+ else:
437
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
438
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
439
+ image, has_nsfw_concept = self.safety_checker(
440
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
441
+ )
442
+ return image, has_nsfw_concept
443
+
444
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
445
+ def prepare_extra_step_kwargs(self, generator, eta):
446
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
447
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
448
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
449
+ # and should be between [0, 1]
450
+
451
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
452
+ extra_step_kwargs = {}
453
+ if accepts_eta:
454
+ extra_step_kwargs["eta"] = eta
455
+
456
+ # check if the scheduler accepts generator
457
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
458
+ if accepts_generator:
459
+ extra_step_kwargs["generator"] = generator
460
+ return extra_step_kwargs
461
+
462
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
463
+ def check_inputs(
464
+ self,
465
+ prompt,
466
+ height,
467
+ width,
468
+ callback_steps,
469
+ negative_prompt=None,
470
+ prompt_embeds=None,
471
+ negative_prompt_embeds=None,
472
+ ip_adapter_image=None,
473
+ ip_adapter_image_embeds=None,
474
+ callback_on_step_end_tensor_inputs=None,
475
+ ):
476
+ if height % 8 != 0 or width % 8 != 0:
477
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
478
+
479
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
480
+ raise ValueError(
481
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
482
+ f" {type(callback_steps)}."
483
+ )
484
+ if callback_on_step_end_tensor_inputs is not None and not all(
485
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
486
+ ):
487
+ raise ValueError(
488
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
489
+ )
490
+
491
+ if prompt is not None and prompt_embeds is not None:
492
+ raise ValueError(
493
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
494
+ " only forward one of the two."
495
+ )
496
+ elif prompt is None and prompt_embeds is None:
497
+ raise ValueError(
498
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
499
+ )
500
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
501
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
502
+
503
+ if negative_prompt is not None and negative_prompt_embeds is not None:
504
+ raise ValueError(
505
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
506
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
507
+ )
508
+
509
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
510
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
511
+ raise ValueError(
512
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
513
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
514
+ f" {negative_prompt_embeds.shape}."
515
+ )
516
+
517
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
518
+ raise ValueError(
519
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
520
+ )
521
+
522
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
523
+ def prepare_latents(
524
+ self,
525
+ batch_size,
526
+ num_channels_latents,
527
+ height,
528
+ width,
529
+ dtype,
530
+ device,
531
+ generator,
532
+ latents=None,
533
+ ):
534
+ shape = (
535
+ batch_size,
536
+ num_channels_latents,
537
+ height // self.vae_scale_factor,
538
+ width // self.vae_scale_factor,
539
+ )
540
+ if isinstance(generator, list) and len(generator) != batch_size:
541
+ raise ValueError(
542
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
543
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
544
+ )
545
+
546
+ if latents is None:
547
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
548
+ else:
549
+ latents = latents.to(device)
550
+
551
+ # scale the initial noise by the standard deviation required by the scheduler
552
+ latents = latents * self.scheduler.init_noise_sigma
553
+ return latents
554
+
555
+ @torch.no_grad()
556
+ def __call__(
557
+ self,
558
+ prompt: Union[str, List[str]],
559
+ height: Optional[int] = None,
560
+ width: Optional[int] = None,
561
+ num_inference_steps: int = 50,
562
+ guidance_scale: float = 7.5,
563
+ negative_prompt: Optional[Union[str, List[str]]] = None,
564
+ num_images_per_prompt: Optional[int] = 1,
565
+ eta: float = 0.0,
566
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
567
+ latents: Optional[torch.Tensor] = None,
568
+ prompt_embeds: Optional[torch.Tensor] = None,
569
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
570
+ output_type: Optional[str] = "pil",
571
+ return_dict: bool = True,
572
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
573
+ callback_steps: Optional[int] = 1,
574
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
575
+ guidance_rescale: float = 0.0,
576
+ ):
577
+ r"""
578
+ Function invoked when calling the pipeline for generation.
579
+
580
+ Args:
581
+ prompt (`str` or `List[str]`):
582
+ The prompt or prompts to guide the image generation.
583
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
584
+ The height in pixels of the generated image.
585
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
586
+ The width in pixels of the generated image.
587
+ num_inference_steps (`int`, *optional*, defaults to 50):
588
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
589
+ expense of slower inference.
590
+ guidance_scale (`float`, *optional*, defaults to 7.5):
591
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
592
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
593
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
594
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
595
+ usually at the expense of lower image quality.
596
+ negative_prompt (`str` or `List[str]`, *optional*):
597
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
598
+ if `guidance_scale` is less than `1`).
599
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
600
+ The number of images to generate per prompt.
601
+ eta (`float`, *optional*, defaults to 0.0):
602
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
603
+ [`schedulers.DDIMScheduler`], will be ignored for others.
604
+ generator (`torch.Generator`, *optional*):
605
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
606
+ to make generation deterministic.
607
+ latents (`torch.Tensor`, *optional*):
608
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
609
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
610
+ tensor will ge generated by sampling using the supplied random `generator`.
611
+ output_type (`str`, *optional*, defaults to `"pil"`):
612
+ The output format of the generate image. Choose between
613
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
614
+ return_dict (`bool`, *optional*, defaults to `True`):
615
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
616
+ plain tuple.
617
+ callback (`Callable`, *optional*):
618
+ A function that will be called every `callback_steps` steps during inference. The function will be
619
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
620
+ callback_steps (`int`, *optional*, defaults to 1):
621
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
622
+ called at every step.
623
+ cross_attention_kwargs (`dict`, *optional*):
624
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
625
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
626
+
627
+ The keyword arguments to configure the edit are:
628
+ - edit_type (`str`). The edit type to apply. Can be either of `replace`, `refine`, `reweight`.
629
+ - n_cross_replace (`int`): Number of diffusion steps in which cross attention should be replaced
630
+ - n_self_replace (`int`): Number of diffusion steps in which self attention should be replaced
631
+ - local_blend_words(`List[str]`, *optional*, default to `None`): Determines which area should be
632
+ changed. If None, then the whole image can be changed.
633
+ - equalizer_words(`List[str]`, *optional*, default to `None`): Required for edit type `reweight`.
634
+ Determines which words should be enhanced.
635
+ - equalizer_strengths (`List[float]`, *optional*, default to `None`) Required for edit type `reweight`.
636
+ Determines which how much the words in `equalizer_words` should be enhanced.
637
+
638
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
639
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
640
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
641
+ using zero terminal SNR.
642
+
643
+ Returns:
644
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
645
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
646
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
647
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
648
+ (nsfw) content, according to the `safety_checker`.
649
+ """
650
+
651
+ self.controller = create_controller(
652
+ prompt,
653
+ cross_attention_kwargs,
654
+ num_inference_steps,
655
+ tokenizer=self.tokenizer,
656
+ device=self.device,
657
+ )
658
+ self.register_attention_control(self.controller) # add attention controller
659
+
660
+ # 0. Default height and width to unet
661
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
662
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
663
+
664
+ # 1. Check inputs. Raise error if not correct
665
+ self.check_inputs(prompt, height, width, callback_steps)
666
+
667
+ # 2. Define call parameters
668
+ if prompt is not None and isinstance(prompt, str):
669
+ batch_size = 1
670
+ elif prompt is not None and isinstance(prompt, list):
671
+ batch_size = len(prompt)
672
+ else:
673
+ batch_size = prompt_embeds.shape[0]
674
+
675
+ device = self._execution_device
676
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
677
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
678
+ # corresponds to doing no classifier free guidance.
679
+ do_classifier_free_guidance = guidance_scale > 1.0
680
+
681
+ # 3. Encode input prompt
682
+ text_encoder_lora_scale = (
683
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
684
+ )
685
+ prompt_embeds = self._encode_prompt(
686
+ prompt,
687
+ device,
688
+ num_images_per_prompt,
689
+ do_classifier_free_guidance,
690
+ negative_prompt,
691
+ prompt_embeds=prompt_embeds,
692
+ negative_prompt_embeds=negative_prompt_embeds,
693
+ lora_scale=text_encoder_lora_scale,
694
+ )
695
+
696
+ # 4. Prepare timesteps
697
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
698
+ timesteps = self.scheduler.timesteps
699
+
700
+ # 5. Prepare latent variables
701
+ num_channels_latents = self.unet.config.in_channels
702
+ latents = self.prepare_latents(
703
+ batch_size * num_images_per_prompt,
704
+ num_channels_latents,
705
+ height,
706
+ width,
707
+ prompt_embeds.dtype,
708
+ device,
709
+ generator,
710
+ latents,
711
+ )
712
+
713
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
714
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
715
+
716
+ # 7. Denoising loop
717
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
718
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
719
+ for i, t in enumerate(timesteps):
720
+ # expand the latents if we are doing classifier free guidance
721
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
722
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
723
+
724
+ # predict the noise residual
725
+ noise_pred = self.unet(latent_model_input, t, encoder_hidden_states=prompt_embeds).sample
726
+
727
+ # perform guidance
728
+ if do_classifier_free_guidance:
729
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
730
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
731
+
732
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
733
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
734
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
735
+
736
+ # compute the previous noisy sample x_t -> x_t-1
737
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
738
+
739
+ # step callback
740
+ latents = self.controller.step_callback(latents)
741
+
742
+ # call the callback, if provided
743
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
744
+ progress_bar.update()
745
+ if callback is not None and i % callback_steps == 0:
746
+ step_idx = i // getattr(self.scheduler, "order", 1)
747
+ callback(step_idx, t, latents)
748
+
749
+ # 8. Post-processing
750
+ if not output_type == "latent":
751
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
752
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
753
+ else:
754
+ image = latents
755
+ has_nsfw_concept = None
756
+
757
+ # 9. Run safety checker
758
+ if has_nsfw_concept is None:
759
+ do_denormalize = [True] * image.shape[0]
760
+ else:
761
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
762
+
763
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
764
+
765
+ # Offload last model to CPU
766
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
767
+ self.final_offload_hook.offload()
768
+
769
+ if not return_dict:
770
+ return (image, has_nsfw_concept)
771
+
772
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
773
+
774
+ def register_attention_control(self, controller):
775
+ attn_procs = {}
776
+ cross_att_count = 0
777
+ for name in self.unet.attn_processors.keys():
778
+ (None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim)
779
+ if name.startswith("mid_block"):
780
+ self.unet.config.block_out_channels[-1]
781
+ place_in_unet = "mid"
782
+ elif name.startswith("up_blocks"):
783
+ block_id = int(name[len("up_blocks.")])
784
+ list(reversed(self.unet.config.block_out_channels))[block_id]
785
+ place_in_unet = "up"
786
+ elif name.startswith("down_blocks"):
787
+ block_id = int(name[len("down_blocks.")])
788
+ self.unet.config.block_out_channels[block_id]
789
+ place_in_unet = "down"
790
+ else:
791
+ continue
792
+ cross_att_count += 1
793
+ attn_procs[name] = P2PCrossAttnProcessor(controller=controller, place_in_unet=place_in_unet)
794
+
795
+ self.unet.set_attn_processor(attn_procs)
796
+ controller.num_att_layers = cross_att_count
797
+
798
+
799
+ class P2PCrossAttnProcessor:
800
+ def __init__(self, controller, place_in_unet):
801
+ super().__init__()
802
+ self.controller = controller
803
+ self.place_in_unet = place_in_unet
804
+
805
+ def __call__(
806
+ self,
807
+ attn: Attention,
808
+ hidden_states,
809
+ encoder_hidden_states=None,
810
+ attention_mask=None,
811
+ ):
812
+ batch_size, sequence_length, _ = hidden_states.shape
813
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
814
+
815
+ query = attn.to_q(hidden_states)
816
+
817
+ is_cross = encoder_hidden_states is not None
818
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
819
+ key = attn.to_k(encoder_hidden_states)
820
+ value = attn.to_v(encoder_hidden_states)
821
+
822
+ query = attn.head_to_batch_dim(query)
823
+ key = attn.head_to_batch_dim(key)
824
+ value = attn.head_to_batch_dim(value)
825
+
826
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
827
+
828
+ # one line change
829
+ self.controller(attention_probs, is_cross, self.place_in_unet)
830
+
831
+ hidden_states = torch.bmm(attention_probs, value)
832
+ hidden_states = attn.batch_to_head_dim(hidden_states)
833
+
834
+ # linear proj
835
+ hidden_states = attn.to_out[0](hidden_states)
836
+ # dropout
837
+ hidden_states = attn.to_out[1](hidden_states)
838
+
839
+ return hidden_states
840
+
841
+
842
+ def create_controller(
843
+ prompts: List[str],
844
+ cross_attention_kwargs: Dict,
845
+ num_inference_steps: int,
846
+ tokenizer,
847
+ device,
848
+ ) -> AttentionControl:
849
+ edit_type = cross_attention_kwargs.get("edit_type", None)
850
+ local_blend_words = cross_attention_kwargs.get("local_blend_words", None)
851
+ equalizer_words = cross_attention_kwargs.get("equalizer_words", None)
852
+ equalizer_strengths = cross_attention_kwargs.get("equalizer_strengths", None)
853
+ n_cross_replace = cross_attention_kwargs.get("n_cross_replace", 0.4)
854
+ n_self_replace = cross_attention_kwargs.get("n_self_replace", 0.4)
855
+
856
+ # only replace
857
+ if edit_type == "replace" and local_blend_words is None:
858
+ return AttentionReplace(
859
+ prompts,
860
+ num_inference_steps,
861
+ n_cross_replace,
862
+ n_self_replace,
863
+ tokenizer=tokenizer,
864
+ device=device,
865
+ )
866
+
867
+ # replace + localblend
868
+ if edit_type == "replace" and local_blend_words is not None:
869
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device)
870
+ return AttentionReplace(
871
+ prompts,
872
+ num_inference_steps,
873
+ n_cross_replace,
874
+ n_self_replace,
875
+ lb,
876
+ tokenizer=tokenizer,
877
+ device=device,
878
+ )
879
+
880
+ # only refine
881
+ if edit_type == "refine" and local_blend_words is None:
882
+ return AttentionRefine(
883
+ prompts,
884
+ num_inference_steps,
885
+ n_cross_replace,
886
+ n_self_replace,
887
+ tokenizer=tokenizer,
888
+ device=device,
889
+ )
890
+
891
+ # refine + localblend
892
+ if edit_type == "refine" and local_blend_words is not None:
893
+ lb = LocalBlend(prompts, local_blend_words, tokenizer=tokenizer, device=device)
894
+ return AttentionRefine(
895
+ prompts,
896
+ num_inference_steps,
897
+ n_cross_replace,
898
+ n_self_replace,
899
+ lb,
900
+ tokenizer=tokenizer,
901
+ device=device,
902
+ )
903
+
904
+ # reweight
905
+ if edit_type == "reweight":
906
+ assert (
907
+ equalizer_words is not None and equalizer_strengths is not None
908
+ ), "To use reweight edit, please specify equalizer_words and equalizer_strengths."
909
+ assert len(equalizer_words) == len(
910
+ equalizer_strengths
911
+ ), "equalizer_words and equalizer_strengths must be of same length."
912
+ equalizer = get_equalizer(prompts[1], equalizer_words, equalizer_strengths, tokenizer=tokenizer)
913
+ return AttentionReweight(
914
+ prompts,
915
+ num_inference_steps,
916
+ n_cross_replace,
917
+ n_self_replace,
918
+ tokenizer=tokenizer,
919
+ device=device,
920
+ equalizer=equalizer,
921
+ )
922
+
923
+ raise ValueError(f"Edit type {edit_type} not recognized. Use one of: replace, refine, reweight.")
924
+
925
+
926
+ class AttentionControl(abc.ABC):
927
+ def step_callback(self, x_t):
928
+ return x_t
929
+
930
+ def between_steps(self):
931
+ return
932
+
933
+ @property
934
+ def num_uncond_att_layers(self):
935
+ return 0
936
+
937
+ @abc.abstractmethod
938
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
939
+ raise NotImplementedError
940
+
941
+ def __call__(self, attn, is_cross: bool, place_in_unet: str):
942
+ if self.cur_att_layer >= self.num_uncond_att_layers:
943
+ h = attn.shape[0]
944
+ attn[h // 2 :] = self.forward(attn[h // 2 :], is_cross, place_in_unet)
945
+ self.cur_att_layer += 1
946
+ if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
947
+ self.cur_att_layer = 0
948
+ self.cur_step += 1
949
+ self.between_steps()
950
+ return attn
951
+
952
+ def reset(self):
953
+ self.cur_step = 0
954
+ self.cur_att_layer = 0
955
+
956
+ def __init__(self):
957
+ self.cur_step = 0
958
+ self.num_att_layers = -1
959
+ self.cur_att_layer = 0
960
+
961
+
962
+ class EmptyControl(AttentionControl):
963
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
964
+ return attn
965
+
966
+
967
+ class AttentionStore(AttentionControl):
968
+ @staticmethod
969
+ def get_empty_store():
970
+ return {
971
+ "down_cross": [],
972
+ "mid_cross": [],
973
+ "up_cross": [],
974
+ "down_self": [],
975
+ "mid_self": [],
976
+ "up_self": [],
977
+ }
978
+
979
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
980
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
981
+ if attn.shape[1] <= 32**2: # avoid memory overhead
982
+ self.step_store[key].append(attn)
983
+ return attn
984
+
985
+ def between_steps(self):
986
+ if len(self.attention_store) == 0:
987
+ self.attention_store = self.step_store
988
+ else:
989
+ for key in self.attention_store:
990
+ for i in range(len(self.attention_store[key])):
991
+ self.attention_store[key][i] += self.step_store[key][i]
992
+ self.step_store = self.get_empty_store()
993
+
994
+ def get_average_attention(self):
995
+ average_attention = {
996
+ key: [item / self.cur_step for item in self.attention_store[key]] for key in self.attention_store
997
+ }
998
+ return average_attention
999
+
1000
+ def reset(self):
1001
+ super(AttentionStore, self).reset()
1002
+ self.step_store = self.get_empty_store()
1003
+ self.attention_store = {}
1004
+
1005
+ def __init__(self):
1006
+ super(AttentionStore, self).__init__()
1007
+ self.step_store = self.get_empty_store()
1008
+ self.attention_store = {}
1009
+
1010
+
1011
+ class LocalBlend:
1012
+ def __call__(self, x_t, attention_store):
1013
+ k = 1
1014
+ maps = attention_store["down_cross"][2:4] + attention_store["up_cross"][:3]
1015
+ maps = [item.reshape(self.alpha_layers.shape[0], -1, 1, 16, 16, self.max_num_words) for item in maps]
1016
+ maps = torch.cat(maps, dim=1)
1017
+ maps = (maps * self.alpha_layers).sum(-1).mean(1)
1018
+ mask = F.max_pool2d(maps, (k * 2 + 1, k * 2 + 1), (1, 1), padding=(k, k))
1019
+ mask = F.interpolate(mask, size=(x_t.shape[2:]))
1020
+ mask = mask / mask.max(2, keepdims=True)[0].max(3, keepdims=True)[0]
1021
+ mask = mask.gt(self.threshold)
1022
+ mask = (mask[:1] + mask[1:]).float()
1023
+ x_t = x_t[:1] + mask * (x_t - x_t[:1])
1024
+ return x_t
1025
+
1026
+ def __init__(
1027
+ self,
1028
+ prompts: List[str],
1029
+ words: [List[List[str]]],
1030
+ tokenizer,
1031
+ device,
1032
+ threshold=0.3,
1033
+ max_num_words=77,
1034
+ ):
1035
+ self.max_num_words = 77
1036
+
1037
+ alpha_layers = torch.zeros(len(prompts), 1, 1, 1, 1, self.max_num_words)
1038
+ for i, (prompt, words_) in enumerate(zip(prompts, words)):
1039
+ if isinstance(words_, str):
1040
+ words_ = [words_]
1041
+ for word in words_:
1042
+ ind = get_word_inds(prompt, word, tokenizer)
1043
+ alpha_layers[i, :, :, :, :, ind] = 1
1044
+ self.alpha_layers = alpha_layers.to(device)
1045
+ self.threshold = threshold
1046
+
1047
+
1048
+ class AttentionControlEdit(AttentionStore, abc.ABC):
1049
+ def step_callback(self, x_t):
1050
+ if self.local_blend is not None:
1051
+ x_t = self.local_blend(x_t, self.attention_store)
1052
+ return x_t
1053
+
1054
+ def replace_self_attention(self, attn_base, att_replace):
1055
+ if att_replace.shape[2] <= 16**2:
1056
+ return attn_base.unsqueeze(0).expand(att_replace.shape[0], *attn_base.shape)
1057
+ else:
1058
+ return att_replace
1059
+
1060
+ @abc.abstractmethod
1061
+ def replace_cross_attention(self, attn_base, att_replace):
1062
+ raise NotImplementedError
1063
+
1064
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
1065
+ super(AttentionControlEdit, self).forward(attn, is_cross, place_in_unet)
1066
+ # FIXME not replace correctly
1067
+ if is_cross or (self.num_self_replace[0] <= self.cur_step < self.num_self_replace[1]):
1068
+ h = attn.shape[0] // (self.batch_size)
1069
+ attn = attn.reshape(self.batch_size, h, *attn.shape[1:])
1070
+ attn_base, attn_repalce = attn[0], attn[1:]
1071
+ if is_cross:
1072
+ alpha_words = self.cross_replace_alpha[self.cur_step]
1073
+ attn_repalce_new = (
1074
+ self.replace_cross_attention(attn_base, attn_repalce) * alpha_words
1075
+ + (1 - alpha_words) * attn_repalce
1076
+ )
1077
+ attn[1:] = attn_repalce_new
1078
+ else:
1079
+ attn[1:] = self.replace_self_attention(attn_base, attn_repalce)
1080
+ attn = attn.reshape(self.batch_size * h, *attn.shape[2:])
1081
+ return attn
1082
+
1083
+ def __init__(
1084
+ self,
1085
+ prompts,
1086
+ num_steps: int,
1087
+ cross_replace_steps: Union[float, Tuple[float, float], Dict[str, Tuple[float, float]]],
1088
+ self_replace_steps: Union[float, Tuple[float, float]],
1089
+ local_blend: Optional[LocalBlend],
1090
+ tokenizer,
1091
+ device,
1092
+ ):
1093
+ super(AttentionControlEdit, self).__init__()
1094
+ # add tokenizer and device here
1095
+
1096
+ self.tokenizer = tokenizer
1097
+ self.device = device
1098
+
1099
+ self.batch_size = len(prompts)
1100
+ self.cross_replace_alpha = get_time_words_attention_alpha(
1101
+ prompts, num_steps, cross_replace_steps, self.tokenizer
1102
+ ).to(self.device)
1103
+ if isinstance(self_replace_steps, float):
1104
+ self_replace_steps = 0, self_replace_steps
1105
+ self.num_self_replace = int(num_steps * self_replace_steps[0]), int(num_steps * self_replace_steps[1])
1106
+ self.local_blend = local_blend # 在外面定义后传进来
1107
+
1108
+
1109
+ class AttentionReplace(AttentionControlEdit):
1110
+ def replace_cross_attention(self, attn_base, att_replace):
1111
+ return torch.einsum("hpw,bwn->bhpn", attn_base, self.mapper)
1112
+
1113
+ def __init__(
1114
+ self,
1115
+ prompts,
1116
+ num_steps: int,
1117
+ cross_replace_steps: float,
1118
+ self_replace_steps: float,
1119
+ local_blend: Optional[LocalBlend] = None,
1120
+ tokenizer=None,
1121
+ device=None,
1122
+ ):
1123
+ super(AttentionReplace, self).__init__(
1124
+ prompts,
1125
+ num_steps,
1126
+ cross_replace_steps,
1127
+ self_replace_steps,
1128
+ local_blend,
1129
+ tokenizer,
1130
+ device,
1131
+ )
1132
+ self.mapper = get_replacement_mapper(prompts, self.tokenizer).to(self.device)
1133
+
1134
+
1135
+ class AttentionRefine(AttentionControlEdit):
1136
+ def replace_cross_attention(self, attn_base, att_replace):
1137
+ attn_base_replace = attn_base[:, :, self.mapper].permute(2, 0, 1, 3)
1138
+ attn_replace = attn_base_replace * self.alphas + att_replace * (1 - self.alphas)
1139
+ return attn_replace
1140
+
1141
+ def __init__(
1142
+ self,
1143
+ prompts,
1144
+ num_steps: int,
1145
+ cross_replace_steps: float,
1146
+ self_replace_steps: float,
1147
+ local_blend: Optional[LocalBlend] = None,
1148
+ tokenizer=None,
1149
+ device=None,
1150
+ ):
1151
+ super(AttentionRefine, self).__init__(
1152
+ prompts,
1153
+ num_steps,
1154
+ cross_replace_steps,
1155
+ self_replace_steps,
1156
+ local_blend,
1157
+ tokenizer,
1158
+ device,
1159
+ )
1160
+ self.mapper, alphas = get_refinement_mapper(prompts, self.tokenizer)
1161
+ self.mapper, alphas = self.mapper.to(self.device), alphas.to(self.device)
1162
+ self.alphas = alphas.reshape(alphas.shape[0], 1, 1, alphas.shape[1])
1163
+
1164
+
1165
+ class AttentionReweight(AttentionControlEdit):
1166
+ def replace_cross_attention(self, attn_base, att_replace):
1167
+ if self.prev_controller is not None:
1168
+ attn_base = self.prev_controller.replace_cross_attention(attn_base, att_replace)
1169
+ attn_replace = attn_base[None, :, :, :] * self.equalizer[:, None, None, :]
1170
+ return attn_replace
1171
+
1172
+ def __init__(
1173
+ self,
1174
+ prompts,
1175
+ num_steps: int,
1176
+ cross_replace_steps: float,
1177
+ self_replace_steps: float,
1178
+ equalizer,
1179
+ local_blend: Optional[LocalBlend] = None,
1180
+ controller: Optional[AttentionControlEdit] = None,
1181
+ tokenizer=None,
1182
+ device=None,
1183
+ ):
1184
+ super(AttentionReweight, self).__init__(
1185
+ prompts,
1186
+ num_steps,
1187
+ cross_replace_steps,
1188
+ self_replace_steps,
1189
+ local_blend,
1190
+ tokenizer,
1191
+ device,
1192
+ )
1193
+ self.equalizer = equalizer.to(self.device)
1194
+ self.prev_controller = controller
1195
+
1196
+
1197
+ ### util functions for all Edits
1198
+ def update_alpha_time_word(
1199
+ alpha,
1200
+ bounds: Union[float, Tuple[float, float]],
1201
+ prompt_ind: int,
1202
+ word_inds: Optional[torch.Tensor] = None,
1203
+ ):
1204
+ if isinstance(bounds, float):
1205
+ bounds = 0, bounds
1206
+ start, end = int(bounds[0] * alpha.shape[0]), int(bounds[1] * alpha.shape[0])
1207
+ if word_inds is None:
1208
+ word_inds = torch.arange(alpha.shape[2])
1209
+ alpha[:start, prompt_ind, word_inds] = 0
1210
+ alpha[start:end, prompt_ind, word_inds] = 1
1211
+ alpha[end:, prompt_ind, word_inds] = 0
1212
+ return alpha
1213
+
1214
+
1215
+ def get_time_words_attention_alpha(
1216
+ prompts,
1217
+ num_steps,
1218
+ cross_replace_steps: Union[float, Dict[str, Tuple[float, float]]],
1219
+ tokenizer,
1220
+ max_num_words=77,
1221
+ ):
1222
+ if not isinstance(cross_replace_steps, dict):
1223
+ cross_replace_steps = {"default_": cross_replace_steps}
1224
+ if "default_" not in cross_replace_steps:
1225
+ cross_replace_steps["default_"] = (0.0, 1.0)
1226
+ alpha_time_words = torch.zeros(num_steps + 1, len(prompts) - 1, max_num_words)
1227
+ for i in range(len(prompts) - 1):
1228
+ alpha_time_words = update_alpha_time_word(alpha_time_words, cross_replace_steps["default_"], i)
1229
+ for key, item in cross_replace_steps.items():
1230
+ if key != "default_":
1231
+ inds = [get_word_inds(prompts[i], key, tokenizer) for i in range(1, len(prompts))]
1232
+ for i, ind in enumerate(inds):
1233
+ if len(ind) > 0:
1234
+ alpha_time_words = update_alpha_time_word(alpha_time_words, item, i, ind)
1235
+ alpha_time_words = alpha_time_words.reshape(num_steps + 1, len(prompts) - 1, 1, 1, max_num_words)
1236
+ return alpha_time_words
1237
+
1238
+
1239
+ ### util functions for LocalBlend and ReplacementEdit
1240
+ def get_word_inds(text: str, word_place: int, tokenizer):
1241
+ split_text = text.split(" ")
1242
+ if isinstance(word_place, str):
1243
+ word_place = [i for i, word in enumerate(split_text) if word_place == word]
1244
+ elif isinstance(word_place, int):
1245
+ word_place = [word_place]
1246
+ out = []
1247
+ if len(word_place) > 0:
1248
+ words_encode = [tokenizer.decode([item]).strip("#") for item in tokenizer.encode(text)][1:-1]
1249
+ cur_len, ptr = 0, 0
1250
+
1251
+ for i in range(len(words_encode)):
1252
+ cur_len += len(words_encode[i])
1253
+ if ptr in word_place:
1254
+ out.append(i + 1)
1255
+ if cur_len >= len(split_text[ptr]):
1256
+ ptr += 1
1257
+ cur_len = 0
1258
+ return np.array(out)
1259
+
1260
+
1261
+ ### util functions for ReplacementEdit
1262
+ def get_replacement_mapper_(x: str, y: str, tokenizer, max_len=77):
1263
+ words_x = x.split(" ")
1264
+ words_y = y.split(" ")
1265
+ if len(words_x) != len(words_y):
1266
+ raise ValueError(
1267
+ f"attention replacement edit can only be applied on prompts with the same length"
1268
+ f" but prompt A has {len(words_x)} words and prompt B has {len(words_y)} words."
1269
+ )
1270
+ inds_replace = [i for i in range(len(words_y)) if words_y[i] != words_x[i]]
1271
+ inds_source = [get_word_inds(x, i, tokenizer) for i in inds_replace]
1272
+ inds_target = [get_word_inds(y, i, tokenizer) for i in inds_replace]
1273
+ mapper = np.zeros((max_len, max_len))
1274
+ i = j = 0
1275
+ cur_inds = 0
1276
+ while i < max_len and j < max_len:
1277
+ if cur_inds < len(inds_source) and inds_source[cur_inds][0] == i:
1278
+ inds_source_, inds_target_ = inds_source[cur_inds], inds_target[cur_inds]
1279
+ if len(inds_source_) == len(inds_target_):
1280
+ mapper[inds_source_, inds_target_] = 1
1281
+ else:
1282
+ ratio = 1 / len(inds_target_)
1283
+ for i_t in inds_target_:
1284
+ mapper[inds_source_, i_t] = ratio
1285
+ cur_inds += 1
1286
+ i += len(inds_source_)
1287
+ j += len(inds_target_)
1288
+ elif cur_inds < len(inds_source):
1289
+ mapper[i, j] = 1
1290
+ i += 1
1291
+ j += 1
1292
+ else:
1293
+ mapper[j, j] = 1
1294
+ i += 1
1295
+ j += 1
1296
+
1297
+ return torch.from_numpy(mapper).float()
1298
+
1299
+
1300
+ def get_replacement_mapper(prompts, tokenizer, max_len=77):
1301
+ x_seq = prompts[0]
1302
+ mappers = []
1303
+ for i in range(1, len(prompts)):
1304
+ mapper = get_replacement_mapper_(x_seq, prompts[i], tokenizer, max_len)
1305
+ mappers.append(mapper)
1306
+ return torch.stack(mappers)
1307
+
1308
+
1309
+ ### util functions for ReweightEdit
1310
+ def get_equalizer(
1311
+ text: str,
1312
+ word_select: Union[int, Tuple[int, ...]],
1313
+ values: Union[List[float], Tuple[float, ...]],
1314
+ tokenizer,
1315
+ ):
1316
+ if isinstance(word_select, (int, str)):
1317
+ word_select = (word_select,)
1318
+ equalizer = torch.ones(len(values), 77)
1319
+ values = torch.tensor(values, dtype=torch.float32)
1320
+ for word in word_select:
1321
+ inds = get_word_inds(text, word, tokenizer)
1322
+ equalizer[:, inds] = values
1323
+ return equalizer
1324
+
1325
+
1326
+ ### util functions for RefinementEdit
1327
+ class ScoreParams:
1328
+ def __init__(self, gap, match, mismatch):
1329
+ self.gap = gap
1330
+ self.match = match
1331
+ self.mismatch = mismatch
1332
+
1333
+ def mis_match_char(self, x, y):
1334
+ if x != y:
1335
+ return self.mismatch
1336
+ else:
1337
+ return self.match
1338
+
1339
+
1340
+ def get_matrix(size_x, size_y, gap):
1341
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
1342
+ matrix[0, 1:] = (np.arange(size_y) + 1) * gap
1343
+ matrix[1:, 0] = (np.arange(size_x) + 1) * gap
1344
+ return matrix
1345
+
1346
+
1347
+ def get_traceback_matrix(size_x, size_y):
1348
+ matrix = np.zeros((size_x + 1, size_y + 1), dtype=np.int32)
1349
+ matrix[0, 1:] = 1
1350
+ matrix[1:, 0] = 2
1351
+ matrix[0, 0] = 4
1352
+ return matrix
1353
+
1354
+
1355
+ def global_align(x, y, score):
1356
+ matrix = get_matrix(len(x), len(y), score.gap)
1357
+ trace_back = get_traceback_matrix(len(x), len(y))
1358
+ for i in range(1, len(x) + 1):
1359
+ for j in range(1, len(y) + 1):
1360
+ left = matrix[i, j - 1] + score.gap
1361
+ up = matrix[i - 1, j] + score.gap
1362
+ diag = matrix[i - 1, j - 1] + score.mis_match_char(x[i - 1], y[j - 1])
1363
+ matrix[i, j] = max(left, up, diag)
1364
+ if matrix[i, j] == left:
1365
+ trace_back[i, j] = 1
1366
+ elif matrix[i, j] == up:
1367
+ trace_back[i, j] = 2
1368
+ else:
1369
+ trace_back[i, j] = 3
1370
+ return matrix, trace_back
1371
+
1372
+
1373
+ def get_aligned_sequences(x, y, trace_back):
1374
+ x_seq = []
1375
+ y_seq = []
1376
+ i = len(x)
1377
+ j = len(y)
1378
+ mapper_y_to_x = []
1379
+ while i > 0 or j > 0:
1380
+ if trace_back[i, j] == 3:
1381
+ x_seq.append(x[i - 1])
1382
+ y_seq.append(y[j - 1])
1383
+ i = i - 1
1384
+ j = j - 1
1385
+ mapper_y_to_x.append((j, i))
1386
+ elif trace_back[i][j] == 1:
1387
+ x_seq.append("-")
1388
+ y_seq.append(y[j - 1])
1389
+ j = j - 1
1390
+ mapper_y_to_x.append((j, -1))
1391
+ elif trace_back[i][j] == 2:
1392
+ x_seq.append(x[i - 1])
1393
+ y_seq.append("-")
1394
+ i = i - 1
1395
+ elif trace_back[i][j] == 4:
1396
+ break
1397
+ mapper_y_to_x.reverse()
1398
+ return x_seq, y_seq, torch.tensor(mapper_y_to_x, dtype=torch.int64)
1399
+
1400
+
1401
+ def get_mapper(x: str, y: str, tokenizer, max_len=77):
1402
+ x_seq = tokenizer.encode(x)
1403
+ y_seq = tokenizer.encode(y)
1404
+ score = ScoreParams(0, 1, -1)
1405
+ matrix, trace_back = global_align(x_seq, y_seq, score)
1406
+ mapper_base = get_aligned_sequences(x_seq, y_seq, trace_back)[-1]
1407
+ alphas = torch.ones(max_len)
1408
+ alphas[: mapper_base.shape[0]] = mapper_base[:, 1].ne(-1).float()
1409
+ mapper = torch.zeros(max_len, dtype=torch.int64)
1410
+ mapper[: mapper_base.shape[0]] = mapper_base[:, 1]
1411
+ mapper[mapper_base.shape[0] :] = len(y_seq) + torch.arange(max_len - len(y_seq))
1412
+ return mapper, alphas
1413
+
1414
+
1415
+ def get_refinement_mapper(prompts, tokenizer, max_len=77):
1416
+ x_seq = prompts[0]
1417
+ mappers, alphas = [], []
1418
+ for i in range(1, len(prompts)):
1419
+ mapper, alpha = get_mapper(x_seq, prompts[i], tokenizer, max_len)
1420
+ mappers.append(mapper)
1421
+ alphas.append(alpha)
1422
+ return torch.stack(mappers), torch.stack(alphas)