Bug_Factory_w/whisper-bemba-stt
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

whisper-bemba-stt 昇腾 NPU 迁移与服务化推理指南

whisper-bemba-stt — 基于 Whisper-small(OpenAI Whisper 架构,约 244M 参数) 在 Bemba 语(赞比亚主要语言)语音数据上微调得到的语音转写(ASR)模型。 本项目将其从通用 PyTorch 环境迁移到华为昇腾 Ascend910 NPU,并基于 FastAPI 提供服务化推理(HTTP 接口)。

项目内容
模型whisper-bemba-stt(WhisperForConditionalGeneration,whisper-small 尺寸)
输入任意采样率单声道音频(自动重采样到 16kHz),路径或 base64 WAV
输出转写文本(JSON),含生成 token 数与延迟统计
硬件Ascend910(本环境 16 卡,部署使用 npu:0)
软件CANN 8.5.1 / Python 3.11 / PyTorch 2.9.0 / torch_npu 2.9.0.post1 / transformers 5.9.0
推理服务FastAPI + uvicorn(HTTP 服务化推理)
测试结果5/5 用例通过,4.4s 语音转写延迟约 226ms

1. 目录结构

whisper-bemba-stt-npu/
├── inference.py              # 服务化推理脚本(FastAPI HTTP 服务)★ 核心交付
├── test_inference.py         # 测试用例(5 项,HTTP 模式)
├── requirements.txt          # 运行环境依赖清单
├── README.md                 # 本文档
├── test_results/
│   └── test_result.txt       # 测试结果记录
└── assets/
    ├── test_speech.wav       # 测试音频(4.4s 英语语音)
    ├── silence_2s.wav        # 静音对照音频(2s 全零)
    ├── npu_device_call.png   # 截图1:NPU 设备调用
    ├── model_result.png      # 截图2:模型测试结果
    ├── agent_workflow.png    # 截图3:适配过程工作流
    └── _make_screenshots.py  # 截图生成脚本(可复现)

2. 环境要求

依赖版本说明
操作系统openEuler / Ubuntu(aarch64)本机 openEuler 2203 SP4
昇腾硬件Ascend910(≥1 卡)bf16 权重约 2.5GB
CANN≥ 8.0(本机 8.5.1)/usr/local/Ascend/ascend-toolkit/set_env.sh
Python3.11—
PyTorch2.9.0与 torch_npu 版本配套
torch_npu2.9.0.post1昇腾 NPU 运行时插件

3. 环境准备

# 1) 加载 CANN 环境
source /usr/local/Ascend/ascend-toolkit/set_env.sh

# 2) 指定可见 NPU 卡
export ASCEND_RT_VISIBLE_DEVICES=0

# 3) 安装依赖(华为镜像源)
export PIP_INDEX_URL=https://repo.huaweicloud.com/repository/pypi/simple/
pip install -r requirements.txt

# 4) 校验 NPU 环境
npu-smi info
python -c "import torch, torch_npu; a=torch.randn(3,4).npu(); print(a+a)"

4. 模型迁移适配说明

4.1 模型架构

Whisper 为标准的 encoder-decoder transformer(纯 PyTorch 算子,无需 CUDA 内核改写):

音频 (16kHz) → Log-Mel 特征 (80 bins) → 12层 Encoder → 12层 Decoder → 文本

4.2 自动迁移注入(inference.py 顶部)

import torch_npu
from torch_npu.contrib import transfer_to_npu

transfer_to_npu 自动完成 CUDA API → NPU API 的映射。

4.3 关键适配点(本次迁移实际遇到的问题与修复)

#适配点说明
1bf16 权重 + bf16 输入权重 torch_dtype=torch.bfloat16,输入 mel 特征也必须转 bf16,否则 Conv1d 报 Input type (float) and bias type (c10::BFloat16)
2采样率重采样Whisper 固定 16kHz 输入,非 16kHz 音频用 torchaudio.functional.resample 转换(否则 feature extractor 直接报错)
3语言 tokenWhisper 语言列表无 Bemba(ValueError: Unsupported language: bem),该微调模型以 <|en|> token 训练,生成时固定 language="en"
4use_cache加载后设置 model.config.use_cache = True(transformers 5.x 不接受 from_pretrained 的 use_cache 参数)
5静音幻觉静音输入可能输出幻听词(如 "you"),属 Whisper 已知行为,测试用例按短输出判定

本项目不涉及 CUDA 自定义算子、DP/DDP 分布式改造、flash_attn 等三方 CUDA 库。

5. 服务化推理(inference.py)

5.1 启动服务

source /usr/local/Ascend/ascend-toolkit/set_env.sh
export ASCEND_RT_VISIBLE_DEVICES=0

python inference.py \
  --model-path /mnt/old_data/whl/models/3/AbelZimba/whisper-bemba-stt \
  --host 0.0.0.0 --port 8004

启动日志:

[inference] Loading model (bf16) -> npu:0 ...
[inference] Model loaded in 0.5s, device=npu:0
INFO:     Uvicorn running on http://0.0.0.0:8004

5.2 接口文档

方法路径说明
GET/health健康检查,返回设备/模型/精度信息
POST/infer语音转写(audio 为路径或 base64 WAV)
POST/v1/audio/transcriptionsOpenAI 风格接口

请求参数:

{
  "audio": "/path/to/audio.wav 或 data:audio/wav;base64,xxxx",
  "language": "en",
  "max_new_tokens": 224,
  "max_seconds": 120.0
}

5.3 调用示例

健康检查:

curl -s http://127.0.0.1:8004/health
# {"status":"ok","model":"whisper-bemba-stt","architecture":"WhisperForConditionalGeneration (small)","device":"npu:0","dtype":"torch.bfloat16"}

语音转写(Python 客户端):

import base64, requests

with open("assets/test_speech.wav", "rb") as f:
    b64 = "data:audio/wav;base64," + base64.b64encode(f.read()).decode()

r = requests.post("http://127.0.0.1:8004/infer", json={"audio": b64})
print(r.json())

返回示例:

{
  "text": "Hello, this is the Chatterbox Speech Synthesis System running on Ascend and Pew.",
  "language": "en",
  "generated_tokens": 21,
  "duration_s": 4.4,
  "latency_ms": 225.94
}

6. 测试用例

python test_inference.py --url http://127.0.0.1:8004

用例覆盖:

用例内容结果
T1健康检查 /health,确认 device=npu:0✅ PASS
T2语音转写(4.4s 英语语音)→ 输出包含关键词 "Chatterbox"✅ PASS
T3静音输入 → 输出为空或非常短✅ PASS
T4重复调用 3 次结果一致(稳定性)✅ PASS
T5OpenAI 风格接口 /v1/audio/transcriptions✅ PASS

完整测试结果见 test_results/test_result.txt,汇总:5 通过 / 0 失败。

7. 交付截图

截图文件说明
NPU 设备调用assets/npu_device_call.pngnpu-smi info + torch_npu 探针 + 部署摘要
测试结果assets/model_result.png转写文本 + 延迟柱状图(RTF 0.05)+ 测试日志
适配过程assets/agent_workflow.png迁移适配工作流(10 步 playbook)

截图可通过 python assets/_make_screenshots.py 重新生成(需服务运行中)。

8. 常见问题(FAQ)

问题原因解决方案
Input type (float) and bias type (c10::BFloat16) should be the same输入 mel 特征为 fp32 而权重 bf16inputs.input_features.to(device, dtype=torch.bfloat16)
ValueError: ... sampled with 16000 and not 24000输入采样率非 16kHz服务已自动 torchaudio 重采样
ValueError: Unsupported language: bemWhisper 语言列表无 Bemba使用 language="en"(微调模型以 en token 训练)
静音输入输出幻听词Whisper 已知行为(hallucination)属正常现象,按输出长度判定
No module named 'decorator'torch_npu 运行时依赖缺失pip install decorator
端口被占用环境预装服务占用端口换用空闲端口(如 8004)

9. 参考

  • 模型主页:https://huggingface.co/AbelZimba/whisper-bemba-stt
  • Whisper 论文:Radford et al., 2022(Robust Speech Recognition via Large-Scale Weak Supervision)
  • transformers Whisper 文档:https://huggingface.co/docs/transformers/model_doc/whisper
  • 迁移 Skill:ai4s-basic(ascend-model-agent-plugin)