Diffusers documentation

HunyuanVideo

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

LoRA

HunyuanVideo

HunyuanVideo 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ó khả năng căn chỉnh hình ảnh-văn bản tốt hơn, 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ỉ dẫn 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.

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

bộ nhớ
tốc độ suy luận

Tham khảo hướng dẫn Giảm mức sử dụng bộ nhớ để 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.

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)

Ghi chú

  • HunyuanVideo hỗ trợ LoRA với load_lora_weights().

    Hiển thị mã ví dụ
    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ị.

    parametergiá trị được khuyến nghị
    dtype của text encodertorch.float16
    dtype của transformertorch.bfloat16
    dtype của vaetorch.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

lớp diffusers.HunyuanVideoPipeline

< >

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

Tham số

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

Mô hình này kế thừa từ 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__

< >

( 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

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng 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 sẽ đượ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 dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần 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 dùng để định hướng 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 cho 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) — Chiều 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ố lượng 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, với cái giá là suy luận chậm hơn.
  • sigmas (list[float], tùy chọn) — 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ợ đối 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 sẽ được sử dụng.
  • true_cfg_scale (float, tùy chọn, 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) — Thang độ guidance nhúng được kích hoạt bằng cách đặt guidance_scale > 1. Giá trị 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 chi phí 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 để tìm hiểu thêm.

  • num_videos_per_prompt (int, tùy 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 để làm cho quá trình sinh ra kết quả xác đị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 embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding 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 gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầ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 đã gộp sẽ được tạo từ đối số đầu vào prompt.
  • negative_prompt_embeds (torch.FloatTensor, tùy chọn) — Các embedding văn bản âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầ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ể dùng để dễ dàng điều chỉnh đầ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ú ý (attention mask) 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, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa dưới self.processor trong diffusers.models.attention_processor.
  • 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, tùy chọn, mặc định là 256) — Chiều 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, tùy chọn) — 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 tensor đầu vào 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 “not-safe-for-work” (nsfw) hay không.

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

Ví dụ:

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

lớp diffusers.pipelines.hunyuan_video.pipeline_output.HunyuanVideoPipelineOutput

< >

( frames: Tensor )

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.

Update on GitHub