diffusers 0.23.0__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 (177) hide show
  1. diffusers/__init__.py +16 -2
  2. diffusers/configuration_utils.py +1 -0
  3. diffusers/dependency_versions_check.py +1 -14
  4. diffusers/dependency_versions_table.py +5 -4
  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 +11 -6
  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/utils/versions.py +117 -0
  171. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/METADATA +83 -64
  172. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/RECORD +176 -157
  173. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/WHEEL +1 -1
  174. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/entry_points.txt +1 -0
  175. diffusers/loaders.py +0 -3336
  176. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/LICENSE +0 -0
  177. {diffusers-0.23.0.dist-info → diffusers-0.24.0.dist-info}/top_level.txt +0 -0
@@ -21,10 +21,10 @@ import numpy as np
21
21
  import PIL.Image
22
22
  import torch
23
23
  import torch.nn.functional as F
24
- from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
24
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
25
25
 
26
26
  from ...image_processor import PipelineImageInput, VaeImageProcessor
27
- from ...loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin
27
+ from ...loaders import FromSingleFileMixin, IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
28
28
  from ...models import AutoencoderKL, ControlNetModel, UNet2DConditionModel
29
29
  from ...models.lora import adjust_lora_scale_text_encoder
30
30
  from ...schedulers import KarrasDiffusionSchedulers
@@ -104,9 +104,13 @@ EXAMPLE_DOC_STRING = """
104
104
 
105
105
 
106
106
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
107
- def retrieve_latents(encoder_output, generator):
108
- if hasattr(encoder_output, "latent_dist"):
107
+ def retrieve_latents(
108
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
109
+ ):
110
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
109
111
  return encoder_output.latent_dist.sample(generator)
112
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
113
+ return encoder_output.latent_dist.mode()
110
114
  elif hasattr(encoder_output, "latents"):
111
115
  return encoder_output.latents
112
116
  else:
@@ -237,7 +241,7 @@ def prepare_mask_and_masked_image(image, mask, height, width, return_image=False
237
241
 
238
242
 
239
243
  class StableDiffusionControlNetInpaintPipeline(
240
- DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
244
+ DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, IPAdapterMixin, FromSingleFileMixin
241
245
  ):
242
246
  r"""
243
247
  Pipeline for image inpainting using Stable Diffusion with ControlNet guidance.
@@ -247,6 +251,7 @@ class StableDiffusionControlNetInpaintPipeline(
247
251
 
248
252
  The pipeline also inherits the following loading methods:
249
253
  - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
254
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
250
255
 
251
256
  <Tip>
252
257
 
@@ -282,9 +287,11 @@ class StableDiffusionControlNetInpaintPipeline(
282
287
  feature_extractor ([`~transformers.CLIPImageProcessor`]):
283
288
  A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
284
289
  """
290
+
285
291
  model_cpu_offload_seq = "text_encoder->unet->vae"
286
- _optional_components = ["safety_checker", "feature_extractor"]
292
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
287
293
  _exclude_from_cpu_offload = ["safety_checker"]
294
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
288
295
 
289
296
  def __init__(
290
297
  self,
@@ -296,6 +303,7 @@ class StableDiffusionControlNetInpaintPipeline(
296
303
  scheduler: KarrasDiffusionSchedulers,
297
304
  safety_checker: StableDiffusionSafetyChecker,
298
305
  feature_extractor: CLIPImageProcessor,
306
+ image_encoder: CLIPVisionModelWithProjection = None,
299
307
  requires_safety_checker: bool = True,
300
308
  ):
301
309
  super().__init__()
@@ -328,6 +336,7 @@ class StableDiffusionControlNetInpaintPipeline(
328
336
  scheduler=scheduler,
329
337
  safety_checker=safety_checker,
330
338
  feature_extractor=feature_extractor,
339
+ image_encoder=image_encoder,
331
340
  )
332
341
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
333
342
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
@@ -587,6 +596,20 @@ class StableDiffusionControlNetInpaintPipeline(
587
596
 
588
597
  return prompt_embeds, negative_prompt_embeds
589
598
 
599
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
600
+ def encode_image(self, image, device, num_images_per_prompt):
601
+ dtype = next(self.image_encoder.parameters()).dtype
602
+
603
+ if not isinstance(image, torch.Tensor):
604
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
605
+
606
+ image = image.to(device=device, dtype=dtype)
607
+ image_embeds = self.image_encoder(image).image_embeds
608
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
609
+
610
+ uncond_image_embeds = torch.zeros_like(image_embeds)
611
+ return image_embeds, uncond_image_embeds
612
+
590
613
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
591
614
  def run_safety_checker(self, image, device, dtype):
592
615
  if self.safety_checker is None:
@@ -655,18 +678,24 @@ class StableDiffusionControlNetInpaintPipeline(
655
678
  controlnet_conditioning_scale=1.0,
656
679
  control_guidance_start=0.0,
657
680
  control_guidance_end=1.0,
681
+ callback_on_step_end_tensor_inputs=None,
658
682
  ):
659
683
  if height is not None and height % 8 != 0 or width is not None and width % 8 != 0:
660
684
  raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
661
685
 
662
- if (callback_steps is None) or (
663
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
664
- ):
686
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
665
687
  raise ValueError(
666
688
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
667
689
  f" {type(callback_steps)}."
668
690
  )
669
691
 
692
+ if callback_on_step_end_tensor_inputs is not None and not all(
693
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
694
+ ):
695
+ raise ValueError(
696
+ 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]}"
697
+ )
698
+
670
699
  if prompt is not None and prompt_embeds is not None:
671
700
  raise ValueError(
672
701
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
@@ -998,6 +1027,29 @@ class StableDiffusionControlNetInpaintPipeline(
998
1027
  """Disables the FreeU mechanism if enabled."""
999
1028
  self.unet.disable_freeu()
1000
1029
 
1030
+ @property
1031
+ def guidance_scale(self):
1032
+ return self._guidance_scale
1033
+
1034
+ @property
1035
+ def clip_skip(self):
1036
+ return self._clip_skip
1037
+
1038
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1039
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1040
+ # corresponds to doing no classifier free guidance.
1041
+ @property
1042
+ def do_classifier_free_guidance(self):
1043
+ return self._guidance_scale > 1
1044
+
1045
+ @property
1046
+ def cross_attention_kwargs(self):
1047
+ return self._cross_attention_kwargs
1048
+
1049
+ @property
1050
+ def num_timesteps(self):
1051
+ return self._num_timesteps
1052
+
1001
1053
  @torch.no_grad()
1002
1054
  @replace_example_docstring(EXAMPLE_DOC_STRING)
1003
1055
  def __call__(
@@ -1018,16 +1070,18 @@ class StableDiffusionControlNetInpaintPipeline(
1018
1070
  latents: Optional[torch.FloatTensor] = None,
1019
1071
  prompt_embeds: Optional[torch.FloatTensor] = None,
1020
1072
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
1073
+ ip_adapter_image: Optional[PipelineImageInput] = None,
1021
1074
  output_type: Optional[str] = "pil",
1022
1075
  return_dict: bool = True,
1023
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
1024
- callback_steps: int = 1,
1025
1076
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1026
1077
  controlnet_conditioning_scale: Union[float, List[float]] = 0.5,
1027
1078
  guess_mode: bool = False,
1028
1079
  control_guidance_start: Union[float, List[float]] = 0.0,
1029
1080
  control_guidance_end: Union[float, List[float]] = 1.0,
1030
1081
  clip_skip: Optional[int] = None,
1082
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
1083
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
1084
+ **kwargs,
1031
1085
  ):
1032
1086
  r"""
1033
1087
  The call function to the pipeline for generation.
@@ -1095,17 +1149,12 @@ class StableDiffusionControlNetInpaintPipeline(
1095
1149
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
1096
1150
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
1097
1151
  not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
1152
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
1098
1153
  output_type (`str`, *optional*, defaults to `"pil"`):
1099
1154
  The output format of the generated image. Choose between `PIL.Image` or `np.array`.
1100
1155
  return_dict (`bool`, *optional*, defaults to `True`):
1101
1156
  Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
1102
1157
  plain tuple.
1103
- callback (`Callable`, *optional*):
1104
- A function that calls every `callback_steps` steps during inference. The function is called with the
1105
- following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
1106
- callback_steps (`int`, *optional*, defaults to 1):
1107
- The frequency at which the `callback` function is called. If not specified, the callback is called at
1108
- every step.
1109
1158
  cross_attention_kwargs (`dict`, *optional*):
1110
1159
  A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
1111
1160
  [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
@@ -1123,6 +1172,15 @@ class StableDiffusionControlNetInpaintPipeline(
1123
1172
  clip_skip (`int`, *optional*):
1124
1173
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
1125
1174
  the output of the pre-final layer will be used for computing the prompt embeddings.
1175
+ callback_on_step_end (`Callable`, *optional*):
1176
+ A function that calls at the end of each denoising steps during the inference. The function is called
1177
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
1178
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
1179
+ `callback_on_step_end_tensor_inputs`.
1180
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
1181
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
1182
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
1183
+ `._callback_tensor_inputs` attribute of your pipeine class.
1126
1184
 
1127
1185
  Examples:
1128
1186
 
@@ -1133,6 +1191,23 @@ class StableDiffusionControlNetInpaintPipeline(
1133
1191
  second element is a list of `bool`s indicating whether the corresponding generated image contains
1134
1192
  "not-safe-for-work" (nsfw) content.
1135
1193
  """
1194
+
1195
+ callback = kwargs.pop("callback", None)
1196
+ callback_steps = kwargs.pop("callback_steps", None)
1197
+
1198
+ if callback is not None:
1199
+ deprecate(
1200
+ "callback",
1201
+ "1.0.0",
1202
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1203
+ )
1204
+ if callback_steps is not None:
1205
+ deprecate(
1206
+ "callback_steps",
1207
+ "1.0.0",
1208
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
1209
+ )
1210
+
1136
1211
  controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
1137
1212
 
1138
1213
  # align format for control guidance
@@ -1142,9 +1217,10 @@ class StableDiffusionControlNetInpaintPipeline(
1142
1217
  control_guidance_end = len(control_guidance_start) * [control_guidance_end]
1143
1218
  elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
1144
1219
  mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
1145
- control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
1146
- control_guidance_end
1147
- ]
1220
+ control_guidance_start, control_guidance_end = (
1221
+ mult * [control_guidance_start],
1222
+ mult * [control_guidance_end],
1223
+ )
1148
1224
 
1149
1225
  # 1. Check inputs. Raise error if not correct
1150
1226
  self.check_inputs(
@@ -1159,8 +1235,13 @@ class StableDiffusionControlNetInpaintPipeline(
1159
1235
  controlnet_conditioning_scale,
1160
1236
  control_guidance_start,
1161
1237
  control_guidance_end,
1238
+ callback_on_step_end_tensor_inputs,
1162
1239
  )
1163
1240
 
1241
+ self._guidance_scale = guidance_scale
1242
+ self._clip_skip = clip_skip
1243
+ self._cross_attention_kwargs = cross_attention_kwargs
1244
+
1164
1245
  # 2. Define call parameters
1165
1246
  if prompt is not None and isinstance(prompt, str):
1166
1247
  batch_size = 1
@@ -1170,10 +1251,6 @@ class StableDiffusionControlNetInpaintPipeline(
1170
1251
  batch_size = prompt_embeds.shape[0]
1171
1252
 
1172
1253
  device = self._execution_device
1173
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
1174
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
1175
- # corresponds to doing no classifier free guidance.
1176
- do_classifier_free_guidance = guidance_scale > 1.0
1177
1254
 
1178
1255
  if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
1179
1256
  controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
@@ -1187,25 +1264,30 @@ class StableDiffusionControlNetInpaintPipeline(
1187
1264
 
1188
1265
  # 3. Encode input prompt
1189
1266
  text_encoder_lora_scale = (
1190
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1267
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
1191
1268
  )
1192
1269
  prompt_embeds, negative_prompt_embeds = self.encode_prompt(
1193
1270
  prompt,
1194
1271
  device,
1195
1272
  num_images_per_prompt,
1196
- do_classifier_free_guidance,
1273
+ self.do_classifier_free_guidance,
1197
1274
  negative_prompt,
1198
1275
  prompt_embeds=prompt_embeds,
1199
1276
  negative_prompt_embeds=negative_prompt_embeds,
1200
1277
  lora_scale=text_encoder_lora_scale,
1201
- clip_skip=clip_skip,
1278
+ clip_skip=self.clip_skip,
1202
1279
  )
1203
1280
  # For classifier free guidance, we need to do two forward passes.
1204
1281
  # Here we concatenate the unconditional and text embeddings into a single batch
1205
1282
  # to avoid doing two forward passes
1206
- if do_classifier_free_guidance:
1283
+ if self.do_classifier_free_guidance:
1207
1284
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
1208
1285
 
1286
+ if ip_adapter_image is not None:
1287
+ image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_images_per_prompt)
1288
+ if self.do_classifier_free_guidance:
1289
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
1290
+
1209
1291
  # 4. Prepare image
1210
1292
  if isinstance(controlnet, ControlNetModel):
1211
1293
  control_image = self.prepare_control_image(
@@ -1216,7 +1298,7 @@ class StableDiffusionControlNetInpaintPipeline(
1216
1298
  num_images_per_prompt=num_images_per_prompt,
1217
1299
  device=device,
1218
1300
  dtype=controlnet.dtype,
1219
- do_classifier_free_guidance=do_classifier_free_guidance,
1301
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1220
1302
  guess_mode=guess_mode,
1221
1303
  )
1222
1304
  elif isinstance(controlnet, MultiControlNetModel):
@@ -1231,7 +1313,7 @@ class StableDiffusionControlNetInpaintPipeline(
1231
1313
  num_images_per_prompt=num_images_per_prompt,
1232
1314
  device=device,
1233
1315
  dtype=controlnet.dtype,
1234
- do_classifier_free_guidance=do_classifier_free_guidance,
1316
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1235
1317
  guess_mode=guess_mode,
1236
1318
  )
1237
1319
 
@@ -1241,7 +1323,7 @@ class StableDiffusionControlNetInpaintPipeline(
1241
1323
  else:
1242
1324
  assert False
1243
1325
 
1244
- # 4. Preprocess mask and image - resizes image and mask w.r.t height and width
1326
+ # 4.1 Preprocess mask and image - resizes image and mask w.r.t height and width
1245
1327
  init_image = self.image_processor.preprocess(image, height=height, width=width)
1246
1328
  init_image = init_image.to(dtype=torch.float32)
1247
1329
 
@@ -1259,6 +1341,7 @@ class StableDiffusionControlNetInpaintPipeline(
1259
1341
  latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1260
1342
  # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise
1261
1343
  is_strength_max = strength == 1.0
1344
+ self._num_timesteps = len(timesteps)
1262
1345
 
1263
1346
  # 6. Prepare latent variables
1264
1347
  num_channels_latents = self.vae.config.latent_channels
@@ -1295,13 +1378,16 @@ class StableDiffusionControlNetInpaintPipeline(
1295
1378
  prompt_embeds.dtype,
1296
1379
  device,
1297
1380
  generator,
1298
- do_classifier_free_guidance,
1381
+ self.do_classifier_free_guidance,
1299
1382
  )
1300
1383
 
1301
1384
  # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1302
1385
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1303
1386
 
1304
- # 7.1 Create tensor stating which controlnets to keep
1387
+ # 7.1 Add image embeds for IP-Adapter
1388
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
1389
+
1390
+ # 7.2 Create tensor stating which controlnets to keep
1305
1391
  controlnet_keep = []
1306
1392
  for i in range(len(timesteps)):
1307
1393
  keeps = [
@@ -1315,11 +1401,11 @@ class StableDiffusionControlNetInpaintPipeline(
1315
1401
  with self.progress_bar(total=num_inference_steps) as progress_bar:
1316
1402
  for i, t in enumerate(timesteps):
1317
1403
  # expand the latents if we are doing classifier free guidance
1318
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1404
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1319
1405
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1320
1406
 
1321
1407
  # controlnet(s) inference
1322
- if guess_mode and do_classifier_free_guidance:
1408
+ if guess_mode and self.do_classifier_free_guidance:
1323
1409
  # Infer ControlNet only for the conditional batch.
1324
1410
  control_model_input = latents
1325
1411
  control_model_input = self.scheduler.scale_model_input(control_model_input, t)
@@ -1346,7 +1432,7 @@ class StableDiffusionControlNetInpaintPipeline(
1346
1432
  return_dict=False,
1347
1433
  )
1348
1434
 
1349
- if guess_mode and do_classifier_free_guidance:
1435
+ if guess_mode and self.do_classifier_free_guidance:
1350
1436
  # Infered ControlNet only for the conditional batch.
1351
1437
  # To apply the output of ControlNet to both the unconditional and conditional batches,
1352
1438
  # add 0 to the unconditional batch to keep it unchanged.
@@ -1361,14 +1447,15 @@ class StableDiffusionControlNetInpaintPipeline(
1361
1447
  latent_model_input,
1362
1448
  t,
1363
1449
  encoder_hidden_states=prompt_embeds,
1364
- cross_attention_kwargs=cross_attention_kwargs,
1450
+ cross_attention_kwargs=self.cross_attention_kwargs,
1365
1451
  down_block_additional_residuals=down_block_res_samples,
1366
1452
  mid_block_additional_residual=mid_block_res_sample,
1453
+ added_cond_kwargs=added_cond_kwargs,
1367
1454
  return_dict=False,
1368
1455
  )[0]
1369
1456
 
1370
1457
  # perform guidance
1371
- if do_classifier_free_guidance:
1458
+ if self.do_classifier_free_guidance:
1372
1459
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1373
1460
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1374
1461
 
@@ -1377,7 +1464,7 @@ class StableDiffusionControlNetInpaintPipeline(
1377
1464
 
1378
1465
  if num_channels_unet == 4:
1379
1466
  init_latents_proper = image_latents
1380
- if do_classifier_free_guidance:
1467
+ if self.do_classifier_free_guidance:
1381
1468
  init_mask, _ = mask.chunk(2)
1382
1469
  else:
1383
1470
  init_mask = mask
@@ -1390,6 +1477,16 @@ class StableDiffusionControlNetInpaintPipeline(
1390
1477
 
1391
1478
  latents = (1 - init_mask) * init_latents_proper + init_mask * latents
1392
1479
 
1480
+ if callback_on_step_end is not None:
1481
+ callback_kwargs = {}
1482
+ for k in callback_on_step_end_tensor_inputs:
1483
+ callback_kwargs[k] = locals()[k]
1484
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1485
+
1486
+ latents = callback_outputs.pop("latents", latents)
1487
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1488
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1489
+
1393
1490
  # call the callback, if provided
1394
1491
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1395
1492
  progress_bar.update()