Diffusers documentation
Wan
Wan
Wan-2.1 của nhóm Wan.
Báo cáo này giới thiệu Wan, một bộ mô hình nền tảng video toàn diện và mã nguồn mở, được thiết kế để đẩy lùi các giới hạn của việc tạo video. Được xây dựng dựa trên hệ thống diffusion transformer phổ biến, Wan đạt được những tiến bộ đáng kể về khả năng sinh nội dung thông qua một loạt các đổi mới, bao gồm VAE mới của chúng tôi, các chiến lược tiền huấn luyện có thể mở rộng, quy trình tuyển chọn dữ liệu quy mô lớn và các chỉ số đánh giá tự động. Những đóng góp này cùng nhau nâng cao hiệu suất và tính đa dụng của mô hình. Cụ thể, Wan được đặc trưng bởi bốn tính năng chính: Hiệu suất dẫn đầu: Mô hình 14B của Wan, được huấn luyện trên một tập dữ liệu khổng lồ bao gồm hàng tỷ hình ảnh và video, minh chứng cho các quy luật mở rộng (scaling laws) của việc tạo video liên quan đến cả kích thước dữ liệu và kích thước mô hình. Nó liên tục vượt trội hơn so với các mô hình mã nguồn mở hiện có cũng như các giải pháp thương mại tiên tiến nhất trên nhiều bộ đánh giá nội bộ và bên ngoài, thể hiện sự vượt trội về hiệu suất rõ ràng và đáng kể. Tính toàn diện: Wan cung cấp hai mô hình có năng lực, cụ thể là 1,3B và 14B tham số, lần lượt cho hiệu quả và hiệu suất. Nó cũng bao phủ nhiều ứng dụng hạ nguồn, bao gồm tạo video từ hình ảnh, chỉnh sửa video theo hướng dẫn, và tạo video cá nhân hóa, bao gồm tối đa tám tác vụ. Hiệu suất cấp tiêu dùng: Mô hình 1,3B thể hiện hiệu quả tài nguyên vượt trội, chỉ yêu cầu 8,19 GB VRAM, giúp nó tương thích với một loạt các GPU cấp tiêu dùng. Tính mở: Chúng tôi mã nguồn mở toàn bộ dòng sản phẩm Wan, bao gồm mã nguồn và tất cả các mô hình, với mục tiêu thúc đẩy sự phát triển của cộng đồng tạo video. Sự mở này nhằm mở rộng đáng kể các khả năng sáng tạo trong sản xuất video trong ngành và cung cấp cho giới học thuật các mô hình nền tảng video chất lượng cao. Tất cả mã và mô hình đều có sẵn tại đường dẫn URL này.
Bạn có thể tìm thấy tất cả các checkpoint gốc của Wan2.1 dưới tổ chức Wan-AI.
Các mô hình Wan sau đây được hỗ trợ trong Diffusers:
- Wan 2.1 T2V 1.3B
- Wan 2.1 T2V 14B
- Wan 2.1 I2V 14B - 480P
- Wan 2.1 I2V 14B - 720P
- Wan 2.1 FLF2V 14B - 720P
- Wan 2.1 VACE 1.3B
- Wan 2.1 VACE 14B
- Wan 2.2 T2V 14B
- Wan 2.2 I2V 14B
- Wan 2.2 TI2V 5B
- Wan 2.2 Animate 14B
Nhấp vào các mô hình Wan ở thanh bên phải để xem thêm các ví dụ về tạo video.
Tạo video từ văn bản
Ví dụ dưới đây minh họa cách tạo video từ văn bản đượ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 text-to-video Wan2.1 bên dưới yêu cầu ~13GB VRAM.
# pip install ftfy
import torch
import numpy as np
from diffusers import AutoModel, WanPipeline
from diffusers.quantizers import PipelineQuantizationConfig
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)Compilation sẽ chậm ở lần đầu tiên nhưng các lần gọi pipeline sau đó sẽ nhanh hơn. Caching cũng có thể tăng tốc suy luận bằng cách lưu trữ và tái sử dụng các đầu ra trung gian.
# 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)
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"
# torch.compile
pipeline.transformer.to(memory_format=torch.channels_last)
pipeline.transformer = torch.compile(
pipeline.transformer, mode="max-autotune", fullgraph=True
)
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)Tạo video từ khung hình đầu-cuối
Ví dụ dưới đây minh họa cách sử dụng pipeline image-to-video để tạo video bằng mô tả văn bản, khung hình bắt đầu và khung hình kết thúc.
import numpy as np
import torch
import torchvision.transforms.functional as TF
from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
from diffusers.utils import export_to_video, load_image
from transformers import CLIPVisionModel
model_id = "Wan-AI/Wan2.1-FLF2V-14B-720P-diffusers"
image_encoder = CLIPVisionModel.from_pretrained(model_id, subfolder="image_encoder", dtype=torch.float32)
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanImageToVideoPipeline.from_pretrained(
model_id, vae=vae, image_encoder=image_encoder, dtype=torch.bfloat16
)
pipe.to("cuda") # or "mps", "xpu", "cpu"
first_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png")
last_frame = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png")
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
def center_crop_resize(image, height, width):
# Calculate resize ratio to match first frame dimensions
resize_ratio = max(width / image.width, height / image.height)
# Resize the image
width = round(image.width * resize_ratio)
height = round(image.height * resize_ratio)
size = [width, height]
image = TF.center_crop(image, size)
return image, height, width
first_frame, height, width = aspect_ratio_resize(first_frame, pipe)
if last_frame.size != first_frame.size:
last_frame, _, _ = center_crop_resize(last_frame, height, width)
prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
output = pipe(
image=first_frame, last_image=last_frame, prompt=prompt, height=height, width=width, guidance_scale=5.5
).frames[0]
export_to_video(output, "output.mp4", fps=16)Tạo video có thể điều khiển từ bất kỳ
Wan VACE hỗ trợ nhiều kỹ thuật tạo khác nhau, đạt được khả năng tạo video có thể kiểm soát. Một số khả năng bao gồm:
- Điều khiển sang Video (Chiều sâu, Tư thế, Phác thảo, Dòng chảy, Xám, Vẽ nguệch ngoạc, Bố cục, Hộp bao, v.v.). Thư viện được khuyến nghị để tiền xử lý video nhằm thu được video điều khiển: huggingface/controlnet_aux
- Hình ảnh/Video sang Video (khung đầu, khung cuối, đoạn clip bắt đầu, đoạn clip kết thúc, các đoạn clip ngẫu nhiên)
- Inpainting và Outpainting
- Đối tượng trong Video (khuôn mặt, vật thể, nhân vật, v.v.)
- Tạo video từ bố cục (tham chiếu bất kỳ thứ gì, tạo chuyển động cho bất kỳ thứ gì, hoán đổi bất kỳ thứ gì, mở rộng bất kỳ thứ gì, di chuyển bất kỳ thứ gì, v.v.)
Các đoạn mã có sẵn trong pull request này minh họa một số ví dụ về cách tạo video với các tín hiệu điều khiển.
Quy tắc chung cần ghi nhớ khi chuẩn bị đầu vào cho pipeline VACE là các hình ảnh đầu vào, hoặc các khung hình của video mà bạn muốn dùng để điều kiện hóa, phải có một mask tương ứng có màu đen. Mask màu đen cho thấy mô hình sẽ không tạo ra nội dung mới cho khu vực đó, mà chỉ sử dụng các phần đó để điều kiện hóa quá trình tạo. Đối với các phần/khung hình cần được mô hình tạo ra, mask phải có màu trắng.
Wan-Animate: Hoạt ảnh và thay thế nhân vật thống nhất với sao chép toàn diện
Wan-Animate của nhóm Wan.
Chúng tôi giới thiệu Wan-Animate, một khung thống nhất cho hoạt hình hóa và thay thế nhân vật. Với một hình ảnh nhân vật và một video tham chiếu, Wan-Animate có thể hoạt hình hóa nhân vật bằng cách tái tạo chính xác các biểu cảm và chuyển động của nhân vật trong video để tạo ra các video nhân vật có độ trung thực cao. Hoặc, nó có thể tích hợp nhân vật đã được hoạt hình hóa vào video tham chiếu để thay thế nhân vật gốc, tái tạo ánh sáng và tông màu của cảnh để đạt được sự tích hợp môi trường liền mạch. Wan-Animate được xây dựng dựa trên mô hình Wan. Để điều chỉnh nó cho các tác vụ hoạt hình hóa nhân vật, chúng tôi sử dụng một hệ thống đầu vào được sửa đổi để phân biệt giữa các điều kiện tham chiếu và các vùng để tạo. Thiết kế này thống nhất nhiều tác vụ vào một biểu diễn ký hiệu chung. Chúng tôi sử dụng các tín hiệu bộ xương được căn chỉnh theo không gian để tái tạo chuyển động cơ thể và các đặc điểm khuôn mặt ẩn được trích xuất từ các hình ảnh nguồn để tái hiện các biểu cảm, cho phép tạo ra các video nhân vật với khả năng kiểm soát và biểu cảm cao. Hơn nữa, để tăng cường tích hợp môi trường trong quá trình thay thế nhân vật, chúng tôi phát triển một Relighting LoRA bổ trợ. Module này giữ cho ngoại hình của nhân vật nhất quán trong khi áp dụng ánh sáng và tông màu môi trường phù hợp. Kết quả thực nghiệm cho thấy Wan-Animate đạt hiệu suất tiên tiến nhất. Chúng tôi cam kết mã hóa nguồn mở các trọng số mô hình và mã nguồn của nó.
Trang dự án: https://humanaigc.github.io/wan-animate
Mô hình này chủ yếu được đóng góp bởi M. Tolga Cangöz.
Cách sử dụng
Pipeline Wan-Animate hỗ trợ hai chế độ hoạt động:
- Chế độ Hoạt hình (mặc định): Tạo hoạt hình cho hình ảnh nhân vật dựa trên chuyển động và biểu cảm từ các video tham chiếu
- Chế độ Thay thế: Thay thế một nhân vật trong video nền bằng một nhân vật mới trong khi giữ nguyên bối cảnh
Yêu cầu tiên quyết
Trước khi sử dụng pipeline, bạn cần tiền xử lý video tham chiếu của mình để trích xuất:
- Video tư thế: Chứa các điểm then chốt của bộ xương thể hiện chuyển động cơ thể
- Video khuôn mặt: Chứa các biểu diễn đặc điểm khuôn mặt để kiểm soát biểu cảm
Đối với chế độ thay thế, bạn cần thêm:
- Video nền: Video gốc chứa cảnh
- Video mặt nạ: Mặt nạ chỉ định nơi cần tạo nội dung (trắng) so với nơi giữ nguyên bản (đen)
Video thô không nên được sử dụng cho các đầu vào như
pose_video, vì pipeline kỳ vọng chúng đã được tiền xử lý để trích xuất thông tin phù hợp. Các script tiền xử lý để chuẩn bị những đầu vào này có sẵn trong kho Wan-Animate gốc. Việc tích hợp các bước tiền xử lý này vào Diffusers được lên kế hoạch cho một bản phát hành trong tương lai.
Ví dụ dưới đây minh họa cách sử dụng pipeline Wan-Animate:
import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load character image and preprocessed videos
image = load_image("path/to/character.jpg")
pose_video = load_video("path/to/pose_video.mp4") # Preprocessed skeletal keypoints
face_video = load_video("path/to/face_video.mp4") # Preprocessed facial features
# Resize image to match VAE constraints
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person dancing energetically in a studio with dynamic lighting and professional camera work"
negative_prompt = "blurry, low quality, distorted, deformed, static, poorly drawn"
# Generate animated video
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_length=77,
guidance_scale=1.0,
mode="animate", # Animation mode (default)
).frames[0]
export_to_video(output, "animated_character.mp4", fps=30)import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
# Load all required inputs for replacement mode
image = load_image("path/to/new_character.jpg")
pose_video = load_video("path/to/pose_video.mp4") # Preprocessed skeletal keypoints
face_video = load_video("path/to/face_video.mp4") # Preprocessed facial features
background_video = load_video("path/to/background_video.mp4") # Original scene
mask_video = load_video("path/to/mask_video.mp4") # Black: preserve, White: generate
# Resize image to match video dimensions
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person seamlessly integrated into the scene with consistent lighting and environment"
negative_prompt = "blurry, low quality, inconsistent lighting, floating, disconnected from scene"
# Replace character in background video
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
background_video=background_video,
mask_video=mask_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_lengths=77,
guidance_scale=1.0,
mode="replace", # Replacement mode
).frames[0]
export_to_video(output, "character_replaced.mp4", fps=30)import numpy as np
import torch
from diffusers import AutoencoderKLWan, WanAnimatePipeline
from diffusers.utils import export_to_video, load_image, load_video
model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", dtype=torch.float32)
pipe = WanAnimatePipeline.from_pretrained(model_id, vae=vae, dtype=torch.bfloat16)
pipe.to("cuda") # or "mps", "xpu", "cpu"
image = load_image("path/to/character.jpg")
pose_video = load_video("path/to/pose_video.mp4")
face_video = load_video("path/to/face_video.mp4")
def aspect_ratio_resize(image, pipe, max_area=720 * 1280):
aspect_ratio = image.height / image.width
mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
image = image.resize((width, height))
return image, height, width
image, height, width = aspect_ratio_resize(image, pipe)
prompt = "A person dancing energetically in a studio"
negative_prompt = "blurry, low quality"
# Advanced: Use temporal guidance and custom callback
def callback_fn(pipe, step_index, timestep, callback_kwargs):
# You can modify latents or other tensors here
print(f"Step {step_index}, Timestep {timestep}")
return callback_kwargs
output = pipe(
image=image,
pose_video=pose_video,
face_video=face_video,
prompt=prompt,
negative_prompt=negative_prompt,
height=height,
width=width,
segment_frame_length=77,
num_inference_steps=50,
guidance_scale=5.0,
prev_segment_conditioning_frames=5, # Use 5 frames for temporal guidance (1 or 5 recommended)
callback_on_step_end=callback_fn,
callback_on_step_end_tensor_inputs=["latents"],
).frames[0]
export_to_video(output, "animated_advanced.mp4", fps=30)Các tham số chính
- mode: Chọn giữa
"animate"(mặc định) hoặc"replace" - prev_segment_conditioning_frames: Số khung hình cho hướng dẫn theo thời gian (khuyến nghị dùng 1 hoặc 5). Dùng 5 giúp tăng tính nhất quán theo thời gian nhưng đòi hỏi nhiều bộ nhớ hơn
- guidance_scale: Kiểm soát mức độ bám sát của kết quả đầu ra so với prompt văn bản. Các giá trị cao hơn (5-7) tạo ra kết quả phù hợp hơn với prompt. Đối với Wan-Animate, CFG bị tắt theo mặc định (
guidance_scale=1.0) nhưng có thể được bật để hỗ trợ negative prompts và kiểm soát chi tiết hơn các biểu cảm khuôn mặt. (Lưu ý rằng CFG chỉ nhắm vào prompt văn bản và điều kiện khuôn mặt.)
Ghi chú
Wan2.1 hỗ trợ LoRA với load_lora_weights().
Hiển thị mã ví dụ
# pip install ftfy import torch from diffusers import AutoModel, WanPipeline from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler from diffusers.utils import export_to_video vae = AutoModel.from_pretrained( "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", subfolder="vae", dtype=torch.float32 ) pipeline = WanPipeline.from_pretrained( "Wan-AI/Wan2.1-T2V-1.3B-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-1.3b", 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)WanTransformer3DModel và AutoencoderKLWan hỗ trợ tải từ các tệp đơn lẻ bằng from_single_file().
Hiển thị mã ví dụ
# pip install ftfy import torch from diffusers import WanPipeline, WanTransformer3DModel, AutoencoderKLWan vae = AutoencoderKLWan.from_single_file( "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/vae/wan_2.1_vae.safetensors" ) transformer = WanTransformer3DModel.from_single_file( "https://huggingface.co/Comfy-Org/Wan_2.1_ComfyUI_repackaged/blob/main/split_files/diffusion_models/wan2.1_t2v_1.3B_bf16.safetensors", dtype=torch.bfloat16 ) pipeline = WanPipeline.from_pretrained( "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", vae=vae, transformer=transformer, dtype=torch.bfloat16 )Đặt dtype của AutoencoderKLWan thành
torch.float32để có chất lượng giải mã tốt hơn.Số khung hình mỗi giây (fps) hoặc
knên được tính bằng4 * k + 1.Thử 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.Wan 2.1 và 2.2 hỗ trợ sử dụng LightX2V LoRAs để tăng tốc suy luận. Việc sử dụng chúng trên Wan 2.2 hơi phức tạp hơn. Tham khảo mảnh mã này để biết thêm.
Wan 2.2 có hai denoiser. Mặc định, LoRA chỉ được nạp vào denoiser đầu tiên. Bạn có thể đặt
load_into_transformer_2=Trueđể nạp LoRA vào denoiser thứ hai. Xem ví dụ này và này để tìm hiểu thêm.
WanPipeline
lớp diffusers.WanPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulertransformer: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = Nonetransformer_2: diffusers.models.transformers.transformer_wan.WanTransformer3DModel | None = Noneboundary_ratio: float | None = Noneexpand_timesteps: bool = False )
Tham số
- tokenizer (
T5Tokenizer) — Tokenizer từ T5, cụ thể là biến thể google/umt5-xxl. - text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/umt5-xxl. - transformer (WanTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (UniPCMultistepScheduler) —
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 (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
- transformer_2 (WanTransformer3DModel, tùy chọn) —
Transformer có điều kiện để khử nhiễu các latents đầu vào trong giai đoạn nhiễu thấp. Nếu được cung cấp, sẽ kích hoạt
khử nhiễu hai giai đoạn, trong đó
transformerxử lý các giai đoạn nhiễu cao vàtransformer_2xử lý các giai đoạn nhiễu thấp. Nếu không được cung cấp, chỉtransformerđược sử dụng. - boundary_ratio (
float, tuỳ chọn, mặc định làNone) — Tỷ lệ tổng số bước thời gian (timesteps) được sử dụng làm ranh giới để chuyển đổi giữa các transformer trong quá trình khử nhiễu hai giai đoạn. Bước thời gian ranh giới thực tế được tính bằngboundary_ratio * num_train_timesteps. Khi được cung cấp,transformerxử lý các bước thời gian >= boundary_timestep vàtransformer_2xử lý các bước thời gian < boundary_timestep. Nếu làNone, chỉtransformerđược sử dụng cho toàn bộ quá trình khử nhiễu.
Pipeline để tạo video từ văn bản sử dụng Wan.
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] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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 = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput 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, hãy truyềnprompt_embedsthay thế. - negative_prompt (
strhoặclist[str], tùy chọn) — Prompt hoặc các prompt cần tránh trong quá trình tạo ảnh. Nếu không được định nghĩa, hãy truyềnnegative_prompt_embedsthay thế. Tham số này bị bỏ qua khi không sử dụng guidance (guidance_scale<1). - height (
int, mặc định là480) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là832) — 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à81) — 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. - guidance_scale (
float, mặc định là5.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_scale_2 (
float, tùy chọn, mặc định làNone) — Thang độ dẫn hướng cho transformer giai đoạn nhiễu thấp (transformer_2). NếuNonevàboundary_ratiocủa pipeline không phải None, sẽ sử dụng cùng giá trị vớiguidance_scale. Chỉ được sử dụng khitransformer_2vàboundary_ratiocủa pipeline không phải None. - 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. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding 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 (trọng số prompt). Nếu không được cung cấp,negative_prompt_embedssẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"np") — Định dạng đầu ra của hình ảnh được tạo. 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ộtWanPipelineOutputthay 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. - 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. - max_sequence_length (
int, mặc định là512) — Chiều dài tối đa của chuỗi cho bộ mã hóa văn bản. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn, nó sẽ được đệm (padding) đến chiều dài này.
Trả về
~WanPipelineOutput hoặc tuple
Nếu return_dict là True, WanPipelineOutput 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.utils import export_to_video
>>> from diffusers import AutoencoderKLWan, WanPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
>>> model_id = "Wan-AI/Wan2.1-T2V-14B-Diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 5.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> prompt = "A cat and a dog baking a cake together in a kitchen. The cat is carefully measuring flour, while the dog is stirring the batter with a wooden spoon. The kitchen is cozy, with sunlight streaming through the window."
>>> 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 = pipe(
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=720,
... width=1280,
... num_frames=81,
... guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - 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ếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - 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, vd. 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. - negative_prompt_embeds (
torch.Tensor, 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. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
WanImageToVideoPipeline
lớp diffusers.WanImageToVideoPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulerimage_processor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModel = Nonetransformer: WanTransformer3DModel = Nonetransformer_2: WanTransformer3DModel = Noneboundary_ratio: float | None = Noneexpand_timesteps: bool = False )
Tham số
- tokenizer (
T5Tokenizer) — Tokenizer từ T5, cụ thể là biến thể google/umt5-xxl. - text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/umt5-xxl. - image_encoder (
CLIPVisionModel) — CLIP, cụ thể là biến thể clip-vit-huge-patch14. - transformer (WanTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (UniPCMultistepScheduler) —
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 (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
- transformer_2 (WanTransformer3DModel, tùy chọn) —
Transformer có điều kiện để khử nhiễu các latents đầu vào trong giai đoạn nhiễu thấp. Trong khử nhiễu hai giai đoạn,
transformerxử lý các giai đoạn nhiễu cao vàtransformer_2xử lý các giai đoạn nhiễu thấp. Nếu không được cung cấp, chỉtransformerđược sử dụng. - boundary_ratio (
float, tuỳ chọn, mặc định làNone) — Tỷ lệ tổng số bước thời gian (timesteps) được sử dụng làm ranh giới để chuyển đổi giữa các transformer trong quá trình khử nhiễu hai giai đoạn. Bước thời gian ranh giới thực tế được tính bằngboundary_ratio * num_train_timesteps. Khi được cung cấp,transformerxử lý các bước thời gian >= boundary_timestep vàtransformer_2xử lý các bước thời gian < boundary_timestep. Nếu làNone, chỉtransformerđược sử dụng cho toàn bộ quá trình khử nhiễu.
Pipeline để tạo video từ hình ảnh sử dụng Wan.
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 >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]prompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneimage_embeds: typing.Optional[torch.Tensor] = Nonelast_image: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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 = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
Tham số
- image (
PipelineImageInput) — Hình ảnh đầu vào để điều kiện cho quá trình tạo. Phải là một hình ảnh, một danh sách các hình ảnh hoặc mộttorch.Tensor. - last_image (
torch.Tensor, tuỳ chọn) — Khung cuối cùng tuỳ chọn để điều kiện cho video được tạo. Khi được cung cấp, mô hình sẽ nội suy giữaimage(khung đầu tiên) vàlast_image(khung cuối cùng). - 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ế. - 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ếuguidance_scalenhỏ hơn1). - height (
int, mặc định là480) — Chiều cao của video được tạo ra. - width (
int, mặc định là832) — Chiều rộng của video được tạo ra. - num_frames (
int, mặc định là81) — 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. - guidance_scale (
float, mặc định là5.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_scale_2 (
float, tùy chọn, mặc định làNone) — Thang độ dẫn hướng cho transformer giai đoạn nhiễu thấp (transformer_2). NếuNonevàboundary_ratiocủa pipeline không phải None, sẽ sử dụng cùng giá trị vớiguidance_scale. Chỉ được sử dụng khitransformer_2vàboundary_ratiocủa pipeline không phải None. - 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. - negative_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àonegative_prompt. - image_embeds (
torch.Tensor, tùy chọn) — Các embedding hình ảnh đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh đầu vào hình ảnh (trọng số). Nếu không được cung cấp, các embedding hình ảnh sẽ được tạo từ đối số đầu vàoimage. - output_type (
str, tùy chọn, mặc định là"np") — Định dạng đầu ra của hình ảnh được tạo. 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ộtWanPipelineOutputthay 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. - 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. - max_sequence_length (
int, mặc định là512) — Chiều dài tối đa của chuỗi cho bộ mã hóa văn bản. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn, nó sẽ được đệm (padding) đến chiều dài này.
Trả về
~WanPipelineOutput hoặc tuple
Nếu return_dict là True, WanPipelineOutput 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
>>> import numpy as np
>>> from diffusers import AutoencoderKLWan, WanImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image
>>> from transformers import CLIPVisionModel
>>> # Available models: Wan-AI/Wan2.1-I2V-14B-480P-Diffusers, Wan-AI/Wan2.1-I2V-14B-720P-Diffusers
>>> model_id = "Wan-AI/Wan2.1-I2V-14B-480P-Diffusers"
>>> image_encoder = CLIPVisionModel.from_pretrained(
... model_id, subfolder="image_encoder", torch_dtype=torch.float32
... )
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanImageToVideoPipeline.from_pretrained(
... model_id, vae=vae, image_encoder=image_encoder, torch_dtype=torch.bfloat16
... )
>>> pipe.to("cuda")
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> max_area = 480 * 832
>>> aspect_ratio = image.height / image.width
>>> mod_value = pipe.vae_scale_factor_spatial * pipe.transformer.config.patch_size[1]
>>> height = round(np.sqrt(max_area * aspect_ratio)) // mod_value * mod_value
>>> width = round(np.sqrt(max_area / aspect_ratio)) // mod_value * mod_value
>>> image = image.resize((width, height))
>>> prompt = (
... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
... )
>>> 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 = pipe(
... image=image,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=height,
... width=width,
... num_frames=81,
... guidance_scale=5.0,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - 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ếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - 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, vd. 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. - negative_prompt_embeds (
torch.Tensor, 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. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
WanVACEPipeline
lớp diffusers.WanVACEPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteSchedulertransformer: WanVACETransformer3DModel = Nonetransformer_2: WanVACETransformer3DModel = Noneboundary_ratio: float | None = None )
Tham số
- tokenizer (
T5Tokenizer) — Tokenizer từ T5, cụ thể là biến thể google/umt5-xxl. - text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/umt5-xxl. - vae (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
- scheduler (UniPCMultistepScheduler) —
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. - transformer (
WanVACETransformer3DModel, tuỳ chọn) — Transformer có điều kiện để khử nhiễu các latents đầu vào trong giai đoạn nhiễu cao. Trong khử nhiễu hai giai đoạn,transformerxử lý các giai đoạn nhiễu cao vàtransformer_2xử lý các giai đoạn nhiễu thấp. Phải cung cấp ít nhất một trongtransformerhoặctransformer_2. - transformer_2 (
WanVACETransformer3DModel, tùy chọn) — Transformer có điều kiện để khử nhiễu các latents đầu vào trong giai đoạn nhiễu thấp. Trong khử nhiễu hai giai đoạn,transformerxử lý các giai đoạn nhiễu cao vàtransformer_2xử lý các giai đoạn nhiễu thấp. Phải cung cấp ít nhất một trongtransformerhoặctransformer_2. - boundary_ratio (
float, tùy chọn, mặc định làNone) — Tỷ lệ tổng số bước thời gian (timesteps) được sử dụng làm ranh giới để chuyển đổi giữa các transformer trong quá trình khử nhiễu hai giai đoạn. Bước thời gian ranh giới thực tế được tính bằngboundary_ratio * num_train_timesteps. Khi được cung cấp,transformerxử lý các bước thời gian >= boundary_timestep vàtransformer_2xử lý các bước thời gian < boundary_timestep. Nếu làNone, chỉ transformer khả dụng sẽ được sử dụng cho toàn bộ quá trình khử nhiễu.
Pipeline cho việc tạo ra có thể kiểm soát bằng Wan.
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] = Nonenegative_prompt: str | list[str] = Nonevideo: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Nonemask: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Nonereference_images: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneconditioning_scale: typing.Union[float, list[float], torch.Tensor] = 1.0height: int = 480width: int = 832num_frames: int = 81num_inference_steps: int = 50guidance_scale: float = 5.0guidance_scale_2: float | None = Nonenum_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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 = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput 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ế. - 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ếuguidance_scalenhỏ hơn1). - video (
list[PIL.Image.Image], optional) — Video đầu vào hoặc các video đầu vào được sử dụng làm điểm khởi đầu cho quá trình tạo. Video phải là một danh sách các hình ảnh PIL, một mảng numpy, hoặc một tensor torch. Hiện tại, pipeline chỉ hỗ trợ tạo một video tại một thời điểm. - mask (
list[PIL.Image.Image], tùy chọn) — Mặt nạ đầu vào xác định các vùng video cần điều kiện và các vùng cần tạo. Các vùng màu đen trong mặt nạ chỉ ra các vùng điều kiện, trong khi các vùng màu trắng chỉ ra các vùng để tạo. Mặt nạ phải là một danh sách các hình ảnh PIL, một mảng numpy, hoặc một tensor torch. Hiện tại chỉ hỗ trợ tạo một video tại một thời điểm. - reference_images (
list[PIL.Image.Image], tùy chọn) — Một danh sách gồm một hoặc nhiều hình ảnh tham chiếu để làm điều kiện bổ sung cho quá trình tạo. Ví dụ, nếu bạn đang cố gắng inpaint một video để thay đổi nhân vật, bạn có thể truyền các hình ảnh tham chiếu của nhân vật mới vào đây. Xem các ví dụ của Diffusers và hướng dẫn sử dụng gốc để biết danh sách đầy đủ các tác vụ và trường hợp sử dụng được hỗ trợ. - conditioning_scale (
float,list[float],torch.Tensor, mặc định là1.0) — Thang độ điều kiện (conditioning scale) được áp dụng khi thêm luồng latent điều khiển (control conditioning latent stream) vào luồng latent khử nhiễu (denoising latent stream) trong mỗi lớp điều khiển (control layer) của mô hình. Nếu một giá trị float được cung cấp, nó sẽ được áp dụng đồng đều cho tất cả các lớp. Nếu một danh sách hoặc tensor được cung cấp, nó phải có cùng độ dài với số lượng lớp điều khiển trong mô hình (len(transformer.config.vace_layers)). - height (
int, mặc định là480) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là832) — 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à81) — 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. - guidance_scale (
float, mặc định là5.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - guidance_scale_2 (
float, tùy chọn, mặc định làNone) — Thang độ dẫn hướng cho transformer giai đoạn nhiễu thấp (transformer_2). NếuNonevàboundary_ratiocủa pipeline không phải None, sẽ sử dụng cùng giá trị vớiguidance_scale. Chỉ được sử dụng khitransformer_2vàboundary_ratiocủa pipeline không phải None. - 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. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding 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 (trọng số prompt). Nếu không được cung cấp,negative_prompt_embedssẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"np") — Định dạng đầu ra của hình ảnh được tạo. 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ộtWanPipelineOutputthay 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. - 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. - max_sequence_length (
int, mặc định là512) — Chiều dài tối đa của chuỗi cho bộ mã hóa văn bản. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn, nó sẽ được đệm (padding) đến chiều dài này.
Trả về
~WanPipelineOutput hoặc tuple
Nếu return_dict là True, WanPipelineOutput 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
>>> import PIL.Image
>>> from diffusers import AutoencoderKLWan, WanVACEPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> from diffusers.utils import export_to_video, load_image
def prepare_video_and_mask(first_img: PIL.Image.Image, last_img: PIL.Image.Image, height: int, width: int, num_frames: int):
first_img = first_img.resize((width, height))
last_img = last_img.resize((width, height))
frames = []
frames.append(first_img)
# Ideally, this should be 127.5 to match original code, but they perform computation on numpy arrays
# whereas we are passing PIL images. If you choose to pass numpy arrays, you can set it to 127.5 to
# match the original code.
frames.extend([PIL.Image.new("RGB", (width, height), (128, 128, 128))] * (num_frames - 2))
frames.append(last_img)
mask_black = PIL.Image.new("L", (width, height), 0)
mask_white = PIL.Image.new("L", (width, height), 255)
mask = [mask_black, *[mask_white] * (num_frames - 2), mask_black]
return frames, mask
>>> # Available checkpoints: Wan-AI/Wan2.1-VACE-1.3B-diffusers, Wan-AI/Wan2.1-VACE-14B-diffusers
>>> model_id = "Wan-AI/Wan2.1-VACE-1.3B-diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanVACEPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> prompt = "CG animation style, a small blue bird takes off from the ground, flapping its wings. The bird's feathers are delicate, with a unique pattern on its chest. The background shows a blue sky with white clouds under bright sunshine. The camera follows the bird upward, capturing its flight and the vastness of the sky from a close-up, low-angle perspective."
>>> 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"
>>> first_frame = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_first_frame.png"
... )
>>> last_frame = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/flf2v_input_last_frame.png>>> "
... )
>>> height = 512
>>> width = 512
>>> num_frames = 81
>>> video, mask = prepare_video_and_mask(first_frame, last_frame, height, width, num_frames)
>>> output = pipe(
... video=video,
... mask=mask,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=height,
... width=width,
... num_frames=num_frames,
... num_inference_steps=30,
... guidance_scale=5.0,
... generator=torch.Generator().manual_seed(42),
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - 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ếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - 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, vd. 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. - negative_prompt_embeds (
torch.Tensor, 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. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
WanVideoToVideoPipeline
lớp diffusers.WanVideoToVideoPipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModeltransformer: WanTransformer3DModelvae: AutoencoderKLWanscheduler: FlowMatchEulerDiscreteScheduler )
Tham số
- tokenizer (
T5Tokenizer) — Tokenizer từ T5, cụ thể là biến thể google/umt5-xxl. - text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/umt5-xxl. - transformer (WanTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (UniPCMultistepScheduler) —
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 (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
Pipeline để tạo video từ video sử dụng Wan.
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 >( video: list = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 480width: int = 832num_inference_steps: int = 50timesteps: list[int] | None = Noneguidance_scale: float = 5.0strength: float = 0.8num_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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'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 = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
Tham số
- video (
list[PIL.Image.Image]) — Video đầu vào được sử dụng làm điểm khởi đầu cho quá trình tạo video từ video. Video nên được cung cấp dưới dạng danh sách các hình ảnh PIL, mảng numpy hoặc tensor torch. - 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ế. - 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ếuguidance_scalenhỏ hơn1). - height (
int, mặc định là480) — Chiều cao của hình ảnh được tạo ra, tính bằng pixel. - width (
int, mặc định là832) — Chiều rộng của hình ảnh được tạo ra, tính bằng pixel. - 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. - timesteps (
list[int], tùy chọn) — Các bước thời gian 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ốtimestepstrong 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 vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần. - guidance_scale (
float, mặc định là5.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. - strength (
float, mặc định là0.8) — Giá trị strength cao hơn sẽ dẫn đến nhiều khác biệt hơn giữa hình ảnh gốc và video được tạo ra. - 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. - negative_prompt_embeds (
torch.Tensor, tùy chọn) — Các embedding 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 (trọng số prompt). Nếu không được cung cấp,negative_prompt_embedssẽ được tạo từ đối số đầu vàonegative_prompt. - output_type (
str, tùy chọn, mặc định là"np") — Định dạng đầu ra của hình ảnh được tạo. 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ộtWanPipelineOutputthay 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. - 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. - max_sequence_length (
int, mặc định là512) — Chiều dài tối đa của chuỗi cho bộ mã hóa văn bản. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn, nó sẽ được đệm (padding) đến chiều dài này.
Trả về
~WanPipelineOutput hoặc tuple
Nếu return_dict là True, WanPipelineOutput 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.utils import export_to_video, load_video
>>> from diffusers import AutoencoderKLWan, WanVideoToVideoPipeline
>>> from diffusers.schedulers.scheduling_unipc_multistep import UniPCMultistepScheduler
>>> # Available models: Wan-AI/Wan2.1-T2V-14B-Diffusers, Wan-AI/Wan2.1-T2V-1.3B-Diffusers
>>> model_id = "Wan-AI/Wan2.1-T2V-1.3B-Diffusers"
>>> vae = AutoencoderKLWan.from_pretrained(model_id, subfolder="vae", torch_dtype=torch.float32)
>>> pipe = WanVideoToVideoPipeline.from_pretrained(model_id, vae=vae, torch_dtype=torch.bfloat16)
>>> flow_shift = 3.0 # 5.0 for 720P, 3.0 for 480P
>>> pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config, flow_shift=flow_shift)
>>> pipe.to("cuda")
>>> prompt = "A robot standing on a mountain top. The sun is setting in the background"
>>> 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"
>>> video = load_video(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
... )
>>> output = pipe(
... video=video,
... prompt=prompt,
... negative_prompt=negative_prompt,
... height=480,
... width=720,
... guidance_scale=5.0,
... strength=0.7,
... ).frames[0]
>>> export_to_video(output, "output.mp4", fps=16)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - 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ếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - 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, vd. 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. - negative_prompt_embeds (
torch.Tensor, 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. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
WanAnimatePipeline
lớp diffusers.WanAnimatePipeline
< source >( tokenizer: AutoTokenizertext_encoder: UMT5EncoderModelvae: AutoencoderKLWanscheduler: UniPCMultistepSchedulerimage_processor: CLIPImageProcessorPilimage_encoder: CLIPVisionModeltransformer: WanAnimateTransformer3DModel )
Tham số
- tokenizer (
T5Tokenizer) — Tokenizer từ T5, cụ thể là biến thể google/umt5-xxl. - text_encoder (
T5EncoderModel) — T5, cụ thể là biến thể google/umt5-xxl. - image_encoder (
CLIPVisionModel) — CLIP, cụ thể là biến thể clip-vit-huge-patch14. - transformer (WanAnimateTransformer3DModel) — Transformer có điều kiện để khử nhiễu các latents đầu vào.
- scheduler (UniPCMultistepScheduler) —
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 (AutoencoderKLWan) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã video từ và sang các biểu diễn ẩn (latent representations).
- image_processor (
CLIPImageProcessor) — Bộ xử lý ảnh để tiền xử lý ảnh trước khi mã hóa.
Quy trình cho hoạt hình hóa và thay thế nhân vật thống nhất sử dụng Wan-Animate.
WanAnimatePipeline nhận một ảnh nhân vật, video tư thế và video khuôn mặt làm đầu vào, và tạo ra video theo hai
Chế độ hoạt hình: Mô hình tạo ra một video của hình ảnh nhân vật mô phỏng chuyển động của con người trong video tư thế và khuôn mặt đầu vào. Nhân vật được hoạt hình hóa dựa trên các điều khiển chuyển động được cung cấp, tạo ra một video hoạt hình mới của nhân vật.
Chế độ thay thế: Mô hình thay thế một nhân vật trong video nền bằng hình ảnh nhân vật được cung cấp, sử dụng video tư thế và khuôn mặt để kiểm soát chuyển động. Chế độ này yêu cầu các đầu vào bổ sung
background_videovàmask_video. Video mask phải có các vùng màu đen ở nơi nội dung gốc cần được giữ nguyên và các vùng màu trắng ở nơi nhân vật mới sẽ được tạo ra.
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.).
Pipeline cũng kế thừa các phương thức nạp sau:
- load_lora_weights() để nạp trọng số LoRA
__call__
< source >( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]pose_video: listface_video: listbackground_video: list[PIL.Image.Image] | None = Nonemask_video: list[PIL.Image.Image] | None = Noneprompt: str | list[str] = Nonenegative_prompt: str | list[str] = Noneheight: int = 720width: int = 1280segment_frame_length: int = 77num_inference_steps: int = 20mode: str = 'animate'prev_segment_conditioning_frames: int = 1motion_encode_batch_size: int | None = Noneguidance_scale: float = 1.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] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneimage_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str | None = 'np'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int, NoneType], diffusers.callbacks.PipelineCallback | diffusers.callbacks.MultiPipelineCallbacks]] = Nonecallback_on_step_end_tensor_inputs: list = ['latents']max_sequence_length: int = 512 ) → ~WanPipelineOutput or tuple
Tham số
- image (
PipelineImageInput) — Ảnh nhân vật đầu vào để điều kiện cho quá trình tạo. Phải là một ảnh, một danh sách các ảnh hoặc mộttorch.Tensor. - pose_video (
list[PIL.Image.Image]) — Video tư thế đầu vào để điều kiện cho quá trình tạo. Phải là một danh sách các hình ảnh PIL. - face_video (
list[PIL.Image.Image]) — Video khuôn mặt đầu vào để điều kiện cho quá trình tạo. Phải là một danh sách các hình ảnh PIL. - background_video (
list[PIL.Image.Image], tùy chọn) — Khi mode là"replace", video nền đầu vào để điều kiện hóa quá trình tạo. Phải là một danh sách các hình ảnh PIL. - mask_video (
list[PIL.Image.Image], tuỳ chọn) — Khi mode là"replace", video mask đầu vào để điều kiện cho quá trình tạo. Phải là một danh sách các hình ảnh PIL. - 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ế. - 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ếuguidance_scalenhỏ hơn1). - mode (
str, mặc định là"animation") — Chế độ của quá trình tạo. Chọn giữa"animate"và"replace". - prev_segment_conditioning_frames (
int, mặc định là1) — Số lượng khung hình từ đoạn video trước được sử dụng để hướng dẫn theo thời gian. Khuyến nghị là 1 hoặc 5. Nhìn chung, nên là 4N + 1, trong đó N là một số nguyên không âm. - motion_encode_batch_size (
int, tùy chọn) — Kích thước lô (batch size) cho việc mã hóa theo lô video khuôn mặt thông qua motion encoder. Điều này cho phép đánh đổi tốc độ suy luận để giảm mức sử dụng bộ nhớ bằng cách đặt kích thước lô nhỏ hơn. Nếu không được đặt, giá trị mặc định sẽ làself.transformer.config.motion_encoder_batch_size. - height (
int, mặc định là720) — Chiều cao của video được tạo ra. - width (
int, mặc định là1280) — Chiều rộng của video được tạo ra. - segment_frame_length (
int, mặc định là77) — Số lượng khung hình trong mỗi đoạn video được tạo ra. Tổng số khung hình của video được tạo sẽ bằng số lượng khung hình trongpose_video; chúng ta sẽ tạo video theo từng đoạn cho đến khi đạt được độ dài này. Nhìn chung, giá trị này nên là 4N + 1, trong đó N là một số nguyên không âm. - num_inference_steps (
int, mặc định là20) — 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. - guidance_scale (
float, mặc định là1.0) — Thang độ dẫn hướng như được định nghĩa trong Classifier-Free Diffusion Guidance.guidance_scaleđược định nghĩa làwcủa phương trình 2. trong Imagen Paper. Thang độ dẫn hướng được kích hoạt bằng cách đặtguidance_scale > 1. Thang độ dẫn hướng cao hơn khuyến khích tạo ra các hình ảnh gắn kết chặt chẽ vớipromptvăn bản, thường phải đánh đổi bằng chất lượng hình ảnh thấp hơn. Mặc định, CFG không được sử dụng trong suy luận Wan Animate. - 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. - negative_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àonegative_prompt. - image_embeds (
torch.Tensor, tùy chọn) — Các embedding hình ảnh đã được tạo trước. Có thể được sử dụng để dễ dàng điều chỉnh đầu vào hình ảnh (trọng số). Nếu không được cung cấp, các embedding hình ảnh sẽ được tạo từ đối số đầu vàoimage. - output_type (
str, tùy chọn, mặc định là"np") — Định dạng đầu ra của hình ảnh được tạo. 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ộtWanPipelineOutputthay 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. - 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. - max_sequence_length (
int, mặc định là512) — Chiều dài tối đa của chuỗi cho bộ mã hóa văn bản. Nếu prompt dài hơn giá trị này, nó sẽ bị cắt bớt. Nếu prompt ngắn hơn, nó sẽ được đệm (padding) đến chiều dài này.
Trả về
~WanPipelineOutput hoặc tuple
Nếu return_dict là True, WanPipelineOutput 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
>>> import numpy as np
>>> from diffusers import WanAnimatePipeline
>>> from diffusers.utils import export_to_video, load_image, load_video
>>> model_id = "Wan-AI/Wan2.2-Animate-14B-Diffusers"
>>> pipe = WanAnimatePipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
>>> # Optionally upcast the Wan VAE to FP32
>>> pipe.vae.to(torch.float32)
>>> pipe.to("cuda")
>>> # Load the reference character image
>>> image = load_image(
... "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> # Load pose and face videos (preprocessed from reference video)
>>> # Note: Videos should be preprocessed to extract pose keypoints and face features
>>> # Refer to the Wan-Animate preprocessing documentation for details
>>> pose_video = load_video("path/to/pose_video.mp4")
>>> face_video = load_video("path/to/face_video.mp4")
>>> # CFG is generally not used for Wan Animate
>>> prompt = (
... "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in "
... "the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
... )
>>> # Animation mode: Animate the character with the motion from pose/face videos
>>> output = pipe(
... image=image,
... pose_video=pose_video,
... face_video=face_video,
... prompt=prompt,
... height=height,
... width=width,
... segment_frame_length=77, # Frame length of each inference segment
... guidance_scale=1.0,
... num_inference_steps=20,
... mode="animate",
... ).frames[0]
>>> export_to_video(output, "output_animation.mp4", fps=30)
>>> # Replacement mode: Replace a character in the background video
>>> # Requires additional background_video and mask_video inputs
>>> background_video = load_video("path/to/background_video.mp4")
>>> mask_video = load_video("path/to/mask_video.mp4") # Black areas preserved, white areas generated
>>> output = pipe(
... image=image,
... pose_video=pose_video,
... face_video=face_video,
... background_video=background_video,
... mask_video=mask_video,
... prompt=prompt,
... height=height,
... width=width,
... segment_frame_length=77, # Frame length of each inference segment
... guidance_scale=1.0,
... num_inference_steps=20,
... mode="replace",
... ).frames[0]
>>> export_to_video(output, "output_replacement.mp4", fps=30)encode_prompt
< source >( prompt: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )
Tham số
- prompt (
strhoặclist[str], tùy chọn) — prompt cần được mã hóa - 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ếuguidance_scalenhỏ hơn1). - do_classifier_free_guidance (
bool, tùy chọn, mặc định làTrue) — Có sử dụng classifier free guidance hay không. - num_videos_per_prompt (
int, tùy chọn, mặc định là 1) — Số lượng video cần được tạo cho mỗi prompt. torch device để đặt các embeddings kết quả - 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, vd. 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. - negative_prompt_embeds (
torch.Tensor, 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. - device — (
torch.device, tùy chọn): thiết bị torch - dtype — (
torch.dtype, tùy chọn): torch dtype
Mã hóa prompt thành các trạng thái ẩn của text encoder.
Đệm mảng video dạng frames lên num_target_frames bằng chiến lược kiểu “reflect”. Chiều khung hình được giả định là chiều đầu tiên. Trong trường hợp 1 chiều, chúng ta có thể hình dung chiến lược này như sau:
pad_video_frames([1, 2, 3, 4, 5], 10) -> [1, 2, 3, 4, 5, 4, 3, 2, 1, 2]
WanPipelineOutput
lớp diffusers.pipelines.wan.pipeline_output.WanPipelineOutput
< 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 Wan.