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
@@ -19,11 +19,11 @@ import numpy as np
19
19
  import PIL.Image
20
20
  import torch
21
21
  from packaging import version
22
- from transformers import CLIPImageProcessor, XLMRobertaTokenizer
22
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, XLMRobertaTokenizer
23
23
 
24
24
  from ...configuration_utils import FrozenDict
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, UNet2DConditionModel
28
28
  from ...models.lora import adjust_lora_scale_text_encoder
29
29
  from ...schedulers import KarrasDiffusionSchedulers
@@ -76,9 +76,13 @@ EXAMPLE_DOC_STRING = """
76
76
 
77
77
 
78
78
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
79
- def retrieve_latents(encoder_output, generator):
80
- if hasattr(encoder_output, "latent_dist"):
79
+ def retrieve_latents(
80
+ encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
81
+ ):
82
+ if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
81
83
  return encoder_output.latent_dist.sample(generator)
84
+ elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
85
+ return encoder_output.latent_dist.mode()
82
86
  elif hasattr(encoder_output, "latents"):
83
87
  return encoder_output.latents
84
88
  else:
@@ -109,9 +113,54 @@ def preprocess(image):
109
113
  return image
110
114
 
111
115
 
116
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
117
+ def retrieve_timesteps(
118
+ scheduler,
119
+ num_inference_steps: Optional[int] = None,
120
+ device: Optional[Union[str, torch.device]] = None,
121
+ timesteps: Optional[List[int]] = None,
122
+ **kwargs,
123
+ ):
124
+ """
125
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
126
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
127
+
128
+ Args:
129
+ scheduler (`SchedulerMixin`):
130
+ The scheduler to get timesteps from.
131
+ num_inference_steps (`int`):
132
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
133
+ `timesteps` must be `None`.
134
+ device (`str` or `torch.device`, *optional*):
135
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
136
+ timesteps (`List[int]`, *optional*):
137
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
138
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
139
+ must be `None`.
140
+
141
+ Returns:
142
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
143
+ second element is the number of inference steps.
144
+ """
145
+ if timesteps is not None:
146
+ accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
147
+ if not accepts_timesteps:
148
+ raise ValueError(
149
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
150
+ f" timestep schedules. Please check whether you are using the correct scheduler."
151
+ )
152
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
153
+ timesteps = scheduler.timesteps
154
+ num_inference_steps = len(timesteps)
155
+ else:
156
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
157
+ timesteps = scheduler.timesteps
158
+ return timesteps, num_inference_steps
159
+
160
+
112
161
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline with Stable->Alt, CLIPTextModel->RobertaSeriesModelWithTransformation, CLIPTokenizer->XLMRobertaTokenizer, AltDiffusionSafetyChecker->StableDiffusionSafetyChecker
113
162
  class AltDiffusionImg2ImgPipeline(
114
- DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin
163
+ DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin, FromSingleFileMixin
115
164
  ):
116
165
  r"""
117
166
  Pipeline for text-guided image-to-image generation using Alt Diffusion.
@@ -124,6 +173,7 @@ class AltDiffusionImg2ImgPipeline(
124
173
  - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights
125
174
  - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights
126
175
  - [`~loaders.FromSingleFileMixin.from_single_file`] for loading `.ckpt` files
176
+ - [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
127
177
 
128
178
  Args:
129
179
  vae ([`AutoencoderKL`]):
@@ -146,7 +196,7 @@ class AltDiffusionImg2ImgPipeline(
146
196
  """
147
197
 
148
198
  model_cpu_offload_seq = "text_encoder->unet->vae"
149
- _optional_components = ["safety_checker", "feature_extractor"]
199
+ _optional_components = ["safety_checker", "feature_extractor", "image_encoder"]
150
200
  _exclude_from_cpu_offload = ["safety_checker"]
151
201
  _callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
152
202
 
@@ -159,6 +209,7 @@ class AltDiffusionImg2ImgPipeline(
159
209
  scheduler: KarrasDiffusionSchedulers,
160
210
  safety_checker: StableDiffusionSafetyChecker,
161
211
  feature_extractor: CLIPImageProcessor,
212
+ image_encoder: CLIPVisionModelWithProjection = None,
162
213
  requires_safety_checker: bool = True,
163
214
  ):
164
215
  super().__init__()
@@ -235,6 +286,7 @@ class AltDiffusionImg2ImgPipeline(
235
286
  scheduler=scheduler,
236
287
  safety_checker=safety_checker,
237
288
  feature_extractor=feature_extractor,
289
+ image_encoder=image_encoder,
238
290
  )
239
291
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
240
292
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
@@ -252,10 +304,7 @@ class AltDiffusionImg2ImgPipeline(
252
304
  lora_scale: Optional[float] = None,
253
305
  **kwargs,
254
306
  ):
255
- deprecation_message = (
256
- "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()`"
257
- " instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
258
- )
307
+ deprecation_message = "`_encode_prompt()` is deprecated and it will be removed in a future version. Use `encode_prompt()` instead. Also, be aware that the output format changed from a concatenated tensor to a tuple."
259
308
  deprecate("_encode_prompt()", "1.0.0", deprecation_message, standard_warn=False)
260
309
 
261
310
  prompt_embeds_tuple = self.encode_prompt(
@@ -456,6 +505,19 @@ class AltDiffusionImg2ImgPipeline(
456
505
 
457
506
  return prompt_embeds, negative_prompt_embeds
458
507
 
508
+ def encode_image(self, image, device, num_images_per_prompt):
509
+ dtype = next(self.image_encoder.parameters()).dtype
510
+
511
+ if not isinstance(image, torch.Tensor):
512
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
513
+
514
+ image = image.to(device=device, dtype=dtype)
515
+ image_embeds = self.image_encoder(image).image_embeds
516
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
517
+
518
+ uncond_image_embeds = torch.zeros_like(image_embeds)
519
+ return image_embeds, uncond_image_embeds
520
+
459
521
  def run_safety_checker(self, image, device, dtype):
460
522
  if self.safety_checker is None:
461
523
  has_nsfw_concept = None
@@ -471,10 +533,7 @@ class AltDiffusionImg2ImgPipeline(
471
533
  return image, has_nsfw_concept
472
534
 
473
535
  def decode_latents(self, latents):
474
- deprecation_message = (
475
- "The decode_latents method is deprecated and will be removed in 1.0.0. Please use"
476
- " VaeImageProcessor.postprocess(...) instead"
477
- )
536
+ deprecation_message = "The decode_latents method is deprecated and will be removed in 1.0.0. Please use VaeImageProcessor.postprocess(...) instead"
478
537
  deprecate("decode_latents", "1.0.0", deprecation_message, standard_warn=False)
479
538
 
480
539
  latents = 1 / self.vae.config.scaling_factor * latents
@@ -524,8 +583,7 @@ class AltDiffusionImg2ImgPipeline(
524
583
  k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
525
584
  ):
526
585
  raise ValueError(
527
- f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found"
528
- f" {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
586
+ 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]}"
529
587
  )
530
588
  if prompt is not None and prompt_embeds is not None:
531
589
  raise ValueError(
@@ -578,8 +636,8 @@ class AltDiffusionImg2ImgPipeline(
578
636
  else:
579
637
  if isinstance(generator, list) and len(generator) != batch_size:
580
638
  raise ValueError(
581
- f"You have passed a list of generators of length {len(generator)}, but requested an effective"
582
- f" batch size of {batch_size}. Make sure the batch size matches the length of the generators."
639
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
640
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
583
641
  )
584
642
 
585
643
  elif isinstance(generator, list):
@@ -705,6 +763,7 @@ class AltDiffusionImg2ImgPipeline(
705
763
  image: PipelineImageInput = None,
706
764
  strength: float = 0.8,
707
765
  num_inference_steps: Optional[int] = 50,
766
+ timesteps: List[int] = None,
708
767
  guidance_scale: Optional[float] = 7.5,
709
768
  negative_prompt: Optional[Union[str, List[str]]] = None,
710
769
  num_images_per_prompt: Optional[int] = 1,
@@ -712,6 +771,7 @@ class AltDiffusionImg2ImgPipeline(
712
771
  generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
713
772
  prompt_embeds: Optional[torch.FloatTensor] = None,
714
773
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
774
+ ip_adapter_image: Optional[PipelineImageInput] = None,
715
775
  output_type: Optional[str] = "pil",
716
776
  return_dict: bool = True,
717
777
  cross_attention_kwargs: Optional[Dict[str, Any]] = None,
@@ -741,6 +801,10 @@ class AltDiffusionImg2ImgPipeline(
741
801
  num_inference_steps (`int`, *optional*, defaults to 50):
742
802
  The number of denoising steps. More denoising steps usually lead to a higher quality image at the
743
803
  expense of slower inference. This parameter is modulated by `strength`.
804
+ timesteps (`List[int]`, *optional*):
805
+ Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
806
+ in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
807
+ passed will be used. Must be in descending order.
744
808
  guidance_scale (`float`, *optional*, defaults to 7.5):
745
809
  A higher guidance scale value encourages the model to generate images closely linked to the text
746
810
  `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
@@ -761,6 +825,7 @@ class AltDiffusionImg2ImgPipeline(
761
825
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
762
826
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
763
827
  not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
828
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
764
829
  output_type (`str`, *optional*, defaults to `"pil"`):
765
830
  The output format of the generated image. Choose between `PIL.Image` or `np.array`.
766
831
  return_dict (`bool`, *optional*, defaults to `True`):
@@ -780,7 +845,7 @@ class AltDiffusionImg2ImgPipeline(
780
845
  callback_on_step_end_tensor_inputs (`List`, *optional*):
781
846
  The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
782
847
  will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
783
- `._callback_tensor_inputs` attribute of your pipeine class.
848
+ `._callback_tensor_inputs` attribute of your pipeline class.
784
849
  Examples:
785
850
 
786
851
  Returns:
@@ -798,15 +863,13 @@ class AltDiffusionImg2ImgPipeline(
798
863
  deprecate(
799
864
  "callback",
800
865
  "1.0.0",
801
- "Passing `callback` as an input argument to `__call__` is deprecated, consider use"
802
- " `callback_on_step_end`",
866
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
803
867
  )
804
868
  if callback_steps is not None:
805
869
  deprecate(
806
870
  "callback_steps",
807
871
  "1.0.0",
808
- "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use"
809
- " `callback_on_step_end`",
872
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider use `callback_on_step_end`",
810
873
  )
811
874
 
812
875
  # 1. Check inputs. Raise error if not correct
@@ -855,11 +918,16 @@ class AltDiffusionImg2ImgPipeline(
855
918
  if self.do_classifier_free_guidance:
856
919
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
857
920
 
921
+ if ip_adapter_image is not None:
922
+ image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_images_per_prompt)
923
+ if self.do_classifier_free_guidance:
924
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
925
+
858
926
  # 4. Preprocess image
859
927
  image = self.image_processor.preprocess(image)
860
928
 
861
929
  # 5. set timesteps
862
- self.scheduler.set_timesteps(num_inference_steps, device=device)
930
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, timesteps)
863
931
  timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
864
932
  latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
865
933
 
@@ -877,7 +945,10 @@ class AltDiffusionImg2ImgPipeline(
877
945
  # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
878
946
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
879
947
 
880
- # 7.5 Optionally get Guidance Scale Embedding
948
+ # 7.1 Add image embeds for IP-Adapter
949
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
950
+
951
+ # 7.2 Optionally get Guidance Scale Embedding
881
952
  timestep_cond = None
882
953
  if self.unet.config.time_cond_proj_dim is not None:
883
954
  guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
@@ -901,6 +972,7 @@ class AltDiffusionImg2ImgPipeline(
901
972
  encoder_hidden_states=prompt_embeds,
902
973
  timestep_cond=timestep_cond,
903
974
  cross_attention_kwargs=self.cross_attention_kwargs,
975
+ added_cond_kwargs=added_cond_kwargs,
904
976
  return_dict=False,
905
977
  )[0]
906
978
 
@@ -18,10 +18,10 @@ from typing import Any, Callable, Dict, List, Optional, Union
18
18
 
19
19
  import numpy as np
20
20
  import torch
21
- from transformers import CLIPTextModel, CLIPTokenizer
21
+ from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection
22
22
 
23
- from ...image_processor import VaeImageProcessor
24
- from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin
23
+ from ...image_processor import PipelineImageInput, VaeImageProcessor
24
+ from ...loaders import IPAdapterMixin, LoraLoaderMixin, TextualInversionLoaderMixin
25
25
  from ...models import AutoencoderKL, UNet2DConditionModel, UNetMotionModel
26
26
  from ...models.lora import adjust_lora_scale_text_encoder
27
27
  from ...models.unet_motion_model import MotionAdapter
@@ -77,7 +77,7 @@ class AnimateDiffPipelineOutput(BaseOutput):
77
77
  frames: Union[torch.Tensor, np.ndarray]
78
78
 
79
79
 
80
- class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
80
+ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, IPAdapterMixin, LoraLoaderMixin):
81
81
  r"""
82
82
  Pipeline for text-to-video generation.
83
83
 
@@ -99,7 +99,9 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
99
99
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
100
100
  [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
101
101
  """
102
+
102
103
  model_cpu_offload_seq = "text_encoder->unet->vae"
104
+ _optional_components = ["feature_extractor", "image_encoder"]
103
105
 
104
106
  def __init__(
105
107
  self,
@@ -116,6 +118,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
116
118
  EulerAncestralDiscreteScheduler,
117
119
  DPMSolverMultistepScheduler,
118
120
  ],
121
+ feature_extractor: CLIPImageProcessor = None,
122
+ image_encoder: CLIPVisionModelWithProjection = None,
119
123
  ):
120
124
  super().__init__()
121
125
  unet = UNetMotionModel.from_unet2d(unet, motion_adapter)
@@ -127,6 +131,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
127
131
  unet=unet,
128
132
  motion_adapter=motion_adapter,
129
133
  scheduler=scheduler,
134
+ feature_extractor=feature_extractor,
135
+ image_encoder=image_encoder,
130
136
  )
131
137
  self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
132
138
  self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
@@ -313,6 +319,20 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
313
319
 
314
320
  return prompt_embeds, negative_prompt_embeds
315
321
 
322
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
323
+ def encode_image(self, image, device, num_images_per_prompt):
324
+ dtype = next(self.image_encoder.parameters()).dtype
325
+
326
+ if not isinstance(image, torch.Tensor):
327
+ image = self.feature_extractor(image, return_tensors="pt").pixel_values
328
+
329
+ image = image.to(device=device, dtype=dtype)
330
+ image_embeds = self.image_encoder(image).image_embeds
331
+ image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
332
+
333
+ uncond_image_embeds = torch.zeros_like(image_embeds)
334
+ return image_embeds, uncond_image_embeds
335
+
316
336
  # Copied from diffusers.pipelines.text_to_video_synthesis/pipeline_text_to_video_synth.TextToVideoSDPipeline.decode_latents
317
337
  def decode_latents(self, latents):
318
338
  latents = 1 / self.vae.config.scaling_factor * latents
@@ -511,6 +531,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
511
531
  latents: Optional[torch.FloatTensor] = None,
512
532
  prompt_embeds: Optional[torch.FloatTensor] = None,
513
533
  negative_prompt_embeds: Optional[torch.FloatTensor] = None,
534
+ ip_adapter_image: Optional[PipelineImageInput] = None,
514
535
  output_type: Optional[str] = "pil",
515
536
  return_dict: bool = True,
516
537
  callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
@@ -557,6 +578,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
557
578
  negative_prompt_embeds (`torch.FloatTensor`, *optional*):
558
579
  Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
559
580
  not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
581
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
560
582
  output_type (`str`, *optional*, defaults to `"pil"`):
561
583
  The output format of the generated video. Choose between `torch.FloatTensor`, `PIL.Image` or
562
584
  `np.array`.
@@ -628,6 +650,11 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
628
650
  if do_classifier_free_guidance:
629
651
  prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
630
652
 
653
+ if ip_adapter_image is not None:
654
+ image_embeds, negative_image_embeds = self.encode_image(ip_adapter_image, device, num_videos_per_prompt)
655
+ if do_classifier_free_guidance:
656
+ image_embeds = torch.cat([negative_image_embeds, image_embeds])
657
+
631
658
  # 4. Prepare timesteps
632
659
  self.scheduler.set_timesteps(num_inference_steps, device=device)
633
660
  timesteps = self.scheduler.timesteps
@@ -648,6 +675,8 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
648
675
 
649
676
  # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
650
677
  extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
678
+ # 7 Add image embeds for IP-Adapter
679
+ added_cond_kwargs = {"image_embeds": image_embeds} if ip_adapter_image is not None else None
651
680
 
652
681
  # Denoising loop
653
682
  num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
@@ -663,6 +692,7 @@ class AnimateDiffPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLo
663
692
  t,
664
693
  encoder_hidden_states=prompt_embeds,
665
694
  cross_attention_kwargs=cross_attention_kwargs,
695
+ added_cond_kwargs=added_cond_kwargs,
666
696
  ).sample
667
697
 
668
698
  # perform guidance
@@ -72,6 +72,7 @@ class AudioLDMPipeline(DiffusionPipeline):
72
72
  vocoder ([`~transformers.SpeechT5HifiGan`]):
73
73
  Vocoder of class `SpeechT5HifiGan`.
74
74
  """
75
+
75
76
  model_cpu_offload_seq = "text_encoder->unet->vae"
76
77
 
77
78
  def __init__(
@@ -42,6 +42,7 @@ from .kandinsky2_2 import (
42
42
  KandinskyV22InpaintPipeline,
43
43
  KandinskyV22Pipeline,
44
44
  )
45
+ from .kandinsky3 import Kandinsky3Img2ImgPipeline, Kandinsky3Pipeline
45
46
  from .latent_consistency_models import LatentConsistencyModelImg2ImgPipeline, LatentConsistencyModelPipeline
46
47
  from .pixart_alpha import PixArtAlphaPipeline
47
48
  from .stable_diffusion import (
@@ -64,6 +65,7 @@ AUTO_TEXT2IMAGE_PIPELINES_MAPPING = OrderedDict(
64
65
  ("if", IFPipeline),
65
66
  ("kandinsky", KandinskyCombinedPipeline),
66
67
  ("kandinsky22", KandinskyV22CombinedPipeline),
68
+ ("kandinsky3", Kandinsky3Pipeline),
67
69
  ("stable-diffusion-controlnet", StableDiffusionControlNetPipeline),
68
70
  ("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetPipeline),
69
71
  ("wuerstchen", WuerstchenCombinedPipeline),
@@ -79,6 +81,7 @@ AUTO_IMAGE2IMAGE_PIPELINES_MAPPING = OrderedDict(
79
81
  ("if", IFImg2ImgPipeline),
80
82
  ("kandinsky", KandinskyImg2ImgCombinedPipeline),
81
83
  ("kandinsky22", KandinskyV22Img2ImgCombinedPipeline),
84
+ ("kandinsky3", Kandinsky3Img2ImgPipeline),
82
85
  ("stable-diffusion-controlnet", StableDiffusionControlNetImg2ImgPipeline),
83
86
  ("stable-diffusion-xl-controlnet", StableDiffusionXLControlNetImg2ImgPipeline),
84
87
  ("lcm", LatentConsistencyModelImg2ImgPipeline),
@@ -181,6 +184,7 @@ class AutoPipelineForText2Image(ConfigMixin):
181
184
  diffusion pipeline's components.
182
185
 
183
186
  """
187
+
184
188
  config_name = "model_index.json"
185
189
 
186
190
  def __init__(self, *args, **kwargs):
@@ -451,6 +455,7 @@ class AutoPipelineForImage2Image(ConfigMixin):
451
455
  diffusion pipeline's components.
452
456
 
453
457
  """
458
+
454
459
  config_name = "model_index.json"
455
460
 
456
461
  def __init__(self, *args, **kwargs):
@@ -726,6 +731,7 @@ class AutoPipelineForInpainting(ConfigMixin):
726
731
  diffusion pipeline's components.
727
732
 
728
733
  """
734
+
729
735
  config_name = "model_index.json"
730
736
 
731
737
  def __init__(self, *args, **kwargs):
@@ -74,6 +74,7 @@ class ConsistencyModelPipeline(DiffusionPipeline):
74
74
  A scheduler to be used in combination with `unet` to denoise the encoded image latents. Currently only
75
75
  compatible with [`CMStochasticIterativeScheduler`].
76
76
  """
77
+
77
78
  model_cpu_offload_seq = "unet"
78
79
 
79
80
  def __init__(self, unet: UNet2DModel, scheduler: CMStochasticIterativeScheduler) -> None: