Diffusers documentation

Video üretimi

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

Video üretimi

Video üretim modelleri, görüntü üretimini (1 karelik bir video olarak düşünülebilir) uzay ve zamana ilişkin verileri de işleyecek şekilde genişletir. Tüm bu verilerin - metin, uzay, zaman - kareden kareye tutarlı ve hizalı kalmasını sağlamak, uzun ve yüksek çözünürlüklü videolar üretirken büyük bir zorluktur.

Modern video models, bu zorluğu diffusion transformer (DiT) mimarisiyle ele alır. Bu, hesaplama maliyetlerini azaltır ve daha büyük ve daha yüksek kaliteli görüntü ve video verilerine daha verimli bir şekilde ölçeklenmeyi mümkün kılar.

Aşağıda bu video modellerinden bazılarının neler yapabildiğine göz atın.

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)

Bu kılavuz, hangi parametrelerin yapılandırılacağı ve bellek kullanımının nasıl azaltılacağı gibi video üretimi temellerini kapsayacaktır.

Belirli bir modelin nasıl kullanılacağı hakkında daha fazla bilgi edinmek istiyorsanız, lütfen ilgili pipeline API model kartına başvurun.

Pipeline parametreleri

Video üretim kalitesini veya hızını etkileyecek, yapılandırmak gereken birkaç parametre vardır. Uygun kalite-hız ödünleşimini keşfetmek için farklı parametre değerleriyle deney yapmak önemlidir.

num_frames

Bir kare, hareket veya bir video oluşturmak için diğer karelerin bir dizisinde oynatılan durağan bir görüntüdür. Saniyede üretilen kare sayısını num_frames ile kontrol edin. num_frames değerini artırmak, algılanan hareket akıcılığını ve görsel bütünlüğü artırır; bu da dinamik içeriğe sahip videolar için özellikle önemlidir. Daha yüksek bir num_frames değeri ayrıca video süresini de artırır.

Bazı video modelleri, çıkarım için daha spesifik num_frames değerleri gerektirir. Örneğin, HunyuanVideoPipeline, num_frames değerinin (4 * num_frames) +1 ile hesaplanmasını önerir. Önerilen bir değer olup olmadığını görmek için her zaman ilgili pipeline'ın API model kartını kontrol edin.

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

Yönlendirme ölçeği veya “cfg”, üretilen karelerin girdi koşullarına (metin, görüntü veya her ikisi) ne kadar sadık kaldığını kontrol eder. guidance_scale değerini artırmak, girdi koşullarına daha fazla benzeyen ve daha ince detaylar içeren kareler üretir; ancak artefakt oluşma riskini artırır ve çıktı çeşitliliğini azaltabilir. Daha düşük guidance_scale değerleri, komuta daha gevşek bir uyum ve artan çıktı çeşitliliği sağlar; ancak detaylar o kadar iyi olmayabilir. Değer çok düşükse, komutunuzu tamamen görmezden gelip rastgele gürültü üretebilir.

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

Negatif bir prompt, üretilen videoda görmek istemediğiniz unsurları dışlamak için kullanışlıdır. Genellikle, “bulanık, bozuk, çirkin” gibi istenmeyen unsurlardan modeli uzaklaştırarak üretilen videonun kalitesini ve uyumunu iyileştirmek için kullanılır. Bu, daha temiz ve odaklanmış videolar oluşturmanızı sağlar.

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

Bellek kullanımını azaltın

HunyuanVideoPipeline ve WanPipeline gibi 10B+ parametreye sahip son video modelleri çok fazla bellek gerektirir ve bu gereksinim genellikle tüketici donanımlarında mevcut belleği aşar. Diffusers, bu büyük modellerin bellek gereksinimlerini azaltmak için çeşitli teknikler sunar.

Diğer bellek tasarrufu teknikleri hakkında daha fazla ayrıntı için Bellek kullanımını azaltma kılavuzuna bakın.

Bu tekniklerden biri, kullanılmadığında modelin iç katman gruplarını (örneğin torch.nn.Sequential) CPU'ya aktaran group-offloading'dir. Bu katmanlar, GPU'da modelin tüm bileşenlerini depolamaktan kaçınmak için yalnızca hesaplama sırasında ihtiyaç duyulduğunda yüklenir. WanPipeline gibi 14B parametreli bir modelde group-offloading, gereken belleği yaklaşık 13GB VRAM'e düşürebilir.

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

Belleği azaltmak için bir diğer seçenek, model ağırlıklarını daha düşük hassasiyetli bir veri türünde saklayan modelin kuantize edilmesini değerlendirmektir. Ancak kuantizasyon, kullanılan belirli video modeline bağlı olarak video kalitesini etkileyebilir. Desteklenen farklı kuantizasyon altyapıları hakkında daha fazla bilgi için kuantizasyon Genel Bakış sayfasına bakın.

Aşağıdaki örnek, bir modeli kuantize etmek için bitsandbytes kullanır.

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

Çıkarım hızı

torch.compile, optimize edilmiş çekirdekleri kullanarak çıkarımı hızlandırabilir. Derleme ilk seferde daha uzun sürer, ancak bir kez derlendikten sonra çok daha hızlı çalışır. En iyi uygulama, hattı (pipeline) bir kez derlemek ve ardından hiçbir şeyi değiştirmeden hattı birden fazla kez kullanmaktır. Görüntü boyutu gibi bir değişiklik, yeniden derlemeyi tetikler.

Aşağıdaki örnek, pipeline'daki transformer'ı derler ve performansı en üst düzeye çıkarmak için "max-autotune" modunu kullanır.

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