Spaces:
Runtime error
Runtime error
<feat> add gradio app header.
Browse files- app.py +39 -0
- models/__init__.py +1 -0
- models/hyvideo/transformer_hunyuan_video_i2v.py +1238 -0
- pipelines/__init__.py +1 -0
- pipelines/pipeline_hunyuan_video_i2v.py +969 -0
- requirements.txt +9 -0
app.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import torch
|
4 |
+
import diffusers
|
5 |
+
import transformers
|
6 |
+
import argparse
|
7 |
+
import peft
|
8 |
+
import copy
|
9 |
+
import cv2
|
10 |
+
import gradio as gr
|
11 |
+
import numpy as np
|
12 |
+
|
13 |
+
from peft import LoraConfig
|
14 |
+
from omegaconf import OmegaConf
|
15 |
+
from safetensors.torch import safe_open
|
16 |
+
from PIL import Image, ImageDraw, ImageFilter
|
17 |
+
|
18 |
+
from models import HunyuanVideoTransformer3DModel
|
19 |
+
from pipelines import HunyuanVideoImageToVideoPipeline
|
20 |
+
|
21 |
+
|
22 |
+
header = """
|
23 |
+
# DRA-Ctrl Gradio App
|
24 |
+
|
25 |
+
<div style="text-align: center; display: flex; justify-content: left; gap: 5px;">
|
26 |
+
<a href="https://arxiv.org/pdf/2505.23325"><img src="https://img.shields.io/badge/ariXv-Paper-A42C25.svg" alt="arXiv"></a>
|
27 |
+
<a href="https://huggingface.co/Kunbyte/DRA-Ctrl"><img src="https://img.shields.io/badge/🤗-Model-ffbd45.svg" alt="HuggingFace"></a>
|
28 |
+
<a href="https://github.com/Kunbyte-AI/DRA-Ctrl"><img src="https://img.shields.io/badge/GitHub-Code-blue.svg?logo=github&" alt="GitHub"></a>
|
29 |
+
<a href="https://dra-ctrl-2025.github.io/DRA-Ctrl/"><img src="https://img.shields.io/badge/Project-Page-blue" alt="Project"></a>
|
30 |
+
</div>
|
31 |
+
"""
|
32 |
+
|
33 |
+
def create_app():
|
34 |
+
with gr.Blocks() as app:
|
35 |
+
gr.Markdown(header, elem_id="header")
|
36 |
+
|
37 |
+
|
38 |
+
if __name__ == "__main__":
|
39 |
+
create_app().launch(debug=True, ssr_mode=False)
|
models/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .hyvideo.transformer_hunyuan_video_i2v import HunyuanVideoTransformer3DModel
|
models/hyvideo/transformer_hunyuan_video_i2v.py
ADDED
@@ -0,0 +1,1238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 The Hunyuan Team and 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 |
+
# Modified by [Hengyuan Cao] in 2025.
|
15 |
+
|
16 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
17 |
+
|
18 |
+
import torch
|
19 |
+
import torch.nn as nn
|
20 |
+
import torch.nn.functional as F
|
21 |
+
|
22 |
+
from diffusers.loaders import FromOriginalModelMixin
|
23 |
+
|
24 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
25 |
+
from diffusers.loaders import PeftAdapterMixin
|
26 |
+
from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
|
27 |
+
from diffusers.models.attention import FeedForward
|
28 |
+
from diffusers.models.attention_processor import Attention, AttentionProcessor
|
29 |
+
from diffusers.models.cache_utils import CacheMixin
|
30 |
+
from diffusers.models.embeddings import (
|
31 |
+
CombinedTimestepTextProjEmbeddings,
|
32 |
+
PixArtAlphaTextProjection,
|
33 |
+
TimestepEmbedding,
|
34 |
+
Timesteps,
|
35 |
+
get_1d_rotary_pos_embed,
|
36 |
+
)
|
37 |
+
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
38 |
+
from diffusers.models.modeling_utils import ModelMixin
|
39 |
+
from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle, FP32LayerNorm
|
40 |
+
from torch.nn.utils.rnn import pad_sequence
|
41 |
+
|
42 |
+
try:
|
43 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
44 |
+
FLASH_ATTN_AVALIABLE = True
|
45 |
+
except:
|
46 |
+
FLASH_ATTN_AVALIABLE = False
|
47 |
+
|
48 |
+
|
49 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
50 |
+
|
51 |
+
|
52 |
+
class HunyuanVideoAttnProcessor2_0:
|
53 |
+
def __init__(self, inference_subject_driven: bool = False):
|
54 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
55 |
+
raise ImportError(
|
56 |
+
"HunyuanVideoAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0."
|
57 |
+
)
|
58 |
+
self.inference_subject_driven = inference_subject_driven
|
59 |
+
|
60 |
+
def __call__(
|
61 |
+
self,
|
62 |
+
attn: Attention,
|
63 |
+
hidden_states: torch.Tensor,
|
64 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
65 |
+
attention_mask: Optional[torch.Tensor] = None,
|
66 |
+
image_rotary_emb: Optional[torch.Tensor] = None,
|
67 |
+
) -> torch.Tensor:
|
68 |
+
if attn.add_q_proj is None and encoder_hidden_states is not None:
|
69 |
+
hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
|
70 |
+
|
71 |
+
# 1. QKV projections
|
72 |
+
query = attn.to_q(hidden_states)
|
73 |
+
key = attn.to_k(hidden_states)
|
74 |
+
value = attn.to_v(hidden_states)
|
75 |
+
|
76 |
+
query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
77 |
+
key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
78 |
+
value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
79 |
+
|
80 |
+
# 2. QK normalization
|
81 |
+
if attn.norm_q is not None:
|
82 |
+
query = attn.norm_q(query)
|
83 |
+
if attn.norm_k is not None:
|
84 |
+
key = attn.norm_k(key)
|
85 |
+
|
86 |
+
# 3. Rotational positional embeddings applied to latent stream
|
87 |
+
if image_rotary_emb is not None:
|
88 |
+
from diffusers.models.embeddings import apply_rotary_emb
|
89 |
+
|
90 |
+
if attn.add_q_proj is None and encoder_hidden_states is not None:
|
91 |
+
query = torch.cat(
|
92 |
+
[
|
93 |
+
apply_rotary_emb(query[:, :, : -encoder_hidden_states.shape[1]], image_rotary_emb),
|
94 |
+
query[:, :, -encoder_hidden_states.shape[1] :],
|
95 |
+
],
|
96 |
+
dim=2,
|
97 |
+
)
|
98 |
+
key = torch.cat(
|
99 |
+
[
|
100 |
+
apply_rotary_emb(key[:, :, : -encoder_hidden_states.shape[1]], image_rotary_emb),
|
101 |
+
key[:, :, -encoder_hidden_states.shape[1] :],
|
102 |
+
],
|
103 |
+
dim=2,
|
104 |
+
)
|
105 |
+
else:
|
106 |
+
query = apply_rotary_emb(query, image_rotary_emb)
|
107 |
+
key = apply_rotary_emb(key, image_rotary_emb)
|
108 |
+
|
109 |
+
# 4. Encoder condition QKV projection and normalization
|
110 |
+
if attn.add_q_proj is not None and encoder_hidden_states is not None:
|
111 |
+
encoder_query = attn.add_q_proj(encoder_hidden_states)
|
112 |
+
encoder_key = attn.add_k_proj(encoder_hidden_states)
|
113 |
+
encoder_value = attn.add_v_proj(encoder_hidden_states)
|
114 |
+
|
115 |
+
encoder_query = encoder_query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
116 |
+
encoder_key = encoder_key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
117 |
+
encoder_value = encoder_value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
|
118 |
+
|
119 |
+
if attn.norm_added_q is not None:
|
120 |
+
encoder_query = attn.norm_added_q(encoder_query)
|
121 |
+
if attn.norm_added_k is not None:
|
122 |
+
encoder_key = attn.norm_added_k(encoder_key)
|
123 |
+
|
124 |
+
query = torch.cat([query, encoder_query], dim=2)
|
125 |
+
key = torch.cat([key, encoder_key], dim=2)
|
126 |
+
value = torch.cat([value, encoder_value], dim=2)
|
127 |
+
|
128 |
+
query = query.transpose(1, 2) # batch, sequence, num_head, head_dim
|
129 |
+
key = key.transpose(1, 2)
|
130 |
+
value = value.transpose(1, 2)
|
131 |
+
|
132 |
+
# 5. Attention
|
133 |
+
if FLASH_ATTN_AVALIABLE:
|
134 |
+
if attention_mask is None:
|
135 |
+
hidden_states = flash_attn_func(query, key, value, dropout=0.0)
|
136 |
+
else:
|
137 |
+
B, S, H, D = query.size()
|
138 |
+
unit_img_seq_len = 1024
|
139 |
+
unit_txt_seq_len = 144 + 252
|
140 |
+
if not (unit_img_seq_len*4+unit_txt_seq_len == S or
|
141 |
+
unit_img_seq_len*4+unit_txt_seq_len*2 == S):
|
142 |
+
raise ValueError("Get wrong sequence length.")
|
143 |
+
if S == unit_img_seq_len*4+unit_txt_seq_len:
|
144 |
+
seg_start = [0, unit_img_seq_len, unit_img_seq_len*4]
|
145 |
+
seg_end = [unit_img_seq_len, unit_img_seq_len*4, unit_img_seq_len*4+unit_txt_seq_len]
|
146 |
+
k_segs = [[0], [0, 1, 2], [1, 2]]
|
147 |
+
elif S == unit_img_seq_len*4+unit_txt_seq_len*2:
|
148 |
+
seg_start = [0, unit_img_seq_len, unit_img_seq_len*4, unit_img_seq_len*4+unit_txt_seq_len]
|
149 |
+
seg_end = [unit_img_seq_len, unit_img_seq_len*4, unit_img_seq_len*4+unit_txt_seq_len, S]
|
150 |
+
k_segs = [[0, 3], [0, 1, 2], [1,2], [0, 3]]
|
151 |
+
valid_indices = attention_mask[:, 0, 0]
|
152 |
+
q_lens = torch.tensor([u[i:j].long().sum().item() for u in valid_indices for i,j in zip(seg_start, seg_end)],
|
153 |
+
dtype=torch.int32, device=valid_indices.device)
|
154 |
+
k_lens = torch.tensor([sum([u[seg_start[seg]:seg_end[seg]].long().sum().item() for seg in segs]) for u in valid_indices for segs in k_segs],
|
155 |
+
dtype=torch.int32, device=valid_indices.device)
|
156 |
+
query = torch.cat([u[i:j][v[i:j]] for u,v in zip(query, valid_indices) for i,j in zip(seg_start, seg_end)], dim=0)
|
157 |
+
if self.inference_subject_driven:
|
158 |
+
key = torch.cat([torch.cat([ torch.cat([u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]][:144], u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]][144:] + 0.6 * u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]][144:].abs().mean()], dim=0) if segs == [0, 1, 2] and seg == 2 else u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]] for seg in segs], dim=0) \
|
159 |
+
for u,v in zip(key, valid_indices) for segs in k_segs], dim=0)
|
160 |
+
else:
|
161 |
+
key = torch.cat([torch.cat([u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]] for seg in segs], dim=0) \
|
162 |
+
for u,v in zip(key, valid_indices) for segs in k_segs], dim=0)
|
163 |
+
value = torch.cat([torch.cat([u[seg_start[seg]:seg_end[seg]][v[seg_start[seg]:seg_end[seg]]] for seg in segs], dim=0) \
|
164 |
+
for u,v in zip(value, valid_indices) for segs in k_segs], dim=0)
|
165 |
+
cu_seqlens_q = F.pad(q_lens.cumsum(dim=0), (1, 0)).to(torch.int32)
|
166 |
+
cu_seqlens_k = F.pad(k_lens.cumsum(dim=0), (1, 0)).to(torch.int32)
|
167 |
+
max_seqlen_q = torch.max(q_lens).item()
|
168 |
+
max_seqlen_k = torch.max(k_lens).item()
|
169 |
+
hidden_states = flash_attn_varlen_func(query, key, value, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k)
|
170 |
+
num_seq_parts = len(k_segs)
|
171 |
+
hidden_states = pad_sequence([
|
172 |
+
hidden_states[start: end]
|
173 |
+
for start, end in zip(cu_seqlens_q[::num_seq_parts][:-1], cu_seqlens_q[::num_seq_parts][1:])
|
174 |
+
], batch_first=True)
|
175 |
+
hidden_states = F.pad(
|
176 |
+
hidden_states,
|
177 |
+
(0, 0, 0, 0, 0, S - hidden_states.size(1), 0, 0)
|
178 |
+
)
|
179 |
+
else:
|
180 |
+
query = query.permute(0, 2, 1, 3) # batch, num_head, sequence, head_dim
|
181 |
+
key = key.permute(0, 2, 1, 3)
|
182 |
+
value = value.permute(0, 2, 1, 3)
|
183 |
+
hidden_states = F.scaled_dot_product_attention(
|
184 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
185 |
+
) # use sdpa in torch may generate black output, upgrade to >=2.5.1 may solve this
|
186 |
+
hidden_states = hidden_states.transpose(1, 2)
|
187 |
+
|
188 |
+
# flatten num_head * head_dim
|
189 |
+
hidden_states = hidden_states.flatten(2, 3)
|
190 |
+
hidden_states = hidden_states.to(query.dtype)
|
191 |
+
|
192 |
+
|
193 |
+
# 6. Output projection
|
194 |
+
if encoder_hidden_states is not None:
|
195 |
+
hidden_states, encoder_hidden_states = (
|
196 |
+
hidden_states[:, : -encoder_hidden_states.shape[1]],
|
197 |
+
hidden_states[:, -encoder_hidden_states.shape[1] :],
|
198 |
+
)
|
199 |
+
|
200 |
+
if getattr(attn, "to_out", None) is not None:
|
201 |
+
hidden_states = attn.to_out[0](hidden_states)
|
202 |
+
hidden_states = attn.to_out[1](hidden_states)
|
203 |
+
|
204 |
+
if getattr(attn, "to_add_out", None) is not None:
|
205 |
+
encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
|
206 |
+
|
207 |
+
return hidden_states, encoder_hidden_states
|
208 |
+
|
209 |
+
|
210 |
+
class HunyuanVideoPatchEmbed(nn.Module):
|
211 |
+
def __init__(
|
212 |
+
self,
|
213 |
+
patch_size: Union[int, Tuple[int, int, int]] = 16,
|
214 |
+
in_chans: int = 3,
|
215 |
+
embed_dim: int = 768,
|
216 |
+
) -> None:
|
217 |
+
super().__init__()
|
218 |
+
|
219 |
+
patch_size = (patch_size, patch_size, patch_size) if isinstance(patch_size, int) else patch_size
|
220 |
+
self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
|
221 |
+
|
222 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
223 |
+
hidden_states = self.proj(hidden_states)
|
224 |
+
hidden_states = hidden_states.flatten(2).transpose(1, 2) # BCFHW -> BNC
|
225 |
+
return hidden_states
|
226 |
+
|
227 |
+
|
228 |
+
class HunyuanVideoAdaNorm(nn.Module):
|
229 |
+
def __init__(self, in_features: int, out_features: Optional[int] = None) -> None:
|
230 |
+
super().__init__()
|
231 |
+
|
232 |
+
out_features = out_features or 2 * in_features
|
233 |
+
self.linear = nn.Linear(in_features, out_features)
|
234 |
+
self.nonlinearity = nn.SiLU()
|
235 |
+
|
236 |
+
def forward(
|
237 |
+
self, temb: torch.Tensor
|
238 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
239 |
+
temb = self.linear(self.nonlinearity(temb))
|
240 |
+
gate_msa, gate_mlp = temb.chunk(2, dim=1)
|
241 |
+
gate_msa, gate_mlp = gate_msa.unsqueeze(1), gate_mlp.unsqueeze(1)
|
242 |
+
return gate_msa, gate_mlp
|
243 |
+
|
244 |
+
|
245 |
+
class HunyuanVideoTokenReplaceAdaLayerNormZero(nn.Module):
|
246 |
+
def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True):
|
247 |
+
super().__init__()
|
248 |
+
|
249 |
+
self.silu = nn.SiLU()
|
250 |
+
self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
|
251 |
+
|
252 |
+
if norm_type == "layer_norm":
|
253 |
+
self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
|
254 |
+
elif norm_type == "fp32_layer_norm":
|
255 |
+
self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
|
256 |
+
else:
|
257 |
+
raise ValueError(
|
258 |
+
f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
|
259 |
+
)
|
260 |
+
|
261 |
+
def forward(
|
262 |
+
self,
|
263 |
+
hidden_states: torch.Tensor,
|
264 |
+
emb: torch.Tensor,
|
265 |
+
token_replace_emb: torch.Tensor,
|
266 |
+
first_frame_num_tokens: int,
|
267 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
268 |
+
emb = self.linear(self.silu(emb))
|
269 |
+
token_replace_emb = self.linear(self.silu(token_replace_emb))
|
270 |
+
|
271 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
|
272 |
+
tr_shift_msa, tr_scale_msa, tr_gate_msa, tr_shift_mlp, tr_scale_mlp, tr_gate_mlp = token_replace_emb.chunk(
|
273 |
+
6, dim=1
|
274 |
+
)
|
275 |
+
|
276 |
+
norm_hidden_states = self.norm(hidden_states)
|
277 |
+
hidden_states_zero = (
|
278 |
+
norm_hidden_states[:, :first_frame_num_tokens] * (1 + tr_scale_msa[:, None]) + tr_shift_msa[:, None]
|
279 |
+
)
|
280 |
+
hidden_states_orig = (
|
281 |
+
norm_hidden_states[:, first_frame_num_tokens:] * (1 + scale_msa[:, None]) + shift_msa[:, None]
|
282 |
+
)
|
283 |
+
hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
284 |
+
|
285 |
+
return (
|
286 |
+
hidden_states,
|
287 |
+
gate_msa,
|
288 |
+
shift_mlp,
|
289 |
+
scale_mlp,
|
290 |
+
gate_mlp,
|
291 |
+
tr_gate_msa,
|
292 |
+
tr_shift_mlp,
|
293 |
+
tr_scale_mlp,
|
294 |
+
tr_gate_mlp,
|
295 |
+
)
|
296 |
+
|
297 |
+
|
298 |
+
class HunyuanVideoTokenReplaceAdaLayerNormZeroSingle(nn.Module):
|
299 |
+
def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True):
|
300 |
+
super().__init__()
|
301 |
+
|
302 |
+
self.silu = nn.SiLU()
|
303 |
+
self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
|
304 |
+
|
305 |
+
if norm_type == "layer_norm":
|
306 |
+
self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
|
307 |
+
else:
|
308 |
+
raise ValueError(
|
309 |
+
f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
|
310 |
+
)
|
311 |
+
|
312 |
+
def forward(
|
313 |
+
self,
|
314 |
+
hidden_states: torch.Tensor,
|
315 |
+
emb: torch.Tensor,
|
316 |
+
token_replace_emb: torch.Tensor,
|
317 |
+
first_frame_num_tokens: int,
|
318 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
319 |
+
emb = self.linear(self.silu(emb))
|
320 |
+
token_replace_emb = self.linear(self.silu(token_replace_emb))
|
321 |
+
|
322 |
+
shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
|
323 |
+
tr_shift_msa, tr_scale_msa, tr_gate_msa = token_replace_emb.chunk(3, dim=1)
|
324 |
+
|
325 |
+
norm_hidden_states = self.norm(hidden_states)
|
326 |
+
hidden_states_zero = (
|
327 |
+
norm_hidden_states[:, :first_frame_num_tokens] * (1 + tr_scale_msa[:, None]) + tr_shift_msa[:, None]
|
328 |
+
)
|
329 |
+
hidden_states_orig = (
|
330 |
+
norm_hidden_states[:, first_frame_num_tokens:] * (1 + scale_msa[:, None]) + shift_msa[:, None]
|
331 |
+
)
|
332 |
+
hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
333 |
+
|
334 |
+
return hidden_states, gate_msa, tr_gate_msa
|
335 |
+
|
336 |
+
|
337 |
+
class HunyuanVideoConditionEmbedding(nn.Module):
|
338 |
+
def __init__(
|
339 |
+
self,
|
340 |
+
embedding_dim: int,
|
341 |
+
pooled_projection_dim: int,
|
342 |
+
guidance_embeds: bool,
|
343 |
+
image_condition_type: Optional[str] = None,
|
344 |
+
):
|
345 |
+
super().__init__()
|
346 |
+
|
347 |
+
self.image_condition_type = image_condition_type
|
348 |
+
|
349 |
+
self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
|
350 |
+
self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
|
351 |
+
self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
|
352 |
+
|
353 |
+
self.guidance_embedder = None
|
354 |
+
if guidance_embeds:
|
355 |
+
self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
|
356 |
+
|
357 |
+
def forward(
|
358 |
+
self, timestep: torch.Tensor, pooled_projection: torch.Tensor, guidance: Optional[torch.Tensor] = None
|
359 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
360 |
+
timesteps_proj = self.time_proj(timestep)
|
361 |
+
timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
|
362 |
+
pooled_projections = self.text_embedder(pooled_projection)
|
363 |
+
conditioning = timesteps_emb + pooled_projections
|
364 |
+
|
365 |
+
token_replace_emb = None
|
366 |
+
if self.image_condition_type == "token_replace":
|
367 |
+
token_replace_timestep = torch.zeros_like(timestep)
|
368 |
+
token_replace_proj = self.time_proj(token_replace_timestep)
|
369 |
+
token_replace_emb = self.timestep_embedder(token_replace_proj.to(dtype=pooled_projection.dtype))
|
370 |
+
token_replace_emb = token_replace_emb + pooled_projections
|
371 |
+
|
372 |
+
if self.guidance_embedder is not None:
|
373 |
+
guidance_proj = self.time_proj(guidance)
|
374 |
+
guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype))
|
375 |
+
conditioning = conditioning + guidance_emb
|
376 |
+
|
377 |
+
return conditioning, token_replace_emb
|
378 |
+
|
379 |
+
|
380 |
+
class HunyuanVideoIndividualTokenRefinerBlock(nn.Module):
|
381 |
+
def __init__(
|
382 |
+
self,
|
383 |
+
num_attention_heads: int,
|
384 |
+
attention_head_dim: int,
|
385 |
+
mlp_width_ratio: str = 4.0,
|
386 |
+
mlp_drop_rate: float = 0.0,
|
387 |
+
attention_bias: bool = True,
|
388 |
+
) -> None:
|
389 |
+
super().__init__()
|
390 |
+
|
391 |
+
hidden_size = num_attention_heads * attention_head_dim
|
392 |
+
|
393 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
394 |
+
self.attn = Attention(
|
395 |
+
query_dim=hidden_size,
|
396 |
+
cross_attention_dim=None,
|
397 |
+
heads=num_attention_heads,
|
398 |
+
dim_head=attention_head_dim,
|
399 |
+
bias=attention_bias,
|
400 |
+
)
|
401 |
+
|
402 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
403 |
+
self.ff = FeedForward(hidden_size, mult=mlp_width_ratio, activation_fn="linear-silu", dropout=mlp_drop_rate)
|
404 |
+
|
405 |
+
self.norm_out = HunyuanVideoAdaNorm(hidden_size, 2 * hidden_size)
|
406 |
+
|
407 |
+
def forward(
|
408 |
+
self,
|
409 |
+
hidden_states: torch.Tensor,
|
410 |
+
temb: torch.Tensor,
|
411 |
+
attention_mask: Optional[torch.Tensor] = None,
|
412 |
+
) -> torch.Tensor:
|
413 |
+
norm_hidden_states = self.norm1(hidden_states)
|
414 |
+
|
415 |
+
attn_output = self.attn(
|
416 |
+
hidden_states=norm_hidden_states,
|
417 |
+
encoder_hidden_states=None,
|
418 |
+
attention_mask=attention_mask,
|
419 |
+
)
|
420 |
+
|
421 |
+
gate_msa, gate_mlp = self.norm_out(temb)
|
422 |
+
hidden_states = hidden_states + attn_output * gate_msa
|
423 |
+
|
424 |
+
ff_output = self.ff(self.norm2(hidden_states))
|
425 |
+
hidden_states = hidden_states + ff_output * gate_mlp
|
426 |
+
|
427 |
+
return hidden_states
|
428 |
+
|
429 |
+
|
430 |
+
class HunyuanVideoIndividualTokenRefiner(nn.Module):
|
431 |
+
def __init__(
|
432 |
+
self,
|
433 |
+
num_attention_heads: int,
|
434 |
+
attention_head_dim: int,
|
435 |
+
num_layers: int,
|
436 |
+
mlp_width_ratio: float = 4.0,
|
437 |
+
mlp_drop_rate: float = 0.0,
|
438 |
+
attention_bias: bool = True,
|
439 |
+
) -> None:
|
440 |
+
super().__init__()
|
441 |
+
|
442 |
+
self.refiner_blocks = nn.ModuleList(
|
443 |
+
[
|
444 |
+
HunyuanVideoIndividualTokenRefinerBlock(
|
445 |
+
num_attention_heads=num_attention_heads,
|
446 |
+
attention_head_dim=attention_head_dim,
|
447 |
+
mlp_width_ratio=mlp_width_ratio,
|
448 |
+
mlp_drop_rate=mlp_drop_rate,
|
449 |
+
attention_bias=attention_bias,
|
450 |
+
)
|
451 |
+
for _ in range(num_layers)
|
452 |
+
]
|
453 |
+
)
|
454 |
+
|
455 |
+
def forward(
|
456 |
+
self,
|
457 |
+
hidden_states: torch.Tensor,
|
458 |
+
temb: torch.Tensor,
|
459 |
+
attention_mask: Optional[torch.Tensor] = None,
|
460 |
+
) -> None:
|
461 |
+
self_attn_mask = None
|
462 |
+
if attention_mask is not None:
|
463 |
+
batch_size = attention_mask.shape[0]
|
464 |
+
seq_len = attention_mask.shape[1]
|
465 |
+
attention_mask = attention_mask.to(hidden_states.device).bool()
|
466 |
+
self_attn_mask_1 = attention_mask.view(batch_size, 1, 1, seq_len).repeat(1, 1, seq_len, 1)
|
467 |
+
self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)
|
468 |
+
self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()
|
469 |
+
self_attn_mask[:, :, :, 0] = True
|
470 |
+
|
471 |
+
for block in self.refiner_blocks:
|
472 |
+
hidden_states = block(hidden_states, temb, self_attn_mask)
|
473 |
+
|
474 |
+
return hidden_states
|
475 |
+
|
476 |
+
|
477 |
+
class HunyuanVideoTokenRefiner(nn.Module):
|
478 |
+
def __init__(
|
479 |
+
self,
|
480 |
+
in_channels: int,
|
481 |
+
num_attention_heads: int,
|
482 |
+
attention_head_dim: int,
|
483 |
+
num_layers: int,
|
484 |
+
mlp_ratio: float = 4.0,
|
485 |
+
mlp_drop_rate: float = 0.0,
|
486 |
+
attention_bias: bool = True,
|
487 |
+
) -> None:
|
488 |
+
super().__init__()
|
489 |
+
|
490 |
+
hidden_size = num_attention_heads * attention_head_dim
|
491 |
+
|
492 |
+
self.time_text_embed = CombinedTimestepTextProjEmbeddings(
|
493 |
+
embedding_dim=hidden_size, pooled_projection_dim=in_channels
|
494 |
+
)
|
495 |
+
self.proj_in = nn.Linear(in_channels, hidden_size, bias=True)
|
496 |
+
self.token_refiner = HunyuanVideoIndividualTokenRefiner(
|
497 |
+
num_attention_heads=num_attention_heads,
|
498 |
+
attention_head_dim=attention_head_dim,
|
499 |
+
num_layers=num_layers,
|
500 |
+
mlp_width_ratio=mlp_ratio,
|
501 |
+
mlp_drop_rate=mlp_drop_rate,
|
502 |
+
attention_bias=attention_bias,
|
503 |
+
)
|
504 |
+
|
505 |
+
def forward(
|
506 |
+
self,
|
507 |
+
hidden_states: torch.Tensor,
|
508 |
+
timestep: torch.LongTensor,
|
509 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
510 |
+
) -> torch.Tensor:
|
511 |
+
if attention_mask is None:
|
512 |
+
pooled_projections = hidden_states.mean(dim=1)
|
513 |
+
else:
|
514 |
+
original_dtype = hidden_states.dtype
|
515 |
+
mask_float = attention_mask.float().unsqueeze(-1)
|
516 |
+
pooled_projections = (hidden_states * mask_float).sum(dim=1) / mask_float.sum(dim=1)
|
517 |
+
pooled_projections = pooled_projections.to(original_dtype)
|
518 |
+
|
519 |
+
temb = self.time_text_embed(timestep, pooled_projections)
|
520 |
+
hidden_states = self.proj_in(hidden_states)
|
521 |
+
hidden_states = self.token_refiner(hidden_states, temb, attention_mask)
|
522 |
+
|
523 |
+
return hidden_states
|
524 |
+
|
525 |
+
|
526 |
+
class HunyuanVideoRotaryPosEmbed(nn.Module):
|
527 |
+
def __init__(self, patch_size: int, patch_size_t: int, rope_dim: List[int], theta: float = 256.0) -> None:
|
528 |
+
super().__init__()
|
529 |
+
|
530 |
+
self.patch_size = patch_size
|
531 |
+
self.patch_size_t = patch_size_t
|
532 |
+
self.rope_dim = rope_dim
|
533 |
+
self.theta = theta
|
534 |
+
|
535 |
+
def forward(self, hidden_states: torch.Tensor, frame_gap: Union[int, None] = None) -> torch.Tensor:
|
536 |
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
537 |
+
rope_sizes = [num_frames // self.patch_size_t, height // self.patch_size, width // self.patch_size]
|
538 |
+
|
539 |
+
axes_grids = []
|
540 |
+
for i in range(3):
|
541 |
+
# Note: The following line diverges from original behaviour. We create the grid on the device, whereas
|
542 |
+
# original implementation creates it on CPU and then moves it to device. This results in numerical
|
543 |
+
# differences in layerwise debugging outputs, but visually it is the same.
|
544 |
+
grid = torch.arange(0, rope_sizes[i], device=hidden_states.device, dtype=torch.float32)
|
545 |
+
if frame_gap is not None and i == 0:
|
546 |
+
grid = grid * frame_gap
|
547 |
+
axes_grids.append(grid)
|
548 |
+
grid = torch.meshgrid(*axes_grids, indexing="ij") # [W, H, T]
|
549 |
+
grid = torch.stack(grid, dim=0) # [3, W, H, T]
|
550 |
+
|
551 |
+
freqs = []
|
552 |
+
for i in range(3):
|
553 |
+
freq = get_1d_rotary_pos_embed(self.rope_dim[i], grid[i].reshape(-1), self.theta, use_real=True)
|
554 |
+
freqs.append(freq)
|
555 |
+
|
556 |
+
freqs_cos = torch.cat([f[0] for f in freqs], dim=1) # (W * H * T, D / 2)
|
557 |
+
freqs_sin = torch.cat([f[1] for f in freqs], dim=1) # (W * H * T, D / 2)
|
558 |
+
return freqs_cos, freqs_sin
|
559 |
+
|
560 |
+
|
561 |
+
class HunyuanVideoSingleTransformerBlock(nn.Module):
|
562 |
+
def __init__(
|
563 |
+
self,
|
564 |
+
num_attention_heads: int,
|
565 |
+
attention_head_dim: int,
|
566 |
+
mlp_ratio: float = 4.0,
|
567 |
+
qk_norm: str = "rms_norm",
|
568 |
+
inference_subject_driven: bool = False,
|
569 |
+
) -> None:
|
570 |
+
super().__init__()
|
571 |
+
|
572 |
+
hidden_size = num_attention_heads * attention_head_dim
|
573 |
+
mlp_dim = int(hidden_size * mlp_ratio)
|
574 |
+
|
575 |
+
self.attn = Attention(
|
576 |
+
query_dim=hidden_size,
|
577 |
+
cross_attention_dim=None,
|
578 |
+
dim_head=attention_head_dim,
|
579 |
+
heads=num_attention_heads,
|
580 |
+
out_dim=hidden_size,
|
581 |
+
bias=True,
|
582 |
+
processor=HunyuanVideoAttnProcessor2_0(inference_subject_driven=inference_subject_driven),
|
583 |
+
qk_norm=qk_norm,
|
584 |
+
eps=1e-6,
|
585 |
+
pre_only=True,
|
586 |
+
)
|
587 |
+
|
588 |
+
self.norm = AdaLayerNormZeroSingle(hidden_size, norm_type="layer_norm")
|
589 |
+
self.proj_mlp = nn.Linear(hidden_size, mlp_dim)
|
590 |
+
self.act_mlp = nn.GELU(approximate="tanh")
|
591 |
+
self.proj_out = nn.Linear(hidden_size + mlp_dim, hidden_size)
|
592 |
+
|
593 |
+
def forward(
|
594 |
+
self,
|
595 |
+
hidden_states: torch.Tensor,
|
596 |
+
encoder_hidden_states: torch.Tensor,
|
597 |
+
temb: torch.Tensor,
|
598 |
+
attention_mask: Optional[torch.Tensor] = None,
|
599 |
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
600 |
+
*args,
|
601 |
+
**kwargs,
|
602 |
+
) -> torch.Tensor:
|
603 |
+
text_seq_length = encoder_hidden_states.shape[1]
|
604 |
+
hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
|
605 |
+
|
606 |
+
residual = hidden_states
|
607 |
+
|
608 |
+
# 1. Input normalization
|
609 |
+
norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
|
610 |
+
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
|
611 |
+
|
612 |
+
norm_hidden_states, norm_encoder_hidden_states = (
|
613 |
+
norm_hidden_states[:, :-text_seq_length, :],
|
614 |
+
norm_hidden_states[:, -text_seq_length:, :],
|
615 |
+
)
|
616 |
+
|
617 |
+
# 2. Attention
|
618 |
+
attn_output, context_attn_output = self.attn(
|
619 |
+
hidden_states=norm_hidden_states,
|
620 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
621 |
+
attention_mask=attention_mask,
|
622 |
+
image_rotary_emb=image_rotary_emb,
|
623 |
+
)
|
624 |
+
attn_output = torch.cat([attn_output, context_attn_output], dim=1)
|
625 |
+
|
626 |
+
# 3. Modulation and residual connection
|
627 |
+
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
|
628 |
+
hidden_states = gate.unsqueeze(1) * self.proj_out(hidden_states)
|
629 |
+
hidden_states = hidden_states + residual
|
630 |
+
|
631 |
+
hidden_states, encoder_hidden_states = (
|
632 |
+
hidden_states[:, :-text_seq_length, :],
|
633 |
+
hidden_states[:, -text_seq_length:, :],
|
634 |
+
)
|
635 |
+
return hidden_states, encoder_hidden_states
|
636 |
+
|
637 |
+
|
638 |
+
class HunyuanVideoTransformerBlock(nn.Module):
|
639 |
+
def __init__(
|
640 |
+
self,
|
641 |
+
num_attention_heads: int,
|
642 |
+
attention_head_dim: int,
|
643 |
+
mlp_ratio: float,
|
644 |
+
qk_norm: str = "rms_norm",
|
645 |
+
inference_subject_driven: bool = False,
|
646 |
+
) -> None:
|
647 |
+
super().__init__()
|
648 |
+
|
649 |
+
hidden_size = num_attention_heads * attention_head_dim
|
650 |
+
|
651 |
+
self.norm1 = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
|
652 |
+
self.norm1_context = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
|
653 |
+
|
654 |
+
self.attn = Attention(
|
655 |
+
query_dim=hidden_size,
|
656 |
+
cross_attention_dim=None,
|
657 |
+
added_kv_proj_dim=hidden_size,
|
658 |
+
dim_head=attention_head_dim,
|
659 |
+
heads=num_attention_heads,
|
660 |
+
out_dim=hidden_size,
|
661 |
+
context_pre_only=False,
|
662 |
+
bias=True,
|
663 |
+
processor=HunyuanVideoAttnProcessor2_0(inference_subject_driven=inference_subject_driven),
|
664 |
+
qk_norm=qk_norm,
|
665 |
+
eps=1e-6,
|
666 |
+
)
|
667 |
+
|
668 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
669 |
+
self.ff = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
|
670 |
+
|
671 |
+
self.norm2_context = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
672 |
+
self.ff_context = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
|
673 |
+
|
674 |
+
def forward(
|
675 |
+
self,
|
676 |
+
hidden_states: torch.Tensor,
|
677 |
+
encoder_hidden_states: torch.Tensor,
|
678 |
+
temb: torch.Tensor,
|
679 |
+
attention_mask: Optional[torch.Tensor] = None,
|
680 |
+
freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
681 |
+
*args,
|
682 |
+
**kwargs,
|
683 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
684 |
+
# 1. Input normalization
|
685 |
+
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
|
686 |
+
norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
|
687 |
+
encoder_hidden_states, emb=temb
|
688 |
+
)
|
689 |
+
|
690 |
+
# 2. Joint attention
|
691 |
+
attn_output, context_attn_output = self.attn(
|
692 |
+
hidden_states=norm_hidden_states,
|
693 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
694 |
+
attention_mask=attention_mask,
|
695 |
+
image_rotary_emb=freqs_cis,
|
696 |
+
)
|
697 |
+
|
698 |
+
# 3. Modulation and residual connection
|
699 |
+
hidden_states = hidden_states + attn_output * gate_msa.unsqueeze(1)
|
700 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
|
701 |
+
|
702 |
+
norm_hidden_states = self.norm2(hidden_states)
|
703 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
704 |
+
|
705 |
+
norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
706 |
+
norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
707 |
+
|
708 |
+
# 4. Feed-forward
|
709 |
+
ff_output = self.ff(norm_hidden_states)
|
710 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
711 |
+
|
712 |
+
hidden_states = hidden_states + gate_mlp.unsqueeze(1) * ff_output
|
713 |
+
encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
714 |
+
|
715 |
+
return hidden_states, encoder_hidden_states
|
716 |
+
|
717 |
+
|
718 |
+
class HunyuanVideoTokenReplaceSingleTransformerBlock(nn.Module):
|
719 |
+
def __init__(
|
720 |
+
self,
|
721 |
+
num_attention_heads: int,
|
722 |
+
attention_head_dim: int,
|
723 |
+
mlp_ratio: float = 4.0,
|
724 |
+
qk_norm: str = "rms_norm",
|
725 |
+
inference_subject_driven: bool = False,
|
726 |
+
) -> None:
|
727 |
+
super().__init__()
|
728 |
+
|
729 |
+
hidden_size = num_attention_heads * attention_head_dim
|
730 |
+
mlp_dim = int(hidden_size * mlp_ratio)
|
731 |
+
|
732 |
+
self.attn = Attention(
|
733 |
+
query_dim=hidden_size,
|
734 |
+
cross_attention_dim=None,
|
735 |
+
dim_head=attention_head_dim,
|
736 |
+
heads=num_attention_heads,
|
737 |
+
out_dim=hidden_size,
|
738 |
+
bias=True,
|
739 |
+
processor=HunyuanVideoAttnProcessor2_0(inference_subject_driven=inference_subject_driven),
|
740 |
+
qk_norm=qk_norm,
|
741 |
+
eps=1e-6,
|
742 |
+
pre_only=True,
|
743 |
+
)
|
744 |
+
|
745 |
+
self.norm = HunyuanVideoTokenReplaceAdaLayerNormZeroSingle(hidden_size, norm_type="layer_norm")
|
746 |
+
self.proj_mlp = nn.Linear(hidden_size, mlp_dim)
|
747 |
+
self.act_mlp = nn.GELU(approximate="tanh")
|
748 |
+
self.proj_out = nn.Linear(hidden_size + mlp_dim, hidden_size)
|
749 |
+
|
750 |
+
def forward(
|
751 |
+
self,
|
752 |
+
hidden_states: torch.Tensor,
|
753 |
+
encoder_hidden_states: torch.Tensor,
|
754 |
+
temb: torch.Tensor,
|
755 |
+
attention_mask: Optional[torch.Tensor] = None,
|
756 |
+
image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
757 |
+
token_replace_emb: torch.Tensor = None,
|
758 |
+
num_tokens: int = None,
|
759 |
+
) -> torch.Tensor:
|
760 |
+
text_seq_length = encoder_hidden_states.shape[1]
|
761 |
+
hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
|
762 |
+
|
763 |
+
residual = hidden_states
|
764 |
+
|
765 |
+
# 1. Input normalization
|
766 |
+
norm_hidden_states, gate, tr_gate = self.norm(hidden_states, temb, token_replace_emb, num_tokens)
|
767 |
+
mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
|
768 |
+
|
769 |
+
norm_hidden_states, norm_encoder_hidden_states = (
|
770 |
+
norm_hidden_states[:, :-text_seq_length, :],
|
771 |
+
norm_hidden_states[:, -text_seq_length:, :],
|
772 |
+
)
|
773 |
+
|
774 |
+
# 2. Attention
|
775 |
+
attn_output, context_attn_output = self.attn(
|
776 |
+
hidden_states=norm_hidden_states,
|
777 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
778 |
+
attention_mask=attention_mask,
|
779 |
+
image_rotary_emb=image_rotary_emb,
|
780 |
+
)
|
781 |
+
attn_output = torch.cat([attn_output, context_attn_output], dim=1)
|
782 |
+
|
783 |
+
# 3. Modulation and residual connection
|
784 |
+
hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
|
785 |
+
|
786 |
+
proj_output = self.proj_out(hidden_states)
|
787 |
+
hidden_states_zero = proj_output[:, :num_tokens] * tr_gate.unsqueeze(1)
|
788 |
+
hidden_states_orig = proj_output[:, num_tokens:] * gate.unsqueeze(1)
|
789 |
+
hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
790 |
+
hidden_states = hidden_states + residual
|
791 |
+
|
792 |
+
hidden_states, encoder_hidden_states = (
|
793 |
+
hidden_states[:, :-text_seq_length, :],
|
794 |
+
hidden_states[:, -text_seq_length:, :],
|
795 |
+
)
|
796 |
+
return hidden_states, encoder_hidden_states
|
797 |
+
|
798 |
+
|
799 |
+
class HunyuanVideoTokenReplaceTransformerBlock(nn.Module):
|
800 |
+
def __init__(
|
801 |
+
self,
|
802 |
+
num_attention_heads: int,
|
803 |
+
attention_head_dim: int,
|
804 |
+
mlp_ratio: float,
|
805 |
+
qk_norm: str = "rms_norm",
|
806 |
+
inference_subject_driven: bool = False,
|
807 |
+
) -> None:
|
808 |
+
super().__init__()
|
809 |
+
|
810 |
+
hidden_size = num_attention_heads * attention_head_dim
|
811 |
+
|
812 |
+
self.norm1 = HunyuanVideoTokenReplaceAdaLayerNormZero(hidden_size, norm_type="layer_norm")
|
813 |
+
self.norm1_context = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
|
814 |
+
|
815 |
+
self.attn = Attention(
|
816 |
+
query_dim=hidden_size,
|
817 |
+
cross_attention_dim=None,
|
818 |
+
added_kv_proj_dim=hidden_size,
|
819 |
+
dim_head=attention_head_dim,
|
820 |
+
heads=num_attention_heads,
|
821 |
+
out_dim=hidden_size,
|
822 |
+
context_pre_only=False,
|
823 |
+
bias=True,
|
824 |
+
processor=HunyuanVideoAttnProcessor2_0(inference_subject_driven=inference_subject_driven),
|
825 |
+
qk_norm=qk_norm,
|
826 |
+
eps=1e-6,
|
827 |
+
)
|
828 |
+
|
829 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
830 |
+
self.ff = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
|
831 |
+
|
832 |
+
self.norm2_context = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
|
833 |
+
self.ff_context = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
|
834 |
+
|
835 |
+
def forward(
|
836 |
+
self,
|
837 |
+
hidden_states: torch.Tensor,
|
838 |
+
encoder_hidden_states: torch.Tensor,
|
839 |
+
temb: torch.Tensor,
|
840 |
+
attention_mask: Optional[torch.Tensor] = None,
|
841 |
+
freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
842 |
+
token_replace_emb: torch.Tensor = None,
|
843 |
+
num_tokens: int = None,
|
844 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
845 |
+
# 1. Input normalization
|
846 |
+
(
|
847 |
+
norm_hidden_states,
|
848 |
+
gate_msa,
|
849 |
+
shift_mlp,
|
850 |
+
scale_mlp,
|
851 |
+
gate_mlp,
|
852 |
+
tr_gate_msa,
|
853 |
+
tr_shift_mlp,
|
854 |
+
tr_scale_mlp,
|
855 |
+
tr_gate_mlp,
|
856 |
+
) = self.norm1(hidden_states, temb, token_replace_emb, num_tokens)
|
857 |
+
norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
|
858 |
+
encoder_hidden_states, emb=temb
|
859 |
+
)
|
860 |
+
|
861 |
+
# 2. Joint attention
|
862 |
+
attn_output, context_attn_output = self.attn(
|
863 |
+
hidden_states=norm_hidden_states,
|
864 |
+
encoder_hidden_states=norm_encoder_hidden_states,
|
865 |
+
attention_mask=attention_mask,
|
866 |
+
image_rotary_emb=freqs_cis,
|
867 |
+
)
|
868 |
+
|
869 |
+
# 3. Modulation and residual connection
|
870 |
+
hidden_states_zero = hidden_states[:, :num_tokens] + attn_output[:, :num_tokens] * tr_gate_msa.unsqueeze(1)
|
871 |
+
hidden_states_orig = hidden_states[:, num_tokens:] + attn_output[:, num_tokens:] * gate_msa.unsqueeze(1)
|
872 |
+
hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
873 |
+
encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
|
874 |
+
|
875 |
+
norm_hidden_states = self.norm2(hidden_states)
|
876 |
+
norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
|
877 |
+
|
878 |
+
hidden_states_zero = norm_hidden_states[:, :num_tokens] * (1 + tr_scale_mlp[:, None]) + tr_shift_mlp[:, None]
|
879 |
+
hidden_states_orig = norm_hidden_states[:, num_tokens:] * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
|
880 |
+
norm_hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
881 |
+
norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
|
882 |
+
|
883 |
+
# 4. Feed-forward
|
884 |
+
ff_output = self.ff(norm_hidden_states)
|
885 |
+
context_ff_output = self.ff_context(norm_encoder_hidden_states)
|
886 |
+
|
887 |
+
hidden_states_zero = hidden_states[:, :num_tokens] + ff_output[:, :num_tokens] * tr_gate_mlp.unsqueeze(1)
|
888 |
+
hidden_states_orig = hidden_states[:, num_tokens:] + ff_output[:, num_tokens:] * gate_mlp.unsqueeze(1)
|
889 |
+
hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
|
890 |
+
encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
|
891 |
+
|
892 |
+
return hidden_states, encoder_hidden_states
|
893 |
+
|
894 |
+
|
895 |
+
class HunyuanVideoTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin):
|
896 |
+
r"""
|
897 |
+
A Transformer model for video-like data used in [HunyuanVideo](https://huggingface.co/tencent/HunyuanVideo).
|
898 |
+
|
899 |
+
Args:
|
900 |
+
in_channels (`int`, defaults to `16`):
|
901 |
+
The number of channels in the input.
|
902 |
+
out_channels (`int`, defaults to `16`):
|
903 |
+
The number of channels in the output.
|
904 |
+
num_attention_heads (`int`, defaults to `24`):
|
905 |
+
The number of heads to use for multi-head attention.
|
906 |
+
attention_head_dim (`int`, defaults to `128`):
|
907 |
+
The number of channels in each head.
|
908 |
+
num_layers (`int`, defaults to `20`):
|
909 |
+
The number of layers of dual-stream blocks to use.
|
910 |
+
num_single_layers (`int`, defaults to `40`):
|
911 |
+
The number of layers of single-stream blocks to use.
|
912 |
+
num_refiner_layers (`int`, defaults to `2`):
|
913 |
+
The number of layers of refiner blocks to use.
|
914 |
+
mlp_ratio (`float`, defaults to `4.0`):
|
915 |
+
The ratio of the hidden layer size to the input size in the feedforward network.
|
916 |
+
patch_size (`int`, defaults to `2`):
|
917 |
+
The size of the spatial patches to use in the patch embedding layer.
|
918 |
+
patch_size_t (`int`, defaults to `1`):
|
919 |
+
The size of the tmeporal patches to use in the patch embedding layer.
|
920 |
+
qk_norm (`str`, defaults to `rms_norm`):
|
921 |
+
The normalization to use for the query and key projections in the attention layers.
|
922 |
+
guidance_embeds (`bool`, defaults to `True`):
|
923 |
+
Whether to use guidance embeddings in the model.
|
924 |
+
text_embed_dim (`int`, defaults to `4096`):
|
925 |
+
Input dimension of text embeddings from the text encoder.
|
926 |
+
pooled_projection_dim (`int`, defaults to `768`):
|
927 |
+
The dimension of the pooled projection of the text embeddings.
|
928 |
+
rope_theta (`float`, defaults to `256.0`):
|
929 |
+
The value of theta to use in the RoPE layer.
|
930 |
+
rope_axes_dim (`Tuple[int]`, defaults to `(16, 56, 56)`):
|
931 |
+
The dimensions of the axes to use in the RoPE layer.
|
932 |
+
image_condition_type (`str`, *optional*, defaults to `None`):
|
933 |
+
The type of image conditioning to use. If `None`, no image conditioning is used. If `latent_concat`, the
|
934 |
+
image is concatenated to the latent stream. If `token_replace`, the image is used to replace first-frame
|
935 |
+
tokens in the latent stream and apply conditioning.
|
936 |
+
"""
|
937 |
+
|
938 |
+
_supports_gradient_checkpointing = True
|
939 |
+
_skip_layerwise_casting_patterns = ["x_embedder", "context_embedder", "norm"]
|
940 |
+
_no_split_modules = [
|
941 |
+
"HunyuanVideoTransformerBlock",
|
942 |
+
"HunyuanVideoSingleTransformerBlock",
|
943 |
+
"HunyuanVideoPatchEmbed",
|
944 |
+
"HunyuanVideoTokenRefiner",
|
945 |
+
]
|
946 |
+
|
947 |
+
@register_to_config
|
948 |
+
def __init__(
|
949 |
+
self,
|
950 |
+
in_channels: int = 16,
|
951 |
+
out_channels: int = 16,
|
952 |
+
num_attention_heads: int = 24,
|
953 |
+
attention_head_dim: int = 128,
|
954 |
+
num_layers: int = 20,
|
955 |
+
num_single_layers: int = 40,
|
956 |
+
num_refiner_layers: int = 2,
|
957 |
+
mlp_ratio: float = 4.0,
|
958 |
+
patch_size: int = 2,
|
959 |
+
patch_size_t: int = 1,
|
960 |
+
qk_norm: str = "rms_norm",
|
961 |
+
guidance_embeds: bool = True,
|
962 |
+
text_embed_dim: int = 4096,
|
963 |
+
pooled_projection_dim: int = 768,
|
964 |
+
rope_theta: float = 256.0,
|
965 |
+
rope_axes_dim: Tuple[int] = (16, 56, 56),
|
966 |
+
image_condition_type: Optional[str] = None,
|
967 |
+
inference_subject_driven: bool = False,
|
968 |
+
) -> None:
|
969 |
+
super().__init__()
|
970 |
+
|
971 |
+
supported_image_condition_types = ["latent_concat", "token_replace"]
|
972 |
+
if image_condition_type is not None and image_condition_type not in supported_image_condition_types:
|
973 |
+
raise ValueError(
|
974 |
+
f"Invalid `image_condition_type` ({image_condition_type}). Supported ones are: {supported_image_condition_types}"
|
975 |
+
)
|
976 |
+
|
977 |
+
inner_dim = num_attention_heads * attention_head_dim
|
978 |
+
out_channels = out_channels or in_channels
|
979 |
+
|
980 |
+
# 1. Latent and condition embedders
|
981 |
+
self.x_embedder = HunyuanVideoPatchEmbed((patch_size_t, patch_size, patch_size), in_channels, inner_dim)
|
982 |
+
self.context_embedder = HunyuanVideoTokenRefiner(
|
983 |
+
text_embed_dim, num_attention_heads, attention_head_dim, num_layers=num_refiner_layers
|
984 |
+
)
|
985 |
+
|
986 |
+
self.time_text_embed = HunyuanVideoConditionEmbedding(
|
987 |
+
inner_dim, pooled_projection_dim, guidance_embeds, image_condition_type
|
988 |
+
)
|
989 |
+
|
990 |
+
# 2. RoPE
|
991 |
+
self.rope = HunyuanVideoRotaryPosEmbed(patch_size, patch_size_t, rope_axes_dim, rope_theta)
|
992 |
+
|
993 |
+
# 3. Dual stream transformer blocks
|
994 |
+
if image_condition_type == "token_replace":
|
995 |
+
self.transformer_blocks = nn.ModuleList(
|
996 |
+
[
|
997 |
+
HunyuanVideoTokenReplaceTransformerBlock(
|
998 |
+
num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm, inference_subject_driven=inference_subject_driven
|
999 |
+
)
|
1000 |
+
for _ in range(num_layers)
|
1001 |
+
]
|
1002 |
+
)
|
1003 |
+
else:
|
1004 |
+
self.transformer_blocks = nn.ModuleList(
|
1005 |
+
[
|
1006 |
+
HunyuanVideoTransformerBlock(
|
1007 |
+
num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm, inference_subject_driven=inference_subject_driven
|
1008 |
+
)
|
1009 |
+
for _ in range(num_layers)
|
1010 |
+
]
|
1011 |
+
)
|
1012 |
+
|
1013 |
+
# 4. Single stream transformer blocks
|
1014 |
+
if image_condition_type == "token_replace":
|
1015 |
+
self.single_transformer_blocks = nn.ModuleList(
|
1016 |
+
[
|
1017 |
+
HunyuanVideoTokenReplaceSingleTransformerBlock(
|
1018 |
+
num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm, inference_subject_driven=inference_subject_driven
|
1019 |
+
)
|
1020 |
+
for _ in range(num_single_layers)
|
1021 |
+
]
|
1022 |
+
)
|
1023 |
+
else:
|
1024 |
+
self.single_transformer_blocks = nn.ModuleList(
|
1025 |
+
[
|
1026 |
+
HunyuanVideoSingleTransformerBlock(
|
1027 |
+
num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm, inference_subject_driven=inference_subject_driven
|
1028 |
+
)
|
1029 |
+
for _ in range(num_single_layers)
|
1030 |
+
]
|
1031 |
+
)
|
1032 |
+
|
1033 |
+
# 5. Output projection
|
1034 |
+
self.norm_out = AdaLayerNormContinuous(inner_dim, inner_dim, elementwise_affine=False, eps=1e-6)
|
1035 |
+
self.proj_out = nn.Linear(inner_dim, patch_size_t * patch_size * patch_size * out_channels)
|
1036 |
+
|
1037 |
+
self.gradient_checkpointing = False
|
1038 |
+
|
1039 |
+
@property
|
1040 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
|
1041 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
1042 |
+
r"""
|
1043 |
+
Returns:
|
1044 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
1045 |
+
indexed by its weight name.
|
1046 |
+
"""
|
1047 |
+
# set recursively
|
1048 |
+
processors = {}
|
1049 |
+
|
1050 |
+
def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
|
1051 |
+
if hasattr(module, "get_processor"):
|
1052 |
+
processors[f"{name}.processor"] = module.get_processor()
|
1053 |
+
|
1054 |
+
for sub_name, child in module.named_children():
|
1055 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
1056 |
+
|
1057 |
+
return processors
|
1058 |
+
|
1059 |
+
for name, module in self.named_children():
|
1060 |
+
fn_recursive_add_processors(name, module, processors)
|
1061 |
+
|
1062 |
+
return processors
|
1063 |
+
|
1064 |
+
# Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
|
1065 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
1066 |
+
r"""
|
1067 |
+
Sets the attention processor to use to compute attention.
|
1068 |
+
|
1069 |
+
Parameters:
|
1070 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
1071 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
1072 |
+
for **all** `Attention` layers.
|
1073 |
+
|
1074 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
1075 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
1076 |
+
|
1077 |
+
"""
|
1078 |
+
count = len(self.attn_processors.keys())
|
1079 |
+
|
1080 |
+
if isinstance(processor, dict) and len(processor) != count:
|
1081 |
+
raise ValueError(
|
1082 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
1083 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
1084 |
+
)
|
1085 |
+
|
1086 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
1087 |
+
if hasattr(module, "set_processor"):
|
1088 |
+
if not isinstance(processor, dict):
|
1089 |
+
module.set_processor(processor)
|
1090 |
+
else:
|
1091 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
1092 |
+
|
1093 |
+
for sub_name, child in module.named_children():
|
1094 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
1095 |
+
|
1096 |
+
for name, module in self.named_children():
|
1097 |
+
fn_recursive_attn_processor(name, module, processor)
|
1098 |
+
|
1099 |
+
def forward(
|
1100 |
+
self,
|
1101 |
+
hidden_states: torch.Tensor,
|
1102 |
+
timestep: torch.LongTensor,
|
1103 |
+
encoder_hidden_states: torch.Tensor,
|
1104 |
+
encoder_attention_mask: torch.Tensor,
|
1105 |
+
pooled_projections: torch.Tensor,
|
1106 |
+
encoder_hidden_states_condition: Union[torch.Tensor, None] = None,
|
1107 |
+
encoder_attention_mask_condition: Union[torch.Tensor, None] = None,
|
1108 |
+
guidance: torch.Tensor = None,
|
1109 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
1110 |
+
return_dict: bool = True,
|
1111 |
+
frame_gap: Union[int, None] = None,
|
1112 |
+
) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
|
1113 |
+
if attention_kwargs is not None:
|
1114 |
+
attention_kwargs = attention_kwargs.copy()
|
1115 |
+
lora_scale = attention_kwargs.pop("scale", 1.0)
|
1116 |
+
else:
|
1117 |
+
lora_scale = 1.0
|
1118 |
+
|
1119 |
+
if USE_PEFT_BACKEND:
|
1120 |
+
# weight the lora layers by setting `lora_scale` for each PEFT layer
|
1121 |
+
scale_lora_layers(self, lora_scale)
|
1122 |
+
else:
|
1123 |
+
if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
|
1124 |
+
logger.warning(
|
1125 |
+
"Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
|
1126 |
+
)
|
1127 |
+
|
1128 |
+
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
1129 |
+
p, p_t = self.config.patch_size, self.config.patch_size_t
|
1130 |
+
post_patch_num_frames = num_frames // p_t
|
1131 |
+
post_patch_height = height // p
|
1132 |
+
post_patch_width = width // p
|
1133 |
+
first_frame_num_tokens = 1 * post_patch_height * post_patch_width
|
1134 |
+
|
1135 |
+
# 1. RoPE
|
1136 |
+
image_rotary_emb = self.rope(hidden_states, frame_gap=frame_gap)
|
1137 |
+
|
1138 |
+
# 2. Conditional embeddings
|
1139 |
+
temb, token_replace_emb = self.time_text_embed(timestep, pooled_projections, guidance)
|
1140 |
+
|
1141 |
+
hidden_states = self.x_embedder(hidden_states)
|
1142 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states, timestep, encoder_attention_mask)
|
1143 |
+
if encoder_hidden_states_condition is not None and encoder_attention_mask_condition is not None:
|
1144 |
+
encoder_hidden_states_condition = self.context_embedder(
|
1145 |
+
encoder_hidden_states_condition,
|
1146 |
+
torch.zeros_like(timestep),
|
1147 |
+
encoder_attention_mask_condition,
|
1148 |
+
)
|
1149 |
+
encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_condition], dim=1)
|
1150 |
+
encoder_attention_mask = torch.cat([encoder_attention_mask, encoder_attention_mask_condition], dim=1)
|
1151 |
+
|
1152 |
+
# 3. Attention mask preparation
|
1153 |
+
latent_sequence_length = hidden_states.shape[1]
|
1154 |
+
condition_sequence_length = encoder_hidden_states.shape[1]
|
1155 |
+
sequence_length = latent_sequence_length + condition_sequence_length
|
1156 |
+
attention_mask = torch.zeros(
|
1157 |
+
batch_size, sequence_length, device=hidden_states.device, dtype=torch.bool
|
1158 |
+
) # [B, N]
|
1159 |
+
|
1160 |
+
effective_condition_sequence_length = encoder_attention_mask.sum(dim=1, dtype=torch.int) # [B,]
|
1161 |
+
effective_sequence_length = latent_sequence_length + effective_condition_sequence_length
|
1162 |
+
|
1163 |
+
for i in range(batch_size):
|
1164 |
+
if encoder_attention_mask_condition is not None and encoder_attention_mask_condition is not None:
|
1165 |
+
attention_mask[i, : latent_sequence_length] = True
|
1166 |
+
attention_mask[i, latent_sequence_length :][encoder_attention_mask[i] == 1.] = True
|
1167 |
+
else:
|
1168 |
+
attention_mask[i, : effective_sequence_length[i]] = True
|
1169 |
+
# [B, 1, 1, N], for broadcasting across attention heads
|
1170 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
|
1171 |
+
|
1172 |
+
# 4. Transformer blocks
|
1173 |
+
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
1174 |
+
for block in self.transformer_blocks:
|
1175 |
+
hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
|
1176 |
+
block,
|
1177 |
+
hidden_states,
|
1178 |
+
encoder_hidden_states,
|
1179 |
+
temb,
|
1180 |
+
attention_mask,
|
1181 |
+
image_rotary_emb,
|
1182 |
+
token_replace_emb,
|
1183 |
+
first_frame_num_tokens,
|
1184 |
+
)
|
1185 |
+
|
1186 |
+
for block in self.single_transformer_blocks:
|
1187 |
+
hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
|
1188 |
+
block,
|
1189 |
+
hidden_states,
|
1190 |
+
encoder_hidden_states,
|
1191 |
+
temb,
|
1192 |
+
attention_mask,
|
1193 |
+
image_rotary_emb,
|
1194 |
+
token_replace_emb,
|
1195 |
+
first_frame_num_tokens,
|
1196 |
+
)
|
1197 |
+
|
1198 |
+
else:
|
1199 |
+
for block in self.transformer_blocks:
|
1200 |
+
hidden_states, encoder_hidden_states = block(
|
1201 |
+
hidden_states,
|
1202 |
+
encoder_hidden_states,
|
1203 |
+
temb,
|
1204 |
+
attention_mask,
|
1205 |
+
image_rotary_emb,
|
1206 |
+
token_replace_emb,
|
1207 |
+
first_frame_num_tokens,
|
1208 |
+
)
|
1209 |
+
|
1210 |
+
for block in self.single_transformer_blocks:
|
1211 |
+
hidden_states, encoder_hidden_states = block(
|
1212 |
+
hidden_states,
|
1213 |
+
encoder_hidden_states,
|
1214 |
+
temb,
|
1215 |
+
attention_mask,
|
1216 |
+
image_rotary_emb,
|
1217 |
+
token_replace_emb,
|
1218 |
+
first_frame_num_tokens,
|
1219 |
+
)
|
1220 |
+
|
1221 |
+
# 5. Output projection
|
1222 |
+
hidden_states = self.norm_out(hidden_states, temb)
|
1223 |
+
hidden_states = self.proj_out(hidden_states)
|
1224 |
+
|
1225 |
+
hidden_states = hidden_states.reshape(
|
1226 |
+
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, -1, p_t, p, p
|
1227 |
+
)
|
1228 |
+
hidden_states = hidden_states.permute(0, 4, 1, 5, 2, 6, 3, 7)
|
1229 |
+
hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
1230 |
+
|
1231 |
+
if USE_PEFT_BACKEND:
|
1232 |
+
# remove `lora_scale` from each PEFT layer
|
1233 |
+
unscale_lora_layers(self, lora_scale)
|
1234 |
+
|
1235 |
+
if not return_dict:
|
1236 |
+
return (hidden_states,)
|
1237 |
+
|
1238 |
+
return Transformer2DModelOutput(sample=hidden_states)
|
pipelines/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
from .pipeline_hunyuan_video_i2v import HunyuanVideoImageToVideoPipeline
|
pipelines/pipeline_hunyuan_video_i2v.py
ADDED
@@ -0,0 +1,969 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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024 The HunyuanVideo Team and 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 |
+
# Modified by [Hengyuan Cao] in 2025.
|
15 |
+
|
16 |
+
import inspect
|
17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
import PIL.Image
|
21 |
+
import torch
|
22 |
+
from transformers import (
|
23 |
+
CLIPImageProcessor,
|
24 |
+
CLIPTextModel,
|
25 |
+
CLIPTokenizer,
|
26 |
+
LlamaTokenizerFast,
|
27 |
+
LlavaForConditionalGeneration,
|
28 |
+
)
|
29 |
+
|
30 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
31 |
+
from diffusers.loaders import HunyuanVideoLoraLoaderMixin
|
32 |
+
from diffusers.models import AutoencoderKLHunyuanVideo, HunyuanVideoTransformer3DModel
|
33 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
34 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
35 |
+
from diffusers.utils.torch_utils import randn_tensor
|
36 |
+
from diffusers.video_processor import VideoProcessor
|
37 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
38 |
+
from diffusers.pipelines.hunyuan_video.pipeline_output import HunyuanVideoPipelineOutput
|
39 |
+
|
40 |
+
|
41 |
+
if is_torch_xla_available():
|
42 |
+
import torch_xla.core.xla_model as xm
|
43 |
+
|
44 |
+
XLA_AVAILABLE = True
|
45 |
+
else:
|
46 |
+
XLA_AVAILABLE = False
|
47 |
+
|
48 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
49 |
+
|
50 |
+
|
51 |
+
EXAMPLE_DOC_STRING = """
|
52 |
+
Examples:
|
53 |
+
```python
|
54 |
+
>>> import torch
|
55 |
+
>>> from diffusers import HunyuanVideoImageToVideoPipeline, HunyuanVideoTransformer3DModel
|
56 |
+
>>> from diffusers.utils import load_image, export_to_video
|
57 |
+
|
58 |
+
>>> # Available checkpoints: hunyuanvideo-community/HunyuanVideo-I2V, hunyuanvideo-community/HunyuanVideo-I2V-33ch
|
59 |
+
>>> model_id = "hunyuanvideo-community/HunyuanVideo-I2V"
|
60 |
+
>>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
|
61 |
+
... model_id, subfolder="transformer", torch_dtype=torch.bfloat16
|
62 |
+
... )
|
63 |
+
>>> pipe = HunyuanVideoImageToVideoPipeline.from_pretrained(
|
64 |
+
... model_id, transformer=transformer, torch_dtype=torch.float16
|
65 |
+
... )
|
66 |
+
>>> pipe.vae.enable_tiling()
|
67 |
+
>>> pipe.to("cuda")
|
68 |
+
|
69 |
+
>>> prompt = "A man with short gray hair plays a red electric guitar."
|
70 |
+
>>> image = load_image(
|
71 |
+
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/guitar-man.png"
|
72 |
+
... )
|
73 |
+
|
74 |
+
>>> # If using hunyuanvideo-community/HunyuanVideo-I2V
|
75 |
+
>>> output = pipe(image=image, prompt=prompt, guidance_scale=6.0).frames[0]
|
76 |
+
|
77 |
+
>>> # If using hunyuanvideo-community/HunyuanVideo-I2V-33ch
|
78 |
+
>>> output = pipe(image=image, prompt=prompt, guidance_scale=1.0, true_cfg_scale=1.0).frames[0]
|
79 |
+
|
80 |
+
>>> export_to_video(output, "output.mp4", fps=15)
|
81 |
+
```
|
82 |
+
"""
|
83 |
+
|
84 |
+
|
85 |
+
DEFAULT_PROMPT_TEMPLATE = {
|
86 |
+
"template": (
|
87 |
+
"<|start_header_id|>system<|end_header_id|>\n\n<image>\nDescribe the video by detailing the following aspects according to the reference image: "
|
88 |
+
"1. The main content and theme of the video."
|
89 |
+
"2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
|
90 |
+
"3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
|
91 |
+
"4. background environment, light, style and atmosphere."
|
92 |
+
"5. camera angles, movements, and transitions used in the video:<|eot_id|>\n\n"
|
93 |
+
"<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
|
94 |
+
"<|start_header_id|>assistant<|end_header_id|>\n\n"
|
95 |
+
),
|
96 |
+
"crop_start": 103,
|
97 |
+
"image_emb_start": 5,
|
98 |
+
"image_emb_end": 581,
|
99 |
+
"image_emb_len": 576,
|
100 |
+
"double_return_token_id": 271,
|
101 |
+
}
|
102 |
+
|
103 |
+
|
104 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
105 |
+
def retrieve_timesteps(
|
106 |
+
scheduler,
|
107 |
+
num_inference_steps: Optional[int] = None,
|
108 |
+
device: Optional[Union[str, torch.device]] = None,
|
109 |
+
timesteps: Optional[List[int]] = None,
|
110 |
+
sigmas: Optional[List[float]] = None,
|
111 |
+
**kwargs,
|
112 |
+
):
|
113 |
+
r"""
|
114 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
115 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
116 |
+
|
117 |
+
Args:
|
118 |
+
scheduler (`SchedulerMixin`):
|
119 |
+
The scheduler to get timesteps from.
|
120 |
+
num_inference_steps (`int`):
|
121 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
122 |
+
must be `None`.
|
123 |
+
device (`str` or `torch.device`, *optional*):
|
124 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
125 |
+
timesteps (`List[int]`, *optional*):
|
126 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
127 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
128 |
+
sigmas (`List[float]`, *optional*):
|
129 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
130 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
131 |
+
|
132 |
+
Returns:
|
133 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
134 |
+
second element is the number of inference steps.
|
135 |
+
"""
|
136 |
+
if timesteps is not None and sigmas is not None:
|
137 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
138 |
+
if timesteps is not None:
|
139 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
140 |
+
if not accepts_timesteps:
|
141 |
+
raise ValueError(
|
142 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
143 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
144 |
+
)
|
145 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
146 |
+
timesteps = scheduler.timesteps
|
147 |
+
num_inference_steps = len(timesteps)
|
148 |
+
elif sigmas is not None:
|
149 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
150 |
+
if not accept_sigmas:
|
151 |
+
raise ValueError(
|
152 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
153 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
154 |
+
)
|
155 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
156 |
+
timesteps = scheduler.timesteps
|
157 |
+
num_inference_steps = len(timesteps)
|
158 |
+
else:
|
159 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
160 |
+
timesteps = scheduler.timesteps
|
161 |
+
return timesteps, num_inference_steps
|
162 |
+
|
163 |
+
|
164 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
165 |
+
def retrieve_latents(
|
166 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
167 |
+
):
|
168 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
169 |
+
return encoder_output.latent_dist.sample(generator)
|
170 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
171 |
+
return encoder_output.latent_dist.mode()
|
172 |
+
elif hasattr(encoder_output, "latents"):
|
173 |
+
return encoder_output.latents
|
174 |
+
else:
|
175 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
176 |
+
|
177 |
+
|
178 |
+
class HunyuanVideoImageToVideoPipeline(DiffusionPipeline, HunyuanVideoLoraLoaderMixin):
|
179 |
+
r"""
|
180 |
+
Pipeline for image-to-video generation using HunyuanVideo.
|
181 |
+
|
182 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
183 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
184 |
+
|
185 |
+
Args:
|
186 |
+
text_encoder ([`LlavaForConditionalGeneration`]):
|
187 |
+
[Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
|
188 |
+
tokenizer (`LlamaTokenizer`):
|
189 |
+
Tokenizer from [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).
|
190 |
+
transformer ([`HunyuanVideoTransformer3DModel`]):
|
191 |
+
Conditional Transformer to denoise the encoded image latents.
|
192 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
193 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
194 |
+
vae ([`AutoencoderKLHunyuanVideo`]):
|
195 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
196 |
+
text_encoder_2 ([`CLIPTextModel`]):
|
197 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
198 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
199 |
+
tokenizer_2 (`CLIPTokenizer`):
|
200 |
+
Tokenizer of class
|
201 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
202 |
+
"""
|
203 |
+
|
204 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
205 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
206 |
+
|
207 |
+
def __init__(
|
208 |
+
self,
|
209 |
+
text_encoder: LlavaForConditionalGeneration,
|
210 |
+
tokenizer: LlamaTokenizerFast,
|
211 |
+
transformer: HunyuanVideoTransformer3DModel,
|
212 |
+
vae: AutoencoderKLHunyuanVideo,
|
213 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
214 |
+
text_encoder_2: CLIPTextModel,
|
215 |
+
tokenizer_2: CLIPTokenizer,
|
216 |
+
image_processor: CLIPImageProcessor,
|
217 |
+
):
|
218 |
+
super().__init__()
|
219 |
+
|
220 |
+
self.register_modules(
|
221 |
+
vae=vae,
|
222 |
+
text_encoder=text_encoder,
|
223 |
+
tokenizer=tokenizer,
|
224 |
+
transformer=transformer,
|
225 |
+
scheduler=scheduler,
|
226 |
+
text_encoder_2=text_encoder_2,
|
227 |
+
tokenizer_2=tokenizer_2,
|
228 |
+
image_processor=image_processor,
|
229 |
+
)
|
230 |
+
|
231 |
+
self.vae_scaling_factor = self.vae.config.scaling_factor if getattr(self, "vae", None) else 0.476986
|
232 |
+
self.vae_scale_factor_temporal = self.vae.temporal_compression_ratio if getattr(self, "vae", None) else 4
|
233 |
+
self.vae_scale_factor_spatial = self.vae.spatial_compression_ratio if getattr(self, "vae", None) else 8
|
234 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
235 |
+
|
236 |
+
def _get_llama_prompt_embeds(
|
237 |
+
self,
|
238 |
+
image: torch.Tensor,
|
239 |
+
prompt: Union[str, List[str]],
|
240 |
+
prompt_template: Dict[str, Any],
|
241 |
+
num_videos_per_prompt: int = 1,
|
242 |
+
device: Optional[torch.device] = None,
|
243 |
+
dtype: Optional[torch.dtype] = None,
|
244 |
+
max_sequence_length: int = 256,
|
245 |
+
num_hidden_layers_to_skip: int = 2,
|
246 |
+
image_embed_interleave: int = 2,
|
247 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
248 |
+
device = device or self._execution_device
|
249 |
+
dtype = dtype or self.text_encoder.dtype
|
250 |
+
|
251 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
252 |
+
prompt = [prompt_template["template"].format(p) for p in prompt]
|
253 |
+
|
254 |
+
crop_start = prompt_template.get("crop_start", None)
|
255 |
+
if crop_start is None:
|
256 |
+
prompt_template_input = self.tokenizer(
|
257 |
+
prompt_template["template"],
|
258 |
+
padding="max_length",
|
259 |
+
return_tensors="pt",
|
260 |
+
return_length=False,
|
261 |
+
return_overflowing_tokens=False,
|
262 |
+
return_attention_mask=False,
|
263 |
+
)
|
264 |
+
crop_start = prompt_template_input["input_ids"].shape[-1]
|
265 |
+
# Remove <|start_header_id|>, <|end_header_id|>, assistant, <|eot_id|>, and placeholder {}
|
266 |
+
crop_start -= 5
|
267 |
+
|
268 |
+
max_sequence_length += crop_start
|
269 |
+
text_inputs = self.tokenizer(
|
270 |
+
prompt,
|
271 |
+
max_length=max_sequence_length,
|
272 |
+
padding="max_length",
|
273 |
+
truncation=True,
|
274 |
+
return_tensors="pt",
|
275 |
+
return_length=False,
|
276 |
+
return_overflowing_tokens=False,
|
277 |
+
return_attention_mask=True,
|
278 |
+
)
|
279 |
+
text_input_ids = text_inputs.input_ids.to(device=device)
|
280 |
+
prompt_attention_mask = text_inputs.attention_mask.to(device=device)
|
281 |
+
|
282 |
+
image_embeds = self.image_processor(image, return_tensors="pt").pixel_values.to(device)
|
283 |
+
|
284 |
+
prompt_embeds = self.text_encoder(
|
285 |
+
input_ids=text_input_ids,
|
286 |
+
attention_mask=prompt_attention_mask,
|
287 |
+
pixel_values=image_embeds,
|
288 |
+
output_hidden_states=True,
|
289 |
+
).hidden_states[-(num_hidden_layers_to_skip + 1)]
|
290 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype)
|
291 |
+
|
292 |
+
image_emb_len = prompt_template.get("image_emb_len", 576)
|
293 |
+
image_emb_start = prompt_template.get("image_emb_start", 5)
|
294 |
+
image_emb_end = prompt_template.get("image_emb_end", 581)
|
295 |
+
double_return_token_id = prompt_template.get("double_return_token_id", 271)
|
296 |
+
|
297 |
+
if crop_start is not None and crop_start > 0:
|
298 |
+
text_crop_start = crop_start - 1 + image_emb_len
|
299 |
+
batch_indices, last_double_return_token_indices = torch.where(text_input_ids == double_return_token_id)
|
300 |
+
|
301 |
+
if last_double_return_token_indices.shape[0] == 3:
|
302 |
+
# in case the prompt is too long
|
303 |
+
last_double_return_token_indices = torch.cat(
|
304 |
+
(last_double_return_token_indices, torch.tensor([text_input_ids.shape[-1]]))
|
305 |
+
)
|
306 |
+
batch_indices = torch.cat((batch_indices, torch.tensor([0])))
|
307 |
+
|
308 |
+
last_double_return_token_indices = last_double_return_token_indices.reshape(text_input_ids.shape[0], -1)[
|
309 |
+
:, -1
|
310 |
+
]
|
311 |
+
batch_indices = batch_indices.reshape(text_input_ids.shape[0], -1)[:, -1]
|
312 |
+
assistant_crop_start = last_double_return_token_indices - 1 + image_emb_len - 4
|
313 |
+
assistant_crop_end = last_double_return_token_indices - 1 + image_emb_len
|
314 |
+
attention_mask_assistant_crop_start = last_double_return_token_indices - 4
|
315 |
+
attention_mask_assistant_crop_end = last_double_return_token_indices
|
316 |
+
|
317 |
+
prompt_embed_list = []
|
318 |
+
prompt_attention_mask_list = []
|
319 |
+
image_embed_list = []
|
320 |
+
image_attention_mask_list = []
|
321 |
+
|
322 |
+
for i in range(text_input_ids.shape[0]):
|
323 |
+
prompt_embed_list.append(
|
324 |
+
torch.cat(
|
325 |
+
[
|
326 |
+
prompt_embeds[i, text_crop_start : assistant_crop_start[i].item()],
|
327 |
+
prompt_embeds[i, assistant_crop_end[i].item() :],
|
328 |
+
]
|
329 |
+
)
|
330 |
+
)
|
331 |
+
prompt_attention_mask_list.append(
|
332 |
+
torch.cat(
|
333 |
+
[
|
334 |
+
prompt_attention_mask[i, crop_start : attention_mask_assistant_crop_start[i].item()],
|
335 |
+
prompt_attention_mask[i, attention_mask_assistant_crop_end[i].item() :],
|
336 |
+
]
|
337 |
+
)
|
338 |
+
)
|
339 |
+
image_embed_list.append(prompt_embeds[i, image_emb_start:image_emb_end])
|
340 |
+
image_attention_mask_list.append(
|
341 |
+
torch.ones(image_embed_list[-1].shape[0]).to(prompt_embeds.device).to(prompt_attention_mask.dtype)
|
342 |
+
)
|
343 |
+
|
344 |
+
prompt_embed_list = torch.stack(prompt_embed_list)
|
345 |
+
prompt_attention_mask_list = torch.stack(prompt_attention_mask_list)
|
346 |
+
image_embed_list = torch.stack(image_embed_list)
|
347 |
+
image_attention_mask_list = torch.stack(image_attention_mask_list)
|
348 |
+
|
349 |
+
if 0 < image_embed_interleave < 6:
|
350 |
+
image_embed_list = image_embed_list[:, ::image_embed_interleave, :]
|
351 |
+
image_attention_mask_list = image_attention_mask_list[:, ::image_embed_interleave]
|
352 |
+
|
353 |
+
if not (
|
354 |
+
prompt_embed_list.shape[0] == prompt_attention_mask_list.shape[0]
|
355 |
+
and image_embed_list.shape[0] == image_attention_mask_list.shape[0]
|
356 |
+
):
|
357 |
+
raise ValueError(
|
358 |
+
"Input tensors have mismatched batch dimensions."
|
359 |
+
)
|
360 |
+
|
361 |
+
prompt_embeds = torch.cat([image_embed_list, prompt_embed_list], dim=1)
|
362 |
+
prompt_attention_mask = torch.cat([image_attention_mask_list, prompt_attention_mask_list], dim=1)
|
363 |
+
|
364 |
+
return prompt_embeds, prompt_attention_mask
|
365 |
+
|
366 |
+
def _get_clip_prompt_embeds(
|
367 |
+
self,
|
368 |
+
prompt: Union[str, List[str]],
|
369 |
+
num_videos_per_prompt: int = 1,
|
370 |
+
device: Optional[torch.device] = None,
|
371 |
+
dtype: Optional[torch.dtype] = None,
|
372 |
+
max_sequence_length: int = 77,
|
373 |
+
) -> torch.Tensor:
|
374 |
+
device = device or self._execution_device
|
375 |
+
dtype = dtype or self.text_encoder_2.dtype
|
376 |
+
|
377 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
378 |
+
|
379 |
+
text_inputs = self.tokenizer_2(
|
380 |
+
prompt,
|
381 |
+
padding="max_length",
|
382 |
+
max_length=max_sequence_length,
|
383 |
+
truncation=True,
|
384 |
+
return_tensors="pt",
|
385 |
+
)
|
386 |
+
|
387 |
+
text_input_ids = text_inputs.input_ids
|
388 |
+
untruncated_ids = self.tokenizer_2(prompt, padding="longest", return_tensors="pt").input_ids
|
389 |
+
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
|
390 |
+
removed_text = self.tokenizer_2.batch_decode(untruncated_ids[:, max_sequence_length - 1 : -1])
|
391 |
+
# logger.warning(
|
392 |
+
# "The following part of your input was truncated because CLIP can only handle sequences up to"
|
393 |
+
# f" {max_sequence_length} tokens: {removed_text}"
|
394 |
+
# )
|
395 |
+
|
396 |
+
prompt_embeds = self.text_encoder_2(text_input_ids.to(device), output_hidden_states=False).pooler_output
|
397 |
+
return prompt_embeds
|
398 |
+
|
399 |
+
def encode_prompt(
|
400 |
+
self,
|
401 |
+
image: torch.Tensor,
|
402 |
+
prompt: Union[str, List[str]],
|
403 |
+
prompt_condition: Union[str, List[str], None] = None,
|
404 |
+
prompt_2: Union[str, List[str]] = None,
|
405 |
+
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
|
406 |
+
num_videos_per_prompt: int = 1,
|
407 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
408 |
+
prompt_embeds_condition: Optional[torch.Tensor] = None,
|
409 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
410 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
411 |
+
prompt_attention_mask_condition: Optional[torch.Tensor] = None,
|
412 |
+
device: Optional[torch.device] = None,
|
413 |
+
dtype: Optional[torch.dtype] = None,
|
414 |
+
max_sequence_length: int = 256,
|
415 |
+
image_embed_interleave: int = 2,
|
416 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
417 |
+
if prompt_embeds is None:
|
418 |
+
prompt_embeds, prompt_attention_mask = self._get_llama_prompt_embeds(
|
419 |
+
image,
|
420 |
+
prompt,
|
421 |
+
prompt_template,
|
422 |
+
num_videos_per_prompt,
|
423 |
+
device=device,
|
424 |
+
dtype=dtype,
|
425 |
+
max_sequence_length=max_sequence_length,
|
426 |
+
image_embed_interleave=image_embed_interleave,
|
427 |
+
)
|
428 |
+
|
429 |
+
if prompt_condition is not None and (prompt_embeds_condition is None or prompt_attention_mask_condition is None):
|
430 |
+
prompt_embeds_condition, prompt_attention_mask_condition = self._get_llama_prompt_embeds(
|
431 |
+
image,
|
432 |
+
prompt_condition,
|
433 |
+
prompt_template,
|
434 |
+
num_videos_per_prompt,
|
435 |
+
device=device,
|
436 |
+
dtype=dtype,
|
437 |
+
max_sequence_length=max_sequence_length,
|
438 |
+
image_embed_interleave=image_embed_interleave,
|
439 |
+
)
|
440 |
+
else:
|
441 |
+
prompt_embeds_condition = prompt_embeds_condition
|
442 |
+
prompt_attention_mask_condition = prompt_attention_mask_condition
|
443 |
+
|
444 |
+
if pooled_prompt_embeds is None:
|
445 |
+
if prompt_2 is None:
|
446 |
+
prompt_2 = prompt
|
447 |
+
pooled_prompt_embeds = self._get_clip_prompt_embeds(
|
448 |
+
prompt,
|
449 |
+
num_videos_per_prompt,
|
450 |
+
device=device,
|
451 |
+
dtype=dtype,
|
452 |
+
max_sequence_length=77,
|
453 |
+
)
|
454 |
+
|
455 |
+
return prompt_embeds, prompt_embeds_condition, pooled_prompt_embeds, prompt_attention_mask, prompt_attention_mask_condition
|
456 |
+
|
457 |
+
def check_inputs(
|
458 |
+
self,
|
459 |
+
prompt,
|
460 |
+
prompt_2,
|
461 |
+
height,
|
462 |
+
width,
|
463 |
+
prompt_embeds=None,
|
464 |
+
callback_on_step_end_tensor_inputs=None,
|
465 |
+
prompt_template=None,
|
466 |
+
true_cfg_scale=1.0,
|
467 |
+
guidance_scale=1.0,
|
468 |
+
):
|
469 |
+
if height % 16 != 0 or width % 16 != 0:
|
470 |
+
raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
471 |
+
|
472 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
473 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
474 |
+
):
|
475 |
+
raise ValueError(
|
476 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
477 |
+
)
|
478 |
+
|
479 |
+
if prompt is not None and prompt_embeds is not None:
|
480 |
+
raise ValueError(
|
481 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
482 |
+
" only forward one of the two."
|
483 |
+
)
|
484 |
+
elif prompt_2 is not None and prompt_embeds is not None:
|
485 |
+
raise ValueError(
|
486 |
+
f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
487 |
+
" only forward one of the two."
|
488 |
+
)
|
489 |
+
elif prompt is None and prompt_embeds is None:
|
490 |
+
raise ValueError(
|
491 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
492 |
+
)
|
493 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
494 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
495 |
+
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
|
496 |
+
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
|
497 |
+
|
498 |
+
if prompt_template is not None:
|
499 |
+
if not isinstance(prompt_template, dict):
|
500 |
+
raise ValueError(f"`prompt_template` has to be of type `dict` but is {type(prompt_template)}")
|
501 |
+
if "template" not in prompt_template:
|
502 |
+
raise ValueError(
|
503 |
+
f"`prompt_template` has to contain a key `template` but only found {prompt_template.keys()}"
|
504 |
+
)
|
505 |
+
|
506 |
+
if true_cfg_scale > 1.0 and guidance_scale > 1.0:
|
507 |
+
logger.warning(
|
508 |
+
"Both `true_cfg_scale` and `guidance_scale` are greater than 1.0. This will result in both "
|
509 |
+
"classifier-free guidance and embedded-guidance to be applied. This is not recommended "
|
510 |
+
"as it may lead to higher memory usage, slower inference and potentially worse results."
|
511 |
+
)
|
512 |
+
|
513 |
+
def prepare_latents(
|
514 |
+
self,
|
515 |
+
image: torch.Tensor,
|
516 |
+
batch_size: int,
|
517 |
+
num_channels_latents: int = 32,
|
518 |
+
height: int = 720,
|
519 |
+
width: int = 1280,
|
520 |
+
num_frames: int = 129,
|
521 |
+
dtype: Optional[torch.dtype] = None,
|
522 |
+
device: Optional[torch.device] = None,
|
523 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
524 |
+
latents: Optional[torch.Tensor] = None,
|
525 |
+
image_condition_type: str = "latent_concat",
|
526 |
+
) -> torch.Tensor:
|
527 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
528 |
+
raise ValueError(
|
529 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
530 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
531 |
+
)
|
532 |
+
|
533 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
534 |
+
latent_height, latent_width = height // self.vae_scale_factor_spatial, width // self.vae_scale_factor_spatial
|
535 |
+
shape = (batch_size, num_channels_latents, num_latent_frames, latent_height, latent_width)
|
536 |
+
|
537 |
+
image = image.unsqueeze(2) # [B, C, 1, H, W]
|
538 |
+
if isinstance(generator, list):
|
539 |
+
image_latents = [
|
540 |
+
retrieve_latents(self.vae.encode(image[i].unsqueeze(0)), generator[i], "argmax")
|
541 |
+
for i in range(batch_size)
|
542 |
+
]
|
543 |
+
else:
|
544 |
+
image_latents = [retrieve_latents(self.vae.encode(img.unsqueeze(0)), generator, "argmax") for img in image]
|
545 |
+
|
546 |
+
image_latents = torch.cat(image_latents, dim=0).to(dtype) * self.vae_scaling_factor
|
547 |
+
image_latents = image_latents.repeat(1, 1, num_latent_frames, 1, 1)
|
548 |
+
|
549 |
+
if latents is None:
|
550 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
551 |
+
else:
|
552 |
+
latents = latents.to(device=device, dtype=dtype)
|
553 |
+
|
554 |
+
t = torch.tensor([0.999]).to(device=device)
|
555 |
+
latents = latents * t + image_latents * (1 - t)
|
556 |
+
|
557 |
+
if image_condition_type == "token_replace":
|
558 |
+
image_latents = image_latents[:, :, :1]
|
559 |
+
|
560 |
+
return latents, image_latents
|
561 |
+
|
562 |
+
def enable_vae_slicing(self):
|
563 |
+
r"""
|
564 |
+
Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
|
565 |
+
compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
|
566 |
+
"""
|
567 |
+
self.vae.enable_slicing()
|
568 |
+
|
569 |
+
def disable_vae_slicing(self):
|
570 |
+
r"""
|
571 |
+
Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
|
572 |
+
computing decoding in one step.
|
573 |
+
"""
|
574 |
+
self.vae.disable_slicing()
|
575 |
+
|
576 |
+
def enable_vae_tiling(self):
|
577 |
+
r"""
|
578 |
+
Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
|
579 |
+
compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
|
580 |
+
processing larger images.
|
581 |
+
"""
|
582 |
+
self.vae.enable_tiling()
|
583 |
+
|
584 |
+
def disable_vae_tiling(self):
|
585 |
+
r"""
|
586 |
+
Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
|
587 |
+
computing decoding in one step.
|
588 |
+
"""
|
589 |
+
self.vae.disable_tiling()
|
590 |
+
|
591 |
+
@property
|
592 |
+
def guidance_scale(self):
|
593 |
+
return self._guidance_scale
|
594 |
+
|
595 |
+
@property
|
596 |
+
def num_timesteps(self):
|
597 |
+
return self._num_timesteps
|
598 |
+
|
599 |
+
@property
|
600 |
+
def attention_kwargs(self):
|
601 |
+
return self._attention_kwargs
|
602 |
+
|
603 |
+
@property
|
604 |
+
def current_timestep(self):
|
605 |
+
return self._current_timestep
|
606 |
+
|
607 |
+
@property
|
608 |
+
def interrupt(self):
|
609 |
+
return self._interrupt
|
610 |
+
|
611 |
+
@torch.no_grad()
|
612 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
613 |
+
def __call__(
|
614 |
+
self,
|
615 |
+
image: PIL.Image.Image,
|
616 |
+
prompt: Union[str, List[str]] = None,
|
617 |
+
prompt_condition: Union[str, List[str], None] = None,
|
618 |
+
prompt_2: Union[str, List[str]] = None,
|
619 |
+
negative_prompt: Union[str, List[str]] = None,
|
620 |
+
negative_prompt_2: Union[str, List[str]] = None,
|
621 |
+
height: int = 720,
|
622 |
+
width: int = 1280,
|
623 |
+
num_frames: int = 129,
|
624 |
+
num_inference_steps: int = 50,
|
625 |
+
sigmas: List[float] = None,
|
626 |
+
true_cfg_scale: float = 1.0,
|
627 |
+
guidance_scale: float = 1.0,
|
628 |
+
num_videos_per_prompt: Optional[int] = 1,
|
629 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
630 |
+
latents: Optional[torch.Tensor] = None,
|
631 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
632 |
+
prompt_embeds_condition: Optional[torch.Tensor] = None,
|
633 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
634 |
+
prompt_attention_mask: Optional[torch.Tensor] = None,
|
635 |
+
prompt_attention_mask_condition: Optional[torch.Tensor] = None,
|
636 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
637 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
638 |
+
negative_prompt_attention_mask: Optional[torch.Tensor] = None,
|
639 |
+
output_type: Optional[str] = "pil",
|
640 |
+
return_dict: bool = True,
|
641 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
642 |
+
callback_on_step_end: Optional[
|
643 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
644 |
+
] = None,
|
645 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
646 |
+
prompt_template: Dict[str, Any] = DEFAULT_PROMPT_TEMPLATE,
|
647 |
+
max_sequence_length: int = 256,
|
648 |
+
image_embed_interleave: Optional[int] = None,
|
649 |
+
frame_gap: Union[int, None] = None,
|
650 |
+
mixup: bool = False,
|
651 |
+
mixup_num_imgs: Union[int, None] = None,
|
652 |
+
):
|
653 |
+
r"""
|
654 |
+
The call function to the pipeline for generation.
|
655 |
+
|
656 |
+
Args:
|
657 |
+
prompt (`str` or `List[str]`, *optional*):
|
658 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
659 |
+
instead.
|
660 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
661 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
662 |
+
will be used instead.
|
663 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
664 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
665 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `true_cfg_scale` is
|
666 |
+
not greater than `1`).
|
667 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
668 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
669 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in all the text-encoders.
|
670 |
+
height (`int`, defaults to `720`):
|
671 |
+
The height in pixels of the generated image.
|
672 |
+
width (`int`, defaults to `1280`):
|
673 |
+
The width in pixels of the generated image.
|
674 |
+
num_frames (`int`, defaults to `129`):
|
675 |
+
The number of frames in the generated video.
|
676 |
+
num_inference_steps (`int`, defaults to `50`):
|
677 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
678 |
+
expense of slower inference.
|
679 |
+
sigmas (`List[float]`, *optional*):
|
680 |
+
Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
|
681 |
+
their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
|
682 |
+
will be used.
|
683 |
+
true_cfg_scale (`float`, *optional*, defaults to 1.0):
|
684 |
+
When > 1.0 and a provided `negative_prompt`, enables true classifier-free guidance.
|
685 |
+
guidance_scale (`float`, defaults to `1.0`):
|
686 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
687 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
688 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
689 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
690 |
+
usually at the expense of lower image quality. Note that the only available HunyuanVideo model is
|
691 |
+
CFG-distilled, which means that traditional guidance between unconditional and conditional latent is
|
692 |
+
not applied.
|
693 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
694 |
+
The number of images to generate per prompt.
|
695 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
696 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
697 |
+
generation deterministic.
|
698 |
+
latents (`torch.Tensor`, *optional*):
|
699 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
700 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
701 |
+
tensor is generated by sampling using the supplied random `generator`.
|
702 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
703 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
704 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
705 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
706 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
707 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
708 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
709 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
710 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
711 |
+
argument.
|
712 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
713 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
714 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
715 |
+
input argument.
|
716 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
717 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
718 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
719 |
+
Whether or not to return a [`HunyuanVideoPipelineOutput`] instead of a plain tuple.
|
720 |
+
attention_kwargs (`dict`, *optional*):
|
721 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
722 |
+
`self.processor` in
|
723 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
724 |
+
clip_skip (`int`, *optional*):
|
725 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
726 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
727 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
728 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
729 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
730 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
731 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
732 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
733 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
734 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
735 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
736 |
+
|
737 |
+
Examples:
|
738 |
+
|
739 |
+
Returns:
|
740 |
+
[`~HunyuanVideoPipelineOutput`] or `tuple`:
|
741 |
+
If `return_dict` is `True`, [`HunyuanVideoPipelineOutput`] is returned, otherwise a `tuple` is returned
|
742 |
+
where the first element is a list with the generated images and the second element is a list of `bool`s
|
743 |
+
indicating whether the corresponding generated image contains "not-safe-for-work" (nsfw) content.
|
744 |
+
"""
|
745 |
+
|
746 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
747 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
748 |
+
|
749 |
+
# 1. Check inputs. Raise error if not correct
|
750 |
+
self.check_inputs(
|
751 |
+
prompt,
|
752 |
+
prompt_2,
|
753 |
+
height,
|
754 |
+
width,
|
755 |
+
prompt_embeds,
|
756 |
+
callback_on_step_end_tensor_inputs,
|
757 |
+
prompt_template,
|
758 |
+
true_cfg_scale,
|
759 |
+
guidance_scale,
|
760 |
+
)
|
761 |
+
|
762 |
+
image_condition_type = self.transformer.config.image_condition_type
|
763 |
+
has_neg_prompt = negative_prompt is not None or (
|
764 |
+
negative_prompt_embeds is not None and negative_pooled_prompt_embeds is not None
|
765 |
+
)
|
766 |
+
do_true_cfg = true_cfg_scale > 1 and has_neg_prompt
|
767 |
+
image_embed_interleave = (
|
768 |
+
image_embed_interleave
|
769 |
+
if image_embed_interleave is not None
|
770 |
+
else (
|
771 |
+
2 if image_condition_type == "latent_concat" else 4 if image_condition_type == "token_replace" else 1
|
772 |
+
)
|
773 |
+
)
|
774 |
+
|
775 |
+
self._guidance_scale = guidance_scale
|
776 |
+
self._attention_kwargs = attention_kwargs
|
777 |
+
self._current_timestep = None
|
778 |
+
self._interrupt = False
|
779 |
+
|
780 |
+
device = self._execution_device
|
781 |
+
|
782 |
+
# 2. Define call parameters
|
783 |
+
if prompt is not None and isinstance(prompt, str):
|
784 |
+
batch_size = 1
|
785 |
+
elif prompt is not None and isinstance(prompt, list):
|
786 |
+
batch_size = len(prompt)
|
787 |
+
else:
|
788 |
+
batch_size = prompt_embeds.shape[0]
|
789 |
+
|
790 |
+
# 3. Prepare latent variables
|
791 |
+
vae_dtype = self.vae.dtype
|
792 |
+
image_tensor = self.video_processor.preprocess(image, height, width).to(device, vae_dtype)
|
793 |
+
|
794 |
+
if image_condition_type == "latent_concat":
|
795 |
+
num_channels_latents = (self.transformer.config.in_channels - 1) // 2
|
796 |
+
elif image_condition_type == "token_replace":
|
797 |
+
num_channels_latents = self.transformer.config.in_channels
|
798 |
+
|
799 |
+
latents, image_latents = self.prepare_latents(
|
800 |
+
image_tensor,
|
801 |
+
batch_size * num_videos_per_prompt,
|
802 |
+
num_channels_latents,
|
803 |
+
height,
|
804 |
+
width,
|
805 |
+
num_frames if not mixup else num_frames + 4 * mixup_num_imgs,
|
806 |
+
torch.float32,
|
807 |
+
device,
|
808 |
+
generator,
|
809 |
+
latents,
|
810 |
+
image_condition_type,
|
811 |
+
)
|
812 |
+
if image_condition_type == "latent_concat":
|
813 |
+
image_latents[:, :, 1:] = 0
|
814 |
+
mask = image_latents.new_ones(image_latents.shape[0], 1, *image_latents.shape[2:])
|
815 |
+
mask[:, :, 1:] = 0
|
816 |
+
|
817 |
+
# 4. Encode input prompt
|
818 |
+
transformer_dtype = self.transformer.dtype
|
819 |
+
(prompt_embeds,
|
820 |
+
prompt_embeds_condition,
|
821 |
+
pooled_prompt_embeds,
|
822 |
+
prompt_attention_mask,
|
823 |
+
prompt_attention_mask_condition) = self.encode_prompt(
|
824 |
+
image=image,
|
825 |
+
prompt=prompt,
|
826 |
+
prompt_condition=prompt_condition,
|
827 |
+
prompt_2=prompt_2,
|
828 |
+
prompt_template=prompt_template,
|
829 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
830 |
+
prompt_embeds=prompt_embeds,
|
831 |
+
prompt_embeds_condition=prompt_embeds_condition,
|
832 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
833 |
+
prompt_attention_mask=prompt_attention_mask,
|
834 |
+
prompt_attention_mask_condition=prompt_attention_mask_condition,
|
835 |
+
device=device,
|
836 |
+
max_sequence_length=max_sequence_length,
|
837 |
+
image_embed_interleave=image_embed_interleave,
|
838 |
+
)
|
839 |
+
prompt_embeds = prompt_embeds.to(transformer_dtype)
|
840 |
+
prompt_attention_mask = prompt_attention_mask.to(transformer_dtype)
|
841 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(transformer_dtype)
|
842 |
+
|
843 |
+
if do_true_cfg:
|
844 |
+
black_image = PIL.Image.new("RGB", (width, height), 0)
|
845 |
+
negative_prompt_embeds, negative_pooled_prompt_embeds, negative_prompt_attention_mask = self.encode_prompt(
|
846 |
+
image=black_image,
|
847 |
+
prompt=negative_prompt,
|
848 |
+
prompt_2=negative_prompt_2,
|
849 |
+
prompt_template=prompt_template,
|
850 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
851 |
+
prompt_embeds=negative_prompt_embeds,
|
852 |
+
pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
853 |
+
prompt_attention_mask=negative_prompt_attention_mask,
|
854 |
+
device=device,
|
855 |
+
max_sequence_length=max_sequence_length,
|
856 |
+
)
|
857 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
858 |
+
negative_prompt_attention_mask = negative_prompt_attention_mask.to(transformer_dtype)
|
859 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.to(transformer_dtype)
|
860 |
+
|
861 |
+
# 5. Prepare timesteps
|
862 |
+
sigmas = np.linspace(1.0, 0.0, num_inference_steps + 1)[:-1] if sigmas is None else sigmas
|
863 |
+
timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, sigmas=sigmas)
|
864 |
+
|
865 |
+
# 6. Prepare guidance condition
|
866 |
+
guidance = None
|
867 |
+
if self.transformer.config.guidance_embeds:
|
868 |
+
guidance = (
|
869 |
+
torch.tensor([guidance_scale] * latents.shape[0], dtype=transformer_dtype, device=device) * 1000.0
|
870 |
+
)
|
871 |
+
|
872 |
+
# 7. Denoising loop
|
873 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
874 |
+
self._num_timesteps = len(timesteps)
|
875 |
+
|
876 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
877 |
+
for i, t in enumerate(timesteps):
|
878 |
+
if self.interrupt:
|
879 |
+
continue
|
880 |
+
|
881 |
+
self._current_timestep = t
|
882 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
883 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
884 |
+
|
885 |
+
if image_condition_type == "latent_concat":
|
886 |
+
latent_model_input = torch.cat([latents, image_latents, mask], dim=1).to(transformer_dtype)
|
887 |
+
elif image_condition_type == "token_replace":
|
888 |
+
latent_model_input = torch.cat([image_latents, latents[:, :, 1:]], dim=2).to(transformer_dtype)
|
889 |
+
|
890 |
+
noise_pred = self.transformer(
|
891 |
+
hidden_states=latent_model_input,
|
892 |
+
timestep=timestep,
|
893 |
+
encoder_hidden_states=prompt_embeds,
|
894 |
+
encoder_hidden_states_condition=prompt_embeds_condition,
|
895 |
+
encoder_attention_mask=prompt_attention_mask,
|
896 |
+
encoder_attention_mask_condition=prompt_attention_mask_condition,
|
897 |
+
pooled_projections=pooled_prompt_embeds,
|
898 |
+
guidance=guidance,
|
899 |
+
attention_kwargs=attention_kwargs,
|
900 |
+
return_dict=False,
|
901 |
+
frame_gap=int(frame_gap / 4) if frame_gap is not None else frame_gap,
|
902 |
+
)[0]
|
903 |
+
|
904 |
+
if do_true_cfg:
|
905 |
+
neg_noise_pred = self.transformer(
|
906 |
+
hidden_states=latent_model_input,
|
907 |
+
timestep=timestep,
|
908 |
+
encoder_hidden_states=negative_prompt_embeds,
|
909 |
+
encoder_attention_mask=negative_prompt_attention_mask,
|
910 |
+
pooled_projections=negative_pooled_prompt_embeds,
|
911 |
+
guidance=guidance,
|
912 |
+
attention_kwargs=attention_kwargs,
|
913 |
+
return_dict=False,
|
914 |
+
)[0]
|
915 |
+
noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)
|
916 |
+
|
917 |
+
# compute the previous noisy sample x_t -> x_t-1
|
918 |
+
if image_condition_type == "latent_concat":
|
919 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
920 |
+
elif image_condition_type == "token_replace":
|
921 |
+
latents = latents = self.scheduler.step(
|
922 |
+
noise_pred[:, :, 1:], t, latents[:, :, 1:], return_dict=False
|
923 |
+
)[0]
|
924 |
+
latents = torch.cat([image_latents, latents], dim=2)
|
925 |
+
|
926 |
+
if callback_on_step_end is not None:
|
927 |
+
callback_kwargs = {}
|
928 |
+
for k in callback_on_step_end_tensor_inputs:
|
929 |
+
callback_kwargs[k] = locals()[k]
|
930 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
931 |
+
|
932 |
+
latents = callback_outputs.pop("latents", latents)
|
933 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
934 |
+
|
935 |
+
# call the callback, if provided
|
936 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
937 |
+
progress_bar.update()
|
938 |
+
|
939 |
+
if XLA_AVAILABLE:
|
940 |
+
xm.mark_step()
|
941 |
+
|
942 |
+
self._current_timestep = None
|
943 |
+
|
944 |
+
if not mixup:
|
945 |
+
generated_img_frame_start = image_latents.shape[2]
|
946 |
+
latents = latents[:, :, generated_img_frame_start:]
|
947 |
+
if not output_type == "latent":
|
948 |
+
latents = latents.to(self.vae.dtype) / self.vae_scaling_factor
|
949 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
950 |
+
if image_condition_type == "latent_concat":
|
951 |
+
video = video[:, :, 4:, :, :]
|
952 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
953 |
+
if mixup:
|
954 |
+
single_generated_decoded = self.vae.decode(latents[:, :, -1:], return_dict=False)[0]
|
955 |
+
single_generated_decoded = self.video_processor.postprocess_video(single_generated_decoded, output_type=output_type)
|
956 |
+
video = torch.cat([single_generated_decoded, video], dim=1)
|
957 |
+
else:
|
958 |
+
if image_condition_type == "latent_concat":
|
959 |
+
video = latents[:, :, 1:, :, :]
|
960 |
+
else:
|
961 |
+
video = latents
|
962 |
+
|
963 |
+
# Offload all models
|
964 |
+
self.maybe_free_model_hooks()
|
965 |
+
|
966 |
+
if not return_dict:
|
967 |
+
return (video,)
|
968 |
+
|
969 |
+
return HunyuanVideoPipelineOutput(frames=video)
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch==2.4.1
|
2 |
+
torchvision==0.19.1
|
3 |
+
diffusers==0.33.1
|
4 |
+
transformers==4.45.0
|
5 |
+
flash-attn==2.7.3
|
6 |
+
gradio
|
7 |
+
omegaconf
|
8 |
+
peft
|
9 |
+
opencv-python
|