diffusers 0.27.2__py3-none-any.whl → 0.28.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. diffusers/__init__.py +26 -1
  2. diffusers/callbacks.py +156 -0
  3. diffusers/commands/env.py +110 -6
  4. diffusers/configuration_utils.py +33 -11
  5. diffusers/dependency_versions_table.py +2 -1
  6. diffusers/image_processor.py +158 -45
  7. diffusers/loaders/__init__.py +2 -5
  8. diffusers/loaders/autoencoder.py +4 -4
  9. diffusers/loaders/controlnet.py +4 -4
  10. diffusers/loaders/ip_adapter.py +80 -22
  11. diffusers/loaders/lora.py +134 -20
  12. diffusers/loaders/lora_conversion_utils.py +46 -43
  13. diffusers/loaders/peft.py +4 -3
  14. diffusers/loaders/single_file.py +401 -170
  15. diffusers/loaders/single_file_model.py +290 -0
  16. diffusers/loaders/single_file_utils.py +616 -672
  17. diffusers/loaders/textual_inversion.py +41 -20
  18. diffusers/loaders/unet.py +168 -115
  19. diffusers/loaders/unet_loader_utils.py +163 -0
  20. diffusers/models/__init__.py +8 -0
  21. diffusers/models/activations.py +23 -3
  22. diffusers/models/attention.py +10 -11
  23. diffusers/models/attention_processor.py +475 -148
  24. diffusers/models/autoencoders/autoencoder_asym_kl.py +14 -16
  25. diffusers/models/autoencoders/autoencoder_kl.py +18 -19
  26. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +11 -11
  27. diffusers/models/autoencoders/autoencoder_tiny.py +16 -16
  28. diffusers/models/autoencoders/consistency_decoder_vae.py +36 -11
  29. diffusers/models/autoencoders/vae.py +23 -24
  30. diffusers/models/controlnet.py +12 -9
  31. diffusers/models/controlnet_flax.py +4 -4
  32. diffusers/models/controlnet_xs.py +1915 -0
  33. diffusers/models/downsampling.py +17 -18
  34. diffusers/models/embeddings.py +363 -32
  35. diffusers/models/model_loading_utils.py +177 -0
  36. diffusers/models/modeling_flax_pytorch_utils.py +2 -1
  37. diffusers/models/modeling_flax_utils.py +4 -4
  38. diffusers/models/modeling_outputs.py +14 -0
  39. diffusers/models/modeling_pytorch_flax_utils.py +1 -1
  40. diffusers/models/modeling_utils.py +175 -99
  41. diffusers/models/normalization.py +2 -1
  42. diffusers/models/resnet.py +18 -23
  43. diffusers/models/transformer_temporal.py +3 -3
  44. diffusers/models/transformers/__init__.py +3 -0
  45. diffusers/models/transformers/dit_transformer_2d.py +240 -0
  46. diffusers/models/transformers/dual_transformer_2d.py +4 -4
  47. diffusers/models/transformers/hunyuan_transformer_2d.py +427 -0
  48. diffusers/models/transformers/pixart_transformer_2d.py +336 -0
  49. diffusers/models/transformers/prior_transformer.py +7 -7
  50. diffusers/models/transformers/t5_film_transformer.py +17 -19
  51. diffusers/models/transformers/transformer_2d.py +292 -184
  52. diffusers/models/transformers/transformer_temporal.py +10 -10
  53. diffusers/models/unets/unet_1d.py +5 -5
  54. diffusers/models/unets/unet_1d_blocks.py +29 -29
  55. diffusers/models/unets/unet_2d.py +6 -6
  56. diffusers/models/unets/unet_2d_blocks.py +137 -128
  57. diffusers/models/unets/unet_2d_condition.py +19 -15
  58. diffusers/models/unets/unet_2d_condition_flax.py +6 -5
  59. diffusers/models/unets/unet_3d_blocks.py +79 -77
  60. diffusers/models/unets/unet_3d_condition.py +13 -9
  61. diffusers/models/unets/unet_i2vgen_xl.py +14 -13
  62. diffusers/models/unets/unet_kandinsky3.py +1 -1
  63. diffusers/models/unets/unet_motion_model.py +114 -14
  64. diffusers/models/unets/unet_spatio_temporal_condition.py +15 -14
  65. diffusers/models/unets/unet_stable_cascade.py +16 -13
  66. diffusers/models/upsampling.py +17 -20
  67. diffusers/models/vq_model.py +16 -15
  68. diffusers/pipelines/__init__.py +27 -3
  69. diffusers/pipelines/amused/pipeline_amused.py +12 -12
  70. diffusers/pipelines/amused/pipeline_amused_img2img.py +14 -12
  71. diffusers/pipelines/amused/pipeline_amused_inpaint.py +13 -11
  72. diffusers/pipelines/animatediff/__init__.py +2 -0
  73. diffusers/pipelines/animatediff/pipeline_animatediff.py +24 -46
  74. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +1284 -0
  75. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +82 -72
  76. diffusers/pipelines/animatediff/pipeline_output.py +3 -2
  77. diffusers/pipelines/audioldm/pipeline_audioldm.py +14 -14
  78. diffusers/pipelines/audioldm2/modeling_audioldm2.py +54 -35
  79. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +120 -36
  80. diffusers/pipelines/auto_pipeline.py +21 -17
  81. diffusers/pipelines/blip_diffusion/blip_image_processing.py +1 -1
  82. diffusers/pipelines/blip_diffusion/modeling_blip2.py +5 -5
  83. diffusers/pipelines/blip_diffusion/modeling_ctx_clip.py +1 -1
  84. diffusers/pipelines/blip_diffusion/pipeline_blip_diffusion.py +2 -2
  85. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +5 -5
  86. diffusers/pipelines/controlnet/multicontrolnet.py +4 -8
  87. diffusers/pipelines/controlnet/pipeline_controlnet.py +87 -52
  88. diffusers/pipelines/controlnet/pipeline_controlnet_blip_diffusion.py +2 -2
  89. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +50 -43
  90. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +52 -40
  91. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +80 -47
  92. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +147 -49
  93. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +89 -55
  94. diffusers/pipelines/controlnet_xs/__init__.py +68 -0
  95. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +911 -0
  96. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +1115 -0
  97. diffusers/pipelines/deepfloyd_if/pipeline_if.py +14 -28
  98. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +18 -33
  99. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +21 -39
  100. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +20 -36
  101. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +23 -39
  102. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +17 -32
  103. diffusers/pipelines/deprecated/alt_diffusion/modeling_roberta_series.py +11 -11
  104. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +43 -20
  105. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +36 -18
  106. diffusers/pipelines/deprecated/repaint/pipeline_repaint.py +2 -2
  107. diffusers/pipelines/deprecated/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +7 -7
  108. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +12 -12
  109. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +18 -18
  110. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +20 -15
  111. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +20 -15
  112. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +30 -25
  113. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +69 -59
  114. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion.py +13 -13
  115. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +10 -5
  116. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +11 -6
  117. diffusers/pipelines/deprecated/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +10 -5
  118. diffusers/pipelines/deprecated/vq_diffusion/pipeline_vq_diffusion.py +5 -5
  119. diffusers/pipelines/dit/pipeline_dit.py +7 -4
  120. diffusers/pipelines/free_init_utils.py +39 -38
  121. diffusers/pipelines/hunyuandit/__init__.py +48 -0
  122. diffusers/pipelines/hunyuandit/pipeline_hunyuandit.py +881 -0
  123. diffusers/pipelines/i2vgen_xl/pipeline_i2vgen_xl.py +33 -48
  124. diffusers/pipelines/kandinsky/pipeline_kandinsky.py +8 -8
  125. diffusers/pipelines/kandinsky/pipeline_kandinsky_combined.py +23 -20
  126. diffusers/pipelines/kandinsky/pipeline_kandinsky_img2img.py +11 -11
  127. diffusers/pipelines/kandinsky/pipeline_kandinsky_inpaint.py +12 -12
  128. diffusers/pipelines/kandinsky/pipeline_kandinsky_prior.py +10 -10
  129. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +6 -6
  130. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +32 -29
  131. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet.py +10 -10
  132. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_controlnet_img2img.py +10 -10
  133. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +6 -6
  134. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +8 -8
  135. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +7 -7
  136. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior_emb2emb.py +6 -6
  137. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +3 -3
  138. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +20 -33
  139. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +24 -35
  140. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +48 -30
  141. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +50 -28
  142. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +11 -11
  143. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +61 -67
  144. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +70 -69
  145. diffusers/pipelines/ledits_pp/pipeline_output.py +2 -2
  146. diffusers/pipelines/marigold/__init__.py +50 -0
  147. diffusers/pipelines/marigold/marigold_image_processing.py +561 -0
  148. diffusers/pipelines/marigold/pipeline_marigold_depth.py +813 -0
  149. diffusers/pipelines/marigold/pipeline_marigold_normals.py +690 -0
  150. diffusers/pipelines/musicldm/pipeline_musicldm.py +14 -14
  151. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +17 -12
  152. diffusers/pipelines/pia/pipeline_pia.py +39 -125
  153. diffusers/pipelines/pipeline_flax_utils.py +4 -4
  154. diffusers/pipelines/pipeline_loading_utils.py +269 -23
  155. diffusers/pipelines/pipeline_utils.py +266 -37
  156. diffusers/pipelines/pixart_alpha/__init__.py +8 -1
  157. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +69 -79
  158. diffusers/pipelines/pixart_alpha/pipeline_pixart_sigma.py +880 -0
  159. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +10 -5
  160. diffusers/pipelines/shap_e/pipeline_shap_e.py +3 -3
  161. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +14 -14
  162. diffusers/pipelines/shap_e/renderer.py +1 -1
  163. diffusers/pipelines/stable_cascade/pipeline_stable_cascade.py +18 -18
  164. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_combined.py +23 -19
  165. diffusers/pipelines/stable_cascade/pipeline_stable_cascade_prior.py +33 -32
  166. diffusers/pipelines/stable_diffusion/__init__.py +0 -1
  167. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +18 -11
  168. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +2 -2
  169. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_upscale.py +6 -6
  170. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +73 -39
  171. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +24 -17
  172. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +13 -8
  173. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +66 -36
  174. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +82 -46
  175. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +123 -28
  176. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +6 -6
  177. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +16 -16
  178. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +24 -19
  179. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +37 -31
  180. diffusers/pipelines/stable_diffusion/safety_checker.py +2 -1
  181. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +23 -15
  182. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +44 -39
  183. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +23 -18
  184. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +19 -14
  185. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +20 -15
  186. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +24 -19
  187. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +65 -32
  188. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +274 -38
  189. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +10 -5
  190. diffusers/pipelines/stable_diffusion_safe/safety_checker.py +1 -1
  191. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +92 -25
  192. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +88 -44
  193. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +108 -56
  194. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +96 -51
  195. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +45 -25
  196. diffusers/pipelines/stable_diffusion_xl/watermark.py +9 -3
  197. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +110 -57
  198. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +59 -30
  199. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +71 -42
  200. diffusers/pipelines/text_to_video_synthesis/pipeline_output.py +3 -2
  201. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +18 -41
  202. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +21 -85
  203. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +28 -19
  204. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +39 -33
  205. diffusers/pipelines/unclip/pipeline_unclip.py +6 -6
  206. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +6 -6
  207. diffusers/pipelines/unidiffuser/modeling_text_decoder.py +1 -1
  208. diffusers/pipelines/unidiffuser/modeling_uvit.py +9 -9
  209. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +23 -23
  210. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +5 -5
  211. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +5 -10
  212. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +4 -6
  213. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +4 -4
  214. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +12 -12
  215. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +10 -10
  216. diffusers/schedulers/__init__.py +2 -2
  217. diffusers/schedulers/deprecated/__init__.py +1 -1
  218. diffusers/schedulers/deprecated/scheduling_karras_ve.py +25 -25
  219. diffusers/schedulers/scheduling_amused.py +5 -5
  220. diffusers/schedulers/scheduling_consistency_decoder.py +11 -11
  221. diffusers/schedulers/scheduling_consistency_models.py +20 -26
  222. diffusers/schedulers/scheduling_ddim.py +22 -24
  223. diffusers/schedulers/scheduling_ddim_flax.py +2 -1
  224. diffusers/schedulers/scheduling_ddim_inverse.py +16 -16
  225. diffusers/schedulers/scheduling_ddim_parallel.py +28 -30
  226. diffusers/schedulers/scheduling_ddpm.py +20 -22
  227. diffusers/schedulers/scheduling_ddpm_flax.py +7 -3
  228. diffusers/schedulers/scheduling_ddpm_parallel.py +26 -28
  229. diffusers/schedulers/scheduling_ddpm_wuerstchen.py +14 -14
  230. diffusers/schedulers/scheduling_deis_multistep.py +42 -42
  231. diffusers/schedulers/scheduling_dpmsolver_multistep.py +103 -77
  232. diffusers/schedulers/scheduling_dpmsolver_multistep_flax.py +2 -2
  233. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +46 -46
  234. diffusers/schedulers/scheduling_dpmsolver_sde.py +23 -23
  235. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +86 -65
  236. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +75 -54
  237. diffusers/schedulers/scheduling_edm_euler.py +50 -31
  238. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +23 -29
  239. diffusers/schedulers/scheduling_euler_discrete.py +160 -68
  240. diffusers/schedulers/scheduling_heun_discrete.py +57 -39
  241. diffusers/schedulers/scheduling_ipndm.py +8 -8
  242. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +19 -19
  243. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +19 -19
  244. diffusers/schedulers/scheduling_karras_ve_flax.py +6 -6
  245. diffusers/schedulers/scheduling_lcm.py +21 -23
  246. diffusers/schedulers/scheduling_lms_discrete.py +24 -26
  247. diffusers/schedulers/scheduling_pndm.py +20 -20
  248. diffusers/schedulers/scheduling_repaint.py +20 -20
  249. diffusers/schedulers/scheduling_sasolver.py +55 -54
  250. diffusers/schedulers/scheduling_sde_ve.py +19 -19
  251. diffusers/schedulers/scheduling_tcd.py +39 -30
  252. diffusers/schedulers/scheduling_unclip.py +15 -15
  253. diffusers/schedulers/scheduling_unipc_multistep.py +111 -41
  254. diffusers/schedulers/scheduling_utils.py +14 -5
  255. diffusers/schedulers/scheduling_utils_flax.py +3 -3
  256. diffusers/schedulers/scheduling_vq_diffusion.py +10 -10
  257. diffusers/training_utils.py +56 -1
  258. diffusers/utils/__init__.py +7 -0
  259. diffusers/utils/doc_utils.py +1 -0
  260. diffusers/utils/dummy_pt_objects.py +75 -0
  261. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  262. diffusers/utils/dynamic_modules_utils.py +24 -11
  263. diffusers/utils/hub_utils.py +3 -2
  264. diffusers/utils/import_utils.py +91 -0
  265. diffusers/utils/loading_utils.py +2 -2
  266. diffusers/utils/logging.py +1 -1
  267. diffusers/utils/peft_utils.py +32 -5
  268. diffusers/utils/state_dict_utils.py +11 -2
  269. diffusers/utils/testing_utils.py +71 -6
  270. diffusers/utils/torch_utils.py +1 -0
  271. diffusers/video_processor.py +113 -0
  272. {diffusers-0.27.2.dist-info → diffusers-0.28.1.dist-info}/METADATA +7 -7
  273. diffusers-0.28.1.dist-info/RECORD +419 -0
  274. diffusers-0.27.2.dist-info/RECORD +0 -399
  275. {diffusers-0.27.2.dist-info → diffusers-0.28.1.dist-info}/LICENSE +0 -0
  276. {diffusers-0.27.2.dist-info → diffusers-0.28.1.dist-info}/WHEEL +0 -0
  277. {diffusers-0.27.2.dist-info → diffusers-0.28.1.dist-info}/entry_points.txt +0 -0
  278. {diffusers-0.27.2.dist-info → diffusers-0.28.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1115 @@
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 torch.nn.functional as F
22
+ from transformers import (
23
+ CLIPImageProcessor,
24
+ CLIPTextModel,
25
+ CLIPTextModelWithProjection,
26
+ CLIPTokenizer,
27
+ )
28
+
29
+ from diffusers.utils.import_utils import is_invisible_watermark_available
30
+
31
+ from ...callbacks import MultiPipelineCallbacks, PipelineCallback
32
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
33
+ from ...loaders import FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
34
+ from ...models import AutoencoderKL, ControlNetXSAdapter, UNet2DConditionModel, UNetControlNetXSModel
35
+ from ...models.attention_processor import (
36
+ AttnProcessor2_0,
37
+ LoRAAttnProcessor2_0,
38
+ LoRAXFormersAttnProcessor,
39
+ XFormersAttnProcessor,
40
+ )
41
+ from ...models.lora import adjust_lora_scale_text_encoder
42
+ from ...schedulers import KarrasDiffusionSchedulers
43
+ from ...utils import (
44
+ USE_PEFT_BACKEND,
45
+ logging,
46
+ replace_example_docstring,
47
+ scale_lora_layers,
48
+ unscale_lora_layers,
49
+ )
50
+ from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
51
+ from ..pipeline_utils import DiffusionPipeline
52
+ from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
53
+
54
+
55
+ if is_invisible_watermark_available():
56
+ from ..stable_diffusion_xl.watermark import StableDiffusionXLWatermarker
57
+
58
+
59
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
60
+
61
+
62
+ EXAMPLE_DOC_STRING = """
63
+ Examples:
64
+ ```py
65
+ >>> # !pip install opencv-python transformers accelerate
66
+ >>> from diffusers import StableDiffusionXLControlNetXSPipeline, ControlNetXSAdapter, AutoencoderKL
67
+ >>> from diffusers.utils import load_image
68
+ >>> import numpy as np
69
+ >>> import torch
70
+
71
+ >>> import cv2
72
+ >>> from PIL import Image
73
+
74
+ >>> prompt = "aerial view, a futuristic research complex in a bright foggy jungle, hard lighting"
75
+ >>> negative_prompt = "low quality, bad quality, sketches"
76
+
77
+ >>> # download an image
78
+ >>> image = load_image(
79
+ ... "https://hf.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/hf-logo.png"
80
+ ... )
81
+
82
+ >>> # initialize the models and pipeline
83
+ >>> controlnet_conditioning_scale = 0.5
84
+ >>> vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
85
+ >>> controlnet = ControlNetXSAdapter.from_pretrained(
86
+ ... "UmerHA/Testing-ConrolNetXS-SDXL-canny", torch_dtype=torch.float16
87
+ ... )
88
+ >>> pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
89
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
90
+ ... )
91
+ >>> pipe.enable_model_cpu_offload()
92
+
93
+ >>> # get canny image
94
+ >>> image = np.array(image)
95
+ >>> image = cv2.Canny(image, 100, 200)
96
+ >>> image = image[:, :, None]
97
+ >>> image = np.concatenate([image, image, image], axis=2)
98
+ >>> canny_image = Image.fromarray(image)
99
+
100
+ >>> # generate image
101
+ >>> image = pipe(
102
+ ... prompt, controlnet_conditioning_scale=controlnet_conditioning_scale, image=canny_image
103
+ ... ).images[0]
104
+ ```
105
+ """
106
+
107
+
108
+ class StableDiffusionXLControlNetXSPipeline(
109
+ DiffusionPipeline,
110
+ TextualInversionLoaderMixin,
111
+ StableDiffusionXLLoraLoaderMixin,
112
+ FromSingleFileMixin,
113
+ ):
114
+ r"""
115
+ Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet-XS guidance.
116
+
117
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
118
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
119
+
120
+ The pipeline also inherits the following loading methods:
121
+ - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
122
+ - [`loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
123
+ - [`loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
124
+
125
+ Args:
126
+ vae ([`AutoencoderKL`]):
127
+ Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
128
+ text_encoder ([`~transformers.CLIPTextModel`]):
129
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
130
+ text_encoder_2 ([`~transformers.CLIPTextModelWithProjection`]):
131
+ Second frozen text-encoder
132
+ ([laion/CLIP-ViT-bigG-14-laion2B-39B-b160k](https://huggingface.co/laion/CLIP-ViT-bigG-14-laion2B-39B-b160k)).
133
+ tokenizer ([`~transformers.CLIPTokenizer`]):
134
+ A `CLIPTokenizer` to tokenize text.
135
+ tokenizer_2 ([`~transformers.CLIPTokenizer`]):
136
+ A `CLIPTokenizer` to tokenize text.
137
+ unet ([`UNet2DConditionModel`]):
138
+ A [`UNet2DConditionModel`] used to create a UNetControlNetXSModel to denoise the encoded image latents.
139
+ controlnet ([`ControlNetXSAdapter`]):
140
+ A [`ControlNetXSAdapter`] to be used in combination with `unet` to denoise the encoded image latents.
141
+ scheduler ([`SchedulerMixin`]):
142
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
143
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
144
+ force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
145
+ Whether the negative prompt embeddings should always be set to 0. Also see the config of
146
+ `stabilityai/stable-diffusion-xl-base-1-0`.
147
+ add_watermarker (`bool`, *optional*):
148
+ Whether to use the [invisible_watermark](https://github.com/ShieldMnt/invisible-watermark/) library to
149
+ watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
150
+ watermarker is used.
151
+ """
152
+
153
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
154
+ _optional_components = [
155
+ "tokenizer",
156
+ "tokenizer_2",
157
+ "text_encoder",
158
+ "text_encoder_2",
159
+ "feature_extractor",
160
+ ]
161
+ _callback_tensor_inputs = [
162
+ "latents",
163
+ "prompt_embeds",
164
+ "negative_prompt_embeds",
165
+ "add_text_embeds",
166
+ "add_time_ids",
167
+ "negative_pooled_prompt_embeds",
168
+ "negative_add_time_ids",
169
+ ]
170
+
171
+ def __init__(
172
+ self,
173
+ vae: AutoencoderKL,
174
+ text_encoder: CLIPTextModel,
175
+ text_encoder_2: CLIPTextModelWithProjection,
176
+ tokenizer: CLIPTokenizer,
177
+ tokenizer_2: CLIPTokenizer,
178
+ unet: Union[UNet2DConditionModel, UNetControlNetXSModel],
179
+ controlnet: ControlNetXSAdapter,
180
+ scheduler: KarrasDiffusionSchedulers,
181
+ force_zeros_for_empty_prompt: bool = True,
182
+ add_watermarker: Optional[bool] = None,
183
+ feature_extractor: CLIPImageProcessor = None,
184
+ ):
185
+ super().__init__()
186
+
187
+ if isinstance(unet, UNet2DConditionModel):
188
+ unet = UNetControlNetXSModel.from_unet(unet, controlnet)
189
+
190
+ self.register_modules(
191
+ vae=vae,
192
+ text_encoder=text_encoder,
193
+ text_encoder_2=text_encoder_2,
194
+ tokenizer=tokenizer,
195
+ tokenizer_2=tokenizer_2,
196
+ unet=unet,
197
+ controlnet=controlnet,
198
+ scheduler=scheduler,
199
+ feature_extractor=feature_extractor,
200
+ )
201
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
202
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
203
+ self.control_image_processor = VaeImageProcessor(
204
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
205
+ )
206
+ add_watermarker = add_watermarker if add_watermarker is not None else is_invisible_watermark_available()
207
+
208
+ if add_watermarker:
209
+ self.watermark = StableDiffusionXLWatermarker()
210
+ else:
211
+ self.watermark = None
212
+
213
+ self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
214
+
215
+ # Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl.StableDiffusionXLPipeline.encode_prompt
216
+ def encode_prompt(
217
+ self,
218
+ prompt: str,
219
+ prompt_2: Optional[str] = None,
220
+ device: Optional[torch.device] = None,
221
+ num_images_per_prompt: int = 1,
222
+ do_classifier_free_guidance: bool = True,
223
+ negative_prompt: Optional[str] = None,
224
+ negative_prompt_2: Optional[str] = None,
225
+ prompt_embeds: Optional[torch.Tensor] = None,
226
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
227
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
228
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
229
+ lora_scale: Optional[float] = None,
230
+ clip_skip: Optional[int] = None,
231
+ ):
232
+ r"""
233
+ Encodes the prompt into text encoder hidden states.
234
+
235
+ Args:
236
+ prompt (`str` or `List[str]`, *optional*):
237
+ prompt to be encoded
238
+ prompt_2 (`str` or `List[str]`, *optional*):
239
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
240
+ used in both text-encoders
241
+ device: (`torch.device`):
242
+ torch device
243
+ num_images_per_prompt (`int`):
244
+ number of images that should be generated per prompt
245
+ do_classifier_free_guidance (`bool`):
246
+ whether to use classifier free guidance or not
247
+ negative_prompt (`str` or `List[str]`, *optional*):
248
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
249
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
250
+ less than `1`).
251
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
252
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
253
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
254
+ prompt_embeds (`torch.Tensor`, *optional*):
255
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
256
+ provided, text embeddings will be generated from `prompt` input argument.
257
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
258
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
259
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
260
+ argument.
261
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
262
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
263
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
264
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
265
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
266
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
267
+ input argument.
268
+ lora_scale (`float`, *optional*):
269
+ A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
270
+ clip_skip (`int`, *optional*):
271
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
272
+ the output of the pre-final layer will be used for computing the prompt embeddings.
273
+ """
274
+ device = device or self._execution_device
275
+
276
+ # set lora scale so that monkey patched LoRA
277
+ # function of text encoder can correctly access it
278
+ if lora_scale is not None and isinstance(self, StableDiffusionXLLoraLoaderMixin):
279
+ self._lora_scale = lora_scale
280
+
281
+ # dynamically adjust the LoRA scale
282
+ if self.text_encoder is not None:
283
+ if not USE_PEFT_BACKEND:
284
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
285
+ else:
286
+ scale_lora_layers(self.text_encoder, lora_scale)
287
+
288
+ if self.text_encoder_2 is not None:
289
+ if not USE_PEFT_BACKEND:
290
+ adjust_lora_scale_text_encoder(self.text_encoder_2, lora_scale)
291
+ else:
292
+ scale_lora_layers(self.text_encoder_2, lora_scale)
293
+
294
+ prompt = [prompt] if isinstance(prompt, str) else prompt
295
+
296
+ if prompt is not None:
297
+ batch_size = len(prompt)
298
+ else:
299
+ batch_size = prompt_embeds.shape[0]
300
+
301
+ # Define tokenizers and text encoders
302
+ tokenizers = [self.tokenizer, self.tokenizer_2] if self.tokenizer is not None else [self.tokenizer_2]
303
+ text_encoders = (
304
+ [self.text_encoder, self.text_encoder_2] if self.text_encoder is not None else [self.text_encoder_2]
305
+ )
306
+
307
+ if prompt_embeds is None:
308
+ prompt_2 = prompt_2 or prompt
309
+ prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
310
+
311
+ # textual inversion: process multi-vector tokens if necessary
312
+ prompt_embeds_list = []
313
+ prompts = [prompt, prompt_2]
314
+ for prompt, tokenizer, text_encoder in zip(prompts, tokenizers, text_encoders):
315
+ if isinstance(self, TextualInversionLoaderMixin):
316
+ prompt = self.maybe_convert_prompt(prompt, tokenizer)
317
+
318
+ text_inputs = tokenizer(
319
+ prompt,
320
+ padding="max_length",
321
+ max_length=tokenizer.model_max_length,
322
+ truncation=True,
323
+ return_tensors="pt",
324
+ )
325
+
326
+ text_input_ids = text_inputs.input_ids
327
+ untruncated_ids = tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
328
+
329
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
330
+ text_input_ids, untruncated_ids
331
+ ):
332
+ removed_text = tokenizer.batch_decode(untruncated_ids[:, tokenizer.model_max_length - 1 : -1])
333
+ logger.warning(
334
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
335
+ f" {tokenizer.model_max_length} tokens: {removed_text}"
336
+ )
337
+
338
+ prompt_embeds = text_encoder(text_input_ids.to(device), output_hidden_states=True)
339
+
340
+ # We are only ALWAYS interested in the pooled output of the final text encoder
341
+ pooled_prompt_embeds = prompt_embeds[0]
342
+ if clip_skip is None:
343
+ prompt_embeds = prompt_embeds.hidden_states[-2]
344
+ else:
345
+ # "2" because SDXL always indexes from the penultimate layer.
346
+ prompt_embeds = prompt_embeds.hidden_states[-(clip_skip + 2)]
347
+
348
+ prompt_embeds_list.append(prompt_embeds)
349
+
350
+ prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
351
+
352
+ # get unconditional embeddings for classifier free guidance
353
+ zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
354
+ if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
355
+ negative_prompt_embeds = torch.zeros_like(prompt_embeds)
356
+ negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
357
+ elif do_classifier_free_guidance and negative_prompt_embeds is None:
358
+ negative_prompt = negative_prompt or ""
359
+ negative_prompt_2 = negative_prompt_2 or negative_prompt
360
+
361
+ # normalize str to list
362
+ negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
363
+ negative_prompt_2 = (
364
+ batch_size * [negative_prompt_2] if isinstance(negative_prompt_2, str) else negative_prompt_2
365
+ )
366
+
367
+ uncond_tokens: List[str]
368
+ if prompt is not None and type(prompt) is not type(negative_prompt):
369
+ raise TypeError(
370
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
371
+ f" {type(prompt)}."
372
+ )
373
+ elif batch_size != len(negative_prompt):
374
+ raise ValueError(
375
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
376
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
377
+ " the batch size of `prompt`."
378
+ )
379
+ else:
380
+ uncond_tokens = [negative_prompt, negative_prompt_2]
381
+
382
+ negative_prompt_embeds_list = []
383
+ for negative_prompt, tokenizer, text_encoder in zip(uncond_tokens, tokenizers, text_encoders):
384
+ if isinstance(self, TextualInversionLoaderMixin):
385
+ negative_prompt = self.maybe_convert_prompt(negative_prompt, tokenizer)
386
+
387
+ max_length = prompt_embeds.shape[1]
388
+ uncond_input = tokenizer(
389
+ negative_prompt,
390
+ padding="max_length",
391
+ max_length=max_length,
392
+ truncation=True,
393
+ return_tensors="pt",
394
+ )
395
+
396
+ negative_prompt_embeds = text_encoder(
397
+ uncond_input.input_ids.to(device),
398
+ output_hidden_states=True,
399
+ )
400
+ # We are only ALWAYS interested in the pooled output of the final text encoder
401
+ negative_pooled_prompt_embeds = negative_prompt_embeds[0]
402
+ negative_prompt_embeds = negative_prompt_embeds.hidden_states[-2]
403
+
404
+ negative_prompt_embeds_list.append(negative_prompt_embeds)
405
+
406
+ negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
407
+
408
+ if self.text_encoder_2 is not None:
409
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
410
+ else:
411
+ prompt_embeds = prompt_embeds.to(dtype=self.unet.dtype, device=device)
412
+
413
+ bs_embed, seq_len, _ = prompt_embeds.shape
414
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
415
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
416
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
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
+ if self.text_encoder_2 is not None:
423
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.text_encoder_2.dtype, device=device)
424
+ else:
425
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=self.unet.dtype, device=device)
426
+
427
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
428
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
429
+
430
+ pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
431
+ bs_embed * num_images_per_prompt, -1
432
+ )
433
+ if do_classifier_free_guidance:
434
+ negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
435
+ bs_embed * num_images_per_prompt, -1
436
+ )
437
+
438
+ if self.text_encoder is not None:
439
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
440
+ # Retrieve the original scale by scaling back the LoRA layers
441
+ unscale_lora_layers(self.text_encoder, lora_scale)
442
+
443
+ if self.text_encoder_2 is not None:
444
+ if isinstance(self, StableDiffusionXLLoraLoaderMixin) and USE_PEFT_BACKEND:
445
+ # Retrieve the original scale by scaling back the LoRA layers
446
+ unscale_lora_layers(self.text_encoder_2, lora_scale)
447
+
448
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
449
+
450
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
451
+ def prepare_extra_step_kwargs(self, generator, eta):
452
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
453
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
454
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
455
+ # and should be between [0, 1]
456
+
457
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
458
+ extra_step_kwargs = {}
459
+ if accepts_eta:
460
+ extra_step_kwargs["eta"] = eta
461
+
462
+ # check if the scheduler accepts generator
463
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
464
+ if accepts_generator:
465
+ extra_step_kwargs["generator"] = generator
466
+ return extra_step_kwargs
467
+
468
+ def check_inputs(
469
+ self,
470
+ prompt,
471
+ prompt_2,
472
+ image,
473
+ negative_prompt=None,
474
+ negative_prompt_2=None,
475
+ prompt_embeds=None,
476
+ negative_prompt_embeds=None,
477
+ pooled_prompt_embeds=None,
478
+ negative_pooled_prompt_embeds=None,
479
+ controlnet_conditioning_scale=1.0,
480
+ control_guidance_start=0.0,
481
+ control_guidance_end=1.0,
482
+ callback_on_step_end_tensor_inputs=None,
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_2 is not None and prompt_embeds is not None:
497
+ raise ValueError(
498
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
499
+ " only forward one of the two."
500
+ )
501
+ elif prompt is None and prompt_embeds is None:
502
+ raise ValueError(
503
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
504
+ )
505
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
506
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
507
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
508
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
509
+
510
+ if negative_prompt is not None and negative_prompt_embeds is not None:
511
+ raise ValueError(
512
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
513
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
514
+ )
515
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
516
+ raise ValueError(
517
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
518
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
519
+ )
520
+
521
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
522
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
523
+ raise ValueError(
524
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
525
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
526
+ f" {negative_prompt_embeds.shape}."
527
+ )
528
+
529
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
530
+ raise ValueError(
531
+ "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`."
532
+ )
533
+
534
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
535
+ raise ValueError(
536
+ "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`."
537
+ )
538
+
539
+ # Check `image` and ``controlnet_conditioning_scale``
540
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
541
+ self.unet, torch._dynamo.eval_frame.OptimizedModule
542
+ )
543
+ if (
544
+ isinstance(self.unet, UNetControlNetXSModel)
545
+ or is_compiled
546
+ and isinstance(self.unet._orig_mod, UNetControlNetXSModel)
547
+ ):
548
+ self.check_image(image, prompt, prompt_embeds)
549
+ if not isinstance(controlnet_conditioning_scale, float):
550
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
551
+ else:
552
+ assert False
553
+
554
+ start, end = control_guidance_start, control_guidance_end
555
+ if start >= end:
556
+ raise ValueError(
557
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
558
+ )
559
+ if start < 0.0:
560
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
561
+ if end > 1.0:
562
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
563
+
564
+ # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image
565
+ def check_image(self, image, prompt, prompt_embeds):
566
+ image_is_pil = isinstance(image, PIL.Image.Image)
567
+ image_is_tensor = isinstance(image, torch.Tensor)
568
+ image_is_np = isinstance(image, np.ndarray)
569
+ image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
570
+ image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
571
+ image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
572
+
573
+ if (
574
+ not image_is_pil
575
+ and not image_is_tensor
576
+ and not image_is_np
577
+ and not image_is_pil_list
578
+ and not image_is_tensor_list
579
+ and not image_is_np_list
580
+ ):
581
+ raise TypeError(
582
+ 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)}"
583
+ )
584
+
585
+ if image_is_pil:
586
+ image_batch_size = 1
587
+ else:
588
+ image_batch_size = len(image)
589
+
590
+ if prompt is not None and isinstance(prompt, str):
591
+ prompt_batch_size = 1
592
+ elif prompt is not None and isinstance(prompt, list):
593
+ prompt_batch_size = len(prompt)
594
+ elif prompt_embeds is not None:
595
+ prompt_batch_size = prompt_embeds.shape[0]
596
+
597
+ if image_batch_size != 1 and image_batch_size != prompt_batch_size:
598
+ raise ValueError(
599
+ 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}"
600
+ )
601
+
602
+ def prepare_image(
603
+ self,
604
+ image,
605
+ width,
606
+ height,
607
+ batch_size,
608
+ num_images_per_prompt,
609
+ device,
610
+ dtype,
611
+ do_classifier_free_guidance=False,
612
+ ):
613
+ image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
614
+ image_batch_size = image.shape[0]
615
+
616
+ if image_batch_size == 1:
617
+ repeat_by = batch_size
618
+ else:
619
+ # image batch size is the same as prompt batch size
620
+ repeat_by = num_images_per_prompt
621
+
622
+ image = image.repeat_interleave(repeat_by, dim=0)
623
+
624
+ image = image.to(device=device, dtype=dtype)
625
+
626
+ if do_classifier_free_guidance:
627
+ image = torch.cat([image] * 2)
628
+
629
+ return image
630
+
631
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
632
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
633
+ shape = (
634
+ batch_size,
635
+ num_channels_latents,
636
+ int(height) // self.vae_scale_factor,
637
+ int(width) // self.vae_scale_factor,
638
+ )
639
+ if isinstance(generator, list) and len(generator) != batch_size:
640
+ raise ValueError(
641
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
642
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
643
+ )
644
+
645
+ if latents is None:
646
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
647
+ else:
648
+ latents = latents.to(device)
649
+
650
+ # scale the initial noise by the standard deviation required by the scheduler
651
+ latents = latents * self.scheduler.init_noise_sigma
652
+ return latents
653
+
654
+ def _get_add_time_ids(
655
+ self, original_size, crops_coords_top_left, target_size, dtype, text_encoder_projection_dim=None
656
+ ):
657
+ add_time_ids = list(original_size + crops_coords_top_left + target_size)
658
+
659
+ passed_add_embed_dim = (
660
+ self.unet.config.addition_time_embed_dim * len(add_time_ids) + text_encoder_projection_dim
661
+ )
662
+ expected_add_embed_dim = self.unet.base_add_embedding.linear_1.in_features
663
+
664
+ if expected_add_embed_dim != passed_add_embed_dim:
665
+ raise ValueError(
666
+ 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`."
667
+ )
668
+
669
+ add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
670
+ return add_time_ids
671
+
672
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
673
+ def upcast_vae(self):
674
+ dtype = self.vae.dtype
675
+ self.vae.to(dtype=torch.float32)
676
+ use_torch_2_0_or_xformers = isinstance(
677
+ self.vae.decoder.mid_block.attentions[0].processor,
678
+ (
679
+ AttnProcessor2_0,
680
+ XFormersAttnProcessor,
681
+ LoRAXFormersAttnProcessor,
682
+ LoRAAttnProcessor2_0,
683
+ ),
684
+ )
685
+ # if xformers or torch_2_0 is used attention block does not need
686
+ # to be in float32 which can save lots of memory
687
+ if use_torch_2_0_or_xformers:
688
+ self.vae.post_quant_conv.to(dtype)
689
+ self.vae.decoder.conv_in.to(dtype)
690
+ self.vae.decoder.mid_block.to(dtype)
691
+
692
+ @property
693
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.guidance_scale
694
+ def guidance_scale(self):
695
+ return self._guidance_scale
696
+
697
+ @property
698
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.clip_skip
699
+ def clip_skip(self):
700
+ return self._clip_skip
701
+
702
+ @property
703
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.do_classifier_free_guidance
704
+ def do_classifier_free_guidance(self):
705
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
706
+
707
+ @property
708
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.cross_attention_kwargs
709
+ def cross_attention_kwargs(self):
710
+ return self._cross_attention_kwargs
711
+
712
+ @property
713
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.num_timesteps
714
+ def num_timesteps(self):
715
+ return self._num_timesteps
716
+
717
+ @torch.no_grad()
718
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
719
+ def __call__(
720
+ self,
721
+ prompt: Union[str, List[str]] = None,
722
+ prompt_2: Optional[Union[str, List[str]]] = None,
723
+ image: PipelineImageInput = None,
724
+ height: Optional[int] = None,
725
+ width: Optional[int] = None,
726
+ num_inference_steps: int = 50,
727
+ guidance_scale: float = 5.0,
728
+ negative_prompt: Optional[Union[str, List[str]]] = None,
729
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
730
+ num_images_per_prompt: Optional[int] = 1,
731
+ eta: float = 0.0,
732
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
733
+ latents: Optional[torch.Tensor] = None,
734
+ prompt_embeds: Optional[torch.Tensor] = None,
735
+ negative_prompt_embeds: Optional[torch.Tensor] = None,
736
+ pooled_prompt_embeds: Optional[torch.Tensor] = None,
737
+ negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
738
+ output_type: Optional[str] = "pil",
739
+ return_dict: bool = True,
740
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
741
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
742
+ control_guidance_start: float = 0.0,
743
+ control_guidance_end: float = 1.0,
744
+ original_size: Tuple[int, int] = None,
745
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
746
+ target_size: Tuple[int, int] = None,
747
+ negative_original_size: Optional[Tuple[int, int]] = None,
748
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
749
+ negative_target_size: Optional[Tuple[int, int]] = None,
750
+ clip_skip: Optional[int] = None,
751
+ callback_on_step_end: Optional[
752
+ Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
753
+ ] = None,
754
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
755
+ ):
756
+ r"""
757
+ The call function to the pipeline for generation.
758
+
759
+ Args:
760
+ prompt (`str` or `List[str]`, *optional*):
761
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
762
+ prompt_2 (`str` or `List[str]`, *optional*):
763
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
764
+ used in both text-encoders.
765
+ image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
766
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
767
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
768
+ specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be accepted
769
+ as an image. The dimensions of the output image defaults to `image`'s dimensions. If height and/or
770
+ width are passed, `image` is resized accordingly. If multiple ControlNets are specified in `init`,
771
+ images must be passed as a list such that each element of the list can be correctly batched for input
772
+ to a single ControlNet.
773
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
774
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
775
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
776
+ and checkpoints that are not specifically fine-tuned on low resolutions.
777
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
778
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
779
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
780
+ and checkpoints that are not specifically fine-tuned on low resolutions.
781
+ num_inference_steps (`int`, *optional*, defaults to 50):
782
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
783
+ expense of slower inference.
784
+ guidance_scale (`float`, *optional*, defaults to 5.0):
785
+ A higher guidance scale value encourages the model to generate images closely linked to the text
786
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
787
+ negative_prompt (`str` or `List[str]`, *optional*):
788
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
789
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
790
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
791
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
792
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
793
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
794
+ The number of images to generate per prompt.
795
+ eta (`float`, *optional*, defaults to 0.0):
796
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
797
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
798
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
799
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
800
+ generation deterministic.
801
+ latents (`torch.Tensor`, *optional*):
802
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
803
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
804
+ tensor is generated by sampling using the supplied random `generator`.
805
+ prompt_embeds (`torch.Tensor`, *optional*):
806
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
807
+ provided, text embeddings are generated from the `prompt` input argument.
808
+ negative_prompt_embeds (`torch.Tensor`, *optional*):
809
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
810
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
811
+ pooled_prompt_embeds (`torch.Tensor`, *optional*):
812
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
813
+ not provided, pooled text embeddings are generated from `prompt` input argument.
814
+ negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
815
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
816
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
817
+ argument.
818
+ output_type (`str`, *optional*, defaults to `"pil"`):
819
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
820
+ return_dict (`bool`, *optional*, defaults to `True`):
821
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
822
+ plain tuple.
823
+ cross_attention_kwargs (`dict`, *optional*):
824
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
825
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
826
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
827
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
828
+ to the residual in the original `unet`.
829
+ control_guidance_start (`float`, *optional*, defaults to 0.0):
830
+ The percentage of total steps at which the ControlNet starts applying.
831
+ control_guidance_end (`float`, *optional*, defaults to 1.0):
832
+ The percentage of total steps at which the ControlNet stops applying.
833
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
834
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
835
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
836
+ explained in section 2.2 of
837
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
838
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
839
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
840
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
841
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
842
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
843
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
844
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
845
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
846
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
847
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
848
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
849
+ micro-conditioning as explained in section 2.2 of
850
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
851
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
852
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
853
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
854
+ micro-conditioning as explained in section 2.2 of
855
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
856
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
857
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
858
+ To negatively condition the generation process based on a target image resolution. It should be as same
859
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
860
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
861
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
862
+ clip_skip (`int`, *optional*):
863
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
864
+ the output of the pre-final layer will be used for computing the prompt embeddings.
865
+ callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
866
+ A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
867
+ each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
868
+ DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
869
+ list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
870
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
871
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
872
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
873
+ `._callback_tensor_inputs` attribute of your pipeine class.
874
+
875
+ Examples:
876
+
877
+ Returns:
878
+ [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] or `tuple`:
879
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionXLPipelineOutput`] is
880
+ returned, otherwise a `tuple` is returned containing the output images.
881
+ """
882
+
883
+ if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
884
+ callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
885
+
886
+ unet = self.unet._orig_mod if is_compiled_module(self.unet) else self.unet
887
+
888
+ # 1. Check inputs. Raise error if not correct
889
+ self.check_inputs(
890
+ prompt,
891
+ prompt_2,
892
+ image,
893
+ negative_prompt,
894
+ negative_prompt_2,
895
+ prompt_embeds,
896
+ negative_prompt_embeds,
897
+ pooled_prompt_embeds,
898
+ negative_pooled_prompt_embeds,
899
+ controlnet_conditioning_scale,
900
+ control_guidance_start,
901
+ control_guidance_end,
902
+ callback_on_step_end_tensor_inputs,
903
+ )
904
+
905
+ self._guidance_scale = guidance_scale
906
+ self._clip_skip = clip_skip
907
+ self._cross_attention_kwargs = cross_attention_kwargs
908
+ self._interrupt = False
909
+
910
+ # 2. Define call parameters
911
+ if prompt is not None and isinstance(prompt, str):
912
+ batch_size = 1
913
+ elif prompt is not None and isinstance(prompt, list):
914
+ batch_size = len(prompt)
915
+ else:
916
+ batch_size = prompt_embeds.shape[0]
917
+
918
+ device = self._execution_device
919
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
920
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
921
+ # corresponds to doing no classifier free guidance.
922
+ do_classifier_free_guidance = guidance_scale > 1.0
923
+
924
+ # 3. Encode input prompt
925
+ text_encoder_lora_scale = (
926
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
927
+ )
928
+ (
929
+ prompt_embeds,
930
+ negative_prompt_embeds,
931
+ pooled_prompt_embeds,
932
+ negative_pooled_prompt_embeds,
933
+ ) = self.encode_prompt(
934
+ prompt,
935
+ prompt_2,
936
+ device,
937
+ num_images_per_prompt,
938
+ do_classifier_free_guidance,
939
+ negative_prompt,
940
+ negative_prompt_2,
941
+ prompt_embeds=prompt_embeds,
942
+ negative_prompt_embeds=negative_prompt_embeds,
943
+ pooled_prompt_embeds=pooled_prompt_embeds,
944
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
945
+ lora_scale=text_encoder_lora_scale,
946
+ clip_skip=clip_skip,
947
+ )
948
+
949
+ # 4. Prepare image
950
+ if isinstance(unet, UNetControlNetXSModel):
951
+ image = self.prepare_image(
952
+ image=image,
953
+ width=width,
954
+ height=height,
955
+ batch_size=batch_size * num_images_per_prompt,
956
+ num_images_per_prompt=num_images_per_prompt,
957
+ device=device,
958
+ dtype=unet.dtype,
959
+ do_classifier_free_guidance=do_classifier_free_guidance,
960
+ )
961
+ height, width = image.shape[-2:]
962
+ else:
963
+ assert False
964
+
965
+ # 5. Prepare timesteps
966
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
967
+ timesteps = self.scheduler.timesteps
968
+
969
+ # 6. Prepare latent variables
970
+ num_channels_latents = self.unet.in_channels
971
+ latents = self.prepare_latents(
972
+ batch_size * num_images_per_prompt,
973
+ num_channels_latents,
974
+ height,
975
+ width,
976
+ prompt_embeds.dtype,
977
+ device,
978
+ generator,
979
+ latents,
980
+ )
981
+
982
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
983
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
984
+
985
+ # 7.1 Prepare added time ids & embeddings
986
+ if isinstance(image, list):
987
+ original_size = original_size or image[0].shape[-2:]
988
+ else:
989
+ original_size = original_size or image.shape[-2:]
990
+ target_size = target_size or (height, width)
991
+
992
+ add_text_embeds = pooled_prompt_embeds
993
+ if self.text_encoder_2 is None:
994
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
995
+ else:
996
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
997
+
998
+ add_time_ids = self._get_add_time_ids(
999
+ original_size,
1000
+ crops_coords_top_left,
1001
+ target_size,
1002
+ dtype=prompt_embeds.dtype,
1003
+ text_encoder_projection_dim=text_encoder_projection_dim,
1004
+ )
1005
+
1006
+ if negative_original_size is not None and negative_target_size is not None:
1007
+ negative_add_time_ids = self._get_add_time_ids(
1008
+ negative_original_size,
1009
+ negative_crops_coords_top_left,
1010
+ negative_target_size,
1011
+ dtype=prompt_embeds.dtype,
1012
+ text_encoder_projection_dim=text_encoder_projection_dim,
1013
+ )
1014
+ else:
1015
+ negative_add_time_ids = add_time_ids
1016
+
1017
+ if do_classifier_free_guidance:
1018
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1019
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1020
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1021
+
1022
+ prompt_embeds = prompt_embeds.to(device)
1023
+ add_text_embeds = add_text_embeds.to(device)
1024
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1025
+
1026
+ # 8. Denoising loop
1027
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1028
+ self._num_timesteps = len(timesteps)
1029
+ is_controlnet_compiled = is_compiled_module(self.unet)
1030
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1031
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1032
+ for i, t in enumerate(timesteps):
1033
+ # Relevant thread:
1034
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1035
+ if is_controlnet_compiled and is_torch_higher_equal_2_1:
1036
+ torch._inductor.cudagraph_mark_step_begin()
1037
+ # expand the latents if we are doing classifier free guidance
1038
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1039
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1040
+
1041
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1042
+
1043
+ # predict the noise residual
1044
+ apply_control = (
1045
+ i / len(timesteps) >= control_guidance_start and (i + 1) / len(timesteps) <= control_guidance_end
1046
+ )
1047
+ noise_pred = self.unet(
1048
+ sample=latent_model_input,
1049
+ timestep=t,
1050
+ encoder_hidden_states=prompt_embeds,
1051
+ controlnet_cond=image,
1052
+ conditioning_scale=controlnet_conditioning_scale,
1053
+ cross_attention_kwargs=cross_attention_kwargs,
1054
+ added_cond_kwargs=added_cond_kwargs,
1055
+ return_dict=True,
1056
+ apply_control=apply_control,
1057
+ ).sample
1058
+
1059
+ # perform guidance
1060
+ if do_classifier_free_guidance:
1061
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1062
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1063
+
1064
+ # compute the previous noisy sample x_t -> x_t-1
1065
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1066
+
1067
+ if callback_on_step_end is not None:
1068
+ callback_kwargs = {}
1069
+ for k in callback_on_step_end_tensor_inputs:
1070
+ callback_kwargs[k] = locals()[k]
1071
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1072
+
1073
+ latents = callback_outputs.pop("latents", latents)
1074
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1075
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1076
+
1077
+ # call the callback, if provided
1078
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1079
+ progress_bar.update()
1080
+
1081
+ # manually for max memory savings
1082
+ if self.vae.dtype == torch.float16 and self.vae.config.force_upcast:
1083
+ self.upcast_vae()
1084
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1085
+
1086
+ if not output_type == "latent":
1087
+ # make sure the VAE is in float32 mode, as it overflows in float16
1088
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1089
+
1090
+ if needs_upcasting:
1091
+ self.upcast_vae()
1092
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1093
+
1094
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1095
+
1096
+ # cast back to fp16 if needed
1097
+ if needs_upcasting:
1098
+ self.vae.to(dtype=torch.float16)
1099
+ else:
1100
+ image = latents
1101
+
1102
+ if not output_type == "latent":
1103
+ # apply watermark if available
1104
+ if self.watermark is not None:
1105
+ image = self.watermark.apply_watermark(image)
1106
+
1107
+ image = self.image_processor.postprocess(image, output_type=output_type)
1108
+
1109
+ # Offload all models
1110
+ self.maybe_free_model_hooks()
1111
+
1112
+ if not return_dict:
1113
+ return (image,)
1114
+
1115
+ return StableDiffusionXLPipelineOutput(images=image)