Diffusers documentation

CogVideoX

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.42.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

CogVideoX

CogVideoX 是一个专注于生成与提示词更加一致、连贯性更强的视频的文本生成视频模型。它通过多种方法来实现这一目标。

  • 一种三维变分自编码器,在空间和时间维度上对视频进行压缩,从而提升压缩率和视频精度。

  • 一个用于帮助对齐文本和视频的专家 Transformer 块,以及一个用于捕捉和生成在空间和时间上均准确的视频的 3D 全注意力模块。

对视频指令维度的实际测试发现,CogVideoX 在主题一致性、动态信息、背景一致性、物体信息、运动流畅度、色彩、场景、外观风格和时间风格方面表现良好,但在人物动作、空间关系和多个物体方面无法取得理想效果。

使用 Diffusers 进行微调可以帮助弥补这些不佳的结果。

数据准备

训练脚本接受两种格式的数据。

第一种格式适用于小规模训练,第二种格式采用 CSV 格式,更适合大规模训练时的流式数据。未来,Diffusers 将支持 <Video> 标签。

小型格式

两个文件,其中一个文件包含以换行符分隔的提示词,另一个文件包含以换行符分隔的视频数据路径(视频文件的路径必须相对于指定 --instance_data_root 时传入的路径)。让我们通过一个示例来更好地理解这一点!

假设你已将 --instance_data_root 指定为 /dataset,并且该目录中包含以下文件:prompts.txt 和 videos.txt。

prompts.txt 文件应包含以换行符分隔的提示词:

A black and white animated sequence featuring a rabbit, named Rabbity Ribfried, and an anthropomorphic goat in a musical, playful environment, showcasing their evolving interaction.
A black and white animated sequence on a ship's deck features a bulldog character, named Bully Bulldoger, showcasing exaggerated facial expressions and body language. The character progresses from confident to focused, then to strained and distressed, displaying a range of emotions as it navigates challenges. The ship's interior remains static in the background, with minimalistic details such as a bell and open door. The character's dynamic movements and changing expressions drive the narrative, with no camera movement to distract from its evolving reactions and physical gestures.
...

videos.txt 文件应包含以换行符分隔的视频文件路径。请注意,该路径应为相对于 --instance_data_root 目录的相对路径。

videos/00000.mp4
videos/00001.mp4
...

总体而言,如果在数据集根目录上运行 tree 命令,你的数据集将呈现如下结构:

/dataset
├── prompts.txt
├── videos.txt
├── videos
    ├── videos/00000.mp4
    ├── videos/00001.mp4
    ├── ...

使用此格式时,--caption_column 必须为 prompts.txt,且 --video_column 必须为 videos.txt。

流格式

您可以使用单个 CSV 文件。为了便于说明,假设您有一个 metadata.csv 文件。其预期格式如下:

<CAPTION_COLUMN>,<PATH_TO_VIDEO_COLUMN>
"""A black and white animated sequence featuring a rabbit, named Rabbity Ribfried, and an anthropomorphic goat in a musical, playful environment, showcasing their evolving interaction.""","""00000.mp4"""
"""A black and white animated sequence on a ship's deck features a bulldog character, named Bully Bulldoger, showcasing exaggerated facial expressions and body language. The character progresses from confident to focused, then to strained and distressed, displaying a range of emotions as it navigates challenges. The ship's interior remains static in the background, with minimalistic details such as a bell and open door. The character's dynamic movements and changing expressions drive the narrative, with no camera movement to distract from its evolving reactions and physical gestures.""","""00001.mp4"""
...

在这种情况下,--instance_data_root 应为视频存储的位置,而 --dataset_name 应为指向本地文件夹的路径,或托管在 Hub 上的兼容 load_dataset 的数据集。假设您在 https://huggingface.co/datasets/my-awesome-username/minecraft-videos 处有 Minecraft 游戏录屏视频,则需要指定 my-awesome-username/minecraft-videos。

使用此格式时,--caption_column 必须为 <CAPTION_COLUMN>,且 --video_column 必须为 <PATH_TO_VIDEO_COLUMN>。

您并不一定非要使用 CSV 格式。只要 load_dataset 方法支持该文件格式,能够加载基本的 <PATH_TO_VIDEO_COLUMN> 和 <CAPTION_COLUMN>,任何格式都可以。之所以要费心进行这些数据集组织上的调整来加载视频数据,是因为 load_dataset 并不完全支持所有类型的视频格式。

CogVideoX 在视频生成时,配合长且描述详尽的、经 LLM 增强的提示词效果最佳。我们建议对视频进行预处理:首先使用 VLM 生成摘要,然后利用 LLM 对提示词进行增强。要生成上述字幕,我们使用了 MiniCPM-V-26 和 Llama-3.1-8B-Instruct。一个非常基础、无额外功能的示例可在此处找到。官方推荐的提示词增强模型是 ChatGLM,提示词长度在 50 到 100 个单词之间通常被认为是合适的。

![NOTE] 预期您的数据集已经过预处理。如果没有,可以通过调整以下参数进行一些基本的预处理:--height、--width、--fps、--max_num_frames、--skip_frames_start 和 --skip_frames_end。 目前,当训练批次大小 > 1 时,数据集中的所有视频应包含相同数量的视频帧。

训练

您需要通过安装必要的依赖项来配置开发环境。所需的软件包如下:

  • 基于您所使用的训练功能,需要 Torch 2.0 或更高版本(量化/DeepSpeed 训练可能需要最新版本或 nightly 版本)
  • pip install diffusers transformers accelerate peft huggingface_hub 用于所有与建模和训练相关的事项
  • 使用 pip install datasets decord 加载视频训练数据
  • pip install bitsandbytes 用于使用 8 位 Adam 或 AdamW 优化器进行内存优化训练
  • pip install wandb 可选,用于监控训练日志
  • pip install deepspeed 可选,用于 DeepSpeed 训练
  • pip install prodigyopt 如果您希望在训练中使用 Prodigy 优化器,可以可选地安装

为确保您能够成功运行最新版本的示例脚本,我们强烈建议通过从源代码安装的方式安装,并保持安装为最新状态,因为我们经常更新示例脚本,并且会安装一些特定于示例的依赖项。为此,请在新的虚拟环境中执行以下步骤:

在运行脚本之前,请确保从源代码安装该库:

git clone https://github.com/huggingface/diffusers
cd diffusers
pip install -e .

然后,导航到包含训练脚本的示例文件夹,并安装您正在使用的脚本所需的依赖项:

  • PyTorch
cd examples/cogvideo
pip install -r requirements.txt

并使用以下命令初始化 🤗 Accelerate 环境:

accelerate config

或者,如果您不想回答有关环境的问题,可以使用默认的 accelerate 配置

accelerate config default

或者,如果你的环境不支持交互式 shell(例如 notebook)

from accelerate.utils import write_basic_config
write_basic_config()

在运行 accelerate config 时,如果使用 torch.compile,可能会获得显著的速度提升。PEFT 库被用作 LoRA 训练的后端,因此请确保您的环境中已安装 peft>=0.6.0。

如果您希望在训练完成后将模型推送到 Hub,并附带一份整洁的模型卡片,请确保您已登录:

hf auth login

# Alternatively, you could upload your model manually using:
# hf upload my-cool-account-name/my-cool-lora-name /path/to/awesome/lora

请确保你的数据已按照数据准备中的说明进行准备。准备就绪后,即可开始训练!

假设您正在使用 50 个相似概念的视频进行训练,我们发现 1500-2000 步效果良好。不过,官方建议使用 100 个视频,总共 4000 步。假设您在单个 GPU 上训练,且 --train_batch_size 为 1:

  • 在 50 个视频上训练 1500 步相当于 30 个训练轮次
  • 在 100 个视频上训练 4000 步相当于 40 个训练轮次
#!/bin/bash

GPU_IDS="0"

accelerate launch --gpu_ids $GPU_IDS examples/cogvideo/train_cogvideox_lora.py \
  --pretrained_model_name_or_path THUDM/CogVideoX-2b \
  --cache_dir <CACHE_DIR> \
  --instance_data_root <PATH_TO_WHERE_VIDEO_FILES_ARE_STORED> \
  --dataset_name my-awesome-name/my-awesome-dataset \
  --caption_column <CAPTION_COLUMN> \
  --video_column <PATH_TO_VIDEO_COLUMN> \
  --id_token <ID_TOKEN> \
  --validation_prompt "<ID_TOKEN> Spiderman swinging over buildings:::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" \
  --validation_prompt_separator ::: \
  --num_validation_videos 1 \
  --validation_epochs 10 \
  --seed 42 \
  --rank 64 \
  --lora_alpha 64 \
  --mixed_precision fp16 \
  --output_dir /raid/aryan/cogvideox-lora \
  --height 480 --width 720 --fps 8 --max_num_frames 49 --skip_frames_start 0 --skip_frames_end 0 \
  --train_batch_size 1 \
  --num_train_epochs 30 \
  --checkpointing_steps 1000 \
  --gradient_accumulation_steps 1 \
  --learning_rate 1e-3 \
  --lr_scheduler cosine_with_restarts \
  --lr_warmup_steps 200 \
  --lr_num_cycles 1 \
  --enable_slicing \
  --enable_tiling \
  --optimizer Adam \
  --adam_beta1 0.9 \
  --adam_beta2 0.95 \
  --max_grad_norm 1.0 \
  --report_to wandb

为了更好地跟踪我们的训练实验,我们在上述命令中使用了以下标志:

  • --report_to wandb 可确保训练运行在 Weights and Biases 上进行跟踪。要使用它,请确保通过 pip install wandb 安装 wandb。
  • validation_prompt 和 validation_epochs,以便脚本执行几次验证推理。这让我们能够定性检查训练是否按预期进行。

设置 <ID_TOKEN> 并非必需。根据有限的实验,我们发现设置该 token 效果更佳(因为它类似于 Dreambooth 的训练方式)。如果提供了 <ID_TOKEN>,它会被添加到每个提示词的开头。因此,如果你的 <ID_TOKEN> 是 "DISNEY",而你的提示词是 "Spiderman swinging over buildings",那么训练时实际使用的有效提示词将是 "DISNEY Spiderman swinging over buildings"。如果未提供,你可以选择不使用任何额外 token 进行训练,或者在开始训练前对数据集进行增强,将 token 添加到你希望的位置。

你可以传入 --use_8bit_adam 来降低训练所需的内存。

在添加 CogVideoX LoRA 训练支持时,已测试了以下设置:

  • 我们的测试主要基于 CogVideoX-2b 进行。我们很快就会着手处理 CogVideoX-5b 和 CogVideoX-5b-I2V。
  • 一个数据集包含 70 个分辨率为 200 x 480 x 720(F x H x W)的训练视频。在此基础上,通过数据预处理中的帧跳过技术,我们构建了两个更小的 49 帧和 16 帧数据集,以加快实验速度,同时因为 CogVideoX 团队建议的最大帧数限制为 49 帧。在这 70 个视频中,我们创建了三个组,分别包含 10、25 和 50 个视频。所有视频在训练概念的性质上均相似。
  • 25 个以上的视频在训练新概念和风格时效果最佳。
  • 我们发现,使用可通过 --id_token 指定的标识符 token 进行训练效果更好。这与 Dreambooth 类训练类似,但普通的微调(不使用此类 token)同样可行。
  • 将训练好的概念与完全不相关的提示词结合使用时,效果相当不错。我们预计,如果对 CogVideoX-5B 进行微调,效果会更好。
  • 原始仓库使用的 lora_alpha 为 1。我们发现这在许多运行中并不合适,可能是由于建模后端和训练设置存在差异所致。我们建议将 lora_alpha 设置为 rank 或 rank // 2。
  • 如果您正在使用原始模型生成效果不佳的标题数据进行训练,那么 rank 设为 64 或更高是合适的,这也是 CogVideoX 开发团队的推荐值。如果您的训练标题已经能产生中等质量的生成结果,那么 rank 设为 16/32 即可。我们发现,将 rank 设置得过低(例如 4)并不理想,无法产生令人满意的结果。
  • CogVideoX 的作者建议总共使用 4000 个训练步骤和 100 个训练视频,以获得最佳效果。虽然这可能会带来最好的结果,但根据我们有限的实验,2000 个步骤和 25 个视频也足以达到良好效果。
  • 使用 Prodigy 优化器进行训练时,可以参考这篇博客中的建议。Prodigy 很容易快速过拟合。根据我有限的测试,除了使用 --prodigy_use_bias_correction、prodigy_safeguard_warmup 和 --prodigy_decouple 之外,0.5 的学习率是合适的。
  • CogVideoX 作者推荐的学习率,以及我们在 Adam/AdamW 上的实验结果表明,对于包含 25 个以上视频的数据集,学习率应在 1e-3 和 1e-4 之间。

请注意,由于探索时间有限,我们的测试并不全面。我们建议尝试调整不同的参数,以找到最适合您数据的设置。

推理

训练好 lora 模型后,只需将 lora 权重加载到 CogVideoXPipeline 中即可进行推理。

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

pipe = CogVideoXPipeline.from_pretrained("THUDM/CogVideoX-2b", dtype=torch.float16)
# pipe.load_lora_weights("/path/to/lora/weights", adapter_name="cogvideox-lora") # Or,
pipe.load_lora_weights("my-awesome-hf-username/my-awesome-lora-name", adapter_name="cogvideox-lora") # If loading from the HF Hub
pipe.to("cuda")  # or "mps", "xpu", "cpu"

# Assuming lora_alpha=32 and rank=64 for training. If different, set accordingly
pipe.set_adapters(["cogvideox-lora"], [32 / 64])

prompt = "A vast, shimmering ocean flows gracefully under a twilight sky, its waves undulating in a mesmerizing dance of blues and greens. The surface glints with the last rays of the setting sun, casting golden highlights that ripple across the water. Seagulls soar above, their cries blending with the gentle roar of the waves. The horizon stretches infinitely, where the ocean meets the sky in a seamless blend of hues. Close-ups reveal the intricate patterns of the waves, capturing the fluidity and dynamic beauty of the sea in motion."
frames = pipe(prompt, guidance_scale=6, use_dynamic_cfg=True).frames[0]
export_to_video(frames, "output.mp4", fps=8)

减少内存使用

在使用 diffusers 库进行测试时,已启用 diffusers 库中包含的所有优化。该方案尚未在 NVIDIA A100 / H100 架构以外的设备上针对实际内存占用进行测试。 通常,该方案可适配所有 NVIDIA Ampere 架构 及更高版本的设备。如果禁用优化,内存消耗将会成倍增加,峰值内存使用量约为表中数值的 3 倍。 不过,速度将提升约 3-4 倍。您可以选择性地禁用部分优化,包括:

pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()
  • 对于多 GPU 推理,需要禁用 enable_sequential_cpu_offload() 优化。
  • 使用 INT8 模型会减慢推理速度,这是为了在保持视频质量损失最小的同时,适配显存更低的 GPU,但推理速度会显著下降。
  • CogVideoX-2B 模型以 FP16 精度进行训练,而所有 CogVideoX-5B 模型均以 BF16 精度进行训练。 我们建议推理时使用模型训练时所采用的精度。
  • PytorchAO 和 Optimum-quanto 可用于对文本编码器、transformer 和 VAE 模块进行量化,从而降低 CogVideoX 的内存需求。这使得模型能够在免费的 T4 Colab 或内存较小的 GPU 上运行!此外,请注意 TorchAO 量化与 torch.compile 完全兼容,可显著提升推理速度。在 NVIDIA H100 及以上设备上必须使用 FP8 精度,这需要从源码安装 torch、torchao、diffusers 和 accelerate Python 包。建议使用 CUDA 12.4。
  • 推理速度测试也使用了上述内存优化方案。如果不进行内存优化,推理速度大约会提升 10%。只有 diffusers 版本的模型支持量化。
  • 该模型仅支持英文输入;其他语言可通过大模型润色功能翻译为英文后使用。
  • 模型微调的内存占用在 8 * H100 环境中进行了测试,程序会自动使用 Zero 2 优化。如果表格中标注了特定的 GPU 数量,则微调时必须使用该数量或更多的 GPU。
属性CogVideoX-2BCogVideoX-5B
模型名称CogVideoX-2BCogVideoX-5B
推理精度FP16(推荐)、BF16、FP32、FP8、INT8、不支持 INT4BF16(推荐)、FP16、FP32、FP8*、INT8、不支持 INT4
单 GPU 推理显存FP16:使用 diffusers 12.5GBINT8:使用 diffusers 和 torchao 7.8GBBF16:使用 diffusers 20.7GBINT8:使用 diffusers 和 torchao 11.4GB
多 GPU 推理 VRAMFP16:使用 diffusers 10GB*BF16:使用 diffusers 15GB*
推理速度单张 A100:约 90 秒,单张 H100:约 45 秒单张 A100:约 180 秒,单张 H100:约 90 秒
微调精度FP16BF16
微调的 VRAM 消耗47 GB(bs=1,LORA)61 GB(bs=2,LORA)62GB(bs=1,SFT)63 GB(bs=1,LORA)80 GB(bs=2,LORA)75GB(bs=1,SFT)
Update on GitHub