Diffusers documentation
HunyuanVideo
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.
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)Compilation sẽ chậm ở lần đầu tiên nhưng các lần gọi pipeline sau đó sẽ nhanh hơn.
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().
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ị.
parameter giá trị được khuyến nghị dtype của text encoder torch.float16dtype của transformer torch.bfloat16dtype của vae torch.float16num_frames (k)4 * k+ 1Thử các giá trị
shiftthấp hơn (2.0đến5.0) cho video có độ phân giải thấp và các giá trịshiftcao hơn (7.0đến12.0) cho hình ảnh có độ phân giải cao.
HunyuanVideoPipeline
lớp diffusers.HunyuanVideoPipeline
< source >( text_encoder: LlamaModeltokenizer: LlamaTokenizertransformer: HunyuanVideoTransformer3DModelvae: AutoencoderKLHunyuanVideoscheduler: FlowMatchEulerDiscreteSchedulertext_encoder_2: CLIPTextModeltokenizer_2: CLIPTokenizer )
Tham số
- text_encoder (
LlamaModel) — Llava Llama3-8B. - tokenizer (
LlamaTokenizer) — Tokenizer từ Llava Llama3-8B. - transformer (HunyuanVideoTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
- scheduler (FlowMatchEulerDiscreteScheduler) —
Một scheduler được sử dụng kết hợp với
transformerđể khử nhiễu các latents ảnh đã được mã hóa. - vae (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 (latent representations).
- text_encoder_2 (
CLIPTextModel) — CLIP, cụ thể là biến thể clip-vit-large-patch14. - tokenizer_2 (
CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer.
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__
< source >( 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 (
strhoặclist[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ềnprompt_embedsthay thế. - prompt_2 (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt sẽ được gửi đếntokenizer_2vàtext_encoder_2. Nếu không được định nghĩa,promptsẽ được sử dụng thay thế. - negative_prompt (
strhoặclist[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ềnnegative_prompt_embedsthay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếutrue_cfg_scalekhông lớn hơn1). - negative_prompt_2 (
strhoặclist[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 đếntokenizer_2vàtext_encoder_2. Nếu không được định nghĩa,negative_promptsẽ đượ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ốsigmastrong phương thứcset_timestepscủa chúng. Nếu không được định nghĩa, hành vi mặc định khinum_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 khitrue_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 đặtguidance_scale> 1. Giá trịguidance_scalecao hơn khuyến khích mô hình tạo ra hình ảnh phù hợp hơn vớipromptvớ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.Generatorhoặclist[torch.Generator], tùy chọn) — Mộttorch.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ụnggeneratorngẫ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àoprompt. - 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àoprompt. - 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àonegative_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àonegative_prompt. - prompt_attention_mask (
torch.Tensor, tùy chọn) — Mặt nạ chú ý choprompt_embeds. Bắt buộc khiprompt_embedsđược truyền trực tiếp. - negative_prompt_attention_mask (
torch.Tensor, tùy chọn) — Mặt nạ chú ý (attention mask) chonegative_prompt_embeds. Bắt buộc khinegative_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ữaPIL.Imagehoặcnp.array. - return_dict (
bool, tùy chọn, mặc định làTrue) — Có nên trả về mộtHunyuanVideoPipelineOutputthay 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 đếnAttentionProcessornhư đã định nghĩa dướiself.processortrong 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ủaPipelineCallbackhoặcMultiPipelineCallbacksđượ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_kwargssẽ bao gồm một danh sách tất cả các tensor như được chỉ định bởicallback_on_step_end_tensor_inputs. - callback_on_step_end_tensor_inputs (
list, optional) — Danh sách các tensor đầu vào cho hàmcallback_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_inputscủ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
< source >( 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àibatch_size,trong đó mỗi danh sách con chứa các chuỗi hình ảnh PIL đã khử nhiễu có độ dàinum_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.