#
# Được cấp phép theo Giấy phép Apache, Phiên bản 2.0 (gọi là "Giấy phép");
# bạn có thể không sử dụng tệp này ngoại trừ tuân thủ theo Giấy phép.
# Bạn có thể nhận được một bản sao của Giấy phép tại
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Trừ khi được yêu cầu bởi luật pháp có hiệu lực hoặc được thỏa thuận bằng văn bản, phần mềm
# được phân phối theo Giấy phép được phân phối trên cơ sở
# KHÔNG CÓ BẢO HÀNH HOẶC ĐIỀU KIỆN DƯỚI BẤT KỲ HÌNH THỨC NÀO, dù được nêu rõ hay ngụ ý.
# Xem Giấy phép để biết ngôn ngữ cụ thể điều chỉnh các quyền và
# giới hạn theo Giấy phép. -->

  
    
      
    
  

# HunyuanVideo

[HunyuanVideo](https://huggingface.co/papers/2412.03603) là mô hình diffusion transformer có 13B tham số, được thiết kế để cạnh tranh với các mô hình nền tảng video mã nguồn đóng và cho phép cộng đồng tiếp cận rộng rãi hơn. Mô hình này sử dụng kiến trúc "dual-stream to single-stream" để xử lý riêng biệt các token video và văn bản trước, sau đó nối chúng lại và đưa vào transformer để tích hợp thông tin đa phương thức. Một mô hình ngôn ngữ lớn đa phương thức (MLLM) đã được huấn luyện trước được sử dụng làm encoder vì nó có sự căn chỉnh hình ảnh-văn bản tốt hơn, khả năng mô tả chi tiết hình ảnh và suy luận tốt hơn, đồng thời có thể được dùng như một trình học zero-shot nếu các chỉ thị hệ thống được thêm vào prompt của người dùng. Cuối cùng, HunyuanVideo sử dụng một autoencoder biến phân nhân quả 3D để xử lý dữ liệu video ở độ phân giải và tốc độ khung hình gốc một cách hiệu quả hơn.

Bạn có thể tìm thấy tất cả các checkpoint HunyuanVideo gốc dưới tổ chức [Tencent](https://huggingface.co/tencent).

> [!TIP]
> Nhấp vào các mô hình HunyuanVideo ở thanh bên phải để xem thêm các ví dụ về tác vụ tạo video.
>
> Các ví dụ bên dưới sử dụng checkpoint từ [hunyuanvideo-community](https://huggingface.co/hunyuanvideo-community) vì trọng số được lưu trữ trong bố cục tương thích với Diffusers.

Ví dụ dưới đây minh họa cách tạo video được tối ưu hóa cho bộ nhớ hoặc tốc độ suy luận.

Tham khảo hướng dẫn [Giảm mức sử dụng bộ nhớ](../../optimization/memory) để biết thêm chi tiết về các kỹ thuật tiết kiệm bộ nhớ khác nhau.

Mô hình HunyuanVideo đã lượng tử hóa bên dưới yêu cầu ~14GB VRAM.

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

[Compilation](../../optimization/fp16#torchcompile) sẽ chậm ở lần đầu tiên nhưng các lần gọi pipeline sau đó sẽ nhanh hơn.

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

## Ghi chú

- HunyuanVideo hỗ trợ LoRA với [load_lora_weights()](/docs/diffusers/v0.43.0/vi/api/loaders/lora#diffusers.loaders.HunyuanVideoLoraLoaderMixin.load_lora_weights).

  
  Hiển thị mã ví dụ

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

  

- Tham khảo bảng dưới đây để biết các giá trị suy luận được khuyến nghị.

  | parameter | giá trị được khuyến nghị |
  |---|---|
  | dtype của text encoder | `torch.float16` |
  | dtype của transformer | `torch.bfloat16` |
  | dtype của vae | `torch.float16` |
  | `num_frames (k)` | 4 * `k` + 1 |

- Thử các giá trị `shift` thấp hơn (`2.0` đến `5.0`) cho video có độ phân giải thấp và các giá trị `shift` cao hơn (`7.0` đến `12.0`) cho hình ảnh có độ phân giải cao.

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

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L144)

**Tham số:**

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

tokenizer (`LlamaTokenizer`) : Tokenizer từ [Llava Llama3-8B](https://huggingface.co/xtuner/llava-llama-3-8b-v1_1-transformers).

transformer ([HunyuanVideoTransformer3DModel](/docs/diffusers/v0.43.0/vi/api/models/hunyuan_video_transformer_3d#diffusers.HunyuanVideoTransformer3DModel)) : Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.

scheduler ([FlowMatchEulerDiscreteScheduler](/docs/diffusers/v0.43.0/vi/api/schedulers/flow_match_euler_discrete#diffusers.FlowMatchEulerDiscreteScheduler)) : Một trình lập lịch được sử dụng kết hợp với `transformer` để khử nhiễu các latent ảnh đã mã hóa.

vae ([AutoencoderKLHunyuanVideo](/docs/diffusers/v0.43.0/vi/api/models/autoencoder_kl_hunyuan_video#diffusers.AutoencoderKLHunyuanVideo)) : Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video sang và từ các biểu diễn ẩn.

text_encoder_2 (`CLIPTextModel`) : [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), cụ thể là biến thể [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14).

tokenizer_2 (`CLIPTokenizer`) : Tokenizer của lớp [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).

Pipeline để tạo video từ văn bản sử dụng HunyuanVideo.

Mô hình này kế thừa từ [DiffusionPipeline](/docs/diffusers/v0.43.0/vi/api/pipelines/overview#diffusers.DiffusionPipeline). Xem tài liệu của lớp cha để biết các phương thức chung được triển khai cho tất cả các pipeline (tải xuống, lưu, chạy trên một thiết bị cụ thể, v.v.).

#### __call__[[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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_hunyuan_video.py#L438)

**Tham số:**

prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `prompt_embeds` thay thế.

prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt cần được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `prompt` sẽ được sử dụng thay thế.

negative_prompt (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn việc tạo ảnh. Nếu không được định nghĩa, bạn phải truyền `negative_prompt_embeds` thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu `true_cfg_scale` không lớn hơn `1`).

negative_prompt_2 (`str` hoặc `list[str]`, *tùy chọn*) : Prompt hoặc các prompt không được dùng để hướng dẫn tạo ảnh, sẽ được gửi đến `tokenizer_2` và `text_encoder_2`. Nếu không được định nghĩa, `negative_prompt` sẽ được sử dụng trong tất cả các text-encoder.

height (`int`, mặc định là `720`) : Chiều cao của hình ảnh được tạo ra, tính bằng pixel.

width (`int`, mặc định là `1280`) : Độ rộng của hình ảnh được tạo ra, tính bằng pixel.

num_frames (`int`, mặc định là `129`) : Số khung hình trong video được tạo ra.

num_inference_steps (`int`, mặc định là `50`) : Số bước khử nhiễu. Số bước khử nhiễu nhiều hơn thường dẫn đến hình ảnh có chất lượng cao hơn, đổi lại là suy luận chậm hơn.

sigmas (`list[float]`, *optional*) : Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ tham số `sigmas` trong phương thức `set_timesteps` của chúng. Nếu không được định nghĩa, hành vi mặc định khi `num_inference_steps` được truyền vào sẽ được sử dụng.

true_cfg_scale (`float`, *optional*, mặc định là 1.0) : True classifier-free guidance (guidance scale) được kích hoạt khi `true_cfg_scale` > 1 và `negative_prompt` được cung cấp.

guidance_scale (`float`, mặc định là `6.0`) : Embedded guiddance scale được kích hoạt bằng cách đặt `guidance_scale` > 1. `guidance_scale` cao hơn khuyến khích mô hình tạo ra hình ảnh phù hợp hơn với `prompt` với cái giá là chất lượng hình ảnh thấp hơn. Các mô hình Guidance-distilled xấp xỉ true classifer-free guidance cho `guidance_scale` > 1. Tham khảo [bài báo](https://huggingface.co/papers/2210.03142) để tìm hiểu thêm.

num_videos_per_prompt (`int`, *tuỳ chọn*, mặc định là 1) : Số lượng hình ảnh cần tạo cho mỗi prompt.

generator (`torch.Generator` hoặc `list[torch.Generator]`, *tùy chọn*) : Một [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) để đảm bảo quá trình sinh là tất định.

latents (`torch.Tensor`, *tùy chọn*) : Các latents nhiễu được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo ảnh. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng `generator` ngẫu nhiên được cung cấp.

prompt_embeds (`torch.Tensor`, *tùy chọn*) : Các vector nhúng văn bản đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các vector nhúng văn bản sẽ được tạo từ đối số đầu vào `prompt`.

pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản đã được pool sẵn. Có thể dùng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã pool sẽ được tạo ra từ đối số đầu vào `prompt`.

negative_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các vector nhúng văn bản âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

negative_pooled_prompt_embeds (`torch.FloatTensor`, *tùy chọn*) : Các embedding văn bản pooled âm đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh các đầu vào văn bản, *vd.* trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào `negative_prompt`.

prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho `prompt_embeds`. Bắt buộc khi `prompt_embeds` được truyền trực tiếp.

negative_prompt_attention_mask (`torch.Tensor`, *tùy chọn*) : Mặt nạ chú ý cho `negative_prompt_embeds`. Bắt buộc khi `negative_prompt_embeds` được truyền trực tiếp.

output_type (`str`, *tùy chọn*, mặc định là `"pil"`) : Định dạng đầu ra của hình ảnh được tạo ra. Chọn giữa `PIL.Image` hoặc `np.array`.

return_dict (`bool`, *tùy chọn*, mặc định là `True`) : Có nên trả về một `HunyuanVideoPipelineOutput` thay vì một tuple thông thường hay không.

attention_kwargs (`dict`, *tùy chọn*) : Một từ điển kwargs mà nếu được chỉ định sẽ được truyền đến `AttentionProcessor` như đã định nghĩa dưới `self.processor` trong [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).

prompt_template (`dict`, *tùy chọn*) : Mẫu được sử dụng để định dạng prompt trước khi mã hóa. Mặc định là mẫu mặc định của model.

max_sequence_length (`int`, *tuỳ chọn*, mặc định là 256) : Độ dài tối đa của chuỗi được sử dụng cho trình mã hóa prompt.

callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*) : Một hàm hoặc một lớp con của `PipelineCallback` hoặc `MultiPipelineCallbacks` được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận, với các đối số sau: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` sẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởi `callback_on_step_end_tensor_inputs`.

callback_on_step_end_tensor_inputs (`list`, *optional*) : Danh sách các đầu vào tensor cho hàm `callback_on_step_end`. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số `callback_kwargs`. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính `._callback_tensor_inputs` của lớp pipeline của bạn.

**Trả về:** `~HunyuanVideoPipelineOutput` hoặc `tuple`

Nếu `return_dict` là `True`, `HunyuanVideoPipelineOutput` sẽ được trả về, ngược lại một `tuple` sẽ được trả về trong đó phần tử đầu tiên là một danh sách chứa các hình ảnh được tạo ra và phần tử thứ hai là một danh sách các `bool` cho biết hình ảnh được tạo ra tương ứng có chứa nội dung "không an toàn cho công việc" (nsfw) hay không.

Hàm gọi call của pipeline để tạo nội dung.

Ví dụ:
```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)
```

[Nguồn](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/pipelines/hunyuan_video/pipeline_output.py#L11)

**Tham số:**

frames (`torch.Tensor`, `np.ndarray`, hoặc list[list[PIL.Image.Image]]) : danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dài `batch_size,` trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dài `num_frames.` Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng `(batch_size, num_frames, channels, height, width)`.

Lớp đầu ra cho các pipeline của HunyuanVideo.

