Delete telestylevideo_transformer.py
Browse files- telestylevideo_transformer.py +0 -546
telestylevideo_transformer.py
DELETED
|
@@ -1,546 +0,0 @@
|
|
| 1 |
-
# Copyright 2025 The Wan 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 |
-
|
| 15 |
-
import math
|
| 16 |
-
from typing import Any, Dict, Optional, Tuple, Union
|
| 17 |
-
|
| 18 |
-
import torch
|
| 19 |
-
import torch.nn as nn
|
| 20 |
-
import torch.nn.functional as F
|
| 21 |
-
|
| 22 |
-
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 23 |
-
from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
|
| 24 |
-
from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
|
| 25 |
-
from diffusers.models.attention import FeedForward
|
| 26 |
-
from diffusers.models.attention_processor import Attention
|
| 27 |
-
from diffusers.models.cache_utils import CacheMixin
|
| 28 |
-
from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
|
| 29 |
-
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
| 30 |
-
from diffusers.models.modeling_utils import ModelMixin
|
| 31 |
-
from diffusers.models.normalization import FP32LayerNorm
|
| 32 |
-
|
| 33 |
-
logger = logging.get_logger(__name__)
|
| 34 |
-
|
| 35 |
-
class WanAttnProcessor2_0:
|
| 36 |
-
"""
|
| 37 |
-
Wan 注意力处理器,使用 PyTorch 2.0 的 scaled_dot_product_attention
|
| 38 |
-
"""
|
| 39 |
-
def __init__(self):
|
| 40 |
-
if not hasattr(F, "scaled_dot_product_attention"):
|
| 41 |
-
raise ImportError("WanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
|
| 42 |
-
|
| 43 |
-
def __call__(
|
| 44 |
-
self,
|
| 45 |
-
attn: Attention,
|
| 46 |
-
hidden_states: torch.Tensor,
|
| 47 |
-
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 48 |
-
attention_mask: Optional[torch.Tensor] = None,
|
| 49 |
-
rotary_emb: Optional[torch.Tensor] = None,
|
| 50 |
-
) -> torch.Tensor:
|
| 51 |
-
"""
|
| 52 |
-
执行注意力计算
|
| 53 |
-
|
| 54 |
-
Args:
|
| 55 |
-
attn: Attention 模块
|
| 56 |
-
hidden_states: 隐藏状态张量
|
| 57 |
-
encoder_hidden_states: 编码器隐藏状态张量
|
| 58 |
-
attention_mask: 注意力掩码
|
| 59 |
-
rotary_emb: 旋转位置编码
|
| 60 |
-
|
| 61 |
-
Returns:
|
| 62 |
-
注意力计算后的隐藏状态
|
| 63 |
-
"""
|
| 64 |
-
if encoder_hidden_states is None:
|
| 65 |
-
encoder_hidden_states = hidden_states
|
| 66 |
-
|
| 67 |
-
query = attn.to_q(hidden_states)
|
| 68 |
-
key = attn.to_k(encoder_hidden_states)
|
| 69 |
-
value = attn.to_v(encoder_hidden_states)
|
| 70 |
-
|
| 71 |
-
if attn.norm_q is not None:
|
| 72 |
-
query = attn.norm_q(query)
|
| 73 |
-
if attn.norm_k is not None:
|
| 74 |
-
key = attn.norm_k(key)
|
| 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 |
-
if rotary_emb is not None:
|
| 81 |
-
def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
|
| 82 |
-
"""应用旋转位置编码"""
|
| 83 |
-
x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
|
| 84 |
-
x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
|
| 85 |
-
return x_out.type_as(hidden_states)
|
| 86 |
-
|
| 87 |
-
query = apply_rotary_emb(query, rotary_emb)
|
| 88 |
-
key = apply_rotary_emb(key, rotary_emb)
|
| 89 |
-
|
| 90 |
-
hidden_states = F.scaled_dot_product_attention(
|
| 91 |
-
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
| 92 |
-
)
|
| 93 |
-
hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
|
| 94 |
-
hidden_states = hidden_states.type_as(query)
|
| 95 |
-
|
| 96 |
-
hidden_states = attn.to_out[0](hidden_states)
|
| 97 |
-
hidden_states = attn.to_out[1](hidden_states)
|
| 98 |
-
return hidden_states
|
| 99 |
-
|
| 100 |
-
class WanImageEmbedding(nn.Module):
|
| 101 |
-
"""
|
| 102 |
-
Wan 图像嵌入模块
|
| 103 |
-
"""
|
| 104 |
-
def __init__(self, image_embed_dim: int, dim: int):
|
| 105 |
-
"""
|
| 106 |
-
初始化图像嵌入模块
|
| 107 |
-
|
| 108 |
-
Args:
|
| 109 |
-
image_embed_dim: 输入图像嵌入维度
|
| 110 |
-
dim: 输出嵌入维度
|
| 111 |
-
"""
|
| 112 |
-
super().__init__()
|
| 113 |
-
self.proj = nn.Linear(image_embed_dim, dim)
|
| 114 |
-
self.act_fn = nn.SiLU()
|
| 115 |
-
|
| 116 |
-
def forward(self, image_embeds: torch.Tensor) -> torch.Tensor:
|
| 117 |
-
"""
|
| 118 |
-
前向传播
|
| 119 |
-
|
| 120 |
-
Args:
|
| 121 |
-
image_embeds: 图像嵌入张量
|
| 122 |
-
|
| 123 |
-
Returns:
|
| 124 |
-
处理后的嵌入张量
|
| 125 |
-
"""
|
| 126 |
-
return self.proj(self.act_fn(image_embeds))
|
| 127 |
-
|
| 128 |
-
class WanTimeTextImageEmbedding(nn.Module):
|
| 129 |
-
"""
|
| 130 |
-
Wan 时间、文本和图像嵌入模块
|
| 131 |
-
"""
|
| 132 |
-
def __init__(
|
| 133 |
-
self,
|
| 134 |
-
dim: int,
|
| 135 |
-
time_freq_dim: int,
|
| 136 |
-
time_proj_dim: int,
|
| 137 |
-
text_embed_dim: int,
|
| 138 |
-
image_embed_dim: Optional[int] = None,
|
| 139 |
-
):
|
| 140 |
-
"""
|
| 141 |
-
初始化嵌入模块
|
| 142 |
-
|
| 143 |
-
Args:
|
| 144 |
-
dim: 嵌入维度
|
| 145 |
-
time_freq_dim: 时间频率维度
|
| 146 |
-
time_proj_dim: 时间投影维度
|
| 147 |
-
text_embed_dim: 文本嵌入维度
|
| 148 |
-
image_embed_dim: 图像嵌入维度
|
| 149 |
-
"""
|
| 150 |
-
super().__init__()
|
| 151 |
-
|
| 152 |
-
self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
|
| 153 |
-
self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
|
| 154 |
-
self.act_fn = nn.SiLU()
|
| 155 |
-
self.time_proj = nn.Linear(dim, time_proj_dim)
|
| 156 |
-
self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
|
| 157 |
-
|
| 158 |
-
self.image_embedder = None
|
| 159 |
-
if image_embed_dim is not None:
|
| 160 |
-
self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
|
| 161 |
-
|
| 162 |
-
def forward(
|
| 163 |
-
self,
|
| 164 |
-
condition_timestep: torch.Tensor,
|
| 165 |
-
timestep: torch.Tensor,
|
| 166 |
-
encoder_hidden_states: torch.Tensor
|
| 167 |
-
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 168 |
-
"""
|
| 169 |
-
前向传播
|
| 170 |
-
|
| 171 |
-
Args:
|
| 172 |
-
condition_timestep: 条件时间步张量
|
| 173 |
-
timestep: 时间步张量
|
| 174 |
-
encoder_hidden_states: 编码器隐藏状态张量
|
| 175 |
-
|
| 176 |
-
Returns:
|
| 177 |
-
时间嵌入、条件时间步投影、时间步投影和处理后的编码器隐藏状态
|
| 178 |
-
"""
|
| 179 |
-
condition_timestep = self.timesteps_proj(condition_timestep)
|
| 180 |
-
timestep = self.timesteps_proj(timestep)
|
| 181 |
-
|
| 182 |
-
time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
|
| 183 |
-
if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
|
| 184 |
-
condition_timestep = condition_timestep.to(time_embedder_dtype)
|
| 185 |
-
timestep = timestep.to(time_embedder_dtype)
|
| 186 |
-
|
| 187 |
-
condition_temb = self.time_embedder(condition_timestep).type_as(encoder_hidden_states)
|
| 188 |
-
condition_timestep_proj = self.time_proj(self.act_fn(condition_temb))
|
| 189 |
-
|
| 190 |
-
temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
|
| 191 |
-
timestep_proj = self.time_proj(self.act_fn(temb))
|
| 192 |
-
|
| 193 |
-
encoder_hidden_states = self.text_embedder(encoder_hidden_states)
|
| 194 |
-
|
| 195 |
-
return temb, condition_timestep_proj, timestep_proj, encoder_hidden_states
|
| 196 |
-
|
| 197 |
-
class WanRotaryPosEmbed(nn.Module):
|
| 198 |
-
"""
|
| 199 |
-
Wan 旋转位置编码模块
|
| 200 |
-
"""
|
| 201 |
-
def __init__(
|
| 202 |
-
self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
|
| 203 |
-
):
|
| 204 |
-
"""
|
| 205 |
-
初始化旋转位置编码模块
|
| 206 |
-
|
| 207 |
-
Args:
|
| 208 |
-
attention_head_dim: 注意力头维度
|
| 209 |
-
patch_size: 补丁大小 (time, height, width)
|
| 210 |
-
max_seq_len: 最大序列长度
|
| 211 |
-
theta: 旋转编码参数
|
| 212 |
-
"""
|
| 213 |
-
super().__init__()
|
| 214 |
-
|
| 215 |
-
self.attention_head_dim = attention_head_dim
|
| 216 |
-
self.patch_size = patch_size
|
| 217 |
-
self.max_seq_len = max_seq_len
|
| 218 |
-
|
| 219 |
-
h_dim = w_dim = 2 * (attention_head_dim // 6)
|
| 220 |
-
t_dim = attention_head_dim - h_dim - w_dim
|
| 221 |
-
|
| 222 |
-
freqs = []
|
| 223 |
-
for dim in [t_dim, h_dim, w_dim]:
|
| 224 |
-
freq = get_1d_rotary_pos_embed(
|
| 225 |
-
dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
|
| 226 |
-
)
|
| 227 |
-
freqs.append(freq)
|
| 228 |
-
self.freqs = torch.cat(freqs, dim=1)
|
| 229 |
-
|
| 230 |
-
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 231 |
-
"""
|
| 232 |
-
前向传播
|
| 233 |
-
|
| 234 |
-
Args:
|
| 235 |
-
hidden_states: 隐藏状态张量
|
| 236 |
-
|
| 237 |
-
Returns:
|
| 238 |
-
旋转位置编码张量
|
| 239 |
-
"""
|
| 240 |
-
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
| 241 |
-
p_t, p_h, p_w = self.patch_size
|
| 242 |
-
ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
|
| 243 |
-
|
| 244 |
-
self.freqs = self.freqs.to(hidden_states.device)
|
| 245 |
-
freqs = self.freqs.split_with_sizes(
|
| 246 |
-
[
|
| 247 |
-
self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
|
| 248 |
-
self.attention_head_dim // 6,
|
| 249 |
-
self.attention_head_dim // 6,
|
| 250 |
-
],
|
| 251 |
-
dim=1,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
|
| 255 |
-
freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
|
| 256 |
-
freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
|
| 257 |
-
freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
|
| 258 |
-
return freqs
|
| 259 |
-
|
| 260 |
-
class WanTransformerBlock(nn.Module):
|
| 261 |
-
"""
|
| 262 |
-
Wan Transformer 块
|
| 263 |
-
"""
|
| 264 |
-
def __init__(
|
| 265 |
-
self,
|
| 266 |
-
dim: int,
|
| 267 |
-
ffn_dim: int,
|
| 268 |
-
num_heads: int,
|
| 269 |
-
qk_norm: str = "rms_norm_across_heads",
|
| 270 |
-
cross_attn_norm: bool = False,
|
| 271 |
-
eps: float = 1e-6,
|
| 272 |
-
added_kv_proj_dim: Optional[int] = None,
|
| 273 |
-
):
|
| 274 |
-
"""
|
| 275 |
-
初始化 Transformer 块
|
| 276 |
-
|
| 277 |
-
Args:
|
| 278 |
-
dim: 隐藏状态维度
|
| 279 |
-
ffn_dim: 前馈网络维度
|
| 280 |
-
num_heads: 注意力头数量
|
| 281 |
-
qk_norm: QK 归一化方式
|
| 282 |
-
cross_attn_norm: 是否使用交叉注意力归一化
|
| 283 |
-
eps: 归一化 epsilon
|
| 284 |
-
added_kv_proj_dim: 额外的 KV 投影维度
|
| 285 |
-
"""
|
| 286 |
-
super().__init__()
|
| 287 |
-
|
| 288 |
-
# 1. Self-attention
|
| 289 |
-
self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 290 |
-
self.attn1 = Attention(
|
| 291 |
-
query_dim=dim,
|
| 292 |
-
heads=num_heads,
|
| 293 |
-
kv_heads=num_heads,
|
| 294 |
-
dim_head=dim // num_heads,
|
| 295 |
-
qk_norm=qk_norm,
|
| 296 |
-
eps=eps,
|
| 297 |
-
bias=True,
|
| 298 |
-
cross_attention_dim=None,
|
| 299 |
-
out_bias=True,
|
| 300 |
-
processor=WanAttnProcessor2_0(),
|
| 301 |
-
)
|
| 302 |
-
|
| 303 |
-
# 2. Cross-attention
|
| 304 |
-
self.attn2 = Attention(
|
| 305 |
-
query_dim=dim,
|
| 306 |
-
heads=num_heads,
|
| 307 |
-
kv_heads=num_heads,
|
| 308 |
-
dim_head=dim // num_heads,
|
| 309 |
-
qk_norm=qk_norm,
|
| 310 |
-
eps=eps,
|
| 311 |
-
bias=True,
|
| 312 |
-
cross_attention_dim=None,
|
| 313 |
-
out_bias=True,
|
| 314 |
-
added_kv_proj_dim=added_kv_proj_dim,
|
| 315 |
-
added_proj_bias=True,
|
| 316 |
-
processor=WanAttnProcessor2_0(),
|
| 317 |
-
)
|
| 318 |
-
self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
|
| 319 |
-
|
| 320 |
-
# 3. Feed-forward
|
| 321 |
-
self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
|
| 322 |
-
self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
|
| 323 |
-
|
| 324 |
-
self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
|
| 325 |
-
|
| 326 |
-
def forward(
|
| 327 |
-
self,
|
| 328 |
-
condition_hidden_states: torch.Tensor,
|
| 329 |
-
hidden_states: torch.Tensor,
|
| 330 |
-
encoder_hidden_states: torch.Tensor,
|
| 331 |
-
condition_temb: torch.Tensor,
|
| 332 |
-
temb: torch.Tensor,
|
| 333 |
-
rotary_emb: torch.Tensor,
|
| 334 |
-
condition_cross_attention: bool
|
| 335 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 336 |
-
"""
|
| 337 |
-
前向传播
|
| 338 |
-
|
| 339 |
-
Args:
|
| 340 |
-
condition_hidden_states: 条件隐藏状态张量
|
| 341 |
-
hidden_states: 隐藏状态张量
|
| 342 |
-
encoder_hidden_states: 编码器隐藏状态张量
|
| 343 |
-
condition_temb: 条件时间嵌入张量
|
| 344 |
-
temb: 时间嵌入张量
|
| 345 |
-
rotary_emb: 旋转位置编码张量
|
| 346 |
-
condition_cross_attention: 是否使用条件交叉注意力
|
| 347 |
-
|
| 348 |
-
Returns:
|
| 349 |
-
处理后的条件隐藏状态和隐藏状态张量
|
| 350 |
-
"""
|
| 351 |
-
condition_shift_msa, condition_scale_msa, condition_gate_msa, condition_c_shift_msa, condition_c_scale_msa, condition_c_gate_msa = (
|
| 352 |
-
self.scale_shift_table + condition_temb.float()
|
| 353 |
-
).chunk(6, dim=1)
|
| 354 |
-
|
| 355 |
-
shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
|
| 356 |
-
self.scale_shift_table + temb.float()
|
| 357 |
-
).chunk(6, dim=1)
|
| 358 |
-
|
| 359 |
-
# 1. Self-attention
|
| 360 |
-
condition_norm_hidden_states = (self.norm1(condition_hidden_states.float()) * (1 + condition_scale_msa) + condition_shift_msa).type_as(hidden_states)
|
| 361 |
-
norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
|
| 362 |
-
f = condition_norm_hidden_states.shape[1]
|
| 363 |
-
norm_hidden_states_ = torch.cat([condition_norm_hidden_states, norm_hidden_states], dim=1)
|
| 364 |
-
attn_output = self.attn1(hidden_states=norm_hidden_states_, rotary_emb=rotary_emb)
|
| 365 |
-
|
| 366 |
-
condition_attn_output = attn_output[:,:f]
|
| 367 |
-
attn_output = attn_output[:,f:]
|
| 368 |
-
condition_hidden_states = (condition_hidden_states.float() + condition_attn_output * condition_gate_msa).type_as(hidden_states)
|
| 369 |
-
hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
|
| 370 |
-
|
| 371 |
-
# 2. Cross-attention
|
| 372 |
-
if condition_cross_attention:
|
| 373 |
-
condition_norm_hidden_states = self.norm2(condition_hidden_states.float()).type_as(hidden_states)
|
| 374 |
-
condition_attn_output = self.attn2(hidden_states=condition_norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
|
| 375 |
-
condition_hidden_states = condition_hidden_states + condition_attn_output
|
| 376 |
-
|
| 377 |
-
norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
|
| 378 |
-
attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
|
| 379 |
-
hidden_states = hidden_states + attn_output
|
| 380 |
-
|
| 381 |
-
# 3. Feed-forward
|
| 382 |
-
condition_norm_hidden_states = (self.norm3(condition_hidden_states.float()) * (1 + condition_c_scale_msa) + condition_c_shift_msa).type_as(
|
| 383 |
-
condition_hidden_states
|
| 384 |
-
)
|
| 385 |
-
condition_ff_output = self.ffn(condition_norm_hidden_states)
|
| 386 |
-
condition_hidden_states = (condition_hidden_states.float() + condition_ff_output.float() * condition_c_gate_msa).type_as(hidden_states)
|
| 387 |
-
|
| 388 |
-
norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
|
| 389 |
-
hidden_states
|
| 390 |
-
)
|
| 391 |
-
ff_output = self.ffn(norm_hidden_states)
|
| 392 |
-
hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
|
| 393 |
-
|
| 394 |
-
return condition_hidden_states, hidden_states
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin):
|
| 398 |
-
"""
|
| 399 |
-
Wan Transformer 3D 模型
|
| 400 |
-
"""
|
| 401 |
-
|
| 402 |
-
_supports_gradient_checkpointing = True
|
| 403 |
-
_skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
|
| 404 |
-
_no_split_modules = ["WanTransformerBlock"]
|
| 405 |
-
_keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
|
| 406 |
-
_keys_to_ignore_on_load_unexpected = ["norm_added_q"]
|
| 407 |
-
|
| 408 |
-
@register_to_config
|
| 409 |
-
def __init__(
|
| 410 |
-
self,
|
| 411 |
-
patch_size: Tuple[int] = (1, 2, 2),
|
| 412 |
-
num_attention_heads: int = 40,
|
| 413 |
-
attention_head_dim: int = 128,
|
| 414 |
-
in_channels: int = 16,
|
| 415 |
-
out_channels: int = 16,
|
| 416 |
-
text_dim: int = 4096,
|
| 417 |
-
freq_dim: int = 256,
|
| 418 |
-
ffn_dim: int = 13824,
|
| 419 |
-
num_layers: int = 40,
|
| 420 |
-
cross_attn_norm: bool = True,
|
| 421 |
-
qk_norm: Optional[str] = "rms_norm_across_heads",
|
| 422 |
-
eps: float = 1e-6,
|
| 423 |
-
image_dim: Optional[int] = None,
|
| 424 |
-
added_kv_proj_dim: Optional[int] = None,
|
| 425 |
-
rope_max_seq_len: int = 1024,
|
| 426 |
-
) -> None:
|
| 427 |
-
"""
|
| 428 |
-
初始化 Transformer 3D 模型
|
| 429 |
-
|
| 430 |
-
Args:
|
| 431 |
-
patch_size: 补丁大小 (time, height, width)
|
| 432 |
-
num_attention_heads: 注意力头数量
|
| 433 |
-
attention_head_dim: 注意力头维度
|
| 434 |
-
in_channels: 输入通道数
|
| 435 |
-
out_channels: 输出通道数
|
| 436 |
-
text_dim: 文本嵌入维度
|
| 437 |
-
freq_dim: 频率维度
|
| 438 |
-
ffn_dim: 前馈网络维度
|
| 439 |
-
num_layers: 模型层数
|
| 440 |
-
cross_attn_norm: 是否使用交叉注意力归一化
|
| 441 |
-
qk_norm: QK 归一化方式
|
| 442 |
-
eps: 归一化 epsilon
|
| 443 |
-
image_dim: 图像嵌入维度
|
| 444 |
-
added_kv_proj_dim: 额外的 KV 投影维度
|
| 445 |
-
rope_max_seq_len: RoPE 最大序列长度
|
| 446 |
-
"""
|
| 447 |
-
super().__init__()
|
| 448 |
-
|
| 449 |
-
inner_dim = num_attention_heads * attention_head_dim
|
| 450 |
-
out_channels = out_channels or in_channels
|
| 451 |
-
|
| 452 |
-
# 1. Patch & position embedding
|
| 453 |
-
self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
|
| 454 |
-
self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 455 |
-
self.patch_embedding2 = nn.Conv3d(2*in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
|
| 456 |
-
|
| 457 |
-
# 2. Condition embeddings
|
| 458 |
-
# image_embedding_dim=1280 for I2V model
|
| 459 |
-
self.condition_embedder = WanTimeTextImageEmbedding(
|
| 460 |
-
dim=inner_dim,
|
| 461 |
-
time_freq_dim=freq_dim,
|
| 462 |
-
time_proj_dim=inner_dim * 6,
|
| 463 |
-
text_embed_dim=text_dim,
|
| 464 |
-
image_embed_dim=image_dim,
|
| 465 |
-
)
|
| 466 |
-
|
| 467 |
-
# 3. Transformer blocks
|
| 468 |
-
self.blocks = nn.ModuleList(
|
| 469 |
-
[
|
| 470 |
-
WanTransformerBlock(
|
| 471 |
-
inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
|
| 472 |
-
)
|
| 473 |
-
for _ in range(num_layers)
|
| 474 |
-
]
|
| 475 |
-
)
|
| 476 |
-
|
| 477 |
-
# 4. Output norm & projection
|
| 478 |
-
self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
|
| 479 |
-
self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
|
| 480 |
-
self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
|
| 481 |
-
|
| 482 |
-
self.gradient_checkpointing = False
|
| 483 |
-
|
| 484 |
-
def forward(
|
| 485 |
-
self,
|
| 486 |
-
condition_hidden_states: torch.Tensor,
|
| 487 |
-
hidden_states: torch.Tensor,
|
| 488 |
-
condition_timestep: torch.LongTensor,
|
| 489 |
-
timestep: torch.LongTensor,
|
| 490 |
-
encoder_hidden_states: torch.Tensor,
|
| 491 |
-
encoder_hidden_states_image: Optional[torch.Tensor] = None,
|
| 492 |
-
return_dict: bool = True,
|
| 493 |
-
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 494 |
-
condition_cross_attention: bool = False
|
| 495 |
-
) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
|
| 496 |
-
|
| 497 |
-
batch_size, num_channels, num_frames, height, width = hidden_states.shape
|
| 498 |
-
p_t, p_h, p_w = self.config.patch_size
|
| 499 |
-
post_patch_num_frames = num_frames // p_t
|
| 500 |
-
post_patch_height = height // p_h
|
| 501 |
-
post_patch_width = width // p_w
|
| 502 |
-
|
| 503 |
-
f = hidden_states.shape[2]
|
| 504 |
-
#print("hidden_states.shape", hidden_states.shape)
|
| 505 |
-
hidden_states_ = torch.cat([condition_hidden_states]*(f+1), dim=2)
|
| 506 |
-
rotary_emb = self.rope(hidden_states_)
|
| 507 |
-
|
| 508 |
-
condition_hidden_states = self.patch_embedding(condition_hidden_states)
|
| 509 |
-
hidden_states = self.patch_embedding2(hidden_states)
|
| 510 |
-
condition_hidden_states = condition_hidden_states.flatten(2).transpose(1, 2)
|
| 511 |
-
hidden_states = hidden_states.flatten(2).transpose(1, 2)
|
| 512 |
-
|
| 513 |
-
temb, condition_timestep_proj, timestep_proj, encoder_hidden_states = self.condition_embedder(condition_timestep, timestep, encoder_hidden_states)
|
| 514 |
-
condition_timestep_proj = condition_timestep_proj.unflatten(1, (6, -1))
|
| 515 |
-
timestep_proj = timestep_proj.unflatten(1, (6, -1))
|
| 516 |
-
|
| 517 |
-
# 4. Transformer blocks
|
| 518 |
-
if torch.is_grad_enabled() and self.gradient_checkpointing:
|
| 519 |
-
for block in self.blocks:
|
| 520 |
-
condition_hidden_states, hidden_states = self._gradient_checkpointing_func(
|
| 521 |
-
block, condition_hidden_states, hidden_states, encoder_hidden_states, condition_timestep_proj, timestep_proj, rotary_emb, condition_cross_attention
|
| 522 |
-
)
|
| 523 |
-
else:
|
| 524 |
-
for block in self.blocks:
|
| 525 |
-
condition_hidden_states, hidden_states = block(condition_hidden_states, hidden_states, encoder_hidden_states, condition_timestep_proj, timestep_proj, rotary_emb, condition_cross_attention)
|
| 526 |
-
|
| 527 |
-
# 5. Output norm, projection & unpatchify
|
| 528 |
-
shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
|
| 529 |
-
|
| 530 |
-
shift = shift.to(hidden_states.device)
|
| 531 |
-
scale = scale.to(hidden_states.device)
|
| 532 |
-
|
| 533 |
-
hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
|
| 534 |
-
hidden_states = self.proj_out(hidden_states)
|
| 535 |
-
|
| 536 |
-
hidden_states = hidden_states.reshape(
|
| 537 |
-
batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
|
| 538 |
-
)
|
| 539 |
-
hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
|
| 540 |
-
output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
if not return_dict:
|
| 544 |
-
return (output,)
|
| 545 |
-
|
| 546 |
-
return Transformer2DModelOutput(sample=output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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