Fabrice-TIERCELIN
commited on
Upload 5 files
Browse files- hyvideo/__init__.py +0 -0
- hyvideo/config.py +398 -0
- hyvideo/constants.py +90 -0
- hyvideo/inference.py +671 -0
- hyvideo/prompt_rewrite.py +51 -0
hyvideo/__init__.py
ADDED
File without changes
|
hyvideo/config.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from .constants import *
|
3 |
+
import re
|
4 |
+
from .modules.models import HUNYUAN_VIDEO_CONFIG
|
5 |
+
|
6 |
+
|
7 |
+
def parse_args(namespace=None):
|
8 |
+
parser = argparse.ArgumentParser(description="HunyuanVideo inference script")
|
9 |
+
|
10 |
+
parser = add_network_args(parser)
|
11 |
+
parser = add_extra_models_args(parser)
|
12 |
+
parser = add_denoise_schedule_args(parser)
|
13 |
+
parser = add_inference_args(parser)
|
14 |
+
parser = add_parallel_args(parser)
|
15 |
+
|
16 |
+
args = parser.parse_args(namespace=namespace)
|
17 |
+
args = sanity_check_args(args)
|
18 |
+
|
19 |
+
return args
|
20 |
+
|
21 |
+
|
22 |
+
def add_network_args(parser: argparse.ArgumentParser):
|
23 |
+
group = parser.add_argument_group(title="HunyuanVideo network args")
|
24 |
+
|
25 |
+
# Main model
|
26 |
+
group.add_argument(
|
27 |
+
"--model",
|
28 |
+
type=str,
|
29 |
+
choices=list(HUNYUAN_VIDEO_CONFIG.keys()),
|
30 |
+
default="HYVideo-T/2-cfgdistill",
|
31 |
+
)
|
32 |
+
group.add_argument(
|
33 |
+
"--latent-channels",
|
34 |
+
type=str,
|
35 |
+
default=16,
|
36 |
+
help="Number of latent channels of DiT. If None, it will be determined by `vae`. If provided, "
|
37 |
+
"it still needs to match the latent channels of the VAE model.",
|
38 |
+
)
|
39 |
+
group.add_argument(
|
40 |
+
"--precision",
|
41 |
+
type=str,
|
42 |
+
default="bf16",
|
43 |
+
choices=PRECISIONS,
|
44 |
+
help="Precision mode. Options: fp32, fp16, bf16. Applied to the backbone model and optimizer.",
|
45 |
+
)
|
46 |
+
|
47 |
+
# RoPE
|
48 |
+
group.add_argument(
|
49 |
+
"--rope-theta", type=int, default=256, help="Theta used in RoPE."
|
50 |
+
)
|
51 |
+
return parser
|
52 |
+
|
53 |
+
|
54 |
+
def add_extra_models_args(parser: argparse.ArgumentParser):
|
55 |
+
group = parser.add_argument_group(
|
56 |
+
title="Extra models args, including vae, text encoders and tokenizers)"
|
57 |
+
)
|
58 |
+
|
59 |
+
# - VAE
|
60 |
+
group.add_argument(
|
61 |
+
"--vae",
|
62 |
+
type=str,
|
63 |
+
default="884-16c-hy",
|
64 |
+
choices=list(VAE_PATH),
|
65 |
+
help="Name of the VAE model.",
|
66 |
+
)
|
67 |
+
group.add_argument(
|
68 |
+
"--vae-precision",
|
69 |
+
type=str,
|
70 |
+
default="fp16",
|
71 |
+
choices=PRECISIONS,
|
72 |
+
help="Precision mode for the VAE model.",
|
73 |
+
)
|
74 |
+
group.add_argument(
|
75 |
+
"--vae-tiling",
|
76 |
+
action="store_true",
|
77 |
+
help="Enable tiling for the VAE model to save GPU memory.",
|
78 |
+
)
|
79 |
+
group.set_defaults(vae_tiling=True)
|
80 |
+
|
81 |
+
group.add_argument(
|
82 |
+
"--text-encoder",
|
83 |
+
type=str,
|
84 |
+
default="llm",
|
85 |
+
choices=list(TEXT_ENCODER_PATH),
|
86 |
+
help="Name of the text encoder model.",
|
87 |
+
)
|
88 |
+
group.add_argument(
|
89 |
+
"--text-encoder-precision",
|
90 |
+
type=str,
|
91 |
+
default="fp16",
|
92 |
+
choices=PRECISIONS,
|
93 |
+
help="Precision mode for the text encoder model.",
|
94 |
+
)
|
95 |
+
group.add_argument(
|
96 |
+
"--text-states-dim",
|
97 |
+
type=int,
|
98 |
+
default=4096,
|
99 |
+
help="Dimension of the text encoder hidden states.",
|
100 |
+
)
|
101 |
+
group.add_argument(
|
102 |
+
"--text-len", type=int, default=256, help="Maximum length of the text input."
|
103 |
+
)
|
104 |
+
group.add_argument(
|
105 |
+
"--tokenizer",
|
106 |
+
type=str,
|
107 |
+
default="llm",
|
108 |
+
choices=list(TOKENIZER_PATH),
|
109 |
+
help="Name of the tokenizer model.",
|
110 |
+
)
|
111 |
+
group.add_argument(
|
112 |
+
"--prompt-template",
|
113 |
+
type=str,
|
114 |
+
default="dit-llm-encode",
|
115 |
+
choices=PROMPT_TEMPLATE,
|
116 |
+
help="Image prompt template for the decoder-only text encoder model.",
|
117 |
+
)
|
118 |
+
group.add_argument(
|
119 |
+
"--prompt-template-video",
|
120 |
+
type=str,
|
121 |
+
default="dit-llm-encode-video",
|
122 |
+
choices=PROMPT_TEMPLATE,
|
123 |
+
help="Video prompt template for the decoder-only text encoder model.",
|
124 |
+
)
|
125 |
+
group.add_argument(
|
126 |
+
"--hidden-state-skip-layer",
|
127 |
+
type=int,
|
128 |
+
default=2,
|
129 |
+
help="Skip layer for hidden states.",
|
130 |
+
)
|
131 |
+
group.add_argument(
|
132 |
+
"--apply-final-norm",
|
133 |
+
action="store_true",
|
134 |
+
help="Apply final normalization to the used text encoder hidden states.",
|
135 |
+
)
|
136 |
+
|
137 |
+
# - CLIP
|
138 |
+
group.add_argument(
|
139 |
+
"--text-encoder-2",
|
140 |
+
type=str,
|
141 |
+
default="clipL",
|
142 |
+
choices=list(TEXT_ENCODER_PATH),
|
143 |
+
help="Name of the second text encoder model.",
|
144 |
+
)
|
145 |
+
group.add_argument(
|
146 |
+
"--text-encoder-precision-2",
|
147 |
+
type=str,
|
148 |
+
default="fp16",
|
149 |
+
choices=PRECISIONS,
|
150 |
+
help="Precision mode for the second text encoder model.",
|
151 |
+
)
|
152 |
+
group.add_argument(
|
153 |
+
"--text-states-dim-2",
|
154 |
+
type=int,
|
155 |
+
default=768,
|
156 |
+
help="Dimension of the second text encoder hidden states.",
|
157 |
+
)
|
158 |
+
group.add_argument(
|
159 |
+
"--tokenizer-2",
|
160 |
+
type=str,
|
161 |
+
default="clipL",
|
162 |
+
choices=list(TOKENIZER_PATH),
|
163 |
+
help="Name of the second tokenizer model.",
|
164 |
+
)
|
165 |
+
group.add_argument(
|
166 |
+
"--text-len-2",
|
167 |
+
type=int,
|
168 |
+
default=77,
|
169 |
+
help="Maximum length of the second text input.",
|
170 |
+
)
|
171 |
+
|
172 |
+
return parser
|
173 |
+
|
174 |
+
|
175 |
+
def add_denoise_schedule_args(parser: argparse.ArgumentParser):
|
176 |
+
group = parser.add_argument_group(title="Denoise schedule args")
|
177 |
+
|
178 |
+
group.add_argument(
|
179 |
+
"--denoise-type",
|
180 |
+
type=str,
|
181 |
+
default="flow",
|
182 |
+
help="Denoise type for noised inputs.",
|
183 |
+
)
|
184 |
+
|
185 |
+
# Flow Matching
|
186 |
+
group.add_argument(
|
187 |
+
"--flow-shift",
|
188 |
+
type=float,
|
189 |
+
default=7.0,
|
190 |
+
help="Shift factor for flow matching schedulers.",
|
191 |
+
)
|
192 |
+
group.add_argument(
|
193 |
+
"--flow-reverse",
|
194 |
+
action="store_true",
|
195 |
+
help="If reverse, learning/sampling from t=1 -> t=0.",
|
196 |
+
)
|
197 |
+
group.add_argument(
|
198 |
+
"--flow-solver",
|
199 |
+
type=str,
|
200 |
+
default="euler",
|
201 |
+
help="Solver for flow matching.",
|
202 |
+
)
|
203 |
+
group.add_argument(
|
204 |
+
"--use-linear-quadratic-schedule",
|
205 |
+
action="store_true",
|
206 |
+
help="Use linear quadratic schedule for flow matching."
|
207 |
+
"Following MovieGen (https://ai.meta.com/static-resource/movie-gen-research-paper)",
|
208 |
+
)
|
209 |
+
group.add_argument(
|
210 |
+
"--linear-schedule-end",
|
211 |
+
type=int,
|
212 |
+
default=25,
|
213 |
+
help="End step for linear quadratic schedule for flow matching.",
|
214 |
+
)
|
215 |
+
|
216 |
+
return parser
|
217 |
+
|
218 |
+
|
219 |
+
def add_inference_args(parser: argparse.ArgumentParser):
|
220 |
+
group = parser.add_argument_group(title="Inference args")
|
221 |
+
|
222 |
+
# ======================== Model loads ========================
|
223 |
+
group.add_argument(
|
224 |
+
"--model-base",
|
225 |
+
type=str,
|
226 |
+
default="ckpts",
|
227 |
+
help="Root path of all the models, including t2v models and extra models.",
|
228 |
+
)
|
229 |
+
group.add_argument(
|
230 |
+
"--dit-weight",
|
231 |
+
type=str,
|
232 |
+
default="ckpts/hunyuan-video-t2v-720p/transformers/mp_rank_00_model_states.pt",
|
233 |
+
help="Path to the HunyuanVideo model. If None, search the model in the args.model_root."
|
234 |
+
"1. If it is a file, load the model directly."
|
235 |
+
"2. If it is a directory, search the model in the directory. Support two types of models: "
|
236 |
+
"1) named `pytorch_model_*.pt`"
|
237 |
+
"2) named `*_model_states.pt`, where * can be `mp_rank_00`.",
|
238 |
+
)
|
239 |
+
group.add_argument(
|
240 |
+
"--model-resolution",
|
241 |
+
type=str,
|
242 |
+
default="540p",
|
243 |
+
choices=["540p", "720p"],
|
244 |
+
help="Root path of all the models, including t2v models and extra models.",
|
245 |
+
)
|
246 |
+
group.add_argument(
|
247 |
+
"--load-key",
|
248 |
+
type=str,
|
249 |
+
default="module",
|
250 |
+
help="Key to load the model states. 'module' for the main model, 'ema' for the EMA model.",
|
251 |
+
)
|
252 |
+
group.add_argument(
|
253 |
+
"--use-cpu-offload",
|
254 |
+
action="store_true",
|
255 |
+
help="Use CPU offload for the model load.",
|
256 |
+
)
|
257 |
+
|
258 |
+
# ======================== Inference general setting ========================
|
259 |
+
group.add_argument(
|
260 |
+
"--batch-size",
|
261 |
+
type=int,
|
262 |
+
default=1,
|
263 |
+
help="Batch size for inference and evaluation.",
|
264 |
+
)
|
265 |
+
group.add_argument(
|
266 |
+
"--infer-steps",
|
267 |
+
type=int,
|
268 |
+
default=50,
|
269 |
+
help="Number of denoising steps for inference.",
|
270 |
+
)
|
271 |
+
group.add_argument(
|
272 |
+
"--disable-autocast",
|
273 |
+
action="store_true",
|
274 |
+
help="Disable autocast for denoising loop and vae decoding in pipeline sampling.",
|
275 |
+
)
|
276 |
+
group.add_argument(
|
277 |
+
"--save-path",
|
278 |
+
type=str,
|
279 |
+
default="./results",
|
280 |
+
help="Path to save the generated samples.",
|
281 |
+
)
|
282 |
+
group.add_argument(
|
283 |
+
"--save-path-suffix",
|
284 |
+
type=str,
|
285 |
+
default="",
|
286 |
+
help="Suffix for the directory of saved samples.",
|
287 |
+
)
|
288 |
+
group.add_argument(
|
289 |
+
"--name-suffix",
|
290 |
+
type=str,
|
291 |
+
default="",
|
292 |
+
help="Suffix for the names of saved samples.",
|
293 |
+
)
|
294 |
+
group.add_argument(
|
295 |
+
"--num-videos",
|
296 |
+
type=int,
|
297 |
+
default=1,
|
298 |
+
help="Number of videos to generate for each prompt.",
|
299 |
+
)
|
300 |
+
# ---sample size---
|
301 |
+
group.add_argument(
|
302 |
+
"--video-size",
|
303 |
+
type=int,
|
304 |
+
nargs="+",
|
305 |
+
default=(720, 1280),
|
306 |
+
help="Video size for training. If a single value is provided, it will be used for both height "
|
307 |
+
"and width. If two values are provided, they will be used for height and width "
|
308 |
+
"respectively.",
|
309 |
+
)
|
310 |
+
group.add_argument(
|
311 |
+
"--video-length",
|
312 |
+
type=int,
|
313 |
+
default=129,
|
314 |
+
help="How many frames to sample from a video. if using 3d vae, the number should be 4n+1",
|
315 |
+
)
|
316 |
+
# --- prompt ---
|
317 |
+
group.add_argument(
|
318 |
+
"--prompt",
|
319 |
+
type=str,
|
320 |
+
default=None,
|
321 |
+
help="Prompt for sampling during evaluation.",
|
322 |
+
)
|
323 |
+
group.add_argument(
|
324 |
+
"--seed-type",
|
325 |
+
type=str,
|
326 |
+
default="auto",
|
327 |
+
choices=["file", "random", "fixed", "auto"],
|
328 |
+
help="Seed type for evaluation. If file, use the seed from the CSV file. If random, generate a "
|
329 |
+
"random seed. If fixed, use the fixed seed given by `--seed`. If auto, `csv` will use the "
|
330 |
+
"seed column if available, otherwise use the fixed `seed` value. `prompt` will use the "
|
331 |
+
"fixed `seed` value.",
|
332 |
+
)
|
333 |
+
group.add_argument("--seed", type=int, default=None, help="Seed for evaluation.")
|
334 |
+
|
335 |
+
# Classifier-Free Guidance
|
336 |
+
group.add_argument(
|
337 |
+
"--neg-prompt", type=str, default=None, help="Negative prompt for sampling."
|
338 |
+
)
|
339 |
+
group.add_argument(
|
340 |
+
"--cfg-scale", type=float, default=1.0, help="Classifier free guidance scale."
|
341 |
+
)
|
342 |
+
group.add_argument(
|
343 |
+
"--embedded-cfg-scale",
|
344 |
+
type=float,
|
345 |
+
default=6.0,
|
346 |
+
help="Embeded classifier free guidance scale.",
|
347 |
+
)
|
348 |
+
|
349 |
+
group.add_argument(
|
350 |
+
"--use-fp8",
|
351 |
+
action="store_true",
|
352 |
+
help="Enable use fp8 for inference acceleration."
|
353 |
+
)
|
354 |
+
|
355 |
+
group.add_argument(
|
356 |
+
"--reproduce",
|
357 |
+
action="store_true",
|
358 |
+
help="Enable reproducibility by setting random seeds and deterministic algorithms.",
|
359 |
+
)
|
360 |
+
|
361 |
+
return parser
|
362 |
+
|
363 |
+
|
364 |
+
def add_parallel_args(parser: argparse.ArgumentParser):
|
365 |
+
group = parser.add_argument_group(title="Parallel args")
|
366 |
+
|
367 |
+
# ======================== Model loads ========================
|
368 |
+
group.add_argument(
|
369 |
+
"--ulysses-degree",
|
370 |
+
type=int,
|
371 |
+
default=1,
|
372 |
+
help="Ulysses degree.",
|
373 |
+
)
|
374 |
+
group.add_argument(
|
375 |
+
"--ring-degree",
|
376 |
+
type=int,
|
377 |
+
default=1,
|
378 |
+
help="Ulysses degree.",
|
379 |
+
)
|
380 |
+
|
381 |
+
return parser
|
382 |
+
|
383 |
+
|
384 |
+
def sanity_check_args(args):
|
385 |
+
# VAE channels
|
386 |
+
vae_pattern = r"\d{2,3}-\d{1,2}c-\w+"
|
387 |
+
if not re.match(vae_pattern, args.vae):
|
388 |
+
raise ValueError(
|
389 |
+
f"Invalid VAE model: {args.vae}. Must be in the format of '{vae_pattern}'."
|
390 |
+
)
|
391 |
+
vae_channels = int(args.vae.split("-")[1][:-1])
|
392 |
+
if args.latent_channels is None:
|
393 |
+
args.latent_channels = vae_channels
|
394 |
+
if vae_channels != args.latent_channels:
|
395 |
+
raise ValueError(
|
396 |
+
f"Latent channels ({args.latent_channels}) must match the VAE channels ({vae_channels})."
|
397 |
+
)
|
398 |
+
return args
|
hyvideo/constants.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
|
4 |
+
__all__ = [
|
5 |
+
"C_SCALE",
|
6 |
+
"PROMPT_TEMPLATE",
|
7 |
+
"MODEL_BASE",
|
8 |
+
"PRECISIONS",
|
9 |
+
"NORMALIZATION_TYPE",
|
10 |
+
"ACTIVATION_TYPE",
|
11 |
+
"VAE_PATH",
|
12 |
+
"TEXT_ENCODER_PATH",
|
13 |
+
"TOKENIZER_PATH",
|
14 |
+
"TEXT_PROJECTION",
|
15 |
+
"DATA_TYPE",
|
16 |
+
"NEGATIVE_PROMPT",
|
17 |
+
]
|
18 |
+
|
19 |
+
PRECISION_TO_TYPE = {
|
20 |
+
'fp32': torch.float32,
|
21 |
+
'fp16': torch.float16,
|
22 |
+
'bf16': torch.bfloat16,
|
23 |
+
}
|
24 |
+
|
25 |
+
# =================== Constant Values =====================
|
26 |
+
# Computation scale factor, 1P = 1_000_000_000_000_000. Tensorboard will display the value in PetaFLOPS to avoid
|
27 |
+
# overflow error when tensorboard logging values.
|
28 |
+
C_SCALE = 1_000_000_000_000_000
|
29 |
+
|
30 |
+
# When using decoder-only models, we must provide a prompt template to instruct the text encoder
|
31 |
+
# on how to generate the text.
|
32 |
+
# --------------------------------------------------------------------
|
33 |
+
PROMPT_TEMPLATE_ENCODE = (
|
34 |
+
"<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, "
|
35 |
+
"quantity, text, spatial relationships of the objects and background:<|eot_id|>"
|
36 |
+
"<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
|
37 |
+
)
|
38 |
+
PROMPT_TEMPLATE_ENCODE_VIDEO = (
|
39 |
+
"<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: "
|
40 |
+
"1. The main content and theme of the video."
|
41 |
+
"2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
|
42 |
+
"3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
|
43 |
+
"4. background environment, light, style and atmosphere."
|
44 |
+
"5. camera angles, movements, and transitions used in the video:<|eot_id|>"
|
45 |
+
"<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
|
46 |
+
)
|
47 |
+
|
48 |
+
NEGATIVE_PROMPT = "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion"
|
49 |
+
|
50 |
+
PROMPT_TEMPLATE = {
|
51 |
+
"dit-llm-encode": {
|
52 |
+
"template": PROMPT_TEMPLATE_ENCODE,
|
53 |
+
"crop_start": 36,
|
54 |
+
},
|
55 |
+
"dit-llm-encode-video": {
|
56 |
+
"template": PROMPT_TEMPLATE_ENCODE_VIDEO,
|
57 |
+
"crop_start": 95,
|
58 |
+
},
|
59 |
+
}
|
60 |
+
|
61 |
+
# ======================= Model ======================
|
62 |
+
PRECISIONS = {"fp32", "fp16", "bf16"}
|
63 |
+
NORMALIZATION_TYPE = {"layer", "rms"}
|
64 |
+
ACTIVATION_TYPE = {"relu", "silu", "gelu", "gelu_tanh"}
|
65 |
+
|
66 |
+
# =================== Model Path =====================
|
67 |
+
MODEL_BASE = os.getenv("MODEL_BASE", "./ckpts")
|
68 |
+
|
69 |
+
# =================== Data =======================
|
70 |
+
DATA_TYPE = {"image", "video", "image_video"}
|
71 |
+
|
72 |
+
# 3D VAE
|
73 |
+
VAE_PATH = {"884-16c-hy": f"{MODEL_BASE}/hunyuan-video-t2v-720p/vae"}
|
74 |
+
|
75 |
+
# Text Encoder
|
76 |
+
TEXT_ENCODER_PATH = {
|
77 |
+
"clipL": f"{MODEL_BASE}/text_encoder_2",
|
78 |
+
"llm": f"{MODEL_BASE}/text_encoder",
|
79 |
+
}
|
80 |
+
|
81 |
+
# Tokenizer
|
82 |
+
TOKENIZER_PATH = {
|
83 |
+
"clipL": f"{MODEL_BASE}/text_encoder_2",
|
84 |
+
"llm": f"{MODEL_BASE}/text_encoder",
|
85 |
+
}
|
86 |
+
|
87 |
+
TEXT_PROJECTION = {
|
88 |
+
"linear", # Default, an nn.Linear() layer
|
89 |
+
"single_refiner", # Single TokenRefiner. Refer to LI-DiT
|
90 |
+
}
|
hyvideo/inference.py
ADDED
@@ -0,0 +1,671 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import random
|
4 |
+
import functools
|
5 |
+
from typing import List, Optional, Tuple, Union
|
6 |
+
|
7 |
+
from pathlib import Path
|
8 |
+
from loguru import logger
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.distributed as dist
|
12 |
+
from hyvideo.constants import PROMPT_TEMPLATE, NEGATIVE_PROMPT, PRECISION_TO_TYPE
|
13 |
+
from hyvideo.vae import load_vae
|
14 |
+
from hyvideo.modules import load_model
|
15 |
+
from hyvideo.text_encoder import TextEncoder
|
16 |
+
from hyvideo.utils.data_utils import align_to
|
17 |
+
from hyvideo.modules.posemb_layers import get_nd_rotary_pos_embed
|
18 |
+
from hyvideo.modules.fp8_optimization import convert_fp8_linear
|
19 |
+
from hyvideo.diffusion.schedulers import FlowMatchDiscreteScheduler
|
20 |
+
from hyvideo.diffusion.pipelines import HunyuanVideoPipeline
|
21 |
+
|
22 |
+
try:
|
23 |
+
import xfuser
|
24 |
+
from xfuser.core.distributed import (
|
25 |
+
get_sequence_parallel_world_size,
|
26 |
+
get_sequence_parallel_rank,
|
27 |
+
get_sp_group,
|
28 |
+
initialize_model_parallel,
|
29 |
+
init_distributed_environment
|
30 |
+
)
|
31 |
+
except:
|
32 |
+
xfuser = None
|
33 |
+
get_sequence_parallel_world_size = None
|
34 |
+
get_sequence_parallel_rank = None
|
35 |
+
get_sp_group = None
|
36 |
+
initialize_model_parallel = None
|
37 |
+
init_distributed_environment = None
|
38 |
+
|
39 |
+
|
40 |
+
def parallelize_transformer(pipe):
|
41 |
+
transformer = pipe.transformer
|
42 |
+
original_forward = transformer.forward
|
43 |
+
|
44 |
+
@functools.wraps(transformer.__class__.forward)
|
45 |
+
def new_forward(
|
46 |
+
self,
|
47 |
+
x: torch.Tensor,
|
48 |
+
t: torch.Tensor, # Should be in range(0, 1000).
|
49 |
+
text_states: torch.Tensor = None,
|
50 |
+
text_mask: torch.Tensor = None, # Now we don't use it.
|
51 |
+
text_states_2: Optional[torch.Tensor] = None, # Text embedding for modulation.
|
52 |
+
freqs_cos: Optional[torch.Tensor] = None,
|
53 |
+
freqs_sin: Optional[torch.Tensor] = None,
|
54 |
+
guidance: torch.Tensor = None, # Guidance for modulation, should be cfg_scale x 1000.
|
55 |
+
return_dict: bool = True,
|
56 |
+
):
|
57 |
+
if x.shape[-2] // 2 % get_sequence_parallel_world_size() == 0:
|
58 |
+
# try to split x by height
|
59 |
+
split_dim = -2
|
60 |
+
elif x.shape[-1] // 2 % get_sequence_parallel_world_size() == 0:
|
61 |
+
# try to split x by width
|
62 |
+
split_dim = -1
|
63 |
+
else:
|
64 |
+
raise ValueError(f"Cannot split video sequence into ulysses_degree x ring_degree ({get_sequence_parallel_world_size()}) parts evenly")
|
65 |
+
|
66 |
+
# patch sizes for the temporal, height, and width dimensions are 1, 2, and 2.
|
67 |
+
temporal_size, h, w = x.shape[2], x.shape[3] // 2, x.shape[4] // 2
|
68 |
+
|
69 |
+
x = torch.chunk(x, get_sequence_parallel_world_size(),dim=split_dim)[get_sequence_parallel_rank()]
|
70 |
+
|
71 |
+
dim_thw = freqs_cos.shape[-1]
|
72 |
+
freqs_cos = freqs_cos.reshape(temporal_size, h, w, dim_thw)
|
73 |
+
freqs_cos = torch.chunk(freqs_cos, get_sequence_parallel_world_size(),dim=split_dim - 1)[get_sequence_parallel_rank()]
|
74 |
+
freqs_cos = freqs_cos.reshape(-1, dim_thw)
|
75 |
+
dim_thw = freqs_sin.shape[-1]
|
76 |
+
freqs_sin = freqs_sin.reshape(temporal_size, h, w, dim_thw)
|
77 |
+
freqs_sin = torch.chunk(freqs_sin, get_sequence_parallel_world_size(),dim=split_dim - 1)[get_sequence_parallel_rank()]
|
78 |
+
freqs_sin = freqs_sin.reshape(-1, dim_thw)
|
79 |
+
|
80 |
+
from xfuser.core.long_ctx_attention import xFuserLongContextAttention
|
81 |
+
|
82 |
+
for block in transformer.double_blocks + transformer.single_blocks:
|
83 |
+
block.hybrid_seq_parallel_attn = xFuserLongContextAttention()
|
84 |
+
|
85 |
+
output = original_forward(
|
86 |
+
x,
|
87 |
+
t,
|
88 |
+
text_states,
|
89 |
+
text_mask,
|
90 |
+
text_states_2,
|
91 |
+
freqs_cos,
|
92 |
+
freqs_sin,
|
93 |
+
guidance,
|
94 |
+
return_dict,
|
95 |
+
)
|
96 |
+
|
97 |
+
return_dict = not isinstance(output, tuple)
|
98 |
+
sample = output["x"]
|
99 |
+
sample = get_sp_group().all_gather(sample, dim=split_dim)
|
100 |
+
output["x"] = sample
|
101 |
+
return output
|
102 |
+
|
103 |
+
new_forward = new_forward.__get__(transformer)
|
104 |
+
transformer.forward = new_forward
|
105 |
+
|
106 |
+
|
107 |
+
class Inference(object):
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
args,
|
111 |
+
vae,
|
112 |
+
vae_kwargs,
|
113 |
+
text_encoder,
|
114 |
+
model,
|
115 |
+
text_encoder_2=None,
|
116 |
+
pipeline=None,
|
117 |
+
use_cpu_offload=False,
|
118 |
+
device=None,
|
119 |
+
logger=None,
|
120 |
+
parallel_args=None,
|
121 |
+
):
|
122 |
+
self.vae = vae
|
123 |
+
self.vae_kwargs = vae_kwargs
|
124 |
+
|
125 |
+
self.text_encoder = text_encoder
|
126 |
+
self.text_encoder_2 = text_encoder_2
|
127 |
+
|
128 |
+
self.model = model
|
129 |
+
self.pipeline = pipeline
|
130 |
+
self.use_cpu_offload = use_cpu_offload
|
131 |
+
|
132 |
+
self.args = args
|
133 |
+
self.device = (
|
134 |
+
device
|
135 |
+
if device is not None
|
136 |
+
else "cuda"
|
137 |
+
if torch.cuda.is_available()
|
138 |
+
else "cpu"
|
139 |
+
)
|
140 |
+
self.logger = logger
|
141 |
+
self.parallel_args = parallel_args
|
142 |
+
|
143 |
+
@classmethod
|
144 |
+
def from_pretrained(cls, pretrained_model_path, args, device=None, **kwargs):
|
145 |
+
"""
|
146 |
+
Initialize the Inference pipeline.
|
147 |
+
|
148 |
+
Args:
|
149 |
+
pretrained_model_path (str or pathlib.Path): The model path, including t2v, text encoder and vae checkpoints.
|
150 |
+
args (argparse.Namespace): The arguments for the pipeline.
|
151 |
+
device (int): The device for inference. Default is 0.
|
152 |
+
"""
|
153 |
+
# ========================================================================
|
154 |
+
logger.info(f"Got text-to-video model root path: {pretrained_model_path}")
|
155 |
+
|
156 |
+
# ==================== Initialize Distributed Environment ================
|
157 |
+
if args.ulysses_degree > 1 or args.ring_degree > 1:
|
158 |
+
assert xfuser is not None, \
|
159 |
+
"Ulysses Attention and Ring Attention requires xfuser package."
|
160 |
+
|
161 |
+
assert args.use_cpu_offload is False, \
|
162 |
+
"Cannot enable use_cpu_offload in the distributed environment."
|
163 |
+
|
164 |
+
dist.init_process_group("nccl")
|
165 |
+
|
166 |
+
assert dist.get_world_size() == args.ring_degree * args.ulysses_degree, \
|
167 |
+
"number of GPUs should be equal to ring_degree * ulysses_degree."
|
168 |
+
|
169 |
+
init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())
|
170 |
+
|
171 |
+
initialize_model_parallel(
|
172 |
+
sequence_parallel_degree=dist.get_world_size(),
|
173 |
+
ring_degree=args.ring_degree,
|
174 |
+
ulysses_degree=args.ulysses_degree,
|
175 |
+
)
|
176 |
+
device = torch.device(f"cuda:{os.environ['LOCAL_RANK']}")
|
177 |
+
else:
|
178 |
+
if device is None:
|
179 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
180 |
+
|
181 |
+
parallel_args = {"ulysses_degree": args.ulysses_degree, "ring_degree": args.ring_degree}
|
182 |
+
|
183 |
+
# ======================== Get the args path =============================
|
184 |
+
|
185 |
+
# Disable gradient
|
186 |
+
torch.set_grad_enabled(False)
|
187 |
+
|
188 |
+
# =========================== Build main model ===========================
|
189 |
+
logger.info("Building model...")
|
190 |
+
factor_kwargs = {"device": device, "dtype": PRECISION_TO_TYPE[args.precision]}
|
191 |
+
in_channels = args.latent_channels
|
192 |
+
out_channels = args.latent_channels
|
193 |
+
|
194 |
+
model = load_model(
|
195 |
+
args,
|
196 |
+
in_channels=in_channels,
|
197 |
+
out_channels=out_channels,
|
198 |
+
factor_kwargs=factor_kwargs,
|
199 |
+
)
|
200 |
+
if args.use_fp8:
|
201 |
+
convert_fp8_linear(model, args.dit_weight, original_dtype=PRECISION_TO_TYPE[args.precision])
|
202 |
+
model = model.to(device)
|
203 |
+
model = Inference.load_state_dict(args, model, pretrained_model_path)
|
204 |
+
model.eval()
|
205 |
+
|
206 |
+
# ============================= Build extra models ========================
|
207 |
+
# VAE
|
208 |
+
vae, _, s_ratio, t_ratio = load_vae(
|
209 |
+
args.vae,
|
210 |
+
args.vae_precision,
|
211 |
+
logger=logger,
|
212 |
+
device=device if not args.use_cpu_offload else "cpu",
|
213 |
+
)
|
214 |
+
vae_kwargs = {"s_ratio": s_ratio, "t_ratio": t_ratio}
|
215 |
+
|
216 |
+
# Text encoder
|
217 |
+
if args.prompt_template_video is not None:
|
218 |
+
crop_start = PROMPT_TEMPLATE[args.prompt_template_video].get(
|
219 |
+
"crop_start", 0
|
220 |
+
)
|
221 |
+
elif args.prompt_template is not None:
|
222 |
+
crop_start = PROMPT_TEMPLATE[args.prompt_template].get("crop_start", 0)
|
223 |
+
else:
|
224 |
+
crop_start = 0
|
225 |
+
max_length = args.text_len + crop_start
|
226 |
+
|
227 |
+
# prompt_template
|
228 |
+
prompt_template = (
|
229 |
+
PROMPT_TEMPLATE[args.prompt_template]
|
230 |
+
if args.prompt_template is not None
|
231 |
+
else None
|
232 |
+
)
|
233 |
+
|
234 |
+
# prompt_template_video
|
235 |
+
prompt_template_video = (
|
236 |
+
PROMPT_TEMPLATE[args.prompt_template_video]
|
237 |
+
if args.prompt_template_video is not None
|
238 |
+
else None
|
239 |
+
)
|
240 |
+
|
241 |
+
text_encoder = TextEncoder(
|
242 |
+
text_encoder_type=args.text_encoder,
|
243 |
+
max_length=max_length,
|
244 |
+
text_encoder_precision=args.text_encoder_precision,
|
245 |
+
tokenizer_type=args.tokenizer,
|
246 |
+
prompt_template=prompt_template,
|
247 |
+
prompt_template_video=prompt_template_video,
|
248 |
+
hidden_state_skip_layer=args.hidden_state_skip_layer,
|
249 |
+
apply_final_norm=args.apply_final_norm,
|
250 |
+
reproduce=args.reproduce,
|
251 |
+
logger=logger,
|
252 |
+
device=device if not args.use_cpu_offload else "cpu",
|
253 |
+
)
|
254 |
+
text_encoder_2 = None
|
255 |
+
if args.text_encoder_2 is not None:
|
256 |
+
text_encoder_2 = TextEncoder(
|
257 |
+
text_encoder_type=args.text_encoder_2,
|
258 |
+
max_length=args.text_len_2,
|
259 |
+
text_encoder_precision=args.text_encoder_precision_2,
|
260 |
+
tokenizer_type=args.tokenizer_2,
|
261 |
+
reproduce=args.reproduce,
|
262 |
+
logger=logger,
|
263 |
+
device=device if not args.use_cpu_offload else "cpu",
|
264 |
+
)
|
265 |
+
|
266 |
+
return cls(
|
267 |
+
args=args,
|
268 |
+
vae=vae,
|
269 |
+
vae_kwargs=vae_kwargs,
|
270 |
+
text_encoder=text_encoder,
|
271 |
+
text_encoder_2=text_encoder_2,
|
272 |
+
model=model,
|
273 |
+
use_cpu_offload=args.use_cpu_offload,
|
274 |
+
device=device,
|
275 |
+
logger=logger,
|
276 |
+
parallel_args=parallel_args
|
277 |
+
)
|
278 |
+
|
279 |
+
@staticmethod
|
280 |
+
def load_state_dict(args, model, pretrained_model_path):
|
281 |
+
load_key = args.load_key
|
282 |
+
dit_weight = Path(args.dit_weight)
|
283 |
+
|
284 |
+
if dit_weight is None:
|
285 |
+
model_dir = pretrained_model_path / f"t2v_{args.model_resolution}"
|
286 |
+
files = list(model_dir.glob("*.pt"))
|
287 |
+
if len(files) == 0:
|
288 |
+
raise ValueError(f"No model weights found in {model_dir}")
|
289 |
+
if str(files[0]).startswith("pytorch_model_"):
|
290 |
+
model_path = dit_weight / f"pytorch_model_{load_key}.pt"
|
291 |
+
bare_model = True
|
292 |
+
elif any(str(f).endswith("_model_states.pt") for f in files):
|
293 |
+
files = [f for f in files if str(f).endswith("_model_states.pt")]
|
294 |
+
model_path = files[0]
|
295 |
+
if len(files) > 1:
|
296 |
+
logger.warning(
|
297 |
+
f"Multiple model weights found in {dit_weight}, using {model_path}"
|
298 |
+
)
|
299 |
+
bare_model = False
|
300 |
+
else:
|
301 |
+
raise ValueError(
|
302 |
+
f"Invalid model path: {dit_weight} with unrecognized weight format: "
|
303 |
+
f"{list(map(str, files))}. When given a directory as --dit-weight, only "
|
304 |
+
f"`pytorch_model_*.pt`(provided by HunyuanDiT official) and "
|
305 |
+
f"`*_model_states.pt`(saved by deepspeed) can be parsed. If you want to load a "
|
306 |
+
f"specific weight file, please provide the full path to the file."
|
307 |
+
)
|
308 |
+
else:
|
309 |
+
if dit_weight.is_dir():
|
310 |
+
files = list(dit_weight.glob("*.pt"))
|
311 |
+
if len(files) == 0:
|
312 |
+
raise ValueError(f"No model weights found in {dit_weight}")
|
313 |
+
if str(files[0]).startswith("pytorch_model_"):
|
314 |
+
model_path = dit_weight / f"pytorch_model_{load_key}.pt"
|
315 |
+
bare_model = True
|
316 |
+
elif any(str(f).endswith("_model_states.pt") for f in files):
|
317 |
+
files = [f for f in files if str(f).endswith("_model_states.pt")]
|
318 |
+
model_path = files[0]
|
319 |
+
if len(files) > 1:
|
320 |
+
logger.warning(
|
321 |
+
f"Multiple model weights found in {dit_weight}, using {model_path}"
|
322 |
+
)
|
323 |
+
bare_model = False
|
324 |
+
else:
|
325 |
+
raise ValueError(
|
326 |
+
f"Invalid model path: {dit_weight} with unrecognized weight format: "
|
327 |
+
f"{list(map(str, files))}. When given a directory as --dit-weight, only "
|
328 |
+
f"`pytorch_model_*.pt`(provided by HunyuanDiT official) and "
|
329 |
+
f"`*_model_states.pt`(saved by deepspeed) can be parsed. If you want to load a "
|
330 |
+
f"specific weight file, please provide the full path to the file."
|
331 |
+
)
|
332 |
+
elif dit_weight.is_file():
|
333 |
+
model_path = dit_weight
|
334 |
+
bare_model = "unknown"
|
335 |
+
else:
|
336 |
+
raise ValueError(f"Invalid model path: {dit_weight}")
|
337 |
+
|
338 |
+
if not model_path.exists():
|
339 |
+
raise ValueError(f"model_path not exists: {model_path}")
|
340 |
+
logger.info(f"Loading torch model {model_path}...")
|
341 |
+
state_dict = torch.load(model_path, map_location=lambda storage, loc: storage)
|
342 |
+
|
343 |
+
if bare_model == "unknown" and ("ema" in state_dict or "module" in state_dict):
|
344 |
+
bare_model = False
|
345 |
+
if bare_model is False:
|
346 |
+
if load_key in state_dict:
|
347 |
+
state_dict = state_dict[load_key]
|
348 |
+
else:
|
349 |
+
raise KeyError(
|
350 |
+
f"Missing key: `{load_key}` in the checkpoint: {model_path}. The keys in the checkpoint "
|
351 |
+
f"are: {list(state_dict.keys())}."
|
352 |
+
)
|
353 |
+
model.load_state_dict(state_dict, strict=True)
|
354 |
+
return model
|
355 |
+
|
356 |
+
@staticmethod
|
357 |
+
def parse_size(size):
|
358 |
+
if isinstance(size, int):
|
359 |
+
size = [size]
|
360 |
+
if not isinstance(size, (list, tuple)):
|
361 |
+
raise ValueError(f"Size must be an integer or (height, width), got {size}.")
|
362 |
+
if len(size) == 1:
|
363 |
+
size = [size[0], size[0]]
|
364 |
+
if len(size) != 2:
|
365 |
+
raise ValueError(f"Size must be an integer or (height, width), got {size}.")
|
366 |
+
return size
|
367 |
+
|
368 |
+
|
369 |
+
class HunyuanVideoSampler(Inference):
|
370 |
+
def __init__(
|
371 |
+
self,
|
372 |
+
args,
|
373 |
+
vae,
|
374 |
+
vae_kwargs,
|
375 |
+
text_encoder,
|
376 |
+
model,
|
377 |
+
text_encoder_2=None,
|
378 |
+
pipeline=None,
|
379 |
+
use_cpu_offload=False,
|
380 |
+
device=0,
|
381 |
+
logger=None,
|
382 |
+
parallel_args=None
|
383 |
+
):
|
384 |
+
super().__init__(
|
385 |
+
args,
|
386 |
+
vae,
|
387 |
+
vae_kwargs,
|
388 |
+
text_encoder,
|
389 |
+
model,
|
390 |
+
text_encoder_2=text_encoder_2,
|
391 |
+
pipeline=pipeline,
|
392 |
+
use_cpu_offload=use_cpu_offload,
|
393 |
+
device=device,
|
394 |
+
logger=logger,
|
395 |
+
parallel_args=parallel_args
|
396 |
+
)
|
397 |
+
|
398 |
+
self.pipeline = self.load_diffusion_pipeline(
|
399 |
+
args=args,
|
400 |
+
vae=self.vae,
|
401 |
+
text_encoder=self.text_encoder,
|
402 |
+
text_encoder_2=self.text_encoder_2,
|
403 |
+
model=self.model,
|
404 |
+
device=self.device,
|
405 |
+
)
|
406 |
+
|
407 |
+
self.default_negative_prompt = NEGATIVE_PROMPT
|
408 |
+
if self.parallel_args['ulysses_degree'] > 1 or self.parallel_args['ring_degree'] > 1:
|
409 |
+
parallelize_transformer(self.pipeline)
|
410 |
+
|
411 |
+
def load_diffusion_pipeline(
|
412 |
+
self,
|
413 |
+
args,
|
414 |
+
vae,
|
415 |
+
text_encoder,
|
416 |
+
text_encoder_2,
|
417 |
+
model,
|
418 |
+
scheduler=None,
|
419 |
+
device=None,
|
420 |
+
progress_bar_config=None,
|
421 |
+
data_type="video",
|
422 |
+
):
|
423 |
+
"""Load the denoising scheduler for inference."""
|
424 |
+
if scheduler is None:
|
425 |
+
if args.denoise_type == "flow":
|
426 |
+
scheduler = FlowMatchDiscreteScheduler(
|
427 |
+
shift=args.flow_shift,
|
428 |
+
reverse=args.flow_reverse,
|
429 |
+
solver=args.flow_solver,
|
430 |
+
)
|
431 |
+
else:
|
432 |
+
raise ValueError(f"Invalid denoise type {args.denoise_type}")
|
433 |
+
|
434 |
+
pipeline = HunyuanVideoPipeline(
|
435 |
+
vae=vae,
|
436 |
+
text_encoder=text_encoder,
|
437 |
+
text_encoder_2=text_encoder_2,
|
438 |
+
transformer=model,
|
439 |
+
scheduler=scheduler,
|
440 |
+
progress_bar_config=progress_bar_config,
|
441 |
+
args=args,
|
442 |
+
)
|
443 |
+
if self.use_cpu_offload:
|
444 |
+
pipeline.enable_sequential_cpu_offload()
|
445 |
+
else:
|
446 |
+
pipeline = pipeline.to(device)
|
447 |
+
|
448 |
+
return pipeline
|
449 |
+
|
450 |
+
def get_rotary_pos_embed(self, video_length, height, width):
|
451 |
+
target_ndim = 3
|
452 |
+
ndim = 5 - 2
|
453 |
+
# 884
|
454 |
+
if "884" in self.args.vae:
|
455 |
+
latents_size = [(video_length - 1) // 4 + 1, height // 8, width // 8]
|
456 |
+
elif "888" in self.args.vae:
|
457 |
+
latents_size = [(video_length - 1) // 8 + 1, height // 8, width // 8]
|
458 |
+
else:
|
459 |
+
latents_size = [video_length, height // 8, width // 8]
|
460 |
+
|
461 |
+
if isinstance(self.model.patch_size, int):
|
462 |
+
assert all(s % self.model.patch_size == 0 for s in latents_size), (
|
463 |
+
f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
|
464 |
+
f"but got {latents_size}."
|
465 |
+
)
|
466 |
+
rope_sizes = [s // self.model.patch_size for s in latents_size]
|
467 |
+
elif isinstance(self.model.patch_size, list):
|
468 |
+
assert all(
|
469 |
+
s % self.model.patch_size[idx] == 0
|
470 |
+
for idx, s in enumerate(latents_size)
|
471 |
+
), (
|
472 |
+
f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
|
473 |
+
f"but got {latents_size}."
|
474 |
+
)
|
475 |
+
rope_sizes = [
|
476 |
+
s // self.model.patch_size[idx] for idx, s in enumerate(latents_size)
|
477 |
+
]
|
478 |
+
|
479 |
+
if len(rope_sizes) != target_ndim:
|
480 |
+
rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
|
481 |
+
head_dim = self.model.hidden_size // self.model.heads_num
|
482 |
+
rope_dim_list = self.model.rope_dim_list
|
483 |
+
if rope_dim_list is None:
|
484 |
+
rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
|
485 |
+
assert (
|
486 |
+
sum(rope_dim_list) == head_dim
|
487 |
+
), "sum(rope_dim_list) should equal to head_dim of attention layer"
|
488 |
+
freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
|
489 |
+
rope_dim_list,
|
490 |
+
rope_sizes,
|
491 |
+
theta=self.args.rope_theta,
|
492 |
+
use_real=True,
|
493 |
+
theta_rescale_factor=1,
|
494 |
+
)
|
495 |
+
return freqs_cos, freqs_sin
|
496 |
+
|
497 |
+
@torch.no_grad()
|
498 |
+
def predict(
|
499 |
+
self,
|
500 |
+
prompt,
|
501 |
+
height=192,
|
502 |
+
width=336,
|
503 |
+
video_length=129,
|
504 |
+
seed=None,
|
505 |
+
negative_prompt=None,
|
506 |
+
infer_steps=50,
|
507 |
+
guidance_scale=6,
|
508 |
+
flow_shift=5.0,
|
509 |
+
embedded_guidance_scale=None,
|
510 |
+
batch_size=1,
|
511 |
+
num_videos_per_prompt=1,
|
512 |
+
**kwargs,
|
513 |
+
):
|
514 |
+
"""
|
515 |
+
Predict the image/video from the given text.
|
516 |
+
|
517 |
+
Args:
|
518 |
+
prompt (str or List[str]): The input text.
|
519 |
+
kwargs:
|
520 |
+
height (int): The height of the output video. Default is 192.
|
521 |
+
width (int): The width of the output video. Default is 336.
|
522 |
+
video_length (int): The frame number of the output video. Default is 129.
|
523 |
+
seed (int or List[str]): The random seed for the generation. Default is a random integer.
|
524 |
+
negative_prompt (str or List[str]): The negative text prompt. Default is an empty string.
|
525 |
+
guidance_scale (float): The guidance scale for the generation. Default is 6.0.
|
526 |
+
num_images_per_prompt (int): The number of images per prompt. Default is 1.
|
527 |
+
infer_steps (int): The number of inference steps. Default is 100.
|
528 |
+
"""
|
529 |
+
out_dict = dict()
|
530 |
+
|
531 |
+
# ========================================================================
|
532 |
+
# Arguments: seed
|
533 |
+
# ========================================================================
|
534 |
+
if isinstance(seed, torch.Tensor):
|
535 |
+
seed = seed.tolist()
|
536 |
+
if seed is None:
|
537 |
+
seeds = [
|
538 |
+
random.randint(0, 1_000_000)
|
539 |
+
for _ in range(batch_size * num_videos_per_prompt)
|
540 |
+
]
|
541 |
+
elif isinstance(seed, int):
|
542 |
+
seeds = [
|
543 |
+
seed + i
|
544 |
+
for _ in range(batch_size)
|
545 |
+
for i in range(num_videos_per_prompt)
|
546 |
+
]
|
547 |
+
elif isinstance(seed, (list, tuple)):
|
548 |
+
if len(seed) == batch_size:
|
549 |
+
seeds = [
|
550 |
+
int(seed[i]) + j
|
551 |
+
for i in range(batch_size)
|
552 |
+
for j in range(num_videos_per_prompt)
|
553 |
+
]
|
554 |
+
elif len(seed) == batch_size * num_videos_per_prompt:
|
555 |
+
seeds = [int(s) for s in seed]
|
556 |
+
else:
|
557 |
+
raise ValueError(
|
558 |
+
f"Length of seed must be equal to number of prompt(batch_size) or "
|
559 |
+
f"batch_size * num_videos_per_prompt ({batch_size} * {num_videos_per_prompt}), got {seed}."
|
560 |
+
)
|
561 |
+
else:
|
562 |
+
raise ValueError(
|
563 |
+
f"Seed must be an integer, a list of integers, or None, got {seed}."
|
564 |
+
)
|
565 |
+
generator = [torch.Generator(self.device).manual_seed(seed) for seed in seeds]
|
566 |
+
out_dict["seeds"] = seeds
|
567 |
+
|
568 |
+
# ========================================================================
|
569 |
+
# Arguments: target_width, target_height, target_video_length
|
570 |
+
# ========================================================================
|
571 |
+
if width <= 0 or height <= 0 or video_length <= 0:
|
572 |
+
raise ValueError(
|
573 |
+
f"`height` and `width` and `video_length` must be positive integers, got height={height}, width={width}, video_length={video_length}"
|
574 |
+
)
|
575 |
+
if (video_length - 1) % 4 != 0:
|
576 |
+
raise ValueError(
|
577 |
+
f"`video_length-1` must be a multiple of 4, got {video_length}"
|
578 |
+
)
|
579 |
+
|
580 |
+
logger.info(
|
581 |
+
f"Input (height, width, video_length) = ({height}, {width}, {video_length})"
|
582 |
+
)
|
583 |
+
|
584 |
+
target_height = align_to(height, 16)
|
585 |
+
target_width = align_to(width, 16)
|
586 |
+
target_video_length = video_length
|
587 |
+
|
588 |
+
out_dict["size"] = (target_height, target_width, target_video_length)
|
589 |
+
|
590 |
+
# ========================================================================
|
591 |
+
# Arguments: prompt, new_prompt, negative_prompt
|
592 |
+
# ========================================================================
|
593 |
+
if not isinstance(prompt, str):
|
594 |
+
raise TypeError(f"`prompt` must be a string, but got {type(prompt)}")
|
595 |
+
prompt = [prompt.strip()]
|
596 |
+
|
597 |
+
# negative prompt
|
598 |
+
if negative_prompt is None or negative_prompt == "":
|
599 |
+
negative_prompt = self.default_negative_prompt
|
600 |
+
if not isinstance(negative_prompt, str):
|
601 |
+
raise TypeError(
|
602 |
+
f"`negative_prompt` must be a string, but got {type(negative_prompt)}"
|
603 |
+
)
|
604 |
+
negative_prompt = [negative_prompt.strip()]
|
605 |
+
|
606 |
+
# ========================================================================
|
607 |
+
# Scheduler
|
608 |
+
# ========================================================================
|
609 |
+
scheduler = FlowMatchDiscreteScheduler(
|
610 |
+
shift=flow_shift,
|
611 |
+
reverse=self.args.flow_reverse,
|
612 |
+
solver=self.args.flow_solver
|
613 |
+
)
|
614 |
+
self.pipeline.scheduler = scheduler
|
615 |
+
|
616 |
+
# ========================================================================
|
617 |
+
# Build Rope freqs
|
618 |
+
# ========================================================================
|
619 |
+
freqs_cos, freqs_sin = self.get_rotary_pos_embed(
|
620 |
+
target_video_length, target_height, target_width
|
621 |
+
)
|
622 |
+
n_tokens = freqs_cos.shape[0]
|
623 |
+
|
624 |
+
# ========================================================================
|
625 |
+
# Print infer args
|
626 |
+
# ========================================================================
|
627 |
+
debug_str = f"""
|
628 |
+
height: {target_height}
|
629 |
+
width: {target_width}
|
630 |
+
video_length: {target_video_length}
|
631 |
+
prompt: {prompt}
|
632 |
+
neg_prompt: {negative_prompt}
|
633 |
+
seed: {seed}
|
634 |
+
infer_steps: {infer_steps}
|
635 |
+
num_videos_per_prompt: {num_videos_per_prompt}
|
636 |
+
guidance_scale: {guidance_scale}
|
637 |
+
n_tokens: {n_tokens}
|
638 |
+
flow_shift: {flow_shift}
|
639 |
+
embedded_guidance_scale: {embedded_guidance_scale}"""
|
640 |
+
logger.debug(debug_str)
|
641 |
+
|
642 |
+
# ========================================================================
|
643 |
+
# Pipeline inference
|
644 |
+
# ========================================================================
|
645 |
+
start_time = time.time()
|
646 |
+
samples = self.pipeline(
|
647 |
+
prompt=prompt,
|
648 |
+
height=target_height,
|
649 |
+
width=target_width,
|
650 |
+
video_length=target_video_length,
|
651 |
+
num_inference_steps=infer_steps,
|
652 |
+
guidance_scale=guidance_scale,
|
653 |
+
negative_prompt=negative_prompt,
|
654 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
655 |
+
generator=generator,
|
656 |
+
output_type="pil",
|
657 |
+
freqs_cis=(freqs_cos, freqs_sin),
|
658 |
+
n_tokens=n_tokens,
|
659 |
+
embedded_guidance_scale=embedded_guidance_scale,
|
660 |
+
data_type="video" if target_video_length > 1 else "image",
|
661 |
+
is_progress_bar=True,
|
662 |
+
vae_ver=self.args.vae,
|
663 |
+
enable_tiling=self.args.vae_tiling,
|
664 |
+
)[0]
|
665 |
+
out_dict["samples"] = samples
|
666 |
+
out_dict["prompts"] = prompt
|
667 |
+
|
668 |
+
gen_time = time.time() - start_time
|
669 |
+
logger.info(f"Success, time: {gen_time}")
|
670 |
+
|
671 |
+
return out_dict
|
hyvideo/prompt_rewrite.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
normal_mode_prompt = """Normal mode - Video Recaption Task:
|
2 |
+
|
3 |
+
You are a large language model specialized in rewriting video descriptions. Your task is to modify the input description.
|
4 |
+
|
5 |
+
0. Preserve ALL information, including style words and technical terms.
|
6 |
+
|
7 |
+
1. If the input is in Chinese, translate the entire description to English.
|
8 |
+
|
9 |
+
2. If the input is just one or two words describing an object or person, provide a brief, simple description focusing on basic visual characteristics. Limit the description to 1-2 short sentences.
|
10 |
+
|
11 |
+
3. If the input does not include style, lighting, atmosphere, you can make reasonable associations.
|
12 |
+
|
13 |
+
4. Output ALL must be in English.
|
14 |
+
|
15 |
+
Given Input:
|
16 |
+
input: "{input}"
|
17 |
+
"""
|
18 |
+
|
19 |
+
|
20 |
+
master_mode_prompt = """Master mode - Video Recaption Task:
|
21 |
+
|
22 |
+
You are a large language model specialized in rewriting video descriptions. Your task is to modify the input description.
|
23 |
+
|
24 |
+
0. Preserve ALL information, including style words and technical terms.
|
25 |
+
|
26 |
+
1. If the input is in Chinese, translate the entire description to English.
|
27 |
+
|
28 |
+
2. If the input is just one or two words describing an object or person, provide a brief, simple description focusing on basic visual characteristics. Limit the description to 1-2 short sentences.
|
29 |
+
|
30 |
+
3. If the input does not include style, lighting, atmosphere, you can make reasonable associations.
|
31 |
+
|
32 |
+
4. Output ALL must be in English.
|
33 |
+
|
34 |
+
Given Input:
|
35 |
+
input: "{input}"
|
36 |
+
"""
|
37 |
+
|
38 |
+
def get_rewrite_prompt(ori_prompt, mode="Normal"):
|
39 |
+
if mode == "Normal":
|
40 |
+
prompt = normal_mode_prompt.format(input=ori_prompt)
|
41 |
+
elif mode == "Master":
|
42 |
+
prompt = master_mode_prompt.format(input=ori_prompt)
|
43 |
+
else:
|
44 |
+
raise Exception("Only supports Normal and Normal", mode)
|
45 |
+
return prompt
|
46 |
+
|
47 |
+
ori_prompt = "一只小狗在草地上奔跑。"
|
48 |
+
normal_prompt = get_rewrite_prompt(ori_prompt, mode="Normal")
|
49 |
+
master_prompt = get_rewrite_prompt(ori_prompt, mode="Master")
|
50 |
+
|
51 |
+
# Then you can use the normal_prompt or master_prompt to access the hunyuan-large rewrite model to get the final prompt.
|