Diffusers documentation

Tạo video

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

and get access to the augmented documentation experience

to get started

Tạo video

Mô hình tạo video mở rộng khả năng tạo ảnh (có thể xem là video một khung hình) để xử lý cả dữ liệu liên quan đến không gian và thời gian. Đảm bảo toàn bộ dữ liệu này – văn bản, không gian, thời gian – luôn nhất quán và đồng bộ từ khung hình này sang khung hình khác là một thách thức lớn khi tạo video dài và có độ phân giải cao.

Các mô hình video hiện đại giải quyết thách thức này bằng kiến trúc diffusion transformer (DiT). Điều này giúp giảm chi phí tính toán và cho phép mở rộng hiệu quả hơn sang dữ liệu hình ảnh và video có kích thước lớn hơn, chất lượng cao hơn.

Xem một số khả năng của các mô hình video này bên dưới.

Wan2.1
HunyuanVideo
LTX-Video
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel

text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)

# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
apply_group_offloading(text_encoder,
    onload_device=onload_device,
    offload_device=offload_device,
    offload_type="block_level",
    num_blocks_per_group=4
)
transformer.enable_group_offload(
    onload_device=onload_device,
    offload_device=offload_device,
    offload_type="leaf_level",
    use_stream=True
)

pipeline = WanPipeline.from_pretrained(
    "Wan-AI/Wan2.1-T2V-14B-Diffusers",
    vae=vae,
    transformer=transformer,
    text_encoder=text_encoder,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

prompt = """
The camera rushes from far to near in a low-angle shot, 
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in 
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. 
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic 
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, 
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, 
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=81,
    guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)

Hướng dẫn này sẽ bao quát các kiến thức cơ bản về tạo video, chẳng hạn như các tham số cần cấu hình và cách giảm mức sử dụng bộ nhớ của chúng.

Nếu bạn muốn tìm hiểu thêm về cách sử dụng một mô hình cụ thể, vui lòng tham khảo thẻ mô hình (model card) của API pipeline của họ.

Tham số Pipeline

Có một số tham số cần cấu hình trong pipeline sẽ ảnh hưởng đến chất lượng hoặc tốc độ tạo video. Thử nghiệm với các giá trị tham số khác nhau là rất quan trọng để tìm ra sự đánh đổi phù hợp giữa chất lượng và tốc độ.

num_frames

Một khung hình là một hình ảnh tĩnh được phát trong một chuỗi các khung hình khác để tạo ra chuyển động hoặc video. Kiểm soát số lượng khung hình được tạo ra mỗi giây bằng num_frames. Việc tăng num_frames sẽ làm tăng độ mượt mà của chuyển động và tính nhất quán thị giác, điều này đặc biệt quan trọng đối với các video có nội dung động. Giá trị num_frames cao hơn cũng làm tăng thời lượng video.

Một số mô hình video yêu cầu các giá trị num_frames cụ thể hơn để suy luận. Ví dụ, HunyuanVideoPipeline khuyến nghị tính toán num_frames bằng (4 * num_frames) +1. Hãy luôn kiểm tra thẻ mô hình API của pipeline để xem có giá trị khuyến nghị nào không.

import torch
from diffusers import LTXPipeline
from diffusers.utils import export_to_video

pipeline = LTXPipeline.from_pretrained(
    "Lightricks/LTX-Video", dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = """
A woman with long brown hair and light skin smiles at another woman with long blonde hair. The woman 
with brown hair wears a black jacket and has a small, barely noticeable mole on her right cheek. The 
camera angle is a close-up, focused on the woman with brown hair's face. The lighting is warm and 
natural, likely from the setting sun, casting a soft glow on the scene. The scene appears to be 
real-life footage
"""

video = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    width=768,
    height=512,
    num_frames=161,
    decode_timestep=0.03,
    decode_noise_scale=0.025,
    num_inference_steps=50,
).frames[0]
export_to_video(video, "output.mp4", fps=24)

guidance_scale

Thang độ dẫn hướng hoặc “cfg” kiểm soát mức độ bám sát của các khung hình được tạo ra đối với điều kiện đầu vào (chữ, ảnh hoặc cả hai). Tăng guidance_scale sẽ tạo ra các khung hình giống với điều kiện đầu vào hơn và bao gồm các chi tiết tinh tế hơn, nhưng có nguy cơ gây ra các lỗi hình ảnh và làm giảm sự đa dạng của đầu ra. Các giá trị guidance_scale thấp hơn khuyến khích việc bám sát prompt lỏng lẻo hơn và tăng sự đa dạng của đầu ra, nhưng chi tiết có thể không được sắc nét bằng. Nếu giá trị quá thấp, mô hình có thể bỏ qua hoàn toàn prompt của bạn và tạo ra nhiễu ngẫu nhiên.

import torch
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
from diffusers.utils import export_to_video

pipeline = CogVideoXPipeline.from_pretrained(
  "THUDM/CogVideoX-2b",
  dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = """
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over
a plush, blue carpet that mimics the waves of the sea. The ship's hull is painted a rich brown, 
with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an 
oceanic expanse. Surrounding the ship are various other toys and children's items, hinting at 
a playful environment. The scene captures the innocence and imagination of childhood, 
with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
"""

video = pipeline(
  prompt=prompt,
  guidance_scale=6,
  num_inference_steps=50
).frames[0]
export_to_video(video, "output.mp4", fps=8)

negative_prompt

Prompt âm tính hữu ích để loại trừ những thứ bạn không muốn xuất hiện trong video được tạo ra. Nó thường được sử dụng để tinh chỉnh chất lượng và độ khớp của video bằng cách đẩy mô hình ra xa các yếu tố không mong muốn như “mờ, méo mó, xấu”. Điều này có thể tạo ra các video sạch sẽ và tập trung hơn.

# pip install ftfy
import torch
from diffusers import WanPipeline
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from diffusers.utils import export_to_video

vae = AutoencoderKLWan.from_pretrained(
  "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32
)
pipeline = WanPipeline.from_pretrained(
  "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, dtype=torch.bfloat16
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
  pipeline.scheduler.config, flow_shift=5.0
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
pipeline.set_adapters("steamboat-willie")

pipeline.enable_model_cpu_offload()

# use "steamboat willie style" to trigger the LoRA
prompt = """
steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot, 
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in 
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. 
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts 
dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""

output = pipeline(
  prompt=prompt,
  num_frames=81,
  guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)

Giảm mức sử dụng bộ nhớ

Các mô hình video gần đây như HunyuanVideoPipeline và WanPipeline, với hơn 10 tỷ tham số, đòi hỏi một lượng bộ nhớ lớn và thường vượt quá bộ nhớ khả dụng trên phần cứng tiêu dùng. Diffusers cung cấp một số kỹ thuật để giảm yêu cầu bộ nhớ của các mô hình lớn này.

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.

Một trong những kỹ thuật này là group-offloading, kỹ thuật này chuyển các nhóm lớp bên trong của mô hình (chẳng hạn như torch.nn.Sequential) sang CPU khi chúng không được sử dụng. Các lớp này chỉ được nạp khi cần thiết cho việc tính toán nhằm tránh việc lưu trữ toàn bộ các thành phần của mô hình trên GPU. Đối với một mô hình có 14 tỷ tham số như WanPipeline, group-offloading có thể giảm bộ nhớ cần thiết xuống còn khoảng 13GB VRAM.

# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.hooks.group_offloading import apply_group_offloading
from diffusers.utils import export_to_video, load_image
from transformers import UMT5EncoderModel

text_encoder = UMT5EncoderModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="text_encoder", dtype=torch.bfloat16)
vae = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32)
transformer = AutoModel.from_pretrained("Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="transformer", dtype=torch.bfloat16)

# group-offloading
onload_device = torch.device("cuda")
offload_device = torch.device("cpu")
apply_group_offloading(text_encoder,
    onload_device=onload_device,
    offload_device=offload_device,
    offload_type="block_level",
    num_blocks_per_group=4
)
transformer.enable_group_offload(
    onload_device=onload_device,
    offload_device=offload_device,
    offload_type="leaf_level",
    use_stream=True
)

pipeline = WanPipeline.from_pretrained(
    "Wan-AI/Wan2.1-T2V-14B-Diffusers",
    vae=vae,
    transformer=transformer,
    text_encoder=text_encoder,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

prompt = """
The camera rushes from far to near in a low-angle shot, 
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in 
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. 
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts dynamic 
shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""
negative_prompt = """
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, 
low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, 
misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
"""

output = pipeline(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=81,
    guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)

Một lựa chọn khác để giảm bộ nhớ là xem xét lượng tử hóa mô hình, trong đó trọng số mô hình được lưu trữ bằng kiểu dữ liệu có độ chính xác thấp hơn. Tuy nhiên, lượng tử hóa có thể ảnh hưởng đến chất lượng video tùy thuộc vào mô hình video cụ thể. Tham khảo Tổng quan về lượng tử hóa để tìm hiểu thêm về các backend lượng tử hóa được hỗ trợ khác nhau.

Ví dụ bên dưới sử dụng bitsandbytes để lượng tử hóa một mô hình.

# pip install ftfy

import torch
from diffusers import WanPipeline
from diffusers import AutoModel, WanPipeline
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
from transformers import UMT5EncoderModel
from diffusers.utils import export_to_video

# quantize transformer and text encoder weights with bitsandbytes
pipeline_quant_config = PipelineQuantizationConfig(
  quant_backend="bitsandbytes_4bit",
  quant_kwargs={"load_in_4bit": True},
  components_to_quantize=["transformer", "text_encoder"]
)

vae = AutoModel.from_pretrained(
  "Wan-AI/Wan2.1-T2V-14B-Diffusers", subfolder="vae", dtype=torch.float32
)
pipeline = WanPipeline.from_pretrained(
  "Wan-AI/Wan2.1-T2V-14B-Diffusers", vae=vae, quantization_config=pipeline_quant_config, dtype=torch.bfloat16
)
pipeline.scheduler = UniPCMultistepScheduler.from_config(
  pipeline.scheduler.config, flow_shift=5.0
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

pipeline.load_lora_weights("benjamin-paine/steamboat-willie-14b", adapter_name="steamboat-willie")
pipeline.set_adapters("steamboat-willie")

pipeline.enable_model_cpu_offload()

# use "steamboat willie style" to trigger the LoRA
prompt = """
steamboat willie style, golden era animation, The camera rushes from far to near in a low-angle shot, 
revealing a white ferret on a log. It plays, leaps into the water, and emerges, as the camera zooms in 
for a close-up. Water splashes berry bushes nearby, while moss, snow, and leaves blanket the ground. 
Birch trees and a light blue sky frame the scene, with ferns in the foreground. Side lighting casts 
dynamic shadows and warm highlights. Medium composition, front view, low angle, with depth of field.
"""

output = pipeline(
  prompt=prompt,
  num_frames=81,
  guidance_scale=5.0,
).frames[0]
export_to_video(output, "output.mp4", fps=16)

Tốc độ suy luận

torch.compile có thể tăng tốc độ suy luận bằng cách sử dụng các kernel được tối ưu hóa. Quá trình biên dịch sẽ mất nhiều thời gian hơn ở lần đầu tiên, nhưng sau khi biên dịch xong, tốc độ sẽ nhanh hơn đáng kể. Tốt nhất là nên biên dịch pipeline một lần, sau đó sử dụng pipeline nhiều lần mà không thay đổi bất kỳ điều gì. Một sự thay đổi, chẳng hạn như kích thước ảnh, sẽ kích hoạt việc biên dịch lại.

Ví dụ dưới đây biên dịch transformer trong pipeline và sử dụng chế độ "max-autotune" để tối đa hóa hiệu năng.

import torch
from diffusers import CogVideoXPipeline, CogVideoXTransformer3DModel
from diffusers.utils import export_to_video

pipeline = CogVideoXPipeline.from_pretrained(
  "THUDM/CogVideoX-2b",
  dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

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

prompt = """
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. 
The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. 
Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, 
with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
"""

video = pipeline(
  prompt=prompt,
  guidance_scale=6,
  num_inference_steps=50
).frames[0]
export_to_video(video, "output.mp4", fps=8)
Update on GitHub