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
@@ -20,13 +20,24 @@ import numpy as np
20
20
  import PIL.Image
21
21
  import torch
22
22
  import torch.nn.functional as F
23
- from transformers import CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
23
+ from transformers import (
24
+ CLIPImageProcessor,
25
+ CLIPTextModel,
26
+ CLIPTextModelWithProjection,
27
+ CLIPTokenizer,
28
+ CLIPVisionModelWithProjection,
29
+ )
24
30
 
25
31
  from diffusers.utils.import_utils import is_invisible_watermark_available
26
32
 
27
33
  from ...image_processor import PipelineImageInput, VaeImageProcessor
28
- from ...loaders import FromSingleFileMixin, StableDiffusionXLLoraLoaderMixin, TextualInversionLoaderMixin
29
- from ...models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
34
+ from ...loaders import (
35
+ FromSingleFileMixin,
36
+ IPAdapterMixin,
37
+ StableDiffusionXLLoraLoaderMixin,
38
+ TextualInversionLoaderMixin,
39
+ )
40
+ from ...models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
30
41
  from ...models.attention_processor import (
31
42
  AttnProcessor2_0,
32
43
  LoRAAttnProcessor2_0,
@@ -35,7 +46,14 @@ from ...models.attention_processor import (
35
46
  )
36
47
  from ...models.lora import adjust_lora_scale_text_encoder
37
48
  from ...schedulers import KarrasDiffusionSchedulers
38
- from ...utils import USE_PEFT_BACKEND, logging, replace_example_docstring, scale_lora_layers, unscale_lora_layers
49
+ from ...utils import (
50
+ USE_PEFT_BACKEND,
51
+ deprecate,
52
+ logging,
53
+ replace_example_docstring,
54
+ scale_lora_layers,
55
+ unscale_lora_layers,
56
+ )
39
57
  from ...utils.torch_utils import is_compiled_module, is_torch_version, randn_tensor
40
58
  from ..pipeline_utils import DiffusionPipeline
41
59
  from ..stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
@@ -97,7 +115,11 @@ EXAMPLE_DOC_STRING = """
97
115
 
98
116
 
99
117
  class StableDiffusionXLControlNetPipeline(
100
- DiffusionPipeline, TextualInversionLoaderMixin, StableDiffusionXLLoraLoaderMixin, FromSingleFileMixin
118
+ DiffusionPipeline,
119
+ TextualInversionLoaderMixin,
120
+ StableDiffusionXLLoraLoaderMixin,
121
+ IPAdapterMixin,
122
+ FromSingleFileMixin,
101
123
  ):
102
124
  r"""
103
125
  Pipeline for text-to-image generation using Stable Diffusion XL with ControlNet guidance.
@@ -107,8 +129,10 @@ class StableDiffusionXLControlNetPipeline(
107
129
 
108
130
  The pipeline also inherits the following loading methods:
109
131
  - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
110
- - [`loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
111
- - [`loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
132
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
133
+ - [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
134
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
135
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
112
136
 
113
137
  Args:
114
138
  vae ([`AutoencoderKL`]):
@@ -139,9 +163,18 @@ class StableDiffusionXLControlNetPipeline(
139
163
  watermark output images. If not defined, it defaults to `True` if the package is installed; otherwise no
140
164
  watermarker is used.
141
165
  """
166
+
142
167
  # leave controlnet out on purpose because it iterates with unet
143
- model_cpu_offload_seq = "text_encoder->text_encoder_2->unet->vae"
144
- _optional_components = ["tokenizer", "tokenizer_2", "text_encoder", "text_encoder_2"]
168
+ model_cpu_offload_seq = "text_encoder->text_encoder_2->image_encoder->unet->vae"
169
+ _optional_components = [
170
+ "tokenizer",
171
+ "tokenizer_2",
172
+ "text_encoder",
173
+ "text_encoder_2",
174
+ "feature_extractor",
175
+ "image_encoder",
176
+ ]
177
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
145
178
 
146
179
  def __init__(
147
180
  self,
@@ -155,6 +188,8 @@ class StableDiffusionXLControlNetPipeline(
155
188
  scheduler: KarrasDiffusionSchedulers,
156
189
  force_zeros_for_empty_prompt: bool = True,
157
190
  add_watermarker: Optional[bool] = None,
191
+ feature_extractor: CLIPImageProcessor = None,
192
+ image_encoder: CLIPVisionModelWithProjection = None,
158
193
  ):
159
194
  super().__init__()
160
195
 
@@ -170,6 +205,8 @@ class StableDiffusionXLControlNetPipeline(
170
205
  unet=unet,
171
206
  controlnet=controlnet,
172
207
  scheduler=scheduler,
208
+ feature_extractor=feature_extractor,
209
+ image_encoder=image_encoder,
173
210
  )
174
211
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
175
212
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
@@ -453,6 +490,31 @@ class StableDiffusionXLControlNetPipeline(
453
490
 
454
491
  return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
455
492
 
493
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
494
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
495
+ dtype = next(self.image_encoder.parameters()).dtype
496
+
497
+ if not isinstance(image, torch.Tensor):
498
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
499
+
500
+ image = image.to(device=device, dtype=dtype)
501
+ if output_hidden_states:
502
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
503
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
504
+ uncond_image_enc_hidden_states = self.image_encoder(
505
+ torch.zeros_like(image), output_hidden_states=True
506
+ ).hidden_states[-2]
507
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
508
+ num_images_per_prompt, dim=0
509
+ )
510
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
511
+ else:
512
+ image_embeds = self.image_encoder(image).image_embeds
513
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
514
+ uncond_image_embeds = torch.zeros_like(image_embeds)
515
+
516
+ return image_embeds, uncond_image_embeds
517
+
456
518
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
457
519
  def prepare_extra_step_kwargs(self, generator, eta):
458
520
  # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
@@ -486,15 +548,21 @@ class StableDiffusionXLControlNetPipeline(
486
548
  controlnet_conditioning_scale=1.0,
487
549
  control_guidance_start=0.0,
488
550
  control_guidance_end=1.0,
551
+ callback_on_step_end_tensor_inputs=None,
489
552
  ):
490
- if (callback_steps is None) or (
491
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
492
- ):
553
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
493
554
  raise ValueError(
494
555
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
495
556
  f" {type(callback_steps)}."
496
557
  )
497
558
 
559
+ if callback_on_step_end_tensor_inputs is not None and not all(
560
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
561
+ ):
562
+ raise ValueError(
563
+ 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]}"
564
+ )
565
+
498
566
  if prompt is not None and prompt_embeds is not None:
499
567
  raise ValueError(
500
568
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
@@ -791,6 +859,58 @@ class StableDiffusionXLControlNetPipeline(
791
859
  """Disables the FreeU mechanism if enabled."""
792
860
  self.unet.disable_freeu()
793
861
 
862
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
863
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
864
+ """
865
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
866
+
867
+ Args:
868
+ timesteps (`torch.Tensor`):
869
+ generate embedding vectors at these timesteps
870
+ embedding_dim (`int`, *optional*, defaults to 512):
871
+ dimension of the embeddings to generate
872
+ dtype:
873
+ data type of the generated embeddings
874
+
875
+ Returns:
876
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
877
+ """
878
+ assert len(w.shape) == 1
879
+ w = w * 1000.0
880
+
881
+ half_dim = embedding_dim // 2
882
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
883
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
884
+ emb = w.to(dtype)[:, None] * emb[None, :]
885
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
886
+ if embedding_dim % 2 == 1: # zero pad
887
+ emb = torch.nn.functional.pad(emb, (0, 1))
888
+ assert emb.shape == (w.shape[0], embedding_dim)
889
+ return emb
890
+
891
+ @property
892
+ def guidance_scale(self):
893
+ return self._guidance_scale
894
+
895
+ @property
896
+ def clip_skip(self):
897
+ return self._clip_skip
898
+
899
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
900
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
901
+ # corresponds to doing no classifier free guidance.
902
+ @property
903
+ def do_classifier_free_guidance(self):
904
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
905
+
906
+ @property
907
+ def cross_attention_kwargs(self):
908
+ return self._cross_attention_kwargs
909
+
910
+ @property
911
+ def num_timesteps(self):
912
+ return self._num_timesteps
913
+
794
914
  @torch.no_grad()
795
915
  @replace_example_docstring(EXAMPLE_DOC_STRING)
796
916
  def __call__(
@@ -812,10 +932,9 @@ class StableDiffusionXLControlNetPipeline(
812
932
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
813
933
  pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
814
934
  negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
935
+ ip_adapter_image: Optional[PipelineImageInput] = None,
815
936
  output_type: Optional[str] = "pil",
816
937
  return_dict: bool = True,
817
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
818
- callback_steps: int = 1,
819
938
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
820
939
  controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
821
940
  guess_mode: bool = False,
@@ -828,6 +947,9 @@ class StableDiffusionXLControlNetPipeline(
828
947
  negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
829
948
  negative_target_size: Optional[Tuple[int, int]] = None,
830
949
  clip_skip: Optional[int] = None,
950
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
951
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
952
+ **kwargs,
831
953
  ):
832
954
  r"""
833
955
  The call function to the pipeline for generation.
@@ -891,17 +1013,12 @@ class StableDiffusionXLControlNetPipeline(
891
1013
  Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
892
1014
  weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
893
1015
  argument.
1016
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
894
1017
  output_type (`str`, *optional*, defaults to `"pil"`):
895
1018
  The output format of the generated image. Choose between `PIL.Image` or `np.array`.
896
1019
  return_dict (`bool`, *optional*, defaults to `True`):
897
1020
  Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
898
1021
  plain tuple.
899
- callback (`Callable`, *optional*):
900
- A function that calls every `callback_steps` steps during inference. The function is called with the
901
- following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
902
- callback_steps (`int`, *optional*, defaults to 1):
903
- The frequency at which the `callback` function is called. If not specified, the callback is called at
904
- every step.
905
1022
  cross_attention_kwargs (`dict`, *optional*):
906
1023
  A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
907
1024
  [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
@@ -948,6 +1065,15 @@ class StableDiffusionXLControlNetPipeline(
948
1065
  clip_skip (`int`, *optional*):
949
1066
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
950
1067
  the output of the pre-final layer will be used for computing the prompt embeddings.
1068
+ callback_on_step_end (`Callable`, *optional*):
1069
+ A function that calls at the end of each denoising steps during the inference. The function is called
1070
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1071
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1072
+ `callback_on_step_end_tensor_inputs`.
1073
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1074
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1075
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1076
+ `._callback_tensor_inputs` attribute of your pipeine class.
951
1077
 
952
1078
  Examples:
953
1079
 
@@ -956,6 +1082,23 @@ class StableDiffusionXLControlNetPipeline(
956
1082
  If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
957
1083
  otherwise a `tuple` is returned containing the output images.
958
1084
  """
1085
+
1086
+ callback = kwargs.pop("callback", None)
1087
+ callback_steps = kwargs.pop("callback_steps", None)
1088
+
1089
+ if callback is not None:
1090
+ deprecate(
1091
+ "callback",
1092
+ "1.0.0",
1093
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1094
+ )
1095
+ if callback_steps is not None:
1096
+ deprecate(
1097
+ "callback_steps",
1098
+ "1.0.0",
1099
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1100
+ )
1101
+
959
1102
  controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
960
1103
 
961
1104
  # align format for control guidance
@@ -965,9 +1108,10 @@ class StableDiffusionXLControlNetPipeline(
965
1108
  control_guidance_end = len(control_guidance_start) * [control_guidance_end]
966
1109
  elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
967
1110
  mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
968
- control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
969
- control_guidance_end
970
- ]
1111
+ control_guidance_start, control_guidance_end = (
1112
+ mult * [control_guidance_start],
1113
+ mult * [control_guidance_end],
1114
+ )
971
1115
 
972
1116
  # 1. Check inputs. Raise error if not correct
973
1117
  self.check_inputs(
@@ -984,8 +1128,13 @@ class StableDiffusionXLControlNetPipeline(
984
1128
  controlnet_conditioning_scale,
985
1129
  control_guidance_start,
986
1130
  control_guidance_end,
1131
+ callback_on_step_end_tensor_inputs,
987
1132
  )
988
1133
 
1134
+ self._guidance_scale = guidance_scale
1135
+ self._clip_skip = clip_skip
1136
+ self._cross_attention_kwargs = cross_attention_kwargs
1137
+
989
1138
  # 2. Define call parameters
990
1139
  if prompt is not None and isinstance(prompt, str):
991
1140
  batch_size = 1
@@ -995,10 +1144,6 @@ class StableDiffusionXLControlNetPipeline(
995
1144
  batch_size = prompt_embeds.shape[0]
996
1145
 
997
1146
  device = self._execution_device
998
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
999
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1000
- # corresponds to doing no classifier free guidance.
1001
- do_classifier_free_guidance = guidance_scale > 1.0
1002
1147
 
1003
1148
  if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1004
1149
  controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
@@ -1010,9 +1155,9 @@ class StableDiffusionXLControlNetPipeline(
1010
1155
  )
1011
1156
  guess_mode = guess_mode or global_pool_conditions
1012
1157
 
1013
- # 3. Encode input prompt
1158
+ # 3.1 Encode input prompt
1014
1159
  text_encoder_lora_scale = (
1015
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1160
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1016
1161
  )
1017
1162
  (
1018
1163
  prompt_embeds,
@@ -1024,7 +1169,7 @@ class StableDiffusionXLControlNetPipeline(
1024
1169
  prompt_2,
1025
1170
  device,
1026
1171
  num_images_per_prompt,
1027
- do_classifier_free_guidance,
1172
+ self.do_classifier_free_guidance,
1028
1173
  negative_prompt,
1029
1174
  negative_prompt_2,
1030
1175
  prompt_embeds=prompt_embeds,
@@ -1032,9 +1177,18 @@ class StableDiffusionXLControlNetPipeline(
1032
1177
  pooled_prompt_embeds=pooled_prompt_embeds,
1033
1178
  negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
1034
1179
  lora_scale=text_encoder_lora_scale,
1035
- clip_skip=clip_skip,
1180
+ clip_skip=self.clip_skip,
1036
1181
  )
1037
1182
 
1183
+ # 3.2 Encode ip_adapter_image
1184
+ if ip_adapter_image is not None:
1185
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1186
+ image_embeds, negative_image_embeds = self.encode_image(
1187
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
1188
+ )
1189
+ if self.do_classifier_free_guidance:
1190
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1191
+
1038
1192
  # 4. Prepare image
1039
1193
  if isinstance(controlnet, ControlNetModel):
1040
1194
  image = self.prepare_image(
@@ -1045,7 +1199,7 @@ class StableDiffusionXLControlNetPipeline(
1045
1199
  num_images_per_prompt=num_images_per_prompt,
1046
1200
  device=device,
1047
1201
  dtype=controlnet.dtype,
1048
- do_classifier_free_guidance=do_classifier_free_guidance,
1202
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1049
1203
  guess_mode=guess_mode,
1050
1204
  )
1051
1205
  height, width = image.shape[-2:]
@@ -1061,7 +1215,7 @@ class StableDiffusionXLControlNetPipeline(
1061
1215
  num_images_per_prompt=num_images_per_prompt,
1062
1216
  device=device,
1063
1217
  dtype=controlnet.dtype,
1064
- do_classifier_free_guidance=do_classifier_free_guidance,
1218
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1065
1219
  guess_mode=guess_mode,
1066
1220
  )
1067
1221
 
@@ -1075,6 +1229,7 @@ class StableDiffusionXLControlNetPipeline(
1075
1229
  # 5. Prepare timesteps
1076
1230
  self.scheduler.set_timesteps(num_inference_steps, device=device)
1077
1231
  timesteps = self.scheduler.timesteps
1232
+ self._num_timesteps = len(timesteps)
1078
1233
 
1079
1234
  # 6. Prepare latent variables
1080
1235
  num_channels_latents = self.unet.config.in_channels
@@ -1089,6 +1244,14 @@ class StableDiffusionXLControlNetPipeline(
1089
1244
  latents,
1090
1245
  )
1091
1246
 
1247
+ # 6.5 Optionally get Guidance Scale Embedding
1248
+ timestep_cond = None
1249
+ if self.unet.config.time_cond_proj_dim is not None:
1250
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1251
+ timestep_cond = self.get_guidance_scale_embedding(
1252
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1253
+ ).to(device=device, dtype=latents.dtype)
1254
+
1092
1255
  # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1093
1256
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1094
1257
 
@@ -1133,7 +1296,7 @@ class StableDiffusionXLControlNetPipeline(
1133
1296
  else:
1134
1297
  negative_add_time_ids = add_time_ids
1135
1298
 
1136
- if do_classifier_free_guidance:
1299
+ if self.do_classifier_free_guidance:
1137
1300
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1138
1301
  add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1139
1302
  add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
@@ -1154,13 +1317,13 @@ class StableDiffusionXLControlNetPipeline(
1154
1317
  if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1155
1318
  torch._inductor.cudagraph_mark_step_begin()
1156
1319
  # expand the latents if we are doing classifier free guidance
1157
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1320
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1158
1321
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1159
1322
 
1160
1323
  added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1161
1324
 
1162
1325
  # controlnet(s) inference
1163
- if guess_mode and do_classifier_free_guidance:
1326
+ if guess_mode and self.do_classifier_free_guidance:
1164
1327
  # Infer ControlNet only for the conditional batch.
1165
1328
  control_model_input = latents
1166
1329
  control_model_input = self.scheduler.scale_model_input(control_model_input, t)
@@ -1193,19 +1356,23 @@ class StableDiffusionXLControlNetPipeline(
1193
1356
  return_dict=False,
1194
1357
  )
1195
1358
 
1196
- if guess_mode and do_classifier_free_guidance:
1359
+ if guess_mode and self.do_classifier_free_guidance:
1197
1360
  # Infered ControlNet only for the conditional batch.
1198
1361
  # To apply the output of ControlNet to both the unconditional and conditional batches,
1199
1362
  # add 0 to the unconditional batch to keep it unchanged.
1200
1363
  down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1201
1364
  mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1202
1365
 
1366
+ if ip_adapter_image is not None:
1367
+ added_cond_kwargs["image_embeds"] = image_embeds
1368
+
1203
1369
  # predict the noise residual
1204
1370
  noise_pred = self.unet(
1205
1371
  latent_model_input,
1206
1372
  t,
1207
1373
  encoder_hidden_states=prompt_embeds,
1208
- cross_attention_kwargs=cross_attention_kwargs,
1374
+ timestep_cond=timestep_cond,
1375
+ cross_attention_kwargs=self.cross_attention_kwargs,
1209
1376
  down_block_additional_residuals=down_block_res_samples,
1210
1377
  mid_block_additional_residual=mid_block_res_sample,
1211
1378
  added_cond_kwargs=added_cond_kwargs,
@@ -1213,13 +1380,23 @@ class StableDiffusionXLControlNetPipeline(
1213
1380
  )[0]
1214
1381
 
1215
1382
  # perform guidance
1216
- if do_classifier_free_guidance:
1383
+ if self.do_classifier_free_guidance:
1217
1384
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1218
1385
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1219
1386
 
1220
1387
  # compute the previous noisy sample x_t -> x_t-1
1221
1388
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1222
1389
 
1390
+ if callback_on_step_end is not None:
1391
+ callback_kwargs = {}
1392
+ for k in callback_on_step_end_tensor_inputs:
1393
+ callback_kwargs[k] = locals()[k]
1394
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1395
+
1396
+ latents = callback_outputs.pop("latents", latents)
1397
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1398
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1399
+
1223
1400
  # call the callback, if provided
1224
1401
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1225
1402
  progress_bar.update()