> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/shi-pin-sheng-cheng/cogvideox.md).

# CogVideoX 视频生成

在 Clore.ai GPU 上使用智谱 AI 的 CogVideoX 扩散变换器，从文本或图像生成 6 秒视频。

CogVideoX 是智谱 AI（清华）推出的一系列开放权重视频扩散 Transformer。该模型可根据文本提示（T2V）或参考图像加提示（I2V）生成连贯的 6 秒视频片段，分辨率为 720×480，帧率为 8 fps。提供两种参数规模——用于快速迭代的 2B 和用于更高保真度的 5B——两者都原生 `diffusers` 通过 `CogVideoXPipeline`.

在租用的 GPU 上运行 CogVideoX，来自 [Clore.ai](https://clore.ai/) 让你无需受本地硬件限制，并能以每个片段几分钱的成本大规模生成视频。

## 主要特性

* **文生视频（T2V）** —— 描述一个场景，即可获得一个 6 秒、720×480、8 fps（49 帧）的片段。
* **图生视频（I2V）** —— 提供一张参考图像和提示词；模型会以时间一致性的方式将其动画化。
* **两种规模** —— CogVideoX-2B（速度快，约 12 GB 显存）和 CogVideoX-5B（质量更高，约 20 GB 显存）。
* **原生支持 diffusers** —— 一等支持 `CogVideoXPipeline` 以及 `CogVideoXImageToVideoPipeline` 类。
* **3D 因果 VAE** —— 将 49 帧压缩到紧凑的潜空间中，以实现高效去噪。
* **开源权重** —— 2B 版本采用 Apache-2.0 许可证；5B 版本采用研究许可证。

## 需求

| 组件     | 最低             | 推荐             |
| ------ | -------------- | -------------- |
| GPU 显存 | 16 GB（2B，fp16） | 24 GB（5B，bf16） |
| 系统内存   | 32 GB          | 64 GB          |
| 磁盘     | 30 GB          | 50 GB          |
| Python | 3.10+          | 3.11           |
| CUDA   | 12.8+          | 12.8+          |

**Clore.ai GPU 推荐：** 一台 **RTX 4090** （24 GB，$0.14–0.42/小时）可以轻松同时处理 2B 和 5B 版本。一台 **RTX 3090** （24 GB，$0.07–0.21/小时）同样适用于 bf16 的 5B，是预算首选。

## 快速开始

```bash
# 创建环境
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128
pip install diffusers transformers accelerate sentencepiece imageio[ffmpeg]

# 验证 GPU
python -c "import torch; print(torch.cuda.get_device_name(0))"
```

## 使用示例

### 文生视频（5B）

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

pipe = CogVideoXPipeline.from_pretrained(
    "THUDM/CogVideoX-5b"，
    torch_dtype=torch.bfloat16,
)
pipe.to("cuda")
pipe.enable_model_cpu_offload()      # 节省约 4 GB 峰值显存
pipe.vae.enable_tiling()             # 在 24 GB 显卡上生成 720x480 所必需

prompt = (
    "一只金毛寻回犬在日落时分穿过向日葵花田，"
    "电影级灯光、慢动作、4K 画质"
)

video_frames = pipe(
    prompt=prompt,
    num_frames=49,
    guidance_scale=6.0,
    num_inference_steps=50,
    generator=torch.Generator("cuda").manual_seed(42),
).frames[0]

export_to_video(video_frames, "retriever_sunset.mp4", fps=8)
print("已保存 retriever_sunset.mp4")
```

### 图生视频（5B）

```python
import torch
from PIL import Image
from diffusers import CogVideoXImageToVideoPipeline
from diffusers.utils import export_to_video

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

image = Image.open("reference.png").resize((720, 480))

video_frames = pipe(
    prompt="摄像机缓慢绕着主体环绕，轻柔的风",
    image=image,
    num_frames=49,
    guidance_scale=6.0,
    num_inference_steps=50,
).frames[0]

export_to_video(video_frames, "animated.mp4", fps=8)
```

### 使用 2B 版本快速生成

```python
from diffusers import CogVideoXPipeline
import torch

pipe = CogVideoXPipeline.from_pretrained(
    "THUDM/CogVideoX-2b",
    torch_dtype=torch.float16,
)
pipe.to("cuda")
pipe.vae.enable_tiling()

frames = pipe(
    prompt="樱花树绽放的延时摄影",
    num_frames=49,
    guidance_scale=6.0,
    num_inference_steps=30,       # 步骤更少 → 更快
).frames[0]
```

## 给 Clore.ai 用户的建议

1. **启用 VAE 分块** —— 若不启用 `pipe.vae.enable_tiling()` ，3D VAE 在 24 GB 显卡上解码时会因显存不足而崩溃。
2. **使用 `enable_model_cpu_offload()`** —— 会自动将空闲模块移到内存；会增加约 10% 的总耗时，但可节省 4 GB 以上的峰值显存。
3. **5B 用 bf16，2B 用 fp16** —— 5B 检查点是用 bf16 训练的；使用 fp16 可能会产生 NaN 输出。
4. **持久化模型** —— 将 Clore.ai 持久卷挂载到 `/models` 并设置 `HF_HOME=/models/hf` ，这样权重就能在容器重启后保留。
5. **批量过夜运行** —— 用一个简单的 Python 循环排队处理较长的提示词列表；Clore.ai 按小时计费，所以要尽量让 GPU 满负载。
6. **SSH + tmux** —— 在其中运行生成 `tmux` ，这样连接断开也不会终止进程。
7. **选择合适的 GPU** —— 在 Clore.ai 市场中筛选显存 ≥24 GB 的显卡；按价格排序，找到当前最便宜的 RTX 3090 / 4090。

## 故障排查

| 问题                            | 修复                                                                               |
| ----------------------------- | -------------------------------------------------------------------------------- |
| `OutOfMemoryError` 在 VAE 解码期间 | 调用 `pipe.vae.enable_tiling()` 在推理前                                               |
| 5B 出现 NaN / 黑帧                | 切换为 `torch.bfloat16`；5B 版本不支持 fp16                                               |
| `ImportError: imageio`        | `pip install imageio[ffmpeg]` —— 导出 MP4 需要 ffmpeg 插件                             |
| 首次运行非常慢                       | 模型下载约 20 GB；后续运行会使用缓存的权重                                                         |
| CUDA 版本不匹配                    | 确保 PyTorch 的 CUDA 版本与驱动一致： `python -c "import torch; print(torch.version.cuda)"` |
| 运动失真 / 闪烁                     | 增大 `推理步数` 到 50；降低 `guidance_scale` 到 5.0                                         |
| 容器在下载中途被终止                    | 设置 `HF_HOME` 到持久卷并重启——部分下载会自动继续                                                  |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/shi-pin-sheng-cheng/cogvideox.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
