Diffusers documentation

HunyuanVideo

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

LoRA

HunyuanVideo

HunyuanVideo 是一个 13B 参数的扩散 Transformer 模型,旨在与闭源视频基础模型相竞争,并让更广泛的社区能够使用。该模型采用“双流到单流”架构,首先分别处理视频和文本 token,然后将其拼接并输入 Transformer,以融合多模态信息。由于预训练的多模态大语言模型(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,
    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,
        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
    transformer 数据类型torch.bfloat16
    vae 数据类型torch.float16
    num_frames (k)4 * k + 1
  • 对于低分辨率视频,尝试使用较低的 shift 值(2.0 到 5.0);对于高分辨率图像,则使用较高的 shift 值(7.0 到 12.0)。

HunyuanVideoPipeline

类 diffusers.HunyuanVideoPipeline

< >

( text_encoder: LlamaModeltokenizer: LlamaTokenizertransformer: HunyuanVideoTransformer3DModelvae: AutoencoderKLHunyuanVideoscheduler: FlowMatchEulerDiscreteSchedulertext_encoder_2: CLIPTextModeltokenizer_2: CLIPTokenizer )

参数

用于使用 HunyuanVideo 进行文本到视频生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关为所有 pipeline 实现的通用方法(下载、保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] = Nonenegative_prompt: str | list[str] = Nonenegative_prompt_2: str | list[str] = Noneheight: int = 720width: int = 1280num_frames: int = 129num_inference_steps: int = 50sigmas: list[float] = Nonetrue_cfg_scale: float = 1.0guidance_scale: float = 6.0num_videos_per_prompt: int | None = 1generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneprompt_attention_mask: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_attention_mask: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']prompt_template: 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 ) → ~HunyuanVideoPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • prompt_2 (str 或 list[str],可选) — 要发送给 tokenizer_2 和 text_encoder_2 的提示词。如果未定义,则使用 prompt。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。当不使用引导时会被忽略(即当 true_cfg_scale 不大于 1 时会被忽略)。
  • negative_prompt_2 (str 或 list[str],可选) — 用于引导图像生成的负面提示词,将发送给 tokenizer_2 和 text_encoder_2。如果未定义,则所有文本编码器都会使用 negative_prompt。
  • height (int,默认为 720) — 生成图像的高度(以像素为单位)。
  • width (int,默认为 1280) — 生成图像的宽度(以像素为单位)。
  • num_frames (int,默认为 129) — 生成视频的帧数。
  • num_inference_steps (int,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但推理速度会变慢。
  • sigmas (list[float],可选) — 用于在支持 sigmas 参数的调度器的 set_timesteps 方法中,为去噪过程指定自定义的 sigmas。如果未定义,则使用传入 num_inference_steps 时的默认行为。
  • true_cfg_scale(float,可选,默认值为 1.0)— 当 true_cfg_scale > 1 且提供了 negative_prompt 时,将启用真正的无分类器引导(guidance scale)。
  • guidance_scale (float, 默认值为 6.0) — 通过设置 guidance_scale > 1. 更高的 guidance_scale 会促使模型生成与 prompt 更一致的图片,但会降低图片质量。

    Guidance-distilled 模型近似了 guidance_scale > 1 时的真实 classifier-free guidance。有关详细信息,请参阅 论文。

  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的图像数量。
  • generator (torch.Generator 或 list[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_embeds 将根据 negative_prompt 输入参数生成。
  • negative_pooled_prompt_embeds (torch.FloatTensor,可选) — 预生成的负向池化文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,将从 negative_prompt 输入参数生成池化的 negative_prompt_embeds。
  • prompt_attention_mask (torch.Tensor, 可选) — prompt_embeds 的注意力掩码。当直接传入 prompt_embeds 时,此参数为必填项。
  • negative_prompt_attention_mask (torch.Tensor, 可选) — negative_prompt_embeds 的注意力掩码。当直接传入 negative_prompt_embeds 时,此参数为必填项。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选 PIL.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 HunyuanVideoPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.processor 下定义。
  • prompt_template (dict, 可选) — 用于在编码前格式化提示词的模板。默认使用模型的默认模板。
  • max_sequence_length (int,可选,默认为 256) — 用于提示编码器的最大序列长度。
  • callback_on_step_end (Callable、PipelineCallback、MultiPipelineCallbacks、可选) — 在推理过程中,每个去噪步骤结束时调用的函数,或 PipelineCallback 或 MultiPipelineCallbacks 的子类,其参数如下: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 属性中列出的变量。

返回值

~HunyuanVideoPipelineOutput 或 tuple

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

用于生成的 pipeline 的调用函数。

示例:

>>> 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)

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 管道的输出类。

Update on GitHub