weixin_62994174/csm-1b
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

CSM-1B Ascend NPU 适配

模型介绍

CSM-1B (Conversational Speech Model) 是由 Sesame AI Labs 开发的对话语音生成模型。该模型基于 Llama 架构,包含 1B 参数的主干网络和 100M 参数的深度解码器,通过 Mimi 音频编解码器生成高质量语音。

本仓库提供了 CSM-1B 模型在华为昇腾 Ascend 910 NPU 上的完整适配方案,包括推理脚本、精度评测和性能测试。

模型架构

组件规格
BackboneLlama-3.2-1B (16 layers, 2048 hidden, 32 heads)
Depth DecoderLlama-100M (4 layers, 1024 hidden, 8 heads)
Audio CodecMimi (Kyutai) - 32 codebooks, 12.5Hz frame rate
Text Vocab128,256
Audio Vocab2,051
Total Params~1.55B
Sample Rate24,000 Hz

环境要求

  • 硬件: 华为 Ascend 910 NPU (Atlas 300T 或同等设备)
  • 驱动: Ascend NPU Driver 25.x+
  • 框架: PyTorch 2.9.0 + torch_npu
  • CANN: Ascend-cann-toolkit 8.x+

依赖安装

# 基础依赖
pip install torch==2.9.0 torch_npu transformers>=5.0.0

# 音频处理
pip install scipy soundfile numpy

# 模型下载
pip install modelscope
modelscope download --model sesameAILabs/csm-1b

快速开始

推理示例

import torch
import torch_npu
from transformers import AutoProcessor, CsmForConditionalGeneration
import scipy.io.wavfile as wavfile
import numpy as np

# 加载模型
model_path = "/path/to/csm-1b"
processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
model = CsmForConditionalGeneration.from_pretrained(
    model_path,
    torch_dtype=torch.bfloat16,
    trust_remote_code=True,
)

# 移到 NPU
device = torch.device("npu:0")
model = model.to(device)
model.eval()

# 使用 Chat Template 构建输入
text = "Hello, this is CSM-1B running on Ascend NPU."
conversation = [{"role": "0", "content": [{"type": "text", "text": text}]}]
inputs = processor.apply_chat_template(conversation, tokenize=True, return_dict=True)
inputs = inputs.to(device)

# 生成语音
with torch.no_grad():
    output = model.generate(**inputs, max_new_tokens=512, do_sample=True, output_audio=True)

# 获取音频
audio = output[0] if isinstance(output, list) else output.audio[0]

# 保存音频
audio_np = audio.cpu().float().numpy()
wavfile.write("output.wav", 24000, np.clip(audio_np, -1, 1).astype("float32"))

命令行推理

# 基础推理
python inference.py --text "Hello from Ascend NPU" --output output.wav

# 运行所有评测
python inference.py --all

# 仅精度评测
python eval_accuracy.py

# 仅性能测试
python eval_performance.py

推理脚本说明

文件说明
inference.py主推理脚本,支持文本转语音及批量测试
eval_accuracy.py精度评测脚本,NPU vs CPU 误差分析
eval_performance.py性能评测脚本,吞吐/延迟/显存基准测试
run_all.sh一键运行完整评测流水线

推理参数

参数类型默认值说明
--textstr-要合成的文本
--speakerint0说话人 ID (0/1)
--max-tokensint1024最大生成 token 数
--temperaturefloat0.9采样温度
--top-kint50Top-K 采样
--compileflagFalse启用 torch.compile 加速
--benchmarkflagFalse运行性能基准
--accuracyflagFalse运行精度评测
--allflagFalse运行全部评测

精度评测结果

评测方法:前向传播 Logit 比较(NPU bfloat16 vs CPU float32 参考)。通过比较模型 backbone 输出的 logits 来直接衡量数值精度。

测试用例Logit 余弦相似度相对误差MAENPU/CPU 加速比结果
Short English (21 tokens)0.999979052.17%0.013086.8xPASS
Medium English (28 tokens)0.999986225.85%0.01076113.2xPASS
Chinese (24 tokens)0.9999399216.82%0.01432110.6xPASS
Average0.999968408.28%0.0127276.9xPASS
  • Logit 余弦相似度均 > 0.9999,NPU bfloat16 与 CPU float32 参考高度一致
  • 平均 MAE 仅 0.013,在 2051 维 logit 空间中误差极小
  • 平均加速 76.9x(前向传播),音频生成加速 23-46x

结论:NPU 推理精度与 CPU 参考结果高度一致(CosSim > 0.9999),满足精度要求。

性能基准测试

测试环境:Ascend 910 NPU,bfloat16 精度,模型加载耗时 34.2s,显存占用 3.32 GB

配置平均耗时RTF实时率峰值显存
short_32t (32 tokens)5.09s2.6262.6x3.38 GB
short_128t (128 tokens)4.43s2.6602.7x3.38 GB
short_256t (256 tokens)14.72s2.5882.6x3.44 GB
medium_256t (256 tokens)18.10s2.5432.5x3.46 GB
medium_512t (512 tokens)19.08s2.5542.6x3.46 GB
long_512t (512 tokens)43.40s2.5732.6x3.60 GB
  • RTF 稳定在 2.5-2.7x 实时 — 生成 1 秒音频约需 2.6 秒计算
  • 峰值显存 3.60 GB — 单卡 Ascend 910 (64 GB) 可轻松容纳

Ascend NPU 适配说明

关键修改点

  1. 设备迁移:将模型所有参数迁移到 NPU (model.to("npu:0"))
  2. 精度选择:使用 torch.bfloat16 混合精度,平衡性能与精度
  3. Mimi Codec:音频编解码器同样迁移到 NPU 运行
  4. 内存优化:配置 PYTORCH_NPU_ALLOC_CONF=expandable_segments:True

适配难点

  • Mimi codec:基于 PyTorch 纯算子实现,无 CUDA 专属代码,天然支持 NPU
  • Attention 算子:Llama 架构的 Flash Attention 可通过 torch_npu 加速
  • 多 Codebook 解码:32 层 codebook 的自回归解码适合 NPU 并行计算

已知问题

  • torch_npu.contrib.transfer_to_npu 修改 sys.path 会导致 transformers 版本冲突,需在导入 torch_npu 之前导入 transformers
  • transformers 5.8.1 与 vllm 0.18.0 存在版本约束冲突 (transformers<5),需使用 --no-deps 安装

文件结构

csm-1b/
├── inference.py              # 主推理脚本
├── eval_accuracy.py          # 精度评测脚本
├── eval_performance.py       # 性能基准测试
├── run_all.sh                # 一键评测流水线
├── README.md                 # 本文档
├── output/                   # 输出目录
│   ├── accuracy_evaluation.json
│   ├── accuracy_summary.txt
│   ├── performance_benchmark.json
│   └── performance_summary.txt
└── model/                    # 模型文件 (需下载)

引用

本模型基于 Sesame AI Labs 的 CSM-1B 模型:

@misc{sesame2025csm,
  title={CSM-1B: A Conversational Speech Generation Model},
  author={Sesame AI Labs},
  year={2025},
  publisher={HuggingFace},
  howpublished={\url{https://huggingface.co/sesame/csm-1b}},
}

许可证

本仓库代码基于 Apache 2.0 许可证。CSM-1B 模型权重遵循原始 Sesame AI 的许可协议。