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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (176) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +0 -1
  4. diffusers/dependency_versions_table.py +4 -5
  5. diffusers/image_processor.py +186 -14
  6. diffusers/loaders/__init__.py +82 -0
  7. diffusers/loaders/ip_adapter.py +157 -0
  8. diffusers/loaders/lora.py +1415 -0
  9. diffusers/loaders/lora_conversion_utils.py +284 -0
  10. diffusers/loaders/single_file.py +631 -0
  11. diffusers/loaders/textual_inversion.py +459 -0
  12. diffusers/loaders/unet.py +735 -0
  13. diffusers/loaders/utils.py +59 -0
  14. diffusers/models/__init__.py +12 -1
  15. diffusers/models/attention.py +165 -14
  16. diffusers/models/attention_flax.py +9 -1
  17. diffusers/models/attention_processor.py +286 -1
  18. diffusers/models/autoencoder_asym_kl.py +14 -9
  19. diffusers/models/autoencoder_kl.py +3 -18
  20. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  21. diffusers/models/autoencoder_tiny.py +20 -24
  22. diffusers/models/consistency_decoder_vae.py +37 -30
  23. diffusers/models/controlnet.py +59 -39
  24. diffusers/models/controlnet_flax.py +19 -18
  25. diffusers/models/embeddings_flax.py +2 -0
  26. diffusers/models/lora.py +131 -1
  27. diffusers/models/modeling_flax_utils.py +2 -1
  28. diffusers/models/modeling_outputs.py +17 -0
  29. diffusers/models/modeling_utils.py +27 -19
  30. diffusers/models/normalization.py +2 -2
  31. diffusers/models/resnet.py +390 -59
  32. diffusers/models/transformer_2d.py +20 -3
  33. diffusers/models/transformer_temporal.py +183 -1
  34. diffusers/models/unet_2d_blocks_flax.py +5 -0
  35. diffusers/models/unet_2d_condition.py +9 -0
  36. diffusers/models/unet_2d_condition_flax.py +13 -13
  37. diffusers/models/unet_3d_blocks.py +957 -173
  38. diffusers/models/unet_3d_condition.py +16 -8
  39. diffusers/models/unet_kandi3.py +589 -0
  40. diffusers/models/unet_motion_model.py +48 -33
  41. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  42. diffusers/models/vae.py +63 -13
  43. diffusers/models/vae_flax.py +7 -0
  44. diffusers/models/vq_model.py +3 -1
  45. diffusers/optimization.py +16 -9
  46. diffusers/pipelines/__init__.py +65 -12
  47. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion.py +93 -23
  48. diffusers/pipelines/alt_diffusion/pipeline_alt_diffusion_img2img.py +97 -25
  49. diffusers/pipelines/animatediff/pipeline_animatediff.py +34 -4
  50. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  51. diffusers/pipelines/auto_pipeline.py +6 -0
  52. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  53. diffusers/pipelines/controlnet/pipeline_controlnet.py +217 -31
  54. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +101 -32
  55. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +136 -39
  56. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +119 -37
  57. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +196 -35
  58. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +102 -31
  59. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  60. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  61. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  62. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  63. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  64. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  65. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  66. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  67. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  68. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  69. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  70. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  71. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  72. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  73. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  74. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  75. diffusers/pipelines/kandinsky3/kandinsky3_pipeline.py +452 -0
  76. diffusers/pipelines/kandinsky3/kandinsky3img2img_pipeline.py +460 -0
  77. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +65 -6
  78. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +55 -3
  79. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  80. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  81. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  82. diffusers/pipelines/pipeline_flax_utils.py +4 -2
  83. diffusers/pipelines/pipeline_utils.py +33 -13
  84. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +196 -36
  85. diffusers/pipelines/score_sde_ve/pipeline_score_sde_ve.py +1 -0
  86. diffusers/pipelines/spectrogram_diffusion/pipeline_spectrogram_diffusion.py +1 -0
  87. diffusers/pipelines/stable_diffusion/__init__.py +64 -21
  88. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +8 -3
  89. diffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +18 -2
  90. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  91. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  92. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  93. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +1 -0
  94. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +88 -9
  95. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_attend_and_excite.py +1 -0
  96. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  97. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py +1 -0
  98. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen.py +1 -0
  99. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_gligen_text_image.py +1 -0
  100. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  101. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +92 -9
  102. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +92 -9
  103. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint_legacy.py +1 -0
  104. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +17 -13
  105. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_k_diffusion.py +1 -0
  106. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +1 -0
  107. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_ldm3d.py +1 -0
  108. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_model_editing.py +1 -0
  109. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_panorama.py +1 -0
  110. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_paradigms.py +1 -0
  111. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py +1 -0
  112. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_sag.py +1 -0
  113. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +1 -0
  114. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +103 -8
  115. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +113 -8
  116. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +115 -9
  117. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +16 -12
  118. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  119. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +649 -0
  120. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  121. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +109 -14
  122. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  123. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +1 -0
  124. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +18 -3
  125. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +4 -2
  126. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +872 -0
  127. diffusers/pipelines/versatile_diffusion/modeling_text_unet.py +29 -40
  128. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_dual_guided.py +1 -0
  129. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_image_variation.py +1 -0
  130. diffusers/pipelines/versatile_diffusion/pipeline_versatile_diffusion_text_to_image.py +1 -0
  131. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  132. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  133. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  134. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  135. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +1 -1
  136. diffusers/schedulers/__init__.py +2 -4
  137. diffusers/schedulers/deprecated/__init__.py +50 -0
  138. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  139. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  140. diffusers/schedulers/scheduling_ddim.py +1 -3
  141. diffusers/schedulers/scheduling_ddim_inverse.py +1 -3
  142. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  143. diffusers/schedulers/scheduling_ddpm.py +1 -3
  144. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -3
  145. diffusers/schedulers/scheduling_deis_multistep.py +15 -5
  146. diffusers/schedulers/scheduling_dpmsolver_multistep.py +15 -5
  147. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +15 -5
  148. diffusers/schedulers/scheduling_dpmsolver_sde.py +1 -3
  149. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +15 -5
  150. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +1 -3
  151. diffusers/schedulers/scheduling_euler_discrete.py +40 -13
  152. diffusers/schedulers/scheduling_heun_discrete.py +15 -5
  153. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +15 -5
  154. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +15 -5
  155. diffusers/schedulers/scheduling_lcm.py +123 -29
  156. diffusers/schedulers/scheduling_lms_discrete.py +1 -3
  157. diffusers/schedulers/scheduling_pndm.py +1 -3
  158. diffusers/schedulers/scheduling_repaint.py +1 -3
  159. diffusers/schedulers/scheduling_unipc_multistep.py +15 -5
  160. diffusers/utils/__init__.py +1 -0
  161. diffusers/utils/constants.py +8 -7
  162. diffusers/utils/dummy_pt_objects.py +45 -0
  163. diffusers/utils/dummy_torch_and_transformers_objects.py +60 -0
  164. diffusers/utils/dynamic_modules_utils.py +4 -4
  165. diffusers/utils/export_utils.py +8 -3
  166. diffusers/utils/logging.py +10 -10
  167. diffusers/utils/outputs.py +5 -5
  168. diffusers/utils/peft_utils.py +88 -44
  169. diffusers/utils/torch_utils.py +2 -2
  170. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/METADATA +38 -22
  171. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/RECORD +175 -157
  172. diffusers/loaders.py +0 -3336
  173. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  174. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/WHEEL +0 -0
  175. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +0 -0
  176. {diffusers-0.23.1.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -20,10 +20,10 @@ 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
26
+ from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
27
27
  from ...models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
28
28
  from ...models.lora import adjust_lora_scale_text_encoder
29
29
  from ...schedulers import KarrasDiffusionSchedulers
@@ -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,7 @@ 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.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
105
151
 
106
152
  Args:
107
153
  vae ([`AutoencoderKL`]):
@@ -126,9 +172,11 @@ class StableDiffusionControlNetPipeline(
126
172
  feature_extractor ([`~transformers.CLIPImageProcessor`]):
127
173
  A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
128
174
  """
175
+
129
176
  model_cpu_offload_seq = "text_encoder->unet->vae"
130
- _optional_components = ["safety_checker", "feature_extractor"]
177
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
131
178
  _exclude_from_cpu_offload = ["safety_checker"]
179
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
132
180
 
133
181
  def __init__(
134
182
  self,
@@ -140,6 +188,7 @@ class StableDiffusionControlNetPipeline(
140
188
  scheduler: KarrasDiffusionSchedulers,
141
189
  safety_checker: StableDiffusionSafetyChecker,
142
190
  feature_extractor: CLIPImageProcessor,
191
+ image_encoder: CLIPVisionModelWithProjection = None,
143
192
  requires_safety_checker: bool = True,
144
193
  ):
145
194
  super().__init__()
@@ -172,6 +221,7 @@ class StableDiffusionControlNetPipeline(
172
221
  scheduler=scheduler,
173
222
  safety_checker=safety_checker,
174
223
  feature_extractor=feature_extractor,
224
+ image_encoder=image_encoder,
175
225
  )
176
226
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
177
227
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
@@ -428,6 +478,20 @@ class StableDiffusionControlNetPipeline(
428
478
 
429
479
  return prompt_embeds, negative_prompt_embeds
430
480
 
481
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
482
+ def encode_image(self, image, device, num_images_per_prompt):
483
+ dtype = next(self.image_encoder.parameters()).dtype
484
+
485
+ if not isinstance(image, torch.Tensor):
486
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
487
+
488
+ image = image.to(device=device, dtype=dtype)
489
+ image_embeds = self.image_encoder(image).image_embeds
490
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
491
+
492
+ uncond_image_embeds = torch.zeros_like(image_embeds)
493
+ return image_embeds, uncond_image_embeds
494
+
431
495
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
432
496
  def run_safety_checker(self, image, device, dtype):
433
497
  if self.safety_checker is None:
@@ -484,15 +548,21 @@ class StableDiffusionControlNetPipeline(
484
548
  controlnet_conditioning_scale=1.0,
485
549
  control_guidance_start=0.0,
486
550
  control_guidance_end=1.0,
551
+ callback_on_step_end_tensor_inputs=None,
487
552
  ):
488
- if (callback_steps is None) or (
489
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
490
- ):
553
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
491
554
  raise ValueError(
492
555
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
493
556
  f" {type(callback_steps)}."
494
557
  )
495
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
+
496
566
  if prompt is not None and prompt_embeds is not None:
497
567
  raise ValueError(
498
568
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
@@ -726,6 +796,58 @@ class StableDiffusionControlNetPipeline(
726
796
  """Disables the FreeU mechanism if enabled."""
727
797
  self.unet.disable_freeu()
728
798
 
799
+ # Copied from diffusers.pipelines.latent_consistency_models.pipeline_latent_consistency_text2img.LatentConsistencyModelPipeline.get_guidance_scale_embedding
800
+ def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
801
+ """
802
+ See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
803
+
804
+ Args:
805
+ timesteps (`torch.Tensor`):
806
+ generate embedding vectors at these timesteps
807
+ embedding_dim (`int`, *optional*, defaults to 512):
808
+ dimension of the embeddings to generate
809
+ dtype:
810
+ data type of the generated embeddings
811
+
812
+ Returns:
813
+ `torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
814
+ """
815
+ assert len(w.shape) == 1
816
+ w = w * 1000.0
817
+
818
+ half_dim = embedding_dim // 2
819
+ emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
820
+ emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
821
+ emb = w.to(dtype)[:, None] * emb[None, :]
822
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
823
+ if embedding_dim % 2 == 1: # zero pad
824
+ emb = torch.nn.functional.pad(emb, (0, 1))
825
+ assert emb.shape == (w.shape[0], embedding_dim)
826
+ return emb
827
+
828
+ @property
829
+ def guidance_scale(self):
830
+ return self._guidance_scale
831
+
832
+ @property
833
+ def clip_skip(self):
834
+ return self._clip_skip
835
+
836
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
837
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
838
+ # corresponds to doing no classifier free guidance.
839
+ @property
840
+ def do_classifier_free_guidance(self):
841
+ return self._guidance_scale > 1 and self.unet.config.time_cond_proj_dim is None
842
+
843
+ @property
844
+ def cross_attention_kwargs(self):
845
+ return self._cross_attention_kwargs
846
+
847
+ @property
848
+ def num_timesteps(self):
849
+ return self._num_timesteps
850
+
729
851
  @torch.no_grad()
730
852
  @replace_example_docstring(EXAMPLE_DOC_STRING)
731
853
  def __call__(
@@ -735,6 +857,7 @@ class StableDiffusionControlNetPipeline(
735
857
  height: Optional[int] = None,
736
858
  width: Optional[int] = None,
737
859
  num_inference_steps: int = 50,
860
+ timesteps: List[int] = None,
738
861
  guidance_scale: float = 7.5,
739
862
  negative_prompt: Optional[Union[str, List[str]]] = None,
740
863
  num_images_per_prompt: Optional[int] = 1,
@@ -743,16 +866,18 @@ class StableDiffusionControlNetPipeline(
743
866
  latents: Optional[torch.FloatTensor] = None,
744
867
  prompt_embeds: Optional[torch.FloatTensor] = None,
745
868
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
869
+ ip_adapter_image: Optional[PipelineImageInput] = None,
746
870
  output_type: Optional[str] = "pil",
747
871
  return_dict: bool = True,
748
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
749
- callback_steps: int = 1,
750
872
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
751
873
  controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
752
874
  guess_mode: bool = False,
753
875
  control_guidance_start: Union[float, List[float]] = 0.0,
754
876
  control_guidance_end: Union[float, List[float]] = 1.0,
755
877
  clip_skip: Optional[int] = None,
878
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
879
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
880
+ **kwargs,
756
881
  ):
757
882
  r"""
758
883
  The call function to the pipeline for generation.
@@ -775,6 +900,10 @@ class StableDiffusionControlNetPipeline(
775
900
  num_inference_steps (`int`, *optional*, defaults to 50):
776
901
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
777
902
  expense of slower inference.
903
+ timesteps (`List[int]`, *optional*):
904
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
905
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
906
+ passed will be used. Must be in descending order.
778
907
  guidance_scale (`float`, *optional*, defaults to 7.5):
779
908
  A higher guidance scale value encourages the model to generate images closely linked to the text
780
909
  `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
@@ -799,6 +928,7 @@ class StableDiffusionControlNetPipeline(
799
928
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
800
929
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
801
930
  not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
931
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
802
932
  output_type (`str`, *optional*, defaults to `"pil"`):
803
933
  The output format of the generated image. Choose between `PIL.Image` or `np.array`.
804
934
  return_dict (`bool`, *optional*, defaults to `True`):
@@ -827,6 +957,15 @@ class StableDiffusionControlNetPipeline(
827
957
  clip_skip (`int`, *optional*):
828
958
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
829
959
  the output of the pre-final layer will be used for computing the prompt embeddings.
960
+ callback_on_step_end (`Callable`, *optional*):
961
+ A function that calls at the end of each denoising steps during the inference. The function is called
962
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
963
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
964
+ `callback_on_step_end_tensor_inputs`.
965
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
966
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
967
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
968
+ `._callback_tensor_inputs` attribute of your pipeine class.
830
969
 
831
970
  Examples:
832
971
 
@@ -837,6 +976,23 @@ class StableDiffusionControlNetPipeline(
837
976
  second element is a list of `bool`s indicating whether the corresponding generated image contains
838
977
  "not-safe-for-work" (nsfw) content.
839
978
  """
979
+
980
+ callback = kwargs.pop("callback", None)
981
+ callback_steps = kwargs.pop("callback_steps", None)
982
+
983
+ if callback is not None:
984
+ deprecate(
985
+ "callback",
986
+ "1.0.0",
987
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
988
+ )
989
+ if callback_steps is not None:
990
+ deprecate(
991
+ "callback_steps",
992
+ "1.0.0",
993
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
994
+ )
995
+
840
996
  controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
841
997
 
842
998
  # align format for control guidance
@@ -846,9 +1002,10 @@ class StableDiffusionControlNetPipeline(
846
1002
  control_guidance_end = len(control_guidance_start) * [control_guidance_end]
847
1003
  elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
848
1004
  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
- ]
1005
+ control_guidance_start, control_guidance_end = (
1006
+ mult * [control_guidance_start],
1007
+ mult * [control_guidance_end],
1008
+ )
852
1009
 
853
1010
  # 1. Check inputs. Raise error if not correct
854
1011
  self.check_inputs(
@@ -861,8 +1018,13 @@ class StableDiffusionControlNetPipeline(
861
1018
  controlnet_conditioning_scale,
862
1019
  control_guidance_start,
863
1020
  control_guidance_end,
1021
+ callback_on_step_end_tensor_inputs,
864
1022
  )
865
1023
 
1024
+ self._guidance_scale = guidance_scale
1025
+ self._clip_skip = clip_skip
1026
+ self._cross_attention_kwargs = cross_attention_kwargs
1027
+
866
1028
  # 2. Define call parameters
867
1029
  if prompt is not None and isinstance(prompt, str):
868
1030
  batch_size = 1
@@ -872,10 +1034,6 @@ class StableDiffusionControlNetPipeline(
872
1034
  batch_size = prompt_embeds.shape[0]
873
1035
 
874
1036
  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
1037
 
880
1038
  if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
881
1039
  controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
@@ -889,25 +1047,30 @@ class StableDiffusionControlNetPipeline(
889
1047
 
890
1048
  # 3. Encode input prompt
891
1049
  text_encoder_lora_scale = (
892
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1050
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
893
1051
  )
894
1052
  prompt_embeds, negative_prompt_embeds = self.encode_prompt(
895
1053
  prompt,
896
1054
  device,
897
1055
  num_images_per_prompt,
898
- do_classifier_free_guidance,
1056
+ self.do_classifier_free_guidance,
899
1057
  negative_prompt,
900
1058
  prompt_embeds=prompt_embeds,
901
1059
  negative_prompt_embeds=negative_prompt_embeds,
902
1060
  lora_scale=text_encoder_lora_scale,
903
- clip_skip=clip_skip,
1061
+ clip_skip=self.clip_skip,
904
1062
  )
905
1063
  # For classifier free guidance, we need to do two forward passes.
906
1064
  # Here we concatenate the unconditional and text embeddings into a single batch
907
1065
  # to avoid doing two forward passes
908
- if do_classifier_free_guidance:
1066
+ if self.do_classifier_free_guidance:
909
1067
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
910
1068
 
1069
+ if ip_adapter_image is not None:
1070
+ image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_images_per_prompt)
1071
+ if self.do_classifier_free_guidance:
1072
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1073
+
911
1074
  # 4. Prepare image
912
1075
  if isinstance(controlnet, ControlNetModel):
913
1076
  image = self.prepare_image(
@@ -918,7 +1081,7 @@ class StableDiffusionControlNetPipeline(
918
1081
  num_images_per_prompt=num_images_per_prompt,
919
1082
  device=device,
920
1083
  dtype=controlnet.dtype,
921
- do_classifier_free_guidance=do_classifier_free_guidance,
1084
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
922
1085
  guess_mode=guess_mode,
923
1086
  )
924
1087
  height, width = image.shape[-2:]
@@ -934,7 +1097,7 @@ class StableDiffusionControlNetPipeline(
934
1097
  num_images_per_prompt=num_images_per_prompt,
935
1098
  device=device,
936
1099
  dtype=controlnet.dtype,
937
- do_classifier_free_guidance=do_classifier_free_guidance,
1100
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
938
1101
  guess_mode=guess_mode,
939
1102
  )
940
1103
 
@@ -946,8 +1109,8 @@ class StableDiffusionControlNetPipeline(
946
1109
  assert False
947
1110
 
948
1111
  # 5. Prepare timesteps
949
- self.scheduler.set_timesteps(num_inference_steps, device=device)
950
- timesteps = self.scheduler.timesteps
1112
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
1113
+ self._num_timesteps = len(timesteps)
951
1114
 
952
1115
  # 6. Prepare latent variables
953
1116
  num_channels_latents = self.unet.config.in_channels
@@ -962,10 +1125,21 @@ class StableDiffusionControlNetPipeline(
962
1125
  latents,
963
1126
  )
964
1127
 
1128
+ # 6.5 Optionally get Guidance Scale Embedding
1129
+ timestep_cond = None
1130
+ if self.unet.config.time_cond_proj_dim is not None:
1131
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
1132
+ timestep_cond = self.get_guidance_scale_embedding(
1133
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
1134
+ ).to(device=device, dtype=latents.dtype)
1135
+
965
1136
  # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
966
1137
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
967
1138
 
968
- # 7.1 Create tensor stating which controlnets to keep
1139
+ # 7.1 Add image embeds for IP-Adapter
1140
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1141
+
1142
+ # 7.2 Create tensor stating which controlnets to keep
969
1143
  controlnet_keep = []
970
1144
  for i in range(len(timesteps)):
971
1145
  keeps = [
@@ -986,11 +1160,11 @@ class StableDiffusionControlNetPipeline(
986
1160
  if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
987
1161
  torch._inductor.cudagraph_mark_step_begin()
988
1162
  # 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
1163
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
990
1164
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
991
1165
 
992
1166
  # controlnet(s) inference
993
- if guess_mode and do_classifier_free_guidance:
1167
+ if guess_mode and self.do_classifier_free_guidance:
994
1168
  # Infer ControlNet only for the conditional batch.
995
1169
  control_model_input = latents
996
1170
  control_model_input = self.scheduler.scale_model_input(control_model_input, t)
@@ -1017,7 +1191,7 @@ class StableDiffusionControlNetPipeline(
1017
1191
  return_dict=False,
1018
1192
  )
1019
1193
 
1020
- if guess_mode and do_classifier_free_guidance:
1194
+ if guess_mode and self.do_classifier_free_guidance:
1021
1195
  # Infered ControlNet only for the conditional batch.
1022
1196
  # To apply the output of ControlNet to both the unconditional and conditional batches,
1023
1197
  # add 0 to the unconditional batch to keep it unchanged.
@@ -1029,20 +1203,32 @@ class StableDiffusionControlNetPipeline(
1029
1203
  latent_model_input,
1030
1204
  t,
1031
1205
  encoder_hidden_states=prompt_embeds,
1032
- cross_attention_kwargs=cross_attention_kwargs,
1206
+ timestep_cond=timestep_cond,
1207
+ cross_attention_kwargs=self.cross_attention_kwargs,
1033
1208
  down_block_additional_residuals=down_block_res_samples,
1034
1209
  mid_block_additional_residual=mid_block_res_sample,
1210
+ added_cond_kwargs=added_cond_kwargs,
1035
1211
  return_dict=False,
1036
1212
  )[0]
1037
1213
 
1038
1214
  # perform guidance
1039
- if do_classifier_free_guidance:
1215
+ if self.do_classifier_free_guidance:
1040
1216
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1041
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1217
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
1042
1218
 
1043
1219
  # compute the previous noisy sample x_t -> x_t-1
1044
1220
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1045
1221
 
1222
+ if callback_on_step_end is not None:
1223
+ callback_kwargs = {}
1224
+ for k in callback_on_step_end_tensor_inputs:
1225
+ callback_kwargs[k] = locals()[k]
1226
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1227
+
1228
+ latents = callback_outputs.pop("latents", latents)
1229
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1230
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1231
+
1046
1232
  # call the callback, if provided
1047
1233
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1048
1234
  progress_bar.update()