Fabrice-TIERCELIN commited on
Commit
0b2a02e
·
verified ·
1 Parent(s): d2722cf

reverse=True,

Browse files
Files changed (1) hide show
  1. hyvideo/inference.py +672 -671
hyvideo/inference.py CHANGED
@@ -1,671 +1,672 @@
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
 
 
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
+ reverse=True,
430
+ solver=args.flow_solver,
431
+ )
432
+ else:
433
+ raise ValueError(f"Invalid denoise type {args.denoise_type}")
434
+
435
+ pipeline = HunyuanVideoPipeline(
436
+ vae=vae,
437
+ text_encoder=text_encoder,
438
+ text_encoder_2=text_encoder_2,
439
+ transformer=model,
440
+ scheduler=scheduler,
441
+ progress_bar_config=progress_bar_config,
442
+ args=args,
443
+ )
444
+ if self.use_cpu_offload:
445
+ pipeline.enable_sequential_cpu_offload()
446
+ else:
447
+ pipeline = pipeline.to(device)
448
+
449
+ return pipeline
450
+
451
+ def get_rotary_pos_embed(self, video_length, height, width):
452
+ target_ndim = 3
453
+ ndim = 5 - 2
454
+ # 884
455
+ if "884" in self.args.vae:
456
+ latents_size = [(video_length - 1) // 4 + 1, height // 8, width // 8]
457
+ elif "888" in self.args.vae:
458
+ latents_size = [(video_length - 1) // 8 + 1, height // 8, width // 8]
459
+ else:
460
+ latents_size = [video_length, height // 8, width // 8]
461
+
462
+ if isinstance(self.model.patch_size, int):
463
+ assert all(s % self.model.patch_size == 0 for s in latents_size), (
464
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
465
+ f"but got {latents_size}."
466
+ )
467
+ rope_sizes = [s // self.model.patch_size for s in latents_size]
468
+ elif isinstance(self.model.patch_size, list):
469
+ assert all(
470
+ s % self.model.patch_size[idx] == 0
471
+ for idx, s in enumerate(latents_size)
472
+ ), (
473
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.model.patch_size}), "
474
+ f"but got {latents_size}."
475
+ )
476
+ rope_sizes = [
477
+ s // self.model.patch_size[idx] for idx, s in enumerate(latents_size)
478
+ ]
479
+
480
+ if len(rope_sizes) != target_ndim:
481
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
482
+ head_dim = self.model.hidden_size // self.model.heads_num
483
+ rope_dim_list = self.model.rope_dim_list
484
+ if rope_dim_list is None:
485
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
486
+ assert (
487
+ sum(rope_dim_list) == head_dim
488
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
489
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
490
+ rope_dim_list,
491
+ rope_sizes,
492
+ theta=self.args.rope_theta,
493
+ use_real=True,
494
+ theta_rescale_factor=1,
495
+ )
496
+ return freqs_cos, freqs_sin
497
+
498
+ @torch.no_grad()
499
+ def predict(
500
+ self,
501
+ prompt,
502
+ height=192,
503
+ width=336,
504
+ video_length=129,
505
+ seed=None,
506
+ negative_prompt=None,
507
+ infer_steps=50,
508
+ guidance_scale=6,
509
+ flow_shift=5.0,
510
+ embedded_guidance_scale=None,
511
+ batch_size=1,
512
+ num_videos_per_prompt=1,
513
+ **kwargs,
514
+ ):
515
+ """
516
+ Predict the image/video from the given text.
517
+
518
+ Args:
519
+ prompt (str or List[str]): The input text.
520
+ kwargs:
521
+ height (int): The height of the output video. Default is 192.
522
+ width (int): The width of the output video. Default is 336.
523
+ video_length (int): The frame number of the output video. Default is 129.
524
+ seed (int or List[str]): The random seed for the generation. Default is a random integer.
525
+ negative_prompt (str or List[str]): The negative text prompt. Default is an empty string.
526
+ guidance_scale (float): The guidance scale for the generation. Default is 6.0.
527
+ num_images_per_prompt (int): The number of images per prompt. Default is 1.
528
+ infer_steps (int): The number of inference steps. Default is 100.
529
+ """
530
+ out_dict = dict()
531
+
532
+ # ========================================================================
533
+ # Arguments: seed
534
+ # ========================================================================
535
+ if isinstance(seed, torch.Tensor):
536
+ seed = seed.tolist()
537
+ if seed is None:
538
+ seeds = [
539
+ random.randint(0, 1_000_000)
540
+ for _ in range(batch_size * num_videos_per_prompt)
541
+ ]
542
+ elif isinstance(seed, int):
543
+ seeds = [
544
+ seed + i
545
+ for _ in range(batch_size)
546
+ for i in range(num_videos_per_prompt)
547
+ ]
548
+ elif isinstance(seed, (list, tuple)):
549
+ if len(seed) == batch_size:
550
+ seeds = [
551
+ int(seed[i]) + j
552
+ for i in range(batch_size)
553
+ for j in range(num_videos_per_prompt)
554
+ ]
555
+ elif len(seed) == batch_size * num_videos_per_prompt:
556
+ seeds = [int(s) for s in seed]
557
+ else:
558
+ raise ValueError(
559
+ f"Length of seed must be equal to number of prompt(batch_size) or "
560
+ f"batch_size * num_videos_per_prompt ({batch_size} * {num_videos_per_prompt}), got {seed}."
561
+ )
562
+ else:
563
+ raise ValueError(
564
+ f"Seed must be an integer, a list of integers, or None, got {seed}."
565
+ )
566
+ generator = [torch.Generator(self.device).manual_seed(seed) for seed in seeds]
567
+ out_dict["seeds"] = seeds
568
+
569
+ # ========================================================================
570
+ # Arguments: target_width, target_height, target_video_length
571
+ # ========================================================================
572
+ if width <= 0 or height <= 0 or video_length <= 0:
573
+ raise ValueError(
574
+ f"`height` and `width` and `video_length` must be positive integers, got height={height}, width={width}, video_length={video_length}"
575
+ )
576
+ if (video_length - 1) % 4 != 0:
577
+ raise ValueError(
578
+ f"`video_length-1` must be a multiple of 4, got {video_length}"
579
+ )
580
+
581
+ logger.info(
582
+ f"Input (height, width, video_length) = ({height}, {width}, {video_length})"
583
+ )
584
+
585
+ target_height = align_to(height, 16)
586
+ target_width = align_to(width, 16)
587
+ target_video_length = video_length
588
+
589
+ out_dict["size"] = (target_height, target_width, target_video_length)
590
+
591
+ # ========================================================================
592
+ # Arguments: prompt, new_prompt, negative_prompt
593
+ # ========================================================================
594
+ if not isinstance(prompt, str):
595
+ raise TypeError(f"`prompt` must be a string, but got {type(prompt)}")
596
+ prompt = [prompt.strip()]
597
+
598
+ # negative prompt
599
+ if negative_prompt is None or negative_prompt == "":
600
+ negative_prompt = self.default_negative_prompt
601
+ if not isinstance(negative_prompt, str):
602
+ raise TypeError(
603
+ f"`negative_prompt` must be a string, but got {type(negative_prompt)}"
604
+ )
605
+ negative_prompt = [negative_prompt.strip()]
606
+
607
+ # ========================================================================
608
+ # Scheduler
609
+ # ========================================================================
610
+ scheduler = FlowMatchDiscreteScheduler(
611
+ shift=flow_shift,
612
+ reverse=self.args.flow_reverse,
613
+ solver=self.args.flow_solver
614
+ )
615
+ self.pipeline.scheduler = scheduler
616
+
617
+ # ========================================================================
618
+ # Build Rope freqs
619
+ # ========================================================================
620
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(
621
+ target_video_length, target_height, target_width
622
+ )
623
+ n_tokens = freqs_cos.shape[0]
624
+
625
+ # ========================================================================
626
+ # Print infer args
627
+ # ========================================================================
628
+ debug_str = f"""
629
+ height: {target_height}
630
+ width: {target_width}
631
+ video_length: {target_video_length}
632
+ prompt: {prompt}
633
+ neg_prompt: {negative_prompt}
634
+ seed: {seed}
635
+ infer_steps: {infer_steps}
636
+ num_videos_per_prompt: {num_videos_per_prompt}
637
+ guidance_scale: {guidance_scale}
638
+ n_tokens: {n_tokens}
639
+ flow_shift: {flow_shift}
640
+ embedded_guidance_scale: {embedded_guidance_scale}"""
641
+ logger.debug(debug_str)
642
+
643
+ # ========================================================================
644
+ # Pipeline inference
645
+ # ========================================================================
646
+ start_time = time.time()
647
+ samples = self.pipeline(
648
+ prompt=prompt,
649
+ height=target_height,
650
+ width=target_width,
651
+ video_length=target_video_length,
652
+ num_inference_steps=infer_steps,
653
+ guidance_scale=guidance_scale,
654
+ negative_prompt=negative_prompt,
655
+ num_videos_per_prompt=num_videos_per_prompt,
656
+ generator=generator,
657
+ output_type="pil",
658
+ freqs_cis=(freqs_cos, freqs_sin),
659
+ n_tokens=n_tokens,
660
+ embedded_guidance_scale=embedded_guidance_scale,
661
+ data_type="video" if target_video_length > 1 else "image",
662
+ is_progress_bar=True,
663
+ vae_ver=self.args.vae,
664
+ enable_tiling=self.args.vae_tiling,
665
+ )[0]
666
+ out_dict["samples"] = samples
667
+ out_dict["prompts"] = prompt
668
+
669
+ gen_time = time.time() - start_time
670
+ logger.info(f"Success, time: {gen_time}")
671
+
672
+ return out_dict