Diffusers 文档
文本到视频生成
并获得增强的文档体验
开始使用
🧪 此管道仅用于研究目的。
文本到视频生成
ModelScope 文本到视频技术报告由王九牛、袁杭杰、陈大友、张莹雅、王翔、张世伟撰写。
论文摘要如下:
本文介绍了 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 支持不同的优化技术,以改善管道的延迟和内存占用。由于视频通常比图像占用更多内存,我们可以启用 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
使用 PyTorch 2.0、“fp16”精度和上述技术生成 64 帧视频仅需**7 GB GPU 内存**。
我们也可以轻松地使用不同的调度器,使用与 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
类 diffusers.TextToVideoSDPipeline
< 来源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )
__调用__
< 来源 >( 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) — 较高的引导比例值鼓励模型生成与文本prompt
紧密相关的图像,但会牺牲图像质量。当guidance_scale > 1
时启用引导比例。 - negative_prompt (
str
或List[str]
, 可选) — 用于引导图像生成中不包含内容的提示词或提示词列表。如果未定义,您需要传递negative_prompt_embeds
。当不使用引导时(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
< 来源 >( 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 表示使用倒数第二层的输出计算提示词嵌入。
将提示编码为文本编码器隐藏状态。
VideoToVideoSDPipeline
class diffusers.VideoToVideoSDPipeline
< 来源 >( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )
__调用__
< 来源 >( 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
) — 视频帧或表示视频批次的张量,用作过程的起始点。如果直接传递潜变量,也可以接受视频潜变量作为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) — 较高的引导比例值鼓励模型生成与文本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
输入参数生成。 - 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 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
< 来源 >( 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 表示使用倒数第二层的输出计算提示词嵌入。
将提示编码为文本编码器隐藏状态。
TextToVideoSDPipelineOutput
class diffusers.pipelines.text_to_video_synthesis.TextToVideoSDPipelineOutput
< 来源 >( frames: typing.Union[torch.Tensor, numpy.ndarray, typing.List[typing.List[PIL.Image.Image]]] )
文本到视频流水线的输出类。
PIL 图像序列,长度为 num_frames
。也可以是形状为 (batch_size, num_frames, channels, height, width)
的 NumPy 数组或 Torch 张量