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,11 +20,11 @@ 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 CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
23
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
24
24
 
25
25
  from ...image_processor import PipelineImageInput, VaeImageProcessor
26
- from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
27
- from ...models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
26
+ from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
27
+ from ...models import AutoencoderKL, ControlNetModel, ImageProjection, UNet2DConditionModel
28
28
  from ...models.lora import adjust_lora_scale_text_encoder
29
29
  from ...schedulers import KarrasDiffusionSchedulers
30
30
  from ...utils import (
@@ -91,8 +91,53 @@ EXAMPLE_DOC_STRING = """
91
91
  """
92
92
 
93
93
 
94
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
95
+ def retrieve_timesteps(
96
+ scheduler,
97
+ num_inference_steps: Optional[int] = None,
98
+ device: Optional[Union[str, torch.device]] = None,
99
+ timesteps: Optional[List[int]] = None,
100
+ **kwargs,
101
+ ):
102
+ """
103
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
104
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
105
+
106
+ Args:
107
+ scheduler (`SchedulerMixin`):
108
+ The scheduler to get timesteps from.
109
+ num_inference_steps (`int`):
110
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
111
+ `timesteps` must be `None`.
112
+ device (`str` or `torch.device`, *optional*):
113
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
114
+ timesteps (`List[int]`, *optional*):
115
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
116
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
117
+ must be `None`.
118
+
119
+ Returns:
120
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
121
+ second element is the number of inference steps.
122
+ """
123
+ if timesteps is not None:
124
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
125
+ if not accepts_timesteps:
126
+ raise ValueError(
127
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
128
+ f" timestep schedules. Please check whether you are using the correct scheduler."
129
+ )
130
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
131
+ timesteps = scheduler.timesteps
132
+ num_inference_steps = len(timesteps)
133
+ else:
134
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
135
+ timesteps = scheduler.timesteps
136
+ return timesteps, num_inference_steps
137
+
138
+
94
139
  class StableDiffusionControlNetPipeline(
95
- DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
140
+ DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
96
141
  ):
97
142
  r"""
98
143
  Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance.
@@ -102,6 +147,10 @@ class StableDiffusionControlNetPipeline(
102
147
 
103
148
  The pipeline also inherits the following loading methods:
104
149
  - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
150
+ - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
151
+ - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
152
+ - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
153
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
105
154
 
106
155
  Args:
107
156
  vae ([`AutoencoderKL`]):
@@ -126,9 +175,11 @@ class StableDiffusionControlNetPipeline(
126
175
  feature_extractor ([`~transformers.CLIPImageProcessor`]):
127
176
  A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
128
177
  """
129
- model_cpu_offload_seq = "text_encoder->unet->vae"
130
- _optional_components = ["safety_checker", "feature_extractor"]
178
+
179
+ model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
180
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
131
181
  _exclude_from_cpu_offload = ["safety_checker"]
182
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
132
183
 
133
184
  def __init__(
134
185
  self,
@@ -140,6 +191,7 @@ class StableDiffusionControlNetPipeline(
140
191
  scheduler: KarrasDiffusionSchedulers,
141
192
  safety_checker: StableDiffusionSafetyChecker,
142
193
  feature_extractor: CLIPImageProcessor,
194
+ image_encoder: CLIPVisionModelWithProjection = None,
143
195
  requires_safety_checker: bool = True,
144
196
  ):
145
197
  super().__init__()
@@ -172,6 +224,7 @@ class StableDiffusionControlNetPipeline(
172
224
  scheduler=scheduler,
173
225
  safety_checker=safety_checker,
174
226
  feature_extractor=feature_extractor,
227
+ image_encoder=image_encoder,
175
228
  )
176
229
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
177
230
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
@@ -428,6 +481,31 @@ class StableDiffusionControlNetPipeline(
428
481
 
429
482
  return prompt_embeds, negative_prompt_embeds
430
483
 
484
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
485
+ def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
486
+ dtype = next(self.image_encoder.parameters()).dtype
487
+
488
+ if not isinstance(image, torch.Tensor):
489
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
490
+
491
+ image = image.to(device=device, dtype=dtype)
492
+ if output_hidden_states:
493
+ image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
494
+ image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
495
+ uncond_image_enc_hidden_states = self.image_encoder(
496
+ torch.zeros_like(image), output_hidden_states=True
497
+ ).hidden_states[-2]
498
+ uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
499
+ num_images_per_prompt, dim=0
500
+ )
501
+ return image_enc_hidden_states, uncond_image_enc_hidden_states
502
+ else:
503
+ image_embeds = self.image_encoder(image).image_embeds
504
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
505
+ uncond_image_embeds = torch.zeros_like(image_embeds)
506
+
507
+ return image_embeds, uncond_image_embeds
508
+
431
509
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
432
510
  def run_safety_checker(self, image, device, dtype):
433
511
  if self.safety_checker is None:
@@ -484,15 +562,21 @@ class StableDiffusionControlNetPipeline(
484
562
  controlnet_conditioning_scale=1.0,
485
563
  control_guidance_start=0.0,
486
564
  control_guidance_end=1.0,
565
+ callback_on_step_end_tensor_inputs=None,
487
566
  ):
488
- if (callback_steps is None) or (
489
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
490
- ):
567
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
491
568
  raise ValueError(
492
569
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
493
570
  f" {type(callback_steps)}."
494
571
  )
495
572
 
573
+ if callback_on_step_end_tensor_inputs is not None and not all(
574
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
575
+ ):
576
+ raise ValueError(
577
+ 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]}"
578
+ )
579
+
496
580
  if prompt is not None and prompt_embeds is not None:
497
581
  raise ValueError(
498
582
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
@@ -549,7 +633,7 @@ class StableDiffusionControlNetPipeline(
549
633
  # When `image` is a nested list:
550
634
  # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
551
635
  elif any(isinstance(i, list) for i in image):
552
- raise ValueError("A single batch of multiple conditionings are supported at the moment.")
636
+ raise ValueError("A single batch of multiple conditionings is not supported at the moment.")
553
637
  elif len(image) != len(self.controlnet.nets):
554
638
  raise ValueError(
555
639
  f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
@@ -575,7 +659,7 @@ class StableDiffusionControlNetPipeline(
575
659
  ):
576
660
  if isinstance(controlnet_conditioning_scale, list):
577
661
  if any(isinstance(i, list) for i in controlnet_conditioning_scale):
578
- raise ValueError("A single batch of multiple conditionings are supported at the moment.")
662
+ raise ValueError("A single batch of multiple conditionings is not supported at the moment.")
579
663
  elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
580
664
  self.controlnet.nets
581
665
  ):
@@ -726,6 +810,58 @@ class StableDiffusionControlNetPipeline(
726
810
  """Disables the FreeU mechanism if enabled."""
727
811
  self.unet.disable_freeu()
728
812
 
813
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
814
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
815
+ """
816
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
817
+
818
+ Args:
819
+ timesteps (`torch.Tensor`):
820
+ generate embedding vectors at these timesteps
821
+ embedding_dim (`int`, *optional*, defaults to 512):
822
+ dimension of the embeddings to generate
823
+ dtype:
824
+ data type of the generated embeddings
825
+
826
+ Returns:
827
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
828
+ """
829
+ assert len(w.shape) == 1
830
+ w = w * 1000.0
831
+
832
+ half_dim = embedding_dim // 2
833
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
834
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
835
+ emb = w.to(dtype)[:, None] * emb[None, :]
836
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
837
+ if embedding_dim % 2 == 1: # zero pad
838
+ emb = torch.nn.functional.pad(emb, (0, 1))
839
+ assert emb.shape == (w.shape[0], embedding_dim)
840
+ return emb
841
+
842
+ @property
843
+ def guidance_scale(self):
844
+ return self._guidance_scale
845
+
846
+ @property
847
+ def clip_skip(self):
848
+ return self._clip_skip
849
+
850
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
851
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
852
+ # corresponds to doing no classifier free guidance.
853
+ @property
854
+ def do_classifier_free_guidance(self):
855
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
856
+
857
+ @property
858
+ def cross_attention_kwargs(self):
859
+ return self._cross_attention_kwargs
860
+
861
+ @property
862
+ def num_timesteps(self):
863
+ return self._num_timesteps
864
+
729
865
  @torch.no_grad()
730
866
  @replace_example_docstring(EXAMPLE_DOC_STRING)
731
867
  def __call__(
@@ -735,6 +871,7 @@ class StableDiffusionControlNetPipeline(
735
871
  height: Optional[int] = None,
736
872
  width: Optional[int] = None,
737
873
  num_inference_steps: int = 50,
874
+ timesteps: List[int] = None,
738
875
  guidance_scale: float = 7.5,
739
876
  negative_prompt: Optional[Union[str, List[str]]] = None,
740
877
  num_images_per_prompt: Optional[int] = 1,
@@ -743,16 +880,18 @@ class StableDiffusionControlNetPipeline(
743
880
  latents: Optional[torch.FloatTensor] = None,
744
881
  prompt_embeds: Optional[torch.FloatTensor] = None,
745
882
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
883
+ ip_adapter_image: Optional[PipelineImageInput] = None,
746
884
  output_type: Optional[str] = "pil",
747
885
  return_dict: bool = True,
748
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
749
- callback_steps: int = 1,
750
886
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
751
887
  controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
752
888
  guess_mode: bool = False,
753
889
  control_guidance_start: Union[float, List[float]] = 0.0,
754
890
  control_guidance_end: Union[float, List[float]] = 1.0,
755
891
  clip_skip: Optional[int] = None,
892
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
893
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
894
+ **kwargs,
756
895
  ):
757
896
  r"""
758
897
  The call function to the pipeline for generation.
@@ -775,6 +914,10 @@ class StableDiffusionControlNetPipeline(
775
914
  num_inference_steps (`int`, *optional*, defaults to 50):
776
915
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
777
916
  expense of slower inference.
917
+ timesteps (`List[int]`, *optional*):
918
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
919
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
920
+ passed will be used. Must be in descending order.
778
921
  guidance_scale (`float`, *optional*, defaults to 7.5):
779
922
  A higher guidance scale value encourages the model to generate images closely linked to the text
780
923
  `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
@@ -799,6 +942,7 @@ class StableDiffusionControlNetPipeline(
799
942
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
800
943
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
801
944
  not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
945
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
802
946
  output_type (`str`, *optional*, defaults to `"pil"`):
803
947
  The output format of the generated image. Choose between `PIL.Image` or `np.array`.
804
948
  return_dict (`bool`, *optional*, defaults to `True`):
@@ -827,6 +971,15 @@ class StableDiffusionControlNetPipeline(
827
971
  clip_skip (`int`, *optional*):
828
972
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
829
973
  the output of the pre-final layer will be used for computing the prompt embeddings.
974
+ callback_on_step_end (`Callable`, *optional*):
975
+ A function that calls at the end of each denoising steps during the inference. The function is called
976
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
977
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
978
+ `callback_on_step_end_tensor_inputs`.
979
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
980
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
981
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
982
+ `._callback_tensor_inputs` attribute of your pipeine class.
830
983
 
831
984
  Examples:
832
985
 
@@ -837,6 +990,23 @@ class StableDiffusionControlNetPipeline(
837
990
  second element is a list of `bool`s indicating whether the corresponding generated image contains
838
991
  "not-safe-for-work" (nsfw) content.
839
992
  """
993
+
994
+ callback = kwargs.pop("callback", None)
995
+ callback_steps = kwargs.pop("callback_steps", None)
996
+
997
+ if callback is not None:
998
+ deprecate(
999
+ "callback",
1000
+ "1.0.0",
1001
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1002
+ )
1003
+ if callback_steps is not None:
1004
+ deprecate(
1005
+ "callback_steps",
1006
+ "1.0.0",
1007
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1008
+ )
1009
+
840
1010
  controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
841
1011
 
842
1012
  # align format for control guidance
@@ -846,9 +1016,10 @@ class StableDiffusionControlNetPipeline(
846
1016
  control_guidance_end = len(control_guidance_start) * [control_guidance_end]
847
1017
  elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
848
1018
  mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
849
- control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
850
- control_guidance_end
851
- ]
1019
+ control_guidance_start, control_guidance_end = (
1020
+ mult * [control_guidance_start],
1021
+ mult * [control_guidance_end],
1022
+ )
852
1023
 
853
1024
  # 1. Check inputs. Raise error if not correct
854
1025
  self.check_inputs(
@@ -861,8 +1032,13 @@ class StableDiffusionControlNetPipeline(
861
1032
  controlnet_conditioning_scale,
862
1033
  control_guidance_start,
863
1034
  control_guidance_end,
1035
+ callback_on_step_end_tensor_inputs,
864
1036
  )
865
1037
 
1038
+ self._guidance_scale = guidance_scale
1039
+ self._clip_skip = clip_skip
1040
+ self._cross_attention_kwargs = cross_attention_kwargs
1041
+
866
1042
  # 2. Define call parameters
867
1043
  if prompt is not None and isinstance(prompt, str):
868
1044
  batch_size = 1
@@ -872,10 +1048,6 @@ class StableDiffusionControlNetPipeline(
872
1048
  batch_size = prompt_embeds.shape[0]
873
1049
 
874
1050
  device = self._execution_device
875
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
876
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
877
- # corresponds to doing no classifier free guidance.
878
- do_classifier_free_guidance = guidance_scale > 1.0
879
1051
 
880
1052
  if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
881
1053
  controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
@@ -889,25 +1061,33 @@ class StableDiffusionControlNetPipeline(
889
1061
 
890
1062
  # 3. Encode input prompt
891
1063
  text_encoder_lora_scale = (
892
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1064
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
893
1065
  )
894
1066
  prompt_embeds, negative_prompt_embeds = self.encode_prompt(
895
1067
  prompt,
896
1068
  device,
897
1069
  num_images_per_prompt,
898
- do_classifier_free_guidance,
1070
+ self.do_classifier_free_guidance,
899
1071
  negative_prompt,
900
1072
  prompt_embeds=prompt_embeds,
901
1073
  negative_prompt_embeds=negative_prompt_embeds,
902
1074
  lora_scale=text_encoder_lora_scale,
903
- clip_skip=clip_skip,
1075
+ clip_skip=self.clip_skip,
904
1076
  )
905
1077
  # For classifier free guidance, we need to do two forward passes.
906
1078
  # Here we concatenate the unconditional and text embeddings into a single batch
907
1079
  # to avoid doing two forward passes
908
- if do_classifier_free_guidance:
1080
+ if self.do_classifier_free_guidance:
909
1081
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
910
1082
 
1083
+ if ip_adapter_image is not None:
1084
+ output_hidden_state = False if isinstance(self.unet.encoder_hid_proj, ImageProjection) else True
1085
+ image_embeds, negative_image_embeds = self.encode_image(
1086
+ ip_adapter_image, device, num_images_per_prompt, output_hidden_state
1087
+ )
1088
+ if self.do_classifier_free_guidance:
1089
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1090
+
911
1091
  # 4. Prepare image
912
1092
  if isinstance(controlnet, ControlNetModel):
913
1093
  image = self.prepare_image(
@@ -918,7 +1098,7 @@ class StableDiffusionControlNetPipeline(
918
1098
  num_images_per_prompt=num_images_per_prompt,
919
1099
  device=device,
920
1100
  dtype=controlnet.dtype,
921
- do_classifier_free_guidance=do_classifier_free_guidance,
1101
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
922
1102
  guess_mode=guess_mode,
923
1103
  )
924
1104
  height, width = image.shape[-2:]
@@ -934,7 +1114,7 @@ class StableDiffusionControlNetPipeline(
934
1114
  num_images_per_prompt=num_images_per_prompt,
935
1115
  device=device,
936
1116
  dtype=controlnet.dtype,
937
- do_classifier_free_guidance=do_classifier_free_guidance,
1117
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
938
1118
  guess_mode=guess_mode,
939
1119
  )
940
1120
 
@@ -946,8 +1126,8 @@ class StableDiffusionControlNetPipeline(
946
1126
  assert False
947
1127
 
948
1128
  # 5. Prepare timesteps
949
- self.scheduler.set_timesteps(num_inference_steps, device=device)
950
- timesteps = self.scheduler.timesteps
1129
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1130
+ self._num_timesteps = len(timesteps)
951
1131
 
952
1132
  # 6. Prepare latent variables
953
1133
  num_channels_latents = self.unet.config.in_channels
@@ -962,10 +1142,21 @@ class StableDiffusionControlNetPipeline(
962
1142
  latents,
963
1143
  )
964
1144
 
1145
+ # 6.5 Optionally get Guidance Scale Embedding
1146
+ timestep_cond = None
1147
+ if self.unet.config.time_cond_proj_dim is not None:
1148
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1149
+ timestep_cond = self.get_guidance_scale_embedding(
1150
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1151
+ ).to(device=device, dtype=latents.dtype)
1152
+
965
1153
  # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
966
1154
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
967
1155
 
968
- # 7.1 Create tensor stating which controlnets to keep
1156
+ # 7.1 Add image embeds for IP-Adapter
1157
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1158
+
1159
+ # 7.2 Create tensor stating which controlnets to keep
969
1160
  controlnet_keep = []
970
1161
  for i in range(len(timesteps)):
971
1162
  keeps = [
@@ -986,11 +1177,11 @@ class StableDiffusionControlNetPipeline(
986
1177
  if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
987
1178
  torch._inductor.cudagraph_mark_step_begin()
988
1179
  # expand the latents if we are doing classifier free guidance
989
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1180
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
990
1181
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
991
1182
 
992
1183
  # controlnet(s) inference
993
- if guess_mode and do_classifier_free_guidance:
1184
+ if guess_mode and self.do_classifier_free_guidance:
994
1185
  # Infer ControlNet only for the conditional batch.
995
1186
  control_model_input = latents
996
1187
  control_model_input = self.scheduler.scale_model_input(control_model_input, t)
@@ -1017,7 +1208,7 @@ class StableDiffusionControlNetPipeline(
1017
1208
  return_dict=False,
1018
1209
  )
1019
1210
 
1020
- if guess_mode and do_classifier_free_guidance:
1211
+ if guess_mode and self.do_classifier_free_guidance:
1021
1212
  # Infered ControlNet only for the conditional batch.
1022
1213
  # To apply the output of ControlNet to both the unconditional and conditional batches,
1023
1214
  # add 0 to the unconditional batch to keep it unchanged.
@@ -1029,20 +1220,32 @@ class StableDiffusionControlNetPipeline(
1029
1220
  latent_model_input,
1030
1221
  t,
1031
1222
  encoder_hidden_states=prompt_embeds,
1032
- cross_attention_kwargs=cross_attention_kwargs,
1223
+ timestep_cond=timestep_cond,
1224
+ cross_attention_kwargs=self.cross_attention_kwargs,
1033
1225
  down_block_additional_residuals=down_block_res_samples,
1034
1226
  mid_block_additional_residual=mid_block_res_sample,
1227
+ added_cond_kwargs=added_cond_kwargs,
1035
1228
  return_dict=False,
1036
1229
  )[0]
1037
1230
 
1038
1231
  # perform guidance
1039
- if do_classifier_free_guidance:
1232
+ if self.do_classifier_free_guidance:
1040
1233
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1041
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1234
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1042
1235
 
1043
1236
  # compute the previous noisy sample x_t -> x_t-1
1044
1237
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1045
1238
 
1239
+ if callback_on_step_end is not None:
1240
+ callback_kwargs = {}
1241
+ for k in callback_on_step_end_tensor_inputs:
1242
+ callback_kwargs[k] = locals()[k]
1243
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1244
+
1245
+ latents = callback_outputs.pop("latents", latents)
1246
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1247
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1248
+
1046
1249
  # call the callback, if provided
1047
1250
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1048
1251
  progress_bar.update()