K
KevinLi11/voxtral-mini-4b-realtime
Model Introduction
Files & versions
Pull Requests
Discussion
Analysis

Voxtral-Mini-4B-Realtime-2602 在 Ascend NPU 上的适配与精度对比

1. 模型简介

Voxtral-Mini-4B-Realtime-2602 是 Mistral AI 推出的多语种实时语音转写 (Realtime ASR) 音频大模型。它由一个 ~970M 的因果音频编码器与一个 3.4B 的 Mistral 语言模型组成,支持 13 种语言,可配置 80ms2400ms 的转写延迟,官方推荐在 480ms 延迟档位取得精度 / 时延的均衡。

  • 模型类型: causal audio encoder + LLM (audio-LLM)
  • 权重格式: bf16
  • 原生推理后端: vLLM;transformers 自 5.2.0 起原生支持 (VoxtralRealtimeForConditionalGeneration)
  • License: Apache-2.0

本目录产出的是将 Voxtral-Mini-4B-Realtime-2602 通过 transformers 推理栈运行在华为 Ascend 910 NPU 上的端到端适配, 并与 CPU bf16 baseline 做精度 / 速度对比。

2. 部署步骤

2.1 环境要求

项目版本
Python3.11.14
torch2.9.0+cpu
torch_npu2.9.0.post1 (CANN 8.5.1)
transformers5.15.0
mistral-common1.11.7 (含 audio 依赖)
numpy / accelerate任意近版本

2.2 安装依赖

export PIP_INDEX_URL=https://repo.huaweicloud.com/repository/pypi/simple/
pip install -r requirements.txt

说明: transformers==4.57.6 不包含 VoxtralRealtime 实现 (官方 README 已注明 Voxtral Realtime 自 5.2.0 起才有 transformers 原生支持), 因此升级到 5.15.0。

2.3 准备权重

将 Mistral 官方权重 (model.safetensors + tekken.json + config.json + processor_config.json + params.json) 放到 /data/dl/voxtral/。

2.4 跑 NPU / CPU 推理

# NPU
python3 inference.py --device npu --runs 3 --max_new_tokens 32
# CPU
python3 inference.py --device cpu --runs 3 --max_new_tokens 32

两条命令同输入同 seed,会各自产出:

  • {device}_output.txt — 模型简介 + transcription + 耗时 + 显存峰值
  • {device}_run.log — 推理完整 stdout 日志
  • {device}_meta.json — 供 compare.py 使用的结构化结果
  • {device}_logits.pt — 单次前向 logits (1, 99, 131072)

2.5 跑 NPU vs CPU 精度对比

python3 compare.py
# 产物: assets/compare_result.txt

3. 推理示例

import numpy as np, torch, torch_npu
from transformers import AutoProcessor, VoxtralRealtimeForConditionalGeneration

torch_npu.npu.set_device(0)
processor = AutoProcessor.from_pretrained("/data/dl/voxtral", trust_remote_code=True)
model = VoxtralRealtimeForConditionalGeneration.from_pretrained(
    "/data/dl/voxtral", torch_dtype=torch.bfloat16, trust_remote_code=True
).to("npu").eval()

# 16kHz 单声道音频
sr = 16000
audio = np.random.default_rng(42).standard_normal(sr * 4).astype(np.float32)
inputs = processor(audio, sampling_rate=sr, return_tensors="pt")

# 关键修复: transformers 5.15.x 的 VoxtralRealtimeModel.forward 用 inputs_embeds += audio_embeds,
# 因此必须把 input_ids 的长度对齐到 audio_tower 输出的嵌入数 (n=99), 否则广播会失败.
with torch.no_grad():
    n = model.get_audio_features(
        input_features=inputs["input_features"].to("npu", dtype=torch.bfloat16)
    ).pooler_output.shape[1]
input_ids = torch.full((1, n), 32, dtype=torch.long, device="npu")
input_ids[:, 0] = 1
attn = torch.ones((1, n), dtype=torch.long, device="npu")

# 绕过 generate 的 max_length 校验 (transformers 5.15.x bug, 在 5.16+ 可能修复)
from transformers.generation.utils import GenerationMixin
GenerationMixin._validate_generated_length = staticmethod(lambda *a, **k: None)

with torch.no_grad():
    out = model.generate(
        input_ids=input_ids,
        attention_mask=attn,
        input_features=inputs["input_features"].to("npu", dtype=torch.bfloat16),
        num_delay_tokens=inputs["num_delay_tokens"],
        max_new_tokens=32, do_sample=False, num_beams=1,
    )
print(processor.batch_decode(out[:, n:], skip_special_tokens=True))

4. 实测 6 指标对比 (NPU vs CPU)

测试环境: 合成 4.0s 单声道 16kHz WAV (440/880 Hz sin + 噪声 + AM 调制) | seed=42 | bf16 | generate 3 次取均值 注: 合成音频不含真实语音, NPU/CPU 输出一致为空串, 这符合预期, 验证的是数值一致性而非转写质量。

指标NPUCPU对比
cos_sim (logits flatten)--0.999986
max_abs (logits 元素级最大绝对差)--1.250000
mean_abs (logits 元素级平均绝对差)--0.111991
text_match (输出一致率)''''1.000000
edit_dist (Levenshtein 编辑距离)--0
time_ratio (NPU mean / CPU mean, <1 表示 NPU 更快)0.090 s36.240 s0.002478
显存峰值8.47 GB (NPU)10.65 GB RSS (CPU)-

详细数值与原始记录见 assets/compare_result.txt。

5. 已知适配点

  • transformers 5.15.x 中 VoxtralRealtimeModel.forward 使用 inputs_embeds += audio_embeds, 要求 input_ids 长度等于 audio_tower 输出嵌入数 (本模型 = 99), 而 VoxtralRealtimeProcessor.__call__ 默认只生成 39 个 token (1 BOS + 38 STREAMING_PAD) —— 需在调用方手动补齐 99 个 STREAMING_PAD。
  • transformers 5.15.x 的 generate 在同时传入 input_features 时, _prepare_generated_length 会把 generation_config.max_length 重置为 inputs_tensor.shape[1], 进而触发 input_ids_length >= max_length 校验报错 —— 本仓库在 inference.py 中 monkey-patch _validate_generated_length 跳过该校验。
  • 显存与速度: NPU bf16 单卡推理显存 8.47 GB, generate 时延 ~0.09 s (32 tokens); CPU bf16 generate 时延 ~36 s, 显存约 10.65 GB RSS。