Datasets:

ArXiv:
Diffusers Bot commited on
Commit
4fe73eb
·
verified ·
1 Parent(s): 91f4894

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.30.0/README.md +0 -0
  2. v0.30.0/README_community_scripts.md +232 -0
  3. v0.30.0/bit_diffusion.py +264 -0
  4. v0.30.0/checkpoint_merger.py +284 -0
  5. v0.30.0/clip_guided_images_mixing_stable_diffusion.py +445 -0
  6. v0.30.0/clip_guided_stable_diffusion.py +337 -0
  7. v0.30.0/clip_guided_stable_diffusion_img2img.py +490 -0
  8. v0.30.0/composable_stable_diffusion.py +532 -0
  9. v0.30.0/ddim_noise_comparative_analysis.py +190 -0
  10. v0.30.0/dps_pipeline.py +466 -0
  11. v0.30.0/edict_pipeline.py +264 -0
  12. v0.30.0/fresco_v2v.py +0 -0
  13. v0.30.0/gluegen.py +816 -0
  14. v0.30.0/hd_painter.py +994 -0
  15. v0.30.0/iadb.py +149 -0
  16. v0.30.0/imagic_stable_diffusion.py +470 -0
  17. v0.30.0/img2img_inpainting.py +437 -0
  18. v0.30.0/instaflow_one_step.py +689 -0
  19. v0.30.0/interpolate_stable_diffusion.py +498 -0
  20. v0.30.0/ip_adapter_face_id.py +1128 -0
  21. v0.30.0/kohya_hires_fix.py +468 -0
  22. v0.30.0/latent_consistency_img2img.py +821 -0
  23. v0.30.0/latent_consistency_interpolate.py +999 -0
  24. v0.30.0/latent_consistency_txt2img.py +729 -0
  25. v0.30.0/llm_grounded_diffusion.py +1563 -0
  26. v0.30.0/lpw_stable_diffusion.py +1427 -0
  27. v0.30.0/lpw_stable_diffusion_onnx.py +1148 -0
  28. v0.30.0/lpw_stable_diffusion_xl.py +0 -0
  29. v0.30.0/magic_mix.py +152 -0
  30. v0.30.0/marigold_depth_estimation.py +673 -0
  31. v0.30.0/masked_stable_diffusion_img2img.py +262 -0
  32. v0.30.0/mixture_canvas.py +501 -0
  33. v0.30.0/mixture_tiling.py +405 -0
  34. v0.30.0/multilingual_stable_diffusion.py +410 -0
  35. v0.30.0/one_step_unet.py +24 -0
  36. v0.30.0/pipeline_animatediff_controlnet.py +1129 -0
  37. v0.30.0/pipeline_animatediff_img2video.py +984 -0
  38. v0.30.0/pipeline_animatediff_ipex.py +1002 -0
  39. v0.30.0/pipeline_demofusion_sdxl.py +1386 -0
  40. v0.30.0/pipeline_fabric.py +751 -0
  41. v0.30.0/pipeline_null_text_inversion.py +260 -0
  42. v0.30.0/pipeline_prompt2prompt.py +1422 -0
  43. v0.30.0/pipeline_sdxl_style_aligned.py +1912 -0
  44. v0.30.0/pipeline_stable_diffusion_3_differential_img2img.py +981 -0
  45. v0.30.0/pipeline_stable_diffusion_boxdiff.py +1705 -0
  46. v0.30.0/pipeline_stable_diffusion_pag.py +1476 -0
  47. v0.30.0/pipeline_stable_diffusion_upscale_ldm3d.py +772 -0
  48. v0.30.0/pipeline_stable_diffusion_xl_controlnet_adapter.py +1401 -0
  49. v0.30.0/pipeline_stable_diffusion_xl_controlnet_adapter_inpaint.py +1840 -0
  50. v0.30.0/pipeline_stable_diffusion_xl_differential_img2img.py +1466 -0
v0.30.0/README.md ADDED
The diff for this file is too large to render. See raw diff
 
v0.30.0/README_community_scripts.md ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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) | | [Álvaro Somoza](https://github.com/asomoza)|
10
+ | asymmetric tiling |configure seamless image tiling independently for the X and Y axes | [Asymmetric Tiling](#asymmetric-tiling ) | | [alexisrolland](https://github.com/alexisrolland)|
11
+
12
+
13
+ ## Example usages
14
+
15
+ ### IP Adapter Negative Noise
16
+
17
+ 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.
18
+
19
+ [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)
20
+
21
+ IP-Adapter without negative noise
22
+ |source|result|
23
+ |---|---|
24
+ |![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)|
25
+
26
+ IP-Adapter with negative noise
27
+ |source|result|
28
+ |---|---|
29
+ |![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)|
30
+
31
+ ```python
32
+ import torch
33
+
34
+ from diffusers import AutoencoderKL, DPMSolverMultistepScheduler, StableDiffusionXLPipeline
35
+ from diffusers.models import ImageProjection
36
+ from diffusers.utils import load_image
37
+
38
+
39
+ def encode_image(
40
+ image_encoder,
41
+ feature_extractor,
42
+ image,
43
+ device,
44
+ num_images_per_prompt,
45
+ output_hidden_states=None,
46
+ negative_image=None,
47
+ ):
48
+ dtype = next(image_encoder.parameters()).dtype
49
+
50
+ if not isinstance(image, torch.Tensor):
51
+ image = feature_extractor(image, return_tensors="pt").pixel_values
52
+
53
+ image = image.to(device=device, dtype=dtype)
54
+ if output_hidden_states:
55
+ image_enc_hidden_states = image_encoder(image, output_hidden_states=True).hidden_states[-2]
56
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
57
+
58
+ if negative_image is None:
59
+ uncond_image_enc_hidden_states = image_encoder(
60
+ torch.zeros_like(image), output_hidden_states=True
61
+ ).hidden_states[-2]
62
+ else:
63
+ if not isinstance(negative_image, torch.Tensor):
64
+ negative_image = feature_extractor(negative_image, return_tensors="pt").pixel_values
65
+ negative_image = negative_image.to(device=device, dtype=dtype)
66
+ uncond_image_enc_hidden_states = image_encoder(negative_image, output_hidden_states=True).hidden_states[-2]
67
+
68
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
69
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
70
+ else:
71
+ image_embeds = image_encoder(image).image_embeds
72
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
73
+ uncond_image_embeds = torch.zeros_like(image_embeds)
74
+
75
+ return image_embeds, uncond_image_embeds
76
+
77
+
78
+ @torch.no_grad()
79
+ def prepare_ip_adapter_image_embeds(
80
+ unet,
81
+ image_encoder,
82
+ feature_extractor,
83
+ ip_adapter_image,
84
+ do_classifier_free_guidance,
85
+ device,
86
+ num_images_per_prompt,
87
+ ip_adapter_negative_image=None,
88
+ ):
89
+ if not isinstance(ip_adapter_image, list):
90
+ ip_adapter_image = [ip_adapter_image]
91
+
92
+ if len(ip_adapter_image) != len(unet.encoder_hid_proj.image_projection_layers):
93
+ raise ValueError(
94
+ 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."
95
+ )
96
+
97
+ image_embeds = []
98
+ for single_ip_adapter_image, image_proj_layer in zip(
99
+ ip_adapter_image, unet.encoder_hid_proj.image_projection_layers
100
+ ):
101
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
102
+ single_image_embeds, single_negative_image_embeds = encode_image(
103
+ image_encoder,
104
+ feature_extractor,
105
+ single_ip_adapter_image,
106
+ device,
107
+ 1,
108
+ output_hidden_state,
109
+ negative_image=ip_adapter_negative_image,
110
+ )
111
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
112
+ single_negative_image_embeds = torch.stack([single_negative_image_embeds] * num_images_per_prompt, dim=0)
113
+
114
+ if do_classifier_free_guidance:
115
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
116
+ single_image_embeds = single_image_embeds.to(device)
117
+
118
+ image_embeds.append(single_image_embeds)
119
+
120
+ return image_embeds
121
+
122
+
123
+ vae = AutoencoderKL.from_pretrained(
124
+ "madebyollin/sdxl-vae-fp16-fix",
125
+ torch_dtype=torch.float16,
126
+ ).to("cuda")
127
+
128
+ pipeline = StableDiffusionXLPipeline.from_pretrained(
129
+ "RunDiffusion/Juggernaut-XL-v9",
130
+ torch_dtype=torch.float16,
131
+ vae=vae,
132
+ variant="fp16",
133
+ ).to("cuda")
134
+
135
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
136
+ pipeline.scheduler.config.use_karras_sigmas = True
137
+
138
+ pipeline.load_ip_adapter(
139
+ "h94/IP-Adapter",
140
+ subfolder="sdxl_models",
141
+ weight_name="ip-adapter-plus_sdxl_vit-h.safetensors",
142
+ image_encoder_folder="models/image_encoder",
143
+ )
144
+ pipeline.set_ip_adapter_scale(0.7)
145
+
146
+ ip_image = load_image("source.png")
147
+ negative_ip_image = load_image("noise.png")
148
+
149
+ image_embeds = prepare_ip_adapter_image_embeds(
150
+ unet=pipeline.unet,
151
+ image_encoder=pipeline.image_encoder,
152
+ feature_extractor=pipeline.feature_extractor,
153
+ ip_adapter_image=[[ip_image]],
154
+ do_classifier_free_guidance=True,
155
+ device="cuda",
156
+ num_images_per_prompt=1,
157
+ ip_adapter_negative_image=negative_ip_image,
158
+ )
159
+
160
+
161
+ prompt = "cinematic photo of a cyborg in the city, 4k, high quality, intricate, highly detailed"
162
+ negative_prompt = "blurry, smooth, plastic"
163
+
164
+ image = pipeline(
165
+ prompt=prompt,
166
+ negative_prompt=negative_prompt,
167
+ ip_adapter_image_embeds=image_embeds,
168
+ guidance_scale=6.0,
169
+ num_inference_steps=25,
170
+ generator=torch.Generator(device="cpu").manual_seed(1556265306),
171
+ ).images[0]
172
+
173
+ image.save("result.png")
174
+ ```
175
+
176
+ ### Asymmetric Tiling
177
+ 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)
178
+
179
+
180
+ |Generated|Tiled|
181
+ |---|---|
182
+ |![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)|
183
+
184
+
185
+ ```py
186
+ import torch
187
+ from typing import Optional
188
+ from diffusers import StableDiffusionPipeline
189
+ from diffusers.models.lora import LoRACompatibleConv
190
+
191
+ def seamless_tiling(pipeline, x_axis, y_axis):
192
+ def asymmetric_conv2d_convforward(self, input: torch.Tensor, weight: torch.Tensor, bias: Optional[torch.Tensor] = None):
193
+ self.paddingX = (self._reversed_padding_repeated_twice[0], self._reversed_padding_repeated_twice[1], 0, 0)
194
+ self.paddingY = (0, 0, self._reversed_padding_repeated_twice[2], self._reversed_padding_repeated_twice[3])
195
+ working = torch.nn.functional.pad(input, self.paddingX, mode=x_mode)
196
+ working = torch.nn.functional.pad(working, self.paddingY, mode=y_mode)
197
+ return torch.nn.functional.conv2d(working, weight, bias, self.stride, torch.nn.modules.utils._pair(0), self.dilation, self.groups)
198
+ x_mode = 'circular' if x_axis else 'constant'
199
+ y_mode = 'circular' if y_axis else 'constant'
200
+ targets = [pipeline.vae, pipeline.text_encoder, pipeline.unet]
201
+ convolution_layers = []
202
+ for target in targets:
203
+ for module in target.modules():
204
+ if isinstance(module, torch.nn.Conv2d):
205
+ convolution_layers.append(module)
206
+ for layer in convolution_layers:
207
+ if isinstance(layer, LoRACompatibleConv) and layer.lora_layer is None:
208
+ layer.lora_layer = lambda * x: 0
209
+ layer._conv_forward = asymmetric_conv2d_convforward.__get__(layer, torch.nn.Conv2d)
210
+ return pipeline
211
+
212
+ pipeline = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16, use_safetensors=True)
213
+ pipeline.enable_model_cpu_offload()
214
+ prompt = ["texture of a red brick wall"]
215
+ seed = 123456
216
+ generator = torch.Generator(device='cuda').manual_seed(seed)
217
+
218
+ pipeline = seamless_tiling(pipeline=pipeline, x_axis=True, y_axis=True)
219
+ image = pipeline(
220
+ prompt=prompt,
221
+ width=512,
222
+ height=512,
223
+ num_inference_steps=20,
224
+ guidance_scale=7,
225
+ num_images_per_prompt=1,
226
+ generator=generator
227
+ ).images[0]
228
+ seamless_tiling(pipeline=pipeline, x_axis=False, y_axis=False)
229
+
230
+ torch.cuda.empty_cache()
231
+ image.save('image.png')
232
+ ```
v0.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.0/fresco_v2v.py ADDED
The diff for this file is too large to render. See raw diff
 
v0.30.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.30.0/hd_painter.py ADDED
@@ -0,0 +1,994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Arguments:
902
+ channels (int, sequence): Number of channels of the input tensors. Output will
903
+ have this number of channels as well.
904
+ kernel_size (int, sequence): Size of the gaussian kernel.
905
+ sigma (float, sequence): Standard deviation of the gaussian kernel.
906
+ dim (int, optional): The number of dimensions of the data.
907
+ Default value is 2 (spatial).
908
+ """
909
+
910
+ def __init__(self, channels, kernel_size, sigma, dim=2):
911
+ super(GaussianSmoothing, self).__init__()
912
+ if isinstance(kernel_size, numbers.Number):
913
+ kernel_size = [kernel_size] * dim
914
+ if isinstance(sigma, numbers.Number):
915
+ sigma = [sigma] * dim
916
+
917
+ # The gaussian kernel is the product of the
918
+ # gaussian function of each dimension.
919
+ kernel = 1
920
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
921
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
922
+ mean = (size - 1) / 2
923
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
924
+
925
+ # Make sure sum of values in gaussian kernel equals 1.
926
+ kernel = kernel / torch.sum(kernel)
927
+
928
+ # Reshape to depthwise convolutional weight
929
+ kernel = kernel.view(1, 1, *kernel.size())
930
+ kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
931
+
932
+ self.register_buffer("weight", kernel)
933
+ self.groups = channels
934
+
935
+ if dim == 1:
936
+ self.conv = F.conv1d
937
+ elif dim == 2:
938
+ self.conv = F.conv2d
939
+ elif dim == 3:
940
+ self.conv = F.conv3d
941
+ else:
942
+ raise RuntimeError("Only 1, 2 and 3 dimensions are supported. Received {}.".format(dim))
943
+
944
+ def forward(self, input):
945
+ """
946
+ Apply gaussian filter to input.
947
+ Arguments:
948
+ input (torch.Tensor): Input to apply gaussian filter on.
949
+ Returns:
950
+ filtered (torch.Tensor): Filtered output.
951
+ """
952
+ return self.conv(input, weight=self.weight.to(input.dtype), groups=self.groups, padding="same")
953
+
954
+
955
+ def get_attention_scores(
956
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None
957
+ ) -> torch.Tensor:
958
+ r"""
959
+ Compute the attention scores.
960
+
961
+ Args:
962
+ query (`torch.Tensor`): The query tensor.
963
+ key (`torch.Tensor`): The key tensor.
964
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
965
+
966
+ Returns:
967
+ `torch.Tensor`: The attention probabilities/scores.
968
+ """
969
+ if self.upcast_attention:
970
+ query = query.float()
971
+ key = key.float()
972
+
973
+ if attention_mask is None:
974
+ baddbmm_input = torch.empty(
975
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
976
+ )
977
+ beta = 0
978
+ else:
979
+ baddbmm_input = attention_mask
980
+ beta = 1
981
+
982
+ attention_scores = torch.baddbmm(
983
+ baddbmm_input,
984
+ query,
985
+ key.transpose(-1, -2),
986
+ beta=beta,
987
+ alpha=self.scale,
988
+ )
989
+ del baddbmm_input
990
+
991
+ if self.upcast_softmax:
992
+ attention_scores = attention_scores.float()
993
+
994
+ return attention_scores
v0.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.0/lpw_stable_diffusion_xl.py ADDED
The diff for this file is too large to render. See raw diff
 
v0.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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.30.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)
v0.30.0/pipeline_sdxl_style_aligned.py ADDED
@@ -0,0 +1,1912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Based on [Style Aligned Image Generation via Shared Attention](https://arxiv.org/abs/2312.02133).
16
+ # Authors: Amir Hertz, Andrey Voynov, Shlomi Fruchter, Daniel Cohen-Or
17
+ # Project Page: https://style-aligned-gen.github.io/
18
+ # Code: https://github.com/google/style-aligned
19
+ #
20
+ # Adapted to Diffusers by [Aryan V S](https://github.com/a-r-r-o-w/).
21
+
22
+ import inspect
23
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ import torch.nn.functional as F
28
+ from PIL import Image
29
+ from transformers import (
30
+ CLIPImageProcessor,
31
+ CLIPTextModel,
32
+ CLIPTextModelWithProjection,
33
+ CLIPTokenizer,
34
+ CLIPVisionModelWithProjection,
35
+ )
36
+
37
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
38
+ from diffusers.loaders import (
39
+ FromSingleFileMixin,
40
+ IPAdapterMixin,
41
+ StableDiffusionXLLoraLoaderMixin,
42
+ TextualInversionLoaderMixin,
43
+ )
44
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
45
+ from diffusers.models.attention_processor import (
46
+ Attention,
47
+ AttnProcessor2_0,
48
+ FusedAttnProcessor2_0,
49
+ XFormersAttnProcessor,
50
+ )
51
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
52
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
53
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
54
+ from diffusers.schedulers import KarrasDiffusionSchedulers
55
+ from diffusers.utils import (
56
+ USE_PEFT_BACKEND,
57
+ deprecate,
58
+ is_invisible_watermark_available,
59
+ is_torch_xla_available,
60
+ logging,
61
+ replace_example_docstring,
62
+ scale_lora_layers,
63
+ unscale_lora_layers,
64
+ )
65
+ from diffusers.utils.torch_utils import randn_tensor
66
+
67
+
68
+ if is_invisible_watermark_available():
69
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
70
+
71
+ if is_torch_xla_available():
72
+ import torch_xla.core.xla_model as xm
73
+
74
+ XLA_AVAILABLE = True
75
+ else:
76
+ XLA_AVAILABLE = False
77
+
78
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
79
+
80
+ EXAMPLE_DOC_STRING = """
81
+ Examples:
82
+ ```py
83
+ >>> from typing import List
84
+
85
+ >>> import torch
86
+ >>> from diffusers.pipelines.pipeline_utils import DiffusionPipeline
87
+ >>> from PIL import Image
88
+
89
+ >>> model_id = "a-r-r-o-w/dreamshaper-xl-turbo"
90
+ >>> pipe = DiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, variant="fp16", custom_pipeline="pipeline_sdxl_style_aligned")
91
+ >>> pipe = pipe.to("cuda")
92
+
93
+ # Enable memory saving techniques
94
+ >>> pipe.enable_vae_slicing()
95
+ >>> pipe.enable_vae_tiling()
96
+
97
+ >>> prompt = [
98
+ ... "a toy train. macro photo. 3d game asset",
99
+ ... "a toy airplane. macro photo. 3d game asset",
100
+ ... "a toy bicycle. macro photo. 3d game asset",
101
+ ... "a toy car. macro photo. 3d game asset",
102
+ ... ]
103
+ >>> negative_prompt = "low quality, worst quality, "
104
+
105
+ >>> # Enable StyleAligned
106
+ >>> pipe.enable_style_aligned(
107
+ ... share_group_norm=False,
108
+ ... share_layer_norm=False,
109
+ ... share_attention=True,
110
+ ... adain_queries=True,
111
+ ... adain_keys=True,
112
+ ... adain_values=False,
113
+ ... full_attention_share=False,
114
+ ... shared_score_scale=1.0,
115
+ ... shared_score_shift=0.0,
116
+ ... only_self_level=0.0,
117
+ >>> )
118
+
119
+ >>> # Run inference
120
+ >>> images = pipe(
121
+ ... prompt=prompt,
122
+ ... negative_prompt=negative_prompt,
123
+ ... guidance_scale=2,
124
+ ... height=1024,
125
+ ... width=1024,
126
+ ... num_inference_steps=10,
127
+ ... generator=torch.Generator().manual_seed(42),
128
+ >>> ).images
129
+
130
+ >>> # Disable StyleAligned if you do not wish to use it anymore
131
+ >>> pipe.disable_style_aligned()
132
+ ```
133
+ """
134
+
135
+
136
+ def expand_first(feat: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
137
+ b = feat.shape[0]
138
+ feat_style = torch.stack((feat[0], feat[b // 2])).unsqueeze(1)
139
+ if scale == 1:
140
+ feat_style = feat_style.expand(2, b // 2, *feat.shape[1:])
141
+ else:
142
+ feat_style = feat_style.repeat(1, b // 2, 1, 1, 1)
143
+ feat_style = torch.cat([feat_style[:, :1], scale * feat_style[:, 1:]], dim=1)
144
+ return feat_style.reshape(*feat.shape)
145
+
146
+
147
+ def concat_first(feat: torch.Tensor, dim: int = 2, scale: float = 1.0) -> torch.Tensor:
148
+ feat_style = expand_first(feat, scale=scale)
149
+ return torch.cat((feat, feat_style), dim=dim)
150
+
151
+
152
+ def calc_mean_std(feat: torch.Tensor, eps: float = 1e-5) -> Tuple[torch.Tensor, torch.Tensor]:
153
+ feat_std = (feat.var(dim=-2, keepdims=True) + eps).sqrt()
154
+ feat_mean = feat.mean(dim=-2, keepdims=True)
155
+ return feat_mean, feat_std
156
+
157
+
158
+ def adain(feat: torch.Tensor) -> torch.Tensor:
159
+ feat_mean, feat_std = calc_mean_std(feat)
160
+ feat_style_mean = expand_first(feat_mean)
161
+ feat_style_std = expand_first(feat_std)
162
+ feat = (feat - feat_mean) / feat_std
163
+ feat = feat * feat_style_std + feat_style_mean
164
+ return feat
165
+
166
+
167
+ def get_switch_vec(total_num_layers, level):
168
+ if level == 0:
169
+ return torch.zeros(total_num_layers, dtype=torch.bool)
170
+ if level == 1:
171
+ return torch.ones(total_num_layers, dtype=torch.bool)
172
+ to_flip = level > 0.5
173
+ if to_flip:
174
+ level = 1 - level
175
+ num_switch = int(level * total_num_layers)
176
+ vec = torch.arange(total_num_layers)
177
+ vec = vec % (total_num_layers // num_switch)
178
+ vec = vec == 0
179
+ if to_flip:
180
+ vec = ~vec
181
+ return vec
182
+
183
+
184
+ class SharedAttentionProcessor(AttnProcessor2_0):
185
+ def __init__(
186
+ self,
187
+ share_attention: bool = True,
188
+ adain_queries: bool = True,
189
+ adain_keys: bool = True,
190
+ adain_values: bool = False,
191
+ full_attention_share: bool = False,
192
+ shared_score_scale: float = 1.0,
193
+ shared_score_shift: float = 0.0,
194
+ ):
195
+ r"""Shared Attention Processor as proposed in the StyleAligned paper."""
196
+ super().__init__()
197
+ self.share_attention = share_attention
198
+ self.adain_queries = adain_queries
199
+ self.adain_keys = adain_keys
200
+ self.adain_values = adain_values
201
+ self.full_attention_share = full_attention_share
202
+ self.shared_score_scale = shared_score_scale
203
+ self.shared_score_shift = shared_score_shift
204
+
205
+ def shifted_scaled_dot_product_attention(
206
+ self, attn: Attention, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor
207
+ ) -> torch.Tensor:
208
+ logits = torch.einsum("bhqd,bhkd->bhqk", query, key) * attn.scale
209
+ logits[:, :, :, query.shape[2] :] += self.shared_score_shift
210
+ probs = logits.softmax(-1)
211
+ return torch.einsum("bhqk,bhkd->bhqd", probs, value)
212
+
213
+ def shared_call(
214
+ self,
215
+ attn: Attention,
216
+ hidden_states: torch.Tensor,
217
+ encoder_hidden_states: Optional[torch.Tensor] = None,
218
+ attention_mask: Optional[torch.Tensor] = None,
219
+ **kwargs,
220
+ ):
221
+ residual = hidden_states
222
+ input_ndim = hidden_states.ndim
223
+ if input_ndim == 4:
224
+ batch_size, channel, height, width = hidden_states.shape
225
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
226
+ batch_size, sequence_length, _ = (
227
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
228
+ )
229
+
230
+ if attention_mask is not None:
231
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
232
+ # scaled_dot_product_attention expects attention_mask shape to be
233
+ # (batch, heads, source_length, target_length)
234
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
235
+
236
+ if attn.group_norm is not None:
237
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
238
+
239
+ query = attn.to_q(hidden_states)
240
+ key = attn.to_k(hidden_states)
241
+ value = attn.to_v(hidden_states)
242
+ inner_dim = key.shape[-1]
243
+ head_dim = inner_dim // attn.heads
244
+
245
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
246
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
247
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
248
+
249
+ if self.adain_queries:
250
+ query = adain(query)
251
+ if self.adain_keys:
252
+ key = adain(key)
253
+ if self.adain_values:
254
+ value = adain(value)
255
+ if self.share_attention:
256
+ key = concat_first(key, -2, scale=self.shared_score_scale)
257
+ value = concat_first(value, -2)
258
+ if self.shared_score_shift != 0:
259
+ hidden_states = self.shifted_scaled_dot_product_attention(attn, query, key, value)
260
+ else:
261
+ hidden_states = F.scaled_dot_product_attention(
262
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
263
+ )
264
+ else:
265
+ hidden_states = F.scaled_dot_product_attention(
266
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
267
+ )
268
+
269
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
270
+ hidden_states = hidden_states.to(query.dtype)
271
+
272
+ # linear proj
273
+ hidden_states = attn.to_out[0](hidden_states)
274
+ # dropout
275
+ hidden_states = attn.to_out[1](hidden_states)
276
+
277
+ if input_ndim == 4:
278
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
279
+
280
+ if attn.residual_connection:
281
+ hidden_states = hidden_states + residual
282
+
283
+ hidden_states = hidden_states / attn.rescale_output_factor
284
+ return hidden_states
285
+
286
+ def __call__(
287
+ self,
288
+ attn: Attention,
289
+ hidden_states: torch.Tensor,
290
+ encoder_hidden_states: Optional[torch.Tensor] = None,
291
+ attention_mask: Optional[torch.Tensor] = None,
292
+ **kwargs,
293
+ ):
294
+ if self.full_attention_share:
295
+ b, n, d = hidden_states.shape
296
+ k = 2
297
+ hidden_states = hidden_states.view(k, b, n, d).permute(0, 1, 3, 2).contiguous().view(-1, n, d)
298
+ # hidden_states = einops.rearrange(hidden_states, "(k b) n d -> k (b n) d", k=2)
299
+ hidden_states = super().__call__(
300
+ attn,
301
+ hidden_states,
302
+ encoder_hidden_states=encoder_hidden_states,
303
+ attention_mask=attention_mask,
304
+ **kwargs,
305
+ )
306
+ hidden_states = hidden_states.view(k, b, n, d).permute(0, 1, 3, 2).contiguous().view(-1, n, d)
307
+ # hidden_states = einops.rearrange(hidden_states, "k (b n) d -> (k b) n d", n=n)
308
+ else:
309
+ hidden_states = self.shared_call(attn, hidden_states, hidden_states, attention_mask, **kwargs)
310
+
311
+ return hidden_states
312
+
313
+
314
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
315
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
316
+ """
317
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
318
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
319
+ """
320
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
321
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
322
+ # rescale the results from guidance (fixes overexposure)
323
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
324
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
325
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
326
+ return noise_cfg
327
+
328
+
329
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
330
+ def retrieve_timesteps(
331
+ scheduler,
332
+ num_inference_steps: Optional[int] = None,
333
+ device: Optional[Union[str, torch.device]] = None,
334
+ timesteps: Optional[List[int]] = None,
335
+ **kwargs,
336
+ ):
337
+ """
338
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
339
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
340
+
341
+ Args:
342
+ scheduler (`SchedulerMixin`):
343
+ The scheduler to get timesteps from.
344
+ num_inference_steps (`int`):
345
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
346
+ `timesteps` must be `None`.
347
+ device (`str` or `torch.device`, *optional*):
348
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
349
+ timesteps (`List[int]`, *optional*):
350
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
351
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
352
+ must be `None`.
353
+
354
+ Returns:
355
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
356
+ second element is the number of inference steps.
357
+ """
358
+ if timesteps is not None:
359
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
360
+ if not accepts_timesteps:
361
+ raise ValueError(
362
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
363
+ f" timestep schedules. Please check whether you are using the correct scheduler."
364
+ )
365
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
366
+ timesteps = scheduler.timesteps
367
+ num_inference_steps = len(timesteps)
368
+ else:
369
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
370
+ timesteps = scheduler.timesteps
371
+ return timesteps, num_inference_steps
372
+
373
+
374
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
375
+ def retrieve_latents(
376
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
377
+ ):
378
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
379
+ return encoder_output.latent_dist.sample(generator)
380
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
381
+ return encoder_output.latent_dist.mode()
382
+ elif hasattr(encoder_output, "latents"):
383
+ return encoder_output.latents
384
+ else:
385
+ raise AttributeError("Could not access latents of provided encoder_output")
386
+
387
+
388
+ class StyleAlignedSDXLPipeline(
389
+ DiffusionPipeline,
390
+ StableDiffusionMixin,
391
+ FromSingleFileMixin,
392
+ StableDiffusionXLLoraLoaderMixin,
393
+ TextualInversionLoaderMixin,
394
+ IPAdapterMixin,
395
+ ):
396
+ r"""
397
+ Pipeline for text-to-image generation using Stable Diffusion XL.
398
+
399
+ This pipeline also adds experimental support for [StyleAligned](https://arxiv.org/abs/2312.02133). It can
400
+ be enabled/disabled using `.enable_style_aligned()` or `.disable_style_aligned()` respectively.
401
+
402
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
403
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
404
+
405
+ The pipeline also inherits the following loading methods:
406
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
407
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
408
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
409
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
410
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
411
+
412
+ Args:
413
+ vae ([`AutoencoderKL`]):
414
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
415
+ text_encoder ([`CLIPTextModel`]):
416
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
417
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
418
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
419
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
420
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
421
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
422
+ specifically the
423
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
424
+ variant.
425
+ tokenizer (`CLIPTokenizer`):
426
+ Tokenizer of class
427
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
428
+ tokenizer_2 (`CLIPTokenizer`):
429
+ Second Tokenizer of class
430
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
431
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
432
+ scheduler ([`SchedulerMixin`]):
433
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
434
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
435
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
436
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
437
+ `stabilityai/stable-diffusion-xl-base-1-0`.
438
+ add_watermarker (`bool`, *optional*):
439
+ Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
440
+ watermark output images. If not defined, it will default to True if the package is installed, otherwise no
441
+ watermarker will be used.
442
+ """
443
+
444
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
445
+ _optional_components = [
446
+ "tokenizer",
447
+ "tokenizer_2",
448
+ "text_encoder",
449
+ "text_encoder_2",
450
+ "image_encoder",
451
+ "feature_extractor",
452
+ ]
453
+ _callback_tensor_inputs = [
454
+ "latents",
455
+ "prompt_embeds",
456
+ "negative_prompt_embeds",
457
+ "add_text_embeds",
458
+ "add_time_ids",
459
+ "negative_pooled_prompt_embeds",
460
+ "negative_add_time_ids",
461
+ ]
462
+
463
+ def __init__(
464
+ self,
465
+ vae: AutoencoderKL,
466
+ text_encoder: CLIPTextModel,
467
+ text_encoder_2: CLIPTextModelWithProjection,
468
+ tokenizer: CLIPTokenizer,
469
+ tokenizer_2: CLIPTokenizer,
470
+ unet: UNet2DConditionModel,
471
+ scheduler: KarrasDiffusionSchedulers,
472
+ image_encoder: CLIPVisionModelWithProjection = None,
473
+ feature_extractor: CLIPImageProcessor = None,
474
+ force_zeros_for_empty_prompt: bool = True,
475
+ add_watermarker: Optional[bool] = None,
476
+ ):
477
+ super().__init__()
478
+
479
+ self.register_modules(
480
+ vae=vae,
481
+ text_encoder=text_encoder,
482
+ text_encoder_2=text_encoder_2,
483
+ tokenizer=tokenizer,
484
+ tokenizer_2=tokenizer_2,
485
+ unet=unet,
486
+ scheduler=scheduler,
487
+ image_encoder=image_encoder,
488
+ feature_extractor=feature_extractor,
489
+ )
490
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
491
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
492
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
493
+ self.mask_processor = VaeImageProcessor(
494
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_binarize=True, do_convert_grayscale=True
495
+ )
496
+
497
+ self.default_sample_size = self.unet.config.sample_size
498
+
499
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
500
+
501
+ if add_watermarker:
502
+ self.watermark = StableDiffusionXLWatermarker()
503
+ else:
504
+ self.watermark = None
505
+
506
+ def encode_prompt(
507
+ self,
508
+ prompt: str,
509
+ prompt_2: Optional[str] = None,
510
+ device: Optional[torch.device] = None,
511
+ num_images_per_prompt: int = 1,
512
+ do_classifier_free_guidance: bool = True,
513
+ negative_prompt: Optional[str] = None,
514
+ negative_prompt_2: Optional[str] = None,
515
+ prompt_embeds: Optional[torch.Tensor] = None,
516
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
517
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
518
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
519
+ lora_scale: Optional[float] = None,
520
+ clip_skip: Optional[int] = None,
521
+ ):
522
+ r"""
523
+ Encodes the prompt into text encoder hidden states.
524
+
525
+ Args:
526
+ prompt (`str` or `List[str]`, *optional*):
527
+ prompt to be encoded
528
+ prompt_2 (`str` or `List[str]`, *optional*):
529
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
530
+ used in both text-encoders
531
+ device: (`torch.device`):
532
+ torch device
533
+ num_images_per_prompt (`int`):
534
+ number of images that should be generated per prompt
535
+ do_classifier_free_guidance (`bool`):
536
+ whether to use classifier free guidance or not
537
+ negative_prompt (`str` or `List[str]`, *optional*):
538
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
539
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
540
+ less than `1`).
541
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
542
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
543
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
544
+ prompt_embeds (`torch.Tensor`, *optional*):
545
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
546
+ provided, text embeddings will be generated from `prompt` input argument.
547
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
548
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
549
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
550
+ argument.
551
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
552
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
553
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
554
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
555
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
556
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
557
+ input argument.
558
+ lora_scale (`float`, *optional*):
559
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
560
+ clip_skip (`int`, *optional*):
561
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
562
+ the output of the pre-final layer will be used for computing the prompt embeddings.
563
+ """
564
+ device = device or self._execution_device
565
+
566
+ # set lora scale so that monkey patched LoRA
567
+ # function of text encoder can correctly access it
568
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
569
+ self._lora_scale = lora_scale
570
+
571
+ # dynamically adjust the LoRA scale
572
+ if self.text_encoder is not None:
573
+ if not USE_PEFT_BACKEND:
574
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
575
+ else:
576
+ scale_lora_layers(self.text_encoder, lora_scale)
577
+
578
+ if self.text_encoder_2 is not None:
579
+ if not USE_PEFT_BACKEND:
580
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
581
+ else:
582
+ scale_lora_layers(self.text_encoder_2, lora_scale)
583
+
584
+ prompt = [prompt] if isinstance(prompt, str) else prompt
585
+
586
+ if prompt is not None:
587
+ batch_size = len(prompt)
588
+ else:
589
+ batch_size = prompt_embeds.shape[0]
590
+
591
+ # Define tokenizers and text encoders
592
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
593
+ text_encoders = (
594
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
595
+ )
596
+
597
+ if prompt_embeds is None:
598
+ prompt_2 = prompt_2 or prompt
599
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
600
+
601
+ # textual inversion: process multi-vector tokens if necessary
602
+ prompt_embeds_list = []
603
+ prompts = [prompt, prompt_2]
604
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
605
+ if isinstance(self, TextualInversionLoaderMixin):
606
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
607
+
608
+ text_inputs = tokenizer(
609
+ prompt,
610
+ padding="max_length",
611
+ max_length=tokenizer.model_max_length,
612
+ truncation=True,
613
+ return_tensors="pt",
614
+ )
615
+
616
+ text_input_ids = text_inputs.input_ids
617
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
618
+
619
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
620
+ text_input_ids, untruncated_ids
621
+ ):
622
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
623
+ logger.warning(
624
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
625
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
626
+ )
627
+
628
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
629
+
630
+ # We are only ALWAYS interested in the pooled output of the final text encoder
631
+ pooled_prompt_embeds = prompt_embeds[0]
632
+ if clip_skip is None:
633
+ prompt_embeds = prompt_embeds.hidden_states[-2]
634
+ else:
635
+ # "2" because SDXL always indexes from the penultimate layer.
636
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
637
+
638
+ prompt_embeds_list.append(prompt_embeds)
639
+
640
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
641
+
642
+ # get unconditional embeddings for classifier free guidance
643
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
644
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
645
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
646
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
647
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
648
+ negative_prompt = negative_prompt or ""
649
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
650
+
651
+ # normalize str to list
652
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
653
+ negative_prompt_2 = (
654
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
655
+ )
656
+
657
+ uncond_tokens: List[str]
658
+ if prompt is not None and type(prompt) is not type(negative_prompt):
659
+ raise TypeError(
660
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
661
+ f" {type(prompt)}."
662
+ )
663
+ elif batch_size != len(negative_prompt):
664
+ raise ValueError(
665
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
666
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
667
+ " the batch size of `prompt`."
668
+ )
669
+ else:
670
+ uncond_tokens = [negative_prompt, negative_prompt_2]
671
+
672
+ negative_prompt_embeds_list = []
673
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
674
+ if isinstance(self, TextualInversionLoaderMixin):
675
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
676
+
677
+ max_length = prompt_embeds.shape[1]
678
+ uncond_input = tokenizer(
679
+ negative_prompt,
680
+ padding="max_length",
681
+ max_length=max_length,
682
+ truncation=True,
683
+ return_tensors="pt",
684
+ )
685
+
686
+ negative_prompt_embeds = text_encoder(
687
+ uncond_input.input_ids.to(device),
688
+ output_hidden_states=True,
689
+ )
690
+ # We are only ALWAYS interested in the pooled output of the final text encoder
691
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
692
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
693
+
694
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
695
+
696
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
697
+
698
+ if self.text_encoder_2 is not None:
699
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
700
+ else:
701
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
702
+
703
+ bs_embed, seq_len, _ = prompt_embeds.shape
704
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
705
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
706
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
707
+
708
+ if do_classifier_free_guidance:
709
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
710
+ seq_len = negative_prompt_embeds.shape[1]
711
+
712
+ if self.text_encoder_2 is not None:
713
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
714
+ else:
715
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
716
+
717
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
718
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
719
+
720
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
721
+ bs_embed * num_images_per_prompt, -1
722
+ )
723
+ if do_classifier_free_guidance:
724
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
725
+ bs_embed * num_images_per_prompt, -1
726
+ )
727
+
728
+ if self.text_encoder is not None:
729
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
730
+ # Retrieve the original scale by scaling back the LoRA layers
731
+ unscale_lora_layers(self.text_encoder, lora_scale)
732
+
733
+ if self.text_encoder_2 is not None:
734
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
735
+ # Retrieve the original scale by scaling back the LoRA layers
736
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
737
+
738
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
739
+
740
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
741
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
742
+ dtype = next(self.image_encoder.parameters()).dtype
743
+
744
+ if not isinstance(image, torch.Tensor):
745
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
746
+
747
+ image = image.to(device=device, dtype=dtype)
748
+ if output_hidden_states:
749
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
750
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
751
+ uncond_image_enc_hidden_states = self.image_encoder(
752
+ torch.zeros_like(image), output_hidden_states=True
753
+ ).hidden_states[-2]
754
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
755
+ num_images_per_prompt, dim=0
756
+ )
757
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
758
+ else:
759
+ image_embeds = self.image_encoder(image).image_embeds
760
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
761
+ uncond_image_embeds = torch.zeros_like(image_embeds)
762
+
763
+ return image_embeds, uncond_image_embeds
764
+
765
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
766
+ def prepare_extra_step_kwargs(self, generator, eta):
767
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
768
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
769
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
770
+ # and should be between [0, 1]
771
+
772
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
773
+ extra_step_kwargs = {}
774
+ if accepts_eta:
775
+ extra_step_kwargs["eta"] = eta
776
+
777
+ # check if the scheduler accepts generator
778
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
779
+ if accepts_generator:
780
+ extra_step_kwargs["generator"] = generator
781
+ return extra_step_kwargs
782
+
783
+ def check_inputs(
784
+ self,
785
+ prompt,
786
+ prompt_2,
787
+ height,
788
+ width,
789
+ callback_steps,
790
+ negative_prompt=None,
791
+ negative_prompt_2=None,
792
+ prompt_embeds=None,
793
+ negative_prompt_embeds=None,
794
+ pooled_prompt_embeds=None,
795
+ negative_pooled_prompt_embeds=None,
796
+ callback_on_step_end_tensor_inputs=None,
797
+ ):
798
+ if height % 8 != 0 or width % 8 != 0:
799
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
800
+
801
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
802
+ raise ValueError(
803
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
804
+ f" {type(callback_steps)}."
805
+ )
806
+
807
+ if callback_on_step_end_tensor_inputs is not None and not all(
808
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
809
+ ):
810
+ raise ValueError(
811
+ 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]}"
812
+ )
813
+
814
+ if prompt is not None and prompt_embeds is not None:
815
+ raise ValueError(
816
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
817
+ " only forward one of the two."
818
+ )
819
+ elif prompt_2 is not None and prompt_embeds is not None:
820
+ raise ValueError(
821
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
822
+ " only forward one of the two."
823
+ )
824
+ elif prompt is None and prompt_embeds is None:
825
+ raise ValueError(
826
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
827
+ )
828
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
829
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
830
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
831
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
832
+
833
+ if negative_prompt is not None and negative_prompt_embeds is not None:
834
+ raise ValueError(
835
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
836
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
837
+ )
838
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
839
+ raise ValueError(
840
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
841
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
842
+ )
843
+
844
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
845
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
846
+ raise ValueError(
847
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
848
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
849
+ f" {negative_prompt_embeds.shape}."
850
+ )
851
+
852
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
853
+ raise ValueError(
854
+ "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`."
855
+ )
856
+
857
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
858
+ raise ValueError(
859
+ "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`."
860
+ )
861
+
862
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
863
+ # get the original timestep using init_timestep
864
+ if denoising_start is None:
865
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
866
+ t_start = max(num_inference_steps - init_timestep, 0)
867
+ else:
868
+ t_start = 0
869
+
870
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
871
+
872
+ # Strength is irrelevant if we directly request a timestep to start at;
873
+ # that is, strength is determined by the denoising_start instead.
874
+ if denoising_start is not None:
875
+ discrete_timestep_cutoff = int(
876
+ round(
877
+ self.scheduler.config.num_train_timesteps
878
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
879
+ )
880
+ )
881
+
882
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
883
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
884
+ # if the scheduler is a 2nd order scheduler we might have to do +1
885
+ # because `num_inference_steps` might be even given that every timestep
886
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
887
+ # mean that we cut the timesteps in the middle of the denoising step
888
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
889
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
890
+ num_inference_steps = num_inference_steps + 1
891
+
892
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
893
+ timesteps = timesteps[-num_inference_steps:]
894
+ return timesteps, num_inference_steps
895
+
896
+ return timesteps, num_inference_steps - t_start
897
+
898
+ def prepare_latents(
899
+ self,
900
+ image,
901
+ mask,
902
+ width,
903
+ height,
904
+ num_channels_latents,
905
+ timestep,
906
+ batch_size,
907
+ num_images_per_prompt,
908
+ dtype,
909
+ device,
910
+ generator=None,
911
+ add_noise=True,
912
+ latents=None,
913
+ is_strength_max=True,
914
+ return_noise=False,
915
+ return_image_latents=False,
916
+ ):
917
+ batch_size *= num_images_per_prompt
918
+
919
+ if image is None:
920
+ shape = (
921
+ batch_size,
922
+ num_channels_latents,
923
+ int(height) // self.vae_scale_factor,
924
+ int(width) // self.vae_scale_factor,
925
+ )
926
+ if isinstance(generator, list) and len(generator) != batch_size:
927
+ raise ValueError(
928
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
929
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
930
+ )
931
+
932
+ if latents is None:
933
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
934
+ else:
935
+ latents = latents.to(device)
936
+
937
+ # scale the initial noise by the standard deviation required by the scheduler
938
+ latents = latents * self.scheduler.init_noise_sigma
939
+ return latents
940
+
941
+ elif mask is None:
942
+ if not isinstance(image, (torch.Tensor, Image.Image, list)):
943
+ raise ValueError(
944
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
945
+ )
946
+
947
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
948
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
949
+ self.text_encoder_2.to("cpu")
950
+ torch.cuda.empty_cache()
951
+
952
+ image = image.to(device=device, dtype=dtype)
953
+
954
+ if image.shape[1] == 4:
955
+ init_latents = image
956
+
957
+ else:
958
+ # make sure the VAE is in float32 mode, as it overflows in float16
959
+ if self.vae.config.force_upcast:
960
+ image = image.float()
961
+ self.vae.to(dtype=torch.float32)
962
+
963
+ if isinstance(generator, list) and len(generator) != batch_size:
964
+ raise ValueError(
965
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
966
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
967
+ )
968
+
969
+ elif isinstance(generator, list):
970
+ init_latents = [
971
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
972
+ for i in range(batch_size)
973
+ ]
974
+ init_latents = torch.cat(init_latents, dim=0)
975
+ else:
976
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
977
+
978
+ if self.vae.config.force_upcast:
979
+ self.vae.to(dtype)
980
+
981
+ init_latents = init_latents.to(dtype)
982
+ init_latents = self.vae.config.scaling_factor * init_latents
983
+
984
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
985
+ # expand init_latents for batch_size
986
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
987
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
988
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
989
+ raise ValueError(
990
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
991
+ )
992
+ else:
993
+ init_latents = torch.cat([init_latents], dim=0)
994
+
995
+ if add_noise:
996
+ shape = init_latents.shape
997
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
998
+ # get latents
999
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
1000
+
1001
+ latents = init_latents
1002
+ return latents
1003
+
1004
+ else:
1005
+ shape = (
1006
+ batch_size,
1007
+ num_channels_latents,
1008
+ int(height) // self.vae_scale_factor,
1009
+ int(width) // self.vae_scale_factor,
1010
+ )
1011
+ if isinstance(generator, list) and len(generator) != batch_size:
1012
+ raise ValueError(
1013
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
1014
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
1015
+ )
1016
+
1017
+ if (image is None or timestep is None) and not is_strength_max:
1018
+ raise ValueError(
1019
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
1020
+ "However, either the image or the noise timestep has not been provided."
1021
+ )
1022
+
1023
+ if image.shape[1] == 4:
1024
+ image_latents = image.to(device=device, dtype=dtype)
1025
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
1026
+ elif return_image_latents or (latents is None and not is_strength_max):
1027
+ image = image.to(device=device, dtype=dtype)
1028
+ image_latents = self._encode_vae_image(image=image, generator=generator)
1029
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
1030
+
1031
+ if latents is None and add_noise:
1032
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
1033
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
1034
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
1035
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
1036
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
1037
+ elif add_noise:
1038
+ noise = latents.to(device)
1039
+ latents = noise * self.scheduler.init_noise_sigma
1040
+ else:
1041
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
1042
+ latents = image_latents.to(device)
1043
+
1044
+ outputs = (latents,)
1045
+
1046
+ if return_noise:
1047
+ outputs += (noise,)
1048
+
1049
+ if return_image_latents:
1050
+ outputs += (image_latents,)
1051
+
1052
+ return outputs
1053
+
1054
+ def prepare_mask_latents(
1055
+ self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance
1056
+ ):
1057
+ # resize the mask to latents shape as we concatenate the mask to the latents
1058
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
1059
+ # and half precision
1060
+ mask = torch.nn.functional.interpolate(
1061
+ mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor)
1062
+ )
1063
+ mask = mask.to(device=device, dtype=dtype)
1064
+
1065
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
1066
+ if mask.shape[0] < batch_size:
1067
+ if not batch_size % mask.shape[0] == 0:
1068
+ raise ValueError(
1069
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
1070
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
1071
+ " of masks that you pass is divisible by the total requested batch size."
1072
+ )
1073
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
1074
+
1075
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
1076
+
1077
+ if masked_image is not None and masked_image.shape[1] == 4:
1078
+ masked_image_latents = masked_image
1079
+ else:
1080
+ masked_image_latents = None
1081
+
1082
+ if masked_image is not None:
1083
+ if masked_image_latents is None:
1084
+ masked_image = masked_image.to(device=device, dtype=dtype)
1085
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
1086
+
1087
+ if masked_image_latents.shape[0] < batch_size:
1088
+ if not batch_size % masked_image_latents.shape[0] == 0:
1089
+ raise ValueError(
1090
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
1091
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
1092
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
1093
+ )
1094
+ masked_image_latents = masked_image_latents.repeat(
1095
+ batch_size // masked_image_latents.shape[0], 1, 1, 1
1096
+ )
1097
+
1098
+ masked_image_latents = (
1099
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
1100
+ )
1101
+
1102
+ # aligning device to prevent device errors when concating it with the latent model input
1103
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
1104
+
1105
+ return mask, masked_image_latents
1106
+
1107
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
1108
+ dtype = image.dtype
1109
+ if self.vae.config.force_upcast:
1110
+ image = image.float()
1111
+ self.vae.to(dtype=torch.float32)
1112
+
1113
+ if isinstance(generator, list):
1114
+ image_latents = [
1115
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
1116
+ for i in range(image.shape[0])
1117
+ ]
1118
+ image_latents = torch.cat(image_latents, dim=0)
1119
+ else:
1120
+ image_latents = retrieve_latents(self.vae.encode(image), generator=generator)
1121
+
1122
+ if self.vae.config.force_upcast:
1123
+ self.vae.to(dtype)
1124
+
1125
+ image_latents = image_latents.to(dtype)
1126
+ image_latents = self.vae.config.scaling_factor * image_latents
1127
+
1128
+ return image_latents
1129
+
1130
+ def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
1131
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1132
+
1133
+ passed_add_embed_dim = (
1134
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + self.text_encoder_2.config.projection_dim
1135
+ )
1136
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
1137
+
1138
+ if expected_add_embed_dim != passed_add_embed_dim:
1139
+ raise ValueError(
1140
+ 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`."
1141
+ )
1142
+
1143
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1144
+ return add_time_ids
1145
+
1146
+ def upcast_vae(self):
1147
+ dtype = self.vae.dtype
1148
+ self.vae.to(dtype=torch.float32)
1149
+ use_torch_2_0_or_xformers = isinstance(
1150
+ self.vae.decoder.mid_block.attentions[0].processor,
1151
+ (
1152
+ AttnProcessor2_0,
1153
+ XFormersAttnProcessor,
1154
+ FusedAttnProcessor2_0,
1155
+ ),
1156
+ )
1157
+ # if xformers or torch_2_0 is used attention block does not need
1158
+ # to be in float32 which can save lots of memory
1159
+ if use_torch_2_0_or_xformers:
1160
+ self.vae.post_quant_conv.to(dtype)
1161
+ self.vae.decoder.conv_in.to(dtype)
1162
+ self.vae.decoder.mid_block.to(dtype)
1163
+
1164
+ def _enable_shared_attention_processors(
1165
+ self,
1166
+ share_attention: bool,
1167
+ adain_queries: bool,
1168
+ adain_keys: bool,
1169
+ adain_values: bool,
1170
+ full_attention_share: bool,
1171
+ shared_score_scale: float,
1172
+ shared_score_shift: float,
1173
+ only_self_level: float,
1174
+ ):
1175
+ r"""Helper method to enable usage of Shared Attention Processor."""
1176
+ attn_procs = {}
1177
+ num_self_layers = len([name for name in self.unet.attn_processors.keys() if "attn1" in name])
1178
+
1179
+ only_self_vec = get_switch_vec(num_self_layers, only_self_level)
1180
+
1181
+ for i, name in enumerate(self.unet.attn_processors.keys()):
1182
+ is_self_attention = "attn1" in name
1183
+ if is_self_attention:
1184
+ if only_self_vec[i // 2]:
1185
+ attn_procs[name] = AttnProcessor2_0()
1186
+ else:
1187
+ attn_procs[name] = SharedAttentionProcessor(
1188
+ share_attention=share_attention,
1189
+ adain_queries=adain_queries,
1190
+ adain_keys=adain_keys,
1191
+ adain_values=adain_values,
1192
+ full_attention_share=full_attention_share,
1193
+ shared_score_scale=shared_score_scale,
1194
+ shared_score_shift=shared_score_shift,
1195
+ )
1196
+ else:
1197
+ attn_procs[name] = AttnProcessor2_0()
1198
+
1199
+ self.unet.set_attn_processor(attn_procs)
1200
+
1201
+ def _disable_shared_attention_processors(self):
1202
+ r"""
1203
+ Helper method to disable usage of the Shared Attention Processor. All processors
1204
+ are reset to the default Attention Processor for pytorch versions above 2.0.
1205
+ """
1206
+ attn_procs = {}
1207
+
1208
+ for i, name in enumerate(self.unet.attn_processors.keys()):
1209
+ attn_procs[name] = AttnProcessor2_0()
1210
+
1211
+ self.unet.set_attn_processor(attn_procs)
1212
+
1213
+ def _register_shared_norm(self, share_group_norm: bool = True, share_layer_norm: bool = True):
1214
+ r"""Helper method to register shared group/layer normalization layers."""
1215
+
1216
+ def register_norm_forward(norm_layer: Union[nn.GroupNorm, nn.LayerNorm]) -> Union[nn.GroupNorm, nn.LayerNorm]:
1217
+ if not hasattr(norm_layer, "orig_forward"):
1218
+ setattr(norm_layer, "orig_forward", norm_layer.forward)
1219
+ orig_forward = norm_layer.orig_forward
1220
+
1221
+ def forward_(hidden_states: torch.Tensor) -> torch.Tensor:
1222
+ n = hidden_states.shape[-2]
1223
+ hidden_states = concat_first(hidden_states, dim=-2)
1224
+ hidden_states = orig_forward(hidden_states)
1225
+ return hidden_states[..., :n, :]
1226
+
1227
+ norm_layer.forward = forward_
1228
+ return norm_layer
1229
+
1230
+ def get_norm_layers(pipeline_, norm_layers_: Dict[str, List[Union[nn.GroupNorm, nn.LayerNorm]]]):
1231
+ if isinstance(pipeline_, nn.LayerNorm) and share_layer_norm:
1232
+ norm_layers_["layer"].append(pipeline_)
1233
+ if isinstance(pipeline_, nn.GroupNorm) and share_group_norm:
1234
+ norm_layers_["group"].append(pipeline_)
1235
+ else:
1236
+ for layer in pipeline_.children():
1237
+ get_norm_layers(layer, norm_layers_)
1238
+
1239
+ norm_layers = {"group": [], "layer": []}
1240
+ get_norm_layers(self.unet, norm_layers)
1241
+
1242
+ norm_layers_list = []
1243
+ for key in ["group", "layer"]:
1244
+ for layer in norm_layers[key]:
1245
+ norm_layers_list.append(register_norm_forward(layer))
1246
+
1247
+ return norm_layers_list
1248
+
1249
+ @property
1250
+ def style_aligned_enabled(self):
1251
+ r"""Returns whether StyleAligned has been enabled in the pipeline or not."""
1252
+ return hasattr(self, "_style_aligned_norm_layers") and self._style_aligned_norm_layers is not None
1253
+
1254
+ def enable_style_aligned(
1255
+ self,
1256
+ share_group_norm: bool = True,
1257
+ share_layer_norm: bool = True,
1258
+ share_attention: bool = True,
1259
+ adain_queries: bool = True,
1260
+ adain_keys: bool = True,
1261
+ adain_values: bool = False,
1262
+ full_attention_share: bool = False,
1263
+ shared_score_scale: float = 1.0,
1264
+ shared_score_shift: float = 0.0,
1265
+ only_self_level: float = 0.0,
1266
+ ):
1267
+ r"""
1268
+ Enables the StyleAligned mechanism as in https://arxiv.org/abs/2312.02133.
1269
+
1270
+ Args:
1271
+ share_group_norm (`bool`, defaults to `True`):
1272
+ Whether or not to use shared group normalization layers.
1273
+ share_layer_norm (`bool`, defaults to `True`):
1274
+ Whether or not to use shared layer normalization layers.
1275
+ share_attention (`bool`, defaults to `True`):
1276
+ Whether or not to use attention sharing between batch images.
1277
+ adain_queries (`bool`, defaults to `True`):
1278
+ Whether or not to apply the AdaIn operation on attention queries.
1279
+ adain_keys (`bool`, defaults to `True`):
1280
+ Whether or not to apply the AdaIn operation on attention keys.
1281
+ adain_values (`bool`, defaults to `False`):
1282
+ Whether or not to apply the AdaIn operation on attention values.
1283
+ full_attention_share (`bool`, defaults to `False`):
1284
+ Whether or not to use full attention sharing between all images in a batch. Can
1285
+ lead to content leakage within each batch and some loss in diversity.
1286
+ shared_score_scale (`float`, defaults to `1.0`):
1287
+ Scale for shared attention.
1288
+ """
1289
+ self._style_aligned_norm_layers = self._register_shared_norm(share_group_norm, share_layer_norm)
1290
+ self._enable_shared_attention_processors(
1291
+ share_attention=share_attention,
1292
+ adain_queries=adain_queries,
1293
+ adain_keys=adain_keys,
1294
+ adain_values=adain_values,
1295
+ full_attention_share=full_attention_share,
1296
+ shared_score_scale=shared_score_scale,
1297
+ shared_score_shift=shared_score_shift,
1298
+ only_self_level=only_self_level,
1299
+ )
1300
+
1301
+ def disable_style_aligned(self):
1302
+ r"""Disables the StyleAligned mechanism if it had been previously enabled."""
1303
+ if self.style_aligned_enabled:
1304
+ for layer in self._style_aligned_norm_layers:
1305
+ layer.forward = layer.orig_forward
1306
+
1307
+ self._style_aligned_norm_layers = None
1308
+ self._disable_shared_attention_processors()
1309
+
1310
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
1311
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
1312
+ """
1313
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
1314
+
1315
+ Args:
1316
+ timesteps (`torch.Tensor`):
1317
+ generate embedding vectors at these timesteps
1318
+ embedding_dim (`int`, *optional*, defaults to 512):
1319
+ dimension of the embeddings to generate
1320
+ dtype:
1321
+ data type of the generated embeddings
1322
+
1323
+ Returns:
1324
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
1325
+ """
1326
+ assert len(w.shape) == 1
1327
+ w = w * 1000.0
1328
+
1329
+ half_dim = embedding_dim // 2
1330
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
1331
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1332
+ emb = w.to(dtype)[:, None] * emb[None, :]
1333
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1334
+ if embedding_dim % 2 == 1: # zero pad
1335
+ emb = torch.nn.functional.pad(emb, (0, 1))
1336
+ assert emb.shape == (w.shape[0], embedding_dim)
1337
+ return emb
1338
+
1339
+ @property
1340
+ def guidance_scale(self):
1341
+ return self._guidance_scale
1342
+
1343
+ @property
1344
+ def guidance_rescale(self):
1345
+ return self._guidance_rescale
1346
+
1347
+ @property
1348
+ def clip_skip(self):
1349
+ return self._clip_skip
1350
+
1351
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1352
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1353
+ # corresponds to doing no classifier free guidance.
1354
+ @property
1355
+ def do_classifier_free_guidance(self):
1356
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1357
+
1358
+ @property
1359
+ def cross_attention_kwargs(self):
1360
+ return self._cross_attention_kwargs
1361
+
1362
+ @property
1363
+ def denoising_end(self):
1364
+ return self._denoising_end
1365
+
1366
+ @property
1367
+ def denoising_start(self):
1368
+ return self._denoising_start
1369
+
1370
+ @property
1371
+ def num_timesteps(self):
1372
+ return self._num_timesteps
1373
+
1374
+ @property
1375
+ def interrupt(self):
1376
+ return self._interrupt
1377
+
1378
+ @torch.no_grad()
1379
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1380
+ def __call__(
1381
+ self,
1382
+ prompt: Union[str, List[str]] = None,
1383
+ prompt_2: Optional[Union[str, List[str]]] = None,
1384
+ image: Optional[PipelineImageInput] = None,
1385
+ mask_image: Optional[PipelineImageInput] = None,
1386
+ masked_image_latents: Optional[torch.Tensor] = None,
1387
+ strength: float = 0.3,
1388
+ height: Optional[int] = None,
1389
+ width: Optional[int] = None,
1390
+ num_inference_steps: int = 50,
1391
+ timesteps: List[int] = None,
1392
+ denoising_start: Optional[float] = None,
1393
+ denoising_end: Optional[float] = None,
1394
+ guidance_scale: float = 5.0,
1395
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1396
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1397
+ num_images_per_prompt: Optional[int] = 1,
1398
+ eta: float = 0.0,
1399
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1400
+ latents: Optional[torch.Tensor] = None,
1401
+ prompt_embeds: Optional[torch.Tensor] = None,
1402
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1403
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1404
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1405
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1406
+ output_type: Optional[str] = "pil",
1407
+ return_dict: bool = True,
1408
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1409
+ guidance_rescale: float = 0.0,
1410
+ original_size: Optional[Tuple[int, int]] = None,
1411
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
1412
+ target_size: Optional[Tuple[int, int]] = None,
1413
+ clip_skip: Optional[int] = None,
1414
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1415
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1416
+ **kwargs,
1417
+ ):
1418
+ r"""
1419
+ Function invoked when calling the pipeline for generation.
1420
+
1421
+ Args:
1422
+ prompt (`str` or `List[str]`, *optional*):
1423
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1424
+ instead.
1425
+ prompt_2 (`str` or `List[str]`, *optional*):
1426
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1427
+ used in both text-encoders
1428
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1429
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
1430
+ Anything below 512 pixels won't work well for
1431
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1432
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1433
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1434
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
1435
+ Anything below 512 pixels won't work well for
1436
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
1437
+ and checkpoints that are not specifically fine-tuned on low resolutions.
1438
+ num_inference_steps (`int`, *optional*, defaults to 50):
1439
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1440
+ expense of slower inference.
1441
+ timesteps (`List[int]`, *optional*):
1442
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1443
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1444
+ passed will be used. Must be in descending order.
1445
+ denoising_end (`float`, *optional*):
1446
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1447
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1448
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1449
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1450
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1451
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1452
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1453
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1454
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1455
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1456
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1457
+ usually at the expense of lower image quality.
1458
+ negative_prompt (`str` or `List[str]`, *optional*):
1459
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1460
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1461
+ less than `1`).
1462
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1463
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1464
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1465
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1466
+ The number of images to generate per prompt.
1467
+ eta (`float`, *optional*, defaults to 0.0):
1468
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1469
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1470
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1471
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1472
+ to make generation deterministic.
1473
+ latents (`torch.Tensor`, *optional*):
1474
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1475
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1476
+ tensor will ge generated by sampling using the supplied random `generator`.
1477
+ prompt_embeds (`torch.Tensor`, *optional*):
1478
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1479
+ provided, text embeddings will be generated from `prompt` input argument.
1480
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1481
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1482
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1483
+ argument.
1484
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1485
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1486
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1487
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1488
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1489
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1490
+ input argument.
1491
+ ip_adapter_image: (`PipelineImageInput`, *optional*):
1492
+ Optional image input to work with IP Adapters.
1493
+ output_type (`str`, *optional*, defaults to `"pil"`):
1494
+ The output format of the generate image. Choose between
1495
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1496
+ return_dict (`bool`, *optional*, defaults to `True`):
1497
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
1498
+ of a plain tuple.
1499
+ cross_attention_kwargs (`dict`, *optional*):
1500
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1501
+ `self.processor` in
1502
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1503
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1504
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1505
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1506
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1507
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1508
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1509
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1510
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1511
+ explained in section 2.2 of
1512
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1513
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1514
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1515
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1516
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1517
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1518
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1519
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1520
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1521
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1522
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1523
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1524
+ micro-conditioning as explained in section 2.2 of
1525
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1526
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1527
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1528
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1529
+ micro-conditioning as explained in section 2.2 of
1530
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1531
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1532
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1533
+ To negatively condition the generation process based on a target image resolution. It should be as same
1534
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1535
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1536
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1537
+ callback_on_step_end (`Callable`, *optional*):
1538
+ A function that calls at the end of each denoising steps during the inference. The function is called
1539
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1540
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1541
+ `callback_on_step_end_tensor_inputs`.
1542
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1543
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1544
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1545
+ `._callback_tensor_inputs` attribute of your pipeline class.
1546
+
1547
+ Examples:
1548
+
1549
+ Returns:
1550
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
1551
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1552
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1553
+ """
1554
+
1555
+ callback = kwargs.pop("callback", None)
1556
+ callback_steps = kwargs.pop("callback_steps", None)
1557
+
1558
+ if callback is not None:
1559
+ deprecate(
1560
+ "callback",
1561
+ "1.0.0",
1562
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1563
+ )
1564
+ if callback_steps is not None:
1565
+ deprecate(
1566
+ "callback_steps",
1567
+ "1.0.0",
1568
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1569
+ )
1570
+
1571
+ # 0. Default height and width to unet
1572
+ height = height or self.default_sample_size * self.vae_scale_factor
1573
+ width = width or self.default_sample_size * self.vae_scale_factor
1574
+
1575
+ original_size = original_size or (height, width)
1576
+ target_size = target_size or (height, width)
1577
+
1578
+ # 1. Check inputs. Raise error if not correct
1579
+ self.check_inputs(
1580
+ prompt=prompt,
1581
+ prompt_2=prompt_2,
1582
+ height=height,
1583
+ width=width,
1584
+ callback_steps=callback_steps,
1585
+ negative_prompt=negative_prompt,
1586
+ negative_prompt_2=negative_prompt_2,
1587
+ prompt_embeds=prompt_embeds,
1588
+ negative_prompt_embeds=negative_prompt_embeds,
1589
+ pooled_prompt_embeds=pooled_prompt_embeds,
1590
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1591
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
1592
+ )
1593
+
1594
+ self._guidance_scale = guidance_scale
1595
+ self._guidance_rescale = guidance_rescale
1596
+ self._clip_skip = clip_skip
1597
+ self._cross_attention_kwargs = cross_attention_kwargs
1598
+ self._denoising_end = denoising_end
1599
+ self._denoising_start = denoising_start
1600
+ self._interrupt = False
1601
+
1602
+ # 2. Define call parameters
1603
+ if prompt is not None and isinstance(prompt, str):
1604
+ batch_size = 1
1605
+ elif prompt is not None and isinstance(prompt, list):
1606
+ batch_size = len(prompt)
1607
+ else:
1608
+ batch_size = prompt_embeds.shape[0]
1609
+
1610
+ device = self._execution_device
1611
+
1612
+ # 3. Encode input prompt
1613
+ lora_scale = (
1614
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1615
+ )
1616
+
1617
+ (
1618
+ prompt_embeds,
1619
+ negative_prompt_embeds,
1620
+ pooled_prompt_embeds,
1621
+ negative_pooled_prompt_embeds,
1622
+ ) = self.encode_prompt(
1623
+ prompt=prompt,
1624
+ prompt_2=prompt_2,
1625
+ device=device,
1626
+ num_images_per_prompt=num_images_per_prompt,
1627
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1628
+ negative_prompt=negative_prompt,
1629
+ negative_prompt_2=negative_prompt_2,
1630
+ prompt_embeds=prompt_embeds,
1631
+ negative_prompt_embeds=negative_prompt_embeds,
1632
+ pooled_prompt_embeds=pooled_prompt_embeds,
1633
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1634
+ lora_scale=lora_scale,
1635
+ clip_skip=self.clip_skip,
1636
+ )
1637
+
1638
+ # 4. Preprocess image and mask_image
1639
+ if image is not None:
1640
+ image = self.image_processor.preprocess(image, height=height, width=width)
1641
+ image = image.to(device=self.device, dtype=prompt_embeds.dtype)
1642
+
1643
+ if mask_image is not None:
1644
+ mask = self.mask_processor.preprocess(mask_image, height=height, width=width)
1645
+ mask = mask.to(device=self.device, dtype=prompt_embeds.dtype)
1646
+
1647
+ if masked_image_latents is not None:
1648
+ masked_image = masked_image_latents
1649
+ elif image.shape[1] == 4:
1650
+ # if image is in latent space, we can't mask it
1651
+ masked_image = None
1652
+ else:
1653
+ masked_image = image * (mask < 0.5)
1654
+ else:
1655
+ mask = None
1656
+
1657
+ # 4. Prepare timesteps
1658
+ def denoising_value_valid(dnv):
1659
+ return isinstance(dnv, float) and 0 < dnv < 1
1660
+
1661
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1662
+
1663
+ if image is not None:
1664
+ timesteps, num_inference_steps = self.get_timesteps(
1665
+ num_inference_steps,
1666
+ strength,
1667
+ device,
1668
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1669
+ )
1670
+
1671
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1672
+ if num_inference_steps < 1:
1673
+ raise ValueError(
1674
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1675
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1676
+ )
1677
+
1678
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1679
+ is_strength_max = strength == 1.0
1680
+ add_noise = True if self.denoising_start is None else False
1681
+
1682
+ # 5. Prepare latent variables
1683
+ num_channels_latents = self.unet.config.in_channels
1684
+ num_channels_unet = self.unet.config.in_channels
1685
+ return_image_latents = num_channels_unet == 4
1686
+
1687
+ latents = self.prepare_latents(
1688
+ image=image,
1689
+ mask=mask,
1690
+ width=width,
1691
+ height=height,
1692
+ num_channels_latents=num_channels_latents,
1693
+ timestep=latent_timestep,
1694
+ batch_size=batch_size * num_images_per_prompt,
1695
+ num_images_per_prompt=num_images_per_prompt,
1696
+ dtype=prompt_embeds.dtype,
1697
+ device=device,
1698
+ generator=generator,
1699
+ add_noise=add_noise,
1700
+ latents=latents,
1701
+ is_strength_max=is_strength_max,
1702
+ return_noise=True,
1703
+ return_image_latents=return_image_latents,
1704
+ )
1705
+
1706
+ if mask is not None:
1707
+ if return_image_latents:
1708
+ latents, noise, image_latents = latents
1709
+ else:
1710
+ latents, noise = latents
1711
+
1712
+ mask, masked_image_latents = self.prepare_mask_latents(
1713
+ mask=mask,
1714
+ masked_image=masked_image,
1715
+ batch_size=batch_size * num_images_per_prompt,
1716
+ height=height,
1717
+ width=width,
1718
+ dtype=prompt_embeds.dtype,
1719
+ device=device,
1720
+ generator=generator,
1721
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1722
+ )
1723
+
1724
+ # Check that sizes of mask, masked image and latents match
1725
+ if num_channels_unet == 9:
1726
+ # default case for runwayml/stable-diffusion-inpainting
1727
+ num_channels_mask = mask.shape[1]
1728
+ num_channels_masked_image = masked_image_latents.shape[1]
1729
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != num_channels_unet:
1730
+ raise ValueError(
1731
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1732
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1733
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1734
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1735
+ " `pipeline.unet` or your `mask_image` or `image` input."
1736
+ )
1737
+ elif num_channels_unet != 4:
1738
+ raise ValueError(
1739
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1740
+ )
1741
+
1742
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1743
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1744
+
1745
+ height, width = latents.shape[-2:]
1746
+ height = height * self.vae_scale_factor
1747
+ width = width * self.vae_scale_factor
1748
+
1749
+ original_size = original_size or (height, width)
1750
+ target_size = target_size or (height, width)
1751
+
1752
+ # 7. Prepare added time ids & embeddings
1753
+ add_text_embeds = pooled_prompt_embeds
1754
+ add_time_ids = self._get_add_time_ids(
1755
+ original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
1756
+ )
1757
+
1758
+ if self.do_classifier_free_guidance:
1759
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1760
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1761
+ add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
1762
+
1763
+ prompt_embeds = prompt_embeds.to(device)
1764
+ add_text_embeds = add_text_embeds.to(device)
1765
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1766
+
1767
+ if ip_adapter_image is not None:
1768
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1769
+ image_embeds, negative_image_embeds = self.encode_image(
1770
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
1771
+ )
1772
+ if self.do_classifier_free_guidance:
1773
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1774
+ image_embeds = image_embeds.to(device)
1775
+
1776
+ # 8. Denoising loop
1777
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1778
+
1779
+ # 8.1 Apply denoising_end
1780
+ if (
1781
+ self.denoising_end is not None
1782
+ and isinstance(self.denoising_end, float)
1783
+ and self.denoising_end > 0
1784
+ and self.denoising_end < 1
1785
+ ):
1786
+ discrete_timestep_cutoff = int(
1787
+ round(
1788
+ self.scheduler.config.num_train_timesteps
1789
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
1790
+ )
1791
+ )
1792
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1793
+ timesteps = timesteps[:num_inference_steps]
1794
+
1795
+ # 9. Optionally get Guidance Scale Embedding
1796
+ timestep_cond = None
1797
+ if self.unet.config.time_cond_proj_dim is not None:
1798
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1799
+ timestep_cond = self.get_guidance_scale_embedding(
1800
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1801
+ ).to(device=device, dtype=latents.dtype)
1802
+
1803
+ self._num_timesteps = len(timesteps)
1804
+
1805
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1806
+ for i, t in enumerate(timesteps):
1807
+ if self.interrupt:
1808
+ continue
1809
+
1810
+ # expand the latents if we are doing classifier free guidance
1811
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1812
+
1813
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1814
+
1815
+ # predict the noise residual
1816
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1817
+ if ip_adapter_image is not None:
1818
+ added_cond_kwargs["image_embeds"] = image_embeds
1819
+
1820
+ noise_pred = self.unet(
1821
+ latent_model_input,
1822
+ t,
1823
+ encoder_hidden_states=prompt_embeds,
1824
+ timestep_cond=timestep_cond,
1825
+ cross_attention_kwargs=self.cross_attention_kwargs,
1826
+ added_cond_kwargs=added_cond_kwargs,
1827
+ return_dict=False,
1828
+ )[0]
1829
+
1830
+ # perform guidance
1831
+ if self.do_classifier_free_guidance:
1832
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1833
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1834
+
1835
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1836
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1837
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1838
+
1839
+ # compute the previous noisy sample x_t -> x_t-1
1840
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1841
+
1842
+ if mask is not None and num_channels_unet == 4:
1843
+ init_latents_proper = image_latents
1844
+
1845
+ if self.do_classifier_free_guidance:
1846
+ init_mask, _ = mask.chunk(2)
1847
+ else:
1848
+ init_mask = mask
1849
+
1850
+ if i < len(timesteps) - 1:
1851
+ noise_timestep = timesteps[i + 1]
1852
+ init_latents_proper = self.scheduler.add_noise(
1853
+ init_latents_proper, noise, torch.tensor([noise_timestep])
1854
+ )
1855
+
1856
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1857
+
1858
+ if callback_on_step_end is not None:
1859
+ callback_kwargs = {}
1860
+ for k in callback_on_step_end_tensor_inputs:
1861
+ callback_kwargs[k] = locals()[k]
1862
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1863
+
1864
+ latents = callback_outputs.pop("latents", latents)
1865
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1866
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1867
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1868
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1869
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1870
+ )
1871
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1872
+
1873
+ # call the callback, if provided
1874
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1875
+ progress_bar.update()
1876
+ if callback is not None and i % callback_steps == 0:
1877
+ step_idx = i // getattr(self.scheduler, "order", 1)
1878
+ callback(step_idx, t, latents)
1879
+
1880
+ if XLA_AVAILABLE:
1881
+ xm.mark_step()
1882
+
1883
+ if not output_type == "latent":
1884
+ # make sure the VAE is in float32 mode, as it overflows in float16
1885
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1886
+
1887
+ if needs_upcasting:
1888
+ self.upcast_vae()
1889
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1890
+
1891
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1892
+
1893
+ # cast back to fp16 if needed
1894
+ if needs_upcasting:
1895
+ self.vae.to(dtype=torch.float16)
1896
+ else:
1897
+ image = latents
1898
+
1899
+ if not output_type == "latent":
1900
+ # apply watermark if available
1901
+ if self.watermark is not None:
1902
+ image = self.watermark.apply_watermark(image)
1903
+
1904
+ image = self.image_processor.postprocess(image, output_type=output_type)
1905
+
1906
+ # Offload all models
1907
+ self.maybe_free_model_hooks()
1908
+
1909
+ if not return_dict:
1910
+ return (image,)
1911
+
1912
+ return StableDiffusionXLPipelineOutput(images=image)
v0.30.0/pipeline_stable_diffusion_3_differential_img2img.py ADDED
@@ -0,0 +1,981 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, Dict, List, Optional, Union
17
+
18
+ import torch
19
+ from transformers import (
20
+ CLIPTextModelWithProjection,
21
+ CLIPTokenizer,
22
+ T5EncoderModel,
23
+ T5TokenizerFast,
24
+ )
25
+
26
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
27
+ from diffusers.models.autoencoders import AutoencoderKL
28
+ from diffusers.models.transformers import SD3Transformer2DModel
29
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
30
+ from diffusers.pipelines.stable_diffusion_3.pipeline_output import StableDiffusion3PipelineOutput
31
+ from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
32
+ from diffusers.utils import (
33
+ is_torch_xla_available,
34
+ logging,
35
+ replace_example_docstring,
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
+
55
+ >>> from diffusers import AutoPipelineForImage2Image
56
+ >>> from diffusers.utils import load_image
57
+
58
+ >>> device = "cuda"
59
+ >>> model_id_or_path = "stabilityai/stable-diffusion-3-medium-diffusers"
60
+ >>> pipe = AutoPipelineForImage2Image.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
61
+ >>> pipe = pipe.to(device)
62
+
63
+ >>> url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/assets/stable-samples/img2img/sketch-mountains-input.jpg"
64
+ >>> init_image = load_image(url).resize((512, 512))
65
+
66
+ >>> prompt = "cat wizard, gandalf, lord of the rings, detailed, fantasy, cute, adorable, Pixar, Disney, 8k"
67
+
68
+ >>> images = pipe(prompt=prompt, image=init_image, strength=0.95, guidance_scale=7.5).images[0]
69
+ ```
70
+ """
71
+
72
+
73
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
74
+ def retrieve_latents(
75
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
76
+ ):
77
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
78
+ return encoder_output.latent_dist.sample(generator)
79
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
80
+ return encoder_output.latent_dist.mode()
81
+ elif hasattr(encoder_output, "latents"):
82
+ return encoder_output.latents
83
+ else:
84
+ raise AttributeError("Could not access latents of provided encoder_output")
85
+
86
+
87
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
88
+ def retrieve_timesteps(
89
+ scheduler,
90
+ num_inference_steps: Optional[int] = None,
91
+ device: Optional[Union[str, torch.device]] = None,
92
+ timesteps: Optional[List[int]] = None,
93
+ sigmas: Optional[List[float]] = None,
94
+ **kwargs,
95
+ ):
96
+ """
97
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
98
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
99
+
100
+ Args:
101
+ scheduler (`SchedulerMixin`):
102
+ The scheduler to get timesteps from.
103
+ num_inference_steps (`int`):
104
+ The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
105
+ must be `None`.
106
+ device (`str` or `torch.device`, *optional*):
107
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
108
+ timesteps (`List[int]`, *optional*):
109
+ Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
110
+ `num_inference_steps` and `sigmas` must be `None`.
111
+ sigmas (`List[float]`, *optional*):
112
+ Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
113
+ `num_inference_steps` and `timesteps` must be `None`.
114
+
115
+ Returns:
116
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
117
+ second element is the number of inference steps.
118
+ """
119
+ if timesteps is not None and sigmas is not None:
120
+ raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
121
+ if timesteps is not None:
122
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
123
+ if not accepts_timesteps:
124
+ raise ValueError(
125
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
126
+ f" timestep schedules. Please check whether you are using the correct scheduler."
127
+ )
128
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
129
+ timesteps = scheduler.timesteps
130
+ num_inference_steps = len(timesteps)
131
+ elif sigmas is not None:
132
+ accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
133
+ if not accept_sigmas:
134
+ raise ValueError(
135
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
136
+ f" sigmas schedules. Please check whether you are using the correct scheduler."
137
+ )
138
+ scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
139
+ timesteps = scheduler.timesteps
140
+ num_inference_steps = len(timesteps)
141
+ else:
142
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
143
+ timesteps = scheduler.timesteps
144
+ return timesteps, num_inference_steps
145
+
146
+
147
+ class StableDiffusion3DifferentialImg2ImgPipeline(DiffusionPipeline):
148
+ r"""
149
+ Args:
150
+ transformer ([`SD3Transformer2DModel`]):
151
+ Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
152
+ scheduler ([`FlowMatchEulerDiscreteScheduler`]):
153
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
154
+ vae ([`AutoencoderKL`]):
155
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
156
+ text_encoder ([`CLIPTextModelWithProjection`]):
157
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
158
+ specifically the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant,
159
+ with an additional added projection layer that is initialized with a diagonal matrix with the `hidden_size`
160
+ as its dimension.
161
+ text_encoder_2 ([`CLIPTextModelWithProjection`]):
162
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
163
+ specifically the
164
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
165
+ variant.
166
+ text_encoder_3 ([`T5EncoderModel`]):
167
+ Frozen text-encoder. Stable Diffusion 3 uses
168
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
169
+ [t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
170
+ tokenizer (`CLIPTokenizer`):
171
+ Tokenizer of class
172
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
173
+ tokenizer_2 (`CLIPTokenizer`):
174
+ Second Tokenizer of class
175
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
176
+ tokenizer_3 (`T5TokenizerFast`):
177
+ Tokenizer of class
178
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
179
+ """
180
+
181
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->text_encoder_3->transformer->vae"
182
+ _optional_components = []
183
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds", "negative_pooled_prompt_embeds"]
184
+
185
+ def __init__(
186
+ self,
187
+ transformer: SD3Transformer2DModel,
188
+ scheduler: FlowMatchEulerDiscreteScheduler,
189
+ vae: AutoencoderKL,
190
+ text_encoder: CLIPTextModelWithProjection,
191
+ tokenizer: CLIPTokenizer,
192
+ text_encoder_2: CLIPTextModelWithProjection,
193
+ tokenizer_2: CLIPTokenizer,
194
+ text_encoder_3: T5EncoderModel,
195
+ tokenizer_3: T5TokenizerFast,
196
+ ):
197
+ super().__init__()
198
+
199
+ self.register_modules(
200
+ vae=vae,
201
+ text_encoder=text_encoder,
202
+ text_encoder_2=text_encoder_2,
203
+ text_encoder_3=text_encoder_3,
204
+ tokenizer=tokenizer,
205
+ tokenizer_2=tokenizer_2,
206
+ tokenizer_3=tokenizer_3,
207
+ transformer=transformer,
208
+ scheduler=scheduler,
209
+ )
210
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
211
+ self.image_processor = VaeImageProcessor(
212
+ vae_scale_factor=self.vae_scale_factor, vae_latent_channels=self.vae.config.latent_channels
213
+ )
214
+ self.mask_processor = VaeImageProcessor(
215
+ vae_scale_factor=self.vae_scale_factor, do_normalize=False, do_convert_grayscale=True
216
+ )
217
+
218
+ self.tokenizer_max_length = self.tokenizer.model_max_length
219
+ self.default_sample_size = self.transformer.config.sample_size
220
+
221
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_t5_prompt_embeds
222
+ def _get_t5_prompt_embeds(
223
+ self,
224
+ prompt: Union[str, List[str]] = None,
225
+ num_images_per_prompt: int = 1,
226
+ max_sequence_length: int = 256,
227
+ device: Optional[torch.device] = None,
228
+ dtype: Optional[torch.dtype] = None,
229
+ ):
230
+ device = device or self._execution_device
231
+ dtype = dtype or self.text_encoder.dtype
232
+
233
+ prompt = [prompt] if isinstance(prompt, str) else prompt
234
+ batch_size = len(prompt)
235
+
236
+ if self.text_encoder_3 is None:
237
+ return torch.zeros(
238
+ (
239
+ batch_size * num_images_per_prompt,
240
+ self.tokenizer_max_length,
241
+ self.transformer.config.joint_attention_dim,
242
+ ),
243
+ device=device,
244
+ dtype=dtype,
245
+ )
246
+
247
+ text_inputs = self.tokenizer_3(
248
+ prompt,
249
+ padding="max_length",
250
+ max_length=max_sequence_length,
251
+ truncation=True,
252
+ add_special_tokens=True,
253
+ return_tensors="pt",
254
+ )
255
+ text_input_ids = text_inputs.input_ids
256
+ untruncated_ids = self.tokenizer_3(prompt, padding="longest", return_tensors="pt").input_ids
257
+
258
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
259
+ removed_text = self.tokenizer_3.batch_decode(untruncated_ids[:, self.tokenizer_max_length - 1 : -1])
260
+ logger.warning(
261
+ "The following part of your input was truncated because `max_sequence_length` is set to "
262
+ f" {max_sequence_length} tokens: {removed_text}"
263
+ )
264
+
265
+ prompt_embeds = self.text_encoder_3(text_input_ids.to(device))[0]
266
+
267
+ dtype = self.text_encoder_3.dtype
268
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
269
+
270
+ _, seq_len, _ = prompt_embeds.shape
271
+
272
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
273
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
274
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
275
+
276
+ return prompt_embeds
277
+
278
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline._get_clip_prompt_embeds
279
+ def _get_clip_prompt_embeds(
280
+ self,
281
+ prompt: Union[str, List[str]],
282
+ num_images_per_prompt: int = 1,
283
+ device: Optional[torch.device] = None,
284
+ clip_skip: Optional[int] = None,
285
+ clip_model_index: int = 0,
286
+ ):
287
+ device = device or self._execution_device
288
+
289
+ clip_tokenizers = [self.tokenizer, self.tokenizer_2]
290
+ clip_text_encoders = [self.text_encoder, self.text_encoder_2]
291
+
292
+ tokenizer = clip_tokenizers[clip_model_index]
293
+ text_encoder = clip_text_encoders[clip_model_index]
294
+
295
+ prompt = [prompt] if isinstance(prompt, str) else prompt
296
+ batch_size = len(prompt)
297
+
298
+ text_inputs = tokenizer(
299
+ prompt,
300
+ padding="max_length",
301
+ max_length=self.tokenizer_max_length,
302
+ truncation=True,
303
+ return_tensors="pt",
304
+ )
305
+
306
+ text_input_ids = text_inputs.input_ids
307
+ untruncated_ids = 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 = 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 = text_encoder(text_input_ids.to(device), output_hidden_states=True)
315
+ pooled_prompt_embeds = prompt_embeds[0]
316
+
317
+ if clip_skip is None:
318
+ prompt_embeds = prompt_embeds.hidden_states[-2]
319
+ else:
320
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
321
+
322
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
323
+
324
+ _, seq_len, _ = prompt_embeds.shape
325
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
326
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
327
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
328
+
329
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt, 1)
330
+ pooled_prompt_embeds = pooled_prompt_embeds.view(batch_size * num_images_per_prompt, -1)
331
+
332
+ return prompt_embeds, pooled_prompt_embeds
333
+
334
+ # Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3.StableDiffusion3Pipeline.encode_prompt
335
+ def encode_prompt(
336
+ self,
337
+ prompt: Union[str, List[str]],
338
+ prompt_2: Union[str, List[str]],
339
+ prompt_3: Union[str, List[str]],
340
+ device: Optional[torch.device] = None,
341
+ num_images_per_prompt: int = 1,
342
+ do_classifier_free_guidance: bool = True,
343
+ negative_prompt: Optional[Union[str, List[str]]] = None,
344
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
345
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
346
+ prompt_embeds: Optional[torch.FloatTensor] = None,
347
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
348
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
349
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
350
+ clip_skip: Optional[int] = None,
351
+ max_sequence_length: int = 256,
352
+ ):
353
+ r"""
354
+
355
+ Args:
356
+ prompt (`str` or `List[str]`, *optional*):
357
+ prompt to be encoded
358
+ prompt_2 (`str` or `List[str]`, *optional*):
359
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
360
+ used in all text-encoders
361
+ prompt_3 (`str` or `List[str]`, *optional*):
362
+ The prompt or prompts to be sent to the `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
363
+ used in all text-encoders
364
+ device: (`torch.device`):
365
+ torch device
366
+ num_images_per_prompt (`int`):
367
+ number of images that should be generated per prompt
368
+ do_classifier_free_guidance (`bool`):
369
+ whether to use classifier free guidance or not
370
+ negative_prompt (`str` or `List[str]`, *optional*):
371
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
372
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
373
+ less than `1`).
374
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
375
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
376
+ `text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
377
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
378
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
379
+ `text_encoder_3`. If not defined, `negative_prompt` is used in both text-encoders
380
+ prompt_embeds (`torch.FloatTensor`, *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.FloatTensor`, *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
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
388
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
389
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
390
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
391
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
392
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
393
+ input argument.
394
+ clip_skip (`int`, *optional*):
395
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
396
+ the output of the pre-final layer will be used for computing the prompt embeddings.
397
+ """
398
+ device = device or self._execution_device
399
+
400
+ prompt = [prompt] if isinstance(prompt, str) else prompt
401
+ if prompt is not None:
402
+ batch_size = len(prompt)
403
+ else:
404
+ batch_size = prompt_embeds.shape[0]
405
+
406
+ if prompt_embeds is None:
407
+ prompt_2 = prompt_2 or prompt
408
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
409
+
410
+ prompt_3 = prompt_3 or prompt
411
+ prompt_3 = [prompt_3] if isinstance(prompt_3, str) else prompt_3
412
+
413
+ prompt_embed, pooled_prompt_embed = self._get_clip_prompt_embeds(
414
+ prompt=prompt,
415
+ device=device,
416
+ num_images_per_prompt=num_images_per_prompt,
417
+ clip_skip=clip_skip,
418
+ clip_model_index=0,
419
+ )
420
+ prompt_2_embed, pooled_prompt_2_embed = self._get_clip_prompt_embeds(
421
+ prompt=prompt_2,
422
+ device=device,
423
+ num_images_per_prompt=num_images_per_prompt,
424
+ clip_skip=clip_skip,
425
+ clip_model_index=1,
426
+ )
427
+ clip_prompt_embeds = torch.cat([prompt_embed, prompt_2_embed], dim=-1)
428
+
429
+ t5_prompt_embed = self._get_t5_prompt_embeds(
430
+ prompt=prompt_3,
431
+ num_images_per_prompt=num_images_per_prompt,
432
+ max_sequence_length=max_sequence_length,
433
+ device=device,
434
+ )
435
+
436
+ clip_prompt_embeds = torch.nn.functional.pad(
437
+ clip_prompt_embeds, (0, t5_prompt_embed.shape[-1] - clip_prompt_embeds.shape[-1])
438
+ )
439
+
440
+ prompt_embeds = torch.cat([clip_prompt_embeds, t5_prompt_embed], dim=-2)
441
+ pooled_prompt_embeds = torch.cat([pooled_prompt_embed, pooled_prompt_2_embed], dim=-1)
442
+
443
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
444
+ negative_prompt = negative_prompt or ""
445
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
446
+ negative_prompt_3 = negative_prompt_3 or negative_prompt
447
+
448
+ # normalize str to list
449
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
450
+ negative_prompt_2 = (
451
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
452
+ )
453
+ negative_prompt_3 = (
454
+ batch_size * [negative_prompt_3] if isinstance(negative_prompt_3, str) else negative_prompt_3
455
+ )
456
+
457
+ if prompt is not None and type(prompt) is not type(negative_prompt):
458
+ raise TypeError(
459
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
460
+ f" {type(prompt)}."
461
+ )
462
+ elif batch_size != len(negative_prompt):
463
+ raise ValueError(
464
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
465
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
466
+ " the batch size of `prompt`."
467
+ )
468
+
469
+ negative_prompt_embed, negative_pooled_prompt_embed = self._get_clip_prompt_embeds(
470
+ negative_prompt,
471
+ device=device,
472
+ num_images_per_prompt=num_images_per_prompt,
473
+ clip_skip=None,
474
+ clip_model_index=0,
475
+ )
476
+ negative_prompt_2_embed, negative_pooled_prompt_2_embed = self._get_clip_prompt_embeds(
477
+ negative_prompt_2,
478
+ device=device,
479
+ num_images_per_prompt=num_images_per_prompt,
480
+ clip_skip=None,
481
+ clip_model_index=1,
482
+ )
483
+ negative_clip_prompt_embeds = torch.cat([negative_prompt_embed, negative_prompt_2_embed], dim=-1)
484
+
485
+ t5_negative_prompt_embed = self._get_t5_prompt_embeds(
486
+ prompt=negative_prompt_3,
487
+ num_images_per_prompt=num_images_per_prompt,
488
+ max_sequence_length=max_sequence_length,
489
+ device=device,
490
+ )
491
+
492
+ negative_clip_prompt_embeds = torch.nn.functional.pad(
493
+ negative_clip_prompt_embeds,
494
+ (0, t5_negative_prompt_embed.shape[-1] - negative_clip_prompt_embeds.shape[-1]),
495
+ )
496
+
497
+ negative_prompt_embeds = torch.cat([negative_clip_prompt_embeds, t5_negative_prompt_embed], dim=-2)
498
+ negative_pooled_prompt_embeds = torch.cat(
499
+ [negative_pooled_prompt_embed, negative_pooled_prompt_2_embed], dim=-1
500
+ )
501
+
502
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
503
+
504
+ def check_inputs(
505
+ self,
506
+ prompt,
507
+ prompt_2,
508
+ prompt_3,
509
+ strength,
510
+ negative_prompt=None,
511
+ negative_prompt_2=None,
512
+ negative_prompt_3=None,
513
+ prompt_embeds=None,
514
+ negative_prompt_embeds=None,
515
+ pooled_prompt_embeds=None,
516
+ negative_pooled_prompt_embeds=None,
517
+ callback_on_step_end_tensor_inputs=None,
518
+ max_sequence_length=None,
519
+ ):
520
+ if strength < 0 or strength > 1:
521
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
522
+
523
+ if callback_on_step_end_tensor_inputs is not None and not all(
524
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
525
+ ):
526
+ raise ValueError(
527
+ 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]}"
528
+ )
529
+
530
+ if prompt is not None and prompt_embeds is not None:
531
+ raise ValueError(
532
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
533
+ " only forward one of the two."
534
+ )
535
+ elif prompt_2 is not None and prompt_embeds is not None:
536
+ raise ValueError(
537
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
538
+ " only forward one of the two."
539
+ )
540
+ elif prompt_3 is not None and prompt_embeds is not None:
541
+ raise ValueError(
542
+ f"Cannot forward both `prompt_3`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
543
+ " only forward one of the two."
544
+ )
545
+ elif prompt is None and prompt_embeds is None:
546
+ raise ValueError(
547
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
548
+ )
549
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
550
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
551
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
552
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
553
+ elif prompt_3 is not None and (not isinstance(prompt_3, str) and not isinstance(prompt_3, list)):
554
+ raise ValueError(f"`prompt_3` has to be of type `str` or `list` but is {type(prompt_3)}")
555
+
556
+ if negative_prompt is not None and negative_prompt_embeds is not None:
557
+ raise ValueError(
558
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
559
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
560
+ )
561
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
562
+ raise ValueError(
563
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
564
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
565
+ )
566
+ elif negative_prompt_3 is not None and negative_prompt_embeds is not None:
567
+ raise ValueError(
568
+ f"Cannot forward both `negative_prompt_3`: {negative_prompt_3} and `negative_prompt_embeds`:"
569
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
570
+ )
571
+
572
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
573
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
574
+ raise ValueError(
575
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
576
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
577
+ f" {negative_prompt_embeds.shape}."
578
+ )
579
+
580
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
581
+ raise ValueError(
582
+ "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`."
583
+ )
584
+
585
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
586
+ raise ValueError(
587
+ "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`."
588
+ )
589
+
590
+ if max_sequence_length is not None and max_sequence_length > 512:
591
+ raise ValueError(f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}")
592
+
593
+ def get_timesteps(self, num_inference_steps, strength, device):
594
+ # get the original timestep using init_timestep
595
+ init_timestep = min(num_inference_steps * strength, num_inference_steps)
596
+
597
+ t_start = int(max(num_inference_steps - init_timestep, 0))
598
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
599
+
600
+ return timesteps, num_inference_steps - t_start
601
+
602
+ def prepare_latents(
603
+ self, batch_size, num_channels_latents, height, width, image, timestep, dtype, device, generator=None
604
+ ):
605
+ shape = (
606
+ batch_size,
607
+ num_channels_latents,
608
+ int(height) // self.vae_scale_factor,
609
+ int(width) // self.vae_scale_factor,
610
+ )
611
+
612
+ image = image.to(device=device, dtype=dtype)
613
+
614
+ if isinstance(generator, list) and len(generator) != batch_size:
615
+ raise ValueError(
616
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
617
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
618
+ )
619
+ elif isinstance(generator, list):
620
+ init_latents = [
621
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i]) for i in range(batch_size)
622
+ ]
623
+ init_latents = torch.cat(init_latents, dim=0)
624
+ else:
625
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
626
+
627
+ init_latents = (init_latents - self.vae.config.shift_factor) * self.vae.config.scaling_factor
628
+
629
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
630
+ # expand init_latents for batch_size
631
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
632
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
633
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
634
+ raise ValueError(
635
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
636
+ )
637
+ else:
638
+ init_latents = torch.cat([init_latents], dim=0)
639
+
640
+ shape = init_latents.shape
641
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
642
+
643
+ init_latents = self.scheduler.scale_noise(init_latents, timestep, noise)
644
+ latents = init_latents.to(device=device, dtype=dtype)
645
+
646
+ return latents
647
+
648
+ @property
649
+ def guidance_scale(self):
650
+ return self._guidance_scale
651
+
652
+ @property
653
+ def clip_skip(self):
654
+ return self._clip_skip
655
+
656
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
657
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
658
+ # corresponds to doing no classifier free guidance.
659
+ @property
660
+ def do_classifier_free_guidance(self):
661
+ return self._guidance_scale > 1
662
+
663
+ @property
664
+ def num_timesteps(self):
665
+ return self._num_timesteps
666
+
667
+ @property
668
+ def interrupt(self):
669
+ return self._interrupt
670
+
671
+ @torch.no_grad()
672
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
673
+ def __call__(
674
+ self,
675
+ prompt: Union[str, List[str]] = None,
676
+ prompt_2: Optional[Union[str, List[str]]] = None,
677
+ prompt_3: Optional[Union[str, List[str]]] = None,
678
+ height: Optional[int] = None,
679
+ width: Optional[int] = None,
680
+ image: PipelineImageInput = None,
681
+ strength: float = 0.6,
682
+ num_inference_steps: int = 50,
683
+ timesteps: List[int] = None,
684
+ guidance_scale: float = 7.0,
685
+ negative_prompt: Optional[Union[str, List[str]]] = None,
686
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
687
+ negative_prompt_3: Optional[Union[str, List[str]]] = None,
688
+ num_images_per_prompt: Optional[int] = 1,
689
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
690
+ latents: Optional[torch.FloatTensor] = None,
691
+ prompt_embeds: Optional[torch.FloatTensor] = None,
692
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
693
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
694
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
695
+ output_type: Optional[str] = "pil",
696
+ return_dict: bool = True,
697
+ clip_skip: Optional[int] = None,
698
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
699
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
700
+ max_sequence_length: int = 256,
701
+ map: PipelineImageInput = None,
702
+ ):
703
+ r"""
704
+ Function invoked when calling the pipeline for generation.
705
+
706
+ Args:
707
+ prompt (`str` or `List[str]`, *optional*):
708
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
709
+ instead.
710
+ prompt_2 (`str` or `List[str]`, *optional*):
711
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
712
+ will be used instead
713
+ prompt_3 (`str` or `List[str]`, *optional*):
714
+ The prompt or prompts to be sent to `tokenizer_3` and `text_encoder_3`. If not defined, `prompt` is
715
+ will be used instead
716
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
717
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
718
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
719
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
720
+ num_inference_steps (`int`, *optional*, defaults to 50):
721
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
722
+ expense of slower inference.
723
+ timesteps (`List[int]`, *optional*):
724
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
725
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
726
+ passed will be used. Must be in descending order.
727
+ guidance_scale (`float`, *optional*, defaults to 5.0):
728
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
729
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
730
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
731
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
732
+ usually at the expense of lower image quality.
733
+ negative_prompt (`str` or `List[str]`, *optional*):
734
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
735
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
736
+ less than `1`).
737
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
738
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
739
+ `text_encoder_2`. If not defined, `negative_prompt` is used instead
740
+ negative_prompt_3 (`str` or `List[str]`, *optional*):
741
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_3` and
742
+ `text_encoder_3`. If not defined, `negative_prompt` is used instead
743
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
744
+ The number of images to generate per prompt.
745
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
746
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
747
+ to make generation deterministic.
748
+ latents (`torch.FloatTensor`, *optional*):
749
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
750
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
751
+ tensor will ge generated by sampling using the supplied random `generator`.
752
+ prompt_embeds (`torch.FloatTensor`, *optional*):
753
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
754
+ provided, text embeddings will be generated from `prompt` input argument.
755
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
756
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
757
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
758
+ argument.
759
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
760
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
761
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
762
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
763
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
764
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
765
+ input argument.
766
+ output_type (`str`, *optional*, defaults to `"pil"`):
767
+ The output format of the generate image. Choose between
768
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
769
+ return_dict (`bool`, *optional*, defaults to `True`):
770
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
771
+ of a plain tuple.
772
+ callback_on_step_end (`Callable`, *optional*):
773
+ A function that calls at the end of each denoising steps during the inference. The function is called
774
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
775
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
776
+ `callback_on_step_end_tensor_inputs`.
777
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
778
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
779
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
780
+ `._callback_tensor_inputs` attribute of your pipeline class.
781
+ max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
782
+
783
+ Examples:
784
+
785
+ Returns:
786
+ [`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] or `tuple`:
787
+ [`~pipelines.stable_diffusion_3.StableDiffusion3PipelineOutput`] if `return_dict` is True, otherwise a
788
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
789
+ """
790
+
791
+ # 0. Default height and width
792
+ height = height or self.default_sample_size * self.vae_scale_factor
793
+ width = width or self.default_sample_size * self.vae_scale_factor
794
+
795
+ # 1. Check inputs. Raise error if not correct
796
+ self.check_inputs(
797
+ prompt,
798
+ prompt_2,
799
+ prompt_3,
800
+ strength,
801
+ negative_prompt=negative_prompt,
802
+ negative_prompt_2=negative_prompt_2,
803
+ negative_prompt_3=negative_prompt_3,
804
+ prompt_embeds=prompt_embeds,
805
+ negative_prompt_embeds=negative_prompt_embeds,
806
+ pooled_prompt_embeds=pooled_prompt_embeds,
807
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
808
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
809
+ max_sequence_length=max_sequence_length,
810
+ )
811
+
812
+ self._guidance_scale = guidance_scale
813
+ self._clip_skip = clip_skip
814
+ self._interrupt = False
815
+
816
+ # 2. Define call parameters
817
+ if prompt is not None and isinstance(prompt, str):
818
+ batch_size = 1
819
+ elif prompt is not None and isinstance(prompt, list):
820
+ batch_size = len(prompt)
821
+ else:
822
+ batch_size = prompt_embeds.shape[0]
823
+
824
+ device = self._execution_device
825
+
826
+ (
827
+ prompt_embeds,
828
+ negative_prompt_embeds,
829
+ pooled_prompt_embeds,
830
+ negative_pooled_prompt_embeds,
831
+ ) = self.encode_prompt(
832
+ prompt=prompt,
833
+ prompt_2=prompt_2,
834
+ prompt_3=prompt_3,
835
+ negative_prompt=negative_prompt,
836
+ negative_prompt_2=negative_prompt_2,
837
+ negative_prompt_3=negative_prompt_3,
838
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
839
+ prompt_embeds=prompt_embeds,
840
+ negative_prompt_embeds=negative_prompt_embeds,
841
+ pooled_prompt_embeds=pooled_prompt_embeds,
842
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
843
+ device=device,
844
+ clip_skip=self.clip_skip,
845
+ num_images_per_prompt=num_images_per_prompt,
846
+ max_sequence_length=max_sequence_length,
847
+ )
848
+
849
+ if self.do_classifier_free_guidance:
850
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
851
+ pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim=0)
852
+
853
+ # 3. Preprocess image
854
+ init_image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
855
+
856
+ map = self.mask_processor.preprocess(
857
+ map, height=height // self.vae_scale_factor, width=width // self.vae_scale_factor
858
+ ).to(device)
859
+
860
+ # 4. Prepare timesteps
861
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
862
+
863
+ # begin diff diff change
864
+ total_time_steps = num_inference_steps
865
+ # end diff diff change
866
+
867
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
868
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
869
+
870
+ # 5. Prepare latent variables
871
+ num_channels_latents = self.transformer.config.in_channels
872
+ if latents is None:
873
+ latents = self.prepare_latents(
874
+ batch_size * num_images_per_prompt,
875
+ num_channels_latents,
876
+ height,
877
+ width,
878
+ init_image,
879
+ latent_timestep,
880
+ prompt_embeds.dtype,
881
+ device,
882
+ generator,
883
+ )
884
+
885
+ # 6. Denoising loop
886
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
887
+ self._num_timesteps = len(timesteps)
888
+
889
+ # preparations for diff diff
890
+ original_with_noise = self.prepare_latents(
891
+ batch_size * num_images_per_prompt,
892
+ num_channels_latents,
893
+ height,
894
+ width,
895
+ init_image,
896
+ timesteps,
897
+ prompt_embeds.dtype,
898
+ device,
899
+ generator,
900
+ )
901
+ thresholds = torch.arange(total_time_steps, dtype=map.dtype) / total_time_steps
902
+ thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(device)
903
+ masks = map.squeeze() > thresholds
904
+ # end diff diff preparations
905
+
906
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
907
+ for i, t in enumerate(timesteps):
908
+ if self.interrupt:
909
+ continue
910
+
911
+ # diff diff
912
+ if i == 0:
913
+ latents = original_with_noise[:1]
914
+ else:
915
+ mask = masks[i].unsqueeze(0).to(latents.dtype)
916
+ mask = mask.unsqueeze(1) # fit shape
917
+ latents = original_with_noise[i] * mask + latents * (1 - mask)
918
+ # end diff diff
919
+
920
+ # expand the latents if we are doing classifier free guidance
921
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
922
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
923
+ timestep = t.expand(latent_model_input.shape[0])
924
+
925
+ noise_pred = self.transformer(
926
+ hidden_states=latent_model_input,
927
+ timestep=timestep,
928
+ encoder_hidden_states=prompt_embeds,
929
+ pooled_projections=pooled_prompt_embeds,
930
+ return_dict=False,
931
+ )[0]
932
+
933
+ # perform guidance
934
+ if self.do_classifier_free_guidance:
935
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
936
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
937
+
938
+ # compute the previous noisy sample x_t -> x_t-1
939
+ latents_dtype = latents.dtype
940
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
941
+
942
+ if latents.dtype != latents_dtype:
943
+ if torch.backends.mps.is_available():
944
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
945
+ latents = latents.to(latents_dtype)
946
+
947
+ if callback_on_step_end is not None:
948
+ callback_kwargs = {}
949
+ for k in callback_on_step_end_tensor_inputs:
950
+ callback_kwargs[k] = locals()[k]
951
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
952
+
953
+ latents = callback_outputs.pop("latents", latents)
954
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
955
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
956
+ negative_pooled_prompt_embeds = callback_outputs.pop(
957
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
958
+ )
959
+
960
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
961
+ progress_bar.update()
962
+
963
+ if XLA_AVAILABLE:
964
+ xm.mark_step()
965
+
966
+ if output_type == "latent":
967
+ image = latents
968
+
969
+ else:
970
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
971
+
972
+ image = self.vae.decode(latents, return_dict=False)[0]
973
+ image = self.image_processor.postprocess(image, output_type=output_type)
974
+
975
+ # Offload all models
976
+ self.maybe_free_model_hooks()
977
+
978
+ if not return_dict:
979
+ return (image,)
980
+
981
+ return StableDiffusion3PipelineOutput(images=image)
v0.30.0/pipeline_stable_diffusion_boxdiff.py ADDED
@@ -0,0 +1,1705 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Jingyang Zhang 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 abc
16
+ import inspect
17
+ import math
18
+ import numbers
19
+ from typing import Any, Callable, Dict, List, Optional, Union
20
+
21
+ import numpy as np
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from packaging import version
26
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
27
+
28
+ from diffusers.configuration_utils import FrozenDict
29
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
30
+ from diffusers.loaders import (
31
+ FromSingleFileMixin,
32
+ IPAdapterMixin,
33
+ StableDiffusionLoraLoaderMixin,
34
+ TextualInversionLoaderMixin,
35
+ )
36
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
37
+ from diffusers.models.attention_processor import Attention, FusedAttnProcessor2_0
38
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
39
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
40
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
41
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
42
+ from diffusers.schedulers import KarrasDiffusionSchedulers
43
+ from diffusers.utils import (
44
+ USE_PEFT_BACKEND,
45
+ deprecate,
46
+ logging,
47
+ replace_example_docstring,
48
+ scale_lora_layers,
49
+ unscale_lora_layers,
50
+ )
51
+ from diffusers.utils.torch_utils import randn_tensor
52
+
53
+
54
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
55
+
56
+ EXAMPLE_DOC_STRING = """
57
+ Examples:
58
+ ```py
59
+ >>> import torch
60
+ >>> from diffusers import StableDiffusionPipeline
61
+
62
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
63
+ >>> pipe = pipe.to("cuda")
64
+
65
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
66
+ >>> image = pipe(prompt).images[0]
67
+ ```
68
+ """
69
+
70
+
71
+ class GaussianSmoothing(nn.Module):
72
+ """
73
+ Copied from official repo: https://github.com/showlab/BoxDiff/blob/master/utils/gaussian_smoothing.py
74
+ Apply gaussian smoothing on a
75
+ 1d, 2d or 3d tensor. Filtering is performed seperately for each channel
76
+ in the input using a depthwise convolution.
77
+ Arguments:
78
+ channels (int, sequence): Number of channels of the input tensors. Output will
79
+ have this number of channels as well.
80
+ kernel_size (int, sequence): Size of the gaussian kernel.
81
+ sigma (float, sequence): Standard deviation of the gaussian kernel.
82
+ dim (int, optional): The number of dimensions of the data.
83
+ Default value is 2 (spatial).
84
+ """
85
+
86
+ def __init__(self, channels, kernel_size, sigma, dim=2):
87
+ super(GaussianSmoothing, self).__init__()
88
+ if isinstance(kernel_size, numbers.Number):
89
+ kernel_size = [kernel_size] * dim
90
+ if isinstance(sigma, numbers.Number):
91
+ sigma = [sigma] * dim
92
+
93
+ # The gaussian kernel is the product of the
94
+ # gaussian function of each dimension.
95
+ kernel = 1
96
+ meshgrids = torch.meshgrid([torch.arange(size, dtype=torch.float32) for size in kernel_size])
97
+ for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
98
+ mean = (size - 1) / 2
99
+ kernel *= 1 / (std * math.sqrt(2 * math.pi)) * torch.exp(-(((mgrid - mean) / (2 * std)) ** 2))
100
+
101
+ # Make sure sum of values in gaussian kernel equals 1.
102
+ kernel = kernel / torch.sum(kernel)
103
+
104
+ # Reshape to depthwise convolutional weight
105
+ kernel = kernel.view(1, 1, *kernel.size())
106
+ kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
107
+
108
+ self.register_buffer("weight", kernel)
109
+ self.groups = channels
110
+
111
+ if dim == 1:
112
+ self.conv = F.conv1d
113
+ elif dim == 2:
114
+ self.conv = F.conv2d
115
+ elif dim == 3:
116
+ self.conv = F.conv3d
117
+ else:
118
+ raise RuntimeError("Only 1, 2 and 3 dimensions are supported. Received {}.".format(dim))
119
+
120
+ def forward(self, input):
121
+ """
122
+ Apply gaussian filter to input.
123
+ Arguments:
124
+ input (torch.Tensor): Input to apply gaussian filter on.
125
+ Returns:
126
+ filtered (torch.Tensor): Filtered output.
127
+ """
128
+ return self.conv(input, weight=self.weight.to(input.dtype), groups=self.groups)
129
+
130
+
131
+ class AttendExciteCrossAttnProcessor:
132
+ def __init__(self, attnstore, place_in_unet):
133
+ super().__init__()
134
+ self.attnstore = attnstore
135
+ self.place_in_unet = place_in_unet
136
+
137
+ def __call__(
138
+ self,
139
+ attn: Attention,
140
+ hidden_states: torch.FloatTensor,
141
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
142
+ attention_mask: Optional[torch.FloatTensor] = None,
143
+ ) -> torch.Tensor:
144
+ batch_size, sequence_length, _ = hidden_states.shape
145
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size=1)
146
+ query = attn.to_q(hidden_states)
147
+
148
+ is_cross = encoder_hidden_states is not None
149
+ encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states
150
+ key = attn.to_k(encoder_hidden_states)
151
+ value = attn.to_v(encoder_hidden_states)
152
+
153
+ query = attn.head_to_batch_dim(query)
154
+ key = attn.head_to_batch_dim(key)
155
+ value = attn.head_to_batch_dim(value)
156
+
157
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
158
+ self.attnstore(attention_probs, is_cross, self.place_in_unet)
159
+
160
+ hidden_states = torch.bmm(attention_probs, value)
161
+ hidden_states = attn.batch_to_head_dim(hidden_states)
162
+
163
+ # linear proj
164
+ hidden_states = attn.to_out[0](hidden_states)
165
+ # dropout
166
+ hidden_states = attn.to_out[1](hidden_states)
167
+
168
+ return hidden_states
169
+
170
+
171
+ class AttentionControl(abc.ABC):
172
+ def step_callback(self, x_t):
173
+ return x_t
174
+
175
+ def between_steps(self):
176
+ return
177
+
178
+ # @property
179
+ # def num_uncond_att_layers(self):
180
+ # return 0
181
+
182
+ @abc.abstractmethod
183
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
184
+ raise NotImplementedError
185
+
186
+ def __call__(self, attn, is_cross: bool, place_in_unet: str):
187
+ if self.cur_att_layer >= self.num_uncond_att_layers:
188
+ self.forward(attn, is_cross, place_in_unet)
189
+ self.cur_att_layer += 1
190
+ if self.cur_att_layer == self.num_att_layers + self.num_uncond_att_layers:
191
+ self.cur_att_layer = 0
192
+ self.cur_step += 1
193
+ self.between_steps()
194
+
195
+ def reset(self):
196
+ self.cur_step = 0
197
+ self.cur_att_layer = 0
198
+
199
+ def __init__(self):
200
+ self.cur_step = 0
201
+ self.num_att_layers = -1
202
+ self.cur_att_layer = 0
203
+
204
+
205
+ class AttentionStore(AttentionControl):
206
+ @staticmethod
207
+ def get_empty_store():
208
+ return {"down_cross": [], "mid_cross": [], "up_cross": [], "down_self": [], "mid_self": [], "up_self": []}
209
+
210
+ def forward(self, attn, is_cross: bool, place_in_unet: str):
211
+ key = f"{place_in_unet}_{'cross' if is_cross else 'self'}"
212
+ if attn.shape[1] <= 32**2: # avoid memory overhead
213
+ self.step_store[key].append(attn)
214
+ return attn
215
+
216
+ def between_steps(self):
217
+ self.attention_store = self.step_store
218
+ if self.save_global_store:
219
+ with torch.no_grad():
220
+ if len(self.global_store) == 0:
221
+ self.global_store = self.step_store
222
+ else:
223
+ for key in self.global_store:
224
+ for i in range(len(self.global_store[key])):
225
+ self.global_store[key][i] += self.step_store[key][i].detach()
226
+ self.step_store = self.get_empty_store()
227
+ self.step_store = self.get_empty_store()
228
+
229
+ def get_average_attention(self):
230
+ average_attention = self.attention_store
231
+ return average_attention
232
+
233
+ def get_average_global_attention(self):
234
+ average_attention = {
235
+ key: [item / self.cur_step for item in self.global_store[key]] for key in self.attention_store
236
+ }
237
+ return average_attention
238
+
239
+ def reset(self):
240
+ super(AttentionStore, self).reset()
241
+ self.step_store = self.get_empty_store()
242
+ self.attention_store = {}
243
+ self.global_store = {}
244
+
245
+ def __init__(self, save_global_store=False):
246
+ """
247
+ Initialize an empty AttentionStore
248
+ :param step_index: used to visualize only a specific step in the diffusion process
249
+ """
250
+ super(AttentionStore, self).__init__()
251
+ self.save_global_store = save_global_store
252
+ self.step_store = self.get_empty_store()
253
+ self.attention_store = {}
254
+ self.global_store = {}
255
+ self.curr_step_index = 0
256
+ self.num_uncond_att_layers = 0
257
+
258
+
259
+ def aggregate_attention(
260
+ attention_store: AttentionStore, res: int, from_where: List[str], is_cross: bool, select: int
261
+ ) -> torch.Tensor:
262
+ """Aggregates the attention across the different layers and heads at the specified resolution."""
263
+ out = []
264
+ attention_maps = attention_store.get_average_attention()
265
+
266
+ # for k, v in attention_maps.items():
267
+ # for vv in v:
268
+ # print(vv.shape)
269
+ # exit()
270
+
271
+ num_pixels = res**2
272
+ for location in from_where:
273
+ for item in attention_maps[f"{location}_{'cross' if is_cross else 'self'}"]:
274
+ if item.shape[1] == num_pixels:
275
+ cross_maps = item.reshape(1, -1, res, res, item.shape[-1])[select]
276
+ out.append(cross_maps)
277
+ out = torch.cat(out, dim=0)
278
+ out = out.sum(0) / out.shape[0]
279
+ return out
280
+
281
+
282
+ def register_attention_control(model, controller):
283
+ attn_procs = {}
284
+ cross_att_count = 0
285
+ for name in model.unet.attn_processors.keys():
286
+ # cross_attention_dim = None if name.endswith("attn1.processor") else model.unet.config.cross_attention_dim
287
+ if name.startswith("mid_block"):
288
+ # hidden_size = model.unet.config.block_out_channels[-1]
289
+ place_in_unet = "mid"
290
+ elif name.startswith("up_blocks"):
291
+ # block_id = int(name[len("up_blocks.")])
292
+ # hidden_size = list(reversed(model.unet.config.block_out_channels))[block_id]
293
+ place_in_unet = "up"
294
+ elif name.startswith("down_blocks"):
295
+ # block_id = int(name[len("down_blocks.")])
296
+ # hidden_size = model.unet.config.block_out_channels[block_id]
297
+ place_in_unet = "down"
298
+ else:
299
+ continue
300
+
301
+ cross_att_count += 1
302
+ attn_procs[name] = AttendExciteCrossAttnProcessor(attnstore=controller, place_in_unet=place_in_unet)
303
+ model.unet.set_attn_processor(attn_procs)
304
+ controller.num_att_layers = cross_att_count
305
+
306
+
307
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
308
+ """
309
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
310
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
311
+ """
312
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
313
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
314
+ # rescale the results from guidance (fixes overexposure)
315
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
316
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
317
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
318
+ return noise_cfg
319
+
320
+
321
+ def retrieve_timesteps(
322
+ scheduler,
323
+ num_inference_steps: Optional[int] = None,
324
+ device: Optional[Union[str, torch.device]] = None,
325
+ timesteps: Optional[List[int]] = None,
326
+ **kwargs,
327
+ ):
328
+ """
329
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
330
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
331
+
332
+ Args:
333
+ scheduler (`SchedulerMixin`):
334
+ The scheduler to get timesteps from.
335
+ num_inference_steps (`int`):
336
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
337
+ `timesteps` must be `None`.
338
+ device (`str` or `torch.device`, *optional*):
339
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
340
+ timesteps (`List[int]`, *optional*):
341
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
342
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
343
+ must be `None`.
344
+
345
+ Returns:
346
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
347
+ second element is the number of inference steps.
348
+ """
349
+ if timesteps is not None:
350
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
351
+ if not accepts_timesteps:
352
+ raise ValueError(
353
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
354
+ f" timestep schedules. Please check whether you are using the correct scheduler."
355
+ )
356
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
357
+ timesteps = scheduler.timesteps
358
+ num_inference_steps = len(timesteps)
359
+ else:
360
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
361
+ timesteps = scheduler.timesteps
362
+ return timesteps, num_inference_steps
363
+
364
+
365
+ class StableDiffusionBoxDiffPipeline(
366
+ DiffusionPipeline, TextualInversionLoaderMixin, StableDiffusionLoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
367
+ ):
368
+ r"""
369
+ Pipeline for text-to-image generation using Stable Diffusion with BoxDiff.
370
+
371
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
372
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
373
+
374
+ The pipeline also inherits the following loading methods:
375
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
376
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
377
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
378
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
379
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
380
+
381
+ Args:
382
+ vae ([`AutoencoderKL`]):
383
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
384
+ text_encoder ([`~transformers.CLIPTextModel`]):
385
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
386
+ tokenizer ([`~transformers.CLIPTokenizer`]):
387
+ A `CLIPTokenizer` to tokenize text.
388
+ unet ([`UNet2DConditionModel`]):
389
+ A `UNet2DConditionModel` to denoise the encoded image latents.
390
+ scheduler ([`SchedulerMixin`]):
391
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
392
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
393
+ safety_checker ([`StableDiffusionSafetyChecker`]):
394
+ Classification module that estimates whether generated images could be considered offensive or harmful.
395
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
396
+ about a model's potential harms.
397
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
398
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
399
+ """
400
+
401
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
402
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
403
+ _exclude_from_cpu_offload = ["safety_checker"]
404
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
405
+
406
+ def __init__(
407
+ self,
408
+ vae: AutoencoderKL,
409
+ text_encoder: CLIPTextModel,
410
+ tokenizer: CLIPTokenizer,
411
+ unet: UNet2DConditionModel,
412
+ scheduler: KarrasDiffusionSchedulers,
413
+ safety_checker: StableDiffusionSafetyChecker,
414
+ feature_extractor: CLIPImageProcessor,
415
+ image_encoder: CLIPVisionModelWithProjection = None,
416
+ requires_safety_checker: bool = True,
417
+ ):
418
+ super().__init__()
419
+
420
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
421
+ deprecation_message = (
422
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
423
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
424
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
425
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
426
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
427
+ " file"
428
+ )
429
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
430
+ new_config = dict(scheduler.config)
431
+ new_config["steps_offset"] = 1
432
+ scheduler._internal_dict = FrozenDict(new_config)
433
+
434
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
435
+ deprecation_message = (
436
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
437
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
438
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
439
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
440
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
441
+ )
442
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
443
+ new_config = dict(scheduler.config)
444
+ new_config["clip_sample"] = False
445
+ scheduler._internal_dict = FrozenDict(new_config)
446
+
447
+ if safety_checker is None and requires_safety_checker:
448
+ logger.warning(
449
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
450
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
451
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
452
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
453
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
454
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
455
+ )
456
+
457
+ if safety_checker is not None and feature_extractor is None:
458
+ raise ValueError(
459
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
460
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
461
+ )
462
+
463
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
464
+ version.parse(unet.config._diffusers_version).base_version
465
+ ) < version.parse("0.9.0.dev0")
466
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
467
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
468
+ deprecation_message = (
469
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
470
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
471
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
472
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
473
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
474
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
475
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
476
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
477
+ " the `unet/config.json` file"
478
+ )
479
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
480
+ new_config = dict(unet.config)
481
+ new_config["sample_size"] = 64
482
+ unet._internal_dict = FrozenDict(new_config)
483
+
484
+ self.register_modules(
485
+ vae=vae,
486
+ text_encoder=text_encoder,
487
+ tokenizer=tokenizer,
488
+ unet=unet,
489
+ scheduler=scheduler,
490
+ safety_checker=safety_checker,
491
+ feature_extractor=feature_extractor,
492
+ image_encoder=image_encoder,
493
+ )
494
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
495
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
496
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
497
+
498
+ def enable_vae_slicing(self):
499
+ r"""
500
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
501
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
502
+ """
503
+ self.vae.enable_slicing()
504
+
505
+ def disable_vae_slicing(self):
506
+ r"""
507
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
508
+ computing decoding in one step.
509
+ """
510
+ self.vae.disable_slicing()
511
+
512
+ def enable_vae_tiling(self):
513
+ r"""
514
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
515
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
516
+ processing larger images.
517
+ """
518
+ self.vae.enable_tiling()
519
+
520
+ def disable_vae_tiling(self):
521
+ r"""
522
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
523
+ computing decoding in one step.
524
+ """
525
+ self.vae.disable_tiling()
526
+
527
+ def _encode_prompt(
528
+ self,
529
+ prompt,
530
+ device,
531
+ num_images_per_prompt,
532
+ do_classifier_free_guidance,
533
+ negative_prompt=None,
534
+ prompt_embeds: Optional[torch.FloatTensor] = None,
535
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
536
+ lora_scale: Optional[float] = None,
537
+ **kwargs,
538
+ ):
539
+ 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."
540
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
541
+
542
+ prompt_embeds_tuple = self.encode_prompt(
543
+ prompt=prompt,
544
+ device=device,
545
+ num_images_per_prompt=num_images_per_prompt,
546
+ do_classifier_free_guidance=do_classifier_free_guidance,
547
+ negative_prompt=negative_prompt,
548
+ prompt_embeds=prompt_embeds,
549
+ negative_prompt_embeds=negative_prompt_embeds,
550
+ lora_scale=lora_scale,
551
+ **kwargs,
552
+ )
553
+
554
+ # concatenate for backwards comp
555
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
556
+
557
+ return prompt_embeds
558
+
559
+ def encode_prompt(
560
+ self,
561
+ prompt,
562
+ device,
563
+ num_images_per_prompt,
564
+ do_classifier_free_guidance,
565
+ negative_prompt=None,
566
+ prompt_embeds: Optional[torch.FloatTensor] = None,
567
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
568
+ lora_scale: Optional[float] = None,
569
+ clip_skip: Optional[int] = None,
570
+ ):
571
+ r"""
572
+ Encodes the prompt into text encoder hidden states.
573
+
574
+ Args:
575
+ prompt (`str` or `List[str]`, *optional*):
576
+ prompt to be encoded
577
+ device: (`torch.device`):
578
+ torch device
579
+ num_images_per_prompt (`int`):
580
+ number of images that should be generated per prompt
581
+ do_classifier_free_guidance (`bool`):
582
+ whether to use classifier free guidance or not
583
+ negative_prompt (`str` or `List[str]`, *optional*):
584
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
585
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
586
+ less than `1`).
587
+ prompt_embeds (`torch.FloatTensor`, *optional*):
588
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
589
+ provided, text embeddings will be generated from `prompt` input argument.
590
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
591
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
592
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
593
+ argument.
594
+ lora_scale (`float`, *optional*):
595
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
596
+ clip_skip (`int`, *optional*):
597
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
598
+ the output of the pre-final layer will be used for computing the prompt embeddings.
599
+ """
600
+ # set lora scale so that monkey patched LoRA
601
+ # function of text encoder can correctly access it
602
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
603
+ self._lora_scale = lora_scale
604
+
605
+ # dynamically adjust the LoRA scale
606
+ if not USE_PEFT_BACKEND:
607
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
608
+ else:
609
+ scale_lora_layers(self.text_encoder, lora_scale)
610
+
611
+ if prompt is not None and isinstance(prompt, str):
612
+ batch_size = 1
613
+ elif prompt is not None and isinstance(prompt, list):
614
+ batch_size = len(prompt)
615
+ else:
616
+ batch_size = prompt_embeds.shape[0]
617
+
618
+ if prompt_embeds is None:
619
+ # textual inversion: procecss multi-vector tokens if necessary
620
+ if isinstance(self, TextualInversionLoaderMixin):
621
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
622
+
623
+ text_inputs = self.tokenizer(
624
+ prompt,
625
+ padding="max_length",
626
+ max_length=self.tokenizer.model_max_length,
627
+ truncation=True,
628
+ return_tensors="pt",
629
+ )
630
+ text_input_ids = text_inputs.input_ids
631
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
632
+
633
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
634
+ text_input_ids, untruncated_ids
635
+ ):
636
+ removed_text = self.tokenizer.batch_decode(
637
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
638
+ )
639
+ logger.warning(
640
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
641
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
642
+ )
643
+
644
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
645
+ attention_mask = text_inputs.attention_mask.to(device)
646
+ else:
647
+ attention_mask = None
648
+
649
+ if clip_skip is None:
650
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
651
+ prompt_embeds = prompt_embeds[0]
652
+ else:
653
+ prompt_embeds = self.text_encoder(
654
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
655
+ )
656
+ # Access the `hidden_states` first, that contains a tuple of
657
+ # all the hidden states from the encoder layers. Then index into
658
+ # the tuple to access the hidden states from the desired layer.
659
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
660
+ # We also need to apply the final LayerNorm here to not mess with the
661
+ # representations. The `last_hidden_states` that we typically use for
662
+ # obtaining the final prompt representations passes through the LayerNorm
663
+ # layer.
664
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
665
+
666
+ if self.text_encoder is not None:
667
+ prompt_embeds_dtype = self.text_encoder.dtype
668
+ elif self.unet is not None:
669
+ prompt_embeds_dtype = self.unet.dtype
670
+ else:
671
+ prompt_embeds_dtype = prompt_embeds.dtype
672
+
673
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
674
+
675
+ bs_embed, seq_len, _ = prompt_embeds.shape
676
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
677
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
678
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
679
+
680
+ # get unconditional embeddings for classifier free guidance
681
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
682
+ uncond_tokens: List[str]
683
+ if negative_prompt is None:
684
+ uncond_tokens = [""] * batch_size
685
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
686
+ raise TypeError(
687
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
688
+ f" {type(prompt)}."
689
+ )
690
+ elif isinstance(negative_prompt, str):
691
+ uncond_tokens = [negative_prompt]
692
+ elif batch_size != len(negative_prompt):
693
+ raise ValueError(
694
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
695
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
696
+ " the batch size of `prompt`."
697
+ )
698
+ else:
699
+ uncond_tokens = negative_prompt
700
+
701
+ # textual inversion: procecss multi-vector tokens if necessary
702
+ if isinstance(self, TextualInversionLoaderMixin):
703
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
704
+
705
+ max_length = prompt_embeds.shape[1]
706
+ uncond_input = self.tokenizer(
707
+ uncond_tokens,
708
+ padding="max_length",
709
+ max_length=max_length,
710
+ truncation=True,
711
+ return_tensors="pt",
712
+ )
713
+
714
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
715
+ attention_mask = uncond_input.attention_mask.to(device)
716
+ else:
717
+ attention_mask = None
718
+
719
+ negative_prompt_embeds = self.text_encoder(
720
+ uncond_input.input_ids.to(device),
721
+ attention_mask=attention_mask,
722
+ )
723
+ negative_prompt_embeds = negative_prompt_embeds[0]
724
+
725
+ if do_classifier_free_guidance:
726
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
727
+ seq_len = negative_prompt_embeds.shape[1]
728
+
729
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
730
+
731
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
732
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
733
+
734
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
735
+ # Retrieve the original scale by scaling back the LoRA layers
736
+ unscale_lora_layers(self.text_encoder, lora_scale)
737
+
738
+ return text_inputs, prompt_embeds, negative_prompt_embeds
739
+
740
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
741
+ dtype = next(self.image_encoder.parameters()).dtype
742
+
743
+ if not isinstance(image, torch.Tensor):
744
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
745
+
746
+ image = image.to(device=device, dtype=dtype)
747
+ if output_hidden_states:
748
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
749
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
750
+ uncond_image_enc_hidden_states = self.image_encoder(
751
+ torch.zeros_like(image), output_hidden_states=True
752
+ ).hidden_states[-2]
753
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
754
+ num_images_per_prompt, dim=0
755
+ )
756
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
757
+ else:
758
+ image_embeds = self.image_encoder(image).image_embeds
759
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
760
+ uncond_image_embeds = torch.zeros_like(image_embeds)
761
+
762
+ return image_embeds, uncond_image_embeds
763
+
764
+ def run_safety_checker(self, image, device, dtype):
765
+ if self.safety_checker is None:
766
+ has_nsfw_concept = None
767
+ else:
768
+ if torch.is_tensor(image):
769
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
770
+ else:
771
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
772
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
773
+ image, has_nsfw_concept = self.safety_checker(
774
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
775
+ )
776
+ return image, has_nsfw_concept
777
+
778
+ def decode_latents(self, latents):
779
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
780
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
781
+
782
+ latents = 1 / self.vae.config.scaling_factor * latents
783
+ image = self.vae.decode(latents, return_dict=False)[0]
784
+ image = (image / 2 + 0.5).clamp(0, 1)
785
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
786
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
787
+ return image
788
+
789
+ def prepare_extra_step_kwargs(self, generator, eta):
790
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
791
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
792
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
793
+ # and should be between [0, 1]
794
+
795
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
796
+ extra_step_kwargs = {}
797
+ if accepts_eta:
798
+ extra_step_kwargs["eta"] = eta
799
+
800
+ # check if the scheduler accepts generator
801
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
802
+ if accepts_generator:
803
+ extra_step_kwargs["generator"] = generator
804
+ return extra_step_kwargs
805
+
806
+ def check_inputs(
807
+ self,
808
+ prompt,
809
+ height,
810
+ width,
811
+ boxdiff_phrases,
812
+ boxdiff_boxes,
813
+ callback_steps,
814
+ negative_prompt=None,
815
+ prompt_embeds=None,
816
+ negative_prompt_embeds=None,
817
+ callback_on_step_end_tensor_inputs=None,
818
+ ):
819
+ if height % 8 != 0 or width % 8 != 0:
820
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
821
+
822
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
823
+ raise ValueError(
824
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
825
+ f" {type(callback_steps)}."
826
+ )
827
+ if callback_on_step_end_tensor_inputs is not None and not all(
828
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
829
+ ):
830
+ raise ValueError(
831
+ 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]}"
832
+ )
833
+
834
+ if prompt is not None and prompt_embeds is not None:
835
+ raise ValueError(
836
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
837
+ " only forward one of the two."
838
+ )
839
+ elif prompt is None and prompt_embeds is None:
840
+ raise ValueError(
841
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
842
+ )
843
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
844
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
845
+
846
+ if negative_prompt is not None and negative_prompt_embeds is not None:
847
+ raise ValueError(
848
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
849
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
850
+ )
851
+
852
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
853
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
854
+ raise ValueError(
855
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
856
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
857
+ f" {negative_prompt_embeds.shape}."
858
+ )
859
+
860
+ if boxdiff_phrases is not None or boxdiff_boxes is not None:
861
+ if not (boxdiff_phrases is not None and boxdiff_boxes is not None):
862
+ raise ValueError("Either both `boxdiff_phrases` and `boxdiff_boxes` must be passed or none of them.")
863
+
864
+ if not isinstance(boxdiff_phrases, list) or not isinstance(boxdiff_boxes, list):
865
+ raise ValueError("`boxdiff_phrases` and `boxdiff_boxes` must be lists.")
866
+
867
+ if len(boxdiff_phrases) != len(boxdiff_boxes):
868
+ raise ValueError(
869
+ "`boxdiff_phrases` and `boxdiff_boxes` must have the same length,"
870
+ f" got: `boxdiff_phrases` {len(boxdiff_phrases)} != `boxdiff_boxes`"
871
+ f" {len(boxdiff_boxes)}."
872
+ )
873
+
874
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
875
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
876
+ if isinstance(generator, list) and len(generator) != batch_size:
877
+ raise ValueError(
878
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
879
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
880
+ )
881
+
882
+ if latents is None:
883
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
884
+ else:
885
+ latents = latents.to(device)
886
+
887
+ # scale the initial noise by the standard deviation required by the scheduler
888
+ latents = latents * self.scheduler.init_noise_sigma
889
+ return latents
890
+
891
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
892
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
893
+
894
+ The suffixes after the scaling factors represent the stages where they are being applied.
895
+
896
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
897
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
898
+
899
+ Args:
900
+ s1 (`float`):
901
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
902
+ mitigate "oversmoothing effect" in the enhanced denoising process.
903
+ s2 (`float`):
904
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
905
+ mitigate "oversmoothing effect" in the enhanced denoising process.
906
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
907
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
908
+ """
909
+ if not hasattr(self, "unet"):
910
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
911
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
912
+
913
+ def disable_freeu(self):
914
+ """Disables the FreeU mechanism if enabled."""
915
+ self.unet.disable_freeu()
916
+
917
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections
918
+ def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
919
+ """
920
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
921
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
922
+
923
+ <Tip warning={true}>
924
+
925
+ This API is 🧪 experimental.
926
+
927
+ </Tip>
928
+
929
+ Args:
930
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
931
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
932
+ """
933
+ self.fusing_unet = False
934
+ self.fusing_vae = False
935
+
936
+ if unet:
937
+ self.fusing_unet = True
938
+ self.unet.fuse_qkv_projections()
939
+ self.unet.set_attn_processor(FusedAttnProcessor2_0())
940
+
941
+ if vae:
942
+ if not isinstance(self.vae, AutoencoderKL):
943
+ raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.")
944
+
945
+ self.fusing_vae = True
946
+ self.vae.fuse_qkv_projections()
947
+ self.vae.set_attn_processor(FusedAttnProcessor2_0())
948
+
949
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections
950
+ def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
951
+ """Disable QKV projection fusion if enabled.
952
+
953
+ <Tip warning={true}>
954
+
955
+ This API is 🧪 experimental.
956
+
957
+ </Tip>
958
+
959
+ Args:
960
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
961
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
962
+
963
+ """
964
+ if unet:
965
+ if not self.fusing_unet:
966
+ logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.")
967
+ else:
968
+ self.unet.unfuse_qkv_projections()
969
+ self.fusing_unet = False
970
+
971
+ if vae:
972
+ if not self.fusing_vae:
973
+ logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
974
+ else:
975
+ self.vae.unfuse_qkv_projections()
976
+ self.fusing_vae = False
977
+
978
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
979
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
980
+ """
981
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
982
+
983
+ Args:
984
+ timesteps (`torch.Tensor`):
985
+ generate embedding vectors at these timesteps
986
+ embedding_dim (`int`, *optional*, defaults to 512):
987
+ dimension of the embeddings to generate
988
+ dtype:
989
+ data type of the generated embeddings
990
+
991
+ Returns:
992
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
993
+ """
994
+ assert len(w.shape) == 1
995
+ w = w * 1000.0
996
+
997
+ half_dim = embedding_dim // 2
998
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
999
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
1000
+ emb = w.to(dtype)[:, None] * emb[None, :]
1001
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
1002
+ if embedding_dim % 2 == 1: # zero pad
1003
+ emb = torch.nn.functional.pad(emb, (0, 1))
1004
+ assert emb.shape == (w.shape[0], embedding_dim)
1005
+ return emb
1006
+
1007
+ @property
1008
+ def guidance_scale(self):
1009
+ return self._guidance_scale
1010
+
1011
+ @property
1012
+ def guidance_rescale(self):
1013
+ return self._guidance_rescale
1014
+
1015
+ @property
1016
+ def clip_skip(self):
1017
+ return self._clip_skip
1018
+
1019
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1020
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1021
+ # corresponds to doing no classifier free guidance.
1022
+ @property
1023
+ def do_classifier_free_guidance(self):
1024
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1025
+
1026
+ @property
1027
+ def cross_attention_kwargs(self):
1028
+ return self._cross_attention_kwargs
1029
+
1030
+ @property
1031
+ def num_timesteps(self):
1032
+ return self._num_timesteps
1033
+
1034
+ @property
1035
+ def interrupt(self):
1036
+ return self._interrupt
1037
+
1038
+ def _compute_max_attention_per_index(
1039
+ self,
1040
+ attention_maps: torch.Tensor,
1041
+ indices_to_alter: List[int],
1042
+ smooth_attentions: bool = False,
1043
+ sigma: float = 0.5,
1044
+ kernel_size: int = 3,
1045
+ normalize_eot: bool = False,
1046
+ bboxes: List[int] = None,
1047
+ L: int = 1,
1048
+ P: float = 0.2,
1049
+ ) -> List[torch.Tensor]:
1050
+ """Computes the maximum attention value for each of the tokens we wish to alter."""
1051
+ last_idx = -1
1052
+ if normalize_eot:
1053
+ prompt = self.prompt
1054
+ if isinstance(self.prompt, list):
1055
+ prompt = self.prompt[0]
1056
+ last_idx = len(self.tokenizer(prompt)["input_ids"]) - 1
1057
+ attention_for_text = attention_maps[:, :, 1:last_idx]
1058
+ attention_for_text *= 100
1059
+ attention_for_text = torch.nn.functional.softmax(attention_for_text, dim=-1)
1060
+
1061
+ # Shift indices since we removed the first token "1:last_idx"
1062
+ indices_to_alter = [index - 1 for index in indices_to_alter]
1063
+
1064
+ # Extract the maximum values
1065
+ max_indices_list_fg = []
1066
+ max_indices_list_bg = []
1067
+ dist_x = []
1068
+ dist_y = []
1069
+
1070
+ cnt = 0
1071
+ for i in indices_to_alter:
1072
+ image = attention_for_text[:, :, i]
1073
+
1074
+ # TODO
1075
+ # box = [max(round(b / (512 / image.shape[0])), 0) for b in bboxes[cnt]]
1076
+ # x1, y1, x2, y2 = box
1077
+ H, W = image.shape
1078
+ x1 = min(max(round(bboxes[cnt][0] * W), 0), W)
1079
+ y1 = min(max(round(bboxes[cnt][1] * H), 0), H)
1080
+ x2 = min(max(round(bboxes[cnt][2] * W), 0), W)
1081
+ y2 = min(max(round(bboxes[cnt][3] * H), 0), H)
1082
+ box = [x1, y1, x2, y2]
1083
+ cnt += 1
1084
+
1085
+ # coordinates to masks
1086
+ obj_mask = torch.zeros_like(image)
1087
+ ones_mask = torch.ones([y2 - y1, x2 - x1], dtype=obj_mask.dtype).to(obj_mask.device)
1088
+ obj_mask[y1:y2, x1:x2] = ones_mask
1089
+ bg_mask = 1 - obj_mask
1090
+
1091
+ if smooth_attentions:
1092
+ smoothing = GaussianSmoothing(channels=1, kernel_size=kernel_size, sigma=sigma, dim=2).to(image.device)
1093
+ input = F.pad(image.unsqueeze(0).unsqueeze(0), (1, 1, 1, 1), mode="reflect")
1094
+ image = smoothing(input).squeeze(0).squeeze(0)
1095
+
1096
+ # Inner-Box constraint
1097
+ k = (obj_mask.sum() * P).long()
1098
+ max_indices_list_fg.append((image * obj_mask).reshape(-1).topk(k)[0].mean())
1099
+
1100
+ # Outer-Box constraint
1101
+ k = (bg_mask.sum() * P).long()
1102
+ max_indices_list_bg.append((image * bg_mask).reshape(-1).topk(k)[0].mean())
1103
+
1104
+ # Corner Constraint
1105
+ gt_proj_x = torch.max(obj_mask, dim=0)[0]
1106
+ gt_proj_y = torch.max(obj_mask, dim=1)[0]
1107
+ corner_mask_x = torch.zeros_like(gt_proj_x)
1108
+ corner_mask_y = torch.zeros_like(gt_proj_y)
1109
+
1110
+ # create gt according to the number config.L
1111
+ N = gt_proj_x.shape[0]
1112
+ corner_mask_x[max(box[0] - L, 0) : min(box[0] + L + 1, N)] = 1.0
1113
+ corner_mask_x[max(box[2] - L, 0) : min(box[2] + L + 1, N)] = 1.0
1114
+ corner_mask_y[max(box[1] - L, 0) : min(box[1] + L + 1, N)] = 1.0
1115
+ corner_mask_y[max(box[3] - L, 0) : min(box[3] + L + 1, N)] = 1.0
1116
+ dist_x.append((F.l1_loss(image.max(dim=0)[0], gt_proj_x, reduction="none") * corner_mask_x).mean())
1117
+ dist_y.append((F.l1_loss(image.max(dim=1)[0], gt_proj_y, reduction="none") * corner_mask_y).mean())
1118
+
1119
+ return max_indices_list_fg, max_indices_list_bg, dist_x, dist_y
1120
+
1121
+ def _aggregate_and_get_max_attention_per_token(
1122
+ self,
1123
+ attention_store: AttentionStore,
1124
+ indices_to_alter: List[int],
1125
+ attention_res: int = 16,
1126
+ smooth_attentions: bool = False,
1127
+ sigma: float = 0.5,
1128
+ kernel_size: int = 3,
1129
+ normalize_eot: bool = False,
1130
+ bboxes: List[int] = None,
1131
+ L: int = 1,
1132
+ P: float = 0.2,
1133
+ ):
1134
+ """Aggregates the attention for each token and computes the max activation value for each token to alter."""
1135
+ attention_maps = aggregate_attention(
1136
+ attention_store=attention_store,
1137
+ res=attention_res,
1138
+ from_where=("up", "down", "mid"),
1139
+ is_cross=True,
1140
+ select=0,
1141
+ )
1142
+ max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y = self._compute_max_attention_per_index(
1143
+ attention_maps=attention_maps,
1144
+ indices_to_alter=indices_to_alter,
1145
+ smooth_attentions=smooth_attentions,
1146
+ sigma=sigma,
1147
+ kernel_size=kernel_size,
1148
+ normalize_eot=normalize_eot,
1149
+ bboxes=bboxes,
1150
+ L=L,
1151
+ P=P,
1152
+ )
1153
+ return max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y
1154
+
1155
+ @staticmethod
1156
+ def _compute_loss(
1157
+ max_attention_per_index_fg: List[torch.Tensor],
1158
+ max_attention_per_index_bg: List[torch.Tensor],
1159
+ dist_x: List[torch.Tensor],
1160
+ dist_y: List[torch.Tensor],
1161
+ return_losses: bool = False,
1162
+ ) -> torch.Tensor:
1163
+ """Computes the attend-and-excite loss using the maximum attention value for each token."""
1164
+ losses_fg = [max(0, 1.0 - curr_max) for curr_max in max_attention_per_index_fg]
1165
+ losses_bg = [max(0, curr_max) for curr_max in max_attention_per_index_bg]
1166
+ loss = sum(losses_fg) + sum(losses_bg) + sum(dist_x) + sum(dist_y)
1167
+ if return_losses:
1168
+ return max(losses_fg), losses_fg
1169
+ else:
1170
+ return max(losses_fg), loss
1171
+
1172
+ @staticmethod
1173
+ def _update_latent(latents: torch.Tensor, loss: torch.Tensor, step_size: float) -> torch.Tensor:
1174
+ """Update the latent according to the computed loss."""
1175
+ grad_cond = torch.autograd.grad(loss.requires_grad_(True), [latents], retain_graph=True)[0]
1176
+ latents = latents - step_size * grad_cond
1177
+ return latents
1178
+
1179
+ def _perform_iterative_refinement_step(
1180
+ self,
1181
+ latents: torch.Tensor,
1182
+ indices_to_alter: List[int],
1183
+ loss_fg: torch.Tensor,
1184
+ threshold: float,
1185
+ text_embeddings: torch.Tensor,
1186
+ text_input,
1187
+ attention_store: AttentionStore,
1188
+ step_size: float,
1189
+ t: int,
1190
+ attention_res: int = 16,
1191
+ smooth_attentions: bool = True,
1192
+ sigma: float = 0.5,
1193
+ kernel_size: int = 3,
1194
+ max_refinement_steps: int = 20,
1195
+ normalize_eot: bool = False,
1196
+ bboxes: List[int] = None,
1197
+ L: int = 1,
1198
+ P: float = 0.2,
1199
+ ):
1200
+ """
1201
+ Performs the iterative latent refinement introduced in the paper. Here, we continuously update the latent
1202
+ code according to our loss objective until the given threshold is reached for all tokens.
1203
+ """
1204
+ iteration = 0
1205
+ target_loss = max(0, 1.0 - threshold)
1206
+
1207
+ while loss_fg > target_loss:
1208
+ iteration += 1
1209
+
1210
+ latents = latents.clone().detach().requires_grad_(True)
1211
+ # noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample
1212
+ self.unet.zero_grad()
1213
+
1214
+ # Get max activation value for each subject token
1215
+ (
1216
+ max_attention_per_index_fg,
1217
+ max_attention_per_index_bg,
1218
+ dist_x,
1219
+ dist_y,
1220
+ ) = self._aggregate_and_get_max_attention_per_token(
1221
+ attention_store=attention_store,
1222
+ indices_to_alter=indices_to_alter,
1223
+ attention_res=attention_res,
1224
+ smooth_attentions=smooth_attentions,
1225
+ sigma=sigma,
1226
+ kernel_size=kernel_size,
1227
+ normalize_eot=normalize_eot,
1228
+ bboxes=bboxes,
1229
+ L=L,
1230
+ P=P,
1231
+ )
1232
+
1233
+ loss_fg, losses_fg = self._compute_loss(
1234
+ max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y, return_losses=True
1235
+ )
1236
+
1237
+ if loss_fg != 0:
1238
+ latents = self._update_latent(latents, loss_fg, step_size)
1239
+
1240
+ # with torch.no_grad():
1241
+ # noise_pred_uncond = self.unet(latents, t, encoder_hidden_states=text_embeddings[0].unsqueeze(0)).sample
1242
+ # noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample
1243
+
1244
+ # try:
1245
+ # low_token = np.argmax([l.item() if not isinstance(l, int) else l for l in losses_fg])
1246
+ # except Exception as e:
1247
+ # print(e) # catch edge case :)
1248
+ # low_token = np.argmax(losses_fg)
1249
+
1250
+ # low_word = self.tokenizer.decode(text_input.input_ids[0][indices_to_alter[low_token]])
1251
+ # print(f'\t Try {iteration}. {low_word} has a max attention of {max_attention_per_index_fg[low_token]}')
1252
+
1253
+ if iteration >= max_refinement_steps:
1254
+ # print(f'\t Exceeded max number of iterations ({max_refinement_steps})! '
1255
+ # f'Finished with a max attention of {max_attention_per_index_fg[low_token]}')
1256
+ break
1257
+
1258
+ # Run one more time but don't compute gradients and update the latents.
1259
+ # We just need to compute the new loss - the grad update will occur below
1260
+ latents = latents.clone().detach().requires_grad_(True)
1261
+ # noise_pred_text = self.unet(latents, t, encoder_hidden_states=text_embeddings[1].unsqueeze(0)).sample
1262
+ self.unet.zero_grad()
1263
+
1264
+ # Get max activation value for each subject token
1265
+ (
1266
+ max_attention_per_index_fg,
1267
+ max_attention_per_index_bg,
1268
+ dist_x,
1269
+ dist_y,
1270
+ ) = self._aggregate_and_get_max_attention_per_token(
1271
+ attention_store=attention_store,
1272
+ indices_to_alter=indices_to_alter,
1273
+ attention_res=attention_res,
1274
+ smooth_attentions=smooth_attentions,
1275
+ sigma=sigma,
1276
+ kernel_size=kernel_size,
1277
+ normalize_eot=normalize_eot,
1278
+ bboxes=bboxes,
1279
+ L=L,
1280
+ P=P,
1281
+ )
1282
+ loss_fg, losses_fg = self._compute_loss(
1283
+ max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y, return_losses=True
1284
+ )
1285
+ # print(f"\t Finished with loss of: {loss_fg}")
1286
+ return loss_fg, latents, max_attention_per_index_fg
1287
+
1288
+ @torch.no_grad()
1289
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1290
+ def __call__(
1291
+ self,
1292
+ prompt: Union[str, List[str]] = None,
1293
+ boxdiff_phrases: List[str] = None,
1294
+ boxdiff_boxes: List[List[float]] = None, # TODO
1295
+ boxdiff_kwargs: Optional[Dict[str, Any]] = {
1296
+ "attention_res": 16,
1297
+ "P": 0.2,
1298
+ "L": 1,
1299
+ "max_iter_to_alter": 25,
1300
+ "loss_thresholds": {0: 0.05, 10: 0.5, 20: 0.8},
1301
+ "scale_factor": 20,
1302
+ "scale_range": (1.0, 0.5),
1303
+ "smooth_attentions": True,
1304
+ "sigma": 0.5,
1305
+ "kernel_size": 3,
1306
+ "refine": False,
1307
+ "normalize_eot": True,
1308
+ },
1309
+ height: Optional[int] = None,
1310
+ width: Optional[int] = None,
1311
+ num_inference_steps: int = 50,
1312
+ timesteps: List[int] = None,
1313
+ guidance_scale: float = 7.5,
1314
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1315
+ num_images_per_prompt: Optional[int] = 1,
1316
+ eta: float = 0.0,
1317
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1318
+ latents: Optional[torch.FloatTensor] = None,
1319
+ prompt_embeds: Optional[torch.FloatTensor] = None,
1320
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1321
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1322
+ output_type: Optional[str] = "pil",
1323
+ return_dict: bool = True,
1324
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1325
+ guidance_rescale: float = 0.0,
1326
+ clip_skip: Optional[int] = None,
1327
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1328
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1329
+ **kwargs,
1330
+ ):
1331
+ r"""
1332
+ The call function to the pipeline for generation.
1333
+
1334
+ Args:
1335
+ prompt (`str` or `List[str]`, *optional*):
1336
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1337
+
1338
+ boxdiff_attention_res (`int`, *optional*, defaults to 16):
1339
+ The resolution of the attention maps used for computing the BoxDiff loss.
1340
+ boxdiff_P (`float`, *optional*, defaults to 0.2):
1341
+
1342
+ boxdiff_L (`int`, *optional*, defaults to 1):
1343
+ The number of pixels around the corner to be selected in BoxDiff loss.
1344
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1345
+ The height in pixels of the generated image.
1346
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1347
+ The width in pixels of the generated image.
1348
+ num_inference_steps (`int`, *optional*, defaults to 50):
1349
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1350
+ expense of slower inference.
1351
+ timesteps (`List[int]`, *optional*):
1352
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1353
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1354
+ passed will be used. Must be in descending order.
1355
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1356
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1357
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1358
+ negative_prompt (`str` or `List[str]`, *optional*):
1359
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1360
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1361
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1362
+ The number of images to generate per prompt.
1363
+ eta (`float`, *optional*, defaults to 0.0):
1364
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1365
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1366
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1367
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1368
+ generation deterministic.
1369
+ latents (`torch.FloatTensor`, *optional*):
1370
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1371
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1372
+ tensor is generated by sampling using the supplied random `generator`.
1373
+ prompt_embeds (`torch.FloatTensor`, *optional*):
1374
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1375
+ provided, text embeddings are generated from the `prompt` input argument.
1376
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1377
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1378
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1379
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1380
+ output_type (`str`, *optional*, defaults to `"pil"`):
1381
+ The output format of the generated image. Choose between `PIL.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
+ cross_attention_kwargs (`dict`, *optional*):
1386
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1387
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1388
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1389
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
1390
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
1391
+ using zero terminal SNR.
1392
+ clip_skip (`int`, *optional*):
1393
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1394
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1395
+ callback_on_step_end (`Callable`, *optional*):
1396
+ A function that calls at the end of each denoising steps during the inference. The function is called
1397
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1398
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1399
+ `callback_on_step_end_tensor_inputs`.
1400
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1401
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1402
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1403
+ `._callback_tensor_inputs` attribute of your pipeline class.
1404
+
1405
+ Examples:
1406
+
1407
+ Returns:
1408
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1409
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1410
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1411
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1412
+ "not-safe-for-work" (nsfw) content.
1413
+ """
1414
+
1415
+ callback = kwargs.pop("callback", None)
1416
+ callback_steps = kwargs.pop("callback_steps", None)
1417
+
1418
+ if callback is not None:
1419
+ deprecate(
1420
+ "callback",
1421
+ "1.0.0",
1422
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1423
+ )
1424
+ if callback_steps is not None:
1425
+ deprecate(
1426
+ "callback_steps",
1427
+ "1.0.0",
1428
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1429
+ )
1430
+
1431
+ # -1. Register attention control (for BoxDiff)
1432
+ attention_store = AttentionStore()
1433
+ register_attention_control(self, attention_store)
1434
+
1435
+ # 0. Default height and width to unet
1436
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1437
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1438
+ # to deal with lora scaling and other possible forward hooks
1439
+
1440
+ # 1. Check inputs. Raise error if not correct
1441
+ self.check_inputs(
1442
+ prompt,
1443
+ height,
1444
+ width,
1445
+ boxdiff_phrases,
1446
+ boxdiff_boxes,
1447
+ callback_steps,
1448
+ negative_prompt,
1449
+ prompt_embeds,
1450
+ negative_prompt_embeds,
1451
+ callback_on_step_end_tensor_inputs,
1452
+ )
1453
+ self.prompt = prompt
1454
+
1455
+ self._guidance_scale = guidance_scale
1456
+ self._guidance_rescale = guidance_rescale
1457
+ self._clip_skip = clip_skip
1458
+ self._cross_attention_kwargs = cross_attention_kwargs
1459
+ self._interrupt = False
1460
+
1461
+ # 2. Define call parameters
1462
+ if prompt is not None and isinstance(prompt, str):
1463
+ batch_size = 1
1464
+ elif prompt is not None and isinstance(prompt, list):
1465
+ batch_size = len(prompt)
1466
+ else:
1467
+ batch_size = prompt_embeds.shape[0]
1468
+
1469
+ device = self._execution_device
1470
+
1471
+ # 3. Encode input prompt
1472
+ lora_scale = (
1473
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1474
+ )
1475
+
1476
+ text_inputs, prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1477
+ prompt,
1478
+ device,
1479
+ num_images_per_prompt,
1480
+ self.do_classifier_free_guidance,
1481
+ negative_prompt,
1482
+ prompt_embeds=prompt_embeds,
1483
+ negative_prompt_embeds=negative_prompt_embeds,
1484
+ lora_scale=lora_scale,
1485
+ clip_skip=self.clip_skip,
1486
+ )
1487
+
1488
+ # For classifier free guidance, we need to do two forward passes.
1489
+ # Here we concatenate the unconditional and text embeddings into a single batch
1490
+ # to avoid doing two forward passes
1491
+ if self.do_classifier_free_guidance:
1492
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1493
+
1494
+ if ip_adapter_image is not None:
1495
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1496
+ image_embeds, negative_image_embeds = self.encode_image(
1497
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
1498
+ )
1499
+ if self.do_classifier_free_guidance:
1500
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1501
+
1502
+ # 4. Prepare timesteps
1503
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1504
+
1505
+ # 5. Prepare latent variables
1506
+ num_channels_latents = self.unet.config.in_channels
1507
+ latents = self.prepare_latents(
1508
+ batch_size * num_images_per_prompt,
1509
+ num_channels_latents,
1510
+ height,
1511
+ width,
1512
+ prompt_embeds.dtype,
1513
+ device,
1514
+ generator,
1515
+ latents,
1516
+ )
1517
+
1518
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1519
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1520
+
1521
+ # 6.1 Add image embeds for IP-Adapter
1522
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1523
+
1524
+ # 6.2 Optionally get Guidance Scale Embedding
1525
+ timestep_cond = None
1526
+ if self.unet.config.time_cond_proj_dim is not None:
1527
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1528
+ timestep_cond = self.get_guidance_scale_embedding(
1529
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1530
+ ).to(device=device, dtype=latents.dtype)
1531
+
1532
+ # 6.3 Prepare BoxDiff inputs
1533
+ # a) Indices to alter
1534
+ input_ids = self.tokenizer(prompt)["input_ids"]
1535
+ decoded = [self.tokenizer.decode([t]) for t in input_ids]
1536
+ indices_to_alter = []
1537
+ bboxes = []
1538
+ for phrase, box in zip(boxdiff_phrases, boxdiff_boxes):
1539
+ # it could happen that phrase does not correspond a single token?
1540
+ if phrase not in decoded:
1541
+ continue
1542
+ indices_to_alter.append(decoded.index(phrase))
1543
+ bboxes.append(box)
1544
+
1545
+ # b) A bunch of hyperparameters
1546
+ attention_res = boxdiff_kwargs.get("attention_res", 16)
1547
+ smooth_attentions = boxdiff_kwargs.get("smooth_attentions", True)
1548
+ sigma = boxdiff_kwargs.get("sigma", 0.5)
1549
+ kernel_size = boxdiff_kwargs.get("kernel_size", 3)
1550
+ L = boxdiff_kwargs.get("L", 1)
1551
+ P = boxdiff_kwargs.get("P", 0.2)
1552
+ thresholds = boxdiff_kwargs.get("loss_thresholds", {0: 0.05, 10: 0.5, 20: 0.8})
1553
+ max_iter_to_alter = boxdiff_kwargs.get("max_iter_to_alter", len(self.scheduler.timesteps) + 1)
1554
+ scale_factor = boxdiff_kwargs.get("scale_factor", 20)
1555
+ refine = boxdiff_kwargs.get("refine", False)
1556
+ normalize_eot = boxdiff_kwargs.get("normalize_eot", True)
1557
+
1558
+ scale_range = boxdiff_kwargs.get("scale_range", (1.0, 0.5))
1559
+ scale_range = np.linspace(scale_range[0], scale_range[1], len(self.scheduler.timesteps))
1560
+
1561
+ # 7. Denoising loop
1562
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1563
+ self._num_timesteps = len(timesteps)
1564
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1565
+ for i, t in enumerate(timesteps):
1566
+ if self.interrupt:
1567
+ continue
1568
+
1569
+ # BoxDiff optimization
1570
+ with torch.enable_grad():
1571
+ latents = latents.clone().detach().requires_grad_(True)
1572
+
1573
+ # Forward pass of denoising with text conditioning
1574
+ noise_pred_text = self.unet(
1575
+ latents,
1576
+ t,
1577
+ encoder_hidden_states=prompt_embeds[1].unsqueeze(0),
1578
+ cross_attention_kwargs=cross_attention_kwargs,
1579
+ ).sample
1580
+ self.unet.zero_grad()
1581
+
1582
+ # Get max activation value for each subject token
1583
+ (
1584
+ max_attention_per_index_fg,
1585
+ max_attention_per_index_bg,
1586
+ dist_x,
1587
+ dist_y,
1588
+ ) = self._aggregate_and_get_max_attention_per_token(
1589
+ attention_store=attention_store,
1590
+ indices_to_alter=indices_to_alter,
1591
+ attention_res=attention_res,
1592
+ smooth_attentions=smooth_attentions,
1593
+ sigma=sigma,
1594
+ kernel_size=kernel_size,
1595
+ normalize_eot=normalize_eot,
1596
+ bboxes=bboxes,
1597
+ L=L,
1598
+ P=P,
1599
+ )
1600
+
1601
+ loss_fg, loss = self._compute_loss(
1602
+ max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y
1603
+ )
1604
+
1605
+ # Refinement from attend-and-excite (not necessary)
1606
+ if refine and i in thresholds.keys() and loss_fg > 1.0 - thresholds[i]:
1607
+ del noise_pred_text
1608
+ torch.cuda.empty_cache()
1609
+ loss_fg, latents, max_attention_per_index_fg = self._perform_iterative_refinement_step(
1610
+ latents=latents,
1611
+ indices_to_alter=indices_to_alter,
1612
+ loss_fg=loss_fg,
1613
+ threshold=thresholds[i],
1614
+ text_embeddings=prompt_embeds,
1615
+ text_input=text_inputs,
1616
+ attention_store=attention_store,
1617
+ step_size=scale_factor * np.sqrt(scale_range[i]),
1618
+ t=t,
1619
+ attention_res=attention_res,
1620
+ smooth_attentions=smooth_attentions,
1621
+ sigma=sigma,
1622
+ kernel_size=kernel_size,
1623
+ normalize_eot=normalize_eot,
1624
+ bboxes=bboxes,
1625
+ L=L,
1626
+ P=P,
1627
+ )
1628
+
1629
+ # Perform gradient update
1630
+ if i < max_iter_to_alter:
1631
+ _, loss = self._compute_loss(
1632
+ max_attention_per_index_fg, max_attention_per_index_bg, dist_x, dist_y
1633
+ )
1634
+ if loss != 0:
1635
+ latents = self._update_latent(
1636
+ latents=latents, loss=loss, step_size=scale_factor * np.sqrt(scale_range[i])
1637
+ )
1638
+
1639
+ # expand the latents if we are doing classifier free guidance
1640
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1641
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1642
+
1643
+ # predict the noise residual
1644
+ noise_pred = self.unet(
1645
+ latent_model_input,
1646
+ t,
1647
+ encoder_hidden_states=prompt_embeds,
1648
+ timestep_cond=timestep_cond,
1649
+ cross_attention_kwargs=self.cross_attention_kwargs,
1650
+ added_cond_kwargs=added_cond_kwargs,
1651
+ return_dict=False,
1652
+ )[0]
1653
+
1654
+ # perform guidance
1655
+ if self.do_classifier_free_guidance:
1656
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1657
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1658
+
1659
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1660
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1661
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1662
+
1663
+ # compute the previous noisy sample x_t -> x_t-1
1664
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1665
+
1666
+ if callback_on_step_end is not None:
1667
+ callback_kwargs = {}
1668
+ for k in callback_on_step_end_tensor_inputs:
1669
+ callback_kwargs[k] = locals()[k]
1670
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1671
+
1672
+ latents = callback_outputs.pop("latents", latents)
1673
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1674
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1675
+
1676
+ # call the callback, if provided
1677
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1678
+ progress_bar.update()
1679
+ if callback is not None and i % callback_steps == 0:
1680
+ step_idx = i // getattr(self.scheduler, "order", 1)
1681
+ callback(step_idx, t, latents)
1682
+
1683
+ if not output_type == "latent":
1684
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1685
+ 0
1686
+ ]
1687
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1688
+ else:
1689
+ image = latents
1690
+ has_nsfw_concept = None
1691
+
1692
+ if has_nsfw_concept is None:
1693
+ do_denormalize = [True] * image.shape[0]
1694
+ else:
1695
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1696
+
1697
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1698
+
1699
+ # Offload all models
1700
+ self.maybe_free_model_hooks()
1701
+
1702
+ if not return_dict:
1703
+ return (image, has_nsfw_concept)
1704
+
1705
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.30.0/pipeline_stable_diffusion_pag.py ADDED
@@ -0,0 +1,1476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Implementation of StableDiffusionPipeline with PAG
2
+ # https://ku-cvlab.github.io/Perturbed-Attention-Guidance
3
+
4
+ import inspect
5
+ from typing import Any, Callable, Dict, List, Optional, Union
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from packaging import version
10
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
11
+
12
+ from diffusers.configuration_utils import FrozenDict
13
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
14
+ from diffusers.loaders import (
15
+ FromSingleFileMixin,
16
+ IPAdapterMixin,
17
+ StableDiffusionLoraLoaderMixin,
18
+ TextualInversionLoaderMixin,
19
+ )
20
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
21
+ from diffusers.models.attention_processor import Attention, AttnProcessor2_0, FusedAttnProcessor2_0
22
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
23
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline
24
+ from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput
25
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
26
+ from diffusers.schedulers import KarrasDiffusionSchedulers
27
+ from diffusers.utils import (
28
+ USE_PEFT_BACKEND,
29
+ deprecate,
30
+ logging,
31
+ replace_example_docstring,
32
+ scale_lora_layers,
33
+ unscale_lora_layers,
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
+ >>> import torch
44
+ >>> from diffusers import StableDiffusionPipeline
45
+ >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16)
46
+ >>> pipe = pipe.to("cuda")
47
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
48
+ >>> image = pipe(prompt).images[0]
49
+ ```
50
+ """
51
+
52
+
53
+ class PAGIdentitySelfAttnProcessor:
54
+ r"""
55
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
56
+ """
57
+
58
+ def __init__(self):
59
+ if not hasattr(F, "scaled_dot_product_attention"):
60
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
61
+
62
+ def __call__(
63
+ self,
64
+ attn: Attention,
65
+ hidden_states: torch.Tensor,
66
+ encoder_hidden_states: Optional[torch.Tensor] = None,
67
+ attention_mask: Optional[torch.Tensor] = None,
68
+ temb: Optional[torch.Tensor] = None,
69
+ *args,
70
+ **kwargs,
71
+ ) -> torch.Tensor:
72
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
73
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
74
+ deprecate("scale", "1.0.0", deprecation_message)
75
+
76
+ residual = hidden_states
77
+ if attn.spatial_norm is not None:
78
+ hidden_states = attn.spatial_norm(hidden_states, temb)
79
+
80
+ input_ndim = hidden_states.ndim
81
+ if input_ndim == 4:
82
+ batch_size, channel, height, width = hidden_states.shape
83
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
84
+
85
+ # chunk
86
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
87
+
88
+ # original path
89
+ batch_size, sequence_length, _ = hidden_states_org.shape
90
+
91
+ if attention_mask is not None:
92
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
93
+ # scaled_dot_product_attention expects attention_mask shape to be
94
+ # (batch, heads, source_length, target_length)
95
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
96
+
97
+ if attn.group_norm is not None:
98
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
99
+
100
+ query = attn.to_q(hidden_states_org)
101
+ key = attn.to_k(hidden_states_org)
102
+ value = attn.to_v(hidden_states_org)
103
+
104
+ inner_dim = key.shape[-1]
105
+ head_dim = inner_dim // attn.heads
106
+
107
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
108
+
109
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
110
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
111
+
112
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
113
+ # TODO: add support for attn.scale when we move to Torch 2.1
114
+ hidden_states_org = F.scaled_dot_product_attention(
115
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
116
+ )
117
+
118
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
119
+ hidden_states_org = hidden_states_org.to(query.dtype)
120
+
121
+ # linear proj
122
+ hidden_states_org = attn.to_out[0](hidden_states_org)
123
+ # dropout
124
+ hidden_states_org = attn.to_out[1](hidden_states_org)
125
+
126
+ if input_ndim == 4:
127
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
128
+
129
+ # perturbed path (identity attention)
130
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
131
+
132
+ if attention_mask is not None:
133
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
134
+ # scaled_dot_product_attention expects attention_mask shape to be
135
+ # (batch, heads, source_length, target_length)
136
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
137
+
138
+ if attn.group_norm is not None:
139
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
140
+
141
+ value = attn.to_v(hidden_states_ptb)
142
+
143
+ # hidden_states_ptb = torch.zeros(value.shape).to(value.get_device())
144
+ hidden_states_ptb = value
145
+
146
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
147
+
148
+ # linear proj
149
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
150
+ # dropout
151
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
152
+
153
+ if input_ndim == 4:
154
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
155
+
156
+ # cat
157
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
158
+
159
+ if attn.residual_connection:
160
+ hidden_states = hidden_states + residual
161
+
162
+ hidden_states = hidden_states / attn.rescale_output_factor
163
+
164
+ return hidden_states
165
+
166
+
167
+ class PAGCFGIdentitySelfAttnProcessor:
168
+ r"""
169
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
170
+ """
171
+
172
+ def __init__(self):
173
+ if not hasattr(F, "scaled_dot_product_attention"):
174
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
175
+
176
+ def __call__(
177
+ self,
178
+ attn: Attention,
179
+ hidden_states: torch.Tensor,
180
+ encoder_hidden_states: Optional[torch.Tensor] = None,
181
+ attention_mask: Optional[torch.Tensor] = None,
182
+ temb: Optional[torch.Tensor] = None,
183
+ *args,
184
+ **kwargs,
185
+ ) -> torch.Tensor:
186
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
187
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
188
+ deprecate("scale", "1.0.0", deprecation_message)
189
+
190
+ residual = hidden_states
191
+ if attn.spatial_norm is not None:
192
+ hidden_states = attn.spatial_norm(hidden_states, temb)
193
+
194
+ input_ndim = hidden_states.ndim
195
+ if input_ndim == 4:
196
+ batch_size, channel, height, width = hidden_states.shape
197
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
198
+
199
+ # chunk
200
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
201
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
202
+
203
+ # original path
204
+ batch_size, sequence_length, _ = hidden_states_org.shape
205
+
206
+ if attention_mask is not None:
207
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
208
+ # scaled_dot_product_attention expects attention_mask shape to be
209
+ # (batch, heads, source_length, target_length)
210
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
211
+
212
+ if attn.group_norm is not None:
213
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
214
+
215
+ query = attn.to_q(hidden_states_org)
216
+ key = attn.to_k(hidden_states_org)
217
+ value = attn.to_v(hidden_states_org)
218
+
219
+ inner_dim = key.shape[-1]
220
+ head_dim = inner_dim // attn.heads
221
+
222
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
223
+
224
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
225
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
226
+
227
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
228
+ # TODO: add support for attn.scale when we move to Torch 2.1
229
+ hidden_states_org = F.scaled_dot_product_attention(
230
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
231
+ )
232
+
233
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
234
+ hidden_states_org = hidden_states_org.to(query.dtype)
235
+
236
+ # linear proj
237
+ hidden_states_org = attn.to_out[0](hidden_states_org)
238
+ # dropout
239
+ hidden_states_org = attn.to_out[1](hidden_states_org)
240
+
241
+ if input_ndim == 4:
242
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
243
+
244
+ # perturbed path (identity attention)
245
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
246
+
247
+ if attention_mask is not None:
248
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
249
+ # scaled_dot_product_attention expects attention_mask shape to be
250
+ # (batch, heads, source_length, target_length)
251
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
252
+
253
+ if attn.group_norm is not None:
254
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
255
+
256
+ value = attn.to_v(hidden_states_ptb)
257
+ hidden_states_ptb = value
258
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
259
+
260
+ # linear proj
261
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
262
+ # dropout
263
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
264
+
265
+ if input_ndim == 4:
266
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
267
+
268
+ # cat
269
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
270
+
271
+ if attn.residual_connection:
272
+ hidden_states = hidden_states + residual
273
+
274
+ hidden_states = hidden_states / attn.rescale_output_factor
275
+
276
+ return hidden_states
277
+
278
+
279
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
280
+ """
281
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
282
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
283
+ """
284
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
285
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
286
+ # rescale the results from guidance (fixes overexposure)
287
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
288
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
289
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
290
+ return noise_cfg
291
+
292
+
293
+ def retrieve_timesteps(
294
+ scheduler,
295
+ num_inference_steps: Optional[int] = None,
296
+ device: Optional[Union[str, torch.device]] = None,
297
+ timesteps: Optional[List[int]] = None,
298
+ **kwargs,
299
+ ):
300
+ """
301
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
302
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
303
+ Args:
304
+ scheduler (`SchedulerMixin`):
305
+ The scheduler to get timesteps from.
306
+ num_inference_steps (`int`):
307
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
308
+ `timesteps` must be `None`.
309
+ device (`str` or `torch.device`, *optional*):
310
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
311
+ timesteps (`List[int]`, *optional*):
312
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
313
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
314
+ must be `None`.
315
+ Returns:
316
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
317
+ second element is the number of inference steps.
318
+ """
319
+ if timesteps is not None:
320
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
321
+ if not accepts_timesteps:
322
+ raise ValueError(
323
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
324
+ f" timestep schedules. Please check whether you are using the correct scheduler."
325
+ )
326
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
327
+ timesteps = scheduler.timesteps
328
+ num_inference_steps = len(timesteps)
329
+ else:
330
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
331
+ timesteps = scheduler.timesteps
332
+ return timesteps, num_inference_steps
333
+
334
+
335
+ class StableDiffusionPAGPipeline(
336
+ DiffusionPipeline, TextualInversionLoaderMixin, StableDiffusionLoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
337
+ ):
338
+ r"""
339
+ Pipeline for text-to-image generation using Stable Diffusion.
340
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
341
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
342
+ The pipeline also inherits the following loading methods:
343
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
344
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
345
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
346
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
347
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
348
+ Args:
349
+ vae ([`AutoencoderKL`]):
350
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
351
+ text_encoder ([`~transformers.CLIPTextModel`]):
352
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
353
+ tokenizer ([`~transformers.CLIPTokenizer`]):
354
+ A `CLIPTokenizer` to tokenize text.
355
+ unet ([`UNet2DConditionModel`]):
356
+ A `UNet2DConditionModel` to denoise the encoded image latents.
357
+ scheduler ([`SchedulerMixin`]):
358
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
359
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
360
+ safety_checker ([`StableDiffusionSafetyChecker`]):
361
+ Classification module that estimates whether generated images could be considered offensive or harmful.
362
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
363
+ about a model's potential harms.
364
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
365
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
366
+ """
367
+
368
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
369
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
370
+ _exclude_from_cpu_offload = ["safety_checker"]
371
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
372
+
373
+ def __init__(
374
+ self,
375
+ vae: AutoencoderKL,
376
+ text_encoder: CLIPTextModel,
377
+ tokenizer: CLIPTokenizer,
378
+ unet: UNet2DConditionModel,
379
+ scheduler: KarrasDiffusionSchedulers,
380
+ safety_checker: StableDiffusionSafetyChecker,
381
+ feature_extractor: CLIPImageProcessor,
382
+ image_encoder: CLIPVisionModelWithProjection = None,
383
+ requires_safety_checker: bool = True,
384
+ ):
385
+ super().__init__()
386
+
387
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
388
+ deprecation_message = (
389
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
390
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
391
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
392
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
393
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
394
+ " file"
395
+ )
396
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
397
+ new_config = dict(scheduler.config)
398
+ new_config["steps_offset"] = 1
399
+ scheduler._internal_dict = FrozenDict(new_config)
400
+
401
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
402
+ deprecation_message = (
403
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
404
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
405
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
406
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
407
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
408
+ )
409
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
410
+ new_config = dict(scheduler.config)
411
+ new_config["clip_sample"] = False
412
+ scheduler._internal_dict = FrozenDict(new_config)
413
+
414
+ if safety_checker is None and requires_safety_checker:
415
+ logger.warning(
416
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
417
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
418
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
419
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
420
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
421
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
422
+ )
423
+
424
+ if safety_checker is not None and feature_extractor is None:
425
+ raise ValueError(
426
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
427
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
428
+ )
429
+
430
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
431
+ version.parse(unet.config._diffusers_version).base_version
432
+ ) < version.parse("0.9.0.dev0")
433
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
434
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
435
+ deprecation_message = (
436
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
437
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
438
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
439
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
440
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
441
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
442
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
443
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
444
+ " the `unet/config.json` file"
445
+ )
446
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
447
+ new_config = dict(unet.config)
448
+ new_config["sample_size"] = 64
449
+ unet._internal_dict = FrozenDict(new_config)
450
+
451
+ self.register_modules(
452
+ vae=vae,
453
+ text_encoder=text_encoder,
454
+ tokenizer=tokenizer,
455
+ unet=unet,
456
+ scheduler=scheduler,
457
+ safety_checker=safety_checker,
458
+ feature_extractor=feature_extractor,
459
+ image_encoder=image_encoder,
460
+ )
461
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
462
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
463
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
464
+
465
+ def enable_vae_slicing(self):
466
+ r"""
467
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
468
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
469
+ """
470
+ self.vae.enable_slicing()
471
+
472
+ def disable_vae_slicing(self):
473
+ r"""
474
+ Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
475
+ computing decoding in one step.
476
+ """
477
+ self.vae.disable_slicing()
478
+
479
+ def enable_vae_tiling(self):
480
+ r"""
481
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
482
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
483
+ processing larger images.
484
+ """
485
+ self.vae.enable_tiling()
486
+
487
+ def disable_vae_tiling(self):
488
+ r"""
489
+ Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
490
+ computing decoding in one step.
491
+ """
492
+ self.vae.disable_tiling()
493
+
494
+ def _encode_prompt(
495
+ self,
496
+ prompt,
497
+ device,
498
+ num_images_per_prompt,
499
+ do_classifier_free_guidance,
500
+ negative_prompt=None,
501
+ prompt_embeds: Optional[torch.Tensor] = None,
502
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
503
+ lora_scale: Optional[float] = None,
504
+ **kwargs,
505
+ ):
506
+ 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."
507
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
508
+
509
+ prompt_embeds_tuple = self.encode_prompt(
510
+ prompt=prompt,
511
+ device=device,
512
+ num_images_per_prompt=num_images_per_prompt,
513
+ do_classifier_free_guidance=do_classifier_free_guidance,
514
+ negative_prompt=negative_prompt,
515
+ prompt_embeds=prompt_embeds,
516
+ negative_prompt_embeds=negative_prompt_embeds,
517
+ lora_scale=lora_scale,
518
+ **kwargs,
519
+ )
520
+
521
+ # concatenate for backwards comp
522
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
523
+
524
+ return prompt_embeds
525
+
526
+ def encode_prompt(
527
+ self,
528
+ prompt,
529
+ device,
530
+ num_images_per_prompt,
531
+ do_classifier_free_guidance,
532
+ negative_prompt=None,
533
+ prompt_embeds: Optional[torch.Tensor] = None,
534
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
535
+ lora_scale: Optional[float] = None,
536
+ clip_skip: Optional[int] = None,
537
+ ):
538
+ r"""
539
+ Encodes the prompt into text encoder hidden states.
540
+ Args:
541
+ prompt (`str` or `List[str]`, *optional*):
542
+ prompt to be encoded
543
+ device: (`torch.device`):
544
+ torch device
545
+ num_images_per_prompt (`int`):
546
+ number of images that should be generated per prompt
547
+ do_classifier_free_guidance (`bool`):
548
+ whether to use classifier free guidance or not
549
+ negative_prompt (`str` or `List[str]`, *optional*):
550
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
551
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
552
+ less than `1`).
553
+ prompt_embeds (`torch.Tensor`, *optional*):
554
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
555
+ provided, text embeddings will be generated from `prompt` input argument.
556
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
557
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
558
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
559
+ argument.
560
+ lora_scale (`float`, *optional*):
561
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
562
+ clip_skip (`int`, *optional*):
563
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
564
+ the output of the pre-final layer will be used for computing the prompt embeddings.
565
+ """
566
+ # set lora scale so that monkey patched LoRA
567
+ # function of text encoder can correctly access it
568
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
569
+ self._lora_scale = lora_scale
570
+
571
+ # dynamically adjust the LoRA scale
572
+ if not USE_PEFT_BACKEND:
573
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
574
+ else:
575
+ scale_lora_layers(self.text_encoder, lora_scale)
576
+
577
+ if prompt is not None and isinstance(prompt, str):
578
+ batch_size = 1
579
+ elif prompt is not None and isinstance(prompt, list):
580
+ batch_size = len(prompt)
581
+ else:
582
+ batch_size = prompt_embeds.shape[0]
583
+
584
+ if prompt_embeds is None:
585
+ # textual inversion: process multi-vector tokens if necessary
586
+ if isinstance(self, TextualInversionLoaderMixin):
587
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
588
+
589
+ text_inputs = self.tokenizer(
590
+ prompt,
591
+ padding="max_length",
592
+ max_length=self.tokenizer.model_max_length,
593
+ truncation=True,
594
+ return_tensors="pt",
595
+ )
596
+ text_input_ids = text_inputs.input_ids
597
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
598
+
599
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
600
+ text_input_ids, untruncated_ids
601
+ ):
602
+ removed_text = self.tokenizer.batch_decode(
603
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
604
+ )
605
+ logger.warning(
606
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
607
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
608
+ )
609
+
610
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
611
+ attention_mask = text_inputs.attention_mask.to(device)
612
+ else:
613
+ attention_mask = None
614
+
615
+ if clip_skip is None:
616
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
617
+ prompt_embeds = prompt_embeds[0]
618
+ else:
619
+ prompt_embeds = self.text_encoder(
620
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
621
+ )
622
+ # Access the `hidden_states` first, that contains a tuple of
623
+ # all the hidden states from the encoder layers. Then index into
624
+ # the tuple to access the hidden states from the desired layer.
625
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
626
+ # We also need to apply the final LayerNorm here to not mess with the
627
+ # representations. The `last_hidden_states` that we typically use for
628
+ # obtaining the final prompt representations passes through the LayerNorm
629
+ # layer.
630
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
631
+
632
+ if self.text_encoder is not None:
633
+ prompt_embeds_dtype = self.text_encoder.dtype
634
+ elif self.unet is not None:
635
+ prompt_embeds_dtype = self.unet.dtype
636
+ else:
637
+ prompt_embeds_dtype = prompt_embeds.dtype
638
+
639
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
640
+
641
+ bs_embed, seq_len, _ = prompt_embeds.shape
642
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
643
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
644
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
645
+
646
+ # get unconditional embeddings for classifier free guidance
647
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
648
+ uncond_tokens: List[str]
649
+ if negative_prompt is None:
650
+ uncond_tokens = [""] * batch_size
651
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
652
+ raise TypeError(
653
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
654
+ f" {type(prompt)}."
655
+ )
656
+ elif isinstance(negative_prompt, str):
657
+ uncond_tokens = [negative_prompt]
658
+ elif batch_size != len(negative_prompt):
659
+ raise ValueError(
660
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
661
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
662
+ " the batch size of `prompt`."
663
+ )
664
+ else:
665
+ uncond_tokens = negative_prompt
666
+
667
+ # textual inversion: process multi-vector tokens if necessary
668
+ if isinstance(self, TextualInversionLoaderMixin):
669
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
670
+
671
+ max_length = prompt_embeds.shape[1]
672
+ uncond_input = self.tokenizer(
673
+ uncond_tokens,
674
+ padding="max_length",
675
+ max_length=max_length,
676
+ truncation=True,
677
+ return_tensors="pt",
678
+ )
679
+
680
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
681
+ attention_mask = uncond_input.attention_mask.to(device)
682
+ else:
683
+ attention_mask = None
684
+
685
+ negative_prompt_embeds = self.text_encoder(
686
+ uncond_input.input_ids.to(device),
687
+ attention_mask=attention_mask,
688
+ )
689
+ negative_prompt_embeds = negative_prompt_embeds[0]
690
+
691
+ if do_classifier_free_guidance:
692
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
693
+ seq_len = negative_prompt_embeds.shape[1]
694
+
695
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
696
+
697
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
698
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
699
+
700
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
701
+ # Retrieve the original scale by scaling back the LoRA layers
702
+ unscale_lora_layers(self.text_encoder, lora_scale)
703
+
704
+ return prompt_embeds, negative_prompt_embeds
705
+
706
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
707
+ dtype = next(self.image_encoder.parameters()).dtype
708
+
709
+ if not isinstance(image, torch.Tensor):
710
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
711
+
712
+ image = image.to(device=device, dtype=dtype)
713
+ if output_hidden_states:
714
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
715
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
716
+ uncond_image_enc_hidden_states = self.image_encoder(
717
+ torch.zeros_like(image), output_hidden_states=True
718
+ ).hidden_states[-2]
719
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
720
+ num_images_per_prompt, dim=0
721
+ )
722
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
723
+ else:
724
+ image_embeds = self.image_encoder(image).image_embeds
725
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
726
+ uncond_image_embeds = torch.zeros_like(image_embeds)
727
+
728
+ return image_embeds, uncond_image_embeds
729
+
730
+ def prepare_ip_adapter_image_embeds(
731
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt
732
+ ):
733
+ if ip_adapter_image_embeds is None:
734
+ if not isinstance(ip_adapter_image, list):
735
+ ip_adapter_image = [ip_adapter_image]
736
+
737
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
738
+ raise ValueError(
739
+ 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."
740
+ )
741
+
742
+ image_embeds = []
743
+ for single_ip_adapter_image, image_proj_layer in zip(
744
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
745
+ ):
746
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
747
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
748
+ single_ip_adapter_image, device, 1, output_hidden_state
749
+ )
750
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
751
+ single_negative_image_embeds = torch.stack(
752
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
753
+ )
754
+
755
+ if self.do_classifier_free_guidance:
756
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
757
+ single_image_embeds = single_image_embeds.to(device)
758
+
759
+ image_embeds.append(single_image_embeds)
760
+ else:
761
+ image_embeds = ip_adapter_image_embeds
762
+ return image_embeds
763
+
764
+ def run_safety_checker(self, image, device, dtype):
765
+ if self.safety_checker is None:
766
+ has_nsfw_concept = None
767
+ else:
768
+ if torch.is_tensor(image):
769
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
770
+ else:
771
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
772
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
773
+ image, has_nsfw_concept = self.safety_checker(
774
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
775
+ )
776
+ return image, has_nsfw_concept
777
+
778
+ def decode_latents(self, latents):
779
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
780
+ deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
781
+
782
+ latents = 1 / self.vae.config.scaling_factor * latents
783
+ image = self.vae.decode(latents, return_dict=False)[0]
784
+ image = (image / 2 + 0.5).clamp(0, 1)
785
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
786
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
787
+ return image
788
+
789
+ def prepare_extra_step_kwargs(self, generator, eta):
790
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
791
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
792
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
793
+ # and should be between [0, 1]
794
+
795
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
796
+ extra_step_kwargs = {}
797
+ if accepts_eta:
798
+ extra_step_kwargs["eta"] = eta
799
+
800
+ # check if the scheduler accepts generator
801
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
802
+ if accepts_generator:
803
+ extra_step_kwargs["generator"] = generator
804
+ return extra_step_kwargs
805
+
806
+ def check_inputs(
807
+ self,
808
+ prompt,
809
+ height,
810
+ width,
811
+ callback_steps,
812
+ negative_prompt=None,
813
+ prompt_embeds=None,
814
+ negative_prompt_embeds=None,
815
+ ip_adapter_image=None,
816
+ ip_adapter_image_embeds=None,
817
+ callback_on_step_end_tensor_inputs=None,
818
+ ):
819
+ if height % 8 != 0 or width % 8 != 0:
820
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
821
+
822
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
823
+ raise ValueError(
824
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
825
+ f" {type(callback_steps)}."
826
+ )
827
+ if callback_on_step_end_tensor_inputs is not None and not all(
828
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
829
+ ):
830
+ raise ValueError(
831
+ 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]}"
832
+ )
833
+
834
+ if prompt is not None and prompt_embeds is not None:
835
+ raise ValueError(
836
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
837
+ " only forward one of the two."
838
+ )
839
+ elif prompt is None and prompt_embeds is None:
840
+ raise ValueError(
841
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
842
+ )
843
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
844
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
845
+
846
+ if negative_prompt is not None and negative_prompt_embeds is not None:
847
+ raise ValueError(
848
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
849
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
850
+ )
851
+
852
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
853
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
854
+ raise ValueError(
855
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
856
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
857
+ f" {negative_prompt_embeds.shape}."
858
+ )
859
+
860
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
861
+ raise ValueError(
862
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
863
+ )
864
+
865
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
866
+ shape = (
867
+ batch_size,
868
+ num_channels_latents,
869
+ int(height) // self.vae_scale_factor,
870
+ int(width) // self.vae_scale_factor,
871
+ )
872
+ if isinstance(generator, list) and len(generator) != batch_size:
873
+ raise ValueError(
874
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
875
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
876
+ )
877
+
878
+ if latents is None:
879
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
880
+ else:
881
+ latents = latents.to(device)
882
+
883
+ # scale the initial noise by the standard deviation required by the scheduler
884
+ latents = latents * self.scheduler.init_noise_sigma
885
+ return latents
886
+
887
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
888
+ r"""Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.
889
+ The suffixes after the scaling factors represent the stages where they are being applied.
890
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
891
+ that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
892
+ Args:
893
+ s1 (`float`):
894
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
895
+ mitigate "oversmoothing effect" in the enhanced denoising process.
896
+ s2 (`float`):
897
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
898
+ mitigate "oversmoothing effect" in the enhanced denoising process.
899
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
900
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
901
+ """
902
+ if not hasattr(self, "unet"):
903
+ raise ValueError("The pipeline must have `unet` for using FreeU.")
904
+ self.unet.enable_freeu(s1=s1, s2=s2, b1=b1, b2=b2)
905
+
906
+ def disable_freeu(self):
907
+ """Disables the FreeU mechanism if enabled."""
908
+ self.unet.disable_freeu()
909
+
910
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.fuse_qkv_projections
911
+ def fuse_qkv_projections(self, unet: bool = True, vae: bool = True):
912
+ """
913
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,
914
+ key, value) are fused. For cross-attention modules, key and value projection matrices are fused.
915
+ <Tip warning={true}>
916
+ This API is 🧪 experimental.
917
+ </Tip>
918
+ Args:
919
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
920
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
921
+ """
922
+ self.fusing_unet = False
923
+ self.fusing_vae = False
924
+
925
+ if unet:
926
+ self.fusing_unet = True
927
+ self.unet.fuse_qkv_projections()
928
+ self.unet.set_attn_processor(FusedAttnProcessor2_0())
929
+
930
+ if vae:
931
+ if not isinstance(self.vae, AutoencoderKL):
932
+ raise ValueError("`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.")
933
+
934
+ self.fusing_vae = True
935
+ self.vae.fuse_qkv_projections()
936
+ self.vae.set_attn_processor(FusedAttnProcessor2_0())
937
+
938
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.unfuse_qkv_projections
939
+ def unfuse_qkv_projections(self, unet: bool = True, vae: bool = True):
940
+ """Disable QKV projection fusion if enabled.
941
+ <Tip warning={true}>
942
+ This API is 🧪 experimental.
943
+ </Tip>
944
+ Args:
945
+ unet (`bool`, defaults to `True`): To apply fusion on the UNet.
946
+ vae (`bool`, defaults to `True`): To apply fusion on the VAE.
947
+ """
948
+ if unet:
949
+ if not self.fusing_unet:
950
+ logger.warning("The UNet was not initially fused for QKV projections. Doing nothing.")
951
+ else:
952
+ self.unet.unfuse_qkv_projections()
953
+ self.fusing_unet = False
954
+
955
+ if vae:
956
+ if not self.fusing_vae:
957
+ logger.warning("The VAE was not initially fused for QKV projections. Doing nothing.")
958
+ else:
959
+ self.vae.unfuse_qkv_projections()
960
+ self.fusing_vae = False
961
+
962
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
963
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
964
+ """
965
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
966
+ Args:
967
+ timesteps (`torch.Tensor`):
968
+ generate embedding vectors at these timesteps
969
+ embedding_dim (`int`, *optional*, defaults to 512):
970
+ dimension of the embeddings to generate
971
+ dtype:
972
+ data type of the generated embeddings
973
+ Returns:
974
+ `torch.Tensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
975
+ """
976
+ assert len(w.shape) == 1
977
+ w = w * 1000.0
978
+
979
+ half_dim = embedding_dim // 2
980
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
981
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
982
+ emb = w.to(dtype)[:, None] * emb[None, :]
983
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
984
+ if embedding_dim % 2 == 1: # zero pad
985
+ emb = torch.nn.functional.pad(emb, (0, 1))
986
+ assert emb.shape == (w.shape[0], embedding_dim)
987
+ return emb
988
+
989
+ def pred_z0(self, sample, model_output, timestep):
990
+ alpha_prod_t = self.scheduler.alphas_cumprod[timestep].to(sample.device)
991
+
992
+ beta_prod_t = 1 - alpha_prod_t
993
+ if self.scheduler.config.prediction_type == "epsilon":
994
+ pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
995
+ elif self.scheduler.config.prediction_type == "sample":
996
+ pred_original_sample = model_output
997
+ elif self.scheduler.config.prediction_type == "v_prediction":
998
+ pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
999
+ # predict V
1000
+ model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
1001
+ else:
1002
+ raise ValueError(
1003
+ f"prediction_type given as {self.scheduler.config.prediction_type} must be one of `epsilon`, `sample`,"
1004
+ " or `v_prediction`"
1005
+ )
1006
+
1007
+ return pred_original_sample
1008
+
1009
+ def pred_x0(self, latents, noise_pred, t, generator, device, prompt_embeds, output_type):
1010
+ pred_z0 = self.pred_z0(latents, noise_pred, t)
1011
+ pred_x0 = self.vae.decode(pred_z0 / self.vae.config.scaling_factor, return_dict=False, generator=generator)[0]
1012
+ pred_x0, ____ = self.run_safety_checker(pred_x0, device, prompt_embeds.dtype)
1013
+ do_denormalize = [True] * pred_x0.shape[0]
1014
+ pred_x0 = self.image_processor.postprocess(pred_x0, output_type=output_type, do_denormalize=do_denormalize)
1015
+
1016
+ return pred_x0
1017
+
1018
+ @property
1019
+ def guidance_scale(self):
1020
+ return self._guidance_scale
1021
+
1022
+ @property
1023
+ def guidance_rescale(self):
1024
+ return self._guidance_rescale
1025
+
1026
+ @property
1027
+ def clip_skip(self):
1028
+ return self._clip_skip
1029
+
1030
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1031
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1032
+ # corresponds to doing no classifier free guidance.
1033
+ @property
1034
+ def do_classifier_free_guidance(self):
1035
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
1036
+
1037
+ @property
1038
+ def cross_attention_kwargs(self):
1039
+ return self._cross_attention_kwargs
1040
+
1041
+ @property
1042
+ def num_timesteps(self):
1043
+ return self._num_timesteps
1044
+
1045
+ @property
1046
+ def interrupt(self):
1047
+ return self._interrupt
1048
+
1049
+ @property
1050
+ def pag_scale(self):
1051
+ return self._pag_scale
1052
+
1053
+ @property
1054
+ def do_perturbed_attention_guidance(self):
1055
+ return self._pag_scale > 0
1056
+
1057
+ @property
1058
+ def pag_adaptive_scaling(self):
1059
+ return self._pag_adaptive_scaling
1060
+
1061
+ @property
1062
+ def do_pag_adaptive_scaling(self):
1063
+ return self._pag_adaptive_scaling > 0
1064
+
1065
+ @property
1066
+ def pag_applied_layers_index(self):
1067
+ return self._pag_applied_layers_index
1068
+
1069
+ @torch.no_grad()
1070
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1071
+ def __call__(
1072
+ self,
1073
+ prompt: Union[str, List[str]] = None,
1074
+ height: Optional[int] = None,
1075
+ width: Optional[int] = None,
1076
+ num_inference_steps: int = 50,
1077
+ timesteps: List[int] = None,
1078
+ guidance_scale: float = 7.5,
1079
+ pag_scale: float = 0.0,
1080
+ pag_adaptive_scaling: float = 0.0,
1081
+ pag_applied_layers_index: List[str] = ["d4"], # ['d4', 'd5', 'm0']
1082
+ negative_prompt: Optional[Union[str, List[str]]] = None,
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
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1090
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
1091
+ output_type: Optional[str] = "pil",
1092
+ return_dict: bool = True,
1093
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1094
+ guidance_rescale: float = 0.0,
1095
+ clip_skip: Optional[int] = None,
1096
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1097
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1098
+ **kwargs,
1099
+ ):
1100
+ r"""
1101
+ The call function to the pipeline for generation.
1102
+ Args:
1103
+ prompt (`str` or `List[str]`, *optional*):
1104
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
1105
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1106
+ The height in pixels of the generated image.
1107
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
1108
+ The width in pixels of the generated image.
1109
+ num_inference_steps (`int`, *optional*, defaults to 50):
1110
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1111
+ expense of slower inference.
1112
+ timesteps (`List[int]`, *optional*):
1113
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
1114
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
1115
+ passed will be used. Must be in descending order.
1116
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1117
+ A higher guidance scale value encourages the model to generate images closely linked to the text
1118
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
1119
+ negative_prompt (`str` or `List[str]`, *optional*):
1120
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
1121
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
1122
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1123
+ The number of images to generate per prompt.
1124
+ eta (`float`, *optional*, defaults to 0.0):
1125
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
1126
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
1127
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1128
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
1129
+ generation deterministic.
1130
+ latents (`torch.Tensor`, *optional*):
1131
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
1132
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1133
+ tensor is generated by sampling using the supplied random `generator`.
1134
+ prompt_embeds (`torch.Tensor`, *optional*):
1135
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
1136
+ provided, text embeddings are generated from the `prompt` input argument.
1137
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1138
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1139
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1140
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1141
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1142
+ Pre-generated image embeddings for IP-Adapter. If not
1143
+ provided, embeddings are computed from the `ip_adapter_image` input argument.
1144
+ output_type (`str`, *optional*, defaults to `"pil"`):
1145
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1146
+ return_dict (`bool`, *optional*, defaults to `True`):
1147
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1148
+ plain tuple.
1149
+ cross_attention_kwargs (`dict`, *optional*):
1150
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1151
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1152
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1153
+ Guidance rescale factor from [Common Diffusion Noise Schedules and Sample Steps are
1154
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when
1155
+ using zero terminal SNR.
1156
+ clip_skip (`int`, *optional*):
1157
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1158
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1159
+ callback_on_step_end (`Callable`, *optional*):
1160
+ A function that calls at the end of each denoising steps during the inference. The function is called
1161
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1162
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1163
+ `callback_on_step_end_tensor_inputs`.
1164
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1165
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1166
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1167
+ `._callback_tensor_inputs` attribute of your pipeline class.
1168
+ Examples:
1169
+ Returns:
1170
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
1171
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
1172
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
1173
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
1174
+ "not-safe-for-work" (nsfw) content.
1175
+ """
1176
+
1177
+ callback = kwargs.pop("callback", None)
1178
+ callback_steps = kwargs.pop("callback_steps", None)
1179
+
1180
+ if callback is not None:
1181
+ deprecate(
1182
+ "callback",
1183
+ "1.0.0",
1184
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1185
+ )
1186
+ if callback_steps is not None:
1187
+ deprecate(
1188
+ "callback_steps",
1189
+ "1.0.0",
1190
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1191
+ )
1192
+
1193
+ # 0. Default height and width to unet
1194
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
1195
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
1196
+ # to deal with lora scaling and other possible forward hooks
1197
+
1198
+ # 1. Check inputs. Raise error if not correct
1199
+ self.check_inputs(
1200
+ prompt,
1201
+ height,
1202
+ width,
1203
+ callback_steps,
1204
+ negative_prompt,
1205
+ prompt_embeds,
1206
+ negative_prompt_embeds,
1207
+ ip_adapter_image,
1208
+ ip_adapter_image_embeds,
1209
+ callback_on_step_end_tensor_inputs,
1210
+ )
1211
+
1212
+ self._guidance_scale = guidance_scale
1213
+ self._guidance_rescale = guidance_rescale
1214
+ self._clip_skip = clip_skip
1215
+ self._cross_attention_kwargs = cross_attention_kwargs
1216
+ self._interrupt = False
1217
+
1218
+ self._pag_scale = pag_scale
1219
+ self._pag_adaptive_scaling = pag_adaptive_scaling
1220
+ self._pag_applied_layers_index = pag_applied_layers_index
1221
+
1222
+ # 2. Define call parameters
1223
+ if prompt is not None and isinstance(prompt, str):
1224
+ batch_size = 1
1225
+ elif prompt is not None and isinstance(prompt, list):
1226
+ batch_size = len(prompt)
1227
+ else:
1228
+ batch_size = prompt_embeds.shape[0]
1229
+
1230
+ device = self._execution_device
1231
+
1232
+ # 3. Encode input prompt
1233
+ lora_scale = (
1234
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1235
+ )
1236
+
1237
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1238
+ prompt,
1239
+ device,
1240
+ num_images_per_prompt,
1241
+ self.do_classifier_free_guidance,
1242
+ negative_prompt,
1243
+ prompt_embeds=prompt_embeds,
1244
+ negative_prompt_embeds=negative_prompt_embeds,
1245
+ lora_scale=lora_scale,
1246
+ clip_skip=self.clip_skip,
1247
+ )
1248
+
1249
+ # For classifier free guidance, we need to do two forward passes.
1250
+ # Here we concatenate the unconditional and text embeddings into a single batch
1251
+ # to avoid doing two forward passes
1252
+
1253
+ # cfg
1254
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1255
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1256
+ # pag
1257
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1258
+ prompt_embeds = torch.cat([prompt_embeds, prompt_embeds])
1259
+ # both
1260
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1261
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds, prompt_embeds])
1262
+
1263
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1264
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1265
+ ip_adapter_image, ip_adapter_image_embeds, device, batch_size * num_images_per_prompt
1266
+ )
1267
+
1268
+ # 4. Prepare timesteps
1269
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1270
+
1271
+ # 5. Prepare latent variables
1272
+ num_channels_latents = self.unet.config.in_channels
1273
+ latents = self.prepare_latents(
1274
+ batch_size * num_images_per_prompt,
1275
+ num_channels_latents,
1276
+ height,
1277
+ width,
1278
+ prompt_embeds.dtype,
1279
+ device,
1280
+ generator,
1281
+ latents,
1282
+ )
1283
+
1284
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1285
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1286
+
1287
+ # 6.1 Add image embeds for IP-Adapter
1288
+ added_cond_kwargs = (
1289
+ {"image_embeds": image_embeds}
1290
+ if (ip_adapter_image is not None or ip_adapter_image_embeds is not None)
1291
+ else None
1292
+ )
1293
+
1294
+ # 6.2 Optionally get Guidance Scale Embedding
1295
+ timestep_cond = None
1296
+ if self.unet.config.time_cond_proj_dim is not None:
1297
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1298
+ timestep_cond = self.get_guidance_scale_embedding(
1299
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1300
+ ).to(device=device, dtype=latents.dtype)
1301
+
1302
+ # 7. Denoising loop
1303
+ if self.do_perturbed_attention_guidance:
1304
+ down_layers = []
1305
+ mid_layers = []
1306
+ up_layers = []
1307
+ for name, module in self.unet.named_modules():
1308
+ if "attn1" in name and "to" not in name:
1309
+ layer_type = name.split(".")[0].split("_")[0]
1310
+ if layer_type == "down":
1311
+ down_layers.append(module)
1312
+ elif layer_type == "mid":
1313
+ mid_layers.append(module)
1314
+ elif layer_type == "up":
1315
+ up_layers.append(module)
1316
+ else:
1317
+ raise ValueError(f"Invalid layer type: {layer_type}")
1318
+
1319
+ # change attention layer in UNet if use PAG
1320
+ if self.do_perturbed_attention_guidance:
1321
+ if self.do_classifier_free_guidance:
1322
+ replace_processor = PAGCFGIdentitySelfAttnProcessor()
1323
+ else:
1324
+ replace_processor = PAGIdentitySelfAttnProcessor()
1325
+
1326
+ drop_layers = self.pag_applied_layers_index
1327
+ for drop_layer in drop_layers:
1328
+ try:
1329
+ if drop_layer[0] == "d":
1330
+ down_layers[int(drop_layer[1])].processor = replace_processor
1331
+ elif drop_layer[0] == "m":
1332
+ mid_layers[int(drop_layer[1])].processor = replace_processor
1333
+ elif drop_layer[0] == "u":
1334
+ up_layers[int(drop_layer[1])].processor = replace_processor
1335
+ else:
1336
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1337
+ except IndexError:
1338
+ raise ValueError(
1339
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1340
+ )
1341
+
1342
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1343
+ self._num_timesteps = len(timesteps)
1344
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1345
+ for i, t in enumerate(timesteps):
1346
+ if self.interrupt:
1347
+ continue
1348
+
1349
+ # cfg
1350
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1351
+ latent_model_input = torch.cat([latents] * 2)
1352
+ # pag
1353
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1354
+ latent_model_input = torch.cat([latents] * 2)
1355
+ # both
1356
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1357
+ latent_model_input = torch.cat([latents] * 3)
1358
+ # no
1359
+ else:
1360
+ latent_model_input = latents
1361
+
1362
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1363
+
1364
+ # predict the noise residual
1365
+ noise_pred = self.unet(
1366
+ latent_model_input,
1367
+ t,
1368
+ encoder_hidden_states=prompt_embeds,
1369
+ timestep_cond=timestep_cond,
1370
+ cross_attention_kwargs=self.cross_attention_kwargs,
1371
+ added_cond_kwargs=added_cond_kwargs,
1372
+ return_dict=False,
1373
+ )[0]
1374
+
1375
+ # perform guidance
1376
+
1377
+ # cfg
1378
+ if self.do_classifier_free_guidance and not self.do_perturbed_attention_guidance:
1379
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1380
+
1381
+ delta = noise_pred_text - noise_pred_uncond
1382
+ noise_pred = noise_pred_uncond + self.guidance_scale * delta
1383
+
1384
+ # pag
1385
+ elif not self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1386
+ noise_pred_original, noise_pred_perturb = noise_pred.chunk(2)
1387
+
1388
+ signal_scale = self.pag_scale
1389
+ if self.do_pag_adaptive_scaling:
1390
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000 - t)
1391
+ if signal_scale < 0:
1392
+ signal_scale = 0
1393
+
1394
+ noise_pred = noise_pred_original + signal_scale * (noise_pred_original - noise_pred_perturb)
1395
+
1396
+ # both
1397
+ elif self.do_classifier_free_guidance and self.do_perturbed_attention_guidance:
1398
+ noise_pred_uncond, noise_pred_text, noise_pred_text_perturb = noise_pred.chunk(3)
1399
+
1400
+ signal_scale = self.pag_scale
1401
+ if self.do_pag_adaptive_scaling:
1402
+ signal_scale = self.pag_scale - self.pag_adaptive_scaling * (1000 - t)
1403
+ if signal_scale < 0:
1404
+ signal_scale = 0
1405
+
1406
+ noise_pred = (
1407
+ noise_pred_text
1408
+ + (self.guidance_scale - 1.0) * (noise_pred_text - noise_pred_uncond)
1409
+ + signal_scale * (noise_pred_text - noise_pred_text_perturb)
1410
+ )
1411
+
1412
+ if self.do_classifier_free_guidance and self.guidance_rescale > 0.0:
1413
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1414
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=self.guidance_rescale)
1415
+
1416
+ # compute the previous noisy sample x_t -> x_t-1
1417
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1418
+
1419
+ if callback_on_step_end is not None:
1420
+ callback_kwargs = {}
1421
+ for k in callback_on_step_end_tensor_inputs:
1422
+ callback_kwargs[k] = locals()[k]
1423
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1424
+
1425
+ latents = callback_outputs.pop("latents", latents)
1426
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1427
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1428
+
1429
+ # call the callback, if provided
1430
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1431
+ progress_bar.update()
1432
+ if callback is not None and i % callback_steps == 0:
1433
+ step_idx = i // getattr(self.scheduler, "order", 1)
1434
+ callback(step_idx, t, latents)
1435
+
1436
+ if not output_type == "latent":
1437
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
1438
+ 0
1439
+ ]
1440
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
1441
+ else:
1442
+ image = latents
1443
+ has_nsfw_concept = None
1444
+
1445
+ if has_nsfw_concept is None:
1446
+ do_denormalize = [True] * image.shape[0]
1447
+ else:
1448
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
1449
+
1450
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
1451
+
1452
+ # Offload all models
1453
+ self.maybe_free_model_hooks()
1454
+
1455
+ # change attention layer in UNet if use PAG
1456
+ if self.do_perturbed_attention_guidance:
1457
+ drop_layers = self.pag_applied_layers_index
1458
+ for drop_layer in drop_layers:
1459
+ try:
1460
+ if drop_layer[0] == "d":
1461
+ down_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1462
+ elif drop_layer[0] == "m":
1463
+ mid_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1464
+ elif drop_layer[0] == "u":
1465
+ up_layers[int(drop_layer[1])].processor = AttnProcessor2_0()
1466
+ else:
1467
+ raise ValueError(f"Invalid layer type: {drop_layer[0]}")
1468
+ except IndexError:
1469
+ raise ValueError(
1470
+ f"Invalid layer index: {drop_layer}. Available layers: {len(down_layers)} down layers, {len(mid_layers)} mid layers, {len(up_layers)} up layers."
1471
+ )
1472
+
1473
+ if not return_dict:
1474
+ return (image, has_nsfw_concept)
1475
+
1476
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
v0.30.0/pipeline_stable_diffusion_upscale_ldm3d.py ADDED
@@ -0,0 +1,772 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Intel Labs Team 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 Any, Callable, Dict, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import PIL
20
+ import torch
21
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
22
+
23
+ from diffusers import DiffusionPipeline
24
+ from diffusers.image_processor import PipelineDepthInput, PipelineImageInput, VaeImageProcessorLDM3D
25
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionLoraLoaderMixin, TextualInversionLoaderMixin
26
+ from diffusers.models import AutoencoderKL, UNet2DConditionModel
27
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
28
+ from diffusers.pipelines.stable_diffusion import StableDiffusionSafetyChecker
29
+ from diffusers.pipelines.stable_diffusion_ldm3d.pipeline_stable_diffusion_ldm3d import LDM3DPipelineOutput
30
+ from diffusers.schedulers import DDPMScheduler, KarrasDiffusionSchedulers
31
+ from diffusers.utils import (
32
+ USE_PEFT_BACKEND,
33
+ deprecate,
34
+ logging,
35
+ scale_lora_layers,
36
+ unscale_lora_layers,
37
+ )
38
+ from diffusers.utils.torch_utils import randn_tensor
39
+
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+ EXAMPLE_DOC_STRING = """
44
+ Examples:
45
+ ```python
46
+ >>> from diffusers import StableDiffusionUpscaleLDM3DPipeline
47
+ >>> from PIL import Image
48
+ >>> from io import BytesIO
49
+ >>> import requests
50
+
51
+ >>> pipe = StableDiffusionUpscaleLDM3DPipeline.from_pretrained("Intel/ldm3d-sr")
52
+ >>> pipe = pipe.to("cuda")
53
+ >>> rgb_path = "https://huggingface.co/Intel/ldm3d-sr/resolve/main/lemons_ldm3d_rgb.jpg"
54
+ >>> depth_path = "https://huggingface.co/Intel/ldm3d-sr/resolve/main/lemons_ldm3d_depth.png"
55
+ >>> low_res_rgb = Image.open(BytesIO(requests.get(rgb_path).content)).convert("RGB")
56
+ >>> low_res_depth = Image.open(BytesIO(requests.get(depth_path).content)).convert("L")
57
+ >>> output = pipe(
58
+ ... prompt="high quality high resolution uhd 4k image",
59
+ ... rgb=low_res_rgb,
60
+ ... depth=low_res_depth,
61
+ ... num_inference_steps=50,
62
+ ... target_res=[1024, 1024],
63
+ ... )
64
+ >>> rgb_image, depth_image = output.rgb, output.depth
65
+ >>> rgb_image[0].save("hr_ldm3d_rgb.jpg")
66
+ >>> depth_image[0].save("hr_ldm3d_depth.png")
67
+ ```
68
+ """
69
+
70
+
71
+ class StableDiffusionUpscaleLDM3DPipeline(
72
+ DiffusionPipeline, TextualInversionLoaderMixin, StableDiffusionLoraLoaderMixin, FromSingleFileMixin
73
+ ):
74
+ r"""
75
+ Pipeline for text-to-image and 3D generation using LDM3D.
76
+
77
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
78
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
79
+
80
+ The pipeline also inherits the following loading methods:
81
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
82
+ - [`~loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
83
+ - [`~loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
84
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
85
+
86
+ Args:
87
+ vae ([`AutoencoderKL`]):
88
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
89
+ text_encoder ([`~transformers.CLIPTextModel`]):
90
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
91
+ tokenizer ([`~transformers.CLIPTokenizer`]):
92
+ A `CLIPTokenizer` to tokenize text.
93
+ unet ([`UNet2DConditionModel`]):
94
+ A `UNet2DConditionModel` to denoise the encoded image latents.
95
+ low_res_scheduler ([`SchedulerMixin`]):
96
+ A scheduler used to add initial noise to the low resolution conditioning image. It must be an instance of
97
+ [`DDPMScheduler`].
98
+ scheduler ([`SchedulerMixin`]):
99
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
100
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
101
+ safety_checker ([`StableDiffusionSafetyChecker`]):
102
+ Classification module that estimates whether generated images could be considered offensive or harmful.
103
+ Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details
104
+ about a model's potential harms.
105
+ feature_extractor ([`~transformers.CLIPImageProcessor`]):
106
+ A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
107
+ """
108
+
109
+ _optional_components = ["safety_checker", "feature_extractor"]
110
+
111
+ def __init__(
112
+ self,
113
+ vae: AutoencoderKL,
114
+ text_encoder: CLIPTextModel,
115
+ tokenizer: CLIPTokenizer,
116
+ unet: UNet2DConditionModel,
117
+ low_res_scheduler: DDPMScheduler,
118
+ scheduler: KarrasDiffusionSchedulers,
119
+ safety_checker: StableDiffusionSafetyChecker,
120
+ feature_extractor: CLIPImageProcessor,
121
+ requires_safety_checker: bool = True,
122
+ watermarker: Optional[Any] = None,
123
+ max_noise_level: int = 350,
124
+ ):
125
+ super().__init__()
126
+
127
+ if safety_checker is None and requires_safety_checker:
128
+ logger.warning(
129
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
130
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
131
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
132
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
133
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
134
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
135
+ )
136
+
137
+ if safety_checker is not None and feature_extractor is None:
138
+ raise ValueError(
139
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
140
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
141
+ )
142
+
143
+ self.register_modules(
144
+ vae=vae,
145
+ text_encoder=text_encoder,
146
+ tokenizer=tokenizer,
147
+ unet=unet,
148
+ low_res_scheduler=low_res_scheduler,
149
+ scheduler=scheduler,
150
+ safety_checker=safety_checker,
151
+ watermarker=watermarker,
152
+ feature_extractor=feature_extractor,
153
+ )
154
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
155
+ self.image_processor = VaeImageProcessorLDM3D(vae_scale_factor=self.vae_scale_factor, resample="bilinear")
156
+ # self.register_to_config(requires_safety_checker=requires_safety_checker)
157
+ self.register_to_config(max_noise_level=max_noise_level)
158
+
159
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_ldm3d.StableDiffusionLDM3DPipeline._encode_prompt
160
+ def _encode_prompt(
161
+ self,
162
+ prompt,
163
+ device,
164
+ num_images_per_prompt,
165
+ do_classifier_free_guidance,
166
+ negative_prompt=None,
167
+ prompt_embeds: Optional[torch.Tensor] = None,
168
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
169
+ lora_scale: Optional[float] = None,
170
+ **kwargs,
171
+ ):
172
+ 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."
173
+ deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
174
+
175
+ prompt_embeds_tuple = self.encode_prompt(
176
+ prompt=prompt,
177
+ device=device,
178
+ num_images_per_prompt=num_images_per_prompt,
179
+ do_classifier_free_guidance=do_classifier_free_guidance,
180
+ negative_prompt=negative_prompt,
181
+ prompt_embeds=prompt_embeds,
182
+ negative_prompt_embeds=negative_prompt_embeds,
183
+ lora_scale=lora_scale,
184
+ **kwargs,
185
+ )
186
+
187
+ # concatenate for backwards comp
188
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
189
+
190
+ return prompt_embeds
191
+
192
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_ldm3d.StableDiffusionLDM3DPipeline.encode_prompt
193
+ def encode_prompt(
194
+ self,
195
+ prompt,
196
+ device,
197
+ num_images_per_prompt,
198
+ do_classifier_free_guidance,
199
+ negative_prompt=None,
200
+ prompt_embeds: Optional[torch.Tensor] = None,
201
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
202
+ lora_scale: Optional[float] = None,
203
+ clip_skip: Optional[int] = None,
204
+ ):
205
+ r"""
206
+ Encodes the prompt into text encoder hidden states.
207
+
208
+ Args:
209
+ prompt (`str` or `List[str]`, *optional*):
210
+ prompt to be encoded
211
+ device: (`torch.device`):
212
+ torch device
213
+ num_images_per_prompt (`int`):
214
+ number of images that should be generated per prompt
215
+ do_classifier_free_guidance (`bool`):
216
+ whether to use classifier free guidance or not
217
+ negative_prompt (`str` or `List[str]`, *optional*):
218
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
219
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
220
+ less than `1`).
221
+ prompt_embeds (`torch.Tensor`, *optional*):
222
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
223
+ provided, text embeddings will be generated from `prompt` input argument.
224
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
225
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
226
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
227
+ argument.
228
+ lora_scale (`float`, *optional*):
229
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
230
+ clip_skip (`int`, *optional*):
231
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
232
+ the output of the pre-final layer will be used for computing the prompt embeddings.
233
+ """
234
+ # set lora scale so that monkey patched LoRA
235
+ # function of text encoder can correctly access it
236
+ if lora_scale is not None and isinstance(self, StableDiffusionLoraLoaderMixin):
237
+ self._lora_scale = lora_scale
238
+
239
+ # dynamically adjust the LoRA scale
240
+ if not USE_PEFT_BACKEND:
241
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
242
+ else:
243
+ scale_lora_layers(self.text_encoder, 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
+ if prompt_embeds is None:
253
+ # textual inversion: process multi-vector tokens if necessary
254
+ if isinstance(self, TextualInversionLoaderMixin):
255
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
256
+
257
+ text_inputs = self.tokenizer(
258
+ prompt,
259
+ padding="max_length",
260
+ max_length=self.tokenizer.model_max_length,
261
+ truncation=True,
262
+ return_tensors="pt",
263
+ )
264
+ text_input_ids = text_inputs.input_ids
265
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
266
+
267
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
268
+ text_input_ids, untruncated_ids
269
+ ):
270
+ removed_text = self.tokenizer.batch_decode(
271
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
272
+ )
273
+ logger.warning(
274
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
275
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
276
+ )
277
+
278
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
279
+ attention_mask = text_inputs.attention_mask.to(device)
280
+ else:
281
+ attention_mask = None
282
+
283
+ if clip_skip is None:
284
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
285
+ prompt_embeds = prompt_embeds[0]
286
+ else:
287
+ prompt_embeds = self.text_encoder(
288
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
289
+ )
290
+ # Access the `hidden_states` first, that contains a tuple of
291
+ # all the hidden states from the encoder layers. Then index into
292
+ # the tuple to access the hidden states from the desired layer.
293
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
294
+ # We also need to apply the final LayerNorm here to not mess with the
295
+ # representations. The `last_hidden_states` that we typically use for
296
+ # obtaining the final prompt representations passes through the LayerNorm
297
+ # layer.
298
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
299
+
300
+ if self.text_encoder is not None:
301
+ prompt_embeds_dtype = self.text_encoder.dtype
302
+ elif self.unet is not None:
303
+ prompt_embeds_dtype = self.unet.dtype
304
+ else:
305
+ prompt_embeds_dtype = prompt_embeds.dtype
306
+
307
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
308
+
309
+ bs_embed, seq_len, _ = prompt_embeds.shape
310
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
311
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
312
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
313
+
314
+ # get unconditional embeddings for classifier free guidance
315
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
316
+ uncond_tokens: List[str]
317
+ if negative_prompt is None:
318
+ uncond_tokens = [""] * batch_size
319
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
320
+ raise TypeError(
321
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
322
+ f" {type(prompt)}."
323
+ )
324
+ elif isinstance(negative_prompt, str):
325
+ uncond_tokens = [negative_prompt]
326
+ elif batch_size != len(negative_prompt):
327
+ raise ValueError(
328
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
329
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
330
+ " the batch size of `prompt`."
331
+ )
332
+ else:
333
+ uncond_tokens = negative_prompt
334
+
335
+ # textual inversion: process multi-vector tokens if necessary
336
+ if isinstance(self, TextualInversionLoaderMixin):
337
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
338
+
339
+ max_length = prompt_embeds.shape[1]
340
+ uncond_input = self.tokenizer(
341
+ uncond_tokens,
342
+ padding="max_length",
343
+ max_length=max_length,
344
+ truncation=True,
345
+ return_tensors="pt",
346
+ )
347
+
348
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
349
+ attention_mask = uncond_input.attention_mask.to(device)
350
+ else:
351
+ attention_mask = None
352
+
353
+ negative_prompt_embeds = self.text_encoder(
354
+ uncond_input.input_ids.to(device),
355
+ attention_mask=attention_mask,
356
+ )
357
+ negative_prompt_embeds = negative_prompt_embeds[0]
358
+
359
+ if do_classifier_free_guidance:
360
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
361
+ seq_len = negative_prompt_embeds.shape[1]
362
+
363
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
364
+
365
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
366
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
367
+
368
+ if isinstance(self, StableDiffusionLoraLoaderMixin) and USE_PEFT_BACKEND:
369
+ # Retrieve the original scale by scaling back the LoRA layers
370
+ unscale_lora_layers(self.text_encoder, lora_scale)
371
+
372
+ return prompt_embeds, negative_prompt_embeds
373
+
374
+ def run_safety_checker(self, image, device, dtype):
375
+ if self.safety_checker is None:
376
+ has_nsfw_concept = None
377
+ else:
378
+ if torch.is_tensor(image):
379
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
380
+ else:
381
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
382
+ rgb_feature_extractor_input = feature_extractor_input[0]
383
+ safety_checker_input = self.feature_extractor(rgb_feature_extractor_input, return_tensors="pt").to(device)
384
+ image, has_nsfw_concept = self.safety_checker(
385
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
386
+ )
387
+ return image, has_nsfw_concept
388
+
389
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
390
+ def prepare_extra_step_kwargs(self, generator, eta):
391
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
392
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
393
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
394
+ # and should be between [0, 1]
395
+
396
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
397
+ extra_step_kwargs = {}
398
+ if accepts_eta:
399
+ extra_step_kwargs["eta"] = eta
400
+
401
+ # check if the scheduler accepts generator
402
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
403
+ if accepts_generator:
404
+ extra_step_kwargs["generator"] = generator
405
+ return extra_step_kwargs
406
+
407
+ def check_inputs(
408
+ self,
409
+ prompt,
410
+ image,
411
+ noise_level,
412
+ callback_steps,
413
+ negative_prompt=None,
414
+ prompt_embeds=None,
415
+ negative_prompt_embeds=None,
416
+ target_res=None,
417
+ ):
418
+ if (callback_steps is None) or (
419
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
420
+ ):
421
+ raise ValueError(
422
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
423
+ f" {type(callback_steps)}."
424
+ )
425
+
426
+ if prompt is not None and prompt_embeds is not None:
427
+ raise ValueError(
428
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
429
+ " only forward one of the two."
430
+ )
431
+ elif prompt is None and prompt_embeds is None:
432
+ raise ValueError(
433
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
434
+ )
435
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
436
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
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
+
444
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
445
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
446
+ raise ValueError(
447
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
448
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
449
+ f" {negative_prompt_embeds.shape}."
450
+ )
451
+
452
+ if (
453
+ not isinstance(image, torch.Tensor)
454
+ and not isinstance(image, PIL.Image.Image)
455
+ and not isinstance(image, np.ndarray)
456
+ and not isinstance(image, list)
457
+ ):
458
+ raise ValueError(
459
+ f"`image` has to be of type `torch.Tensor`, `np.ndarray`, `PIL.Image.Image` or `list` but is {type(image)}"
460
+ )
461
+
462
+ # verify batch size of prompt and image are same if image is a list or tensor or numpy array
463
+ if isinstance(image, (list, np.ndarray, torch.Tensor)):
464
+ if prompt is not None and isinstance(prompt, str):
465
+ batch_size = 1
466
+ elif prompt is not None and isinstance(prompt, list):
467
+ batch_size = len(prompt)
468
+ else:
469
+ batch_size = prompt_embeds.shape[0]
470
+
471
+ if isinstance(image, list):
472
+ image_batch_size = len(image)
473
+ else:
474
+ image_batch_size = image.shape[0]
475
+ if batch_size != image_batch_size:
476
+ raise ValueError(
477
+ f"`prompt` has batch size {batch_size} and `image` has batch size {image_batch_size}."
478
+ " Please make sure that passed `prompt` matches the batch size of `image`."
479
+ )
480
+
481
+ # check noise level
482
+ if noise_level > self.config.max_noise_level:
483
+ raise ValueError(f"`noise_level` has to be <= {self.config.max_noise_level} but is {noise_level}")
484
+
485
+ if (callback_steps is None) or (
486
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
487
+ ):
488
+ raise ValueError(
489
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
490
+ f" {type(callback_steps)}."
491
+ )
492
+
493
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
494
+ shape = (batch_size, num_channels_latents, height, width)
495
+ if latents is None:
496
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
497
+ else:
498
+ if latents.shape != shape:
499
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
500
+ latents = latents.to(device)
501
+
502
+ # scale the initial noise by the standard deviation required by the scheduler
503
+ latents = latents * self.scheduler.init_noise_sigma
504
+ return latents
505
+
506
+ # def upcast_vae(self):
507
+ # dtype = self.vae.dtype
508
+ # self.vae.to(dtype=torch.float32)
509
+ # use_torch_2_0_or_xformers = isinstance(
510
+ # self.vae.decoder.mid_block.attentions[0].processor,
511
+ # (
512
+ # AttnProcessor2_0,
513
+ # XFormersAttnProcessor,
514
+ # LoRAXFormersAttnProcessor,
515
+ # LoRAAttnProcessor2_0,
516
+ # ),
517
+ # )
518
+ # # if xformers or torch_2_0 is used attention block does not need
519
+ # # to be in float32 which can save lots of memory
520
+ # if use_torch_2_0_or_xformers:
521
+ # self.vae.post_quant_conv.to(dtype)
522
+ # self.vae.decoder.conv_in.to(dtype)
523
+ # self.vae.decoder.mid_block.to(dtype)
524
+
525
+ @torch.no_grad()
526
+ def __call__(
527
+ self,
528
+ prompt: Union[str, List[str]] = None,
529
+ rgb: PipelineImageInput = None,
530
+ depth: PipelineDepthInput = None,
531
+ num_inference_steps: int = 75,
532
+ guidance_scale: float = 9.0,
533
+ noise_level: int = 20,
534
+ negative_prompt: Optional[Union[str, List[str]]] = None,
535
+ num_images_per_prompt: Optional[int] = 1,
536
+ eta: float = 0.0,
537
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
538
+ latents: Optional[torch.Tensor] = None,
539
+ prompt_embeds: Optional[torch.Tensor] = None,
540
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
541
+ output_type: Optional[str] = "pil",
542
+ return_dict: bool = True,
543
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
544
+ callback_steps: int = 1,
545
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
546
+ target_res: Optional[List[int]] = [1024, 1024],
547
+ ):
548
+ r"""
549
+ The call function to the pipeline for generation.
550
+
551
+ Args:
552
+ prompt (`str` or `List[str]`, *optional*):
553
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
554
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, or `List[np.ndarray]`):
555
+ `Image` or tensor representing an image batch to be upscaled.
556
+ num_inference_steps (`int`, *optional*, defaults to 50):
557
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
558
+ expense of slower inference.
559
+ guidance_scale (`float`, *optional*, defaults to 5.0):
560
+ A higher guidance scale value encourages the model to generate images closely linked to the text
561
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
562
+ negative_prompt (`str` or `List[str]`, *optional*):
563
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
564
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
565
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
566
+ The number of images to generate per prompt.
567
+ eta (`float`, *optional*, defaults to 0.0):
568
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
569
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
570
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
571
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
572
+ generation deterministic.
573
+ latents (`torch.Tensor`, *optional*):
574
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
575
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
576
+ tensor is generated by sampling using the supplied random `generator`.
577
+ prompt_embeds (`torch.Tensor`, *optional*):
578
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
579
+ provided, text embeddings are generated from the `prompt` input argument.
580
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
581
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
582
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
583
+ output_type (`str`, *optional*, defaults to `"pil"`):
584
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
585
+ return_dict (`bool`, *optional*, defaults to `True`):
586
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
587
+ plain tuple.
588
+ callback (`Callable`, *optional*):
589
+ A function that calls every `callback_steps` steps during inference. The function is called with the
590
+ following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
591
+ callback_steps (`int`, *optional*, defaults to 1):
592
+ The frequency at which the `callback` function is called. If not specified, the callback is called at
593
+ every step.
594
+ cross_attention_kwargs (`dict`, *optional*):
595
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
596
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
597
+
598
+ Examples:
599
+
600
+ Returns:
601
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
602
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
603
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
604
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
605
+ "not-safe-for-work" (nsfw) content.
606
+ """
607
+ # 1. Check inputs. Raise error if not correct
608
+ self.check_inputs(
609
+ prompt,
610
+ rgb,
611
+ noise_level,
612
+ callback_steps,
613
+ negative_prompt,
614
+ prompt_embeds,
615
+ negative_prompt_embeds,
616
+ )
617
+ # 2. Define call parameters
618
+ if prompt is not None and isinstance(prompt, str):
619
+ batch_size = 1
620
+ elif prompt is not None and isinstance(prompt, list):
621
+ batch_size = len(prompt)
622
+ else:
623
+ batch_size = prompt_embeds.shape[0]
624
+
625
+ device = self._execution_device
626
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
627
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
628
+ # corresponds to doing no classifier free guidance.
629
+ do_classifier_free_guidance = guidance_scale > 1.0
630
+
631
+ # 3. Encode input prompt
632
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
633
+ prompt,
634
+ device,
635
+ num_images_per_prompt,
636
+ do_classifier_free_guidance,
637
+ negative_prompt,
638
+ prompt_embeds=prompt_embeds,
639
+ negative_prompt_embeds=negative_prompt_embeds,
640
+ )
641
+ # For classifier free guidance, we need to do two forward passes.
642
+ # Here we concatenate the unconditional and text embeddings into a single batch
643
+ # to avoid doing two forward passes
644
+ if do_classifier_free_guidance:
645
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
646
+
647
+ # 4. Preprocess image
648
+ rgb, depth = self.image_processor.preprocess(rgb, depth, target_res=target_res)
649
+ rgb = rgb.to(dtype=prompt_embeds.dtype, device=device)
650
+ depth = depth.to(dtype=prompt_embeds.dtype, device=device)
651
+
652
+ # 5. set timesteps
653
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
654
+ timesteps = self.scheduler.timesteps
655
+
656
+ # 6. Encode low resolutiom image to latent space
657
+ image = torch.cat([rgb, depth], axis=1)
658
+ latent_space_image = self.vae.encode(image).latent_dist.sample(generator)
659
+ latent_space_image *= self.vae.scaling_factor
660
+ noise_level = torch.tensor([noise_level], dtype=torch.long, device=device)
661
+ # noise_rgb = randn_tensor(rgb.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)
662
+ # rgb = self.low_res_scheduler.add_noise(rgb, noise_rgb, noise_level)
663
+ # noise_depth = randn_tensor(depth.shape, generator=generator, device=device, dtype=prompt_embeds.dtype)
664
+ # depth = self.low_res_scheduler.add_noise(depth, noise_depth, noise_level)
665
+
666
+ batch_multiplier = 2 if do_classifier_free_guidance else 1
667
+ latent_space_image = torch.cat([latent_space_image] * batch_multiplier * num_images_per_prompt)
668
+ noise_level = torch.cat([noise_level] * latent_space_image.shape[0])
669
+
670
+ # 7. Prepare latent variables
671
+ height, width = latent_space_image.shape[2:]
672
+ num_channels_latents = self.vae.config.latent_channels
673
+
674
+ latents = self.prepare_latents(
675
+ batch_size * num_images_per_prompt,
676
+ num_channels_latents,
677
+ height,
678
+ width,
679
+ prompt_embeds.dtype,
680
+ device,
681
+ generator,
682
+ latents,
683
+ )
684
+
685
+ # 8. Check that sizes of image and latents match
686
+ num_channels_image = latent_space_image.shape[1]
687
+ if num_channels_latents + num_channels_image != self.unet.config.in_channels:
688
+ raise ValueError(
689
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
690
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
691
+ f" `num_channels_image`: {num_channels_image} "
692
+ f" = {num_channels_latents+num_channels_image}. Please verify the config of"
693
+ " `pipeline.unet` or your `image` input."
694
+ )
695
+
696
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
697
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
698
+
699
+ # 10. Denoising loop
700
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
701
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
702
+ for i, t in enumerate(timesteps):
703
+ # expand the latents if we are doing classifier free guidance
704
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
705
+
706
+ # concat latents, mask, masked_image_latents in the channel dimension
707
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
708
+ latent_model_input = torch.cat([latent_model_input, latent_space_image], dim=1)
709
+
710
+ # predict the noise residual
711
+ noise_pred = self.unet(
712
+ latent_model_input,
713
+ t,
714
+ encoder_hidden_states=prompt_embeds,
715
+ cross_attention_kwargs=cross_attention_kwargs,
716
+ class_labels=noise_level,
717
+ return_dict=False,
718
+ )[0]
719
+
720
+ # perform guidance
721
+ if do_classifier_free_guidance:
722
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
723
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
724
+
725
+ # compute the previous noisy sample x_t -> x_t-1
726
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
727
+
728
+ # call the callback, if provided
729
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
730
+ progress_bar.update()
731
+ if callback is not None and i % callback_steps == 0:
732
+ callback(i, t, latents)
733
+
734
+ if not output_type == "latent":
735
+ # make sure the VAE is in float32 mode, as it overflows in float16
736
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
737
+
738
+ if needs_upcasting:
739
+ self.upcast_vae()
740
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
741
+
742
+ image = self.vae.decode(latents / self.vae.scaling_factor, return_dict=False)[0]
743
+
744
+ # cast back to fp16 if needed
745
+ if needs_upcasting:
746
+ self.vae.to(dtype=torch.float16)
747
+
748
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
749
+
750
+ else:
751
+ image = latents
752
+ has_nsfw_concept = None
753
+
754
+ if has_nsfw_concept is None:
755
+ do_denormalize = [True] * image.shape[0]
756
+ else:
757
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
758
+
759
+ rgb, depth = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
760
+
761
+ # 11. Apply watermark
762
+ if output_type == "pil" and self.watermarker is not None:
763
+ rgb = self.watermarker.apply_watermark(rgb)
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 ((rgb, depth), has_nsfw_concept)
771
+
772
+ return LDM3DPipelineOutput(rgb=rgb, depth=depth, nsfw_content_detected=has_nsfw_concept)
v0.30.0/pipeline_stable_diffusion_xl_controlnet_adapter.py ADDED
@@ -0,0 +1,1401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 TencentARC 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
+
16
+ import inspect
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import numpy as np
20
+ import PIL.Image
21
+ import torch
22
+ import torch.nn.functional as F
23
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
24
+
25
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
26
+ from diffusers.loaders import FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
27
+ from diffusers.models import AutoencoderKL, ControlNetModel, MultiAdapter, T2IAdapter, UNet2DConditionModel
28
+ from diffusers.models.attention_processor import AttnProcessor2_0, XFormersAttnProcessor
29
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
30
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
31
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
32
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
33
+ from diffusers.schedulers import KarrasDiffusionSchedulers
34
+ from diffusers.utils import (
35
+ PIL_INTERPOLATION,
36
+ USE_PEFT_BACKEND,
37
+ logging,
38
+ replace_example_docstring,
39
+ scale_lora_layers,
40
+ unscale_lora_layers,
41
+ )
42
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
43
+
44
+
45
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
46
+
47
+ EXAMPLE_DOC_STRING = """
48
+ Examples:
49
+ ```py
50
+ >>> import torch
51
+ >>> from diffusers import T2IAdapter, StableDiffusionXLAdapterPipeline, DDPMScheduler
52
+ >>> from diffusers.utils import load_image
53
+ >>> from controlnet_aux.midas import MidasDetector
54
+
55
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
56
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
57
+
58
+ >>> image = load_image(img_url).resize((1024, 1024))
59
+ >>> mask_image = load_image(mask_url).resize((1024, 1024))
60
+
61
+ >>> midas_depth = MidasDetector.from_pretrained(
62
+ ... "valhalla/t2iadapter-aux-models", filename="dpt_large_384.pt", model_type="dpt_large"
63
+ ... ).to("cuda")
64
+
65
+ >>> depth_image = midas_depth(
66
+ ... image, detect_resolution=512, image_resolution=1024
67
+ ... )
68
+
69
+ >>> model_id = "stabilityai/stable-diffusion-xl-base-1.0"
70
+
71
+ >>> adapter = T2IAdapter.from_pretrained(
72
+ ... "Adapter/t2iadapter",
73
+ ... subfolder="sketch_sdxl_1.0",
74
+ ... torch_dtype=torch.float16,
75
+ ... adapter_type="full_adapter_xl",
76
+ ... )
77
+
78
+ >>> controlnet = ControlNetModel.from_pretrained(
79
+ ... "diffusers/controlnet-depth-sdxl-1.0",
80
+ ... torch_dtype=torch.float16,
81
+ ... variant="fp16",
82
+ ... use_safetensors=True
83
+ ... ).to("cuda")
84
+
85
+ >>> scheduler = DDPMScheduler.from_pretrained(model_id, subfolder="scheduler")
86
+
87
+ >>> pipe = StableDiffusionXLAdapterPipeline.from_pretrained(
88
+ ... model_id,
89
+ ... adapter=adapter,
90
+ ... controlnet=controlnet,
91
+ ... torch_dtype=torch.float16,
92
+ ... variant="fp16",
93
+ ... scheduler=scheduler
94
+ ... ).to("cuda")
95
+
96
+ >>> strength = 0.5
97
+
98
+ >>> generator = torch.manual_seed(42)
99
+ >>> sketch_image_out = pipe(
100
+ ... prompt="a photo of a tiger sitting on a park bench",
101
+ ... negative_prompt="extra digit, fewer digits, cropped, worst quality, low quality",
102
+ ... adapter_image=depth_image,
103
+ ... control_image=mask_image,
104
+ ... adapter_conditioning_scale=strength,
105
+ ... controlnet_conditioning_scale=strength,
106
+ ... generator=generator,
107
+ ... guidance_scale=7.5,
108
+ ... ).images[0]
109
+ ```
110
+ """
111
+
112
+
113
+ def _preprocess_adapter_image(image, height, width):
114
+ if isinstance(image, torch.Tensor):
115
+ return image
116
+ elif isinstance(image, PIL.Image.Image):
117
+ image = [image]
118
+
119
+ if isinstance(image[0], PIL.Image.Image):
120
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
121
+ image = [
122
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
123
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
124
+ image = np.concatenate(image, axis=0)
125
+ image = np.array(image).astype(np.float32) / 255.0
126
+ image = image.transpose(0, 3, 1, 2)
127
+ image = torch.from_numpy(image)
128
+ elif isinstance(image[0], torch.Tensor):
129
+ if image[0].ndim == 3:
130
+ image = torch.stack(image, dim=0)
131
+ elif image[0].ndim == 4:
132
+ image = torch.cat(image, dim=0)
133
+ else:
134
+ raise ValueError(
135
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
136
+ )
137
+ return image
138
+
139
+
140
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
141
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
142
+ """
143
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
144
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
145
+ """
146
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
147
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
148
+ # rescale the results from guidance (fixes overexposure)
149
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
150
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
151
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
152
+ return noise_cfg
153
+
154
+
155
+ class StableDiffusionXLControlNetAdapterPipeline(
156
+ DiffusionPipeline,
157
+ StableDiffusionMixin,
158
+ FromSingleFileMixin,
159
+ StableDiffusionXLLoraLoaderMixin,
160
+ TextualInversionLoaderMixin,
161
+ ):
162
+ r"""
163
+ Pipeline for text-to-image generation using Stable Diffusion augmented with T2I-Adapter
164
+ https://arxiv.org/abs/2302.08453
165
+
166
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
167
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
168
+
169
+ Args:
170
+ adapter ([`T2IAdapter`] or [`MultiAdapter`] or `List[T2IAdapter]`):
171
+ Provides additional conditioning to the unet during the denoising process. If you set multiple Adapter as a
172
+ list, the outputs from each Adapter are added together to create one combined additional conditioning.
173
+ adapter_weights (`List[float]`, *optional*, defaults to None):
174
+ List of floats representing the weight which will be multiply to each adapter's output before adding them
175
+ together.
176
+ vae ([`AutoencoderKL`]):
177
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
178
+ text_encoder ([`CLIPTextModel`]):
179
+ Frozen text-encoder. Stable Diffusion uses the text portion of
180
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
181
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
182
+ tokenizer (`CLIPTokenizer`):
183
+ Tokenizer of class
184
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
185
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
186
+ scheduler ([`SchedulerMixin`]):
187
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
188
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
189
+ safety_checker ([`StableDiffusionSafetyChecker`]):
190
+ Classification module that estimates whether generated images could be considered offensive or harmful.
191
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
192
+ feature_extractor ([`CLIPImageProcessor`]):
193
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
194
+ """
195
+
196
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
197
+ _optional_components = ["tokenizer", "tokenizer_2", "text_encoder", "text_encoder_2"]
198
+
199
+ def __init__(
200
+ self,
201
+ vae: AutoencoderKL,
202
+ text_encoder: CLIPTextModel,
203
+ text_encoder_2: CLIPTextModelWithProjection,
204
+ tokenizer: CLIPTokenizer,
205
+ tokenizer_2: CLIPTokenizer,
206
+ unet: UNet2DConditionModel,
207
+ adapter: Union[T2IAdapter, MultiAdapter, List[T2IAdapter]],
208
+ controlnet: Union[ControlNetModel, MultiControlNetModel],
209
+ scheduler: KarrasDiffusionSchedulers,
210
+ force_zeros_for_empty_prompt: bool = True,
211
+ ):
212
+ super().__init__()
213
+
214
+ if isinstance(controlnet, (list, tuple)):
215
+ controlnet = MultiControlNetModel(controlnet)
216
+
217
+ self.register_modules(
218
+ vae=vae,
219
+ text_encoder=text_encoder,
220
+ text_encoder_2=text_encoder_2,
221
+ tokenizer=tokenizer,
222
+ tokenizer_2=tokenizer_2,
223
+ unet=unet,
224
+ adapter=adapter,
225
+ controlnet=controlnet,
226
+ scheduler=scheduler,
227
+ )
228
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
229
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
230
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
231
+ self.control_image_processor = VaeImageProcessor(
232
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
233
+ )
234
+ self.default_sample_size = self.unet.config.sample_size
235
+
236
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
237
+ def encode_prompt(
238
+ self,
239
+ prompt: str,
240
+ prompt_2: Optional[str] = None,
241
+ device: Optional[torch.device] = None,
242
+ num_images_per_prompt: int = 1,
243
+ do_classifier_free_guidance: bool = True,
244
+ negative_prompt: Optional[str] = None,
245
+ negative_prompt_2: Optional[str] = None,
246
+ prompt_embeds: Optional[torch.Tensor] = None,
247
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
248
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
249
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
250
+ lora_scale: Optional[float] = None,
251
+ clip_skip: Optional[int] = None,
252
+ ):
253
+ r"""
254
+ Encodes the prompt into text encoder hidden states.
255
+
256
+ Args:
257
+ prompt (`str` or `List[str]`, *optional*):
258
+ prompt to be encoded
259
+ prompt_2 (`str` or `List[str]`, *optional*):
260
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
261
+ used in both text-encoders
262
+ device: (`torch.device`):
263
+ torch device
264
+ num_images_per_prompt (`int`):
265
+ number of images that should be generated per prompt
266
+ do_classifier_free_guidance (`bool`):
267
+ whether to use classifier free guidance or not
268
+ negative_prompt (`str` or `List[str]`, *optional*):
269
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
270
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
271
+ less than `1`).
272
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
273
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
274
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
275
+ prompt_embeds (`torch.Tensor`, *optional*):
276
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
277
+ provided, text embeddings will be generated from `prompt` input argument.
278
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
279
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
280
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
281
+ argument.
282
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
283
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
284
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
285
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
286
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
287
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
288
+ input argument.
289
+ lora_scale (`float`, *optional*):
290
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
291
+ clip_skip (`int`, *optional*):
292
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
293
+ the output of the pre-final layer will be used for computing the prompt embeddings.
294
+ """
295
+ device = device or self._execution_device
296
+
297
+ # set lora scale so that monkey patched LoRA
298
+ # function of text encoder can correctly access it
299
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
300
+ self._lora_scale = lora_scale
301
+
302
+ # dynamically adjust the LoRA scale
303
+ if self.text_encoder is not None:
304
+ if not USE_PEFT_BACKEND:
305
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
306
+ else:
307
+ scale_lora_layers(self.text_encoder, lora_scale)
308
+
309
+ if self.text_encoder_2 is not None:
310
+ if not USE_PEFT_BACKEND:
311
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
312
+ else:
313
+ scale_lora_layers(self.text_encoder_2, lora_scale)
314
+
315
+ prompt = [prompt] if isinstance(prompt, str) else prompt
316
+
317
+ if prompt is not None:
318
+ batch_size = len(prompt)
319
+ else:
320
+ batch_size = prompt_embeds.shape[0]
321
+
322
+ # Define tokenizers and text encoders
323
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
324
+ text_encoders = (
325
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
326
+ )
327
+
328
+ if prompt_embeds is None:
329
+ prompt_2 = prompt_2 or prompt
330
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
331
+
332
+ # textual inversion: process multi-vector tokens if necessary
333
+ prompt_embeds_list = []
334
+ prompts = [prompt, prompt_2]
335
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
336
+ if isinstance(self, TextualInversionLoaderMixin):
337
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
338
+
339
+ text_inputs = tokenizer(
340
+ prompt,
341
+ padding="max_length",
342
+ max_length=tokenizer.model_max_length,
343
+ truncation=True,
344
+ return_tensors="pt",
345
+ )
346
+
347
+ text_input_ids = text_inputs.input_ids
348
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
349
+
350
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
351
+ text_input_ids, untruncated_ids
352
+ ):
353
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
354
+ logger.warning(
355
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
356
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
357
+ )
358
+
359
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
360
+
361
+ # We are only ALWAYS interested in the pooled output of the final text encoder
362
+ pooled_prompt_embeds = prompt_embeds[0]
363
+ if clip_skip is None:
364
+ prompt_embeds = prompt_embeds.hidden_states[-2]
365
+ else:
366
+ # "2" because SDXL always indexes from the penultimate layer.
367
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
368
+
369
+ prompt_embeds_list.append(prompt_embeds)
370
+
371
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
372
+
373
+ # get unconditional embeddings for classifier free guidance
374
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
375
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
376
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
377
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
378
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
379
+ negative_prompt = negative_prompt or ""
380
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
381
+
382
+ # normalize str to list
383
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
384
+ negative_prompt_2 = (
385
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
386
+ )
387
+
388
+ uncond_tokens: List[str]
389
+ if prompt is not None and type(prompt) is not type(negative_prompt):
390
+ raise TypeError(
391
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
392
+ f" {type(prompt)}."
393
+ )
394
+ elif batch_size != len(negative_prompt):
395
+ raise ValueError(
396
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
397
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
398
+ " the batch size of `prompt`."
399
+ )
400
+ else:
401
+ uncond_tokens = [negative_prompt, negative_prompt_2]
402
+
403
+ negative_prompt_embeds_list = []
404
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
405
+ if isinstance(self, TextualInversionLoaderMixin):
406
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
407
+
408
+ max_length = prompt_embeds.shape[1]
409
+ uncond_input = tokenizer(
410
+ negative_prompt,
411
+ padding="max_length",
412
+ max_length=max_length,
413
+ truncation=True,
414
+ return_tensors="pt",
415
+ )
416
+
417
+ negative_prompt_embeds = text_encoder(
418
+ uncond_input.input_ids.to(device),
419
+ output_hidden_states=True,
420
+ )
421
+ # We are only ALWAYS interested in the pooled output of the final text encoder
422
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
423
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
424
+
425
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
426
+
427
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
428
+
429
+ if self.text_encoder_2 is not None:
430
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
431
+ else:
432
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
433
+
434
+ bs_embed, seq_len, _ = prompt_embeds.shape
435
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
436
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
437
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
438
+
439
+ if do_classifier_free_guidance:
440
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
441
+ seq_len = negative_prompt_embeds.shape[1]
442
+
443
+ if self.text_encoder_2 is not None:
444
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
445
+ else:
446
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
447
+
448
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
449
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
450
+
451
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
452
+ bs_embed * num_images_per_prompt, -1
453
+ )
454
+ if do_classifier_free_guidance:
455
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
456
+ bs_embed * num_images_per_prompt, -1
457
+ )
458
+
459
+ if self.text_encoder is not None:
460
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
461
+ # Retrieve the original scale by scaling back the LoRA layers
462
+ unscale_lora_layers(self.text_encoder, lora_scale)
463
+
464
+ if self.text_encoder_2 is not None:
465
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
466
+ # Retrieve the original scale by scaling back the LoRA layers
467
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
468
+
469
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
470
+
471
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
472
+ def prepare_extra_step_kwargs(self, generator, eta):
473
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
474
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
475
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
476
+ # and should be between [0, 1]
477
+
478
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
479
+ extra_step_kwargs = {}
480
+ if accepts_eta:
481
+ extra_step_kwargs["eta"] = eta
482
+
483
+ # check if the scheduler accepts generator
484
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
485
+ if accepts_generator:
486
+ extra_step_kwargs["generator"] = generator
487
+ return extra_step_kwargs
488
+
489
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
490
+ def check_image(self, image, prompt, prompt_embeds):
491
+ image_is_pil = isinstance(image, PIL.Image.Image)
492
+ image_is_tensor = isinstance(image, torch.Tensor)
493
+ image_is_np = isinstance(image, np.ndarray)
494
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
495
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
496
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
497
+
498
+ if (
499
+ not image_is_pil
500
+ and not image_is_tensor
501
+ and not image_is_np
502
+ and not image_is_pil_list
503
+ and not image_is_tensor_list
504
+ and not image_is_np_list
505
+ ):
506
+ raise TypeError(
507
+ 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)}"
508
+ )
509
+
510
+ if image_is_pil:
511
+ image_batch_size = 1
512
+ else:
513
+ image_batch_size = len(image)
514
+
515
+ if prompt is not None and isinstance(prompt, str):
516
+ prompt_batch_size = 1
517
+ elif prompt is not None and isinstance(prompt, list):
518
+ prompt_batch_size = len(prompt)
519
+ elif prompt_embeds is not None:
520
+ prompt_batch_size = prompt_embeds.shape[0]
521
+
522
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
523
+ raise ValueError(
524
+ 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}"
525
+ )
526
+
527
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.check_inputs
528
+ def check_inputs(
529
+ self,
530
+ prompt,
531
+ prompt_2,
532
+ height,
533
+ width,
534
+ callback_steps,
535
+ negative_prompt=None,
536
+ negative_prompt_2=None,
537
+ prompt_embeds=None,
538
+ negative_prompt_embeds=None,
539
+ pooled_prompt_embeds=None,
540
+ negative_pooled_prompt_embeds=None,
541
+ callback_on_step_end_tensor_inputs=None,
542
+ ):
543
+ if height % 8 != 0 or width % 8 != 0:
544
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
545
+
546
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
547
+ raise ValueError(
548
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
549
+ f" {type(callback_steps)}."
550
+ )
551
+
552
+ if callback_on_step_end_tensor_inputs is not None and not all(
553
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
554
+ ):
555
+ raise ValueError(
556
+ 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]}"
557
+ )
558
+
559
+ if prompt is not None and prompt_embeds is not None:
560
+ raise ValueError(
561
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
562
+ " only forward one of the two."
563
+ )
564
+ elif prompt_2 is not None and prompt_embeds is not None:
565
+ raise ValueError(
566
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
567
+ " only forward one of the two."
568
+ )
569
+ elif prompt is None and prompt_embeds is None:
570
+ raise ValueError(
571
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
572
+ )
573
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
574
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
575
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
576
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
577
+
578
+ if negative_prompt is not None and negative_prompt_embeds is not None:
579
+ raise ValueError(
580
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
581
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
582
+ )
583
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
584
+ raise ValueError(
585
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
586
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
587
+ )
588
+
589
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
590
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
591
+ raise ValueError(
592
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
593
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
594
+ f" {negative_prompt_embeds.shape}."
595
+ )
596
+
597
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
598
+ raise ValueError(
599
+ "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`."
600
+ )
601
+
602
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
603
+ raise ValueError(
604
+ "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`."
605
+ )
606
+
607
+ def check_conditions(
608
+ self,
609
+ prompt,
610
+ prompt_embeds,
611
+ adapter_image,
612
+ control_image,
613
+ adapter_conditioning_scale,
614
+ controlnet_conditioning_scale,
615
+ control_guidance_start,
616
+ control_guidance_end,
617
+ ):
618
+ # controlnet checks
619
+ if not isinstance(control_guidance_start, (tuple, list)):
620
+ control_guidance_start = [control_guidance_start]
621
+
622
+ if not isinstance(control_guidance_end, (tuple, list)):
623
+ control_guidance_end = [control_guidance_end]
624
+
625
+ if len(control_guidance_start) != len(control_guidance_end):
626
+ raise ValueError(
627
+ 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."
628
+ )
629
+
630
+ if isinstance(self.controlnet, MultiControlNetModel):
631
+ if len(control_guidance_start) != len(self.controlnet.nets):
632
+ raise ValueError(
633
+ 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)}."
634
+ )
635
+
636
+ for start, end in zip(control_guidance_start, control_guidance_end):
637
+ if start >= end:
638
+ raise ValueError(
639
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
640
+ )
641
+ if start < 0.0:
642
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
643
+ if end > 1.0:
644
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
645
+
646
+ # Check controlnet `image`
647
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
648
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
649
+ )
650
+ if (
651
+ isinstance(self.controlnet, ControlNetModel)
652
+ or is_compiled
653
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
654
+ ):
655
+ self.check_image(control_image, prompt, prompt_embeds)
656
+ elif (
657
+ isinstance(self.controlnet, MultiControlNetModel)
658
+ or is_compiled
659
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
660
+ ):
661
+ if not isinstance(control_image, list):
662
+ raise TypeError("For multiple controlnets: `control_image` must be type `list`")
663
+
664
+ # When `image` is a nested list:
665
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
666
+ elif any(isinstance(i, list) for i in control_image):
667
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
668
+ elif len(control_image) != len(self.controlnet.nets):
669
+ raise ValueError(
670
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(control_image)} images and {len(self.controlnet.nets)} ControlNets."
671
+ )
672
+
673
+ for image_ in control_image:
674
+ self.check_image(image_, prompt, prompt_embeds)
675
+ else:
676
+ assert False
677
+
678
+ # Check `controlnet_conditioning_scale`
679
+ if (
680
+ isinstance(self.controlnet, ControlNetModel)
681
+ or is_compiled
682
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
683
+ ):
684
+ if not isinstance(controlnet_conditioning_scale, float):
685
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
686
+ elif (
687
+ isinstance(self.controlnet, MultiControlNetModel)
688
+ or is_compiled
689
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
690
+ ):
691
+ if isinstance(controlnet_conditioning_scale, list):
692
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
693
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
694
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
695
+ self.controlnet.nets
696
+ ):
697
+ raise ValueError(
698
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
699
+ " the same length as the number of controlnets"
700
+ )
701
+ else:
702
+ assert False
703
+
704
+ # adapter checks
705
+ if isinstance(self.adapter, T2IAdapter) or is_compiled and isinstance(self.adapter._orig_mod, T2IAdapter):
706
+ self.check_image(adapter_image, prompt, prompt_embeds)
707
+ elif (
708
+ isinstance(self.adapter, MultiAdapter) or is_compiled and isinstance(self.adapter._orig_mod, MultiAdapter)
709
+ ):
710
+ if not isinstance(adapter_image, list):
711
+ raise TypeError("For multiple adapters: `adapter_image` must be type `list`")
712
+
713
+ # When `image` is a nested list:
714
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
715
+ elif any(isinstance(i, list) for i in adapter_image):
716
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
717
+ elif len(adapter_image) != len(self.adapter.adapters):
718
+ raise ValueError(
719
+ f"For multiple adapters: `image` must have the same length as the number of adapters, but got {len(adapter_image)} images and {len(self.adapters.nets)} Adapters."
720
+ )
721
+
722
+ for image_ in adapter_image:
723
+ self.check_image(image_, prompt, prompt_embeds)
724
+ else:
725
+ assert False
726
+
727
+ # Check `adapter_conditioning_scale`
728
+ if isinstance(self.adapter, T2IAdapter) or is_compiled and isinstance(self.adapter._orig_mod, T2IAdapter):
729
+ if not isinstance(adapter_conditioning_scale, float):
730
+ raise TypeError("For single adapter: `adapter_conditioning_scale` must be type `float`.")
731
+ elif (
732
+ isinstance(self.adapter, MultiAdapter) or is_compiled and isinstance(self.adapter._orig_mod, MultiAdapter)
733
+ ):
734
+ if isinstance(adapter_conditioning_scale, list):
735
+ if any(isinstance(i, list) for i in adapter_conditioning_scale):
736
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
737
+ elif isinstance(adapter_conditioning_scale, list) and len(adapter_conditioning_scale) != len(
738
+ self.adapter.adapters
739
+ ):
740
+ raise ValueError(
741
+ "For multiple adapters: When `adapter_conditioning_scale` is specified as `list`, it must have"
742
+ " the same length as the number of adapters"
743
+ )
744
+ else:
745
+ assert False
746
+
747
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
748
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
749
+ shape = (
750
+ batch_size,
751
+ num_channels_latents,
752
+ int(height) // self.vae_scale_factor,
753
+ int(width) // self.vae_scale_factor,
754
+ )
755
+ if isinstance(generator, list) and len(generator) != batch_size:
756
+ raise ValueError(
757
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
758
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
759
+ )
760
+
761
+ if latents is None:
762
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
763
+ else:
764
+ latents = latents.to(device)
765
+
766
+ # scale the initial noise by the standard deviation required by the scheduler
767
+ latents = latents * self.scheduler.init_noise_sigma
768
+ return latents
769
+
770
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline._get_add_time_ids
771
+ def _get_add_time_ids(
772
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
773
+ ):
774
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
775
+
776
+ passed_add_embed_dim = (
777
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
778
+ )
779
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
780
+
781
+ if expected_add_embed_dim != passed_add_embed_dim:
782
+ raise ValueError(
783
+ 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`."
784
+ )
785
+
786
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
787
+ return add_time_ids
788
+
789
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
790
+ def upcast_vae(self):
791
+ dtype = self.vae.dtype
792
+ self.vae.to(dtype=torch.float32)
793
+ use_torch_2_0_or_xformers = isinstance(
794
+ self.vae.decoder.mid_block.attentions[0].processor,
795
+ (AttnProcessor2_0, XFormersAttnProcessor),
796
+ )
797
+ # if xformers or torch_2_0 is used attention block does not need
798
+ # to be in float32 which can save lots of memory
799
+ if use_torch_2_0_or_xformers:
800
+ self.vae.post_quant_conv.to(dtype)
801
+ self.vae.decoder.conv_in.to(dtype)
802
+ self.vae.decoder.mid_block.to(dtype)
803
+
804
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
805
+ def _default_height_width(self, height, width, image):
806
+ # NOTE: It is possible that a list of images have different
807
+ # dimensions for each image, so just checking the first image
808
+ # is not _exactly_ correct, but it is simple.
809
+ while isinstance(image, list):
810
+ image = image[0]
811
+
812
+ if height is None:
813
+ if isinstance(image, PIL.Image.Image):
814
+ height = image.height
815
+ elif isinstance(image, torch.Tensor):
816
+ height = image.shape[-2]
817
+
818
+ # round down to nearest multiple of `self.adapter.downscale_factor`
819
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
820
+
821
+ if width is None:
822
+ if isinstance(image, PIL.Image.Image):
823
+ width = image.width
824
+ elif isinstance(image, torch.Tensor):
825
+ width = image.shape[-1]
826
+
827
+ # round down to nearest multiple of `self.adapter.downscale_factor`
828
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
829
+
830
+ return height, width
831
+
832
+ def prepare_control_image(
833
+ self,
834
+ image,
835
+ width,
836
+ height,
837
+ batch_size,
838
+ num_images_per_prompt,
839
+ device,
840
+ dtype,
841
+ do_classifier_free_guidance=False,
842
+ guess_mode=False,
843
+ ):
844
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
845
+ image_batch_size = image.shape[0]
846
+
847
+ if image_batch_size == 1:
848
+ repeat_by = batch_size
849
+ else:
850
+ # image batch size is the same as prompt batch size
851
+ repeat_by = num_images_per_prompt
852
+
853
+ image = image.repeat_interleave(repeat_by, dim=0)
854
+
855
+ image = image.to(device=device, dtype=dtype)
856
+
857
+ if do_classifier_free_guidance and not guess_mode:
858
+ image = torch.cat([image] * 2)
859
+
860
+ return image
861
+
862
+ @torch.no_grad()
863
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
864
+ def __call__(
865
+ self,
866
+ prompt: Union[str, List[str]] = None,
867
+ prompt_2: Optional[Union[str, List[str]]] = None,
868
+ adapter_image: PipelineImageInput = None,
869
+ control_image: PipelineImageInput = None,
870
+ height: Optional[int] = None,
871
+ width: Optional[int] = None,
872
+ num_inference_steps: int = 50,
873
+ denoising_end: Optional[float] = None,
874
+ guidance_scale: float = 5.0,
875
+ negative_prompt: Optional[Union[str, List[str]]] = None,
876
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
877
+ num_images_per_prompt: Optional[int] = 1,
878
+ eta: float = 0.0,
879
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
880
+ latents: Optional[torch.Tensor] = None,
881
+ prompt_embeds: Optional[torch.Tensor] = None,
882
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
883
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
884
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
885
+ output_type: Optional[str] = "pil",
886
+ return_dict: bool = True,
887
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
888
+ callback_steps: int = 1,
889
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
890
+ guidance_rescale: float = 0.0,
891
+ original_size: Optional[Tuple[int, int]] = None,
892
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
893
+ target_size: Optional[Tuple[int, int]] = None,
894
+ negative_original_size: Optional[Tuple[int, int]] = None,
895
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
896
+ negative_target_size: Optional[Tuple[int, int]] = None,
897
+ adapter_conditioning_scale: Union[float, List[float]] = 1.0,
898
+ adapter_conditioning_factor: float = 1.0,
899
+ clip_skip: Optional[int] = None,
900
+ controlnet_conditioning_scale=1.0,
901
+ guess_mode: bool = False,
902
+ control_guidance_start: float = 0.0,
903
+ control_guidance_end: float = 1.0,
904
+ ):
905
+ r"""
906
+ Function invoked when calling the pipeline for generation.
907
+
908
+ Args:
909
+ prompt (`str` or `List[str]`, *optional*):
910
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
911
+ instead.
912
+ prompt_2 (`str` or `List[str]`, *optional*):
913
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
914
+ used in both text-encoders
915
+ adapter_image (`torch.Tensor`, `PIL.Image.Image`, `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[List[PIL.Image.Image]]`):
916
+ The Adapter input condition. Adapter uses this input condition to generate guidance to Unet. If the
917
+ type is specified as `torch.Tensor`, it is passed to Adapter as is. PIL.Image.Image` can also be
918
+ accepted as an image. The control image is automatically resized to fit the output image.
919
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
920
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
921
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
922
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
923
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
924
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
925
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
926
+ input to a single ControlNet.
927
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
928
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
929
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
930
+ and checkpoints that are not specifically fine-tuned on low resolutions.
931
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
932
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
933
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
934
+ and checkpoints that are not specifically fine-tuned on low resolutions.
935
+ num_inference_steps (`int`, *optional*, defaults to 50):
936
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
937
+ expense of slower inference.
938
+ denoising_end (`float`, *optional*):
939
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
940
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
941
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
942
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
943
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
944
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
945
+ guidance_scale (`float`, *optional*, defaults to 5.0):
946
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
947
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
948
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
949
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
950
+ usually at the expense of lower image quality.
951
+ negative_prompt (`str` or `List[str]`, *optional*):
952
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
953
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
954
+ less than `1`).
955
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
956
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
957
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
958
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
959
+ The number of images to generate per prompt.
960
+ eta (`float`, *optional*, defaults to 0.0):
961
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
962
+ [`schedulers.DDIMScheduler`], will be ignored for others.
963
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
964
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
965
+ to make generation deterministic.
966
+ latents (`torch.Tensor`, *optional*):
967
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
968
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
969
+ tensor will ge generated by sampling using the supplied random `generator`.
970
+ prompt_embeds (`torch.Tensor`, *optional*):
971
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
972
+ provided, text embeddings will be generated from `prompt` input argument.
973
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
974
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
975
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
976
+ argument.
977
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
978
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
979
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
980
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
981
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
982
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
983
+ input argument.
984
+ output_type (`str`, *optional*, defaults to `"pil"`):
985
+ The output format of the generate image. Choose between
986
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
987
+ return_dict (`bool`, *optional*, defaults to `True`):
988
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionAdapterPipelineOutput`]
989
+ instead of a plain tuple.
990
+ callback (`Callable`, *optional*):
991
+ A function that will be called every `callback_steps` steps during inference. The function will be
992
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
993
+ callback_steps (`int`, *optional*, defaults to 1):
994
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
995
+ called at every step.
996
+ cross_attention_kwargs (`dict`, *optional*):
997
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
998
+ `self.processor` in
999
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1000
+ guidance_rescale (`float`, *optional*, defaults to 0.0):
1001
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1002
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1003
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1004
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1005
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1006
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1007
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
1008
+ explained in section 2.2 of
1009
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1010
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1011
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1012
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1013
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1014
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1015
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1016
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1017
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
1018
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1019
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1020
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1021
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
1022
+ micro-conditioning as explained in section 2.2 of
1023
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1024
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1025
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1026
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
1027
+ micro-conditioning as explained in section 2.2 of
1028
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1029
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1030
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1031
+ To negatively condition the generation process based on a target image resolution. It should be as same
1032
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
1033
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
1034
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
1035
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1036
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added to the
1037
+ residual in the original unet. If multiple adapters are specified in init, you can set the
1038
+ corresponding scale as a list.
1039
+ adapter_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1040
+ The outputs of the adapter are multiplied by `adapter_conditioning_scale` before they are added to the
1041
+ residual in the original unet. If multiple adapters are specified in init, you can set the
1042
+ corresponding scale as a list.
1043
+ adapter_conditioning_factor (`float`, *optional*, defaults to 1.0):
1044
+ The fraction of timesteps for which adapter should be applied. If `adapter_conditioning_factor` is
1045
+ `0.0`, adapter is not applied at all. If `adapter_conditioning_factor` is `1.0`, adapter is applied for
1046
+ all timesteps. If `adapter_conditioning_factor` is `0.5`, adapter is applied for half of the timesteps.
1047
+ clip_skip (`int`, *optional*):
1048
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1049
+ the output of the pre-final layer will be used for computing the prompt embeddings.
1050
+
1051
+ Examples:
1052
+
1053
+ Returns:
1054
+ [`~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput`] or `tuple`:
1055
+ [`~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput`] if `return_dict` is True, otherwise a
1056
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1057
+ """
1058
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1059
+ adapter = self.adapter._orig_mod if is_compiled_module(self.adapter) else self.adapter
1060
+
1061
+ # 0. Default height and width to unet
1062
+
1063
+ height, width = self._default_height_width(height, width, adapter_image)
1064
+ device = self._execution_device
1065
+
1066
+ if isinstance(adapter, MultiAdapter):
1067
+ adapter_input = []
1068
+
1069
+ for one_image in adapter_image:
1070
+ one_image = _preprocess_adapter_image(one_image, height, width)
1071
+ one_image = one_image.to(device=device, dtype=adapter.dtype)
1072
+ adapter_input.append(one_image)
1073
+ else:
1074
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1075
+ adapter_input = adapter_input.to(device=device, dtype=adapter.dtype)
1076
+ original_size = original_size or (height, width)
1077
+ target_size = target_size or (height, width)
1078
+
1079
+ # 0.1 align format for control guidance
1080
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1081
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1082
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1083
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1084
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1085
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1086
+ control_guidance_start, control_guidance_end = (
1087
+ mult * [control_guidance_start],
1088
+ mult * [control_guidance_end],
1089
+ )
1090
+
1091
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1092
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1093
+ if isinstance(adapter, MultiAdapter) and isinstance(adapter_conditioning_scale, float):
1094
+ adapter_conditioning_scale = [adapter_conditioning_scale] * len(adapter.adapters)
1095
+
1096
+ # 1. Check inputs. Raise error if not correct
1097
+ self.check_inputs(
1098
+ prompt,
1099
+ prompt_2,
1100
+ height,
1101
+ width,
1102
+ callback_steps,
1103
+ negative_prompt=negative_prompt,
1104
+ negative_prompt_2=negative_prompt_2,
1105
+ prompt_embeds=prompt_embeds,
1106
+ negative_prompt_embeds=negative_prompt_embeds,
1107
+ pooled_prompt_embeds=pooled_prompt_embeds,
1108
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1109
+ )
1110
+
1111
+ self.check_conditions(
1112
+ prompt,
1113
+ prompt_embeds,
1114
+ adapter_image,
1115
+ control_image,
1116
+ adapter_conditioning_scale,
1117
+ controlnet_conditioning_scale,
1118
+ control_guidance_start,
1119
+ control_guidance_end,
1120
+ )
1121
+
1122
+ # 2. Define call parameters
1123
+ if prompt is not None and isinstance(prompt, str):
1124
+ batch_size = 1
1125
+ elif prompt is not None and isinstance(prompt, list):
1126
+ batch_size = len(prompt)
1127
+ else:
1128
+ batch_size = prompt_embeds.shape[0]
1129
+
1130
+ device = self._execution_device
1131
+
1132
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1133
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1134
+ # corresponds to doing no classifier free guidance.
1135
+ do_classifier_free_guidance = guidance_scale > 1.0
1136
+
1137
+ # 3. Encode input prompt
1138
+ (
1139
+ prompt_embeds,
1140
+ negative_prompt_embeds,
1141
+ pooled_prompt_embeds,
1142
+ negative_pooled_prompt_embeds,
1143
+ ) = self.encode_prompt(
1144
+ prompt=prompt,
1145
+ prompt_2=prompt_2,
1146
+ device=device,
1147
+ num_images_per_prompt=num_images_per_prompt,
1148
+ do_classifier_free_guidance=do_classifier_free_guidance,
1149
+ negative_prompt=negative_prompt,
1150
+ negative_prompt_2=negative_prompt_2,
1151
+ prompt_embeds=prompt_embeds,
1152
+ negative_prompt_embeds=negative_prompt_embeds,
1153
+ pooled_prompt_embeds=pooled_prompt_embeds,
1154
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1155
+ clip_skip=clip_skip,
1156
+ )
1157
+
1158
+ # 4. Prepare timesteps
1159
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1160
+
1161
+ timesteps = self.scheduler.timesteps
1162
+
1163
+ # 5. Prepare latent variables
1164
+ num_channels_latents = self.unet.config.in_channels
1165
+ latents = self.prepare_latents(
1166
+ batch_size * num_images_per_prompt,
1167
+ num_channels_latents,
1168
+ height,
1169
+ width,
1170
+ prompt_embeds.dtype,
1171
+ device,
1172
+ generator,
1173
+ latents,
1174
+ )
1175
+
1176
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1177
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1178
+
1179
+ # 7. Prepare added time ids & embeddings & adapter features
1180
+ if isinstance(adapter, MultiAdapter):
1181
+ adapter_state = adapter(adapter_input, adapter_conditioning_scale)
1182
+ for k, v in enumerate(adapter_state):
1183
+ adapter_state[k] = v
1184
+ else:
1185
+ adapter_state = adapter(adapter_input)
1186
+ for k, v in enumerate(adapter_state):
1187
+ adapter_state[k] = v * adapter_conditioning_scale
1188
+ if num_images_per_prompt > 1:
1189
+ for k, v in enumerate(adapter_state):
1190
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1191
+ if do_classifier_free_guidance:
1192
+ for k, v in enumerate(adapter_state):
1193
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1194
+
1195
+ # 7.2 Prepare control images
1196
+ if isinstance(controlnet, ControlNetModel):
1197
+ control_image = self.prepare_control_image(
1198
+ image=control_image,
1199
+ width=width,
1200
+ height=height,
1201
+ batch_size=batch_size * num_images_per_prompt,
1202
+ num_images_per_prompt=num_images_per_prompt,
1203
+ device=device,
1204
+ dtype=controlnet.dtype,
1205
+ do_classifier_free_guidance=do_classifier_free_guidance,
1206
+ guess_mode=guess_mode,
1207
+ )
1208
+ elif isinstance(controlnet, MultiControlNetModel):
1209
+ control_images = []
1210
+
1211
+ for control_image_ in control_image:
1212
+ control_image_ = self.prepare_control_image(
1213
+ image=control_image_,
1214
+ width=width,
1215
+ height=height,
1216
+ batch_size=batch_size * num_images_per_prompt,
1217
+ num_images_per_prompt=num_images_per_prompt,
1218
+ device=device,
1219
+ dtype=controlnet.dtype,
1220
+ do_classifier_free_guidance=do_classifier_free_guidance,
1221
+ guess_mode=guess_mode,
1222
+ )
1223
+
1224
+ control_images.append(control_image_)
1225
+
1226
+ control_image = control_images
1227
+ else:
1228
+ raise ValueError(f"{controlnet.__class__} is not supported.")
1229
+
1230
+ # 8.2 Create tensor stating which controlnets to keep
1231
+ controlnet_keep = []
1232
+ for i in range(len(timesteps)):
1233
+ keeps = [
1234
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1235
+ for s, e in zip(control_guidance_start, control_guidance_end)
1236
+ ]
1237
+ if isinstance(self.controlnet, MultiControlNetModel):
1238
+ controlnet_keep.append(keeps)
1239
+ else:
1240
+ controlnet_keep.append(keeps[0])
1241
+
1242
+ add_text_embeds = pooled_prompt_embeds
1243
+ if self.text_encoder_2 is None:
1244
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1245
+ else:
1246
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1247
+
1248
+ add_time_ids = self._get_add_time_ids(
1249
+ original_size,
1250
+ crops_coords_top_left,
1251
+ target_size,
1252
+ dtype=prompt_embeds.dtype,
1253
+ text_encoder_projection_dim=text_encoder_projection_dim,
1254
+ )
1255
+ if negative_original_size is not None and negative_target_size is not None:
1256
+ negative_add_time_ids = self._get_add_time_ids(
1257
+ negative_original_size,
1258
+ negative_crops_coords_top_left,
1259
+ negative_target_size,
1260
+ dtype=prompt_embeds.dtype,
1261
+ text_encoder_projection_dim=text_encoder_projection_dim,
1262
+ )
1263
+ else:
1264
+ negative_add_time_ids = add_time_ids
1265
+
1266
+ if do_classifier_free_guidance:
1267
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1268
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1269
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1270
+
1271
+ prompt_embeds = prompt_embeds.to(device)
1272
+ add_text_embeds = add_text_embeds.to(device)
1273
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1274
+
1275
+ # 8. Denoising loop
1276
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1277
+
1278
+ # 7.1 Apply denoising_end
1279
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
1280
+ discrete_timestep_cutoff = int(
1281
+ round(
1282
+ self.scheduler.config.num_train_timesteps
1283
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1284
+ )
1285
+ )
1286
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1287
+ timesteps = timesteps[:num_inference_steps]
1288
+
1289
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1290
+ for i, t in enumerate(timesteps):
1291
+ # expand the latents if we are doing classifier free guidance
1292
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1293
+
1294
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1295
+
1296
+ # predict the noise residual
1297
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1298
+
1299
+ if i < int(num_inference_steps * adapter_conditioning_factor):
1300
+ down_intrablock_additional_residuals = [state.clone() for state in adapter_state]
1301
+ else:
1302
+ down_intrablock_additional_residuals = None
1303
+
1304
+ # ----------- ControlNet
1305
+
1306
+ # expand the latents if we are doing classifier free guidance
1307
+ latent_model_input_controlnet = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1308
+
1309
+ # concat latents, mask, masked_image_latents in the channel dimension
1310
+ latent_model_input_controlnet = self.scheduler.scale_model_input(latent_model_input_controlnet, t)
1311
+
1312
+ # controlnet(s) inference
1313
+ if guess_mode and do_classifier_free_guidance:
1314
+ # Infer ControlNet only for the conditional batch.
1315
+ control_model_input = latents
1316
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1317
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1318
+ controlnet_added_cond_kwargs = {
1319
+ "text_embeds": add_text_embeds.chunk(2)[1],
1320
+ "time_ids": add_time_ids.chunk(2)[1],
1321
+ }
1322
+ else:
1323
+ control_model_input = latent_model_input_controlnet
1324
+ controlnet_prompt_embeds = prompt_embeds
1325
+ controlnet_added_cond_kwargs = added_cond_kwargs
1326
+
1327
+ if isinstance(controlnet_keep[i], list):
1328
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1329
+ else:
1330
+ controlnet_cond_scale = controlnet_conditioning_scale
1331
+ if isinstance(controlnet_cond_scale, list):
1332
+ controlnet_cond_scale = controlnet_cond_scale[0]
1333
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1334
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1335
+ control_model_input,
1336
+ t,
1337
+ encoder_hidden_states=controlnet_prompt_embeds,
1338
+ controlnet_cond=control_image,
1339
+ conditioning_scale=cond_scale,
1340
+ guess_mode=guess_mode,
1341
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1342
+ return_dict=False,
1343
+ )
1344
+
1345
+ noise_pred = self.unet(
1346
+ latent_model_input,
1347
+ t,
1348
+ encoder_hidden_states=prompt_embeds,
1349
+ cross_attention_kwargs=cross_attention_kwargs,
1350
+ added_cond_kwargs=added_cond_kwargs,
1351
+ return_dict=False,
1352
+ down_intrablock_additional_residuals=down_intrablock_additional_residuals, # t2iadapter
1353
+ down_block_additional_residuals=down_block_res_samples, # controlnet
1354
+ mid_block_additional_residual=mid_block_res_sample, # controlnet
1355
+ )[0]
1356
+
1357
+ # perform guidance
1358
+ if do_classifier_free_guidance:
1359
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1360
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1361
+
1362
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1363
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1364
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1365
+
1366
+ # compute the previous noisy sample x_t -> x_t-1
1367
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1368
+
1369
+ # call the callback, if provided
1370
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1371
+ progress_bar.update()
1372
+ if callback is not None and i % callback_steps == 0:
1373
+ step_idx = i // getattr(self.scheduler, "order", 1)
1374
+ callback(step_idx, t, latents)
1375
+
1376
+ if not output_type == "latent":
1377
+ # make sure the VAE is in float32 mode, as it overflows in float16
1378
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1379
+
1380
+ if needs_upcasting:
1381
+ self.upcast_vae()
1382
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1383
+
1384
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1385
+
1386
+ # cast back to fp16 if needed
1387
+ if needs_upcasting:
1388
+ self.vae.to(dtype=torch.float16)
1389
+ else:
1390
+ image = latents
1391
+ return StableDiffusionXLPipelineOutput(images=image)
1392
+
1393
+ image = self.image_processor.postprocess(image, output_type=output_type)
1394
+
1395
+ # Offload all models
1396
+ self.maybe_free_model_hooks()
1397
+
1398
+ if not return_dict:
1399
+ return (image,)
1400
+
1401
+ return StableDiffusionXLPipelineOutput(images=image)
v0.30.0/pipeline_stable_diffusion_xl_controlnet_adapter_inpaint.py ADDED
@@ -0,0 +1,1840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Jake Babbidge, TencentARC 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
+ # ignore the entire file for precommit
16
+ # type: ignore
17
+
18
+ import inspect
19
+ from collections.abc import Callable
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import PIL
24
+ import torch
25
+ import torch.nn.functional as F
26
+ from transformers import (
27
+ CLIPTextModel,
28
+ CLIPTextModelWithProjection,
29
+ CLIPTokenizer,
30
+ )
31
+
32
+ from diffusers import DiffusionPipeline
33
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
34
+ from diffusers.loaders import (
35
+ FromSingleFileMixin,
36
+ StableDiffusionLoraLoaderMixin,
37
+ StableDiffusionXLLoraLoaderMixin,
38
+ TextualInversionLoaderMixin,
39
+ )
40
+ from diffusers.models import (
41
+ AutoencoderKL,
42
+ ControlNetModel,
43
+ MultiAdapter,
44
+ T2IAdapter,
45
+ UNet2DConditionModel,
46
+ )
47
+ from diffusers.models.attention_processor import AttnProcessor2_0, XFormersAttnProcessor
48
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
49
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
50
+ from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
51
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
52
+ from diffusers.schedulers import KarrasDiffusionSchedulers
53
+ from diffusers.utils import (
54
+ PIL_INTERPOLATION,
55
+ USE_PEFT_BACKEND,
56
+ logging,
57
+ replace_example_docstring,
58
+ scale_lora_layers,
59
+ unscale_lora_layers,
60
+ )
61
+ from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
62
+
63
+
64
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
65
+
66
+ EXAMPLE_DOC_STRING = """
67
+ Examples:
68
+ ```py
69
+ >>> import torch
70
+ >>> from diffusers import DiffusionPipeline, T2IAdapter
71
+ >>> from diffusers.utils import load_image
72
+ >>> from PIL import Image
73
+ >>> from controlnet_aux.midas import MidasDetector
74
+
75
+ >>> adapter = T2IAdapter.from_pretrained(
76
+ ... "TencentARC/t2i-adapter-sketch-sdxl-1.0", torch_dtype=torch.float16, variant="fp16"
77
+ ... ).to("cuda")
78
+
79
+ >>> controlnet = ControlNetModel.from_pretrained(
80
+ ... "diffusers/controlnet-depth-sdxl-1.0",
81
+ ... torch_dtype=torch.float16,
82
+ ... variant="fp16",
83
+ ... use_safetensors=True
84
+ ... ).to("cuda")
85
+
86
+ >>> pipe = DiffusionPipeline.from_pretrained(
87
+ ... "diffusers/stable-diffusion-xl-1.0-inpainting-0.1",
88
+ ... torch_dtype=torch.float16,
89
+ ... variant="fp16",
90
+ ... use_safetensors=True,
91
+ ... custom_pipeline="stable_diffusion_xl_adapter_controlnet_inpaint",
92
+ ... adapter=adapter,
93
+ ... controlnet=controlnet,
94
+ ... ).to("cuda")
95
+
96
+ >>> prompt = "a tiger sitting on a park bench"
97
+ >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png"
98
+ >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png"
99
+
100
+ >>> image = load_image(img_url).resize((1024, 1024))
101
+ >>> mask_image = load_image(mask_url).resize((1024, 1024))
102
+
103
+ >>> midas_depth = MidasDetector.from_pretrained(
104
+ ... "valhalla/t2iadapter-aux-models", filename="dpt_large_384.pt", model_type="dpt_large"
105
+ ... ).to("cuda")
106
+
107
+ >>> depth_image = midas_depth(
108
+ ... image, detect_resolution=512, image_resolution=1024
109
+ ... )
110
+
111
+ >>> strength = 0.4
112
+
113
+ >>> generator = torch.manual_seed(42)
114
+
115
+ >>> result_image = pipe(
116
+ ... image=image,
117
+ ... mask_image=mask,
118
+ ... adapter_image=depth_image,
119
+ ... control_image=depth_image,
120
+ ... controlnet_conditioning_scale=strength,
121
+ ... adapter_conditioning_scale=strength,
122
+ ... strength=0.7,
123
+ ... generator=generator,
124
+ ... prompt=prompt,
125
+ ... negative_prompt="extra digit, fewer digits, cropped, worst quality, low quality",
126
+ ... num_inference_steps=50
127
+ ... ).images[0]
128
+ ```
129
+ """
130
+
131
+
132
+ def _preprocess_adapter_image(image, height, width):
133
+ if isinstance(image, torch.Tensor):
134
+ return image
135
+ elif isinstance(image, PIL.Image.Image):
136
+ image = [image]
137
+
138
+ if isinstance(image[0], PIL.Image.Image):
139
+ image = [np.array(i.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])) for i in image]
140
+ image = [
141
+ i[None, ..., None] if i.ndim == 2 else i[None, ...] for i in image
142
+ ] # expand [h, w] or [h, w, c] to [b, h, w, c]
143
+ image = np.concatenate(image, axis=0)
144
+ image = np.array(image).astype(np.float32) / 255.0
145
+ image = image.transpose(0, 3, 1, 2)
146
+ image = torch.from_numpy(image)
147
+ elif isinstance(image[0], torch.Tensor):
148
+ if image[0].ndim == 3:
149
+ image = torch.stack(image, dim=0)
150
+ elif image[0].ndim == 4:
151
+ image = torch.cat(image, dim=0)
152
+ else:
153
+ raise ValueError(
154
+ f"Invalid image tensor! Expecting image tensor with 3 or 4 dimension, but recive: {image[0].ndim}"
155
+ )
156
+ return image
157
+
158
+
159
+ def mask_pil_to_torch(mask, height, width):
160
+ # preprocess mask
161
+ if isinstance(mask, Union[PIL.Image.Image, np.ndarray]):
162
+ mask = [mask]
163
+
164
+ if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image):
165
+ mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask]
166
+ mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0)
167
+ mask = mask.astype(np.float32) / 255.0
168
+ elif isinstance(mask, list) and isinstance(mask[0], np.ndarray):
169
+ mask = np.concatenate([m[None, None, :] for m in mask], axis=0)
170
+
171
+ mask = torch.from_numpy(mask)
172
+ return mask
173
+
174
+
175
+ def prepare_mask_and_masked_image(image, mask, height, width, return_image: bool = False):
176
+ """
177
+ Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be
178
+ converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the
179
+ ``image`` and ``1`` for the ``mask``.
180
+
181
+ The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be
182
+ binarized (``mask > 0.5``) and cast to ``torch.float32`` too.
183
+
184
+ Args:
185
+ image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint.
186
+ It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width``
187
+ ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``.
188
+ mask (_type_): The mask to apply to the image, i.e. regions to inpaint.
189
+ It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width``
190
+ ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``.
191
+
192
+
193
+ Raises:
194
+ ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask
195
+ should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions.
196
+ TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not
197
+ (ot the other way around).
198
+
199
+ Returns:
200
+ tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4
201
+ dimensions: ``batch x channels x height x width``.
202
+ """
203
+
204
+ # checkpoint. #TODO(Yiyi) - need to clean this up later
205
+ if image is None:
206
+ raise ValueError("`image` input cannot be undefined.")
207
+
208
+ if mask is None:
209
+ raise ValueError("`mask_image` input cannot be undefined.")
210
+
211
+ if isinstance(image, torch.Tensor):
212
+ if not isinstance(mask, torch.Tensor):
213
+ mask = mask_pil_to_torch(mask, height, width)
214
+
215
+ if image.ndim == 3:
216
+ image = image.unsqueeze(0)
217
+
218
+ # Batch and add channel dim for single mask
219
+ if mask.ndim == 2:
220
+ mask = mask.unsqueeze(0).unsqueeze(0)
221
+
222
+ # Batch single mask or add channel dim
223
+ if mask.ndim == 3:
224
+ # Single batched mask, no channel dim or single mask not batched but channel dim
225
+ if mask.shape[0] == 1:
226
+ mask = mask.unsqueeze(0)
227
+
228
+ # Batched masks no channel dim
229
+ else:
230
+ mask = mask.unsqueeze(1)
231
+
232
+ assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions"
233
+ # assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions"
234
+ assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size"
235
+
236
+ # Check image is in [-1, 1]
237
+ # if image.min() < -1 or image.max() > 1:
238
+ # raise ValueError("Image should be in [-1, 1] range")
239
+
240
+ # Check mask is in [0, 1]
241
+ if mask.min() < 0 or mask.max() > 1:
242
+ raise ValueError("Mask should be in [0, 1] range")
243
+
244
+ # Binarize mask
245
+ mask[mask < 0.5] = 0
246
+ mask[mask >= 0.5] = 1
247
+
248
+ # Image as float32
249
+ image = image.to(dtype=torch.float32)
250
+ elif isinstance(mask, torch.Tensor):
251
+ raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not")
252
+ else:
253
+ # preprocess image
254
+ if isinstance(image, Union[PIL.Image.Image, np.ndarray]):
255
+ image = [image]
256
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
257
+ # resize all images w.r.t passed height an width
258
+ image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image]
259
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
260
+ image = np.concatenate(image, axis=0)
261
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
262
+ image = np.concatenate([i[None, :] for i in image], axis=0)
263
+
264
+ image = image.transpose(0, 3, 1, 2)
265
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
266
+
267
+ mask = mask_pil_to_torch(mask, height, width)
268
+ mask[mask < 0.5] = 0
269
+ mask[mask >= 0.5] = 1
270
+
271
+ if image.shape[1] == 4:
272
+ # images are in latent space and thus can't
273
+ # be masked set masked_image to None
274
+ # we assume that the checkpoint is not an inpainting
275
+ # checkpoint. #TODO(Yiyi) - need to clean this up later
276
+ masked_image = None
277
+ else:
278
+ masked_image = image * (mask < 0.5)
279
+
280
+ # n.b. ensure backwards compatibility as old function does not return image
281
+ if return_image:
282
+ return mask, masked_image, image
283
+
284
+ return mask, masked_image
285
+
286
+
287
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
288
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
289
+ """
290
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
291
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
292
+ """
293
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
294
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
295
+ # rescale the results from guidance (fixes overexposure)
296
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
297
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
298
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
299
+ return noise_cfg
300
+
301
+
302
+ class StableDiffusionXLControlNetAdapterInpaintPipeline(
303
+ DiffusionPipeline, StableDiffusionMixin, FromSingleFileMixin, StableDiffusionLoraLoaderMixin
304
+ ):
305
+ r"""
306
+ Pipeline for text-to-image generation using Stable Diffusion augmented with T2I-Adapter
307
+ https://arxiv.org/abs/2302.08453
308
+
309
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
310
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
311
+
312
+ Args:
313
+ adapter ([`T2IAdapter`] or [`MultiAdapter`] or `List[T2IAdapter]`):
314
+ Provides additional conditioning to the unet during the denoising process. If you set multiple Adapter as a
315
+ list, the outputs from each Adapter are added together to create one combined additional conditioning.
316
+ adapter_weights (`List[float]`, *optional*, defaults to None):
317
+ List of floats representing the weight which will be multiply to each adapter's output before adding them
318
+ together.
319
+ vae ([`AutoencoderKL`]):
320
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
321
+ text_encoder ([`CLIPTextModel`]):
322
+ Frozen text-encoder. Stable Diffusion uses the text portion of
323
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
324
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
325
+ tokenizer (`CLIPTokenizer`):
326
+ Tokenizer of class
327
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
328
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
329
+ scheduler ([`SchedulerMixin`]):
330
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
331
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
332
+ safety_checker ([`StableDiffusionSafetyChecker`]):
333
+ Classification module that estimates whether generated images could be considered offensive or harmful.
334
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
335
+ feature_extractor ([`CLIPImageProcessor`]):
336
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
337
+ requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
338
+ Whether the `unet` requires a aesthetic_score condition to be passed during inference. Also see the config
339
+ of `stabilityai/stable-diffusion-xl-refiner-1-0`.
340
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
341
+ Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
342
+ `stabilityai/stable-diffusion-xl-base-1-0`.
343
+ """
344
+
345
+ def __init__(
346
+ self,
347
+ vae: AutoencoderKL,
348
+ text_encoder: CLIPTextModel,
349
+ text_encoder_2: CLIPTextModelWithProjection,
350
+ tokenizer: CLIPTokenizer,
351
+ tokenizer_2: CLIPTokenizer,
352
+ unet: UNet2DConditionModel,
353
+ adapter: Union[T2IAdapter, MultiAdapter],
354
+ controlnet: Union[ControlNetModel, MultiControlNetModel],
355
+ scheduler: KarrasDiffusionSchedulers,
356
+ requires_aesthetics_score: bool = False,
357
+ force_zeros_for_empty_prompt: bool = True,
358
+ ):
359
+ super().__init__()
360
+
361
+ if isinstance(controlnet, (list, tuple)):
362
+ controlnet = MultiControlNetModel(controlnet)
363
+
364
+ self.register_modules(
365
+ vae=vae,
366
+ text_encoder=text_encoder,
367
+ text_encoder_2=text_encoder_2,
368
+ tokenizer=tokenizer,
369
+ tokenizer_2=tokenizer_2,
370
+ unet=unet,
371
+ adapter=adapter,
372
+ controlnet=controlnet,
373
+ scheduler=scheduler,
374
+ )
375
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
376
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
377
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
378
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
379
+ self.control_image_processor = VaeImageProcessor(
380
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
381
+ )
382
+ self.default_sample_size = self.unet.config.sample_size
383
+
384
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
385
+ def encode_prompt(
386
+ self,
387
+ prompt: str,
388
+ prompt_2: Optional[str] = None,
389
+ device: Optional[torch.device] = None,
390
+ num_images_per_prompt: int = 1,
391
+ do_classifier_free_guidance: bool = True,
392
+ negative_prompt: Optional[str] = None,
393
+ negative_prompt_2: Optional[str] = None,
394
+ prompt_embeds: Optional[torch.Tensor] = None,
395
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
396
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
397
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
398
+ lora_scale: Optional[float] = None,
399
+ clip_skip: Optional[int] = None,
400
+ ):
401
+ r"""
402
+ Encodes the prompt into text encoder hidden states.
403
+
404
+ Args:
405
+ prompt (`str` or `List[str]`, *optional*):
406
+ prompt to be encoded
407
+ prompt_2 (`str` or `List[str]`, *optional*):
408
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
409
+ used in both text-encoders
410
+ device: (`torch.device`):
411
+ torch device
412
+ num_images_per_prompt (`int`):
413
+ number of images that should be generated per prompt
414
+ do_classifier_free_guidance (`bool`):
415
+ whether to use classifier free guidance or not
416
+ negative_prompt (`str` or `List[str]`, *optional*):
417
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
418
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
419
+ less than `1`).
420
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
421
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
422
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
423
+ prompt_embeds (`torch.Tensor`, *optional*):
424
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
425
+ provided, text embeddings will be generated from `prompt` input argument.
426
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
427
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
428
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
429
+ argument.
430
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
431
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
432
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
433
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
434
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
435
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
436
+ input argument.
437
+ lora_scale (`float`, *optional*):
438
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
439
+ clip_skip (`int`, *optional*):
440
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
441
+ the output of the pre-final layer will be used for computing the prompt embeddings.
442
+ """
443
+ device = device or self._execution_device
444
+
445
+ # set lora scale so that monkey patched LoRA
446
+ # function of text encoder can correctly access it
447
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
448
+ self._lora_scale = lora_scale
449
+
450
+ # dynamically adjust the LoRA scale
451
+ if self.text_encoder is not None:
452
+ if not USE_PEFT_BACKEND:
453
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
454
+ else:
455
+ scale_lora_layers(self.text_encoder, lora_scale)
456
+
457
+ if self.text_encoder_2 is not None:
458
+ if not USE_PEFT_BACKEND:
459
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
460
+ else:
461
+ scale_lora_layers(self.text_encoder_2, lora_scale)
462
+
463
+ prompt = [prompt] if isinstance(prompt, str) else prompt
464
+
465
+ if prompt is not None:
466
+ batch_size = len(prompt)
467
+ else:
468
+ batch_size = prompt_embeds.shape[0]
469
+
470
+ # Define tokenizers and text encoders
471
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
472
+ text_encoders = (
473
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
474
+ )
475
+
476
+ if prompt_embeds is None:
477
+ prompt_2 = prompt_2 or prompt
478
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
479
+
480
+ # textual inversion: process multi-vector tokens if necessary
481
+ prompt_embeds_list = []
482
+ prompts = [prompt, prompt_2]
483
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
484
+ if isinstance(self, TextualInversionLoaderMixin):
485
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
486
+
487
+ text_inputs = tokenizer(
488
+ prompt,
489
+ padding="max_length",
490
+ max_length=tokenizer.model_max_length,
491
+ truncation=True,
492
+ return_tensors="pt",
493
+ )
494
+
495
+ text_input_ids = text_inputs.input_ids
496
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
497
+
498
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
499
+ text_input_ids, untruncated_ids
500
+ ):
501
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
502
+ logger.warning(
503
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
504
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
505
+ )
506
+
507
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
508
+
509
+ # We are only ALWAYS interested in the pooled output of the final text encoder
510
+ pooled_prompt_embeds = prompt_embeds[0]
511
+ if clip_skip is None:
512
+ prompt_embeds = prompt_embeds.hidden_states[-2]
513
+ else:
514
+ # "2" because SDXL always indexes from the penultimate layer.
515
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
516
+
517
+ prompt_embeds_list.append(prompt_embeds)
518
+
519
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
520
+
521
+ # get unconditional embeddings for classifier free guidance
522
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
523
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
524
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
525
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
526
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
527
+ negative_prompt = negative_prompt or ""
528
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
529
+
530
+ # normalize str to list
531
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
532
+ negative_prompt_2 = (
533
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
534
+ )
535
+
536
+ uncond_tokens: List[str]
537
+ if prompt is not None and type(prompt) is not type(negative_prompt):
538
+ raise TypeError(
539
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
540
+ f" {type(prompt)}."
541
+ )
542
+ elif batch_size != len(negative_prompt):
543
+ raise ValueError(
544
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
545
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
546
+ " the batch size of `prompt`."
547
+ )
548
+ else:
549
+ uncond_tokens = [negative_prompt, negative_prompt_2]
550
+
551
+ negative_prompt_embeds_list = []
552
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
553
+ if isinstance(self, TextualInversionLoaderMixin):
554
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
555
+
556
+ max_length = prompt_embeds.shape[1]
557
+ uncond_input = tokenizer(
558
+ negative_prompt,
559
+ padding="max_length",
560
+ max_length=max_length,
561
+ truncation=True,
562
+ return_tensors="pt",
563
+ )
564
+
565
+ negative_prompt_embeds = text_encoder(
566
+ uncond_input.input_ids.to(device),
567
+ output_hidden_states=True,
568
+ )
569
+ # We are only ALWAYS interested in the pooled output of the final text encoder
570
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
571
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
572
+
573
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
574
+
575
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
576
+
577
+ if self.text_encoder_2 is not None:
578
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
579
+ else:
580
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
581
+
582
+ bs_embed, seq_len, _ = prompt_embeds.shape
583
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
584
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
585
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
586
+
587
+ if do_classifier_free_guidance:
588
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
589
+ seq_len = negative_prompt_embeds.shape[1]
590
+
591
+ if self.text_encoder_2 is not None:
592
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
593
+ else:
594
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
595
+
596
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
597
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
598
+
599
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
600
+ bs_embed * num_images_per_prompt, -1
601
+ )
602
+ if do_classifier_free_guidance:
603
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
604
+ bs_embed * num_images_per_prompt, -1
605
+ )
606
+
607
+ if self.text_encoder is not None:
608
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
609
+ # Retrieve the original scale by scaling back the LoRA layers
610
+ unscale_lora_layers(self.text_encoder, lora_scale)
611
+
612
+ if self.text_encoder_2 is not None:
613
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
614
+ # Retrieve the original scale by scaling back the LoRA layers
615
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
616
+
617
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
618
+
619
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
620
+ def prepare_extra_step_kwargs(self, generator, eta):
621
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
622
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
623
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
624
+ # and should be between [0, 1]
625
+
626
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
627
+ extra_step_kwargs = {}
628
+ if accepts_eta:
629
+ extra_step_kwargs["eta"] = eta
630
+
631
+ # check if the scheduler accepts generator
632
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
633
+ if accepts_generator:
634
+ extra_step_kwargs["generator"] = generator
635
+ return extra_step_kwargs
636
+
637
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
638
+ def check_image(self, image, prompt, prompt_embeds):
639
+ image_is_pil = isinstance(image, PIL.Image.Image)
640
+ image_is_tensor = isinstance(image, torch.Tensor)
641
+ image_is_np = isinstance(image, np.ndarray)
642
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
643
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
644
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
645
+
646
+ if (
647
+ not image_is_pil
648
+ and not image_is_tensor
649
+ and not image_is_np
650
+ and not image_is_pil_list
651
+ and not image_is_tensor_list
652
+ and not image_is_np_list
653
+ ):
654
+ raise TypeError(
655
+ 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)}"
656
+ )
657
+
658
+ if image_is_pil:
659
+ image_batch_size = 1
660
+ else:
661
+ image_batch_size = len(image)
662
+
663
+ if prompt is not None and isinstance(prompt, str):
664
+ prompt_batch_size = 1
665
+ elif prompt is not None and isinstance(prompt, list):
666
+ prompt_batch_size = len(prompt)
667
+ elif prompt_embeds is not None:
668
+ prompt_batch_size = prompt_embeds.shape[0]
669
+
670
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
671
+ raise ValueError(
672
+ 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}"
673
+ )
674
+
675
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.check_inputs
676
+ def check_inputs(
677
+ self,
678
+ prompt,
679
+ prompt_2,
680
+ height,
681
+ width,
682
+ callback_steps,
683
+ negative_prompt=None,
684
+ negative_prompt_2=None,
685
+ prompt_embeds=None,
686
+ negative_prompt_embeds=None,
687
+ pooled_prompt_embeds=None,
688
+ negative_pooled_prompt_embeds=None,
689
+ callback_on_step_end_tensor_inputs=None,
690
+ ):
691
+ if height % 8 != 0 or width % 8 != 0:
692
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
693
+
694
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
695
+ raise ValueError(
696
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
697
+ f" {type(callback_steps)}."
698
+ )
699
+
700
+ if callback_on_step_end_tensor_inputs is not None and not all(
701
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
702
+ ):
703
+ raise ValueError(
704
+ 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]}"
705
+ )
706
+
707
+ if prompt is not None and prompt_embeds is not None:
708
+ raise ValueError(
709
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
710
+ " only forward one of the two."
711
+ )
712
+ elif prompt_2 is not None and prompt_embeds is not None:
713
+ raise ValueError(
714
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
715
+ " only forward one of the two."
716
+ )
717
+ elif prompt is None and prompt_embeds is None:
718
+ raise ValueError(
719
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
720
+ )
721
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
722
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
723
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
724
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
725
+
726
+ if negative_prompt is not None and negative_prompt_embeds is not None:
727
+ raise ValueError(
728
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
729
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
730
+ )
731
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
732
+ raise ValueError(
733
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
734
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
735
+ )
736
+
737
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
738
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
739
+ raise ValueError(
740
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
741
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
742
+ f" {negative_prompt_embeds.shape}."
743
+ )
744
+
745
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
746
+ raise ValueError(
747
+ "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`."
748
+ )
749
+
750
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
751
+ raise ValueError(
752
+ "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`."
753
+ )
754
+
755
+ def check_conditions(
756
+ self,
757
+ prompt,
758
+ prompt_embeds,
759
+ adapter_image,
760
+ control_image,
761
+ adapter_conditioning_scale,
762
+ controlnet_conditioning_scale,
763
+ control_guidance_start,
764
+ control_guidance_end,
765
+ ):
766
+ # controlnet checks
767
+ if not isinstance(control_guidance_start, (tuple, list)):
768
+ control_guidance_start = [control_guidance_start]
769
+
770
+ if not isinstance(control_guidance_end, (tuple, list)):
771
+ control_guidance_end = [control_guidance_end]
772
+
773
+ if len(control_guidance_start) != len(control_guidance_end):
774
+ raise ValueError(
775
+ 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."
776
+ )
777
+
778
+ if isinstance(self.controlnet, MultiControlNetModel):
779
+ if len(control_guidance_start) != len(self.controlnet.nets):
780
+ raise ValueError(
781
+ 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)}."
782
+ )
783
+
784
+ for start, end in zip(control_guidance_start, control_guidance_end):
785
+ if start >= end:
786
+ raise ValueError(
787
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
788
+ )
789
+ if start < 0.0:
790
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
791
+ if end > 1.0:
792
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
793
+
794
+ # Check controlnet `image`
795
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
796
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
797
+ )
798
+ if (
799
+ isinstance(self.controlnet, ControlNetModel)
800
+ or is_compiled
801
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
802
+ ):
803
+ self.check_image(control_image, prompt, prompt_embeds)
804
+ elif (
805
+ isinstance(self.controlnet, MultiControlNetModel)
806
+ or is_compiled
807
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
808
+ ):
809
+ if not isinstance(control_image, list):
810
+ raise TypeError("For multiple controlnets: `control_image` must be type `list`")
811
+
812
+ # When `image` is a nested list:
813
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
814
+ elif any(isinstance(i, list) for i in control_image):
815
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
816
+ elif len(control_image) != len(self.controlnet.nets):
817
+ raise ValueError(
818
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(control_image)} images and {len(self.controlnet.nets)} ControlNets."
819
+ )
820
+
821
+ for image_ in control_image:
822
+ self.check_image(image_, prompt, prompt_embeds)
823
+ else:
824
+ assert False
825
+
826
+ # Check `controlnet_conditioning_scale`
827
+ if (
828
+ isinstance(self.controlnet, ControlNetModel)
829
+ or is_compiled
830
+ and isinstance(self.controlnet._orig_mod, ControlNetModel)
831
+ ):
832
+ if not isinstance(controlnet_conditioning_scale, float):
833
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
834
+ elif (
835
+ isinstance(self.controlnet, MultiControlNetModel)
836
+ or is_compiled
837
+ and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
838
+ ):
839
+ if isinstance(controlnet_conditioning_scale, list):
840
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
841
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
842
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
843
+ self.controlnet.nets
844
+ ):
845
+ raise ValueError(
846
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
847
+ " the same length as the number of controlnets"
848
+ )
849
+ else:
850
+ assert False
851
+
852
+ # adapter checks
853
+ if isinstance(self.adapter, T2IAdapter) or is_compiled and isinstance(self.adapter._orig_mod, T2IAdapter):
854
+ self.check_image(adapter_image, prompt, prompt_embeds)
855
+ elif (
856
+ isinstance(self.adapter, MultiAdapter) or is_compiled and isinstance(self.adapter._orig_mod, MultiAdapter)
857
+ ):
858
+ if not isinstance(adapter_image, list):
859
+ raise TypeError("For multiple adapters: `adapter_image` must be type `list`")
860
+
861
+ # When `image` is a nested list:
862
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
863
+ elif any(isinstance(i, list) for i in adapter_image):
864
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
865
+ elif len(adapter_image) != len(self.adapter.adapters):
866
+ raise ValueError(
867
+ f"For multiple adapters: `image` must have the same length as the number of adapters, but got {len(adapter_image)} images and {len(self.adapters.nets)} Adapters."
868
+ )
869
+
870
+ for image_ in adapter_image:
871
+ self.check_image(image_, prompt, prompt_embeds)
872
+ else:
873
+ assert False
874
+
875
+ # Check `adapter_conditioning_scale`
876
+ if isinstance(self.adapter, T2IAdapter) or is_compiled and isinstance(self.adapter._orig_mod, T2IAdapter):
877
+ if not isinstance(adapter_conditioning_scale, float):
878
+ raise TypeError("For single adapter: `adapter_conditioning_scale` must be type `float`.")
879
+ elif (
880
+ isinstance(self.adapter, MultiAdapter) or is_compiled and isinstance(self.adapter._orig_mod, MultiAdapter)
881
+ ):
882
+ if isinstance(adapter_conditioning_scale, list):
883
+ if any(isinstance(i, list) for i in adapter_conditioning_scale):
884
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
885
+ elif isinstance(adapter_conditioning_scale, list) and len(adapter_conditioning_scale) != len(
886
+ self.adapter.adapters
887
+ ):
888
+ raise ValueError(
889
+ "For multiple adapters: When `adapter_conditioning_scale` is specified as `list`, it must have"
890
+ " the same length as the number of adapters"
891
+ )
892
+ else:
893
+ assert False
894
+
895
+ def prepare_latents(
896
+ self,
897
+ batch_size,
898
+ num_channels_latents,
899
+ height,
900
+ width,
901
+ dtype,
902
+ device,
903
+ generator,
904
+ latents=None,
905
+ image=None,
906
+ timestep=None,
907
+ is_strength_max=True,
908
+ add_noise=True,
909
+ return_noise=False,
910
+ return_image_latents=False,
911
+ ):
912
+ shape = (
913
+ batch_size,
914
+ num_channels_latents,
915
+ height // self.vae_scale_factor,
916
+ width // self.vae_scale_factor,
917
+ )
918
+ if isinstance(generator, list) and len(generator) != batch_size:
919
+ raise ValueError(
920
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
921
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
922
+ )
923
+
924
+ if (image is None or timestep is None) and not is_strength_max:
925
+ raise ValueError(
926
+ "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise."
927
+ "However, either the image or the noise timestep has not been provided."
928
+ )
929
+
930
+ if image.shape[1] == 4:
931
+ image_latents = image.to(device=device, dtype=dtype)
932
+ elif return_image_latents or (latents is None and not is_strength_max):
933
+ image = image.to(device=device, dtype=dtype)
934
+ image_latents = self._encode_vae_image(image=image, generator=generator)
935
+
936
+ image_latents = image_latents.repeat(batch_size // image_latents.shape[0], 1, 1, 1)
937
+
938
+ if latents is None and add_noise:
939
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
940
+ # if strength is 1. then initialise the latents to noise, else initial to image + noise
941
+ latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep)
942
+ # if pure noise then scale the initial latents by the Scheduler's init sigma
943
+ latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents
944
+ elif add_noise:
945
+ noise = latents.to(device)
946
+ latents = noise * self.scheduler.init_noise_sigma
947
+ else:
948
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
949
+ latents = image_latents.to(device)
950
+
951
+ outputs = (latents,)
952
+
953
+ if return_noise:
954
+ outputs += (noise,)
955
+
956
+ if return_image_latents:
957
+ outputs += (image_latents,)
958
+
959
+ return outputs
960
+
961
+ def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
962
+ dtype = image.dtype
963
+ if self.vae.config.force_upcast:
964
+ image = image.float()
965
+ self.vae.to(dtype=torch.float32)
966
+
967
+ if isinstance(generator, list):
968
+ image_latents = [
969
+ self.vae.encode(image[i : i + 1]).latent_dist.sample(generator=generator[i])
970
+ for i in range(image.shape[0])
971
+ ]
972
+ image_latents = torch.cat(image_latents, dim=0)
973
+ else:
974
+ image_latents = self.vae.encode(image).latent_dist.sample(generator=generator)
975
+
976
+ if self.vae.config.force_upcast:
977
+ self.vae.to(dtype)
978
+
979
+ image_latents = image_latents.to(dtype)
980
+ image_latents = self.vae.config.scaling_factor * image_latents
981
+
982
+ return image_latents
983
+
984
+ def prepare_mask_latents(
985
+ self,
986
+ mask,
987
+ masked_image,
988
+ batch_size,
989
+ height,
990
+ width,
991
+ dtype,
992
+ device,
993
+ generator,
994
+ do_classifier_free_guidance,
995
+ ):
996
+ # resize the mask to latents shape as we concatenate the mask to the latents
997
+ # we do that before converting to dtype to avoid breaking in case we're using cpu_offload
998
+ # and half precision
999
+ mask = torch.nn.functional.interpolate(
1000
+ mask,
1001
+ size=(
1002
+ height // self.vae_scale_factor,
1003
+ width // self.vae_scale_factor,
1004
+ ),
1005
+ )
1006
+ mask = mask.to(device=device, dtype=dtype)
1007
+
1008
+ # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method
1009
+ if mask.shape[0] < batch_size:
1010
+ if not batch_size % mask.shape[0] == 0:
1011
+ raise ValueError(
1012
+ "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to"
1013
+ f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number"
1014
+ " of masks that you pass is divisible by the total requested batch size."
1015
+ )
1016
+ mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1)
1017
+
1018
+ mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask
1019
+
1020
+ masked_image_latents = None
1021
+ if masked_image is not None:
1022
+ masked_image = masked_image.to(device=device, dtype=dtype)
1023
+ masked_image_latents = self._encode_vae_image(masked_image, generator=generator)
1024
+ if masked_image_latents.shape[0] < batch_size:
1025
+ if not batch_size % masked_image_latents.shape[0] == 0:
1026
+ raise ValueError(
1027
+ "The passed images and the required batch size don't match. Images are supposed to be duplicated"
1028
+ f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed."
1029
+ " Make sure the number of images that you pass is divisible by the total requested batch size."
1030
+ )
1031
+ masked_image_latents = masked_image_latents.repeat(
1032
+ batch_size // masked_image_latents.shape[0], 1, 1, 1
1033
+ )
1034
+
1035
+ masked_image_latents = (
1036
+ torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
1037
+ )
1038
+
1039
+ # aligning device to prevent device errors when concating it with the latent model input
1040
+ masked_image_latents = masked_image_latents.to(device=device, dtype=dtype)
1041
+
1042
+ return mask, masked_image_latents
1043
+
1044
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.get_timesteps
1045
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
1046
+ # get the original timestep using init_timestep
1047
+ if denoising_start is None:
1048
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
1049
+ t_start = max(num_inference_steps - init_timestep, 0)
1050
+ else:
1051
+ t_start = 0
1052
+
1053
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
1054
+
1055
+ # Strength is irrelevant if we directly request a timestep to start at;
1056
+ # that is, strength is determined by the denoising_start instead.
1057
+ if denoising_start is not None:
1058
+ discrete_timestep_cutoff = int(
1059
+ round(
1060
+ self.scheduler.config.num_train_timesteps
1061
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
1062
+ )
1063
+ )
1064
+
1065
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
1066
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
1067
+ # if the scheduler is a 2nd order scheduler we might have to do +1
1068
+ # because `num_inference_steps` might be even given that every timestep
1069
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
1070
+ # mean that we cut the timesteps in the middle of the denoising step
1071
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
1072
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
1073
+ num_inference_steps = num_inference_steps + 1
1074
+
1075
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
1076
+ timesteps = timesteps[-num_inference_steps:]
1077
+ return timesteps, num_inference_steps
1078
+
1079
+ return timesteps, num_inference_steps - t_start
1080
+
1081
+ def _get_add_time_ids(
1082
+ self,
1083
+ original_size,
1084
+ crops_coords_top_left,
1085
+ target_size,
1086
+ aesthetic_score,
1087
+ negative_aesthetic_score,
1088
+ dtype,
1089
+ text_encoder_projection_dim=None,
1090
+ ):
1091
+ if self.config.requires_aesthetics_score:
1092
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
1093
+ add_neg_time_ids = list(original_size + crops_coords_top_left + (negative_aesthetic_score,))
1094
+ else:
1095
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
1096
+ add_neg_time_ids = list(original_size + crops_coords_top_left + target_size)
1097
+
1098
+ passed_add_embed_dim = (
1099
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
1100
+ )
1101
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
1102
+
1103
+ if (
1104
+ expected_add_embed_dim > passed_add_embed_dim
1105
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
1106
+ ):
1107
+ raise ValueError(
1108
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
1109
+ )
1110
+ elif (
1111
+ expected_add_embed_dim < passed_add_embed_dim
1112
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
1113
+ ):
1114
+ raise ValueError(
1115
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
1116
+ )
1117
+ elif expected_add_embed_dim != passed_add_embed_dim:
1118
+ raise ValueError(
1119
+ 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`."
1120
+ )
1121
+
1122
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
1123
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
1124
+
1125
+ return add_time_ids, add_neg_time_ids
1126
+
1127
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
1128
+ def upcast_vae(self):
1129
+ dtype = self.vae.dtype
1130
+ self.vae.to(dtype=torch.float32)
1131
+ use_torch_2_0_or_xformers = isinstance(
1132
+ self.vae.decoder.mid_block.attentions[0].processor,
1133
+ (AttnProcessor2_0, XFormersAttnProcessor),
1134
+ )
1135
+ # if xformers or torch_2_0 is used attention block does not need
1136
+ # to be in float32 which can save lots of memory
1137
+ if use_torch_2_0_or_xformers:
1138
+ self.vae.post_quant_conv.to(dtype)
1139
+ self.vae.decoder.conv_in.to(dtype)
1140
+ self.vae.decoder.mid_block.to(dtype)
1141
+
1142
+ # Copied from diffusers.pipelines.t2i_adapter.pipeline_stable_diffusion_adapter.StableDiffusionAdapterPipeline._default_height_width
1143
+ def _default_height_width(self, height, width, image):
1144
+ # NOTE: It is possible that a list of images have different
1145
+ # dimensions for each image, so just checking the first image
1146
+ # is not _exactly_ correct, but it is simple.
1147
+ while isinstance(image, list):
1148
+ image = image[0]
1149
+
1150
+ if height is None:
1151
+ if isinstance(image, PIL.Image.Image):
1152
+ height = image.height
1153
+ elif isinstance(image, torch.Tensor):
1154
+ height = image.shape[-2]
1155
+
1156
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1157
+ height = (height // self.adapter.downscale_factor) * self.adapter.downscale_factor
1158
+
1159
+ if width is None:
1160
+ if isinstance(image, PIL.Image.Image):
1161
+ width = image.width
1162
+ elif isinstance(image, torch.Tensor):
1163
+ width = image.shape[-1]
1164
+
1165
+ # round down to nearest multiple of `self.adapter.downscale_factor`
1166
+ width = (width // self.adapter.downscale_factor) * self.adapter.downscale_factor
1167
+
1168
+ return height, width
1169
+
1170
+ def prepare_control_image(
1171
+ self,
1172
+ image,
1173
+ width,
1174
+ height,
1175
+ batch_size,
1176
+ num_images_per_prompt,
1177
+ device,
1178
+ dtype,
1179
+ do_classifier_free_guidance=False,
1180
+ guess_mode=False,
1181
+ ):
1182
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1183
+ image_batch_size = image.shape[0]
1184
+
1185
+ if image_batch_size == 1:
1186
+ repeat_by = batch_size
1187
+ else:
1188
+ # image batch size is the same as prompt batch size
1189
+ repeat_by = num_images_per_prompt
1190
+
1191
+ image = image.repeat_interleave(repeat_by, dim=0)
1192
+
1193
+ image = image.to(device=device, dtype=dtype)
1194
+
1195
+ if do_classifier_free_guidance and not guess_mode:
1196
+ image = torch.cat([image] * 2)
1197
+
1198
+ return image
1199
+
1200
+ @torch.no_grad()
1201
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
1202
+ def __call__(
1203
+ self,
1204
+ prompt: Optional[Union[str, List[str]]] = None,
1205
+ prompt_2: Optional[Union[str, List[str]]] = None,
1206
+ image: Optional[Union[torch.Tensor, PIL.Image.Image]] = None,
1207
+ mask_image: Optional[Union[torch.Tensor, PIL.Image.Image]] = None,
1208
+ adapter_image: PipelineImageInput = None,
1209
+ control_image: PipelineImageInput = None,
1210
+ height: Optional[int] = None,
1211
+ width: Optional[int] = None,
1212
+ strength: float = 0.9999,
1213
+ num_inference_steps: int = 50,
1214
+ denoising_start: Optional[float] = None,
1215
+ denoising_end: Optional[float] = None,
1216
+ guidance_scale: float = 5.0,
1217
+ negative_prompt: Optional[Union[str, List[str]]] = None,
1218
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
1219
+ num_images_per_prompt: Optional[int] = 1,
1220
+ eta: float = 0.0,
1221
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
1222
+ latents: Optional[Union[torch.Tensor]] = None,
1223
+ prompt_embeds: Optional[torch.Tensor] = None,
1224
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
1225
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
1226
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
1227
+ output_type: Optional[str] = "pil",
1228
+ return_dict: bool = True,
1229
+ callback: Optional[Callable[[int, int, torch.Tensor], None]] = None,
1230
+ callback_steps: int = 1,
1231
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1232
+ guidance_rescale: float = 0.0,
1233
+ original_size: Optional[Tuple[int, int]] = None,
1234
+ crops_coords_top_left: Optional[Tuple[int, int]] = (0, 0),
1235
+ target_size: Optional[Tuple[int, int]] = None,
1236
+ adapter_conditioning_scale: Optional[Union[float, List[float]]] = 1.0,
1237
+ cond_tau: float = 1.0,
1238
+ aesthetic_score: float = 6.0,
1239
+ negative_aesthetic_score: float = 2.5,
1240
+ controlnet_conditioning_scale=1.0,
1241
+ guess_mode: bool = False,
1242
+ control_guidance_start=0.0,
1243
+ control_guidance_end=1.0,
1244
+ ):
1245
+ r"""
1246
+ Function invoked when calling the pipeline for generation.
1247
+
1248
+ Args:
1249
+ prompt (`str` or `List[str]`, *optional*):
1250
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
1251
+ instead.
1252
+ prompt_2 (`str` or `List[str]`, *optional*):
1253
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1254
+ used in both text-encoders
1255
+ image (`PIL.Image.Image`):
1256
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
1257
+ be masked out with `mask_image` and repainted according to `prompt`.
1258
+ mask_image (`PIL.Image.Image`):
1259
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
1260
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
1261
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
1262
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
1263
+ adapter_image (`torch.Tensor`, `PIL.Image.Image`, `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[List[PIL.Image.Image]]`):
1264
+ The Adapter input condition. Adapter uses this input condition to generate guidance to Unet. If the
1265
+ type is specified as `torch.Tensor`, it is passed to Adapter as is. PIL.Image.Image` can also be
1266
+ accepted as an image. The control image is automatically resized to fit the output image.
1267
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
1268
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
1269
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
1270
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
1271
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
1272
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
1273
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
1274
+ input to a single ControlNet.
1275
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1276
+ The height in pixels of the generated image.
1277
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
1278
+ The width in pixels of the generated image.
1279
+ strength (`float`, *optional*, defaults to 1.0):
1280
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
1281
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
1282
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
1283
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
1284
+ essentially ignores `image`.
1285
+ num_inference_steps (`int`, *optional*, defaults to 50):
1286
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1287
+ expense of slower inference.
1288
+ denoising_start (`float`, *optional*):
1289
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1290
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1291
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1292
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1293
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1294
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1295
+ denoising_end (`float`, *optional*):
1296
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1297
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1298
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
1299
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
1300
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1301
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
1302
+ guidance_scale (`float`, *optional*, defaults to 5.0):
1303
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1304
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1305
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1306
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1307
+ usually at the expense of lower image quality.
1308
+ negative_prompt (`str` or `List[str]`, *optional*):
1309
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1310
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1311
+ less than `1`).
1312
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1313
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1314
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1315
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1316
+ The number of images to generate per prompt.
1317
+ eta (`float`, *optional*, defaults to 0.0):
1318
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1319
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1320
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1321
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1322
+ to make generation deterministic.
1323
+ latents (`torch.Tensor`, *optional*):
1324
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1325
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1326
+ tensor will ge generated by sampling using the supplied random `generator`.
1327
+ prompt_embeds (`torch.Tensor`, *optional*):
1328
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1329
+ provided, text embeddings will be generated from `prompt` input argument.
1330
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1331
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1332
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1333
+ argument.
1334
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1335
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1336
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1337
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1338
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1339
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1340
+ input argument.
1341
+ output_type (`str`, *optional*, defaults to `"pil"`):
1342
+ The output format of the generate image. Choose between
1343
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1344
+ return_dict (`bool`, *optional*, defaults to `True`):
1345
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionAdapterPipelineOutput`]
1346
+ instead of a plain tuple.
1347
+ callback (`Callable`, *optional*):
1348
+ A function that will be called every `callback_steps` steps during inference. The function will be
1349
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1350
+ callback_steps (`int`, *optional*, defaults to 1):
1351
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1352
+ called at every step.
1353
+ cross_attention_kwargs (`dict`, *optional*):
1354
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1355
+ `self.processor` in
1356
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
1357
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
1358
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1359
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1360
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1361
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1362
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1363
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1364
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
1365
+ explained in section 2.2 of
1366
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1367
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1368
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1369
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1370
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1371
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1372
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1373
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1374
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
1375
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1376
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1377
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added to the
1378
+ residual in the original unet. If multiple adapters are specified in init, you can set the
1379
+ corresponding scale as a list.
1380
+ adapter_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
1381
+ The outputs of the adapter are multiplied by `adapter_conditioning_scale` before they are added to the
1382
+ residual in the original unet. If multiple adapters are specified in init, you can set the
1383
+ corresponding scale as a list.
1384
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1385
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1386
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1387
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1388
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1389
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1390
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1391
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1392
+ Examples:
1393
+
1394
+ Returns:
1395
+ [`~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput`] or `tuple`:
1396
+ [`~pipelines.stable_diffusion.StableDiffusionAdapterPipelineOutput`] if `return_dict` is True, otherwise a
1397
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
1398
+ """
1399
+ # 0. Default height and width to unet
1400
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1401
+ adapter = self.adapter._orig_mod if is_compiled_module(self.adapter) else self.adapter
1402
+ height, width = self._default_height_width(height, width, adapter_image)
1403
+ device = self._execution_device
1404
+
1405
+ if isinstance(adapter, MultiAdapter):
1406
+ adapter_input = []
1407
+ for one_image in adapter_image:
1408
+ one_image = _preprocess_adapter_image(one_image, height, width)
1409
+ one_image = one_image.to(device=device, dtype=adapter.dtype)
1410
+ adapter_input.append(one_image)
1411
+ else:
1412
+ adapter_input = _preprocess_adapter_image(adapter_image, height, width)
1413
+ adapter_input = adapter_input.to(device=device, dtype=adapter.dtype)
1414
+
1415
+ original_size = original_size or (height, width)
1416
+ target_size = target_size or (height, width)
1417
+
1418
+ # 0.1 align format for control guidance
1419
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
1420
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
1421
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
1422
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1423
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1424
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1425
+ control_guidance_start, control_guidance_end = (
1426
+ mult * [control_guidance_start],
1427
+ mult * [control_guidance_end],
1428
+ )
1429
+
1430
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1431
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
1432
+ if isinstance(adapter, MultiAdapter) and isinstance(adapter_conditioning_scale, float):
1433
+ adapter_conditioning_scale = [adapter_conditioning_scale] * len(adapter.nets)
1434
+
1435
+ # 1. Check inputs. Raise error if not correct
1436
+ self.check_inputs(
1437
+ prompt,
1438
+ prompt_2,
1439
+ height,
1440
+ width,
1441
+ callback_steps,
1442
+ negative_prompt=negative_prompt,
1443
+ negative_prompt_2=negative_prompt_2,
1444
+ prompt_embeds=prompt_embeds,
1445
+ negative_prompt_embeds=negative_prompt_embeds,
1446
+ pooled_prompt_embeds=pooled_prompt_embeds,
1447
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1448
+ )
1449
+
1450
+ self.check_conditions(
1451
+ prompt,
1452
+ prompt_embeds,
1453
+ adapter_image,
1454
+ control_image,
1455
+ adapter_conditioning_scale,
1456
+ controlnet_conditioning_scale,
1457
+ control_guidance_start,
1458
+ control_guidance_end,
1459
+ )
1460
+
1461
+ # 2. Define call parameters
1462
+ if prompt is not None and isinstance(prompt, str):
1463
+ batch_size = 1
1464
+ elif prompt is not None and isinstance(prompt, list):
1465
+ batch_size = len(prompt)
1466
+ else:
1467
+ batch_size = prompt_embeds.shape[0]
1468
+
1469
+ device = self._execution_device
1470
+
1471
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1472
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1473
+ # corresponds to doing no classifier free guidance.
1474
+ do_classifier_free_guidance = guidance_scale > 1.0
1475
+
1476
+ # 3. Encode input prompt
1477
+ (
1478
+ prompt_embeds,
1479
+ negative_prompt_embeds,
1480
+ pooled_prompt_embeds,
1481
+ negative_pooled_prompt_embeds,
1482
+ ) = self.encode_prompt(
1483
+ prompt=prompt,
1484
+ prompt_2=prompt_2,
1485
+ device=device,
1486
+ num_images_per_prompt=num_images_per_prompt,
1487
+ do_classifier_free_guidance=do_classifier_free_guidance,
1488
+ negative_prompt=negative_prompt,
1489
+ negative_prompt_2=negative_prompt_2,
1490
+ prompt_embeds=prompt_embeds,
1491
+ negative_prompt_embeds=negative_prompt_embeds,
1492
+ pooled_prompt_embeds=pooled_prompt_embeds,
1493
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1494
+ )
1495
+
1496
+ # 4. set timesteps
1497
+ def denoising_value_valid(dnv):
1498
+ return isinstance(dnv, float) and 0 < dnv < 1
1499
+
1500
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
1501
+ timesteps, num_inference_steps = self.get_timesteps(
1502
+ num_inference_steps,
1503
+ strength,
1504
+ device,
1505
+ denoising_start=denoising_start if denoising_value_valid(denoising_start) else None,
1506
+ )
1507
+ # check that number of inference steps is not < 1 - as this doesn't make sense
1508
+ if num_inference_steps < 1:
1509
+ raise ValueError(
1510
+ f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
1511
+ f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
1512
+ )
1513
+ # at which timestep to set the initial noise (n.b. 50% if strength is 0.5)
1514
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1515
+ # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1516
+ is_strength_max = strength == 1.0
1517
+
1518
+ # 5. Preprocess mask and image - resizes image and mask w.r.t height and width
1519
+ mask, masked_image, init_image = prepare_mask_and_masked_image(
1520
+ image, mask_image, height, width, return_image=True
1521
+ )
1522
+
1523
+ # 6. Prepare latent variables
1524
+ num_channels_latents = self.vae.config.latent_channels
1525
+ num_channels_unet = self.unet.config.in_channels
1526
+ return_image_latents = num_channels_unet == 4
1527
+
1528
+ add_noise = denoising_start is None
1529
+ latents_outputs = self.prepare_latents(
1530
+ batch_size * num_images_per_prompt,
1531
+ num_channels_latents,
1532
+ height,
1533
+ width,
1534
+ prompt_embeds.dtype,
1535
+ device,
1536
+ generator,
1537
+ latents,
1538
+ image=init_image,
1539
+ timestep=latent_timestep,
1540
+ is_strength_max=is_strength_max,
1541
+ add_noise=add_noise,
1542
+ return_noise=True,
1543
+ return_image_latents=return_image_latents,
1544
+ )
1545
+
1546
+ if return_image_latents:
1547
+ latents, noise, image_latents = latents_outputs
1548
+ else:
1549
+ latents, noise = latents_outputs
1550
+
1551
+ # 7. Prepare mask latent variables
1552
+ mask, masked_image_latents = self.prepare_mask_latents(
1553
+ mask,
1554
+ masked_image,
1555
+ batch_size * num_images_per_prompt,
1556
+ height,
1557
+ width,
1558
+ prompt_embeds.dtype,
1559
+ device,
1560
+ generator,
1561
+ do_classifier_free_guidance,
1562
+ )
1563
+
1564
+ # 8. Check that sizes of mask, masked image and latents match
1565
+ if num_channels_unet == 9:
1566
+ # default case for runwayml/stable-diffusion-inpainting
1567
+ num_channels_mask = mask.shape[1]
1568
+ num_channels_masked_image = masked_image_latents.shape[1]
1569
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels:
1570
+ raise ValueError(
1571
+ f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects"
1572
+ f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +"
1573
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
1574
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
1575
+ " `pipeline.unet` or your `mask_image` or `image` input."
1576
+ )
1577
+ elif num_channels_unet != 4:
1578
+ raise ValueError(
1579
+ f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}."
1580
+ )
1581
+
1582
+ # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1583
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1584
+
1585
+ # 10. Prepare added time ids & embeddings & adapter features
1586
+ if isinstance(adapter, MultiAdapter):
1587
+ adapter_state = adapter(adapter_input, adapter_conditioning_scale)
1588
+ for k, v in enumerate(adapter_state):
1589
+ adapter_state[k] = v
1590
+ else:
1591
+ adapter_state = adapter(adapter_input)
1592
+ for k, v in enumerate(adapter_state):
1593
+ adapter_state[k] = v * adapter_conditioning_scale
1594
+ if num_images_per_prompt > 1:
1595
+ for k, v in enumerate(adapter_state):
1596
+ adapter_state[k] = v.repeat(num_images_per_prompt, 1, 1, 1)
1597
+ if do_classifier_free_guidance:
1598
+ for k, v in enumerate(adapter_state):
1599
+ adapter_state[k] = torch.cat([v] * 2, dim=0)
1600
+
1601
+ # 10.2 Prepare control images
1602
+ if isinstance(controlnet, ControlNetModel):
1603
+ control_image = self.prepare_control_image(
1604
+ image=control_image,
1605
+ width=width,
1606
+ height=height,
1607
+ batch_size=batch_size * num_images_per_prompt,
1608
+ num_images_per_prompt=num_images_per_prompt,
1609
+ device=device,
1610
+ dtype=controlnet.dtype,
1611
+ do_classifier_free_guidance=do_classifier_free_guidance,
1612
+ guess_mode=guess_mode,
1613
+ )
1614
+ elif isinstance(controlnet, MultiControlNetModel):
1615
+ control_images = []
1616
+
1617
+ for control_image_ in control_image:
1618
+ control_image_ = self.prepare_control_image(
1619
+ image=control_image_,
1620
+ width=width,
1621
+ height=height,
1622
+ batch_size=batch_size * num_images_per_prompt,
1623
+ num_images_per_prompt=num_images_per_prompt,
1624
+ device=device,
1625
+ dtype=controlnet.dtype,
1626
+ do_classifier_free_guidance=do_classifier_free_guidance,
1627
+ guess_mode=guess_mode,
1628
+ )
1629
+
1630
+ control_images.append(control_image_)
1631
+
1632
+ control_image = control_images
1633
+ else:
1634
+ raise ValueError(f"{controlnet.__class__} is not supported.")
1635
+
1636
+ # 8.2 Create tensor stating which controlnets to keep
1637
+ controlnet_keep = []
1638
+ for i in range(len(timesteps)):
1639
+ keeps = [
1640
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
1641
+ for s, e in zip(control_guidance_start, control_guidance_end)
1642
+ ]
1643
+ if isinstance(self.controlnet, MultiControlNetModel):
1644
+ controlnet_keep.append(keeps)
1645
+ else:
1646
+ controlnet_keep.append(keeps[0])
1647
+ # ----------------------------------------------------------------
1648
+
1649
+ add_text_embeds = pooled_prompt_embeds
1650
+ if self.text_encoder_2 is None:
1651
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1652
+ else:
1653
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1654
+
1655
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1656
+ original_size,
1657
+ crops_coords_top_left,
1658
+ target_size,
1659
+ aesthetic_score,
1660
+ negative_aesthetic_score,
1661
+ dtype=prompt_embeds.dtype,
1662
+ text_encoder_projection_dim=text_encoder_projection_dim,
1663
+ )
1664
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1665
+
1666
+ if do_classifier_free_guidance:
1667
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1668
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1669
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1670
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1671
+
1672
+ prompt_embeds = prompt_embeds.to(device)
1673
+ add_text_embeds = add_text_embeds.to(device)
1674
+ add_time_ids = add_time_ids.to(device)
1675
+
1676
+ # 11. Denoising loop
1677
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1678
+
1679
+ # 11.1 Apply denoising_end
1680
+ if (
1681
+ denoising_end is not None
1682
+ and denoising_start is not None
1683
+ and denoising_value_valid(denoising_end)
1684
+ and denoising_value_valid(denoising_start)
1685
+ and denoising_start >= denoising_end
1686
+ ):
1687
+ raise ValueError(
1688
+ f"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: "
1689
+ + f" {denoising_end} when using type float."
1690
+ )
1691
+ elif denoising_end is not None and denoising_value_valid(denoising_end):
1692
+ discrete_timestep_cutoff = int(
1693
+ round(
1694
+ self.scheduler.config.num_train_timesteps
1695
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1696
+ )
1697
+ )
1698
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1699
+ timesteps = timesteps[:num_inference_steps]
1700
+
1701
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1702
+ for i, t in enumerate(timesteps):
1703
+ # expand the latents if we are doing classifier free guidance
1704
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1705
+
1706
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1707
+
1708
+ if num_channels_unet == 9:
1709
+ latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1)
1710
+
1711
+ # predict the noise residual
1712
+ added_cond_kwargs = {
1713
+ "text_embeds": add_text_embeds,
1714
+ "time_ids": add_time_ids,
1715
+ }
1716
+
1717
+ if i < int(num_inference_steps * cond_tau):
1718
+ down_block_additional_residuals = [state.clone() for state in adapter_state]
1719
+ else:
1720
+ down_block_additional_residuals = None
1721
+
1722
+ # ----------- ControlNet
1723
+
1724
+ # expand the latents if we are doing classifier free guidance
1725
+ latent_model_input_controlnet = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1726
+
1727
+ # concat latents, mask, masked_image_latents in the channel dimension
1728
+ latent_model_input_controlnet = self.scheduler.scale_model_input(latent_model_input_controlnet, t)
1729
+
1730
+ # controlnet(s) inference
1731
+ if guess_mode and do_classifier_free_guidance:
1732
+ # Infer ControlNet only for the conditional batch.
1733
+ control_model_input = latents
1734
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1735
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1736
+ controlnet_added_cond_kwargs = {
1737
+ "text_embeds": add_text_embeds.chunk(2)[1],
1738
+ "time_ids": add_time_ids.chunk(2)[1],
1739
+ }
1740
+ else:
1741
+ control_model_input = latent_model_input_controlnet
1742
+ controlnet_prompt_embeds = prompt_embeds
1743
+ controlnet_added_cond_kwargs = added_cond_kwargs
1744
+
1745
+ if isinstance(controlnet_keep[i], list):
1746
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1747
+ else:
1748
+ controlnet_cond_scale = controlnet_conditioning_scale
1749
+ if isinstance(controlnet_cond_scale, list):
1750
+ controlnet_cond_scale = controlnet_cond_scale[0]
1751
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1752
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1753
+ control_model_input,
1754
+ t,
1755
+ encoder_hidden_states=controlnet_prompt_embeds,
1756
+ controlnet_cond=control_image,
1757
+ conditioning_scale=cond_scale,
1758
+ guess_mode=guess_mode,
1759
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1760
+ return_dict=False,
1761
+ )
1762
+
1763
+ noise_pred = self.unet(
1764
+ latent_model_input,
1765
+ t,
1766
+ encoder_hidden_states=prompt_embeds,
1767
+ cross_attention_kwargs=cross_attention_kwargs,
1768
+ added_cond_kwargs=added_cond_kwargs,
1769
+ return_dict=False,
1770
+ down_intrablock_additional_residuals=down_block_additional_residuals, # t2iadapter
1771
+ down_block_additional_residuals=down_block_res_samples, # controlnet
1772
+ mid_block_additional_residual=mid_block_res_sample, # controlnet
1773
+ )[0]
1774
+
1775
+ # perform guidance
1776
+ if do_classifier_free_guidance:
1777
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1778
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1779
+
1780
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
1781
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1782
+ noise_pred = rescale_noise_cfg(
1783
+ noise_pred,
1784
+ noise_pred_text,
1785
+ guidance_rescale=guidance_rescale,
1786
+ )
1787
+
1788
+ # compute the previous noisy sample x_t -> x_t-1
1789
+ latents = self.scheduler.step(
1790
+ noise_pred,
1791
+ t,
1792
+ latents,
1793
+ **extra_step_kwargs,
1794
+ return_dict=False,
1795
+ )[0]
1796
+
1797
+ if num_channels_unet == 4:
1798
+ init_latents_proper = image_latents
1799
+ if do_classifier_free_guidance:
1800
+ init_mask, _ = mask.chunk(2)
1801
+ else:
1802
+ init_mask = mask
1803
+
1804
+ if i < len(timesteps) - 1:
1805
+ noise_timestep = timesteps[i + 1]
1806
+ init_latents_proper = self.scheduler.add_noise(
1807
+ init_latents_proper,
1808
+ noise,
1809
+ torch.tensor([noise_timestep]),
1810
+ )
1811
+
1812
+ latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1813
+
1814
+ # call the callback, if provided
1815
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1816
+ progress_bar.update()
1817
+ if callback is not None and i % callback_steps == 0:
1818
+ callback(i, t, latents)
1819
+
1820
+ # make sure the VAE is in float32 mode, as it overflows in float16
1821
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1822
+ self.upcast_vae()
1823
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1824
+
1825
+ if output_type != "latent":
1826
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1827
+ else:
1828
+ image = latents
1829
+ return StableDiffusionXLPipelineOutput(images=image)
1830
+
1831
+ image = self.image_processor.postprocess(image, output_type=output_type)
1832
+
1833
+ # Offload last model to CPU
1834
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
1835
+ self.final_offload_hook.offload()
1836
+
1837
+ if not return_dict:
1838
+ return (image,)
1839
+
1840
+ return StableDiffusionXLPipelineOutput(images=image)
v0.30.0/pipeline_stable_diffusion_xl_differential_img2img.py ADDED
@@ -0,0 +1,1466 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PIL.Image
20
+ import torch
21
+ import torchvision
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ CLIPVisionModelWithProjection,
28
+ )
29
+
30
+ from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
31
+ from diffusers.loaders import (
32
+ FromSingleFileMixin,
33
+ IPAdapterMixin,
34
+ StableDiffusionXLLoraLoaderMixin,
35
+ TextualInversionLoaderMixin,
36
+ )
37
+ from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
38
+ from diffusers.models.attention_processor import (
39
+ AttnProcessor2_0,
40
+ XFormersAttnProcessor,
41
+ )
42
+ from diffusers.models.lora import adjust_lora_scale_text_encoder
43
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
44
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
45
+ from diffusers.schedulers import KarrasDiffusionSchedulers
46
+ from diffusers.utils import (
47
+ USE_PEFT_BACKEND,
48
+ deprecate,
49
+ is_invisible_watermark_available,
50
+ is_torch_xla_available,
51
+ logging,
52
+ replace_example_docstring,
53
+ scale_lora_layers,
54
+ unscale_lora_layers,
55
+ )
56
+ from diffusers.utils.torch_utils import randn_tensor
57
+
58
+
59
+ if is_invisible_watermark_available():
60
+ from diffusers.pipelines.stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
61
+
62
+ if is_torch_xla_available():
63
+ import torch_xla.core.xla_model as xm
64
+
65
+ XLA_AVAILABLE = True
66
+ else:
67
+ XLA_AVAILABLE = False
68
+
69
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
70
+
71
+ EXAMPLE_DOC_STRING = """
72
+ Examples:
73
+ ```py
74
+ >>> import torch
75
+ >>> from diffusers import StableDiffusionXLImg2ImgPipeline
76
+ >>> from diffusers.utils import load_image
77
+
78
+ >>> pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
79
+ ... "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16
80
+ ... )
81
+ >>> pipe = pipe.to("cuda")
82
+ >>> url = "https://huggingface.co/datasets/patrickvonplaten/images/resolve/main/aa_xl/000000009.png"
83
+
84
+ >>> init_image = load_image(url).convert("RGB")
85
+ >>> prompt = "a photo of an astronaut riding a horse on mars"
86
+ >>> image = pipe(prompt, image=init_image).images[0]
87
+ ```
88
+ """
89
+
90
+
91
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg
92
+ def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0):
93
+ """
94
+ Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules and
95
+ Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). See Section 3.4
96
+ """
97
+ std_text = noise_pred_text.std(dim=list(range(1, noise_pred_text.ndim)), keepdim=True)
98
+ std_cfg = noise_cfg.std(dim=list(range(1, noise_cfg.ndim)), keepdim=True)
99
+ # rescale the results from guidance (fixes overexposure)
100
+ noise_pred_rescaled = noise_cfg * (std_text / std_cfg)
101
+ # mix with the original results from guidance by factor guidance_rescale to avoid "plain looking" images
102
+ noise_cfg = guidance_rescale * noise_pred_rescaled + (1 - guidance_rescale) * noise_cfg
103
+ return noise_cfg
104
+
105
+
106
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
107
+ def retrieve_latents(
108
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
109
+ ):
110
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
111
+ return encoder_output.latent_dist.sample(generator)
112
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
113
+ return encoder_output.latent_dist.mode()
114
+ elif hasattr(encoder_output, "latents"):
115
+ return encoder_output.latents
116
+ else:
117
+ raise AttributeError("Could not access latents of provided encoder_output")
118
+
119
+
120
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
121
+ def retrieve_timesteps(
122
+ scheduler,
123
+ num_inference_steps: Optional[int] = None,
124
+ device: Optional[Union[str, torch.device]] = None,
125
+ timesteps: Optional[List[int]] = None,
126
+ **kwargs,
127
+ ):
128
+ """
129
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
130
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
131
+
132
+ Args:
133
+ scheduler (`SchedulerMixin`):
134
+ The scheduler to get timesteps from.
135
+ num_inference_steps (`int`):
136
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
137
+ `timesteps` must be `None`.
138
+ device (`str` or `torch.device`, *optional*):
139
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
140
+ timesteps (`List[int]`, *optional*):
141
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
142
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
143
+ must be `None`.
144
+
145
+ Returns:
146
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
147
+ second element is the number of inference steps.
148
+ """
149
+ if timesteps is not None:
150
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
151
+ if not accepts_timesteps:
152
+ raise ValueError(
153
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
154
+ f" timestep schedules. Please check whether you are using the correct scheduler."
155
+ )
156
+ scheduler.set_timesteps(timesteps=timesteps, 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 StableDiffusionXLDifferentialImg2ImgPipeline(
166
+ DiffusionPipeline,
167
+ StableDiffusionMixin,
168
+ TextualInversionLoaderMixin,
169
+ FromSingleFileMixin,
170
+ StableDiffusionXLLoraLoaderMixin,
171
+ IPAdapterMixin,
172
+ ):
173
+ r"""
174
+ Pipeline for text-to-image generation using Stable Diffusion XL.
175
+
176
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
177
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
178
+
179
+ In addition the pipeline inherits the following loading methods:
180
+ - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`]
181
+ - *LoRA*: [`loaders.StableDiffusionLoraLoaderMixin.load_lora_weights`]
182
+ - *Ckpt*: [`loaders.FromSingleFileMixin.from_single_file`]
183
+
184
+ as well as the following saving methods:
185
+ - *LoRA*: [`loaders.StableDiffusionLoraLoaderMixin.save_lora_weights`]
186
+
187
+ Args:
188
+ vae ([`AutoencoderKL`]):
189
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
190
+ text_encoder ([`CLIPTextModel`]):
191
+ Frozen text-encoder. Stable Diffusion XL uses the text portion of
192
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
193
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
194
+ text_encoder_2 ([` CLIPTextModelWithProjection`]):
195
+ Second frozen text-encoder. Stable Diffusion XL uses the text and pool portion of
196
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModelWithProjection),
197
+ specifically the
198
+ [laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)
199
+ variant.
200
+ tokenizer (`CLIPTokenizer`):
201
+ Tokenizer of class
202
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
203
+ tokenizer_2 (`CLIPTokenizer`):
204
+ Second Tokenizer of class
205
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
206
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
207
+ scheduler ([`SchedulerMixin`]):
208
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
209
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
210
+ """
211
+
212
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
213
+ _optional_components = [
214
+ "tokenizer",
215
+ "tokenizer_2",
216
+ "text_encoder",
217
+ "text_encoder_2",
218
+ "image_encoder",
219
+ "feature_extractor",
220
+ ]
221
+ _callback_tensor_inputs = [
222
+ "latents",
223
+ "prompt_embeds",
224
+ "negative_prompt_embeds",
225
+ "add_text_embeds",
226
+ "add_time_ids",
227
+ "negative_pooled_prompt_embeds",
228
+ "add_neg_time_ids",
229
+ ]
230
+
231
+ def __init__(
232
+ self,
233
+ vae: AutoencoderKL,
234
+ text_encoder: CLIPTextModel,
235
+ text_encoder_2: CLIPTextModelWithProjection,
236
+ tokenizer: CLIPTokenizer,
237
+ tokenizer_2: CLIPTokenizer,
238
+ unet: UNet2DConditionModel,
239
+ scheduler: KarrasDiffusionSchedulers,
240
+ image_encoder: CLIPVisionModelWithProjection = None,
241
+ feature_extractor: CLIPImageProcessor = None,
242
+ requires_aesthetics_score: bool = False,
243
+ force_zeros_for_empty_prompt: bool = True,
244
+ add_watermarker: Optional[bool] = None,
245
+ ):
246
+ super().__init__()
247
+
248
+ self.register_modules(
249
+ vae=vae,
250
+ text_encoder=text_encoder,
251
+ text_encoder_2=text_encoder_2,
252
+ tokenizer=tokenizer,
253
+ tokenizer_2=tokenizer_2,
254
+ unet=unet,
255
+ image_encoder=image_encoder,
256
+ feature_extractor=feature_extractor,
257
+ scheduler=scheduler,
258
+ )
259
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
260
+ self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
261
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
262
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
263
+
264
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
265
+
266
+ if add_watermarker:
267
+ self.watermark = StableDiffusionXLWatermarker()
268
+ else:
269
+ self.watermark = None
270
+
271
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
272
+ def encode_prompt(
273
+ self,
274
+ prompt: str,
275
+ prompt_2: Optional[str] = None,
276
+ device: Optional[torch.device] = None,
277
+ num_images_per_prompt: int = 1,
278
+ do_classifier_free_guidance: bool = True,
279
+ negative_prompt: Optional[str] = None,
280
+ negative_prompt_2: Optional[str] = None,
281
+ prompt_embeds: Optional[torch.Tensor] = None,
282
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
283
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
284
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
285
+ lora_scale: Optional[float] = None,
286
+ clip_skip: Optional[int] = None,
287
+ ):
288
+ r"""
289
+ Encodes the prompt into text encoder hidden states.
290
+
291
+ Args:
292
+ prompt (`str` or `List[str]`, *optional*):
293
+ prompt to be encoded
294
+ prompt_2 (`str` or `List[str]`, *optional*):
295
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
296
+ used in both text-encoders
297
+ device: (`torch.device`):
298
+ torch device
299
+ num_images_per_prompt (`int`):
300
+ number of images that should be generated per prompt
301
+ do_classifier_free_guidance (`bool`):
302
+ whether to use classifier free guidance or not
303
+ negative_prompt (`str` or `List[str]`, *optional*):
304
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
305
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
306
+ less than `1`).
307
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
308
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
309
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
310
+ prompt_embeds (`torch.Tensor`, *optional*):
311
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
312
+ provided, text embeddings will be generated from `prompt` input argument.
313
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
314
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
315
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
316
+ argument.
317
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
318
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
319
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
320
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
321
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
322
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
323
+ input argument.
324
+ lora_scale (`float`, *optional*):
325
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
326
+ clip_skip (`int`, *optional*):
327
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
328
+ the output of the pre-final layer will be used for computing the prompt embeddings.
329
+ """
330
+ device = device or self._execution_device
331
+
332
+ # set lora scale so that monkey patched LoRA
333
+ # function of text encoder can correctly access it
334
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
335
+ self._lora_scale = lora_scale
336
+
337
+ # dynamically adjust the LoRA scale
338
+ if self.text_encoder is not None:
339
+ if not USE_PEFT_BACKEND:
340
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
341
+ else:
342
+ scale_lora_layers(self.text_encoder, lora_scale)
343
+
344
+ if self.text_encoder_2 is not None:
345
+ if not USE_PEFT_BACKEND:
346
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
347
+ else:
348
+ scale_lora_layers(self.text_encoder_2, lora_scale)
349
+
350
+ prompt = [prompt] if isinstance(prompt, str) else prompt
351
+
352
+ if prompt is not None:
353
+ batch_size = len(prompt)
354
+ else:
355
+ batch_size = prompt_embeds.shape[0]
356
+
357
+ # Define tokenizers and text encoders
358
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
359
+ text_encoders = (
360
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
361
+ )
362
+
363
+ if prompt_embeds is None:
364
+ prompt_2 = prompt_2 or prompt
365
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
366
+
367
+ # textual inversion: process multi-vector tokens if necessary
368
+ prompt_embeds_list = []
369
+ prompts = [prompt, prompt_2]
370
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
371
+ if isinstance(self, TextualInversionLoaderMixin):
372
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
373
+
374
+ text_inputs = tokenizer(
375
+ prompt,
376
+ padding="max_length",
377
+ max_length=tokenizer.model_max_length,
378
+ truncation=True,
379
+ return_tensors="pt",
380
+ )
381
+
382
+ text_input_ids = text_inputs.input_ids
383
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
384
+
385
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
386
+ text_input_ids, untruncated_ids
387
+ ):
388
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
389
+ logger.warning(
390
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
391
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
392
+ )
393
+
394
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
395
+
396
+ # We are only ALWAYS interested in the pooled output of the final text encoder
397
+ pooled_prompt_embeds = prompt_embeds[0]
398
+ if clip_skip is None:
399
+ prompt_embeds = prompt_embeds.hidden_states[-2]
400
+ else:
401
+ # "2" because SDXL always indexes from the penultimate layer.
402
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
403
+
404
+ prompt_embeds_list.append(prompt_embeds)
405
+
406
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
407
+
408
+ # get unconditional embeddings for classifier free guidance
409
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
410
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
411
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
412
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
413
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
414
+ negative_prompt = negative_prompt or ""
415
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
416
+
417
+ # normalize str to list
418
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
419
+ negative_prompt_2 = (
420
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
421
+ )
422
+
423
+ uncond_tokens: List[str]
424
+ if prompt is not None and type(prompt) is not type(negative_prompt):
425
+ raise TypeError(
426
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
427
+ f" {type(prompt)}."
428
+ )
429
+ elif batch_size != len(negative_prompt):
430
+ raise ValueError(
431
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
432
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
433
+ " the batch size of `prompt`."
434
+ )
435
+ else:
436
+ uncond_tokens = [negative_prompt, negative_prompt_2]
437
+
438
+ negative_prompt_embeds_list = []
439
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
440
+ if isinstance(self, TextualInversionLoaderMixin):
441
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
442
+
443
+ max_length = prompt_embeds.shape[1]
444
+ uncond_input = tokenizer(
445
+ negative_prompt,
446
+ padding="max_length",
447
+ max_length=max_length,
448
+ truncation=True,
449
+ return_tensors="pt",
450
+ )
451
+
452
+ negative_prompt_embeds = text_encoder(
453
+ uncond_input.input_ids.to(device),
454
+ output_hidden_states=True,
455
+ )
456
+ # We are only ALWAYS interested in the pooled output of the final text encoder
457
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
458
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
459
+
460
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
461
+
462
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
463
+
464
+ if self.text_encoder_2 is not None:
465
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
466
+ else:
467
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
468
+
469
+ bs_embed, seq_len, _ = prompt_embeds.shape
470
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
471
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
472
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
473
+
474
+ if do_classifier_free_guidance:
475
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
476
+ seq_len = negative_prompt_embeds.shape[1]
477
+
478
+ if self.text_encoder_2 is not None:
479
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
480
+ else:
481
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
482
+
483
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
484
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
485
+
486
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
487
+ bs_embed * num_images_per_prompt, -1
488
+ )
489
+ if do_classifier_free_guidance:
490
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
491
+ bs_embed * num_images_per_prompt, -1
492
+ )
493
+
494
+ if self.text_encoder is not None:
495
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
496
+ # Retrieve the original scale by scaling back the LoRA layers
497
+ unscale_lora_layers(self.text_encoder, lora_scale)
498
+
499
+ if self.text_encoder_2 is not None:
500
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
501
+ # Retrieve the original scale by scaling back the LoRA layers
502
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
503
+
504
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
505
+
506
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
507
+ def prepare_extra_step_kwargs(self, generator, eta):
508
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
509
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
510
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
511
+ # and should be between [0, 1]
512
+
513
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
514
+ extra_step_kwargs = {}
515
+ if accepts_eta:
516
+ extra_step_kwargs["eta"] = eta
517
+
518
+ # check if the scheduler accepts generator
519
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
520
+ if accepts_generator:
521
+ extra_step_kwargs["generator"] = generator
522
+ return extra_step_kwargs
523
+
524
+ def check_inputs(
525
+ self,
526
+ prompt,
527
+ prompt_2,
528
+ strength,
529
+ num_inference_steps,
530
+ callback_steps,
531
+ negative_prompt=None,
532
+ negative_prompt_2=None,
533
+ prompt_embeds=None,
534
+ negative_prompt_embeds=None,
535
+ ip_adapter_image=None,
536
+ ip_adapter_image_embeds=None,
537
+ callback_on_step_end_tensor_inputs=None,
538
+ ):
539
+ if strength < 0 or strength > 1:
540
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
541
+ if num_inference_steps is None:
542
+ raise ValueError("`num_inference_steps` cannot be None.")
543
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
544
+ raise ValueError(
545
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
546
+ f" {type(num_inference_steps)}."
547
+ )
548
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
549
+ raise ValueError(
550
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
551
+ f" {type(callback_steps)}."
552
+ )
553
+
554
+ if callback_on_step_end_tensor_inputs is not None and not all(
555
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
556
+ ):
557
+ raise ValueError(
558
+ 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]}"
559
+ )
560
+
561
+ if prompt is not None and prompt_embeds is not None:
562
+ raise ValueError(
563
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
564
+ " only forward one of the two."
565
+ )
566
+ elif prompt_2 is not None and prompt_embeds is not None:
567
+ raise ValueError(
568
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
569
+ " only forward one of the two."
570
+ )
571
+ elif prompt is None and prompt_embeds is None:
572
+ raise ValueError(
573
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
574
+ )
575
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
576
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
577
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
578
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
579
+
580
+ if negative_prompt is not None and negative_prompt_embeds is not None:
581
+ raise ValueError(
582
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
583
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
584
+ )
585
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
586
+ raise ValueError(
587
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
588
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
589
+ )
590
+
591
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
592
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
593
+ raise ValueError(
594
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
595
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
596
+ f" {negative_prompt_embeds.shape}."
597
+ )
598
+
599
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
600
+ raise ValueError(
601
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
602
+ )
603
+
604
+ if ip_adapter_image_embeds is not None:
605
+ if not isinstance(ip_adapter_image_embeds, list):
606
+ raise ValueError(
607
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
608
+ )
609
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
610
+ raise ValueError(
611
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
612
+ )
613
+
614
+ def get_timesteps(self, num_inference_steps, strength, device, denoising_start=None):
615
+ # get the original timestep using init_timestep
616
+ if denoising_start is None:
617
+ init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
618
+ t_start = max(num_inference_steps - init_timestep, 0)
619
+ else:
620
+ t_start = 0
621
+
622
+ timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
623
+
624
+ # Strength is irrelevant if we directly request a timestep to start at;
625
+ # that is, strength is determined by the denoising_start instead.
626
+ if denoising_start is not None:
627
+ discrete_timestep_cutoff = int(
628
+ round(
629
+ self.scheduler.config.num_train_timesteps
630
+ - (denoising_start * self.scheduler.config.num_train_timesteps)
631
+ )
632
+ )
633
+
634
+ num_inference_steps = (timesteps < discrete_timestep_cutoff).sum().item()
635
+ if self.scheduler.order == 2 and num_inference_steps % 2 == 0:
636
+ # if the scheduler is a 2nd order scheduler we might have to do +1
637
+ # because `num_inference_steps` might be even given that every timestep
638
+ # (except the highest one) is duplicated. If `num_inference_steps` is even it would
639
+ # mean that we cut the timesteps in the middle of the denoising step
640
+ # (between 1st and 2nd derivative) which leads to incorrect results. By adding 1
641
+ # we ensure that the denoising process always ends after the 2nd derivate step of the scheduler
642
+ num_inference_steps = num_inference_steps + 1
643
+
644
+ # because t_n+1 >= t_n, we slice the timesteps starting from the end
645
+ timesteps = timesteps[-num_inference_steps:]
646
+ return timesteps, num_inference_steps
647
+
648
+ return timesteps, num_inference_steps - t_start
649
+
650
+ def prepare_latents(
651
+ self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
652
+ ):
653
+ if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
654
+ raise ValueError(
655
+ f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
656
+ )
657
+
658
+ # Offload text encoder if `enable_model_cpu_offload` was enabled
659
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
660
+ self.text_encoder_2.to("cpu")
661
+ torch.cuda.empty_cache()
662
+
663
+ image = image.to(device=device, dtype=dtype)
664
+
665
+ batch_size = batch_size * num_images_per_prompt
666
+
667
+ if image.shape[1] == 4:
668
+ init_latents = image
669
+
670
+ else:
671
+ # make sure the VAE is in float32 mode, as it overflows in float16
672
+ if self.vae.config.force_upcast:
673
+ image = image.float()
674
+ self.vae.to(dtype=torch.float32)
675
+
676
+ if isinstance(generator, list) and len(generator) != batch_size:
677
+ raise ValueError(
678
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
679
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
680
+ )
681
+
682
+ elif isinstance(generator, list):
683
+ init_latents = [
684
+ retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
685
+ for i in range(batch_size)
686
+ ]
687
+ init_latents = torch.cat(init_latents, dim=0)
688
+ else:
689
+ init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
690
+
691
+ if self.vae.config.force_upcast:
692
+ self.vae.to(dtype)
693
+
694
+ init_latents = init_latents.to(dtype)
695
+ init_latents = self.vae.config.scaling_factor * init_latents
696
+
697
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
698
+ # expand init_latents for batch_size
699
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
700
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
701
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
702
+ raise ValueError(
703
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
704
+ )
705
+ else:
706
+ init_latents = torch.cat([init_latents], dim=0)
707
+
708
+ if add_noise:
709
+ shape = init_latents.shape
710
+ noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
711
+ # get latents
712
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
713
+
714
+ latents = init_latents
715
+
716
+ return latents
717
+
718
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
719
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
720
+ dtype = next(self.image_encoder.parameters()).dtype
721
+
722
+ if not isinstance(image, torch.Tensor):
723
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
724
+
725
+ image = image.to(device=device, dtype=dtype)
726
+ if output_hidden_states:
727
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
728
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
729
+ uncond_image_enc_hidden_states = self.image_encoder(
730
+ torch.zeros_like(image), output_hidden_states=True
731
+ ).hidden_states[-2]
732
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
733
+ num_images_per_prompt, dim=0
734
+ )
735
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
736
+ else:
737
+ image_embeds = self.image_encoder(image).image_embeds
738
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
739
+ uncond_image_embeds = torch.zeros_like(image_embeds)
740
+
741
+ return image_embeds, uncond_image_embeds
742
+
743
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
744
+ def prepare_ip_adapter_image_embeds(
745
+ self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
746
+ ):
747
+ if ip_adapter_image_embeds is None:
748
+ if not isinstance(ip_adapter_image, list):
749
+ ip_adapter_image = [ip_adapter_image]
750
+
751
+ if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
752
+ raise ValueError(
753
+ 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."
754
+ )
755
+
756
+ image_embeds = []
757
+ for single_ip_adapter_image, image_proj_layer in zip(
758
+ ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
759
+ ):
760
+ output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
761
+ single_image_embeds, single_negative_image_embeds = self.encode_image(
762
+ single_ip_adapter_image, device, 1, output_hidden_state
763
+ )
764
+ single_image_embeds = torch.stack([single_image_embeds] * num_images_per_prompt, dim=0)
765
+ single_negative_image_embeds = torch.stack(
766
+ [single_negative_image_embeds] * num_images_per_prompt, dim=0
767
+ )
768
+
769
+ if do_classifier_free_guidance:
770
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
771
+ single_image_embeds = single_image_embeds.to(device)
772
+
773
+ image_embeds.append(single_image_embeds)
774
+ else:
775
+ repeat_dims = [1]
776
+ image_embeds = []
777
+ for single_image_embeds in ip_adapter_image_embeds:
778
+ if do_classifier_free_guidance:
779
+ single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
780
+ single_image_embeds = single_image_embeds.repeat(
781
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
782
+ )
783
+ single_negative_image_embeds = single_negative_image_embeds.repeat(
784
+ num_images_per_prompt, *(repeat_dims * len(single_negative_image_embeds.shape[1:]))
785
+ )
786
+ single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds])
787
+ else:
788
+ single_image_embeds = single_image_embeds.repeat(
789
+ num_images_per_prompt, *(repeat_dims * len(single_image_embeds.shape[1:]))
790
+ )
791
+ image_embeds.append(single_image_embeds)
792
+
793
+ return image_embeds
794
+
795
+ def _get_add_time_ids(
796
+ self,
797
+ original_size,
798
+ crops_coords_top_left,
799
+ target_size,
800
+ aesthetic_score,
801
+ negative_aesthetic_score,
802
+ negative_original_size,
803
+ negative_crops_coords_top_left,
804
+ negative_target_size,
805
+ dtype,
806
+ text_encoder_projection_dim=None,
807
+ ):
808
+ if self.config.requires_aesthetics_score:
809
+ add_time_ids = list(original_size + crops_coords_top_left + (aesthetic_score,))
810
+ add_neg_time_ids = list(
811
+ negative_original_size + negative_crops_coords_top_left + (negative_aesthetic_score,)
812
+ )
813
+ else:
814
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
815
+ add_neg_time_ids = list(negative_original_size + crops_coords_top_left + negative_target_size)
816
+
817
+ passed_add_embed_dim = (
818
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
819
+ )
820
+ expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
821
+
822
+ if (
823
+ expected_add_embed_dim > passed_add_embed_dim
824
+ and (expected_add_embed_dim - passed_add_embed_dim) == self.unet.config.addition_time_embed_dim
825
+ ):
826
+ raise ValueError(
827
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to enable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=True)` to make sure `aesthetic_score` {aesthetic_score} and `negative_aesthetic_score` {negative_aesthetic_score} is correctly used by the model."
828
+ )
829
+ elif (
830
+ expected_add_embed_dim < passed_add_embed_dim
831
+ and (passed_add_embed_dim - expected_add_embed_dim) == self.unet.config.addition_time_embed_dim
832
+ ):
833
+ raise ValueError(
834
+ f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. Please make sure to disable `requires_aesthetics_score` with `pipe.register_to_config(requires_aesthetics_score=False)` to make sure `target_size` {target_size} is correctly used by the model."
835
+ )
836
+ elif expected_add_embed_dim != passed_add_embed_dim:
837
+ raise ValueError(
838
+ 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`."
839
+ )
840
+
841
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
842
+ add_neg_time_ids = torch.tensor([add_neg_time_ids], dtype=dtype)
843
+
844
+ return add_time_ids, add_neg_time_ids
845
+
846
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
847
+ def upcast_vae(self):
848
+ dtype = self.vae.dtype
849
+ self.vae.to(dtype=torch.float32)
850
+ use_torch_2_0_or_xformers = isinstance(
851
+ self.vae.decoder.mid_block.attentions[0].processor,
852
+ (
853
+ AttnProcessor2_0,
854
+ XFormersAttnProcessor,
855
+ ),
856
+ )
857
+ # if xformers or torch_2_0 is used attention block does not need
858
+ # to be in float32 which can save lots of memory
859
+ if use_torch_2_0_or_xformers:
860
+ self.vae.post_quant_conv.to(dtype)
861
+ self.vae.decoder.conv_in.to(dtype)
862
+ self.vae.decoder.mid_block.to(dtype)
863
+
864
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
865
+ def get_guidance_scale_embedding(
866
+ self, w: torch.Tensor, embedding_dim: int = 512, dtype: torch.dtype = torch.float32
867
+ ) -> torch.Tensor:
868
+ """
869
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
870
+
871
+ Args:
872
+ w (`torch.Tensor`):
873
+ Generate embedding vectors with a specified guidance scale to subsequently enrich timestep embeddings.
874
+ embedding_dim (`int`, *optional*, defaults to 512):
875
+ Dimension of the embeddings to generate.
876
+ dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
877
+ Data type of the generated embeddings.
878
+
879
+ Returns:
880
+ `torch.Tensor`: Embedding vectors with shape `(len(w), embedding_dim)`.
881
+ """
882
+ assert len(w.shape) == 1
883
+ w = w * 1000.0
884
+
885
+ half_dim = embedding_dim // 2
886
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
887
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
888
+ emb = w.to(dtype)[:, None] * emb[None, :]
889
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
890
+ if embedding_dim % 2 == 1: # zero pad
891
+ emb = torch.nn.functional.pad(emb, (0, 1))
892
+ assert emb.shape == (w.shape[0], embedding_dim)
893
+ return emb
894
+
895
+ @property
896
+ def guidance_scale(self):
897
+ return self._guidance_scale
898
+
899
+ @property
900
+ def guidance_rescale(self):
901
+ return self._guidance_rescale
902
+
903
+ @property
904
+ def clip_skip(self):
905
+ return self._clip_skip
906
+
907
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
908
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
909
+ # corresponds to doing no classifier free guidance.
910
+ @property
911
+ def do_classifier_free_guidance(self):
912
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
913
+
914
+ @property
915
+ def cross_attention_kwargs(self):
916
+ return self._cross_attention_kwargs
917
+
918
+ @property
919
+ def denoising_end(self):
920
+ return self._denoising_end
921
+
922
+ @property
923
+ def denoising_start(self):
924
+ return self._denoising_start
925
+
926
+ @property
927
+ def num_timesteps(self):
928
+ return self._num_timesteps
929
+
930
+ @property
931
+ def interrupt(self):
932
+ return self._interrupt
933
+
934
+ @torch.no_grad()
935
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
936
+ def __call__(
937
+ self,
938
+ prompt: Union[str, List[str]] = None,
939
+ prompt_2: Optional[Union[str, List[str]]] = None,
940
+ image: Union[
941
+ torch.Tensor,
942
+ PIL.Image.Image,
943
+ np.ndarray,
944
+ List[torch.Tensor],
945
+ List[PIL.Image.Image],
946
+ List[np.ndarray],
947
+ ] = None,
948
+ strength: float = 0.3,
949
+ num_inference_steps: int = 50,
950
+ timesteps: List[int] = None,
951
+ denoising_start: Optional[float] = None,
952
+ denoising_end: Optional[float] = None,
953
+ guidance_scale: float = 5.0,
954
+ negative_prompt: Optional[Union[str, List[str]]] = None,
955
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
956
+ num_images_per_prompt: Optional[int] = 1,
957
+ eta: float = 0.0,
958
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
959
+ latents: Optional[torch.Tensor] = None,
960
+ prompt_embeds: Optional[torch.Tensor] = None,
961
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
962
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
963
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
964
+ ip_adapter_image: Optional[PipelineImageInput] = None,
965
+ ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
966
+ output_type: Optional[str] = "pil",
967
+ return_dict: bool = True,
968
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
969
+ guidance_rescale: float = 0.0,
970
+ original_size: Tuple[int, int] = None,
971
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
972
+ target_size: Tuple[int, int] = None,
973
+ negative_original_size: Optional[Tuple[int, int]] = None,
974
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
975
+ negative_target_size: Optional[Tuple[int, int]] = None,
976
+ aesthetic_score: float = 6.0,
977
+ negative_aesthetic_score: float = 2.5,
978
+ clip_skip: Optional[int] = None,
979
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
980
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
981
+ map: torch.Tensor = None,
982
+ original_image: Union[
983
+ torch.Tensor,
984
+ PIL.Image.Image,
985
+ np.ndarray,
986
+ List[torch.Tensor],
987
+ List[PIL.Image.Image],
988
+ List[np.ndarray],
989
+ ] = None,
990
+ **kwargs,
991
+ ):
992
+ r"""
993
+ Function invoked when calling the pipeline for generation.
994
+
995
+ Args:
996
+ prompt (`str` or `List[str]`, *optional*):
997
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
998
+ instead.
999
+ prompt_2 (`str` or `List[str]`, *optional*):
1000
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
1001
+ used in both text-encoders
1002
+ image (`torch.Tensor` or `PIL.Image.Image` or `np.ndarray` or `List[torch.Tensor]` or `List[PIL.Image.Image]` or `List[np.ndarray]`):
1003
+ The image(s) to modify with the pipeline.
1004
+ strength (`float`, *optional*, defaults to 0.3):
1005
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
1006
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
1007
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
1008
+ be maximum and the denoising process will run for the full number of iterations specified in
1009
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`. Note that in the case of
1010
+ `denoising_start` being declared as an integer, the value of `strength` will be ignored.
1011
+ num_inference_steps (`int`, *optional*, defaults to 50):
1012
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
1013
+ expense of slower inference.
1014
+ denoising_start (`float`, *optional*):
1015
+ When specified, indicates the fraction (between 0.0 and 1.0) of the total denoising process to be
1016
+ bypassed before it is initiated. Consequently, the initial part of the denoising process is skipped and
1017
+ it is assumed that the passed `image` is a partly denoised image. Note that when this is specified,
1018
+ strength will be ignored. The `denoising_start` parameter is particularly beneficial when this pipeline
1019
+ is integrated into a "Mixture of Denoisers" multi-pipeline setup, as detailed in [**Refining the Image
1020
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1021
+ denoising_end (`float`, *optional*):
1022
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
1023
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
1024
+ still retain a substantial amount of noise (ca. final 20% of timesteps still needed) and should be
1025
+ denoised by a successor pipeline that has `denoising_start` set to 0.8 so that it only denoises the
1026
+ final 20% of the scheduler. The denoising_end parameter should ideally be utilized when this pipeline
1027
+ forms a part of a "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
1028
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output).
1029
+ guidance_scale (`float`, *optional*, defaults to 7.5):
1030
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
1031
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
1032
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1033
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
1034
+ usually at the expense of lower image quality.
1035
+ negative_prompt (`str` or `List[str]`, *optional*):
1036
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
1037
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
1038
+ less than `1`).
1039
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
1040
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
1041
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
1042
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
1043
+ The number of images to generate per prompt.
1044
+ eta (`float`, *optional*, defaults to 0.0):
1045
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
1046
+ [`schedulers.DDIMScheduler`], will be ignored for others.
1047
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
1048
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
1049
+ to make generation deterministic.
1050
+ latents (`torch.Tensor`, *optional*):
1051
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
1052
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
1053
+ tensor will ge generated by sampling using the supplied random `generator`.
1054
+ prompt_embeds (`torch.Tensor`, *optional*):
1055
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
1056
+ provided, text embeddings will be generated from `prompt` input argument.
1057
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
1058
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1059
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
1060
+ argument.
1061
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
1062
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
1063
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
1064
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
1065
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
1066
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
1067
+ input argument.
1068
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1069
+ ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
1070
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
1071
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
1072
+ if `do_classifier_free_guidance` is set to `True`.
1073
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
1074
+ output_type (`str`, *optional*, defaults to `"pil"`):
1075
+ The output format of the generate image. Choose between
1076
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
1077
+ return_dict (`bool`, *optional*, defaults to `True`):
1078
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] instead of a
1079
+ plain tuple.
1080
+ callback (`Callable`, *optional*):
1081
+ A function that will be called every `callback_steps` steps during inference. The function will be
1082
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
1083
+ callback_steps (`int`, *optional*, defaults to 1):
1084
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
1085
+ called at every step.
1086
+ cross_attention_kwargs (`dict`, *optional*):
1087
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
1088
+ `self.processor` in
1089
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
1090
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
1091
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
1092
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
1093
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
1094
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
1095
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1096
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
1097
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
1098
+ explained in section 2.2 of
1099
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1100
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
1101
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
1102
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
1103
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
1104
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1105
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
1106
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
1107
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
1108
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1109
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
1110
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
1111
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1112
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
1113
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
1114
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
1115
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
1116
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
1117
+
1118
+ Examples:
1119
+
1120
+ Returns:
1121
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
1122
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
1123
+ `tuple. When returning a tuple, the first element is a list with the generated images.
1124
+ """
1125
+
1126
+ callback = kwargs.pop("callback", None)
1127
+ callback_steps = kwargs.pop("callback_steps", None)
1128
+
1129
+ if callback is not None:
1130
+ deprecate(
1131
+ "callback",
1132
+ "1.0.0",
1133
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1134
+ )
1135
+ if callback_steps is not None:
1136
+ deprecate(
1137
+ "callback_steps",
1138
+ "1.0.0",
1139
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
1140
+ )
1141
+
1142
+ # 1. Check inputs. Raise error if not correct
1143
+ self.check_inputs(
1144
+ prompt,
1145
+ prompt_2,
1146
+ strength,
1147
+ num_inference_steps,
1148
+ callback_steps,
1149
+ negative_prompt,
1150
+ negative_prompt_2,
1151
+ prompt_embeds,
1152
+ negative_prompt_embeds,
1153
+ ip_adapter_image,
1154
+ ip_adapter_image_embeds,
1155
+ callback_on_step_end_tensor_inputs,
1156
+ )
1157
+
1158
+ self._guidance_scale = guidance_scale
1159
+ self._guidance_rescale = guidance_rescale
1160
+ self._clip_skip = clip_skip
1161
+ self._cross_attention_kwargs = cross_attention_kwargs
1162
+ self._denoising_end = denoising_end
1163
+ self._denoising_start = denoising_start
1164
+ self._interrupt = False
1165
+
1166
+ # 2. Define call parameters
1167
+ if prompt is not None and isinstance(prompt, str):
1168
+ batch_size = 1
1169
+ elif prompt is not None and isinstance(prompt, list):
1170
+ batch_size = len(prompt)
1171
+ else:
1172
+ batch_size = prompt_embeds.shape[0]
1173
+
1174
+ device = self._execution_device
1175
+
1176
+ # 3. Encode input prompt
1177
+ text_encoder_lora_scale = (
1178
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1179
+ )
1180
+ (
1181
+ prompt_embeds,
1182
+ negative_prompt_embeds,
1183
+ pooled_prompt_embeds,
1184
+ negative_pooled_prompt_embeds,
1185
+ ) = self.encode_prompt(
1186
+ prompt=prompt,
1187
+ prompt_2=prompt_2,
1188
+ device=device,
1189
+ num_images_per_prompt=num_images_per_prompt,
1190
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1191
+ negative_prompt=negative_prompt,
1192
+ negative_prompt_2=negative_prompt_2,
1193
+ prompt_embeds=prompt_embeds,
1194
+ negative_prompt_embeds=negative_prompt_embeds,
1195
+ pooled_prompt_embeds=pooled_prompt_embeds,
1196
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1197
+ lora_scale=text_encoder_lora_scale,
1198
+ )
1199
+
1200
+ # 4. Preprocess image
1201
+ # image = self.image_processor.preprocess(image) #ideally we would have preprocess the image with diffusers, but for this POC we won't --- it throws a deprecated warning
1202
+ map = torchvision.transforms.Resize(
1203
+ tuple(s // self.vae_scale_factor for s in original_image.shape[2:]), antialias=None
1204
+ )(map)
1205
+
1206
+ # 5. Prepare timesteps
1207
+ def denoising_value_valid(dnv):
1208
+ return isinstance(dnv, float) and 0 < dnv < 1
1209
+
1210
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1211
+
1212
+ # begin diff diff change
1213
+ total_time_steps = num_inference_steps
1214
+ # end diff diff change
1215
+
1216
+ timesteps, num_inference_steps = self.get_timesteps(
1217
+ num_inference_steps,
1218
+ strength,
1219
+ device,
1220
+ denoising_start=self.denoising_start if denoising_value_valid(self.denoising_start) else None,
1221
+ )
1222
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1223
+
1224
+ add_noise = True if denoising_start is None else False
1225
+ # 6. Prepare latent variables
1226
+ latents = self.prepare_latents(
1227
+ image,
1228
+ latent_timestep,
1229
+ batch_size,
1230
+ num_images_per_prompt,
1231
+ prompt_embeds.dtype,
1232
+ device,
1233
+ generator,
1234
+ add_noise,
1235
+ )
1236
+ # 7. Prepare extra step kwargs.
1237
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1238
+
1239
+ height, width = latents.shape[-2:]
1240
+ height = height * self.vae_scale_factor
1241
+ width = width * self.vae_scale_factor
1242
+
1243
+ original_size = original_size or (height, width)
1244
+ target_size = target_size or (height, width)
1245
+
1246
+ # 8. Prepare added time ids & embeddings
1247
+ if negative_original_size is None:
1248
+ negative_original_size = original_size
1249
+ if negative_target_size is None:
1250
+ negative_target_size = target_size
1251
+
1252
+ add_text_embeds = pooled_prompt_embeds
1253
+ if self.text_encoder_2 is None:
1254
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1255
+ else:
1256
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1257
+
1258
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
1259
+ original_size,
1260
+ crops_coords_top_left,
1261
+ target_size,
1262
+ aesthetic_score,
1263
+ negative_aesthetic_score,
1264
+ negative_original_size,
1265
+ negative_crops_coords_top_left,
1266
+ negative_target_size,
1267
+ dtype=prompt_embeds.dtype,
1268
+ text_encoder_projection_dim=text_encoder_projection_dim,
1269
+ )
1270
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1271
+
1272
+ if self.do_classifier_free_guidance:
1273
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1274
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1275
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
1276
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
1277
+
1278
+ prompt_embeds = prompt_embeds.to(device)
1279
+ add_text_embeds = add_text_embeds.to(device)
1280
+ add_time_ids = add_time_ids.to(device)
1281
+
1282
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1283
+ image_embeds = self.prepare_ip_adapter_image_embeds(
1284
+ ip_adapter_image,
1285
+ ip_adapter_image_embeds,
1286
+ device,
1287
+ batch_size * num_images_per_prompt,
1288
+ self.do_classifier_free_guidance,
1289
+ )
1290
+
1291
+ # 9. Denoising loop
1292
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
1293
+
1294
+ # 9.1 Apply denoising_end
1295
+ if (
1296
+ denoising_end is not None
1297
+ and denoising_start is not None
1298
+ and denoising_value_valid(denoising_end)
1299
+ and denoising_value_valid(denoising_start)
1300
+ and denoising_start >= denoising_end
1301
+ ):
1302
+ raise ValueError(
1303
+ f"`denoising_start`: {denoising_start} cannot be larger than or equal to `denoising_end`: "
1304
+ + f" {denoising_end} when using type float."
1305
+ )
1306
+ elif denoising_end is not None and denoising_value_valid(denoising_end):
1307
+ discrete_timestep_cutoff = int(
1308
+ round(
1309
+ self.scheduler.config.num_train_timesteps
1310
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
1311
+ )
1312
+ )
1313
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
1314
+ timesteps = timesteps[:num_inference_steps]
1315
+
1316
+ # preparations for diff diff
1317
+ original_with_noise = self.prepare_latents(
1318
+ original_image, timesteps, batch_size, num_images_per_prompt, prompt_embeds.dtype, device, generator
1319
+ )
1320
+ thresholds = torch.arange(total_time_steps, dtype=map.dtype) / total_time_steps
1321
+ thresholds = thresholds.unsqueeze(1).unsqueeze(1).to(device)
1322
+ masks = map > (thresholds + (denoising_start or 0))
1323
+ # end diff diff preparations
1324
+
1325
+ # 9.2 Optionally get Guidance Scale Embedding
1326
+ timestep_cond = None
1327
+ if self.unet.config.time_cond_proj_dim is not None:
1328
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1329
+ timestep_cond = self.get_guidance_scale_embedding(
1330
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1331
+ ).to(device=device, dtype=latents.dtype)
1332
+
1333
+ self._num_timesteps = len(timesteps)
1334
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1335
+ for i, t in enumerate(timesteps):
1336
+ if self.interrupt:
1337
+ continue
1338
+
1339
+ # diff diff
1340
+ if i == 0 and denoising_start is None:
1341
+ latents = original_with_noise[:1]
1342
+ else:
1343
+ mask = masks[i].unsqueeze(0)
1344
+ # cast mask to the same type as latents etc
1345
+ mask = mask.to(latents.dtype)
1346
+ mask = mask.unsqueeze(1) # fit shape
1347
+ latents = original_with_noise[i] * mask + latents * (1 - mask)
1348
+ # end diff diff
1349
+
1350
+ # expand the latents if we are doing classifier free guidance
1351
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1352
+
1353
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1354
+
1355
+ # predict the noise residual
1356
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1357
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
1358
+ added_cond_kwargs["image_embeds"] = image_embeds
1359
+ noise_pred = self.unet(
1360
+ latent_model_input,
1361
+ t,
1362
+ encoder_hidden_states=prompt_embeds,
1363
+ timestep_cond=timestep_cond,
1364
+ cross_attention_kwargs=cross_attention_kwargs,
1365
+ added_cond_kwargs=added_cond_kwargs,
1366
+ return_dict=False,
1367
+ )[0]
1368
+
1369
+ # perform guidance
1370
+ if self.do_classifier_free_guidance:
1371
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1372
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1373
+
1374
+ if self.do_classifier_free_guidance and guidance_rescale > 0.0:
1375
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
1376
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
1377
+
1378
+ # compute the previous noisy sample x_t -> x_t-1
1379
+ latents_dtype = latents.dtype
1380
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1381
+ if latents.dtype != latents_dtype:
1382
+ if torch.backends.mps.is_available():
1383
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1384
+ latents = latents.to(latents_dtype)
1385
+ else:
1386
+ raise ValueError(
1387
+ "For the given accelerator, there seems to be an unexpected problem in type-casting. Please file an issue on the PyTorch GitHub repository. See also: https://github.com/huggingface/diffusers/pull/7446/."
1388
+ )
1389
+
1390
+ if callback_on_step_end is not None:
1391
+ callback_kwargs = {}
1392
+ for k in callback_on_step_end_tensor_inputs:
1393
+ callback_kwargs[k] = locals()[k]
1394
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1395
+
1396
+ latents = callback_outputs.pop("latents", latents)
1397
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1398
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1399
+ add_text_embeds = callback_outputs.pop("add_text_embeds", add_text_embeds)
1400
+ negative_pooled_prompt_embeds = callback_outputs.pop(
1401
+ "negative_pooled_prompt_embeds", negative_pooled_prompt_embeds
1402
+ )
1403
+ add_time_ids = callback_outputs.pop("add_time_ids", add_time_ids)
1404
+ add_neg_time_ids = callback_outputs.pop("add_neg_time_ids", add_neg_time_ids)
1405
+
1406
+ # call the callback, if provided
1407
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1408
+ progress_bar.update()
1409
+ if callback is not None and i % callback_steps == 0:
1410
+ step_idx = i // getattr(self.scheduler, "order", 1)
1411
+ callback(step_idx, t, latents)
1412
+
1413
+ if XLA_AVAILABLE:
1414
+ xm.mark_step()
1415
+
1416
+ if not output_type == "latent":
1417
+ # make sure the VAE is in float32 mode, as it overflows in float16
1418
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1419
+
1420
+ if needs_upcasting:
1421
+ self.upcast_vae()
1422
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1423
+ elif latents.dtype != self.vae.dtype:
1424
+ if torch.backends.mps.is_available():
1425
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1426
+ self.vae = self.vae.to(latents.dtype)
1427
+ else:
1428
+ raise ValueError(
1429
+ "For the given accelerator, there seems to be an unexpected problem in type-casting. Please file an issue on the PyTorch GitHub repository. See also: https://github.com/huggingface/diffusers/pull/7446/."
1430
+ )
1431
+ # unscale/denormalize the latents
1432
+ # denormalize with the mean and std if available and not None
1433
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1434
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1435
+ if has_latents_mean and has_latents_std:
1436
+ latents_mean = (
1437
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1438
+ )
1439
+ latents_std = (
1440
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1441
+ )
1442
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1443
+ else:
1444
+ latents = latents / self.vae.config.scaling_factor
1445
+
1446
+ image = self.vae.decode(latents, return_dict=False)[0]
1447
+
1448
+ # cast back to fp16 if needed
1449
+ if needs_upcasting:
1450
+ self.vae.to(dtype=torch.float16)
1451
+ else:
1452
+ image = latents
1453
+
1454
+ # apply watermark if available
1455
+ if self.watermark is not None:
1456
+ image = self.watermark.apply_watermark(image)
1457
+
1458
+ image = self.image_processor.postprocess(image, output_type=output_type)
1459
+
1460
+ # Offload all models
1461
+ self.maybe_free_model_hooks()
1462
+
1463
+ if not return_dict:
1464
+ return (image,)
1465
+
1466
+ return StableDiffusionXLPipelineOutput(images=image)