Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
4a3d698
1
Parent(s):
02bf03c
init
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- app.py +386 -0
- edit.py +486 -0
- generate.py +412 -0
- requirements.txt +19 -0
- video_list/bear_g.mp4 +3 -0
- video_list/blackswan.mp4 +3 -0
- video_list/cat_box.mp4 +3 -0
- video_list/cockatiel.mp4 +3 -0
- video_list/dog_flower_g.mp4 +3 -0
- video_list/girl_and_dog.mp4 +3 -0
- video_list/gym_woman.mp4 +3 -0
- video_list/jeep.mp4 +3 -0
- video_list/puppy.mp4 +3 -0
- video_list/rabbit.mp4 +3 -0
- video_list/sea_lion.mp4 +3 -0
- video_list/sea_turtle.mp4 +3 -0
- video_list/wolf.mp4 +3 -0
- video_list/woman.mp4 +3 -0
- wan/__init__.py +3 -0
- wan/__pycache__/__init__.cpython-310.pyc +0 -0
- wan/__pycache__/__init__.cpython-312.pyc +0 -0
- wan/__pycache__/image2video.cpython-310.pyc +0 -0
- wan/__pycache__/image2video.cpython-312.pyc +0 -0
- wan/__pycache__/text2video.cpython-310.pyc +0 -0
- wan/__pycache__/text2video.cpython-312.pyc +0 -0
- wan/configs/__init__.py +42 -0
- wan/configs/__pycache__/__init__.cpython-310.pyc +0 -0
- wan/configs/__pycache__/__init__.cpython-312.pyc +0 -0
- wan/configs/__pycache__/shared_config.cpython-310.pyc +0 -0
- wan/configs/__pycache__/shared_config.cpython-312.pyc +0 -0
- wan/configs/__pycache__/wan_i2v_14B.cpython-310.pyc +0 -0
- wan/configs/__pycache__/wan_i2v_14B.cpython-312.pyc +0 -0
- wan/configs/__pycache__/wan_t2v_14B.cpython-310.pyc +0 -0
- wan/configs/__pycache__/wan_t2v_14B.cpython-312.pyc +0 -0
- wan/configs/__pycache__/wan_t2v_1_3B.cpython-310.pyc +0 -0
- wan/configs/__pycache__/wan_t2v_1_3B.cpython-312.pyc +0 -0
- wan/configs/shared_config.py +19 -0
- wan/configs/wan_i2v_14B.py +35 -0
- wan/configs/wan_t2v_14B.py +29 -0
- wan/configs/wan_t2v_1_3B.py +29 -0
- wan/distributed/__init__.py +0 -0
- wan/distributed/__pycache__/__init__.cpython-310.pyc +0 -0
- wan/distributed/__pycache__/__init__.cpython-312.pyc +0 -0
- wan/distributed/__pycache__/fsdp.cpython-310.pyc +0 -0
- wan/distributed/__pycache__/fsdp.cpython-312.pyc +0 -0
- wan/distributed/__pycache__/xdit_context_parallel.cpython-310.pyc +0 -0
- wan/distributed/__pycache__/xdit_context_parallel.cpython-312.pyc +0 -0
- wan/distributed/fsdp.py +32 -0
- wan/distributed/xdit_context_parallel.py +420 -0
.gitattributes
CHANGED
@@ -30,6 +30,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
30 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
*.xz 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
|
|
|
30 |
*.tgz filter=lfs diff=lfs merge=lfs -text
|
31 |
*.wasm filter=lfs diff=lfs merge=lfs -text
|
32 |
*.xz filter=lfs diff=lfs merge=lfs -text
|
33 |
+
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
35 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
36 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import gradio as gr
|
3 |
+
import subprocess
|
4 |
+
import os
|
5 |
+
import sys
|
6 |
+
import datetime
|
7 |
+
import shutil
|
8 |
+
import time # Moved import time to the top for global access
|
9 |
+
import argparse
|
10 |
+
|
11 |
+
# --- Configuration ---
|
12 |
+
# !!! IMPORTANT: Ensure this path is correct for your environment !!!
|
13 |
+
CKPT_DIR = "./checkpoints/Wan2.1-T2V-1.3B"
|
14 |
+
EDIT_SCRIPT_PATH = "edit.py" # Assumes edit.py is in the same directory
|
15 |
+
OUTPUT_DIR = "gradio_outputs"
|
16 |
+
PYTHON_EXECUTABLE = sys.executable # Uses the same python that runs gradio
|
17 |
+
VIDEO_EXAMPLES_DIR = "video_list" # Directory for example videos
|
18 |
+
|
19 |
+
# Create output directory if it doesn't exist
|
20 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
21 |
+
os.makedirs(VIDEO_EXAMPLES_DIR, exist_ok=True) # Ensure video_list exists for clarity
|
22 |
+
|
23 |
+
def _parse_args():
|
24 |
+
parser = argparse.ArgumentParser(
|
25 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
26 |
+
)
|
27 |
+
parser.add_argument(
|
28 |
+
"--ckpt",
|
29 |
+
type=str,
|
30 |
+
default="./checkpoints/Wan2.1-T2V-1.3B",
|
31 |
+
help="The path to the checkpoint directory.")
|
32 |
+
|
33 |
+
return parser.parse_args()
|
34 |
+
|
35 |
+
def generate_safe_filename_part(text, max_len=20):
|
36 |
+
"""Generates a filesystem-safe string from text."""
|
37 |
+
if not text:
|
38 |
+
return "untitled"
|
39 |
+
safe_text = "".join(c if c.isalnum() or c in [' ', '_'] else '_' for c in text).strip()
|
40 |
+
safe_text = "_".join(safe_text.split()) # Replace spaces with underscores
|
41 |
+
return safe_text[:max_len]
|
42 |
+
|
43 |
+
def run_video_edit(source_video_path, source_prompt, target_prompt, source_words, target_words,
|
44 |
+
omega_value, n_max_value, n_avg_value, progress=gr.Progress(track_tqdm=True)):
|
45 |
+
if not source_video_path:
|
46 |
+
raise gr.Error("Please upload a source video.")
|
47 |
+
if not source_prompt:
|
48 |
+
raise gr.Error("Please provide a source prompt.")
|
49 |
+
if not target_prompt:
|
50 |
+
raise gr.Error("Please provide a target prompt (the 'prompt' for edit.py).")
|
51 |
+
# Allow empty source_words for additive edits
|
52 |
+
if source_words is None: # Check for None, as empty string is valid
|
53 |
+
raise gr.Error("Please provide source words (can be empty string for additions).")
|
54 |
+
if not target_words:
|
55 |
+
raise gr.Error("Please provide target words.")
|
56 |
+
|
57 |
+
progress(0, desc="Preparing for video editing...")
|
58 |
+
print(f"Source video received at: {source_video_path}")
|
59 |
+
print(f"Omega value: {omega_value}")
|
60 |
+
print(f"N_max value: {n_max_value}")
|
61 |
+
print(f"N_avg value: {n_avg_value}")
|
62 |
+
|
63 |
+
worse_avg_value = n_avg_value // 2
|
64 |
+
print(f"Calculated Worse_avg value: {worse_avg_value}")
|
65 |
+
|
66 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
67 |
+
src_words_fn = generate_safe_filename_part(source_words)
|
68 |
+
tar_words_fn = generate_safe_filename_part(target_words)
|
69 |
+
|
70 |
+
output_filename_base = f"{timestamp}_{src_words_fn}_to_{tar_words_fn}_omega{omega_value}_nmax{n_max_value}_navg{n_avg_value}"
|
71 |
+
output_video_path = os.path.join(OUTPUT_DIR, f"{output_filename_base}.mp4")
|
72 |
+
|
73 |
+
cmd = [
|
74 |
+
PYTHON_EXECUTABLE, EDIT_SCRIPT_PATH,
|
75 |
+
"--task", "t2v-1.3B",
|
76 |
+
"--size", "832*480",
|
77 |
+
"--base_seed", "42",
|
78 |
+
"--ckpt_dir", CKPT_DIR,
|
79 |
+
"--sample_solver", "unipc",
|
80 |
+
"--source_video_path", source_video_path,
|
81 |
+
"--source_prompt", source_prompt,
|
82 |
+
"--source_words", source_words, # Pass as is, even if empty
|
83 |
+
"--prompt", target_prompt,
|
84 |
+
"--target_words", target_words,
|
85 |
+
"--sample_guide_scale", "3.5",
|
86 |
+
"--tar_guide_scale", "10.5",
|
87 |
+
"--sample_shift", "12",
|
88 |
+
"--sample_steps", "50",
|
89 |
+
"--n_max", str(n_max_value),
|
90 |
+
"--n_min", "0",
|
91 |
+
"--n_avg", str(n_avg_value),
|
92 |
+
"--worse_avg", str(worse_avg_value),
|
93 |
+
"--omega", str(omega_value),
|
94 |
+
"--window_size", "11",
|
95 |
+
"--decay_factor", "0.25",
|
96 |
+
"--frame_num", "41",
|
97 |
+
"--save_file", output_video_path
|
98 |
+
]
|
99 |
+
|
100 |
+
print(f"Executing command: {' '.join(cmd)}")
|
101 |
+
progress(0.1, desc="Starting video editing process...")
|
102 |
+
|
103 |
+
try:
|
104 |
+
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, universal_newlines=True)
|
105 |
+
|
106 |
+
# Simulate progress
|
107 |
+
for i in range(10):
|
108 |
+
if process.poll() is not None:
|
109 |
+
break
|
110 |
+
progress(0.1 + i * 0.08, desc=f"Editing in progress... (simulated step {i+1}/10)")
|
111 |
+
time.sleep(1)
|
112 |
+
|
113 |
+
stdout, stderr = process.communicate()
|
114 |
+
|
115 |
+
progress(0.9, desc="Finalizing video...")
|
116 |
+
|
117 |
+
if process.returncode != 0:
|
118 |
+
print(f"Error during video editing:\nStdout:\n{stdout}\nStderr:\n{stderr}")
|
119 |
+
raise gr.Error(f"Video editing failed. Stderr: {stderr[:500]}")
|
120 |
+
|
121 |
+
print(f"Video editing successful. Output at: {output_video_path}")
|
122 |
+
if not os.path.exists(output_video_path):
|
123 |
+
print(f"Error: Output file {output_video_path} was not created.")
|
124 |
+
raise gr.Error(f"Output file not found, though script reported success. Stdout: {stdout}")
|
125 |
+
|
126 |
+
progress(1, desc="Video ready!")
|
127 |
+
return output_video_path
|
128 |
+
|
129 |
+
except FileNotFoundError:
|
130 |
+
progress(1, desc="Error")
|
131 |
+
print(f"Error: The script '{EDIT_SCRIPT_PATH}' or python executable '{PYTHON_EXECUTABLE}' was not found.")
|
132 |
+
raise gr.Error(f"Execution error: Ensure '{EDIT_SCRIPT_PATH}' and Python are correctly pathed.")
|
133 |
+
except Exception as e:
|
134 |
+
progress(1, desc="Error")
|
135 |
+
print(f"An unexpected error occurred: {e}")
|
136 |
+
raise gr.Error(f"An unexpected error: {str(e)}")
|
137 |
+
|
138 |
+
# --- Gradio UI Definition ---
|
139 |
+
|
140 |
+
# Define all examples to be loaded
|
141 |
+
examples_to_load_definitions = [
|
142 |
+
{ # Original bear_g example (corresponds to bear_g_03 in YAML)
|
143 |
+
"video_base_name": "bear_g",
|
144 |
+
"src_prompt": "A large brown bear is walking slowly across a rocky terrain in a zoo enclosure, surrounded by stone walls and scattered greenery. The camera remains fixed, capturing the bear's deliberate movements.",
|
145 |
+
"tar_prompt": "A large dinosaur is walking slowly across a rocky terrain in a zoo enclosure, surrounded by stone walls and scattered greenery. The camera remains fixed, capturing the dinosaur's deliberate movements.",
|
146 |
+
"src_words": "large brown bear",
|
147 |
+
"tar_words": "large dinosaur",
|
148 |
+
},
|
149 |
+
{ # blackswan_02
|
150 |
+
"video_base_name": "blackswan",
|
151 |
+
"src_prompt": "A black swan with a red beak swimming in a river near a wall and bushes.",
|
152 |
+
"tar_prompt": "A white duck with a red beak swimming in a river near a wall and bushes.",
|
153 |
+
"src_words": "black swan",
|
154 |
+
"tar_words": "white duck",
|
155 |
+
},
|
156 |
+
{ # jeep_01
|
157 |
+
"video_base_name": "jeep",
|
158 |
+
"src_prompt": "A silver jeep driving down a curvy road in the countryside.",
|
159 |
+
"tar_prompt": "A Porsche car driving down a curvy road in the countryside.",
|
160 |
+
"src_words": "silver jeep",
|
161 |
+
"tar_words": "Porsche car",
|
162 |
+
},
|
163 |
+
{ # woman_02 (additive edit)
|
164 |
+
"video_base_name": "woman",
|
165 |
+
"src_prompt": "A woman in a black dress is walking along a paved path in a lush green park, with trees and a wooden bench in the background. The camera remains fixed, capturing her steady movement.",
|
166 |
+
"tar_prompt": "A woman in a black dress and a red baseball cap is walking along a paved path in a lush green park, with trees and a wooden bench in the background. The camera remains fixed, capturing her steady movement.",
|
167 |
+
"src_words": "", # Empty source words for addition
|
168 |
+
"tar_words": "a red baseball cap",
|
169 |
+
}
|
170 |
+
]
|
171 |
+
|
172 |
+
examples_data = []
|
173 |
+
# Default advanced parameters for all examples
|
174 |
+
default_omega = 2.75
|
175 |
+
default_n_max = 40
|
176 |
+
default_n_avg = 4
|
177 |
+
|
178 |
+
for ex_def in examples_to_load_definitions:
|
179 |
+
# Assuming .mp4 extension for all videos
|
180 |
+
video_file_name = f"{ex_def['video_base_name']}.mp4"
|
181 |
+
example_video_path = os.path.join(VIDEO_EXAMPLES_DIR, video_file_name)
|
182 |
+
|
183 |
+
if os.path.exists(example_video_path):
|
184 |
+
examples_data.append([
|
185 |
+
example_video_path,
|
186 |
+
ex_def["src_prompt"],
|
187 |
+
ex_def["tar_prompt"],
|
188 |
+
ex_def["src_words"],
|
189 |
+
ex_def["tar_words"],
|
190 |
+
default_omega,
|
191 |
+
default_n_max,
|
192 |
+
default_n_avg
|
193 |
+
])
|
194 |
+
else:
|
195 |
+
print(f"Warning: Example video {example_video_path} not found. Example for '{ex_def['video_base_name']}' will be skipped.")
|
196 |
+
|
197 |
+
if not examples_data:
|
198 |
+
print(f"Warning: No example videos found in '{VIDEO_EXAMPLES_DIR}'. Examples section will be empty or not show.")
|
199 |
+
|
200 |
+
|
201 |
+
with gr.Blocks(theme=gr.themes.Soft(), css="""
|
202 |
+
/* Main container - maximize width and improve spacing */
|
203 |
+
.gradio-container {
|
204 |
+
max-width: 98% !important;
|
205 |
+
width: 98% !important;
|
206 |
+
margin: 0 auto !important;
|
207 |
+
padding: 20px !important;
|
208 |
+
min-height: 100vh !important;
|
209 |
+
}
|
210 |
+
|
211 |
+
/* All containers should use full width */
|
212 |
+
.contain, .container {
|
213 |
+
max-width: 100% !important;
|
214 |
+
width: 100% !important;
|
215 |
+
padding: 0 !important;
|
216 |
+
}
|
217 |
+
|
218 |
+
/* Remove default padding from main wrapper */
|
219 |
+
.main, .wrap, .panel {
|
220 |
+
max-width: 100% !important;
|
221 |
+
width: 100% !important;
|
222 |
+
padding: 0 !important;
|
223 |
+
}
|
224 |
+
|
225 |
+
/* Improve spacing for components */
|
226 |
+
.gap, .form {
|
227 |
+
gap: 15px !important;
|
228 |
+
}
|
229 |
+
|
230 |
+
/* Make all components full width */
|
231 |
+
#component-0, .block {
|
232 |
+
max-width: 100% !important;
|
233 |
+
width: 100% !important;
|
234 |
+
}
|
235 |
+
|
236 |
+
/* Better padding for groups */
|
237 |
+
.group {
|
238 |
+
padding: 20px !important;
|
239 |
+
margin-bottom: 15px !important;
|
240 |
+
border-radius: 8px !important;
|
241 |
+
}
|
242 |
+
|
243 |
+
/* Make rows and columns use full space with better gaps */
|
244 |
+
.row {
|
245 |
+
gap: 30px !important;
|
246 |
+
margin-bottom: 20px !important;
|
247 |
+
}
|
248 |
+
|
249 |
+
/* Improve column spacing */
|
250 |
+
.column {
|
251 |
+
padding: 0 10px !important;
|
252 |
+
}
|
253 |
+
|
254 |
+
/* Better video component sizing */
|
255 |
+
.video-container {
|
256 |
+
width: 100% !important;
|
257 |
+
}
|
258 |
+
|
259 |
+
/* Textbox improvements */
|
260 |
+
.textbox, .input-field {
|
261 |
+
width: 100% !important;
|
262 |
+
}
|
263 |
+
|
264 |
+
/* Button styling */
|
265 |
+
.primary {
|
266 |
+
width: 100% !important;
|
267 |
+
padding: 12px !important;
|
268 |
+
font-size: 16px !important;
|
269 |
+
margin-top: 20px !important;
|
270 |
+
}
|
271 |
+
|
272 |
+
/* Examples section spacing */
|
273 |
+
.examples {
|
274 |
+
margin-top: 30px !important;
|
275 |
+
padding: 20px !important;
|
276 |
+
}
|
277 |
+
|
278 |
+
/* Accordion improvements */
|
279 |
+
.accordion {
|
280 |
+
margin: 15px 0 !important;
|
281 |
+
}
|
282 |
+
""") as demo:
|
283 |
+
gr.Markdown(
|
284 |
+
"""
|
285 |
+
<h1 style="text-align: center; font-size: 2.5em;">🪄 FlowDirector Video Edit</h1>
|
286 |
+
<p style="text-align: center;">
|
287 |
+
Edit videos by providing a source video, descriptive prompts, and specifying words to change.<br>
|
288 |
+
Powered by FlowDirector.
|
289 |
+
</p>
|
290 |
+
"""
|
291 |
+
)
|
292 |
+
|
293 |
+
with gr.Row():
|
294 |
+
with gr.Column(scale=5): # Input column - increased scale for better space usage
|
295 |
+
with gr.Group():
|
296 |
+
gr.Markdown("### 🎬 Source Material")
|
297 |
+
source_video_input = gr.Video(label="Upload Source Video", height=540)
|
298 |
+
source_prompt_input = gr.Textbox(
|
299 |
+
label="Source Prompt",
|
300 |
+
placeholder="Describe the original video content accurately.",
|
301 |
+
lines=3,
|
302 |
+
show_label=True
|
303 |
+
)
|
304 |
+
target_prompt_input = gr.Textbox(
|
305 |
+
label="Target Prompt (Desired Edit)",
|
306 |
+
placeholder="Describe how you want the video to be after editing.",
|
307 |
+
lines=3,
|
308 |
+
show_label=True
|
309 |
+
)
|
310 |
+
|
311 |
+
with gr.Group():
|
312 |
+
gr.Markdown("### ✍️ Editing Instructions")
|
313 |
+
source_words_input = gr.Textbox(
|
314 |
+
label="Source Words (to be replaced, or empty for addition)",
|
315 |
+
placeholder="e.g., large brown bear (leave empty to add target words globally)"
|
316 |
+
)
|
317 |
+
target_words_input = gr.Textbox(
|
318 |
+
label="Target Words (replacement or addition)",
|
319 |
+
placeholder="e.g., large dinosaur OR a red baseball cap"
|
320 |
+
)
|
321 |
+
|
322 |
+
with gr.Accordion("🔧 Advanced Parameters", open=False):
|
323 |
+
omega_slider = gr.Slider(
|
324 |
+
minimum=0.0, maximum=5.0, step=0.05, value=default_omega, label="Omega (ω)",
|
325 |
+
info="Controls the intensity/style of the edit. Higher values might lead to stronger edits."
|
326 |
+
)
|
327 |
+
n_max_slider = gr.Slider(
|
328 |
+
minimum=0, maximum=50, step=1, value=default_n_max, label="N_max",
|
329 |
+
info="Max value for an adaptive param. `n_min` is fixed at 0."
|
330 |
+
)
|
331 |
+
n_avg_slider = gr.Slider(
|
332 |
+
minimum=0, maximum=5, step=1, value=default_n_avg, label="N_avg",
|
333 |
+
info="Average value for an adaptive param. `worse_avg` will be N_avg // 2."
|
334 |
+
)
|
335 |
+
|
336 |
+
submit_button = gr.Button("✨ Generate Edited Video", variant="primary")
|
337 |
+
|
338 |
+
with gr.Column(scale=4): # Output column - increased scale for better proportion
|
339 |
+
gr.Markdown("### 🖼️ Edited Video Output")
|
340 |
+
output_video = gr.Video(label="Result", height=540, show_label=False)
|
341 |
+
|
342 |
+
|
343 |
+
if examples_data: # Only show examples if some were successfully loaded
|
344 |
+
gr.Examples(
|
345 |
+
examples=examples_data,
|
346 |
+
inputs=[
|
347 |
+
source_video_input,
|
348 |
+
source_prompt_input,
|
349 |
+
target_prompt_input,
|
350 |
+
source_words_input,
|
351 |
+
target_words_input,
|
352 |
+
omega_slider,
|
353 |
+
n_max_slider,
|
354 |
+
n_avg_slider
|
355 |
+
],
|
356 |
+
outputs=output_video,
|
357 |
+
fn=run_video_edit,
|
358 |
+
cache_examples=False # For long processes, False is better
|
359 |
+
)
|
360 |
+
|
361 |
+
all_process_inputs = [
|
362 |
+
source_video_input,
|
363 |
+
source_prompt_input,
|
364 |
+
target_prompt_input,
|
365 |
+
source_words_input,
|
366 |
+
target_words_input,
|
367 |
+
omega_slider,
|
368 |
+
n_max_slider,
|
369 |
+
n_avg_slider
|
370 |
+
]
|
371 |
+
|
372 |
+
submit_button.click(
|
373 |
+
fn=run_video_edit,
|
374 |
+
inputs=all_process_inputs,
|
375 |
+
outputs=output_video
|
376 |
+
)
|
377 |
+
|
378 |
+
if __name__ == "__main__":
|
379 |
+
# print(f"Make sure your checkpoint directory is correctly set to: {CKPT_DIR}")
|
380 |
+
# print(f"And that '{EDIT_SCRIPT_PATH}' is in the same directory as app.py or correctly pathed.")
|
381 |
+
# print(f"Outputs will be saved to: {os.path.abspath(OUTPUT_DIR)}")
|
382 |
+
# print(f"Place example videos (e.g., bear_g.mp4, blackswan.mp4, etc.) in: {os.path.abspath(VIDEO_EXAMPLES_DIR)}")
|
383 |
+
|
384 |
+
args = _parse_args()
|
385 |
+
CKPT_DIR = args.ckpt
|
386 |
+
demo.launch()
|
edit.py
ADDED
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
import argparse
|
3 |
+
from datetime import datetime
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import sys
|
7 |
+
import warnings
|
8 |
+
|
9 |
+
warnings.filterwarnings('ignore')
|
10 |
+
|
11 |
+
import torch, random
|
12 |
+
import torch.distributed as dist
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
import wan
|
16 |
+
from wan.configs import WAN_CONFIGS, SIZE_CONFIGS, MAX_AREA_CONFIGS, SUPPORTED_SIZES
|
17 |
+
from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
|
18 |
+
from wan.utils.utils import cache_video, cache_image, str2bool
|
19 |
+
|
20 |
+
EXAMPLE_PROMPT = {
|
21 |
+
"t2v-1.3B": {
|
22 |
+
"prompt": "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
23 |
+
},
|
24 |
+
"t2v-14B": {
|
25 |
+
"prompt": "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
26 |
+
},
|
27 |
+
"t2i-14B": {
|
28 |
+
"prompt": "一个朴素端庄的美人",
|
29 |
+
},
|
30 |
+
"i2v-14B": {
|
31 |
+
"prompt":
|
32 |
+
"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.",
|
33 |
+
"image":
|
34 |
+
"examples/i2v_input.JPG",
|
35 |
+
},
|
36 |
+
}
|
37 |
+
|
38 |
+
|
39 |
+
def _validate_args(args):
|
40 |
+
# Basic check
|
41 |
+
assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
|
42 |
+
assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
|
43 |
+
assert args.task in EXAMPLE_PROMPT, f"Unsupport task: {args.task}"
|
44 |
+
|
45 |
+
# The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
|
46 |
+
if args.sample_steps is None:
|
47 |
+
args.sample_steps = 40 if "i2v" in args.task else 50
|
48 |
+
|
49 |
+
if args.sample_shift is None:
|
50 |
+
args.sample_shift = 5.0
|
51 |
+
if "i2v" in args.task and args.size in ["832*480", "480*832"]:
|
52 |
+
args.sample_shift = 3.0
|
53 |
+
|
54 |
+
# The default number of frames are 1 for text-to-image tasks and 81 for other tasks.
|
55 |
+
if args.frame_num is None:
|
56 |
+
args.frame_num = 1 if "t2i" in args.task else 81
|
57 |
+
|
58 |
+
# T2I frame_num check
|
59 |
+
if "t2i" in args.task:
|
60 |
+
assert args.frame_num == 1, f"Unsupport frame_num {args.frame_num} for task {args.task}"
|
61 |
+
|
62 |
+
args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
|
63 |
+
0, sys.maxsize)
|
64 |
+
# Size check
|
65 |
+
assert args.size in SUPPORTED_SIZES[
|
66 |
+
args.
|
67 |
+
task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
|
68 |
+
|
69 |
+
|
70 |
+
def _parse_args():
|
71 |
+
parser = argparse.ArgumentParser(
|
72 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
73 |
+
)
|
74 |
+
parser.add_argument(
|
75 |
+
"--task",
|
76 |
+
type=str,
|
77 |
+
default="t2v-14B",
|
78 |
+
choices=list(WAN_CONFIGS.keys()),
|
79 |
+
help="The task to run.")
|
80 |
+
parser.add_argument(
|
81 |
+
"--size",
|
82 |
+
type=str,
|
83 |
+
default="1280*720",
|
84 |
+
choices=list(SIZE_CONFIGS.keys()),
|
85 |
+
help="The area (width*height) of the generated video. For the I2V task, the aspect ratio of the output video will follow that of the input image."
|
86 |
+
)
|
87 |
+
parser.add_argument(
|
88 |
+
"--frame_num",
|
89 |
+
type=int,
|
90 |
+
default=None,
|
91 |
+
help="How many frames to sample from a image or video. The number should be 4n+1"
|
92 |
+
)
|
93 |
+
parser.add_argument(
|
94 |
+
"--ckpt_dir",
|
95 |
+
type=str,
|
96 |
+
default=None,
|
97 |
+
help="The path to the checkpoint directory.")
|
98 |
+
parser.add_argument(
|
99 |
+
"--offload_model",
|
100 |
+
type=str2bool,
|
101 |
+
default=None,
|
102 |
+
help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
|
103 |
+
)
|
104 |
+
parser.add_argument(
|
105 |
+
"--ulysses_size",
|
106 |
+
type=int,
|
107 |
+
default=1,
|
108 |
+
help="The size of the ulysses parallelism in DiT.")
|
109 |
+
parser.add_argument(
|
110 |
+
"--ring_size",
|
111 |
+
type=int,
|
112 |
+
default=1,
|
113 |
+
help="The size of the ring attention parallelism in DiT.")
|
114 |
+
parser.add_argument(
|
115 |
+
"--t5_fsdp",
|
116 |
+
action="store_true",
|
117 |
+
default=False,
|
118 |
+
help="Whether to use FSDP for T5.")
|
119 |
+
parser.add_argument(
|
120 |
+
"--t5_cpu",
|
121 |
+
action="store_true",
|
122 |
+
default=False,
|
123 |
+
help="Whether to place T5 model on CPU.")
|
124 |
+
parser.add_argument(
|
125 |
+
"--dit_fsdp",
|
126 |
+
action="store_true",
|
127 |
+
default=False,
|
128 |
+
help="Whether to use FSDP for DiT.")
|
129 |
+
parser.add_argument(
|
130 |
+
"--save_file",
|
131 |
+
type=str,
|
132 |
+
default=None,
|
133 |
+
help="The file to save the generated image or video to.")
|
134 |
+
parser.add_argument(
|
135 |
+
"--prompt",
|
136 |
+
type=str,
|
137 |
+
default=None,
|
138 |
+
help="The prompt to generate the image or video from.")
|
139 |
+
parser.add_argument(
|
140 |
+
"--use_prompt_extend",
|
141 |
+
action="store_true",
|
142 |
+
default=False,
|
143 |
+
help="Whether to use prompt extend.")
|
144 |
+
parser.add_argument(
|
145 |
+
"--prompt_extend_method",
|
146 |
+
type=str,
|
147 |
+
default="local_qwen",
|
148 |
+
choices=["dashscope", "local_qwen"],
|
149 |
+
help="The prompt extend method to use.")
|
150 |
+
parser.add_argument(
|
151 |
+
"--prompt_extend_model",
|
152 |
+
type=str,
|
153 |
+
default=None,
|
154 |
+
help="The prompt extend model to use.")
|
155 |
+
parser.add_argument(
|
156 |
+
"--prompt_extend_target_lang",
|
157 |
+
type=str,
|
158 |
+
default="ch",
|
159 |
+
choices=["ch", "en"],
|
160 |
+
help="The target language of prompt extend.")
|
161 |
+
parser.add_argument(
|
162 |
+
"--base_seed",
|
163 |
+
type=int,
|
164 |
+
default=-1,
|
165 |
+
help="The seed to use for generating the image or video.")
|
166 |
+
parser.add_argument(
|
167 |
+
"--image",
|
168 |
+
type=str,
|
169 |
+
default=None,
|
170 |
+
help="The image to generate the video from.")
|
171 |
+
parser.add_argument(
|
172 |
+
"--sample_solver",
|
173 |
+
type=str,
|
174 |
+
default='unipc',
|
175 |
+
choices=['unipc', 'dpm++'],
|
176 |
+
help="The solver used to sample.")
|
177 |
+
parser.add_argument(
|
178 |
+
"--sample_steps", type=int, default=None, help="The sampling steps.")
|
179 |
+
parser.add_argument(
|
180 |
+
"--sample_shift",
|
181 |
+
type=float,
|
182 |
+
default=None,
|
183 |
+
help="Sampling shift factor for flow matching schedulers.")
|
184 |
+
parser.add_argument(
|
185 |
+
"--sample_guide_scale",
|
186 |
+
type=float,
|
187 |
+
default=5.0,
|
188 |
+
help="Classifier free guidance scale.")
|
189 |
+
parser.add_argument(
|
190 |
+
"--tar_guide_scale",
|
191 |
+
type=float,
|
192 |
+
default=10.0,
|
193 |
+
help="Classifier free guidance scale for target video.")
|
194 |
+
parser.add_argument(
|
195 |
+
"--source_video_path",
|
196 |
+
type=str,
|
197 |
+
default=None,
|
198 |
+
help="Path to the source video for editing.")
|
199 |
+
parser.add_argument(
|
200 |
+
"--source_prompt",
|
201 |
+
type=str,
|
202 |
+
default=None,
|
203 |
+
help="Text prompt describing the source video.")
|
204 |
+
parser.add_argument(
|
205 |
+
"--n_max",
|
206 |
+
type=int,
|
207 |
+
default=35,
|
208 |
+
help="Number of steps to start editing, controlling the editing intensity.")
|
209 |
+
parser.add_argument(
|
210 |
+
"--n_min",
|
211 |
+
type=int,
|
212 |
+
default=0,
|
213 |
+
help="Number of steps at the end of editing, using the vector from tar after completion to control the intensity of style transfer.")
|
214 |
+
parser.add_argument(
|
215 |
+
"--n_avg",
|
216 |
+
type=int,
|
217 |
+
default=5,
|
218 |
+
help="number of steps to average")
|
219 |
+
parser.add_argument(
|
220 |
+
"--worse_avg",
|
221 |
+
type=int,
|
222 |
+
default=3,
|
223 |
+
help="number of steps for worse average")
|
224 |
+
parser.add_argument(
|
225 |
+
"--omega",
|
226 |
+
type=float,
|
227 |
+
default=3,
|
228 |
+
help="omega")
|
229 |
+
parser.add_argument(
|
230 |
+
"--source_words",
|
231 |
+
type=str,
|
232 |
+
default=None,
|
233 |
+
help="Object edited in the source prompt.")
|
234 |
+
parser.add_argument(
|
235 |
+
"--target_words",
|
236 |
+
type=str,
|
237 |
+
default=None,
|
238 |
+
help="Object edited in the target prompt.")
|
239 |
+
parser.add_argument(
|
240 |
+
"--window_size",
|
241 |
+
type=int,
|
242 |
+
default=13,
|
243 |
+
help="window size")
|
244 |
+
parser.add_argument(
|
245 |
+
"--decay_factor",
|
246 |
+
type=float,
|
247 |
+
default=0.1,
|
248 |
+
help="Window decay factor")
|
249 |
+
|
250 |
+
|
251 |
+
args = parser.parse_args()
|
252 |
+
|
253 |
+
_validate_args(args)
|
254 |
+
|
255 |
+
return args
|
256 |
+
|
257 |
+
|
258 |
+
def _init_logging(rank):
|
259 |
+
# logging
|
260 |
+
if rank == 0:
|
261 |
+
# set format
|
262 |
+
logging.basicConfig(
|
263 |
+
level=logging.INFO,
|
264 |
+
format="[%(asctime)s] %(levelname)s: %(message)s",
|
265 |
+
handlers=[logging.StreamHandler(stream=sys.stdout)])
|
266 |
+
else:
|
267 |
+
logging.basicConfig(level=logging.ERROR)
|
268 |
+
|
269 |
+
|
270 |
+
def edit(args):
|
271 |
+
rank = int(os.getenv("RANK", 0))
|
272 |
+
world_size = int(os.getenv("WORLD_SIZE", 1))
|
273 |
+
local_rank = int(os.getenv("LOCAL_RANK", 0))
|
274 |
+
device = local_rank
|
275 |
+
_init_logging(rank)
|
276 |
+
|
277 |
+
if args.offload_model is None:
|
278 |
+
args.offload_model = False if world_size > 1 else True
|
279 |
+
logging.info(
|
280 |
+
f"offload_model is not specified, set to {args.offload_model}.")
|
281 |
+
if world_size > 1:
|
282 |
+
torch.cuda.set_device(local_rank)
|
283 |
+
dist.init_process_group(
|
284 |
+
backend="nccl",
|
285 |
+
init_method="env://",
|
286 |
+
rank=rank,
|
287 |
+
world_size=world_size)
|
288 |
+
else:
|
289 |
+
assert not (
|
290 |
+
args.t5_fsdp or args.dit_fsdp
|
291 |
+
), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
|
292 |
+
assert not (
|
293 |
+
args.ulysses_size > 1 or args.ring_size > 1
|
294 |
+
), f"context parallel are not supported in non-distributed environments."
|
295 |
+
|
296 |
+
if args.ulysses_size > 1 or args.ring_size > 1:
|
297 |
+
assert args.ulysses_size * args.ring_size == world_size, f"The number of ulysses_size and ring_size should be equal to the world size."
|
298 |
+
from xfuser.core.distributed import (initialize_model_parallel,
|
299 |
+
init_distributed_environment)
|
300 |
+
init_distributed_environment(
|
301 |
+
rank=dist.get_rank(), world_size=dist.get_world_size())
|
302 |
+
|
303 |
+
initialize_model_parallel(
|
304 |
+
sequence_parallel_degree=dist.get_world_size(),
|
305 |
+
ring_degree=args.ring_size,
|
306 |
+
ulysses_degree=args.ulysses_size,
|
307 |
+
)
|
308 |
+
|
309 |
+
if args.use_prompt_extend:
|
310 |
+
if args.prompt_extend_method == "dashscope":
|
311 |
+
prompt_expander = DashScopePromptExpander(
|
312 |
+
model_name=args.prompt_extend_model, is_vl="i2v" in args.task)
|
313 |
+
elif args.prompt_extend_method == "local_qwen":
|
314 |
+
prompt_expander = QwenPromptExpander(
|
315 |
+
model_name=args.prompt_extend_model,
|
316 |
+
is_vl="i2v" in args.task,
|
317 |
+
device=rank)
|
318 |
+
else:
|
319 |
+
raise NotImplementedError(
|
320 |
+
f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
|
321 |
+
|
322 |
+
cfg = WAN_CONFIGS[args.task]
|
323 |
+
if args.ulysses_size > 1:
|
324 |
+
assert cfg.num_heads % args.ulysses_size == 0, f"`num_heads` must be divisible by `ulysses_size`."
|
325 |
+
|
326 |
+
logging.info(f"Generation job args: {args}")
|
327 |
+
logging.info(f"Generation model config: {cfg}")
|
328 |
+
|
329 |
+
if dist.is_initialized():
|
330 |
+
base_seed = [args.base_seed] if rank == 0 else [None]
|
331 |
+
dist.broadcast_object_list(base_seed, src=0)
|
332 |
+
args.base_seed = base_seed[0]
|
333 |
+
|
334 |
+
if "t2v" in args.task or "t2i" in args.task:
|
335 |
+
if args.prompt is None:
|
336 |
+
args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
|
337 |
+
logging.info(f"Input prompt: {args.prompt}")
|
338 |
+
if args.use_prompt_extend:
|
339 |
+
logging.info("Extending prompt ...")
|
340 |
+
if rank == 0:
|
341 |
+
prompt_output = prompt_expander(
|
342 |
+
args.prompt,
|
343 |
+
tar_lang=args.prompt_extend_target_lang,
|
344 |
+
seed=args.base_seed)
|
345 |
+
if prompt_output.status == False:
|
346 |
+
logging.info(
|
347 |
+
f"Extending prompt failed: {prompt_output.message}")
|
348 |
+
logging.info("Falling back to original prompt.")
|
349 |
+
input_prompt = args.prompt
|
350 |
+
else:
|
351 |
+
input_prompt = prompt_output.prompt
|
352 |
+
input_prompt = [input_prompt]
|
353 |
+
else:
|
354 |
+
input_prompt = [None]
|
355 |
+
if dist.is_initialized():
|
356 |
+
dist.broadcast_object_list(input_prompt, src=0)
|
357 |
+
args.prompt = input_prompt[0]
|
358 |
+
logging.info(f"Extended prompt: {args.prompt}")
|
359 |
+
|
360 |
+
logging.info("Creating WanT2V pipeline.")
|
361 |
+
wan_t2v = wan.WanT2V(
|
362 |
+
config=cfg,
|
363 |
+
checkpoint_dir=args.ckpt_dir,
|
364 |
+
device_id=device,
|
365 |
+
rank=rank,
|
366 |
+
t5_fsdp=args.t5_fsdp,
|
367 |
+
dit_fsdp=args.dit_fsdp,
|
368 |
+
# use_usp=False,
|
369 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
370 |
+
t5_cpu=args.t5_cpu,
|
371 |
+
)
|
372 |
+
|
373 |
+
logging.info(
|
374 |
+
f"Generating {'image' if 't2i' in args.task else 'video'} ...")
|
375 |
+
video = wan_t2v.edit(
|
376 |
+
args.prompt,
|
377 |
+
size=SIZE_CONFIGS[args.size],
|
378 |
+
frame_num=args.frame_num,
|
379 |
+
shift=args.sample_shift,
|
380 |
+
sample_solver=args.sample_solver,
|
381 |
+
sampling_steps=args.sample_steps,
|
382 |
+
guide_scale=args.sample_guide_scale,
|
383 |
+
tar_guide_scale=args.tar_guide_scale,
|
384 |
+
seed=args.base_seed,
|
385 |
+
offload_model=args.offload_model,
|
386 |
+
source_video_path=args.source_video_path,
|
387 |
+
source_prompt=args.source_prompt,
|
388 |
+
nmax_step=args.n_max,
|
389 |
+
nmin_step=args.n_min,
|
390 |
+
n_avg=args.n_avg,
|
391 |
+
worse_avg=args.worse_avg,
|
392 |
+
omega=args.omega,
|
393 |
+
source_words=args.source_words,
|
394 |
+
target_words=args.target_words,
|
395 |
+
window_size=args.window_size,
|
396 |
+
decay_factor=args.decay_factor)
|
397 |
+
|
398 |
+
else:
|
399 |
+
if args.prompt is None:
|
400 |
+
args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
|
401 |
+
if args.image is None:
|
402 |
+
args.image = EXAMPLE_PROMPT[args.task]["image"]
|
403 |
+
logging.info(f"Input prompt: {args.prompt}")
|
404 |
+
logging.info(f"Input image: {args.image}")
|
405 |
+
|
406 |
+
img = Image.open(args.image).convert("RGB")
|
407 |
+
if args.use_prompt_extend:
|
408 |
+
logging.info("Extending prompt ...")
|
409 |
+
if rank == 0:
|
410 |
+
prompt_output = prompt_expander(
|
411 |
+
args.prompt,
|
412 |
+
tar_lang=args.prompt_extend_target_lang,
|
413 |
+
image=img,
|
414 |
+
seed=args.base_seed)
|
415 |
+
if prompt_output.status == False:
|
416 |
+
logging.info(
|
417 |
+
f"Extending prompt failed: {prompt_output.message}")
|
418 |
+
logging.info("Falling back to original prompt.")
|
419 |
+
input_prompt = args.prompt
|
420 |
+
else:
|
421 |
+
input_prompt = prompt_output.prompt
|
422 |
+
input_prompt = [input_prompt]
|
423 |
+
else:
|
424 |
+
input_prompt = [None]
|
425 |
+
if dist.is_initialized():
|
426 |
+
dist.broadcast_object_list(input_prompt, src=0)
|
427 |
+
args.prompt = input_prompt[0]
|
428 |
+
logging.info(f"Extended prompt: {args.prompt}")
|
429 |
+
|
430 |
+
logging.info("Creating WanI2V pipeline.")
|
431 |
+
wan_i2v = wan.WanI2V(
|
432 |
+
config=cfg,
|
433 |
+
checkpoint_dir=args.ckpt_dir,
|
434 |
+
device_id=device,
|
435 |
+
rank=rank,
|
436 |
+
t5_fsdp=args.t5_fsdp,
|
437 |
+
dit_fsdp=args.dit_fsdp,
|
438 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
439 |
+
t5_cpu=args.t5_cpu,
|
440 |
+
)
|
441 |
+
|
442 |
+
logging.info("Generating video ...")
|
443 |
+
video = wan_i2v.edit(
|
444 |
+
args.prompt,
|
445 |
+
img,
|
446 |
+
max_area=MAX_AREA_CONFIGS[args.size],
|
447 |
+
frame_num=args.frame_num,
|
448 |
+
shift=args.sample_shift,
|
449 |
+
sample_solver=args.sample_solver,
|
450 |
+
sampling_steps=args.sample_steps,
|
451 |
+
guide_scale=args.sample_guide_scale,
|
452 |
+
seed=args.base_seed,
|
453 |
+
offload_model=args.offload_model)
|
454 |
+
|
455 |
+
if rank == 0:
|
456 |
+
if args.save_file is None:
|
457 |
+
formatted_time = datetime.now().strftime("%m%d_%H%M")
|
458 |
+
formatted_prompt = args.prompt.replace(" ", "_").replace("/",
|
459 |
+
"_")[:30]
|
460 |
+
suffix = '.png' if "t2i" in args.task else '.mp4'
|
461 |
+
args.save_file = f"videos/{formatted_time}_{args.source_words.replace(' ', '_').replace('/', '_')}_{args.target_words.replace(' ', '_').replace('/', '_')}_n{args.n_avg}_w{args.worse_avg}_omega{args.omega}_s{args.base_seed}" + suffix
|
462 |
+
|
463 |
+
if "t2i" in args.task:
|
464 |
+
logging.info(f"Saving generated image to {args.save_file}")
|
465 |
+
cache_image(
|
466 |
+
tensor=video.squeeze(1)[None],
|
467 |
+
save_file=args.save_file,
|
468 |
+
nrow=1,
|
469 |
+
normalize=True,
|
470 |
+
value_range=(-1, 1))
|
471 |
+
else:
|
472 |
+
logging.info(f"Saving generated video to {args.save_file}")
|
473 |
+
cache_video(
|
474 |
+
tensor=video[None],
|
475 |
+
save_file=args.save_file,
|
476 |
+
fps=cfg.sample_fps,
|
477 |
+
nrow=1,
|
478 |
+
normalize=True,
|
479 |
+
value_range=(-1, 1))
|
480 |
+
logging.info("Finished.")
|
481 |
+
|
482 |
+
|
483 |
+
|
484 |
+
if __name__ == "__main__":
|
485 |
+
args = _parse_args()
|
486 |
+
edit(args)
|
generate.py
ADDED
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
import argparse
|
3 |
+
from datetime import datetime
|
4 |
+
import logging
|
5 |
+
import os
|
6 |
+
import sys
|
7 |
+
import warnings
|
8 |
+
|
9 |
+
warnings.filterwarnings('ignore')
|
10 |
+
|
11 |
+
import torch, random
|
12 |
+
import torch.distributed as dist
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
import wan
|
16 |
+
from wan.configs import WAN_CONFIGS, SIZE_CONFIGS, MAX_AREA_CONFIGS, SUPPORTED_SIZES
|
17 |
+
from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
|
18 |
+
from wan.utils.utils import cache_video, cache_image, str2bool
|
19 |
+
|
20 |
+
EXAMPLE_PROMPT = {
|
21 |
+
"t2v-1.3B": {
|
22 |
+
"prompt": "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
23 |
+
},
|
24 |
+
"t2v-14B": {
|
25 |
+
"prompt": "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
|
26 |
+
},
|
27 |
+
"t2i-14B": {
|
28 |
+
"prompt": "一个朴素端庄的美人",
|
29 |
+
},
|
30 |
+
"i2v-14B": {
|
31 |
+
"prompt":
|
32 |
+
"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.",
|
33 |
+
"image":
|
34 |
+
"examples/i2v_input.JPG",
|
35 |
+
},
|
36 |
+
}
|
37 |
+
|
38 |
+
|
39 |
+
def _validate_args(args):
|
40 |
+
# Basic check
|
41 |
+
assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
|
42 |
+
assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
|
43 |
+
assert args.task in EXAMPLE_PROMPT, f"Unsupport task: {args.task}"
|
44 |
+
|
45 |
+
# The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
|
46 |
+
if args.sample_steps is None:
|
47 |
+
args.sample_steps = 40 if "i2v" in args.task else 50
|
48 |
+
|
49 |
+
if args.sample_shift is None:
|
50 |
+
args.sample_shift = 5.0
|
51 |
+
if "i2v" in args.task and args.size in ["832*480", "480*832"]:
|
52 |
+
args.sample_shift = 3.0
|
53 |
+
|
54 |
+
# The default number of frames are 1 for text-to-image tasks and 81 for other tasks.
|
55 |
+
if args.frame_num is None:
|
56 |
+
args.frame_num = 1 if "t2i" in args.task else 81
|
57 |
+
|
58 |
+
# T2I frame_num check
|
59 |
+
if "t2i" in args.task:
|
60 |
+
assert args.frame_num == 1, f"Unsupport frame_num {args.frame_num} for task {args.task}"
|
61 |
+
|
62 |
+
args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
|
63 |
+
0, sys.maxsize)
|
64 |
+
# Size check
|
65 |
+
assert args.size in SUPPORTED_SIZES[
|
66 |
+
args.
|
67 |
+
task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
|
68 |
+
|
69 |
+
|
70 |
+
def _parse_args():
|
71 |
+
parser = argparse.ArgumentParser(
|
72 |
+
description="Generate a image or video from a text prompt or image using Wan"
|
73 |
+
)
|
74 |
+
parser.add_argument(
|
75 |
+
"--task",
|
76 |
+
type=str,
|
77 |
+
default="t2v-14B",
|
78 |
+
choices=list(WAN_CONFIGS.keys()),
|
79 |
+
help="The task to run.")
|
80 |
+
parser.add_argument(
|
81 |
+
"--size",
|
82 |
+
type=str,
|
83 |
+
default="1280*720",
|
84 |
+
choices=list(SIZE_CONFIGS.keys()),
|
85 |
+
help="The area (width*height) of the generated video. For the I2V task, the aspect ratio of the output video will follow that of the input image."
|
86 |
+
)
|
87 |
+
parser.add_argument(
|
88 |
+
"--frame_num",
|
89 |
+
type=int,
|
90 |
+
default=None,
|
91 |
+
help="How many frames to sample from a image or video. The number should be 4n+1"
|
92 |
+
)
|
93 |
+
parser.add_argument(
|
94 |
+
"--ckpt_dir",
|
95 |
+
type=str,
|
96 |
+
default=None,
|
97 |
+
help="The path to the checkpoint directory.")
|
98 |
+
parser.add_argument(
|
99 |
+
"--offload_model",
|
100 |
+
type=str2bool,
|
101 |
+
default=None,
|
102 |
+
help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
|
103 |
+
)
|
104 |
+
parser.add_argument(
|
105 |
+
"--ulysses_size",
|
106 |
+
type=int,
|
107 |
+
default=1,
|
108 |
+
help="The size of the ulysses parallelism in DiT.")
|
109 |
+
parser.add_argument(
|
110 |
+
"--ring_size",
|
111 |
+
type=int,
|
112 |
+
default=1,
|
113 |
+
help="The size of the ring attention parallelism in DiT.")
|
114 |
+
parser.add_argument(
|
115 |
+
"--t5_fsdp",
|
116 |
+
action="store_true",
|
117 |
+
default=False,
|
118 |
+
help="Whether to use FSDP for T5.")
|
119 |
+
parser.add_argument(
|
120 |
+
"--t5_cpu",
|
121 |
+
action="store_true",
|
122 |
+
default=False,
|
123 |
+
help="Whether to place T5 model on CPU.")
|
124 |
+
parser.add_argument(
|
125 |
+
"--dit_fsdp",
|
126 |
+
action="store_true",
|
127 |
+
default=False,
|
128 |
+
help="Whether to use FSDP for DiT.")
|
129 |
+
parser.add_argument(
|
130 |
+
"--save_file",
|
131 |
+
type=str,
|
132 |
+
default=None,
|
133 |
+
help="The file to save the generated image or video to.")
|
134 |
+
parser.add_argument(
|
135 |
+
"--prompt",
|
136 |
+
type=str,
|
137 |
+
default=None,
|
138 |
+
help="The prompt to generate the image or video from.")
|
139 |
+
parser.add_argument(
|
140 |
+
"--use_prompt_extend",
|
141 |
+
action="store_true",
|
142 |
+
default=False,
|
143 |
+
help="Whether to use prompt extend.")
|
144 |
+
parser.add_argument(
|
145 |
+
"--prompt_extend_method",
|
146 |
+
type=str,
|
147 |
+
default="local_qwen",
|
148 |
+
choices=["dashscope", "local_qwen"],
|
149 |
+
help="The prompt extend method to use.")
|
150 |
+
parser.add_argument(
|
151 |
+
"--prompt_extend_model",
|
152 |
+
type=str,
|
153 |
+
default=None,
|
154 |
+
help="The prompt extend model to use.")
|
155 |
+
parser.add_argument(
|
156 |
+
"--prompt_extend_target_lang",
|
157 |
+
type=str,
|
158 |
+
default="ch",
|
159 |
+
choices=["ch", "en"],
|
160 |
+
help="The target language of prompt extend.")
|
161 |
+
parser.add_argument(
|
162 |
+
"--base_seed",
|
163 |
+
type=int,
|
164 |
+
default=-1,
|
165 |
+
help="The seed to use for generating the image or video.")
|
166 |
+
parser.add_argument(
|
167 |
+
"--image",
|
168 |
+
type=str,
|
169 |
+
default=None,
|
170 |
+
help="The image to generate the video from.")
|
171 |
+
parser.add_argument(
|
172 |
+
"--sample_solver",
|
173 |
+
type=str,
|
174 |
+
default='unipc',
|
175 |
+
choices=['unipc', 'dpm++'],
|
176 |
+
help="The solver used to sample.")
|
177 |
+
parser.add_argument(
|
178 |
+
"--sample_steps", type=int, default=None, help="The sampling steps.")
|
179 |
+
parser.add_argument(
|
180 |
+
"--sample_shift",
|
181 |
+
type=float,
|
182 |
+
default=None,
|
183 |
+
help="Sampling shift factor for flow matching schedulers.")
|
184 |
+
parser.add_argument(
|
185 |
+
"--sample_guide_scale",
|
186 |
+
type=float,
|
187 |
+
default=5.0,
|
188 |
+
help="Classifier free guidance scale.")
|
189 |
+
|
190 |
+
args = parser.parse_args()
|
191 |
+
|
192 |
+
_validate_args(args)
|
193 |
+
|
194 |
+
return args
|
195 |
+
|
196 |
+
|
197 |
+
def _init_logging(rank):
|
198 |
+
# logging
|
199 |
+
if rank == 0:
|
200 |
+
# set format
|
201 |
+
logging.basicConfig(
|
202 |
+
level=logging.INFO,
|
203 |
+
format="[%(asctime)s] %(levelname)s: %(message)s",
|
204 |
+
handlers=[logging.StreamHandler(stream=sys.stdout)])
|
205 |
+
else:
|
206 |
+
logging.basicConfig(level=logging.ERROR)
|
207 |
+
|
208 |
+
|
209 |
+
def generate(args):
|
210 |
+
rank = int(os.getenv("RANK", 0))
|
211 |
+
world_size = int(os.getenv("WORLD_SIZE", 1))
|
212 |
+
local_rank = int(os.getenv("LOCAL_RANK", 0))
|
213 |
+
device = local_rank
|
214 |
+
_init_logging(rank)
|
215 |
+
|
216 |
+
if args.offload_model is None:
|
217 |
+
args.offload_model = False if world_size > 1 else True
|
218 |
+
logging.info(
|
219 |
+
f"offload_model is not specified, set to {args.offload_model}.")
|
220 |
+
if world_size > 1:
|
221 |
+
torch.cuda.set_device(local_rank)
|
222 |
+
dist.init_process_group(
|
223 |
+
backend="nccl",
|
224 |
+
init_method="env://",
|
225 |
+
rank=rank,
|
226 |
+
world_size=world_size)
|
227 |
+
else:
|
228 |
+
assert not (
|
229 |
+
args.t5_fsdp or args.dit_fsdp
|
230 |
+
), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
|
231 |
+
assert not (
|
232 |
+
args.ulysses_size > 1 or args.ring_size > 1
|
233 |
+
), f"context parallel are not supported in non-distributed environments."
|
234 |
+
|
235 |
+
if args.ulysses_size > 1 or args.ring_size > 1:
|
236 |
+
assert args.ulysses_size * args.ring_size == world_size, f"The number of ulysses_size and ring_size should be equal to the world size."
|
237 |
+
from xfuser.core.distributed import (initialize_model_parallel,
|
238 |
+
init_distributed_environment)
|
239 |
+
init_distributed_environment(
|
240 |
+
rank=dist.get_rank(), world_size=dist.get_world_size())
|
241 |
+
|
242 |
+
initialize_model_parallel(
|
243 |
+
sequence_parallel_degree=dist.get_world_size(),
|
244 |
+
ring_degree=args.ring_size,
|
245 |
+
ulysses_degree=args.ulysses_size,
|
246 |
+
)
|
247 |
+
|
248 |
+
if args.use_prompt_extend:
|
249 |
+
if args.prompt_extend_method == "dashscope":
|
250 |
+
prompt_expander = DashScopePromptExpander(
|
251 |
+
model_name=args.prompt_extend_model, is_vl="i2v" in args.task)
|
252 |
+
elif args.prompt_extend_method == "local_qwen":
|
253 |
+
prompt_expander = QwenPromptExpander(
|
254 |
+
model_name=args.prompt_extend_model,
|
255 |
+
is_vl="i2v" in args.task,
|
256 |
+
device=rank)
|
257 |
+
else:
|
258 |
+
raise NotImplementedError(
|
259 |
+
f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
|
260 |
+
|
261 |
+
cfg = WAN_CONFIGS[args.task]
|
262 |
+
if args.ulysses_size > 1:
|
263 |
+
assert cfg.num_heads % args.ulysses_size == 0, f"`num_heads` must be divisible by `ulysses_size`."
|
264 |
+
|
265 |
+
logging.info(f"Generation job args: {args}")
|
266 |
+
logging.info(f"Generation model config: {cfg}")
|
267 |
+
|
268 |
+
if dist.is_initialized():
|
269 |
+
base_seed = [args.base_seed] if rank == 0 else [None]
|
270 |
+
dist.broadcast_object_list(base_seed, src=0)
|
271 |
+
args.base_seed = base_seed[0]
|
272 |
+
|
273 |
+
if "t2v" in args.task or "t2i" in args.task:
|
274 |
+
if args.prompt is None:
|
275 |
+
args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
|
276 |
+
logging.info(f"Input prompt: {args.prompt}")
|
277 |
+
if args.use_prompt_extend:
|
278 |
+
logging.info("Extending prompt ...")
|
279 |
+
if rank == 0:
|
280 |
+
prompt_output = prompt_expander(
|
281 |
+
args.prompt,
|
282 |
+
tar_lang=args.prompt_extend_target_lang,
|
283 |
+
seed=args.base_seed)
|
284 |
+
if prompt_output.status == False:
|
285 |
+
logging.info(
|
286 |
+
f"Extending prompt failed: {prompt_output.message}")
|
287 |
+
logging.info("Falling back to original prompt.")
|
288 |
+
input_prompt = args.prompt
|
289 |
+
else:
|
290 |
+
input_prompt = prompt_output.prompt
|
291 |
+
input_prompt = [input_prompt]
|
292 |
+
else:
|
293 |
+
input_prompt = [None]
|
294 |
+
if dist.is_initialized():
|
295 |
+
dist.broadcast_object_list(input_prompt, src=0)
|
296 |
+
args.prompt = input_prompt[0]
|
297 |
+
logging.info(f"Extended prompt: {args.prompt}")
|
298 |
+
|
299 |
+
logging.info("Creating WanT2V pipeline.")
|
300 |
+
wan_t2v = wan.WanT2V(
|
301 |
+
config=cfg,
|
302 |
+
checkpoint_dir=args.ckpt_dir,
|
303 |
+
device_id=device,
|
304 |
+
rank=rank,
|
305 |
+
t5_fsdp=args.t5_fsdp,
|
306 |
+
dit_fsdp=args.dit_fsdp,
|
307 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
308 |
+
t5_cpu=args.t5_cpu,
|
309 |
+
)
|
310 |
+
|
311 |
+
logging.info(
|
312 |
+
f"Generating {'image' if 't2i' in args.task else 'video'} ...")
|
313 |
+
video = wan_t2v.generate(
|
314 |
+
args.prompt,
|
315 |
+
size=SIZE_CONFIGS[args.size],
|
316 |
+
frame_num=args.frame_num,
|
317 |
+
shift=args.sample_shift,
|
318 |
+
sample_solver=args.sample_solver,
|
319 |
+
sampling_steps=args.sample_steps,
|
320 |
+
guide_scale=args.sample_guide_scale,
|
321 |
+
seed=args.base_seed,
|
322 |
+
offload_model=args.offload_model)
|
323 |
+
|
324 |
+
else:
|
325 |
+
if args.prompt is None:
|
326 |
+
args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
|
327 |
+
if args.image is None:
|
328 |
+
args.image = EXAMPLE_PROMPT[args.task]["image"]
|
329 |
+
logging.info(f"Input prompt: {args.prompt}")
|
330 |
+
logging.info(f"Input image: {args.image}")
|
331 |
+
|
332 |
+
img = Image.open(args.image).convert("RGB")
|
333 |
+
if args.use_prompt_extend:
|
334 |
+
logging.info("Extending prompt ...")
|
335 |
+
if rank == 0:
|
336 |
+
prompt_output = prompt_expander(
|
337 |
+
args.prompt,
|
338 |
+
tar_lang=args.prompt_extend_target_lang,
|
339 |
+
image=img,
|
340 |
+
seed=args.base_seed)
|
341 |
+
if prompt_output.status == False:
|
342 |
+
logging.info(
|
343 |
+
f"Extending prompt failed: {prompt_output.message}")
|
344 |
+
logging.info("Falling back to original prompt.")
|
345 |
+
input_prompt = args.prompt
|
346 |
+
else:
|
347 |
+
input_prompt = prompt_output.prompt
|
348 |
+
input_prompt = [input_prompt]
|
349 |
+
else:
|
350 |
+
input_prompt = [None]
|
351 |
+
if dist.is_initialized():
|
352 |
+
dist.broadcast_object_list(input_prompt, src=0)
|
353 |
+
args.prompt = input_prompt[0]
|
354 |
+
logging.info(f"Extended prompt: {args.prompt}")
|
355 |
+
|
356 |
+
logging.info("Creating WanI2V pipeline.")
|
357 |
+
wan_i2v = wan.WanI2V(
|
358 |
+
config=cfg,
|
359 |
+
checkpoint_dir=args.ckpt_dir,
|
360 |
+
device_id=device,
|
361 |
+
rank=rank,
|
362 |
+
t5_fsdp=args.t5_fsdp,
|
363 |
+
dit_fsdp=args.dit_fsdp,
|
364 |
+
use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
|
365 |
+
t5_cpu=args.t5_cpu,
|
366 |
+
)
|
367 |
+
|
368 |
+
logging.info("Generating video ...")
|
369 |
+
video = wan_i2v.generate(
|
370 |
+
args.prompt,
|
371 |
+
img,
|
372 |
+
max_area=MAX_AREA_CONFIGS[args.size],
|
373 |
+
frame_num=args.frame_num,
|
374 |
+
shift=args.sample_shift,
|
375 |
+
sample_solver=args.sample_solver,
|
376 |
+
sampling_steps=args.sample_steps,
|
377 |
+
guide_scale=args.sample_guide_scale,
|
378 |
+
seed=args.base_seed,
|
379 |
+
offload_model=args.offload_model)
|
380 |
+
|
381 |
+
if rank == 0:
|
382 |
+
if args.save_file is None:
|
383 |
+
formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
|
384 |
+
formatted_prompt = args.prompt.replace(" ", "_").replace("/",
|
385 |
+
"_")[:50]
|
386 |
+
suffix = '.png' if "t2i" in args.task else '.mp4'
|
387 |
+
args.save_file = f"videos/{args.task}_{args.size}_{args.ulysses_size}_{args.ring_size}_{formatted_prompt}_{formatted_time}" + suffix
|
388 |
+
|
389 |
+
if "t2i" in args.task:
|
390 |
+
logging.info(f"Saving generated image to {args.save_file}")
|
391 |
+
cache_image(
|
392 |
+
tensor=video.squeeze(1)[None],
|
393 |
+
save_file=args.save_file,
|
394 |
+
nrow=1,
|
395 |
+
normalize=True,
|
396 |
+
value_range=(-1, 1))
|
397 |
+
else:
|
398 |
+
logging.info(f"Saving generated video to {args.save_file}")
|
399 |
+
cache_video(
|
400 |
+
tensor=video[None],
|
401 |
+
save_file=args.save_file,
|
402 |
+
fps=cfg.sample_fps,
|
403 |
+
nrow=1,
|
404 |
+
normalize=True,
|
405 |
+
value_range=(-1, 1))
|
406 |
+
logging.info("Finished.")
|
407 |
+
|
408 |
+
|
409 |
+
|
410 |
+
if __name__ == "__main__":
|
411 |
+
args = _parse_args()
|
412 |
+
generate(args)
|
requirements.txt
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=2.4.0
|
2 |
+
torchvision>=0.19.0
|
3 |
+
opencv-python>=4.9.0.80
|
4 |
+
diffusers>=0.31.0
|
5 |
+
transformers>=4.49.0
|
6 |
+
tokenizers>=0.20.3
|
7 |
+
accelerate>=1.1.1
|
8 |
+
tqdm
|
9 |
+
imageio
|
10 |
+
easydict
|
11 |
+
ftfy
|
12 |
+
dashscope
|
13 |
+
imageio-ffmpeg
|
14 |
+
# flash_attn
|
15 |
+
gradio>=5.0.0
|
16 |
+
kornia
|
17 |
+
scikit-image==0.25.2
|
18 |
+
scipy==1.15.2
|
19 |
+
xfuser==0.4.3.post3
|
video_list/bear_g.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9ac72d17e79d3d4bbe047725f1c8ed86de7cc09d2d19dc6b80158f77967c9d12
|
3 |
+
size 677684
|
video_list/blackswan.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:d79222bae7552dff46dc9cccd4117595a4e2d419c3129383649b37b76116f512
|
3 |
+
size 718245
|
video_list/cat_box.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:081c4604f94766e1f984e0748d842470e5bf547e174bfe0dd9e6f7b2bb521e28
|
3 |
+
size 473103
|
video_list/cockatiel.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:dfd0bbe2cb8785addde99965d33e23c03e7795426120decd419c87968a2e2248
|
3 |
+
size 739609
|
video_list/dog_flower_g.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4a89adfe04aba2fdda8ba9dc701edc97936c6840893424af1c780ae21854ee60
|
3 |
+
size 264406
|
video_list/girl_and_dog.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0a9fdd6c2621e82a52236703b60211fe6b5d9bf26aba256742bae795aa37f65c
|
3 |
+
size 560330
|
video_list/gym_woman.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:95f324cd4cc528600a88a76c2d176fa2efbb825d9c67166a61d3d27e8ff9bdf1
|
3 |
+
size 326086
|
video_list/jeep.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ba0a4604c475c4b9e9ed0af4e2c087186c73b5f7ec32757c6ae1fa13c3023cd5
|
3 |
+
size 605012
|
video_list/puppy.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:640841865905d8185583f77ea687544ca98861d8a84b30088de4dfa0d170b6aa
|
3 |
+
size 160233
|
video_list/rabbit.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b537200243ef47033a3ca1b69aa2eac988eb547f330dbc319d9acc493db56fe9
|
3 |
+
size 212112
|
video_list/sea_lion.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:ac0786d7565882956c8000b470c38837144d0211ed380e2b4169040778da016c
|
3 |
+
size 695222
|
video_list/sea_turtle.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b0759b3562748c13d4fdf92d3f596de9b3f8786a7d7431c09ad3f8df24ca0d2d
|
3 |
+
size 917310
|
video_list/wolf.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:90879c594eb4ca1133144f07a96138396c49dcb0732c37a7816c657c3f451cae
|
3 |
+
size 382231
|
video_list/woman.mp4
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:80e8f0bdbab6aa26b510f5a90be3f6e689901d8837e2e69cd4163bba0e8de72e
|
3 |
+
size 949087
|
wan/__init__.py
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
from . import configs, distributed, modules
|
2 |
+
from .image2video import WanI2V
|
3 |
+
from .text2video import WanT2V
|
wan/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (276 Bytes). View file
|
|
wan/__pycache__/__init__.cpython-312.pyc
ADDED
Binary file (288 Bytes). View file
|
|
wan/__pycache__/image2video.cpython-310.pyc
ADDED
Binary file (9.73 kB). View file
|
|
wan/__pycache__/image2video.cpython-312.pyc
ADDED
Binary file (16.7 kB). View file
|
|
wan/__pycache__/text2video.cpython-310.pyc
ADDED
Binary file (25 kB). View file
|
|
wan/__pycache__/text2video.cpython-312.pyc
ADDED
Binary file (76.5 kB). View file
|
|
wan/configs/__init__.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
import copy
|
3 |
+
import os
|
4 |
+
|
5 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
6 |
+
|
7 |
+
from .wan_i2v_14B import i2v_14B
|
8 |
+
from .wan_t2v_1_3B import t2v_1_3B
|
9 |
+
from .wan_t2v_14B import t2v_14B
|
10 |
+
|
11 |
+
# the config of t2i_14B is the same as t2v_14B
|
12 |
+
t2i_14B = copy.deepcopy(t2v_14B)
|
13 |
+
t2i_14B.__name__ = 'Config: Wan T2I 14B'
|
14 |
+
|
15 |
+
WAN_CONFIGS = {
|
16 |
+
't2v-14B': t2v_14B,
|
17 |
+
't2v-1.3B': t2v_1_3B,
|
18 |
+
'i2v-14B': i2v_14B,
|
19 |
+
't2i-14B': t2i_14B,
|
20 |
+
}
|
21 |
+
|
22 |
+
SIZE_CONFIGS = {
|
23 |
+
'720*1280': (720, 1280),
|
24 |
+
'1280*720': (1280, 720),
|
25 |
+
'480*832': (480, 832),
|
26 |
+
'832*480': (832, 480),
|
27 |
+
'1024*1024': (1024, 1024),
|
28 |
+
}
|
29 |
+
|
30 |
+
MAX_AREA_CONFIGS = {
|
31 |
+
'720*1280': 720 * 1280,
|
32 |
+
'1280*720': 1280 * 720,
|
33 |
+
'480*832': 480 * 832,
|
34 |
+
'832*480': 832 * 480,
|
35 |
+
}
|
36 |
+
|
37 |
+
SUPPORTED_SIZES = {
|
38 |
+
't2v-14B': ('720*1280', '1280*720', '480*832', '832*480'),
|
39 |
+
't2v-1.3B': ('480*832', '832*480'),
|
40 |
+
'i2v-14B': ('720*1280', '1280*720', '480*832', '832*480'),
|
41 |
+
't2i-14B': tuple(SIZE_CONFIGS.keys()),
|
42 |
+
}
|
wan/configs/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (794 Bytes). View file
|
|
wan/configs/__pycache__/__init__.cpython-312.pyc
ADDED
Binary file (986 Bytes). View file
|
|
wan/configs/__pycache__/shared_config.cpython-310.pyc
ADDED
Binary file (814 Bytes). View file
|
|
wan/configs/__pycache__/shared_config.cpython-312.pyc
ADDED
Binary file (988 Bytes). View file
|
|
wan/configs/__pycache__/wan_i2v_14B.cpython-310.pyc
ADDED
Binary file (938 Bytes). View file
|
|
wan/configs/__pycache__/wan_i2v_14B.cpython-312.pyc
ADDED
Binary file (1.28 kB). View file
|
|
wan/configs/__pycache__/wan_t2v_14B.cpython-310.pyc
ADDED
Binary file (718 Bytes). View file
|
|
wan/configs/__pycache__/wan_t2v_14B.cpython-312.pyc
ADDED
Binary file (977 Bytes). View file
|
|
wan/configs/__pycache__/wan_t2v_1_3B.cpython-310.pyc
ADDED
Binary file (726 Bytes). View file
|
|
wan/configs/__pycache__/wan_t2v_1_3B.cpython-312.pyc
ADDED
Binary file (987 Bytes). View file
|
|
wan/configs/shared_config.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
import torch
|
3 |
+
from easydict import EasyDict
|
4 |
+
|
5 |
+
#------------------------ Wan shared config ------------------------#
|
6 |
+
wan_shared_cfg = EasyDict()
|
7 |
+
|
8 |
+
# t5
|
9 |
+
wan_shared_cfg.t5_model = 'umt5_xxl'
|
10 |
+
wan_shared_cfg.t5_dtype = torch.bfloat16
|
11 |
+
wan_shared_cfg.text_len = 512
|
12 |
+
|
13 |
+
# transformer
|
14 |
+
wan_shared_cfg.param_dtype = torch.bfloat16
|
15 |
+
|
16 |
+
# inference
|
17 |
+
wan_shared_cfg.num_train_timesteps = 1000
|
18 |
+
wan_shared_cfg.sample_fps = 16
|
19 |
+
wan_shared_cfg.sample_neg_prompt = '色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走'
|
wan/configs/wan_i2v_14B.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
import torch
|
3 |
+
from easydict import EasyDict
|
4 |
+
|
5 |
+
from .shared_config import wan_shared_cfg
|
6 |
+
|
7 |
+
#------------------------ Wan I2V 14B ------------------------#
|
8 |
+
|
9 |
+
i2v_14B = EasyDict(__name__='Config: Wan I2V 14B')
|
10 |
+
i2v_14B.update(wan_shared_cfg)
|
11 |
+
|
12 |
+
i2v_14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
|
13 |
+
i2v_14B.t5_tokenizer = 'google/umt5-xxl'
|
14 |
+
|
15 |
+
# clip
|
16 |
+
i2v_14B.clip_model = 'clip_xlm_roberta_vit_h_14'
|
17 |
+
i2v_14B.clip_dtype = torch.float16
|
18 |
+
i2v_14B.clip_checkpoint = 'models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth'
|
19 |
+
i2v_14B.clip_tokenizer = 'xlm-roberta-large'
|
20 |
+
|
21 |
+
# vae
|
22 |
+
i2v_14B.vae_checkpoint = 'Wan2.1_VAE.pth'
|
23 |
+
i2v_14B.vae_stride = (4, 8, 8)
|
24 |
+
|
25 |
+
# transformer
|
26 |
+
i2v_14B.patch_size = (1, 2, 2)
|
27 |
+
i2v_14B.dim = 5120
|
28 |
+
i2v_14B.ffn_dim = 13824
|
29 |
+
i2v_14B.freq_dim = 256
|
30 |
+
i2v_14B.num_heads = 40
|
31 |
+
i2v_14B.num_layers = 40
|
32 |
+
i2v_14B.window_size = (-1, -1)
|
33 |
+
i2v_14B.qk_norm = True
|
34 |
+
i2v_14B.cross_attn_norm = True
|
35 |
+
i2v_14B.eps = 1e-6
|
wan/configs/wan_t2v_14B.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
from easydict import EasyDict
|
3 |
+
|
4 |
+
from .shared_config import wan_shared_cfg
|
5 |
+
|
6 |
+
#------------------------ Wan T2V 14B ------------------------#
|
7 |
+
|
8 |
+
t2v_14B = EasyDict(__name__='Config: Wan T2V 14B')
|
9 |
+
t2v_14B.update(wan_shared_cfg)
|
10 |
+
|
11 |
+
# t5
|
12 |
+
t2v_14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
|
13 |
+
t2v_14B.t5_tokenizer = 'google/umt5-xxl'
|
14 |
+
|
15 |
+
# vae
|
16 |
+
t2v_14B.vae_checkpoint = 'Wan2.1_VAE.pth'
|
17 |
+
t2v_14B.vae_stride = (4, 8, 8)
|
18 |
+
|
19 |
+
# transformer
|
20 |
+
t2v_14B.patch_size = (1, 2, 2)
|
21 |
+
t2v_14B.dim = 5120
|
22 |
+
t2v_14B.ffn_dim = 13824
|
23 |
+
t2v_14B.freq_dim = 256
|
24 |
+
t2v_14B.num_heads = 40
|
25 |
+
t2v_14B.num_layers = 40
|
26 |
+
t2v_14B.window_size = (-1, -1)
|
27 |
+
t2v_14B.qk_norm = True
|
28 |
+
t2v_14B.cross_attn_norm = True
|
29 |
+
t2v_14B.eps = 1e-6
|
wan/configs/wan_t2v_1_3B.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
from easydict import EasyDict
|
3 |
+
|
4 |
+
from .shared_config import wan_shared_cfg
|
5 |
+
|
6 |
+
#------------------------ Wan T2V 1.3B ------------------------#
|
7 |
+
|
8 |
+
t2v_1_3B = EasyDict(__name__='Config: Wan T2V 1.3B')
|
9 |
+
t2v_1_3B.update(wan_shared_cfg)
|
10 |
+
|
11 |
+
# t5
|
12 |
+
t2v_1_3B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
|
13 |
+
t2v_1_3B.t5_tokenizer = 'google/umt5-xxl'
|
14 |
+
|
15 |
+
# vae
|
16 |
+
t2v_1_3B.vae_checkpoint = 'Wan2.1_VAE.pth'
|
17 |
+
t2v_1_3B.vae_stride = (4, 8, 8)
|
18 |
+
|
19 |
+
# transformer
|
20 |
+
t2v_1_3B.patch_size = (1, 2, 2)
|
21 |
+
t2v_1_3B.dim = 1536
|
22 |
+
t2v_1_3B.ffn_dim = 8960
|
23 |
+
t2v_1_3B.freq_dim = 256
|
24 |
+
t2v_1_3B.num_heads = 12
|
25 |
+
t2v_1_3B.num_layers = 30
|
26 |
+
t2v_1_3B.window_size = (-1, -1)
|
27 |
+
t2v_1_3B.qk_norm = True
|
28 |
+
t2v_1_3B.cross_attn_norm = True
|
29 |
+
t2v_1_3B.eps = 1e-6
|
wan/distributed/__init__.py
ADDED
File without changes
|
wan/distributed/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (133 Bytes). View file
|
|
wan/distributed/__pycache__/__init__.cpython-312.pyc
ADDED
Binary file (137 Bytes). View file
|
|
wan/distributed/__pycache__/fsdp.cpython-310.pyc
ADDED
Binary file (1 kB). View file
|
|
wan/distributed/__pycache__/fsdp.cpython-312.pyc
ADDED
Binary file (1.24 kB). View file
|
|
wan/distributed/__pycache__/xdit_context_parallel.cpython-310.pyc
ADDED
Binary file (5.29 kB). View file
|
|
wan/distributed/__pycache__/xdit_context_parallel.cpython-312.pyc
ADDED
Binary file (27.2 kB). View file
|
|
wan/distributed/fsdp.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
from functools import partial
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
6 |
+
from torch.distributed.fsdp import MixedPrecision, ShardingStrategy
|
7 |
+
from torch.distributed.fsdp.wrap import lambda_auto_wrap_policy
|
8 |
+
|
9 |
+
|
10 |
+
def shard_model(
|
11 |
+
model,
|
12 |
+
device_id,
|
13 |
+
param_dtype=torch.bfloat16,
|
14 |
+
reduce_dtype=torch.float32,
|
15 |
+
buffer_dtype=torch.float32,
|
16 |
+
process_group=None,
|
17 |
+
sharding_strategy=ShardingStrategy.FULL_SHARD,
|
18 |
+
sync_module_states=True,
|
19 |
+
):
|
20 |
+
model = FSDP(
|
21 |
+
module=model,
|
22 |
+
process_group=process_group,
|
23 |
+
sharding_strategy=sharding_strategy,
|
24 |
+
auto_wrap_policy=partial(
|
25 |
+
lambda_auto_wrap_policy, lambda_fn=lambda m: m in model.blocks),
|
26 |
+
mixed_precision=MixedPrecision(
|
27 |
+
param_dtype=param_dtype,
|
28 |
+
reduce_dtype=reduce_dtype,
|
29 |
+
buffer_dtype=buffer_dtype),
|
30 |
+
device_id=device_id,
|
31 |
+
sync_module_states=sync_module_states)
|
32 |
+
return model
|
wan/distributed/xdit_context_parallel.py
ADDED
@@ -0,0 +1,420 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
|
2 |
+
from time import time
|
3 |
+
import torch
|
4 |
+
import torch.cuda.amp as amp
|
5 |
+
from xfuser.core.distributed import (get_sequence_parallel_rank,
|
6 |
+
get_sequence_parallel_world_size,
|
7 |
+
get_sp_group)
|
8 |
+
from xfuser.core.long_ctx_attention import xFuserLongContextAttention
|
9 |
+
|
10 |
+
from ..modules.model import sinusoidal_embedding_1d
|
11 |
+
from typing import List, Union, Optional, Tuple
|
12 |
+
import torch.nn.functional as F
|
13 |
+
import torch
|
14 |
+
|
15 |
+
|
16 |
+
def pad_freqs(original_tensor, target_len):
|
17 |
+
seq_len, s1, s2 = original_tensor.shape
|
18 |
+
pad_size = target_len - seq_len
|
19 |
+
padding_tensor = torch.ones(
|
20 |
+
pad_size,
|
21 |
+
s1,
|
22 |
+
s2,
|
23 |
+
dtype=original_tensor.dtype,
|
24 |
+
device=original_tensor.device)
|
25 |
+
padded_tensor = torch.cat([original_tensor, padding_tensor], dim=0)
|
26 |
+
return padded_tensor
|
27 |
+
|
28 |
+
|
29 |
+
@amp.autocast(enabled=False)
|
30 |
+
def rope_apply(x, grid_sizes, freqs):
|
31 |
+
"""
|
32 |
+
x: [B, L, N, C].
|
33 |
+
grid_sizes: [B, 3].
|
34 |
+
freqs: [M, C // 2].
|
35 |
+
"""
|
36 |
+
s, n, c = x.size(1), x.size(2), x.size(3) // 2
|
37 |
+
# split freqs
|
38 |
+
freqs = freqs.split([c - 2 * (c // 3), c // 3, c // 3], dim=1)
|
39 |
+
|
40 |
+
# loop over samples
|
41 |
+
output = []
|
42 |
+
for i, (f, h, w) in enumerate(grid_sizes.tolist()):
|
43 |
+
seq_len = f * h * w
|
44 |
+
|
45 |
+
# precompute multipliers
|
46 |
+
x_i = torch.view_as_complex(x[i, :s].to(torch.float64).reshape(
|
47 |
+
s, n, -1, 2))
|
48 |
+
freqs_i = torch.cat([
|
49 |
+
freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
50 |
+
freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
51 |
+
freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1)
|
52 |
+
],
|
53 |
+
dim=-1).reshape(seq_len, 1, -1)
|
54 |
+
|
55 |
+
# apply rotary embedding
|
56 |
+
sp_size = get_sequence_parallel_world_size()
|
57 |
+
sp_rank = get_sequence_parallel_rank()
|
58 |
+
freqs_i = pad_freqs(freqs_i, s * sp_size)
|
59 |
+
s_per_rank = s
|
60 |
+
freqs_i_rank = freqs_i[(sp_rank * s_per_rank):((sp_rank + 1) *
|
61 |
+
s_per_rank), :, :]
|
62 |
+
x_i = torch.view_as_real(x_i * freqs_i_rank).flatten(2)
|
63 |
+
x_i = torch.cat([x_i, x[i, s:]])
|
64 |
+
|
65 |
+
# append to collection
|
66 |
+
output.append(x_i)
|
67 |
+
return torch.stack(output).float()
|
68 |
+
|
69 |
+
|
70 |
+
@torch.no_grad() # Usually don't need gradients for mask generation
|
71 |
+
def generate_attention_mask(
|
72 |
+
attention_map: torch.Tensor,
|
73 |
+
grid_sizes: torch.Tensor,
|
74 |
+
target_x_shape: Tuple[int, int, int, int], # Target shape: (C, T, H, W)
|
75 |
+
batch_index: int = 0,
|
76 |
+
target_word_indices: Union[List[int], slice] = None,
|
77 |
+
head_index: Optional[int] = None, # Process single head or average
|
78 |
+
word_aggregation_method: str = 'mean', # How to combine scores for multiple words
|
79 |
+
upsample_mode_spatial: str = 'nearest', # 'nearest', 'bilinear'
|
80 |
+
upsample_mode_temporal: str = 'nearest', # 'nearest', 'linear'
|
81 |
+
output_dtype: torch.dtype = torch.float32 # or torch.bool for soft mask before threshold
|
82 |
+
) -> torch.Tensor:
|
83 |
+
"""
|
84 |
+
Generates a binary mask from an attention map based on attention towards target words.
|
85 |
+
|
86 |
+
The mask identifies regions in the video (x) that attend strongly to the specified
|
87 |
+
context words, exceeding a given threshold. The mask has the same dimensions as x.
|
88 |
+
|
89 |
+
Args:
|
90 |
+
attention_map (torch.Tensor): Attention weights [B, Head_num, Lx, Lctx].
|
91 |
+
Lx = flattened video tokens (patches),
|
92 |
+
Lctx = context tokens (words).
|
93 |
+
target_word_indices (Union[List[int], slice]): Indices or slice for the target
|
94 |
+
word(s) in the Lctx dimension.
|
95 |
+
grid_sizes (torch.Tensor): Patch grid dimensions [B, 3] -> (F, H_patch, W_patch)
|
96 |
+
for each batch item, corresponding to Lx.
|
97 |
+
F, H_patch, W_patch should be integers.
|
98 |
+
target_x_shape (Tuple[int, int, int, int]): The desired output shape [C, T, H, W],
|
99 |
+
matching the original video tensor x.
|
100 |
+
threshold (float): Value between 0 and 1. Attention scores >= threshold become 1 (True),
|
101 |
+
otherwise 0 (False).
|
102 |
+
batch_index (int, optional): Batch item to process. Defaults to 0.
|
103 |
+
head_index (Optional[int], optional): Specific head to use. If None, average
|
104 |
+
attention across all heads. Defaults to None.
|
105 |
+
word_aggregation_method (str, optional): How to aggregate scores if multiple
|
106 |
+
target_word_indices are given ('mean',
|
107 |
+
'sum', 'max'). Defaults to 'mean'.
|
108 |
+
upsample_mode_spatial (str, optional): PyTorch interpolate mode for H, W dimensions.
|
109 |
+
Defaults to 'nearest'.
|
110 |
+
upsample_mode_temporal (str, optional): PyTorch interpolate mode for T dimension.
|
111 |
+
Defaults to 'nearest'.
|
112 |
+
output_dtype (torch.dtype, optional): Data type of the output mask.
|
113 |
+
Defaults to torch.bool.
|
114 |
+
|
115 |
+
Returns:
|
116 |
+
torch.Tensor: A binary mask tensor of shape target_x_shape [C, T, H, W].
|
117 |
+
|
118 |
+
Raises:
|
119 |
+
TypeError: If inputs are not torch.Tensors.
|
120 |
+
ValueError: If tensor dimensions or indices are invalid, or if
|
121 |
+
aggregation/upsample modes are unknown.
|
122 |
+
IndexError: If batch_index or head_index are out of bounds.
|
123 |
+
"""
|
124 |
+
# --- Input Validation ---
|
125 |
+
if not isinstance(attention_map, torch.Tensor):
|
126 |
+
raise TypeError("attention_map must be a torch.Tensor")
|
127 |
+
if not isinstance(grid_sizes, torch.Tensor):
|
128 |
+
raise TypeError("grid_sizes must be a torch.Tensor")
|
129 |
+
if attention_map.dim() != 4:
|
130 |
+
raise ValueError(f"attention_map must be [B, H, Lx, Lctx], got {attention_map.dim()} dims")
|
131 |
+
if grid_sizes.dim() != 2 or grid_sizes.shape[1] != 3:
|
132 |
+
raise ValueError(f"grid_sizes must be [B, 3], got {grid_sizes.shape}")
|
133 |
+
if len(target_x_shape) != 4:
|
134 |
+
raise ValueError(f"target_x_shape must be [C, T, H, W], got length {len(target_x_shape)}")
|
135 |
+
|
136 |
+
B, H, Lx, Lctx = attention_map.shape
|
137 |
+
C_out, T_out, H_out, W_out = target_x_shape
|
138 |
+
|
139 |
+
if not 0 <= batch_index < B:
|
140 |
+
raise IndexError(f"batch_index {batch_index} out of range for batch size {B}")
|
141 |
+
if head_index is not None and not 0 <= head_index < H:
|
142 |
+
raise IndexError(f"head_index {head_index} out of range for head count {H}")
|
143 |
+
if word_aggregation_method not in ['mean', 'sum', 'max']:
|
144 |
+
raise ValueError(f"Unknown word_aggregation_method: {word_aggregation_method}")
|
145 |
+
if upsample_mode_spatial not in ['nearest', 'bilinear']:
|
146 |
+
raise ValueError(f"Unknown upsample_mode_spatial: {upsample_mode_spatial}")
|
147 |
+
if upsample_mode_temporal not in ['nearest', 'linear']:
|
148 |
+
raise ValueError(f"Unknown upsample_mode_temporal: {upsample_mode_temporal}")
|
149 |
+
|
150 |
+
|
151 |
+
# --- Select Head(s) ---
|
152 |
+
if head_index is None:
|
153 |
+
# Average across heads. Shape -> [Lx, Lctx]
|
154 |
+
attn_map_processed = attention_map[batch_index].mean(dim=0)
|
155 |
+
else:
|
156 |
+
# Select specific head. Shape -> [Lx, Lctx]
|
157 |
+
attn_map_processed = attention_map[batch_index, head_index]
|
158 |
+
|
159 |
+
# --- Select and Aggregate Word Attention ---
|
160 |
+
# Ensure target_word_indices are valid before slicing
|
161 |
+
if isinstance(target_word_indices, slice):
|
162 |
+
_slice_indices = range(*target_word_indices.indices(Lctx))
|
163 |
+
if not _slice_indices: # Empty slice
|
164 |
+
num_words = 0
|
165 |
+
elif _slice_indices.start >= Lctx or _slice_indices.stop < -Lctx : # Basic out of bounds check
|
166 |
+
num_words = len(_slice_indices) # Proceed cautiously or add stricter check
|
167 |
+
else:
|
168 |
+
num_words = len(_slice_indices)
|
169 |
+
word_indices_str = f"slice({_slice_indices.start}:{_slice_indices.stop}:{_slice_indices.step})"
|
170 |
+
word_attn_scores = attn_map_processed[:, target_word_indices] # Shape -> [Lx, num_words]
|
171 |
+
elif isinstance(target_word_indices, list):
|
172 |
+
# Check indices are within bounds
|
173 |
+
valid_indices = [idx for idx in target_word_indices if -Lctx <= idx < Lctx]
|
174 |
+
if not valid_indices:
|
175 |
+
num_words = 0
|
176 |
+
word_attn_scores = torch.empty((Lx, 0), device=attention_map.device, dtype=attention_map.dtype) # Handle empty case
|
177 |
+
else:
|
178 |
+
word_attn_scores = attn_map_processed[:, valid_indices] # Shape -> [Lx, num_words]
|
179 |
+
num_words = len(valid_indices)
|
180 |
+
word_indices_str = str(valid_indices) # Report used indices
|
181 |
+
else:
|
182 |
+
raise TypeError(f"target_word_indices must be list or slice, got {type(target_word_indices)}")
|
183 |
+
|
184 |
+
if num_words > 1:
|
185 |
+
if word_aggregation_method == 'mean':
|
186 |
+
aggregated_scores = word_attn_scores.mean(dim=-1)
|
187 |
+
elif word_aggregation_method == 'sum':
|
188 |
+
aggregated_scores = word_attn_scores.sum(dim=-1)
|
189 |
+
elif word_aggregation_method == 'max':
|
190 |
+
aggregated_scores = word_attn_scores.max(dim=-1).values
|
191 |
+
# aggregated_scores shape -> [Lx]
|
192 |
+
elif num_words == 1:
|
193 |
+
aggregated_scores = word_attn_scores.squeeze(-1) # Shape -> [Lx]
|
194 |
+
else: # No valid words selected
|
195 |
+
return torch.zeros(target_x_shape, dtype=output_dtype, device=attention_map.device)
|
196 |
+
|
197 |
+
# --- Reshape to Video Patch Grid ---
|
198 |
+
# Ensure grid sizes are integers
|
199 |
+
f_patch, h_patch, w_patch = map(int, grid_sizes[batch_index].tolist())
|
200 |
+
actual_num_tokens = f_patch * h_patch * w_patch
|
201 |
+
|
202 |
+
if actual_num_tokens == 0:
|
203 |
+
return torch.zeros(target_x_shape, dtype=output_dtype, device=attention_map.device)
|
204 |
+
|
205 |
+
# Handle mismatch between expected tokens (from grid) and actual attention length (Lx)
|
206 |
+
if actual_num_tokens > Lx:
|
207 |
+
# Pad aggregated_scores to actual_num_tokens size
|
208 |
+
padding_size = actual_num_tokens - aggregated_scores.numel()
|
209 |
+
scores_padded = F.pad(aggregated_scores, (0, padding_size), "constant", 0)
|
210 |
+
scores_unpadded = scores_padded # Use the padded version for reshaping
|
211 |
+
# This scenario is less common than Lx > actual_num_tokens
|
212 |
+
elif actual_num_tokens < Lx:
|
213 |
+
scores_unpadded = aggregated_scores[:actual_num_tokens]
|
214 |
+
else:
|
215 |
+
scores_unpadded = aggregated_scores # Shape [actual_num_tokens]
|
216 |
+
|
217 |
+
try:
|
218 |
+
# Reshape to [F_patch, H_patch, W_patch]
|
219 |
+
attention_patch_grid = scores_unpadded.reshape(f_patch, h_patch, w_patch)
|
220 |
+
except RuntimeError as e:
|
221 |
+
raise e
|
222 |
+
|
223 |
+
# --- Upsample to Original Video Resolution ---
|
224 |
+
# Add batch and channel dims for interpolation: [1, 1, F_patch, H_patch, W_patch]
|
225 |
+
# Note: Assuming attention is channel-agnostic here.
|
226 |
+
grid_for_upsample = attention_patch_grid.unsqueeze(0).unsqueeze(0).float() # Interpolate needs float
|
227 |
+
|
228 |
+
|
229 |
+
# --- SIMPLIFIED LOGIC: Always use 3D interpolation ---
|
230 |
+
target_size_3d = (T_out, H_out, W_out)
|
231 |
+
|
232 |
+
# Determine the 3D interpolation mode.
|
233 |
+
# Default to 'nearest' unless temporal dimension changes AND 'linear' is requested.
|
234 |
+
if upsample_mode_temporal == 'linear' and f_patch != T_out:
|
235 |
+
upsample_mode_3d = 'trilinear'
|
236 |
+
align_corners_3d = False # align_corners usually False for non-nearest modes
|
237 |
+
else:
|
238 |
+
# Use 'nearest' if T isn't changing, or if temporal mode is 'nearest'.
|
239 |
+
# 'nearest' is generally safer and handles spatial modes implicitly.
|
240 |
+
upsample_mode_3d = 'nearest'
|
241 |
+
align_corners_3d = None # align_corners=None for nearest
|
242 |
+
|
243 |
+
upsampled_scores_grid = F.interpolate(grid_for_upsample,
|
244 |
+
size=target_size_3d,
|
245 |
+
mode=upsample_mode_3d,
|
246 |
+
align_corners=align_corners_3d)
|
247 |
+
# Expected shape: [1, 1, T_out, H_out, W_out] == [1, 1, 21, 60, 104]
|
248 |
+
|
249 |
+
# --- END SIMPLIFIED LOGIC ---
|
250 |
+
|
251 |
+
# Remove batch and channel dims: [T_out, H_out, W_out]
|
252 |
+
upsampled_scores = upsampled_scores_grid.squeeze(0).squeeze(0)
|
253 |
+
|
254 |
+
# --- Thresholding ---
|
255 |
+
binary_mask_thw = (upsampled_scores / torch.max(upsampled_scores)) # Shape [T_out, H_out, W_out]
|
256 |
+
|
257 |
+
# --- Expand Channel Dimension ---
|
258 |
+
# Repeat the mask across the channel dimension C_out
|
259 |
+
# Input shape: [T_out, H_out, W_out]
|
260 |
+
# After unsqueeze(0): [1, T_out, H_out, W_out]
|
261 |
+
# Target shape: [C_out, T_out, H_out, W_out]
|
262 |
+
# This expand operation is valid as explained above.
|
263 |
+
final_mask = binary_mask_thw.unsqueeze(0).expand(C_out, T_out, H_out, W_out)
|
264 |
+
|
265 |
+
return final_mask.to(dtype=output_dtype)
|
266 |
+
|
267 |
+
|
268 |
+
def usp_dit_forward(
|
269 |
+
self,
|
270 |
+
x,
|
271 |
+
t,
|
272 |
+
context,
|
273 |
+
seq_len,
|
274 |
+
clip_fea=None,
|
275 |
+
y=None,
|
276 |
+
words_indices=None,
|
277 |
+
block_id=-1,
|
278 |
+
type=None,
|
279 |
+
timestep=None
|
280 |
+
):
|
281 |
+
"""
|
282 |
+
x: A list of videos each with shape [C, T, H, W].
|
283 |
+
t: [B].
|
284 |
+
context: A list of text embeddings each with shape [L, C].
|
285 |
+
"""
|
286 |
+
if self.model_type == 'i2v':
|
287 |
+
assert clip_fea is not None and y is not None
|
288 |
+
# params
|
289 |
+
device = self.patch_embedding.weight.device
|
290 |
+
if self.freqs.device != device:
|
291 |
+
self.freqs = self.freqs.to(device)
|
292 |
+
|
293 |
+
if y is not None:
|
294 |
+
x = [torch.cat([u, v], dim=0) for u, v in zip(x, y)]
|
295 |
+
|
296 |
+
# embeddings
|
297 |
+
x = [self.patch_embedding(u.unsqueeze(0)) for u in x]
|
298 |
+
grid_sizes = torch.stack(
|
299 |
+
[torch.tensor(u.shape[2:], dtype=torch.long) for u in x])
|
300 |
+
|
301 |
+
x = [u.flatten(2).transpose(1, 2) for u in x]
|
302 |
+
seq_lens = torch.tensor([u.size(1) for u in x], dtype=torch.long)
|
303 |
+
assert seq_lens.max() <= seq_len
|
304 |
+
x = torch.cat([
|
305 |
+
torch.cat([u, u.new_zeros(1, seq_len - u.size(1), u.size(2))], dim=1)
|
306 |
+
for u in x
|
307 |
+
])
|
308 |
+
|
309 |
+
# time embeddings
|
310 |
+
with amp.autocast(dtype=torch.float32):
|
311 |
+
e = self.time_embedding(
|
312 |
+
sinusoidal_embedding_1d(self.freq_dim, t).float())
|
313 |
+
e0 = self.time_projection(e).unflatten(1, (6, self.dim))
|
314 |
+
assert e.dtype == torch.float32 and e0.dtype == torch.float32
|
315 |
+
|
316 |
+
# context
|
317 |
+
context_lens = None
|
318 |
+
context = self.text_embedding(
|
319 |
+
torch.stack([
|
320 |
+
torch.cat([u, u.new_zeros(self.text_len - u.size(0), u.size(1))])
|
321 |
+
for u in context
|
322 |
+
]))
|
323 |
+
|
324 |
+
if clip_fea is not None:
|
325 |
+
context_clip = self.img_emb(clip_fea) # bs x 257 x dim
|
326 |
+
context = torch.concat([context_clip, context], dim=1)
|
327 |
+
|
328 |
+
# arguments
|
329 |
+
kwargs = dict(
|
330 |
+
e=e0,
|
331 |
+
seq_lens=seq_lens,
|
332 |
+
grid_sizes=grid_sizes,
|
333 |
+
freqs=self.freqs,
|
334 |
+
context=context,
|
335 |
+
context_lens=context_lens,
|
336 |
+
collect_attn_map=False)
|
337 |
+
|
338 |
+
# Context Parallel
|
339 |
+
x = torch.chunk(
|
340 |
+
x, get_sequence_parallel_world_size(),
|
341 |
+
dim=1)[get_sequence_parallel_rank()]
|
342 |
+
|
343 |
+
save_block_id = block_id
|
344 |
+
attn_map = None
|
345 |
+
binary_mask = None
|
346 |
+
for i, block in enumerate(self.blocks):
|
347 |
+
kwargs["collect_attn_map"] = False
|
348 |
+
if i == save_block_id:
|
349 |
+
kwargs["collect_attn_map"] = True
|
350 |
+
x, attn_map = block(x, **kwargs)
|
351 |
+
else:
|
352 |
+
x = block(x, **kwargs)
|
353 |
+
|
354 |
+
# head
|
355 |
+
x = self.head(x, e)
|
356 |
+
# Context Parallel
|
357 |
+
x = get_sp_group().all_gather(x, dim=1)
|
358 |
+
|
359 |
+
# unpatchify
|
360 |
+
x = self.unpatchify(x, grid_sizes)
|
361 |
+
|
362 |
+
if save_block_id != -1 and words_indices is not None:
|
363 |
+
attention_map = get_sp_group().all_gather(attn_map, dim=2)
|
364 |
+
binary_mask = generate_attention_mask(
|
365 |
+
attention_map=attention_map, # [1, 12, 32760, 512] batchsize, head_num, l_x, l_context
|
366 |
+
target_word_indices=words_indices,
|
367 |
+
grid_sizes=grid_sizes, # Make sure grid_sizes covers the full batch
|
368 |
+
target_x_shape=x[0].shape, # channel, frames, h, W
|
369 |
+
batch_index=0, # Process the first item in the batch
|
370 |
+
head_index=None, # Average over heads
|
371 |
+
word_aggregation_method='mean'
|
372 |
+
)
|
373 |
+
|
374 |
+
return [u.float() for u in x], binary_mask
|
375 |
+
|
376 |
+
|
377 |
+
|
378 |
+
def usp_attn_forward(self,
|
379 |
+
x,
|
380 |
+
seq_lens,
|
381 |
+
grid_sizes,
|
382 |
+
freqs,
|
383 |
+
dtype=torch.bfloat16):
|
384 |
+
b, s, n, d = *x.shape[:2], self.num_heads, self.head_dim
|
385 |
+
half_dtypes = (torch.float16, torch.bfloat16)
|
386 |
+
|
387 |
+
def half(x):
|
388 |
+
return x if x.dtype in half_dtypes else x.to(dtype)
|
389 |
+
|
390 |
+
# query, key, value function
|
391 |
+
def qkv_fn(x):
|
392 |
+
q = self.norm_q(self.q(x)).view(b, s, n, d)
|
393 |
+
k = self.norm_k(self.k(x)).view(b, s, n, d)
|
394 |
+
v = self.v(x).view(b, s, n, d)
|
395 |
+
return q, k, v
|
396 |
+
q, k, v = qkv_fn(x)
|
397 |
+
q = rope_apply(q, grid_sizes, freqs)
|
398 |
+
k = rope_apply(k, grid_sizes, freqs)
|
399 |
+
|
400 |
+
# TODO: We should use unpaded q,k,v for attention.
|
401 |
+
# k_lens = seq_lens // get_sequence_parallel_world_size()
|
402 |
+
# if k_lens is not None:
|
403 |
+
# q = torch.cat([u[:l] for u, l in zip(q, k_lens)]).unsqueeze(0)
|
404 |
+
# k = torch.cat([u[:l] for u, l in zip(k, k_lens)]).unsqueeze(0)
|
405 |
+
# v = torch.cat([u[:l] for u, l in zip(v, k_lens)]).unsqueeze(0)
|
406 |
+
|
407 |
+
x = xFuserLongContextAttention()(
|
408 |
+
None,
|
409 |
+
query=half(q),
|
410 |
+
key=half(k),
|
411 |
+
value=half(v),
|
412 |
+
window_size=self.window_size)
|
413 |
+
|
414 |
+
# TODO: padding after attention.
|
415 |
+
# x = torch.cat([x, x.new_zeros(b, s - x.size(1), n, d)], dim=1)
|
416 |
+
|
417 |
+
# output
|
418 |
+
x = x.flatten(2)
|
419 |
+
x = self.o(x)
|
420 |
+
return x
|