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
@@ -0,0 +1,59 @@
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Dict
16
+
17
+ import torch
18
+
19
+
20
+ class AttnProcsLayers(torch.nn.Module):
21
+ def __init__(self, state_dict: Dict[str, torch.Tensor]):
22
+ super().__init__()
23
+ self.layers = torch.nn.ModuleList(state_dict.values())
24
+ self.mapping = dict(enumerate(state_dict.keys()))
25
+ self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
26
+
27
+ # .processor for unet, .self_attn for text encoder
28
+ self.split_keys = [".processor", ".self_attn"]
29
+
30
+ # we add a hook to state_dict() and load_state_dict() so that the
31
+ # naming fits with `unet.attn_processors`
32
+ def map_to(module, state_dict, *args, **kwargs):
33
+ new_state_dict = {}
34
+ for key, value in state_dict.items():
35
+ num = int(key.split(".")[1]) # 0 is always "layers"
36
+ new_key = key.replace(f"layers.{num}", module.mapping[num])
37
+ new_state_dict[new_key] = value
38
+
39
+ return new_state_dict
40
+
41
+ def remap_key(key, state_dict):
42
+ for k in self.split_keys:
43
+ if k in key:
44
+ return key.split(k)[0] + k
45
+
46
+ raise ValueError(
47
+ f"There seems to be a problem with the state_dict: {set(state_dict.keys())}. {key} has to have one of {self.split_keys}."
48
+ )
49
+
50
+ def map_from(module, state_dict, *args, **kwargs):
51
+ all_keys = list(state_dict.keys())
52
+ for key in all_keys:
53
+ replace_key = remap_key(key, state_dict)
54
+ new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
55
+ state_dict[new_key] = state_dict[key]
56
+ del state_dict[key]
57
+
58
+ self._register_state_dict_hook(map_to)
59
+ self._register_load_state_dict_pre_hook(map_from, with_module=True)
@@ -14,19 +14,26 @@
14
14
 
15
15
  from typing import TYPE_CHECKING
16
16
 
17
- from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, is_flax_available, is_torch_available
17
+ from ..utils import (
18
+ DIFFUSERS_SLOW_IMPORT,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_torch_available,
22
+ )
18
23
 
19
24
 
20
25
  _import_structure = {}
21
26
 
22
27
  if is_torch_available():
23
28
  _import_structure["adapter"] = ["MultiAdapter", "T2IAdapter"]
24
- _import_structure["autoencoder_asym_kl"] = ["AsymmetricAutoencoderKL"]
25
- _import_structure["autoencoder_kl"] = ["AutoencoderKL"]
26
- _import_structure["autoencoder_tiny"] = ["AutoencoderTiny"]
27
- _import_structure["consistency_decoder_vae"] = ["ConsistencyDecoderVAE"]
29
+ _import_structure["autoencoders.autoencoder_asym_kl"] = ["AsymmetricAutoencoderKL"]
30
+ _import_structure["autoencoders.autoencoder_kl"] = ["AutoencoderKL"]
31
+ _import_structure["autoencoders.autoencoder_kl_temporal_decoder"] = ["AutoencoderKLTemporalDecoder"]
32
+ _import_structure["autoencoders.autoencoder_tiny"] = ["AutoencoderTiny"]
33
+ _import_structure["autoencoders.consistency_decoder_vae"] = ["ConsistencyDecoderVAE"]
28
34
  _import_structure["controlnet"] = ["ControlNetModel"]
29
35
  _import_structure["dual_transformer_2d"] = ["DualTransformer2DModel"]
36
+ _import_structure["embeddings"] = ["ImageProjection"]
30
37
  _import_structure["modeling_utils"] = ["ModelMixin"]
31
38
  _import_structure["prior_transformer"] = ["PriorTransformer"]
32
39
  _import_structure["t5_film_transformer"] = ["T5FilmDecoder"]
@@ -36,7 +43,10 @@ if is_torch_available():
36
43
  _import_structure["unet_2d"] = ["UNet2DModel"]
37
44
  _import_structure["unet_2d_condition"] = ["UNet2DConditionModel"]
38
45
  _import_structure["unet_3d_condition"] = ["UNet3DConditionModel"]
46
+ _import_structure["unet_kandinsky3"] = ["Kandinsky3UNet"]
39
47
  _import_structure["unet_motion_model"] = ["MotionAdapter", "UNetMotionModel"]
48
+ _import_structure["unet_spatio_temporal_condition"] = ["UNetSpatioTemporalConditionModel"]
49
+ _import_structure["uvit_2d"] = ["UVit2DModel"]
40
50
  _import_structure["vq_model"] = ["VQModel"]
41
51
 
42
52
  if is_flax_available():
@@ -48,12 +58,16 @@ if is_flax_available():
48
58
  if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
49
59
  if is_torch_available():
50
60
  from .adapter import MultiAdapter, T2IAdapter
51
- from .autoencoder_asym_kl import AsymmetricAutoencoderKL
52
- from .autoencoder_kl import AutoencoderKL
53
- from .autoencoder_tiny import AutoencoderTiny
54
- from .consistency_decoder_vae import ConsistencyDecoderVAE
61
+ from .autoencoders import (
62
+ AsymmetricAutoencoderKL,
63
+ AutoencoderKL,
64
+ AutoencoderKLTemporalDecoder,
65
+ AutoencoderTiny,
66
+ ConsistencyDecoderVAE,
67
+ )
55
68
  from .controlnet import ControlNetModel
56
69
  from .dual_transformer_2d import DualTransformer2DModel
70
+ from .embeddings import ImageProjection
57
71
  from .modeling_utils import ModelMixin
58
72
  from .prior_transformer import PriorTransformer
59
73
  from .t5_film_transformer import T5FilmDecoder
@@ -63,7 +77,10 @@ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
63
77
  from .unet_2d import UNet2DModel
64
78
  from .unet_2d_condition import UNet2DConditionModel
65
79
  from .unet_3d_condition import UNet3DConditionModel
80
+ from .unet_kandinsky3 import Kandinsky3UNet
66
81
  from .unet_motion_model import MotionAdapter, UNetMotionModel
82
+ from .unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel
83
+ from .uvit_2d import UVit2DModel
67
84
  from .vq_model import VQModel
68
85
 
69
86
  if is_flax_available():
@@ -55,11 +55,12 @@ class GELU(nn.Module):
55
55
  dim_in (`int`): The number of channels in the input.
56
56
  dim_out (`int`): The number of channels in the output.
57
57
  approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
58
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
58
59
  """
59
60
 
60
- def __init__(self, dim_in: int, dim_out: int, approximate: str = "none"):
61
+ def __init__(self, dim_in: int, dim_out: int, approximate: str = "none", bias: bool = True):
61
62
  super().__init__()
62
- self.proj = nn.Linear(dim_in, dim_out)
63
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
63
64
  self.approximate = approximate
64
65
 
65
66
  def gelu(self, gate: torch.Tensor) -> torch.Tensor:
@@ -81,13 +82,14 @@ class GEGLU(nn.Module):
81
82
  Parameters:
82
83
  dim_in (`int`): The number of channels in the input.
83
84
  dim_out (`int`): The number of channels in the output.
85
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
84
86
  """
85
87
 
86
- def __init__(self, dim_in: int, dim_out: int):
88
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
87
89
  super().__init__()
88
90
  linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
89
91
 
90
- self.proj = linear_cls(dim_in, dim_out * 2)
92
+ self.proj = linear_cls(dim_in, dim_out * 2, bias=bias)
91
93
 
92
94
  def gelu(self, gate: torch.Tensor) -> torch.Tensor:
93
95
  if gate.device.type != "mps":
@@ -109,11 +111,12 @@ class ApproximateGELU(nn.Module):
109
111
  Parameters:
110
112
  dim_in (`int`): The number of channels in the input.
111
113
  dim_out (`int`): The number of channels in the output.
114
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
112
115
  """
113
116
 
114
- def __init__(self, dim_in: int, dim_out: int):
117
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
115
118
  super().__init__()
116
- self.proj = nn.Linear(dim_in, dim_out)
119
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
117
120
 
118
121
  def forward(self, x: torch.Tensor) -> torch.Tensor:
119
122
  x = self.proj(x)
@@ -14,6 +14,7 @@
14
14
  from typing import Any, Dict, Optional
15
15
 
16
16
  import torch
17
+ import torch.nn.functional as F
17
18
  from torch import nn
18
19
 
19
20
  from ..utils import USE_PEFT_BACKEND
@@ -22,7 +23,32 @@ from .activations import GEGLU, GELU, ApproximateGELU
22
23
  from .attention_processor import Attention
23
24
  from .embeddings import SinusoidalPositionalEmbedding
24
25
  from .lora import LoRACompatibleLinear
25
- from .normalization import AdaLayerNorm, AdaLayerNormZero
26
+ from .normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
27
+
28
+
29
+ def _chunked_feed_forward(
30
+ ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
31
+ ):
32
+ # "feed_forward_chunk_size" can be used to save memory
33
+ if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
+ raise ValueError(
35
+ f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
36
+ )
37
+
38
+ num_chunks = hidden_states.shape[chunk_dim] // chunk_size
39
+ if lora_scale is None:
40
+ ff_output = torch.cat(
41
+ [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
42
+ dim=chunk_dim,
43
+ )
44
+ else:
45
+ # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
46
+ ff_output = torch.cat(
47
+ [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
48
+ dim=chunk_dim,
49
+ )
50
+
51
+ return ff_output
26
52
 
27
53
 
28
54
  @maybe_allow_in_graph
@@ -123,6 +149,11 @@ class BasicTransformerBlock(nn.Module):
123
149
  attention_type: str = "default",
124
150
  positional_embeddings: Optional[str] = None,
125
151
  num_positional_embeddings: Optional[int] = None,
152
+ ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
153
+ ada_norm_bias: Optional[int] = None,
154
+ ff_inner_dim: Optional[int] = None,
155
+ ff_bias: bool = True,
156
+ attention_out_bias: bool = True,
126
157
  ):
127
158
  super().__init__()
128
159
  self.only_cross_attention = only_cross_attention
@@ -131,6 +162,7 @@ class BasicTransformerBlock(nn.Module):
131
162
  self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
132
163
  self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
133
164
  self.use_layer_norm = norm_type == "layer_norm"
165
+ self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
134
166
 
135
167
  if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
136
168
  raise ValueError(
@@ -154,6 +186,15 @@ class BasicTransformerBlock(nn.Module):
154
186
  self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
155
187
  elif self.use_ada_layer_norm_zero:
156
188
  self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
189
+ elif self.use_ada_layer_norm_continuous:
190
+ self.norm1 = AdaLayerNormContinuous(
191
+ dim,
192
+ ada_norm_continous_conditioning_embedding_dim,
193
+ norm_elementwise_affine,
194
+ norm_eps,
195
+ ada_norm_bias,
196
+ "rms_norm",
197
+ )
157
198
  else:
158
199
  self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
159
200
 
@@ -165,6 +206,7 @@ class BasicTransformerBlock(nn.Module):
165
206
  bias=attention_bias,
166
207
  cross_attention_dim=cross_attention_dim if only_cross_attention else None,
167
208
  upcast_attention=upcast_attention,
209
+ out_bias=attention_out_bias,
168
210
  )
169
211
 
170
212
  # 2. Cross-Attn
@@ -172,11 +214,20 @@ class BasicTransformerBlock(nn.Module):
172
214
  # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
173
215
  # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
174
216
  # the second cross attention block.
175
- self.norm2 = (
176
- AdaLayerNorm(dim, num_embeds_ada_norm)
177
- if self.use_ada_layer_norm
178
- else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
179
- )
217
+ if self.use_ada_layer_norm:
218
+ self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
219
+ elif self.use_ada_layer_norm_continuous:
220
+ self.norm2 = AdaLayerNormContinuous(
221
+ dim,
222
+ ada_norm_continous_conditioning_embedding_dim,
223
+ norm_elementwise_affine,
224
+ norm_eps,
225
+ ada_norm_bias,
226
+ "rms_norm",
227
+ )
228
+ else:
229
+ self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
230
+
180
231
  self.attn2 = Attention(
181
232
  query_dim=dim,
182
233
  cross_attention_dim=cross_attention_dim if not double_self_attention else None,
@@ -185,16 +236,33 @@ class BasicTransformerBlock(nn.Module):
185
236
  dropout=dropout,
186
237
  bias=attention_bias,
187
238
  upcast_attention=upcast_attention,
239
+ out_bias=attention_out_bias,
188
240
  ) # is self-attn if encoder_hidden_states is none
189
241
  else:
190
242
  self.norm2 = None
191
243
  self.attn2 = None
192
244
 
193
245
  # 3. Feed-forward
194
- if not self.use_ada_layer_norm_single:
195
- self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
246
+ if self.use_ada_layer_norm_continuous:
247
+ self.norm3 = AdaLayerNormContinuous(
248
+ dim,
249
+ ada_norm_continous_conditioning_embedding_dim,
250
+ norm_elementwise_affine,
251
+ norm_eps,
252
+ ada_norm_bias,
253
+ "layer_norm",
254
+ )
255
+ elif not self.use_ada_layer_norm_single:
256
+ self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
196
257
 
197
- self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn, final_dropout=final_dropout)
258
+ self.ff = FeedForward(
259
+ dim,
260
+ dropout=dropout,
261
+ activation_fn=activation_fn,
262
+ final_dropout=final_dropout,
263
+ inner_dim=ff_inner_dim,
264
+ bias=ff_bias,
265
+ )
198
266
 
199
267
  # 4. Fuser
200
268
  if attention_type == "gated" or attention_type == "gated-text-image":
@@ -208,7 +276,7 @@ class BasicTransformerBlock(nn.Module):
208
276
  self._chunk_size = None
209
277
  self._chunk_dim = 0
210
278
 
211
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int):
279
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
212
280
  # Sets chunk feed-forward
213
281
  self._chunk_size = chunk_size
214
282
  self._chunk_dim = dim
@@ -222,6 +290,7 @@ class BasicTransformerBlock(nn.Module):
222
290
  timestep: Optional[torch.LongTensor] = None,
223
291
  cross_attention_kwargs: Dict[str, Any] = None,
224
292
  class_labels: Optional[torch.LongTensor] = None,
293
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
225
294
  ) -> torch.FloatTensor:
226
295
  # Notice that normalization is always applied before the real computation in the following blocks.
227
296
  # 0. Self-Attention
@@ -235,6 +304,8 @@ class BasicTransformerBlock(nn.Module):
235
304
  )
236
305
  elif self.use_layer_norm:
237
306
  norm_hidden_states = self.norm1(hidden_states)
307
+ elif self.use_ada_layer_norm_continuous:
308
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
238
309
  elif self.use_ada_layer_norm_single:
239
310
  shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
240
311
  self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
@@ -284,6 +355,8 @@ class BasicTransformerBlock(nn.Module):
284
355
  # For PixArt norm2 isn't applied here:
285
356
  # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
286
357
  norm_hidden_states = hidden_states
358
+ elif self.use_ada_layer_norm_continuous:
359
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
287
360
  else:
288
361
  raise ValueError("Incorrect norm")
289
362
 
@@ -299,7 +372,9 @@ class BasicTransformerBlock(nn.Module):
299
372
  hidden_states = attn_output + hidden_states
300
373
 
301
374
  # 4. Feed-forward
302
- if not self.use_ada_layer_norm_single:
375
+ if self.use_ada_layer_norm_continuous:
376
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
377
+ elif not self.use_ada_layer_norm_single:
303
378
  norm_hidden_states = self.norm3(hidden_states)
304
379
 
305
380
  if self.use_ada_layer_norm_zero:
@@ -311,18 +386,8 @@ class BasicTransformerBlock(nn.Module):
311
386
 
312
387
  if self._chunk_size is not None:
313
388
  # "feed_forward_chunk_size" can be used to save memory
314
- if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
315
- raise ValueError(
316
- f"`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
317
- )
318
-
319
- num_chunks = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
320
- ff_output = torch.cat(
321
- [
322
- self.ff(hid_slice, scale=lora_scale)
323
- for hid_slice in norm_hidden_states.chunk(num_chunks, dim=self._chunk_dim)
324
- ],
325
- dim=self._chunk_dim,
389
+ ff_output = _chunked_feed_forward(
390
+ self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
326
391
  )
327
392
  else:
328
393
  ff_output = self.ff(norm_hidden_states, scale=lora_scale)
@@ -339,6 +404,209 @@ class BasicTransformerBlock(nn.Module):
339
404
  return hidden_states
340
405
 
341
406
 
407
+ @maybe_allow_in_graph
408
+ class TemporalBasicTransformerBlock(nn.Module):
409
+ r"""
410
+ A basic Transformer block for video like data.
411
+
412
+ Parameters:
413
+ dim (`int`): The number of channels in the input and output.
414
+ time_mix_inner_dim (`int`): The number of channels for temporal attention.
415
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
416
+ attention_head_dim (`int`): The number of channels in each head.
417
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
418
+ """
419
+
420
+ def __init__(
421
+ self,
422
+ dim: int,
423
+ time_mix_inner_dim: int,
424
+ num_attention_heads: int,
425
+ attention_head_dim: int,
426
+ cross_attention_dim: Optional[int] = None,
427
+ ):
428
+ super().__init__()
429
+ self.is_res = dim == time_mix_inner_dim
430
+
431
+ self.norm_in = nn.LayerNorm(dim)
432
+
433
+ # Define 3 blocks. Each block has its own normalization layer.
434
+ # 1. Self-Attn
435
+ self.norm_in = nn.LayerNorm(dim)
436
+ self.ff_in = FeedForward(
437
+ dim,
438
+ dim_out=time_mix_inner_dim,
439
+ activation_fn="geglu",
440
+ )
441
+
442
+ self.norm1 = nn.LayerNorm(time_mix_inner_dim)
443
+ self.attn1 = Attention(
444
+ query_dim=time_mix_inner_dim,
445
+ heads=num_attention_heads,
446
+ dim_head=attention_head_dim,
447
+ cross_attention_dim=None,
448
+ )
449
+
450
+ # 2. Cross-Attn
451
+ if cross_attention_dim is not None:
452
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
453
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
454
+ # the second cross attention block.
455
+ self.norm2 = nn.LayerNorm(time_mix_inner_dim)
456
+ self.attn2 = Attention(
457
+ query_dim=time_mix_inner_dim,
458
+ cross_attention_dim=cross_attention_dim,
459
+ heads=num_attention_heads,
460
+ dim_head=attention_head_dim,
461
+ ) # is self-attn if encoder_hidden_states is none
462
+ else:
463
+ self.norm2 = None
464
+ self.attn2 = None
465
+
466
+ # 3. Feed-forward
467
+ self.norm3 = nn.LayerNorm(time_mix_inner_dim)
468
+ self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
469
+
470
+ # let chunk size default to None
471
+ self._chunk_size = None
472
+ self._chunk_dim = None
473
+
474
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
475
+ # Sets chunk feed-forward
476
+ self._chunk_size = chunk_size
477
+ # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
478
+ self._chunk_dim = 1
479
+
480
+ def forward(
481
+ self,
482
+ hidden_states: torch.FloatTensor,
483
+ num_frames: int,
484
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
485
+ ) -> torch.FloatTensor:
486
+ # Notice that normalization is always applied before the real computation in the following blocks.
487
+ # 0. Self-Attention
488
+ batch_size = hidden_states.shape[0]
489
+
490
+ batch_frames, seq_length, channels = hidden_states.shape
491
+ batch_size = batch_frames // num_frames
492
+
493
+ hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
494
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
495
+ hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
496
+
497
+ residual = hidden_states
498
+ hidden_states = self.norm_in(hidden_states)
499
+
500
+ if self._chunk_size is not None:
501
+ hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
502
+ else:
503
+ hidden_states = self.ff_in(hidden_states)
504
+
505
+ if self.is_res:
506
+ hidden_states = hidden_states + residual
507
+
508
+ norm_hidden_states = self.norm1(hidden_states)
509
+ attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
510
+ hidden_states = attn_output + hidden_states
511
+
512
+ # 3. Cross-Attention
513
+ if self.attn2 is not None:
514
+ norm_hidden_states = self.norm2(hidden_states)
515
+ attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
516
+ hidden_states = attn_output + hidden_states
517
+
518
+ # 4. Feed-forward
519
+ norm_hidden_states = self.norm3(hidden_states)
520
+
521
+ if self._chunk_size is not None:
522
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
523
+ else:
524
+ ff_output = self.ff(norm_hidden_states)
525
+
526
+ if self.is_res:
527
+ hidden_states = ff_output + hidden_states
528
+ else:
529
+ hidden_states = ff_output
530
+
531
+ hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
532
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
533
+ hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
534
+
535
+ return hidden_states
536
+
537
+
538
+ class SkipFFTransformerBlock(nn.Module):
539
+ def __init__(
540
+ self,
541
+ dim: int,
542
+ num_attention_heads: int,
543
+ attention_head_dim: int,
544
+ kv_input_dim: int,
545
+ kv_input_dim_proj_use_bias: bool,
546
+ dropout=0.0,
547
+ cross_attention_dim: Optional[int] = None,
548
+ attention_bias: bool = False,
549
+ attention_out_bias: bool = True,
550
+ ):
551
+ super().__init__()
552
+ if kv_input_dim != dim:
553
+ self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
554
+ else:
555
+ self.kv_mapper = None
556
+
557
+ self.norm1 = RMSNorm(dim, 1e-06)
558
+
559
+ self.attn1 = Attention(
560
+ query_dim=dim,
561
+ heads=num_attention_heads,
562
+ dim_head=attention_head_dim,
563
+ dropout=dropout,
564
+ bias=attention_bias,
565
+ cross_attention_dim=cross_attention_dim,
566
+ out_bias=attention_out_bias,
567
+ )
568
+
569
+ self.norm2 = RMSNorm(dim, 1e-06)
570
+
571
+ self.attn2 = Attention(
572
+ query_dim=dim,
573
+ cross_attention_dim=cross_attention_dim,
574
+ heads=num_attention_heads,
575
+ dim_head=attention_head_dim,
576
+ dropout=dropout,
577
+ bias=attention_bias,
578
+ out_bias=attention_out_bias,
579
+ )
580
+
581
+ def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
582
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
583
+
584
+ if self.kv_mapper is not None:
585
+ encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
586
+
587
+ norm_hidden_states = self.norm1(hidden_states)
588
+
589
+ attn_output = self.attn1(
590
+ norm_hidden_states,
591
+ encoder_hidden_states=encoder_hidden_states,
592
+ **cross_attention_kwargs,
593
+ )
594
+
595
+ hidden_states = attn_output + hidden_states
596
+
597
+ norm_hidden_states = self.norm2(hidden_states)
598
+
599
+ attn_output = self.attn2(
600
+ norm_hidden_states,
601
+ encoder_hidden_states=encoder_hidden_states,
602
+ **cross_attention_kwargs,
603
+ )
604
+
605
+ hidden_states = attn_output + hidden_states
606
+
607
+ return hidden_states
608
+
609
+
342
610
  class FeedForward(nn.Module):
343
611
  r"""
344
612
  A feed-forward layer.
@@ -350,6 +618,7 @@ class FeedForward(nn.Module):
350
618
  dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
351
619
  activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
352
620
  final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
621
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
353
622
  """
354
623
 
355
624
  def __init__(
@@ -360,20 +629,23 @@ class FeedForward(nn.Module):
360
629
  dropout: float = 0.0,
361
630
  activation_fn: str = "geglu",
362
631
  final_dropout: bool = False,
632
+ inner_dim=None,
633
+ bias: bool = True,
363
634
  ):
364
635
  super().__init__()
365
- inner_dim = int(dim * mult)
636
+ if inner_dim is None:
637
+ inner_dim = int(dim * mult)
366
638
  dim_out = dim_out if dim_out is not None else dim
367
639
  linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
368
640
 
369
641
  if activation_fn == "gelu":
370
- act_fn = GELU(dim, inner_dim)
642
+ act_fn = GELU(dim, inner_dim, bias=bias)
371
643
  if activation_fn == "gelu-approximate":
372
- act_fn = GELU(dim, inner_dim, approximate="tanh")
644
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
373
645
  elif activation_fn == "geglu":
374
- act_fn = GEGLU(dim, inner_dim)
646
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
375
647
  elif activation_fn == "geglu-approximate":
376
- act_fn = ApproximateGELU(dim, inner_dim)
648
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
377
649
 
378
650
  self.net = nn.ModuleList([])
379
651
  # project in
@@ -381,7 +653,7 @@ class FeedForward(nn.Module):
381
653
  # project dropout
382
654
  self.net.append(nn.Dropout(dropout))
383
655
  # project out
384
- self.net.append(linear_cls(inner_dim, dim_out))
656
+ self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
385
657
  # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
386
658
  if final_dropout:
387
659
  self.net.append(nn.Dropout(dropout))