Diffusers 文档

文本到视频

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

🧪 此 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-vilabcerspense 找到。

使用示例

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

以下是一些示例输出

一位宇航员骑着马。
An astronaut riding a horse.
达斯·维德在海浪中冲浪。
Darth vader surfing in waves.

cerspense/zeroscope_v2_576w & cerspense/zeroscope_v2_XL

Zeroscope 是无水印模型,并在特定尺寸(例如 576x3201024x576)上进行了训练。应首先使用较低分辨率的检查点 cerspense/zeroscope_v2_576wTextToVideoSDPipeline 生成视频,然后可以使用 VideoToVideoSDPipelinecerspense/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

以下是一些示例输出

达斯·维德在海浪中冲浪。
Darth vader surfing in waves.

提示

视频生成是内存密集型的,降低内存使用量的一种方法是在管线的 UNet 上设置 enable_forward_chunking,这样您就不会一次运行整个前馈层。将其分解为循环中的块效率更高。

查看文本或图像到视频指南,了解有关某些参数如何影响视频生成以及如何通过减少内存使用量来优化推理的更多详细信息。

请务必查看调度器指南,了解如何探索调度器速度和质量之间的权衡,并查看跨管线重用组件部分,了解如何有效地将相同组件加载到多个管线中。

TextToVideoSDPipeline

class diffusers.TextToVideoSDPipeline

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )

参数

用于文本到视频生成的管线。

此模型继承自 DiffusionPipeline。有关所有管线通用的泛型方法的实现(下载、保存、在特定设备上运行等),请查看超类文档。

该管线还继承了以下加载方法

__call__

< >

( 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 ) TextToVideoSDPipelineOutputtuple

参数

  • prompt (strList[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 (strList[str], 可选) — 用于引导图像生成中不包含的内容的提示。如果未定义,则需要传递 negative_prompt_embeds。当不使用 guidance 时(guidance_scale < 1),将被忽略。
  • num_images_per_prompt (int, 可选, 默认为 1) — 每个提示要生成的图像数量。
  • eta (float, 可选, 默认为 0.0) — 对应于 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中将被忽略。
  • generator (torch.GeneratorList[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.Tensornp.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 表示将使用倒数第二层的输出用于计算提示词嵌入。

返回

TextToVideoSDPipelineOutputtuple

如果 return_dictTrue,则返回 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 (strList[str], 可选的) — 要编码的提示词
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个提示词应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器引导
  • negative_prompt (strList[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

< >

( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet3DConditionModel scheduler: KarrasDiffusionSchedulers )

参数

用于文本引导的视频到视频生成的 Pipeline。

此模型继承自 DiffusionPipeline。有关所有管线通用的泛型方法的实现(下载、保存、在特定设备上运行等),请查看超类文档。

该管线还继承了以下加载方法

__call__

< >

( 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 ) TextToVideoSDPipelineOutputtuple

参数

  • prompt (strList[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.GeneratorList[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.Tensornp.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。

返回

TextToVideoSDPipelineOutputtuple

如果 return_dictTrue,则返回 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 (strList[str], 可选) — 要编码的 prompt
  • device — (torch.device): torch 设备
  • num_images_per_prompt (int) — 每个 prompt 应生成的图像数量
  • do_classifier_free_guidance (bool) — 是否使用无分类器 guidance
  • negative_prompt (strList[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

< >

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

参数

  • frames (torch.Tensor, np.ndarray, 或 List[List[PIL.Image.Image]]) — 视频输出列表 - 它可以是长度为 batch_size 的嵌套列表,每个子列表包含去噪后的

text-to-video 管道的输出类。

长度为 num_frames 的 PIL 图像序列。它也可以是形状为 (batch_size, num_frames, channels, height, width) 的 NumPy 数组或 Torch 张量

< > GitHub 上更新