Diffusers documentation

Tạo Video từ Văn bản với AnimateDiff

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Tạo Video từ Văn bản với AnimateDiff

LoRA

Tổng quan

AnimateDiff: Animate Your Personalized Text-to-Image Diffusion Models without Specific Tuning của Yuwei Guo, Ceyuan Yang, Anyi Rao, Yaohui Wang, Yu Qiao, Dahua Lin, Bo Dai.

Tóm tắt của bài báo như sau:

Với sự phát triển của các mô hình text-to-image (ví dụ: Stable Diffusion) và các kỹ thuật cá nhân hóa tương ứng như DreamBooth và LoRA, bất kỳ ai cũng có thể hiện thực hóa trí tưởng tượng của mình thành các hình ảnh chất lượng cao với chi phí hợp lý. Tiếp theo đó, nhu cầu về các kỹ thuật tạo chuyển động cho hình ảnh ngày càng lớn nhằm kết hợp thêm động lực chuyển động với các hình ảnh tĩnh đã được tạo ra. Trong báo cáo này, chúng tôi đề xuất một khung làm việc thực tiễn để tạo chuyển động cho hầu hết các mô hình text-to-image cá nhân hóa hiện có một cách triệt để, giúp tiết kiệm công sức trong việc tinh chỉnh riêng cho từng mô hình. Nền tảng cốt lõi của khung làm việc được đề xuất là chèn một module mô hình hóa chuyển động mới được khởi tạo vào mô hình text-to-image đã đóng băng và huấn luyện nó trên các đoạn video để chưng cất các tiên nghiệm chuyển động hợp lý. Sau khi huấn luyện, chỉ cần tiêm module mô hình hóa chuyển động này, tất cả các phiên bản cá nhân hóa được dẫn xuất từ cùng một mô hình T2I cơ sở sẽ dễ dàng trở thành các mô hình điều khiển bằng văn bản, tạo ra các hình ảnh động đa dạng và mang tính cá nhân hóa. Chúng tôi tiến hành đánh giá trên một số mô hình text-to-image cá nhân hóa đại diện công khai, trải qua các bức ảnh anime và ảnh chụp chân thực, và chứng minh rằng khung làm việc do chúng tôi đề xuất giúp các mô hình này tạo ra các đoạn phim hoạt hình mượt mà theo thời gian trong khi vẫn giữ nguyên lĩnh vực và sự đa dạng của đầu ra. Mã nguồn và trọng số được huấn luyện trước sẽ được công bố công khai tại this https URL.

Các Pipeline khả dụng

PipelineNhiệm vụDemo
AnimateDiffPipelineĐánh giá khả năng tạo video từ văn bản với AnimateDiff
AnimateDiffControlNetPipelineTạo video từ video có kiểm soát bằng AnimateDiff sử dụng ControlNet
AnimateDiffSparseControlNetPipelineTạo video từ video có kiểm soát với AnimateDiff sử dụng SparseCtrl
AnimateDiffSDXLPipelineTạo video từ video với AnimateDiff
AnimateDiffVideoToVideoPipelineTạo video từ video với AnimateDiff
AnimateDiffVideoToVideoControlNetPipelineTạo Video từ Video bằng AnimateDiff sử dụng ControlNet

Các checkpoint khả dụng

Các checkpoint của Motion Adapter có thể được tìm thấy dưới guoyww. Các checkpoint này được thiết kế để hoạt động với bất kỳ mô hình nào dựa trên Stable Diffusion 1.4/1.5.

Ví dụ sử dụng

AnimateDiffPipeline

AnimateDiff hoạt động với một checkpoint MotionAdapter và một checkpoint mô hình Stable Diffusion. MotionAdapter là một tập hợp các Motion Module chịu trách nhiệm thêm chuyển động nhất quán giữa các khung hình. Các module này được áp dụng sau các khối Resnet và Attention trong UNet của Stable Diffusion.

Ví dụ sau minh họa cách sử dụng checkpoint MotionAdapter với Diffusers để suy luận dựa trên StableDiffusion-1.4/1.5.

import torch
from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

# Load the motion adapter
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2", dtype=torch.float16)
# load SD 1.5 based finetuned model
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffPipeline.from_pretrained(model_id, motion_adapter=adapter, dtype=torch.float16)
scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    timestep_spacing="linspace",
    beta_schedule="linear",
    steps_offset=1,
)
pipe.scheduler = scheduler

# enable memory savings
pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt=(
        "masterpiece, bestquality, highlydetailed, ultradetailed, sunset, "
        "orange sky, warm lighting, fishing boats, ocean waves seagulls, "
        "rippling water, wharf, silhouette, serene atmosphere, dusk, evening glow, "
        "golden hour, coastal landscape, seaside scenery"
    ),
    negative_prompt="bad quality, worse quality",
    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=25,
    generator=torch.Generator("cpu").manual_seed(42),
)
frames = output.frames[0]
export_to_gif(frames, "animation.gif")

Dưới đây là một số kết quả mẫu:

tác phẩm, chất lượng tốt nhất, hoàng hôn.
masterpiece, bestquality, sunset

AnimateDiff thường hoạt động tốt hơn với các mô hình Stable Diffusion đã được tinh chỉnh. Nếu bạn dự định sử dụng một scheduler có khả năng cắt mẫu (clip samples), hãy đảm bảo tắt tính năng này bằng cách đặt clip_sample=False trong scheduler, vì điều này cũng có thể gây ảnh hưởng tiêu cực đến các mẫu được tạo ra. Ngoài ra, các checkpoint của AnimateDiff có thể nhạy cảm với lịch beta (beta schedule) của scheduler. Chúng tôi khuyến nghị đặt giá trị này thành linear.

AnimateDiffControlNetPipeline

AnimateDiff cũng có thể được sử dụng cùng với ControlNet. ControlNet được giới thiệu trong Adding Conditional Control to Text-to-Image Diffusion Models bởi Lvmin Zhang, Anyi Rao và Maneesh Agrawala. Với một mô hình ControlNet, bạn có thể cung cấp một hình ảnh điều khiển bổ sung để điều kiện hóa và kiểm soát quá trình tạo nội dung của Stable Diffusion. Ví dụ, nếu bạn cung cấp các bản đồ độ sâu, mô hình ControlNet sẽ tạo ra một video giữ nguyên thông tin không gian từ các bản đồ độ sâu đó. Đây là một cách linh hoạt và chính xác hơn để kiểm soát quá trình tạo video.

import torch
from diffusers import AnimateDiffControlNetPipeline, AutoencoderKL, ControlNetModel, MotionAdapter, LCMScheduler
from diffusers.utils import export_to_gif, load_video

# Additionally, you will need a preprocess videos before they can be used with the ControlNet
# HF maintains just the right package for it: `pip install controlnet_aux`
from controlnet_aux.processor import ZoeDetector

# Download controlnets from https://huggingface.co/lllyasviel/ControlNet-v1-1 to use .from_single_file
# Download Diffusers-format controlnets, such as https://huggingface.co/lllyasviel/sd-controlnet-depth, to use .from_pretrained()
controlnet = ControlNetModel.from_single_file("control_v11f1p_sd15_depth.pth", dtype=torch.float16)

# We use AnimateLCM for this example but one can use the original motion adapters as well (for example, https://huggingface.co/guoyww/animatediff-motion-adapter-v1-5-3)
motion_adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM")

vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", dtype=torch.float16)
pipe: AnimateDiffControlNetPipeline = AnimateDiffControlNetPipeline.from_pretrained(
    "SG161222/Realistic_Vision_V5.1_noVAE",
    motion_adapter=motion_adapter,
    controlnet=controlnet,
    vae=vae,
).to(device="cuda", dtype=torch.float16)  # or "mps", "xpu", "cpu"
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")
pipe.load_lora_weights("wangfuyun/AnimateLCM", weight_name="AnimateLCM_sd15_t2v_lora.safetensors", adapter_name="lcm-lora")
pipe.set_adapters(["lcm-lora"], [0.8])

depth_detector = ZoeDetector.from_pretrained("lllyasviel/Annotators").to("cuda")
video = load_video("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-vid2vid-input-1.gif")
conditioning_frames = []

with pipe.progress_bar(total=len(video)) as progress_bar:
    for frame in video:
        conditioning_frames.append(depth_detector(frame))
        progress_bar.update()

prompt = "a panda, playing a guitar, sitting in a pink boat, in the ocean, mountains in background, realistic, high quality"
negative_prompt = "bad quality, worst quality"

video = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=len(video),
    num_inference_steps=10,
    guidance_scale=2.0,
    conditioning_frames=conditioning_frames,
    generator=torch.Generator().manual_seed(42),
).frames[0]

export_to_gif(video, "animatediff_controlnet.gif", fps=8)

Dưới đây là một số kết quả mẫu:

Video nguồnVideo đầu ra
cáo rửa chén chơi guitar
racoon playing a guitar
một con gấu trúc, đang chơi guitar, ngồi trên một chiếc thuyền màu hồng, giữa đại dương, núi non ở phía sau, chân thực, chất lượng cao
a panda, playing a guitar, sitting in a pink boat, in the ocean, mountains in background, realistic, high quality

AnimateDiffSparseControlNetPipeline

SparseCtrl: Thêm các điều khiển thưa vào các mô hình khuếch tán từ văn bản sang video để đạt được sinh có kiểm soát trong các mô hình khuếch tán từ văn bản sang video của Yuwei Guo, Ceyuan Yang, Anyi Rao, Maneesh Agrawala, Dahua Lin và Bo Dai.

Tóm tắt từ bài báo là:

Việc phát triển text-to-video (T2V), tức là tạo video từ một prompt văn bản cho trước, đã được thúc đẩy đáng kể trong những năm gần đây. Tuy nhiên, việc chỉ dựa vào prompt văn bản thường dẫn đến bố cục khung hình mơ hồ do sự không chắc chắn về không gian. Do đó, cộng đồng nghiên cứu tận dụng các tín hiệu cấu trúc dày đặc, chẳng hạn như chuỗi depth/edge cho từng khung hình, để tăng cường khả năng kiểm soát, nhưng việc thu thập các tín hiệu này làm tăng gánh nặng suy luận. Trong công trình này, chúng tôi giới thiệu SparseCtrl để cho phép kiểm soát cấu trúc linh hoạt bằng các tín hiệu thưa theo thời gian, chỉ yêu cầu một hoặc một vài đầu vào, như minh họa trong Hình 1. Phương pháp này tích hợp một bộ mã hóa điều kiện bổ sung để xử lý các tín hiệu thưa này trong khi giữ nguyên mô hình T2V đã được huấn luyện trước. Cách tiếp cận đề xuất tương thích với nhiều loại dữ liệu khác nhau, bao gồm phác thảo, bản đồ depth và hình ảnh RGB, cung cấp khả năng kiểm soát thực tế hơn cho việc tạo video và thúc đẩy các ứng dụng như storyboarding, depth rendering, keyframe animation và nội suy. Các thí nghiệm rộng rãi chứng minh khả năng tổng quát hóa của SparseCtrl trên cả các bộ tạo T2V gốc và T2V cá nhân hóa. Mã nguồn và mô hình sẽ được công bố công khai tại this https URL.

SparseCtrl giới thiệu các checkpoint sau cho việc tạo video từ văn bản có kiểm soát:

Sử dụng SparseCtrl Scribble

import torch

from diffusers import AnimateDiffSparseControlNetPipeline
from diffusers.models import AutoencoderKL, MotionAdapter, SparseControlNetModel
from diffusers.schedulers import DPMSolverMultistepScheduler
from diffusers.utils import export_to_gif, load_image


model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-3"
controlnet_id = "guoyww/animatediff-sparsectrl-scribble"
lora_adapter_id = "guoyww/animatediff-motion-lora-v1-5-3"
vae_id = "stabilityai/sd-vae-ft-mse"
device = "cuda"  # or "mps", "xpu", "cpu"

motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id, dtype=torch.float16).to(device)
controlnet = SparseControlNetModel.from_pretrained(controlnet_id, dtype=torch.float16).to(device)
vae = AutoencoderKL.from_pretrained(vae_id, dtype=torch.float16).to(device)
scheduler = DPMSolverMultistepScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    beta_schedule="linear",
    algorithm_type="dpmsolver++",
    use_karras_sigmas=True,
)
pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
    model_id,
    motion_adapter=motion_adapter,
    controlnet=controlnet,
    vae=vae,
    scheduler=scheduler,
    dtype=torch.float16,
).to(device)
pipe.load_lora_weights(lora_adapter_id, adapter_name="motion_lora")
pipe.fuse_lora(lora_scale=1.0)

prompt = "an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality"
negative_prompt = "low quality, worst quality, letterboxed"

image_files = [
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-1.png",
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-2.png",
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-3.png"
]
condition_frame_indices = [0, 8, 15]
conditioning_frames = [load_image(img_file) for img_file in image_files]

video = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_inference_steps=25,
    conditioning_frames=conditioning_frames,
    controlnet_conditioning_scale=1.0,
    controlnet_frame_indices=condition_frame_indices,
    generator=torch.Generator().manual_seed(1337),
).frames[0]
export_to_gif(video, "output.gif")

Dưới đây là một số kết quả mẫu:

an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality
scribble-1
scribble-2
scribble-3
an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality

Sử dụng SparseCtrl RGB

import torch

from diffusers import AnimateDiffSparseControlNetPipeline
from diffusers.models import AutoencoderKL, MotionAdapter, SparseControlNetModel
from diffusers.schedulers import DPMSolverMultistepScheduler
from diffusers.utils import export_to_gif, load_image


model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-3"
controlnet_id = "guoyww/animatediff-sparsectrl-rgb"
lora_adapter_id = "guoyww/animatediff-motion-lora-v1-5-3"
vae_id = "stabilityai/sd-vae-ft-mse"
device = "cuda"  # or "mps", "xpu", "cpu"

motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id, dtype=torch.float16).to(device)
controlnet = SparseControlNetModel.from_pretrained(controlnet_id, dtype=torch.float16).to(device)
vae = AutoencoderKL.from_pretrained(vae_id, dtype=torch.float16).to(device)
scheduler = DPMSolverMultistepScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    beta_schedule="linear",
    algorithm_type="dpmsolver++",
    use_karras_sigmas=True,
)
pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
    model_id,
    motion_adapter=motion_adapter,
    controlnet=controlnet,
    vae=vae,
    scheduler=scheduler,
    dtype=torch.float16,
).to(device)
pipe.load_lora_weights(lora_adapter_id, adapter_name="motion_lora")

image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-firework.png")

video = pipe(
    prompt="closeup face photo of man in black clothes, night city street, bokeh, fireworks in background",
    negative_prompt="low quality, worst quality",
    num_inference_steps=25,
    conditioning_frames=image,
    controlnet_frame_indices=[0],
    controlnet_conditioning_scale=1.0,
    generator=torch.Generator().manual_seed(42),
).frames[0]
export_to_gif(video, "output.gif")

Dưới đây là một số kết quả mẫu:

closeup face photo of man in black clothes, night city street, bokeh, fireworks in background
closeup face photo of man in black clothes, night city street, bokeh, fireworks in background
closeup face photo of man in black clothes, night city street, bokeh, fireworks in background

AnimateDiffSDXLPipeline

AnimateDiff cũng có thể được sử dụng với các mô hình SDXL. Đây hiện là một tính năng thử nghiệm vì chỉ có bản phát hành beta của checkpoint bộ thích ứng chuyển động.

import torch
from diffusers.models import MotionAdapter
from diffusers import AnimateDiffSDXLPipeline, DDIMScheduler
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-sdxl-beta", dtype=torch.float16)

model_id = "stabilityai/stable-diffusion-xl-base-1.0"
scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    timestep_spacing="linspace",
    beta_schedule="linear",
    steps_offset=1,
)
pipe = AnimateDiffSDXLPipeline.from_pretrained(
    model_id,
    motion_adapter=adapter,
    scheduler=scheduler,
    dtype=torch.float16,
    variant="fp16",
).to("cuda")  # or "mps", "xpu", "cpu"

# enable memory savings
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

output = pipe(
    prompt="a panda surfing in the ocean, realistic, high quality",
    negative_prompt="low quality, worst quality",
    num_inference_steps=20,
    guidance_scale=8,
    width=1024,
    height=1024,
    num_frames=16,
)

frames = output.frames[0]
export_to_gif(frames, "animation.gif")

AnimateDiffVideoToVideoPipeline

AnimateDiff cũng có thể được sử dụng để tạo ra các video có ngoại hình tương tự hoặc cho phép chỉnh sửa phong cách/đặc điểm nhân vật/nền hoặc các yếu tố khác bắt đầu từ một video ban đầu, giúp bạn khám phá liền mạch các khả năng sáng tạo.

import imageio
import requests
import torch
from diffusers import AnimateDiffVideoToVideoPipeline, DDIMScheduler, MotionAdapter
from diffusers.utils import export_to_gif
from io import BytesIO
from PIL import Image

# Load the motion adapter
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2", dtype=torch.float16)
# load SD 1.5 based finetuned model
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffVideoToVideoPipeline.from_pretrained(model_id, motion_adapter=adapter, dtype=torch.float16)
scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    timestep_spacing="linspace",
    beta_schedule="linear",
    steps_offset=1,
)
pipe.scheduler = scheduler

# enable memory savings
pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

# helper function to load videos
def load_video(file_path: str):
    images = []

    if file_path.startswith(('http://', 'https://')):
        # If the file_path is a URL
        response = requests.get(file_path)
        response.raise_for_status()
        content = BytesIO(response.content)
        vid = imageio.get_reader(content)
    else:
        # Assuming it's a local file path
        vid = imageio.get_reader(file_path)

    for frame in vid:
        pil_image = Image.fromarray(frame)
        images.append(pil_image)

    return images

video = load_video("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-vid2vid-input-1.gif")

output = pipe(
    video = video,
    prompt="panda playing a guitar, on a boat, in the ocean, high quality",
    negative_prompt="bad quality, worse quality",
    guidance_scale=7.5,
    num_inference_steps=25,
    strength=0.5,
    generator=torch.Generator("cpu").manual_seed(42),
)
frames = output.frames[0]
export_to_gif(frames, "animation.gif")

Dưới đây là một số kết quả mẫu:

Video nguồnVideo đầu ra
cáo rửa chén chơi guitar
racoon playing a guitar
panda đang chơi guitar
panda playing a guitar
chụp cận cảnh Margot Robbie, pháo hoa ở phía sau, chất lượng cao
closeup of margot robbie, fireworks in the background, high quality
chụp cận cảnh tony stark, robert downey jr, pháo hoa
closeup of tony stark, robert downey jr, fireworks

AnimateDiffVideoToVideoControlNetPipeline

AnimateDiff có thể được sử dụng cùng với ControlNets để tăng cường quá trình tạo video từ video bằng cách cho phép kiểm soát chính xác đầu ra. ControlNet được giới thiệu trong Adding Conditional Control to Text-to-Image Diffusion Models bởi Lvmin Zhang, Anyi Rao và Maneesh Agrawala, cho phép bạn điều kiện hóa Stable Diffusion bằng một hình ảnh điều khiển bổ sung để đảm bảo thông tin không gian được duy trì xuyên suốt video.

Pipeline này cho phép bạn điều kiện hóa quá trình tạo của mình dựa trên cả video gốc và một chuỗi hình ảnh điều khiển.

import torch
from PIL import Image
from tqdm.auto import tqdm

from controlnet_aux.processor import OpenposeDetector
from diffusers import AnimateDiffVideoToVideoControlNetPipeline
from diffusers.utils import export_to_gif, load_video
from diffusers import AutoencoderKL, ControlNetModel, MotionAdapter, LCMScheduler

# Load the ControlNet
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-openpose", dtype=torch.float16)
# Load the motion adapter
motion_adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM")
# Load SD 1.5 based finetuned model
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", dtype=torch.float16)
pipe = AnimateDiffVideoToVideoControlNetPipeline.from_pretrained(
    "SG161222/Realistic_Vision_V5.1_noVAE",
    motion_adapter=motion_adapter,
    controlnet=controlnet,
    vae=vae,
).to(device="cuda", dtype=torch.float16)  # or "mps", "xpu", "cpu"

# Enable LCM to speed up inference
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")
pipe.load_lora_weights("wangfuyun/AnimateLCM", weight_name="AnimateLCM_sd15_t2v_lora.safetensors", adapter_name="lcm-lora")
pipe.set_adapters(["lcm-lora"], [0.8])

video = load_video("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/dance.gif")
video = [frame.convert("RGB") for frame in video]

prompt = "astronaut in space, dancing"
negative_prompt = "bad quality, worst quality, jpeg artifacts, ugly"

# Create controlnet preprocessor
open_pose = OpenposeDetector.from_pretrained("lllyasviel/Annotators").to("cuda")

# Preprocess controlnet images
conditioning_frames = []
for frame in tqdm(video):
    conditioning_frames.append(open_pose(frame))

strength = 0.8
with torch.inference_mode():
    video = pipe(
        video=video,
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_inference_steps=10,
        guidance_scale=2.0,
        controlnet_conditioning_scale=0.75,
        conditioning_frames=conditioning_frames,
        strength=strength,
        generator=torch.Generator().manual_seed(42),
    ).frames[0]

video = [frame.resize(conditioning_frames[0].size) for frame in video]
export_to_gif(video, f"animatediff_vid2vid_controlnet.gif", fps=8)

Dưới đây là một số kết quả mẫu:

Video nguồnVideo đầu ra
cô gái anime, đang nhảy
anime girl, dancing
thiên hà vũ trụ, khiêu vũ
astronaut in space, dancing

Ánh sáng và bố cục được chuyển từ Video Nguồn.

Sử dụng Motion LoRAs

Motion LoRAs là một tập hợp các LoRAs hoạt động với checkpoint guoyww/animatediff-motion-adapter-v1-5-2. Các LoRAs này chịu trách nhiệm thêm các loại chuyển động cụ thể vào các bản dựng hoạt hình.

import torch
from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

# Load the motion adapter
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2", dtype=torch.float16)
# load SD 1.5 based finetuned model
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffPipeline.from_pretrained(model_id, motion_adapter=adapter, dtype=torch.float16)
pipe.load_lora_weights(
    "guoyww/animatediff-motion-lora-zoom-out", adapter_name="zoom-out"
)

scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    beta_schedule="linear",
    timestep_spacing="linspace",
    steps_offset=1,
)
pipe.scheduler = scheduler

# enable memory savings
pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt=(
        "masterpiece, bestquality, highlydetailed, ultradetailed, sunset, "
        "orange sky, warm lighting, fishing boats, ocean waves seagulls, "
        "rippling water, wharf, silhouette, serene atmosphere, dusk, evening glow, "
        "golden hour, coastal landscape, seaside scenery"
    ),
    negative_prompt="bad quality, worse quality",
    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=25,
    generator=torch.Generator("cpu").manual_seed(42),
)
frames = output.frames[0]
export_to_gif(frames, "animation.gif")
tác phẩm, chất lượng tốt nhất, hoàng hôn.
masterpiece, bestquality, sunset

Sử dụng Motion LoRAs với PEFT

Bạn cũng có thể tận dụng backend PEFT để kết hợp các Motion LoRA và tạo ra các hoạt ảnh phức tạp hơn.

Trước tiên, hãy cài đặt PEFT bằng

pip install peft

Sau đó, bạn có thể sử dụng mã sau để kết hợp các Motion LoRA.

import torch
from diffusers import AnimateDiffPipeline, DDIMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

# Load the motion adapter
adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2", dtype=torch.float16)
# load SD 1.5 based finetuned model
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffPipeline.from_pretrained(model_id, motion_adapter=adapter, dtype=torch.float16)

pipe.load_lora_weights(
    "diffusers/animatediff-motion-lora-zoom-out", adapter_name="zoom-out",
)
pipe.load_lora_weights(
    "diffusers/animatediff-motion-lora-pan-left", adapter_name="pan-left",
)
pipe.set_adapters(["zoom-out", "pan-left"], adapter_weights=[1.0, 1.0])

scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    clip_sample=False,
    timestep_spacing="linspace",
    beta_schedule="linear",
    steps_offset=1,
)
pipe.scheduler = scheduler

# enable memory savings
pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt=(
        "masterpiece, bestquality, highlydetailed, ultradetailed, sunset, "
        "orange sky, warm lighting, fishing boats, ocean waves seagulls, "
        "rippling water, wharf, silhouette, serene atmosphere, dusk, evening glow, "
        "golden hour, coastal landscape, seaside scenery"
    ),
    negative_prompt="bad quality, worse quality",
    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=25,
    generator=torch.Generator("cpu").manual_seed(42),
)
frames = output.frames[0]
export_to_gif(frames, "animation.gif")
tác phẩm, chất lượng tốt nhất, hoàng hôn.
masterpiece, bestquality, sunset

Sử dụng FreeInit

FreeInit: Bridging Initialization Gap in Video Diffusion Models của Tianxing Wu, Chenyang Si, Yuming Jiang, Ziqi Huang, Ziwei Liu.

FreeInit là một phương pháp hiệu quả giúp cải thiện tính nhất quán theo thời gian và chất lượng tổng thể của các video được tạo bằng video-diffusion-models mà không cần thêm bất kỳ bước huấn luyện nào. Phương pháp này có thể được áp dụng một cách liền mạch vào AnimateDiff, ModelScope, VideoCrafter và nhiều mô hình tạo video khác tại thời điểm suy luận, và hoạt động bằng cách tinh chỉnh lặp đi lặp lại nhiễu khởi tạo latent. Chi tiết hơn có thể tìm thấy trong bài báo.

Ví dụ sau minh họa cách sử dụng FreeInit.

import torch
from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
pipe = AnimateDiffPipeline.from_pretrained(model_id, motion_adapter=adapter, dtype=torch.float16).to("cuda")  # or "mps", "xpu", "cpu"
pipe.scheduler = DDIMScheduler.from_pretrained(
    model_id,
    subfolder="scheduler",
    beta_schedule="linear",
    clip_sample=False,
    timestep_spacing="linspace",
    steps_offset=1
)

# enable memory savings
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

# enable FreeInit
# Refer to the enable_free_init documentation for a full list of configurable parameters
pipe.enable_free_init(method="butterworth", use_fast_sampling=True)

# run inference
output = pipe(
    prompt="a panda playing a guitar, on a boat, in the ocean, high quality",
    negative_prompt="bad quality, worse quality",
    num_frames=16,
    guidance_scale=7.5,
    num_inference_steps=20,
    generator=torch.Generator("cpu").manual_seed(666),
)

# disable FreeInit
pipe.disable_free_init()

frames = output.frames[0]
export_to_gif(frames, "animation.gif")

FreeInit không thực sự miễn phí - chất lượng được cải thiện phải trả giá bằng lượng tính toán bổ sung. Nó yêu cầu lấy mẫu thêm một vài lần tùy thuộc vào tham số num_iters được đặt khi bật tính năng này. Việc đặt tham số use_fast_sampling thành True có thể cải thiện hiệu suất tổng thể (với chi phí là chất lượng thấp hơn so với khi use_fast_sampling=False nhưng vẫn cho kết quả tốt hơn so với các mô hình tạo video thông thường).

Hãy chắc chắn xem qua hướng dẫn về Schedulers để tìm hiểu cách khám phá sự đánh đổi giữa tốc độ và chất lượng của scheduler, và xem phần tái sử dụng các thành phần giữa các pipeline để tìm hiểu cách nạp các thành phần giống nhau vào nhiều pipeline một cách hiệu quả.

Khi không bật FreeInitVới FreeInit được bật
panda đang chơi guitar
panda playing a guitar
panda đang chơi guitar
panda playing a guitar

Sử dụng AnimateLCM

AnimateLCM là một checkpoint của module chuyển động và một LCM LoRA được tạo ra bằng cách sử dụng chiến lược học nhất quán, tách biệt quá trình chưng cất các tiên nghiệm sinh ảnh và các tiên nghiệm sinh chuyển động.

import torch
from diffusers import AnimateDiffPipeline, LCMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM")
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")

pipe.load_lora_weights("wangfuyun/AnimateLCM", weight_name="sd15_lora_beta.safetensors", adapter_name="lcm-lora")

pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt="A space rocket with trails of smoke behind it launching into space from the desert, 4k, high resolution",
    negative_prompt="bad quality, worse quality, low resolution",
    num_frames=16,
    guidance_scale=1.5,
    num_inference_steps=6,
    generator=torch.Generator("cpu").manual_seed(0),
)
frames = output.frames[0]
export_to_gif(frames, "animatelcm.gif")
Tên lửa vũ trụ, 4K.
A space rocket, 4K

AnimateLCM cũng tương thích với các Motion LoRAs hiện có.

import torch
from diffusers import AnimateDiffPipeline, LCMScheduler, MotionAdapter
from diffusers.utils import export_to_gif

adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM")
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")

pipe.load_lora_weights("wangfuyun/AnimateLCM", weight_name="sd15_lora_beta.safetensors", adapter_name="lcm-lora")
pipe.load_lora_weights("guoyww/animatediff-motion-lora-tilt-up", adapter_name="tilt-up")

pipe.set_adapters(["lcm-lora", "tilt-up"], [1.0, 0.8])
pipe.vae.enable_slicing()
pipe.enable_model_cpu_offload()

output = pipe(
    prompt="A space rocket with trails of smoke behind it launching into space from the desert, 4k, high resolution",
    negative_prompt="bad quality, worse quality, low resolution",
    num_frames=16,
    guidance_scale=1.5,
    num_inference_steps=6,
    generator=torch.Generator("cpu").manual_seed(0),
)
frames = output.frames[0]
export_to_gif(frames, "animatelcm-motion-lora.gif")
Tên lửa vũ trụ, 4K.
A space rocket, 4K

Sử dụng FreeNoise

FreeNoise: Khuyếch tán video dài hơn không cần tinh chỉnh thông qua lên lịch lại nhiễu của Haonan Qiu, Menghan Xia, Yong Zhang, Yingqing He, Xintao Wang, Ying Shan, Ziwei Liu.

FreeNoise là một cơ chế lấy mẫu có thể tạo ra các video dài hơn bằng các mô hình tạo video ngắn thông qua việc lên lịch lại nhiễu, chú ý thời gian trên các cửa sổ trượt và trung bình có trọng số các khung hình tiềm ẩn. Nó cũng có thể được sử dụng với nhiều prompt để cho phép tạo video nội suy. Chi tiết hơn có sẵn trong bài báo.

Các pipeline AnimateDiff hiện được hỗ trợ và có thể sử dụng với FreeNoise là:

Để sử dụng FreeNoise, bạn cần thêm một dòng duy nhất vào mã suy luận sau khi tải các pipeline của mình.

+ pipe.enable_free_noise()

Sau bước này, bạn có thể sử dụng một prompt duy nhất, hoặc truyền nhiều prompt dưới dạng từ điển các cặp số nguyên - chuỗi. Các khóa số nguyên của từ điển tương ứng với chỉ số khung hình mà tại đó ảnh hưởng của prompt đó là lớn nhất. Mỗi chỉ số khung hình phải ánh xạ đến một prompt chuỗi duy nhất. Các prompt cho các chỉ số khung hình trung gian, không được truyền trong từ điển, sẽ được tạo ra bằng cách nội suy giữa các prompt khung hình được truyền. Mặc định, nội suy tuyến tính đơn giản được sử dụng. Tuy nhiên, bạn có thể tùy chỉnh hành vi này bằng cách sử dụng callback cho tham số prompt_interpolation_callback khi bật FreeNoise.

Ví dụ đầy đủ:

import torch
from diffusers import AutoencoderKL, AnimateDiffPipeline, LCMScheduler, MotionAdapter
from diffusers.utils import export_to_video, load_image

# Load pipeline
dtype = torch.float16
motion_adapter = MotionAdapter.from_pretrained("wangfuyun/AnimateLCM", dtype=dtype)
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", dtype=dtype)

pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=motion_adapter, vae=vae, dtype=dtype)
pipe.scheduler = LCMScheduler.from_config(pipe.scheduler.config, beta_schedule="linear")

pipe.load_lora_weights(
    "wangfuyun/AnimateLCM", weight_name="AnimateLCM_sd15_t2v_lora.safetensors", adapter_name="lcm_lora"
)
pipe.set_adapters(["lcm_lora"], [0.8])

# Enable FreeNoise for long prompt generation
pipe.enable_free_noise(context_length=16, context_stride=4)
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Can be a single prompt, or a dictionary with frame timesteps
prompt = {
    0: "A caterpillar on a leaf, high quality, photorealistic",
    40: "A caterpillar transforming into a cocoon, on a leaf, near flowers, photorealistic",
    80: "A cocoon on a leaf, flowers in the background, photorealistic",
    120: "A cocoon maturing and a butterfly being born, flowers and leaves visible in the background, photorealistic",
    160: "A beautiful butterfly, vibrant colors, sitting on a leaf, flowers in the background, photorealistic",
    200: "A beautiful butterfly, flying away in a forest, photorealistic",
    240: "A cyberpunk butterfly, neon lights, glowing",
}
negative_prompt = "bad quality, worst quality, jpeg artifacts"

# Run inference
output = pipe(
    prompt=prompt,
    negative_prompt=negative_prompt,
    num_frames=256,
    guidance_scale=2.5,
    num_inference_steps=10,
    generator=torch.Generator("cpu").manual_seed(0),
)

# Save video
frames = output.frames[0]
export_to_video(frames, "output.mp4", fps=16)

Tiết kiệm bộ nhớ FreeNoise

Vì FreeNoise xử lý nhiều khung hình cùng lúc, có những phần trong mô hình mà bộ nhớ cần thiết vượt quá dung lượng khả dụng trên các GPU tiêu dùng thông thường. Các nút thắt cổ chai bộ nhớ chính mà chúng tôi xác định là các khối chú ý không gian và thời gian, các khối lấy mẫu lên và lấy mẫu xuống, các khối resnet và các lớp feed-forward. Vì hầu hết các khối này chỉ hoạt động hiệu quả trên chiều kênh/độ nhúng, người ta có thể thực hiện suy luận theo từng lô (chunked inference) trên các chiều batch. Chiều batch trong AnimateDiff có bản chất là không gian ([B x F, H x W, C]) hoặc thời gian (B x H x W, F, C) (lưu ý rằng điều này có vẻ trái với trực giác, nhưng các chiều batch ở đây là chính xác, vì các khối không gian xử lý trên chiều B x F trong khi các khối thời gian xử lý trên chiều B x H x W). Chúng tôi giới thiệu SplitInferenceModule giúp dễ dàng chia nhỏ theo bất kỳ chiều nào và thực hiện suy luận. Điều này tiết kiệm được nhiều bộ nhớ nhưng đổi lại là thời gian suy luận dài hơn.

# Load pipeline and adapters
# ...
+ pipe.enable_free_noise_split_inference()
+ pipe.unet.enable_forward_chunking(16)

Gọi phương thức pipe.enable_free_noise_split_inference chấp nhận hai tham số: spatial_split_size (mặc định là 256) và temporal_split_size (mặc định là 16). Các giá trị này có thể được cấu hình dựa trên lượng VRAM bạn có sẵn. Kích thước chia nhỏ thấp hơn dẫn đến mức sử dụng bộ nhớ thấp hơn nhưng suy luận chậm hơn, trong khi kích thước chia nhỏ lớn hơn cho phép suy luận nhanh hơn với chi phí là sử dụng nhiều bộ nhớ hơn.

Sử dụng from_single_file với MotionAdapter

diffusers>=0.30.0 hỗ trợ nạp các checkpoint AnimateDiff vào MotionAdapter ở định dạng gốc thông qua from_single_file

from diffusers import MotionAdapter

ckpt_path = "https://huggingface.co/Lightricks/LongAnimateDiff/blob/main/lt_long_mm_32_frames.ckpt"

adapter = MotionAdapter.from_single_file(ckpt_path, dtype=torch.float16)
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)

AnimateDiffPipeline

lớp diffusers.AnimateDiffPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdapterscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulerfeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
  • tokenizer (CLIPTokenizer) — Một CLIPTokenizer để phân tách văn bản.
  • unet (UNet2DConditionModel) — Một UNet2DConditionModel được dùng để tạo ra UNetMotionModel nhằm khử nhiễu các video latents đã được mã hóa.
  • motion_adapter (MotionAdapter) — Một MotionAdapter được sử dụng kết hợp với unet để khử nhiễu các latents video đã mã hóa.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.

Pipeline để tạo video từ văn bản.

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:

__call__

< >

( prompt: str | list[str] | None = Nonenum_frames: int | None = 16height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5negative_prompt: str | list[str] | None = Nonenum_videos_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']decode_chunk_size: int = 16**kwargs ) → AnimateDiffPipelineOutput or tuple

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyền prompt_embeds.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao của video được tạo ra, tính bằng pixel.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng của video được tạo ra, tính bằng pixel.
  • num_frames (int, tùy chọn, mặc định là 16) — Số lượng khung hình video được tạo ra. Mặc định là 16 khung hình, tương đương 2 giây video với tốc độ 8 khung hình mỗi giây.
  • num_inference_steps (int, tùy chọn, 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 video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.
  • guidance_scale (float, tùy chọn, mặc định là 7.5) — Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi guidance_scale > 1.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM. Chỉ áp dụng cho DDIMScheduler và bị bỏ qua ở các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tùy chọn) — Một torch.Generator để làm cho quá trình sinh ra kết quả xác định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp. Latents phải có hình dạng (batch_size, num_channel, num_frames, height, width).
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • 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_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image — (PipelineImageInput, tùy chọn): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh được tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng (batch_size, num_images, emb_dim). Nó phải chứa embedding hình ảnh âm nếu do_classifier_free_guidance được đặt thành True. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa torch.Tensor, PIL.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một ~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa trong self.processor.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.
  • decode_chunk_size (int, mặc định là 16) — Số lượng khung hình được giải mã mỗi lần khi gọi phương thức decode_latents.

Trả về

AnimateDiffPipelineOutput hoặc tuple

Nếu return_dict là True, AnimateDiffPipelineOutput 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 khung hình đã tạo.

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

Ví dụ:

>>> import torch
>>> from diffusers import MotionAdapter, AnimateDiffPipeline, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> adapter = MotionAdapter.from_pretrained("guoyww/animatediff-motion-adapter-v1-5-2")
>>> pipe = AnimateDiffPipeline.from_pretrained("frankjoshua/toonyou_beta6", motion_adapter=adapter)
>>> pipe.scheduler = DDIMScheduler(beta_schedule="linear", steps_offset=1, clip_sample=False)
>>> output = pipe(prompt="A corgi walking in the park")
>>> frames = output.frames[0]
>>> export_to_gif(frames, "animation.gif")

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • device — (torch.device): thiết bị torch
  • num_images_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • 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ào prompt.
  • 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ào negative_prompt.
  • lora_scale (float, tùy chọn) — Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

AnimateDiffControlNetPipeline

lớp diffusers.AnimateDiffControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdaptercontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: KarrasDiffusionSchedulersfeature_extractor: transformers.models.clip.image_processing_pil_clip.CLIPImageProcessorPil | None = Noneimage_encoder: transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection | None = None )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
  • tokenizer (CLIPTokenizer) — Một CLIPTokenizer để phân tách văn bản.
  • unet (UNet2DConditionModel) — Một UNet2DConditionModel được dùng để tạo ra UNetMotionModel nhằm khử nhiễu các video latents đã được mã hóa.
  • motion_adapter (MotionAdapter) — Một MotionAdapter được sử dụng kết hợp với unet để khử nhiễu các latents video đã mã hóa.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.

Pipeline để tạo video từ văn bản với sự dẫn dắt của ControlNet.

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:

__call__

< >

( prompt: str | list[str] = Nonenum_frames: int | None = 16height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50guidance_scale: float = 7.5negative_prompt: str | list[str] | None = Nonenum_videos_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneconditioning_frames: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0clip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']decode_chunk_size: int = 16 ) → AnimateDiffPipelineOutput or tuple

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyền prompt_embeds.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao của video được tạo ra, tính bằng pixel.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng của video được tạo ra, tính bằng pixel.
  • num_frames (int, tùy chọn, mặc định là 16) — Số lượng khung hình video được tạo ra. Mặc định là 16 khung hình, tương đương 2 giây video với tốc độ 8 khung hình mỗi giây.
  • num_inference_steps (int, tùy chọn, 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 video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.
  • guidance_scale (float, tùy chọn, mặc định là 7.5) — Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi guidance_scale > 1.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM. Chỉ áp dụng cho DDIMScheduler và bị bỏ qua ở các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tùy chọn) — Một torch.Generator để làm cho quá trình sinh ra kết quả xác định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp. Latents phải có hình dạng (batch_size, num_channel, num_frames, height, width).
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • 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_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image (PipelineImageInput, tùy chọn) — Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh được tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng (batch_size, num_images, emb_dim). Nó phải chứa embedding hình ảnh âm nếu do_classifier_free_guidance được đặt thành True. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • conditioning_frames (list[PipelineImageInput], tùy chọn) — Điều kiện đầu vào của ControlNet để cung cấp hướng dẫn cho unet trong quá trình tạo. Nếu chỉ định nhiều ControlNet, hình ảnh phải được truyền dưới dạng danh sách sao cho mỗi phần tử của danh sách có thể được batch đúng cách để làm đầu vào cho một ControlNet duy nhất.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa torch.Tensor, PIL.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một ~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa trong self.processor.
  • controlnet_conditioning_scale (float hoặc list[float], tùy chọn, mặc định là 1.0) — Đầu ra của ControlNet được nhân với controlnet_conditioning_scale trước khi được cộng vào phần dư trong unet gốc. Nếu nhiều ControlNet được chỉ định trong init, bạn có thể đặt thang tương ứng dưới dạng một danh sách.
  • guess_mode (bool, tùy chọn, mặc định là False) — Bộ mã hóa ControlNet sẽ cố gắng nhận diện nội dung của hình ảnh đầu vào ngay cả khi bạn xóa tất cả các prompt. Khuyến nghị sử dụng giá trị guidance_scale nằm trong khoảng từ 3.0 đến 5.0.
  • control_guidance_start (float hoặc list[float], tùy chọn, mặc định là 0.0) — Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet bắt đầu áp dụng.
  • control_guidance_end (float hoặc list[float], tùy chọn, mặc định là 1.0) — Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet ngừng áp dụng.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.
  • decode_chunk_size (int, mặc định là 16) — Số lượng khung hình được giải mã mỗi lần khi gọi phương thức decode_latents.

Trả về

AnimateDiffPipelineOutput hoặc tuple

Nếu return_dict là True, AnimateDiffPipelineOutput 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 khung hình đã tạo.

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

Ví dụ:

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • device — (torch.device): thiết bị torch
  • num_images_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • 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ào prompt.
  • 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ào negative_prompt.
  • lora_scale (float, tùy chọn) — Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

AnimateDiffSparseControlNetPipeline

lớp diffusers.AnimateDiffSparseControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdaptercontrolnet: SparseControlNetModelscheduler: KarrasDiffusionSchedulersfeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
  • tokenizer (CLIPTokenizer) — Một CLIPTokenizer để phân tách văn bản.
  • unet (UNet2DConditionModel) — Một UNet2DConditionModel được dùng để tạo ra UNetMotionModel nhằm khử nhiễu các video latents đã được mã hóa.
  • motion_adapter (MotionAdapter) — Một MotionAdapter được sử dụng kết hợp với unet để khử nhiễu các latents video đã mã hóa.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.

Pipeline cho việc tạo video từ văn bản có kiểm soát sử dụng phương pháp được mô tả trong SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models.

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:

__call__

< >

( prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_frames: int = 16num_inference_steps: int = 50guidance_scale: float = 7.5negative_prompt: str | list[str] | None = Nonenum_videos_per_prompt: int = 1eta: float = 0.0generator: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneconditioning_frames: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneoutput_type: str = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0controlnet_frame_indices: list[int] = [0]guess_mode: bool = Falseclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → AnimateDiffPipelineOutput or tuple

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyền prompt_embeds.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao của video được tạo ra, tính bằng pixel.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng của video được tạo ra, tính bằng pixel.
  • num_frames (int, tùy chọn, mặc định là 16) — Số lượng khung hình video được tạo ra. Mặc định là 16 khung hình, tương đương 2 giây video với tốc độ 8 khung hình mỗi giây.
  • num_inference_steps (int, tùy chọn, 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 video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.
  • guidance_scale (float, tùy chọn, mặc định là 7.5) — Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi guidance_scale > 1.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM. Chỉ áp dụng cho DDIMScheduler và bị bỏ qua ở các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tùy chọn) — Một torch.Generator để làm cho quá trình sinh ra kết quả xác định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp. Latents phải có hình dạng (batch_size, num_channel, num_frames, height, width).
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • 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_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image — (PipelineImageInput, tùy chọn): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh được tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng (batch_size, num_images, emb_dim). Nó phải chứa embedding hình ảnh âm nếu do_classifier_free_guidance được đặt thành True. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • conditioning_frames (list[PipelineImageInput], tùy chọn) — Đầu vào SparseControlNet để cung cấp hướng dẫn cho unet trong quá trình tạo.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa torch.Tensor, PIL.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một ~pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa trong self.processor.
  • controlnet_conditioning_scale (float hoặc list[float], tùy chọn, mặc định là 1.0) — Đầu ra của ControlNet được nhân với controlnet_conditioning_scale trước khi được cộng vào phần dư trong unet gốc. Nếu nhiều ControlNet được chỉ định trong init, bạn có thể đặt thang tương ứng dưới dạng một danh sách.
  • controlnet_frame_indices (list[int]) — Các chỉ số nơi các khung hình điều kiện phải được áp dụng cho quá trình tạo. Có thể cung cấp nhiều khung hình để hướng dẫn mô hình tạo ra các đầu ra có cấu trúc tương tự, trong đó unet có thể “điền vào khoảng trống” cho các video nội suy, hoặc chỉ cần cung cấp một khung hình duy nhất cho cấu trúc mong đợi nói chung. Phải có cùng độ dài với conditioning_frames.
  • guess_mode (bool, tùy chọn, mặc định là False) — Bộ mã hóa ControlNet sẽ cố gắng nhận diện nội dung của hình ảnh đầu vào ngay cả khi bạn xóa tất cả các prompt. Khuyến nghị sử dụng giá trị guidance_scale nằm trong khoảng từ 3.0 đến 5.0.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.

Trả về

AnimateDiffPipelineOutput hoặc tuple

Nếu return_dict là True, AnimateDiffPipelineOutput 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 khung hình đã tạo.

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

Ví dụ:

>>> import torch
>>> from diffusers import AnimateDiffSparseControlNetPipeline
>>> from diffusers.models import AutoencoderKL, MotionAdapter, SparseControlNetModel
>>> from diffusers.schedulers import DPMSolverMultistepScheduler
>>> from diffusers.utils import export_to_gif, load_image

>>> model_id = "SG161222/Realistic_Vision_V5.1_noVAE"
>>> motion_adapter_id = "guoyww/animatediff-motion-adapter-v1-5-3"
>>> controlnet_id = "guoyww/animatediff-sparsectrl-scribble"
>>> lora_adapter_id = "guoyww/animatediff-motion-lora-v1-5-3"
>>> vae_id = "stabilityai/sd-vae-ft-mse"
>>> device = "cuda"

>>> motion_adapter = MotionAdapter.from_pretrained(motion_adapter_id, torch_dtype=torch.float16).to(device)
>>> controlnet = SparseControlNetModel.from_pretrained(controlnet_id, torch_dtype=torch.float16).to(device)
>>> vae = AutoencoderKL.from_pretrained(vae_id, torch_dtype=torch.float16).to(device)
>>> scheduler = DPMSolverMultistepScheduler.from_pretrained(
...     model_id,
...     subfolder="scheduler",
...     beta_schedule="linear",
...     algorithm_type="dpmsolver++",
...     use_karras_sigmas=True,
... )
>>> pipe = AnimateDiffSparseControlNetPipeline.from_pretrained(
...     model_id,
...     motion_adapter=motion_adapter,
...     controlnet=controlnet,
...     vae=vae,
...     scheduler=scheduler,
...     torch_dtype=torch.float16,
... ).to(device)
>>> pipe.load_lora_weights(lora_adapter_id, adapter_name="motion_lora")
>>> pipe.fuse_lora(lora_scale=1.0)

>>> prompt = "an aerial view of a cyberpunk city, night time, neon lights, masterpiece, high quality"
>>> negative_prompt = "low quality, worst quality, letterboxed"

>>> image_files = [
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-1.png",
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-2.png",
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/animatediff-scribble-3.png",
... ]
>>> condition_frame_indices = [0, 8, 15]
>>> conditioning_frames = [load_image(img_file) for img_file in image_files]

>>> video = pipe(
...     prompt=prompt,
...     negative_prompt=negative_prompt,
...     num_inference_steps=25,
...     conditioning_frames=conditioning_frames,
...     controlnet_conditioning_scale=1.0,
...     controlnet_frame_indices=condition_frame_indices,
...     generator=torch.Generator().manual_seed(1337),
... ).frames[0]
>>> export_to_gif(video, "output.gif")

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • device — (torch.device): thiết bị torch
  • num_images_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • 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ào prompt.
  • 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ào negative_prompt.
  • lora_scale (float, tùy chọn) — Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

AnimateDiffSDXLPipeline

lớp diffusers.AnimateDiffSDXLPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltext_encoder_2: CLIPTextModelWithProjectiontokenizer: CLIPTokenizertokenizer_2: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdapterscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulerimage_encoder: CLIPVisionModelWithProjection = Nonefeature_extractor: CLIPImageProcessorPil = Noneforce_zeros_for_empty_prompt: bool = True )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng. Stable Diffusion XL sử dụng phần văn bản của CLIP, cụ thể là biến thể clip-vit-large-patch14.
  • text_encoder_2 ( CLIPTextModelWithProjection) — Bộ mã hóa văn bản đóng băng thứ hai. Stable Diffusion XL sử dụng phần văn bản và pool của CLIP, cụ thể là biến thể laion/CLIP-ViT-bigG-14-laion2B-39B-b160k.
  • tokenizer (CLIPTokenizer) — Tokenizer của lớp CLIPTokenizer.
  • tokenizer_2 (CLIPTokenizer) — Tokenizer thứ hai thuộc lớp CLIPTokenizer.
  • unet (UNet2DConditionModel) — Kiến trúc U-Net có điều kiện để khử nhiễu các latents ảnh đã mã hóa.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.
  • force_zeros_for_empty_prompt (bool, tùy chọn, mặc định là "True") — Xác định xem các embedding của prompt tiêu cực có nên được ép luôn về 0 hay không. Xem thêm cấu hình của stabilityai/stable-diffusion-xl-base-1-0.

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

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 mà thư viện triển khai cho tất cả các pipeline (chẳng hạn như tải xuống hoặc 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:

__call__

< >

( prompt: str | list[str] = Noneprompt_2: str | list[str] | None = Nonenum_frames: int = 16height: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list[int] = Nonesigmas: list[float] = Nonedenoising_end: float | None = Noneguidance_scale: float = 5.0negative_prompt: str | list[str] | None = Nonenegative_prompt_2: str | list[str] | None = Nonenum_videos_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneguidance_rescale: float = 0.0original_size: tuple[int, int] | None = Nonecrops_coords_top_left: tuple[int, int] = (0, 0)target_size: tuple[int, int] | None = Nonenegative_original_size: tuple[int, int] | None = Nonenegative_crops_coords_top_left: tuple[int, int] = (0, 0)negative_target_size: tuple[int, int] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents'] ) → AnimateDiffPipelineOutput or tuple

Tham số

  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo video. Nếu không được định nghĩa, bạn phải truyền prompt_embeds thay thế.
  • prompt_2 (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt sẽ được gửi đến tokenizer_2 và text_encoder_2. Nếu không được định nghĩa, prompt sẽ được sử dụng cho cả hai text-encoder.
  • num_frames — Số lượng khung hình video được tạo ra. Mặc định là 16 khung hình, tương đương 2 giây video với tốc độ 8 khung hình mỗi giây.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao tính bằng pixel của video được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với stabilityai/stable-diffusion-xl-base-1.0 và các checkpoint không được tinh chỉnh cụ thể cho độ phân giải thấp.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng tính bằng pixel của video được tạo ra. Mặc định được đặt là 1024 để đạt kết quả tốt nhất. Bất kỳ giá trị nào dưới 512 pixel sẽ không hoạt động tốt với stabilityai/stable-diffusion-xl-base-1.0 và các checkpoint không được tinh chỉnh cụ thể cho độ phân giải thấp.
  • num_inference_steps (int, tùy chọn, 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 video 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ố timesteps trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.
  • sigmas (list[float], tùy chọn) — Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối số sigmas trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền sẽ được sử dụng.
  • denoising_end (float, tùy chọn) — Khi được chỉ định, tham số này xác định tỷ lệ (từ 0.0 đến 1.0) của toàn bộ quá trình khử nhiễu cần hoàn thành trước khi bị kết thúc sớm một cách có chủ đích. Kết quả là, mẫu được trả về vẫn sẽ giữ lại một lượng nhiễu đáng kể, được xác định bởi các bước thời gian rời rạc do trình lập lịch (scheduler) chọn. Tham số denoising_end nên được sử dụng khi pipeline này là một phần của cấu hình đa pipeline “Mixture of Denoisers”, như đã mô tả chi tiết trong Refining the Image Output
  • guidance_scale (float, tùy chọn, 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à w của phương trình 2. trong Bài báo Imagen. Thang độ dẫn hướng được kích hoạt bằng cách đặt guidance_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ới prompt văn bản, thường phải đánh đổi bằng chất lượng video thấp hơn.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo video. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • negative_prompt_2 (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo video, sẽ được gửi đến tokenizer_2 và text_encoder_2. Nếu không được định nghĩa, negative_prompt sẽ được sử dụng cho cả hai text-encoder
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM: https://huggingface.co/papers/2010.02502. Chỉ áp dụng cho schedulers.DDIMScheduler, sẽ bị bỏ qua với các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tuỳ chọn) — Một hoặc một danh sách torch generator để đảm bảo quá trình sinh là tất đị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 video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp.
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, 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ào prompt.
  • 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ào negative_prompt.
  • pooled_prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã gộp sẽ được tạo từ đối số đầu vào prompt.
  • negative_pooled_prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản pooled âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image — (PipelineImageInput, tùy chọn): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh đã được tạo trước cho IP-Adapter. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa PIL: PIL.Image.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một ~pipelines.stable_diffusion_xl.AnimateDiffPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa dưới self.processor trong diffusers.models.attention_processor.
  • guidance_rescale (float, tùy chọn, mặc định là 0.0) — Hệ số rescale guidance được đề xuất trong Common Diffusion Noise Schedules and Sample Steps are Flawed guidance_scale được định nghĩa là φ trong phương trình 16. của Common Diffusion Noise Schedules and Sample Steps are Flawed. Hệ số rescale guidance nên khắc phục tình trạng phơi sáng quá mức khi sử dụng zero terminal SNR.
  • original_size (tuple[int], tuỳ chọn, mặc định là (1024, 1024)) — Nếu original_size không giống với target_size, hình ảnh sẽ có vẻ bị giảm hoặc tăng mẫu. original_size mặc định là (height, width) nếu không được chỉ định. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952.
  • crops_coords_top_left (tuple[int], tuỳ chọn, mặc định là (0, 0)) — crops_coords_top_left có thể được dùng để tạo ra một hình ảnh trông như đã được “cắt” từ vị trí crops_coords_top_left trở xuống. Các hình ảnh đẹp, được căn giữa tốt thường đạt được bằng cách đặt crops_coords_top_left thành (0, 0). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952.
  • target_size (tuple[int], tuỳ chọn, mặc định là (1024, 1024)) — Trong hầu hết các trường hợp, target_size nên được đặt thành chiều cao và chiều rộng mong muốn của hình ảnh được tạo ra. Nếu không được chỉ định, giá trị mặc định sẽ là (height, width). Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952.
  • negative_original_size (tuple[int], tuỳ chọn, mặc định là (1024, 1024)) — Để điều kiện âm quá trình tạo dựa trên độ phân giải hình ảnh cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952. Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.
  • negative_crops_coords_top_left (tuple[int], tuỳ chọn, mặc định là (0, 0)) — Để điều kiện âm quá trình tạo dựa trên tọa độ cắt cụ thể. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952. Để biết thêm thông tin, hãy tham khảo luồng vấn đề này: https://github.com/huggingface/diffusers/issues/4208.
  • negative_target_size (tuple[int], tuỳ chọn, mặc định là (1024, 1024)) — Điều kiện âm cho quá trình tạo dựa trên độ phân giải của ảnh đích. Trong hầu hết các trường hợp, giá trị này nên giống với target_size. Đây là một phần của micro-conditioning của SDXL như được giải thích trong mục 2.2 của https://huggingface.co/papers/2307.01952. Để biết thêm thông tin, hãy tham khảo luồng issue này: https://github.com/huggingface/diffusers/issues/4208.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.

Trả về

AnimateDiffPipelineOutput hoặc tuple

Nếu return_dict là True, AnimateDiffPipelineOutput 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 khung hình đã tạo.

Hàm được gọi khi gọi pipeline cho việc sinh.

Ví dụ:

>>> import torch
>>> from diffusers.models import MotionAdapter
>>> from diffusers import AnimateDiffSDXLPipeline, DDIMScheduler
>>> from diffusers.utils import export_to_gif

>>> adapter = MotionAdapter.from_pretrained(
...     "a-r-r-o-w/animatediff-motion-adapter-sdxl-beta", torch_dtype=torch.float16
... )

>>> model_id = "stabilityai/stable-diffusion-xl-base-1.0"
>>> scheduler = DDIMScheduler.from_pretrained(
...     model_id,
...     subfolder="scheduler",
...     clip_sample=False,
...     timestep_spacing="linspace",
...     beta_schedule="linear",
...     steps_offset=1,
... )
>>> pipe = AnimateDiffSDXLPipeline.from_pretrained(
...     model_id,
...     motion_adapter=adapter,
...     scheduler=scheduler,
...     torch_dtype=torch.float16,
...     variant="fp16",
... ).to("cuda")

>>> # enable memory savings
>>> pipe.vae.enable_slicing()
>>> pipe.vae.enable_tiling()

>>> output = pipe(
...     prompt="a panda surfing in the ocean, realistic, high quality",
...     negative_prompt="low quality, worst quality",
...     num_inference_steps=20,
...     guidance_scale=8,
...     width=1024,
...     height=1024,
...     num_frames=16,
... )

>>> frames = output.frames[0]
>>> export_to_gif(frames, "animation.gif")

encode_prompt

< >

( prompt: strprompt_2: str | None = Nonedevice: typing.Optional[torch.device] = Nonenum_videos_per_prompt: int = 1do_classifier_free_guidance: bool = Truenegative_prompt: str | None = Nonenegative_prompt_2: str | None = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonepooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • prompt_2 (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt sẽ được gửi đến tokenizer_2 và text_encoder_2. Nếu không được định nghĩa, prompt sẽ được sử dụng cho cả hai text-encoder.
  • device — (torch.device): thiết bị torch
  • num_videos_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • negative_prompt_2 (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng tạo ảnh, sẽ được gửi đến tokenizer_2 và text_encoder_2. Nếu không được định nghĩa, negative_prompt sẽ được sử dụng cho cả hai text-encoder
  • 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ào prompt.
  • 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ào negative_prompt.
  • pooled_prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được gộp (pooled) sẵn. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, các embedding văn bản đã gộp sẽ được tạo từ đối số đầu vào prompt.
  • negative_pooled_prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản pooled âm đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản, vd. trọng số prompt. Nếu không được cung cấp, pooled negative_prompt_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • lora_scale (float, tùy chọn) — Hệ số lora sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

get_guidance_scale_embedding

< >

( w: Tensorembedding_dim: int = 512dtype: dtype = torch.float32 ) → torch.Tensor

Tham số

  • w (torch.Tensor) — Tạo các vector nhúng với thang độ dẫn hướng được chỉ định để sau đó làm phong phú các nhúng bước thời gian.
  • embedding_dim (int, tùy chọn, mặc định là 512) — Kích thước của các embedding cần tạo.
  • dtype (torch.dtype, tùy chọn, mặc định là torch.float32) — Kiểu dữ liệu của các embedding được tạo ra.

Trả về

torch.Tensor

Các vector nhúng có hình dạng (len(w), embedding_dim).

Xem https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298

AnimateDiffVideoToVideoPipeline

lớp diffusers.AnimateDiffVideoToVideoPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdapterscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulerfeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
  • tokenizer (CLIPTokenizer) — Một CLIPTokenizer để phân tách văn bản.
  • unet (UNet2DConditionModel) — Một UNet2DConditionModel được dùng để tạo ra UNetMotionModel nhằm khử nhiễu các video latents đã được mã hóa.
  • motion_adapter (MotionAdapter) — Một MotionAdapter được sử dụng kết hợp với unet để khử nhiễu các latents video đã mã hóa.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.

Pipeline cho việc tạo video từ video.

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:

__call__

< >

( video: list[list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]] = Noneprompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50enforce_inference_steps: bool = Falsetimesteps: list[int] | None = Nonesigmas: list[float] | None = Noneguidance_scale: float = 7.5strength: float = 0.8negative_prompt: str | list[str] | None = Nonenum_videos_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Noneclip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']decode_chunk_size: int = 16 ) → pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput or tuple

Tham số

  • video (list[PipelineImageInput]) — Video đầ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/khung của video.
  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyền prompt_embeds.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao của video được tạo ra, tính bằng pixel.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng của video được tạo ra, tính bằng pixel.
  • num_inference_steps (int, tùy chọn, 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 video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.
  • enforce_inference_steps (bool, tùy chọn, mặc định là False) — Có nên thực thi num_inference_steps bước khử nhiễu bất kể tham số strength hay không. Khi False, số bước suy luận hiệu dụng sẽ được giảm theo strength.
  • 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ố timesteps trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.
  • sigmas (list[float], tùy chọn) — Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối số sigmas trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền sẽ được sử dụng.
  • strength (float, tùy chọn, mặc định là 0.8) — Giá trị strength cao hơn dẫn đến nhiều khác biệt hơn giữa video gốc và video được tạo ra.
  • guidance_scale (float, tùy chọn, mặc định là 7.5) — Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi guidance_scale > 1.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM. Chỉ áp dụng cho DDIMScheduler và bị bỏ qua ở các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tùy chọn) — Một torch.Generator để làm cho quá trình sinh ra kết quả xác định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp. Latents phải có hình dạng (batch_size, num_channel, num_frames, height, width).
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • 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_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image — (PipelineImageInput, tùy chọn): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh được tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng (batch_size, num_images, emb_dim). Nó phải chứa embedding hình ảnh âm nếu do_classifier_free_guidance được đặt thành True. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa torch.Tensor, PIL.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một AnimateDiffPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa trong self.processor.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.
  • decode_chunk_size (int, mặc định là 16) — Số lượng khung hình được giải mã mỗi lần khi gọi phương thức decode_latents.

Nếu return_dict là True, pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput 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 khung hình đã tạo.

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

Ví dụ:

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • device — (torch.device): thiết bị torch
  • num_images_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • 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ào prompt.
  • 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ào negative_prompt.
  • lora_scale (float, tùy chọn) — Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

AnimateDiffVideoToVideoControlNetPipeline

lớp diffusers.AnimateDiffVideoToVideoControlNetPipeline

< >

( vae: AutoencoderKLtext_encoder: CLIPTextModeltokenizer: CLIPTokenizerunet: diffusers.models.unets.unet_2d_condition.UNet2DConditionModel | diffusers.models.unets.unet_motion_model.UNetMotionModelmotion_adapter: MotionAdaptercontrolnet: diffusers.models.controlnets.controlnet.ControlNetModel | list[diffusers.models.controlnets.controlnet.ControlNetModel] | tuple[diffusers.models.controlnets.controlnet.ControlNetModel] | diffusers.models.controlnets.multicontrolnet.MultiControlNetModelscheduler: diffusers.schedulers.scheduling_ddim.DDIMScheduler | diffusers.schedulers.scheduling_pndm.PNDMScheduler | diffusers.utils.dummy_torch_and_scipy_objects.LMSDiscreteScheduler | diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler | diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler | diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepSchedulerfeature_extractor: CLIPImageProcessorPil = Noneimage_encoder: CLIPVisionModelWithProjection = None )

Tham số

  • vae (AutoencoderKL) — Mô hình Variational Auto-Encoder (VAE) để mã hóa và giải mã hình ảnh từ và sang các biểu diễn ẩn.
  • text_encoder (CLIPTextModel) — Bộ mã hóa văn bản đóng băng (clip-vit-large-patch14).
  • tokenizer (CLIPTokenizer) — Một CLIPTokenizer để phân tách văn bản.
  • unet (UNet2DConditionModel) — Một UNet2DConditionModel được dùng để tạo ra UNetMotionModel nhằm khử nhiễu các video latents đã được mã hóa.
  • motion_adapter (MotionAdapter) — Một MotionAdapter được sử dụng kết hợp với unet để khử nhiễu các latents video đã mã hóa.
  • controlnet (ControlNetModel hoặc list[ControlNetModel] hoặc tuple[ControlNetModel] hoặc MultiControlNetModel) — Cung cấp điều kiện bổ sung cho unet trong quá trình khử nhiễu. Nếu bạn đặt nhiều ControlNet dưới dạng danh sách, đầu ra từ mỗi ControlNet sẽ được cộng lại với nhau để tạo thành một điều kiện bổ sung kết hợp.
  • scheduler (SchedulerMixin) — Một scheduler được sử dụng kết hợp với unet để khử nhiễu các latents của ảnh đã mã hóa. Có thể là một trong DDIMScheduler, LMSDiscreteScheduler, hoặc PNDMScheduler.

Pipeline cho việc tạo video từ video với sự dẫn dắt của ControlNet.

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:

__call__

< >

( video: list[list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]]] = Noneprompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50enforce_inference_steps: bool = Falsetimesteps: list[int] | None = Nonesigmas: list[float] | None = Noneguidance_scale: float = 7.5strength: float = 0.8negative_prompt: str | list[str] | None = Nonenum_videos_per_prompt: int | None = 1eta: float = 0.0generator: 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] = Noneip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor], NoneType] = Noneip_adapter_image_embeds: list[torch.Tensor] | None = Noneconditioning_frames: list[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]] | None = Noneoutput_type: str | None = 'pil'return_dict: bool = Truecross_attention_kwargs: dict[str, typing.Any] | None = Nonecontrolnet_conditioning_scale: float | list[float] = 1.0guess_mode: bool = Falsecontrol_guidance_start: float | list[float] = 0.0control_guidance_end: float | list[float] = 1.0clip_skip: int | None = Nonecallback_on_step_end: typing.Optional[typing.Callable[[int, int], NoneType]] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']decode_chunk_size: int = 16 ) → pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput or tuple

Tham số

  • video (list[PipelineImageInput]) — Video đầ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/khung của video.
  • prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để định hướng việc tạo ảnh. Nếu không được định nghĩa, bạn cần truyền prompt_embeds.
  • height (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều cao của video được tạo ra, tính bằng pixel.
  • width (int, tùy chọn, mặc định là self.unet.config.sample_size * self.vae_scale_factor) — Chiều rộng của video được tạo ra, tính bằng pixel.
  • num_inference_steps (int, tùy chọn, 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 video có chất lượng cao hơn, với cái giá là suy luận chậm hơn.
  • enforce_inference_steps (bool, tùy chọn, mặc định là False) — Có nên thực thi num_inference_steps bước khử nhiễu bất kể tham số strength hay không. Khi False, số bước suy luận hiệu dụng sẽ được giảm theo strength.
  • 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ố timesteps trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền vào sẽ được sử dụng. Phải được sắp xếp theo thứ tự giảm dần.
  • sigmas (list[float], tùy chọn) — Các sigma tùy chỉnh để sử dụng cho quá trình khử nhiễu với các trình lập lịch hỗ trợ đối số sigmas trong phương thức set_timesteps của chúng. Nếu không được định nghĩa, hành vi mặc định khi num_inference_steps được truyền sẽ được sử dụng.
  • strength (float, tùy chọn, mặc định là 0.8) — Giá trị strength cao hơn dẫn đến nhiều khác biệt hơn giữa video gốc và video được tạo ra.
  • guidance_scale (float, tùy chọn, mặc định là 7.5) — Giá trị guidance scale cao hơn khuyến khích mô hình tạo ra các hình ảnh gắn kết chặt chẽ với prompt văn bản, với cái giá là chất lượng hình ảnh thấp hơn. Guidance scale được kích hoạt khi guidance_scale > 1.
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt để hướng dẫn những gì không nên bao gồm trong quá trình tạo ảnh. Nếu không được định nghĩa, bạn cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (guidance_scale < 1).
  • num_videos_per_prompt (int, tùy chọn, mặc định là 1) — Số lượng video cần tạo cho mỗi prompt.
  • eta (float, tùy chọn, mặc định là 0.0) — Tương ứng với tham số eta (η) trong bài báo DDIM. Chỉ áp dụng cho DDIMScheduler và bị bỏ qua ở các scheduler khác.
  • generator (torch.Generator hoặc list[torch.Generator], tùy chọn) — Một torch.Generator để làm cho quá trình sinh ra kết quả xác định.
  • latents (torch.Tensor, tùy chọn) — Các latents nhiễu đã được tạo trước, lấy mẫu từ phân phối Gaussian, dùng làm đầu vào cho việc tạo video. Có thể dùng để tinh chỉnh cùng một quá trình tạo với các prompt khác nhau. Nếu không được cung cấp, một tensor latents sẽ được tạo bằng cách lấy mẫu sử dụng generator ngẫu nhiên được cung cấp. Latents phải có hình dạng (batch_size, num_channel, num_frames, height, width).
  • prompt_embeds (torch.Tensor, tùy chọn) — Các embedding văn bản đã được tạo trước. Có thể dùng để dễ dàng điều chỉnh đầu vào văn bản (trọng số prompt). Nếu không được cung cấp, các embedding văn bản sẽ được tạo từ đối số đầu vào prompt.
  • 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_embeds sẽ được tạo từ đối số đầu vào negative_prompt.
  • ip_adapter_image — (PipelineImageInput, tùy chọn): Đầu vào hình ảnh tùy chọn để làm việc với IP Adapters.
  • ip_adapter_image_embeds (list[torch.Tensor], tùy chọn) — Các embedding hình ảnh được tạo trước cho IP-Adapter. Nó phải là một danh sách có độ dài bằng với số lượng IP-adapter. Mỗi phần tử phải là một tensor có hình dạng (batch_size, num_images, emb_dim). Nó phải chứa embedding hình ảnh âm nếu do_classifier_free_guidance được đặt thành True. Nếu không được cung cấp, các embedding sẽ được tính toán từ đối số đầu vào ip_adapter_image.
  • conditioning_frames (list[PipelineImageInput], tùy chọn) — Điều kiện đầu vào của ControlNet để cung cấp hướng dẫn cho unet trong quá trình tạo. Nếu chỉ định nhiều ControlNet, hình ảnh phải được truyền dưới dạng danh sách sao cho mỗi phần tử của danh sách có thể được batch đúng cách để làm đầu vào cho một ControlNet duy nhất.
  • output_type (str, tùy chọn, mặc định là "pil") — Định dạng đầu ra của video được tạo. Chọn giữa torch.Tensor, PIL.Image hoặc np.array.
  • return_dict (bool, tùy chọn, mặc định là True) — Có nên trả về một AnimateDiffPipelineOutput thay vì một tuple thông thường hay không.
  • cross_attention_kwargs (dict, tùy chọn) — Một từ điển kwargs, nếu được chỉ định, sẽ được truyền đến AttentionProcessor như đã định nghĩa trong self.processor.
  • controlnet_conditioning_scale (float hoặc list[float], tùy chọn, mặc định là 1.0) — Đầu ra của ControlNet được nhân với controlnet_conditioning_scale trước khi được cộng vào phần dư trong unet gốc. Nếu nhiều ControlNet được chỉ định trong init, bạn có thể đặt thang tương ứng dưới dạng một danh sách.
  • guess_mode (bool, tùy chọn, mặc định là False) — Bộ mã hóa ControlNet sẽ cố gắng nhận diện nội dung của hình ảnh đầu vào ngay cả khi bạn xóa tất cả các prompt. Khuyến nghị sử dụng giá trị guidance_scale nằm trong khoảng từ 3.0 đến 5.0.
  • control_guidance_start (float hoặc list[float], tùy chọn, mặc định là 0.0) — Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet bắt đầu áp dụng.
  • control_guidance_end (float hoặc list[float], tùy chọn, mặc định là 1.0) — Tỷ lệ phần trăm tổng số bước mà tại đó ControlNet ngừng áp dụng.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.
  • callback_on_step_end (Callable, tùy chọn) — Một hàm được gọi vào cuối mỗi bước khử nhiễu trong quá trình suy luận. Hàm này được gọi với các đối số sau: callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict). callback_kwargs sẽ bao gồm danh sách tất cả các tensor như được chỉ định bởi callback_on_step_end_tensor_inputs.
  • callback_on_step_end_tensor_inputs (list, optional) — Danh sách các tensor đầu vào cho hàm callback_on_step_end. Các tensor được chỉ định trong danh sách sẽ được truyền dưới dạng tham số callback_kwargs. Bạn chỉ có thể bao gồm các biến được liệt kê trong thuộc tính ._callback_tensor_inputs của lớp pipeline của bạn.
  • decode_chunk_size (int, mặc định là 16) — Số lượng khung hình được giải mã mỗi lần khi gọi phương thức decode_latents.

Nếu return_dict là True, pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput 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 khung hình đã tạo.

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

Ví dụ:

encode_prompt

< >

( promptdevicenum_images_per_promptdo_classifier_free_guidancenegative_prompt = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonelora_scale: float | None = Noneclip_skip: int | None = None )

Tham số

  • prompt (str hoặc list[str], tùy chọn) — prompt cần được mã hóa
  • device — (torch.device): thiết bị torch
  • num_images_per_prompt (int) — số lượng hình ảnh cần được tạo cho mỗi prompt
  • do_classifier_free_guidance (bool) — có sử dụng classifier free guidance hay không
  • negative_prompt (str hoặc list[str], tùy chọn) — Prompt hoặc các prompt không dùng để định hướng việc tạo ảnh. Nếu không được định nghĩa, cần truyền negative_prompt_embeds thay thế. Bỏ qua khi không sử dụng guidance (tức là bị bỏ qua nếu guidance_scale nhỏ hơn 1).
  • 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ào prompt.
  • 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ào negative_prompt.
  • lora_scale (float, tùy chọn) — Thang LoRA sẽ được áp dụng cho tất cả các lớp LoRA của text encoder nếu các lớp LoRA được nạp.
  • clip_skip (int, tùy chọn) — Số lượng lớp được bỏ qua từ CLIP khi tính toán các embedding của prompt. Giá trị 1 có nghĩa là đầu ra của lớp trước lớp cuối sẽ được sử dụng để tính toán các embedding của prompt.

Mã hóa prompt thành các trạng thái ẩn của text encoder.

AnimateDiffPipelineOutput

lớp diffusers.pipelines.animatediff.AnimateDiffPipelineOutput

< >

( frames: typing.Union[torch.Tensor, numpy.ndarray, list[list[PIL.Image.Image]]] )

Tham số

  • frames (torch.Tensor, np.ndarray, hoặc list[list[PIL.Image.Image]]) — danh sách các đầu ra video - Có thể là một danh sách lồng nhau có độ dài batch_size, trong đó mỗi danh sách con chứa các khung đã khử nhiễu

Lớp đầu ra cho các pipeline AnimateDiff.

Các chuỗi ảnh PIL có độ dài num_frames. Nó cũng có thể là một mảng NumPy hoặc tensor Torch có hình dạng (batch_size, num_frames, channels, height, width)

Update on GitHub