jbilcke-hf HF Staff commited on
Commit
4c2e381
·
1 Parent(s): 8b46ae0
.claude/settings.local.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "enableAllProjectMcpServers": false
3
+ }
Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
- FROM nvidia/cuda:12.4.0-devel-ubuntu22.04
2
 
3
  # Prevent interactive prompts during build
4
  ARG DEBIAN_FRONTEND=noninteractive
 
1
+ FROM nvidia/cuda:12.8.1-devel-ubuntu24.04
2
 
3
  # Prevent interactive prompts during build
4
  ARG DEBIAN_FRONTEND=noninteractive
degraded_finetrainers_requirements.txt CHANGED
@@ -9,10 +9,10 @@ peft>=0.13.0
9
  #decord>=0.6.0
10
  wandb
11
  pandas
12
- torch>=2.5.1
13
- torchvision>=0.20.1
14
- torchdata>=0.10.1
15
- torchao>=0.7.0
16
  sentencepiece>=0.2.0
17
  imageio-ffmpeg>=0.5.1
18
  numpy>=1.26.4
 
9
  #decord>=0.6.0
10
  wandb
11
  pandas
12
+ torch==2.6.0
13
+ torchvision==0.21.0
14
+ torchdata==0.1.0
15
+ torchao==0.9.0
16
  sentencepiece>=0.2.0
17
  imageio-ffmpeg>=0.5.1
18
  numpy>=1.26.4
degraded_requirements.txt CHANGED
@@ -15,7 +15,7 @@ imageio-ffmpeg
15
  eva-decord
16
 
17
  # don't install flash attention on macOS
18
- #flash-attn @ https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.4cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
19
 
20
  #--------------- / MACOS HACKS --------------
21
 
 
15
  eva-decord
16
 
17
  # don't install flash attention on macOS
18
+ #flash-attn @ https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
19
 
20
  #--------------- / MACOS HACKS --------------
21
 
docs/wan/README-for-Wan2.1-FLF2V-14B-720P-diffusers.md ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ ---
4
+ # Wan2.1
5
+
6
+ <p align="center">
7
+ <img src="assets/logo.png" width="400"/>
8
+ <p>
9
+
10
+ <p align="center">
11
+ 💜 <a href="https://wan.video"><b>Wan</b></a> &nbsp&nbsp | &nbsp&nbsp 🖥️ <a href="https://github.com/Wan-Video/Wan2.1">GitHub</a> &nbsp&nbsp | &nbsp&nbsp🤗 <a href="https://huggingface.co/Wan-AI/">Hugging Face</a>&nbsp&nbsp | &nbsp&nbsp🤖 <a href="https://modelscope.cn/organization/Wan-AI">ModelScope</a>&nbsp&nbsp | &nbsp&nbsp 📑 <a href="https://arxiv.org/abs/2503.20314">Technical Report</a> &nbsp&nbsp | &nbsp&nbsp 📑 <a href="https://wan.video/welcome?spm=a2ty_o02.30011076.0.0.6c9ee41eCcluqg">Blog</a> &nbsp&nbsp | &nbsp&nbsp💬 <a href="https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg">WeChat Group</a>&nbsp&nbsp | &nbsp&nbsp 📖 <a href="https://discord.gg/AKNgpMK4Yj">Discord</a>&nbsp&nbsp
12
+ <br>
13
+
14
+ -----
15
+
16
+ [**Wan: Open and Advanced Large-Scale Video Generative Models**](https://arxiv.org/abs/2503.20314) <be>
17
+
18
+ In this repository, we present **Wan2.1**, a comprehensive and open suite of video foundation models that pushes the boundaries of video generation. **Wan2.1** offers these key features:
19
+ - 👍 **SOTA Performance**: **Wan2.1** consistently outperforms existing open-source models and state-of-the-art commercial solutions across multiple benchmarks.
20
+ - 👍 **Supports Consumer-grade GPUs**: The T2V-1.3B model requires only 8.19 GB VRAM, making it compatible with almost all consumer-grade GPUs. It can generate a 5-second 480P video on an RTX 4090 in about 4 minutes (without optimization techniques like quantization). Its performance is even comparable to some closed-source models.
21
+ - 👍 **Multiple Tasks**: **Wan2.1** excels in Text-to-Video, Image-to-Video, Video Editing, Text-to-Image, and Video-to-Audio, advancing the field of video generation.
22
+ - 👍 **Visual Text Generation**: **Wan2.1** is the first video model capable of generating both Chinese and English text, featuring robust text generation that enhances its practical applications.
23
+ - 👍 **Powerful Video VAE**: **Wan-VAE** delivers exceptional efficiency and performance, encoding and decoding 1080P videos of any length while preserving temporal information, making it an ideal foundation for video and image generation.
24
+
25
+ ## Video Demos
26
+
27
+ <div align="center">
28
+ <video width="80%" controls>
29
+ <source src="https://cloud.video.taobao.com/vod/Jth64Y7wNoPcJki_Bo1ZJTDBvNjsgjlVKsNs05Fqfps.mp4" type="video/mp4">
30
+ Your browser does not support the video tag.
31
+ </video>
32
+ </div>
33
+
34
+ ## 🔥 Latest News!!
35
+
36
+ * Apr 17, 2025: 👋 We introduce **Wan2.1** [FLF2V](#run-first-last-frame-to-video-generation) with its inference code and weights!
37
+ * Mar 21, 2025: 👋 We are excited to announce the release of the **Wan2.1** [technical report](https://files.alicdn.com/tpsservice/5c9de1c74de03972b7aa657e5a54756b.pdf). We welcome discussions and feedback!
38
+ * Mar 3, 2025: 👋 **Wan2.1**'s T2V and I2V have been integrated into Diffusers ([T2V](https://huggingface.co/docs/diffusers/main/en/api/pipelines/wan#diffusers.WanPipeline) | [I2V](https://huggingface.co/docs/diffusers/main/en/api/pipelines/wan#diffusers.WanImageToVideoPipeline)). Feel free to give it a try!
39
+ * Feb 27, 2025: 👋 **Wan2.1** has been integrated into [ComfyUI](https://comfyanonymous.github.io/ComfyUI_examples/wan/). Enjoy!
40
+ * Feb 25, 2025: 👋 We've released the inference code and weights of **Wan2.1**.
41
+
42
+ ## Community Works
43
+ If your work has improved **Wan2.1** and you would like more people to see it, please inform us.
44
+ - [CFG-Zero](https://github.com/WeichenFan/CFG-Zero-star) enhances **Wan2.1** (covering both T2V and I2V models) from the perspective of CFG.
45
+ - [TeaCache](https://github.com/ali-vilab/TeaCache) now supports **Wan2.1** acceleration, capable of increasing speed by approximately 2x. Feel free to give it a try!
46
+ - [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio) provides more support for **Wan2.1**, including video-to-video, FP8 quantization, VRAM optimization, LoRA training, and more. Please refer to [their examples](https://github.com/modelscope/DiffSynth-Studio/tree/main/examples/wanvideo).
47
+
48
+
49
+ ## 📑 Todo List
50
+ - Wan2.1 Text-to-Video
51
+ - [x] Multi-GPU Inference code of the 14B and 1.3B models
52
+ - [x] Checkpoints of the 14B and 1.3B models
53
+ - [x] Gradio demo
54
+ - [x] ComfyUI integration
55
+ - [x] Diffusers integration
56
+ - [ ] Diffusers + Multi-GPU Inference
57
+ - Wan2.1 Image-to-Video
58
+ - [x] Multi-GPU Inference code of the 14B model
59
+ - [x] Checkpoints of the 14B model
60
+ - [x] Gradio demo
61
+ - [x] ComfyUI integration
62
+ - [x] Diffusers integration
63
+ - [ ] Diffusers + Multi-GPU Inference
64
+ - Wan2.1 First-Last-Frame-to-Video
65
+ - [x] Multi-GPU Inference code of the 14B model
66
+ - [x] Checkpoints of the 14B model
67
+ - [x] Gradio demo
68
+ - [ ] ComfyUI integration
69
+ - [x] Diffusers integration
70
+ - [ ] Diffusers + Multi-GPU Inference
71
+
72
+
73
+ ## 🚀 Quickstart
74
+
75
+ This repository corresponding to the diffusers format weights. You can find original release weights here: [Wan2.1-FLF2V-14B-720P](https://huggingface.co/Wan-AI/Wan2.1-FLF2V-14B-720P).
76
+
77
+ ### Using with diffusers
78
+
79
+ Make sure you upgrade to latest version of diffusers:
80
+ ```python
81
+ pip install git+https://github.com/huggingface/diffusers.git
82
+ ```
83
+ And then you can run:
84
+
85
+ ```python
86
+
87
+ import numpy as np
88
+ import torch
89
+ import torchvision.transforms.functional as TF
90
+ from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
91
+ from diffusers.utils import export_to_video, load_image
92
+ from transformers import CLIPVisionModel
93
+
94
+ model_id = "Wan-AI/Wan2.1-FLF2V-14B-720P-Diffusers"
95
+ image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
96
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
97
+ pipe = WanImageToVideoPipeline.from_pretrained(
98
+ model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
99
+ )
100
+ pipe.to("cuda")
101
+
102
+ first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png")
103
+ last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png")
104
+
105
+ def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
106
+ aspect_ratio = image.height / image.width
107
+ mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
108
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
109
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
110
+ image = image.resize((width, height))
111
+ return image, height, width
112
+
113
+ def center_crop_resize(image, height, width):
114
+ # Calculate resize ratio to match first frame dimensions
115
+ resize_ratio = max(width / image.width, height / image.height)
116
+
117
+ # Resize the image
118
+ width = round(image.width * resize_ratio)
119
+ height = round(image.height * resize_ratio)
120
+ size = [width, height]
121
+ image = TF.center_crop(image, size)
122
+
123
+ return image, height, width
124
+
125
+ first_frame, height, width = aspect_ratio_resize(first_frame, pipe)
126
+ if last_frame.size != first_frame.size:
127
+ last_frame, _, _ = center_crop_resize(last_frame, height, width)
128
+
129
+ prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
130
+
131
+ output = pipe(
132
+ image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.5
133
+ ).frames[0]
134
+ export_to_video(output, f"wan-ff2v.mp4", fps=16)
135
+ ```
136
+
137
+ > 💡Note: Please note that this example does not integrate Prompt Extension and distributed inference. We will soon update with the integrated prompt extension and multi-GPU version of Diffusers.
138
+
139
+
140
+ ## Manual Evaluation
141
+
142
+ ##### (1) Text-to-Video Evaluation
143
+
144
+ Through manual evaluation, the results generated after prompt extension are superior to those from both closed-source and open-source models.
145
+
146
+ <div align="center">
147
+ <img src="assets/t2v_res.jpg" alt="" style="width: 80%;" />
148
+ </div>
149
+
150
+
151
+ ##### (2) Image-to-Video Evaluation
152
+
153
+ We also conducted extensive manual evaluations to evaluate the performance of the Image-to-Video model, and the results are presented in the table below. The results clearly indicate that **Wan2.1** outperforms both closed-source and open-source models.
154
+
155
+ <div align="center">
156
+ <img src="assets/i2v_res.png" alt="" style="width: 80%;" />
157
+ </div>
158
+
159
+
160
+ ## Computational Efficiency on Different GPUs
161
+
162
+ We test the computational efficiency of different **Wan2.1** models on different GPUs in the following table. The results are presented in the format: **Total time (s) / peak GPU memory (GB)**.
163
+
164
+
165
+ <div align="center">
166
+ <img src="assets/comp_effic.png" alt="" style="width: 80%;" />
167
+ </div>
168
+
169
+ > The parameter settings for the tests presented in this table are as follows:
170
+ > (1) For the 1.3B model on 8 GPUs, set `--ring_size 8` and `--ulysses_size 1`;
171
+ > (2) For the 14B model on 1 GPU, use `--offload_model True`;
172
+ > (3) For the 1.3B model on a single 4090 GPU, set `--offload_model True --t5_cpu`;
173
+ > (4) For all testings, no prompt extension was applied, meaning `--use_prompt_extend` was not enabled.
174
+
175
+ > 💡Note: T2V-14B is slower than I2V-14B because the former samples 50 steps while the latter uses 40 steps.
176
+
177
+
178
+ -------
179
+
180
+ ## Introduction of Wan2.1
181
+
182
+ **Wan2.1** is designed on the mainstream diffusion transformer paradigm, achieving significant advancements in generative capabilities through a series of innovations. These include our novel spatio-temporal variational autoencoder (VAE), scalable training strategies, large-scale data construction, and automated evaluation metrics. Collectively, these contributions enhance the model’s performance and versatility.
183
+
184
+
185
+ ##### (1) 3D Variational Autoencoders
186
+ We propose a novel 3D causal VAE architecture, termed **Wan-VAE** specifically designed for video generation. By combining multiple strategies, we improve spatio-temporal compression, reduce memory usage, and ensure temporal causality. **Wan-VAE** demonstrates significant advantages in performance efficiency compared to other open-source VAEs. Furthermore, our **Wan-VAE** can encode and decode unlimited-length 1080P videos without losing historical temporal information, making it particularly well-suited for video generation tasks.
187
+
188
+
189
+ <div align="center">
190
+ <img src="assets/video_vae_res.jpg" alt="" style="width: 80%;" />
191
+ </div>
192
+
193
+
194
+ ##### (2) Video Diffusion DiT
195
+
196
+ **Wan2.1** is designed using the Flow Matching framework within the paradigm of mainstream Diffusion Transformers. Our model's architecture uses the T5 Encoder to encode multilingual text input, with cross-attention in each transformer block embedding the text into the model structure. Additionally, we employ an MLP with a Linear layer and a SiLU layer to process the input time embeddings and predict six modulation parameters individually. This MLP is shared across all transformer blocks, with each block learning a distinct set of biases. Our experimental findings reveal a significant performance improvement with this approach at the same parameter scale.
197
+
198
+ <div align="center">
199
+ <img src="assets/video_dit_arch.jpg" alt="" style="width: 80%;" />
200
+ </div>
201
+
202
+
203
+ | Model | Dimension | Input Dimension | Output Dimension | Feedforward Dimension | Frequency Dimension | Number of Heads | Number of Layers |
204
+ |--------|-----------|-----------------|------------------|-----------------------|---------------------|-----------------|------------------|
205
+ | 1.3B | 1536 | 16 | 16 | 8960 | 256 | 12 | 30 |
206
+ | 14B | 5120 | 16 | 16 | 13824 | 256 | 40 | 40 |
207
+
208
+
209
+
210
+ ##### Data
211
+
212
+ We curated and deduplicated a candidate dataset comprising a vast amount of image and video data. During the data curation process, we designed a four-step data cleaning process, focusing on fundamental dimensions, visual quality and motion quality. Through the robust data processing pipeline, we can easily obtain high-quality, diverse, and large-scale training sets of images and videos.
213
+
214
+ ![figure1](assets/data_for_diff_stage.jpg "figure1")
215
+
216
+
217
+ ##### Comparisons to SOTA
218
+ We compared **Wan2.1** with leading open-source and closed-source models to evaluate the performance. Using our carefully designed set of 1,035 internal prompts, we tested across 14 major dimensions and 26 sub-dimensions. We then compute the total score by performing a weighted calculation on the scores of each dimension, utilizing weights derived from human preferences in the matching process. The detailed results are shown in the table below. These results demonstrate our model's superior performance compared to both open-source and closed-source models.
219
+
220
+ ![figure1](assets/vben_vs_sota.png "figure1")
221
+
222
+
223
+ ## Citation
224
+ If you find our work helpful, please cite us.
225
+
226
+ ```
227
+ @article{wan2025,
228
+ title={Wan: Open and Advanced Large-Scale Video Generative Models},
229
+ author={WanTeam and Ang Wang and Baole Ai and Bin Wen and Chaojie Mao and Chen-Wei Xie and Di Chen and Feiwu Yu and Haiming Zhao and Jianxiao Yang and Jianyuan Zeng and Jiayu Wang and Jingfeng Zhang and Jingren Zhou and Jinkai Wang and Jixuan Chen and Kai Zhu and Kang Zhao and Keyu Yan and Lianghua Huang and Mengyang Feng and Ningyi Zhang and Pandeng Li and Pingyu Wu and Ruihang Chu and Ruili Feng and Shiwei Zhang and Siyang Sun and Tao Fang and Tianxing Wang and Tianyi Gui and Tingyu Weng and Tong Shen and Wei Lin and Wei Wang and Wei Wang and Wenmeng Zhou and Wente Wang and Wenting Shen and Wenyuan Yu and Xianzhong Shi and Xiaoming Huang and Xin Xu and Yan Kou and Yangyu Lv and Yifei Li and Yijing Liu and Yiming Wang and Yingya Zhang and Yitong Huang and Yong Li and You Wu and Yu Liu and Yulin Pan and Yun Zheng and Yuntao Hong and Yupeng Shi and Yutong Feng and Zeyinzi Jiang and Zhen Han and Zhi-Fan Wu and Ziyu Liu},
230
+ journal = {arXiv preprint arXiv:2503.20314},
231
+ year={2025}
232
+ }
233
+ ```
234
+
235
+ ## License Agreement
236
+ The models in this repository are licensed under the Apache 2.0 License. We claim no rights over the your generated contents, granting you the freedom to use them while ensuring that your usage complies with the provisions of this license. You are fully accountable for your use of the models, which must not involve sharing any content that violates applicable laws, causes harm to individuals or groups, disseminates personal information intended for harm, spreads misinformation, or targets vulnerable populations. For a complete list of restrictions and details regarding your rights, please refer to the full text of the [license](LICENSE.txt).
237
+
238
+
239
+ ## Acknowledgements
240
+
241
+ We would like to thank the contributors to the [SD3](https://huggingface.co/stabilityai/stable-diffusion-3-medium), [Qwen](https://huggingface.co/Qwen), [umt5-xxl](https://huggingface.co/google/umt5-xxl), [diffusers](https://github.com/huggingface/diffusers) and [HuggingFace](https://huggingface.co) repositories, for their open research.
242
+
243
+
244
+
245
+ ## Contact Us
246
+ If you would like to leave a message to our research or product teams, feel free to join our [Discord](https://discord.gg/AKNgpMK4Yj) or [WeChat groups](https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg)!
docs/wan/README-for-Wan2.1-I2V-14B-480P-diffusers.md ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - zh
6
+ pipeline_tag: image-to-video
7
+ library_name: diffusers
8
+ tags:
9
+ - video
10
+ - video-generation
11
+ ---
12
+ # Wan2.1
13
+
14
+ <p align="center">
15
+ <img src="assets/logo.png" width="400"/>
16
+ <p>
17
+
18
+ <p align="center">
19
+ 💜 <a href=""><b>Wan</b></a> &nbsp&nbsp | &nbsp&nbsp 🖥️ <a href="https://github.com/Wan-Video/Wan2.1">GitHub</a> &nbsp&nbsp | &nbsp&nbsp🤗 <a href="https://huggingface.co/Wan-AI/">Hugging Face</a>&nbsp&nbsp | &nbsp&nbsp🤖 <a href="https://modelscope.cn/organization/Wan-AI">ModelScope</a>&nbsp&nbsp | &nbsp&nbsp 📑 <a href="">Paper (Coming soon)</a> &nbsp&nbsp | &nbsp&nbsp 📑 <a href="https://wanxai.com">Blog</a> &nbsp&nbsp | &nbsp&nbsp💬 <a href="https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg">WeChat Group</a>&nbsp&nbsp | &nbsp&nbsp 📖 <a href="https://discord.gg/p5XbdQV7">Discord</a>&nbsp&nbsp
20
+ <br>
21
+
22
+ -----
23
+
24
+ [**Wan: Open and Advanced Large-Scale Video Generative Models**]() <be>
25
+
26
+ In this repository, we present **Wan2.1**, a comprehensive and open suite of video foundation models that pushes the boundaries of video generation. **Wan2.1** offers these key features:
27
+ - 👍 **SOTA Performance**: **Wan2.1** consistently outperforms existing open-source models and state-of-the-art commercial solutions across multiple benchmarks.
28
+ - 👍 **Supports Consumer-grade GPUs**: The T2V-1.3B model requires only 8.19 GB VRAM, making it compatible with almost all consumer-grade GPUs. It can generate a 5-second 480P video on an RTX 4090 in about 4 minutes (without optimization techniques like quantization). Its performance is even comparable to some closed-source models.
29
+ - 👍 **Multiple Tasks**: **Wan2.1** excels in Text-to-Video, Image-to-Video, Video Editing, Text-to-Image, and Video-to-Audio, advancing the field of video generation.
30
+ - 👍 **Visual Text Generation**: **Wan2.1** is the first video model capable of generating both Chinese and English text, featuring robust text generation that enhances its practical applications.
31
+ - 👍 **Powerful Video VAE**: **Wan-VAE** delivers exceptional efficiency and performance, encoding and decoding 1080P videos of any length while preserving temporal information, making it an ideal foundation for video and image generation.
32
+
33
+
34
+ This repo contains our I2V-14B model, which is capable of generating 480P videos, offering advantages in terms of fast generation and excellent quality.
35
+
36
+
37
+ ## Video Demos
38
+
39
+ <div align="center">
40
+ <video width="80%" controls>
41
+ <source src="https://cloud.video.taobao.com/vod/Jth64Y7wNoPcJki_Bo1ZJTDBvNjsgjlVKsNs05Fqfps.mp4" type="video/mp4">
42
+ Your browser does not support the video tag.
43
+ </video>
44
+ </div>
45
+
46
+ ## 🔥 Latest News!!
47
+
48
+ * Feb 25, 2025: 👋 We've released the inference code and weights of Wan2.1.
49
+
50
+
51
+ ## 📑 Todo List
52
+ - Wan2.1 Text-to-Video
53
+ - [x] Multi-GPU Inference code of the 14B and 1.3B models
54
+ - [x] Checkpoints of the 14B and 1.3B models
55
+ - [x] Gradio demo
56
+ - [x] Diffusers integration
57
+ - [ ] ComfyUI integration
58
+ - Wan2.1 Image-to-Video
59
+ - [x] Multi-GPU Inference code of the 14B model
60
+ - [x] Checkpoints of the 14B model
61
+ - [x] Gradio demo
62
+ - [x] Diffusers integration
63
+ - [ ] ComfyUI integration
64
+
65
+
66
+ ## Quickstart
67
+
68
+ #### Installation
69
+ Clone the repo:
70
+ ```
71
+ git clone https://github.com/Wan-Video/Wan2.1.git
72
+ cd Wan2.1
73
+ ```
74
+
75
+ Install dependencies:
76
+ ```
77
+ # Ensure torch >= 2.4.0
78
+ pip install -r requirements.txt
79
+ ```
80
+
81
+
82
+ #### Model Download
83
+
84
+ | Models | Download Link | Notes |
85
+ | --------------|-------------------------------------------------------------------------------|-------------------------------|
86
+ | T2V-14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-T2V-14B) | Supports both 480P and 720P
87
+ | I2V-14B-720P | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-I2V-14B-720P) | Supports 720P
88
+ | I2V-14B-480P | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-480P) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-I2V-14B-480P) | Supports 480P
89
+ | T2V-1.3B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-T2V-1.3B) | Supports 480P
90
+
91
+ > 💡Note: The 1.3B model is capable of generating videos at 720P resolution. However, due to limited training at this resolution, the results are generally less stable compared to 480P. For optimal performance, we recommend using 480P resolution.
92
+
93
+
94
+ Download models using 🤗 huggingface-cli:
95
+ ```
96
+ pip install "huggingface_hub[cli]"
97
+ huggingface-cli download Wan-AI/Wan2.1-I2V-14B-480P-Diffusers --local-dir ./Wan2.1-I2V-14B-480P-Diffusers
98
+ ```
99
+
100
+ Download models using 🤖 modelscope-cli:
101
+ ```
102
+ pip install modelscope
103
+ modelscope download Wan-AI/Wan2.1-I2V-14B-480P-Diffusers --local_dir ./Wan2.1-I2V-14B-480P-Diffusers
104
+ ```
105
+
106
+ #### Run Image-to-Video Generation
107
+
108
+ Similar to Text-to-Video, Image-to-Video is also divided into processes with and without the prompt extension step. The specific parameters and their corresponding settings are as follows:
109
+ <table>
110
+ <thead>
111
+ <tr>
112
+ <th rowspan="2">Task</th>
113
+ <th colspan="2">Resolution</th>
114
+ <th rowspan="2">Model</th>
115
+ </tr>
116
+ <tr>
117
+ <th>480P</th>
118
+ <th>720P</th>
119
+ </tr>
120
+ </thead>
121
+ <tbody>
122
+ <tr>
123
+ <td>i2v-14B</td>
124
+ <td style="color: green;">❌</td>
125
+ <td style="color: green;">✔️</td>
126
+ <td>Wan2.1-I2V-14B-720P</td>
127
+ </tr>
128
+ <tr>
129
+ <td>i2v-14B</td>
130
+ <td style="color: green;">✔️</td>
131
+ <td style="color: red;">❌</td>
132
+ <td>Wan2.1-T2V-14B-480P</td>
133
+ </tr>
134
+ </tbody>
135
+ </table>
136
+
137
+
138
+ ##### (1) Without Prompt Extention
139
+
140
+ - Single-GPU inference
141
+ ```
142
+ python generate.py --task i2v-14B --size 832*480 --ckpt_dir ./Wan2.1-I2V-14B-480P --image examples/i2v_input.JPG --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
143
+ ```
144
+
145
+ > 💡For the Image-to-Video task, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
146
+
147
+ - Multi-GPU inference using FSDP + xDiT USP
148
+
149
+ ```
150
+ pip install "xfuser>=0.4.1"
151
+ torchrun --nproc_per_node=8 generate.py --task i2v-14B --size 832*480 --ckpt_dir ./Wan2.1-I2V-14B-480P --image examples/i2v_input.JPG --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
152
+ ```
153
+
154
+ Wan can also be run directly using 🤗 Diffusers!
155
+
156
+ ```python
157
+ import torch
158
+ import numpy as np
159
+ from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
160
+ from diffusers.utils import export_to_video, load_image
161
+ from transformers import CLIPVisionModel
162
+
163
+ # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
164
+ model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
165
+ image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
166
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
167
+ pipe = WanImageToVideoPipeline.from_pretrained(model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16)
168
+ pipe.to("cuda")
169
+
170
+ image = load_image(
171
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
172
+ )
173
+ max_area = 480 * 832
174
+ aspect_ratio = image.height / image.width
175
+ mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
176
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
177
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
178
+ image = image.resize((width, height))
179
+ prompt = (
180
+ "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
181
+ "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
182
+ )
183
+ 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"
184
+
185
+ output = pipe(
186
+ image=image, prompt=prompt, negative_prompt=negative_prompt, height=height, width=width, num_frames=81, guidance_scale=5.0
187
+ ).frames[0]
188
+ export_to_video(output, "output.mp4", fps=16)
189
+ ```
190
+
191
+ ##### (2) Using Prompt Extention
192
+
193
+ Run with local prompt extention using `Qwen/Qwen2.5-VL-7B-Instruct`:
194
+ ```
195
+ python generate.py --task i2v-14B --size 832*480 --ckpt_dir ./Wan2.1-I2V-14B-480P --image examples/i2v_input.JPG --use_prompt_extend --prompt_extend_model Qwen/Qwen2.5-VL-7B-Instruct --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
196
+ ```
197
+
198
+ Run with remote prompt extention using `dashscope`:
199
+ ```
200
+ DASH_API_KEY=your_key python generate.py --task i2v-14B --size 832*480 --ckpt_dir ./Wan2.1-I2V-14B-480P --image examples/i2v_input.JPG --use_prompt_extend --prompt_extend_method 'dashscope' --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
201
+ ```
202
+
203
+ ##### (3) Runing local gradio
204
+
205
+ ```
206
+ cd gradio
207
+ # if one only uses 480P model in gradio
208
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_480p ./Wan2.1-I2V-14B-480P
209
+
210
+ # if one only uses 720P model in gradio
211
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_720p ./Wan2.1-I2V-14B-720P
212
+
213
+ # if one uses both 480P and 720P models in gradio
214
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_480p ./Wan2.1-I2V-14B-480P --ckpt_dir_720p ./Wan2.1-I2V-14B-720P
215
+ ```
216
+
217
+
218
+ ## Manual Evaluation
219
+
220
+ We conducted extensive manual evaluations to evaluate the performance of the Image-to-Video model, and the results are presented in the table below. The results clearly indicate that **Wan2.1** outperforms both closed-source and open-source models.
221
+
222
+ <div align="center">
223
+ <img src="assets/i2v_res.png" alt="" style="width: 80%;" />
224
+ </div>
225
+
226
+
227
+ ## Computational Efficiency on Different GPUs
228
+
229
+ We test the computational efficiency of different **Wan2.1** models on different GPUs in the following table. The results are presented in the format: **Total time (s) / peak GPU memory (GB)**.
230
+
231
+
232
+ <div align="center">
233
+ <img src="assets/comp_effic.png" alt="" style="width: 80%;" />
234
+ </div>
235
+
236
+ > The parameter settings for the tests presented in this table are as follows:
237
+ > (1) For the 1.3B model on 8 GPUs, set `--ring_size 8` and `--ulysses_size 1`;
238
+ > (2) For the 14B model on 1 GPU, use `--offload_model True`;
239
+ > (3) For the 1.3B model on a single 4090 GPU, set `--offload_model True --t5_cpu`;
240
+ > (4) For all testings, no prompt extension was applied, meaning `--use_prompt_extend` was not enabled.
241
+
242
+ -------
243
+
244
+ ## Introduction of Wan2.1
245
+
246
+ **Wan2.1** is designed on the mainstream diffusion transformer paradigm, achieving significant advancements in generative capabilities through a series of innovations. These include our novel spatio-temporal variational autoencoder (VAE), scalable training strategies, large-scale data construction, and automated evaluation metrics. Collectively, these contributions enhance the model’s performance and versatility.
247
+
248
+
249
+ ##### (1) 3D Variational Autoencoders
250
+ We propose a novel 3D causal VAE architecture, termed **Wan-VAE** specifically designed for video generation. By combining multiple strategies, we improve spatio-temporal compression, reduce memory usage, and ensure temporal causality. **Wan-VAE** demonstrates significant advantages in performance efficiency compared to other open-source VAEs. Furthermore, our **Wan-VAE** can encode and decode unlimited-length 1080P videos without losing historical temporal information, making it particularly well-suited for video generation tasks.
251
+
252
+
253
+ <div align="center">
254
+ <img src="assets/video_vae_res.jpg" alt="" style="width: 80%;" />
255
+ </div>
256
+
257
+
258
+ ##### (2) Video Diffusion DiT
259
+
260
+ **Wan2.1** is designed using the Flow Matching framework within the paradigm of mainstream Diffusion Transformers. Our model's architecture uses the T5 Encoder to encode multilingual text input, with cross-attention in each transformer block embedding the text into the model structure. Additionally, we employ an MLP with a Linear layer and a SiLU layer to process the input time embeddings and predict six modulation parameters individually. This MLP is shared across all transformer blocks, with each block learning a distinct set of biases. Our experimental findings reveal a significant performance improvement with this approach at the same parameter scale.
261
+
262
+ <div align="center">
263
+ <img src="assets/video_dit_arch.jpg" alt="" style="width: 80%;" />
264
+ </div>
265
+
266
+
267
+ | Model | Dimension | Input Dimension | Output Dimension | Feedforward Dimension | Frequency Dimension | Number of Heads | Number of Layers |
268
+ |--------|-----------|-----------------|------------------|-----------------------|---------------------|-----------------|------------------|
269
+ | 1.3B | 1536 | 16 | 16 | 8960 | 256 | 12 | 30 |
270
+ | 14B | 5120 | 16 | 16 | 13824 | 256 | 40 | 40 |
271
+
272
+
273
+
274
+ ##### Data
275
+
276
+ We curated and deduplicated a candidate dataset comprising a vast amount of image and video data. During the data curation process, we designed a four-step data cleaning process, focusing on fundamental dimensions, visual quality and motion quality. Through the robust data processing pipeline, we can easily obtain high-quality, diverse, and large-scale training sets of images and videos.
277
+
278
+ ![figure1](assets/data_for_diff_stage.jpg "figure1")
279
+
280
+
281
+ ##### Comparisons to SOTA
282
+ We compared **Wan2.1** with leading open-source and closed-source models to evaluate the performace. Using our carefully designed set of 1,035 internal prompts, we tested across 14 major dimensions and 26 sub-dimensions. We then compute the total score by performing a weighted calculation on the scores of each dimension, utilizing weights derived from human preferences in the matching process. The detailed results are shown in the table below. These results demonstrate our model's superior performance compared to both open-source and closed-source models.
283
+
284
+ ![figure1](assets/vben_vs_sota.png "figure1")
285
+
286
+
287
+ ## Citation
288
+ If you find our work helpful, please cite us.
289
+
290
+ ```
291
+ @article{wan2.1,
292
+ title = {Wan: Open and Advanced Large-Scale Video Generative Models},
293
+ author = {Wan Team},
294
+ journal = {},
295
+ year = {2025}
296
+ }
297
+ ```
298
+
299
+ ## License Agreement
300
+ The models in this repository are licensed under the Apache 2.0 License. We claim no rights over the your generate contents, granting you the freedom to use them while ensuring that your usage complies with the provisions of this license. You are fully accountable for your use of the models, which must not involve sharing any content that violates applicable laws, causes harm to individuals or groups, disseminates personal information intended for harm, spreads misinformation, or targets vulnerable populations. For a complete list of restrictions and details regarding your rights, please refer to the full text of the [license](LICENSE.txt).
301
+
302
+
303
+ ## Acknowledgements
304
+
305
+ We would like to thank the contributors to the [SD3](https://huggingface.co/stabilityai/stable-diffusion-3-medium), [Qwen](https://huggingface.co/Qwen), [umt5-xxl](https://huggingface.co/google/umt5-xxl), [diffusers](https://github.com/huggingface/diffusers) and [HuggingFace](https://huggingface.co) repositories, for their open research.
306
+
307
+
308
+
309
+ ## Contact Us
310
+ If you would like to leave a message to our research or product teams, feel free to join our [Discord](https://discord.gg/p5XbdQV7) or [WeChat groups](https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg)!
docs/wan/README-for-Wan2.1-I2V-14B-720P-diffusers.md ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ - zh
6
+ pipeline_tag: image-to-video
7
+ library_name: diffusers
8
+ tags:
9
+ - video
10
+ - video genration
11
+ ---
12
+ # Wan2.1
13
+
14
+ <p align="center">
15
+ <img src="assets/logo.png" width="400"/>
16
+ <p>
17
+
18
+ <p align="center">
19
+ 💜 <a href=""><b>Wan</b></a> &nbsp&nbsp | &nbsp&nbsp 🖥️ <a href="https://github.com/Wan-Video/Wan2.1">GitHub</a> &nbsp&nbsp | &nbsp&nbsp🤗 <a href="https://huggingface.co/Wan-AI/">Hugging Face</a>&nbsp&nbsp | &nbsp&nbsp🤖 <a href="https://modelscope.cn/organization/Wan-AI">ModelScope</a>&nbsp&nbsp | &nbsp&nbsp 📑 <a href="">Paper (Coming soon)</a> &nbsp&nbsp | &nbsp&nbsp 📑 <a href="https://wanxai.com">Blog</a> &nbsp&nbsp | &nbsp&nbsp💬 <a href="https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg">WeChat Group</a>&nbsp&nbsp | &nbsp&nbsp 📖 <a href="https://discord.gg/p5XbdQV7">Discord</a>&nbsp&nbsp
20
+ <br>
21
+
22
+ -----
23
+
24
+ [**Wan: Open and Advanced Large-Scale Video Generative Models**]() <be>
25
+
26
+ In this repository, we present **Wan2.1**, a comprehensive and open suite of video foundation models that pushes the boundaries of video generation. **Wan2.1** offers these key features:
27
+ - 👍 **SOTA Performance**: **Wan2.1** consistently outperforms existing open-source models and state-of-the-art commercial solutions across multiple benchmarks.
28
+ - 👍 **Supports Consumer-grade GPUs**: The T2V-1.3B model requires only 8.19 GB VRAM, making it compatible with almost all consumer-grade GPUs. It can generate a 5-second 480P video on an RTX 4090 in about 4 minutes (without optimization techniques like quantization). Its performance is even comparable to some closed-source models.
29
+ - 👍 **Multiple Tasks**: **Wan2.1** excels in Text-to-Video, Image-to-Video, Video Editing, Text-to-Image, and Video-to-Audio, advancing the field of video generation.
30
+ - 👍 **Visual Text Generation**: **Wan2.1** is the first video model capable of generating both Chinese and English text, featuring robust text generation that enhances its practical applications.
31
+ - 👍 **Powerful Video VAE**: **Wan-VAE** delivers exceptional efficiency and performance, encoding and decoding 1080P videos of any length while preserving temporal information, making it an ideal foundation for video and image generation.
32
+
33
+
34
+ This repository contains our I2V-14B model, which is capable of generating 720P high-definition videos. After thousands of rounds of human evaluations, this model has outperformed both closed-source and open-source alternatives, achieving state-of-the-art performance.
35
+
36
+
37
+ ## Video Demos
38
+
39
+ <div align="center">
40
+ <video width="80%" controls>
41
+ <source src="https://cloud.video.taobao.com/vod/Jth64Y7wNoPcJki_Bo1ZJTDBvNjsgjlVKsNs05Fqfps.mp4" type="video/mp4">
42
+ Your browser does not support the video tag.
43
+ </video>
44
+ </div>
45
+
46
+ ## 🔥 Latest News!!
47
+
48
+ * Feb 25, 2025: 👋 We've released the inference code and weights of Wan2.1.
49
+
50
+
51
+ ## 📑 Todo List
52
+ - Wan2.1 Text-to-Video
53
+ - [x] Multi-GPU Inference code of the 14B and 1.3B models
54
+ - [x] Checkpoints of the 14B and 1.3B models
55
+ - [x] Gradio demo
56
+ - [x] Diffusers integration
57
+ - [ ] ComfyUI integration
58
+ - Wan2.1 Image-to-Video
59
+ - [x] Multi-GPU Inference code of the 14B model
60
+ - [x] Checkpoints of the 14B model
61
+ - [x] Gradio demo
62
+ - [x] Diffusers integration
63
+ - [ ] ComfyUI integration
64
+
65
+
66
+ ## Quickstart
67
+
68
+ #### Installation
69
+ Clone the repo:
70
+ ```
71
+ git clone https://github.com/Wan-Video/Wan2.1.git
72
+ cd Wan2.1
73
+ ```
74
+
75
+ Install dependencies:
76
+ ```
77
+ # Ensure torch >= 2.4.0
78
+ pip install -r requirements.txt
79
+ ```
80
+
81
+
82
+ #### Model Download
83
+
84
+ | Models | Download Link | Notes |
85
+ | --------------|-------------------------------------------------------------------------------|-------------------------------|
86
+ | T2V-14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-T2V-14B) | Supports both 480P and 720P
87
+ | I2V-14B-720P | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-I2V-14B-720P) | Supports 720P
88
+ | I2V-14B-480P | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-480P) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-I2V-14B-480P) | Supports 480P
89
+ | T2V-1.3B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-T2V-1.3B) | Supports 480P
90
+
91
+ > 💡Note: The 1.3B model is capable of generating videos at 720P resolution. However, due to limited training at this resolution, the results are generally less stable compared to 480P. For optimal performance, we recommend using 480P resolution.
92
+
93
+
94
+ Download models using 🤗 huggingface-cli:
95
+ ```
96
+ pip install "huggingface_hub[cli]"
97
+ huggingface-cli download Wan-AI/Wan2.1-I2V-14B-720P-Diffusers --local-dir ./Wan2.1-I2V-14B-720P-Diffusers
98
+ ```
99
+
100
+ Download models using 🤖 modelscope-cli:
101
+ ```
102
+ pip install modelscope
103
+ modelscope download Wan-AI/Wan2.1-I2V-14B-720P-Diffusers --local_dir ./Wan2.1-I2V-14B-720P-Diffusers
104
+ ```
105
+
106
+ #### Run Image-to-Video Generation
107
+
108
+ Similar to Text-to-Video, Image-to-Video is also divided into processes with and without the prompt extension step. The specific parameters and their corresponding settings are as follows:
109
+ <table>
110
+ <thead>
111
+ <tr>
112
+ <th rowspan="2">Task</th>
113
+ <th colspan="2">Resolution</th>
114
+ <th rowspan="2">Model</th>
115
+ </tr>
116
+ <tr>
117
+ <th>480P</th>
118
+ <th>720P</th>
119
+ </tr>
120
+ </thead>
121
+ <tbody>
122
+ <tr>
123
+ <td>i2v-14B</td>
124
+ <td style="color: green;">❌</td>
125
+ <td style="color: green;">✔️</td>
126
+ <td>Wan2.1-I2V-14B-720P</td>
127
+ </tr>
128
+ <tr>
129
+ <td>i2v-14B</td>
130
+ <td style="color: green;">✔️</td>
131
+ <td style="color: red;">❌</td>
132
+ <td>Wan2.1-T2V-14B-480P</td>
133
+ </tr>
134
+ </tbody>
135
+ </table>
136
+
137
+
138
+ ##### (1) Without Prompt Extention
139
+
140
+ - Single-GPU inference
141
+ ```
142
+ python generate.py --task i2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-I2V-14B-720P --image examples/i2v_input.JPG --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
143
+ ```
144
+
145
+ > 💡For the Image-to-Video task, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
146
+
147
+ - Multi-GPU inference using FSDP + xDiT USP
148
+
149
+ ```
150
+ pip install "xfuser>=0.4.1"
151
+ torchrun --nproc_per_node=8 generate.py --task i2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-I2V-14B-720P --image examples/i2v_input.JPG --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
152
+ ```
153
+
154
+ Wan can also be run directly using 🤗 Diffusers!
155
+
156
+ ```python
157
+ import torch
158
+ import numpy as np
159
+ from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
160
+ from diffusers.utils import export_to_video, load_image
161
+ from transformers import CLIPVisionModel
162
+
163
+ # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
164
+ model_id = "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers"
165
+ image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
166
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
167
+ pipe = WanImageToVideoPipeline.from_pretrained(model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16)
168
+ pipe.to("cuda")
169
+
170
+ image = load_image(
171
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
172
+ )
173
+ max_area = 720 * 1280
174
+ aspect_ratio = image.height / image.width
175
+ mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
176
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
177
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
178
+ image = image.resize((width, height))
179
+ prompt = (
180
+ "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
181
+ "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
182
+ )
183
+ 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"
184
+
185
+ output = pipe(
186
+ image=image, prompt=prompt, negative_prompt=negative_prompt, height=height, width=width, num_frames=81, guidance_scale=5.0
187
+ ).frames[0]
188
+ export_to_video(output, "output.mp4", fps=16)
189
+ ```
190
+
191
+ ##### (2) Using Prompt Extention
192
+
193
+
194
+ Run with local prompt extention using `Qwen/Qwen2.5-VL-7B-Instruct`:
195
+ ```
196
+ python generate.py --task i2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-I2V-14B-720P --image examples/i2v_input.JPG --use_prompt_extend --prompt_extend_model Qwen/Qwen2.5-VL-7B-Instruct --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
197
+ ```
198
+
199
+ Run with remote prompt extention using `dashscope`:
200
+ ```
201
+ DASH_API_KEY=your_key python generate.py --task i2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-I2V-14B-720P --image examples/i2v_input.JPG --use_prompt_extend --prompt_extend_method 'dashscope' --prompt "Summer beach vacation style, a white cat wearing sunglasses sits on a surfboard. The fluffy-furred feline gazes directly at the camera with a relaxed expression. Blurred beach scenery forms the background featuring crystal-clear waters, distant green hills, and a blue sky dotted with white clouds. The cat assumes a naturally relaxed posture, as if savoring the sea breeze and warm sunlight. A close-up shot highlights the feline's intricate details and the refreshing atmosphere of the seaside."
202
+ ```
203
+
204
+ ##### (3) Runing local gradio
205
+
206
+ ```
207
+ cd gradio
208
+ # if one only uses 480P model in gradio
209
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_480p ./Wan2.1-I2V-14B-480P
210
+
211
+ # if one only uses 720P model in gradio
212
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_720p ./Wan2.1-I2V-14B-720P
213
+
214
+ # if one uses both 480P and 720P models in gradio
215
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_480p ./Wan2.1-I2V-14B-480P --ckpt_dir_720p ./Wan2.1-I2V-14B-720P
216
+ ```
217
+
218
+
219
+ ## Manual Evaluation
220
+
221
+ We conducted extensive manual evaluations to evaluate the performance of the Image-to-Video model, and the results are presented in the table below. The results clearly indicate that **Wan2.1** outperforms both closed-source and open-source models.
222
+
223
+ <div align="center">
224
+ <img src="assets/i2v_res.png" alt="" style="width: 80%;" />
225
+ </div>
226
+
227
+
228
+ ## Computational Efficiency on Different GPUs
229
+
230
+ We test the computational efficiency of different **Wan2.1** models on different GPUs in the following table. The results are presented in the format: **Total time (s) / peak GPU memory (GB)**.
231
+
232
+
233
+ <div align="center">
234
+ <img src="assets/comp_effic.png" alt="" style="width: 80%;" />
235
+ </div>
236
+
237
+ > The parameter settings for the tests presented in this table are as follows:
238
+ > (1) For the 1.3B model on 8 GPUs, set `--ring_size 8` and `--ulysses_size 1`;
239
+ > (2) For the 14B model on 1 GPU, use `--offload_model True`;
240
+ > (3) For the 1.3B model on a single 4090 GPU, set `--offload_model True --t5_cpu`;
241
+ > (4) For all testings, no prompt extension was applied, meaning `--use_prompt_extend` was not enabled.
242
+
243
+ -------
244
+
245
+ ## Introduction of Wan2.1
246
+
247
+ **Wan2.1** is designed on the mainstream diffusion transformer paradigm, achieving significant advancements in generative capabilities through a series of innovations. These include our novel spatio-temporal variational autoencoder (VAE), scalable training strategies, large-scale data construction, and automated evaluation metrics. Collectively, these contributions enhance the model’s performance and versatility.
248
+
249
+
250
+ ##### (1) 3D Variational Autoencoders
251
+ We propose a novel 3D causal VAE architecture, termed **Wan-VAE** specifically designed for video generation. By combining multiple strategies, we improve spatio-temporal compression, reduce memory usage, and ensure temporal causality. **Wan-VAE** demonstrates significant advantages in performance efficiency compared to other open-source VAEs. Furthermore, our **Wan-VAE** can encode and decode unlimited-length 1080P videos without losing historical temporal information, making it particularly well-suited for video generation tasks.
252
+
253
+
254
+ <div align="center">
255
+ <img src="assets/video_vae_res.jpg" alt="" style="width: 80%;" />
256
+ </div>
257
+
258
+
259
+ ##### (2) Video Diffusion DiT
260
+
261
+ **Wan2.1** is designed using the Flow Matching framework within the paradigm of mainstream Diffusion Transformers. Our model's architecture uses the T5 Encoder to encode multilingual text input, with cross-attention in each transformer block embedding the text into the model structure. Additionally, we employ an MLP with a Linear layer and a SiLU layer to process the input time embeddings and predict six modulation parameters individually. This MLP is shared across all transformer blocks, with each block learning a distinct set of biases. Our experimental findings reveal a significant performance improvement with this approach at the same parameter scale.
262
+
263
+ <div align="center">
264
+ <img src="assets/video_dit_arch.jpg" alt="" style="width: 80%;" />
265
+ </div>
266
+
267
+
268
+ | Model | Dimension | Input Dimension | Output Dimension | Feedforward Dimension | Frequency Dimension | Number of Heads | Number of Layers |
269
+ |--------|-----------|-----------------|------------------|-----------------------|---------------------|-----------------|------------------|
270
+ | 1.3B | 1536 | 16 | 16 | 8960 | 256 | 12 | 30 |
271
+ | 14B | 5120 | 16 | 16 | 13824 | 256 | 40 | 40 |
272
+
273
+
274
+
275
+ ##### Data
276
+
277
+ We curated and deduplicated a candidate dataset comprising a vast amount of image and video data. During the data curation process, we designed a four-step data cleaning process, focusing on fundamental dimensions, visual quality and motion quality. Through the robust data processing pipeline, we can easily obtain high-quality, diverse, and large-scale training sets of images and videos.
278
+
279
+ ![figure1](assets/data_for_diff_stage.jpg "figure1")
280
+
281
+
282
+ ##### Comparisons to SOTA
283
+ We compared **Wan2.1** with leading open-source and closed-source models to evaluate the performace. Using our carefully designed set of 1,035 internal prompts, we tested across 14 major dimensions and 26 sub-dimensions. We then compute the total score by performing a weighted calculation on the scores of each dimension, utilizing weights derived from human preferences in the matching process. The detailed results are shown in the table below. These results demonstrate our model's superior performance compared to both open-source and closed-source models.
284
+
285
+ ![figure1](assets/vben_vs_sota.png "figure1")
286
+
287
+
288
+ ## Citation
289
+ If you find our work helpful, please cite us.
290
+
291
+ ```
292
+ @article{wan2.1,
293
+ title = {Wan: Open and Advanced Large-Scale Video Generative Models},
294
+ author = {Wan Team},
295
+ journal = {},
296
+ year = {2025}
297
+ }
298
+ ```
299
+
300
+ ## License Agreement
301
+ The models in this repository are licensed under the Apache 2.0 License. We claim no rights over the your generate contents, granting you the freedom to use them while ensuring that your usage complies with the provisions of this license. You are fully accountable for your use of the models, which must not involve sharing any content that violates applicable laws, causes harm to individuals or groups, disseminates personal information intended for harm, spreads misinformation, or targets vulnerable populations. For a complete list of restrictions and details regarding your rights, please refer to the full text of the [license](LICENSE.txt).
302
+
303
+
304
+ ## Acknowledgements
305
+
306
+ We would like to thank the contributors to the [SD3](https://huggingface.co/stabilityai/stable-diffusion-3-medium), [Qwen](https://huggingface.co/Qwen), [umt5-xxl](https://huggingface.co/google/umt5-xxl), [diffusers](https://github.com/huggingface/diffusers) and [HuggingFace](https://huggingface.co) repositories, for their open research.
307
+
308
+
309
+
310
+ ## Contact Us
311
+ If you would like to leave a message to our research or product teams, feel free to join our [Discord](https://discord.gg/p5XbdQV7) or [WeChat groups](https://gw.alicdn.com/imgextra/i2/O1CN01tqjWFi1ByuyehkTSB_!!6000000000015-0-tps-611-1279.jpg)!
requirements.txt CHANGED
@@ -1,4 +1,9 @@
1
-
 
 
 
 
 
2
 
3
  # For GPU monitoring of NVIDIA chipsets
4
  pynvml
@@ -15,7 +20,7 @@ diffusers @ git+https://github.com/huggingface/diffusers.git@main
15
  imageio
16
  imageio-ffmpeg
17
 
18
- flash-attn @ https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.4cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
19
 
20
  # for youtube video download
21
  pytube
 
1
+ # we don't have a flash attention binary yet for Pytorch 2.7
2
+ # so we use pytorch 2.6
3
+ torch==2.6.0
4
+ torchvision==0.21.0
5
+ torchdata==0.1.0
6
+ torchao==0.9.0
7
 
8
  # For GPU monitoring of NVIDIA chipsets
9
  pynvml
 
20
  imageio
21
  imageio-ffmpeg
22
 
23
+ flash-attn @ https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.6cxx11abiFALSE-cp310-cp310-linux_x86_64.whl
24
 
25
  # for youtube video download
26
  pytube
vms/config.py CHANGED
@@ -232,6 +232,11 @@ MODEL_VERSIONS = {
232
  "name": "Wan 2.1 I2V 720p (image+text)",
233
  "type": "image-to-video",
234
  "description": "Image conditioning at 720p resolution"
 
 
 
 
 
235
  }
236
  },
237
  "ltx_video": {
 
232
  "name": "Wan 2.1 I2V 720p (image+text)",
233
  "type": "image-to-video",
234
  "description": "Image conditioning at 720p resolution"
235
+ },
236
+ "Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers": {
237
+ "name": "Wan 2.1 FLF2V 720p (frame conditioning)",
238
+ "type": "frame-to-video",
239
+ "description": "Frame conditioning (first/last frame to video) at 720p resolution"
240
  }
241
  },
242
  "ltx_video": {
vms/ui/project/services/previewing.py CHANGED
@@ -78,7 +78,8 @@ class PreviewingService:
78
  seed: int = -1,
79
  enable_cpu_offload: bool = True,
80
  fps: int = 16,
81
- conditioning_image: Optional[str] = None
 
82
  ) -> Tuple[Optional[str], str, str]:
83
  """Generate a video using the trained model"""
84
  try:
@@ -149,10 +150,15 @@ class PreviewingService:
149
  model_version = "hunyuanvideo-community/HunyuanVideo"
150
  log(f"No versions defined for model type, using default: {model_version}")
151
 
152
- # Check if this is an image-to-video model but no image was provided
153
  model_version_info = versions.get(model_version, {})
154
- if model_version_info.get("type") == "image-to-video" and not conditioning_image:
155
- return None, "Error: This model requires a conditioning image", log("Error: This model version requires a conditioning image but none was provided")
 
 
 
 
 
156
 
157
  log(f"Generating video with model type: {internal_model_type}")
158
  log(f"Using model version: {model_version}")
@@ -170,7 +176,7 @@ class PreviewingService:
170
  full_prompt, negative_prompt, width, height, num_frames,
171
  guidance_scale, flow_shift, lora_path, lora_scale,
172
  inference_steps, seed, enable_cpu_offload, fps, log,
173
- model_version, conditioning_image
174
  )
175
  elif internal_model_type == "ltx_video":
176
  return self.generate_ltx_video(
@@ -210,16 +216,18 @@ class PreviewingService:
210
  fps: int = 16,
211
  log_fn: Callable = print,
212
  model_version: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
213
- conditioning_image: Optional[str] = None
 
214
  ) -> Tuple[Optional[str], str, str]:
215
  """Generate video using Wan model"""
216
 
217
  try:
218
  import torch
219
  import numpy as np
220
- from diffusers import AutoencoderKLWan, WanPipeline
221
  from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
222
  from diffusers.utils import export_to_video
 
223
  from PIL import Image
224
  import os
225
 
@@ -241,17 +249,32 @@ class PreviewingService:
241
  generator = torch.Generator(device="cuda")
242
  generator = generator.manual_seed(seed)
243
 
 
 
 
 
 
244
  log_fn(f"Loading VAE from {model_version}...")
245
  vae = AutoencoderKLWan.from_pretrained(model_version, subfolder="vae", torch_dtype=torch.float32)
246
 
247
- log_fn(f"Loading transformer from {model_version}...")
248
- pipe = WanPipeline.from_pretrained(model_version, vae=vae, torch_dtype=torch.bfloat16)
249
-
250
- log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")
251
- pipe.scheduler = UniPCMultistepScheduler.from_config(
252
- pipe.scheduler.config,
253
- flow_shift=flow_shift
254
- )
 
 
 
 
 
 
 
 
 
 
255
 
256
  log_fn("Moving pipeline to CUDA device...")
257
  pipe.to("cuda")
@@ -274,27 +297,49 @@ class PreviewingService:
274
  log_fn("Starting video generation...")
275
  start_time.record()
276
 
277
- # Check if this is an image-to-video model
278
- is_i2v = "I2V" in model_version
279
 
280
- if is_i2v and conditioning_image:
281
- log_fn(f"Loading conditioning image from {conditioning_image}...")
282
- image = Image.open(conditioning_image).convert("RGB")
283
- image = image.resize((width, height))
284
 
285
- log_fn("Generating video with image conditioning...")
286
- output = pipe(
287
- prompt=prompt,
288
- negative_prompt=negative_prompt,
289
- image=image,
290
- height=height,
291
- width=width,
292
- num_frames=num_frames,
293
- guidance_scale=guidance_scale,
294
- num_inference_steps=inference_steps,
295
- cross_attention_kwargs={"scale": lora_scale},
296
- generator=generator,
297
- ).frames[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  else:
299
  log_fn("Generating video with text-only conditioning...")
300
  output = pipe(
 
78
  seed: int = -1,
79
  enable_cpu_offload: bool = True,
80
  fps: int = 16,
81
+ first_frame_image: Optional[str] = None,
82
+ last_frame_image: Optional[str] = None
83
  ) -> Tuple[Optional[str], str, str]:
84
  """Generate a video using the trained model"""
85
  try:
 
150
  model_version = "hunyuanvideo-community/HunyuanVideo"
151
  log(f"No versions defined for model type, using default: {model_version}")
152
 
153
+ # Check if this is an image-to-video or frame-to-video model but no image was provided
154
  model_version_info = versions.get(model_version, {})
155
+ if model_version_info.get("type") in ["image-to-video", "frame-to-video"] and not first_frame_image:
156
+ model_type_name = "frame conditioning" if model_version_info.get("type") == "frame-to-video" else "conditioning"
157
+ return None, f"Error: This model requires a {model_type_name} image", log(f"Error: This model version requires a {model_type_name} image but none was provided")
158
+
159
+ # Additional check for FLF2V models that require both first and last frame
160
+ if model_version_info.get("type") == "frame-to-video" and first_frame_image and not last_frame_image:
161
+ return None, "Error: FLF2V models require both first and last frame images", log("Error: FLF2V models require both first and last frame images but only first frame was provided")
162
 
163
  log(f"Generating video with model type: {internal_model_type}")
164
  log(f"Using model version: {model_version}")
 
176
  full_prompt, negative_prompt, width, height, num_frames,
177
  guidance_scale, flow_shift, lora_path, lora_scale,
178
  inference_steps, seed, enable_cpu_offload, fps, log,
179
+ model_version, first_frame_image, last_frame_image
180
  )
181
  elif internal_model_type == "ltx_video":
182
  return self.generate_ltx_video(
 
216
  fps: int = 16,
217
  log_fn: Callable = print,
218
  model_version: str = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
219
+ first_frame_image: Optional[str] = None,
220
+ last_frame_image: Optional[str] = None
221
  ) -> Tuple[Optional[str], str, str]:
222
  """Generate video using Wan model"""
223
 
224
  try:
225
  import torch
226
  import numpy as np
227
+ from diffusers import AutoencoderKLWan, WanPipeline, WanImageToVideoPipeline
228
  from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
229
  from diffusers.utils import export_to_video
230
+ from transformers import CLIPVisionModel
231
  from PIL import Image
232
  import os
233
 
 
249
  generator = torch.Generator(device="cuda")
250
  generator = generator.manual_seed(seed)
251
 
252
+ # Check if this is an I2V or FLF2V model that requires WanImageToVideoPipeline
253
+ is_i2v = "I2V" in model_version
254
+ is_flf2v = "FLF2V" in model_version
255
+ uses_image_pipeline = is_i2v or is_flf2v
256
+
257
  log_fn(f"Loading VAE from {model_version}...")
258
  vae = AutoencoderKLWan.from_pretrained(model_version, subfolder="vae", torch_dtype=torch.float32)
259
 
260
+ if uses_image_pipeline:
261
+ model_type_str = "FLF2V" if is_flf2v else "I2V"
262
+ log_fn(f"Loading image encoder for {model_type_str} model from {model_version}...")
263
+ image_encoder = CLIPVisionModel.from_pretrained(model_version, subfolder="image_encoder", torch_dtype=torch.float32)
264
+
265
+ log_fn(f"Loading WanImageToVideoPipeline from {model_version}...")
266
+ pipe = WanImageToVideoPipeline.from_pretrained(
267
+ model_version, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
268
+ )
269
+ else:
270
+ log_fn(f"Loading WanPipeline from {model_version}...")
271
+ pipe = WanPipeline.from_pretrained(model_version, vae=vae, torch_dtype=torch.bfloat16)
272
+
273
+ log_fn(f"Configuring scheduler with flow_shift={flow_shift}...")
274
+ pipe.scheduler = UniPCMultistepScheduler.from_config(
275
+ pipe.scheduler.config,
276
+ flow_shift=flow_shift
277
+ )
278
 
279
  log_fn("Moving pipeline to CUDA device...")
280
  pipe.to("cuda")
 
297
  log_fn("Starting video generation...")
298
  start_time.record()
299
 
300
+ # Generate video based on model type
 
301
 
302
+ if (is_i2v or is_flf2v) and first_frame_image:
303
+ log_fn(f"Loading first frame image from {first_frame_image}...")
304
+ first_frame = Image.open(first_frame_image).convert("RGB")
305
+ first_frame = first_frame.resize((width, height))
306
 
307
+ if is_flf2v:
308
+ log_fn("Generating video with frame conditioning (FLF2V)...")
309
+ if not last_frame_image:
310
+ return None, "Error: FLF2V model requires both first and last frame images", log_fn("Error: FLF2V model requires both first and last frame images")
311
+
312
+ log_fn(f"Loading last frame image from {last_frame_image}...")
313
+ last_frame = Image.open(last_frame_image).convert("RGB")
314
+ last_frame = last_frame.resize((width, height))
315
+
316
+ output = pipe(
317
+ prompt=prompt,
318
+ negative_prompt=negative_prompt,
319
+ image=first_frame,
320
+ last_image=last_frame,
321
+ height=height,
322
+ width=width,
323
+ num_frames=num_frames,
324
+ guidance_scale=guidance_scale,
325
+ num_inference_steps=inference_steps,
326
+ cross_attention_kwargs={"scale": lora_scale},
327
+ generator=generator,
328
+ ).frames[0]
329
+ else:
330
+ log_fn("Generating video with image conditioning...")
331
+ output = pipe(
332
+ prompt=prompt,
333
+ negative_prompt=negative_prompt,
334
+ image=first_frame,
335
+ height=height,
336
+ width=width,
337
+ num_frames=num_frames,
338
+ guidance_scale=guidance_scale,
339
+ num_inference_steps=inference_steps,
340
+ cross_attention_kwargs={"scale": lora_scale},
341
+ generator=generator,
342
+ ).frames[0]
343
  else:
344
  log_fn("Generating video with text-only conditioning...")
345
  output = pipe(
vms/ui/project/tabs/preview_tab.py CHANGED
@@ -103,8 +103,15 @@ class PreviewTab(BaseTab):
103
  )
104
 
105
  # Add image input for image-to-video models
106
- self.components["conditioning_image"] = gr.Image(
107
- label="Conditioning Image (for Image-to-Video models)",
 
 
 
 
 
 
 
108
  type="filepath",
109
  visible=False
110
  )
@@ -371,7 +378,8 @@ class PreviewTab(BaseTab):
371
  self.components["model_version"]
372
  ],
373
  outputs=[
374
- self.components["conditioning_image"]
 
375
  ]
376
  )
377
 
@@ -437,7 +445,8 @@ class PreviewTab(BaseTab):
437
  self.components["inference_steps"],
438
  self.components["enable_cpu_offload"],
439
  self.components["fps"],
440
- self.components["conditioning_image"],
 
441
  self.components["seed"],
442
  self.components["use_lora"]
443
  ],
@@ -452,11 +461,26 @@ class PreviewTab(BaseTab):
452
  """Update UI based on the selected model version"""
453
  model_version_type = self.get_model_version_type(model_type, model_version)
454
 
455
- # Show conditioning image input only for image-to-video models
456
- show_conditioning_image = model_version_type == "image-to-video"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
457
 
458
  return {
459
- self.components["conditioning_image"]: gr.Image(visible=show_conditioning_image)
 
460
  }
461
 
462
  def sync_model_type_and_versions(self) -> Tuple[str, str]:
@@ -607,7 +631,8 @@ class PreviewTab(BaseTab):
607
  inference_steps: int,
608
  enable_cpu_offload: bool,
609
  fps: int,
610
- conditioning_image: Optional[str] = None,
 
611
  seed: int = -1,
612
  use_lora: str = "Use LoRA model"
613
  ) -> Tuple[Optional[str], str, str]:
@@ -675,7 +700,8 @@ class PreviewTab(BaseTab):
675
  inference_steps=inference_steps,
676
  enable_cpu_offload=enable_cpu_offload,
677
  fps=fps,
678
- conditioning_image=conditioning_image,
 
679
  seed=seed
680
  )
681
 
 
103
  )
104
 
105
  # Add image input for image-to-video models
106
+ self.components["first_frame_image"] = gr.Image(
107
+ label="First Frame Image (for Image-to-Video models)",
108
+ type="filepath",
109
+ visible=False
110
+ )
111
+
112
+ # Add second image input for frame conditioning models (last frame)
113
+ self.components["last_frame_image"] = gr.Image(
114
+ label="Last Frame Image (for Frame conditioning models)",
115
  type="filepath",
116
  visible=False
117
  )
 
378
  self.components["model_version"]
379
  ],
380
  outputs=[
381
+ self.components["first_frame_image"],
382
+ self.components["last_frame_image"]
383
  ]
384
  )
385
 
 
445
  self.components["inference_steps"],
446
  self.components["enable_cpu_offload"],
447
  self.components["fps"],
448
+ self.components["first_frame_image"],
449
+ self.components["last_frame_image"],
450
  self.components["seed"],
451
  self.components["use_lora"]
452
  ],
 
461
  """Update UI based on the selected model version"""
462
  model_version_type = self.get_model_version_type(model_type, model_version)
463
 
464
+ # Show conditioning image input for image-to-video and frame-to-video models
465
+ show_conditioning_image = model_version_type in ["image-to-video", "frame-to-video"]
466
+
467
+ # Show last frame image input only for frame-to-video models
468
+ show_last_frame_image = model_version_type == "frame-to-video"
469
+
470
+ # Update labels based on model type
471
+ if model_version_type == "frame-to-video":
472
+ first_frame_label = "First Frame Image (for Frame conditioning models)"
473
+ last_frame_label = "Last Frame Image (for Frame conditioning models)"
474
+ elif model_version_type == "image-to-video":
475
+ first_frame_label = "Conditioning Image (for Image-to-Video models)"
476
+ last_frame_label = "Last Frame Image (for Frame conditioning models)"
477
+ else:
478
+ first_frame_label = "Conditioning Image (for Image-to-Video models)"
479
+ last_frame_label = "Last Frame Image (for Frame conditioning models)"
480
 
481
  return {
482
+ self.components["first_frame_image"]: gr.Image(visible=show_conditioning_image, label=first_frame_label),
483
+ self.components["last_frame_image"]: gr.Image(visible=show_last_frame_image, label=last_frame_label)
484
  }
485
 
486
  def sync_model_type_and_versions(self) -> Tuple[str, str]:
 
631
  inference_steps: int,
632
  enable_cpu_offload: bool,
633
  fps: int,
634
+ first_frame_image: Optional[str] = None,
635
+ last_frame_image: Optional[str] = None,
636
  seed: int = -1,
637
  use_lora: str = "Use LoRA model"
638
  ) -> Tuple[Optional[str], str, str]:
 
700
  inference_steps=inference_steps,
701
  enable_cpu_offload=enable_cpu_offload,
702
  fps=fps,
703
+ first_frame_image=first_frame_image,
704
+ last_frame_image=last_frame_image,
705
  seed=seed
706
  )
707