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
@@ -92,9 +92,13 @@ EXAMPLE_DOC_STRING = """
92
92
 
93
93
 
94
94
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
95
- def retrieve_latents(encoder_output, generator):
96
- if hasattr(encoder_output, "latent_dist"):
95
+ def retrieve_latents(
96
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
97
+ ):
98
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
97
99
  return encoder_output.latent_dist.sample(generator)
100
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
101
+ return encoder_output.latent_dist.mode()
98
102
  elif hasattr(encoder_output, "latents"):
99
103
  return encoder_output.latents
100
104
  else:
@@ -160,9 +164,11 @@ class StableDiffusionControlNetImg2ImgPipeline(
160
164
  feature_extractor ([`~transformers.CLIPImageProcessor`]):
161
165
  A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
162
166
  """
167
+
163
168
  model_cpu_offload_seq = "text_encoder->unet->vae"
164
169
  _optional_components = ["safety_checker", "feature_extractor"]
165
170
  _exclude_from_cpu_offload = ["safety_checker"]
171
+ _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
166
172
 
167
173
  def __init__(
168
174
  self,
@@ -518,15 +524,21 @@ class StableDiffusionControlNetImg2ImgPipeline(
518
524
  controlnet_conditioning_scale=1.0,
519
525
  control_guidance_start=0.0,
520
526
  control_guidance_end=1.0,
527
+ callback_on_step_end_tensor_inputs=None,
521
528
  ):
522
- if (callback_steps is None) or (
523
- callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
524
- ):
529
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
525
530
  raise ValueError(
526
531
  f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
527
532
  f" {type(callback_steps)}."
528
533
  )
529
534
 
535
+ if callback_on_step_end_tensor_inputs is not None and not all(
536
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
537
+ ):
538
+ raise ValueError(
539
+ 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]}"
540
+ )
541
+
530
542
  if prompt is not None and prompt_embeds is not None:
531
543
  raise ValueError(
532
544
  f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
@@ -807,6 +819,29 @@ class StableDiffusionControlNetImg2ImgPipeline(
807
819
  """Disables the FreeU mechanism if enabled."""
808
820
  self.unet.disable_freeu()
809
821
 
822
+ @property
823
+ def guidance_scale(self):
824
+ return self._guidance_scale
825
+
826
+ @property
827
+ def clip_skip(self):
828
+ return self._clip_skip
829
+
830
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
831
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
832
+ # corresponds to doing no classifier free guidance.
833
+ @property
834
+ def do_classifier_free_guidance(self):
835
+ return self._guidance_scale > 1
836
+
837
+ @property
838
+ def cross_attention_kwargs(self):
839
+ return self._cross_attention_kwargs
840
+
841
+ @property
842
+ def num_timesteps(self):
843
+ return self._num_timesteps
844
+
810
845
  @torch.no_grad()
811
846
  @replace_example_docstring(EXAMPLE_DOC_STRING)
812
847
  def __call__(
@@ -828,14 +863,15 @@ class StableDiffusionControlNetImg2ImgPipeline(
828
863
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
829
864
  output_type: Optional[str] = "pil",
830
865
  return_dict: bool = True,
831
- callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
832
- callback_steps: int = 1,
833
866
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
834
867
  controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
835
868
  guess_mode: bool = False,
836
869
  control_guidance_start: Union[float, List[float]] = 0.0,
837
870
  control_guidance_end: Union[float, List[float]] = 1.0,
838
871
  clip_skip: Optional[int] = None,
872
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
873
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
874
+ **kwargs,
839
875
  ):
840
876
  r"""
841
877
  The call function to the pipeline for generation.
@@ -891,12 +927,6 @@ class StableDiffusionControlNetImg2ImgPipeline(
891
927
  return_dict (`bool`, *optional*, defaults to `True`):
892
928
  Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
893
929
  plain tuple.
894
- callback (`Callable`, *optional*):
895
- A function that calls every `callback_steps` steps during inference. The function is called with the
896
- following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
897
- callback_steps (`int`, *optional*, defaults to 1):
898
- The frequency at which the `callback` function is called. If not specified, the callback is called at
899
- every step.
900
930
  cross_attention_kwargs (`dict`, *optional*):
901
931
  A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
902
932
  [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
@@ -914,6 +944,15 @@ class StableDiffusionControlNetImg2ImgPipeline(
914
944
  clip_skip (`int`, *optional*):
915
945
  Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
916
946
  the output of the pre-final layer will be used for computing the prompt embeddings.
947
+ callback_on_step_end (`Callable`, *optional*):
948
+ A function that calls at the end of each denoising steps during the inference. The function is called
949
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
950
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
951
+ `callback_on_step_end_tensor_inputs`.
952
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
953
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
954
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
955
+ `._callback_tensor_inputs` attribute of your pipeine class.
917
956
 
918
957
  Examples:
919
958
 
@@ -924,6 +963,23 @@ class StableDiffusionControlNetImg2ImgPipeline(
924
963
  second element is a list of `bool`s indicating whether the corresponding generated image contains
925
964
  "not-safe-for-work" (nsfw) content.
926
965
  """
966
+
967
+ callback = kwargs.pop("callback", None)
968
+ callback_steps = kwargs.pop("callback_steps", None)
969
+
970
+ if callback is not None:
971
+ deprecate(
972
+ "callback",
973
+ "1.0.0",
974
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
975
+ )
976
+ if callback_steps is not None:
977
+ deprecate(
978
+ "callback_steps",
979
+ "1.0.0",
980
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
981
+ )
982
+
927
983
  controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
928
984
 
929
985
  # align format for control guidance
@@ -933,9 +989,10 @@ class StableDiffusionControlNetImg2ImgPipeline(
933
989
  control_guidance_end = len(control_guidance_start) * [control_guidance_end]
934
990
  elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
935
991
  mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
936
- control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [
937
- control_guidance_end
938
- ]
992
+ control_guidance_start, control_guidance_end = (
993
+ mult * [control_guidance_start],
994
+ mult * [control_guidance_end],
995
+ )
939
996
 
940
997
  # 1. Check inputs. Raise error if not correct
941
998
  self.check_inputs(
@@ -948,8 +1005,13 @@ class StableDiffusionControlNetImg2ImgPipeline(
948
1005
  controlnet_conditioning_scale,
949
1006
  control_guidance_start,
950
1007
  control_guidance_end,
1008
+ callback_on_step_end_tensor_inputs,
951
1009
  )
952
1010
 
1011
+ self._guidance_scale = guidance_scale
1012
+ self._clip_skip = clip_skip
1013
+ self._cross_attention_kwargs = cross_attention_kwargs
1014
+
953
1015
  # 2. Define call parameters
954
1016
  if prompt is not None and isinstance(prompt, str):
955
1017
  batch_size = 1
@@ -959,10 +1021,6 @@ class StableDiffusionControlNetImg2ImgPipeline(
959
1021
  batch_size = prompt_embeds.shape[0]
960
1022
 
961
1023
  device = self._execution_device
962
- # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
963
- # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
964
- # corresponds to doing no classifier free guidance.
965
- do_classifier_free_guidance = guidance_scale > 1.0
966
1024
 
967
1025
  if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
968
1026
  controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
@@ -976,27 +1034,27 @@ class StableDiffusionControlNetImg2ImgPipeline(
976
1034
 
977
1035
  # 3. Encode input prompt
978
1036
  text_encoder_lora_scale = (
979
- cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
1037
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
980
1038
  )
981
1039
  prompt_embeds, negative_prompt_embeds = self.encode_prompt(
982
1040
  prompt,
983
1041
  device,
984
1042
  num_images_per_prompt,
985
- do_classifier_free_guidance,
1043
+ self.do_classifier_free_guidance,
986
1044
  negative_prompt,
987
1045
  prompt_embeds=prompt_embeds,
988
1046
  negative_prompt_embeds=negative_prompt_embeds,
989
1047
  lora_scale=text_encoder_lora_scale,
990
- clip_skip=clip_skip,
1048
+ clip_skip=self.clip_skip,
991
1049
  )
992
1050
  # For classifier free guidance, we need to do two forward passes.
993
1051
  # Here we concatenate the unconditional and text embeddings into a single batch
994
1052
  # to avoid doing two forward passes
995
- if do_classifier_free_guidance:
1053
+ if self.do_classifier_free_guidance:
996
1054
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
997
1055
 
998
1056
  # 4. Prepare image
999
- image = self.image_processor.preprocess(image).to(dtype=torch.float32)
1057
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
1000
1058
 
1001
1059
  # 5. Prepare controlnet_conditioning_image
1002
1060
  if isinstance(controlnet, ControlNetModel):
@@ -1008,7 +1066,7 @@ class StableDiffusionControlNetImg2ImgPipeline(
1008
1066
  num_images_per_prompt=num_images_per_prompt,
1009
1067
  device=device,
1010
1068
  dtype=controlnet.dtype,
1011
- do_classifier_free_guidance=do_classifier_free_guidance,
1069
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1012
1070
  guess_mode=guess_mode,
1013
1071
  )
1014
1072
  elif isinstance(controlnet, MultiControlNetModel):
@@ -1023,7 +1081,7 @@ class StableDiffusionControlNetImg2ImgPipeline(
1023
1081
  num_images_per_prompt=num_images_per_prompt,
1024
1082
  device=device,
1025
1083
  dtype=controlnet.dtype,
1026
- do_classifier_free_guidance=do_classifier_free_guidance,
1084
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
1027
1085
  guess_mode=guess_mode,
1028
1086
  )
1029
1087
 
@@ -1037,6 +1095,7 @@ class StableDiffusionControlNetImg2ImgPipeline(
1037
1095
  self.scheduler.set_timesteps(num_inference_steps, device=device)
1038
1096
  timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
1039
1097
  latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
1098
+ self._num_timesteps = len(timesteps)
1040
1099
 
1041
1100
  # 6. Prepare latent variables
1042
1101
  latents = self.prepare_latents(
@@ -1066,11 +1125,11 @@ class StableDiffusionControlNetImg2ImgPipeline(
1066
1125
  with self.progress_bar(total=num_inference_steps) as progress_bar:
1067
1126
  for i, t in enumerate(timesteps):
1068
1127
  # expand the latents if we are doing classifier free guidance
1069
- latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
1128
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1070
1129
  latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1071
1130
 
1072
1131
  # controlnet(s) inference
1073
- if guess_mode and do_classifier_free_guidance:
1132
+ if guess_mode and self.do_classifier_free_guidance:
1074
1133
  # Infer ControlNet only for the conditional batch.
1075
1134
  control_model_input = latents
1076
1135
  control_model_input = self.scheduler.scale_model_input(control_model_input, t)
@@ -1097,7 +1156,7 @@ class StableDiffusionControlNetImg2ImgPipeline(
1097
1156
  return_dict=False,
1098
1157
  )
1099
1158
 
1100
- if guess_mode and do_classifier_free_guidance:
1159
+ if guess_mode and self.do_classifier_free_guidance:
1101
1160
  # Infered ControlNet only for the conditional batch.
1102
1161
  # To apply the output of ControlNet to both the unconditional and conditional batches,
1103
1162
  # add 0 to the unconditional batch to keep it unchanged.
@@ -1109,20 +1168,30 @@ class StableDiffusionControlNetImg2ImgPipeline(
1109
1168
  latent_model_input,
1110
1169
  t,
1111
1170
  encoder_hidden_states=prompt_embeds,
1112
- cross_attention_kwargs=cross_attention_kwargs,
1171
+ cross_attention_kwargs=self.cross_attention_kwargs,
1113
1172
  down_block_additional_residuals=down_block_res_samples,
1114
1173
  mid_block_additional_residual=mid_block_res_sample,
1115
1174
  return_dict=False,
1116
1175
  )[0]
1117
1176
 
1118
1177
  # perform guidance
1119
- if do_classifier_free_guidance:
1178
+ if self.do_classifier_free_guidance:
1120
1179
  noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1121
1180
  noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1122
1181
 
1123
1182
  # compute the previous noisy sample x_t -> x_t-1
1124
1183
  latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1125
1184
 
1185
+ if callback_on_step_end is not None:
1186
+ callback_kwargs = {}
1187
+ for k in callback_on_step_end_tensor_inputs:
1188
+ callback_kwargs[k] = locals()[k]
1189
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1190
+
1191
+ latents = callback_outputs.pop("latents", latents)
1192
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1193
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1194
+
1126
1195
  # call the callback, if provided
1127
1196
  if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1128
1197
  progress_bar.update()