diffusers 0.23.1__py3-none-any.whl → 0.24.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (176) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +0 -1
  4. diffusers/dependency_versions_table.py +4 -5
  5. diffusers/image_processor.py +186 -14
  6. diffusers/loaders/__init__.py +82 -0
  7. diffusers/loaders/ip_adapter.py +157 -0
  8. diffusers/loaders/lora.py +1415 -0
  9. diffusers/loaders/lora_conversion_utils.py +284 -0
  10. diffusers/loaders/single_file.py +631 -0
  11. diffusers/loaders/textual_inversion.py +459 -0
  12. diffusers/loaders/unet.py +735 -0
  13. diffusers/loaders/utils.py +59 -0
  14. diffusers/models/__init__.py +12 -1
  15. diffusers/models/attention.py +165 -14
  16. diffusers/models/attention_flax.py +9 -1
  17. diffusers/models/attention_processor.py +286 -1
  18. diffusers/models/autoencoder_asym_kl.py +14 -9
  19. diffusers/models/autoencoder_kl.py +3 -18
  20. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  21. diffusers/models/autoencoder_tiny.py +20 -24
  22. diffusers/models/consistency_decoder_vae.py +37 -30
  23. diffusers/models/controlnet.py +59 -39
  24. diffusers/models/controlnet_flax.py +19 -18
  25. diffusers/models/embeddings_flax.py +2 -0
  26. diffusers/models/lora.py +131 -1
  27. diffusers/models/modeling_flax_utils.py +2 -1
  28. diffusers/models/modeling_outputs.py +17 -0
  29. diffusers/models/modeling_utils.py +27 -19
  30. diffusers/models/normalization.py +2 -2
  31. diffusers/models/resnet.py +390 -59
  32. diffusers/models/transformer_2d.py +20 -3
  33. diffusers/models/transformer_temporal.py +183 -1
  34. diffusers/models/unet_2d_blocks_flax.py +5 -0
  35. diffusers/models/unet_2d_condition.py +9 -0
  36. diffusers/models/unet_2d_condition_flax.py +13 -13
  37. diffusers/models/unet_3d_blocks.py +957 -173
  38. diffusers/models/unet_3d_condition.py +16 -8
  39. diffusers/models/unet_kandi3.py +589 -0
  40. diffusers/models/unet_motion_model.py +48 -33
  41. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  42. diffusers/models/vae.py +63 -13
  43. diffusers/models/vae_flax.py +7 -0
  44. diffusers/models/vq_model.py +3 -1
  45. diffusers/optimization.py +16 -9
  46. diffusers/pipelines/__init__.py +65 -12
  47. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
  48. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
  49. diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
  50. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  51. diffusers/pipelines/auto_pipeline.py +6 -0
  52. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  53. diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
  54. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
  55. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
  56. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
  57. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
  58. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
  59. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  60. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  61. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  62. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  63. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  64. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  65. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  66. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  67. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  68. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  69. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  70. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  71. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  72. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  73. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  74. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  75. diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
  76. diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
  77. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
  78. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
  79. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  80. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  81. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  82. diffusers/pipelines/pipeline_flax_utils.py +4 -2
  83. diffusers/pipelines/pipeline_utils.py +33 -13
  84. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
  85. diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
  86. diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
  87. diffusers/pipelines/stable_diffusion/__init__.py +64 -21
  88. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
  89. diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
  90. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  91. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  92. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  93. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
  94. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
  95. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
  96. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  97. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
  98. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
  107. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
  108. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
  109. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
  110. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
  111. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
  112. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
  113. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
  114. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
  115. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
  116. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
  117. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
  118. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  119. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
  120. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  121. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
  122. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  123. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
  124. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
  125. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
  126. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
  127. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
  128. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
  129. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
  130. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
  131. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  132. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  133. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  134. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  135. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
  136. diffusers/schedulers/__init__.py +2 -4
  137. diffusers/schedulers/deprecated/__init__.py +50 -0
  138. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  139. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  140. diffusers/schedulers/scheduling_ddim.py +1 -3
  141. diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
  142. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  143. diffusers/schedulers/scheduling_ddpm.py +1 -3
  144. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
  145. diffusers/schedulers/scheduling_deis_multistep.py +15 -5
  146. diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
  147. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
  148. diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
  149. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
  150. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
  151. diffusers/schedulers/scheduling_euler_discrete.py +40 -13
  152. diffusers/schedulers/scheduling_heun_discrete.py +15 -5
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
  155. diffusers/schedulers/scheduling_lcm.py +123 -29
  156. diffusers/schedulers/scheduling_lms_discrete.py +1 -3
  157. diffusers/schedulers/scheduling_pndm.py +1 -3
  158. diffusers/schedulers/scheduling_repaint.py +1 -3
  159. diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
  160. diffusers/utils/__init__.py +1 -0
  161. diffusers/utils/constants.py +8 -7
  162. diffusers/utils/dummy_pt_objects.py +45 -0
  163. diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
  164. diffusers/utils/dynamic_modules_utils.py +4 -4
  165. diffusers/utils/export_utils.py +8 -3
  166. diffusers/utils/logging.py +10 -10
  167. diffusers/utils/outputs.py +5 -5
  168. diffusers/utils/peft_utils.py +88 -44
  169. diffusers/utils/torch_utils.py +2 -2
  170. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
  171. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
  172. diffusers/loaders.py +0 -3336
  173. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
  175. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
  176. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,452 @@
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import torch
4
+ from transformers import T5EncoderModel, T5Tokenizer
5
+
6
+ from ...loaders import LoraLoaderMixin
7
+ from ...models import Kandinsky3UNet, VQModel
8
+ from ...schedulers import DDPMScheduler
9
+ from ...utils import (
10
+ is_accelerate_available,
11
+ logging,
12
+ )
13
+ from ...utils.torch_utils import randn_tensor
14
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
15
+
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ def downscale_height_and_width(height, width, scale_factor=8):
21
+ new_height = height // scale_factor**2
22
+ if height % scale_factor**2 != 0:
23
+ new_height += 1
24
+ new_width = width // scale_factor**2
25
+ if width % scale_factor**2 != 0:
26
+ new_width += 1
27
+ return new_height * scale_factor, new_width * scale_factor
28
+
29
+
30
+ class Kandinsky3Pipeline(DiffusionPipeline, LoraLoaderMixin):
31
+ model_cpu_offload_seq = "text_encoder->unet->movq"
32
+
33
+ def __init__(
34
+ self,
35
+ tokenizer: T5Tokenizer,
36
+ text_encoder: T5EncoderModel,
37
+ unet: Kandinsky3UNet,
38
+ scheduler: DDPMScheduler,
39
+ movq: VQModel,
40
+ ):
41
+ super().__init__()
42
+
43
+ self.register_modules(
44
+ tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
45
+ )
46
+
47
+ def remove_all_hooks(self):
48
+ if is_accelerate_available():
49
+ from accelerate.hooks import remove_hook_from_module
50
+ else:
51
+ raise ImportError("Please install accelerate via `pip install accelerate`")
52
+
53
+ for model in [self.text_encoder, self.unet]:
54
+ if model is not None:
55
+ remove_hook_from_module(model, recurse=True)
56
+
57
+ self.unet_offload_hook = None
58
+ self.text_encoder_offload_hook = None
59
+ self.final_offload_hook = None
60
+
61
+ def process_embeds(self, embeddings, attention_mask, cut_context):
62
+ if cut_context:
63
+ embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
64
+ max_seq_length = attention_mask.sum(-1).max() + 1
65
+ embeddings = embeddings[:, :max_seq_length]
66
+ attention_mask = attention_mask[:, :max_seq_length]
67
+ return embeddings, attention_mask
68
+
69
+ @torch.no_grad()
70
+ def encode_prompt(
71
+ self,
72
+ prompt,
73
+ do_classifier_free_guidance=True,
74
+ num_images_per_prompt=1,
75
+ device=None,
76
+ negative_prompt=None,
77
+ prompt_embeds: Optional[torch.FloatTensor] = None,
78
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
79
+ _cut_context=False,
80
+ ):
81
+ r"""
82
+ Encodes the prompt into text encoder hidden states.
83
+
84
+ Args:
85
+ prompt (`str` or `List[str]`, *optional*):
86
+ prompt to be encoded
87
+ device: (`torch.device`, *optional*):
88
+ torch device to place the resulting embeddings on
89
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
90
+ number of images that should be generated per prompt
91
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
92
+ whether to use classifier free guidance or not
93
+ negative_prompt (`str` or `List[str]`, *optional*):
94
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
95
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
96
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
97
+ prompt_embeds (`torch.FloatTensor`, *optional*):
98
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
99
+ provided, text embeddings will be generated from `prompt` input argument.
100
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
101
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
102
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
103
+ argument.
104
+ """
105
+ if prompt is not None and negative_prompt is not None:
106
+ if type(prompt) is not type(negative_prompt):
107
+ raise TypeError(
108
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
109
+ f" {type(prompt)}."
110
+ )
111
+
112
+ if device is None:
113
+ device = self._execution_device
114
+
115
+ if prompt is not None and isinstance(prompt, str):
116
+ batch_size = 1
117
+ elif prompt is not None and isinstance(prompt, list):
118
+ batch_size = len(prompt)
119
+ else:
120
+ batch_size = prompt_embeds.shape[0]
121
+
122
+ max_length = 128
123
+
124
+ if prompt_embeds is None:
125
+ text_inputs = self.tokenizer(
126
+ prompt,
127
+ padding="max_length",
128
+ max_length=max_length,
129
+ truncation=True,
130
+ return_tensors="pt",
131
+ )
132
+ text_input_ids = text_inputs.input_ids.to(device)
133
+ attention_mask = text_inputs.attention_mask.to(device)
134
+ prompt_embeds = self.text_encoder(
135
+ text_input_ids,
136
+ attention_mask=attention_mask,
137
+ )
138
+ prompt_embeds = prompt_embeds[0]
139
+ prompt_embeds, attention_mask = self.process_embeds(prompt_embeds, attention_mask, _cut_context)
140
+ prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
141
+
142
+ if self.text_encoder is not None:
143
+ dtype = self.text_encoder.dtype
144
+ else:
145
+ dtype = None
146
+
147
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
148
+
149
+ bs_embed, seq_len, _ = prompt_embeds.shape
150
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
151
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
152
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
153
+ attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
154
+ # get unconditional embeddings for classifier free guidance
155
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
156
+ uncond_tokens: List[str]
157
+
158
+ if negative_prompt is None:
159
+ uncond_tokens = [""] * batch_size
160
+ elif isinstance(negative_prompt, str):
161
+ uncond_tokens = [negative_prompt]
162
+ elif batch_size != len(negative_prompt):
163
+ raise ValueError(
164
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
165
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
166
+ " the batch size of `prompt`."
167
+ )
168
+ else:
169
+ uncond_tokens = negative_prompt
170
+ if negative_prompt is not None:
171
+ uncond_input = self.tokenizer(
172
+ uncond_tokens,
173
+ padding="max_length",
174
+ max_length=128,
175
+ truncation=True,
176
+ return_attention_mask=True,
177
+ return_tensors="pt",
178
+ )
179
+ text_input_ids = uncond_input.input_ids.to(device)
180
+ negative_attention_mask = uncond_input.attention_mask.to(device)
181
+
182
+ negative_prompt_embeds = self.text_encoder(
183
+ text_input_ids,
184
+ attention_mask=negative_attention_mask,
185
+ )
186
+ negative_prompt_embeds = negative_prompt_embeds[0]
187
+ negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
188
+ negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
189
+ negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
190
+
191
+ else:
192
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
193
+ negative_attention_mask = torch.zeros_like(attention_mask)
194
+
195
+ if do_classifier_free_guidance:
196
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
197
+ seq_len = negative_prompt_embeds.shape[1]
198
+
199
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
200
+ if negative_prompt_embeds.shape != prompt_embeds.shape:
201
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
202
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
203
+ negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
204
+
205
+ # For classifier free guidance, we need to do two forward passes.
206
+ # Here we concatenate the unconditional and text embeddings into a single batch
207
+ # to avoid doing two forward passes
208
+ else:
209
+ negative_prompt_embeds = None
210
+ negative_attention_mask = None
211
+ return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
212
+
213
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
214
+ if latents is None:
215
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
216
+ else:
217
+ if latents.shape != shape:
218
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
219
+ latents = latents.to(device)
220
+
221
+ latents = latents * scheduler.init_noise_sigma
222
+ return latents
223
+
224
+ def check_inputs(
225
+ self,
226
+ prompt,
227
+ callback_steps,
228
+ negative_prompt=None,
229
+ prompt_embeds=None,
230
+ negative_prompt_embeds=None,
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
+ if prompt is not None and prompt_embeds is not None:
241
+ raise ValueError(
242
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
243
+ " only forward one of the two."
244
+ )
245
+ elif prompt is None and prompt_embeds is None:
246
+ raise ValueError(
247
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
248
+ )
249
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
250
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
251
+
252
+ if negative_prompt is not None and negative_prompt_embeds is not None:
253
+ raise ValueError(
254
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
255
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
256
+ )
257
+
258
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
259
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
260
+ raise ValueError(
261
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
262
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
263
+ f" {negative_prompt_embeds.shape}."
264
+ )
265
+
266
+ @torch.no_grad()
267
+ def __call__(
268
+ self,
269
+ prompt: Union[str, List[str]] = None,
270
+ num_inference_steps: int = 25,
271
+ guidance_scale: float = 3.0,
272
+ negative_prompt: Optional[Union[str, List[str]]] = None,
273
+ num_images_per_prompt: Optional[int] = 1,
274
+ height: Optional[int] = 1024,
275
+ width: Optional[int] = 1024,
276
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
277
+ prompt_embeds: Optional[torch.FloatTensor] = None,
278
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
279
+ output_type: Optional[str] = "pil",
280
+ return_dict: bool = True,
281
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
282
+ callback_steps: int = 1,
283
+ latents=None,
284
+ ):
285
+ """
286
+ Function invoked when calling the pipeline for generation.
287
+
288
+ Args:
289
+ prompt (`str` or `List[str]`, *optional*):
290
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
291
+ instead.
292
+ num_inference_steps (`int`, *optional*, defaults to 50):
293
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
294
+ expense of slower inference.
295
+ timesteps (`List[int]`, *optional*):
296
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
297
+ timesteps are used. Must be in descending order.
298
+ guidance_scale (`float`, *optional*, defaults to 3.0):
299
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
300
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
301
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
302
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
303
+ usually at the expense of lower image quality.
304
+ negative_prompt (`str` or `List[str]`, *optional*):
305
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
306
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
307
+ less than `1`).
308
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
309
+ The number of images to generate per prompt.
310
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
311
+ The height in pixels of the generated image.
312
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
313
+ The width in pixels of the generated image.
314
+ eta (`float`, *optional*, defaults to 0.0):
315
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
316
+ [`schedulers.DDIMScheduler`], will be ignored for others.
317
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
318
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
319
+ to make generation deterministic.
320
+ prompt_embeds (`torch.FloatTensor`, *optional*):
321
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
322
+ provided, text embeddings will be generated from `prompt` input argument.
323
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
324
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
325
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
326
+ argument.
327
+ output_type (`str`, *optional*, defaults to `"pil"`):
328
+ The output format of the generate image. Choose between
329
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
330
+ return_dict (`bool`, *optional*, defaults to `True`):
331
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
332
+ callback (`Callable`, *optional*):
333
+ A function that will be called every `callback_steps` steps during inference. The function will be
334
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
335
+ callback_steps (`int`, *optional*, defaults to 1):
336
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
337
+ called at every step.
338
+ clean_caption (`bool`, *optional*, defaults to `True`):
339
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
340
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
341
+ prompt.
342
+ cross_attention_kwargs (`dict`, *optional*):
343
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
344
+ `self.processor` in
345
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
346
+ """
347
+ cut_context = True
348
+ device = self._execution_device
349
+
350
+ # 1. Check inputs. Raise error if not correct
351
+ self.check_inputs(prompt, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds)
352
+
353
+ if prompt is not None and isinstance(prompt, str):
354
+ batch_size = 1
355
+ elif prompt is not None and isinstance(prompt, list):
356
+ batch_size = len(prompt)
357
+ else:
358
+ batch_size = prompt_embeds.shape[0]
359
+
360
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
361
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
362
+ # corresponds to doing no classifier free guidance.
363
+ do_classifier_free_guidance = guidance_scale > 1.0
364
+
365
+ # 3. Encode input prompt
366
+ prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
367
+ prompt,
368
+ do_classifier_free_guidance,
369
+ num_images_per_prompt=num_images_per_prompt,
370
+ device=device,
371
+ negative_prompt=negative_prompt,
372
+ prompt_embeds=prompt_embeds,
373
+ negative_prompt_embeds=negative_prompt_embeds,
374
+ _cut_context=cut_context,
375
+ )
376
+
377
+ if do_classifier_free_guidance:
378
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
379
+ attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
380
+ # 4. Prepare timesteps
381
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
382
+ timesteps = self.scheduler.timesteps
383
+
384
+ # 5. Prepare latents
385
+ height, width = downscale_height_and_width(height, width, 8)
386
+
387
+ latents = self.prepare_latents(
388
+ (batch_size * num_images_per_prompt, 4, height, width),
389
+ prompt_embeds.dtype,
390
+ device,
391
+ generator,
392
+ latents,
393
+ self.scheduler,
394
+ )
395
+
396
+ if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
397
+ self.text_encoder_offload_hook.offload()
398
+
399
+ # 7. Denoising loop
400
+ # TODO(Yiyi): Correct the following line and use correctly
401
+ # num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
402
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
403
+ for i, t in enumerate(timesteps):
404
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
405
+
406
+ # predict the noise residual
407
+ noise_pred = self.unet(
408
+ latent_model_input,
409
+ t,
410
+ encoder_hidden_states=prompt_embeds,
411
+ encoder_attention_mask=attention_mask,
412
+ return_dict=False,
413
+ )[0]
414
+
415
+ if do_classifier_free_guidance:
416
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
417
+
418
+ noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
419
+ # noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
420
+
421
+ # compute the previous noisy sample x_t -> x_t-1
422
+ latents = self.scheduler.step(
423
+ noise_pred,
424
+ t,
425
+ latents,
426
+ generator=generator,
427
+ ).prev_sample
428
+ progress_bar.update()
429
+ if callback is not None and i % callback_steps == 0:
430
+ step_idx = i // getattr(self.scheduler, "order", 1)
431
+ callback(step_idx, t, latents)
432
+
433
+ # post-processing
434
+ image = self.movq.decode(latents, force_not_quantize=True)["sample"]
435
+
436
+ if output_type not in ["pt", "np", "pil"]:
437
+ raise ValueError(
438
+ f"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"
439
+ )
440
+
441
+ if output_type in ["np", "pil"]:
442
+ image = image * 0.5 + 0.5
443
+ image = image.clamp(0, 1)
444
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
445
+
446
+ if output_type == "pil":
447
+ image = self.numpy_to_pil(image)
448
+
449
+ if not return_dict:
450
+ return (image,)
451
+
452
+ return ImagePipelineOutput(images=image)