Cccccz commited on
Commit
d7b69b2
·
verified ·
1 Parent(s): 891eb6b

Upload Wan2.1

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. Wan2.1/.codex +0 -0
  3. Wan2.1/.gitignore +37 -0
  4. Wan2.1/.pytest_cache/.gitignore +2 -0
  5. Wan2.1/.pytest_cache/CACHEDIR.TAG +4 -0
  6. Wan2.1/.pytest_cache/README.md +8 -0
  7. Wan2.1/.pytest_cache/v/cache/nodeids +1 -0
  8. Wan2.1/.style.yapf +393 -0
  9. Wan2.1/INSTALL.md +54 -0
  10. Wan2.1/LICENSE.txt +201 -0
  11. Wan2.1/Makefile +5 -0
  12. Wan2.1/README.md +674 -0
  13. Wan2.1/assets/comp_effic.png +3 -0
  14. Wan2.1/assets/data_for_diff_stage.jpg +3 -0
  15. Wan2.1/assets/i2v_res.png +3 -0
  16. Wan2.1/assets/logo.png +3 -0
  17. Wan2.1/assets/t2v_res.jpg +3 -0
  18. Wan2.1/assets/vben_vs_sota.png +3 -0
  19. Wan2.1/assets/video_dit_arch.jpg +3 -0
  20. Wan2.1/assets/video_vae_res.jpg +3 -0
  21. Wan2.1/examples/flf2v_input_first_frame.png +3 -0
  22. Wan2.1/examples/flf2v_input_last_frame.png +3 -0
  23. Wan2.1/examples/girl.png +3 -0
  24. Wan2.1/examples/i2v_input.JPG +3 -0
  25. Wan2.1/examples/snake.png +3 -0
  26. Wan2.1/generate.py +587 -0
  27. Wan2.1/gradio/fl2v_14B_singleGPU.py +254 -0
  28. Wan2.1/gradio/i2v_14B_singleGPU.py +288 -0
  29. Wan2.1/gradio/t2i_14B_singleGPU.py +206 -0
  30. Wan2.1/gradio/t2v_1.3B_singleGPU.py +208 -0
  31. Wan2.1/gradio/t2v_14B_singleGPU.py +206 -0
  32. Wan2.1/gradio/vace.py +349 -0
  33. Wan2.1/pyproject.toml +67 -0
  34. Wan2.1/requirements.txt +16 -0
  35. Wan2.1/tests/README.md +6 -0
  36. Wan2.1/tests/test.sh +120 -0
  37. Wan2.1/wan/__init__.py +5 -0
  38. Wan2.1/wan/__pycache__/__init__.cpython-312.pyc +0 -0
  39. Wan2.1/wan/configs/__init__.py +53 -0
  40. Wan2.1/wan/configs/__pycache__/__init__.cpython-312.pyc +0 -0
  41. Wan2.1/wan/configs/__pycache__/shared_config.cpython-312.pyc +0 -0
  42. Wan2.1/wan/configs/__pycache__/wan_i2v_14B.cpython-312.pyc +0 -0
  43. Wan2.1/wan/configs/__pycache__/wan_t2v_14B.cpython-312.pyc +0 -0
  44. Wan2.1/wan/configs/__pycache__/wan_t2v_1_3B.cpython-312.pyc +0 -0
  45. Wan2.1/wan/configs/shared_config.py +19 -0
  46. Wan2.1/wan/configs/wan_i2v_14B.py +36 -0
  47. Wan2.1/wan/configs/wan_t2v_14B.py +29 -0
  48. Wan2.1/wan/configs/wan_t2v_1_3B.py +29 -0
  49. Wan2.1/wan/distributed/__init__.py +0 -0
  50. Wan2.1/wan/distributed/__pycache__/__init__.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -43116,3 +43116,4 @@ CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_029/01-08
43116
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_029/01-08-2000-NA-CT[[:space:]]ABDOMEN[[:space:]]WWO[[:space:]]CONT-44277/3.000000-ABD-24994/1-01.dcm filter=lfs diff=lfs merge=lfs -text
43117
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_001/11-30-1999-NA-CT-CAP[[:space:]]WWO[[:space:]]CON-00377/3.000000-C-A-P-42120/1-12.dcm filter=lfs diff=lfs merge=lfs -text
43118
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_001/11-30-1999-NA-CT-CAP[[:space:]]WWO[[:space:]]CON-00377/3.000000-C-A-P-42120/1-13.dcm filter=lfs diff=lfs merge=lfs -text
 
 
43116
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_029/01-08-2000-NA-CT[[:space:]]ABDOMEN[[:space:]]WWO[[:space:]]CONT-44277/3.000000-ABD-24994/1-01.dcm filter=lfs diff=lfs merge=lfs -text
43117
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_001/11-30-1999-NA-CT-CAP[[:space:]]WWO[[:space:]]CON-00377/3.000000-C-A-P-42120/1-12.dcm filter=lfs diff=lfs merge=lfs -text
43118
  CT/liver/data/raw/hcc_tace_seg/manifest-1643035385102/HCC-TACE-Seg/HCC_001/11-30-1999-NA-CT-CAP[[:space:]]WWO[[:space:]]CON-00377/3.000000-C-A-P-42120/1-13.dcm filter=lfs diff=lfs merge=lfs -text
43119
+ Wan2.1/examples/i2v_input.JPG filter=lfs diff=lfs merge=lfs -text
Wan2.1/.codex ADDED
File without changes
Wan2.1/.gitignore ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .*
2
+ *.py[cod]
3
+ # *.jpg
4
+ *.jpeg
5
+ # *.png
6
+ *.gif
7
+ *.bmp
8
+ *.mp4
9
+ *.mov
10
+ *.mkv
11
+ *.log
12
+ *.zip
13
+ *.pt
14
+ *.pth
15
+ *.ckpt
16
+ *.safetensors
17
+ *.json
18
+ # *.txt
19
+ *.backup
20
+ *.pkl
21
+ *.html
22
+ *.pdf
23
+ *.whl
24
+ cache
25
+ __pycache__/
26
+ storage/
27
+ samples/
28
+ !.gitignore
29
+ !requirements.txt
30
+ .DS_Store
31
+ *DS_Store
32
+ google/
33
+ Wan2.1-T2V-14B/
34
+ Wan2.1-T2V-1.3B/
35
+ Wan2.1-I2V-14B-480P/
36
+ Wan2.1-I2V-14B-720P/
37
+ poetry.lock
Wan2.1/.pytest_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Created by pytest automatically.
2
+ *
Wan2.1/.pytest_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
2
+ # This file is a cache directory tag created by pytest.
3
+ # For information about cache directory tags, see:
4
+ # https://bford.info/cachedir/spec.html
Wan2.1/.pytest_cache/README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # pytest cache directory #
2
+
3
+ This directory contains data from the pytest's cache plugin,
4
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
5
+
6
+ **Do not** commit this to version control.
7
+
8
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
Wan2.1/.pytest_cache/v/cache/nodeids ADDED
@@ -0,0 +1 @@
 
 
1
+ []
Wan2.1/.style.yapf ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [style]
2
+ # Align closing bracket with visual indentation.
3
+ align_closing_bracket_with_visual_indent=False
4
+
5
+ # Allow dictionary keys to exist on multiple lines. For example:
6
+ #
7
+ # x = {
8
+ # ('this is the first element of a tuple',
9
+ # 'this is the second element of a tuple'):
10
+ # value,
11
+ # }
12
+ allow_multiline_dictionary_keys=False
13
+
14
+ # Allow lambdas to be formatted on more than one line.
15
+ allow_multiline_lambdas=False
16
+
17
+ # Allow splitting before a default / named assignment in an argument list.
18
+ allow_split_before_default_or_named_assigns=False
19
+
20
+ # Allow splits before the dictionary value.
21
+ allow_split_before_dict_value=True
22
+
23
+ # Let spacing indicate operator precedence. For example:
24
+ #
25
+ # a = 1 * 2 + 3 / 4
26
+ # b = 1 / 2 - 3 * 4
27
+ # c = (1 + 2) * (3 - 4)
28
+ # d = (1 - 2) / (3 + 4)
29
+ # e = 1 * 2 - 3
30
+ # f = 1 + 2 + 3 + 4
31
+ #
32
+ # will be formatted as follows to indicate precedence:
33
+ #
34
+ # a = 1*2 + 3/4
35
+ # b = 1/2 - 3*4
36
+ # c = (1+2) * (3-4)
37
+ # d = (1-2) / (3+4)
38
+ # e = 1*2 - 3
39
+ # f = 1 + 2 + 3 + 4
40
+ #
41
+ arithmetic_precedence_indication=False
42
+
43
+ # Number of blank lines surrounding top-level function and class
44
+ # definitions.
45
+ blank_lines_around_top_level_definition=2
46
+
47
+ # Insert a blank line before a class-level docstring.
48
+ blank_line_before_class_docstring=False
49
+
50
+ # Insert a blank line before a module docstring.
51
+ blank_line_before_module_docstring=False
52
+
53
+ # Insert a blank line before a 'def' or 'class' immediately nested
54
+ # within another 'def' or 'class'. For example:
55
+ #
56
+ # class Foo:
57
+ # # <------ this blank line
58
+ # def method():
59
+ # ...
60
+ blank_line_before_nested_class_or_def=True
61
+
62
+ # Do not split consecutive brackets. Only relevant when
63
+ # dedent_closing_brackets is set. For example:
64
+ #
65
+ # call_func_that_takes_a_dict(
66
+ # {
67
+ # 'key1': 'value1',
68
+ # 'key2': 'value2',
69
+ # }
70
+ # )
71
+ #
72
+ # would reformat to:
73
+ #
74
+ # call_func_that_takes_a_dict({
75
+ # 'key1': 'value1',
76
+ # 'key2': 'value2',
77
+ # })
78
+ coalesce_brackets=False
79
+
80
+ # The column limit.
81
+ column_limit=80
82
+
83
+ # The style for continuation alignment. Possible values are:
84
+ #
85
+ # - SPACE: Use spaces for continuation alignment. This is default behavior.
86
+ # - FIXED: Use fixed number (CONTINUATION_INDENT_WIDTH) of columns
87
+ # (ie: CONTINUATION_INDENT_WIDTH/INDENT_WIDTH tabs or
88
+ # CONTINUATION_INDENT_WIDTH spaces) for continuation alignment.
89
+ # - VALIGN-RIGHT: Vertically align continuation lines to multiple of
90
+ # INDENT_WIDTH columns. Slightly right (one tab or a few spaces) if
91
+ # cannot vertically align continuation lines with indent characters.
92
+ continuation_align_style=SPACE
93
+
94
+ # Indent width used for line continuations.
95
+ continuation_indent_width=4
96
+
97
+ # Put closing brackets on a separate line, dedented, if the bracketed
98
+ # expression can't fit in a single line. Applies to all kinds of brackets,
99
+ # including function definitions and calls. For example:
100
+ #
101
+ # config = {
102
+ # 'key1': 'value1',
103
+ # 'key2': 'value2',
104
+ # } # <--- this bracket is dedented and on a separate line
105
+ #
106
+ # time_series = self.remote_client.query_entity_counters(
107
+ # entity='dev3246.region1',
108
+ # key='dns.query_latency_tcp',
109
+ # transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
110
+ # start_ts=now()-timedelta(days=3),
111
+ # end_ts=now(),
112
+ # ) # <--- this bracket is dedented and on a separate line
113
+ dedent_closing_brackets=False
114
+
115
+ # Disable the heuristic which places each list element on a separate line
116
+ # if the list is comma-terminated.
117
+ disable_ending_comma_heuristic=False
118
+
119
+ # Place each dictionary entry onto its own line.
120
+ each_dict_entry_on_separate_line=True
121
+
122
+ # Require multiline dictionary even if it would normally fit on one line.
123
+ # For example:
124
+ #
125
+ # config = {
126
+ # 'key1': 'value1'
127
+ # }
128
+ force_multiline_dict=False
129
+
130
+ # The regex for an i18n comment. The presence of this comment stops
131
+ # reformatting of that line, because the comments are required to be
132
+ # next to the string they translate.
133
+ i18n_comment=#\..*
134
+
135
+ # The i18n function call names. The presence of this function stops
136
+ # reformattting on that line, because the string it has cannot be moved
137
+ # away from the i18n comment.
138
+ i18n_function_call=N_, _
139
+
140
+ # Indent blank lines.
141
+ indent_blank_lines=False
142
+
143
+ # Put closing brackets on a separate line, indented, if the bracketed
144
+ # expression can't fit in a single line. Applies to all kinds of brackets,
145
+ # including function definitions and calls. For example:
146
+ #
147
+ # config = {
148
+ # 'key1': 'value1',
149
+ # 'key2': 'value2',
150
+ # } # <--- this bracket is indented and on a separate line
151
+ #
152
+ # time_series = self.remote_client.query_entity_counters(
153
+ # entity='dev3246.region1',
154
+ # key='dns.query_latency_tcp',
155
+ # transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
156
+ # start_ts=now()-timedelta(days=3),
157
+ # end_ts=now(),
158
+ # ) # <--- this bracket is indented and on a separate line
159
+ indent_closing_brackets=False
160
+
161
+ # Indent the dictionary value if it cannot fit on the same line as the
162
+ # dictionary key. For example:
163
+ #
164
+ # config = {
165
+ # 'key1':
166
+ # 'value1',
167
+ # 'key2': value1 +
168
+ # value2,
169
+ # }
170
+ indent_dictionary_value=True
171
+
172
+ # The number of columns to use for indentation.
173
+ indent_width=4
174
+
175
+ # Join short lines into one line. E.g., single line 'if' statements.
176
+ join_multiple_lines=False
177
+
178
+ # Do not include spaces around selected binary operators. For example:
179
+ #
180
+ # 1 + 2 * 3 - 4 / 5
181
+ #
182
+ # will be formatted as follows when configured with "*,/":
183
+ #
184
+ # 1 + 2*3 - 4/5
185
+ no_spaces_around_selected_binary_operators=
186
+
187
+ # Use spaces around default or named assigns.
188
+ spaces_around_default_or_named_assign=False
189
+
190
+ # Adds a space after the opening '{' and before the ending '}' dict delimiters.
191
+ #
192
+ # {1: 2}
193
+ #
194
+ # will be formatted as:
195
+ #
196
+ # { 1: 2 }
197
+ spaces_around_dict_delimiters=False
198
+
199
+ # Adds a space after the opening '[' and before the ending ']' list delimiters.
200
+ #
201
+ # [1, 2]
202
+ #
203
+ # will be formatted as:
204
+ #
205
+ # [ 1, 2 ]
206
+ spaces_around_list_delimiters=False
207
+
208
+ # Use spaces around the power operator.
209
+ spaces_around_power_operator=False
210
+
211
+ # Use spaces around the subscript / slice operator. For example:
212
+ #
213
+ # my_list[1 : 10 : 2]
214
+ spaces_around_subscript_colon=False
215
+
216
+ # Adds a space after the opening '(' and before the ending ')' tuple delimiters.
217
+ #
218
+ # (1, 2, 3)
219
+ #
220
+ # will be formatted as:
221
+ #
222
+ # ( 1, 2, 3 )
223
+ spaces_around_tuple_delimiters=False
224
+
225
+ # The number of spaces required before a trailing comment.
226
+ # This can be a single value (representing the number of spaces
227
+ # before each trailing comment) or list of values (representing
228
+ # alignment column values; trailing comments within a block will
229
+ # be aligned to the first column value that is greater than the maximum
230
+ # line length within the block). For example:
231
+ #
232
+ # With spaces_before_comment=5:
233
+ #
234
+ # 1 + 1 # Adding values
235
+ #
236
+ # will be formatted as:
237
+ #
238
+ # 1 + 1 # Adding values <-- 5 spaces between the end of the statement and comment
239
+ #
240
+ # With spaces_before_comment=15, 20:
241
+ #
242
+ # 1 + 1 # Adding values
243
+ # two + two # More adding
244
+ #
245
+ # longer_statement # This is a longer statement
246
+ # short # This is a shorter statement
247
+ #
248
+ # a_very_long_statement_that_extends_beyond_the_final_column # Comment
249
+ # short # This is a shorter statement
250
+ #
251
+ # will be formatted as:
252
+ #
253
+ # 1 + 1 # Adding values <-- end of line comments in block aligned to col 15
254
+ # two + two # More adding
255
+ #
256
+ # longer_statement # This is a longer statement <-- end of line comments in block aligned to col 20
257
+ # short # This is a shorter statement
258
+ #
259
+ # a_very_long_statement_that_extends_beyond_the_final_column # Comment <-- the end of line comments are aligned based on the line length
260
+ # short # This is a shorter statement
261
+ #
262
+ spaces_before_comment=2
263
+
264
+ # Insert a space between the ending comma and closing bracket of a list,
265
+ # etc.
266
+ space_between_ending_comma_and_closing_bracket=False
267
+
268
+ # Use spaces inside brackets, braces, and parentheses. For example:
269
+ #
270
+ # method_call( 1 )
271
+ # my_dict[ 3 ][ 1 ][ get_index( *args, **kwargs ) ]
272
+ # my_set = { 1, 2, 3 }
273
+ space_inside_brackets=False
274
+
275
+ # Split before arguments
276
+ split_all_comma_separated_values=False
277
+
278
+ # Split before arguments, but do not split all subexpressions recursively
279
+ # (unless needed).
280
+ split_all_top_level_comma_separated_values=False
281
+
282
+ # Split before arguments if the argument list is terminated by a
283
+ # comma.
284
+ split_arguments_when_comma_terminated=False
285
+
286
+ # Set to True to prefer splitting before '+', '-', '*', '/', '//', or '@'
287
+ # rather than after.
288
+ split_before_arithmetic_operator=False
289
+
290
+ # Set to True to prefer splitting before '&', '|' or '^' rather than
291
+ # after.
292
+ split_before_bitwise_operator=False
293
+
294
+ # Split before the closing bracket if a list or dict literal doesn't fit on
295
+ # a single line.
296
+ split_before_closing_bracket=True
297
+
298
+ # Split before a dictionary or set generator (comp_for). For example, note
299
+ # the split before the 'for':
300
+ #
301
+ # foo = {
302
+ # variable: 'Hello world, have a nice day!'
303
+ # for variable in bar if variable != 42
304
+ # }
305
+ split_before_dict_set_generator=False
306
+
307
+ # Split before the '.' if we need to split a longer expression:
308
+ #
309
+ # foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d))
310
+ #
311
+ # would reformat to something like:
312
+ #
313
+ # foo = ('This is a really long string: {}, {}, {}, {}'
314
+ # .format(a, b, c, d))
315
+ split_before_dot=False
316
+
317
+ # Split after the opening paren which surrounds an expression if it doesn't
318
+ # fit on a single line.
319
+ split_before_expression_after_opening_paren=True
320
+
321
+ # If an argument / parameter list is going to be split, then split before
322
+ # the first argument.
323
+ split_before_first_argument=False
324
+
325
+ # Set to True to prefer splitting before 'and' or 'or' rather than
326
+ # after.
327
+ split_before_logical_operator=False
328
+
329
+ # Split named assignments onto individual lines.
330
+ split_before_named_assigns=True
331
+
332
+ # Set to True to split list comprehensions and generators that have
333
+ # non-trivial expressions and multiple clauses before each of these
334
+ # clauses. For example:
335
+ #
336
+ # result = [
337
+ # a_long_var + 100 for a_long_var in xrange(1000)
338
+ # if a_long_var % 10]
339
+ #
340
+ # would reformat to something like:
341
+ #
342
+ # result = [
343
+ # a_long_var + 100
344
+ # for a_long_var in xrange(1000)
345
+ # if a_long_var % 10]
346
+ split_complex_comprehension=True
347
+
348
+ # The penalty for splitting right after the opening bracket.
349
+ split_penalty_after_opening_bracket=300
350
+
351
+ # The penalty for splitting the line after a unary operator.
352
+ split_penalty_after_unary_operator=10000
353
+
354
+ # The penalty of splitting the line around the '+', '-', '*', '/', '//',
355
+ # ``%``, and '@' operators.
356
+ split_penalty_arithmetic_operator=300
357
+
358
+ # The penalty for splitting right before an if expression.
359
+ split_penalty_before_if_expr=0
360
+
361
+ # The penalty of splitting the line around the '&', '|', and '^'
362
+ # operators.
363
+ split_penalty_bitwise_operator=300
364
+
365
+ # The penalty for splitting a list comprehension or generator
366
+ # expression.
367
+ split_penalty_comprehension=2100
368
+
369
+ # The penalty for characters over the column limit.
370
+ split_penalty_excess_character=7000
371
+
372
+ # The penalty incurred by adding a line split to the unwrapped line. The
373
+ # more line splits added the higher the penalty.
374
+ split_penalty_for_added_line_split=30
375
+
376
+ # The penalty of splitting a list of "import as" names. For example:
377
+ #
378
+ # from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
379
+ # long_argument_2,
380
+ # long_argument_3)
381
+ #
382
+ # would reformat to something like:
383
+ #
384
+ # from a_very_long_or_indented_module_name_yada_yad import (
385
+ # long_argument_1, long_argument_2, long_argument_3)
386
+ split_penalty_import_names=0
387
+
388
+ # The penalty of splitting the line around the 'and' and 'or'
389
+ # operators.
390
+ split_penalty_logical_operator=300
391
+
392
+ # Use the Tab character for indentation.
393
+ use_tabs=False
Wan2.1/INSTALL.md ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation Guide
2
+
3
+ ## Install with pip
4
+
5
+ ```bash
6
+ pip install .
7
+ pip install .[dev] # Installe aussi les outils de dev
8
+ ```
9
+
10
+ ## Install with Poetry
11
+
12
+ Ensure you have [Poetry](https://python-poetry.org/docs/#installation) installed on your system.
13
+
14
+ To install all dependencies:
15
+
16
+ ```bash
17
+ poetry install
18
+ ```
19
+
20
+ ### Handling `flash-attn` Installation Issues
21
+
22
+ If `flash-attn` fails due to **PEP 517 build issues**, you can try one of the following fixes.
23
+
24
+ #### No-Build-Isolation Installation (Recommended)
25
+ ```bash
26
+ poetry run pip install --upgrade pip setuptools wheel
27
+ poetry run pip install flash-attn --no-build-isolation
28
+ poetry install
29
+ ```
30
+
31
+ #### Install from Git (Alternative)
32
+ ```bash
33
+ poetry run pip install git+https://github.com/Dao-AILab/flash-attention.git
34
+ ```
35
+
36
+ ---
37
+
38
+ ### Running the Model
39
+
40
+ Once the installation is complete, you can run **Wan2.1** using:
41
+
42
+ ```bash
43
+ poetry run python generate.py --task t2v-14B --size '1280x720' --ckpt_dir ./Wan2.1-T2V-14B --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
44
+ ```
45
+
46
+ #### Test
47
+ ```bash
48
+ pytest tests/
49
+ ```
50
+ #### Format
51
+ ```bash
52
+ black .
53
+ isort .
54
+ ```
Wan2.1/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Wan2.1/Makefile ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .PHONY: format
2
+
3
+ format:
4
+ isort generate.py gradio wan
5
+ yapf -i -r *.py generate.py gradio wan
Wan2.1/README.md ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Wan2.1
2
+
3
+ <p align="center">
4
+ <img src="assets/logo.png" width="400"/>
5
+ <p>
6
+
7
+ <p align="center">
8
+ 💜 <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
9
+ <br>
10
+
11
+ -----
12
+
13
+ [**Wan: Open and Advanced Large-Scale Video Generative Models**](https://arxiv.org/abs/2503.20314) <be>
14
+
15
+ 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:
16
+ - 👍 **SOTA Performance**: **Wan2.1** consistently outperforms existing open-source models and state-of-the-art commercial solutions across multiple benchmarks.
17
+ - 👍 **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.
18
+ - 👍 **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.
19
+ - 👍 **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.
20
+ - 👍 **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.
21
+
22
+ ## Video Demos
23
+
24
+ <div align="center">
25
+ <video src="https://github.com/user-attachments/assets/4aca6063-60bf-4953-bfb7-e265053f49ef" width="70%" poster=""> </video>
26
+ </div>
27
+
28
+ ## 🔥 Latest News!!
29
+
30
+ * May 14, 2025: 👋 We introduce **Wan2.1** [VACE](https://github.com/ali-vilab/VACE), an all-in-one model for video creation and editing, along with its [inference code](#run-vace), [weights](#model-download), and [technical report](https://arxiv.org/abs/2503.07598)!
31
+ * Apr 17, 2025: 👋 We introduce **Wan2.1** [FLF2V](#run-first-last-frame-to-video-generation) with its inference code and weights!
32
+ * 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!
33
+ * 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!
34
+ * Feb 27, 2025: 👋 **Wan2.1** has been integrated into [ComfyUI](https://comfyanonymous.github.io/ComfyUI_examples/wan/). Enjoy!
35
+ * Feb 25, 2025: 👋 We've released the inference code and weights of **Wan2.1**.
36
+
37
+ ## Community Works
38
+ If your work has improved **Wan2.1** and you would like more people to see it, please inform us.
39
+ - [Helios](https://github.com/PKU-YuanGroup/Helios), a breakthrough video generation model base on **Wan2.1** that achieves minute-scale, high-quality video synthesis at 19.5 FPS on a single H100 GPU (about 10 FPS on a single Ascend NPU) —without relying on conventional long video anti-drifting strategies or standard video acceleration techniques. Visit their [webpage](https://pku-yuangroup.github.io/Helios-Page/) for more details.
40
+ - [Video-As-Prompt](https://github.com/bytedance/Video-As-Prompt), the first unified semantic-controlled video generation model based on **Wan2.1-14B-I2V** with a Mixture-of-Transformers architecture and in-context controls (e.g., concept, style, motion, camera). Refer to the [project page](https://bytedance.github.io/Video-As-Prompt/) for more examples.
41
+ - [LightX2V](https://github.com/ModelTC/LightX2V), a lightweight and efficient video generation framework that integrates **Wan2.1** and **Wan2.2**, supports multiple engineering acceleration techniques for fast inference, which can run on RTX 5090 and RTX 4060 (8GB VRAM).
42
+ - [DriVerse](https://github.com/shalfun/DriVerse), an autonomous driving world model based on **Wan2.1-14B-I2V**, generates future driving videos conditioned on any scene frame and given trajectory. Refer to the [project page](https://github.com/shalfun/DriVerse/tree/main) for more examples.
43
+ - [Training-Free-WAN-Editing](https://github.com/KyujinHan/Awesome-Training-Free-WAN2.1-Editing), built on **Wan2.1-T2V-1.3B**, allows training-free video editing with image-based training-free methods, such as [FlowEdit](https://arxiv.org/abs/2412.08629) and [FlowAlign](https://arxiv.org/abs/2505.23145).
44
+ - [Wan-Move](https://github.com/ali-vilab/Wan-Move), accepted to NeurIPS 2025, a framework that brings **Wan2.1-I2V-14B** to SOTA fine-grained, point-level motion control! Refer to [their project page](https://wan-move.github.io/) for more information.
45
+ - [EchoShot](https://github.com/JoHnneyWang/EchoShot), a native multi-shot portrait video generation model based on **Wan2.1-T2V-1.3B**, allows generation of multiple video clips featuring the same character as well as highly flexible content controllability. Refer to [their project page](https://johnneywang.github.io/EchoShot-webpage/) for more information.
46
+ - [AniCrafter](https://github.com/MyNiuuu/AniCrafter), a human-centric animation model based on **Wan2.1-14B-I2V**, controls the Video Diffusion Models with 3DGS Avatars to insert and animate anyone into any scene following given motion sequences. Refer to the [project page](https://myniuuu.github.io/AniCrafter) for more examples.
47
+ - [HyperMotion](https://vivocameraresearch.github.io/hypermotion/), a human image animation framework based on **Wan2.1**, addresses the challenge of generating complex human body motions in pose-guided animation. Refer to [their website](https://vivocameraresearch.github.io/magictryon/) for more examples.
48
+ - [MagicTryOn](https://vivocameraresearch.github.io/magictryon/), a video virtual try-on framework built upon **Wan2.1-14B-I2V**, addresses the limitations of existing models in expressing garment details and maintaining dynamic stability during human motion. Refer to [their website](https://vivocameraresearch.github.io/magictryon/) for more examples.
49
+ - [ATI](https://github.com/bytedance/ATI), built on **Wan2.1-I2V-14B**, is a trajectory-based motion-control framework that unifies object, local, and camera movements in video generation. Refer to [their website](https://anytraj.github.io/) for more examples.
50
+ - [Phantom](https://github.com/Phantom-video/Phantom) has developed a unified video generation framework for single and multi-subject references based on both **Wan2.1-T2V-1.3B** and **Wan2.1-T2V-14B**. Please refer to [their examples](https://github.com/Phantom-video/Phantom).
51
+ - [UniAnimate-DiT](https://github.com/ali-vilab/UniAnimate-DiT), based on **Wan2.1-14B-I2V**, has trained a Human image animation model and has open-sourced the inference and training code. Feel free to enjoy it!
52
+ - [CFG-Zero](https://github.com/WeichenFan/CFG-Zero-star) enhances **Wan2.1** (covering both T2V and I2V models) from the perspective of CFG.
53
+ - [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!
54
+ - [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).
55
+
56
+
57
+ ## 📑 Todo List
58
+ - Wan2.1 Text-to-Video
59
+ - [x] Multi-GPU Inference code of the 14B and 1.3B models
60
+ - [x] Checkpoints of the 14B and 1.3B models
61
+ - [x] Gradio demo
62
+ - [x] ComfyUI integration
63
+ - [x] Diffusers integration
64
+ - [ ] Diffusers + Multi-GPU Inference
65
+ - Wan2.1 Image-to-Video
66
+ - [x] Multi-GPU Inference code of the 14B model
67
+ - [x] Checkpoints of the 14B model
68
+ - [x] Gradio demo
69
+ - [x] ComfyUI integration
70
+ - [x] Diffusers integration
71
+ - [ ] Diffusers + Multi-GPU Inference
72
+ - Wan2.1 First-Last-Frame-to-Video
73
+ - [x] Multi-GPU Inference code of the 14B model
74
+ - [x] Checkpoints of the 14B model
75
+ - [x] Gradio demo
76
+ - [ ] ComfyUI integration
77
+ - [ ] Diffusers integration
78
+ - [ ] Diffusers + Multi-GPU Inference
79
+ - Wan2.1 VACE
80
+ - [x] Multi-GPU Inference code of the 14B and 1.3B models
81
+ - [x] Checkpoints of the 14B and 1.3B models
82
+ - [x] Gradio demo
83
+ - [x] ComfyUI integration
84
+ - [ ] Diffusers integration
85
+ - [ ] Diffusers + Multi-GPU Inference
86
+
87
+ ## Quickstart
88
+
89
+ #### Installation
90
+ Clone the repo:
91
+ ```sh
92
+ git clone https://github.com/Wan-Video/Wan2.1.git
93
+ cd Wan2.1
94
+ ```
95
+
96
+ Install dependencies:
97
+ ```sh
98
+ # Ensure torch >= 2.4.0
99
+ pip install -r requirements.txt
100
+ ```
101
+
102
+
103
+ #### Model Download
104
+
105
+ | Models | Download Link | Notes |
106
+ |--------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------|
107
+ | 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
108
+ | 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
109
+ | 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
110
+ | 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
111
+ | FLF2V-14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-FLF2V-14B-720P) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-FLF2V-14B-720P) | Supports 720P
112
+ | VACE-1.3B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-VACE-1.3B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-VACE-1.3B) | Supports 480P
113
+ | VACE-14B | 🤗 [Huggingface](https://huggingface.co/Wan-AI/Wan2.1-VACE-14B) 🤖 [ModelScope](https://www.modelscope.cn/models/Wan-AI/Wan2.1-VACE-14B) | Supports both 480P and 720P
114
+
115
+ > 💡Note:
116
+ > * 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.
117
+ > * For the first-last frame to video generation, we train our model primarily on Chinese text-video pairs. Therefore, we recommend using Chinese prompt to achieve better results.
118
+
119
+
120
+ Download models using huggingface-cli:
121
+ ``` sh
122
+ pip install "huggingface_hub[cli]"
123
+ huggingface-cli download Wan-AI/Wan2.1-T2V-14B --local-dir ./Wan2.1-T2V-14B
124
+ ```
125
+
126
+ Download models using modelscope-cli:
127
+ ``` sh
128
+ pip install modelscope
129
+ modelscope download Wan-AI/Wan2.1-T2V-14B --local_dir ./Wan2.1-T2V-14B
130
+ ```
131
+ #### Run Text-to-Video Generation
132
+
133
+ This repository supports two Text-to-Video models (1.3B and 14B) and two resolutions (480P and 720P). The parameters and configurations for these models are as follows:
134
+
135
+ <table>
136
+ <thead>
137
+ <tr>
138
+ <th rowspan="2">Task</th>
139
+ <th colspan="2">Resolution</th>
140
+ <th rowspan="2">Model</th>
141
+ </tr>
142
+ <tr>
143
+ <th>480P</th>
144
+ <th>720P</th>
145
+ </tr>
146
+ </thead>
147
+ <tbody>
148
+ <tr>
149
+ <td>t2v-14B</td>
150
+ <td style="color: green;">✔️</td>
151
+ <td style="color: green;">✔️</td>
152
+ <td>Wan2.1-T2V-14B</td>
153
+ </tr>
154
+ <tr>
155
+ <td>t2v-1.3B</td>
156
+ <td style="color: green;">✔️</td>
157
+ <td style="color: red;">❌</td>
158
+ <td>Wan2.1-T2V-1.3B</td>
159
+ </tr>
160
+ </tbody>
161
+ </table>
162
+
163
+
164
+ ##### (1) Without Prompt Extension
165
+
166
+ To facilitate implementation, we will start with a basic version of the inference process that skips the [prompt extension](#2-using-prompt-extention) step.
167
+
168
+ - Single-GPU inference
169
+
170
+ ``` sh
171
+ python generate.py --task t2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-T2V-14B --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
172
+ ```
173
+
174
+ If you encounter OOM (Out-of-Memory) issues, you can use the `--offload_model True` and `--t5_cpu` options to reduce GPU memory usage. For example, on an RTX 4090 GPU:
175
+
176
+ ``` sh
177
+ python generate.py --task t2v-1.3B --size 832*480 --ckpt_dir ./Wan2.1-T2V-1.3B --offload_model True --t5_cpu --sample_shift 8 --sample_guide_scale 6 --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
178
+ ```
179
+
180
+ > 💡Note: If you are using the `T2V-1.3B` model, we recommend setting the parameter `--sample_guide_scale 6`. The `--sample_shift parameter` can be adjusted within the range of 8 to 12 based on the performance.
181
+
182
+
183
+ - Multi-GPU inference using FSDP + xDiT USP
184
+
185
+ We use FSDP and [xDiT](https://github.com/xdit-project/xDiT) USP to accelerate inference.
186
+
187
+ * Ulysess Strategy
188
+
189
+ If you want to use [`Ulysses`](https://arxiv.org/abs/2309.14509) strategy, you should set `--ulysses_size $GPU_NUMS`. Note that the `num_heads` should be divisible by `ulysses_size` if you wish to use `Ulysess` strategy. For the 1.3B model, the `num_heads` is `12` which can't be divided by 8 (as most multi-GPU machines have 8 GPUs). Therefore, it is recommended to use `Ring Strategy` instead.
190
+
191
+ * Ring Strategy
192
+
193
+ If you want to use [`Ring`](https://arxiv.org/pdf/2310.01889) strategy, you should set `--ring_size $GPU_NUMS`. Note that the `sequence length` should be divisible by `ring_size` when using the `Ring` strategy.
194
+
195
+ Of course, you can also combine the use of `Ulysses` and `Ring` strategies.
196
+
197
+
198
+ ``` sh
199
+ pip install "xfuser>=0.4.1"
200
+ torchrun --nproc_per_node=8 generate.py --task t2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-T2V-14B --dit_fsdp --t5_fsdp --ulysses_size 8 --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage."
201
+ ```
202
+
203
+
204
+ ##### (2) Using Prompt Extension
205
+
206
+ Extending the prompts can effectively enrich the details in the generated videos, further enhancing the video quality. Therefore, we recommend enabling prompt extension. We provide the following two methods for prompt extension:
207
+
208
+ - Use the Dashscope API for extension.
209
+ - Apply for a `dashscope.api_key` in advance ([EN](https://www.alibabacloud.com/help/en/model-studio/getting-started/first-api-call-to-qwen) | [CN](https://help.aliyun.com/zh/model-studio/getting-started/first-api-call-to-qwen)).
210
+ - Configure the environment variable `DASH_API_KEY` to specify the Dashscope API key. For users of Alibaba Cloud's international site, you also need to set the environment variable `DASH_API_URL` to 'https://dashscope-intl.aliyuncs.com/api/v1'. For more detailed instructions, please refer to the [dashscope document](https://www.alibabacloud.com/help/en/model-studio/developer-reference/use-qwen-by-calling-api?spm=a2c63.p38356.0.i1).
211
+ - Use the `qwen-plus` model for text-to-video tasks and `qwen-vl-max` for image-to-video tasks.
212
+ - You can modify the model used for extension with the parameter `--prompt_extend_model`. For example:
213
+ ```sh
214
+ DASH_API_KEY=your_key python generate.py --task t2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-T2V-14B --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage" --use_prompt_extend --prompt_extend_method 'dashscope' --prompt_extend_target_lang 'zh'
215
+ ```
216
+
217
+ - Using a local model for extension.
218
+
219
+ - By default, the Qwen model on HuggingFace is used for this extension. Users can choose Qwen models or other models based on the available GPU memory size.
220
+ - For text-to-video tasks, you can use models like `Qwen/Qwen2.5-14B-Instruct`, `Qwen/Qwen2.5-7B-Instruct` and `Qwen/Qwen2.5-3B-Instruct`.
221
+ - For image-to-video or first-last-frame-to-video tasks, you can use models like `Qwen/Qwen2.5-VL-7B-Instruct` and `Qwen/Qwen2.5-VL-3B-Instruct`.
222
+ - Larger models generally provide better extension results but require more GPU memory.
223
+ - You can modify the model used for extension with the parameter `--prompt_extend_model` , allowing you to specify either a local model path or a Hugging Face model. For example:
224
+
225
+ ``` sh
226
+ python generate.py --task t2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-T2V-14B --prompt "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage" --use_prompt_extend --prompt_extend_method 'local_qwen' --prompt_extend_target_lang 'zh'
227
+ ```
228
+
229
+
230
+ ##### (3) Running with Diffusers
231
+
232
+ You can easily inference **Wan2.1**-T2V using Diffusers with the following command:
233
+ ``` python
234
+ import torch
235
+ from diffusers.utils import export_to_video
236
+ from diffusers import AutoencoderKLWan, WanPipeline
237
+ from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
238
+
239
+ # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
240
+ model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
241
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
242
+ flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
243
+ scheduler = UniPCMultistepScheduler(prediction_type='flow_prediction', use_flow_sigmas=True, num_train_timesteps=1000, flow_shift=flow_shift)
244
+ pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
245
+ pipe.scheduler = scheduler
246
+ pipe.to("cuda")
247
+
248
+ prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
249
+ 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"
250
+
251
+ output = pipe(
252
+ prompt=prompt,
253
+ negative_prompt=negative_prompt,
254
+ height=720,
255
+ width=1280,
256
+ num_frames=81,
257
+ guidance_scale=5.0,
258
+ ).frames[0]
259
+ export_to_video(output, "output.mp4", fps=16)
260
+ ```
261
+ > 💡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.
262
+
263
+
264
+ ##### (4) Running local gradio
265
+
266
+ ``` sh
267
+ cd gradio
268
+ # if one uses dashscope’s API for prompt extension
269
+ DASH_API_KEY=your_key python t2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir ./Wan2.1-T2V-14B
270
+
271
+ # if one uses a local model for prompt extension
272
+ python t2v_14B_singleGPU.py --prompt_extend_method 'local_qwen' --ckpt_dir ./Wan2.1-T2V-14B
273
+ ```
274
+
275
+
276
+
277
+ #### Run Image-to-Video Generation
278
+
279
+ 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:
280
+ <table>
281
+ <thead>
282
+ <tr>
283
+ <th rowspan="2">Task</th>
284
+ <th colspan="2">Resolution</th>
285
+ <th rowspan="2">Model</th>
286
+ </tr>
287
+ <tr>
288
+ <th>480P</th>
289
+ <th>720P</th>
290
+ </tr>
291
+ </thead>
292
+ <tbody>
293
+ <tr>
294
+ <td>i2v-14B</td>
295
+ <td style="color: green;">❌</td>
296
+ <td style="color: green;">✔️</td>
297
+ <td>Wan2.1-I2V-14B-720P</td>
298
+ </tr>
299
+ <tr>
300
+ <td>i2v-14B</td>
301
+ <td style="color: green;">✔️</td>
302
+ <td style="color: red;">❌</td>
303
+ <td>Wan2.1-T2V-14B-480P</td>
304
+ </tr>
305
+ </tbody>
306
+ </table>
307
+
308
+
309
+ ##### (1) Without Prompt Extension
310
+
311
+ - Single-GPU inference
312
+ ```sh
313
+ 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."
314
+ ```
315
+
316
+ > 💡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.
317
+
318
+
319
+ - Multi-GPU inference using FSDP + xDiT USP
320
+
321
+ ```sh
322
+ pip install "xfuser>=0.4.1"
323
+ 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."
324
+ ```
325
+
326
+ ##### (2) Using Prompt Extension
327
+
328
+
329
+ The process of prompt extension can be referenced [here](#2-using-prompt-extention).
330
+
331
+ Run with local prompt extension using `Qwen/Qwen2.5-VL-7B-Instruct`:
332
+ ```
333
+ 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."
334
+ ```
335
+
336
+ Run with remote prompt extension using `dashscope`:
337
+ ```
338
+ 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."
339
+ ```
340
+
341
+
342
+ ##### (3) Running with Diffusers
343
+
344
+ You can easily inference **Wan2.1**-I2V using Diffusers with the following command:
345
+ ``` python
346
+ import torch
347
+ import numpy as np
348
+ from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
349
+ from diffusers.utils import export_to_video, load_image
350
+ from transformers import CLIPVisionModel
351
+
352
+ # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
353
+ model_id = "Wan-AI/Wan2.1-I2V-14B-720P-Diffusers"
354
+ image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", torch_dtype=torch.float32)
355
+ vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
356
+ pipe = WanImageToVideoPipeline.from_pretrained(model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16)
357
+ pipe.to("cuda")
358
+
359
+ image = load_image(
360
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
361
+ )
362
+ max_area = 720 * 1280
363
+ aspect_ratio = image.height / image.width
364
+ mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
365
+ height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
366
+ width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
367
+ image = image.resize((width, height))
368
+ prompt = (
369
+ "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
370
+ "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
371
+ )
372
+ 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"
373
+
374
+ output = pipe(
375
+ image=image,
376
+ prompt=prompt,
377
+ negative_prompt=negative_prompt,
378
+ height=height, width=width,
379
+ num_frames=81,
380
+ guidance_scale=5.0
381
+ ).frames[0]
382
+ export_to_video(output, "output.mp4", fps=16)
383
+
384
+ ```
385
+ > 💡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.
386
+
387
+
388
+ ##### (4) Running local gradio
389
+
390
+ ```sh
391
+ cd gradio
392
+ # if one only uses 480P model in gradio
393
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_480p ./Wan2.1-I2V-14B-480P
394
+
395
+ # if one only uses 720P model in gradio
396
+ DASH_API_KEY=your_key python i2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_720p ./Wan2.1-I2V-14B-720P
397
+
398
+ # if one uses both 480P and 720P models in gradio
399
+ 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
400
+ ```
401
+
402
+
403
+ #### Run First-Last-Frame-to-Video Generation
404
+
405
+ First-Last-Frame-to-Video is also divided into processes with and without the prompt extension step. Currently, only 720P is supported. The specific parameters and corresponding settings are as follows:
406
+ <table>
407
+ <thead>
408
+ <tr>
409
+ <th rowspan="2">Task</th>
410
+ <th colspan="2">Resolution</th>
411
+ <th rowspan="2">Model</th>
412
+ </tr>
413
+ <tr>
414
+ <th>480P</th>
415
+ <th>720P</th>
416
+ </tr>
417
+ </thead>
418
+ <tbody>
419
+ <tr>
420
+ <td>flf2v-14B</td>
421
+ <td style="color: green;">❌</td>
422
+ <td style="color: green;">✔️</td>
423
+ <td>Wan2.1-FLF2V-14B-720P</td>
424
+ </tr>
425
+ </tbody>
426
+ </table>
427
+
428
+
429
+ ##### (1) Without Prompt Extension
430
+
431
+ - Single-GPU inference
432
+ ```sh
433
+ python generate.py --task flf2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-FLF2V-14B-720P --first_frame examples/flf2v_input_first_frame.png --last_frame examples/flf2v_input_last_frame.png --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."
434
+ ```
435
+
436
+ > 💡Similar to Image-to-Video, the `size` parameter represents the area of the generated video, with the aspect ratio following that of the original input image.
437
+
438
+
439
+ - Multi-GPU inference using FSDP + xDiT USP
440
+
441
+ ```sh
442
+ pip install "xfuser>=0.4.1"
443
+ torchrun --nproc_per_node=8 generate.py --task flf2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-FLF2V-14B-720P --first_frame examples/flf2v_input_first_frame.png --last_frame examples/flf2v_input_last_frame.png --dit_fsdp --t5_fsdp --ulysses_size 8 --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."
444
+ ```
445
+
446
+ ##### (2) Using Prompt Extension
447
+
448
+
449
+ The process of prompt extension can be referenced [here](#2-using-prompt-extention).
450
+
451
+ Run with local prompt extension using `Qwen/Qwen2.5-VL-7B-Instruct`:
452
+ ```
453
+ python generate.py --task flf2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-FLF2V-14B-720P --first_frame examples/flf2v_input_first_frame.png --last_frame examples/flf2v_input_last_frame.png --use_prompt_extend --prompt_extend_model Qwen/Qwen2.5-VL-7B-Instruct --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."
454
+ ```
455
+
456
+ Run with remote prompt extension using `dashscope`:
457
+ ```
458
+ DASH_API_KEY=your_key python generate.py --task flf2v-14B --size 1280*720 --ckpt_dir ./Wan2.1-FLF2V-14B-720P --first_frame examples/flf2v_input_first_frame.png --last_frame examples/flf2v_input_last_frame.png --use_prompt_extend --prompt_extend_method 'dashscope' --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."
459
+ ```
460
+
461
+
462
+ ##### (3) Running local gradio
463
+
464
+ ```sh
465
+ cd gradio
466
+ # use 720P model in gradio
467
+ DASH_API_KEY=your_key python flf2v_14B_singleGPU.py --prompt_extend_method 'dashscope' --ckpt_dir_720p ./Wan2.1-FLF2V-14B-720P
468
+ ```
469
+
470
+
471
+ #### Run VACE
472
+
473
+ [VACE](https://github.com/ali-vilab/VACE) now supports two models (1.3B and 14B) and two main resolutions (480P and 720P).
474
+ The input supports any resolution, but to achieve optimal results, the video size should fall within a specific range.
475
+ The parameters and configurations for these models are as follows:
476
+
477
+ <table>
478
+ <thead>
479
+ <tr>
480
+ <th rowspan="2">Task</th>
481
+ <th colspan="2">Resolution</th>
482
+ <th rowspan="2">Model</th>
483
+ </tr>
484
+ <tr>
485
+ <th>480P(~81x480x832)</th>
486
+ <th>720P(~81x720x1280)</th>
487
+ </tr>
488
+ </thead>
489
+ <tbody>
490
+ <tr>
491
+ <td>VACE</td>
492
+ <td style="color: green; text-align: center; vertical-align: middle;">✔️</td>
493
+ <td style="color: green; text-align: center; vertical-align: middle;">✔️</td>
494
+ <td>Wan2.1-VACE-14B</td>
495
+ </tr>
496
+ <tr>
497
+ <td>VACE</td>
498
+ <td style="color: green; text-align: center; vertical-align: middle;">✔️</td>
499
+ <td style="color: red; text-align: center; vertical-align: middle;">❌</td>
500
+ <td>Wan2.1-VACE-1.3B</td>
501
+ </tr>
502
+ </tbody>
503
+ </table>
504
+
505
+ In VACE, users can input text prompt and optional video, mask, and image for video generation or editing. Detailed instructions for using VACE can be found in the [User Guide](https://github.com/ali-vilab/VACE/blob/main/UserGuide.md).
506
+ The execution process is as follows:
507
+
508
+ ##### (1) Preprocessing
509
+
510
+ User-collected materials needs to be preprocessed into VACE-recognizable inputs, including `src_video`, `src_mask`, `src_ref_images`, and `prompt`.
511
+ For R2V (Reference-to-Video Generation), you may skip this preprocessing, but for V2V (Video-to-Video Editing) and MV2V (Masked Video-to-Video Editing) tasks, additional preprocessing is required to obtain video with conditions such as depth, pose or masked regions.
512
+ For more details, please refer to [vace_preproccess](https://github.com/ali-vilab/VACE/blob/main/vace/vace_preproccess.py).
513
+
514
+ ##### (2) cli inference
515
+
516
+ - Single-GPU inference
517
+ ```sh
518
+ python generate.py --task vace-1.3B --size 832*480 --ckpt_dir ./Wan2.1-VACE-1.3B --src_ref_images examples/girl.png,examples/snake.png --prompt "在一个欢乐而充满节日气氛的场景中,穿着鲜艳红色春服的小女孩正与她的可爱卡通蛇嬉戏。她的春服上绣着金色吉祥图案,散发着喜庆的气息,脸上洋溢着灿烂的笑容。蛇身呈现出亮眼的绿色,形状圆润,宽大的眼睛让它显得既友善又幽默。小女孩欢快地用手轻轻抚摸着蛇的头部,共同享受着这温馨的时刻。周围五彩斑斓的灯笼和彩带装饰着环境,阳光透过洒在她们身上,营造出一个充满友爱与幸福的新年氛围。"
519
+ ```
520
+
521
+ - Multi-GPU inference using FSDP + xDiT USP
522
+
523
+ ```sh
524
+ torchrun --nproc_per_node=8 generate.py --task vace-14B --size 1280*720 --ckpt_dir ./Wan2.1-VACE-14B --dit_fsdp --t5_fsdp --ulysses_size 8 --src_ref_images examples/girl.png,examples/snake.png --prompt "在一个欢乐而充满节日气氛的场景中,穿着鲜艳红色春服的小女孩正与她的可爱卡通蛇嬉戏。她的春服上绣着金色吉祥图案,散发着喜庆的气息,脸上洋溢着灿烂的笑容。蛇身呈现出亮眼的绿色,形状圆润,宽大的眼睛让它显得既友善又幽默。小女孩欢快地用手轻轻抚摸着蛇的头部,共同享受着这温馨的时刻。周围五彩斑斓的灯笼和彩带装饰着环境,阳光透过洒在她们身上,营造出一个充满友爱与幸福的新年氛围。"
525
+ ```
526
+
527
+ ##### (3) Running local gradio
528
+ - Single-GPU inference
529
+ ```sh
530
+ python gradio/vace.py --ckpt_dir ./Wan2.1-VACE-1.3B
531
+ ```
532
+
533
+ - Multi-GPU inference using FSDP + xDiT USP
534
+ ```sh
535
+ python gradio/vace.py --mp --ulysses_size 8 --ckpt_dir ./Wan2.1-VACE-14B/
536
+ ```
537
+
538
+ #### Run Text-to-Image Generation
539
+
540
+ Wan2.1 is a unified model for both image and video generation. Since it was trained on both types of data, it can also generate images. The command for generating images is similar to video generation, as follows:
541
+
542
+ ##### (1) Without Prompt Extension
543
+
544
+ - Single-GPU inference
545
+ ```sh
546
+ python generate.py --task t2i-14B --size 1024*1024 --ckpt_dir ./Wan2.1-T2V-14B --prompt '一个朴素端庄的美人'
547
+ ```
548
+
549
+ - Multi-GPU inference using FSDP + xDiT USP
550
+
551
+ ```sh
552
+ torchrun --nproc_per_node=8 generate.py --dit_fsdp --t5_fsdp --ulysses_size 8 --base_seed 0 --frame_num 1 --task t2i-14B --size 1024*1024 --prompt '一个朴素端庄的美人' --ckpt_dir ./Wan2.1-T2V-14B
553
+ ```
554
+
555
+ ##### (2) With Prompt Extention
556
+
557
+ - Single-GPU inference
558
+ ```sh
559
+ python generate.py --task t2i-14B --size 1024*1024 --ckpt_dir ./Wan2.1-T2V-14B --prompt '一个朴素端庄的美人' --use_prompt_extend
560
+ ```
561
+
562
+ - Multi-GPU inference using FSDP + xDiT USP
563
+ ```sh
564
+ torchrun --nproc_per_node=8 generate.py --dit_fsdp --t5_fsdp --ulysses_size 8 --base_seed 0 --frame_num 1 --task t2i-14B --size 1024*1024 --ckpt_dir ./Wan2.1-T2V-14B --prompt '一个朴素端庄的美人' --use_prompt_extend
565
+ ```
566
+
567
+
568
+ ## Manual Evaluation
569
+
570
+ ##### (1) Text-to-Video Evaluation
571
+
572
+ Through manual evaluation, the results generated after prompt extension are superior to those from both closed-source and open-source models.
573
+
574
+ <div align="center">
575
+ <img src="assets/t2v_res.jpg" alt="" style="width: 80%;" />
576
+ </div>
577
+
578
+
579
+ ##### (2) Image-to-Video Evaluation
580
+
581
+ 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.
582
+
583
+ <div align="center">
584
+ <img src="assets/i2v_res.png" alt="" style="width: 80%;" />
585
+ </div>
586
+
587
+
588
+ ## Computational Efficiency on Different GPUs
589
+
590
+ 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)**.
591
+
592
+
593
+ <div align="center">
594
+ <img src="assets/comp_effic.png" alt="" style="width: 80%;" />
595
+ </div>
596
+
597
+ > The parameter settings for the tests presented in this table are as follows:
598
+ > (1) For the 1.3B model on 8 GPUs, set `--ring_size 8` and `--ulysses_size 1`;
599
+ > (2) For the 14B model on 1 GPU, use `--offload_model True`;
600
+ > (3) For the 1.3B model on a single 4090 GPU, set `--offload_model True --t5_cpu`;
601
+ > (4) For all testings, no prompt extension was applied, meaning `--use_prompt_extend` was not enabled.
602
+
603
+ > 💡Note: T2V-14B is slower than I2V-14B because the former samples 50 steps while the latter uses 40 steps.
604
+
605
+
606
+ -------
607
+
608
+ ## Introduction of Wan2.1
609
+
610
+ **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.
611
+
612
+
613
+ ##### (1) 3D Variational Autoencoders
614
+ 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.
615
+
616
+
617
+ <div align="center">
618
+ <img src="assets/video_vae_res.jpg" alt="" style="width: 80%;" />
619
+ </div>
620
+
621
+
622
+ ##### (2) Video Diffusion DiT
623
+
624
+ **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.
625
+
626
+ <div align="center">
627
+ <img src="assets/video_dit_arch.jpg" alt="" style="width: 80%;" />
628
+ </div>
629
+
630
+
631
+ | Model | Dimension | Input Dimension | Output Dimension | Feedforward Dimension | Frequency Dimension | Number of Heads | Number of Layers |
632
+ |--------|-----------|-----------------|------------------|-----------------------|---------------------|-----------------|------------------|
633
+ | 1.3B | 1536 | 16 | 16 | 8960 | 256 | 12 | 30 |
634
+ | 14B | 5120 | 16 | 16 | 13824 | 256 | 40 | 40 |
635
+
636
+
637
+
638
+ ##### Data
639
+
640
+ 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.
641
+
642
+ ![figure1](assets/data_for_diff_stage.jpg "figure1")
643
+
644
+
645
+ ##### Comparisons to SOTA
646
+ 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.
647
+
648
+ ![figure1](assets/vben_vs_sota.png "figure1")
649
+
650
+
651
+ ## Citation
652
+ If you find our work helpful, please cite us.
653
+
654
+ ```
655
+ @article{wan2025,
656
+ title={Wan: Open and Advanced Large-Scale Video Generative Models},
657
+ author={Team Wan 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},
658
+ journal = {arXiv preprint arXiv:2503.20314},
659
+ year={2025}
660
+ }
661
+ ```
662
+
663
+ ## License Agreement
664
+ 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).
665
+
666
+
667
+ ## Acknowledgements
668
+
669
+ 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.
670
+
671
+
672
+
673
+ ## Contact Us
674
+ 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)!
Wan2.1/assets/comp_effic.png ADDED

Git LFS Details

  • SHA256: b0e225caffb4b31295ad150f95ee852e4c3dde4a00ac8f79a2ff500f2ce26b8d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.79 MB
Wan2.1/assets/data_for_diff_stage.jpg ADDED

Git LFS Details

  • SHA256: 59aec08409f2d46b0e640e4e120dc7cca52c08c3de56d026602dbcff1ebf241a
  • Pointer size: 131 Bytes
  • Size of remote file: 528 kB
Wan2.1/assets/i2v_res.png ADDED

Git LFS Details

  • SHA256: 6823b3206d8d0cb18d3b5b949dec1217f1178109ba11f14e977b67e1f7b8a248
  • Pointer size: 131 Bytes
  • Size of remote file: 892 kB
Wan2.1/assets/logo.png ADDED

Git LFS Details

  • SHA256: 96cddc0f667293436d0b9f92a299b6346b65b231d38ee49719a33d46c91fe1e3
  • Pointer size: 130 Bytes
  • Size of remote file: 56.3 kB
Wan2.1/assets/t2v_res.jpg ADDED

Git LFS Details

  • SHA256: 91db579092446be2a834bc67721a8e4346936f38c4edb912f459ca3e10f8f439
  • Pointer size: 131 Bytes
  • Size of remote file: 301 kB
Wan2.1/assets/vben_vs_sota.png ADDED

Git LFS Details

  • SHA256: 9a0e86ca85046d2675f97984b88b6e74df07bba8a62a31ab8a1aef50d4eda44e
  • Pointer size: 132 Bytes
  • Size of remote file: 1.55 MB
Wan2.1/assets/video_dit_arch.jpg ADDED

Git LFS Details

  • SHA256: 195dceec6570289d8b01cc51d2e28a7786216f19de55b23978a52610d1646a66
  • Pointer size: 131 Bytes
  • Size of remote file: 643 kB
Wan2.1/assets/video_vae_res.jpg ADDED

Git LFS Details

  • SHA256: d8f9e7f7353848056a615c8ef35ab86ec22976bb46cb27405008b4089701945c
  • Pointer size: 131 Bytes
  • Size of remote file: 213 kB
Wan2.1/examples/flf2v_input_first_frame.png ADDED

Git LFS Details

  • SHA256: fc27f36ae244c3366d6d342c5fc78a959bfeddc7c6ddfb62fc255c18cdac977f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.78 MB
Wan2.1/examples/flf2v_input_last_frame.png ADDED

Git LFS Details

  • SHA256: 981d904fda073c87225089971b4bbff6f15d1f2511a111903989f391c526820f
  • Pointer size: 132 Bytes
  • Size of remote file: 1.46 MB
Wan2.1/examples/girl.png ADDED

Git LFS Details

  • SHA256: f461a83c0772dbe93a05ae6b8ce9fa77f0e7f5facb4402685b5410c0dc18397f
  • Pointer size: 131 Bytes
  • Size of remote file: 836 kB
Wan2.1/examples/i2v_input.JPG ADDED

Git LFS Details

  • SHA256: 077e3d965090c9028c69c00931675f42e1acc815c6eb450ab291b3b72d211a8e
  • Pointer size: 131 Bytes
  • Size of remote file: 251 kB
Wan2.1/examples/snake.png ADDED

Git LFS Details

  • SHA256: 60ae5e275f64de6ca99c5e63eaea6812fe09a6d7e7a233e483e700122ad08124
  • Pointer size: 131 Bytes
  • Size of remote file: 446 kB
Wan2.1/generate.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import logging
4
+ import os
5
+ import sys
6
+ import warnings
7
+ from datetime import datetime
8
+
9
+ warnings.filterwarnings('ignore')
10
+
11
+ import random
12
+
13
+ import torch
14
+ import torch.distributed as dist
15
+ from PIL import Image
16
+
17
+ import wan
18
+ from wan.configs import MAX_AREA_CONFIGS, SIZE_CONFIGS, SUPPORTED_SIZES, WAN_CONFIGS
19
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
20
+ from wan.utils.utils import cache_image, cache_video, str2bool
21
+
22
+
23
+ EXAMPLE_PROMPT = {
24
+ "t2v-1.3B": {
25
+ "prompt":
26
+ "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
27
+ },
28
+ "t2v-14B": {
29
+ "prompt":
30
+ "Two anthropomorphic cats in comfy boxing gear and bright gloves fight intensely on a spotlighted stage.",
31
+ },
32
+ "t2i-14B": {
33
+ "prompt": "一个朴素端庄的美人",
34
+ },
35
+ "i2v-14B": {
36
+ "prompt":
37
+ "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.",
38
+ "image":
39
+ "examples/i2v_input.JPG",
40
+ },
41
+ "flf2v-14B": {
42
+ "prompt":
43
+ "CG动画风格,一只蓝色的小鸟从地面起飞,煽动翅膀。小鸟羽毛细腻,胸前有独特的花纹,背景是蓝天白云,阳光明媚。镜跟随小鸟向上移动,展现出小鸟飞翔的姿态和天空的广阔。近景,仰视视角。",
44
+ "first_frame":
45
+ "examples/flf2v_input_first_frame.png",
46
+ "last_frame":
47
+ "examples/flf2v_input_last_frame.png",
48
+ },
49
+ "vace-1.3B": {
50
+ "src_ref_images":
51
+ 'examples/girl.png,examples/snake.png',
52
+ "prompt":
53
+ "在一个欢乐而充满节日气氛的场景中,穿着鲜艳红色春服的小女孩正与她的可爱卡通蛇嬉戏。她的春服上绣着金色吉祥图案,散发着喜庆的气息,脸上洋溢着灿烂的笑容。蛇身呈现出亮眼的绿色,形状圆润,宽大的眼睛让它显得既友善又幽默。小女孩欢快地用手轻轻抚摸着蛇的头部,共同享受着这温馨的时刻。周围五彩斑斓的灯笼和彩带装饰着环境,阳光透过洒在她们身上,营造出一个充满友爱与幸福的新年氛围。"
54
+ },
55
+ "vace-14B": {
56
+ "src_ref_images":
57
+ 'examples/girl.png,examples/snake.png',
58
+ "prompt":
59
+ "在一个欢乐而充满节日气氛的场景中,穿着鲜艳红色春服的小女孩正与她的可爱卡通蛇嬉戏。她的春服上绣着金色吉祥图案,散发着喜庆的气息,脸上洋溢着灿烂的笑容。蛇身呈现出亮眼的绿色,形状圆润,宽大的眼睛让它显得既友善又幽默。小女孩欢快地用手轻轻抚摸着蛇的头部,共同享受着这温馨的时刻。周围五彩斑斓的灯笼和彩带装饰着环境,阳光透过洒在她们身上,营造出一个充满友爱与幸福的新年氛围。"
60
+ }
61
+ }
62
+
63
+
64
+ def _validate_args(args):
65
+ # Basic check
66
+ assert args.ckpt_dir is not None, "Please specify the checkpoint directory."
67
+ assert args.task in WAN_CONFIGS, f"Unsupport task: {args.task}"
68
+ assert args.task in EXAMPLE_PROMPT, f"Unsupport task: {args.task}"
69
+
70
+ # The default sampling steps are 40 for image-to-video tasks and 50 for text-to-video tasks.
71
+ if args.sample_steps is None:
72
+ args.sample_steps = 50
73
+ if "i2v" in args.task:
74
+ args.sample_steps = 40
75
+
76
+ if args.sample_shift is None:
77
+ args.sample_shift = 5.0
78
+ if "i2v" in args.task and args.size in ["832*480", "480*832"]:
79
+ args.sample_shift = 3.0
80
+ elif "flf2v" in args.task or "vace" in args.task:
81
+ args.sample_shift = 16
82
+
83
+ # The default number of frames are 1 for text-to-image tasks and 81 for other tasks.
84
+ if args.frame_num is None:
85
+ args.frame_num = 1 if "t2i" in args.task else 81
86
+
87
+ # T2I frame_num check
88
+ if "t2i" in args.task:
89
+ assert args.frame_num == 1, f"Unsupport frame_num {args.frame_num} for task {args.task}"
90
+
91
+ args.base_seed = args.base_seed if args.base_seed >= 0 else random.randint(
92
+ 0, sys.maxsize)
93
+ # Size check
94
+ assert args.size in SUPPORTED_SIZES[
95
+ args.
96
+ task], f"Unsupport size {args.size} for task {args.task}, supported sizes are: {', '.join(SUPPORTED_SIZES[args.task])}"
97
+
98
+
99
+ def _parse_args():
100
+ parser = argparse.ArgumentParser(
101
+ description="Generate a image or video from a text prompt or image using Wan"
102
+ )
103
+ parser.add_argument(
104
+ "--task",
105
+ type=str,
106
+ default="t2v-14B",
107
+ choices=list(WAN_CONFIGS.keys()),
108
+ help="The task to run.")
109
+ parser.add_argument(
110
+ "--size",
111
+ type=str,
112
+ default="1280*720",
113
+ choices=list(SIZE_CONFIGS.keys()),
114
+ 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."
115
+ )
116
+ parser.add_argument(
117
+ "--frame_num",
118
+ type=int,
119
+ default=None,
120
+ help="How many frames to sample from a image or video. The number should be 4n+1"
121
+ )
122
+ parser.add_argument(
123
+ "--ckpt_dir",
124
+ type=str,
125
+ default=None,
126
+ help="The path to the checkpoint directory.")
127
+ parser.add_argument(
128
+ "--offload_model",
129
+ type=str2bool,
130
+ default=None,
131
+ help="Whether to offload the model to CPU after each model forward, reducing GPU memory usage."
132
+ )
133
+ parser.add_argument(
134
+ "--ulysses_size",
135
+ type=int,
136
+ default=1,
137
+ help="The size of the ulysses parallelism in DiT.")
138
+ parser.add_argument(
139
+ "--ring_size",
140
+ type=int,
141
+ default=1,
142
+ help="The size of the ring attention parallelism in DiT.")
143
+ parser.add_argument(
144
+ "--t5_fsdp",
145
+ action="store_true",
146
+ default=False,
147
+ help="Whether to use FSDP for T5.")
148
+ parser.add_argument(
149
+ "--t5_cpu",
150
+ action="store_true",
151
+ default=False,
152
+ help="Whether to place T5 model on CPU.")
153
+ parser.add_argument(
154
+ "--dit_fsdp",
155
+ action="store_true",
156
+ default=False,
157
+ help="Whether to use FSDP for DiT.")
158
+ parser.add_argument(
159
+ "--save_file",
160
+ type=str,
161
+ default=None,
162
+ help="The file to save the generated image or video to.")
163
+ parser.add_argument(
164
+ "--src_video",
165
+ type=str,
166
+ default=None,
167
+ help="The file of the source video. Default None.")
168
+ parser.add_argument(
169
+ "--src_mask",
170
+ type=str,
171
+ default=None,
172
+ help="The file of the source mask. Default None.")
173
+ parser.add_argument(
174
+ "--src_ref_images",
175
+ type=str,
176
+ default=None,
177
+ help="The file list of the source reference images. Separated by ','. Default None."
178
+ )
179
+ parser.add_argument(
180
+ "--prompt",
181
+ type=str,
182
+ default=None,
183
+ help="The prompt to generate the image or video from.")
184
+ parser.add_argument(
185
+ "--use_prompt_extend",
186
+ action="store_true",
187
+ default=False,
188
+ help="Whether to use prompt extend.")
189
+ parser.add_argument(
190
+ "--prompt_extend_method",
191
+ type=str,
192
+ default="local_qwen",
193
+ choices=["dashscope", "local_qwen"],
194
+ help="The prompt extend method to use.")
195
+ parser.add_argument(
196
+ "--prompt_extend_model",
197
+ type=str,
198
+ default=None,
199
+ help="The prompt extend model to use.")
200
+ parser.add_argument(
201
+ "--prompt_extend_target_lang",
202
+ type=str,
203
+ default="zh",
204
+ choices=["zh", "en"],
205
+ help="The target language of prompt extend.")
206
+ parser.add_argument(
207
+ "--base_seed",
208
+ type=int,
209
+ default=-1,
210
+ help="The seed to use for generating the image or video.")
211
+ parser.add_argument(
212
+ "--image",
213
+ type=str,
214
+ default=None,
215
+ help="[image to video] The image to generate the video from.")
216
+ parser.add_argument(
217
+ "--first_frame",
218
+ type=str,
219
+ default=None,
220
+ help="[first-last frame to video] The image (first frame) to generate the video from."
221
+ )
222
+ parser.add_argument(
223
+ "--last_frame",
224
+ type=str,
225
+ default=None,
226
+ help="[first-last frame to video] The image (last frame) to generate the video from."
227
+ )
228
+ parser.add_argument(
229
+ "--sample_solver",
230
+ type=str,
231
+ default='unipc',
232
+ choices=['unipc', 'dpm++'],
233
+ help="The solver used to sample.")
234
+ parser.add_argument(
235
+ "--sample_steps", type=int, default=None, help="The sampling steps.")
236
+ parser.add_argument(
237
+ "--sample_shift",
238
+ type=float,
239
+ default=None,
240
+ help="Sampling shift factor for flow matching schedulers.")
241
+ parser.add_argument(
242
+ "--sample_guide_scale",
243
+ type=float,
244
+ default=5.0,
245
+ help="Classifier free guidance scale.")
246
+
247
+ args = parser.parse_args()
248
+
249
+ _validate_args(args)
250
+
251
+ return args
252
+
253
+
254
+ def _init_logging(rank):
255
+ # logging
256
+ if rank == 0:
257
+ # set format
258
+ logging.basicConfig(
259
+ level=logging.INFO,
260
+ format="[%(asctime)s] %(levelname)s: %(message)s",
261
+ handlers=[logging.StreamHandler(stream=sys.stdout)])
262
+ else:
263
+ logging.basicConfig(level=logging.ERROR)
264
+
265
+
266
+ def generate(args):
267
+ rank = int(os.getenv("RANK", 0))
268
+ world_size = int(os.getenv("WORLD_SIZE", 1))
269
+ local_rank = int(os.getenv("LOCAL_RANK", 0))
270
+ device = local_rank
271
+ _init_logging(rank)
272
+
273
+ if args.offload_model is None:
274
+ args.offload_model = False if world_size > 1 else True
275
+ logging.info(
276
+ f"offload_model is not specified, set to {args.offload_model}.")
277
+ if world_size > 1:
278
+ torch.cuda.set_device(local_rank)
279
+ dist.init_process_group(
280
+ backend="nccl",
281
+ init_method="env://",
282
+ rank=rank,
283
+ world_size=world_size)
284
+ else:
285
+ assert not (
286
+ args.t5_fsdp or args.dit_fsdp
287
+ ), f"t5_fsdp and dit_fsdp are not supported in non-distributed environments."
288
+ assert not (
289
+ args.ulysses_size > 1 or args.ring_size > 1
290
+ ), f"context parallel are not supported in non-distributed environments."
291
+
292
+ if args.ulysses_size > 1 or args.ring_size > 1:
293
+ 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."
294
+ from xfuser.core.distributed import (
295
+ init_distributed_environment,
296
+ initialize_model_parallel,
297
+ )
298
+ init_distributed_environment(
299
+ rank=dist.get_rank(), world_size=dist.get_world_size())
300
+
301
+ initialize_model_parallel(
302
+ sequence_parallel_degree=dist.get_world_size(),
303
+ ring_degree=args.ring_size,
304
+ ulysses_degree=args.ulysses_size,
305
+ )
306
+
307
+ if args.use_prompt_extend:
308
+ if args.prompt_extend_method == "dashscope":
309
+ prompt_expander = DashScopePromptExpander(
310
+ model_name=args.prompt_extend_model,
311
+ is_vl="i2v" in args.task or "flf2v" in args.task)
312
+ elif args.prompt_extend_method == "local_qwen":
313
+ prompt_expander = QwenPromptExpander(
314
+ model_name=args.prompt_extend_model,
315
+ is_vl="i2v" in args.task,
316
+ device=rank)
317
+ else:
318
+ raise NotImplementedError(
319
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
320
+
321
+ cfg = WAN_CONFIGS[args.task]
322
+ if args.ulysses_size > 1:
323
+ assert cfg.num_heads % args.ulysses_size == 0, f"`{cfg.num_heads=}` cannot be divided evenly by `{args.ulysses_size=}`."
324
+
325
+ logging.info(f"Generation job args: {args}")
326
+ logging.info(f"Generation model config: {cfg}")
327
+
328
+ if dist.is_initialized():
329
+ base_seed = [args.base_seed] if rank == 0 else [None]
330
+ dist.broadcast_object_list(base_seed, src=0)
331
+ args.base_seed = base_seed[0]
332
+
333
+ if "t2v" in args.task or "t2i" in args.task:
334
+ if args.prompt is None:
335
+ args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
336
+ logging.info(f"Input prompt: {args.prompt}")
337
+ if args.use_prompt_extend:
338
+ logging.info("Extending prompt ...")
339
+ if rank == 0:
340
+ prompt_output = prompt_expander(
341
+ args.prompt,
342
+ tar_lang=args.prompt_extend_target_lang,
343
+ seed=args.base_seed)
344
+ if prompt_output.status == False:
345
+ logging.info(
346
+ f"Extending prompt failed: {prompt_output.message}")
347
+ logging.info("Falling back to original prompt.")
348
+ input_prompt = args.prompt
349
+ else:
350
+ input_prompt = prompt_output.prompt
351
+ input_prompt = [input_prompt]
352
+ else:
353
+ input_prompt = [None]
354
+ if dist.is_initialized():
355
+ dist.broadcast_object_list(input_prompt, src=0)
356
+ args.prompt = input_prompt[0]
357
+ logging.info(f"Extended prompt: {args.prompt}")
358
+
359
+ logging.info("Creating WanT2V pipeline.")
360
+ wan_t2v = wan.WanT2V(
361
+ config=cfg,
362
+ checkpoint_dir=args.ckpt_dir,
363
+ device_id=device,
364
+ rank=rank,
365
+ t5_fsdp=args.t5_fsdp,
366
+ dit_fsdp=args.dit_fsdp,
367
+ use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
368
+ t5_cpu=args.t5_cpu,
369
+ )
370
+
371
+ logging.info(
372
+ f"Generating {'image' if 't2i' in args.task else 'video'} ...")
373
+ video = wan_t2v.generate(
374
+ args.prompt,
375
+ size=SIZE_CONFIGS[args.size],
376
+ frame_num=args.frame_num,
377
+ shift=args.sample_shift,
378
+ sample_solver=args.sample_solver,
379
+ sampling_steps=args.sample_steps,
380
+ guide_scale=args.sample_guide_scale,
381
+ seed=args.base_seed,
382
+ offload_model=args.offload_model)
383
+
384
+ elif "i2v" in args.task:
385
+ if args.prompt is None:
386
+ args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
387
+ if args.image is None:
388
+ args.image = EXAMPLE_PROMPT[args.task]["image"]
389
+ logging.info(f"Input prompt: {args.prompt}")
390
+ logging.info(f"Input image: {args.image}")
391
+
392
+ img = Image.open(args.image).convert("RGB")
393
+ if args.use_prompt_extend:
394
+ logging.info("Extending prompt ...")
395
+ if rank == 0:
396
+ prompt_output = prompt_expander(
397
+ args.prompt,
398
+ tar_lang=args.prompt_extend_target_lang,
399
+ image=img,
400
+ seed=args.base_seed)
401
+ if prompt_output.status == False:
402
+ logging.info(
403
+ f"Extending prompt failed: {prompt_output.message}")
404
+ logging.info("Falling back to original prompt.")
405
+ input_prompt = args.prompt
406
+ else:
407
+ input_prompt = prompt_output.prompt
408
+ input_prompt = [input_prompt]
409
+ else:
410
+ input_prompt = [None]
411
+ if dist.is_initialized():
412
+ dist.broadcast_object_list(input_prompt, src=0)
413
+ args.prompt = input_prompt[0]
414
+ logging.info(f"Extended prompt: {args.prompt}")
415
+
416
+ logging.info("Creating WanI2V pipeline.")
417
+ wan_i2v = wan.WanI2V(
418
+ config=cfg,
419
+ checkpoint_dir=args.ckpt_dir,
420
+ device_id=device,
421
+ rank=rank,
422
+ t5_fsdp=args.t5_fsdp,
423
+ dit_fsdp=args.dit_fsdp,
424
+ use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
425
+ t5_cpu=args.t5_cpu,
426
+ )
427
+
428
+ logging.info("Generating video ...")
429
+ video = wan_i2v.generate(
430
+ args.prompt,
431
+ img,
432
+ max_area=MAX_AREA_CONFIGS[args.size],
433
+ frame_num=args.frame_num,
434
+ shift=args.sample_shift,
435
+ sample_solver=args.sample_solver,
436
+ sampling_steps=args.sample_steps,
437
+ guide_scale=args.sample_guide_scale,
438
+ seed=args.base_seed,
439
+ offload_model=args.offload_model)
440
+ elif "flf2v" in args.task:
441
+ if args.prompt is None:
442
+ args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
443
+ if args.first_frame is None or args.last_frame is None:
444
+ args.first_frame = EXAMPLE_PROMPT[args.task]["first_frame"]
445
+ args.last_frame = EXAMPLE_PROMPT[args.task]["last_frame"]
446
+ logging.info(f"Input prompt: {args.prompt}")
447
+ logging.info(f"Input first frame: {args.first_frame}")
448
+ logging.info(f"Input last frame: {args.last_frame}")
449
+ first_frame = Image.open(args.first_frame).convert("RGB")
450
+ last_frame = Image.open(args.last_frame).convert("RGB")
451
+ if args.use_prompt_extend:
452
+ logging.info("Extending prompt ...")
453
+ if rank == 0:
454
+ prompt_output = prompt_expander(
455
+ args.prompt,
456
+ tar_lang=args.prompt_extend_target_lang,
457
+ image=[first_frame, last_frame],
458
+ seed=args.base_seed)
459
+ if prompt_output.status == False:
460
+ logging.info(
461
+ f"Extending prompt failed: {prompt_output.message}")
462
+ logging.info("Falling back to original prompt.")
463
+ input_prompt = args.prompt
464
+ else:
465
+ input_prompt = prompt_output.prompt
466
+ input_prompt = [input_prompt]
467
+ else:
468
+ input_prompt = [None]
469
+ if dist.is_initialized():
470
+ dist.broadcast_object_list(input_prompt, src=0)
471
+ args.prompt = input_prompt[0]
472
+ logging.info(f"Extended prompt: {args.prompt}")
473
+
474
+ logging.info("Creating WanFLF2V pipeline.")
475
+ wan_flf2v = wan.WanFLF2V(
476
+ config=cfg,
477
+ checkpoint_dir=args.ckpt_dir,
478
+ device_id=device,
479
+ rank=rank,
480
+ t5_fsdp=args.t5_fsdp,
481
+ dit_fsdp=args.dit_fsdp,
482
+ use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
483
+ t5_cpu=args.t5_cpu,
484
+ )
485
+
486
+ logging.info("Generating video ...")
487
+ video = wan_flf2v.generate(
488
+ args.prompt,
489
+ first_frame,
490
+ last_frame,
491
+ max_area=MAX_AREA_CONFIGS[args.size],
492
+ frame_num=args.frame_num,
493
+ shift=args.sample_shift,
494
+ sample_solver=args.sample_solver,
495
+ sampling_steps=args.sample_steps,
496
+ guide_scale=args.sample_guide_scale,
497
+ seed=args.base_seed,
498
+ offload_model=args.offload_model)
499
+ elif "vace" in args.task:
500
+ if args.prompt is None:
501
+ args.prompt = EXAMPLE_PROMPT[args.task]["prompt"]
502
+ args.src_video = EXAMPLE_PROMPT[args.task].get("src_video", None)
503
+ args.src_mask = EXAMPLE_PROMPT[args.task].get("src_mask", None)
504
+ args.src_ref_images = EXAMPLE_PROMPT[args.task].get(
505
+ "src_ref_images", None)
506
+
507
+ logging.info(f"Input prompt: {args.prompt}")
508
+ if args.use_prompt_extend and args.use_prompt_extend != 'plain':
509
+ logging.info("Extending prompt ...")
510
+ if rank == 0:
511
+ prompt = prompt_expander.forward(args.prompt)
512
+ logging.info(
513
+ f"Prompt extended from '{args.prompt}' to '{prompt}'")
514
+ input_prompt = [prompt]
515
+ else:
516
+ input_prompt = [None]
517
+ if dist.is_initialized():
518
+ dist.broadcast_object_list(input_prompt, src=0)
519
+ args.prompt = input_prompt[0]
520
+ logging.info(f"Extended prompt: {args.prompt}")
521
+
522
+ logging.info("Creating VACE pipeline.")
523
+ wan_vace = wan.WanVace(
524
+ config=cfg,
525
+ checkpoint_dir=args.ckpt_dir,
526
+ device_id=device,
527
+ rank=rank,
528
+ t5_fsdp=args.t5_fsdp,
529
+ dit_fsdp=args.dit_fsdp,
530
+ use_usp=(args.ulysses_size > 1 or args.ring_size > 1),
531
+ t5_cpu=args.t5_cpu,
532
+ )
533
+
534
+ src_video, src_mask, src_ref_images = wan_vace.prepare_source(
535
+ [args.src_video], [args.src_mask], [
536
+ None if args.src_ref_images is None else
537
+ args.src_ref_images.split(',')
538
+ ], args.frame_num, SIZE_CONFIGS[args.size], device)
539
+
540
+ logging.info(f"Generating video...")
541
+ video = wan_vace.generate(
542
+ args.prompt,
543
+ src_video,
544
+ src_mask,
545
+ src_ref_images,
546
+ size=SIZE_CONFIGS[args.size],
547
+ frame_num=args.frame_num,
548
+ shift=args.sample_shift,
549
+ sample_solver=args.sample_solver,
550
+ sampling_steps=args.sample_steps,
551
+ guide_scale=args.sample_guide_scale,
552
+ seed=args.base_seed,
553
+ offload_model=args.offload_model)
554
+ else:
555
+ raise ValueError(f"Unkown task type: {args.task}")
556
+
557
+ if rank == 0:
558
+ if args.save_file is None:
559
+ formatted_time = datetime.now().strftime("%Y%m%d_%H%M%S")
560
+ formatted_prompt = args.prompt.replace(" ", "_").replace("/",
561
+ "_")[:50]
562
+ suffix = '.png' if "t2i" in args.task else '.mp4'
563
+ args.save_file = f"{args.task}_{args.size.replace('*','x') if sys.platform=='win32' else args.size}_{args.ulysses_size}_{args.ring_size}_{formatted_prompt}_{formatted_time}" + suffix
564
+
565
+ if "t2i" in args.task:
566
+ logging.info(f"Saving generated image to {args.save_file}")
567
+ cache_image(
568
+ tensor=video.squeeze(1)[None],
569
+ save_file=args.save_file,
570
+ nrow=1,
571
+ normalize=True,
572
+ value_range=(-1, 1))
573
+ else:
574
+ logging.info(f"Saving generated video to {args.save_file}")
575
+ cache_video(
576
+ tensor=video[None],
577
+ save_file=args.save_file,
578
+ fps=cfg.sample_fps,
579
+ nrow=1,
580
+ normalize=True,
581
+ value_range=(-1, 1))
582
+ logging.info("Finished.")
583
+
584
+
585
+ if __name__ == "__main__":
586
+ args = _parse_args()
587
+ generate(args)
Wan2.1/gradio/fl2v_14B_singleGPU.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import gc
4
+ import os
5
+ import os.path as osp
6
+ import sys
7
+ import warnings
8
+
9
+ import gradio as gr
10
+
11
+ warnings.filterwarnings('ignore')
12
+
13
+ # Model
14
+ sys.path.insert(
15
+ 0, os.path.sep.join(osp.realpath(__file__).split(os.path.sep)[:-2]))
16
+ import wan
17
+ from wan.configs import MAX_AREA_CONFIGS, WAN_CONFIGS
18
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
19
+ from wan.utils.utils import cache_video
20
+
21
+ # Global Var
22
+ prompt_expander = None
23
+ wan_flf2v_720P = None
24
+
25
+
26
+ # Button Func
27
+ def load_model(value):
28
+ global wan_flf2v_720P
29
+
30
+ if value == '------':
31
+ print("No model loaded")
32
+ return '------'
33
+
34
+ if value == '720P':
35
+ if args.ckpt_dir_720p is None:
36
+ print("Please specify the checkpoint directory for 720P model")
37
+ return '------'
38
+ if wan_flf2v_720P is not None:
39
+ pass
40
+ else:
41
+ gc.collect()
42
+
43
+ print("load 14B-720P flf2v model...", end='', flush=True)
44
+ cfg = WAN_CONFIGS['flf2v-14B']
45
+ wan_flf2v_720P = wan.WanFLF2V(
46
+ config=cfg,
47
+ checkpoint_dir=args.ckpt_dir_720p,
48
+ device_id=0,
49
+ rank=0,
50
+ t5_fsdp=False,
51
+ dit_fsdp=False,
52
+ use_usp=False,
53
+ )
54
+ print("done", flush=True)
55
+ return '720P'
56
+ return value
57
+
58
+
59
+ def prompt_enc(prompt, img_first, img_last, tar_lang):
60
+ print('prompt extend...')
61
+ if img_first is None or img_last is None:
62
+ print('Please upload the first and last frames')
63
+ return prompt
64
+ global prompt_expander
65
+ prompt_output = prompt_expander(
66
+ prompt, image=[img_first, img_last], tar_lang=tar_lang.lower())
67
+ if prompt_output.status == False:
68
+ return prompt
69
+ else:
70
+ return prompt_output.prompt
71
+
72
+
73
+ def flf2v_generation(flf2vid_prompt, flf2vid_image_first, flf2vid_image_last,
74
+ resolution, sd_steps, guide_scale, shift_scale, seed,
75
+ n_prompt):
76
+
77
+ if resolution == '------':
78
+ print(
79
+ 'Please specify the resolution ckpt dir or specify the resolution')
80
+ return None
81
+
82
+ else:
83
+ if resolution == '720P':
84
+ global wan_flf2v_720P
85
+ video = wan_flf2v_720P.generate(
86
+ flf2vid_prompt,
87
+ flf2vid_image_first,
88
+ flf2vid_image_last,
89
+ max_area=MAX_AREA_CONFIGS['720*1280'],
90
+ shift=shift_scale,
91
+ sampling_steps=sd_steps,
92
+ guide_scale=guide_scale,
93
+ n_prompt=n_prompt,
94
+ seed=seed,
95
+ offload_model=True)
96
+ pass
97
+ else:
98
+ print('Sorry, currently only 720P is supported.')
99
+ return None
100
+
101
+ cache_video(
102
+ tensor=video[None],
103
+ save_file="example.mp4",
104
+ fps=16,
105
+ nrow=1,
106
+ normalize=True,
107
+ value_range=(-1, 1))
108
+
109
+ return "example.mp4"
110
+
111
+
112
+ # Interface
113
+ def gradio_interface():
114
+ with gr.Blocks() as demo:
115
+ gr.Markdown("""
116
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
117
+ Wan2.1 (FLF2V-14B)
118
+ </div>
119
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
120
+ Wan: Open and Advanced Large-Scale Video Generative Models.
121
+ </div>
122
+ """)
123
+
124
+ with gr.Row():
125
+ with gr.Column():
126
+ resolution = gr.Dropdown(
127
+ label='Resolution',
128
+ choices=['------', '720P'],
129
+ value='------')
130
+ flf2vid_image_first = gr.Image(
131
+ type="pil",
132
+ label="Upload First Frame",
133
+ elem_id="image_upload",
134
+ )
135
+ flf2vid_image_last = gr.Image(
136
+ type="pil",
137
+ label="Upload Last Frame",
138
+ elem_id="image_upload",
139
+ )
140
+ flf2vid_prompt = gr.Textbox(
141
+ label="Prompt",
142
+ placeholder="Describe the video you want to generate",
143
+ )
144
+ tar_lang = gr.Radio(
145
+ choices=["ZH", "EN"],
146
+ label="Target language of prompt enhance",
147
+ value="ZH")
148
+ run_p_button = gr.Button(value="Prompt Enhance")
149
+
150
+ with gr.Accordion("Advanced Options", open=True):
151
+ with gr.Row():
152
+ sd_steps = gr.Slider(
153
+ label="Diffusion steps",
154
+ minimum=1,
155
+ maximum=1000,
156
+ value=50,
157
+ step=1)
158
+ guide_scale = gr.Slider(
159
+ label="Guide scale",
160
+ minimum=0,
161
+ maximum=20,
162
+ value=5.0,
163
+ step=1)
164
+ with gr.Row():
165
+ shift_scale = gr.Slider(
166
+ label="Shift scale",
167
+ minimum=0,
168
+ maximum=20,
169
+ value=5.0,
170
+ step=1)
171
+ seed = gr.Slider(
172
+ label="Seed",
173
+ minimum=-1,
174
+ maximum=2147483647,
175
+ step=1,
176
+ value=-1)
177
+ n_prompt = gr.Textbox(
178
+ label="Negative Prompt",
179
+ placeholder="Describe the negative prompt you want to add"
180
+ )
181
+
182
+ run_flf2v_button = gr.Button("Generate Video")
183
+
184
+ with gr.Column():
185
+ result_gallery = gr.Video(
186
+ label='Generated Video', interactive=False, height=600)
187
+
188
+ resolution.input(
189
+ fn=load_model, inputs=[resolution], outputs=[resolution])
190
+
191
+ run_p_button.click(
192
+ fn=prompt_enc,
193
+ inputs=[
194
+ flf2vid_prompt, flf2vid_image_first, flf2vid_image_last,
195
+ tar_lang
196
+ ],
197
+ outputs=[flf2vid_prompt])
198
+
199
+ run_flf2v_button.click(
200
+ fn=flf2v_generation,
201
+ inputs=[
202
+ flf2vid_prompt, flf2vid_image_first, flf2vid_image_last,
203
+ resolution, sd_steps, guide_scale, shift_scale, seed, n_prompt
204
+ ],
205
+ outputs=[result_gallery],
206
+ )
207
+
208
+ return demo
209
+
210
+
211
+ # Main
212
+ def _parse_args():
213
+ parser = argparse.ArgumentParser(
214
+ description="Generate a video from a text prompt or image using Gradio")
215
+ parser.add_argument(
216
+ "--ckpt_dir_720p",
217
+ type=str,
218
+ default=None,
219
+ help="The path to the checkpoint directory.")
220
+ parser.add_argument(
221
+ "--prompt_extend_method",
222
+ type=str,
223
+ default="local_qwen",
224
+ choices=["dashscope", "local_qwen"],
225
+ help="The prompt extend method to use.")
226
+ parser.add_argument(
227
+ "--prompt_extend_model",
228
+ type=str,
229
+ default=None,
230
+ help="The prompt extend model to use.")
231
+
232
+ args = parser.parse_args()
233
+ assert args.ckpt_dir_720p is not None, "Please specify the checkpoint directory."
234
+
235
+ return args
236
+
237
+
238
+ if __name__ == '__main__':
239
+ args = _parse_args()
240
+
241
+ print("Step1: Init prompt_expander...", end='', flush=True)
242
+ if args.prompt_extend_method == "dashscope":
243
+ prompt_expander = DashScopePromptExpander(
244
+ model_name=args.prompt_extend_model, is_vl=True)
245
+ elif args.prompt_extend_method == "local_qwen":
246
+ prompt_expander = QwenPromptExpander(
247
+ model_name=args.prompt_extend_model, is_vl=True, device=0)
248
+ else:
249
+ raise NotImplementedError(
250
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
251
+ print("done", flush=True)
252
+
253
+ demo = gradio_interface()
254
+ demo.launch(server_name="0.0.0.0", share=False, server_port=7860)
Wan2.1/gradio/i2v_14B_singleGPU.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import gc
4
+ import os
5
+ import os.path as osp
6
+ import sys
7
+ import warnings
8
+
9
+ import gradio as gr
10
+
11
+ warnings.filterwarnings('ignore')
12
+
13
+ # Model
14
+ sys.path.insert(
15
+ 0, os.path.sep.join(osp.realpath(__file__).split(os.path.sep)[:-2]))
16
+ import wan
17
+ from wan.configs import MAX_AREA_CONFIGS, WAN_CONFIGS
18
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
19
+ from wan.utils.utils import cache_video
20
+
21
+ # Global Var
22
+ prompt_expander = None
23
+ wan_i2v_480P = None
24
+ wan_i2v_720P = None
25
+
26
+
27
+ # Button Func
28
+ def load_model(value):
29
+ global wan_i2v_480P, wan_i2v_720P
30
+
31
+ if value == '------':
32
+ print("No model loaded")
33
+ return '------'
34
+
35
+ if value == '720P':
36
+ if args.ckpt_dir_720p is None:
37
+ print("Please specify the checkpoint directory for 720P model")
38
+ return '------'
39
+ if wan_i2v_720P is not None:
40
+ pass
41
+ else:
42
+ del wan_i2v_480P
43
+ gc.collect()
44
+ wan_i2v_480P = None
45
+
46
+ print("load 14B-720P i2v model...", end='', flush=True)
47
+ cfg = WAN_CONFIGS['i2v-14B']
48
+ wan_i2v_720P = wan.WanI2V(
49
+ config=cfg,
50
+ checkpoint_dir=args.ckpt_dir_720p,
51
+ device_id=0,
52
+ rank=0,
53
+ t5_fsdp=False,
54
+ dit_fsdp=False,
55
+ use_usp=False,
56
+ )
57
+ print("done", flush=True)
58
+ return '720P'
59
+
60
+ if value == '480P':
61
+ if args.ckpt_dir_480p is None:
62
+ print("Please specify the checkpoint directory for 480P model")
63
+ return '------'
64
+ if wan_i2v_480P is not None:
65
+ pass
66
+ else:
67
+ del wan_i2v_720P
68
+ gc.collect()
69
+ wan_i2v_720P = None
70
+
71
+ print("load 14B-480P i2v model...", end='', flush=True)
72
+ cfg = WAN_CONFIGS['i2v-14B']
73
+ wan_i2v_480P = wan.WanI2V(
74
+ config=cfg,
75
+ checkpoint_dir=args.ckpt_dir_480p,
76
+ device_id=0,
77
+ rank=0,
78
+ t5_fsdp=False,
79
+ dit_fsdp=False,
80
+ use_usp=False,
81
+ )
82
+ print("done", flush=True)
83
+ return '480P'
84
+ return value
85
+
86
+
87
+ def prompt_enc(prompt, img, tar_lang):
88
+ print('prompt extend...')
89
+ if img is None:
90
+ print('Please upload an image')
91
+ return prompt
92
+ global prompt_expander
93
+ prompt_output = prompt_expander(
94
+ prompt, image=img, tar_lang=tar_lang.lower())
95
+ if prompt_output.status == False:
96
+ return prompt
97
+ else:
98
+ return prompt_output.prompt
99
+
100
+
101
+ def i2v_generation(img2vid_prompt, img2vid_image, resolution, sd_steps,
102
+ guide_scale, shift_scale, seed, n_prompt):
103
+ # print(f"{img2vid_prompt},{resolution},{sd_steps},{guide_scale},{shift_scale},{seed},{n_prompt}")
104
+
105
+ if resolution == '------':
106
+ print(
107
+ 'Please specify at least one resolution ckpt dir or specify the resolution'
108
+ )
109
+ return None
110
+
111
+ else:
112
+ if resolution == '720P':
113
+ global wan_i2v_720P
114
+ video = wan_i2v_720P.generate(
115
+ img2vid_prompt,
116
+ img2vid_image,
117
+ max_area=MAX_AREA_CONFIGS['720*1280'],
118
+ shift=shift_scale,
119
+ sampling_steps=sd_steps,
120
+ guide_scale=guide_scale,
121
+ n_prompt=n_prompt,
122
+ seed=seed,
123
+ offload_model=True)
124
+ else:
125
+ global wan_i2v_480P
126
+ video = wan_i2v_480P.generate(
127
+ img2vid_prompt,
128
+ img2vid_image,
129
+ max_area=MAX_AREA_CONFIGS['480*832'],
130
+ shift=shift_scale,
131
+ sampling_steps=sd_steps,
132
+ guide_scale=guide_scale,
133
+ n_prompt=n_prompt,
134
+ seed=seed,
135
+ offload_model=True)
136
+
137
+ cache_video(
138
+ tensor=video[None],
139
+ save_file="example.mp4",
140
+ fps=16,
141
+ nrow=1,
142
+ normalize=True,
143
+ value_range=(-1, 1))
144
+
145
+ return "example.mp4"
146
+
147
+
148
+ # Interface
149
+ def gradio_interface():
150
+ with gr.Blocks() as demo:
151
+ gr.Markdown("""
152
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
153
+ Wan2.1 (I2V-14B)
154
+ </div>
155
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
156
+ Wan: Open and Advanced Large-Scale Video Generative Models.
157
+ </div>
158
+ """)
159
+
160
+ with gr.Row():
161
+ with gr.Column():
162
+ resolution = gr.Dropdown(
163
+ label='Resolution',
164
+ choices=['------', '720P', '480P'],
165
+ value='------')
166
+
167
+ img2vid_image = gr.Image(
168
+ type="pil",
169
+ label="Upload Input Image",
170
+ elem_id="image_upload",
171
+ )
172
+ img2vid_prompt = gr.Textbox(
173
+ label="Prompt",
174
+ placeholder="Describe the video you want to generate",
175
+ )
176
+ tar_lang = gr.Radio(
177
+ choices=["ZH", "EN"],
178
+ label="Target language of prompt enhance",
179
+ value="ZH")
180
+ run_p_button = gr.Button(value="Prompt Enhance")
181
+
182
+ with gr.Accordion("Advanced Options", open=True):
183
+ with gr.Row():
184
+ sd_steps = gr.Slider(
185
+ label="Diffusion steps",
186
+ minimum=1,
187
+ maximum=1000,
188
+ value=50,
189
+ step=1)
190
+ guide_scale = gr.Slider(
191
+ label="Guide scale",
192
+ minimum=0,
193
+ maximum=20,
194
+ value=5.0,
195
+ step=1)
196
+ with gr.Row():
197
+ shift_scale = gr.Slider(
198
+ label="Shift scale",
199
+ minimum=0,
200
+ maximum=10,
201
+ value=5.0,
202
+ step=1)
203
+ seed = gr.Slider(
204
+ label="Seed",
205
+ minimum=-1,
206
+ maximum=2147483647,
207
+ step=1,
208
+ value=-1)
209
+ n_prompt = gr.Textbox(
210
+ label="Negative Prompt",
211
+ placeholder="Describe the negative prompt you want to add"
212
+ )
213
+
214
+ run_i2v_button = gr.Button("Generate Video")
215
+
216
+ with gr.Column():
217
+ result_gallery = gr.Video(
218
+ label='Generated Video', interactive=False, height=600)
219
+
220
+ resolution.input(
221
+ fn=load_model, inputs=[resolution], outputs=[resolution])
222
+
223
+ run_p_button.click(
224
+ fn=prompt_enc,
225
+ inputs=[img2vid_prompt, img2vid_image, tar_lang],
226
+ outputs=[img2vid_prompt])
227
+
228
+ run_i2v_button.click(
229
+ fn=i2v_generation,
230
+ inputs=[
231
+ img2vid_prompt, img2vid_image, resolution, sd_steps,
232
+ guide_scale, shift_scale, seed, n_prompt
233
+ ],
234
+ outputs=[result_gallery],
235
+ )
236
+
237
+ return demo
238
+
239
+
240
+ # Main
241
+ def _parse_args():
242
+ parser = argparse.ArgumentParser(
243
+ description="Generate a video from a text prompt or image using Gradio")
244
+ parser.add_argument(
245
+ "--ckpt_dir_720p",
246
+ type=str,
247
+ default=None,
248
+ help="The path to the checkpoint directory.")
249
+ parser.add_argument(
250
+ "--ckpt_dir_480p",
251
+ type=str,
252
+ default=None,
253
+ help="The path to the checkpoint directory.")
254
+ parser.add_argument(
255
+ "--prompt_extend_method",
256
+ type=str,
257
+ default="local_qwen",
258
+ choices=["dashscope", "local_qwen"],
259
+ help="The prompt extend method to use.")
260
+ parser.add_argument(
261
+ "--prompt_extend_model",
262
+ type=str,
263
+ default=None,
264
+ help="The prompt extend model to use.")
265
+
266
+ args = parser.parse_args()
267
+ assert args.ckpt_dir_720p is not None or args.ckpt_dir_480p is not None, "Please specify at least one checkpoint directory."
268
+
269
+ return args
270
+
271
+
272
+ if __name__ == '__main__':
273
+ args = _parse_args()
274
+
275
+ print("Step1: Init prompt_expander...", end='', flush=True)
276
+ if args.prompt_extend_method == "dashscope":
277
+ prompt_expander = DashScopePromptExpander(
278
+ model_name=args.prompt_extend_model, is_vl=True)
279
+ elif args.prompt_extend_method == "local_qwen":
280
+ prompt_expander = QwenPromptExpander(
281
+ model_name=args.prompt_extend_model, is_vl=True, device=0)
282
+ else:
283
+ raise NotImplementedError(
284
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
285
+ print("done", flush=True)
286
+
287
+ demo = gradio_interface()
288
+ demo.launch(server_name="0.0.0.0", share=False, server_port=7860)
Wan2.1/gradio/t2i_14B_singleGPU.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import os
4
+ import os.path as osp
5
+ import sys
6
+ import warnings
7
+
8
+ import gradio as gr
9
+
10
+ warnings.filterwarnings('ignore')
11
+
12
+ # Model
13
+ sys.path.insert(
14
+ 0, os.path.sep.join(osp.realpath(__file__).split(os.path.sep)[:-2]))
15
+ import wan
16
+ from wan.configs import WAN_CONFIGS
17
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
18
+ from wan.utils.utils import cache_image
19
+
20
+ # Global Var
21
+ prompt_expander = None
22
+ wan_t2i = None
23
+
24
+
25
+ # Button Func
26
+ def prompt_enc(prompt, tar_lang):
27
+ global prompt_expander
28
+ prompt_output = prompt_expander(prompt, tar_lang=tar_lang.lower())
29
+ if prompt_output.status == False:
30
+ return prompt
31
+ else:
32
+ return prompt_output.prompt
33
+
34
+
35
+ def t2i_generation(txt2img_prompt, resolution, sd_steps, guide_scale,
36
+ shift_scale, seed, n_prompt):
37
+ global wan_t2i
38
+ # print(f"{txt2img_prompt},{resolution},{sd_steps},{guide_scale},{shift_scale},{seed},{n_prompt}")
39
+
40
+ W = int(resolution.split("*")[0])
41
+ H = int(resolution.split("*")[1])
42
+ video = wan_t2i.generate(
43
+ txt2img_prompt,
44
+ size=(W, H),
45
+ frame_num=1,
46
+ shift=shift_scale,
47
+ sampling_steps=sd_steps,
48
+ guide_scale=guide_scale,
49
+ n_prompt=n_prompt,
50
+ seed=seed,
51
+ offload_model=True)
52
+
53
+ cache_image(
54
+ tensor=video.squeeze(1)[None],
55
+ save_file="example.png",
56
+ nrow=1,
57
+ normalize=True,
58
+ value_range=(-1, 1))
59
+
60
+ return "example.png"
61
+
62
+
63
+ # Interface
64
+ def gradio_interface():
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("""
67
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
68
+ Wan2.1 (T2I-14B)
69
+ </div>
70
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
71
+ Wan: Open and Advanced Large-Scale Video Generative Models.
72
+ </div>
73
+ """)
74
+
75
+ with gr.Row():
76
+ with gr.Column():
77
+ txt2img_prompt = gr.Textbox(
78
+ label="Prompt",
79
+ placeholder="Describe the image you want to generate",
80
+ )
81
+ tar_lang = gr.Radio(
82
+ choices=["ZH", "EN"],
83
+ label="Target language of prompt enhance",
84
+ value="ZH")
85
+ run_p_button = gr.Button(value="Prompt Enhance")
86
+
87
+ with gr.Accordion("Advanced Options", open=True):
88
+ resolution = gr.Dropdown(
89
+ label='Resolution(Width*Height)',
90
+ choices=[
91
+ '720*1280', '1280*720', '960*960', '1088*832',
92
+ '832*1088', '480*832', '832*480', '624*624',
93
+ '704*544', '544*704'
94
+ ],
95
+ value='720*1280')
96
+
97
+ with gr.Row():
98
+ sd_steps = gr.Slider(
99
+ label="Diffusion steps",
100
+ minimum=1,
101
+ maximum=1000,
102
+ value=50,
103
+ step=1)
104
+ guide_scale = gr.Slider(
105
+ label="Guide scale",
106
+ minimum=0,
107
+ maximum=20,
108
+ value=5.0,
109
+ step=1)
110
+ with gr.Row():
111
+ shift_scale = gr.Slider(
112
+ label="Shift scale",
113
+ minimum=0,
114
+ maximum=10,
115
+ value=5.0,
116
+ step=1)
117
+ seed = gr.Slider(
118
+ label="Seed",
119
+ minimum=-1,
120
+ maximum=2147483647,
121
+ step=1,
122
+ value=-1)
123
+ n_prompt = gr.Textbox(
124
+ label="Negative Prompt",
125
+ placeholder="Describe the negative prompt you want to add"
126
+ )
127
+
128
+ run_t2i_button = gr.Button("Generate Image")
129
+
130
+ with gr.Column():
131
+ result_gallery = gr.Image(
132
+ label='Generated Image', interactive=False, height=600)
133
+
134
+ run_p_button.click(
135
+ fn=prompt_enc,
136
+ inputs=[txt2img_prompt, tar_lang],
137
+ outputs=[txt2img_prompt])
138
+
139
+ run_t2i_button.click(
140
+ fn=t2i_generation,
141
+ inputs=[
142
+ txt2img_prompt, resolution, sd_steps, guide_scale, shift_scale,
143
+ seed, n_prompt
144
+ ],
145
+ outputs=[result_gallery],
146
+ )
147
+
148
+ return demo
149
+
150
+
151
+ # Main
152
+ def _parse_args():
153
+ parser = argparse.ArgumentParser(
154
+ description="Generate a image from a text prompt or image using Gradio")
155
+ parser.add_argument(
156
+ "--ckpt_dir",
157
+ type=str,
158
+ default="cache",
159
+ help="The path to the checkpoint directory.")
160
+ parser.add_argument(
161
+ "--prompt_extend_method",
162
+ type=str,
163
+ default="local_qwen",
164
+ choices=["dashscope", "local_qwen"],
165
+ help="The prompt extend method to use.")
166
+ parser.add_argument(
167
+ "--prompt_extend_model",
168
+ type=str,
169
+ default=None,
170
+ help="The prompt extend model to use.")
171
+
172
+ args = parser.parse_args()
173
+
174
+ return args
175
+
176
+
177
+ if __name__ == '__main__':
178
+ args = _parse_args()
179
+
180
+ print("Step1: Init prompt_expander...", end='', flush=True)
181
+ if args.prompt_extend_method == "dashscope":
182
+ prompt_expander = DashScopePromptExpander(
183
+ model_name=args.prompt_extend_model, is_vl=False)
184
+ elif args.prompt_extend_method == "local_qwen":
185
+ prompt_expander = QwenPromptExpander(
186
+ model_name=args.prompt_extend_model, is_vl=False, device=0)
187
+ else:
188
+ raise NotImplementedError(
189
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
190
+ print("done", flush=True)
191
+
192
+ print("Step2: Init 14B t2i model...", end='', flush=True)
193
+ cfg = WAN_CONFIGS['t2i-14B']
194
+ wan_t2i = wan.WanT2V(
195
+ config=cfg,
196
+ checkpoint_dir=args.ckpt_dir,
197
+ device_id=0,
198
+ rank=0,
199
+ t5_fsdp=False,
200
+ dit_fsdp=False,
201
+ use_usp=False,
202
+ )
203
+ print("done", flush=True)
204
+
205
+ demo = gradio_interface()
206
+ demo.launch(server_name="0.0.0.0", share=False, server_port=7860)
Wan2.1/gradio/t2v_1.3B_singleGPU.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import os
4
+ import os.path as osp
5
+ import sys
6
+ import warnings
7
+
8
+ import gradio as gr
9
+
10
+ warnings.filterwarnings('ignore')
11
+
12
+ # Model
13
+ sys.path.insert(
14
+ 0, os.path.sep.join(osp.realpath(__file__).split(os.path.sep)[:-2]))
15
+ import wan
16
+ from wan.configs import WAN_CONFIGS
17
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
18
+ from wan.utils.utils import cache_video
19
+
20
+ # Global Var
21
+ prompt_expander = None
22
+ wan_t2v = None
23
+
24
+
25
+ # Button Func
26
+ def prompt_enc(prompt, tar_lang):
27
+ global prompt_expander
28
+ prompt_output = prompt_expander(prompt, tar_lang=tar_lang.lower())
29
+ if prompt_output.status == False:
30
+ return prompt
31
+ else:
32
+ return prompt_output.prompt
33
+
34
+
35
+ def t2v_generation(txt2vid_prompt, resolution, sd_steps, guide_scale,
36
+ shift_scale, seed, n_prompt):
37
+ global wan_t2v
38
+ # print(f"{txt2vid_prompt},{resolution},{sd_steps},{guide_scale},{shift_scale},{seed},{n_prompt}")
39
+
40
+ W = int(resolution.split("*")[0])
41
+ H = int(resolution.split("*")[1])
42
+ video = wan_t2v.generate(
43
+ txt2vid_prompt,
44
+ size=(W, H),
45
+ shift=shift_scale,
46
+ sampling_steps=sd_steps,
47
+ guide_scale=guide_scale,
48
+ n_prompt=n_prompt,
49
+ seed=seed,
50
+ offload_model=True)
51
+
52
+ cache_video(
53
+ tensor=video[None],
54
+ save_file="example.mp4",
55
+ fps=16,
56
+ nrow=1,
57
+ normalize=True,
58
+ value_range=(-1, 1))
59
+
60
+ return "example.mp4"
61
+
62
+
63
+ # Interface
64
+ def gradio_interface():
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("""
67
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
68
+ Wan2.1 (T2V-1.3B)
69
+ </div>
70
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
71
+ Wan: Open and Advanced Large-Scale Video Generative Models.
72
+ </div>
73
+ """)
74
+
75
+ with gr.Row():
76
+ with gr.Column():
77
+ txt2vid_prompt = gr.Textbox(
78
+ label="Prompt",
79
+ placeholder="Describe the video you want to generate",
80
+ )
81
+ tar_lang = gr.Radio(
82
+ choices=["ZH", "EN"],
83
+ label="Target language of prompt enhance",
84
+ value="ZH")
85
+ run_p_button = gr.Button(value="Prompt Enhance")
86
+
87
+ with gr.Accordion("Advanced Options", open=True):
88
+ resolution = gr.Dropdown(
89
+ label='Resolution(Width*Height)',
90
+ choices=[
91
+ '480*832',
92
+ '832*480',
93
+ '624*624',
94
+ '704*544',
95
+ '544*704',
96
+ ],
97
+ value='480*832')
98
+
99
+ with gr.Row():
100
+ sd_steps = gr.Slider(
101
+ label="Diffusion steps",
102
+ minimum=1,
103
+ maximum=1000,
104
+ value=50,
105
+ step=1)
106
+ guide_scale = gr.Slider(
107
+ label="Guide scale",
108
+ minimum=0,
109
+ maximum=20,
110
+ value=6.0,
111
+ step=1)
112
+ with gr.Row():
113
+ shift_scale = gr.Slider(
114
+ label="Shift scale",
115
+ minimum=0,
116
+ maximum=20,
117
+ value=8.0,
118
+ step=1)
119
+ seed = gr.Slider(
120
+ label="Seed",
121
+ minimum=-1,
122
+ maximum=2147483647,
123
+ step=1,
124
+ value=-1)
125
+ n_prompt = gr.Textbox(
126
+ label="Negative Prompt",
127
+ placeholder="Describe the negative prompt you want to add"
128
+ )
129
+
130
+ run_t2v_button = gr.Button("Generate Video")
131
+
132
+ with gr.Column():
133
+ result_gallery = gr.Video(
134
+ label='Generated Video', interactive=False, height=600)
135
+
136
+ run_p_button.click(
137
+ fn=prompt_enc,
138
+ inputs=[txt2vid_prompt, tar_lang],
139
+ outputs=[txt2vid_prompt])
140
+
141
+ run_t2v_button.click(
142
+ fn=t2v_generation,
143
+ inputs=[
144
+ txt2vid_prompt, resolution, sd_steps, guide_scale, shift_scale,
145
+ seed, n_prompt
146
+ ],
147
+ outputs=[result_gallery],
148
+ )
149
+
150
+ return demo
151
+
152
+
153
+ # Main
154
+ def _parse_args():
155
+ parser = argparse.ArgumentParser(
156
+ description="Generate a video from a text prompt or image using Gradio")
157
+ parser.add_argument(
158
+ "--ckpt_dir",
159
+ type=str,
160
+ default="cache",
161
+ help="The path to the checkpoint directory.")
162
+ parser.add_argument(
163
+ "--prompt_extend_method",
164
+ type=str,
165
+ default="local_qwen",
166
+ choices=["dashscope", "local_qwen"],
167
+ help="The prompt extend method to use.")
168
+ parser.add_argument(
169
+ "--prompt_extend_model",
170
+ type=str,
171
+ default=None,
172
+ help="The prompt extend model to use.")
173
+
174
+ args = parser.parse_args()
175
+
176
+ return args
177
+
178
+
179
+ if __name__ == '__main__':
180
+ args = _parse_args()
181
+
182
+ print("Step1: Init prompt_expander...", end='', flush=True)
183
+ if args.prompt_extend_method == "dashscope":
184
+ prompt_expander = DashScopePromptExpander(
185
+ model_name=args.prompt_extend_model, is_vl=False)
186
+ elif args.prompt_extend_method == "local_qwen":
187
+ prompt_expander = QwenPromptExpander(
188
+ model_name=args.prompt_extend_model, is_vl=False, device=0)
189
+ else:
190
+ raise NotImplementedError(
191
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
192
+ print("done", flush=True)
193
+
194
+ print("Step2: Init 1.3B t2v model...", end='', flush=True)
195
+ cfg = WAN_CONFIGS['t2v-1.3B']
196
+ wan_t2v = wan.WanT2V(
197
+ config=cfg,
198
+ checkpoint_dir=args.ckpt_dir,
199
+ device_id=0,
200
+ rank=0,
201
+ t5_fsdp=False,
202
+ dit_fsdp=False,
203
+ use_usp=False,
204
+ )
205
+ print("done", flush=True)
206
+
207
+ demo = gradio_interface()
208
+ demo.launch(server_name="0.0.0.0", share=False, server_port=7860)
Wan2.1/gradio/t2v_14B_singleGPU.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import argparse
3
+ import os
4
+ import os.path as osp
5
+ import sys
6
+ import warnings
7
+
8
+ import gradio as gr
9
+
10
+ warnings.filterwarnings('ignore')
11
+
12
+ # Model
13
+ sys.path.insert(
14
+ 0, os.path.sep.join(osp.realpath(__file__).split(os.path.sep)[:-2]))
15
+ import wan
16
+ from wan.configs import WAN_CONFIGS
17
+ from wan.utils.prompt_extend import DashScopePromptExpander, QwenPromptExpander
18
+ from wan.utils.utils import cache_video
19
+
20
+ # Global Var
21
+ prompt_expander = None
22
+ wan_t2v = None
23
+
24
+
25
+ # Button Func
26
+ def prompt_enc(prompt, tar_lang):
27
+ global prompt_expander
28
+ prompt_output = prompt_expander(prompt, tar_lang=tar_lang.lower())
29
+ if prompt_output.status == False:
30
+ return prompt
31
+ else:
32
+ return prompt_output.prompt
33
+
34
+
35
+ def t2v_generation(txt2vid_prompt, resolution, sd_steps, guide_scale,
36
+ shift_scale, seed, n_prompt):
37
+ global wan_t2v
38
+ # print(f"{txt2vid_prompt},{resolution},{sd_steps},{guide_scale},{shift_scale},{seed},{n_prompt}")
39
+
40
+ W = int(resolution.split("*")[0])
41
+ H = int(resolution.split("*")[1])
42
+ video = wan_t2v.generate(
43
+ txt2vid_prompt,
44
+ size=(W, H),
45
+ shift=shift_scale,
46
+ sampling_steps=sd_steps,
47
+ guide_scale=guide_scale,
48
+ n_prompt=n_prompt,
49
+ seed=seed,
50
+ offload_model=True)
51
+
52
+ cache_video(
53
+ tensor=video[None],
54
+ save_file="example.mp4",
55
+ fps=16,
56
+ nrow=1,
57
+ normalize=True,
58
+ value_range=(-1, 1))
59
+
60
+ return "example.mp4"
61
+
62
+
63
+ # Interface
64
+ def gradio_interface():
65
+ with gr.Blocks() as demo:
66
+ gr.Markdown("""
67
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 20px;">
68
+ Wan2.1 (T2V-14B)
69
+ </div>
70
+ <div style="text-align: center; font-size: 16px; font-weight: normal; margin-bottom: 20px;">
71
+ Wan: Open and Advanced Large-Scale Video Generative Models.
72
+ </div>
73
+ """)
74
+
75
+ with gr.Row():
76
+ with gr.Column():
77
+ txt2vid_prompt = gr.Textbox(
78
+ label="Prompt",
79
+ placeholder="Describe the video you want to generate",
80
+ )
81
+ tar_lang = gr.Radio(
82
+ choices=["ZH", "EN"],
83
+ label="Target language of prompt enhance",
84
+ value="ZH")
85
+ run_p_button = gr.Button(value="Prompt Enhance")
86
+
87
+ with gr.Accordion("Advanced Options", open=True):
88
+ resolution = gr.Dropdown(
89
+ label='Resolution(Width*Height)',
90
+ choices=[
91
+ '720*1280', '1280*720', '960*960', '1088*832',
92
+ '832*1088', '480*832', '832*480', '624*624',
93
+ '704*544', '544*704'
94
+ ],
95
+ value='720*1280')
96
+
97
+ with gr.Row():
98
+ sd_steps = gr.Slider(
99
+ label="Diffusion steps",
100
+ minimum=1,
101
+ maximum=1000,
102
+ value=50,
103
+ step=1)
104
+ guide_scale = gr.Slider(
105
+ label="Guide scale",
106
+ minimum=0,
107
+ maximum=20,
108
+ value=5.0,
109
+ step=1)
110
+ with gr.Row():
111
+ shift_scale = gr.Slider(
112
+ label="Shift scale",
113
+ minimum=0,
114
+ maximum=10,
115
+ value=5.0,
116
+ step=1)
117
+ seed = gr.Slider(
118
+ label="Seed",
119
+ minimum=-1,
120
+ maximum=2147483647,
121
+ step=1,
122
+ value=-1)
123
+ n_prompt = gr.Textbox(
124
+ label="Negative Prompt",
125
+ placeholder="Describe the negative prompt you want to add"
126
+ )
127
+
128
+ run_t2v_button = gr.Button("Generate Video")
129
+
130
+ with gr.Column():
131
+ result_gallery = gr.Video(
132
+ label='Generated Video', interactive=False, height=600)
133
+
134
+ run_p_button.click(
135
+ fn=prompt_enc,
136
+ inputs=[txt2vid_prompt, tar_lang],
137
+ outputs=[txt2vid_prompt])
138
+
139
+ run_t2v_button.click(
140
+ fn=t2v_generation,
141
+ inputs=[
142
+ txt2vid_prompt, resolution, sd_steps, guide_scale, shift_scale,
143
+ seed, n_prompt
144
+ ],
145
+ outputs=[result_gallery],
146
+ )
147
+
148
+ return demo
149
+
150
+
151
+ # Main
152
+ def _parse_args():
153
+ parser = argparse.ArgumentParser(
154
+ description="Generate a video from a text prompt or image using Gradio")
155
+ parser.add_argument(
156
+ "--ckpt_dir",
157
+ type=str,
158
+ default="cache",
159
+ help="The path to the checkpoint directory.")
160
+ parser.add_argument(
161
+ "--prompt_extend_method",
162
+ type=str,
163
+ default="local_qwen",
164
+ choices=["dashscope", "local_qwen"],
165
+ help="The prompt extend method to use.")
166
+ parser.add_argument(
167
+ "--prompt_extend_model",
168
+ type=str,
169
+ default=None,
170
+ help="The prompt extend model to use.")
171
+
172
+ args = parser.parse_args()
173
+
174
+ return args
175
+
176
+
177
+ if __name__ == '__main__':
178
+ args = _parse_args()
179
+
180
+ print("Step1: Init prompt_expander...", end='', flush=True)
181
+ if args.prompt_extend_method == "dashscope":
182
+ prompt_expander = DashScopePromptExpander(
183
+ model_name=args.prompt_extend_model, is_vl=False)
184
+ elif args.prompt_extend_method == "local_qwen":
185
+ prompt_expander = QwenPromptExpander(
186
+ model_name=args.prompt_extend_model, is_vl=False, device=0)
187
+ else:
188
+ raise NotImplementedError(
189
+ f"Unsupport prompt_extend_method: {args.prompt_extend_method}")
190
+ print("done", flush=True)
191
+
192
+ print("Step2: Init 14B t2v model...", end='', flush=True)
193
+ cfg = WAN_CONFIGS['t2v-14B']
194
+ wan_t2v = wan.WanT2V(
195
+ config=cfg,
196
+ checkpoint_dir=args.ckpt_dir,
197
+ device_id=0,
198
+ rank=0,
199
+ t5_fsdp=False,
200
+ dit_fsdp=False,
201
+ use_usp=False,
202
+ )
203
+ print("done", flush=True)
204
+
205
+ demo = gradio_interface()
206
+ demo.launch(server_name="0.0.0.0", share=False, server_port=7860)
Wan2.1/gradio/vace.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) Alibaba, Inc. and its affiliates.
3
+
4
+ import argparse
5
+ import datetime
6
+ import os
7
+ import sys
8
+
9
+ import imageio
10
+ import numpy as np
11
+ import torch
12
+
13
+ import gradio as gr
14
+
15
+ sys.path.insert(
16
+ 0, os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-2]))
17
+ import wan
18
+ from wan import WanVace, WanVaceMP
19
+ from wan.configs import SIZE_CONFIGS, WAN_CONFIGS
20
+
21
+
22
+ class FixedSizeQueue:
23
+
24
+ def __init__(self, max_size):
25
+ self.max_size = max_size
26
+ self.queue = []
27
+
28
+ def add(self, item):
29
+ self.queue.insert(0, item)
30
+ if len(self.queue) > self.max_size:
31
+ self.queue.pop()
32
+
33
+ def get(self):
34
+ return self.queue
35
+
36
+ def __repr__(self):
37
+ return str(self.queue)
38
+
39
+
40
+ class VACEInference:
41
+
42
+ def __init__(self,
43
+ cfg,
44
+ skip_load=False,
45
+ gallery_share=True,
46
+ gallery_share_limit=5):
47
+ self.cfg = cfg
48
+ self.save_dir = cfg.save_dir
49
+ self.gallery_share = gallery_share
50
+ self.gallery_share_data = FixedSizeQueue(max_size=gallery_share_limit)
51
+ if not skip_load:
52
+ if not args.mp:
53
+ self.pipe = WanVace(
54
+ config=WAN_CONFIGS[cfg.model_name],
55
+ checkpoint_dir=cfg.ckpt_dir,
56
+ device_id=0,
57
+ rank=0,
58
+ t5_fsdp=False,
59
+ dit_fsdp=False,
60
+ use_usp=False,
61
+ )
62
+ else:
63
+ self.pipe = WanVaceMP(
64
+ config=WAN_CONFIGS[cfg.model_name],
65
+ checkpoint_dir=cfg.ckpt_dir,
66
+ use_usp=True,
67
+ ulysses_size=cfg.ulysses_size,
68
+ ring_size=cfg.ring_size)
69
+
70
+ def create_ui(self, *args, **kwargs):
71
+ gr.Markdown("""
72
+ <div style="text-align: center; font-size: 24px; font-weight: bold; margin-bottom: 15px;">
73
+ <a href="https://ali-vilab.github.io/VACE-Page/" style="text-decoration: none; color: inherit;">VACE-WAN Demo</a>
74
+ </div>
75
+ """)
76
+ with gr.Row(variant='panel', equal_height=True):
77
+ with gr.Column(scale=1, min_width=0):
78
+ self.src_video = gr.Video(
79
+ label="src_video",
80
+ sources=['upload'],
81
+ value=None,
82
+ interactive=True)
83
+ with gr.Column(scale=1, min_width=0):
84
+ self.src_mask = gr.Video(
85
+ label="src_mask",
86
+ sources=['upload'],
87
+ value=None,
88
+ interactive=True)
89
+ #
90
+ with gr.Row(variant='panel', equal_height=True):
91
+ with gr.Column(scale=1, min_width=0):
92
+ with gr.Row(equal_height=True):
93
+ self.src_ref_image_1 = gr.Image(
94
+ label='src_ref_image_1',
95
+ height=200,
96
+ interactive=True,
97
+ type='filepath',
98
+ image_mode='RGB',
99
+ sources=['upload'],
100
+ elem_id="src_ref_image_1",
101
+ format='png')
102
+ self.src_ref_image_2 = gr.Image(
103
+ label='src_ref_image_2',
104
+ height=200,
105
+ interactive=True,
106
+ type='filepath',
107
+ image_mode='RGB',
108
+ sources=['upload'],
109
+ elem_id="src_ref_image_2",
110
+ format='png')
111
+ self.src_ref_image_3 = gr.Image(
112
+ label='src_ref_image_3',
113
+ height=200,
114
+ interactive=True,
115
+ type='filepath',
116
+ image_mode='RGB',
117
+ sources=['upload'],
118
+ elem_id="src_ref_image_3",
119
+ format='png')
120
+ with gr.Row(variant='panel', equal_height=True):
121
+ with gr.Column(scale=1):
122
+ self.prompt = gr.Textbox(
123
+ show_label=False,
124
+ placeholder="positive_prompt_input",
125
+ elem_id='positive_prompt',
126
+ container=True,
127
+ autofocus=True,
128
+ elem_classes='type_row',
129
+ visible=True,
130
+ lines=2)
131
+ self.negative_prompt = gr.Textbox(
132
+ show_label=False,
133
+ value=self.pipe.config.sample_neg_prompt,
134
+ placeholder="negative_prompt_input",
135
+ elem_id='negative_prompt',
136
+ container=True,
137
+ autofocus=False,
138
+ elem_classes='type_row',
139
+ visible=True,
140
+ interactive=True,
141
+ lines=1)
142
+ #
143
+ with gr.Row(variant='panel', equal_height=True):
144
+ with gr.Column(scale=1, min_width=0):
145
+ with gr.Row(equal_height=True):
146
+ self.shift_scale = gr.Slider(
147
+ label='shift_scale',
148
+ minimum=0.0,
149
+ maximum=100.0,
150
+ step=1.0,
151
+ value=16.0,
152
+ interactive=True)
153
+ self.sample_steps = gr.Slider(
154
+ label='sample_steps',
155
+ minimum=1,
156
+ maximum=100,
157
+ step=1,
158
+ value=25,
159
+ interactive=True)
160
+ self.context_scale = gr.Slider(
161
+ label='context_scale',
162
+ minimum=0.0,
163
+ maximum=2.0,
164
+ step=0.1,
165
+ value=1.0,
166
+ interactive=True)
167
+ self.guide_scale = gr.Slider(
168
+ label='guide_scale',
169
+ minimum=1,
170
+ maximum=10,
171
+ step=0.5,
172
+ value=5.0,
173
+ interactive=True)
174
+ self.infer_seed = gr.Slider(
175
+ minimum=-1, maximum=10000000, value=2025, label="Seed")
176
+ #
177
+ with gr.Accordion(label="Usable without source video", open=False):
178
+ with gr.Row(equal_height=True):
179
+ self.output_height = gr.Textbox(
180
+ label='resolutions_height',
181
+ # value=480,
182
+ value=720,
183
+ interactive=True)
184
+ self.output_width = gr.Textbox(
185
+ label='resolutions_width',
186
+ # value=832,
187
+ value=1280,
188
+ interactive=True)
189
+ self.frame_rate = gr.Textbox(
190
+ label='frame_rate', value=16, interactive=True)
191
+ self.num_frames = gr.Textbox(
192
+ label='num_frames', value=81, interactive=True)
193
+ #
194
+ with gr.Row(equal_height=True):
195
+ with gr.Column(scale=5):
196
+ self.generate_button = gr.Button(
197
+ value='Run',
198
+ elem_classes='type_row',
199
+ elem_id='generate_button',
200
+ visible=True)
201
+ with gr.Column(scale=1):
202
+ self.refresh_button = gr.Button(value='\U0001f504') # 🔄
203
+ #
204
+ self.output_gallery = gr.Gallery(
205
+ label="output_gallery",
206
+ value=[],
207
+ interactive=False,
208
+ allow_preview=True,
209
+ preview=True)
210
+
211
+ def generate(self, output_gallery, src_video, src_mask, src_ref_image_1,
212
+ src_ref_image_2, src_ref_image_3, prompt, negative_prompt,
213
+ shift_scale, sample_steps, context_scale, guide_scale,
214
+ infer_seed, output_height, output_width, frame_rate,
215
+ num_frames):
216
+ output_height, output_width, frame_rate, num_frames = int(
217
+ output_height), int(output_width), int(frame_rate), int(num_frames)
218
+ src_ref_images = [
219
+ x for x in [src_ref_image_1, src_ref_image_2, src_ref_image_3]
220
+ if x is not None
221
+ ]
222
+ src_video, src_mask, src_ref_images = self.pipe.prepare_source(
223
+ [src_video], [src_mask], [src_ref_images],
224
+ num_frames=num_frames,
225
+ image_size=SIZE_CONFIGS[f"{output_width}*{output_height}"],
226
+ device=self.pipe.device)
227
+ video = self.pipe.generate(
228
+ prompt,
229
+ src_video,
230
+ src_mask,
231
+ src_ref_images,
232
+ size=(output_width, output_height),
233
+ context_scale=context_scale,
234
+ shift=shift_scale,
235
+ sampling_steps=sample_steps,
236
+ guide_scale=guide_scale,
237
+ n_prompt=negative_prompt,
238
+ seed=infer_seed,
239
+ offload_model=True)
240
+
241
+ name = '{0:%Y%m%d%-H%M%S}'.format(datetime.datetime.now())
242
+ video_path = os.path.join(self.save_dir, f'cur_gallery_{name}.mp4')
243
+ video_frames = (
244
+ torch.clamp(video / 2 + 0.5, min=0.0, max=1.0).permute(1, 2, 3, 0) *
245
+ 255).cpu().numpy().astype(np.uint8)
246
+
247
+ try:
248
+ writer = imageio.get_writer(
249
+ video_path,
250
+ fps=frame_rate,
251
+ codec='libx264',
252
+ quality=8,
253
+ macro_block_size=1)
254
+ for frame in video_frames:
255
+ writer.append_data(frame)
256
+ writer.close()
257
+ print(video_path)
258
+ except Exception as e:
259
+ raise gr.Error(f"Video save error: {e}")
260
+
261
+ if self.gallery_share:
262
+ self.gallery_share_data.add(video_path)
263
+ return self.gallery_share_data.get()
264
+ else:
265
+ return [video_path]
266
+
267
+ def set_callbacks(self, **kwargs):
268
+ self.gen_inputs = [
269
+ self.output_gallery, self.src_video, self.src_mask,
270
+ self.src_ref_image_1, self.src_ref_image_2, self.src_ref_image_3,
271
+ self.prompt, self.negative_prompt, self.shift_scale,
272
+ self.sample_steps, self.context_scale, self.guide_scale,
273
+ self.infer_seed, self.output_height, self.output_width,
274
+ self.frame_rate, self.num_frames
275
+ ]
276
+ self.gen_outputs = [self.output_gallery]
277
+ self.generate_button.click(
278
+ self.generate,
279
+ inputs=self.gen_inputs,
280
+ outputs=self.gen_outputs,
281
+ queue=True)
282
+ self.refresh_button.click(
283
+ lambda x: self.gallery_share_data.get()
284
+ if self.gallery_share else x,
285
+ inputs=[self.output_gallery],
286
+ outputs=[self.output_gallery])
287
+
288
+
289
+ if __name__ == '__main__':
290
+ parser = argparse.ArgumentParser(
291
+ description='Argparser for VACE-WAN Demo:\n')
292
+ parser.add_argument(
293
+ '--server_port', dest='server_port', help='', type=int, default=7860)
294
+ parser.add_argument(
295
+ '--server_name', dest='server_name', help='', default='0.0.0.0')
296
+ parser.add_argument('--root_path', dest='root_path', help='', default=None)
297
+ parser.add_argument('--save_dir', dest='save_dir', help='', default='cache')
298
+ parser.add_argument(
299
+ "--mp",
300
+ action="store_true",
301
+ help="Use Multi-GPUs",
302
+ )
303
+ parser.add_argument(
304
+ "--model_name",
305
+ type=str,
306
+ default="vace-14B",
307
+ choices=list(WAN_CONFIGS.keys()),
308
+ help="The model name to run.")
309
+ parser.add_argument(
310
+ "--ulysses_size",
311
+ type=int,
312
+ default=1,
313
+ help="The size of the ulysses parallelism in DiT.")
314
+ parser.add_argument(
315
+ "--ring_size",
316
+ type=int,
317
+ default=1,
318
+ help="The size of the ring attention parallelism in DiT.")
319
+ parser.add_argument(
320
+ "--ckpt_dir",
321
+ type=str,
322
+ # default='models/VACE-Wan2.1-1.3B-Preview',
323
+ default='models/Wan2.1-VACE-14B/',
324
+ help="The path to the checkpoint directory.",
325
+ )
326
+ parser.add_argument(
327
+ "--offload_to_cpu",
328
+ action="store_true",
329
+ help="Offloading unnecessary computations to CPU.",
330
+ )
331
+
332
+ args = parser.parse_args()
333
+
334
+ if not os.path.exists(args.save_dir):
335
+ os.makedirs(args.save_dir, exist_ok=True)
336
+
337
+ with gr.Blocks() as demo:
338
+ infer_gr = VACEInference(
339
+ args, skip_load=False, gallery_share=True, gallery_share_limit=5)
340
+ infer_gr.create_ui()
341
+ infer_gr.set_callbacks()
342
+ allowed_paths = [args.save_dir]
343
+ demo.queue(status_update_rate=1).launch(
344
+ server_name=args.server_name,
345
+ server_port=args.server_port,
346
+ root_path=args.root_path,
347
+ allowed_paths=allowed_paths,
348
+ show_error=True,
349
+ debug=True)
Wan2.1/pyproject.toml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "wan"
7
+ version = "2.1.0"
8
+ description = "Wan: Open and Advanced Large-Scale Video Generative Models"
9
+ authors = [
10
+ { name = "Wan Team", email = "wan.ai@alibabacloud.com" }
11
+ ]
12
+ license = { file = "LICENSE.txt" }
13
+ readme = "README.md"
14
+ requires-python = ">=3.10,<4.0"
15
+ dependencies = [
16
+ "torch>=2.4.0",
17
+ "torchvision>=0.19.0",
18
+ "opencv-python>=4.9.0.80",
19
+ "diffusers>=0.31.0",
20
+ "transformers>=4.49.0",
21
+ "tokenizers>=0.20.3",
22
+ "accelerate>=1.1.1",
23
+ "tqdm",
24
+ "imageio",
25
+ "easydict",
26
+ "ftfy",
27
+ "dashscope",
28
+ "imageio-ffmpeg",
29
+ "flash_attn",
30
+ "gradio>=5.0.0",
31
+ "numpy>=1.23.5,<2"
32
+ ]
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest",
37
+ "black",
38
+ "flake8",
39
+ "isort",
40
+ "mypy",
41
+ "huggingface-hub[cli]"
42
+ ]
43
+
44
+ [project.urls]
45
+ homepage = "https://wanxai.com"
46
+ documentation = "https://github.com/Wan-Video/Wan2.1"
47
+ repository = "https://github.com/Wan-Video/Wan2.1"
48
+ huggingface = "https://huggingface.co/Wan-AI/"
49
+ modelscope = "https://modelscope.cn/organization/Wan-AI"
50
+ discord = "https://discord.gg/p5XbdQV7"
51
+
52
+ [tool.setuptools]
53
+ packages = ["wan"]
54
+
55
+ [tool.setuptools.package-data]
56
+ "wan" = ["**/*.py"]
57
+
58
+ [tool.black]
59
+ line-length = 88
60
+
61
+ [tool.isort]
62
+ profile = "black"
63
+
64
+ [tool.mypy]
65
+ strict = true
66
+
67
+
Wan2.1/requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ numpy>=1.23.5,<2
Wan2.1/tests/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+
2
+ Put all your models (Wan2.1-T2V-1.3B, Wan2.1-T2V-14B, Wan2.1-I2V-14B-480P, Wan2.1-I2V-14B-720P) in a folder and specify the max GPU number you want to use.
3
+
4
+ ```bash
5
+ bash ./test.sh <local model dir> <gpu number>
6
+ ```
Wan2.1/tests/test.sh ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+
4
+ if [ "$#" -eq 2 ]; then
5
+ MODEL_DIR=$(realpath "$1")
6
+ GPUS=$2
7
+ else
8
+ echo "Usage: $0 <local model dir> <gpu number>"
9
+ exit 1
10
+ fi
11
+
12
+ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
13
+ REPO_ROOT="$(dirname "$SCRIPT_DIR")"
14
+ cd "$REPO_ROOT" || exit 1
15
+
16
+ PY_FILE=./generate.py
17
+
18
+
19
+ function t2v_1_3B() {
20
+ T2V_1_3B_CKPT_DIR="$MODEL_DIR/Wan2.1-T2V-1.3B"
21
+
22
+ # 1-GPU Test
23
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_1_3B 1-GPU Test: "
24
+ python $PY_FILE --task t2v-1.3B --size 480*832 --ckpt_dir $T2V_1_3B_CKPT_DIR
25
+
26
+ # Multiple GPU Test
27
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_1_3B Multiple GPU Test: "
28
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-1.3B --ckpt_dir $T2V_1_3B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
29
+
30
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_1_3B Multiple GPU, prompt extend local_qwen: "
31
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-1.3B --ckpt_dir $T2V_1_3B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang "en"
32
+
33
+ if [ -n "${DASH_API_KEY+x}" ]; then
34
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_1_3B Multiple GPU, prompt extend dashscope: "
35
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-1.3B --ckpt_dir $T2V_1_3B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_method "dashscope"
36
+ else
37
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> No DASH_API_KEY found, skip the dashscope extend test."
38
+ fi
39
+ }
40
+
41
+ function t2v_14B() {
42
+ T2V_14B_CKPT_DIR="$MODEL_DIR/Wan2.1-T2V-14B"
43
+
44
+ # 1-GPU Test
45
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_14B 1-GPU Test: "
46
+ python $PY_FILE --task t2v-14B --size 480*832 --ckpt_dir $T2V_14B_CKPT_DIR
47
+
48
+ # Multiple GPU Test
49
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_14B Multiple GPU Test: "
50
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-14B --ckpt_dir $T2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
51
+
52
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2v_14B Multiple GPU, prompt extend local_qwen: "
53
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2v-14B --ckpt_dir $T2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang "en"
54
+ }
55
+
56
+
57
+
58
+ function t2i_14B() {
59
+ T2V_14B_CKPT_DIR="$MODEL_DIR/Wan2.1-T2V-14B"
60
+
61
+ # 1-GPU Test
62
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2i_14B 1-GPU Test: "
63
+ python $PY_FILE --task t2i-14B --size 480*832 --ckpt_dir $T2V_14B_CKPT_DIR
64
+
65
+ # Multiple GPU Test
66
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2i_14B Multiple GPU Test: "
67
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2i-14B --ckpt_dir $T2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
68
+
69
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> t2i_14B Multiple GPU, prompt extend local_qwen: "
70
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task t2i-14B --ckpt_dir $T2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-3B-Instruct" --prompt_extend_target_lang "en"
71
+ }
72
+
73
+
74
+ function i2v_14B_480p() {
75
+ I2V_14B_CKPT_DIR="$MODEL_DIR/Wan2.1-I2V-14B-480P"
76
+
77
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B 1-GPU Test: "
78
+ python $PY_FILE --task i2v-14B --size 832*480 --ckpt_dir $I2V_14B_CKPT_DIR
79
+
80
+ # Multiple GPU Test
81
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU Test: "
82
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-14B --ckpt_dir $I2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
83
+
84
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU, prompt extend local_qwen: "
85
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-14B --ckpt_dir $I2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_model "Qwen/Qwen2.5-VL-3B-Instruct" --prompt_extend_target_lang "en"
86
+
87
+ if [ -n "${DASH_API_KEY+x}" ]; then
88
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU, prompt extend dashscope: "
89
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-14B --ckpt_dir $I2V_14B_CKPT_DIR --size 832*480 --dit_fsdp --t5_fsdp --ulysses_size $GPUS --use_prompt_extend --prompt_extend_method "dashscope"
90
+ else
91
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> No DASH_API_KEY found, skip the dashscope extend test."
92
+ fi
93
+ }
94
+
95
+
96
+ function i2v_14B_720p() {
97
+ I2V_14B_CKPT_DIR="$MODEL_DIR/Wan2.1-I2V-14B-720P"
98
+
99
+ # 1-GPU Test
100
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B 1-GPU Test: "
101
+ python $PY_FILE --task i2v-14B --size 720*1280 --ckpt_dir $I2V_14B_CKPT_DIR
102
+
103
+ # Multiple GPU Test
104
+ echo -e "\n\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> i2v_14B Multiple GPU Test: "
105
+ torchrun --nproc_per_node=$GPUS $PY_FILE --task i2v-14B --ckpt_dir $I2V_14B_CKPT_DIR --size 720*1280 --dit_fsdp --t5_fsdp --ulysses_size $GPUS
106
+ }
107
+
108
+ function vace_1_3B() {
109
+ VACE_1_3B_CKPT_DIR="$MODEL_DIR/VACE-Wan2.1-1.3B-Preview/"
110
+ torchrun --nproc_per_node=$GPUS $PY_FILE --ulysses_size $GPUS --task vace-1.3B --size 480*832 --ckpt_dir $VACE_1_3B_CKPT_DIR
111
+
112
+ }
113
+
114
+
115
+ t2i_14B
116
+ t2v_1_3B
117
+ t2v_14B
118
+ i2v_14B_480p
119
+ i2v_14B_720p
120
+ vace_1_3B
Wan2.1/wan/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from . import configs, distributed, modules
2
+ from .first_last_frame2video import WanFLF2V
3
+ from .image2video import WanI2V
4
+ from .text2video import WanT2V
5
+ from .vace import WanVace, WanVaceMP
Wan2.1/wan/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (441 Bytes). View file
 
Wan2.1/wan/configs/__init__.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # the config of flf2v_14B is the same as i2v_14B
16
+ flf2v_14B = copy.deepcopy(i2v_14B)
17
+ flf2v_14B.__name__ = 'Config: Wan FLF2V 14B'
18
+ flf2v_14B.sample_neg_prompt = "镜头切换," + flf2v_14B.sample_neg_prompt
19
+
20
+ WAN_CONFIGS = {
21
+ 't2v-14B': t2v_14B,
22
+ 't2v-1.3B': t2v_1_3B,
23
+ 'i2v-14B': i2v_14B,
24
+ 't2i-14B': t2i_14B,
25
+ 'flf2v-14B': flf2v_14B,
26
+ 'vace-1.3B': t2v_1_3B,
27
+ 'vace-14B': t2v_14B,
28
+ }
29
+
30
+ SIZE_CONFIGS = {
31
+ '720*1280': (720, 1280),
32
+ '1280*720': (1280, 720),
33
+ '480*832': (480, 832),
34
+ '832*480': (832, 480),
35
+ '1024*1024': (1024, 1024),
36
+ }
37
+
38
+ MAX_AREA_CONFIGS = {
39
+ '720*1280': 720 * 1280,
40
+ '1280*720': 1280 * 720,
41
+ '480*832': 480 * 832,
42
+ '832*480': 832 * 480,
43
+ }
44
+
45
+ SUPPORTED_SIZES = {
46
+ 't2v-14B': ('720*1280', '1280*720', '480*832', '832*480'),
47
+ 't2v-1.3B': ('480*832', '832*480'),
48
+ 'i2v-14B': ('720*1280', '1280*720', '480*832', '832*480'),
49
+ 'flf2v-14B': ('720*1280', '1280*720', '480*832', '832*480'),
50
+ 't2i-14B': tuple(SIZE_CONFIGS.keys()),
51
+ 'vace-1.3B': ('480*832', '832*480'),
52
+ 'vace-14B': ('720*1280', '1280*720', '480*832', '832*480')
53
+ }
Wan2.1/wan/configs/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.33 kB). View file
 
Wan2.1/wan/configs/__pycache__/shared_config.cpython-312.pyc ADDED
Binary file (1.03 kB). View file
 
Wan2.1/wan/configs/__pycache__/wan_i2v_14B.cpython-312.pyc ADDED
Binary file (1.41 kB). View file
 
Wan2.1/wan/configs/__pycache__/wan_t2v_14B.cpython-312.pyc ADDED
Binary file (1.01 kB). View file
 
Wan2.1/wan/configs/__pycache__/wan_t2v_1_3B.cpython-312.pyc ADDED
Binary file (1.02 kB). View file
 
Wan2.1/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压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走'
Wan2.1/wan/configs/wan_i2v_14B.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ i2v_14B.sample_neg_prompt = "镜头晃动," + i2v_14B.sample_neg_prompt
12
+
13
+ i2v_14B.t5_checkpoint = 'models_t5_umt5-xxl-enc-bf16.pth'
14
+ i2v_14B.t5_tokenizer = 'google/umt5-xxl'
15
+
16
+ # clip
17
+ i2v_14B.clip_model = 'clip_xlm_roberta_vit_h_14'
18
+ i2v_14B.clip_dtype = torch.float16
19
+ i2v_14B.clip_checkpoint = 'models_clip_open-clip-xlm-roberta-large-vit-huge-14.pth'
20
+ i2v_14B.clip_tokenizer = 'xlm-roberta-large'
21
+
22
+ # vae
23
+ i2v_14B.vae_checkpoint = 'Wan2.1_VAE.pth'
24
+ i2v_14B.vae_stride = (4, 8, 8)
25
+
26
+ # transformer
27
+ i2v_14B.patch_size = (1, 2, 2)
28
+ i2v_14B.dim = 5120
29
+ i2v_14B.ffn_dim = 13824
30
+ i2v_14B.freq_dim = 256
31
+ i2v_14B.num_heads = 40
32
+ i2v_14B.num_layers = 40
33
+ i2v_14B.window_size = (-1, -1)
34
+ i2v_14B.qk_norm = True
35
+ i2v_14B.cross_attn_norm = True
36
+ i2v_14B.eps = 1e-6
Wan2.1/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
Wan2.1/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
Wan2.1/wan/distributed/__init__.py ADDED
File without changes
Wan2.1/wan/distributed/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (174 Bytes). View file