Diffusers 文档

CogVideoX

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

CogVideoX

CogVideoX:带有专家 Transformer 的文本到视频扩散模型 来自清华大学 & ZhipuAI,作者:Zhuoyi Yang, Jiayan Teng, Wendi Zheng, Ming Ding, Shiyu Huang, Jiazheng Xu, Yuanming Yang, Wenyi Hong, Xiaohan Zhang, Guanyu Feng, Da Yin, Xiaotao Gu, Yuxuan Zhang, Weihan Wang, Yean Cheng, Ting Liu, Bin Xu, Yuxiao Dong, Jie Tang。

以下是论文摘要

我们介绍了 CogVideoX,这是一个大型扩散 Transformer 模型,旨在根据文本提示生成视频。为了高效地建模视频数据,我们建议利用 3D 变分自编码器 (VAE) 来压缩视频的空间和时间维度。为了提高文本-视频对齐效果,我们提出了一个专家 Transformer,并结合专家自适应 LayerNorm,以促进两种模态之间的深度融合。通过采用渐进式训练技术,CogVideoX 擅长生成连贯、时长较长且具有显著运动特征的视频。此外,我们还开发了一个有效的文本-视频数据处理流程,其中包括各种数据预处理策略和视频字幕方法。这显著地帮助提升了 CogVideoX 的性能,提高了生成质量和语义对齐度。结果表明,CogVideoX 在多项机器指标和人工评估中均展示了最先进的性能。CogVideoX-2B 的模型权重已公开在 https://github.com/THUDM/CogVideo 上提供。

请务必查看 调度器(Schedulers)指南,了解如何在调度器速度和质量之间进行权衡,并查看 跨管道重用组件(reuse components across pipelines) 部分,了解如何有效地将相同的组件加载到多个管道中。

此管道由 zRzRzRzRzRzRzR 贡献。原始代码库可以在 这里 找到。原始权重可以在 hf.co/THUDM 下找到。

有三个官方 CogVideoX 检查点(checkpoints)用于文本到视频(text-to-video)和视频到视频(video-to-video)。

检查点(checkpoints) 推荐的推理数据类型(dtype)
THUDM/CogVideoX-2b torch.float16
THUDM/CogVideoX-5b torch.bfloat16
THUDM/CogVideoX1.5-5b torch.bfloat16

有两个官方 CogVideoX 检查点可用于图像到视频(image-to-video)。

检查点(checkpoints) 推荐的推理数据类型(dtype)
THUDM/CogVideoX-5b-I2V torch.bfloat16
THUDM/CogVideoX-1.5-5b-I2V torch.bfloat16

对于 CogVideoX 1.5 系列

  • 文本到视频 (T2V) 在 1360x768 的分辨率下效果最佳,因为它是在该特定分辨率下训练的。
  • 图像到视频 (I2V) 适用于多种分辨率。宽度可以在 768 到 1360 之间变化,但高度必须为 768。高度/宽度必须能被 16 整除。
  • T2V 和 I2V 模型都支持生成 81 帧和 161 帧的视频,并且在此值下效果最佳。建议以 16 FPS(帧每秒)导出视频。

有两个官方 CogVideoX 检查点支持姿势可控生成(由 Alibaba-PAI 团队提供)。

检查点(checkpoints) 推荐的推理数据类型(dtype)
alibaba-pai/CogVideoX-Fun-V1.1-2b-Pose torch.bfloat16
alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose torch.bfloat16

推理(Inference)

使用 torch.compile 来减少推理延迟。

首先,加载管道(pipeline)

import torch
from diffusers import CogVideoXPipeline, CogVideoXImageToVideoPipeline
from diffusers.utils import export_to_video,load_image
pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-5b").to("cuda") # or "THUDM/CogVideoX-2b" 

如果您正在使用图像到视频(image-to-video)管道,请按如下方式加载它

pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V").to("cuda")

然后将管道的 transformer 组件的内存布局更改为 torch.channels_last

pipe.transformer.to(memory_format=torch.channels_last)

编译组件并运行推理

pipe.transformer = torch.compile(pipeline.transformer, mode="max-autotune", fullgraph=True)

# CogVideoX works well with long and well-described prompts
prompt = "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical atmosphere of this unique musical performance."
video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]

在 80GB A100 机器上的 T2V 基准测试 结果如下

Without torch.compile(): Average inference time: 96.89 seconds.
With torch.compile(): Average inference time: 76.27 seconds.

内存优化(Memory optimization)

CogVideoX-2b 需要大约 19 GB 的 GPU 内存来解码 49 帧(在 8 FPS 下为 6 秒视频),输出分辨率为 720x480 (宽 x 高),这使得它无法在消费级 GPU 或免费的 T4 Colab 上运行。以下内存优化可以用来减少内存占用。如需复现,您可以参考 脚本。

  • pipe.enable_model_cpu_offload():
    • 在不启用 CPU 卸载的情况下,内存使用量为 33 GB
    • 在启用 CPU 卸载的情况下,内存使用量为 19 GB
  • pipe.enable_sequential_cpu_offload():
    • 类似于 enable_model_cpu_offload,但可以显著减少内存使用量,但会牺牲推理速度
    • 启用后,内存使用量低于 4 GB
  • pipe.vae.enable_tiling():
    • 在启用 CPU 卸载和 tiling 的情况下,内存使用量为 11 GB
  • pipe.vae.enable_slicing()

量化推理(Quantized inference)

可以使用 torchaooptimum-quanto 来量化文本编码器(text encoder)、Transformer 和 VAE 模块,以降低内存需求。这使得在免费的 T4 Colab 或更低 VRAM 的 GPU 上运行模型成为可能!

还值得注意的是,torchao 量化与 torch.compile 完全兼容,这可以大大提高推理速度。此外,模型可以序列化并以量化数据类型存储,以使用 torchao 节省磁盘空间。在下面的 gists 中查找示例和基准测试。

CogVideoXPipeline

class diffusers.CogVideoXPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

参数(Parameters)

  • vae (AutoencoderKL) — 变分自编码器(VAE)模型,用于将视频编码和解码为潜在表示(latent representations)。
  • text_encoder (T5EncoderModel) — 冻结的文本编码器(frozen text-encoder)。CogVideoX 使用 T5;特别是 t5-v1_1-xxl 变体。
  • tokenizer (T5Tokenizer) — T5Tokenizer 类的分词器(Tokenizer)。
  • transformer (CogVideoXTransformer3DModel) — 一个文本条件 CogVideoXTransformer3DModel,用于对编码后的视频潜在空间(video latents)进行去噪。
  • scheduler (SchedulerMixin) — 一个调度器(scheduler),与 transformer 结合使用,以对编码后的视频潜在空间(video latents)进行去噪。

用于文本到视频生成的管道,使用 CogVideoX。

此模型继承自 DiffusionPipeline。查看超类文档以获取库为所有管道实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False 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.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) CogVideoXPipelineOutputtuple

参数(Parameters)

  • prompt (strList[str], 可选) — 用于引导图像生成的提示(prompt)或提示列表。如果未定义,则必须传递 prompt_embeds 代替。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示(prompt)或提示列表。如果未定义,则必须传递 negative_prompt_embeds 代替。当不使用引导(guidance)时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • height (int, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的高度像素。默认设置为 480 以获得最佳效果。
  • width (int, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的宽度像素。默认设置为 720 以获得最佳效果。
  • num_frames (int, 默认为 48) — 要生成的帧数。必须能被 self.vae_scale_factor_temporal 整除。生成的视频将包含 1 个额外的帧,因为 CogVideoX 使用 (num_seconds * fps + 1) 帧进行条件控制,其中 num_seconds 为 6,fps 为 8。然而,由于视频可以以任何 fps 保存,因此唯一需要满足的条件是上述的可除性条件。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高的图像质量,但会牺牲更慢的推理速度。
  • timesteps (List[int], 可选) — 自定义的时间步长(timesteps),用于支持在其 set_timesteps 方法中使用 timesteps 参数的调度器(schedulers)的去噪过程。如果未定义,将使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float, 可选, 默认为 7.0) — 指导尺度(guidance scale),如 Classifier-Free Diffusion Guidance 中所定义。 guidance_scale 定义为 Imagen Paper 的等式 2 中的 w。通过设置 guidance_scale > 1 启用指导尺度。较高的指导尺度鼓励生成与文本 prompt 紧密相关的图像,但通常以降低图像质量为代价。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个提示生成的视频数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或一组 torch 生成器,用于使生成过程确定化。
  • latents (torch.FloatTensor, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于通过不同的提示调整相同的生成结果。如果未提供,则将使用提供的随机 generator 采样生成潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 AttentionProcessor,如 diffusers.models.attention_processorself.processor 下定义的那样。
  • 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 属性中列出的变量。
  • max_sequence_length (int, 默认为 226) — 编码提示中的最大序列长度。必须与 self.transformer.config.max_text_seq_length 保持一致,否则可能导致不良结果。

返回值

CogVideoXPipelineOutputtuple

如果 return_dict 为 True,则返回 CogVideoXPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import CogVideoXPipeline
>>> from diffusers.utils import export_to_video

>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
>>> pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", torch_dtype=torch.float16).to("cuda")
>>> prompt = (
...     "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest. "
...     "The panda's fluffy paws strum a miniature acoustic guitar, producing soft, melodic tunes. Nearby, a few other "
...     "pandas gather, watching curiously and some clapping in rhythm. Sunlight filters through the tall bamboo, "
...     "casting a gentle glow on the scene. The panda's face is expressive, showing concentration and joy as it plays. "
...     "The background includes a small, flowing stream and vibrant green foliage, enhancing the peaceful and magical "
...     "atmosphere of this unique musical performance."
... )
>>> video = pipe(prompt=prompt, guidance_scale=6, num_inference_steps=50).frames[0]
>>> export_to_video(video, "output.mp4", fps=8)

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

参数(Parameters)

  • prompt (strList[str], 可选) — 要编码的提示
  • negative_prompt (strList[str], 可选) — 不引导图像生成的提示。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器引导。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个提示应生成的视频数量。用于放置结果嵌入的 torch 设备
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • device — (torch.device, 可选): torch 设备
  • dtype — (torch.dtype, 可选): torch 数据类型

将提示编码为文本编码器隐藏状态。

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

如果启用,则禁用 QKV 投影融合。

CogVideoXImageToVideoPipeline

class diffusers.CogVideoXImageToVideoPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

参数(Parameters)

  • vae (AutoencoderKL) — 变分自动编码器 (VAE) 模型,用于将视频编码和解码为潜在表示形式,以及从潜在表示形式解码为视频。
  • text_encoder (T5EncoderModel) — 冻结的文本编码器。 CogVideoX 使用 T5;特别是 t5-v1_1-xxl 变体。
  • tokenizer (T5Tokenizer) — T5Tokenizer 类的分词器。
  • transformer (CogVideoXTransformer3DModel) — 一个文本条件化的 CogVideoXTransformer3DModel,用于对编码的视频潜在变量进行去噪。
  • scheduler (SchedulerMixin) — 与 transformer 结合使用的调度器,用于对编码后的视频潜在变量进行去噪。

使用 CogVideoX 的图像到视频生成管线。

此模型继承自 DiffusionPipeline。查看超类文档以获取库为所有管道实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, typing.List[PIL.Image.Image], typing.List[numpy.ndarray], typing.List[torch.Tensor]] prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_frames: int = 49 num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False 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.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) CogVideoXPipelineOutput or tuple

参数(Parameters)

  • image (PipelineImageInput) — 用于条件生成的输入图像。必须是图像、图像列表或 torch.Tensor
  • prompt (str or List[str], optional) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须传递 prompt_embeds
  • negative_prompt (str or List[str], optional) — 不用于引导图像生成的提示词或提示词列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • height (int, optional, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素高度。默认设置为 480 以获得最佳效果。
  • width (int, optional, defaults to self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素宽度。默认设置为 720 以获得最佳效果。
  • num_frames (int, defaults to 48) — 要生成的帧数。必须可被 self.vae_scale_factor_temporal 整除。生成的视频将包含 1 个额外的帧,因为 CogVideoX 使用 (num_seconds * fps + 1) 帧进行条件化,其中 num_seconds 为 6,fps 为 8。但是,由于视频可以以任何 fps 保存,因此唯一需要满足的条件是上述的可除性。
  • num_inference_steps (int, optional, defaults to 50) — 去噪步骤的数量。更多的去噪步骤通常会以较慢的推理速度为代价,产生更高质量的图像。
  • timesteps (List[int], optional) — 用于去噪过程的自定义时间步,适用于在其 set_timesteps 方法中支持 timesteps 参数的调度器。如果未定义,则将使用传递 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float, optional, defaults to 7.0) — 引导尺度,如 Classifier-Free Diffusion Guidance 中所定义。 guidance_scale 定义为 Imagen Paper 的公式 2 中的 w。通过设置 guidance_scale > 1 启用引导尺度。较高的引导尺度鼓励生成与文本 prompt 紧密相关的图像,但通常以较低的图像质量为代价。
  • num_videos_per_prompt (int, optional, defaults to 1) — 每个提示词要生成的视频数量。
  • generator (torch.Generator or List[torch.Generator], optional) — 用于使生成具有确定性的单个或列表形式的 torch 生成器
  • latents (torch.FloatTensor, optional) — 预生成的噪声潜在变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词调整相同的生成。如果未提供,则将通过使用提供的随机 generator 进行采样来生成潜在变量张量。
  • prompt_embeds (torch.FloatTensor, optional) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, optional) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 提示词权重。如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • output_type (str, optional, defaults to "pil") — 生成图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, optional, defaults to True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, optional) — 一个 kwargs 字典,如果指定,则会传递给在 diffusers.models.attention_processorself.processor 下定义的 AttentionProcessor
  • 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` 属性中列出的变量。
  • max_sequence_length (int, defaults to 226) — 编码提示词中的最大序列长度。必须与 self.transformer.config.max_text_seq_length 一致,否则可能导致不良结果。

返回值

CogVideoXPipelineOutputtuple

如果 return_dict 为 True,则返回 CogVideoXPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import CogVideoXImageToVideoPipeline
>>> from diffusers.utils import export_to_video, load_image

>>> pipe = CogVideoXImageToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b-I2V", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")

>>> prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
>>> image = load_image(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
... )
>>> video = pipe(image, prompt, use_dynamic_cfg=True)
>>> export_to_video(video.frames[0], "output.mp4", fps=8)

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

参数(Parameters)

  • prompt (str or List[str], optional) — 要编码的提示词
  • negative_prompt (str or List[str], optional) — 不用于引导图像生成的提示词或提示词列表。如果未定义,则必须传递 negative_prompt_embeds。当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • do_classifier_free_guidance (bool, 可选,默认为 True) — 是否使用无分类器引导(classifier free guidance)。
  • num_videos_per_prompt (int, 可选,默认为 1) — 每个提示应生成的视频数量。用于放置结果嵌入的 torch 设备。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可以用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可以用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • device — (torch.device, 可选): torch 设备
  • dtype — (torch.dtype, 可选): torch 数据类型

将提示编码为文本编码器隐藏状态。

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

如果启用,则禁用 QKV 投影融合。

CogVideoXVideoToVideoPipeline

class diffusers.CogVideoXVideoToVideoPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: typing.Union[diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler, diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler] )

参数(Parameters)

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将视频编码和解码为潜在表示。
  • text_encoder (T5EncoderModel) — 冻结的文本编码器。 CogVideoX 使用 T5; 特别是 t5-v1_1-xxl 变体。
  • tokenizer (T5Tokenizer) — T5Tokenizer 类的分词器。
  • transformer (CogVideoXTransformer3DModel) — 一个文本条件 CogVideoXTransformer3DModel,用于对编码的视频潜在空间进行去噪。
  • scheduler (SchedulerMixin) — 调度器,与 transformer 结合使用,以对编码的视频潜在空间进行去噪。

用于使用 CogVideoX 进行视频到视频生成的 Pipeline。

此模型继承自 DiffusionPipeline。查看超类文档以获取库为所有管道实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( video: typing.List[PIL.Image.Image] = None prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None strength: float = 0.8 guidance_scale: float = 6 use_dynamic_cfg: bool = False 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.FloatTensor] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) CogVideoXPipelineOutput or tuple

参数(Parameters)

  • video (List[PIL.Image.Image]) — 作为生成条件输入的视频。 必须是视频的图像/帧列表。
  • prompt (strList[str], 可选) — 用于引导图像生成的提示。 如果未定义,则必须传递 prompt_embeds
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示。 如果未定义,则必须传递 negative_prompt_embeds。 当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • height (int, 可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素高度。 默认设置为 480 以获得最佳效果。
  • width (int, 可选,默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成图像的像素宽度。 默认设置为 720 以获得最佳效果。
  • num_inference_steps (int, 可选,默认为 50) — 去噪步骤的数量。 更多的去噪步骤通常会带来更高质量的图像,但代价是推理速度较慢。
  • timesteps (List[int], 可选) — 用于支持在其 set_timesteps 方法中使用 timesteps 参数的调度器的去噪过程的自定义时间步长。如果未定义,将使用传递 num_inference_steps 时的默认行为。 必须按降序排列。
  • strength (float, 可选, 默认为 0.8) — 较高的 strength 值会导致原始视频和生成的视频之间存在更多差异。
  • guidance_scale (float, 可选, 默认为 7.0) — Guidance scale,定义见 Classifier-Free Diffusion Guidanceguidance_scale 定义为 Imagen Paper 的公式 2 中的 w。通过设置 guidance_scale > 1 启用 Guidance scale。较高的 guidance scale 鼓励生成与文本 prompt 紧密相关的图像,但通常会牺牲图像质量。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的视频数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或一组 torch generator(s),用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的 prompt 微调相同的生成结果。如果未提供,将通过使用提供的随机 generator 采样来生成潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成的图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — kwargs 字典,如果指定,则作为 self.processor 下定义的 AttentionProcessor 传递到 diffusers.models.attention_processor
  • 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 属性中列出的变量。
  • max_sequence_length (int, 默认为 226) — 编码 prompt 中的最大序列长度。必须与 self.transformer.config.max_text_seq_length 一致,否则可能导致较差的结果。

返回值

CogVideoXPipelineOutputtuple

如果 return_dict 为 True,则返回 CogVideoXPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import CogVideoXDPMScheduler, CogVideoXVideoToVideoPipeline
>>> from diffusers.utils import export_to_video, load_video

>>> # Models: "THUDM/CogVideoX-2b" or "THUDM/CogVideoX-5b"
>>> pipe = CogVideoXVideoToVideoPipeline.from_pretrained("THUDM/CogVideoX-5b", torch_dtype=torch.bfloat16)
>>> pipe.to("cuda")
>>> pipe.scheduler = CogVideoXDPMScheduler.from_config(pipe.scheduler.config)

>>> input_video = load_video(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
... )
>>> prompt = (
...     "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and "
...     "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in "
...     "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, "
...     "moons, but the remainder of the scene is mostly realistic."
... )

>>> video = pipe(
...     video=input_video, prompt=prompt, strength=0.8, guidance_scale=6, num_inference_steps=50
... ).frames[0]
>>> export_to_video(video, "output.mp4", fps=8)

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

参数(Parameters)

  • prompt (strList[str], 可选) — 要编码的 prompt
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的 prompt 或 prompts。如果未定义,则必须传递 negative_prompt_embeds。当不使用 guidance 时(即,如果 guidance_scale 小于 1 时)将被忽略。
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器 guidance。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个 prompt 应生成的视频数量。用于放置结果嵌入的 torch 设备
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • device — (torch.device, 可选): torch 设备
  • dtype — (torch.dtype, 可选): torch dtype

将提示编码为文本编码器隐藏状态。

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

如果启用,则禁用 QKV 投影融合。

CogVideoXFunControlPipeline

class diffusers.CogVideoXFunControlPipeline

< >

( tokenizer: T5Tokenizer text_encoder: T5EncoderModel vae: AutoencoderKLCogVideoX transformer: CogVideoXTransformer3DModel scheduler: KarrasDiffusionSchedulers )

参数(Parameters)

  • vae (AutoencoderKL) — 变分自编码器 (VAE) 模型,用于将视频编码和解码为潜在表示形式,以及从潜在表示形式解码为视频。
  • text_encoder (T5EncoderModel) — 冻结的文本编码器。CogVideoX 使用 T5;特别是 t5-v1_1-xxl 变体。
  • tokenizer (T5Tokenizer) — T5Tokenizer 类的分词器。
  • transformer (CogVideoXTransformer3DModel) — 文本条件 CogVideoXTransformer3DModel,用于对编码后的视频潜在空间进行去噪。
  • scheduler (SchedulerMixin) — 调度器,与 transformer 结合使用,以对编码后的视频潜在空间进行去噪。

使用 CogVideoX Fun 进行受控文本到视频生成的管线。

此模型继承自 DiffusionPipeline。查看超类文档以获取库为所有管道实现的通用方法(例如下载或保存、在特定设备上运行等)。

__call__

< >

( prompt: typing.Union[str, typing.List[str], NoneType] = None negative_prompt: typing.Union[str, typing.List[str], NoneType] = None control_video: typing.Optional[typing.List[PIL.Image.Image]] = None height: typing.Optional[int] = None width: typing.Optional[int] = None num_inference_steps: int = 50 timesteps: typing.Optional[typing.List[int]] = None guidance_scale: float = 6 use_dynamic_cfg: bool = False 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 control_video_latents: typing.Optional[torch.Tensor] = None prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None output_type: str = 'pil' return_dict: bool = True attention_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None callback_on_step_end: typing.Union[typing.Callable[[int, int, typing.Dict], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = None callback_on_step_end_tensor_inputs: typing.List[str] = ['latents'] max_sequence_length: int = 226 ) CogVideoXPipelineOutput or tuple

参数(Parameters)

  • prompt (strList[str], 可选) — 用于引导图像生成的提示或提示列表。如果未定义,则必须传递 prompt_embeds 代替。
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。如果未定义,则必须传递 negative_prompt_embeds 代替。不使用 guidance 时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • control_video (List[PIL.Image.Image]) — 用于控制生成的控制视频。必须是视频的图像/帧列表。如果未提供,则必须提供 control_video_latents
  • height (int, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成的图像的像素高度。默认设置为 480 以获得最佳效果。
  • width (int, 可选, 默认为 self.transformer.config.sample_height * self.vae_scale_factor_spatial) — 生成的图像的像素宽度。默认设置为 720 以获得最佳效果。
  • num_inference_steps (int, 可选, 默认为 50) — 去噪步骤的数量。更多的去噪步骤通常会带来更高质量的图像,但会牺牲推理速度。
  • timesteps (List[int], 可选) — 用于去噪过程的自定义时间步长,与调度器结合使用,这些调度器在其 set_timesteps 方法中支持 timesteps 参数。如果未定义,则将使用传递 num_inference_steps 时的默认行为。必须以降序排列。
  • guidance_scale (float, 可选, 默认为 6.0) — Classifier-Free Diffusion Guidance 中定义的 Guidance scale。 guidance_scale 定义为 Imagen Paper 等式 2 中的 w。通过设置 guidance_scale > 1 启用 Guidance scale。较高的 guidance scale 鼓励生成与文本 prompt 紧密关联的图像,但通常以降低图像质量为代价。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个 prompt 生成的视频数量。
  • generator (torch.GeneratorList[torch.Generator], 可选) — 一个或多个 torch generator(s) 以使生成具有确定性。
  • latents (torch.Tensor, 可选) — 预生成的噪声潜在变量,从高斯分布中采样,用作视频生成的输入。可用于使用不同的 prompt 调整相同的生成。如果未提供,则将通过使用提供的随机 generator 进行采样来生成潜在变量张量。
  • control_video_latents (torch.Tensor, 可选) — 预生成的控制潜在变量,从高斯分布中采样,用作用于控制视频生成的输入。如果未提供,则必须提供 control_video
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。可用于轻松调整文本输入,例如 prompt 权重。如果未提供,将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • output_type (str, 可选, 默认为 "pil") — 生成的图像的输出格式。在 PIL: PIL.Image.Imagenp.array 之间选择。
  • return_dict (bool, 可选, 默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,则会传递给 AttentionProcessor,如 diffusers.models.attention_processorself.processor 下定义的那样。
  • 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 属性中列出的变量。
  • max_sequence_length (int, 默认为 226) — 编码 prompt 中的最大序列长度。必须与 self.transformer.config.max_text_seq_length 一致,否则可能导致不良结果。

返回值

CogVideoXPipelineOutputtuple

如果 return_dict 为 True,则返回 CogVideoXPipelineOutput,否则返回 tuple。当返回元组时,第一个元素是包含生成图像的列表。

调用管道进行生成时调用的函数。

示例

>>> import torch
>>> from diffusers import CogVideoXFunControlPipeline, DDIMScheduler
>>> from diffusers.utils import export_to_video, load_video

>>> pipe = CogVideoXFunControlPipeline.from_pretrained(
...     "alibaba-pai/CogVideoX-Fun-V1.1-5b-Pose", torch_dtype=torch.bfloat16
... )
>>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
>>> pipe.to("cuda")

>>> control_video = load_video(
...     "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
... )
>>> prompt = (
...     "An astronaut stands triumphantly at the peak of a towering mountain. Panorama of rugged peaks and "
...     "valleys. Very futuristic vibe and animated aesthetic. Highlights of purple and golden colors in "
...     "the scene. The sky is looks like an animated/cartoonish dream of galaxies, nebulae, stars, planets, "
...     "moons, but the remainder of the scene is mostly realistic."
... )

>>> video = pipe(prompt=prompt, control_video=control_video).frames[0]
>>> export_to_video(video, "output.mp4", fps=8)

encode_prompt

< >

( prompt: typing.Union[str, typing.List[str]] negative_prompt: typing.Union[str, typing.List[str], NoneType] = None do_classifier_free_guidance: bool = True num_videos_per_prompt: int = 1 prompt_embeds: typing.Optional[torch.Tensor] = None negative_prompt_embeds: typing.Optional[torch.Tensor] = None max_sequence_length: int = 226 device: typing.Optional[torch.device] = None dtype: typing.Optional[torch.dtype] = None )

参数(Parameters)

  • prompt (strList[str], 可选) — 要编码的提示
  • negative_prompt (strList[str], 可选) — 不用于引导图像生成的提示或提示列表。 如果未定义,则必须传入 negative_prompt_embeds。 当不使用引导时忽略(即,如果 guidance_scale 小于 1 则忽略)。
  • do_classifier_free_guidance (bool, 可选, 默认为 True) — 是否使用无分类器引导。
  • num_videos_per_prompt (int, 可选, 默认为 1) — 每个提示应生成的视频数量。 用于放置结果嵌入的 torch 设备
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 prompt 输入参数生成文本嵌入。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负面文本嵌入。 可用于轻松调整文本输入,例如 提示权重。 如果未提供,则将从 negative_prompt 输入参数生成 negative_prompt_embeds。
  • device — (torch.device, 可选): torch 设备
  • dtype — (torch.dtype, 可选): torch 数据类型

将提示编码为文本编码器隐藏状态。

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

如果启用,则禁用 QKV 投影融合。

CogVideoXPipelineOutput

class diffusers.pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput

< >

( frames: Tensor )

参数(Parameters)

  • frames (torch.Tensor, np.ndarray, 或 List[List[PIL.Image.Image]]) — 视频输出列表 - 它可以是长度为 batch_size 的嵌套列表,每个子列表包含长度为 num_frames 的去噪 PIL 图像序列。 它也可以是形状为 (batch_size, num_frames, channels, height, width) 的 NumPy 数组或 Torch 张量。

CogVideo 管道的输出类。

< > 在 GitHub 上更新