diffusers 0.29.2__py3-none-any.whl → 0.30.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. diffusers/__init__.py +94 -3
  2. diffusers/commands/env.py +1 -5
  3. diffusers/configuration_utils.py +4 -9
  4. diffusers/dependency_versions_table.py +2 -2
  5. diffusers/image_processor.py +1 -2
  6. diffusers/loaders/__init__.py +17 -2
  7. diffusers/loaders/ip_adapter.py +10 -7
  8. diffusers/loaders/lora_base.py +752 -0
  9. diffusers/loaders/lora_pipeline.py +2222 -0
  10. diffusers/loaders/peft.py +213 -5
  11. diffusers/loaders/single_file.py +1 -12
  12. diffusers/loaders/single_file_model.py +31 -10
  13. diffusers/loaders/single_file_utils.py +262 -2
  14. diffusers/loaders/textual_inversion.py +1 -6
  15. diffusers/loaders/unet.py +23 -208
  16. diffusers/models/__init__.py +20 -0
  17. diffusers/models/activations.py +22 -0
  18. diffusers/models/attention.py +386 -7
  19. diffusers/models/attention_processor.py +1795 -629
  20. diffusers/models/autoencoders/__init__.py +2 -0
  21. diffusers/models/autoencoders/autoencoder_kl.py +14 -3
  22. diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1035 -0
  23. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
  24. diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
  25. diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
  26. diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
  27. diffusers/models/autoencoders/vq_model.py +4 -4
  28. diffusers/models/controlnet.py +2 -3
  29. diffusers/models/controlnet_hunyuan.py +401 -0
  30. diffusers/models/controlnet_sd3.py +11 -11
  31. diffusers/models/controlnet_sparsectrl.py +789 -0
  32. diffusers/models/controlnet_xs.py +40 -10
  33. diffusers/models/downsampling.py +68 -0
  34. diffusers/models/embeddings.py +319 -36
  35. diffusers/models/model_loading_utils.py +1 -3
  36. diffusers/models/modeling_flax_utils.py +1 -6
  37. diffusers/models/modeling_utils.py +4 -16
  38. diffusers/models/normalization.py +203 -12
  39. diffusers/models/transformers/__init__.py +6 -0
  40. diffusers/models/transformers/auraflow_transformer_2d.py +527 -0
  41. diffusers/models/transformers/cogvideox_transformer_3d.py +345 -0
  42. diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
  43. diffusers/models/transformers/latte_transformer_3d.py +327 -0
  44. diffusers/models/transformers/lumina_nextdit2d.py +340 -0
  45. diffusers/models/transformers/pixart_transformer_2d.py +102 -1
  46. diffusers/models/transformers/prior_transformer.py +1 -1
  47. diffusers/models/transformers/stable_audio_transformer.py +458 -0
  48. diffusers/models/transformers/transformer_flux.py +455 -0
  49. diffusers/models/transformers/transformer_sd3.py +18 -4
  50. diffusers/models/unets/unet_1d_blocks.py +1 -1
  51. diffusers/models/unets/unet_2d_condition.py +8 -1
  52. diffusers/models/unets/unet_3d_blocks.py +51 -920
  53. diffusers/models/unets/unet_3d_condition.py +4 -1
  54. diffusers/models/unets/unet_i2vgen_xl.py +4 -1
  55. diffusers/models/unets/unet_kandinsky3.py +1 -1
  56. diffusers/models/unets/unet_motion_model.py +1330 -84
  57. diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
  58. diffusers/models/unets/unet_stable_cascade.py +1 -3
  59. diffusers/models/unets/uvit_2d.py +1 -1
  60. diffusers/models/upsampling.py +64 -0
  61. diffusers/models/vq_model.py +8 -4
  62. diffusers/optimization.py +1 -1
  63. diffusers/pipelines/__init__.py +100 -3
  64. diffusers/pipelines/animatediff/__init__.py +4 -0
  65. diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
  66. diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
  67. diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
  68. diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
  69. diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
  70. diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
  71. diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
  72. diffusers/pipelines/aura_flow/__init__.py +48 -0
  73. diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
  74. diffusers/pipelines/auto_pipeline.py +97 -19
  75. diffusers/pipelines/cogvideo/__init__.py +48 -0
  76. diffusers/pipelines/cogvideo/pipeline_cogvideox.py +687 -0
  77. diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
  78. diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
  79. diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
  80. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
  81. diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
  82. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
  83. diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
  84. diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
  85. diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
  86. diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
  87. diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
  88. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
  89. diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
  90. diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
  91. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
  92. diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
  93. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
  94. diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
  95. diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
  96. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
  97. diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
  98. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
  99. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
  100. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
  101. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
  102. diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
  103. diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
  104. diffusers/pipelines/flux/__init__.py +47 -0
  105. diffusers/pipelines/flux/pipeline_flux.py +749 -0
  106. diffusers/pipelines/flux/pipeline_output.py +21 -0
  107. diffusers/pipelines/free_init_utils.py +2 -0
  108. diffusers/pipelines/free_noise_utils.py +236 -0
  109. diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
  110. diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
  111. diffusers/pipelines/kolors/__init__.py +54 -0
  112. diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
  113. diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
  114. diffusers/pipelines/kolors/pipeline_output.py +21 -0
  115. diffusers/pipelines/kolors/text_encoder.py +889 -0
  116. diffusers/pipelines/kolors/tokenizer.py +334 -0
  117. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
  118. diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
  119. diffusers/pipelines/latte/__init__.py +48 -0
  120. diffusers/pipelines/latte/pipeline_latte.py +881 -0
  121. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
  122. diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
  123. diffusers/pipelines/lumina/__init__.py +48 -0
  124. diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
  125. diffusers/pipelines/pag/__init__.py +67 -0
  126. diffusers/pipelines/pag/pag_utils.py +237 -0
  127. diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
  128. diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
  129. diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
  130. diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
  131. diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
  132. diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
  133. diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
  134. diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
  135. diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
  136. diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
  137. diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
  138. diffusers/pipelines/pia/pipeline_pia.py +30 -37
  139. diffusers/pipelines/pipeline_flax_utils.py +4 -9
  140. diffusers/pipelines/pipeline_loading_utils.py +0 -3
  141. diffusers/pipelines/pipeline_utils.py +2 -14
  142. diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
  143. diffusers/pipelines/stable_audio/__init__.py +50 -0
  144. diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
  145. diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
  146. diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
  147. diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
  148. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
  149. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
  150. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
  151. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
  152. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
  153. diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
  154. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
  155. diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
  156. diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
  157. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
  158. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
  159. diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
  160. diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
  161. diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
  162. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
  163. diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
  164. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
  165. diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
  166. diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
  167. diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
  168. diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
  169. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
  170. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
  171. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
  172. diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
  173. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
  174. diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
  175. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
  176. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
  177. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
  178. diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
  179. diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
  180. diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
  181. diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
  182. diffusers/schedulers/__init__.py +8 -0
  183. diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
  184. diffusers/schedulers/scheduling_ddim.py +1 -1
  185. diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
  186. diffusers/schedulers/scheduling_ddpm.py +1 -1
  187. diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
  188. diffusers/schedulers/scheduling_deis_multistep.py +2 -2
  189. diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
  190. diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
  191. diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
  192. diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
  193. diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
  194. diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
  195. diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
  196. diffusers/schedulers/scheduling_ipndm.py +1 -1
  197. diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
  198. diffusers/schedulers/scheduling_utils.py +1 -3
  199. diffusers/schedulers/scheduling_utils_flax.py +1 -3
  200. diffusers/training_utils.py +99 -14
  201. diffusers/utils/__init__.py +2 -2
  202. diffusers/utils/dummy_pt_objects.py +210 -0
  203. diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
  204. diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
  205. diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
  206. diffusers/utils/dynamic_modules_utils.py +1 -11
  207. diffusers/utils/export_utils.py +1 -4
  208. diffusers/utils/hub_utils.py +45 -42
  209. diffusers/utils/import_utils.py +19 -16
  210. diffusers/utils/loading_utils.py +76 -3
  211. diffusers/utils/testing_utils.py +11 -8
  212. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/METADATA +73 -83
  213. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/RECORD +217 -164
  214. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/WHEEL +1 -1
  215. diffusers/loaders/autoencoder.py +0 -146
  216. diffusers/loaders/controlnet.py +0 -136
  217. diffusers/loaders/lora.py +0 -1728
  218. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/LICENSE +0 -0
  219. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/entry_points.txt +0 -0
  220. {diffusers-0.29.2.dist-info → diffusers-0.30.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,345 @@
1
+ # Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Any, Dict, Optional, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...utils import is_torch_version, logging
23
+ from ...utils.torch_utils import maybe_allow_in_graph
24
+ from ..attention import Attention, FeedForward
25
+ from ..embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps, get_3d_sincos_pos_embed
26
+ from ..modeling_outputs import Transformer2DModelOutput
27
+ from ..modeling_utils import ModelMixin
28
+ from ..normalization import AdaLayerNorm, CogVideoXLayerNormZero
29
+
30
+
31
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
+
33
+
34
+ @maybe_allow_in_graph
35
+ class CogVideoXBlock(nn.Module):
36
+ r"""
37
+ Transformer block used in [CogVideoX](https://github.com/THUDM/CogVideo) model.
38
+
39
+ Parameters:
40
+ dim (`int`): The number of channels in the input and output.
41
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
42
+ attention_head_dim (`int`): The number of channels in each head.
43
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
44
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
45
+ attention_bias (:
46
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
47
+ qk_norm (`bool`, defaults to `True`):
48
+ Whether or not to use normalization after query and key projections in Attention.
49
+ norm_elementwise_affine (`bool`, defaults to `True`):
50
+ Whether to use learnable elementwise affine parameters for normalization.
51
+ norm_eps (`float`, defaults to `1e-5`):
52
+ Epsilon value for normalization layers.
53
+ final_dropout (`bool` defaults to `False`):
54
+ Whether to apply a final dropout after the last feed-forward layer.
55
+ ff_inner_dim (`int`, *optional*, defaults to `None`):
56
+ Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used.
57
+ ff_bias (`bool`, defaults to `True`):
58
+ Whether or not to use bias in Feed-forward layer.
59
+ attention_out_bias (`bool`, defaults to `True`):
60
+ Whether or not to use bias in Attention output projection layer.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ dim: int,
66
+ num_attention_heads: int,
67
+ attention_head_dim: int,
68
+ time_embed_dim: int,
69
+ dropout: float = 0.0,
70
+ activation_fn: str = "gelu-approximate",
71
+ attention_bias: bool = False,
72
+ qk_norm: bool = True,
73
+ norm_elementwise_affine: bool = True,
74
+ norm_eps: float = 1e-5,
75
+ final_dropout: bool = True,
76
+ ff_inner_dim: Optional[int] = None,
77
+ ff_bias: bool = True,
78
+ attention_out_bias: bool = True,
79
+ ):
80
+ super().__init__()
81
+
82
+ # 1. Self Attention
83
+ self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
84
+
85
+ self.attn1 = Attention(
86
+ query_dim=dim,
87
+ dim_head=attention_head_dim,
88
+ heads=num_attention_heads,
89
+ qk_norm="layer_norm" if qk_norm else None,
90
+ eps=1e-6,
91
+ bias=attention_bias,
92
+ out_bias=attention_out_bias,
93
+ )
94
+
95
+ # 2. Feed Forward
96
+ self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
97
+
98
+ self.ff = FeedForward(
99
+ dim,
100
+ dropout=dropout,
101
+ activation_fn=activation_fn,
102
+ final_dropout=final_dropout,
103
+ inner_dim=ff_inner_dim,
104
+ bias=ff_bias,
105
+ )
106
+
107
+ def forward(
108
+ self,
109
+ hidden_states: torch.Tensor,
110
+ encoder_hidden_states: torch.Tensor,
111
+ temb: torch.Tensor,
112
+ ) -> torch.Tensor:
113
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
114
+ hidden_states, encoder_hidden_states, temb
115
+ )
116
+
117
+ # attention
118
+ text_length = norm_encoder_hidden_states.size(1)
119
+
120
+ # CogVideoX uses concatenated text + video embeddings with self-attention instead of using
121
+ # them in cross-attention individually
122
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
123
+ attn_output = self.attn1(
124
+ hidden_states=norm_hidden_states,
125
+ encoder_hidden_states=None,
126
+ )
127
+
128
+ hidden_states = hidden_states + gate_msa * attn_output[:, text_length:]
129
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_output[:, :text_length]
130
+
131
+ # norm & modulate
132
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
133
+ hidden_states, encoder_hidden_states, temb
134
+ )
135
+
136
+ # feed-forward
137
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
138
+ ff_output = self.ff(norm_hidden_states)
139
+
140
+ hidden_states = hidden_states + gate_ff * ff_output[:, text_length:]
141
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_length]
142
+ return hidden_states, encoder_hidden_states
143
+
144
+
145
+ class CogVideoXTransformer3DModel(ModelMixin, ConfigMixin):
146
+ """
147
+ A Transformer model for video-like data in [CogVideoX](https://github.com/THUDM/CogVideo).
148
+
149
+ Parameters:
150
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
151
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
152
+ in_channels (`int`, *optional*):
153
+ The number of channels in the input.
154
+ out_channels (`int`, *optional*):
155
+ The number of channels in the output.
156
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
157
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
158
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
159
+ attention_bias (`bool`, *optional*):
160
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
161
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
162
+ This is fixed during training since it is used to learn a number of position embeddings.
163
+ patch_size (`int`, *optional*):
164
+ The size of the patches to use in the patch embedding layer.
165
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
166
+ num_embeds_ada_norm ( `int`, *optional*):
167
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
168
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
169
+ added to the hidden states. During inference, you can denoise for up to but not more steps than
170
+ `num_embeds_ada_norm`.
171
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
172
+ The type of normalization to use. Options are `"layer_norm"` or `"ada_layer_norm"`.
173
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
174
+ Whether or not to use elementwise affine in normalization layers.
175
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon value to use in normalization layers.
176
+ caption_channels (`int`, *optional*):
177
+ The number of channels in the caption embeddings.
178
+ video_length (`int`, *optional*):
179
+ The number of frames in the video-like data.
180
+ """
181
+
182
+ _supports_gradient_checkpointing = True
183
+
184
+ @register_to_config
185
+ def __init__(
186
+ self,
187
+ num_attention_heads: int = 30,
188
+ attention_head_dim: int = 64,
189
+ in_channels: Optional[int] = 16,
190
+ out_channels: Optional[int] = 16,
191
+ flip_sin_to_cos: bool = True,
192
+ freq_shift: int = 0,
193
+ time_embed_dim: int = 512,
194
+ text_embed_dim: int = 4096,
195
+ num_layers: int = 30,
196
+ dropout: float = 0.0,
197
+ attention_bias: bool = True,
198
+ sample_width: int = 90,
199
+ sample_height: int = 60,
200
+ sample_frames: int = 49,
201
+ patch_size: int = 2,
202
+ temporal_compression_ratio: int = 4,
203
+ max_text_seq_length: int = 226,
204
+ activation_fn: str = "gelu-approximate",
205
+ timestep_activation_fn: str = "silu",
206
+ norm_elementwise_affine: bool = True,
207
+ norm_eps: float = 1e-5,
208
+ spatial_interpolation_scale: float = 1.875,
209
+ temporal_interpolation_scale: float = 1.0,
210
+ ):
211
+ super().__init__()
212
+ inner_dim = num_attention_heads * attention_head_dim
213
+
214
+ post_patch_height = sample_height // patch_size
215
+ post_patch_width = sample_width // patch_size
216
+ post_time_compression_frames = (sample_frames - 1) // temporal_compression_ratio + 1
217
+ self.num_patches = post_patch_height * post_patch_width * post_time_compression_frames
218
+
219
+ # 1. Patch embedding
220
+ self.patch_embed = CogVideoXPatchEmbed(patch_size, in_channels, inner_dim, text_embed_dim, bias=True)
221
+ self.embedding_dropout = nn.Dropout(dropout)
222
+
223
+ # 2. 3D positional embeddings
224
+ spatial_pos_embedding = get_3d_sincos_pos_embed(
225
+ inner_dim,
226
+ (post_patch_width, post_patch_height),
227
+ post_time_compression_frames,
228
+ spatial_interpolation_scale,
229
+ temporal_interpolation_scale,
230
+ )
231
+ spatial_pos_embedding = torch.from_numpy(spatial_pos_embedding).flatten(0, 1)
232
+ pos_embedding = torch.zeros(1, max_text_seq_length + self.num_patches, inner_dim, requires_grad=False)
233
+ pos_embedding.data[:, max_text_seq_length:].copy_(spatial_pos_embedding)
234
+ self.register_buffer("pos_embedding", pos_embedding, persistent=False)
235
+
236
+ # 3. Time embeddings
237
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
238
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
239
+
240
+ # 4. Define spatio-temporal transformers blocks
241
+ self.transformer_blocks = nn.ModuleList(
242
+ [
243
+ CogVideoXBlock(
244
+ dim=inner_dim,
245
+ num_attention_heads=num_attention_heads,
246
+ attention_head_dim=attention_head_dim,
247
+ time_embed_dim=time_embed_dim,
248
+ dropout=dropout,
249
+ activation_fn=activation_fn,
250
+ attention_bias=attention_bias,
251
+ norm_elementwise_affine=norm_elementwise_affine,
252
+ norm_eps=norm_eps,
253
+ )
254
+ for _ in range(num_layers)
255
+ ]
256
+ )
257
+ self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
258
+
259
+ # 5. Output blocks
260
+ self.norm_out = AdaLayerNorm(
261
+ embedding_dim=time_embed_dim,
262
+ output_dim=2 * inner_dim,
263
+ norm_elementwise_affine=norm_elementwise_affine,
264
+ norm_eps=norm_eps,
265
+ chunk_dim=1,
266
+ )
267
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
268
+
269
+ self.gradient_checkpointing = False
270
+
271
+ def _set_gradient_checkpointing(self, module, value=False):
272
+ self.gradient_checkpointing = value
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ encoder_hidden_states: torch.Tensor,
278
+ timestep: Union[int, float, torch.LongTensor],
279
+ timestep_cond: Optional[torch.Tensor] = None,
280
+ return_dict: bool = True,
281
+ ):
282
+ batch_size, num_frames, channels, height, width = hidden_states.shape
283
+
284
+ # 1. Time embedding
285
+ timesteps = timestep
286
+ t_emb = self.time_proj(timesteps)
287
+
288
+ # timesteps does not contain any weights and will always return f32 tensors
289
+ # but time_embedding might actually be running in fp16. so we need to cast here.
290
+ # there might be better ways to encapsulate this.
291
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
292
+ emb = self.time_embedding(t_emb, timestep_cond)
293
+
294
+ # 2. Patch embedding
295
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
296
+
297
+ # 3. Position embedding
298
+ seq_length = height * width * num_frames // (self.config.patch_size**2)
299
+
300
+ pos_embeds = self.pos_embedding[:, : self.config.max_text_seq_length + seq_length]
301
+ hidden_states = hidden_states + pos_embeds
302
+ hidden_states = self.embedding_dropout(hidden_states)
303
+
304
+ encoder_hidden_states = hidden_states[:, : self.config.max_text_seq_length]
305
+ hidden_states = hidden_states[:, self.config.max_text_seq_length :]
306
+
307
+ # 5. Transformer blocks
308
+ for i, block in enumerate(self.transformer_blocks):
309
+ if self.training and self.gradient_checkpointing:
310
+
311
+ def create_custom_forward(module):
312
+ def custom_forward(*inputs):
313
+ return module(*inputs)
314
+
315
+ return custom_forward
316
+
317
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
318
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
319
+ create_custom_forward(block),
320
+ hidden_states,
321
+ encoder_hidden_states,
322
+ emb,
323
+ **ckpt_kwargs,
324
+ )
325
+ else:
326
+ hidden_states, encoder_hidden_states = block(
327
+ hidden_states=hidden_states,
328
+ encoder_hidden_states=encoder_hidden_states,
329
+ temb=emb,
330
+ )
331
+
332
+ hidden_states = self.norm_final(hidden_states)
333
+
334
+ # 6. Final block
335
+ hidden_states = self.norm_out(hidden_states, temb=emb)
336
+ hidden_states = self.proj_out(hidden_states)
337
+
338
+ # 7. Unpatchify
339
+ p = self.config.patch_size
340
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, channels, p, p)
341
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
342
+
343
+ if not return_dict:
344
+ return (output,)
345
+ return Transformer2DModelOutput(sample=output)
@@ -1,4 +1,4 @@
1
- # Copyright 2024 HunyuanDiT Authors and The HuggingFace Team. All rights reserved.
1
+ # Copyright 2024 HunyuanDiT Authors, Qixun Wang and The HuggingFace Team. All rights reserved.
2
2
  #
3
3
  # Licensed under the Apache License, Version 2.0 (the "License");
4
4
  # you may not use this file except in compliance with the License.
@@ -14,14 +14,13 @@
14
14
  from typing import Dict, Optional, Union
15
15
 
16
16
  import torch
17
- import torch.nn.functional as F
18
17
  from torch import nn
19
18
 
20
19
  from ...configuration_utils import ConfigMixin, register_to_config
21
20
  from ...utils import logging
22
21
  from ...utils.torch_utils import maybe_allow_in_graph
23
22
  from ..attention import FeedForward
24
- from ..attention_processor import Attention, AttentionProcessor, HunyuanAttnProcessor2_0
23
+ from ..attention_processor import Attention, AttentionProcessor, FusedHunyuanAttnProcessor2_0, HunyuanAttnProcessor2_0
25
24
  from ..embeddings import (
26
25
  HunyuanCombinedTimestepTextSizeStyleEmbedding,
27
26
  PatchEmbed,
@@ -29,20 +28,12 @@ from ..embeddings import (
29
28
  )
30
29
  from ..modeling_outputs import Transformer2DModelOutput
31
30
  from ..modeling_utils import ModelMixin
32
- from ..normalization import AdaLayerNormContinuous
31
+ from ..normalization import AdaLayerNormContinuous, FP32LayerNorm
33
32
 
34
33
 
35
34
  logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
35
 
37
36
 
38
- class FP32LayerNorm(nn.LayerNorm):
39
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
40
- origin_dtype = inputs.dtype
41
- return F.layer_norm(
42
- inputs.float(), self.normalized_shape, self.weight.float(), self.bias.float(), self.eps
43
- ).to(origin_dtype)
44
-
45
-
46
37
  class AdaLayerNormShift(nn.Module):
47
38
  r"""
48
39
  Norm layer modified to incorporate timestep embeddings.
@@ -249,6 +240,8 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
249
240
  The length of the clip text embedding.
250
241
  text_len_t5 (`int`, *optional*):
251
242
  The length of the T5 text embedding.
243
+ use_style_cond_and_image_meta_size (`bool`, *optional*):
244
+ Whether or not to use style condition and image meta size. True for version <=1.1, False for version >= 1.2
252
245
  """
253
246
 
254
247
  @register_to_config
@@ -270,6 +263,7 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
270
263
  pooled_projection_dim: int = 1024,
271
264
  text_len: int = 77,
272
265
  text_len_t5: int = 256,
266
+ use_style_cond_and_image_meta_size: bool = True,
273
267
  ):
274
268
  super().__init__()
275
269
  self.out_channels = in_channels * 2 if learn_sigma else in_channels
@@ -301,6 +295,7 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
301
295
  pooled_projection_dim=pooled_projection_dim,
302
296
  seq_len=text_len_t5,
303
297
  cross_attention_dim=cross_attention_dim_t5,
298
+ use_style_cond_and_image_meta_size=use_style_cond_and_image_meta_size,
304
299
  )
305
300
 
306
301
  # HunyuanDiT Blocks
@@ -322,7 +317,7 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
322
317
  self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
323
318
  self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
324
319
 
325
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
320
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedHunyuanAttnProcessor2_0
326
321
  def fuse_qkv_projections(self):
327
322
  """
328
323
  Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
@@ -346,6 +341,8 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
346
341
  if isinstance(module, Attention):
347
342
  module.fuse_projections(fuse=True)
348
343
 
344
+ self.set_attn_processor(FusedHunyuanAttnProcessor2_0())
345
+
349
346
  # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
350
347
  def unfuse_qkv_projections(self):
351
348
  """Disables the fused QKV projection if enabled.
@@ -373,7 +370,7 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
373
370
 
374
371
  def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
375
372
  if hasattr(module, "get_processor"):
376
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
373
+ processors[f"{name}.processor"] = module.get_processor()
377
374
 
378
375
  for sub_name, child in module.named_children():
379
376
  fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
@@ -437,6 +434,7 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
437
434
  image_meta_size=None,
438
435
  style=None,
439
436
  image_rotary_emb=None,
437
+ controlnet_block_samples=None,
440
438
  return_dict=True,
441
439
  ):
442
440
  """
@@ -491,7 +489,10 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
491
489
  skips = []
492
490
  for layer, block in enumerate(self.blocks):
493
491
  if layer > self.config.num_layers // 2:
494
- skip = skips.pop()
492
+ if controlnet_block_samples is not None:
493
+ skip = skips.pop() + controlnet_block_samples.pop()
494
+ else:
495
+ skip = skips.pop()
495
496
  hidden_states = block(
496
497
  hidden_states,
497
498
  temb=temb,
@@ -510,6 +511,9 @@ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
510
511
  if layer < (self.config.num_layers // 2 - 1):
511
512
  skips.append(hidden_states)
512
513
 
514
+ if controlnet_block_samples is not None and len(controlnet_block_samples) != 0:
515
+ raise ValueError("The number of controls is not equal to the number of skip connections.")
516
+
513
517
  # final layer
514
518
  hidden_states = self.norm_out(hidden_states, temb.to(torch.float32))
515
519
  hidden_states = self.proj_out(hidden_states)