Diffusers 文档

混元视频(HunyuanVideo)

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LoRA

混元视频(HunyuanVideo)

混元视频(HunyuanVideo)是一个130亿参数的扩散变换器模型,旨在与闭源视频基础模型竞争,并为更广泛的社区提供访问权限。该模型采用“双流到单流”架构,首先独立处理视频和文本标记,然后将它们连接起来并送入变换器以融合多模态信息。预训练的多模态大型语言模型(MLLM)被用作编码器,因为它具有更好的图像-文本对齐、更好的图像细节描述和推理能力,并且如果将系统指令添加到用户提示中,它可以用作零样本学习器。最后,混元视频(HunyuanVideo)使用3D因果变分自编码器以更高的效率处理原始分辨率和帧率的视频数据。

您可以在腾讯(Tencent)组织下找到所有原始的混元视频(HunyuanVideo)检查点。

点击右侧边栏的混元视频(HunyuanVideo)模型,查看更多视频生成任务示例。

以下示例使用hunyuanvideo-community的检查点,因为其权重以兼容 Diffusers 的布局存储。

以下示例演示了如何生成针对内存或推理速度进行优化的视频。

内存
推理速度

有关各种内存节省技术的更多详细信息,请参阅减少内存使用指南。

以下量化后的混元视频(HunyuanVideo)模型需要约 14GB 显存。

import torch
from diffusers import AutoModel, HunyuanVideoPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.utils import export_to_video

# quantize weights to int4 with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
    quant_backend="bitsandbytes_4bit",
    quant_kwargs={
      "load_in_4bit": True,
      "bnb_4bit_quant_type": "nf4",
      "bnb_4bit_compute_dtype": torch.bfloat16
      },
    components_to_quantize=["transformer"]
)

pipeline = HunyuanVideoPipeline.from_pretrained(
    "hunyuanvideo-community/HunyuanVideo",
    quantization_config=pipeline_quant_config,
    torch_dtype=torch.bfloat16,
)

# model-offloading and tiling
pipeline.enable_model_cpu_offload()
pipeline.vae.enable_tiling()

prompt = "A fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys."
video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
export_to_video(video, "output.mp4", fps=15)

注意事项

  • 混元视频(HunyuanVideo)支持使用 load_lora_weights() 加载 LoRA。

    显示示例代码
    import torch
    from diffusers import AutoModel, HunyuanVideoPipeline
    from diffusers.quantizers import PipelineQuantizationConfig
    from diffusers.utils import export_to_video
    
    # quantize weights to int4 with bitsandbytes
    pipeline_quant_config = PipelineQuantizationConfig(
        quant_backend="bitsandbytes_4bit",
        quant_kwargs={
          "load_in_4bit": True,
          "bnb_4bit_quant_type": "nf4",
          "bnb_4bit_compute_dtype": torch.bfloat16
          },
        components_to_quantize=["transformer"]
    )
    
    pipeline = HunyuanVideoPipeline.from_pretrained(
        "hunyuanvideo-community/HunyuanVideo",
        quantization_config=pipeline_quant_config,
        torch_dtype=torch.bfloat16,
    )
    
    # load LoRA weights
    pipeline.load_lora_weights("https://huggingface.co/lucataco/hunyuan-steamboat-willie-10", adapter_name="steamboat-willie")
    pipeline.set_adapters("steamboat-willie", 0.9)
    
    # model-offloading and tiling
    pipeline.enable_model_cpu_offload()
    pipeline.vae.enable_tiling()
    
    # use "In the style of SWR" to trigger the LoRA
    prompt = """
    In the style of SWR. A black and white animated scene featuring a fluffy teddy bear sits on a bed of soft pillows surrounded by children's toys.
    """
    video = pipeline(prompt=prompt, num_frames=61, num_inference_steps=30).frames[0]
    export_to_video(video, "output.mp4", fps=15)
  • 推荐的推理值请参考下表。

    参数 推荐值
    文本编码器数据类型 torch.float16
    变换器数据类型 torch.bfloat16
    VAE 数据类型 torch.float16
    帧数 (k) 4 * `k` + 1
  • 对于较低分辨率的视频,请尝试较低的 `shift` 值(`2.0` 到 `5.0`);对于较高分辨率的图像,请尝试较高的 `shift` 值(`7.0` 到 `12.0`)。

HunyuanVideoPipeline

diffusers.HunyuanVideoPipeline

< >

( text_encoder: LlamaModel tokenizer: LlamaTokenizerFast transformer: HunyuanVideoTransformer3DModel vae: AutoencoderKLHunyuanVideo scheduler: FlowMatchEulerDiscreteScheduler text_encoder_2: CLIPTextModel tokenizer_2: CLIPTokenizer )

参数

用于使用混元视频(HunyuanVideo)进行文本到视频生成的管道。

此模型继承自DiffusionPipeline。有关所有管道实现的通用方法(下载、保存、在特定设备上运行等),请查看父类文档。

__call__

< >

( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str]] = None negative_prompt: typing.Union[str, typing.List[str]] = None negative_prompt_2: typing.Union[str, typing.List[str]] = None height: int = 720 width: int = 1280 num_frames: int = 129 num_inference_steps: int = 50 sigmas: typing.List[float] = None true_cfg_scale: float = 1.0 guidance_scale: float = 6.0 num_videos_per_prompt: typing.Optional[int] = 1 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None prompt_attention_mask: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_attention_mask: typing.Optional[torch.Tensor] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] prompt_template: typing.Dict[str, typing.Any] = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: 1. The main content and theme of the video.2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.4. background environment, light, style and atmosphere.5. camera angles, movements, and transitions used in the video:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95} max_sequence_length: int = 256 ) ~HunyuanVideoPipelineOutputtuple

参数

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传递 prompt_embeds
  • prompt_2 (strList[str], 可选) — 发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,将使用 prompt
  • negative_prompt (strList[str], 可选) — 用于不引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时(即,如果 true_cfg_scale 不大于 1 则忽略),此参数将被忽略。
  • negative_prompt_2 (strList[str], 可选) — 用于不引导图像生成并发送到 tokenizer_2text_encoder_2 的提示或提示列表。如果未定义,则在所有文本编码器中使用 negative_prompt
  • height (int, 默认为 720) — 生成图像的高度(像素)。
  • width (int, 默认为 1280) — 生成图像的宽度(像素)。
  • num_frames (int, 默认为 129) — 生成视频的帧数。
  • num_inference_steps (int, 默认为 50) — 去噪步数。更多的去噪步数通常会带来更高质量的图像,但推理速度会变慢。
  • sigmas (List[float], 可选) — 在调度器的 set_timesteps 方法中支持 sigmas 参数时,用于去噪过程的自定义 sigmas。如果未定义,将使用传递 num_inference_steps 时的默认行为。
  • true_cfg_scale (float, 可选, 默认为 1.0) — 当 > 1.0 且提供了 negative_prompt 时,启用真正的无分类器引导。
  • guidance_scale (float, 默认为 6.0) — Classifier-Free Diffusion Guidance 中定义的引导比例。guidance_scale 定义为 Imagen Paper 方程 2 中的 w。通过设置 guidance_scale > 1 启用引导比例。更高的引导比例有助于生成与文本 prompt 紧密相关的图像,但通常以牺牲图像质量为代价。请注意,唯一可用的 HunyuanVideo 模型是 CFG 蒸馏模型,这意味着不应用无条件和有条件潜在之间的传统引导。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个提示生成的图像数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 用于使生成具有确定性的 torch.Generator
  • latents (torch.Tensor, 可选) — 预先生成的高斯分布采样噪声潜在变量,用作图像生成的输入。可用于使用不同提示调整相同的生成。如果未提供,则使用提供的随机 generator 采样生成潜在变量张量。
  • prompt_embeds (torch.Tensor, 可选) — 预先生成的文本嵌入。可用于轻松调整文本输入(提示权重)。如果未提供,则从 prompt 输入参数生成文本嵌入。
  • pooled_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 prompt 输入参数生成池化文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的负面文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • negative_pooled_prompt_embeds (torch.FloatTensor, 可选) — 预先生成的负面池化文本嵌入。可用于轻松调整文本输入,例如提示权重。如果未提供,将从 negative_prompt 输入参数生成池化 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。选择 PIL.Imagenp.array
  • return_dict (bool, 可选, 默认为 True) — 是否返回 HunyuanVideoPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将作为参数传递给 AttentionProcessor,其定义位于 diffusers.models.attention_processor 中的 self.processor 下。
  • clip_skip (int, 可选) — 在计算提示嵌入时从 CLIP 跳过的层数。值为 1 意味着将使用倒数第二层的输出计算提示嵌入。
  • callback_on_step_end (Callable, PipelineCallback, MultiPipelineCallbacks, 可选) — 一个函数或 PipelineCallbackMultiPipelineCallbacks 的子类,在推理过程中每个去噪步骤结束时调用,并使用以下参数:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)callback_kwargs 将包含 callback_on_step_end_tensor_inputs 指定的所有张量列表。
  • callback_on_step_end_tensor_inputs (List, 可选) — callback_on_step_end 函数的张量输入列表。列表中指定的张量将作为 callback_kwargs 参数传递。您只能包含管道类 ._callback_tensor_inputs 属性中列出的变量。

返回

~HunyuanVideoPipelineOutputtuple

如果 return_dictTrue,则返回 HunyuanVideoPipelineOutput,否则返回一个 tuple,其中第一个元素是生成的图像列表,第二个元素是指示相应生成的图像是否包含“不适合工作”(nsfw) 内容的 bool 列表。

用于生成的管道的调用函数。

示例

>>> import torch
>>> from diffusers import HunyuanVideoPipeline, HunyuanVideoTransformer3DModel
>>> from diffusers.utils import export_to_video

>>> model_id = "hunyuanvideo-community/HunyuanVideo"
>>> transformer = HunyuanVideoTransformer3DModel.from_pretrained(
...     model_id, subfolder="transformer", torch_dtype=torch.bfloat16
... )
>>> pipe = HunyuanVideoPipeline.from_pretrained(model_id, transformer=transformer, torch_dtype=torch.float16)
>>> pipe.vae.enable_tiling()
>>> pipe.to("cuda")

>>> output = pipe(
...     prompt="A cat walks on the grass, realistic",
...     height=320,
...     width=512,
...     num_frames=61,
...     num_inference_steps=30,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=15)

disable_vae_slicing

< >

( )

禁用切片 VAE 解码。如果之前启用了 enable_vae_slicing,此方法将返回一步计算解码。

disable_vae_tiling

< >

( )

禁用平铺 VAE 解码。如果之前启用了 enable_vae_tiling,此方法将恢复一步计算解码。

enable_vae_slicing

< >

( )

启用切片 VAE 解码。启用此选项后,VAE 会将输入张量分片,分步计算解码。这有助于节省一些内存并允许更大的批次大小。

enable_vae_tiling

< >

( )

启用平铺 VAE 解码。启用此选项后,VAE 将把输入张量分割成瓦片,分多步计算编码和解码。这对于节省大量内存和处理更大的图像非常有用。

HunyuanVideoPipelineOutput

class diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput

< >

( frames: Tensor )

参数

  • frames (torch.Tensor, np.ndarray, 或 List[List[PIL.Image.Image]]) — 视频输出列表 - 可以是长度为 batch_size 的嵌套列表,每个子列表包含长度为 num_frames 的去噪 PIL 图像序列。也可以是形状为 (batch_size, num_frames, channels, height, width) 的 NumPy 数组或 Torch 张量。

HunyuanVideo 管道的输出类。

< > 在 GitHub 上更新