Upload folder using huggingface_hub
Browse files- .gitattributes +6 -0
- assets/1-0.png +3 -0
- assets/1-1.png +3 -0
- assets/1.mp4 +3 -0
- assets/2-0.png +3 -0
- assets/2-1.png +3 -0
- assets/2.mp4 +3 -0
- telestylevideo_inference.py +207 -0
- telestylevideo_pipeline.py +548 -0
- telestylevideo_transformer.py +546 -0
- weights/dit.ckpt +3 -0
- weights/prompt_embeds.pth +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,9 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
assets/1-0.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
assets/1-1.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
assets/1.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
assets/2-0.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
assets/2-1.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
assets/2.mp4 filter=lfs diff=lfs merge=lfs -text
|
assets/1-0.png
ADDED
|
Git LFS Details
|
assets/1-1.png
ADDED
|
Git LFS Details
|
assets/1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6d6f6e7f86b97be1935136bd486cb3f7011ebf3e0253402addd1727db24228f1
|
| 3 |
+
size 363304
|
assets/2-0.png
ADDED
|
Git LFS Details
|
assets/2-1.png
ADDED
|
Git LFS Details
|
ass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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import cv2
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
import torch
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from typing import List, Dict, Optional, Tuple
|
| 12 |
+
from einops import rearrange
|
| 13 |
+
from omegaconf import OmegaConf
|
| 14 |
+
from decord import VideoReader
|
| 15 |
+
from diffusers.utils import export_to_video
|
| 16 |
+
from diffusers.models import AutoencoderKLWan
|
| 17 |
+
from diffusers.schedulers import UniPCMultistepScheduler
|
| 18 |
+
from telestylevideo_transformer import WanTransformer3DModel
|
| 19 |
+
from telestylevideo_pipeline import WanPipeline
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def load_video(video_path: str, video_length: int) -> torch.Tensor:
|
| 23 |
+
if "png" in video_path.lower() or "jpeg" in video_path.lower() or "jpg" in video_path.lower():
|
| 24 |
+
image = cv2.imread(video_path)
|
| 25 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 26 |
+
image = np.array(image)
|
| 27 |
+
image = image[None, None] # 添加 batch 和 frame 维度
|
| 28 |
+
image = torch.from_numpy(image) / 127.5 - 1.0
|
| 29 |
+
return image
|
| 30 |
+
|
| 31 |
+
vr = VideoReader(video_path)
|
| 32 |
+
frames = list(range(min(len(vr), video_length)))
|
| 33 |
+
images = vr.get_batch(frames).asnumpy()
|
| 34 |
+
images = torch.from_numpy(images) / 127.5 - 1.0
|
| 35 |
+
images = images[None] # 添加 batch 维度
|
| 36 |
+
return images
|
| 37 |
+
|
| 38 |
+
class VideoStyleInference:
|
| 39 |
+
"""
|
| 40 |
+
视频风格转换推理类
|
| 41 |
+
"""
|
| 42 |
+
def __init__(self, config: Dict):
|
| 43 |
+
"""
|
| 44 |
+
初始化推理器
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
config: 配置字典
|
| 48 |
+
"""
|
| 49 |
+
self.config = config
|
| 50 |
+
self.device = torch.device(f"cuda:0")
|
| 51 |
+
self.random_seed = config['random_seed']
|
| 52 |
+
self.video_length = config['video_length']
|
| 53 |
+
self.H = config['height']
|
| 54 |
+
self.W = config['width']
|
| 55 |
+
self.num_inference_steps = config['num_inference_steps']
|
| 56 |
+
self.vae_path = os.path.join(config['ckpt_t2v_path'], "vae")
|
| 57 |
+
self.transformer_config_path = os.path.join(config['ckpt_t2v_path'], "transformer_config.json")
|
| 58 |
+
self.scheduler_path = os.path.join(config['ckpt_t2v_path'], "scheduler")
|
| 59 |
+
self.ckpt_path = config['ckpt_dit_path']
|
| 60 |
+
self.output_path = config['output_path']
|
| 61 |
+
self.prompt_embeds_path = config['prompt_embeds_path']
|
| 62 |
+
|
| 63 |
+
# 加载模型
|
| 64 |
+
self._load_models()
|
| 65 |
+
|
| 66 |
+
def _load_models(self):
|
| 67 |
+
"""
|
| 68 |
+
加载模型和权重
|
| 69 |
+
"""
|
| 70 |
+
# 加载状态字典
|
| 71 |
+
state_dict = torch.load(self.ckpt_path, map_location="cpu")["transformer_state_dict"]
|
| 72 |
+
transformer_state_dict = {}
|
| 73 |
+
for key in state_dict:
|
| 74 |
+
transformer_state_dict[key.split("module.")[1]] = state_dict[key]
|
| 75 |
+
|
| 76 |
+
# 加载配置
|
| 77 |
+
config = OmegaConf.to_container(
|
| 78 |
+
OmegaConf.load(self.transformer_config_path)
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# 初始化模型
|
| 82 |
+
self.vae = AutoencoderKLWan.from_pretrained(self.vae_path, torch_dtype=torch.float16).to(self.device)
|
| 83 |
+
self.transformer = WanTransformer3DModel(**config)
|
| 84 |
+
self.transformer.load_state_dict(transformer_state_dict)
|
| 85 |
+
self.transformer = self.transformer.to(self.device).half()
|
| 86 |
+
self.scheduler = UniPCMultistepScheduler.from_pretrained(self.scheduler_path)
|
| 87 |
+
|
| 88 |
+
# 初始化管道
|
| 89 |
+
self.pipe = WanPipeline(
|
| 90 |
+
transformer=self.transformer,
|
| 91 |
+
vae=self.vae,
|
| 92 |
+
scheduler=self.scheduler
|
| 93 |
+
)
|
| 94 |
+
self.pipe.to(self.device)
|
| 95 |
+
|
| 96 |
+
def inference(self, source_videos: torch.Tensor, first_images: torch.Tensor, video_path: str, step: int) -> torch.Tensor:
|
| 97 |
+
"""
|
| 98 |
+
执行风格转换推理
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
source_videos: 源视频张量
|
| 102 |
+
first_images: 风格参考图像张量
|
| 103 |
+
video_path: 源视频路径
|
| 104 |
+
step: 推理步骤索引
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
生成的视频张量
|
| 108 |
+
"""
|
| 109 |
+
source_videos = source_videos.to(self.device).half()
|
| 110 |
+
first_images = first_images.to(self.device).half()
|
| 111 |
+
prompt_embeds_ = torch.load(self.prompt_embeds_path).to(self.device).half()
|
| 112 |
+
|
| 113 |
+
print(f"Source videos shape: {source_videos.shape}, First images shape: {first_images.shape}")
|
| 114 |
+
|
| 115 |
+
latents_mean = torch.tensor(self.vae.config.latents_mean)
|
| 116 |
+
latents_mean = latents_mean.view(1, 16, 1, 1, 1).to(self.device, torch.float16)
|
| 117 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std)
|
| 118 |
+
latents_std = latents_std.view(1, 16, 1, 1, 1).to(self.device, torch.float16)
|
| 119 |
+
|
| 120 |
+
bsz = 1
|
| 121 |
+
_, _, h, w, _ = source_videos.shape
|
| 122 |
+
|
| 123 |
+
if h < w:
|
| 124 |
+
output_h, output_w = self.H, self.W
|
| 125 |
+
else:
|
| 126 |
+
output_h, output_w = self.W, self.H
|
| 127 |
+
|
| 128 |
+
with torch.no_grad():
|
| 129 |
+
# 处理源视频
|
| 130 |
+
source_videos = rearrange(source_videos, "b f h w c -> (b f) c h w")
|
| 131 |
+
source_videos = F.interpolate(source_videos, (output_h, output_w), mode="bilinear")
|
| 132 |
+
source_videos = rearrange(source_videos, "(b f) c h w -> b c f h w", b=bsz)
|
| 133 |
+
|
| 134 |
+
# 处理风格参考图像
|
| 135 |
+
first_images = rearrange(first_images, "b f h w c -> (b f) c h w")
|
| 136 |
+
first_images = F.interpolate(first_images, (output_h, output_w), mode="bilinear")
|
| 137 |
+
first_images = rearrange(first_images, "(b f) c h w -> b c f h w", b=bsz)
|
| 138 |
+
|
| 139 |
+
# 编码到潜在空间
|
| 140 |
+
source_latents = self.vae.encode(source_videos).latent_dist.mode()
|
| 141 |
+
source_latents = (source_latents - latents_mean) * latents_std
|
| 142 |
+
|
| 143 |
+
first_latents = self.vae.encode(first_images).latent_dist.mode()
|
| 144 |
+
first_latents = (first_latents - latents_mean) * latents_std
|
| 145 |
+
|
| 146 |
+
neg_first_latents = self.vae.encode(torch.zeros_like(first_images)).latent_dist.mode()
|
| 147 |
+
neg_first_latents = (neg_first_latents - latents_mean) * latents_std
|
| 148 |
+
|
| 149 |
+
video = self.pipe(
|
| 150 |
+
source_latents=source_latents,
|
| 151 |
+
first_latents=first_latents,
|
| 152 |
+
neg_first_latents=neg_first_latents,
|
| 153 |
+
num_frames=self.video_length,
|
| 154 |
+
guidance_scale=3.0,
|
| 155 |
+
height=output_h,
|
| 156 |
+
width=output_w,
|
| 157 |
+
prompt_embeds_=prompt_embeds_,
|
| 158 |
+
num_inference_steps=self.num_inference_steps,
|
| 159 |
+
generator=torch.Generator(device=self.device).manual_seed(self.random_seed),
|
| 160 |
+
).frames[0]
|
| 161 |
+
|
| 162 |
+
return video
|
| 163 |
+
|
| 164 |
+
if __name__ == "__main__":
|
| 165 |
+
config = {
|
| 166 |
+
"random_seed": 42,
|
| 167 |
+
"video_length": 129,
|
| 168 |
+
"height": 720,
|
| 169 |
+
"width": 1248,
|
| 170 |
+
"num_inference_steps": 25,
|
| 171 |
+
"ckpt_t2v_path": "./Wan2.1-T2V-1.3B-Diffusers",
|
| 172 |
+
"ckpt_dit_path": "weights/dit.ckpt",
|
| 173 |
+
"prompt_embeds_path": "weights/prompt_embeds.pth",
|
| 174 |
+
"output_path": "./results"
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
# 初始化推理器
|
| 178 |
+
inference_engine = VideoStyleInference(config)
|
| 179 |
+
|
| 180 |
+
data_list = [
|
| 181 |
+
{
|
| 182 |
+
"video_path": "assets/example/2.mp4",
|
| 183 |
+
"image_path": "assets/example/2-0.png"
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"video_path": "assets/example/2.mp4",
|
| 187 |
+
"image_path": "assets/example/2-1.png"
|
| 188 |
+
},
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
for step, data in enumerate(data_list):
|
| 192 |
+
video_path = data['video_path']
|
| 193 |
+
style_image_path = data['image_path']
|
| 194 |
+
|
| 195 |
+
source_video = load_video(video_path, config['video_length'])
|
| 196 |
+
style_image = Image.open(style_image_path)
|
| 197 |
+
style_image = np.array(style_image)
|
| 198 |
+
style_image = torch.from_numpy(style_image) / 127.5 - 1.0
|
| 199 |
+
style_image = style_image[None, None, :, :, :] # 添加 batch 和 frame 维度
|
| 200 |
+
|
| 201 |
+
with torch.no_grad():
|
| 202 |
+
generated_video = inference_engine.inference(source_video, style_image, video_path, step)
|
| 203 |
+
|
| 204 |
+
os.makedirs(config['output_path'], exist_ok=True)
|
| 205 |
+
output_filename = f"{config['output_path']}/{step}.mp4"
|
| 206 |
+
export_to_video(generated_video, output_filename)
|
| 207 |
+
|
telestylevideo_pipeline.py
ADDED
|
@@ -0,0 +1,548 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 html
|
| 16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import ftfy
|
| 19 |
+
import regex as re
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 22 |
+
|
| 23 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 24 |
+
from diffusers.loaders import WanLoraLoaderMixin
|
| 25 |
+
from diffusers.models import AutoencoderKLWan
|
| 26 |
+
from transformer_semi_dit_2_patch_embedders import WanTransformer3DModel
|
| 27 |
+
from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
|
| 28 |
+
from diffusers.utils import is_torch_xla_available, logging, replace_example_docstring
|
| 29 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 30 |
+
from diffusers.video_processor import VideoProcessor
|
| 31 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 32 |
+
from diffusers.pipelines.wan.pipeline_output import WanPipelineOutput
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_xla_available():
|
| 36 |
+
import torch_xla.core.xla_model as xm
|
| 37 |
+
|
| 38 |
+
XLA_AVAILABLE = True
|
| 39 |
+
else:
|
| 40 |
+
XLA_AVAILABLE = False
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
EXAMPLE_DOC_STRING = """
|
| 46 |
+
Examples:
|
| 47 |
+
```python
|
| 48 |
+
>>> import torch
|
| 49 |
+
>>> from diffusers.utils import export_to_video
|
| 50 |
+
>>> from diffusers import AutoencoderKLWan, WanPipeline
|
| 51 |
+
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
|
| 52 |
+
|
| 53 |
+
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
|
| 54 |
+
>>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
|
| 55 |
+
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
|
| 56 |
+
>>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
|
| 57 |
+
>>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
|
| 58 |
+
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
|
| 59 |
+
>>> pipe.to("cuda")
|
| 60 |
+
|
| 61 |
+
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
|
| 62 |
+
>>> negative_prompt = "Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards"
|
| 63 |
+
|
| 64 |
+
>>> output = pipe(
|
| 65 |
+
... prompt=prompt,
|
| 66 |
+
... negative_prompt=negative_prompt,
|
| 67 |
+
... height=720,
|
| 68 |
+
... width=1280,
|
| 69 |
+
... num_frames=81,
|
| 70 |
+
... guidance_scale=5.0,
|
| 71 |
+
... ).frames[0]
|
| 72 |
+
>>> export_to_video(output, "output.mp4", fps=16)
|
| 73 |
+
```
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def basic_clean(text):
|
| 78 |
+
text = ftfy.fix_text(text)
|
| 79 |
+
text = html.unescape(html.unescape(text))
|
| 80 |
+
return text.strip()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def whitespace_clean(text):
|
| 84 |
+
text = re.sub(r"\s+", " ", text)
|
| 85 |
+
text = text.strip()
|
| 86 |
+
return text
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def prompt_clean(text):
|
| 90 |
+
text = whitespace_clean(basic_clean(text))
|
| 91 |
+
return text
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class WanPipeline(DiffusionPipeline, WanLoraLoaderMixin):
|
| 95 |
+
r"""
|
| 96 |
+
Pipeline for text-to-video generation using Wan.
|
| 97 |
+
|
| 98 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 99 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
tokenizer ([`T5Tokenizer`]):
|
| 103 |
+
Tokenizer from [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Tokenizer),
|
| 104 |
+
specifically the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 105 |
+
text_encoder ([`T5EncoderModel`]):
|
| 106 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
| 107 |
+
the [google/umt5-xxl](https://huggingface.co/google/umt5-xxl) variant.
|
| 108 |
+
transformer ([`WanTransformer3DModel`]):
|
| 109 |
+
Conditional Transformer to denoise the input latents.
|
| 110 |
+
scheduler ([`UniPCMultistepScheduler`]):
|
| 111 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 112 |
+
vae ([`AutoencoderKLWan`]):
|
| 113 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 117 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 118 |
+
|
| 119 |
+
def __init__(
|
| 120 |
+
self,
|
| 121 |
+
#tokenizer: AutoTokenizer,
|
| 122 |
+
#text_encoder: UMT5EncoderModel,
|
| 123 |
+
transformer: WanTransformer3DModel,
|
| 124 |
+
vae: AutoencoderKLWan,
|
| 125 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
| 126 |
+
):
|
| 127 |
+
super().__init__()
|
| 128 |
+
self.register_modules(
|
| 129 |
+
vae=vae,
|
| 130 |
+
transformer=transformer,
|
| 131 |
+
scheduler=scheduler,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# self.register_modules(
|
| 135 |
+
# vae=vae,
|
| 136 |
+
# text_encoder=text_encoder,
|
| 137 |
+
# tokenizer=tokenizer,
|
| 138 |
+
# transformer=transformer,
|
| 139 |
+
# scheduler=scheduler,
|
| 140 |
+
# )
|
| 141 |
+
|
| 142 |
+
self.vae_scale_factor_temporal = 2 ** sum(self.vae.temperal_downsample) if getattr(self, "vae", None) else 4
|
| 143 |
+
self.vae_scale_factor_spatial = 2 ** len(self.vae.temperal_downsample) if getattr(self, "vae", None) else 8
|
| 144 |
+
self.video_processor = VideoProcessor(vae_scale_factor=self.vae_scale_factor_spatial)
|
| 145 |
+
|
| 146 |
+
# def _get_t5_prompt_embeds(
|
| 147 |
+
# self,
|
| 148 |
+
# prompt: Union[str, List[str]] = None,
|
| 149 |
+
# num_videos_per_prompt: int = 1,
|
| 150 |
+
# max_sequence_length: int = 226,
|
| 151 |
+
# device: Optional[torch.device] = None,
|
| 152 |
+
# dtype: Optional[torch.dtype] = None,
|
| 153 |
+
# ):
|
| 154 |
+
# device = device or self._execution_device
|
| 155 |
+
# dtype = dtype or self.text_encoder.dtype
|
| 156 |
+
|
| 157 |
+
# prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 158 |
+
# prompt = [prompt_clean(u) for u in prompt]
|
| 159 |
+
# batch_size = len(prompt)
|
| 160 |
+
|
| 161 |
+
# text_inputs = self.tokenizer(
|
| 162 |
+
# prompt,
|
| 163 |
+
# padding="max_length",
|
| 164 |
+
# max_length=max_sequence_length,
|
| 165 |
+
# truncation=True,
|
| 166 |
+
# add_special_tokens=True,
|
| 167 |
+
# return_attention_mask=True,
|
| 168 |
+
# return_tensors="pt",
|
| 169 |
+
# )
|
| 170 |
+
# text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 171 |
+
# seq_lens = mask.gt(0).sum(dim=1).long()
|
| 172 |
+
|
| 173 |
+
# prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
|
| 174 |
+
# prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 175 |
+
# prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 176 |
+
# prompt_embeds = torch.stack(
|
| 177 |
+
# [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
|
| 178 |
+
# )
|
| 179 |
+
|
| 180 |
+
# # duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 181 |
+
# _, seq_len, _ = prompt_embeds.shape
|
| 182 |
+
# prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 183 |
+
# prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
|
| 184 |
+
|
| 185 |
+
# return prompt_embeds
|
| 186 |
+
|
| 187 |
+
# def encode_prompt(
|
| 188 |
+
# self,
|
| 189 |
+
# prompt: Union[str, List[str]],
|
| 190 |
+
# negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 191 |
+
# do_classifier_free_guidance: bool = True,
|
| 192 |
+
# num_videos_per_prompt: int = 1,
|
| 193 |
+
# prompt_embeds: Optional[torch.Tensor] = None,
|
| 194 |
+
# negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 195 |
+
# max_sequence_length: int = 226,
|
| 196 |
+
# device: Optional[torch.device] = None,
|
| 197 |
+
# dtype: Optional[torch.dtype] = None,
|
| 198 |
+
# ):
|
| 199 |
+
# r"""
|
| 200 |
+
# Encodes the prompt into text encoder hidden states.
|
| 201 |
+
|
| 202 |
+
# Args:
|
| 203 |
+
# prompt (`str` or `List[str]`, *optional*):
|
| 204 |
+
# prompt to be encoded
|
| 205 |
+
# negative_prompt (`str` or `List[str]`, *optional*):
|
| 206 |
+
# The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 207 |
+
# `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 208 |
+
# less than `1`).
|
| 209 |
+
# do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 210 |
+
# Whether to use classifier free guidance or not.
|
| 211 |
+
# num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 212 |
+
# Number of videos that should be generated per prompt. torch device to place the resulting embeddings on
|
| 213 |
+
# prompt_embeds (`torch.Tensor`, *optional*):
|
| 214 |
+
# Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 215 |
+
# provided, text embeddings will be generated from `prompt` input argument.
|
| 216 |
+
# negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 217 |
+
# Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 218 |
+
# weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 219 |
+
# argument.
|
| 220 |
+
# device: (`torch.device`, *optional*):
|
| 221 |
+
# torch device
|
| 222 |
+
# dtype: (`torch.dtype`, *optional*):
|
| 223 |
+
# torch dtype
|
| 224 |
+
# """
|
| 225 |
+
# device = device or self._execution_device
|
| 226 |
+
|
| 227 |
+
# prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 228 |
+
# if prompt is not None:
|
| 229 |
+
# batch_size = len(prompt)
|
| 230 |
+
# else:
|
| 231 |
+
# batch_size = prompt_embeds.shape[0]
|
| 232 |
+
|
| 233 |
+
# if prompt_embeds is None:
|
| 234 |
+
# prompt_embeds = self._get_t5_prompt_embeds(
|
| 235 |
+
# prompt=prompt,
|
| 236 |
+
# num_videos_per_prompt=num_videos_per_prompt,
|
| 237 |
+
# max_sequence_length=max_sequence_length,
|
| 238 |
+
# device=device,
|
| 239 |
+
# dtype=dtype,
|
| 240 |
+
# )
|
| 241 |
+
|
| 242 |
+
# if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 243 |
+
# negative_prompt = negative_prompt or ""
|
| 244 |
+
# negative_prompt = batch_size * [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt
|
| 245 |
+
|
| 246 |
+
# if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 247 |
+
# raise TypeError(
|
| 248 |
+
# f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 249 |
+
# f" {type(prompt)}."
|
| 250 |
+
# )
|
| 251 |
+
# elif batch_size != len(negative_prompt):
|
| 252 |
+
# raise ValueError(
|
| 253 |
+
# f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 254 |
+
# f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 255 |
+
# " the batch size of `prompt`."
|
| 256 |
+
# )
|
| 257 |
+
|
| 258 |
+
# negative_prompt_embeds = self._get_t5_prompt_embeds(
|
| 259 |
+
# prompt=negative_prompt,
|
| 260 |
+
# num_videos_per_prompt=num_videos_per_prompt,
|
| 261 |
+
# max_sequence_length=max_sequence_length,
|
| 262 |
+
# device=device,
|
| 263 |
+
# dtype=dtype,
|
| 264 |
+
# )
|
| 265 |
+
|
| 266 |
+
# return prompt_embeds, negative_prompt_embeds
|
| 267 |
+
|
| 268 |
+
# def check_inputs(
|
| 269 |
+
# self,
|
| 270 |
+
# prompt,
|
| 271 |
+
# negative_prompt,
|
| 272 |
+
# height,
|
| 273 |
+
# width,
|
| 274 |
+
# prompt_embeds=None,
|
| 275 |
+
# negative_prompt_embeds=None,
|
| 276 |
+
# callback_on_step_end_tensor_inputs=None,
|
| 277 |
+
# ):
|
| 278 |
+
# if height % 16 != 0 or width % 16 != 0:
|
| 279 |
+
# raise ValueError(f"`height` and `width` have to be divisible by 16 but are {height} and {width}.")
|
| 280 |
+
|
| 281 |
+
# if callback_on_step_end_tensor_inputs is not None and not all(
|
| 282 |
+
# k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 283 |
+
# ):
|
| 284 |
+
# raise ValueError(
|
| 285 |
+
# 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]}"
|
| 286 |
+
# )
|
| 287 |
+
|
| 288 |
+
# if prompt is not None and prompt_embeds is not None:
|
| 289 |
+
# raise ValueError(
|
| 290 |
+
# f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 291 |
+
# " only forward one of the two."
|
| 292 |
+
# )
|
| 293 |
+
# elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 294 |
+
# raise ValueError(
|
| 295 |
+
# f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 296 |
+
# " only forward one of the two."
|
| 297 |
+
# )
|
| 298 |
+
# elif prompt is None and prompt_embeds is None:
|
| 299 |
+
# raise ValueError(
|
| 300 |
+
# "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 301 |
+
# )
|
| 302 |
+
# elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 303 |
+
# raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 304 |
+
# elif negative_prompt is not None and (
|
| 305 |
+
# not isinstance(negative_prompt, str) and not isinstance(negative_prompt, list)
|
| 306 |
+
# ):
|
| 307 |
+
# raise ValueError(f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}")
|
| 308 |
+
|
| 309 |
+
def prepare_latents(
|
| 310 |
+
self,
|
| 311 |
+
batch_size: int,
|
| 312 |
+
num_channels_latents: int = 16,
|
| 313 |
+
height: int = 480,
|
| 314 |
+
width: int = 832,
|
| 315 |
+
num_frames: int = 81,
|
| 316 |
+
dtype: Optional[torch.dtype] = None,
|
| 317 |
+
device: Optional[torch.device] = None,
|
| 318 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 319 |
+
latents: Optional[torch.Tensor] = None,
|
| 320 |
+
) -> torch.Tensor:
|
| 321 |
+
if latents is not None:
|
| 322 |
+
return latents.to(device=device, dtype=dtype)
|
| 323 |
+
|
| 324 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 325 |
+
shape = (
|
| 326 |
+
batch_size,
|
| 327 |
+
num_channels_latents,
|
| 328 |
+
num_latent_frames,
|
| 329 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 330 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 331 |
+
)
|
| 332 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 333 |
+
raise ValueError(
|
| 334 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 335 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 339 |
+
return latents
|
| 340 |
+
|
| 341 |
+
@property
|
| 342 |
+
def guidance_scale(self):
|
| 343 |
+
return self._guidance_scale
|
| 344 |
+
|
| 345 |
+
@property
|
| 346 |
+
def do_classifier_free_guidance(self):
|
| 347 |
+
return self._guidance_scale > 1.0
|
| 348 |
+
|
| 349 |
+
@property
|
| 350 |
+
def num_timesteps(self):
|
| 351 |
+
return self._num_timesteps
|
| 352 |
+
|
| 353 |
+
@property
|
| 354 |
+
def current_timestep(self):
|
| 355 |
+
return self._current_timestep
|
| 356 |
+
|
| 357 |
+
# @property
|
| 358 |
+
# def interrupt(self):
|
| 359 |
+
# return self._interrupt
|
| 360 |
+
|
| 361 |
+
# @property
|
| 362 |
+
# def attention_kwargs(self):
|
| 363 |
+
# return self._attention_kwargs
|
| 364 |
+
|
| 365 |
+
@torch.no_grad()
|
| 366 |
+
#@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 367 |
+
def __call__(
|
| 368 |
+
self,
|
| 369 |
+
prompt: Union[str, List[str]] = None,
|
| 370 |
+
negative_prompt: Union[str, List[str]] = None,
|
| 371 |
+
height: int = 480,
|
| 372 |
+
width: int = 832,
|
| 373 |
+
num_frames: int = 81,
|
| 374 |
+
num_inference_steps: int = 50,
|
| 375 |
+
guidance_scale: float = 5.0,
|
| 376 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 377 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 378 |
+
latents: Optional[torch.Tensor] = None,
|
| 379 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 380 |
+
prompt_embeds_: Optional[torch.Tensor] = None,
|
| 381 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 382 |
+
output_type: Optional[str] = "np",
|
| 383 |
+
return_dict: bool = True,
|
| 384 |
+
attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 385 |
+
callback_on_step_end: Optional[
|
| 386 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 387 |
+
] = None,
|
| 388 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 389 |
+
max_sequence_length: int = 512,
|
| 390 |
+
source_latents: Optional[torch.Tensor] = None,
|
| 391 |
+
first_latents: Optional[torch.Tensor] = None,
|
| 392 |
+
neg_first_latents: Optional[torch.Tensor] = None,
|
| 393 |
+
):
|
| 394 |
+
|
| 395 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 396 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 397 |
+
|
| 398 |
+
# 1. Check inputs. Raise error if not correct
|
| 399 |
+
# self.check_inputs(
|
| 400 |
+
# prompt,
|
| 401 |
+
# negative_prompt,
|
| 402 |
+
# height,
|
| 403 |
+
# width,
|
| 404 |
+
# prompt_embeds,
|
| 405 |
+
# negative_prompt_embeds,
|
| 406 |
+
# callback_on_step_end_tensor_inputs,
|
| 407 |
+
# )
|
| 408 |
+
|
| 409 |
+
# if num_frames % self.vae_scale_factor_temporal != 1:
|
| 410 |
+
# logger.warning(
|
| 411 |
+
# f"`num_frames - 1` has to be divisible by {self.vae_scale_factor_temporal}. Rounding to the nearest number."
|
| 412 |
+
# )
|
| 413 |
+
# num_frames = num_frames // self.vae_scale_factor_temporal * self.vae_scale_factor_temporal + 1
|
| 414 |
+
# num_frames = max(num_frames, 1)
|
| 415 |
+
|
| 416 |
+
self._guidance_scale = guidance_scale
|
| 417 |
+
# self._attention_kwargs = attention_kwargs
|
| 418 |
+
self._current_timestep = None
|
| 419 |
+
self._interrupt = False
|
| 420 |
+
|
| 421 |
+
device = self._execution_device
|
| 422 |
+
|
| 423 |
+
# 2. Define call parameters
|
| 424 |
+
# if prompt is not None and isinstance(prompt, str):
|
| 425 |
+
# batch_size = 1
|
| 426 |
+
# elif prompt is not None and isinstance(prompt, list):
|
| 427 |
+
# batch_size = len(prompt)
|
| 428 |
+
# else:
|
| 429 |
+
# batch_size = prompt_embeds.shape[0]
|
| 430 |
+
|
| 431 |
+
# batch_size = 1
|
| 432 |
+
|
| 433 |
+
# 3. Encode input prompt
|
| 434 |
+
# prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 435 |
+
# prompt=prompt,
|
| 436 |
+
# negative_prompt=negative_prompt,
|
| 437 |
+
# do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 438 |
+
# num_videos_per_prompt=num_videos_per_prompt,
|
| 439 |
+
# prompt_embeds=prompt_embeds,
|
| 440 |
+
# negative_prompt_embeds=negative_prompt_embeds,
|
| 441 |
+
# max_sequence_length=max_sequence_length,
|
| 442 |
+
# device=device,
|
| 443 |
+
# )
|
| 444 |
+
|
| 445 |
+
transformer_dtype = self.transformer.dtype
|
| 446 |
+
# prompt_embeds = prompt_embeds.to(transformer_dtype)
|
| 447 |
+
# if negative_prompt_embeds is not None:
|
| 448 |
+
# negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 449 |
+
|
| 450 |
+
# 4. Prepare timesteps
|
| 451 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 452 |
+
timesteps = self.scheduler.timesteps
|
| 453 |
+
|
| 454 |
+
# 5. Prepare latent variables
|
| 455 |
+
# num_channels_latents = self.transformer.config.in_channels
|
| 456 |
+
# latents = self.prepare_latents(
|
| 457 |
+
# batch_size * num_videos_per_prompt,
|
| 458 |
+
# num_channels_latents,
|
| 459 |
+
# height,
|
| 460 |
+
# width,
|
| 461 |
+
# num_frames,
|
| 462 |
+
# torch.float32,
|
| 463 |
+
# device,
|
| 464 |
+
# generator,
|
| 465 |
+
# latents,
|
| 466 |
+
# )
|
| 467 |
+
|
| 468 |
+
latents = torch.randn_like(source_latents)
|
| 469 |
+
|
| 470 |
+
# 6. Denoising loop
|
| 471 |
+
# num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 472 |
+
self._num_timesteps = len(timesteps)
|
| 473 |
+
|
| 474 |
+
condition_latent_model_input = first_latents
|
| 475 |
+
neg_condition_latent_model_input = neg_first_latents
|
| 476 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 477 |
+
for i, t in enumerate(timesteps):
|
| 478 |
+
|
| 479 |
+
self._current_timestep = t
|
| 480 |
+
latent_model_input = torch.cat([source_latents, latents.to(transformer_dtype)], dim=1)
|
| 481 |
+
timestep = t.expand(latents.shape[0])
|
| 482 |
+
|
| 483 |
+
print(timestep, torch.zeros_like(timestep))
|
| 484 |
+
noise_pred = self.transformer(
|
| 485 |
+
condition_hidden_states=condition_latent_model_input,
|
| 486 |
+
hidden_states=latent_model_input,
|
| 487 |
+
condition_timestep=torch.zeros_like(timestep),
|
| 488 |
+
timestep=timestep,
|
| 489 |
+
encoder_hidden_states=prompt_embeds_,
|
| 490 |
+
return_dict=False,
|
| 491 |
+
)[0]
|
| 492 |
+
|
| 493 |
+
if self.do_classifier_free_guidance:
|
| 494 |
+
noise_uncond = self.transformer(
|
| 495 |
+
condition_hidden_states=neg_condition_latent_model_input,
|
| 496 |
+
hidden_states=latent_model_input,
|
| 497 |
+
condition_timestep=torch.zeros_like(timestep),
|
| 498 |
+
timestep=timestep,
|
| 499 |
+
encoder_hidden_states=prompt_embeds_,
|
| 500 |
+
return_dict=False,
|
| 501 |
+
)[0]
|
| 502 |
+
noise_pred = noise_uncond + guidance_scale * (noise_pred - noise_uncond)
|
| 503 |
+
|
| 504 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 505 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
| 506 |
+
|
| 507 |
+
# if callback_on_step_end is not None:
|
| 508 |
+
# callback_kwargs = {}
|
| 509 |
+
# for k in callback_on_step_end_tensor_inputs:
|
| 510 |
+
# callback_kwargs[k] = locals()[k]
|
| 511 |
+
# callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 512 |
+
|
| 513 |
+
# latents = callback_outputs.pop("latents", latents)
|
| 514 |
+
# prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 515 |
+
# negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 516 |
+
|
| 517 |
+
# call the callback, if provided
|
| 518 |
+
#if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 519 |
+
progress_bar.update()
|
| 520 |
+
|
| 521 |
+
# if XLA_AVAILABLE:
|
| 522 |
+
# xm.mark_step()
|
| 523 |
+
|
| 524 |
+
self._current_timestep = None
|
| 525 |
+
|
| 526 |
+
if not output_type == "latent":
|
| 527 |
+
latents = latents.to(self.vae.dtype)
|
| 528 |
+
latents_mean = (
|
| 529 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 530 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 531 |
+
.to(latents.device, latents.dtype)
|
| 532 |
+
)
|
| 533 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(1, self.vae.config.z_dim, 1, 1, 1).to(
|
| 534 |
+
latents.device, latents.dtype
|
| 535 |
+
)
|
| 536 |
+
latents = latents / latents_std + latents_mean
|
| 537 |
+
video = self.vae.decode(latents, return_dict=False)[0]
|
| 538 |
+
video = self.video_processor.postprocess_video(video, output_type=output_type)
|
| 539 |
+
else:
|
| 540 |
+
video = latents
|
| 541 |
+
|
| 542 |
+
# Offload all models
|
| 543 |
+
# self.maybe_free_model_hooks()
|
| 544 |
+
|
| 545 |
+
if not return_dict:
|
| 546 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
weights/dit.ckpt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eebc7e54d3e5b4fc6852380fede55f968cf4cf2909ab0dc2959ccaf909faf597
|
| 3 |
+
size 5677100884
|
weights/prompt_embeds.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3791522a17130f2df6f8c5e84a3643605b911b63ccad7428961452cd002a2a8
|
| 3 |
+
size 4195514
|