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

Sign up to get free protection for your applications and to get access to all the features.
Files changed (238) hide show
  1. diffusers/__init__.py +26 -2
  2. diffusers/commands/fp16_safetensors.py +10 -11
  3. diffusers/configuration_utils.py +13 -8
  4. diffusers/dependency_versions_check.py +0 -1
  5. diffusers/dependency_versions_table.py +5 -5
  6. diffusers/experimental/rl/value_guided_sampling.py +1 -1
  7. diffusers/image_processor.py +463 -51
  8. diffusers/loaders/__init__.py +82 -0
  9. diffusers/loaders/ip_adapter.py +159 -0
  10. diffusers/loaders/lora.py +1553 -0
  11. diffusers/loaders/lora_conversion_utils.py +284 -0
  12. diffusers/loaders/single_file.py +637 -0
  13. diffusers/loaders/textual_inversion.py +455 -0
  14. diffusers/loaders/unet.py +828 -0
  15. diffusers/loaders/utils.py +59 -0
  16. diffusers/models/__init__.py +26 -9
  17. diffusers/models/activations.py +9 -6
  18. diffusers/models/attention.py +301 -29
  19. diffusers/models/attention_flax.py +9 -1
  20. diffusers/models/attention_processor.py +378 -6
  21. diffusers/models/autoencoders/__init__.py +5 -0
  22. diffusers/models/{autoencoder_asym_kl.py → autoencoders/autoencoder_asym_kl.py} +17 -12
  23. diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +47 -23
  24. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +402 -0
  25. diffusers/models/{autoencoder_tiny.py → autoencoders/autoencoder_tiny.py} +24 -28
  26. diffusers/models/{consistency_decoder_vae.py → autoencoders/consistency_decoder_vae.py} +51 -44
  27. diffusers/models/{vae.py → autoencoders/vae.py} +71 -17
  28. diffusers/models/controlnet.py +59 -39
  29. diffusers/models/controlnet_flax.py +19 -18
  30. diffusers/models/downsampling.py +338 -0
  31. diffusers/models/embeddings.py +112 -29
  32. diffusers/models/embeddings_flax.py +2 -0
  33. diffusers/models/lora.py +131 -1
  34. diffusers/models/modeling_flax_utils.py +14 -8
  35. diffusers/models/modeling_outputs.py +17 -0
  36. diffusers/models/modeling_utils.py +37 -29
  37. diffusers/models/normalization.py +110 -4
  38. diffusers/models/resnet.py +299 -652
  39. diffusers/models/transformer_2d.py +22 -5
  40. diffusers/models/transformer_temporal.py +183 -1
  41. diffusers/models/unet_2d_blocks_flax.py +5 -0
  42. diffusers/models/unet_2d_condition.py +46 -0
  43. diffusers/models/unet_2d_condition_flax.py +13 -13
  44. diffusers/models/unet_3d_blocks.py +957 -173
  45. diffusers/models/unet_3d_condition.py +16 -8
  46. diffusers/models/unet_kandinsky3.py +535 -0
  47. diffusers/models/unet_motion_model.py +48 -33
  48. diffusers/models/unet_spatio_temporal_condition.py +489 -0
  49. diffusers/models/upsampling.py +454 -0
  50. diffusers/models/uvit_2d.py +471 -0
  51. diffusers/models/vae_flax.py +7 -0
  52. diffusers/models/vq_model.py +12 -3
  53. diffusers/optimization.py +16 -9
  54. diffusers/pipelines/__init__.py +137 -76
  55. diffusers/pipelines/amused/__init__.py +62 -0
  56. diffusers/pipelines/amused/pipeline_amused.py +328 -0
  57. diffusers/pipelines/amused/pipeline_amused_img2img.py +347 -0
  58. diffusers/pipelines/amused/pipeline_amused_inpaint.py +378 -0
  59. diffusers/pipelines/animatediff/pipeline_animatediff.py +66 -8
  60. diffusers/pipelines/audioldm/pipeline_audioldm.py +1 -0
  61. diffusers/pipelines/auto_pipeline.py +23 -13
  62. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -0
  63. diffusers/pipelines/controlnet/pipeline_controlnet.py +238 -35
  64. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +148 -37
  65. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +155 -41
  66. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +123 -43
  67. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +216 -39
  68. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +106 -34
  69. diffusers/pipelines/dance_diffusion/pipeline_dance_diffusion.py +1 -0
  70. diffusers/pipelines/ddim/pipeline_ddim.py +1 -0
  71. diffusers/pipelines/ddpm/pipeline_ddpm.py +1 -0
  72. diffusers/pipelines/deepfloyd_if/pipeline_if.py +13 -1
  73. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +13 -1
  74. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +13 -1
  75. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +13 -1
  76. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +13 -1
  77. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +13 -1
  78. diffusers/pipelines/deprecated/__init__.py +153 -0
  79. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/__init__.py +3 -3
  80. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion.py +177 -34
  81. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_alt_diffusion_img2img.py +182 -37
  82. diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/pipeline_output.py +1 -1
  83. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/__init__.py +1 -1
  84. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/mel.py +2 -2
  85. diffusers/pipelines/{audio_diffusion → deprecated/audio_diffusion}/pipeline_audio_diffusion.py +4 -4
  86. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/__init__.py +1 -1
  87. diffusers/pipelines/{latent_diffusion_uncond → deprecated/latent_diffusion_uncond}/pipeline_latent_diffusion_uncond.py +4 -4
  88. diffusers/pipelines/{pndm → deprecated/pndm}/__init__.py +1 -1
  89. diffusers/pipelines/{pndm → deprecated/pndm}/pipeline_pndm.py +4 -4
  90. diffusers/pipelines/{repaint → deprecated/repaint}/__init__.py +1 -1
  91. diffusers/pipelines/{repaint → deprecated/repaint}/pipeline_repaint.py +5 -5
  92. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/__init__.py +1 -1
  93. diffusers/pipelines/{score_sde_ve → deprecated/score_sde_ve}/pipeline_score_sde_ve.py +5 -4
  94. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/__init__.py +6 -6
  95. diffusers/pipelines/{spectrogram_diffusion/continous_encoder.py → deprecated/spectrogram_diffusion/continuous_encoder.py} +2 -2
  96. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/midi_utils.py +1 -1
  97. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/notes_encoder.py +2 -2
  98. diffusers/pipelines/{spectrogram_diffusion → deprecated/spectrogram_diffusion}/pipeline_spectrogram_diffusion.py +8 -7
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/__init__.py +55 -0
  100. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_cycle_diffusion.py +34 -13
  101. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_onnx_stable_diffusion_inpaint_legacy.py +7 -6
  102. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_inpaint_legacy.py +12 -11
  103. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_model_editing.py +17 -11
  104. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_paradigms.py +11 -10
  105. diffusers/pipelines/{stable_diffusion → deprecated/stable_diffusion_variants}/pipeline_stable_diffusion_pix2pix_zero.py +14 -13
  106. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/__init__.py +1 -1
  107. diffusers/pipelines/{stochastic_karras_ve → deprecated/stochastic_karras_ve}/pipeline_stochastic_karras_ve.py +4 -4
  108. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/__init__.py +3 -3
  109. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/modeling_text_unet.py +83 -51
  110. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion.py +4 -4
  111. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_dual_guided.py +7 -6
  112. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_image_variation.py +7 -6
  113. diffusers/pipelines/{versatile_diffusion → deprecated/versatile_diffusion}/pipeline_versatile_diffusion_text_to_image.py +7 -6
  114. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/__init__.py +3 -3
  115. diffusers/pipelines/{vq_diffusion → deprecated/vq_diffusion}/pipeline_vq_diffusion.py +5 -5
  116. diffusers/pipelines/dit/pipeline_dit.py +1 -0
  117. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +1 -1
  118. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +3 -3
  119. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +1 -1
  120. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpainting.py +1 -1
  121. diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +1 -1
  122. diffusers/pipelines/kandinsky3/__init__.py +49 -0
  123. diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.py +98 -0
  124. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +589 -0
  125. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +654 -0
  126. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +111 -11
  127. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +102 -9
  128. diffusers/pipelines/latent_diffusion/pipeline_latent_diffusion.py +1 -0
  129. diffusers/pipelines/musicldm/pipeline_musicldm.py +1 -1
  130. diffusers/pipelines/onnx_utils.py +8 -5
  131. diffusers/pipelines/paint_by_example/pipeline_paint_by_example.py +7 -2
  132. diffusers/pipelines/pipeline_flax_utils.py +11 -8
  133. diffusers/pipelines/pipeline_utils.py +63 -42
  134. diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py +247 -38
  135. diffusers/pipelines/shap_e/pipeline_shap_e_img2img.py +3 -3
  136. diffusers/pipelines/stable_diffusion/__init__.py +37 -65
  137. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +75 -78
  138. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +2 -2
  139. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +2 -4
  140. diffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +1 -0
  141. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +174 -11
  142. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +8 -3
  143. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_image_variation.py +1 -0
  144. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +178 -11
  145. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +224 -13
  146. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +74 -20
  147. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_latent_upscale.py +4 -0
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +7 -0
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +5 -0
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +5 -0
  151. diffusers/pipelines/stable_diffusion_attend_and_excite/__init__.py +48 -0
  152. diffusers/pipelines/{stable_diffusion → stable_diffusion_attend_and_excite}/pipeline_stable_diffusion_attend_and_excite.py +6 -2
  153. diffusers/pipelines/stable_diffusion_diffedit/__init__.py +48 -0
  154. diffusers/pipelines/{stable_diffusion → stable_diffusion_diffedit}/pipeline_stable_diffusion_diffedit.py +3 -3
  155. diffusers/pipelines/stable_diffusion_gligen/__init__.py +50 -0
  156. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen.py +3 -2
  157. diffusers/pipelines/{stable_diffusion → stable_diffusion_gligen}/pipeline_stable_diffusion_gligen_text_image.py +4 -3
  158. diffusers/pipelines/stable_diffusion_k_diffusion/__init__.py +60 -0
  159. diffusers/pipelines/{stable_diffusion → stable_diffusion_k_diffusion}/pipeline_stable_diffusion_k_diffusion.py +7 -1
  160. diffusers/pipelines/stable_diffusion_ldm3d/__init__.py +48 -0
  161. diffusers/pipelines/{stable_diffusion → stable_diffusion_ldm3d}/pipeline_stable_diffusion_ldm3d.py +51 -7
  162. diffusers/pipelines/stable_diffusion_panorama/__init__.py +48 -0
  163. diffusers/pipelines/{stable_diffusion → stable_diffusion_panorama}/pipeline_stable_diffusion_panorama.py +57 -8
  164. diffusers/pipelines/stable_diffusion_safe/pipeline_stable_diffusion_safe.py +58 -6
  165. diffusers/pipelines/stable_diffusion_sag/__init__.py +48 -0
  166. diffusers/pipelines/{stable_diffusion → stable_diffusion_sag}/pipeline_stable_diffusion_sag.py +68 -10
  167. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +194 -17
  168. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +205 -16
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +206 -17
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +23 -17
  171. diffusers/pipelines/stable_video_diffusion/__init__.py +58 -0
  172. diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +652 -0
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +108 -12
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +115 -14
  175. diffusers/pipelines/text_to_video_synthesis/__init__.py +2 -0
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +6 -0
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +23 -3
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +334 -10
  179. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +1331 -0
  180. diffusers/pipelines/unclip/pipeline_unclip.py +2 -1
  181. diffusers/pipelines/unclip/pipeline_unclip_image_variation.py +1 -0
  182. diffusers/pipelines/wuerstchen/modeling_paella_vq_model.py +1 -1
  183. diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py +14 -4
  184. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +9 -5
  185. diffusers/pipelines/wuerstchen/pipeline_wuerstchen.py +1 -1
  186. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_combined.py +2 -2
  187. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -1
  188. diffusers/schedulers/__init__.py +4 -4
  189. diffusers/schedulers/deprecated/__init__.py +50 -0
  190. diffusers/schedulers/{scheduling_karras_ve.py → deprecated/scheduling_karras_ve.py} +4 -4
  191. diffusers/schedulers/{scheduling_sde_vp.py → deprecated/scheduling_sde_vp.py} +4 -6
  192. diffusers/schedulers/scheduling_amused.py +162 -0
  193. diffusers/schedulers/scheduling_consistency_models.py +2 -0
  194. diffusers/schedulers/scheduling_ddim.py +1 -3
  195. diffusers/schedulers/scheduling_ddim_inverse.py +2 -7
  196. diffusers/schedulers/scheduling_ddim_parallel.py +1 -3
  197. diffusers/schedulers/scheduling_ddpm.py +47 -3
  198. diffusers/schedulers/scheduling_ddpm_parallel.py +47 -3
  199. diffusers/schedulers/scheduling_deis_multistep.py +28 -6
  200. diffusers/schedulers/scheduling_dpmsolver_multistep.py +28 -6
  201. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +28 -6
  202. diffusers/schedulers/scheduling_dpmsolver_sde.py +3 -3
  203. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +28 -6
  204. diffusers/schedulers/scheduling_euler_ancestral_discrete.py +59 -3
  205. diffusers/schedulers/scheduling_euler_discrete.py +102 -16
  206. diffusers/schedulers/scheduling_heun_discrete.py +17 -5
  207. diffusers/schedulers/scheduling_k_dpm_2_ancestral_discrete.py +17 -5
  208. diffusers/schedulers/scheduling_k_dpm_2_discrete.py +17 -5
  209. diffusers/schedulers/scheduling_lcm.py +123 -29
  210. diffusers/schedulers/scheduling_lms_discrete.py +3 -3
  211. diffusers/schedulers/scheduling_pndm.py +1 -3
  212. diffusers/schedulers/scheduling_repaint.py +1 -3
  213. diffusers/schedulers/scheduling_unipc_multistep.py +28 -6
  214. diffusers/schedulers/scheduling_utils.py +3 -1
  215. diffusers/schedulers/scheduling_utils_flax.py +3 -1
  216. diffusers/training_utils.py +1 -1
  217. diffusers/utils/__init__.py +1 -2
  218. diffusers/utils/constants.py +10 -12
  219. diffusers/utils/dummy_pt_objects.py +75 -0
  220. diffusers/utils/dummy_torch_and_transformers_objects.py +105 -0
  221. diffusers/utils/dynamic_modules_utils.py +18 -22
  222. diffusers/utils/export_utils.py +8 -3
  223. diffusers/utils/hub_utils.py +24 -36
  224. diffusers/utils/logging.py +11 -11
  225. diffusers/utils/outputs.py +5 -5
  226. diffusers/utils/peft_utils.py +88 -44
  227. diffusers/utils/state_dict_utils.py +8 -0
  228. diffusers/utils/testing_utils.py +199 -1
  229. diffusers/utils/torch_utils.py +4 -4
  230. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/METADATA +86 -69
  231. diffusers-0.25.0.dist-info/RECORD +360 -0
  232. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/WHEEL +1 -1
  233. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/entry_points.txt +0 -1
  234. diffusers/loaders.py +0 -3336
  235. diffusers-0.23.1.dist-info/RECORD +0 -323
  236. /diffusers/pipelines/{alt_diffusion → deprecated/alt_diffusion}/modeling_roberta_series.py +0 -0
  237. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/LICENSE +0 -0
  238. {diffusers-0.23.1.dist-info → diffusers-0.25.0.dist-info}/top_level.txt +0 -0
@@ -1,4 +1,5 @@
1
1
  import copy
2
+ import inspect
2
3
  from dataclasses import dataclass
3
4
  from typing import Callable, List, Optional, Union
4
5
 
@@ -9,10 +10,18 @@ import torch.nn.functional as F
9
10
  from torch.nn.functional import grid_sample
10
11
  from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
11
12
 
12
- from diffusers.models import AutoencoderKL, UNet2DConditionModel
13
- from diffusers.pipelines.stable_diffusion import StableDiffusionPipeline, StableDiffusionSafetyChecker
14
- from diffusers.schedulers import KarrasDiffusionSchedulers
15
- from diffusers.utils import BaseOutput
13
+ from ...image_processor import VaeImageProcessor
14
+ from ...loaders import LoraLoaderMixin, TextualInversionLoaderMixin
15
+ from ...models import AutoencoderKL, UNet2DConditionModel
16
+ from ...models.lora import adjust_lora_scale_text_encoder
17
+ from ...schedulers import KarrasDiffusionSchedulers
18
+ from ...utils import USE_PEFT_BACKEND, BaseOutput, logging, scale_lora_layers, unscale_lora_layers
19
+ from ...utils.torch_utils import randn_tensor
20
+ from ..pipeline_utils import DiffusionPipeline
21
+ from ..stable_diffusion import StableDiffusionSafetyChecker
22
+
23
+
24
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
16
25
 
17
26
 
18
27
  def rearrange_0(tensor, f):
@@ -135,7 +144,7 @@ class CrossFrameAttnProcessor2_0:
135
144
 
136
145
  # Cross Frame Attention
137
146
  if not is_cross_attention:
138
- video_length = key.size()[0] // self.batch_size
147
+ video_length = max(1, key.size()[0] // self.batch_size)
139
148
  first_frame_index = [0] * video_length
140
149
 
141
150
  # rearrange keys to have batch and frames in the 1st and 2nd dims respectively
@@ -183,6 +192,7 @@ class TextToVideoPipelineOutput(BaseOutput):
183
192
  List indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content or
184
193
  `None` if safety checking could not be performed.
185
194
  """
195
+
186
196
  images: Union[List[PIL.Image.Image], np.ndarray]
187
197
  nsfw_content_detected: Optional[List[bool]]
188
198
 
@@ -271,7 +281,7 @@ def create_motion_field_and_warp_latents(motion_field_strength_x, motion_field_s
271
281
  return warped_latents
272
282
 
273
283
 
274
- class TextToVideoZeroPipeline(StableDiffusionPipeline):
284
+ class TextToVideoZeroPipeline(DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin):
275
285
  r"""
276
286
  Pipeline for zero-shot text-to-video generation using Stable Diffusion.
277
287
 
@@ -309,8 +319,15 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
309
319
  feature_extractor: CLIPImageProcessor,
310
320
  requires_safety_checker: bool = True,
311
321
  ):
312
- super().__init__(
313
- vae, text_encoder, tokenizer, unet, scheduler, safety_checker, feature_extractor, requires_safety_checker
322
+ super().__init__()
323
+ self.register_modules(
324
+ vae=vae,
325
+ text_encoder=text_encoder,
326
+ tokenizer=tokenizer,
327
+ unet=unet,
328
+ scheduler=scheduler,
329
+ safety_checker=safety_checker,
330
+ feature_extractor=feature_extractor,
314
331
  )
315
332
  processor = (
316
333
  CrossFrameAttnProcessor2_0(batch_size=2)
@@ -319,6 +336,18 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
319
336
  )
320
337
  self.unet.set_attn_processor(processor)
321
338
 
339
+ if safety_checker is None and requires_safety_checker:
340
+ logger.warning(
341
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
342
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
343
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
344
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
345
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
346
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
347
+ )
348
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
349
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
350
+
322
351
  def forward_loop(self, x_t0, t0, t1, generator):
323
352
  """
324
353
  Perform DDPM forward process from time t0 to t1. This is the same as adding noise with corresponding variance.
@@ -338,7 +367,7 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
338
367
  x_t1:
339
368
  Forward process applied to x_t0 from time t0 to t1.
340
369
  """
341
- eps = torch.randn(x_t0.size(), generator=generator, dtype=x_t0.dtype, device=x_t0.device)
370
+ eps = randn_tensor(x_t0.size(), generator=generator, dtype=x_t0.dtype, device=x_t0.device)
342
371
  alpha_vec = torch.prod(self.scheduler.alphas[t0:t1])
343
372
  x_t1 = torch.sqrt(alpha_vec) * x_t0 + torch.sqrt(1 - alpha_vec) * eps
344
373
  return x_t1
@@ -418,6 +447,77 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
418
447
  callback(step_idx, t, latents)
419
448
  return latents.clone().detach()
420
449
 
450
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.check_inputs
451
+ def check_inputs(
452
+ self,
453
+ prompt,
454
+ height,
455
+ width,
456
+ callback_steps,
457
+ negative_prompt=None,
458
+ prompt_embeds=None,
459
+ negative_prompt_embeds=None,
460
+ callback_on_step_end_tensor_inputs=None,
461
+ ):
462
+ if height % 8 != 0 or width % 8 != 0:
463
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
464
+
465
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
466
+ raise ValueError(
467
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
468
+ f" {type(callback_steps)}."
469
+ )
470
+ if callback_on_step_end_tensor_inputs is not None and not all(
471
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
472
+ ):
473
+ raise ValueError(
474
+ 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]}"
475
+ )
476
+
477
+ if prompt is not None and prompt_embeds is not None:
478
+ raise ValueError(
479
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
480
+ " only forward one of the two."
481
+ )
482
+ elif prompt is None and prompt_embeds is None:
483
+ raise ValueError(
484
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
485
+ )
486
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
487
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
488
+
489
+ if negative_prompt is not None and negative_prompt_embeds is not None:
490
+ raise ValueError(
491
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
492
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
493
+ )
494
+
495
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
496
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
497
+ raise ValueError(
498
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
499
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
500
+ f" {negative_prompt_embeds.shape}."
501
+ )
502
+
503
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
504
+ def prepare_latents(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
505
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
506
+ if isinstance(generator, list) and len(generator) != batch_size:
507
+ raise ValueError(
508
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
509
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
510
+ )
511
+
512
+ if latents is None:
513
+ latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
514
+ else:
515
+ latents = latents.to(device)
516
+
517
+ # scale the initial noise by the standard deviation required by the scheduler
518
+ latents = latents * self.scheduler.init_noise_sigma
519
+ return latents
520
+
421
521
  @torch.no_grad()
422
522
  def __call__(
423
523
  self,
@@ -537,9 +637,10 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
537
637
  do_classifier_free_guidance = guidance_scale > 1.0
538
638
 
539
639
  # Encode input prompt
540
- prompt_embeds = self._encode_prompt(
640
+ prompt_embeds_tuple = self.encode_prompt(
541
641
  prompt, device, num_videos_per_prompt, do_classifier_free_guidance, negative_prompt
542
642
  )
643
+ prompt_embeds = torch.cat([prompt_embeds_tuple[1], prompt_embeds_tuple[0]])
543
644
 
544
645
  # Prepare timesteps
545
646
  self.scheduler.set_timesteps(num_inference_steps, device=device)
@@ -643,3 +744,226 @@ class TextToVideoZeroPipeline(StableDiffusionPipeline):
643
744
  return (image, has_nsfw_concept)
644
745
 
645
746
  return TextToVideoPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
747
+
748
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
749
+ def run_safety_checker(self, image, device, dtype):
750
+ if self.safety_checker is None:
751
+ has_nsfw_concept = None
752
+ else:
753
+ if torch.is_tensor(image):
754
+ feature_extractor_input = self.image_processor.postprocess(image, output_type="pil")
755
+ else:
756
+ feature_extractor_input = self.image_processor.numpy_to_pil(image)
757
+ safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device)
758
+ image, has_nsfw_concept = self.safety_checker(
759
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
760
+ )
761
+ return image, has_nsfw_concept
762
+
763
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
764
+ def prepare_extra_step_kwargs(self, generator, eta):
765
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
766
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
767
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
768
+ # and should be between [0, 1]
769
+
770
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
771
+ extra_step_kwargs = {}
772
+ if accepts_eta:
773
+ extra_step_kwargs["eta"] = eta
774
+
775
+ # check if the scheduler accepts generator
776
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
777
+ if accepts_generator:
778
+ extra_step_kwargs["generator"] = generator
779
+ return extra_step_kwargs
780
+
781
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_prompt
782
+ def encode_prompt(
783
+ self,
784
+ prompt,
785
+ device,
786
+ num_images_per_prompt,
787
+ do_classifier_free_guidance,
788
+ negative_prompt=None,
789
+ prompt_embeds: Optional[torch.FloatTensor] = None,
790
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
791
+ lora_scale: Optional[float] = None,
792
+ clip_skip: Optional[int] = None,
793
+ ):
794
+ r"""
795
+ Encodes the prompt into text encoder hidden states.
796
+
797
+ Args:
798
+ prompt (`str` or `List[str]`, *optional*):
799
+ prompt to be encoded
800
+ device: (`torch.device`):
801
+ torch device
802
+ num_images_per_prompt (`int`):
803
+ number of images that should be generated per prompt
804
+ do_classifier_free_guidance (`bool`):
805
+ whether to use classifier free guidance or not
806
+ negative_prompt (`str` or `List[str]`, *optional*):
807
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
808
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
809
+ less than `1`).
810
+ prompt_embeds (`torch.FloatTensor`, *optional*):
811
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
812
+ provided, text embeddings will be generated from `prompt` input argument.
813
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
814
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
815
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
816
+ argument.
817
+ lora_scale (`float`, *optional*):
818
+ A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
819
+ clip_skip (`int`, *optional*):
820
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
821
+ the output of the pre-final layer will be used for computing the prompt embeddings.
822
+ """
823
+ # set lora scale so that monkey patched LoRA
824
+ # function of text encoder can correctly access it
825
+ if lora_scale is not None and isinstance(self, LoraLoaderMixin):
826
+ self._lora_scale = lora_scale
827
+
828
+ # dynamically adjust the LoRA scale
829
+ if not USE_PEFT_BACKEND:
830
+ adjust_lora_scale_text_encoder(self.text_encoder, lora_scale)
831
+ else:
832
+ scale_lora_layers(self.text_encoder, lora_scale)
833
+
834
+ if prompt is not None and isinstance(prompt, str):
835
+ batch_size = 1
836
+ elif prompt is not None and isinstance(prompt, list):
837
+ batch_size = len(prompt)
838
+ else:
839
+ batch_size = prompt_embeds.shape[0]
840
+
841
+ if prompt_embeds is None:
842
+ # textual inversion: procecss multi-vector tokens if necessary
843
+ if isinstance(self, TextualInversionLoaderMixin):
844
+ prompt = self.maybe_convert_prompt(prompt, self.tokenizer)
845
+
846
+ text_inputs = self.tokenizer(
847
+ prompt,
848
+ padding="max_length",
849
+ max_length=self.tokenizer.model_max_length,
850
+ truncation=True,
851
+ return_tensors="pt",
852
+ )
853
+ text_input_ids = text_inputs.input_ids
854
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
855
+
856
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
857
+ text_input_ids, untruncated_ids
858
+ ):
859
+ removed_text = self.tokenizer.batch_decode(
860
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
861
+ )
862
+ logger.warning(
863
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
864
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
865
+ )
866
+
867
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
868
+ attention_mask = text_inputs.attention_mask.to(device)
869
+ else:
870
+ attention_mask = None
871
+
872
+ if clip_skip is None:
873
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask)
874
+ prompt_embeds = prompt_embeds[0]
875
+ else:
876
+ prompt_embeds = self.text_encoder(
877
+ text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True
878
+ )
879
+ # Access the `hidden_states` first, that contains a tuple of
880
+ # all the hidden states from the encoder layers. Then index into
881
+ # the tuple to access the hidden states from the desired layer.
882
+ prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)]
883
+ # We also need to apply the final LayerNorm here to not mess with the
884
+ # representations. The `last_hidden_states` that we typically use for
885
+ # obtaining the final prompt representations passes through the LayerNorm
886
+ # layer.
887
+ prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds)
888
+
889
+ if self.text_encoder is not None:
890
+ prompt_embeds_dtype = self.text_encoder.dtype
891
+ elif self.unet is not None:
892
+ prompt_embeds_dtype = self.unet.dtype
893
+ else:
894
+ prompt_embeds_dtype = prompt_embeds.dtype
895
+
896
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
897
+
898
+ bs_embed, seq_len, _ = prompt_embeds.shape
899
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
900
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
901
+ prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
902
+
903
+ # get unconditional embeddings for classifier free guidance
904
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
905
+ uncond_tokens: List[str]
906
+ if negative_prompt is None:
907
+ uncond_tokens = [""] * batch_size
908
+ elif prompt is not None and type(prompt) is not type(negative_prompt):
909
+ raise TypeError(
910
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
911
+ f" {type(prompt)}."
912
+ )
913
+ elif isinstance(negative_prompt, str):
914
+ uncond_tokens = [negative_prompt]
915
+ elif batch_size != len(negative_prompt):
916
+ raise ValueError(
917
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
918
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
919
+ " the batch size of `prompt`."
920
+ )
921
+ else:
922
+ uncond_tokens = negative_prompt
923
+
924
+ # textual inversion: procecss multi-vector tokens if necessary
925
+ if isinstance(self, TextualInversionLoaderMixin):
926
+ uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer)
927
+
928
+ max_length = prompt_embeds.shape[1]
929
+ uncond_input = self.tokenizer(
930
+ uncond_tokens,
931
+ padding="max_length",
932
+ max_length=max_length,
933
+ truncation=True,
934
+ return_tensors="pt",
935
+ )
936
+
937
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
938
+ attention_mask = uncond_input.attention_mask.to(device)
939
+ else:
940
+ attention_mask = None
941
+
942
+ negative_prompt_embeds = self.text_encoder(
943
+ uncond_input.input_ids.to(device),
944
+ attention_mask=attention_mask,
945
+ )
946
+ negative_prompt_embeds = negative_prompt_embeds[0]
947
+
948
+ if do_classifier_free_guidance:
949
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
950
+ seq_len = negative_prompt_embeds.shape[1]
951
+
952
+ negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
953
+
954
+ negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
955
+ negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
956
+
957
+ if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND:
958
+ # Retrieve the original scale by scaling back the LoRA layers
959
+ unscale_lora_layers(self.text_encoder, lora_scale)
960
+
961
+ return prompt_embeds, negative_prompt_embeds
962
+
963
+ def decode_latents(self, latents):
964
+ latents = 1 / self.vae.config.scaling_factor * latents
965
+ image = self.vae.decode(latents, return_dict=False)[0]
966
+ image = (image / 2 + 0.5).clamp(0, 1)
967
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
968
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
969
+ return image