Diffusers 文档
文本到视频
并获得增强的文档体验
开始使用
🧪 此 pipeline 仅用于研究目的。
文本到视频
ModelScope 文本到视频技术报告 作者:Jiuniu Wang, Hangjie Yuan, Dayou Chen, Yingya Zhang, Xiang Wang, Shiwei Zhang。
该论文的摘要是
本文介绍了 ModelScopeT2V,这是一种从文本到图像合成模型(即 Stable Diffusion)演变而来的文本到视频合成模型。ModelScopeT2V 融入了时空块,以确保帧生成的一致性和平滑的运动过渡。该模型可以适应训练和推理过程中不同的帧数,使其适用于图像-文本和视频-文本数据集。ModelScopeT2V 汇集了三个组件(即 VQGAN、文本编码器和去噪 UNet),总共包含 17 亿个参数,其中 5 亿个参数专用于时间功能。该模型在三个评估指标上展示了优于最先进方法的性能。代码和在线演示可在 https://modelscope.cn/models/damo/text-to-video-synthesis/summary 上找到。
您可以在项目页面、原始代码库上找到有关文本到视频的更多信息,并在演示中试用。官方检查点可在damo-vilab 和 cerspense 找到。
使用示例
text-to-video-ms-1.7b
让我们开始生成一个短视频,默认长度为 16 帧(8 fps 时为 2 秒)
import torch
from diffusers import DiffusionPipeline
from diffusers.utils import export_to_video
pipe = DiffusionPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16")
pipe = pipe.to("cuda")
prompt = "Spiderman is surfing"
video_frames = pipe(prompt).frames[0]
video_path = export_to_video(video_frames)
video_path
Diffusers 支持不同的优化技术,以提高 pipeline 的延迟和内存占用。由于视频通常比图像更占用内存,我们可以启用 CPU 卸载和 VAE 切片,以控制内存占用。
让我们在同一 GPU 上使用 CPU 卸载和 VAE 切片生成一个 8 秒(64 帧)的视频
import torch
from diffusers import DiffusionPipeline
from diffusers.utils import export_to_video
pipe = DiffusionPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16")
pipe.enable_model_cpu_offload()
# memory optimization
pipe.enable_vae_slicing()
prompt = "Darth Vader surfing a wave"
video_frames = pipe(prompt, num_frames=64).frames[0]
video_path = export_to_video(video_frames)
video_path
仅需 7 GB 的 GPU 内存即可使用 PyTorch 2.0、“fp16” 精度和上述技术生成 64 个视频帧。
我们还可以轻松使用不同的 scheduler,使用与 Stable Diffusion 相同的方法
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.utils import export_to_video
pipe = DiffusionPipeline.from_pretrained("damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.enable_model_cpu_offload()
prompt = "Spiderman is surfing"
video_frames = pipe(prompt, num_inference_steps=25).frames[0]
video_path = export_to_video(video_frames)
video_path
以下是一些示例输出
![]() | ![]() |
cerspense/zeroscope_v2_576w & cerspense/zeroscope_v2_XL
Zeroscope 是无水印模型,并在特定尺寸(例如 576x320
和 1024x576
)上进行了训练。应首先使用较低分辨率的检查点 cerspense/zeroscope_v2_576w
和 TextToVideoSDPipeline 生成视频,然后可以使用 VideoToVideoSDPipeline 和 cerspense/zeroscope_v2_XL
进行放大。
import torch
from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
from diffusers.utils import export_to_video
from PIL import Image
pipe = DiffusionPipeline.from_pretrained("cerspense/zeroscope_v2_576w", torch_dtype=torch.float16)
pipe.enable_model_cpu_offload()
# memory optimization
pipe.unet.enable_forward_chunking(chunk_size=1, dim=1)
pipe.enable_vae_slicing()
prompt = "Darth Vader surfing a wave"
video_frames = pipe(prompt, num_frames=24).frames[0]
video_path = export_to_video(video_frames)
video_path
现在可以放大视频了
pipe = DiffusionPipeline.from_pretrained("cerspense/zeroscope_v2_XL", torch_dtype=torch.float16)
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe.enable_model_cpu_offload()
# memory optimization
pipe.unet.enable_forward_chunking(chunk_size=1, dim=1)
pipe.enable_vae_slicing()
video = [Image.fromarray(frame).resize((1024, 576)) for frame in video_frames]
video_frames = pipe(prompt, video=video, strength=0.6).frames[0]
video_path = export_to_video(video_frames)
video_path
以下是一些示例输出
![]() |
提示
视频生成是内存密集型的,降低内存使用量的一种方法是在管线的 UNet 上设置 enable_forward_chunking
,这样您就不会一次运行整个前馈层。将其分解为循环中的块效率更高。
查看文本或图像到视频指南,了解有关某些参数如何影响视频生成以及如何通过减少内存使用量来优化推理的更多详细信息。
TextToVideoSDPipeline
class diffusers.TextToVideoSDPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )
参数
- vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将图像编码和解码为潜在表示形式,以及从潜在表示形式解码为图像。
- text_encoder (
CLIPTextModel
) — 冻结的文本编码器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — CLIPTokenizer,用于文本标记化。 - unet (UNet3DConditionModel) — UNet3DConditionModel,用于对编码后的视频潜在空间进行去噪。
- scheduler (SchedulerMixin) — 与
unet
结合使用的调度器,用于对编码后的图像潜在空间进行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
用于文本到视频生成的管线。
此模型继承自 DiffusionPipeline。有关所有管线通用的泛型方法的实现(下载、保存、在特定设备上运行等),请查看超类文档。
该管线还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: int = 16 num_inference_steps: int = 50 guidance_scale: float = 9.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None 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 output_type: typing.Optional[str] = 'np' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None ) → TextToVideoSDPipelineOutput 或 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) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会以降低图像质量为代价。当guidance_scale > 1
时,guidance scale 启用。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不包含的内容的提示。如果未定义,则需要传递negative_prompt_embeds
。当不使用 guidance 时(guidance_scale < 1
),将被忽略。 - num_images_per_prompt (
int
, 可选, 默认为 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
输入参数生成。 - output_type (
str
, 可选, 默认为"np"
) — 生成视频的输出格式。在torch.Tensor
或np.array
之间选择。 - return_dict (
bool
, 可选, 默认为True
) — 是否返回 TextToVideoSDPipelineOutput 而不是普通元组。 - callback (
Callable
, 可选) — 在推理期间每callback_steps
步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选, 默认为 1) — 调用callback
函数的频率。如果未指定,则在每个步骤中调用回调。 - cross_attention_kwargs (
dict
, 可选的) — 一个 kwargs 字典,如果指定,则会传递给在self.processor
中定义的AttentionProcessor
。 - clip_skip (
int
, 可选的) — 在计算提示词嵌入时,从 CLIP 模型中跳过的层数。值为 1 表示将使用倒数第二层的输出用于计算提示词嵌入。
返回
TextToVideoSDPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 TextToVideoSDPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成帧的列表。
用于生成的管道调用函数。
示例
>>> import torch
>>> from diffusers import TextToVideoSDPipeline
>>> from diffusers.utils import export_to_video
>>> pipe = TextToVideoSDPipeline.from_pretrained(
... "damo-vilab/text-to-video-ms-1.7b", torch_dtype=torch.float16, variant="fp16"
... )
>>> pipe.enable_model_cpu_offload()
>>> prompt = "Spiderman is surfing"
>>> video_frames = pipe(prompt).frames[0]
>>> video_path = export_to_video(video_frames)
>>> video_path
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 表示将使用倒数第二层的输出用于计算提示词嵌入。
将提示词编码为文本编码器隐藏状态。
VideoToVideoSDPipeline
class diffusers.VideoToVideoSDPipeline
< source >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )
参数
- vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将视频编码和解码为潜在表示形式。
- text_encoder (
CLIPTextModel
) — 冻结的文本编码器 (clip-vit-large-patch14)。 - tokenizer (
CLIPTokenizer
) — 用于标记文本的 CLIPTokenizer。 - unet (UNet3DConditionModel) — 用于对编码的视频潜在变量进行去噪的 UNet3DConditionModel。
- scheduler (SchedulerMixin) — 一个调度器,与
unet
结合使用,以对编码的图像潜在变量进行去噪。可以是 DDIMScheduler、LMSDiscreteScheduler 或 PNDMScheduler 之一。
用于文本引导的视频到视频生成的 Pipeline。
此模型继承自 DiffusionPipeline。有关所有管线通用的泛型方法的实现(下载、保存、在特定设备上运行等),请查看超类文档。
该管线还继承了以下加载方法
- load_textual_inversion() 用于加载文本反演嵌入
- load_lora_weights() 用于加载 LoRA 权重
- save_lora_weights() 用于保存 LoRA 权重
__call__
< source >( prompt: typing.Union[str, typing.List[str]] = None video: typing.Union[typing.List[numpy.ndarray], torch.Tensor] = None strength: float = 0.6 num_inference_steps: int = 50 guidance_scale: float = 15.0 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None 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 output_type: typing.Optional[str] = 'np' return_dict: bool = True callback: typing.Optional[typing.Callable[[int, int, torch.Tensor], NoneType]] = None callback_steps: int = 1 cross_attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None clip_skip: typing.Optional[int] = None ) → TextToVideoSDPipelineOutput 或 tuple
参数
- prompt (
str
或List[str]
, 可选的) — 用于引导图像生成的提示或提示词。如果未定义,则需要传递prompt_embeds
。 - video (
List[np.ndarray]
或torch.Tensor
) —video
帧或表示视频批次的张量,用作过程的起点。也可以接受视频潜在变量作为image
,如果直接传递潜在变量,则不会再次编码。 - strength (
float
, 可选的, 默认为 0.8) — 指示转换参考video
的程度。必须介于 0 和 1 之间。video
用作起点,strength
越大,向其添加的噪声就越多。去噪步骤的数量取决于最初添加的噪声量。当strength
为 1 时,添加的噪声最大,去噪过程将运行在num_inference_steps
中指定的完整迭代次数。值为 1 本质上会忽略video
。 - num_inference_steps (
int
, 可选的, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的视频,但会牺牲推理速度。 - guidance_scale (
float
, 可选,默认为 7.5) — 更高的 guidance scale 值会鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲较低的图像质量。当guidance_scale > 1
时, Guidance scale 启用。 - eta (
float
, 可选,默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。 - generator (
torch.Generator
或List[torch.Generator]
, 可选) — 用于使生成过程具有确定性的torch.Generator
。 - latents (
torch.Tensor
, 可选) — 预生成的噪声 latents,从高斯分布中采样,用作视频生成的输入。可用于通过不同的 prompts 调整相同的生成结果。如果未提供,则会使用提供的随机generator
采样生成 latents 张量。 Latents 的形状应为(batch_size, num_channel, num_frames, height, width)
。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入(prompt 权重)。如果未提供,则会从negative_prompt
输入参数生成negative_prompt_embeds
。 - output_type (
str
, 可选,默认为"np"
) — 生成视频的输出格式。在torch.Tensor
或np.array
之间选择。 - return_dict (
bool
, 可选,默认为True
) — 是否返回 TextToVideoSDPipelineOutput 而不是普通元组。 - callback (
Callable
, 可选) — 在推理期间每callback_steps
步调用一次的函数。该函数使用以下参数调用:callback(step: int, timestep: int, latents: torch.Tensor)
。 - callback_steps (
int
, 可选,默认为 1) — 调用callback
函数的频率。如果未指定,则每步都调用回调函数。 - cross_attention_kwargs (
dict
, 可选) — 一个 kwargs 字典,如果指定,则会传递给self.processor
中定义的AttentionProcessor
。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预最终层的输出计算 prompt embeddings。
返回
TextToVideoSDPipelineOutput 或 tuple
如果 return_dict
为 True
,则返回 TextToVideoSDPipelineOutput,否则返回 tuple
,其中第一个元素是包含生成帧的列表。
用于生成的管道调用函数。
示例
>>> import torch
>>> from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
>>> from diffusers.utils import export_to_video
>>> pipe = DiffusionPipeline.from_pretrained("cerspense/zeroscope_v2_576w", torch_dtype=torch.float16)
>>> pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.to("cuda")
>>> prompt = "spiderman running in the desert"
>>> video_frames = pipe(prompt, num_inference_steps=40, height=320, width=576, num_frames=24).frames[0]
>>> # safe low-res video
>>> video_path = export_to_video(video_frames, output_video_path="./video_576_spiderman.mp4")
>>> # let's offload the text-to-image model
>>> pipe.to("cpu")
>>> # and load the image-to-image model
>>> pipe = DiffusionPipeline.from_pretrained(
... "cerspense/zeroscope_v2_XL", torch_dtype=torch.float16, revision="refs/pr/15"
... )
>>> pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
>>> pipe.enable_model_cpu_offload()
>>> # The VAE consumes A LOT of memory, let's make sure we run it in sliced mode
>>> pipe.vae.enable_slicing()
>>> # now let's upscale it
>>> video = [Image.fromarray(frame).resize((1024, 576)) for frame in video_frames]
>>> # and denoise it
>>> video_frames = pipe(prompt, video=video, strength=0.6).frames[0]
>>> video_path = export_to_video(video_frames, output_video_path="./video_1024_spiderman.mp4")
>>> video_path
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]
, 可选) — 要编码的 prompt - device — (
torch.device
): torch 设备 - num_images_per_prompt (
int
) — 每个 prompt 应生成的图像数量 - do_classifier_free_guidance (
bool
) — 是否使用无分类器 guidance - negative_prompt (
str
或List[str]
, 可选) — 不用于指导图像生成的 prompt 或 prompts。如果未定义,则必须传递negative_prompt_embeds
。当不使用 guidance 时(即,如果guidance_scale
小于1
),此参数将被忽略。 - prompt_embeds (
torch.Tensor
, 可选) — 预生成的文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从prompt
输入参数生成文本 embeddings。 - negative_prompt_embeds (
torch.Tensor
, 可选) — 预生成的负面文本 embeddings。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,则将从negative_prompt
输入参数生成 negative_prompt_embeds。 - lora_scale (
float
, 可选) — LoRA 缩放比例,如果加载了 LoRA 层,则将应用于文本编码器的所有 LoRA 层。 - clip_skip (
int
, 可选) — 从 CLIP 中跳过的层数,用于计算 prompt embeddings。值为 1 表示将使用预最终层的输出计算 prompt embeddings。
将提示词编码为文本编码器隐藏状态。
TextToVideoSDPipelineOutput
class diffusers.pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput
< source >( frames: typing.Union[torch.Tensor, numpy.ndarray, typing.List[typing.List[PIL.Image.Image]]] )
text-to-video 管道的输出类。
长度为 num_frames
的 PIL 图像序列。它也可以是形状为 (batch_size, num_frames, channels, height, width)
的 NumPy 数组或 Torch 张量