Spaces:
Runtime error
Runtime error
reverse=True,
Browse files- 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[
|
| 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 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
f"
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
f"
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
#
|
| 533 |
-
#
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
for
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
for
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
f"
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
#
|
| 570 |
-
#
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
#
|
| 592 |
-
#
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
#
|
| 608 |
-
#
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
#
|
| 618 |
-
#
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
#
|
| 626 |
-
#
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
#
|
| 644 |
-
#
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
out_dict["
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 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 |
+
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
|