Diffusers 文件
使用 AnimateDiff 進行文字到影片生成
並獲得增強的文件體驗
開始使用
使用 AnimateDiff 進行文字到影片生成
概覽
AnimateDiff: 無需特定調整即可為個性化文字到影像擴散模型新增動畫 作者:Yuwei Guo, Ceyuan Yang, Anyi Rao, Yaohui Wang, Yu Qiao, Dahua Lin, Bo Dai。
論文摘要如下:
隨著文字到影像模型(例如 Stable Diffusion)和相應的個性化技術(如 DreamBooth 和 LoRA)的進步,每個人都可以以可承受的成本將自己的想象力轉化為高質量的影像。隨後,對影像動畫技術的需求巨大,以進一步將生成的靜態影像與運動動態相結合。在本報告中,我們提出了一個實用的框架,可以一勞永逸地為大多數現有個性化文字到影像模型新增動畫,從而省去了模型特定調整的工作。所提出的框架的核心是將新初始化的運動建模模組插入到凍結的文字到影像模型中,並在影片剪輯上對其進行訓練,以提取合理的運動先驗。一旦訓練完成,只需注入這個運動建模模組,所有源自相同基礎 T2I 的個性化版本都可以輕鬆成為文字驅動模型,生成多樣化且個性化的動畫影像。我們對動漫圖片和寫實照片的幾個公共代表性個性化文字到影像模型進行了評估,並證明我們提出的框架有助於這些模型生成時間上平滑的動畫剪輯,同時保留其輸出的領域和多樣性。程式碼和預訓練權重將在 此 https URL 公開提供。
可用管道
流水線 | 任務 | 演示 |
---|---|---|
AnimateDiffPipeline | 使用 AnimateDiff 進行文字到影片生成 | |
AnimateDiffControlNetPipeline | 使用 ControlNet 透過 AnimateDiff 進行受控影片到影片生成 | |
AnimateDiffSparseControlNetPipeline | 使用 SparseCtrl 透過 AnimateDiff 進行受控影片到影片生成 | |
AnimateDiffSDXLPipeline | 使用 AnimateDiff 進行影片到影片生成 | |
AnimateDiffVideoToVideoPipeline | 使用 AnimateDiff 進行影片到影片生成 | |
AnimateDiffVideoToVideoControlNetPipeline | 使用 ControlNet 透過 AnimateDiff 進行影片到影片生成 |
可用檢查點
Motion Adapter 檢查點可以在 guoyww 下找到。這些檢查點旨在與任何基於 Stable Diffusion 1.4/1.5 的模型一起使用。
使用示例
AnimateDiffPipeline
AnimateDiff 配合 MotionAdapter 檢查點和 Stable Diffusion 模型檢查點使用。MotionAdapter 是一系列 Motion Modules 的集合,負責在影像幀之間新增連貫的運動。這些模組在 Stable Diffusion UNet 中的 Resnet 和 Attention 塊之後應用。
以下示例演示瞭如何將 MotionAdapter 檢查點與 Diffusers 結合使用,以進行基於 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", torch_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, torch_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.enable_vae_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")
以下是一些樣本輸出
![]() |
AnimateDiff 更適用於經過微調的 Stable Diffusion 模型。如果您打算使用可以剪裁樣本的排程器,請確保透過在排程器中設定 clip_sample=False
來停用它,因為這也會對生成的樣本產生不利影響。此外,AnimateDiff 檢查點可能對排程器的 beta 排程敏感。我們建議將其設定為 linear
。
AnimateDiffControlNetPipeline
AnimateDiff 也可以與 ControlNets 一起使用。ControlNet 是由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《Adding Conditional Control to Text-to-Image Diffusion Models》 中引入的。透過 ControlNet 模型,您可以提供一個額外的控制影像來調整和控制 Stable Diffusion 的生成。例如,如果您提供深度圖,ControlNet 模型會生成一個影片,該影片將保留深度圖中的空間資訊。這是一種更靈活、更準確的影片生成控制方式。
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", torch_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", torch_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)
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)
以下是一些樣本輸出
源影片 | 輸出影片 |
---|---|
彈吉他的浣熊![]() | 一隻熊貓,彈著吉他,坐在粉色的小船上,在大海中,背景是山脈,逼真,高質量![]() |
AnimateDiffSparseControlNetPipeline
SparseCtrl: 為文字到影片擴散模型新增稀疏控制,用於透過 Yuwei Guo、Ceyuan Yang、Anyi Rao、Maneesh Agrawala、Dahua Lin 和 Bo Dai 實現文字到影片擴散模型中的受控生成。
論文摘要如下:
近年來,文字到影片(T2V),即根據給定的文字提示生成影片,取得了顯著進展。然而,僅僅依靠文字提示往往會導致由於空間不確定性而產生的模糊幀構圖。因此,研究界利用密集的結構訊號(例如,每幀深度/邊緣序列)來增強可控性,但其收集相應地增加了推理負擔。在這項工作中,我們提出了 SparseCtrl,以實現對時間稀疏訊號的靈活結構控制,如圖 1 所示,僅需要一個或幾個輸入。它整合了一個額外的條件編碼器來處理這些稀疏訊號,同時保持預訓練的 T2V 模型不變。所提出的方法與各種模態相容,包括草圖、深度圖和 RGB 影像,為影片生成提供了更實用的控制,並促進了故事板、深度渲染、關鍵幀動畫和插值等應用。大量的實驗證明了 SparseCtrl 在原始和個性化 T2V 生成器上的泛化能力。程式碼和模型將在 此 https URL 公開提供。
SparseCtrl 為受控文字到影片生成引入了以下檢查點
使用 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"
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")
以下是一些樣本輸出
![]() | ![]() | ![]() |
![]() |
使用 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"
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")
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")
以下是一些樣本輸出
![]() | ![]() |
AnimateDiffSDXLPipeline
AnimateDiff 也可以與 SDXL 模型一起使用。這目前是一項實驗性功能,因為目前只有運動介面卡檢查點的測試版可用。
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", 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.enable_vae_slicing()
pipe.enable_vae_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 也可用於生成視覺上相似的影片,或啟用從初始影片開始的風格/角色/背景或其他編輯,讓您無縫探索創意可能性。
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", torch_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, torch_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.enable_vae_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")
以下是一些樣本輸出
源影片 | 輸出影片 |
---|---|
彈吉他的浣熊![]() | 彈吉他的熊貓![]() |
瑪格特·羅位元寫,背景煙花,高質量![]() | 託尼·斯塔克特寫,小羅伯特·唐尼,煙花![]() |
AnimateDiffVideoToVideoControlNetPipeline
AnimateDiff 可與 ControlNet 結合使用,透過精確控制輸出來增強影片到影片的生成。ControlNet 由 Lvmin Zhang、Anyi Rao 和 Maneesh Agrawala 在 《為文字到影像擴散模型新增條件控制》 中引入,允許您使用額外的控制影像來調整 Stable Diffusion,以確保空間資訊在整個影片中得到保留。
此管道允許您同時根據原始影片和控制影像序列來調整生成。
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", torch_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", torch_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)
# 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)
以下是一些樣本輸出
源影片 | 輸出影片 |
---|---|
動漫女孩,跳舞![]() | 太空中的宇航員,跳舞![]() |
燈光和構圖從源影片中轉移而來。
使用 Motion LoRA
Motion LoRA 是一系列與 guoyww/animatediff-motion-adapter-v1-5-2
檢查點配合使用的 LoRA。這些 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", torch_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, torch_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.enable_vae_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")
![]() |
將 Motion LoRA 與 PEFT 結合使用
您還可以利用 PEFT 後端來組合 Motion LoRA 以建立更復雜的動畫。
首先安裝 PEFT:
pip install peft
然後您可以使用以下程式碼組合 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", torch_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, torch_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.enable_vae_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")
![]() |
使用 FreeInit
FreeInit: 彌合影片擴散模型中的初始化差距 作者:Tianxing Wu, Chenyang Si, Yuming Jiang, Ziqi Huang, Ziwei Liu。
FreeInit 是一種有效的方法,無需額外訓練即可提高使用影片擴散模型生成的影片的時間一致性和整體質量。它可以在推理時無縫應用於 AnimateDiff、ModelScope、VideoCrafter 和各種其他影片生成模型,透過迭代最佳化潛在初始化噪聲來工作。更多詳細資訊可在論文中找到。
以下示例演示了 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, torch_dtype=torch.float16).to("cuda")
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.enable_vae_slicing()
pipe.enable_vae_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 並非真正免費——改進的質量是以額外計算為代價的。它需要根據啟用時設定的 num_iters
引數進行幾次額外取樣。將 use_fast_sampling
引數設定為 True
可以提高整體效能(以犧牲質量為代價,但仍優於普通影片生成模型)。
未啟用 FreeInit | 已啟用 FreeInit |
---|---|
彈吉他的熊貓![]() | 彈吉他的熊貓![]() |
使用 AnimateLCM
AnimateLCM 是一個運動模組檢查點和一個 LCM LoRA,它們是使用一致性學習策略建立的,該策略將影像生成先驗和運動生成先驗的蒸餾解耦。
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.enable_vae_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")
![]() |
AnimateLCM 還與現有 Motion LoRA 相容。
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.enable_vae_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")
![]() |
使用 FreeNoise
FreeNoise: 透過噪聲重排程實現免調優更長影片擴散 作者:Haonan Qiu、Menghan Xia、Yong Zhang、Yingqing He、Xintao Wang、Ying Shan、Ziwei Liu。
FreeNoise 是一種取樣機制,可以透過噪聲重排程、滑動視窗上的時間注意力以及潛在幀的加權平均,使用短影片生成模型生成更長的影片。它還可以與多個提示一起使用,以實現插值影片生成。更多詳細資訊可在論文中找到。
目前支援與 FreeNoise 一起使用的 AnimateDiff 管道有:
- AnimateDiffPipeline
- AnimateDiffControlNetPipeline
- AnimateDiffVideoToVideoPipeline
- AnimateDiffVideoToVideoControlNetPipeline
為了使用 FreeNoise,在載入管道後,需要在推理程式碼中新增一行。
+ pipe.enable_free_noise()
此後,可以使用單個提示,或者將多個提示作為整數-字串對的字典傳遞。字典的整數鍵對應於該提示影響最大的幀索引。每個幀索引應對映到一個字串提示。字典中未傳遞的中間幀索引的提示是透過在傳遞的幀提示之間進行插值建立的。預設情況下,使用簡單的線性插值。但是,您可以透過在啟用 FreeNoise 時向 `prompt_interpolation_callback` 引數添加回調來自定義此行為。
完整示例
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", torch_dtype=dtype)
vae = AutoencoderKL.from_pretrained("stabilityai/sd-vae-ft-mse", torch_dtype=dtype)
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=motion_adapter, vae=vae, torch_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")
# 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)
FreeNoise 記憶體節省
由於 FreeNoise 同時處理多個幀,因此在建模過程中,所需的記憶體會超出普通消費級 GPU 的可用記憶體。我們識別的主要記憶體瓶頸是空間和時間注意力塊、上取樣和下采樣塊、ResNet 塊和前饋層。由於這些塊大多數只在通道/嵌入維度上有效操作,因此可以對批次維度進行分塊推理。AnimateDiff 中的批次維度本質上是空間([B x F, H x W, C]
)或時間(B x H x W, F, C
)的(請注意,這可能看起來違反直覺,但這裡的批次維度是正確的,因為空間塊跨 B x F
維度處理,而時間塊跨 B x H x W
維度處理)。我們引入了一個 SplitInferenceModule
,可以更輕鬆地在任何維度上進行分塊並執行推理。這節省了大量記憶體,但代價是需要更長的推理時間。
# Load pipeline and adapters
# ...
+ pipe.enable_free_noise_split_inference()
+ pipe.unet.enable_forward_chunking(16)
對 pipe.enable_free_noise_split_inference
方法的呼叫接受兩個引數:spatial_split_size
(預設為 256
)和 temporal_split_size
(預設為 16
)。這些可以根據您可用的 VRAM 進行配置。較小的拆分大小導致較低的記憶體使用,但推理速度較慢,而較大的拆分大小導致較快的推理,但需要更多記憶體。
使用 from_single_file 與 MotionAdapter
diffusers>=0.30.0
支援透過 from_single_file
將 AnimateDiff 檢查點以其原始格式載入到 MotionAdapter
中
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, torch_dtype=torch.float16)
pipe = AnimateDiffPipeline.from_pretrained("emilianJR/epiCRealism", motion_adapter=adapter)
AnimateDiffPipeline
class diffusers.AnimateDiffPipeline
< 源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler, diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler, diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (
CLIPTextModel
) — 凍結的文字編碼器(clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用於文字分詞的 CLIPTokenizer。 - unet (UNet2DConditionModel) — 用於建立 UNetMotionModel 以對編碼影片潛在空間進行去噪的 UNet2DConditionModel。
- motion_adapter (
MotionAdapter
) — 一個與unet
結合使用的MotionAdapter
,用於對編碼影片潛在空間進行去噪。 - scheduler (SchedulerMixin) — 一個排程器,與
unet
結合使用,用於對編碼影像潛在空間進行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 中的一個。
文字到影片生成管道。
此模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< 源 >( prompt: typing.Union[str, typing.List[str], NoneType] = None num_frames: typing.Optional[int] = 16 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] decode_chunk_size: int = 16 **kwargs ) → AnimateDiffPipelineOutput or tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則需要傳遞prompt_embeds
。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的高度(畫素)。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的寬度(畫素)。 - num_frames (
int
, 可選, 預設為 16) — 生成的影片幀數。預設為 16 幀,按每秒 8 幀計算,相當於 2 秒的影片。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但代價是推理速度變慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — 更高的引導尺度值會鼓勵模型生成與文字prompt
緊密相關的影像,但代價是影像質量會降低。當guidance_scale > 1
時啟用引導尺度。 - negative_prompt (
str
或List[str]
, 可選) — 引導影像生成時不包含的提示詞。如果未定義,則需要傳遞negative_prompt_embeds
。當不使用引導時(guidance_scale < 1
),此引數將被忽略。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, 可選) — 預先生成的從高斯分佈取樣的噪聲潛變數,用作影片生成的輸入。可用於使用不同的提示詞調整相同的生成。如果未提供,則使用提供的隨機generator
取樣生成潛變數張量。潛變數的形狀應為(batch_size, num_channel, num_frames, height, width)
。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入(提示詞權重)。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入(提示詞權重)。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 用於 IP-Adapter 的預先生成的影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影片的輸出格式。選擇torch.Tensor
、PIL.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 TextToVideoSDPipelineOutput,否則返回一個tuple
,其中第一個元素是生成的幀列表。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給self.processor
中定義的AttentionProcessor
。 - clip_skip (
int
, 可選) — 在計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理過程中每次去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。 - decode_chunk_size (
int
, 預設為16
) — 呼叫decode_latents
方法時每次解碼的幀數。
返回
AnimateDiffPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
用於生成的管道的呼叫函式。
示例
>>> 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
< source >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示詞 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示詞應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示詞。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用引導時(即guidance_scale
小於1
時忽略)。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示詞加權。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 應用於文字編碼器所有 LoRA 層的 LoRA 比例(如果已載入 LoRA 層)。 - clip_skip (
int
, 可選) — 在計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
AnimateDiffControlNetPipeline
class diffusers.AnimateDiffControlNetPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: KarrasDiffusionSchedulers feature_extractor: typing.Optional[transformers.models.clip.image_processing_clip.CLIPImageProcessor] = None image_encoder: typing.Optional[transformers.models.clip.modeling_clip.CLIPVisionModelWithProjection] = None )
引數
- vae (AutoencoderKL) — 變分自動編碼器 (VAE) 模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (
CLIPTextModel
) — 凍結文字編碼器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用於文字分詞的 CLIPTokenizer。 - unet (UNet2DConditionModel) — 用於建立 UNetMotionModel 以對編碼影片潛變數進行去噪的 UNet2DConditionModel。
- motion_adapter (
MotionAdapter
) — 用於與unet
結合使用的MotionAdapter
,對編碼影片潛變數進行去噪。 - scheduler (SchedulerMixin) — 用於與
unet
結合使用以對編碼影像潛變數進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
帶 ControlNet 引導的文字到影片生成管道。
此模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None num_frames: typing.Optional[int] = 16 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None conditioning_frames: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] decode_chunk_size: int = 16 ) → AnimateDiffPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示詞。如果未定義,則需要傳遞prompt_embeds
。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的高度(畫素)。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的寬度(畫素)。 - num_frames (
int
, 可選, 預設為 16) — 生成影片的幀數。預設為 16 幀,按每秒 8 幀計算,相當於 2 秒的影片。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但代價是推理速度會更慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — 較高的指導尺度值會鼓勵模型生成與文字prompt
密切相關的影像,但代價是影像質量較低。當guidance_scale > 1
時啟用指導尺度。 - negative_prompt (
str
或List[str]
, 可選) — 用於指導影像生成中不應包含的內容的提示。如果未定義,則需要傳入negative_prompt_embeds
。當不使用指導時(guidance_scale < 1
)則忽略。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在值,用作影片生成的輸入。可用於使用不同提示調整相同生成。如果未提供,則使用提供的隨機generator
進行取樣以生成潛在張量。潛在值的形狀應為(batch_size, num_channel, num_frames, height, width)
。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,則從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - ip_adapter_image (
PipelineImageInput
, 可選) — 用於 IP Adapters 的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 用於 IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP-adapter 的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,則應包含負影像嵌入。如果未提供,則根據ip_adapter_image
輸入引數計算嵌入。 - conditioning_frames (
List[PipelineImageInput]
, 可選) — ControlNet 輸入條件,為unet
提供生成指導。如果指定了多個 ControlNet,則影像必須作為列表傳遞,以便列表中的每個元素都可以正確批處理以輸入到單個 ControlNet。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影片的輸出格式。可選擇torch.Tensor
、PIL.Image
或np.array
。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 TextToVideoSDPipelineOutput 而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給self.processor
中定義的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出乘以controlnet_conditioning_scale
後再新增到原始unet
中的殘差。如果init
中指定了多個 ControlNet,則可以將其相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — 即使您刪除所有提示,ControlNet 編碼器也會嘗試識別輸入影像的內容。建議guidance_scale
值介於 3.0 到 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的步數總百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的步數總百分比。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 中跳過的層數。值為 1 表示使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理期間,每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
中指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
AnimateDiffPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
用於生成的管道的呼叫函式。
示例
encode_prompt
< source >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由指導 - negative_prompt (
str
或List[str]
, 可選) — 用於指導影像生成中不應包含的內容的提示。如果未定義,則必須傳入negative_prompt_embeds
。當不使用指導時(即guidance_scale
小於1
時),則忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則將從negative_prompt
輸入引數生成 negative_prompt_embeds。 - lora_scale (
float
, 可選) — 一個 LoRA 比例,如果載入了 LoRA 層,它將應用於文字編碼器的所有 LoRA 層。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 中跳過的層數。值為 1 表示使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
AnimateDiffSparseControlNetPipeline
類 diffusers.AnimateDiffSparseControlNetPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter controlnet: SparseControlNetModel scheduler: KarrasDiffusionSchedulers feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 用於編碼和解碼影像與潛在表示的變分自編碼器(VAE)模型。
- text_encoder (
CLIPTextModel
) — 凍結文字編碼器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用於標記文字的 CLIPTokenizer。 - unet (UNet2DConditionModel) — 用於建立 UNetMotionModel 以去噪編碼影片潛在值的 UNet2DConditionModel。
- motion_adapter (
MotionAdapter
) — 與unet
結合使用以去噪編碼影片潛在值的MotionAdapter
。 - scheduler (SchedulerMixin) — 用於與
unet
結合使用以去噪編碼影像潛在值的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 中的一個。
使用 SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion Models 中描述的方法進行受控文字到影片生成的管道。
此模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: int = 16 num_inference_steps: int = 50 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: int = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None conditioning_frames: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None output_type: str = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 controlnet_frame_indices: typing.List[int] = [0] guess_mode: bool = False clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] ) → AnimateDiffPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於指導影像生成的提示。如果未定義,則需要傳入prompt_embeds
。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的高度(畫素)。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的寬度(畫素)。 - num_frames (
int
, 可選, 預設為 16) — 生成影片的幀數。預設為 16 幀,按每秒 8 幀計算,相當於 2 秒的影片。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但代價是推理速度會更慢。 - guidance_scale (
float
, 可選, 預設為 7.5) — 較高的指導尺度值會鼓勵模型生成與文字prompt
密切相關的影像,但代價是影像質量較低。當guidance_scale > 1
時啟用指導尺度。 - negative_prompt (
str
或List[str]
, 可選) — 用於指導影像生成中不應包含的內容的提示。如果未定義,則需要傳入negative_prompt_embeds
。當不使用指導時(guidance_scale < 1
)則忽略。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, optional) — 預先生成的噪聲潛變數,從高斯分佈中取樣,用作影片生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,則潛變數張量透過使用提供的隨機generator
進行取樣生成。潛變數的形狀應為(batch_size, num_channel, num_frames, height, width)
。 - prompt_embeds (
torch.Tensor
, optional) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,則文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, optional) — 預先生成的負文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,則negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選):與 IP Adapters 配合使用的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預先生成的 IP-Adapter 影像嵌入。它應該是一個列表,長度與 IP-Adapter 的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,則嵌入將從ip_adapter_image
輸入引數計算。 - conditioning_frames (
List[PipelineImageInput]
, 可選) — 用於為unet
生成提供指導的 SparseControlNet 輸入。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影片的輸出格式。在torch.Tensor
、PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回 TextToVideoSDPipelineOutput 而不是普通的元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給self.processor
中定義的AttentionProcessor
。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始unet
中的殘差之前會乘以controlnet_conditioning_scale
。如果在init
中指定了多個 ControlNet,則可以將其相應的比例設定為列表。 - controlnet_frame_indices (
List[int]
) — 生成時必須應用條件幀的索引。可以提供多個幀來指導模型生成相似的結構輸出,其中unet
可以為插值影片“填充空白”,或者可以提供單個幀以獲得一般預期的結構。必須與conditioning_frames
具有相同的長度。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用預最終層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
, 可選) — 推理過程中每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類的._callback_tensor_inputs
屬性中列出的變數。
返回
AnimateDiffPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
用於生成的管道的呼叫函式。
示例
>>> 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
< 來源 >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由指導 - negative_prompt (
str
或List[str]
, 可選) — 不用於指導影像生成的提示。如果未定義,則必須傳遞negative_prompt_embeds
。當不使用指導時(即,如果guidance_scale
小於1
時忽略)。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,則negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 如果載入了 LoRA 層,則將應用於文字編碼器所有 LoRA 層的 LoRA 比例。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用預最終層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
AnimateDiffSDXLPipeline
class diffusers.AnimateDiffSDXLPipeline
< 來源 >( vae: AutoencoderKL text_encoder: CLIPTextModel text_encoder_2: CLIPTextModelWithProjection tokenizer: CLIPTokenizer tokenizer_2: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler, diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler, diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] image_encoder: CLIPVisionModelWithProjection = None feature_extractor: CLIPImageProcessor = None force_zeros_for_empty_prompt: bool = True )
引數
- vae (AutoencoderKL) — 變分自編碼器(VAE)模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (
CLIPTextModel
) — 凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字部分,特別是 clip-vit-large-patch14 變體。 - text_encoder_2 (
CLIPTextModelWithProjection
) — 第二個凍結的文字編碼器。Stable Diffusion XL 使用 CLIP 的文字和池化部分,特別是 laion/CLIP-ViT-bigG-14-laion2B-39B-b160k 變體。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer 類的分詞器。 - tokenizer_2 (
CLIPTokenizer
) — CLIPTokenizer 類的第二個分詞器。 - unet (UNet2DConditionModel) — 用於對編碼影像潛變數進行去噪的條件 U-Net 架構。
- scheduler (SchedulerMixin) — 與
unet
結合使用的排程器,用於對編碼影像潛變數進行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。 - force_zeros_for_empty_prompt (
bool
, 可選, 預設為"True"
) — 是否強制將負提示嵌入始終設定為 0。另請參閱stabilityai/stable-diffusion-xl-base-1-0
的配置。
使用 Stable Diffusion XL 進行文字到影片生成的管道。
此模型繼承自 DiffusionPipeline。請檢視超類文件,瞭解庫為所有管道實現的通用方法(例如下載或儲存、在特定裝置上執行等)。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- from_single_file() 用於載入
.ckpt
檔案 - load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< 來源 >( prompt: typing.Union[str, typing.List[str]] = None prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_frames: int = 16 height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.List[int] = None sigmas: typing.List[float] = None denoising_end: typing.Optional[float] = None guidance_scale: float = 5.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt_2: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None guidance_rescale: float = 0.0 original_size: typing.Optional[typing.Tuple[int, int]] = None crops_coords_top_left: typing.Tuple[int, int] = (0, 0) target_size: typing.Optional[typing.Tuple[int, int]] = None negative_original_size: typing.Optional[typing.Tuple[int, int]] = None negative_crops_coords_top_left: typing.Tuple[int, int] = (0, 0) negative_target_size: typing.Optional[typing.Tuple[int, int]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] ) → AnimateDiffPipelineOutput 或 tuple
引數
- prompt (
str
或List[str]
, 可選) — 用於指導影片生成的提示。如果未定義,則必須傳遞prompt_embeds
。 - prompt_2 (
str
或List[str]
, 可選) — 要傳送到tokenizer_2
和text_encoder_2
的提示。如果未定義,則prompt
將在兩個文字編碼器中使用。 - num_frames — 生成的影片幀數。預設為 16 幀,每秒 8 幀,相當於 2 秒的影片。
- height (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影片的高度(以畫素為單位)。為了獲得最佳效果,此值預設為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都將無法正常工作。 - width (
int
, 可選, 預設為 self.unet.config.sample_size * self.vae_scale_factor) — 生成影片的寬度(以畫素為單位)。為了獲得最佳效果,此值預設為 1024。對於 stabilityai/stable-diffusion-xl-base-1.0 和未專門針對低解析度進行微調的檢查點,任何低於 512 畫素的值都將無法正常工作。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但代價是推理速度變慢。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步,適用於其set_timesteps
方法支援timesteps
引數的排程器。如果未定義,將使用傳遞num_inference_steps
時的預設行為。必須按降序排列。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於其set_timesteps
方法支援sigmas
引數的排程器。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - denoising_end (
float
, 可選) — 指定時,確定在故意提前終止之前要完成的總去噪過程的分數(介於 0.0 和 1.0 之間)。因此,返回的樣本仍將保留大量噪聲,具體由排程器選擇的離散時間步決定。當此管道作為“去噪器混合”多管道設定的一部分時,應理想地使用denoising_end
引數,如最佳化影像輸出中所詳述。 - guidance_scale (
float
, 可選, 預設為 5.0) — Classifier-Free Diffusion Guidance 中定義的指導比例。guidance_scale
定義為 Imagen Paper 中公式 2 的w
。透過設定guidance_scale > 1
啟用指導比例。較高的指導比例鼓勵生成與文字prompt
緊密相關的影像,通常以犧牲較低影片質量為代價。 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影片生成的提示或提示列表。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
時),此引數將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 不用於引導影片生成的提示或提示列表,將被髮送到tokenizer_2
和text_encoder_2
。如果未定義,則negative_prompt
將用於兩個文字編碼器。 - num_videos_per_prompt (
int
, 可選, 預設為 1) — 每個提示生成的影片數量。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η):https://huggingface.co/papers/2010.02502。僅適用於 schedulers.DDIMScheduler,對於其他排程器將被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 一個或多個 torch generator(s),用於使生成過程確定化。 - latents (
torch.Tensor
, 可選) — 預生成的噪聲潛在變數,從高斯分佈中取樣,用作影片生成的輸入。可用於使用不同提示調整相同生成。如果未提供,將使用提供的隨機generator
取樣生成一個潛在變數張量。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,負文字嵌入將從negative_prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化負文字嵌入將從negative_prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 預生成的 IP-Adapter 影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影片的輸出格式。在 PIL:PIL.Image.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回~pipelines.stable_diffusion_xl.AnimateDiffPipelineOutput
而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將作為引數傳遞給 diffusers.models.attention_processor 中定義的self.processor
的AttentionProcessor
。 - guidance_rescale (
float
, 可選, 預設為 0.0) — Common Diffusion Noise Schedules and Sample Steps are Flawed 中提出的引導重新縮放因子。guidance_scale
定義為 Common Diffusion Noise Schedules and Sample Steps are Flawed 方程 16 中的φ
。引導重新縮放因子應在使用零終端 SNR 時修復過度曝光。 - original_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 如果original_size
與target_size
不同,影像將顯示為縮小或放大。如果未指定,original_size
預設為(height, width)
。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。 - crops_coords_top_left (
Tuple[int]
, 可選, 預設為 (0, 0)) —crops_coords_top_left
可用於生成一個影像,該影像看起來像是從crops_coords_top_left
位置向下“裁剪”的。通常透過將crops_coords_top_left
設定為 (0, 0) 來獲得良好、居中的影像。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。 - target_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 在大多數情況下,target_size
應設定為生成影像的所需高度和寬度。如果未指定,它將預設為(height, width)
。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。 - negative_original_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 基於特定影像解析度對生成過程進行負面條件限制。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - negative_crops_coords_top_left (
Tuple[int]
, 可選, 預設為 (0, 0)) — 基於特定裁剪座標對生成過程進行負面條件限制。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - negative_target_size (
Tuple[int]
, 可選, 預設為 (1024, 1024)) — 基於目標影像解析度對生成過程進行負面條件限制。在大多數情況下,它應與target_size
相同。SDXL 微條件的一部分,如 https://huggingface.co/papers/2307.01952 第 2.2 節所述。有關更多資訊,請參閱此問題討論串:https://github.com/huggingface/diffusers/issues/4208。 - callback_on_step_end (
Callable
, 可選) — 在推理期間,每個去噪步驟結束時呼叫的函式。該函式透過以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。
返回
AnimateDiffPipelineOutput 或 tuple
如果 return_dict
為 True
,則返回 AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
呼叫管道進行生成時呼叫的函式。
示例
>>> 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.enable_vae_slicing()
>>> pipe.enable_vae_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
< source 源 >( prompt: str prompt_2: typing.Optional[str] = None device: typing.Optional[torch.device] = None num_videos_per_prompt: int = 1 do_classifier_free_guidance: bool = True negative_prompt: typing.Optional[str] = None negative_prompt_2: typing.Optional[str] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None pooled_prompt_embeds: typing.Optional[torch.Tensor] = None negative_pooled_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示 - prompt_2 (
str
或List[str]
, 可選) — 將傳送到tokenizer_2
和text_encoder_2
的提示或提示列表。如果未定義,則prompt
將用於兩個文字編碼器。 - device — (
torch.device
): torch 裝置 - num_videos_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳入negative_prompt_embeds
。當不使用引導時(即,如果guidance_scale
小於1
時),此引數將被忽略。 - negative_prompt_2 (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示列表,將被髮送到tokenizer_2
和text_encoder_2
。如果未定義,則negative_prompt
將用於兩個文字編碼器。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,負文字嵌入將從negative_prompt
輸入引數生成。 - pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化文字嵌入將從prompt
輸入引數生成。 - negative_pooled_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負池化文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,池化負文字嵌入將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 如果載入了 LoRA 層,將應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子。 - clip_skip (
int
, 可選) — 計算提示嵌入時要跳過的 CLIP 層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
get_guidance_scale_embedding
< source 源 >( w: Tensor embedding_dim: int = 512 dtype: dtype = torch.float32 ) → torch.Tensor
AnimateDiffVideoToVideoPipeline
class diffusers.AnimateDiffVideoToVideoPipeline
< source 源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler, diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler, diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 變分自動編碼器(VAE)模型,用於將影像編碼和解碼為潛在表示。
- text_encoder (
CLIPTextModel
) — 凍結文字編碼器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用於文字分詞的 CLIPTokenizer。 - unet (UNet2DConditionModel) — 用於建立 UNetMotionModel 以對編碼影片潛在變數進行去噪的 UNet2DConditionModel。
- motion_adapter (
MotionAdapter
) — 一個MotionAdapter
,與unet
結合使用,以對編碼影片潛在變數進行去噪。 - scheduler (SchedulerMixin) — 一個排程器,與
unet
結合使用以對編碼影像潛在變數進行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
用於影片到影片生成的管道。
此模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< source 源 >( video: typing.List[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 enforce_inference_steps: bool = False timesteps: typing.Optional[typing.List[int]] = None sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.5 strength: float = 0.8 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] decode_chunk_size: int = 16 ) → pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput 或 tuple
引數
- video (
List[PipelineImageInput]
) — 用於條件生成的輸入影片。必須是影片影像/幀的列表。 - prompt (
str
或List[str]
, 可選) — 用於引導影像生成的提示或提示列表。如果未定義,則需要傳入prompt_embeds
。 - height (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的畫素高度。 - width (
int
, optional, defaults toself.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的畫素寬度。 - num_inference_steps (
int
, optional, defaults to 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但會犧牲推理速度。 - timesteps (
List[int]
, optional) — 用於去噪過程的自定義時間步,適用於其set_timesteps
方法支援timesteps
引數的排程器。如果未定義,將使用傳遞num_inference_steps
時的預設行為。必須按降序排列。 - sigmas (
List[float]
, optional) — 用於去噪過程的自定義 sigmas,適用於其set_timesteps
方法支援sigmas
引數的排程器。如果未定義,將使用傳遞num_inference_steps
時的預設行為。 - strength (
float
, optional, defaults to 0.8) — 強度越高,原始影片與生成影片之間的差異越大。 - guidance_scale (
float
, optional, defaults to 7.5) — 較高的指導比例值會促使模型生成與文字prompt
緊密相關的影像,但影像質量會降低。當guidance_scale > 1
時,啟用指導比例。 - negative_prompt (
str
orList[str]
, optional) — 用於指導影像生成時不包含內容的提示。如果未定義,需要傳入negative_prompt_embeds
。當不使用指導時(guidance_scale < 1
)將被忽略。 - eta (
float
, optional, defaults to 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中將被忽略。 - generator (
torch.Generator
orList[torch.Generator]
, optional) — 一個torch.Generator
,用於使生成具有確定性。 - latents (
torch.Tensor
, optional) — 預先生成的從高斯分佈取樣的噪聲潛在變數,用作影片生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,則使用提供的隨機generator
取樣生成一個潛在張量。潛在變數的形狀應為(batch_size, num_channel, num_frames, height, width)
。 - prompt_embeds (
torch.Tensor
, optional) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,將從prompt
輸入引數生成文字嵌入。 - negative_prompt_embeds (
torch.Tensor
, optional) — 預先生成的負文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, optional): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, optional) — 用於 IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP 介面卡的數量相同。每個元素都應該是一個形狀為(batch_size, num_images, emb_dim)
的張量。如果do_classifier_free_guidance
設定為True
,它應該包含負影像嵌入。如果未提供,嵌入將從ip_adapter_image
輸入引數計算。 - output_type (
str
, optional, defaults to"pil"
) — 生成影片的輸出格式。在torch.Tensor
、PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, optional, defaults toTrue
) — 是否返回AnimateDiffPipelineOutput
而不是普通元組。 - cross_attention_kwargs (
dict
, optional) — 一個 kwargs 字典,如果指定,將作為AttentionProcessor
中定義的self.processor
傳遞。 - clip_skip (
int
, optional) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
, optional) — 在推理過程中每個去噪步驟結束時呼叫的函式。該函式透過以下引數呼叫:callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)
。callback_kwargs
將包含callback_on_step_end_tensor_inputs
指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, optional) —callback_on_step_end
函式的張量輸入列表。列表中指定的張量將作為callback_kwargs
引數傳遞。您只能包含管道類._callback_tensor_inputs
屬性中列出的變數。 - decode_chunk_size (
int
, defaults to16
) — 呼叫decode_latents
方法時每次解碼的幀數。
如果 return_dict
為 True
,則返回 pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
用於生成的管道的呼叫函式。
示例
encode_prompt
< source >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 待編碼的提示 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用無分類器指導 - negative_prompt (
str
或List[str]
, 可選) — 不用於指導影像生成的提示。如果未定義,必須傳遞negative_prompt_embeds
。當不使用指導時(即,如果guidance_scale
小於1
),將被忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預先生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從prompt
輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預先生成的負文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,negative_prompt_embeds
將從negative_prompt
輸入引數生成。 - lora_scale (
float
, 可選) — 如果載入了 LoRA 層,將應用於文字編碼器所有 LoRA 層的 LoRA 縮放因子。 - clip_skip (
int
, 可選) — 計算提示嵌入時從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
AnimateDiffVideoToVideoControlNetPipeline
class diffusers.AnimateDiffVideoToVideoControlNetPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: typing.Union[diffusers.models.unets.unet_2d_condition.UNet2DConditionModel, diffusers.models.unets.unet_motion_model.UNetMotionModel] motion_adapter: MotionAdapter controlnet: typing.Union[diffusers.models.controlnets.controlnet.ControlNetModel, typing.List[diffusers.models.controlnets.controlnet.ControlNetModel], typing.Tuple[diffusers.models.controlnets.controlnet.ControlNetModel], diffusers.models.controlnets.multicontrolnet.MultiControlNetModel] scheduler: typing.Union[diffusers.schedulers.scheduling_ddim.DDIMScheduler, diffusers.schedulers.scheduling_pndm.PNDMScheduler, diffusers.schedulers.scheduling_lms_discrete.LMSDiscreteScheduler, diffusers.schedulers.scheduling_euler_discrete.EulerDiscreteScheduler, diffusers.schedulers.scheduling_euler_ancestral_discrete.EulerAncestralDiscreteScheduler, diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler] feature_extractor: CLIPImageProcessor = None image_encoder: CLIPVisionModelWithProjection = None )
引數
- vae (AutoencoderKL) — 用於將影像編碼和解碼為潛在表示的變分自編碼器 (VAE) 模型。
- text_encoder (
CLIPTextModel
) — 凍結的文字編碼器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用於對文字進行標記的 CLIPTokenizer。 - unet (UNet2DConditionModel) — 用於建立 UNetMotionModel 以對編碼影片潛在變數進行去噪的 UNet2DConditionModel。
- motion_adapter (
MotionAdapter
) — 一個MotionAdapter
,與unet
結合使用,用於對編碼影片潛在變數進行去噪。 - controlnet (ControlNetModel 或
List[ControlNetModel]
或Tuple[ControlNetModel]
或MultiControlNetModel
) — 在去噪過程中為unet
提供額外的條件。如果將多個 ControlNet 設定為列表,則每個 ControlNet 的輸出將相加在一起以建立組合的額外條件。 - scheduler (SchedulerMixin) — 與
unet
結合使用以對編碼影像潛在變數進行去噪的排程器。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
帶 ControlNet 指導的影片到影片生成管道。
此模型繼承自 DiffusionPipeline。有關所有管道實現的通用方法(下載、儲存、在特定裝置上執行等),請檢視超類文件。
該管道還繼承了以下載入方法
- load_textual_inversion() 用於載入文字反演嵌入
- load_lora_weights() 用於載入 LoRA 權重
- save_lora_weights() 用於儲存 LoRA 權重
- load_ip_adapter() 用於載入 IP 介面卡
__call__
< source >( video: typing.List[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 enforce_inference_steps: bool = False timesteps: typing.Optional[typing.List[int]] = None sigmas: typing.Optional[typing.List[float]] = None guidance_scale: float = 7.5 strength: float = 0.8 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None num_videos_per_prompt: typing.Optional[int] = 1 eta: float = 0.0 generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None ip_adapter_image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor], NoneType] = None ip_adapter_image_embeds: typing.Optional[typing.List[torch.Tensor]] = None conditioning_frames: typing.Optional[typing.List[typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]]]] = None output_type: typing.Optional[str] = 'pil' return_dict: bool = True cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None controlnet_conditioning_scale: typing.Union[float, typing.List[float]] = 1.0 guess_mode: bool = False control_guidance_start: typing.Union[float, typing.List[float]] = 0.0 control_guidance_end: typing.Union[float, typing.List[float]] = 1.0 clip_skip: typing.Optional[int] = None callback_on_step_end: typing.Optional[typing.Callable[[int, int, typing.Dict], NoneType]] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] decode_chunk_size: int = 16 ) → pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput 或 tuple
引數
- video (
List[PipelineImageInput]
) — 用於條件生成輸入的影片。必須是影片影像/幀的列表。 - prompt (
str
或List[str]
, 可選) — 用於指導影像生成的提示。如果未定義,需要傳遞prompt_embeds
。 - height (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的畫素高度。 - width (
int
, 可選, 預設為self.unet.config.sample_size * self.vae_scale_factor
) — 生成影片的畫素寬度。 - num_inference_steps (
int
, 可選, 預設為 50) — 去噪步數。更多的去噪步數通常會帶來更高質量的影片,但會犧牲推理速度。 - timesteps (
List[int]
, 可選) — 用於去噪過程的自定義時間步,適用於其 `set_timesteps` 方法支援 `timesteps` 引數的排程器。如果未定義,將使用傳遞 `num_inference_steps` 時的預設行為。必須按降序排列。 - sigmas (
List[float]
, 可選) — 用於去噪過程的自定義 sigmas,適用於其 `set_timesteps` 方法支援 `sigmas` 引數的排程器。如果未定義,將使用傳遞 `num_inference_steps` 時的預設行為。 - strength (
float
, 可選, 預設為 0.8) — 強度越高,原始影片和生成影片之間的差異越大。 - guidance_scale (
float
, 可選, 預設為 7.5) — 引導比例值越高,模型越能生成與文字 `prompt` 密切相關的影像,但影像質量會降低。當 `guidance_scale > 1` 時啟用引導比例。 - negative_prompt (
str
或List[str]
, 可選) — 指導影像生成中不包含的內容的提示或提示列表。如果未定義,您需要傳遞 `negative_prompt_embeds`。當不使用引導時 (`guidance_scale < 1`) 將忽略。 - eta (
float
, 可選, 預設為 0.0) — 對應於 DDIM 論文中的引數 eta (η)。僅適用於 DDIMScheduler,在其他排程器中被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可選) — 用於使生成具有確定性的torch.Generator
。 - latents (
torch.Tensor
, 可選) — 從高斯分佈中取樣的預生成噪聲潛在變數,用作影片生成的輸入。可用於使用不同的提示調整相同的生成。如果未提供,將使用提供的隨機 `generator` 進行取樣生成一個潛在變數張量。潛在變數的形狀應為 `(batch_size, num_channel, num_frames, height, width)`。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,文字嵌入將從 `prompt` 輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入(提示權重)。如果未提供,`negative_prompt_embeds` 將從 `negative_prompt` 輸入引數生成。 - ip_adapter_image — (
PipelineImageInput
, 可選): 用於 IP 介面卡的可選影像輸入。 - ip_adapter_image_embeds (
List[torch.Tensor]
, 可選) — 用於 IP-Adapter 的預生成影像嵌入。它應該是一個列表,長度與 IP 介面卡數量相同。每個元素應該是一個形狀為 `(batch_size, num_images, emb_dim)` 的張量。如果 `do_classifier_free_guidance` 設定為 `True`,它應該包含負影像嵌入。如果未提供,嵌入將從 `ip_adapter_image` 輸入引數計算。 - conditioning_frames (
List[PipelineImageInput]
, 可選) — ControlNet 輸入條件,用於為 `unet` 提供生成指導。如果指定了多個 ControlNet,影像必須作為列表傳遞,以便列表的每個元素可以正確批處理以輸入到單個 ControlNet。 - output_type (
str
, 可選, 預設為"pil"
) — 生成影片的輸出格式。在torch.Tensor
、PIL.Image
或np.array
之間選擇。 - return_dict (
bool
, 可選, 預設為True
) — 是否返回AnimateDiffPipelineOutput
而不是普通元組。 - cross_attention_kwargs (
dict
, 可選) — 一個 kwargs 字典,如果指定,將傳遞給self.processor
中定義的 `AttentionProcessor`。 - controlnet_conditioning_scale (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 的輸出在新增到原始 `unet` 中的殘差之前乘以 `controlnet_conditioning_scale`。如果在 `init` 中指定了多個 ControlNet,您可以將相應的比例設定為列表。 - guess_mode (
bool
, 可選, 預設為False
) — 即使您刪除所有提示,ControlNet 編碼器也會嘗試識別輸入影像的內容。建議 `guidance_scale` 值在 3.0 到 5.0 之間。 - control_guidance_start (
float
或List[float]
, 可選, 預設為 0.0) — ControlNet 開始應用的步數總百分比。 - control_guidance_end (
float
或List[float]
, 可選, 預設為 1.0) — ControlNet 停止應用的步數總百分比。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。 - callback_on_step_end (
Callable
, 可選) — 在推理過程中,每個去噪步驟結束時呼叫的函式。該函式將使用以下引數呼叫:`callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`。`callback_kwargs` 將包含 `callback_on_step_end_tensor_inputs` 指定的所有張量列表。 - callback_on_step_end_tensor_inputs (
List
, 可選) — `callback_on_step_end` 函式的張量輸入列表。列表中指定的張量將作為 `callback_kwargs` 引數傳遞。您只能包含管道類 `._callback_tensor_inputs` 屬性中列出的變數。 - decode_chunk_size (
int
, 預設為16
) — 呼叫 `decode_latents` 方法時一次解碼的幀數。
如果 return_dict
為 True
,則返回 pipelines.animatediff.pipeline_output.AnimateDiffPipelineOutput,否則返回一個 tuple
,其中第一個元素是生成的幀列表。
用於生成的管道的呼叫函式。
示例
encode_prompt
< 原始檔 >( prompt device num_images_per_prompt do_classifier_free_guidance negative_prompt = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None lora_scale: typing.Optional[float] = None clip_skip: typing.Optional[int] = None )
引數
- prompt (
str
或List[str]
, 可選) — 要編碼的提示 - device — (
torch.device
): torch 裝置 - num_images_per_prompt (
int
) — 每個提示應生成的影像數量 - do_classifier_free_guidance (
bool
) — 是否使用分類器自由引導 - negative_prompt (
str
或List[str]
, 可選) — 不用於引導影像生成的提示或提示列表。如果未定義,則必須傳遞 `negative_prompt_embeds`。當不使用引導時(即,如果 `guidance_scale` 小於 `1`),則忽略。 - prompt_embeds (
torch.Tensor
, 可選) — 預生成的文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,文字嵌入將從 `prompt` 輸入引數生成。 - negative_prompt_embeds (
torch.Tensor
, 可選) — 預生成的負面文字嵌入。可用於輕鬆調整文字輸入,例如提示權重。如果未提供,`negative_prompt_embeds` 將從 `negative_prompt` 輸入引數生成。 - lora_scale (
float
, 可選) — 應用於文字編碼器所有 LoRA 層的 LoRA 比例(如果已載入 LoRA 層)。 - clip_skip (
int
, 可選) — 在計算提示嵌入時,從 CLIP 跳過的層數。值為 1 表示將使用倒數第二層的輸出計算提示嵌入。
將提示編碼為文字編碼器隱藏狀態。
AnimateDiffPipelineOutput
class diffusers.pipelines.animatediff.AnimateDiffPipelineOutput
< 原始檔 >( frames: typing.Union[torch.Tensor, numpy.ndarray, typing.List[typing.List[PIL.Image.Image]]] )
AnimateDiff 管道的輸出類。
PIL 影像序列,長度為 num_frames
。也可以是形狀為 (batch_size, num_frames, channels, height, width)
的 NumPy 陣列或 Torch 張量