HunyuanVideo: A Systematic Framework For Large Video Generation Model
leverage parallelization powered by xDiT
Xibo Sunbb71cfe95941
diff --git a/README.md b/README.mdindex 501a5c9..b4bd7e6 100644--- a/README.md+++ b/README.md@@ -10,15 +10,28 @@ Follow the [instruction](https://github.com/Tencent/HunyuanVideo?tab=readme-ov-f## Install+Single GPU:+```bashconda install pytorch==2.5.0 torchvision==0.20.0 torchaudio==2.5.0 pytorch-cuda=11.8 -c pytorch -c nvidiapip install -r requirements.txt```-## Usage+Multiple GPUs:```bash-bash run.sh+cd HunyuanVideo++torchrun --nproc_per_node=8 sample_video_parallel.py \+ --video-size 1280 720 \+ --video-length 129 \+ --infer-steps 50 \+ --prompt "A cat walks on the grass, realistic style." \+ --flow-reverse \+ --seed 42 \+ --ulysses_degree 8 \+ --ring_degree 1 \+ --save-path ./results```## BibTeXdiff --git a/README_zh.md b/README_zh.mdindex ad06e45..ec4ef2d 100644--- a/README_zh.md+++ b/README_zh.md@@ -241,13 +241,15 @@ python3 sample_video.py \```bashcd HunyuanVideo-torchrun --nproc_per_node=3 sample_video_parallel.py \- --video-size 720 1280 \+torchrun --nproc_per_node=8 sample_video_parallel.py \+ --video-size 1280 720 \--video-length 129 \--infer-steps 50 \--prompt "A cat walks on the grass, realistic style." \--flow-reverse \- --use-cpu-offload \+ --seed 42 \+ --ulysses_degree 8 \+ --ring_degree 1 \--save-path ./results```diff --git a/hyvideo/config.py b/hyvideo/config.pyindex 2fd2964..d650ac7 100644--- a/hyvideo/config.py+++ b/hyvideo/config.py@@ -11,6 +11,7 @@ def parse_args(namespace=None):parser = add_extra_models_args(parser)parser = add_denoise_schedule_args(parser)parser = add_inference_args(parser)+ parser = add_parallel_args(parser)args = parser.parse_args(namespace=namespace)args = sanity_check_args(args)@@ -354,6 +355,26 @@ def add_inference_args(parser: argparse.ArgumentParser):return parser+def add_parallel_args(parser: argparse.ArgumentParser):+ group = parser.add_argument_group(title="Parallel args")++ # ======================== Model loads ========================+ group.add_argument(+ "--ulysses-degree",+ type=int,+ default=1,+ help="Ulysses degree.",+ )+ group.add_argument(+ "--ring-degree",+ type=int,+ default=1,+ help="Ulysses degree.",+ )++ return parser++def sanity_check_args(args):# VAE channelsvae_pattern = r"\d{2,3}-\d{1,2}c-\w+"diff --git a/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py b/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.pyindex ff83c67..c129316 100644--- a/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py+++ b/hyvideo/diffusion/pipelines/pipeline_hunyuan_video.py@@ -19,6 +19,7 @@import inspectfrom typing import Any, Callable, Dict, List, Optional, Union, Tupleimport torch+import torch.distributed as distimport numpy as npfrom dataclasses import dataclassfrom packaging import version@@ -834,7 +835,7 @@ class HunyuanVideoPipeline(DiffusionPipeline):else:batch_size = prompt_embeds.shape[0]- device = self._execution_device+ device = torch.device(f"cuda:{dist.get_rank()}") if dist.is_initialized() else self._execution_device# 3. Encode input promptlora_scale = (diff --git a/hyvideo/inference.py b/hyvideo/inference.pyindex 1d291f3..8f57a9c 100644--- a/hyvideo/inference.py+++ b/hyvideo/inference.py@@ -1,10 +1,13 @@import timeimport random+import functools+from typing import List, Optional, Tuple, Unionfrom pathlib import Pathfrom loguru import loggerimport torch+import torch.distributed as distfrom hyvideo.constants import PROMPT_TEMPLATE, NEGATIVE_PROMPT, PRECISION_TO_TYPEfrom hyvideo.vae import load_vaefrom hyvideo.modules import load_model@@ -14,6 +17,81 @@ from hyvideo.modules.posemb_layers import get_nd_rotary_pos_embedfrom hyvideo.diffusion.schedulers import FlowMatchDiscreteSchedulerfrom hyvideo.diffusion.pipelines import HunyuanVideoPipeline+try:+ import xfuser+ from xfuser.core.distributed import (+ get_sequence_parallel_world_size,+ get_sequence_parallel_rank,+ get_sp_group,+ initialize_model_parallel,+ init_distributed_environment+ )+except:+ xfuser = None+ get_sequence_parallel_world_size = None+ get_sequence_parallel_rank = None+ get_sp_group = None+ initialize_model_parallel = None+ init_distributed_environment = None+++def parallelize_transformer(pipe):+ transformer = pipe.transformer+ original_forward = transformer.forward++ @functools.wraps(transformer.__class__.forward)+ def new_forward(+ self,+ x: torch.Tensor,+ t: torch.Tensor, # Should be in range(0, 1000).+ text_states: torch.Tensor = None,+ text_mask: torch.Tensor = None, # Now we don't use it.+ text_states_2: Optional[torch.Tensor] = None, # Text embedding for modulation.+ freqs_cos: Optional[torch.Tensor] = None,+ freqs_sin: Optional[torch.Tensor] = None,+ guidance: torch.Tensor = None, # Guidance for modulation, should be cfg_scale x 1000.+ return_dict: bool = True,+ ):+ temporal_size = x.shape[2]+ x = torch.chunk(x, get_sequence_parallel_world_size(),dim=-2)[get_sequence_parallel_rank()]+ #text_states = torch.chunk(text_states, get_sequence_parallel_world_size(),dim=-2)[get_sequence_parallel_rank()]+ #text_mask = torch.chunk(text_mask, get_sequence_parallel_world_size(),dim=-1)[get_sequence_parallel_rank()]++ dim_thw = freqs_cos.shape[-1]+ freqs_cos = freqs_cos.reshape(temporal_size, -1, dim_thw)+ freqs_cos = torch.chunk(freqs_cos, get_sequence_parallel_world_size(),dim=-2)[get_sequence_parallel_rank()]+ freqs_cos = freqs_cos.reshape(-1, dim_thw)+ dim_thw = freqs_sin.shape[-1]+ freqs_sin = freqs_sin.reshape(temporal_size, -1, dim_thw)+ freqs_sin = torch.chunk(freqs_sin, get_sequence_parallel_world_size(),dim=-2)[get_sequence_parallel_rank()]+ freqs_sin = freqs_sin.reshape(-1, dim_thw)++ from xfuser.core.long_ctx_attention import xFuserLongContextAttention++ for block in [transformer.double_blocks + transformer.single_blocks]:+ block.hybrid_seq_parallel_attn = xFuserLongContextAttention()++ output = original_forward(+ x,+ t,+ text_states,+ text_mask,+ text_states_2,+ freqs_cos,+ freqs_sin,+ guidance,+ return_dict,+ )++ return_dict = not isinstance(output, tuple)+ sample = output["x"]+ sample = get_sp_group().all_gather(sample, dim=-2)+ output["x"] = sample+ return output++ new_forward = new_forward.__get__(transformer)+ transformer.forward = new_forward+class Inference(object):def __init__(@@ -28,6 +106,7 @@ class Inference(object):use_cpu_offload=False,device=None,logger=None,+ parallel_args=None,):self.vae = vaeself.vae_kwargs = vae_kwargs@@ -48,6 +127,7 @@ class Inference(object):else "cpu")self.logger = logger+ self.parallel_args = parallel_args@classmethoddef from_pretrained(cls, pretrained_model_path, args, device=None, **kwargs):@@ -61,12 +141,37 @@ class Inference(object):"""# ========================================================================logger.info(f"Got text-to-video model root path: {pretrained_model_path}")++ # ==================== Initialize Distributed Environment ================+ if args.ulysses_degree > 1 or args.ring_degree > 1:+ assert xfuser is not None, \+ "Ulysses Attention and Ring Attention requires xfuser package."++ assert args.use_cpu_offload is False, \+ "Cannot enable use_cpu_offload in the distributed environment."++ dist.init_process_group("nccl")++ assert dist.get_world_size() == args.ring_degree * args.ulysses_degree, \+ "number of GPUs should be equal to ring_degree * ulysses_degree."++ init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())++ initialize_model_parallel(+ sequence_parallel_degree=dist.get_world_size(),+ ring_degree=args.ring_degree,+ ulysses_degree=args.ulysses_degree,+ )+ device = torch.device(f"cuda:{dist.get_rank()}")+ else:+ if device is None:+ device = "cuda" if torch.cuda.is_available() else "cpu"++ parallel_args = {"ulysses_degree": args.ulysses_degree, "ring_degree": args.ring_degree}# ======================== Get the args path =============================- # Set device and disable gradient- if device is None:- device = "cuda" if torch.cuda.is_available() else "cpu"+ # Disable gradienttorch.set_grad_enabled(False)# =========================== Build main model ===========================@@ -155,6 +260,7 @@ class Inference(object):use_cpu_offload=args.use_cpu_offload,device=device,logger=logger,+ parallel_args=parallel_args)@staticmethod@@ -260,6 +366,7 @@ class HunyuanVideoSampler(Inference):use_cpu_offload=False,device=0,logger=None,+ parallel_args=None):super().__init__(args,@@ -272,6 +379,7 @@ class HunyuanVideoSampler(Inference):use_cpu_offload=use_cpu_offload,device=device,logger=logger,+ parallel_args=parallel_args)self.pipeline = self.load_diffusion_pipeline(@@ -403,6 +511,12 @@ class HunyuanVideoSampler(Inference):num_images_per_prompt (int): The number of images per prompt. Default is 1.infer_steps (int): The number of inference steps. Default is 100."""+ if self.parallel_args['ulysses_degree'] > 1 or self.parallel_args['ring_degree'] > 1:+ assert seed is not None, \+ "You have to set a seed in the distributed environment, please rerun with --seed <your-seed>."++ parallelize_transformer(self.pipeline)+out_dict = dict()# ========================================================================diff --git a/hyvideo/modules/models.py b/hyvideo/modules/models.pyindex ab4c251..2e0c969 100644--- a/hyvideo/modules/models.py+++ b/hyvideo/modules/models.py@@ -17,7 +17,10 @@ from .mlp_layers import MLP, MLPEmbedder, FinalLayerfrom .modulate_layers import ModulateDiT, modulate, apply_gatefrom .token_refiner import SingleTokenRefiner-from xfuser.core.long_ctx_attention import xFuserLongContextAttention+try:+ from flash_attn.flash_attn_interface import _flash_attn_forward+except:+ _flash_attn_forward = Noneclass MMDoubleStreamBlock(nn.Module):@@ -123,7 +126,7 @@ class MMDoubleStreamBlock(nn.Module):bias=True,**factory_kwargs,)- self.hybrid_seq_parallel_attn = xFuserLongContextAttention()+ self.hybrid_seq_parallel_attn = Nonedef enable_deterministic(self):self.deterministic = True@@ -202,30 +205,46 @@ class MMDoubleStreamBlock(nn.Module):), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"# attention computation start- #attn = attention(- # q,- # k,- # v,- # cu_seqlens_q=cu_seqlens_q,- # cu_seqlens_kv=cu_seqlens_kv,- # max_seqlen_q=max_seqlen_q,- # max_seqlen_kv=max_seqlen_kv,- # batch_size=img_k.shape[0],- #)- attn = self.hybrid_seq_parallel_attn(- None,- img_q,- img_k,- img_v,- dropout_p=0.0,- causal=False,- joint_tensor_query=txt_q,- joint_tensor_key=txt_k,- joint_tensor_value=txt_v,- joint_strategy="rear",- )- b, s, a, d = attn.shape- attn = attn.reshape(b, s, -1)+ if not self.hybrid_seq_parallel_attn:+ attn = attention(+ q,+ k,+ v,+ cu_seqlens_q=cu_seqlens_q,+ cu_seqlens_kv=cu_seqlens_kv,+ max_seqlen_q=max_seqlen_q,+ max_seqlen_kv=max_seqlen_kv,+ batch_size=img_k.shape[0],+ )+ else:+ attn1 = self.hybrid_seq_parallel_attn(+ None,+ img_q,+ img_k,+ img_v,+ dropout_p=0.0,+ causal=False,+ joint_tensor_query=txt_q[:,:cu_seqlens_q[1] - img_q.shape[1]],+ joint_tensor_key=txt_k[:,:cu_seqlens_kv[1] - img_k.shape[1]],+ joint_tensor_value=txt_v[:,:cu_seqlens_kv[1] - img_v.shape[1]],+ joint_strategy="rear",+ )+ attn2, *_ = _flash_attn_forward(+ txt_q[:,cu_seqlens_q[1] - img_q.shape[1]:],+ txt_k[:,cu_seqlens_kv[1] - img_k.shape[1]:],+ txt_v[:,cu_seqlens_kv[1] - img_v.shape[1]:],+ dropout_p=0.0,+ softmax_scale=txt_q.shape[-1] ** (-0.5),+ causal=False,+ window_size_left=-1,+ window_size_right=-1,+ softcap=0.0,+ alibi_slopes=None,+ return_softmax=False,+ )+ attn = torch.cat([attn1, attn2], dim=1)+ b, s, a, d = attn.shape+ attn = attn.reshape(b, s, -1)# attention computation endimg_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]@@ -318,7 +337,7 @@ class MMSingleStreamBlock(nn.Module):act_layer=get_activation_layer("silu"),**factory_kwargs,)- self.hybrid_seq_parallel_attn = xFuserLongContextAttention()+ self.hybrid_seq_parallel_attn = Nonedef enable_deterministic(self):self.deterministic = True@@ -367,30 +386,46 @@ class MMSingleStreamBlock(nn.Module):), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"# attention computation start- #attn = attention(- # q,- # k,- # v,- # cu_seqlens_q=cu_seqlens_q,- # cu_seqlens_kv=cu_seqlens_kv,- # max_seqlen_q=max_seqlen_q,- # max_seqlen_kv=max_seqlen_kv,- # batch_size=x.shape[0],- #)- attn = self.hybrid_seq_parallel_attn(- None,- q[:, :-txt_len, :, :],- k[:, :-txt_len, :, :],- v[:, :-txt_len, :, :],- dropout_p=0.0,- causal=False,- joint_tensor_query=q[:, -txt_len:, :, :],- joint_tensor_key=k[:, -txt_len:, :, :],- joint_tensor_value=v[:, -txt_len:, :, :],- joint_strategy="rear",- )- b, s, a, d = attn.shape- attn = attn.reshape(b, s, -1)+ if not self.hybrid_seq_parallel_attn:+ attn = attention(+ q,+ k,+ v,+ cu_seqlens_q=cu_seqlens_q,+ cu_seqlens_kv=cu_seqlens_kv,+ max_seqlen_q=max_seqlen_q,+ max_seqlen_kv=max_seqlen_kv,+ batch_size=x.shape[0],+ )+ else:+ attn1 = self.hybrid_seq_parallel_attn(+ None,+ q[:, :-txt_len, :, :],+ k[:, :-txt_len, :, :],+ v[:, :-txt_len, :, :],+ dropout_p=0.0,+ causal=False,+ joint_tensor_query=q[:, -txt_len:cu_seqlens_q[1], :, :],+ joint_tensor_key=k[:, -txt_len:cu_seqlens_kv[1], :, :],+ joint_tensor_value=v[:, -txt_len:cu_seqlens_kv[1], :, :],+ joint_strategy="rear",+ )+ attn2, *_ = _flash_attn_forward(+ q[:,cu_seqlens_q[1]:],+ k[:,cu_seqlens_kv[1]:],+ v[:,cu_seqlens_kv[1]:],+ dropout_p=0.0,+ softmax_scale=txt_q.shape[-1] ** (-0.5),+ causal=False,+ window_size_left=-1,+ window_size_right=-1,+ softcap=0.0,+ alibi_slopes=None,+ return_softmax=False,+ )+ attn = torch.cat([attn1, attn2], dim=1)+ b, s, a, d = attn.shape+ attn = attn.reshape(b, s, -1)# attention computation end# Compute activation in mlp stream, cat again and run second linear layer.