Skip to content

从零开始:基于 ModelScope 本地部署 CogVideoX-2B 文生视频完全指南

约 8625 字大约 29 分钟

AICogVideoX文生视频视频生成

2026-01-12

本文档记录了使用魔搭社区 ModelScope 平台,从零开始在本地部署 CogVideoX-2B 文生视频模型的完整过程,包括环境配置、依赖安装、模型下载、提示词编写技巧以及实战示例。

关于 ModelScope: ModelScope 社区是一个模型开源社区及创新平台,由阿里巴巴通义实验室,联合 CCF 开源发展技术委员会,共同作为项目发起创建。(摘自官方文档)


前置准备:安装 Python(如果未安装)

0.1 检查是否已安装 Python

打开命令提示符(CMD),输入:

python --version
  • 如果显示版本号(如 Python 3.11.9)→ 已安装,跳到「一、环境信息」
  • 如果提示「不是内部或外部命令」 → 未安装,继续下面步骤

0.2 下载 Python

  1. 访问 Python 官网:https://www.python.org/downloads/
  2. 点击 Download Python 3.11.x(推荐 3.10 或 3.11 版本)
  3. 下载 Windows 安装包(约 25MB)

0.3 安装 Python

  1. 双击运行下载的安装包
  2. 重要! 勾选底部的 「Add Python to PATH」(添加到环境变量)
  3. 点击 Install Now 开始安装
  4. 等待安装完成,点击 Close

0.4 验证安装

关闭并重新打开命令提示符,输入:

python --version

显示版本号即安装成功:

Python 3.11.9

0.5 验证 pip(Python 包管理器)

pip --version

显示类似以下内容即正常:

pip 24.0 from D:\Program Files\Python311\Lib\site-packages\pip (python 3.11)

0.6 常见问题

问题:安装后仍提示「不是内部命令」

原因: 安装时没有勾选「Add Python to PATH」

解决方案 1:重新安装

  1. 卸载 Python(控制面板 → 程序和功能)
  2. 重新运行安装包,务必勾选 Add Python to PATH

解决方案 2:手动添加环境变量

  1. 右键「此电脑」→ 属性 → 高级系统设置 → 环境变量
  2. 在「系统变量」中找到 Path,点击编辑
  3. 添加 Python 安装路径,例如:
    • D:\Program Files\Python311\
    • D:\Program Files\Python311\Scripts\
  4. 确定保存,重新打开 CMD

一、环境信息

说明: 以下是博主个人电脑的配置环境,本文档所有操作和测试结果均基于此环境。不同的硬件配置可能会有不同的表现,仅供参考。

项目配置
操作系统Windows 10
Python 版本3.11.9
显卡NVIDIA GeForce RTX 3060 (12GB 显存)
CUDA 版本12.4
PyTorch2.6.0+cu124
模型CogVideoX-2B

二、安装依赖

2.1 安装 ModelScope

官网写法:

pip install modelscope

推荐写法(国内用户):

pip install modelscope -i https://mirrors.aliyun.com/pypi/simple/

两者区别:

命令下载来源速度
pip install modelscopePyPI 官方源(国外服务器)国内较慢
pip install modelscope -i 镜像地址国内镜像服务器快很多

-i--index-url 的缩写,用于指定下载源。安装的包完全相同,只是下载速度不同。

2.2 安装 PyTorch(CUDA 版本)

重要:必须安装 CUDA 版本的 PyTorch,否则无法使用 GPU 加速!

# 安装 CUDA 12.4 版本的 PyTorch
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

说明: 如果之前安装过 CPU 版本的 PyTorch,直接运行上面命令会自动覆盖安装。如果担心冲突,可以先卸载:

pip uninstall torch torchvision torchaudio -y

遇到的问题:安装了 CPU 版本的 PyTorch

如何检查? 运行以下命令验证:

python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available())"

正确的输出(CUDA 版本):

PyTorch: 2.6.0+cu124
CUDA可用: True

注意版本号后面的 +cu124,说明安装的是 CUDA 12.4 版本

错误的输出(CPU 版本):

PyTorch: 2.9.1+cpu
CUDA可用: False

注意版本号后面的 +cpu,说明安装的是 CPU 版本,无法使用 GPU

原因:

  • 使用阿里云镜像 pip install torch 默认安装的是 CPU 版本
  • 阿里云镜像没有 CUDA 版本的 PyTorch
  • PyTorch CUDA 版本托管在 PyTorch 官方服务器

解决方案:

第一步:卸载错误的 CPU 版本

pip uninstall torch torchvision torchaudio -y

第二步:从 PyTorch 官方源安装 CUDA 版本

pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

第三步:重新验证

python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available())"

确认输出 CUDA可用: True 即修复成功。

2.3 安装 Diffusers 和相关依赖

# 安装 diffusers 和相关依赖
pip install diffusers>=0.30.3 transformers>=4.44.2 accelerate>=0.34.0 -i https://mirrors.aliyun.com/pypi/simple/

2.4 安装 CogVideoX 专用依赖

pip install sentencepiece protobuf imageio-ffmpeg -i https://mirrors.aliyun.com/pypi/simple/

核心库的作用:

库名作用
torchPyTorch 深度学习框架,模型运行的“引擎”
diffusers扩散模型库,提供视频生成框架
transformers文本编码器(T5)
accelerateGPU 加速库
sentencepieceT5 分词器依赖
protobufT5 分词器协议缓冲区
imageio-ffmpeg视频编码(保存为 MP4 格式)

三、验证环境

3.1 验证 Python

python --version
# 输出: Python 3.11.9

3.2 验证显卡

nvidia-smi

正常会显示显卡型号、驱动版本、显存使用情况等信息。

如果提示「不是内部或外部命令」,说明 NVIDIA 驱动未安装,请到 NVIDIA 官网下载安装驱动。

3.3 验证 PyTorch CUDA

python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA可用:', torch.cuda.is_available()); print('显卡:', torch.cuda.get_device_name(0) if torch.cuda.is_available() else '无')"

正确输出:

PyTorch: 2.6.0+cu124
CUDA可用: True
显卡: NVIDIA GeForce RTX 3060

四、下载模型

4.1 使用命令行下载

D:                          # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
modelscope download --model ZhipuAI/CogVideoX-2b --local_dir models/cogvideox-2b

说明: d:\wwwroot\modelscope 是本教程的示例路径,请替换成你自己的项目目录。如果 CMD 当前不在 D 盘,需要先切换盘符。输入 D: 回车即可切换到 D 盘。

参数说明:

  • --model ZhipuAI/CogVideoX-2b → 指定要下载的模型
  • --local_dir models/cogvideox-2b → 指定下载目录

4.2 模型信息

项目说明
模型名称CogVideoX-2B
开发者智谱 AI (ZhipuAI)
模型大小约 5-6GB
支持精度FP16(推荐)
显存要求8GB 起(启用优化后)
视频规格6 秒,720×480 分辨率,8fps

五、加载和运行模型

进入 Python 交互模式:

D:                          # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
python

正确进入后显示如下:

Python 3.11.9 (tags/v3.11.9:de54cf5, Apr  2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

看到 >>> 提示符表示已进入 Python 环境,可以开始输入代码。

5.1 导入库

import torch
from diffusers import CogVideoXPipeline
from transformers import T5Tokenizer
from diffusers.utils import export_to_video
import os

5.2 手动加载 Tokenizer

tokenizer = T5Tokenizer.from_pretrained(
    "models/cogvideox-2b/tokenizer",
    legacy=False
)

说明: 手动加载 Tokenizer 可以解决 SentencePiece 依赖问题。

5.3 加载模型到 GPU

pipe = CogVideoXPipeline.from_pretrained(
    "models/cogvideox-2b",
    tokenizer=tokenizer,
    torch_dtype=torch.float16
)

参数说明:

  • tokenizer=tokenizer → 使用手动加载的分词器
  • torch_dtype=torch.float16 → 使用半精度浮点数,节省显存

5.4 启用显存优化

pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

重要: RTX 3060 12GB 显卡必须启用这些优化,否则会显存不足。

5.5 创建视频保存目录

os.makedirs("videos", exist_ok=True)

完整执行效果示例(从导入库到加载完成):

>>> import torch
>>> from diffusers import CogVideoXPipeline
>>> from transformers import T5Tokenizer
>>> from diffusers.utils import export_to_video
>>> import os
>>> tokenizer = T5Tokenizer.from_pretrained("models/cogvideox-2b/tokenizer", legacy=False)
>>> pipe = CogVideoXPipeline.from_pretrained("models/cogvideox-2b", tokenizer=tokenizer, torch_dtype=torch.float16)
Loading pipeline components...: 100%|██████████| 5/5 [00:XX<00:00, XXit/s]
Loading checkpoint shards: 100%|██████████| 2/2 [00:XX<00:00, XXit/s]
>>> pipe.enable_sequential_cpu_offload()
>>> pipe.vae.enable_slicing()
>>> pipe.vae.enable_tiling()
>>> os.makedirs("videos", exist_ok=True)
>>>

说明:

  • Loading pipeline components 显示模型加载进度,100% 表示加载完成
  • 首次加载需要约 1-2 分钟,取决于硬件配置
  • 看到 >>> 提示符表示可以继续输入下一步

六、生成视频

6.1 基础用法

prompt = "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest."

video = pipe(
    prompt=prompt,
    num_videos_per_prompt=1,      # 生成数量
    num_inference_steps=50,       # 推理步数(质量与时间平衡)
    num_frames=49,                # 帧数(49 帧 ≈ 6 秒,8fps)
    guidance_scale=6,             # 引导强度(推荐 6)
    generator=torch.Generator(device="cuda").manual_seed(42),  # 随机种子
).frames[0]

export_to_video(video, "videos/output.mp4", fps=8)
print("✓ 视频已保存到: videos/output.mp4")

运行效果:

>>> prompt = "A panda, dressed in a small, red jacket and a tiny hat, sits on a wooden stool in a serene bamboo forest."
>>> video = pipe(
...     prompt=prompt,
...     num_videos_per_prompt=1,
...     num_inference_steps=50,
...     num_frames=49,
...     guidance_scale=6,
...     generator=torch.Generator(device="cuda").manual_seed(42),
... ).frames[0]
100%|████████████████████| 50/50 [05:30<00:00,  6.60s/it]
>>> export_to_video(video, "videos/output.mp4", fps=8)
>>> print("✓ 视频已保存到: videos/output.mp4")
✓ 视频已保存到: videos/output.mp4
>>>

生成的视频会自动保存到 videos 目录下。


6.2 参数说明

参数值/示例作用
prompt英文提示词描述想要生成的视频内容
num_videos_per_prompt1生成视频数量
num_inference_steps50推理步数,越多越精细但越慢
num_frames49生成帧数,49 帧 ≈ 6 秒(8fps)
guidance_scale6提示词引导强度,越高越贴近提示词
generator随机种子设置后可复现相同结果

七、示例提示词

注意:CogVideoX-2B 不支持负面提示词(negative_prompt),只能通过正面描述来引导生成。

1. 动物类(简单动作)

基础示例

prompt = "a cute orange cat walking slowly on green grass"

描述: 可爱的橙色猫在绿色草地上缓慢行走
效果: ⭐⭐⭐⭐ 良好

prompt = "a golden retriever dog running happily in the park, tail wagging"

描述: 金毛犬在公园里快乐地奔跑,尾巴摇摆
效果: ⭐⭐⭐⭐ 良好

prompt = "a small bird flying gracefully across the blue sky"

描述: 小鸟优雅地飞过蓝天
效果: ⭐⭐⭐⭐⭐ 优秀

进阶示例(添加细节)

prompt = "a giant panda eating fresh green bamboo in a peaceful bamboo forest, chewing slowly"

描述: 大熊猫在宁静的竹林里吃新鲜的绿竹,慢慢咀嚼
效果: ⭐⭐⭐⭐ 良好

prompt = "a white rabbit hopping through a field of wildflowers under bright sunlight"

描述: 白兔在阳光下的野花田里跳跃
效果: ⭐⭐⭐⭐ 良好

prompt = "a colorful butterfly flying from flower to flower in a blooming garden"

描述: 彩色蝴蝶在盛开的花园里从一朵花飞到另一朵花
效果: ⭐⭐⭐⭐⭐ 优秀


2. 自然风景(动态元素)

水景类

prompt = "ocean waves crashing on a sandy beach at golden sunset"

描述: 金色日落时海浪拍打沙滩
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "a powerful waterfall cascading down mossy rocks in a dense forest"

描述: 强劲的瀑布从长满苔藓的岩石上倾泻而下,身处茂密森林中
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "gentle rain falling on a calm lake surface, creating ripples"

描述: 细雨落在平静的湖面上,泛起涟漪
效果: ⭐⭐⭐⭐ 良好

天空云景类

prompt = "white fluffy clouds drifting slowly across a bright blue sky"

描述: 白色蓬松的云朵缓慢飘过明亮的蓝天
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "pink cherry blossom petals falling gently in the spring breeze"

描述: 粉色樱花花瓣在春风中轻轻飘落
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "golden autumn leaves swirling and dancing in the wind"

描述: 金色秋叶在风中旋转舞动
效果: ⭐⭐⭐⭐ 良好


3. 城市场景(运动物体)

交通类

prompt = "cars with bright headlights driving on a busy highway at night, city lights in background"

描述: 夜晚繁忙高速公路上前灯明亮的汽车,背景是城市灯光
效果: ⭐⭐⭐⭐ 良好

prompt = "a red double-decker bus driving through rainy London streets"

描述: 红色双层巴士驶过雨中的伦敦街道
效果: ⭐⭐⭐ 一般

prompt = "a yellow taxi cab moving through crowded New York city traffic"

描述: 黄色出租车在拥挤的纽约市交通中穿行
效果: ⭐⭐⭐ 一般

人群与建筑

prompt = "people walking with umbrellas on a rainy Tokyo street, neon signs glowing"

描述: 人们撑着伞走在雨中的东京街道上,霓虹灯闪烁
效果: ⭐⭐⭐ 一般(人物细节可能不佳)

prompt = "colorful fireworks bursting and sparkling in the dark night sky over a city"

描述: 彩色烟花在城市上空的黑夜中绽放闪烁
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "a Ferris wheel rotating slowly at sunset, lights beginning to glow"

描述: 摩天轮在日落时缓慢旋转,灯光开始闪烁
效果: ⭐⭐⭐⭐ 良好


4. 科幻与幻想(创意场景)

prompt = "an astronaut in a white spacesuit floating peacefully in the dark space, Earth visible in background"

描述: 身着白色太空服的宇航员在黑暗太空中平静漂浮,背景可见地球
效果: ⭐⭐⭐⭐ 良好

prompt = "a majestic dragon with golden scales soaring over snowy mountain peaks"

描述: 金色鳞片的威严巨龙翱翔在雪山之巅
效果: ⭐⭐⭐ 一般(幻想生物细节可能模糊)

prompt = "a sleek humanoid robot walking through a futuristic city with glowing buildings"

描述: 光滑的人形机器人走在未来城市中,建筑发光
效果: ⭐⭐⭐ 一般

prompt = "a UFO spaceship hovering and spinning slowly in the night sky, beams of light shooting down"

描述: UFO 飞船在夜空中悬停缓慢旋转,光束向下照射
效果: ⭐⭐⭐⭐ 良好


5. 日常生活(细节动作)

prompt = "hot coffee being poured slowly into a white ceramic cup, steam rising"

描述: 热咖啡缓慢倒入白色陶瓷杯中,蒸汽升腾
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "a single candle flame flickering gently in the darkness, warm orange glow"

描述: 单根蜡烛火焰在黑暗中轻柔摇曳,温暖的橙色光芒
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "a red balloon slowly floating upward into the clear blue sky"

描述: 红色气球缓缓向上飘入晴朗的蓝天
效果: ⭐⭐⭐⭐⭐ 优秀

prompt = "pages of an old book turning slowly in the gentle breeze"

描述: 旧书的书页在微风中缓慢翻动
效果: ⭐⭐⭐⭐ 良好

prompt = "colorful koi fish swimming gracefully in a clear pond with lily pads"

描述: 彩色锦鲤在有睡莲的清澈池塘中优雅游动
效果: ⭐⭐⭐⭐⭐ 优秀


6. 抽象与艺术(慎用)

prompt = "colorful ink drops spreading and swirling in clear water, creating abstract patterns"

描述: 彩色墨滴在清水中扩散旋转,形成抽象图案
效果: ⭐⭐⭐⭐ 良好

prompt = "smoke wisps rising and dancing in slow motion against a black background"

描述: 烟雾缕缕升起,在黑色背景下以慢动作舞动
效果: ⭐⭐⭐⭐ 良好

prompt = "northern lights aurora borealis dancing and shifting colors in the night sky"

描述: 北极光在夜空中舞动变换色彩
效果: ⭐⭐⭐ 一般


八、退出 Python

exit()

或按 Ctrl+Z 然后回车。


九、常见问题和解决方案

问题 1:显存不足 (Out of Memory)

现象:

CUDA out of memory

解决方案:

  1. 确保启用了显存优化

    pipe.enable_sequential_cpu_offload()
    pipe.vae.enable_slicing()
    pipe.vae.enable_tiling()
  2. 减少推理步数

    num_inference_steps=30
  3. 减少生成帧数

    num_frames=25
  4. 关闭其他占用显存的程序


问题 2:生成速度很慢

原因: 视频生成计算量巨大,正常现象

优化建议:

  • 首次生成慢是正常的(需要初始化)
  • 后续生成会稍快一些
  • 使用 num_inference_steps=30 加快速度
  • 使用 num_frames=25 生成较短视频

问题 3:模型加载失败

检查清单:

  1. 确认模型已完整下载

    dir models\cogvideox-2b
  2. 确认依赖已安装

    pip list | findstr sentencepiece
    pip list | findstr protobuf
  3. 确认路径正确

    • 检查 models/cogvideox-2b 路径是否存在
    • 确认包含 model_index.json 文件

问题 4:缺少 SentencePiece 库

错误信息:

T5Tokenizer requires the SentencePiece library

解决方案:

pip install sentencepiece protobuf -i https://mirrors.aliyun.com/pypi/simple/

十、提示词编写技巧

10.1 基础结构

[主体] + [详细描述] + [动作/动态] + [场景/环境] + [时间/光线] + [氛围/风格]

示例:

# 基础版(简单)
prompt = "a cat walking on grass"

# 进阶版(添加细节)
prompt = "a fluffy orange cat walking slowly on green grass"

# 完整版(丰富描述)
prompt = "a fluffy orange cat with white paws walking gracefully on lush green grass in a sunny garden, soft morning light"

10.2 编写规则

✅ 推荐做法

  1. 使用英文 - 模型仅支持英文提示词
  2. 添加动词 - 必须包含动态动作,如 walking, flying, moving
  3. 具体细节 - 描述颜色、大小、材质等具体特征
  4. 环境描述 - 说明场景、光线、天气
  5. 适当长度 - 15-30 个单词最佳,最多 226 tokens
  6. 逗号分隔 - 用逗号清晰分隔不同描述元素

❌ 避免做法

  1. 避免静态 - 不要只描述静止画面(如 "a cat sitting")
  2. 避免过于复杂 - 不要在一个提示词中包含过多元素
  3. 避免抽象概念 - 具体的物理动作比抽象情感更有效
  4. 避免负面描述 - 模型不支持 negative_prompt,只能正面引导
  5. 避免多个主体 - 单一主体效果更好,多主体容易混乱

10.3 负面提示词说明

⚠️ 重要提示:CogVideoX-2B 不支持负面提示词(negative_prompt)功能。

与文生图模型(如 SDXL)不同,CogVideoX 的 API 中没有 negative_prompt 参数。因此:

  • 无法使用negative_prompt="blurry, low quality, distorted"
  • 只能通过正面提示词引导:在 prompt 中详细描述想要的效果

替代方案:

  1. 详细描述想要的内容,而不是试图排除不想要的
  2. 使用质量增强词:如 "high quality", "clear", "smooth motion"
  3. 调整生成参数:增加 num_inference_steps 提升质量

10.4 推荐词汇库

动作词汇(核心)

慢速动作中速动作快速动作
floatingwalkingrunning
driftingmovingracing
swayingflowingdashing
hoveringswimmingzooming
glidingflyingrushing
swirlingdancingbursting
flickeringrotatingexploding

描述性形容词

视觉描述氛围描述质感描述
brightpeacefulfluffy
colorfulserenesmooth
glowingmajesticshiny
sparklingmysterioustransparent
vividdramaticglossy
goldentranquilsoft
shimmeringetherealdelicate

质量增强词

cinematic, high quality, detailed, realistic, stunning, beautiful,
majestic, graceful, elegant, smooth motion, slow motion

十一、使用 Python 文件进行视频生成(推荐)

11.1 为什么使用 Python 文件更方便?

前面介绍的交互式命令行方式适合学习和测试,但在实际使用中存在以下不便:

交互式命令行Python 文件方式
✗ 每次启动需要重新加载模型(耗时 1-2 分钟)✓ 一次加载,持续生成
✗ 代码无法保存,关闭就丢失✓ 代码保存在文件中,可重复使用
✗ 不支持命令快捷操作✓ 支持命令快速调整参数
✗ 无法查看已生成的视频列表✓ 内置视频管理功能
✗ 每次都要写完整代码✓ 只需输入提示词即可
✗ 功能单一,难以扩展✓ 支持步数、帧数、引导强度调整等高级功能

结论:Python 文件方式更适合日常使用!


11.2 准备工作

创建 Python 文件

在项目目录下创建一个名为 video.py 的文件,例如:

d:\wwwroot\modelscope\video.py

可以使用任何文本编辑器(记事本、VS Code、PyCharm 等)创建。


11.3 完整代码

将以下代码保存到 video.py 文件中:

"""CogVideoX-2B 文本生成视频工具

功能特性:
1. 交互式输入 - 输入提示词即可生成视频
2. 显存优化 - 启用 CPU offload + VAE 优化,适配 12GB 显卡
3. 参数可调 - 可配置推理步数、帧数、引导强度等
4. 自动保存 - 视频自动保存到 videos 目录
5. 支持 T5 Tokenizer - 正确加载 CogVideoX 所需的分词器

命令:
- quit: 退出程序
- help: 显示帮助信息
- steps: 修改推理步数
- frames: 修改生成帧数
- guidance: 修改引导强度
- list: 列出已生成的视频
"""

import torch
import os
from diffusers import CogVideoXPipeline
from transformers import T5Tokenizer
from diffusers.utils import export_to_video

# ==================== 配置区 ====================
# 本地模型路径(修改为你的模型路径)
MODEL_PATH = "models/cogvideox-2b"
TOKENIZER_PATH = "models/cogvideox-2b/tokenizer"

# 视频保存目录
OUTPUT_DIR = "videos"

# 生成参数(针对 RTX 3060 12GB 优化)
NUM_INFERENCE_STEPS = 50  # 推理步数,越多越精细(建议 25-100)
NUM_FRAMES = 49  # 生成帧数(49 帧 ≈ 6 秒,建议 25-49)
GUIDANCE_SCALE = 6  # 引导强度(建议 4-8)
# ================================================

# 创建输出目录
os.makedirs(OUTPUT_DIR, exist_ok=True)

print("=" * 60)
print("  CogVideoX-2B 文本生成视频工具")
print("=" * 60)
print("\n正在加载模型,请稍候...")
print("(首次加载需要约 1-2 分钟)")
print("(显存优化已启用,适配 RTX 3060 12GB)\n")

# 手动加载 T5 Tokenizer(解决 SentencePiece 依赖问题)
print("[1/3] 正在加载 T5 Tokenizer...")
tokenizer = T5Tokenizer.from_pretrained(TOKENIZER_PATH, legacy=False)

# 加载 CogVideoX Pipeline
print("[2/3] 正在加载 CogVideoX-2B 模型...")
pipe = CogVideoXPipeline.from_pretrained(
    MODEL_PATH, tokenizer=tokenizer, torch_dtype=torch.float16
)

# 显存优化:启用 CPU offload
print("[3/3] 启用显存优化...")
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

print("\n" + "=" * 60)
print("  ✓ 模型加载完成!")
print("=" * 60)
print("\n输入英文提示词生成视频,或输入命令:")
print("  quit     - 退出程序")
print("  help     - 显示帮助")
print("  steps    - 修改推理步数")
print("  frames   - 修改生成帧数")
print("  guidance - 修改引导强度")
print("  list     - 已生成视频")
print("=" * 60 + "\n")

# 当前配置
current_steps = NUM_INFERENCE_STEPS
current_frames = NUM_FRAMES
current_guidance = GUIDANCE_SCALE
video_count = 0


def show_help():
    """显示帮助信息"""
    print(
        """
╔══════════════════════════════════════════════════════════════╗
║              CogVideoX-2B 文本生成视频帮助                    ║
╠══════════════════════════════════════════════════════════════╣
║ 直接输入英文提示词即可生成视频(6 秒,720×480,8fps)         ║
║                                                              ║
║ 命令:                                                        ║
║   quit         - 退出程序                                    ║
║   help         - 显示本帮助                                  ║
║   steps        - 查看当前推理步数                            ║
║   steps:N      - 设置推理步数(如 steps:50,范围 25-100)    ║
║   frames       - 查看当前生成帧数                            ║
║   frames:N     - 设置生成帧数(如 frames:49,范围 25-49)    ║
║   guidance     - 查看当前引导强度                            ║
║   guidance:N   - 设置引导强度(如 guidance:7,范围 4-8)     ║
║   list         - 列出已生成的视频                            ║
║                                                              ║
║ 提示词技巧(必须使用英文):                                  ║
║   [主体] + [详细描述] + [动作] + [场景] + [光线/氛围]        ║
║                                                              ║
║   示例 1 (简单):                                             ║
║   a cat walking on the grass                                ║
║                                                              ║
║   示例 2 (详细):                                             ║
║   a fluffy orange cat walking slowly on green grass         ║
║   in a sunny garden, soft morning light                     ║
║                                                              ║
║   示例 3 (风景):                                             ║
║   ocean waves crashing on a sandy beach at golden sunset    ║
║                                                              ║
║   示例 4 (科幻):                                             ║
║   astronaut in white spacesuit floating in dark space       ║
║                                                              ║
║ 参数说明:                                                    ║
║   推理步数: 50(标准)、30(快速)、60-100(高质量)         ║
║   生成帧数: 49≈6秒、25≈3秒                                  ║
║   引导强度: 6(平衡)、4-5(创意)、7-8(精确)              ║
║                                                              ║
║ 注意事项:                                                    ║
║   1. 视频生成较慢,单次约 6-10 分钟,请耐心等待              ║
║   2. 仅支持英文提示词,最多 226 tokens                       ║
║   3. 不支持负面提示词(negative_prompt)                     ║
║   4. 推荐场景:自然风景、动物动作、简单物体运动              ║
║   5. 慎用场景:复杂人物、抽象概念                            ║
╚══════════════════════════════════════════════════════════════╝
"""
    )


def list_videos():
    """列出已生成的视频"""
    if not os.path.exists(OUTPUT_DIR):
        print("[videos 目录不存在]\n")
        return

    files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith(".mp4")]
    if not files:
        print("[尚未生成任何视频]\n")
        return

    print(f"\n已生成 {len(files)} 个视频:")
    for f in sorted(files):
        filepath = os.path.join(OUTPUT_DIR, f)
        size = os.path.getsize(filepath) / 1024 / 1024
        print(f"  - {f} ({size:.2f} MB)")
    print()


def generate_video(prompt: str) -> str:
    """生成视频"""
    global video_count

    print("\n" + "=" * 60)
    print("  开始生成视频")
    print("=" * 60)
    print(f"提示词: {prompt}")
    print(f"推理步数: {current_steps}")
    print(f"生成帧数: {current_frames} 帧 ≈ {current_frames/8:.1f} 秒")
    print(f"引导强度: {current_guidance}")
    print(f"分辨率: 720×480 @ 8fps")
    print("=" * 60)

    # 预估时间(基于 RTX 3060 12GB 实测)
    base_time = 8  # 基准时间(分钟)
    time_factor = (current_steps / 50) * (current_frames / 49)
    estimated_min = base_time * time_factor * 0.75
    estimated_max = base_time * time_factor * 1.25

    print(
        f"\n⏳ 预计需要 {estimated_min:.0f}-{estimated_max:.0f} 分钟,请耐心等待...\n"
    )

    # 生成视频
    video = pipe(
        prompt=prompt,
        num_videos_per_prompt=1,
        num_inference_steps=current_steps,
        num_frames=current_frames,
        guidance_scale=current_guidance,
        generator=torch.Generator(device="cuda").manual_seed(42),
    ).frames[0]

    # 生成文件名
    video_count += 1
    filename = f"video_{video_count:03d}.mp4"
    filepath = os.path.join(OUTPUT_DIR, filename)

    # 保存视频
    export_to_video(video, filepath, fps=8)

    file_size = os.path.getsize(filepath) / 1024 / 1024
    print("\n" + "=" * 60)
    print(f"  ✓ 视频生成完成!")
    print("=" * 60)
    print(f"文件路径: {filepath}")
    print(f"文件大小: {file_size:.2f} MB")
    print("=" * 60 + "\n")

    return filepath


# 主循环
while True:
    user_input = input("提示词> ").strip()

    if not user_input:
        continue

    # 处理命令
    if user_input.lower() == "quit":
        print("\n" + "=" * 60)
        print("  感谢使用 CogVideoX-2B 文本生成视频工具!")
        print("=" * 60 + "\n")
        break

    elif user_input.lower() == "help":
        show_help()
        continue

    elif user_input.lower() == "steps":
        print(f"\n当前推理步数: {current_steps}\n")
        continue

    elif user_input.lower().startswith("steps:"):
        try:
            value = int(user_input[6:].strip())
            if 25 <= value <= 100:
                current_steps = value
                print(f"[✓ 推理步数已设置为: {value}]")
                if value < 40:
                    print("  提示: 步数较少,生成速度快但质量一般")
                elif value > 60:
                    print("  提示: 步数较多,生成质量高但耗时较长")
                print()
            else:
                print("[✗ 步数应在 25-100 之间]\n")
        except ValueError:
            print("[✗ 无效的步数,请输入数字]\n")
        continue

    elif user_input.lower() == "frames":
        print(f"\n当前生成帧数: {current_frames} 帧 ≈ {current_frames/8:.1f}\n")
        continue

    elif user_input.lower().startswith("frames:"):
        try:
            value = int(user_input[7:].strip())
            if 25 <= value <= 49:
                current_frames = value
                print(f"[✓ 生成帧数已设置为: {value} 帧 ≈ {value/8:.1f} 秒]\n")
            else:
                print("[✗ 帧数应在 25-49 之间]\n")
        except ValueError:
            print("[✗ 无效的帧数,请输入数字]\n")
        continue

    elif user_input.lower() == "guidance":
        print(f"\n当前引导强度: {current_guidance}\n")
        continue

    elif user_input.lower().startswith("guidance:"):
        try:
            value = float(user_input[9:].strip())
            if 4 <= value <= 8:
                current_guidance = value
                print(f"[✓ 引导强度已设置为: {value}]")
                if value < 5:
                    print("  提示: 引导较弱,生成结果更具创意性")
                elif value > 7:
                    print("  提示: 引导较强,生成结果更贴合提示词")
                print()
            else:
                print("[✗ 引导强度应在 4-8 之间]\n")
        except ValueError:
            print("[✗ 无效的引导强度,请输入数字]\n")
        continue

    elif user_input.lower() == "list":
        list_videos()
        continue

    # 生成视频
    try:
        generate_video(user_input)
    except Exception as e:
        print("\n" + "=" * 60)
        print("  ✗ 视频生成失败")
        print("=" * 60)
        print(f"错误信息: {e}")
        print("=" * 60 + "\n")

        if "out of memory" in str(e).lower():
            print("💡 显存不足,建议尝试:")
            print("  1. 减少推理步数: steps:30")
            print("  2. 减少生成帧数: frames:25")
            print("  3. 降低引导强度: guidance:5")
            print("  4. 关闭其他占用显存的程序(浏览器、游戏等)")
            print("  5. 重启 Python 脚本\n")
        elif "tokenizer" in str(e).lower() or "sentencepiece" in str(e).lower():
            print("💡 Tokenizer 加载失败,建议:")
            print("  1. 确认已安装: pip install sentencepiece protobuf")
            print("  2. 确认模型路径正确: models/cogvideox-2b\n")
        else:
            print("💡 建议:")
            print("  1. 检查提示词是否为英文")
            print("  2. 检查提示词长度(不超过 226 tokens)")
            print("  3. 输入 help 查看使用帮助\n")

11.4 运行 Python 文件

打开命令提示符(CMD),进入项目目录:

注意: 如果 CMD 当前不在 D 盘,需要先切换盘符。输入 D: 回车即可切换到 D 盘。

D:                          # 切换到 D 盘(如果已在 D 盘可跳过)
cd d:\wwwroot\modelscope
python video.py

11.5 使用说明

基本操作

============================================================
  CogVideoX-2B 文本生成视频工具
============================================================

正在加载模型,请稍候...
(首次加载需要约 1-2 分钟)
(显存优化已启用,适配 RTX 3060 12GB)

[1/3] 正在加载 T5 Tokenizer...
[2/3] 正在加载 CogVideoX-2B 模型...
[3/3] 启用显存优化...

============================================================
  ✓ 模型加载完成!
============================================================

输入英文提示词生成视频,或输入命令:
  quit     - 退出程序
  help     - 显示帮助
  steps    - 修改推理步数
  frames   - 修改生成帧数
  guidance - 修改引导强度
  list     - 已生成视频
============================================================

提示词> a cute cat walking on the grass

============================================================
  开始生成视频
============================================================
提示词: a cute cat walking on the grass
推理步数: 50
生成帧数: 49 帧 ≈ 6.1 秒
引导强度: 6
分辨率: 720×480 @ 8fps
============================================================

⏳ 预计需要 6-10 分钟,请耐心等待...

============================================================
  ✓ 视频生成完成!
============================================================
文件路径: videos\video_001.mp4
文件大小: 1.23 MB
============================================================

提示词>

使用命令

1. 查看帮助

提示词> help

╔══════════════════════════════════════════════════════════════╗
║              CogVideoX-2B 文本生成视频帮助                    ║
╠══════════════════════════════════════════════════════════════╣
║ 直接输入英文提示词即可生成视频(6 秒,720×480,8fps)         ║
║                                                              ║
║ 命令:                                                        ║
║   quit         - 退出程序                                    ║
║   help         - 显示本帮助                                  ║
║   steps        - 查看当前推理步数                            ║
║   steps:N      - 设置推理步数(如 steps:50,范围 25-100)    ║
║   frames       - 查看当前生成帧数                            ║
║   frames:N     - 设置生成帧数(如 frames:49,范围 25-49)    ║
║   guidance     - 查看当前引导强度                            ║
║   guidance:N   - 设置引导强度(如 guidance:7,范围 4-8)     ║
║   list         - 列出已生成的视频                            ║
╚══════════════════════════════════════════════════════════════╝

2. 查看当前推理步数

提示词> steps

当前推理步数: 50

3. 修改推理步数

提示词> steps:30
[✓ 推理步数已设置为: 30]
  提示: 步数较少,生成速度快但质量一般

4. 查看当前生成帧数

提示词> frames

当前生成帧数: 49 帧 ≈ 6.1 秒

5. 修改生成帧数

提示词> frames:25
[✓ 生成帧数已设置为: 25 帧 ≈ 3.1 秒]

6. 查看当前引导强度

提示词> guidance

当前引导强度: 6

7. 修改引导强度

提示词> guidance:7
[✓ 引导强度已设置为: 7]
  提示: 引导较强,生成结果更贴合提示词

8. 查看已生成的视频

提示词> list

已生成 3 个视频:
  - video_001.mp4 (1.23 MB)
  - video_002.mp4 (1.45 MB)
  - video_003.mp4 (1.18 MB)

9. 退出程序

提示词> quit

============================================================
  感谢使用 CogVideoX-2B 文本生成视频工具!
============================================================

11.6 自定义配置

代码开头的配置区域可以根据需要修改:

# ==================== 配置区 ====================
# 本地模型路径
MODEL_PATH = "models/cogvideox-2b"
TOKENIZER_PATH = "models/cogvideox-2b/tokenizer"

# 视频保存目录
OUTPUT_DIR = "videos"

# 生成参数
NUM_INFERENCE_STEPS = 50  # 推理步数(25-100)
NUM_FRAMES = 49           # 生成帧数(25-49)
GUIDANCE_SCALE = 6        # 引导强度(4-8)
# ================================================

配置说明

配置项说明推荐值
MODEL_PATH模型路径"models/cogvideox-2b"
TOKENIZER_PATH分词器路径"models/cogvideox-2b/tokenizer"
OUTPUT_DIR视频保存目录"videos"
NUM_INFERENCE_STEPS默认推理步数,越多越精细但越慢50
NUM_FRAMES默认生成帧数,49 帧 ≈6 秒49
GUIDANCE_SCALE提示词引导强度,越高越符合提示词6

参数调整建议

# 快速生成(质量一般)
NUM_INFERENCE_STEPS = 30
NUM_FRAMES = 25
GUIDANCE_SCALE = 6

# 标准质量(推荐)
NUM_INFERENCE_STEPS = 50
NUM_FRAMES = 49
GUIDANCE_SCALE = 6

# 高质量(耗时长)
NUM_INFERENCE_STEPS = 60
NUM_FRAMES = 49
GUIDANCE_SCALE = 7

11.7 常见问题

问题 1:提示「ModuleNotFoundError: No module named 'diffusers'」

原因: 未安装 diffusers 库

解决:

pip install diffusers>=0.30.3 transformers>=4.44.2 accelerate>=0.34.0 -i https://mirrors.aliyun.com/pypi/simple/

问题 2:提示「找不到模型路径」

原因: MODEL_PATH 设置错误

解决: 修改代码中的 MODEL_PATH 为你实际的模型路径

MODEL_PATH = "你的模型路径/cogvideox-2b"

问题 3:显存不足(Out of Memory)

解决方案:

  1. 减少推理步数:steps:30
  2. 减少生成帧数:frames:25
  3. 降低引导强度:guidance:5
  4. 关闭其他占用显存的程序
  5. 确认已启用显存优化(代码中已默认启用)

问题 4:缺少 SentencePiece 库

错误信息:

T5Tokenizer requires the SentencePiece library

解决:

pip install sentencepiece protobuf imageio-ffmpeg -i https://mirrors.aliyun.com/pypi/simple/

问题 5:生成速度太慢

原因: 视频生成计算量巨大,正常现象

优化建议:

提示词> steps:30
提示词> frames:25

这样可以生成 3 秒的视频,耗时约 3-4 分钟。


11.8 进阶技巧

技巧 1:批量生成

如果想生成多个相似的视频,可以多次输入提示词:

提示词> a cat walking on the grass
✓ 视频生成完成!videos\video_001.mp4

提示词> a dog running in the park
✓ 视频生成完成!videos\video_002.mp4

提示词> ocean waves at sunset
✓ 视频生成完成!videos\video_003.mp4

模型保持加载状态,无需重复加载。

技巧 2:快速测试提示词

想快速测试提示词效果,可以降低参数:

提示词> steps:30
提示词> frames:25
提示词> your test prompt here

生成速度提升约 60%,但质量会有所下降。

技巧 3:高质量生成

确认提示词效果后,提升参数生成高质量视频:

提示词> steps:60
提示词> frames:49
提示词> guidance:7
提示词> your final prompt here

技巧 4:分场景优化

根据不同场景调整引导强度:

# 自然风景(更自由)
提示词> guidance:5
提示词> ocean waves crashing on beach at sunset

# 动物动作(平衡)
提示词> guidance:6
提示词> a cat walking on grass

# 精确物体运动(更精确)
提示词> guidance:7
提示词> a red balloon floating upward into blue sky

11.9 实用工作流示例

工作流 1:生成自然风景

1. 启动程序
python video.py

2. 设置标准参数
提示词> steps:50
提示词> frames:49
提示词> guidance:6

3. 生成多个风景视频
提示词> ocean waves crashing on a sandy beach at golden sunset
✓ 视频生成完成!

提示词> white fluffy clouds drifting slowly across a bright blue sky
✓ 视频生成完成!

提示词> cherry blossom petals falling gently in the spring breeze
✓ 视频生成完成!

4. 查看生成的视频
提示词> list

工作流 2:快速测试多个提示词

1. 设置快速参数
提示词> steps:30
提示词> frames:25

2. 批量测试
提示词> a cat walking
提示词> a dog running
提示词> a bird flying
提示词> ocean waves
提示词> falling leaves

3. 选择最佳提示词,提升质量重新生成
提示词> steps:50
提示词> frames:49
提示词> [最佳提示词]

工作流 3:生成抽象效果

1. 设置创意参数
提示词> guidance:5
提示词> steps:50

2. 生成抽象视频
提示词> colorful ink drops spreading and swirling in clear water
✓ 视频生成完成!

提示词> smoke wisps rising and dancing in slow motion
✓ 视频生成完成!

十二、总结

恭喜!到这里你已经掌握了基于 ModelScope 本地部署 CogVideoX-2B 文生视频模型的完整流程。

本教程内容回顾

我们从零开始,依次完成了以下关键步骤:

  1. 环境准备:安装 Python、配置环境变量
  2. 依赖安装:ModelScope、PyTorch CUDA 版、Diffusers、T5 Tokenizer 等核心库
  3. 环境验证:检查 Python、显卡、CUDA 是否配置正确
  4. 模型下载:使用 ModelScope 命令行工具下载 CogVideoX-2B 模型(约 5-6GB)
  5. 模型加载:在 Python 交互式环境中加载并测试模型
  6. 视频生成:使用提示词生成 6 秒视频
  7. 问题解决:处理常见错误,如显存不足、生成速度慢等
  8. 提示词技巧:掌握提示词的编写方法和最佳实践
  9. 实用工具:创建 Python 文件,实现交互式视频生成、命令管理等功能
  10. 高级配置:自定义生成参数、调整推理步数、优化显存占用

学习掌握的能力

完成本教程后,一般来说将能够:

独立部署文生视频模型:掌握从环境配置到模型运行的完整流程
使用 ModelScope 平台:熟悉魔搭社区的模型下载和管理方式
配置 GPU 加速:理解 CUDA 原理,正确安装和验证 PyTorch
排查常见错误:处理环境问题、显存不足、生成质量等问题
编写高质量提示词:掌握视频提示词的编写技巧和词汇库
开发视频生成应用:创建支持交互式操作、命令系统的 AI 视频工具
自定义模型行为:通过参数调整控制生成效果和质量
优化生成性能:调整推理步数、使用显存优化技术降低资源消耗

适用场景与应用方向

基于实际测试,CogVideoX-2B 模型在不同场景下的表现各有差异:

场景适用性评估:

场景推荐程度生成效果使用建议
自然风景⭐⭐⭐⭐⭐优秀波浪、云彩、花瓣飘落等动态元素效果极佳
动物动作⭐⭐⭐⭐良好简单动作如行走、飞翔效果好,注意控制肢体数量
物体运动⭐⭐⭐⭐良好气球上升、烟雾飘散等简单运动效果稳定
城市场景⭐⭐⭐一般车流、雨夜等场景可尝试,细节可能不精确
复杂人物⭐⭐较差人物细节容易出问题,建议用远景或剰影
抽象概念较差避免使用,模型难以理解抽象描述

后续学习建议

如果想进一步提升,可以尝试:

  • 探索其他模型:在 ModelScope 上尝试 CogVideoX-5B(需要更大显存)等其他视频生成模型
  • 学习图生视频:尝试使用图片作为参考生成视频的 Image-to-Video 模式
  • 集成到应用:将模型集成到 Web 应用、自动化工具中
  • 结合文生图:先用 SDXL 生成静态图,再用视频模型赋予动态效果

感谢阅读

希望这篇教程能帮助你顺利部署属于自己的 AI 视频生成模型!如果遇到问题,欢迎反馈和交流。

祝你在 AI 视频创作领域不断探索,创作出精彩的作品! 🎬