diffusers 0.29.2__py3-none-any.whl → 0.30.1__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.
- diffusers/__init__.py +94 -3
- diffusers/commands/env.py +1 -5
- diffusers/configuration_utils.py +4 -9
- diffusers/dependency_versions_table.py +2 -2
- diffusers/image_processor.py +1 -2
- diffusers/loaders/__init__.py +17 -2
- diffusers/loaders/ip_adapter.py +10 -7
- diffusers/loaders/lora_base.py +752 -0
- diffusers/loaders/lora_pipeline.py +2252 -0
- diffusers/loaders/peft.py +213 -5
- diffusers/loaders/single_file.py +3 -14
- diffusers/loaders/single_file_model.py +31 -10
- diffusers/loaders/single_file_utils.py +293 -8
- diffusers/loaders/textual_inversion.py +1 -6
- diffusers/loaders/unet.py +23 -208
- diffusers/models/__init__.py +20 -0
- diffusers/models/activations.py +22 -0
- diffusers/models/attention.py +386 -7
- diffusers/models/attention_processor.py +1937 -629
- diffusers/models/autoencoders/__init__.py +2 -0
- diffusers/models/autoencoders/autoencoder_kl.py +14 -3
- diffusers/models/autoencoders/autoencoder_kl_cogvideox.py +1271 -0
- diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +1 -1
- diffusers/models/autoencoders/autoencoder_oobleck.py +464 -0
- diffusers/models/autoencoders/autoencoder_tiny.py +1 -0
- diffusers/models/autoencoders/consistency_decoder_vae.py +1 -1
- diffusers/models/autoencoders/vq_model.py +4 -4
- diffusers/models/controlnet.py +2 -3
- diffusers/models/controlnet_hunyuan.py +401 -0
- diffusers/models/controlnet_sd3.py +11 -11
- diffusers/models/controlnet_sparsectrl.py +789 -0
- diffusers/models/controlnet_xs.py +40 -10
- diffusers/models/downsampling.py +68 -0
- diffusers/models/embeddings.py +403 -36
- diffusers/models/model_loading_utils.py +1 -3
- diffusers/models/modeling_flax_utils.py +1 -6
- diffusers/models/modeling_utils.py +4 -16
- diffusers/models/normalization.py +203 -12
- diffusers/models/transformers/__init__.py +6 -0
- diffusers/models/transformers/auraflow_transformer_2d.py +543 -0
- diffusers/models/transformers/cogvideox_transformer_3d.py +485 -0
- diffusers/models/transformers/hunyuan_transformer_2d.py +19 -15
- diffusers/models/transformers/latte_transformer_3d.py +327 -0
- diffusers/models/transformers/lumina_nextdit2d.py +340 -0
- diffusers/models/transformers/pixart_transformer_2d.py +102 -1
- diffusers/models/transformers/prior_transformer.py +1 -1
- diffusers/models/transformers/stable_audio_transformer.py +458 -0
- diffusers/models/transformers/transformer_flux.py +455 -0
- diffusers/models/transformers/transformer_sd3.py +18 -4
- diffusers/models/unets/unet_1d_blocks.py +1 -1
- diffusers/models/unets/unet_2d_condition.py +8 -1
- diffusers/models/unets/unet_3d_blocks.py +51 -920
- diffusers/models/unets/unet_3d_condition.py +4 -1
- diffusers/models/unets/unet_i2vgen_xl.py +4 -1
- diffusers/models/unets/unet_kandinsky3.py +1 -1
- diffusers/models/unets/unet_motion_model.py +1330 -84
- diffusers/models/unets/unet_spatio_temporal_condition.py +1 -1
- diffusers/models/unets/unet_stable_cascade.py +1 -3
- diffusers/models/unets/uvit_2d.py +1 -1
- diffusers/models/upsampling.py +64 -0
- diffusers/models/vq_model.py +8 -4
- diffusers/optimization.py +1 -1
- diffusers/pipelines/__init__.py +100 -3
- diffusers/pipelines/animatediff/__init__.py +4 -0
- diffusers/pipelines/animatediff/pipeline_animatediff.py +50 -40
- diffusers/pipelines/animatediff/pipeline_animatediff_controlnet.py +1076 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_sdxl.py +17 -27
- diffusers/pipelines/animatediff/pipeline_animatediff_sparsectrl.py +1008 -0
- diffusers/pipelines/animatediff/pipeline_animatediff_video2video.py +51 -38
- diffusers/pipelines/audioldm2/modeling_audioldm2.py +1 -1
- diffusers/pipelines/audioldm2/pipeline_audioldm2.py +1 -0
- diffusers/pipelines/aura_flow/__init__.py +48 -0
- diffusers/pipelines/aura_flow/pipeline_aura_flow.py +591 -0
- diffusers/pipelines/auto_pipeline.py +97 -19
- diffusers/pipelines/cogvideo/__init__.py +48 -0
- diffusers/pipelines/cogvideo/pipeline_cogvideox.py +746 -0
- diffusers/pipelines/consistency_models/pipeline_consistency_models.py +1 -1
- diffusers/pipelines/controlnet/pipeline_controlnet.py +24 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +31 -30
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint.py +24 -153
- diffusers/pipelines/controlnet/pipeline_controlnet_inpaint_sd_xl.py +19 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +18 -28
- diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +29 -32
- diffusers/pipelines/controlnet/pipeline_flax_controlnet.py +2 -2
- diffusers/pipelines/controlnet_hunyuandit/__init__.py +48 -0
- diffusers/pipelines/controlnet_hunyuandit/pipeline_hunyuandit_controlnet.py +1042 -0
- diffusers/pipelines/controlnet_sd3/pipeline_stable_diffusion_3_controlnet.py +35 -0
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs.py +10 -6
- diffusers/pipelines/controlnet_xs/pipeline_controlnet_xs_sd_xl.py +0 -4
- diffusers/pipelines/deepfloyd_if/pipeline_if.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_img2img_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_inpainting_superresolution.py +2 -2
- diffusers/pipelines/deepfloyd_if/pipeline_if_superresolution.py +2 -2
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion.py +11 -6
- diffusers/pipelines/deprecated/alt_diffusion/pipeline_alt_diffusion_img2img.py +11 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_cycle_diffusion.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_inpaint_legacy.py +6 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_model_editing.py +10 -10
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_paradigms.py +10 -6
- diffusers/pipelines/deprecated/stable_diffusion_variants/pipeline_stable_diffusion_pix2pix_zero.py +3 -3
- diffusers/pipelines/deprecated/versatile_diffusion/modeling_text_unet.py +1 -1
- diffusers/pipelines/flux/__init__.py +47 -0
- diffusers/pipelines/flux/pipeline_flux.py +749 -0
- diffusers/pipelines/flux/pipeline_output.py +21 -0
- diffusers/pipelines/free_init_utils.py +2 -0
- diffusers/pipelines/free_noise_utils.py +236 -0
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3.py +2 -2
- diffusers/pipelines/kandinsky3/pipeline_kandinsky3_img2img.py +2 -2
- diffusers/pipelines/kolors/__init__.py +54 -0
- diffusers/pipelines/kolors/pipeline_kolors.py +1070 -0
- diffusers/pipelines/kolors/pipeline_kolors_img2img.py +1247 -0
- diffusers/pipelines/kolors/pipeline_output.py +21 -0
- diffusers/pipelines/kolors/text_encoder.py +889 -0
- diffusers/pipelines/kolors/tokenizer.py +334 -0
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_img2img.py +30 -29
- diffusers/pipelines/latent_consistency_models/pipeline_latent_consistency_text2img.py +23 -29
- diffusers/pipelines/latte/__init__.py +48 -0
- diffusers/pipelines/latte/pipeline_latte.py +881 -0
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion.py +4 -4
- diffusers/pipelines/ledits_pp/pipeline_leditspp_stable_diffusion_xl.py +0 -4
- diffusers/pipelines/lumina/__init__.py +48 -0
- diffusers/pipelines/lumina/pipeline_lumina.py +897 -0
- diffusers/pipelines/pag/__init__.py +67 -0
- diffusers/pipelines/pag/pag_utils.py +237 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd.py +1329 -0
- diffusers/pipelines/pag/pipeline_pag_controlnet_sd_xl.py +1612 -0
- diffusers/pipelines/pag/pipeline_pag_hunyuandit.py +953 -0
- diffusers/pipelines/pag/pipeline_pag_kolors.py +1136 -0
- diffusers/pipelines/pag/pipeline_pag_pixart_sigma.py +872 -0
- diffusers/pipelines/pag/pipeline_pag_sd.py +1050 -0
- diffusers/pipelines/pag/pipeline_pag_sd_3.py +985 -0
- diffusers/pipelines/pag/pipeline_pag_sd_animatediff.py +862 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl.py +1333 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_img2img.py +1529 -0
- diffusers/pipelines/pag/pipeline_pag_sd_xl_inpaint.py +1753 -0
- diffusers/pipelines/pia/pipeline_pia.py +30 -37
- diffusers/pipelines/pipeline_flax_utils.py +4 -9
- diffusers/pipelines/pipeline_loading_utils.py +0 -3
- diffusers/pipelines/pipeline_utils.py +2 -14
- diffusers/pipelines/semantic_stable_diffusion/pipeline_semantic_stable_diffusion.py +0 -1
- diffusers/pipelines/stable_audio/__init__.py +50 -0
- diffusers/pipelines/stable_audio/modeling_stable_audio.py +158 -0
- diffusers/pipelines/stable_audio/pipeline_stable_audio.py +745 -0
- diffusers/pipelines/stable_diffusion/convert_from_ckpt.py +2 -0
- diffusers/pipelines/stable_diffusion/pipeline_flax_stable_diffusion.py +1 -1
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +23 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_depth2img.py +15 -8
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +30 -29
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +23 -152
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py +8 -4
- diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_upscale.py +11 -11
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip.py +8 -6
- diffusers/pipelines/stable_diffusion/pipeline_stable_unclip_img2img.py +6 -6
- diffusers/pipelines/stable_diffusion_3/__init__.py +2 -0
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +34 -3
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +33 -7
- diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +1201 -0
- diffusers/pipelines/stable_diffusion_attend_and_excite/pipeline_stable_diffusion_attend_and_excite.py +3 -3
- diffusers/pipelines/stable_diffusion_diffedit/pipeline_stable_diffusion_diffedit.py +6 -6
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen.py +5 -5
- diffusers/pipelines/stable_diffusion_gligen/pipeline_stable_diffusion_gligen_text_image.py +5 -5
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_k_diffusion.py +6 -6
- diffusers/pipelines/stable_diffusion_k_diffusion/pipeline_stable_diffusion_xl_k_diffusion.py +0 -4
- diffusers/pipelines/stable_diffusion_ldm3d/pipeline_stable_diffusion_ldm3d.py +23 -29
- diffusers/pipelines/stable_diffusion_panorama/pipeline_stable_diffusion_panorama.py +27 -29
- diffusers/pipelines/stable_diffusion_sag/pipeline_stable_diffusion_sag.py +3 -3
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +17 -27
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +26 -29
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +17 -145
- diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_instruct_pix2pix.py +0 -4
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_adapter.py +6 -6
- diffusers/pipelines/t2i_adapter/pipeline_stable_diffusion_xl_adapter.py +18 -28
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_synth_img2img.py +8 -6
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero.py +6 -4
- diffusers/pipelines/text_to_video_synthesis/pipeline_text_to_video_zero_sdxl.py +0 -4
- diffusers/pipelines/unidiffuser/pipeline_unidiffuser.py +3 -3
- diffusers/pipelines/wuerstchen/modeling_wuerstchen_prior.py +1 -1
- diffusers/pipelines/wuerstchen/pipeline_wuerstchen_prior.py +5 -4
- diffusers/schedulers/__init__.py +8 -0
- diffusers/schedulers/scheduling_cosine_dpmsolver_multistep.py +572 -0
- diffusers/schedulers/scheduling_ddim.py +1 -1
- diffusers/schedulers/scheduling_ddim_cogvideox.py +449 -0
- diffusers/schedulers/scheduling_ddpm.py +1 -1
- diffusers/schedulers/scheduling_ddpm_parallel.py +1 -1
- diffusers/schedulers/scheduling_deis_multistep.py +2 -2
- diffusers/schedulers/scheduling_dpm_cogvideox.py +489 -0
- diffusers/schedulers/scheduling_dpmsolver_multistep.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_multistep_inverse.py +1 -1
- diffusers/schedulers/scheduling_dpmsolver_singlestep.py +64 -19
- diffusers/schedulers/scheduling_edm_dpmsolver_multistep.py +2 -2
- diffusers/schedulers/scheduling_flow_match_euler_discrete.py +63 -39
- diffusers/schedulers/scheduling_flow_match_heun_discrete.py +321 -0
- diffusers/schedulers/scheduling_ipndm.py +1 -1
- diffusers/schedulers/scheduling_unipc_multistep.py +1 -1
- diffusers/schedulers/scheduling_utils.py +1 -3
- diffusers/schedulers/scheduling_utils_flax.py +1 -3
- diffusers/training_utils.py +99 -14
- diffusers/utils/__init__.py +2 -2
- diffusers/utils/dummy_pt_objects.py +210 -0
- diffusers/utils/dummy_torch_and_torchsde_objects.py +15 -0
- diffusers/utils/dummy_torch_and_transformers_and_sentencepiece_objects.py +47 -0
- diffusers/utils/dummy_torch_and_transformers_objects.py +315 -0
- diffusers/utils/dynamic_modules_utils.py +1 -11
- diffusers/utils/export_utils.py +50 -6
- diffusers/utils/hub_utils.py +45 -42
- diffusers/utils/import_utils.py +37 -15
- diffusers/utils/loading_utils.py +80 -3
- diffusers/utils/testing_utils.py +11 -8
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/METADATA +73 -83
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/RECORD +217 -164
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/WHEEL +1 -1
- diffusers/loaders/autoencoder.py +0 -146
- diffusers/loaders/controlnet.py +0 -136
- diffusers/loaders/lora.py +0 -1728
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/LICENSE +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/entry_points.txt +0 -0
- {diffusers-0.29.2.dist-info → diffusers-0.30.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,485 @@
|
|
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, Tuple, 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 ..attention_processor import AttentionProcessor, CogVideoXAttnProcessor2_0, FusedCogVideoXAttnProcessor2_0
|
26
|
+
from ..embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps, get_3d_sincos_pos_embed
|
27
|
+
from ..modeling_outputs import Transformer2DModelOutput
|
28
|
+
from ..modeling_utils import ModelMixin
|
29
|
+
from ..normalization import AdaLayerNorm, CogVideoXLayerNormZero
|
30
|
+
|
31
|
+
|
32
|
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
33
|
+
|
34
|
+
|
35
|
+
@maybe_allow_in_graph
|
36
|
+
class CogVideoXBlock(nn.Module):
|
37
|
+
r"""
|
38
|
+
Transformer block used in [CogVideoX](https://github.com/THUDM/CogVideo) model.
|
39
|
+
|
40
|
+
Parameters:
|
41
|
+
dim (`int`):
|
42
|
+
The number of channels in the input and output.
|
43
|
+
num_attention_heads (`int`):
|
44
|
+
The number of heads to use for multi-head attention.
|
45
|
+
attention_head_dim (`int`):
|
46
|
+
The number of channels in each head.
|
47
|
+
time_embed_dim (`int`):
|
48
|
+
The number of channels in timestep embedding.
|
49
|
+
dropout (`float`, defaults to `0.0`):
|
50
|
+
The dropout probability to use.
|
51
|
+
activation_fn (`str`, defaults to `"gelu-approximate"`):
|
52
|
+
Activation function to be used in feed-forward.
|
53
|
+
attention_bias (`bool`, defaults to `False`):
|
54
|
+
Whether or not to use bias in attention projection layers.
|
55
|
+
qk_norm (`bool`, defaults to `True`):
|
56
|
+
Whether or not to use normalization after query and key projections in Attention.
|
57
|
+
norm_elementwise_affine (`bool`, defaults to `True`):
|
58
|
+
Whether to use learnable elementwise affine parameters for normalization.
|
59
|
+
norm_eps (`float`, defaults to `1e-5`):
|
60
|
+
Epsilon value for normalization layers.
|
61
|
+
final_dropout (`bool` defaults to `False`):
|
62
|
+
Whether to apply a final dropout after the last feed-forward layer.
|
63
|
+
ff_inner_dim (`int`, *optional*, defaults to `None`):
|
64
|
+
Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used.
|
65
|
+
ff_bias (`bool`, defaults to `True`):
|
66
|
+
Whether or not to use bias in Feed-forward layer.
|
67
|
+
attention_out_bias (`bool`, defaults to `True`):
|
68
|
+
Whether or not to use bias in Attention output projection layer.
|
69
|
+
"""
|
70
|
+
|
71
|
+
def __init__(
|
72
|
+
self,
|
73
|
+
dim: int,
|
74
|
+
num_attention_heads: int,
|
75
|
+
attention_head_dim: int,
|
76
|
+
time_embed_dim: int,
|
77
|
+
dropout: float = 0.0,
|
78
|
+
activation_fn: str = "gelu-approximate",
|
79
|
+
attention_bias: bool = False,
|
80
|
+
qk_norm: bool = True,
|
81
|
+
norm_elementwise_affine: bool = True,
|
82
|
+
norm_eps: float = 1e-5,
|
83
|
+
final_dropout: bool = True,
|
84
|
+
ff_inner_dim: Optional[int] = None,
|
85
|
+
ff_bias: bool = True,
|
86
|
+
attention_out_bias: bool = True,
|
87
|
+
):
|
88
|
+
super().__init__()
|
89
|
+
|
90
|
+
# 1. Self Attention
|
91
|
+
self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
|
92
|
+
|
93
|
+
self.attn1 = Attention(
|
94
|
+
query_dim=dim,
|
95
|
+
dim_head=attention_head_dim,
|
96
|
+
heads=num_attention_heads,
|
97
|
+
qk_norm="layer_norm" if qk_norm else None,
|
98
|
+
eps=1e-6,
|
99
|
+
bias=attention_bias,
|
100
|
+
out_bias=attention_out_bias,
|
101
|
+
processor=CogVideoXAttnProcessor2_0(),
|
102
|
+
)
|
103
|
+
|
104
|
+
# 2. Feed Forward
|
105
|
+
self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
|
106
|
+
|
107
|
+
self.ff = FeedForward(
|
108
|
+
dim,
|
109
|
+
dropout=dropout,
|
110
|
+
activation_fn=activation_fn,
|
111
|
+
final_dropout=final_dropout,
|
112
|
+
inner_dim=ff_inner_dim,
|
113
|
+
bias=ff_bias,
|
114
|
+
)
|
115
|
+
|
116
|
+
def forward(
|
117
|
+
self,
|
118
|
+
hidden_states: torch.Tensor,
|
119
|
+
encoder_hidden_states: torch.Tensor,
|
120
|
+
temb: torch.Tensor,
|
121
|
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
122
|
+
) -> torch.Tensor:
|
123
|
+
text_seq_length = encoder_hidden_states.size(1)
|
124
|
+
|
125
|
+
# norm & modulate
|
126
|
+
norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
|
127
|
+
hidden_states, encoder_hidden_states, temb
|
128
|
+
)
|
129
|
+
|
130
|
+
# attention
|
131
|
+
attn_hidden_states, attn_encoder_hidden_states = self.attn1(
|
132
|
+
hidden_states=norm_hidden_states,
|
133
|
+
encoder_hidden_states=norm_encoder_hidden_states,
|
134
|
+
image_rotary_emb=image_rotary_emb,
|
135
|
+
)
|
136
|
+
|
137
|
+
hidden_states = hidden_states + gate_msa * attn_hidden_states
|
138
|
+
encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states
|
139
|
+
|
140
|
+
# norm & modulate
|
141
|
+
norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
|
142
|
+
hidden_states, encoder_hidden_states, temb
|
143
|
+
)
|
144
|
+
|
145
|
+
# feed-forward
|
146
|
+
norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
|
147
|
+
ff_output = self.ff(norm_hidden_states)
|
148
|
+
|
149
|
+
hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:]
|
150
|
+
encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length]
|
151
|
+
|
152
|
+
return hidden_states, encoder_hidden_states
|
153
|
+
|
154
|
+
|
155
|
+
class CogVideoXTransformer3DModel(ModelMixin, ConfigMixin):
|
156
|
+
"""
|
157
|
+
A Transformer model for video-like data in [CogVideoX](https://github.com/THUDM/CogVideo).
|
158
|
+
|
159
|
+
Parameters:
|
160
|
+
num_attention_heads (`int`, defaults to `30`):
|
161
|
+
The number of heads to use for multi-head attention.
|
162
|
+
attention_head_dim (`int`, defaults to `64`):
|
163
|
+
The number of channels in each head.
|
164
|
+
in_channels (`int`, defaults to `16`):
|
165
|
+
The number of channels in the input.
|
166
|
+
out_channels (`int`, *optional*, defaults to `16`):
|
167
|
+
The number of channels in the output.
|
168
|
+
flip_sin_to_cos (`bool`, defaults to `True`):
|
169
|
+
Whether to flip the sin to cos in the time embedding.
|
170
|
+
time_embed_dim (`int`, defaults to `512`):
|
171
|
+
Output dimension of timestep embeddings.
|
172
|
+
text_embed_dim (`int`, defaults to `4096`):
|
173
|
+
Input dimension of text embeddings from the text encoder.
|
174
|
+
num_layers (`int`, defaults to `30`):
|
175
|
+
The number of layers of Transformer blocks to use.
|
176
|
+
dropout (`float`, defaults to `0.0`):
|
177
|
+
The dropout probability to use.
|
178
|
+
attention_bias (`bool`, defaults to `True`):
|
179
|
+
Whether or not to use bias in the attention projection layers.
|
180
|
+
sample_width (`int`, defaults to `90`):
|
181
|
+
The width of the input latents.
|
182
|
+
sample_height (`int`, defaults to `60`):
|
183
|
+
The height of the input latents.
|
184
|
+
sample_frames (`int`, defaults to `49`):
|
185
|
+
The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49
|
186
|
+
instead of 13 because CogVideoX processed 13 latent frames at once in its default and recommended settings,
|
187
|
+
but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with
|
188
|
+
K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1).
|
189
|
+
patch_size (`int`, defaults to `2`):
|
190
|
+
The size of the patches to use in the patch embedding layer.
|
191
|
+
temporal_compression_ratio (`int`, defaults to `4`):
|
192
|
+
The compression ratio across the temporal dimension. See documentation for `sample_frames`.
|
193
|
+
max_text_seq_length (`int`, defaults to `226`):
|
194
|
+
The maximum sequence length of the input text embeddings.
|
195
|
+
activation_fn (`str`, defaults to `"gelu-approximate"`):
|
196
|
+
Activation function to use in feed-forward.
|
197
|
+
timestep_activation_fn (`str`, defaults to `"silu"`):
|
198
|
+
Activation function to use when generating the timestep embeddings.
|
199
|
+
norm_elementwise_affine (`bool`, defaults to `True`):
|
200
|
+
Whether or not to use elementwise affine in normalization layers.
|
201
|
+
norm_eps (`float`, defaults to `1e-5`):
|
202
|
+
The epsilon value to use in normalization layers.
|
203
|
+
spatial_interpolation_scale (`float`, defaults to `1.875`):
|
204
|
+
Scaling factor to apply in 3D positional embeddings across spatial dimensions.
|
205
|
+
temporal_interpolation_scale (`float`, defaults to `1.0`):
|
206
|
+
Scaling factor to apply in 3D positional embeddings across temporal dimensions.
|
207
|
+
"""
|
208
|
+
|
209
|
+
_supports_gradient_checkpointing = True
|
210
|
+
|
211
|
+
@register_to_config
|
212
|
+
def __init__(
|
213
|
+
self,
|
214
|
+
num_attention_heads: int = 30,
|
215
|
+
attention_head_dim: int = 64,
|
216
|
+
in_channels: int = 16,
|
217
|
+
out_channels: Optional[int] = 16,
|
218
|
+
flip_sin_to_cos: bool = True,
|
219
|
+
freq_shift: int = 0,
|
220
|
+
time_embed_dim: int = 512,
|
221
|
+
text_embed_dim: int = 4096,
|
222
|
+
num_layers: int = 30,
|
223
|
+
dropout: float = 0.0,
|
224
|
+
attention_bias: bool = True,
|
225
|
+
sample_width: int = 90,
|
226
|
+
sample_height: int = 60,
|
227
|
+
sample_frames: int = 49,
|
228
|
+
patch_size: int = 2,
|
229
|
+
temporal_compression_ratio: int = 4,
|
230
|
+
max_text_seq_length: int = 226,
|
231
|
+
activation_fn: str = "gelu-approximate",
|
232
|
+
timestep_activation_fn: str = "silu",
|
233
|
+
norm_elementwise_affine: bool = True,
|
234
|
+
norm_eps: float = 1e-5,
|
235
|
+
spatial_interpolation_scale: float = 1.875,
|
236
|
+
temporal_interpolation_scale: float = 1.0,
|
237
|
+
use_rotary_positional_embeddings: bool = False,
|
238
|
+
):
|
239
|
+
super().__init__()
|
240
|
+
inner_dim = num_attention_heads * attention_head_dim
|
241
|
+
|
242
|
+
post_patch_height = sample_height // patch_size
|
243
|
+
post_patch_width = sample_width // patch_size
|
244
|
+
post_time_compression_frames = (sample_frames - 1) // temporal_compression_ratio + 1
|
245
|
+
self.num_patches = post_patch_height * post_patch_width * post_time_compression_frames
|
246
|
+
|
247
|
+
# 1. Patch embedding
|
248
|
+
self.patch_embed = CogVideoXPatchEmbed(patch_size, in_channels, inner_dim, text_embed_dim, bias=True)
|
249
|
+
self.embedding_dropout = nn.Dropout(dropout)
|
250
|
+
|
251
|
+
# 2. 3D positional embeddings
|
252
|
+
spatial_pos_embedding = get_3d_sincos_pos_embed(
|
253
|
+
inner_dim,
|
254
|
+
(post_patch_width, post_patch_height),
|
255
|
+
post_time_compression_frames,
|
256
|
+
spatial_interpolation_scale,
|
257
|
+
temporal_interpolation_scale,
|
258
|
+
)
|
259
|
+
spatial_pos_embedding = torch.from_numpy(spatial_pos_embedding).flatten(0, 1)
|
260
|
+
pos_embedding = torch.zeros(1, max_text_seq_length + self.num_patches, inner_dim, requires_grad=False)
|
261
|
+
pos_embedding.data[:, max_text_seq_length:].copy_(spatial_pos_embedding)
|
262
|
+
self.register_buffer("pos_embedding", pos_embedding, persistent=False)
|
263
|
+
|
264
|
+
# 3. Time embeddings
|
265
|
+
self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
|
266
|
+
self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
|
267
|
+
|
268
|
+
# 4. Define spatio-temporal transformers blocks
|
269
|
+
self.transformer_blocks = nn.ModuleList(
|
270
|
+
[
|
271
|
+
CogVideoXBlock(
|
272
|
+
dim=inner_dim,
|
273
|
+
num_attention_heads=num_attention_heads,
|
274
|
+
attention_head_dim=attention_head_dim,
|
275
|
+
time_embed_dim=time_embed_dim,
|
276
|
+
dropout=dropout,
|
277
|
+
activation_fn=activation_fn,
|
278
|
+
attention_bias=attention_bias,
|
279
|
+
norm_elementwise_affine=norm_elementwise_affine,
|
280
|
+
norm_eps=norm_eps,
|
281
|
+
)
|
282
|
+
for _ in range(num_layers)
|
283
|
+
]
|
284
|
+
)
|
285
|
+
self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
|
286
|
+
|
287
|
+
# 5. Output blocks
|
288
|
+
self.norm_out = AdaLayerNorm(
|
289
|
+
embedding_dim=time_embed_dim,
|
290
|
+
output_dim=2 * inner_dim,
|
291
|
+
norm_elementwise_affine=norm_elementwise_affine,
|
292
|
+
norm_eps=norm_eps,
|
293
|
+
chunk_dim=1,
|
294
|
+
)
|
295
|
+
self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
|
296
|
+
|
297
|
+
self.gradient_checkpointing = False
|
298
|
+
|
299
|
+
def _set_gradient_checkpointing(self, module, value=False):
|
300
|
+
self.gradient_checkpointing = value
|
301
|
+
|
302
|
+
@property
|
303
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
304
|
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
305
|
+
r"""
|
306
|
+
Returns:
|
307
|
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
308
|
+
indexed by its weight name.
|
309
|
+
"""
|
310
|
+
# set recursively
|
311
|
+
processors = {}
|
312
|
+
|
313
|
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
314
|
+
if hasattr(module, "get_processor"):
|
315
|
+
processors[f"{name}.processor"] = module.get_processor()
|
316
|
+
|
317
|
+
for sub_name, child in module.named_children():
|
318
|
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
319
|
+
|
320
|
+
return processors
|
321
|
+
|
322
|
+
for name, module in self.named_children():
|
323
|
+
fn_recursive_add_processors(name, module, processors)
|
324
|
+
|
325
|
+
return processors
|
326
|
+
|
327
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
328
|
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
329
|
+
r"""
|
330
|
+
Sets the attention processor to use to compute attention.
|
331
|
+
|
332
|
+
Parameters:
|
333
|
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
334
|
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
335
|
+
for **all** `Attention` layers.
|
336
|
+
|
337
|
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
338
|
+
processor. This is strongly recommended when setting trainable attention processors.
|
339
|
+
|
340
|
+
"""
|
341
|
+
count = len(self.attn_processors.keys())
|
342
|
+
|
343
|
+
if isinstance(processor, dict) and len(processor) != count:
|
344
|
+
raise ValueError(
|
345
|
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
346
|
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
347
|
+
)
|
348
|
+
|
349
|
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
350
|
+
if hasattr(module, "set_processor"):
|
351
|
+
if not isinstance(processor, dict):
|
352
|
+
module.set_processor(processor)
|
353
|
+
else:
|
354
|
+
module.set_processor(processor.pop(f"{name}.processor"))
|
355
|
+
|
356
|
+
for sub_name, child in module.named_children():
|
357
|
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
358
|
+
|
359
|
+
for name, module in self.named_children():
|
360
|
+
fn_recursive_attn_processor(name, module, processor)
|
361
|
+
|
362
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedCogVideoXAttnProcessor2_0
|
363
|
+
def fuse_qkv_projections(self):
|
364
|
+
"""
|
365
|
+
Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
|
366
|
+
are fused. For cross-attention modules, key and value projection matrices are fused.
|
367
|
+
|
368
|
+
<Tip warning={true}>
|
369
|
+
|
370
|
+
This API is 🧪 experimental.
|
371
|
+
|
372
|
+
</Tip>
|
373
|
+
"""
|
374
|
+
self.original_attn_processors = None
|
375
|
+
|
376
|
+
for _, attn_processor in self.attn_processors.items():
|
377
|
+
if "Added" in str(attn_processor.__class__.__name__):
|
378
|
+
raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
|
379
|
+
|
380
|
+
self.original_attn_processors = self.attn_processors
|
381
|
+
|
382
|
+
for module in self.modules():
|
383
|
+
if isinstance(module, Attention):
|
384
|
+
module.fuse_projections(fuse=True)
|
385
|
+
|
386
|
+
self.set_attn_processor(FusedCogVideoXAttnProcessor2_0())
|
387
|
+
|
388
|
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
|
389
|
+
def unfuse_qkv_projections(self):
|
390
|
+
"""Disables the fused QKV projection if enabled.
|
391
|
+
|
392
|
+
<Tip warning={true}>
|
393
|
+
|
394
|
+
This API is 🧪 experimental.
|
395
|
+
|
396
|
+
</Tip>
|
397
|
+
|
398
|
+
"""
|
399
|
+
if self.original_attn_processors is not None:
|
400
|
+
self.set_attn_processor(self.original_attn_processors)
|
401
|
+
|
402
|
+
def forward(
|
403
|
+
self,
|
404
|
+
hidden_states: torch.Tensor,
|
405
|
+
encoder_hidden_states: torch.Tensor,
|
406
|
+
timestep: Union[int, float, torch.LongTensor],
|
407
|
+
timestep_cond: Optional[torch.Tensor] = None,
|
408
|
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
409
|
+
return_dict: bool = True,
|
410
|
+
):
|
411
|
+
batch_size, num_frames, channels, height, width = hidden_states.shape
|
412
|
+
|
413
|
+
# 1. Time embedding
|
414
|
+
timesteps = timestep
|
415
|
+
t_emb = self.time_proj(timesteps)
|
416
|
+
|
417
|
+
# timesteps does not contain any weights and will always return f32 tensors
|
418
|
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
419
|
+
# there might be better ways to encapsulate this.
|
420
|
+
t_emb = t_emb.to(dtype=hidden_states.dtype)
|
421
|
+
emb = self.time_embedding(t_emb, timestep_cond)
|
422
|
+
|
423
|
+
# 2. Patch embedding
|
424
|
+
hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
|
425
|
+
|
426
|
+
# 3. Position embedding
|
427
|
+
text_seq_length = encoder_hidden_states.shape[1]
|
428
|
+
if not self.config.use_rotary_positional_embeddings:
|
429
|
+
seq_length = height * width * num_frames // (self.config.patch_size**2)
|
430
|
+
|
431
|
+
pos_embeds = self.pos_embedding[:, : text_seq_length + seq_length]
|
432
|
+
hidden_states = hidden_states + pos_embeds
|
433
|
+
hidden_states = self.embedding_dropout(hidden_states)
|
434
|
+
|
435
|
+
encoder_hidden_states = hidden_states[:, :text_seq_length]
|
436
|
+
hidden_states = hidden_states[:, text_seq_length:]
|
437
|
+
|
438
|
+
# 4. Transformer blocks
|
439
|
+
for i, block in enumerate(self.transformer_blocks):
|
440
|
+
if self.training and self.gradient_checkpointing:
|
441
|
+
|
442
|
+
def create_custom_forward(module):
|
443
|
+
def custom_forward(*inputs):
|
444
|
+
return module(*inputs)
|
445
|
+
|
446
|
+
return custom_forward
|
447
|
+
|
448
|
+
ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
|
449
|
+
hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
|
450
|
+
create_custom_forward(block),
|
451
|
+
hidden_states,
|
452
|
+
encoder_hidden_states,
|
453
|
+
emb,
|
454
|
+
image_rotary_emb,
|
455
|
+
**ckpt_kwargs,
|
456
|
+
)
|
457
|
+
else:
|
458
|
+
hidden_states, encoder_hidden_states = block(
|
459
|
+
hidden_states=hidden_states,
|
460
|
+
encoder_hidden_states=encoder_hidden_states,
|
461
|
+
temb=emb,
|
462
|
+
image_rotary_emb=image_rotary_emb,
|
463
|
+
)
|
464
|
+
|
465
|
+
if not self.config.use_rotary_positional_embeddings:
|
466
|
+
# CogVideoX-2B
|
467
|
+
hidden_states = self.norm_final(hidden_states)
|
468
|
+
else:
|
469
|
+
# CogVideoX-5B
|
470
|
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
471
|
+
hidden_states = self.norm_final(hidden_states)
|
472
|
+
hidden_states = hidden_states[:, text_seq_length:]
|
473
|
+
|
474
|
+
# 5. Final block
|
475
|
+
hidden_states = self.norm_out(hidden_states, temb=emb)
|
476
|
+
hidden_states = self.proj_out(hidden_states)
|
477
|
+
|
478
|
+
# 6. Unpatchify
|
479
|
+
p = self.config.patch_size
|
480
|
+
output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, channels, p, p)
|
481
|
+
output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
|
482
|
+
|
483
|
+
if not return_dict:
|
484
|
+
return (output,)
|
485
|
+
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(
|
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
|
-
|
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)
|