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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (238) hide show
  1. diffusers/__init__.py +26 -2
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +13 -8
  4. diffusers/dependency_versions_check.py +0 -1
  5. diffusers/dependency_versions_table.py +5 -5
  6. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  7. diffusers/image_processor.py +463 -51
  8. diffusers/loaders/__init__.py +82 -0
  9. diffusers/loaders/ip_adapter.py +159 -0
  10. diffusers/loaders/lora.py +1553 -0
  11. diffusers/loaders/lora_conversion_utils.py +284 -0
  12. diffusers/loaders/single_file.py +637 -0
  13. diffusers/loaders/textual_inversion.py +455 -0
  14. diffusers/loaders/unet.py +828 -0
  15. diffusers/loaders/utils.py +59 -0
  16. diffusers/models/__init__.py +26 -9
  17. diffusers/models/activations.py +9 -6
  18. diffusers/models/attention.py +301 -29
  19. diffusers/models/attention_flax.py +9 -1
  20. diffusers/models/attention_processor.py +378 -6
  21. diffusers/models/autoencoders/__init__.py +5 -0
  22. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
  23. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
  24. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
  25. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
  26. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
  27. diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
  28. diffusers/models/controlnet.py +59 -39
  29. diffusers/models/controlnet_flax.py +19 -18
  30. diffusers/models/downsampling.py +338 -0
  31. diffusers/models/embeddings.py +112 -29
  32. diffusers/models/embeddings_flax.py +2 -0
  33. diffusers/models/lora.py +131 -1
  34. diffusers/models/modeling_flax_utils.py +14 -8
  35. diffusers/models/modeling_outputs.py +17 -0
  36. diffusers/models/modeling_utils.py +37 -29
  37. diffusers/models/normalization.py +110 -4
  38. diffusers/models/resnet.py +299 -652
  39. diffusers/models/transformer_2d.py +22 -5
  40. diffusers/models/transformer_temporal.py +183 -1
  41. diffusers/models/unet_2d_blocks_flax.py +5 -0
  42. diffusers/models/unet_2d_condition.py +46 -0
  43. diffusers/models/unet_2d_condition_flax.py +13 -13
  44. diffusers/models/unet_3d_blocks.py +957 -173
  45. diffusers/models/unet_3d_condition.py +16 -8
  46. diffusers/models/unet_kandinsky3.py +535 -0
  47. diffusers/models/unet_motion_model.py +48 -33
  48. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  49. diffusers/models/upsampling.py +454 -0
  50. diffusers/models/uvit_2d.py +471 -0
  51. diffusers/models/vae_flax.py +7 -0
  52. diffusers/models/vq_model.py +12 -3
  53. diffusers/optimization.py +16 -9
  54. diffusers/pipelines/__init__.py +137 -76
  55. diffusers/pipelines/amused/__init__.py +62 -0
  56. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  57. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  58. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  59. diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
  60. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  61. diffusers/pipelines/auto_pipeline.py +23 -13
  62. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  63. diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
  64. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
  65. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
  66. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
  67. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
  68. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
  69. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  70. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  71. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  72. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  73. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  74. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  75. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  76. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  77. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  78. diffusers/pipelines/deprecated/__init__.py +153 -0
  79. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  80. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
  81. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
  82. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  83. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  84. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  85. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  86. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  87. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  88. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  89. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  90. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  91. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  92. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  93. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
  94. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  95. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  96. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  97. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  98. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  100. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
  101. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
  102. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
  103. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
  104. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
  105. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
  106. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  107. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  108. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  109. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
  110. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  111. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
  112. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
  113. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
  114. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  115. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  116. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  117. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  118. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  119. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  120. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  122. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  123. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  124. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
  125. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
  126. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
  127. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
  128. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  129. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  130. diffusers/pipelines/onnx_utils.py +8 -5
  131. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  132. diffusers/pipelines/pipeline_flax_utils.py +11 -8
  133. diffusers/pipelines/pipeline_utils.py +63 -42
  134. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
  135. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  136. diffusers/pipelines/stable_diffusion/__init__.py +37 -65
  137. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
  138. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  139. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  140. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  141. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
  142. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  143. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  144. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
  145. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
  146. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
  147. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  151. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  152. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
  153. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  154. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
  155. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  156. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
  157. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  158. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  159. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
  160. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  161. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
  162. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  163. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
  164. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  165. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  166. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
  171. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  172. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
  175. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
  179. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
  180. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  181. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  182. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  183. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  184. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  185. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  186. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  187. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
  188. diffusers/schedulers/__init__.py +4 -4
  189. diffusers/schedulers/deprecated/__init__.py +50 -0
  190. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  191. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  192. diffusers/schedulers/scheduling_amused.py +162 -0
  193. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  194. diffusers/schedulers/scheduling_ddim.py +1 -3
  195. diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
  196. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  197. diffusers/schedulers/scheduling_ddpm.py +47 -3
  198. diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
  199. diffusers/schedulers/scheduling_deis_multistep.py +28 -6
  200. diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
  201. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
  202. diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
  203. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
  204. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
  205. diffusers/schedulers/scheduling_euler_discrete.py +102 -16
  206. diffusers/schedulers/scheduling_heun_discrete.py +17 -5
  207. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
  208. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
  209. diffusers/schedulers/scheduling_lcm.py +123 -29
  210. diffusers/schedulers/scheduling_lms_discrete.py +3 -3
  211. diffusers/schedulers/scheduling_pndm.py +1 -3
  212. diffusers/schedulers/scheduling_repaint.py +1 -3
  213. diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
  214. diffusers/schedulers/scheduling_utils.py +3 -1
  215. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  216. diffusers/training_utils.py +1 -1
  217. diffusers/utils/__init__.py +1 -2
  218. diffusers/utils/constants.py +10 -12
  219. diffusers/utils/dummy_pt_objects.py +75 -0
  220. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  221. diffusers/utils/dynamic_modules_utils.py +18 -22
  222. diffusers/utils/export_utils.py +8 -3
  223. diffusers/utils/hub_utils.py +24 -36
  224. diffusers/utils/logging.py +11 -11
  225. diffusers/utils/outputs.py +5 -5
  226. diffusers/utils/peft_utils.py +88 -44
  227. diffusers/utils/state_dict_utils.py +8 -0
  228. diffusers/utils/testing_utils.py +199 -1
  229. diffusers/utils/torch_utils.py +4 -4
  230. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
  231. diffusers-0.25.0.dist-info/RECORD +360 -0
  232. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  233. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  234. diffusers/loaders.py +0 -3336
  235. diffusers-0.23.1.dist-info/RECORD +0 -323
  236. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  237. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  238. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,589 @@
1
+ from typing import Callable, Dict, 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
+ deprecate,
11
+ is_accelerate_available,
12
+ logging,
13
+ replace_example_docstring,
14
+ )
15
+ from ...utils.torch_utils import randn_tensor
16
+ from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
17
+
18
+
19
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
20
+
21
+ EXAMPLE_DOC_STRING = """
22
+ Examples:
23
+ ```py
24
+ >>> from diffusers import AutoPipelineForText2Image
25
+ >>> import torch
26
+
27
+ >>> pipe = AutoPipelineForText2Image.from_pretrained("kandinsky-community/kandinsky-3", variant="fp16", torch_dtype=torch.float16)
28
+ >>> pipe.enable_model_cpu_offload()
29
+
30
+ >>> prompt = "A photograph of the inside of a subway train. There are raccoons sitting on the seats. One of them is reading a newspaper. The window shows the city in the background."
31
+
32
+ >>> generator = torch.Generator(device="cpu").manual_seed(0)
33
+ >>> image = pipe(prompt, num_inference_steps=25, generator=generator).images[0]
34
+ ```
35
+
36
+ """
37
+
38
+
39
+ def downscale_height_and_width(height, width, scale_factor=8):
40
+ new_height = height // scale_factor**2
41
+ if height % scale_factor**2 != 0:
42
+ new_height += 1
43
+ new_width = width // scale_factor**2
44
+ if width % scale_factor**2 != 0:
45
+ new_width += 1
46
+ return new_height * scale_factor, new_width * scale_factor
47
+
48
+
49
+ class Kandinsky3Pipeline(DiffusionPipeline, LoraLoaderMixin):
50
+ model_cpu_offload_seq = "text_encoder->unet->movq"
51
+ _callback_tensor_inputs = [
52
+ "latents",
53
+ "prompt_embeds",
54
+ "negative_prompt_embeds",
55
+ "negative_attention_mask",
56
+ "attention_mask",
57
+ ]
58
+
59
+ def __init__(
60
+ self,
61
+ tokenizer: T5Tokenizer,
62
+ text_encoder: T5EncoderModel,
63
+ unet: Kandinsky3UNet,
64
+ scheduler: DDPMScheduler,
65
+ movq: VQModel,
66
+ ):
67
+ super().__init__()
68
+
69
+ self.register_modules(
70
+ tokenizer=tokenizer, text_encoder=text_encoder, unet=unet, scheduler=scheduler, movq=movq
71
+ )
72
+
73
+ def remove_all_hooks(self):
74
+ if is_accelerate_available():
75
+ from accelerate.hooks import remove_hook_from_module
76
+ else:
77
+ raise ImportError("Please install accelerate via `pip install accelerate`")
78
+
79
+ for model in [self.text_encoder, self.unet, self.movq]:
80
+ if model is not None:
81
+ remove_hook_from_module(model, recurse=True)
82
+
83
+ self.unet_offload_hook = None
84
+ self.text_encoder_offload_hook = None
85
+ self.final_offload_hook = None
86
+
87
+ def process_embeds(self, embeddings, attention_mask, cut_context):
88
+ if cut_context:
89
+ embeddings[attention_mask == 0] = torch.zeros_like(embeddings[attention_mask == 0])
90
+ max_seq_length = attention_mask.sum(-1).max() + 1
91
+ embeddings = embeddings[:, :max_seq_length]
92
+ attention_mask = attention_mask[:, :max_seq_length]
93
+ return embeddings, attention_mask
94
+
95
+ @torch.no_grad()
96
+ def encode_prompt(
97
+ self,
98
+ prompt,
99
+ do_classifier_free_guidance=True,
100
+ num_images_per_prompt=1,
101
+ device=None,
102
+ negative_prompt=None,
103
+ prompt_embeds: Optional[torch.FloatTensor] = None,
104
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
105
+ _cut_context=False,
106
+ attention_mask: Optional[torch.FloatTensor] = None,
107
+ negative_attention_mask: Optional[torch.FloatTensor] = None,
108
+ ):
109
+ r"""
110
+ Encodes the prompt into text encoder hidden states.
111
+
112
+ Args:
113
+ prompt (`str` or `List[str]`, *optional*):
114
+ prompt to be encoded
115
+ device: (`torch.device`, *optional*):
116
+ torch device to place the resulting embeddings on
117
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
118
+ number of images that should be generated per prompt
119
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
120
+ whether to use classifier free guidance or not
121
+ negative_prompt (`str` or `List[str]`, *optional*):
122
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
123
+ `negative_prompt_embeds`. instead. If not defined, one has to pass `negative_prompt_embeds`. instead.
124
+ Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`).
125
+ prompt_embeds (`torch.FloatTensor`, *optional*):
126
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
127
+ provided, text embeddings will be generated from `prompt` input argument.
128
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
129
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
130
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
131
+ argument.
132
+ attention_mask (`torch.FloatTensor`, *optional*):
133
+ Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
134
+ negative_attention_mask (`torch.FloatTensor`, *optional*):
135
+ Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
136
+ """
137
+ if prompt is not None and negative_prompt is not None:
138
+ if type(prompt) is not type(negative_prompt):
139
+ raise TypeError(
140
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
141
+ f" {type(prompt)}."
142
+ )
143
+
144
+ if device is None:
145
+ device = self._execution_device
146
+
147
+ if prompt is not None and isinstance(prompt, str):
148
+ batch_size = 1
149
+ elif prompt is not None and isinstance(prompt, list):
150
+ batch_size = len(prompt)
151
+ else:
152
+ batch_size = prompt_embeds.shape[0]
153
+
154
+ max_length = 128
155
+
156
+ if prompt_embeds is None:
157
+ text_inputs = self.tokenizer(
158
+ prompt,
159
+ padding="max_length",
160
+ max_length=max_length,
161
+ truncation=True,
162
+ return_tensors="pt",
163
+ )
164
+ text_input_ids = text_inputs.input_ids.to(device)
165
+ attention_mask = text_inputs.attention_mask.to(device)
166
+ prompt_embeds = self.text_encoder(
167
+ text_input_ids,
168
+ attention_mask=attention_mask,
169
+ )
170
+ prompt_embeds = prompt_embeds[0]
171
+ prompt_embeds, attention_mask = self.process_embeds(prompt_embeds, attention_mask, _cut_context)
172
+ prompt_embeds = prompt_embeds * attention_mask.unsqueeze(2)
173
+
174
+ if self.text_encoder is not None:
175
+ dtype = self.text_encoder.dtype
176
+ else:
177
+ dtype = None
178
+
179
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
180
+
181
+ bs_embed, seq_len, _ = prompt_embeds.shape
182
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
183
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
184
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
185
+ attention_mask = attention_mask.repeat(num_images_per_prompt, 1)
186
+ # get unconditional embeddings for classifier free guidance
187
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
188
+ uncond_tokens: List[str]
189
+
190
+ if negative_prompt is None:
191
+ uncond_tokens = [""] * batch_size
192
+ elif isinstance(negative_prompt, str):
193
+ uncond_tokens = [negative_prompt]
194
+ elif batch_size != len(negative_prompt):
195
+ raise ValueError(
196
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
197
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
198
+ " the batch size of `prompt`."
199
+ )
200
+ else:
201
+ uncond_tokens = negative_prompt
202
+ if negative_prompt is not None:
203
+ uncond_input = self.tokenizer(
204
+ uncond_tokens,
205
+ padding="max_length",
206
+ max_length=128,
207
+ truncation=True,
208
+ return_attention_mask=True,
209
+ return_tensors="pt",
210
+ )
211
+ text_input_ids = uncond_input.input_ids.to(device)
212
+ negative_attention_mask = uncond_input.attention_mask.to(device)
213
+
214
+ negative_prompt_embeds = self.text_encoder(
215
+ text_input_ids,
216
+ attention_mask=negative_attention_mask,
217
+ )
218
+ negative_prompt_embeds = negative_prompt_embeds[0]
219
+ negative_prompt_embeds = negative_prompt_embeds[:, : prompt_embeds.shape[1]]
220
+ negative_attention_mask = negative_attention_mask[:, : prompt_embeds.shape[1]]
221
+ negative_prompt_embeds = negative_prompt_embeds * negative_attention_mask.unsqueeze(2)
222
+
223
+ else:
224
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
225
+ negative_attention_mask = torch.zeros_like(attention_mask)
226
+
227
+ if do_classifier_free_guidance:
228
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
229
+ seq_len = negative_prompt_embeds.shape[1]
230
+
231
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=dtype, device=device)
232
+ if negative_prompt_embeds.shape != prompt_embeds.shape:
233
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
234
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
235
+ negative_attention_mask = negative_attention_mask.repeat(num_images_per_prompt, 1)
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
+ else:
241
+ negative_prompt_embeds = None
242
+ negative_attention_mask = None
243
+ return prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask
244
+
245
+ def prepare_latents(self, shape, dtype, device, generator, latents, scheduler):
246
+ if latents is None:
247
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
248
+ else:
249
+ if latents.shape != shape:
250
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
251
+ latents = latents.to(device)
252
+
253
+ latents = latents * scheduler.init_noise_sigma
254
+ return latents
255
+
256
+ def check_inputs(
257
+ self,
258
+ prompt,
259
+ callback_steps,
260
+ negative_prompt=None,
261
+ prompt_embeds=None,
262
+ negative_prompt_embeds=None,
263
+ callback_on_step_end_tensor_inputs=None,
264
+ attention_mask=None,
265
+ negative_attention_mask=None,
266
+ ):
267
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
268
+ raise ValueError(
269
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
270
+ f" {type(callback_steps)}."
271
+ )
272
+ if callback_on_step_end_tensor_inputs is not None and not all(
273
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
274
+ ):
275
+ raise ValueError(
276
+ 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]}"
277
+ )
278
+
279
+ if prompt is not None and prompt_embeds is not None:
280
+ raise ValueError(
281
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
282
+ " only forward one of the two."
283
+ )
284
+ elif prompt is None and prompt_embeds is None:
285
+ raise ValueError(
286
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
287
+ )
288
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
289
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
290
+
291
+ if negative_prompt is not None and negative_prompt_embeds is not None:
292
+ raise ValueError(
293
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
294
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
295
+ )
296
+
297
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
298
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
299
+ raise ValueError(
300
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
301
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
302
+ f" {negative_prompt_embeds.shape}."
303
+ )
304
+ if negative_prompt_embeds is not None and negative_attention_mask is None:
305
+ raise ValueError("Please provide `negative_attention_mask` along with `negative_prompt_embeds`")
306
+
307
+ if negative_prompt_embeds is not None and negative_attention_mask is not None:
308
+ if negative_prompt_embeds.shape[:2] != negative_attention_mask.shape:
309
+ raise ValueError(
310
+ "`negative_prompt_embeds` and `negative_attention_mask` must have the same batch_size and token length when passed directly, but"
311
+ f" got: `negative_prompt_embeds` {negative_prompt_embeds.shape[:2]} != `negative_attention_mask`"
312
+ f" {negative_attention_mask.shape}."
313
+ )
314
+
315
+ if prompt_embeds is not None and attention_mask is None:
316
+ raise ValueError("Please provide `attention_mask` along with `prompt_embeds`")
317
+
318
+ if prompt_embeds is not None and attention_mask is not None:
319
+ if prompt_embeds.shape[:2] != attention_mask.shape:
320
+ raise ValueError(
321
+ "`prompt_embeds` and `attention_mask` must have the same batch_size and token length when passed directly, but"
322
+ f" got: `prompt_embeds` {prompt_embeds.shape[:2]} != `attention_mask`"
323
+ f" {attention_mask.shape}."
324
+ )
325
+
326
+ @property
327
+ def guidance_scale(self):
328
+ return self._guidance_scale
329
+
330
+ @property
331
+ def do_classifier_free_guidance(self):
332
+ return self._guidance_scale > 1
333
+
334
+ @property
335
+ def num_timesteps(self):
336
+ return self._num_timesteps
337
+
338
+ @torch.no_grad()
339
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
340
+ def __call__(
341
+ self,
342
+ prompt: Union[str, List[str]] = None,
343
+ num_inference_steps: int = 25,
344
+ guidance_scale: float = 3.0,
345
+ negative_prompt: Optional[Union[str, List[str]]] = None,
346
+ num_images_per_prompt: Optional[int] = 1,
347
+ height: Optional[int] = 1024,
348
+ width: Optional[int] = 1024,
349
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
350
+ prompt_embeds: Optional[torch.FloatTensor] = None,
351
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
352
+ attention_mask: Optional[torch.FloatTensor] = None,
353
+ negative_attention_mask: Optional[torch.FloatTensor] = None,
354
+ output_type: Optional[str] = "pil",
355
+ return_dict: bool = True,
356
+ latents=None,
357
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
358
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
359
+ **kwargs,
360
+ ):
361
+ """
362
+ Function invoked when calling the pipeline for generation.
363
+
364
+ Args:
365
+ prompt (`str` or `List[str]`, *optional*):
366
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
367
+ instead.
368
+ num_inference_steps (`int`, *optional*, defaults to 25):
369
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
370
+ expense of slower inference.
371
+ timesteps (`List[int]`, *optional*):
372
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
373
+ timesteps are used. Must be in descending order.
374
+ guidance_scale (`float`, *optional*, defaults to 3.0):
375
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
376
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
377
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
378
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
379
+ usually at the expense of lower image quality.
380
+ negative_prompt (`str` or `List[str]`, *optional*):
381
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
382
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
383
+ less than `1`).
384
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
385
+ The number of images to generate per prompt.
386
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
387
+ The height in pixels of the generated image.
388
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
389
+ The width in pixels of the generated image.
390
+ eta (`float`, *optional*, defaults to 0.0):
391
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
392
+ [`schedulers.DDIMScheduler`], will be ignored for others.
393
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
394
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
395
+ to make generation deterministic.
396
+ prompt_embeds (`torch.FloatTensor`, *optional*):
397
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
398
+ provided, text embeddings will be generated from `prompt` input argument.
399
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
400
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
401
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
402
+ argument.
403
+ attention_mask (`torch.FloatTensor`, *optional*):
404
+ Pre-generated attention mask. Must provide if passing `prompt_embeds` directly.
405
+ negative_attention_mask (`torch.FloatTensor`, *optional*):
406
+ Pre-generated negative attention mask. Must provide if passing `negative_prompt_embeds` directly.
407
+ output_type (`str`, *optional*, defaults to `"pil"`):
408
+ The output format of the generate image. Choose between
409
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
410
+ return_dict (`bool`, *optional*, defaults to `True`):
411
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
412
+ callback (`Callable`, *optional*):
413
+ A function that will be called every `callback_steps` steps during inference. The function will be
414
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
415
+ callback_steps (`int`, *optional*, defaults to 1):
416
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
417
+ called at every step.
418
+ clean_caption (`bool`, *optional*, defaults to `True`):
419
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
420
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
421
+ prompt.
422
+ cross_attention_kwargs (`dict`, *optional*):
423
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
424
+ `self.processor` in
425
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
426
+
427
+ Examples:
428
+
429
+ Returns:
430
+ [`~pipelines.ImagePipelineOutput`] or `tuple`
431
+
432
+ """
433
+
434
+ callback = kwargs.pop("callback", None)
435
+ callback_steps = kwargs.pop("callback_steps", None)
436
+
437
+ if callback is not None:
438
+ deprecate(
439
+ "callback",
440
+ "1.0.0",
441
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
442
+ )
443
+ if callback_steps is not None:
444
+ deprecate(
445
+ "callback_steps",
446
+ "1.0.0",
447
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
448
+ )
449
+
450
+ if callback_on_step_end_tensor_inputs is not None and not all(
451
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
452
+ ):
453
+ raise ValueError(
454
+ 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]}"
455
+ )
456
+
457
+ cut_context = True
458
+ device = self._execution_device
459
+
460
+ # 1. Check inputs. Raise error if not correct
461
+ self.check_inputs(
462
+ prompt,
463
+ callback_steps,
464
+ negative_prompt,
465
+ prompt_embeds,
466
+ negative_prompt_embeds,
467
+ callback_on_step_end_tensor_inputs,
468
+ attention_mask,
469
+ negative_attention_mask,
470
+ )
471
+
472
+ self._guidance_scale = guidance_scale
473
+
474
+ if prompt is not None and isinstance(prompt, str):
475
+ batch_size = 1
476
+ elif prompt is not None and isinstance(prompt, list):
477
+ batch_size = len(prompt)
478
+ else:
479
+ batch_size = prompt_embeds.shape[0]
480
+
481
+ # 3. Encode input prompt
482
+ prompt_embeds, negative_prompt_embeds, attention_mask, negative_attention_mask = self.encode_prompt(
483
+ prompt,
484
+ self.do_classifier_free_guidance,
485
+ num_images_per_prompt=num_images_per_prompt,
486
+ device=device,
487
+ negative_prompt=negative_prompt,
488
+ prompt_embeds=prompt_embeds,
489
+ negative_prompt_embeds=negative_prompt_embeds,
490
+ _cut_context=cut_context,
491
+ attention_mask=attention_mask,
492
+ negative_attention_mask=negative_attention_mask,
493
+ )
494
+
495
+ if self.do_classifier_free_guidance:
496
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
497
+ attention_mask = torch.cat([negative_attention_mask, attention_mask]).bool()
498
+ # 4. Prepare timesteps
499
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
500
+ timesteps = self.scheduler.timesteps
501
+
502
+ # 5. Prepare latents
503
+ height, width = downscale_height_and_width(height, width, 8)
504
+
505
+ latents = self.prepare_latents(
506
+ (batch_size * num_images_per_prompt, 4, height, width),
507
+ prompt_embeds.dtype,
508
+ device,
509
+ generator,
510
+ latents,
511
+ self.scheduler,
512
+ )
513
+
514
+ if hasattr(self, "text_encoder_offload_hook") and self.text_encoder_offload_hook is not None:
515
+ self.text_encoder_offload_hook.offload()
516
+
517
+ # 7. Denoising loop
518
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
519
+ self._num_timesteps = len(timesteps)
520
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
521
+ for i, t in enumerate(timesteps):
522
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
523
+
524
+ # predict the noise residual
525
+ noise_pred = self.unet(
526
+ latent_model_input,
527
+ t,
528
+ encoder_hidden_states=prompt_embeds,
529
+ encoder_attention_mask=attention_mask,
530
+ return_dict=False,
531
+ )[0]
532
+
533
+ if self.do_classifier_free_guidance:
534
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
535
+
536
+ noise_pred = (guidance_scale + 1.0) * noise_pred_text - guidance_scale * noise_pred_uncond
537
+ # noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
538
+
539
+ # compute the previous noisy sample x_t -> x_t-1
540
+ latents = self.scheduler.step(
541
+ noise_pred,
542
+ t,
543
+ latents,
544
+ generator=generator,
545
+ ).prev_sample
546
+
547
+ if callback_on_step_end is not None:
548
+ callback_kwargs = {}
549
+ for k in callback_on_step_end_tensor_inputs:
550
+ callback_kwargs[k] = locals()[k]
551
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
552
+
553
+ latents = callback_outputs.pop("latents", latents)
554
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
555
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
556
+ attention_mask = callback_outputs.pop("attention_mask", attention_mask)
557
+ negative_attention_mask = callback_outputs.pop("negative_attention_mask", negative_attention_mask)
558
+
559
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
560
+ progress_bar.update()
561
+ if callback is not None and i % callback_steps == 0:
562
+ step_idx = i // getattr(self.scheduler, "order", 1)
563
+ callback(step_idx, t, latents)
564
+
565
+ # post-processing
566
+ if output_type not in ["pt", "np", "pil", "latent"]:
567
+ raise ValueError(
568
+ f"Only the output types `pt`, `pil`, `np` and `latent` are supported not output_type={output_type}"
569
+ )
570
+
571
+ if not output_type == "latent":
572
+ image = self.movq.decode(latents, force_not_quantize=True)["sample"]
573
+
574
+ if output_type in ["np", "pil"]:
575
+ image = image * 0.5 + 0.5
576
+ image = image.clamp(0, 1)
577
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
578
+
579
+ if output_type == "pil":
580
+ image = self.numpy_to_pil(image)
581
+ else:
582
+ image = latents
583
+
584
+ self.maybe_free_model_hooks()
585
+
586
+ if not return_dict:
587
+ return (image,)
588
+
589
+ return ImagePipelineOutput(images=image)