#
# 根据 Apache 许可证 2.0 版本（“许可证”）授权
# 您只能在遵守许可证的情况下使用本文件。
# 您可以在以下位置获取许可证副本
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 除非适用法律要求或双方书面同意，软件
# 根据许可证分发，本软件按“原样”
# 不附带任何明示或暗示的保证或条件。
# 请参阅许可证中关于权限的具体语言
# 许可证下的限制。-->

  
    
      
    
  

# HunyuanVideo

[HunyuanVideo](https://huggingface.co/papers/2412.03603) 是一个拥有 130 亿参数的扩散 Transformer 模型，旨在与闭源视频基础模型相竞争，并让更广泛的社区能够使用。该模型采用“双流到单流”架构，首先分别处理视频和文本 token，然后将它们拼接并输入 Transformer，以融合多模态信息。由于预训练的多模态大语言模型（MLLM）具有更好的图文对齐能力、更出色的图像细节描述与推理能力，并且当在用户提示中加入系统指令时可作为零样本学习器使用，因此被用作编码器。最后，HunyuanVideo 使用 3D 因果变分自编码器，以更高的效率在原始分辨率和帧率下处理视频数据。

您可以在 [Tencent](https://huggingface.co/tencent) 组织下找到所有原始的 HunyuanVideo 检查点。

> [!TIP]
> 点击右侧边栏中的 HunyuanVideo 模型，以查看更多视频生成任务的示例。
>
> 以下示例使用 [hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community) 的检查点，因为其权重存储在与 Diffusers 兼容的布局中。

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

有关各种内存节省技术的详细信息，请参阅 [减少内存使用](../../optimization/memory) 指南。

以下量化后的 HunyuanVideo 模型需要约 14GB 的显存。

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

[编译](../../optimization/fp16#torchcompile)在首次执行时较慢，但后续对 pipeline 的调用会更快。

```py
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()

# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
    pipeline.transformer, mode="max-autotune", fullgraph=True
)

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()](/docs/diffusers/v0.43.0/zh/api/loaders/lora#diffusers.loaders.HunyuanVideoLoraLoaderMixin.load_lora_weights) 加载 LoRA。

  
  显示示例代码

  ```py
  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]]

#### diffusers.HunyuanVideoPipeline[[diffusers.HunyuanVideoPipeline]]

```python
diffusers.HunyuanVideoPipeline(text_encoder: LlamaModel, tokenizer: LlamaTokenizer, transformer: HunyuanVideoTransformer3DModel, vae: AutoencoderKLHunyuanVideo, scheduler: FlowMatchEulerDiscreteScheduler, text_encoder_2: CLIPTextModel, tokenizer_2: CLIPTokenizer)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L144)

**参数：**

text_encoder (`LlamaModel`)：[Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers)。

tokenizer (`LlamaTokenizer`)：来自 [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers) 的分词器。

transformer ([HunyuanVideoTransformer3DModel](/docs/diffusers/v0.43.0/zh/api/models/hunyuan_video_transformer_3d#diffusers.HunyuanVideoTransformer3DModel))：用于对编码后的图像潜在变量进行去噪的条件 Transformer。

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/zh/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler))：用于与 `transformer` 配合，对编码后的图像潜变量进行去噪的调度器。

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/zh/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo))：变分自编码器（VAE）模型，用于将视频编码为潜在表示，并从潜在表示解码为视频。

text_encoder_2 (`CLIPTextModel`)：即 [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel)，具体为 [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) 变体。

tokenizer_2 (`CLIPTokenizer`)：[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer) 类的分词器。

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

该模型继承自 [DiffusionPipeline](/docs/diffusers/v0.43.0/zh/api/pipelines/overview#diffusers.DiffusionPipeline)。有关为所有流水线实现的通用方法（下载、保存、在特定设备上运行等），请参阅父类文档。

#### __调用__[[diffusers.HunyuanVideoPipeline.__call__]]

```python
__call__(prompt: str | list[str] = None, prompt_2: str | list[str] = None, negative_prompt: str | list[str] = None, negative_prompt_2: str | list[str] = None, height: int = 720, width: int = 1280, num_frames: int = 129, num_inference_steps: int = 50, sigmas: list[float] = None, true_cfg_scale: float = 1.0, guidance_scale: float = 6.0, num_videos_per_prompt: int | None = 1, generator: typing.Union[torch.Generator, list[torch.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: str | None = 'pil', return_dict: bool = True, attention_kwargs: dict[str, typing.Any] | None = None, callback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None, callback_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)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L438)

**参数：**

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]`, *可选*) : 用于支持在 `set_timesteps` 方法中接受 `sigmas` 参数的调度器的去噪过程的自定义 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_scale` > 1 时近似真实的无分类器引导。请参阅 [论文](https://huggingface.co/papers/2210.03142) 以了解更多信息。

num_videos_per_prompt (`int`，*可选*，默认为 1)：每个提示词生成的图像数量。

generator (`torch.Generator` 或 `list[torch.Generator]`，*可选*)：用于使生成过程确定性的 [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html)。

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` 输入参数生成 pooled 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](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py) 中 `self.processor` 下定义的 `AttentionProcessor`。

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 的调用函数。

示例：
```python
>>> 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[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

#### diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput[[diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput]]

```python
diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput(frames: Tensor)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_output.py#L11)

**参数：**

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

