Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

DiffSynth-Studio MUSA Patch 使用文档

DiffSynth-Studio MUSA Patch User Documentation


目录 / Table of Contents

  1. 项目简介 / Introduction
  2. 功能特性 / Features
  3. 系统要求 / System Requirements
  4. 安装指南 / Installation Guide
  5. 核心架构 / Core Architecture
  6. 推理使用 / Inference Usage
  7. 训练使用 / Training Usage

1. 项目简介 / Introduction

中文

DiffSynth-Studio MUSA Patch 是为 DiffSynth-Studio 扩散模型引擎开发的摩尔线程(Moore Threads)GPU 适配补丁。它使 DiffSynth-Studio 能够在摩尔线程 MUSA 架构的 GPU 上高效运行视频生成和训练任务,同时保持与 NVIDIA CUDA 环境的完全兼容。

该补丁采用双后端自适应设计:导入时自动检测当前 GPU 类型(MUSA 或 CUDA),并透明切换底层设备调用,用户代码无需任何修改即可在两种硬件上运行。

English

DiffSynth-Studio MUSA Patch is a Moore Threads GPU adaptation patch for the DiffSynth-Studio diffusion model engine. It enables DiffSynth-Studio to efficiently run video generation and training tasks on Moore Threads MUSA-architecture GPUs while maintaining full compatibility with NVIDIA CUDA environments.

The patch uses a dual-backend adaptive design: it automatically detects the current GPU type (MUSA or CUDA) at import time and transparently switches underlying device calls. User code runs unmodified on both hardware platforms.


2. 功能特性 / Features

功能 中文说明 English Description
CUDA→MUSA 透明转换 将 torch.cuda.* 调用自动映射为 torch.musa.*,无需修改业务代码 Transparently maps torch.cuda.* to torch.musa.* calls
设备自动检测 运行时自动识别 MUSA 或 CUDA 环境,选择对应后端 Runtime auto-detection of MUSA/CUDA backend
Disk Offload 兼容 修复 safetensors 在非 CUDA 设备上的加载问题 Fixes safetensors loading on non-CUDA devices
FSDP2 分布式训练 支持 FSDP2 全分片数据并行,含 text_encoder 和 image_encoder 分片 FSDP2 full-shard data parallel with text/image encoder sharding
FusedAdamW 优化器 在 MUSA 上使用融合 AdamW 优化器提升训练速度 Uses FusedAdamW optimizer on MUSA for faster training
梯度检查点控制 可配置 DiT Block 的梯度检查点层数,精确控制显存占用 Configurable gradient checkpointing layers for precise VRAM control
批量训练 支持多样本批量训练(batch_size > 1),提供自定义 collate 函数 Multi-sample batch training with custom collate function
Profiling 工具 内置 PyTorch Profiler 封装,支持 MUSA/CUDA 双后端性能分析 Built-in PyTorch Profiler wrapper for both MUSA/CUDA backends
训练路径修复 修复本地路径 + glob 模式的模型加载问题 Fixes local path + glob pattern model loading

3. 系统要求 / System Requirements

MUSA 环境 / MUSA Environment

依赖 版本 说明
MUSA 软件栈 (driver + toolkits) 5.3.0 摩尔线程 GPU 软件栈;musa_toolkits/mcc/musa_runtime 均为 5.3.0,DDK 驱动随宿主机安装
Python 3.10.12 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
PyTorch 2.13.0.post1 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
torch_musa 2.13.0.post1 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
torchvision 0.28.0.post1+musa5.2.0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
torchaudio 2.11.0+cpu Linux CPU wheel,由 requirements.txt 安装 / installed via requirements.txt
flash_attn 2.8.3.post4 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
triton 3.6.0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
deepspeed 0.19.3+f2f11ddb 由 MUSA 训练框架镜像提供(源码构建)/ image source build
DiffSynth-Studio 2.1.0 由 requirements.txt / pyproject.toml 安装 / installed via requirements.txt
torchada 0.1.89 cuda→musa 重定向适配层(镜像预装 0.1.89;requirements.txt 锁定 0.1.102)
accelerate 1.12.0 由 requirements.txt 安装 / installed via requirements.txt
transformers 5.17.0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
safetensors 0.8.0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
einops 0.9.0.dev0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
tokenizers 0.23.2 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
numpy 1.23.5 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
Pillow 9.2.0 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
peft 0.18.1 由 requirements.txt 安装 / installed via requirements.txt
modelscope 1.35.0 由 requirements.txt 安装 / installed via requirements.txt
tqdm 4.70.1 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
scipy 1.15.3 由 MUSA 训练框架镜像提供 / supplied by the MUSA base image
uv 0.12.18 Python 包管理器,由 MUSA 训练框架镜像提供

注:上表"镜像提供"的版本取自摩尔线程 MUSA 训练框架容器 training-framework-torch213(基于 musa-devel-py310:pt213_5.3.0-ph1,torch 2.13 + MUSA 5.3.0)的实测值;标注"由 requirements.txt 安装"的包在该容器中未预装,需按 §4.2 另行安装。torchada 镜像预装 0.1.89,而 requirements.txt 锁定 0.1.102,按 §4.2 安装后以实际解析结果为准。如自行构建,最终版本以实际解析结果为准。

中文 — 已验证的 MUSA 驱动及工具链版本:

组件 版本
musa_toolkits 5.3.0
musa_runtime 5.3.0
mcc (MUSA C Compiler) 5.3.0
mublas / mublasLt (BLAS) 1.12.0
mufft (FFT) 1.12.0
murand (Random) 1.3.0
musolver (Solver) 1.8.0
musparse (Sparse) 1.7.0
muPP (Image Processing) 1.13.0
MUPTI (Profiling) 1.4.0
mtjpeg (JPEG) 1.0.5
musify 1.3.0
mualg (Algorithm) 1.17.2
muthrust (Thrust) 1.17.2

English — Verified MUSA driver and toolkit versions: see table above.

查看版本信息 / Check Version Info

中文

在宿主机上查看 DDK 驱动版本:

dpkg -s musa

在容器内查看 MUSA 工具链版本:

cat /usr/local/musa/version.json

English

Check DDK driver version on the host machine:

dpkg -s musa

Check MUSA toolkit version inside the container:

cat /usr/local/musa/version.json

CUDA 环境 / CUDA Environment

依赖 版本要求 说明
Python >= 3.10 /
PyTorch >= 2.11 CUDA 版本
DiffSynth-Studio 2.1.0 uv 安装 / uv install

4. 安装指南 / Installation Guide

4.0 MUSA 基础镜像(推荐)/ MUSA Base Image (Recommended)

中文 — 获取可用 MUSA 环境的最快方式:拉取摩尔线程 MUSA 基础镜像,它已包含 MUSA 软件栈(driver + toolkits)、PyTorch / torch_musa / torchvision 等 GPU 运行依赖以及 Python 3.10,并已预装 uv;但它不包含本仓库代码。因此进入容器后,仍需按 §4.2 的步骤 git clone 本仓库并用 uv 安装 Python 依赖(这一步同时会装上 cuda→musa 重定向适配层 torchada)。

# 拉取 MUSA 基础镜像(提供 torch / torch_musa 2.13.0.post1 软件栈;请将 <your-musa-base-image> 替换为你实际可用的 MUSA 基础镜像地址)
docker pull <your-musa-base-image>

# 启动容器:挂载模型与权重目录,并暴露 GPU 与主机网络(便于容器内 git clone)
# DS_ACCELERATOR=musa 必须设置:镜像自带的 DeepSpeed 源码版在导入时会探测 nvcc,
# 而 torchada 会把 CUDA_HOME 指向 /usr/local/musa;不指定加速器会导致 import 失败。
docker run -it --privileged --env MTHREADS_VISIBLE_DEVICES=all --env DS_ACCELERATOR=musa --shm-size=256g \
  --network=host \
  -v <your_model_path>:<your_model_path> \
  -v <your_weight_path>:<your_weight_path> \
  <your-musa-base-image> /bin/bash

说明:上面挂载的 <your_model_path> / <your_weight_path> 即为模型权重所在的宿主目录(例如 Wan2.1-T2V-1.3B 等),容器内外使用同一路径即可。若你的镜像已自带权重目录,可省去对应 -v 挂载。

已知问题(基础镜像完整性):该基础镜像只提供 MUSA 软件栈与 torch/torch_musa/torchvision,但未预装完整的 Python 依赖栈。其中 huggingface_hub 与 modelscope 的摩尔线程内部构建分别依赖内部包 httpx2 / httpcore2 / modelscope_hub,这些内部包不在公开 PyPI 上,需由可访问摩尔线程内部索引的基础镜像提供;否则 import diffsynth_musa 会在导入 huggingface_hub / modelscope 时因缺少上述内部包而失败。开源场景请将 requirements.txt 中的内部构建替换为公开等价版本,或确保你的基础镜像已包含完整的内部依赖栈(可对照已验证可用的参考 MUSA 环境)。

进入容器后,按 §4.2 完成「克隆仓库 → 安装 uv → 创建虚拟环境 → uv pip install -r requirements.txt --no-deps」,再运行 examples/ 下的训练/推理脚本(将模型与数据集路径指向你挂载的实际位置)。

English — The fastest way to get a working MUSA environment is to pull the Moore Threads MUSA base image, which already bundles the MUSA software stack (driver + toolkits), the GPU runtime dependencies (PyTorch / torch_musa / torchvision), Python 3.10, and preinstalls uv — but does not include this repository's code. Inside the container you still need to git clone this repository and install Python dependencies with uv per §4.2 (this also installs the cuda→musa adapter torchada).

docker pull <your-musa-base-image>
# DS_ACCELERATOR=musa is required: the image's DeepSpeed source build probes for
# nvcc at import time, and torchada points CUDA_HOME at /usr/local/musa; without an
# explicit accelerator, the import fails.
docker run -it --privileged --env MTHREADS_VISIBLE_DEVICES=all --env DS_ACCELERATOR=musa --shm-size=256g \
  --network=host \
  -v <your_model_path>:<your_model_path> \
  -v <your_weight_path>:<your_weight_path> \
  <your-musa-base-image> /bin/bash

Note: <your_model_path> / <your_weight_path> are the host directories holding model weights (e.g. Wan2.1-T2V-1.3B). Mount them at the same path inside the container. If your image already bundles the weights, omit the corresponding -v.

Known issue (base image completeness): This base image only provides the MUSA software stack and torch/torch_musa/torchvision; it does not ship the full Python dependency set. The Moore Threads internal builds of huggingface_hub and modelscope depend on internal packages httpx2 / httpcore2 / modelscope_hub, which are not on public PyPI and must be provided by a base image that can reach the internal Moore Threads index. Otherwise import diffsynth_musa fails while importing huggingface_hub / modelscope due to the missing internal packages. For an open-source build, replace the internal builds in requirements.txt with public equivalents, or ensure your base image bundles the complete internal dependency stack (cf. a verified reference MUSA environment that bundles the complete internal dependency stack).

Inside the container, follow §4.2 (clone the repo → install uv → create the venv → uv pip install -r requirements.txt --no-deps), then run the training/inference scripts under examples/, pointing the model and dataset paths at your mounted locations.

4.1 作为 Python wheel 安装 / Install as a Python wheel

从当前源码构建 wheel(无需在构建机安装 GPU 运行依赖):在仓库根目录运行 uv build --wheel,构建产物位于 dist/diffsynth_musa-2.1.0+torch.musa2.13.0.post1-py3-none-any.whl。这个纯 Python wheel 不含模型、CUDA/MUSA 二进制包;修改源码或版本号后需要重新构建。构建时确保 pyproject.toml 和代码是同一个待交付版本。

uv build --wheel
python -m pip install --no-deps ./dist/diffsynth_musa-2.1.0+torch.musa2.13.0.post1-py3-none-any.whl

将 .whl 文件交付客户后,在客户机器上的目标 Python 环境中安装(先按下文准备依赖):python -m pip install --no-deps /实际存放路径/diffsynth_musa-2.1.0+torch.musa2.13.0.post1-py3-none-any.whl。如果使用普通 CUDA 环境且允许 pip 解析依赖,可去掉 --no-deps,但请先装好匹配的 PyTorch 栈。建议始终使用目标环境的 python -m pip,避免装进错误的解释器。

Wheel 的分发名为 diffsynth-musa(导入名 diffsynth_musa)。源码版本 2.1.0+torch_musa2.13.0.post1 中,公开段 2.1.0 对应上游 diffsynth==2.1.0,本地版本段标识目标环境的 torch_musa 2.13.0.post1;PEP 440 会把下划线规范化为点,因此实际 wheel 文件名及安装后的版本为 2.1.0+torch.musa2.13.0.post1。版本标签不负责安装或验证 torch、torch_musa 的二进制兼容性,仍需按目标环境预装并测试。含本地版本段的构建仅适合直接交付 wheel 或发布至允许本地版本的私有索引,不可上传 PyPI。pyproject.toml 声明 wheel 的依赖;requirements.txt 是运行示例/CI 的环境清单,不会整体加入 wheel 安装依赖。

The distribution name is diffsynth-musa (imported as diffsynth_musa). Its source version 2.1.0+torch_musa2.13.0.post1 uses the public segment for upstream diffsynth==2.1.0 and a local segment to label the targeted torch_musa environment. PEP 440 normalizes the underscore to a dot: the built wheel and installed version use 2.1.0+torch.musa2.13.0.post1. This label neither installs nor validates the GPU binary stack. Local-version builds can be distributed as wheel files or through an accepting private index, but cannot be uploaded to PyPI.

已发布版本的安装命令(无需克隆仓库):以下命令仅在 2.1.0+torch.musa2.13.0.post1 已上传至允许本地版本的私有包索引后可用;该版本不能上传 PyPI(若要公开发布到 PyPI,须改用不含本地版本段的干净版本号,例如 2.1.0)。写入 pyproject.toml 的版本号并不等于已经发布。

# 普通 CUDA 环境:先安装匹配的 torch / torchvision,再解析其余依赖
python -m pip install "diffsynth-musa==2.1.0+torch.musa2.13.0.post1"

# 预装 MUSA 环境:先按下文配齐依赖,再保留镜像中的 GPU 二进制栈
python -m pip install --no-deps "diffsynth-musa==2.1.0+torch.musa2.13.0.post1"

预装 MUSA 栈(推荐,沿用主环境):请先确保主环境中的 Python 与虚拟环境同版本,并已安装匹配的 torch、torch_musa、torchvision、flash_attn、deepspeed 等。若持有本仓库,以下步骤用 requirements.txt 配齐示例环境,然后安装已发布的指定版本;--no-deps 保留主环境二进制包,但也要求安装者自行保证包括上游 diffsynth 传递依赖在内的所有依赖齐全。

uv venv --python 3.10 --system-site-packages
source .venv/bin/activate
python -c 'import torch, torch_musa, torchvision; print(torch.__version__, torch_musa.__version__, torchvision.__version__)'
uv pip install --no-deps -r requirements.txt --index-strategy unsafe-best-match
python -m pip install --no-deps "diffsynth-musa==2.1.0+torch.musa2.13.0.post1"
python -c 'import diffsynth_musa, diffsynth; print("diffsynth-musa import OK")'
python -m pip check

尚未发布时,从仓库构建 wheel 后可改用 python -m pip install --no-deps dist/diffsynth_musa-2.1.0+torch.musa2.13.0.post1-py3-none-any.whl;uv pip install --no-deps . 仅用于安装当前仓库源码,不是从包索引安装指定版本。若使用私有包索引,请按组织要求配置索引地址或凭据,不要让安装器从错误的同名来源下载。

pip check 检查元数据依赖,但不能替代 MUSA 二进制兼容性或推理/训练验证。尤其是 torchaudio==2.11.0+cpu 的上游依赖可能与镜像中的 torch==2.13.0.post1 不完全一致:安装前先检查主环境是否已有可用的 torchaudio,勿仅凭版本号覆盖原有二进制栈;若检查失败,应在目标镜像中验证兼容组合,而不是忽略失败。

普通 CUDA 环境:预装匹配的 torch / torchvision 后,上方未带 --no-deps 的版本化命令会正常解析 diffsynth==2.1.0 的传递依赖(其中声明了 torch>=2.0.0 和 torchvision);它并不保证自动选到特定 CUDA/MUSA 构建。

English — Once published to a private index that accepts local versions (not PyPI), run python -m pip install "diffsynth-musa==2.1.0+torch.musa2.13.0.post1" for a CUDA environment with a matching PyTorch stack already installed. On an image with preinstalled MUSA binaries, provision all dependencies first and use python -m pip install --no-deps "diffsynth-musa==2.1.0+torch.musa2.13.0.post1" to avoid replacing that stack. Before publication, install a built wheel file instead; uv pip install --no-deps . installs the local source tree, not the published release.

安装后,只需在使用前先导入本包即可自动对上游 diffsynth 打补丁:

import diffsynth_musa   # 必须在 import diffsynth 之前
import diffsynth

注意:wheel 只打包 diffsynth_musa 代码,不捆绑 torch、torch_musa 或示例文件。普通安装会根据 pyproject.toml 和上游 diffsynth 的元数据解析传递依赖(包括 torch、torchvision、accelerate 等);使用 --no-deps 时必须预先配齐这些依赖。torchada 由 requirements.txt 提供,或在非 --no-deps 安装时选择 [musa] extra。

4.2 完整安装(MUSA 环境)/ Full Installation (MUSA)

# ========== Step 1: 安装 torch_musa(如已安装可跳过)==========
# Step 1: Install torch_musa (skip if already installed)
# torch_musa 由摩尔线程官方提供;请从官方渠道获取并安装与你环境匹配的 MUSA DDK 与 torch_musa。
# torch_musa is provided by Moore Threads; install a MUSA DDK and torch_musa matching your
# environment from official channels.

# ========== Step 2: 克隆 MUSA Patch ==========
# Step 2: Clone MUSA Patch
git clone https://github.com/MooreThreads/DiffSynth-MUSA.git
cd DiffSynth-MUSA

# ========== Step 3: 安装 uv ==========
# Step 3: Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
grep -qF 'export PATH="$HOME/.local/bin:$PATH"' ~/.bashrc || echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

# ========== Step 4: 创建虚拟环境 ==========
# Step 4: Create Virtual Environment
uv venv --python 3.10 --system-site-packages
source .venv/bin/activate

# ========== Step 5: 安装依赖 ==========
# Step 5: Install Dependencies
# requirements.txt 中包含 diffsynth==2.1.0,无需单独克隆官方仓库
# requirements.txt includes diffsynth==2.1.0, no need to clone the official repo separately
uv pip install --no-deps -r requirements.txt --index-strategy unsafe-best-match

4.3 CUDA 环境安装 / CUDA Installation

在 CUDA 环境下,patch 包同样适用(自动检测后端)。安装流程相同,跳过 torch_musa 构建步骤即可。

# 克隆 MUSA Patch / Clone MUSA Patch
git clone https://github.com/MooreThreads/DiffSynth-MUSA.git
cd DiffSynth-MUSA

# 安装 uv / Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh
grep -qF 'export PATH="$HOME/.local/bin:$PATH"' ~/.bashrc || echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

# 创建虚拟环境并安装依赖 / Create venv and install dependencies
uv venv --python 3.10 --system-site-packages
source .venv/bin/activate
uv pip install --no-deps -r requirements.txt

4.4 验证安装 / Verify Installation

在 MUSA 基础镜像上运行前,请确保已设置 export DS_ACCELERATOR=musa(见 §4.0),否则 import diffsynth_musa 会因 DeepSpeed 在导入时探测 nvcc 而失败。若使用 §7.1 的 setup_env.sh,该变量会由脚本自动导出。

import diffsynth_musa

# 检测当前后端 / Check current backend
if diffsynth_musa.IS_MUSA:
    print("Running on Moore Threads MUSA backend")
else:
    print("Running on NVIDIA CUDA backend")

5. 核心架构 / Core Architecture

中文

补丁通过 Python 模块导入自动生效。在已安装本包(见 §4 安装,或使用预装镜像)后,只需在代码顶部直接导入即可完成所有适配:

import diffsynth_musa   # 导入即生效(需先 pip install diffsynth-musa 或使用预装镜像)

若你从源码仓库直接运行示例(未执行 pip install),则需先将项目根目录加入 sys.path:

import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", ".."))
import diffsynth_musa

diffsynth_musa/__init__.py 执行以下操作:

  1. patch_before_import_diffsynth() — 在 diffsynth 导入前修补其模块
  2. 各子模块的 apply_*() 函数自动在导入时运行
  3. 在 MUSA 后端自动 import torchada(通过 requirements.txt 或 [musa] extra 提供的适配包),透明地把 torch.cuda.* 重定向到 torch.musa.*,替代原先手写的 cuda→musa monkey-patch

English

Patches are applied automatically via Python module imports. After installing this package (see §4, or use the prebuilt image), simply import it at the top of your code:

import diffsynth_musa   # Patches applied on import (requires pip install diffsynth-musa or the prebuilt image)

If you run the examples directly from the source tree without pip install, add the project root to sys.path first:

import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", ".."))
import diffsynth_musa

diffsynth_musa/__init__.py performs:

  1. patch_before_import_diffsynth() — Patches diffsynth modules before they're imported
  2. Each submodule's apply_*() function runs automatically on import
  3. On the MUSA backend, import torchada (provided via requirements.txt or the [musa] extra) transparently redirects torch.cuda.* to torch.musa.*, replacing the hand-written cuda->musa monkey-patch

6. 推理使用 / Inference Usage

中文

以下示例展示如何使用 Wan2.1-T2V-1.3B 模型生成视频。代码自动检测 GPU 后端,在 MUSA 和 CUDA 上均可运行。

English

The following example demonstrates video generation with Wan2.1-T2V-1.3B. The code auto-detects the GPU backend and works on both MUSA and CUDA.

import os
import torch

import diffsynth_musa

from diffsynth.utils.data import save_video
from diffsynth.pipelines.wan_video import WanVideoPipeline, ModelConfig

# 自动检测设备类型 / Auto-detect device type
if diffsynth_musa.IS_MUSA:
    target_device = "musa:0"
    total_vram = torch.musa.mem_get_info("musa")[1] / (1024 ** 3)
else:
    target_device = "cuda:0"
    total_vram = torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3)

# VRAM 配置(磁盘卸载)/ VRAM config (disk offload)
vram_config = {
    "offload_dtype": "disk",
    "offload_device": "disk",
    "onload_dtype": torch.bfloat16,
    "onload_device": "cpu",
    "preparing_dtype": torch.bfloat16,
    "preparing_device": target_device,
    "computation_dtype": torch.bfloat16,
    "computation_device": target_device,
}

model_base_path = "/path/to/models/Wan2.1-T2V-1.3B"

pipe = WanVideoPipeline.from_pretrained(
    torch_dtype=torch.bfloat16,
    device=target_device,
    model_configs=[
        ModelConfig(path=os.path.join(model_base_path, "diffusion_pytorch_model.safetensors"), **vram_config),
        ModelConfig(path=os.path.join(model_base_path, "models_t5_umt5-xxl-enc-bf16.pth"), **vram_config),
        ModelConfig(path=os.path.join(model_base_path, "Wan2.1_VAE.pth"), **vram_config),
    ],
    tokenizer_config=ModelConfig(path=os.path.join(model_base_path, "google/umt5-xxl/")),
    redirect_common_files=False,
    vram_limit=total_vram - 2,
)

# 生成视频 / Generate video
video = pipe(
    prompt="A cute puppy running on a green lawn, documentary style.",
    negative_prompt="static, blurry, low quality",
    seed=0,
    tiled=True,
)
save_video(video, "output.mp4", fps=15, quality=5)

7. 训练使用 / Training Usage

7.1 环境准备 / Environment Setup

中文

训练前使用 setup_env.sh 自动配置 GPU 环境:

English

Before training, use setup_env.sh to auto-configure the GPU environment:

# 自动检测并配置 8 GPU 环境 / Auto-detect and configure 8 GPU environment
source examples/wanvideo/model_training/setup_env.sh 8

# 脚本会自动设置 / The script auto-configures:
# - MUSA: MUSA_VISIBLE_DEVICES, MCCL_*, TORCH_MUSA_FSDP2_*
# - CUDA: CUDA_VISIBLE_DEVICES, NCCL_*, PYTORCH_CUDA_ALLOC_CONF

中文 — setup_env.sh 位于 model_training/ 目录下,Accelerate 配置位于其 config/ 子目录中,由 full/ 和 lora/ 下的训练脚本共享引用:

examples/wanvideo/model_training/
├── setup_env.sh                    # 共享环境配置脚本 / Shared env setup
├── config/                         # Accelerate 配置 / Accelerate configs
│   ├── accelerate_config_fsdp2.yaml
│   ├── accelerate_config_zero2.yaml
│   └── accelerate_config_zero3.yaml
├── multi_nodes_training.sh         # 多机训练启动脚本 / Multi-node launcher
├── train.py
├── full/                           # 全参数训练脚本 / Full-parameter training
│   ├── Wan2.1-T2V-1.3B.sh
│   └── ...
└── lora/                           # LoRA 训练脚本 / LoRA training
    ├── Wan2.1-T2V-1.3B.sh
    └── ...

English — setup_env.sh resides in model_training/, while the Accelerate configurations reside in its config/ subdirectory. They are shared by training scripts under full/ and lora/.

7.2 准备数据集 / Prepare Dataset

中文

训练数据集使用 CSV 或 JSON 格式的元数据文件:

English

Training datasets use CSV or JSON format metadata files:

video,prompt
videos/clip1.mp4,"A sunset over a small town"
videos/clip2.mp4,"Waves crashing on the shore"

对于 I2V 训练,添加 input_image 列 / For I2V training, add an input_image column:

video,prompt,input_image
videos/clip1.mp4,"A puppy running","images/frame1.jpg"

7.3 配置训练数据路径 / Configure Training Data Paths

中文

训练脚本通过两个关键变量指定数据集路径,所有训练脚本(examples/wanvideo/model_training/full/*.sh 和 lora/*.sh)头部均有以下配置段:

# ============================================================
# Dataset Configuration
# ============================================================
DATASET_NAME="${DATASET_NAME:-/path/to/datasets/demo_video_dataset/videos}"
DATASET_META_NAME="${DATASET_META_NAME:-/path/to/datasets/demo_video_dataset/metadata.csv}"
  • DATASET_NAME:对应启动参数 --dataset_base_path,即数据集的根目录。metadata.csv 中所有相对路径(如 videos/clip1.mp4)都基于此目录解析。
  • DATASET_META_NAME:对应启动参数 --dataset_metadata_path,即元数据 CSV/JSON 文件的绝对路径。
  • 两个变量都采用 ${VAR:-默认值} 写法:不设环境变量时用公开占位路径,设置了就用你的真实路径。

内部开发:在自己的 ~/.bashrc 中设置路径

公开代码树不含任何内部路径。数据集 / 模型路径由每位开发者在自己的 ~/.bashrc 中 export,脚本里的 ${VAR:-默认值} 会自动采用这些值,无需改动仓库里的任何脚本:

# 写入 ~/.bashrc(示例:Wan2.1-T2V-14B + OpenVidHD)
export DATASET_NAME="/workspace/datasets/OpenVidHD/videos"
export DATASET_META_NAME="/workspace/datasets/OpenVidHD/metadata.csv"
export MODEL_DIR="/workspace/models/Wan2.1-T2V-14B"
# 重新登录或 source ~/.bashrc 后运行
bash examples/wanvideo/model_training/full/Wan2.1-T2V-14B.sh

路径只存在于各自的 bashrc,不进 git。内部 CI 的真实路径与镜像标签放在 .ci/s5000.env(被 .gitignore 忽略,只提交到内部 GitLab,需 git add -f)。

推荐的目录结构 / Recommended directory structure:

/path/to/datasets/my_dataset/
├── metadata.csv              # 元数据文件
├── videos/                   # 视频/图像文件目录
│   ├── clip1.mp4
│   ├── clip2.mp4
│   └── ...
└── images/                   # I2V 训练用的参考图像目录(可选)
    ├── ref1.jpg
    └── ref2.jpg

修改数据集路径:推荐在 ~/.bashrc 里设置 DATASET_NAME / DATASET_META_NAME,或在启动命令前临时 export:

export DATASET_NAME="/data/my_training_data"
export DATASET_META_NAME="/data/my_training_data/metadata.csv"
bash examples/wanvideo/model_training/full/Wan2.1-T2V-1.3B.sh

配置模型路径:训练脚本通过 MODEL_DIR / MODEL_PATH 环境变量(同样可在 ~/.bashrc 中设置)指定预训练模型根目录,脚本据此拼出 --model_paths 所需的权重文件列表,例如:

export MODEL_DIR="/path/to/models/Wan2.1-T2V-1.3B"
# 脚本内部据此拼出 --model_paths:DiT 权重 + T5 文本编码器 + VAE

English

Training scripts specify dataset paths through two key variables at the top of each script (examples/wanvideo/model_training/full/*.sh and lora/*.sh):

# ============================================================
# Dataset Configuration
# ============================================================
DATASET_NAME="${DATASET_NAME:-/path/to/datasets/demo_video_dataset/videos}"
DATASET_META_NAME="${DATASET_META_NAME:-/path/to/datasets/demo_video_dataset/metadata.csv}"
  • DATASET_NAME → --dataset_base_path: The dataset root directory. All relative paths in metadata.csv (e.g. videos/clip1.mp4) are resolved relative to this directory.
  • DATASET_META_NAME → --dataset_metadata_path: The absolute path to the CSV/JSON metadata file.
  • Both use ${VAR:-default}: the public placeholder is used only when the environment variable is unset.

For internal development (set paths in your own ~/.bashrc)

The public tree contains no internal paths. Export dataset/model paths from your own ~/.bashrc; the ${VAR:-default} in each script picks them up — no script edits needed:

# add to ~/.bashrc (example: Wan2.1-T2V-14B + OpenVidHD)
export DATASET_NAME="/workspace/datasets/OpenVidHD/videos"
export DATASET_META_NAME="/workspace/datasets/OpenVidHD/metadata.csv"
export MODEL_DIR="/workspace/models/Wan2.1-T2V-14B"
# re-login or source ~/.bashrc, then launch
bash examples/wanvideo/model_training/full/Wan2.1-T2V-14B.sh

Paths stay in each developer's bashrc and never enter git. Internal CI paths and the image tag live in .ci/s5000.env (gitignored, committed only to the internal GitLab, requires git add -f).

To use your own dataset, export the variables before launching, or set them in ~/.bashrc:

export DATASET_NAME="/data/my_training_data"
export DATASET_META_NAME="/data/my_training_data/metadata.csv"
bash examples/wanvideo/model_training/full/Wan2.1-T2V-1.3B.sh

Configure model paths: scripts use the MODEL_DIR / MODEL_PATH environment variables (also settable in ~/.bashrc) as the pretrained model root, and build the --model_paths weight list from it (DiT weights + T5 text encoder + VAE), e.g. export MODEL_DIR="/path/to/models/Wan2.1-T2V-1.3B".

7.4 启动训练 / Launch Training

单机 8 卡训练(T2V)/ Single-node 8-GPU Training (T2V)

# Wan2.1-T2V-1.3B 全参数训练 / Full-parameter training
bash examples/wanvideo/model_training/full/Wan2.1-T2V-1.3B.sh

训练脚本的核心参数说明 / Key training script parameters:

参数 默认值 说明 / Description
--dataset_base_path — 数据集根目录 / Dataset root directory
--dataset_metadata_path — 元数据文件路径 / Metadata file path
--height 480 视频高度 / Video height
--width 832 视频宽度 / Video width
--num_frames 81 帧数 / Number of frames
--model_paths — 模型权重文件列表(JSON 数组)/ Model weight file list (JSON array)
--learning_rate 1e-5 学习率 / Learning rate
--num_epochs 30 训练轮数 / Number of epochs
--trainable_models dit 可训练模型 / Trainable models
--batch_size 1 每 GPU 批量大小 / Per-GPU batch size
--recompute_num_layers None 梯度检查点层数 / Gradient checkpoint layers
--gradient_accumulation_steps 4 梯度累积步数 / Gradient accumulation steps
--initialize_model_on_cpu False 在 CPU 上初始化 / Initialize on CPU
--max_timestep_boundary 1.0 最大时间步边界 / Max timestep boundary
--min_timestep_boundary 0.0 最小时间步边界 / Min timestep boundary

I2V 训练 / I2V Training

# I2V 训练需要添加 extra_inputs 参数 / I2V training requires extra_inputs parameter
bash examples/wanvideo/model_training/full/Wan2.1-I2V-14B-480P.sh

Wan2.2 双阶段训练 / Wan2.2 Two-stage Training

中文

Wan2.2-A14B 模型需要分两个阶段训练:先训练高噪声模型(timestep 0.4171.0),再训练低噪声模型(timestep 00.417):

English

Wan2.2-A14B requires two-stage training: first train the high-noise model (timestep 0.4171.0), then the low-noise model (timestep 00.417):

# 脚本内包含两个连续的 accelerate launch 命令
# Script contains two consecutive accelerate launch commands
bash examples/wanvideo/model_training/full/Wan2.2-T2V-A14B.sh

7.5 多机多卡训练 / Multi-node Multi-GPU Training

中文

训练脚本已内置多机多卡支持,通过环境变量 NNODES、NODE_RANK、MASTER_ADDR、MASTER_PORT 控制单机/多机模式,无需修改脚本内容。

使用 multi_nodes_training.sh 可一键启动多节点训练:

bash examples/wanvideo/model_training/multi_nodes_training.sh

English

Training scripts have built-in multi-node support via environment variables NNODES, NODE_RANK, MASTER_ADDR, MASTER_PORT. No script modification needed.

Use multi_nodes_training.sh to launch multi-node training with a single command:

bash examples/wanvideo/model_training/multi_nodes_training.sh

配置 multi_nodes_training.sh / Configuration

中文

打开 multi_nodes_training.sh,修改配置区:

# 指定要运行的训练脚本
SCRIPT_PATH=".../full/Wan2.1-T2V-14B.sh"

MASTER_PORT=58888
WORKDIR="<project_root>"

# 节点列表,格式: IP:SSH用户:SSH端口:容器名
# 第一行是主节点(本地执行),后续行是远程节点(通过 SSH + docker exec)
NODES=(
  "<MASTER_IP>:::"                                    # 主节点:本地容器,SSH 字段留空
  "<NODE_IP>:<ssh_user>:22:<container_name>"        # 远程节点:SSH用户:端口:容器名
)

每个字段含义:

字段 主节点示例 远程节点示例 说明
IP <MASTER_IP> <NODE_IP> 节点间可互通的 IP
SSH 用户 (留空) <ssh_user> 远程宿主机 SSH 用户名
SSH 端口 (留空) 22 远程宿主机 SSH 端口
容器名 (留空) <container_name> 远程宿主机上的容器名称

增加更多节点只需在 NODES 数组中追加一行即可。

English

Edit the configuration section in multi_nodes_training.sh:

# Training script to run
SCRIPT_PATH=".../full/Wan2.1-T2V-14B.sh"

MASTER_PORT=58888
WORKDIR="<project_root>"

# Node list, format: IP:SSH_USER:SSH_PORT:CONTAINER_NAME
# First line = primary node (local), subsequent lines = remote nodes (via SSH + docker exec)
NODES=(
  "<MASTER_IP>:::"                                    # Primary: local container, SSH fields empty
  "<NODE_IP>:<ssh_user>:22:<container_name>"        # Remote: SSH user:port:container name
)

Add more nodes by appending lines to the NODES array.

前提条件 / Prerequisites

中文

  1. 所有容器使用 --network=host 启动,容器间 IP 可互通
  2. 主节点可通过 SSH(免密)登录到远程宿主机
  3. 所有节点上的代码、数据集、模型文件路径一致
  4. multi_nodes_training.sh 在主节点容器内执行

English

  1. All containers started with --network=host, containers can reach each other by IP
  2. Primary node can SSH (passwordless) to remote hosts
  3. Code, dataset, and model paths are identical across all nodes
  4. Run multi_nodes_training.sh from the primary node container

工作原理 / How It Works

中文

  • 主节点 (RANK=0):直接在本地容器内启动训练脚本
  • 远程节点 (RANK≥1):通过 ssh → docker exec 在远程容器内启动训练脚本
  • 所有节点自动传递 NNODES(节点数)、NODE_RANK(节点编号)、MASTER_ADDR(主节点 IP)、MASTER_PORT 环境变量
  • 训练脚本根据 NNODES 自动配置 accelerate 的 --num_machines、--num_processes(= NNODES × NUM_GPUS_PER_NODE)等参数
  • FSDP2 模式下自动禁用 ce_comm(不支持 HSDP),回退到标准 MCCL
  • Ctrl+C 会自动清理所有节点的训练进程

English

  • Primary node (RANK=0): Launches training script locally
  • Remote nodes (RANK≥1): Launches via ssh → docker exec into remote containers
  • All nodes receive NNODES, NODE_RANK, MASTER_ADDR, MASTER_PORT environment variables
  • Training scripts auto-configure accelerate's --num_machines, --num_processes (= NNODES × NUM_GPUS_PER_NODE), etc.
  • In FSDP2 mode, ce_comm is automatically disabled (not HSDP-compatible), falling back to standard MCCL
  • Ctrl+C automatically cleans up training processes on all nodes

单机训练无需 multi_nodes_training.sh / Single-node Training

单机训练直接运行训练脚本即可,NNODES 默认为 1,所有多机参数自动使用默认值:

bash examples/wanvideo/model_training/full/Wan2.1-T2V-14B.sh

7.6 自定义训练脚本 / Custom Training Script

source examples/wanvideo/model_training/setup_env.sh 8
source .venv/bin/activate

accelerate launch \
  --config_file "$ACCELERATE_CONFIG" \
  --num_processes 8 \
  --mixed_precision bf16 \
  examples/wanvideo/model_training/train.py \
  --dataset_base_path /path/to/dataset \
  --dataset_metadata_path /path/to/metadata.csv \
  --height 480 --width 832 --num_frames 81 \
  --model_paths '["/path/to/model/diffusion_pytorch_model.safetensors","/path/to/model/models_t5_umt5-xxl-enc-bf16.pth","/path/to/model/Wan2.1_VAE.pth"]' \
  --learning_rate 1e-5 --num_epochs 30 \
  --trainable_models dit --save_steps 100 \
  --initialize_model_on_cpu \
  --recompute_num_layers 40 \
  --dataset_num_workers 4

许可证 / License

本项目以 BSD 3-Clause License 发布(Copyright © 2026 Moore Threads Technology Co., Ltd.),详见仓库根目录的 LICENSE 文件。项目使用的第三方依赖(DiffSynth-Studio、PyTorch、torch_musa)的版权与许可证全文,见仓库根目录的 ThirdPartyNotices.txt。

本补丁在兼容许可下对上游 DiffSynth-Studio(Apache License 2.0,Copyright 2023 Zhongjie Duan)进行导入期 monkey-patch。上游许可证已核对:Apache-2.0 与本项目 BSD-3-Clause 兼容;本仓库不打包上游源码,仅通过 pyproject.toml 声明对 diffsynth 的依赖,分发时各自遵守其许可证即可。模型权重不包含在本仓库中,用户需自行获取并遵守相应模型的许可证。

English — This project is released under the BSD 3-Clause License (Copyright © 2026 Moore Threads Technology Co., Ltd.). See the LICENSE file at the repository root. Attribution and full license texts for the third-party dependencies (DiffSynth-Studio, PyTorch, torch_musa) are provided in ThirdPartyNotices.txt at the repository root.

This patch monkey-patches upstream DiffSynth-Studio (Apache License 2.0, Copyright 2023 Zhongjie Duan) at import time under a compatible license. Upstream license compatibility has been verified: Apache-2.0 is compatible with this project's BSD-3-Clause. This repository does not bundle upstream source code; it only declares a dependency on diffsynth in pyproject.toml, so each component's license must be honored on distribution. Model weights are not included in this repository; users must obtain them separately and comply with the applicable model licenses.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages