Diffusers documentation

CogVideoX

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

LoRA

CogVideoX

CogVideoX 是一个大型扩散 Transformer 模型,提供 2B 和 5B 参数版本,旨在根据文本生成更长且更具一致性的视频。该模型采用 3D 因果变分自编码器,通过缩短序列长度(从而降低相关的训练计算量)并防止生成视频中出现闪烁,更高效地处理视频数据。一个带有自适应 LayerNorm 的“专家” Transformer 提升了文本与视频之间的对齐效果,而 3D 全注意力机制则有助于准确捕捉生成视频中的运动和时间信息。

您可以在 CogVideoX 集合中找到所有原始的 CogVideoX 检查点。

点击右侧边栏中的 CogVideoX 模型,以查看其他视频生成任务的更多示例。

下面的示例演示了如何生成针对内存或推理速度进行优化的视频。

内存
推理速度

有关各种内存节省技术的详细信息,请参阅 减少内存使用 指南。

以下量化后的 CogVideoX 5B 模型需要约 16GB 的显存。

import torch
from diffusers import CogVideoXPipeline, AutoModel, TorchAoConfig
from diffusers.quantizers import PipelineQuantizationConfig
from diffusers.hooks import apply_group_offloading
from diffusers.utils import export_to_video
from torchao.quantization import Int8WeightOnlyConfig

# quantize weights to int8 with torchao
pipeline_quant_config = PipelineQuantizationConfig(
  quant_mapping={"transformer": TorchAoConfig(Int8WeightOnlyConfig())}
)

# fp8 layerwise weight-casting
transformer = AutoModel.from_pretrained(
    "THUDM/CogVideoX-5b",
    subfolder="transformer",
    dtype=torch.bfloat16
)
transformer.enable_layerwise_casting(
    storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16
)

pipeline = CogVideoXPipeline.from_pretrained(
    "THUDM/CogVideoX-5b",
    transformer=transformer,
    quantization_config=pipeline_quant_config,
    dtype=torch.bfloat16
)
pipeline.to("cuda")  # or "mps", "xpu", "cpu"

# model-offloading
pipeline.enable_model_cpu_offload()

prompt = """
A detailed wooden toy ship with intricately carved masts and sails is seen gliding smoothly over a plush, blue carpet that mimics the waves of the sea. 
The ship's hull is painted a rich brown, with tiny windows. The carpet, soft and textured, provides a perfect backdrop, resembling an oceanic expanse. 
Surrounding the ship are various other toys and children's items, hinting at a playful environment. The scene captures the innocence and imagination of childhood, 
with the toy ship's journey symbolizing endless adventures in a whimsical, indoor setting.
"""

video = pipeline(
    prompt=prompt,
    guidance_scale=6,
    num_inference_steps=50
).frames[0]
export_to_video(video, "output.mp4", fps=8)

备注

  • CogVideoX 支持通过 load_lora_weights() 加载 LoRA。

    查看示例代码
    import torch
    from diffusers import CogVideoXPipeline
    from diffusers.hooks import apply_group_offloading
    from diffusers.utils import export_to_video
    
    pipeline = CogVideoXPipeline.from_pretrained(
        "THUDM/CogVideoX-5b",
        dtype=torch.bfloat16
    )
    pipeline.to("cuda")  # or "mps", "xpu", "cpu"
    
    # load LoRA weights
    pipeline.load_lora_weights("finetrainers/CogVideoX-1.5-crush-smol-v0", adapter_name="crush-lora")
    pipeline.set_adapters("crush-lora", 0.9)
    
    # model-offloading
    pipeline.enable_model_cpu_offload()
    
    prompt = """
    PIKA_CRUSH A large metal cylinder is seen pressing down on a pile of Oreo cookies, flattening them as if they were under a hydraulic press.
    """
    negative_prompt = "inconsistent motion, blurry motion, worse quality, degenerate outputs, deformed outputs"
    
    video = pipeline(
        prompt=prompt, 
        negative_prompt=negative_prompt, 
        num_frames=81, 
        height=480,
        width=768,
        num_inference_steps=50
    ).frames[0]
    export_to_video(video, "output.mp4", fps=16)
  • 文本到视频(T2V)检查点在 1360x768 分辨率下效果最佳,因为该模型正是在此分辨率上进行预训练的。

  • 图像到视频(I2V)检查点支持多种分辨率。宽度可在 768 到 1360 之间变化,但高度必须为 758。高度和宽度都必须能被 16 整除。

  • T2V 和 I2V 检查点在 81 帧和 161 帧时效果最佳。建议以 16fps 导出生成的视频。

  • 请参阅下表,查看启用各种内存节省技术时的内存使用情况。

    方法内存使用情况(已启用)内存使用情况(已禁用)
    enable_model_cpu_offload19GB33GB
    enable_sequential_cpu_offload<4GB~33GB(推理速度非常慢)
    enable_tiling11GB(使用 enable_model_cpu_offload)---

CogVideoXPipeline

类 diffusers.CogVideoXPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelvae: AutoencoderKLCogVideoXtransformer: CogVideoXTransformer3DModelscheduler: diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler | diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler )

参数

  • 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__

< >

( prompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_frames: int | None = Nonenum_inference_steps: int = 50timesteps: list[int] | None = Noneguidance_scale: float = 6use_dynamic_cfg: bool = Falsenum_videos_per_prompt: int = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • negative_prompt (str 或 list[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_frames (int,默认为 48) — 要生成的帧数。该值必须能被 self.vae_scale_factor_temporal 整除。由于 CogVideoX 以 (num_seconds * fps + 1) 帧作为条件,其中 num_seconds 为 6,fps 为 8,因此生成的视频将额外包含 1 帧。不过,由于视频可以以任意 fps 保存,唯一需要满足的条件就是上述的整除性要求。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • use_dynamic_cfg (bool,可选,默认为 False) — 如果为 True,则在推理过程中动态调整 guidance scale。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的视频数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.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 保持一致,否则可能导致效果不佳。

返回值

CogVideoXPipelineOutput 或 tuple

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

调用生成 pipeline 时调用的函数。

示例:

>>> 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: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 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_embeds 将从 negative_prompt 输入参数生成。
  • device — (torch.device,可选): torch 设备
  • dtype — (torch.dtype,可选): torch 数据类型

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

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

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

CogVideoXImageToVideoPipeline

类 diffusers.CogVideoXImageToVideoPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelvae: AutoencoderKLCogVideoXtransformer: CogVideoXTransformer3DModelscheduler: diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler | diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler )

参数

  • 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__

< >

( image: typing.Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]prompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_frames: int = 49num_inference_steps: int = 50timesteps: list[int] | None = Noneguidance_scale: float = 6use_dynamic_cfg: bool = Falsenum_videos_per_prompt: int = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

参数

  • image (PipelineImageInput) — 用于条件生成的输入图像。必须为图像、图像列表或 torch.Tensor。
  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • negative_prompt (str 或 list[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_frames (int,默认为 48) — 要生成的帧数。该值必须能被 self.vae_scale_factor_temporal 整除。由于 CogVideoX 以 (num_seconds * fps + 1) 帧作为条件,其中 num_seconds 为 6,fps 为 8,因此生成的视频将额外包含 1 帧。不过,由于视频可以以任意 fps 保存,唯一需要满足的条件就是上述的整除性要求。
  • num_inference_steps (int,可选,默认为 50) — 去噪步数。更多的去噪步数通常能生成更高质量的图像,但代价是推理速度变慢。
  • timesteps (list[int], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • use_dynamic_cfg (bool,可选,默认为 False) — 如果为 True,则在推理过程中动态调整 guidance scale。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的视频数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.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 保持一致,否则可能导致效果不佳。

返回值

CogVideoXPipelineOutput 或 tuple

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

调用生成 pipeline 时调用的函数。

示例:

>>> 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: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 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_embeds 将从 negative_prompt 输入参数生成。
  • device — (torch.device,可选): torch 设备
  • dtype — (torch.dtype,可选): torch 数据类型

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

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

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

CogVideoXVideoToVideoPipeline

类 diffusers.CogVideoXVideoToVideoPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelvae: AutoencoderKLCogVideoXtransformer: CogVideoXTransformer3DModelscheduler: diffusers.schedulers.scheduling_ddim_cogvideox.CogVideoXDDIMScheduler | diffusers.schedulers.scheduling_dpm_cogvideox.CogVideoXDPMScheduler )

参数

  • 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: list[PIL.Image.Image] = Noneprompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list[int] | None = Nonestrength: float = 0.8guidance_scale: float = 6use_dynamic_cfg: bool = Falsenum_videos_per_prompt: int = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.FloatTensor] = Noneprompt_embeds: typing.Optional[torch.FloatTensor] = Nonenegative_prompt_embeds: typing.Optional[torch.FloatTensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

参数

  • video (list[PIL.Image.Image]) — 用于条件生成的输入视频。必须是视频图像/帧的列表。
  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • negative_prompt (str 或 list[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], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • strength (float,可选,默认值为 0.8) — strength 值越高,原始视频与生成视频之间的差异越大。
  • guidance_scale (float,可选,默认值为 7.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,但通常以牺牲图像质量为代价。
  • use_dynamic_cfg (bool,可选,默认为 False) — 如果为 True,则在推理过程中动态调整 guidance scale。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的视频数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.FloatTensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作图像生成的输入。可用于使用不同的提示词对同一生成过程进行微调。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • prompt_embeds (torch.FloatTensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.FloatTensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将根据 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.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 保持一致,否则可能导致效果不佳。

返回值

CogVideoXPipelineOutput 或 tuple

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

调用生成 pipeline 时调用的函数。

示例:

>>> 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: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 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_embeds 将从 negative_prompt 输入参数生成。
  • device — (torch.device,可选): torch 设备
  • dtype — (torch.dtype,可选): torch 数据类型

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

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

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

CogVideoXFunControlPipeline

类 diffusers.CogVideoXFunControlPipeline

< >

( tokenizer: T5Tokenizertext_encoder: T5EncoderModelvae: AutoencoderKLCogVideoXtransformer: CogVideoXTransformer3DModelscheduler: KarrasDiffusionSchedulers )

参数

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

使用 CogVideoX Fun 进行可控文本到视频生成的 Pipeline。

该模型继承自 DiffusionPipeline。有关该库为所有流水线实现的通用方法(例如下载或保存、在特定设备上运行等),请参阅父类文档。

__call__

< >

( prompt: str | list[str] | None = Nonenegative_prompt: str | list[str] | None = Nonecontrol_video: list[PIL.Image.Image] | None = Noneheight: int | None = Nonewidth: int | None = Nonenum_inference_steps: int = 50timesteps: list[int] | None = Noneguidance_scale: float = 6use_dynamic_cfg: bool = Falsenum_videos_per_prompt: int = 1eta: float = 0.0generator: typing.Union[torch.Generator, list[torch.Generator], NoneType] = Nonelatents: typing.Optional[torch.Tensor] = Nonecontrol_video_latents: typing.Optional[torch.Tensor] = Noneprompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Noneoutput_type: str = 'pil'return_dict: bool = Trueattention_kwargs: dict[str, typing.Any] | None = Nonecallback_on_step_end: typing.Union[typing.Callable[[int, int], NoneType], diffusers.callbacks.PipelineCallback, diffusers.callbacks.MultiPipelineCallbacks, NoneType] = Nonecallback_on_step_end_tensor_inputs: list[str] = ['latents']max_sequence_length: int = 226 ) → CogVideoXPipelineOutput or tuple

参数

  • prompt (str 或 list[str],可选) — 用于引导图像生成的提示词或提示词列表。如果未定义,则必须改为传入 prompt_embeds。
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 negative_prompt_embeds。在未使用引导时会被忽略(即当 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], 可选) — 用于支持 timesteps 参数的调度器去噪过程的自定义时间步,该参数位于其 set_timesteps 方法中。如果未定义,则使用传入 num_inference_steps 时的默认行为。必须按降序排列。
  • guidance_scale (float,可选,默认为 6.0) — Classifier-Free Diffusion Guidance 中定义的引导尺度。guidance_scale 定义为 Imagen Paper 中公式 2 的 w。通过设置 guidance_scale > 1 来启用引导尺度。较高的引导尺度会促使生成与文本 prompt 紧密关联的图像,通常以牺牲图像质量为代价。
  • use_dynamic_cfg (bool,可选,默认为 False) — 如果为 True,则在推理过程中动态调整 guidance scale。
  • num_videos_per_prompt (int,可选,默认为 1) — 每个提示词生成的视频数量。
  • eta(float,可选,默认值为 0.0)— 对应 DDIM 论文中的参数 eta (η)。仅适用于 DDIMScheduler,在其他调度器中会被忽略。
  • generator (torch.Generator 或 list[torch.Generator],可选) — 一个或一组 torch 生成器,用于使生成过程具有确定性。
  • latents (torch.Tensor, 可选) — 预先生成的噪声潜变量,从高斯分布中采样,用作视频生成的输入。可用于以不同的提示词微调同一生成过程。如果未提供,将通过使用提供的随机generator进行采样来生成一个潜变量张量。
  • control_video_latents (torch.Tensor, 可选) — 预生成的控制潜变量,从高斯分布中采样,用作受控视频生成的输入。如果未提供,则必须提供 control_video。
  • prompt_embeds (torch.Tensor, 可选) — 预生成的文本嵌入。可用于轻松调整文本输入,例如 提示词加权。如果未提供,文本嵌入将从 prompt 输入参数生成。
  • negative_prompt_embeds (torch.Tensor, 可选) — 预生成的负向文本嵌入。可用于轻松调整文本输入,例如提示词加权。如果未提供,negative_prompt_embeds 将从 negative_prompt 输入参数生成。
  • output_type (str,可选,默认为 "pil") — 生成图像的输出格式。可选值为 PIL:PIL.Image.Image 或 np.array。
  • return_dict (bool,可选,默认为 True) — 是否返回 ~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput 而不是普通元组。
  • attention_kwargs (dict, 可选) — 一个 kwargs 字典,如果指定,将传递给 diffusers.models.attention_processor 中定义的 AttentionProcessor,该处理器在 self.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 保持一致,否则可能导致效果不佳。

返回值

CogVideoXPipelineOutput 或 tuple

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

调用生成 pipeline 时调用的函数。

示例:

>>> 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: str | list[str]negative_prompt: str | list[str] | None = Nonedo_classifier_free_guidance: bool = Truenum_videos_per_prompt: int = 1prompt_embeds: typing.Optional[torch.Tensor] = Nonenegative_prompt_embeds: typing.Optional[torch.Tensor] = Nonemax_sequence_length: int = 226device: typing.Optional[torch.device] = Nonedtype: typing.Optional[torch.dtype] = None )

参数

  • prompt (str 或 list[str],可选) — 要编码的提示
  • negative_prompt (str 或 list[str],可选) — 用于不引导图像生成的提示词。如果未定义,则必须传入 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_embeds 将从 negative_prompt 输入参数生成。
  • device — (torch.device,可选): torch 设备
  • dtype — (torch.dtype,可选): torch 数据类型

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

fuse_qkv_projections

< >

( )

启用融合的 QKV 投影。

unfuse_qkv_projections

< >

( )

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

CogVideoXPipelineOutput

类 diffusers.pipelines.cogvideo.pipeline_output.CogVideoXPipelineOutput

< >

( frames: Tensor )

参数

  • 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 流水线的输出类。

Update on GitHub