本文档记录在 Ascend 910B NPU 服务器上部署 MOSS-Audio-4B-Instruct 模型的完整流程,从环境检查、模型下载、代码适配到推理验证,全部覆盖。
| 项目 | 要求 |
|---|---|
| NPU | Ascend 910B 系列(910B1/910B2/910B2C) |
| HBM | 单卡 >= 32GB(4B 模型 bfloat16 约需 10GB) |
| 组件 | 版本 | 说明 |
|---|---|---|
| CANN | 9.1.0 | Ascend 驱动 + toolkit |
| Python | 3.12 | |
| torch | 2.10.0+cpu | NPU 版,CPU 后端 |
| torch_npu | 2.10.0.post4 | NPU 适配层 |
| transformers | 5.14.1 | vllm-ascend 强制要求此版本 |
| vllm | 0.28.0 | 含原生 moss_audio 支持 |
| vllm-ascend | 对应版本 | NPU 插件 |
| soundfile | >= 0.12 | 音频加载 |
| scipy | >= 1.12 | 音频重采样 |
| modelscope | >= 1.0 | 模型下载(国内推荐) |
MOSS-Audio 官方代码基于 transformers==4.57.1 编写。但在同一环境中 vllm-ascend 强制要求 transformers==5.14.1,两者不可共存。因此:
moss_audio.py,已兼容 5.14.1,无需任何代码修改。src/modeling_moss_audio.py,需要适配 5.14.1 的 API 变化(见第 6 节)。部署完成后,工作目录结构如下:
moss-audio/
├── DEPLOY_GUIDE.md # 本文件
├── infer.py # HuggingFace NPU 推理脚本
├── infer_vllm.sh # vLLM-Ascend 服务器启动脚本
├── test_vllm_client.py # vLLM 客户端测试脚本
├── vllm_server.log # vLLM 服务器日志(运行时生成)
└── MOSS-Audio/ # 官方仓库 + 权重
├── src/
│ ├── __init__.py
│ ├── audio_io.py # 已修改: soundfile 替代 torchaudio
│ ├── modeling_moss_audio.py # 已修改: NPU + transformers 5.x 适配
│ ├── processing_moss_audio.py # 未修改
│ ├── configuration_moss_audio.py # 未修改
│ └── hf_inference.py # 未修改
├── test/
│ ├── test_zh.mp3 # 中文测试音频
│ ├── test_en.mp3 # 英文测试音频
│ └── test_kr.mp3 # 韩文测试音频
├── weights/
│ └── MOSS-Audio-4B-Instruct/ # 模型权重 (~10.4GB)
│ ├── config.json
│ ├── generation_config.json
│ ├── processor_config.json
│ ├── chat_template.jinja
│ ├── tokenizer_config.json
│ ├── vocab.json
│ ├── merges.txt
│ ├── special_tokens_map.json
│ ├── added_tokens.json
│ ├── model.safetensors.index.json
│ ├── model-00001-of-00003.safetensors (~4.7GB)
│ ├── model-00002-of-00003.safetensors (~4.4GB)
│ └── model-00003-of-00003.safetensors (~0.7GB)
├── infer.py # 官方原始推理脚本(参考)
├── app.py # Gradio 应用
├── pyproject.toml
└── README.mdnpu-smi info预期输出类似:
+------------------------------------------------------------------------------------------------+
| NPU Name | Health | Power(W) Temp(C) Hugepages-Usage(page)|
| Chip | Bus-Id | AICore(%) Memory-Usage(MB) HBM-Usage(MB) |
+===========================+===============+====================================================+
| 2 910B2C | OK | 93.8 54 0 / 0 |
| 0 | 0000:49:00.0 | 0 0 / 0 3407 / 65536 |
+===========================+===============+====================================================+
| ...
+===========================+===============+====================================================+# 检查 torch + torch_npu
python -c "import torch; import torch_npu; print('torch:', torch.__version__); print('npu available:', torch.npu.is_available()); print('npu count:', torch.npu.device_count())"
# 检查 transformers
python -c "import transformers; print('transformers:', transformers.__version__)"
# 检查 vllm + vllm_ascend
python -c "import vllm; print('vllm:', vllm.__version__)"
python -c "import vllm_ascend; print('vllm_ascend OK')"
# 检查音频处理库
python -c "import soundfile; print('soundfile OK')"
python -c "import scipy; print('scipy OK')"
# 检查 CANN 环境
echo "ASCEND_HOME_PATH: $ASCEND_HOME_PATH"
echo "SOC_VERSION: $SOC_VERSION"确保以下环境变量已设置(通常 CANN 安装时自动配置):
export ASCEND_HOME_PATH=/usr/local/Ascend/cann-9.1.0
export ASCEND_TOOLKIT_HOME=/usr/local/Ascend/cann-9.1.0
export ASCEND_OPP_PATH=/usr/local/Ascend/cann-9.1.0/opp
export SOC_VERSION=ascend910b1
export LD_LIBRARY_PATH=/usr/local/Ascend/cann-9.1.0/lib64:$LD_LIBRARY_PATH
export PYTHONPATH=/usr/local/Ascend/cann-9.1.0/python/site-packages:$PYTHONPATH# 安装 modelscope(如果尚未安装)
pip install modelscope
# 下载 MOSS-Audio-4B-Instruct
modelscope download \
--model openmoss/MOSS-Audio-4B-Instruct \
--local_dir MOSS-Audio/weights/MOSS-Audio-4B-Instruct下载完成后验证:
ls -la MOSS-Audio/weights/MOSS-Audio-4B-Instruct/*.safetensors
# 应看到 3 个文件:
# model-00001-of-00003.safetensors (~4.7GB)
# model-00002-of-00003.safetensors (~4.4GB)
# model-00003-of-00003.safetensors (~0.7GB)
du -sh MOSS-Audio/weights/MOSS-Audio-4B-Instruct/
# 应为 ~14GB(含缓存)# 设置镜像
export HF_ENDPOINT=https://hf-mirror.com
# 下载
hf download OpenMOSS-Team/MOSS-Audio-4B-Instruct \
--local-dir MOSS-Audio/weights/MOSS-Audio-4B-Instruct# 4B-Thinking
modelscope download --model openmoss/MOSS-Audio-4B-Thinking --local_dir MOSS-Audio/weights/MOSS-Audio-4B-Thinking
# 8B-Instruct
modelscope download --model openmoss/MOSS-Audio-8B-Instruct --local_dir MOSS-Audio/weights/MOSS-Audio-8B-Instruct
# 8B-Thinking
modelscope download --model openmoss/MOSS-Audio-8B-Thinking --local_dir MOSS-Audio/weights/MOSS-Audio-8B-Thinkinggit clone https://github.com/OpenMOSS/MOSS-Audio.git MOSS-Audiocd MOSS-Audio
pip install -e ".[torch-runtime]" --no-deps注意:用
--no-deps是因为pyproject.toml里的 torch 依赖指向 CUDA 版本,NPU 环境已有 torch_npu,不需要重复安装。
pip list | grep -E "safetensors|soundfile|tiktoken|einops|scipy|accelerate"预期输出包含:
accelerate 1.12.0
einops 0.8.2
safetensors 0.8.0
scipy 1.13.1
soundfile 0.14.0
tiktoken 0.14.0如果缺少 soundfile 或 scipy:
pip install soundfile scipy重要:以下修改仅影响
infer.py(HuggingFace 直接推理)。infer_vllm.sh(vLLM 推理)使用 vLLM 自带的模型实现,完全不受这些修改影响。
需要修改 2 个文件,共 4 处改动。每处改动的根本原因都是 transformers==5.14.1 与官方代码(为 4.57.1 编写)的 API 不兼容。
MOSS-Audio/src/audio_io.py原始代码使用 torchaudio.load() 加载音频,但 torchaudio 2.10 需要 torchcodec 模块(NPU 环境下编译困难):
ImportError: TorchCodec is required for load_with_torchcodec.from __future__ import annotations
import numpy as np
import soundfile as sf
from scipy.signal import resample_poly
def load_audio(path: str, sample_rate: int):
data, original_sample_rate = sf.read(path, dtype="float32")
if data.ndim == 2:
data = data.mean(axis=1)
if original_sample_rate != sample_rate:
from math import gcd
g = gcd(int(original_sample_rate), int(sample_rate))
up = int(sample_rate) // g
down = int(original_sample_rate) // g
data = resample_poly(data, up, down).astype(np.float32)
return dataMOSS-Audio/src/modeling_moss_audio.py此文件需要 3 处修改。
原因:transformers 5.x 中 WhisperEncoderLayer.forward() 签名和 attention mask 维度处理发生变化,导致:
RuntimeError: The size of tensor a (50) must match the size of tensor b (20) at non-singleton dimension 1操作:将文件顶部的导入和类定义部分,从:
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model, Qwen3DecoderLayer
from transformers.models.whisper.modeling_whisper import WhisperEncoderLayer
from src.configuration_moss_audio import MossAudioEncoderConfig, MossAudioConfig替换为:
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model, Qwen3DecoderLayer
from src.configuration_moss_audio import MossAudioEncoderConfig, MossAudioConfig
class WhisperAttention(nn.Module):
"""Multi-head attention compatible with Whisper weight names."""
def __init__(self, embed_dim: int, num_heads: int, dropout: float = 0.0):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
if self.head_dim * self.num_heads != embed_dim:
raise ValueError(
f"embed_dim {embed_dim} must be divisible by num_heads {num_heads}"
)
self.scaling = self.head_dim ** -0.5
self.dropout = dropout
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=False)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=True)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=True)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
B, T, _ = hidden_states.shape
q = self.q_proj(hidden_states).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(hidden_states).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(hidden_states).view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
attn_output = F.scaled_dot_product_attention(
q, k, v,
attn_mask=attention_mask if attention_mask is not None else None,
dropout_p=0.0,
scale=self.scaling,
)
attn_output = attn_output.transpose(1, 2).contiguous().reshape(B, T, -1)
return self.out_proj(attn_output)
class WhisperEncoderLayer(nn.Module):
"""Custom encoder layer matching Whisper weight names, transformers-version-agnostic."""
def __init__(self, config):
super().__init__()
self.embed_dim = config.d_model
self.self_attn = WhisperAttention(
self.embed_dim,
config.encoder_attention_heads,
dropout=config.attention_dropout,
)
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.dropout = config.dropout
self.activation_fn = nn.GELU()
self.activation_dropout = config.activation_dropout
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim, bias=True)
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim, bias=True)
self.final_layer_norm = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask=None,
output_attentions: bool = False,
):
residual = hidden_states
hidden_states = self.self_attn_layer_norm(hidden_states)
hidden_states = self.self_attn(hidden_states, attention_mask)
hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.final_layer_norm(hidden_states)
hidden_states = self.activation_fn(self.fc1(hidden_states))
hidden_states = F.dropout(hidden_states, p=self.activation_dropout, training=self.training)
hidden_states = self.fc2(hidden_states)
hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
hidden_states = residual + hidden_states
return (hidden_states,)自定义类的权重名(
self_attn.q_proj,self_attn.k_proj,self_attn.v_proj,self_attn.out_proj,self_attn_layer_norm,fc1,fc2,final_layer_norm)与原始 Whisper encoder 完全一致,所以权重加载无缺失。使用F.scaled_dot_product_attention,NPU 上有优化实现。
forward() 方法中 audio_input_mask 形状对齐原因:transformers 5.x 的 generate() 会在 input_ids 前附加 BOS token,导致 audio_input_mask 的序列长度比 inputs_embeds 少 1,报错:
RuntimeError: The expanded size of the tensor (79) must match the existing size (78) at non-singleton dimension 1.操作:在 forward() 方法中,audio_input_mask 使用之前(audio_token_count 计算之前),插入形状对齐逻辑:
hook_handles = []
if audio_data is not None:
if audio_input_mask is None:
raise ValueError("audio_input_mask is required when audio_data is provided.")
audio_embeds, deepstack = self.get_audio_features(audio_data, audio_data_seqlens)
audio_embeds = self.audio_adapter(audio_embeds)
if audio_input_mask.shape[1] != inputs_embeds.shape[1]:
diff = inputs_embeds.shape[1] - audio_input_mask.shape[1]
if diff > 0:
pad = torch.zeros(
(audio_input_mask.shape[0], diff),
dtype=audio_input_mask.dtype, device=audio_input_mask.device,
)
audio_input_mask = torch.cat([pad, audio_input_mask], dim=1)
else:
audio_input_mask = audio_input_mask[:, :inputs_embeds.shape[1]]
audio_token_count = int(audio_input_mask.to(torch.int32).sum().item())
if audio_token_count != int(audio_embeds.shape[1]):
raise ValueError(
f"Audio token count mismatch: audio_input_mask has {audio_token_count} audio tokens, "
f"but audio_embeds has length {int(audio_embeds.shape[1])}."
)
mask_expanded = audio_input_mask.unsqueeze(-1).expand_as(inputs_embeds)
inputs_embeds = inputs_embeds.clone()
inputs_embeds.masked_scatter_(mask_expanded, audio_embeds)
# ... 后续 deepstack 代码不变 ...forward() 中调用 Qwen3Model 的参数简化原因:transformers 5.x 的 Qwen3Model.forward() 签名变为 (input_ids, attention_mask, position_ids, past_key_values, inputs_embeds, use_cache, **kwargs),不再接受 output_attentions、output_hidden_states、return_dict、cache_position 等显式参数。传入这些参数会通过 **kwargs 被转发给 decoder layer,引发冲突,导致 KV cache 模式下输出乱码。
操作:将 forward() 中调用 self.language_model() 的部分,从:
try:
outputs = self.language_model(
input_ids=None,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
**kwargs,
)替换为:
try:
outputs = self.language_model(
input_ids=None,
attention_mask=attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
)同时移除了
position_ids,让 Qwen3Model 内部自动从past_key_values计算位置编码。
prepare_inputs_for_generation() 修复 KV cache 判断原因(最关键的修改):transformers 5.x 的 generate() 不再向 prepare_inputs_for_generation() 传递有效的 cache_position 参数(值为 None)。原始代码依赖 cache_position[0] > 0 来判断是否处于解码阶段(需要截断 input_ids 到最后一个 token),导致每次都传完整 input_ids,KV cache 完全失效,输出乱码(如 "ToToTo")。
操作:将 prepare_inputs_for_generation() 方法替换为:
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
**kwargs,
):
position_ids = kwargs.get("position_ids", None)
has_cached = (
past_key_values is not None
and hasattr(past_key_values, "get_seq_length")
and past_key_values.get_seq_length() > 0
)
if has_cached or (cache_position is not None and cache_position[0] > 0):
input_ids = input_ids[:, -1:]
if position_ids is not None:
position_ids = position_ids[:, -1:]
audio_data = None
audio_input_mask = None
audio_data_seqlens = None
else:
audio_data = kwargs.get("audio_data", None)
audio_input_mask = kwargs.get("audio_input_mask", None)
audio_data_seqlens = kwargs.get("audio_data_seqlens", None)
if inputs_embeds is not None and not has_cached:
model_inputs = {"inputs_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
model_inputs.update(
{
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": attention_mask,
"audio_data": audio_data,
"audio_input_mask": audio_input_mask,
"audio_data_seqlens": audio_data_seqlens,
}
)
return model_inputs核心变化:用
past_key_values.get_seq_length() > 0替代cache_position[0] > 0来判断是否在解码阶段;同时移除了position_ids和cache_position从返回的model_inputs中(让 Qwen3Model 内部处理)。
infer.py在工作目录下创建 infer.py:
"""MOSS-Audio HuggingFace inference on Ascend NPU.
Usage:
python infer.py
python infer.py --model_path weights/MOSS-Audio-4B-Instruct --audio_path MOSS-Audio/test/test_zh.mp3
python infer.py --prompt "Please transcribe this audio." --audio_path MOSS-Audio/test/test_en.mp3
"""
import argparse
import os
import time
os.environ["HF_TRUST_REMOTE_CODE"] = "1"
os.environ["TRANSFORMERS_TRUST_REMOTE_CODE"] = "1"
import torch
import torch_npu # noqa: F401 must be imported before torch is used on NPU
from src.audio_io import load_audio
from src.modeling_moss_audio import MossAudioModel
from src.processing_moss_audio import MossAudioProcessor
def parse_args():
p = argparse.ArgumentParser(description="MOSS-Audio NPU inference (HuggingFace)")
here = os.path.dirname(os.path.abspath(__file__))
p.add_argument(
"--model_path",
default=os.path.join(here, "MOSS-Audio", "weights", "MOSS-Audio-4B-Instruct"),
)
p.add_argument(
"--audio_path",
default=os.path.join(here, "MOSS-Audio", "test", "test_zh.mp3"),
)
p.add_argument("--prompt", default="Describe this audio.")
p.add_argument("--max_new_tokens", type=int, default=1024)
p.add_argument("--temperature", type=float, default=1.0)
p.add_argument("--top_p", type=float, default=1.0)
p.add_argument("--top_k", type=int, default=50)
p.add_argument("--device_id", type=int, default=0)
return p.parse_args()
def resolve_device(device_id: int) -> str:
if torch.npu.is_available():
return f"npu:{device_id}"
if torch.cuda.is_available():
return f"cuda:{device_id}"
if torch.backends.mps.is_available():
return "mps"
return "cpu"
def main():
args = parse_args()
device = resolve_device(args.device_id)
print(f"[INFO] Using device: {device}")
print(f"[INFO] Loading model from {args.model_path} ...")
t0 = time.time()
model = MossAudioModel.from_pretrained(
args.model_path,
trust_remote_code=True,
dtype="auto",
device_map=device,
)
model.eval()
print(f"[INFO] Model loaded in {time.time() - t0:.1f}s")
processor = MossAudioProcessor.from_pretrained(
args.model_path,
trust_remote_code=True,
enable_time_marker=True,
)
print(f"[INFO] Loading audio from {args.audio_path} ...")
raw_audio = load_audio(args.audio_path, sample_rate=processor.config.mel_sr)
prompt = args.prompt
print(f"[INFO] Prompt: {prompt}")
inputs = processor(text=prompt, audios=[raw_audio], return_tensors="pt")
inputs = inputs.to(model.device)
if inputs.get("audio_data") is not None:
inputs["audio_data"] = inputs["audio_data"].to(model.dtype)
audio_input_mask = inputs["input_ids"] == processor.audio_token_id
inputs["audio_input_mask"] = audio_input_mask
print(f"[INFO] Input ids shape: {inputs['input_ids'].shape}")
print("[INFO] Generating ...")
t1 = time.time()
with torch.no_grad():
generated_ids = model.generate(
**inputs,
max_new_tokens=args.max_new_tokens,
do_sample=False,
num_beams=1,
use_cache=True,
)
elapsed = time.time() - t1
print(f"[INFO] Generation done in {elapsed:.1f}s")
input_len = inputs["input_ids"].shape[1]
output_ids = generated_ids[0, input_len:]
num_out = output_ids.shape[0]
transcription = processor.decode(output_ids, skip_special_tokens=True)
print("=" * 60)
print("OUTPUT:")
print("=" * 60)
print(transcription)
print("=" * 60)
print(f"[INFO] Output tokens: {num_out}, throughput: {num_out / elapsed:.1f} tok/s")
if __name__ == "__main__":
main()# 指定 NPU 卡号(通过 ASCEND_VISIBLE_DEVICES)
# 注意:ASCEND_VISIBLE_DEVICES 映射后,卡内编号从 0 开始
# 例如 ASCEND_VISIBLE_DEVICES=4 表示物理卡 4,对应 npu:0
# 中文音频转写
ASCEND_VISIBLE_DEVICES=4 python infer.py --prompt "Please transcribe this audio."
# 英文音频描述
ASCEND_VISIBLE_DEVICES=4 python infer.py \
--audio_path MOSS-Audio/test/test_en.mp3 \
--prompt "Describe this audio."
# 韩文音频描述
ASCEND_VISIBLE_DEVICES=4 python infer.py \
--audio_path MOSS-Audio/test/test_kr.mp3 \
--prompt "Describe this audio."
# 指定模型路径和输出长度
ASCEND_VISIBLE_DEVICES=9 python infer.py \
--model_path MOSS-Audio/weights/MOSS-Audio-4B-Instruct \
--audio_path MOSS-Audio/test/test_zh.mp3 \
--prompt "Please transcribe this audio." \
--max_new_tokens 512| 设计点 | 说明 |
|---|---|
os.environ["HF_TRUST_REMOTE_CODE"] = "1" | 避免 trust_remote_code 交互提示 |
import torch_npu | 必须在 import torch 之后、使用 NPU 之前导入 |
resolve_device() | 自动检测 NPU > CUDA > MPS > CPU |
dtype="auto" | 模型用 bfloat16(NPU 原生支持) |
do_sample=False | 贪心解码,结果可复现 |
vLLM 使用其自带的 moss_audio.py(位于 /vllm-workspace/vllm/vllm/model_executor/models/moss_audio.py),已原生支持 transformers 5.x,不需要上述代码修改。
infer_vllm.sh在工作目录下创建 infer_vllm.sh:
#!/bin/bash
# MOSS-Audio vLLM-Ascend NPU inference server startup script
#
# Usage:
# bash infer_vllm.sh # Start server on NPU 4
# bash infer_vllm.sh 9 # Start server on NPU 9
# bash infer_vllm.sh 4 8001 # Start server on NPU 4, port 8001
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODEL_PATH="${SCRIPT_DIR}/MOSS-Audio/weights/MOSS-Audio-4B-Instruct"
DEVICE_ID="${1:-4}"
PORT="${2:-8000}"
export ASCEND_VISIBLE_DEVICES="${DEVICE_ID}"
export VLLM_USE_V1=1
echo "[INFO] Starting vLLM server for MOSS-Audio on NPU ${DEVICE_ID}, port ${PORT}"
echo "[INFO] Model path: ${MODEL_PATH}"
vllm serve "${MODEL_PATH}" \
--trust-remote-code \
--dtype bfloat16 \
--max-model-len 4096 \
--limit-mm-per-prompt '{"audio": 1}' \
--port "${PORT}" \
--enforce-eager \
--served-model-name moss-audio \
--allowed-local-media-path "${SCRIPT_DIR}"启动参数说明:
| 参数 | 说明 |
|---|---|
--trust-remote-code | 加载自定义模型代码 |
--dtype bfloat16 | NPU 原生支持的精度 |
--max-model-len 4096 | 最大序列长度 |
--limit-mm-per-prompt '{"audio": 1}' | 每个请求最多 1 个音频输入 |
--enforce-eager | 禁用 CUDA graph,NPU 兼容 |
--served-model-name moss-audio | 客户端用简短名称引用模型 |
--allowed-local-media-path | 允许服务器读取本地音频文件 |
chmod +x infer_vllm.sh
# 后台启动(NPU 卡 4,端口 8000)
bash infer_vllm.sh 4 8000 > vllm_server.log 2>&1 &
# 等待启动完成(约 30-60 秒)
# 观察日志直到出现 "Application startup complete"
tail -f vllm_server.log看到以下日志表示启动成功:
INFO: Application startup complete.test_vllm_client.py"""Test MOSS-Audio vLLM server with sample audio.
Prerequisites:
- Start the server first: bash infer_vllm.sh
- Wait for "Application startup complete" in the server log
Usage:
python test_vllm_client.py
python test_vllm_client.py --audio_path MOSS-Audio/test/test_en.mp3
"""
import argparse
import os
import time
import requests
def parse_args():
here = os.path.dirname(os.path.abspath(__file__))
p = argparse.ArgumentParser(description="Test MOSS-Audio vLLM server")
p.add_argument("--server_url", default="http://localhost:8000")
p.add_argument(
"--audio_path",
default=os.path.join(here, "MOSS-Audio", "test", "test_zh.mp3"),
)
p.add_argument("--prompt", default="Please transcribe this audio.")
return p.parse_args()
def main():
args = parse_args()
audio_abs = os.path.abspath(args.audio_path)
print(f"[INFO] Server: {args.server_url}")
print(f"[INFO] Audio: {audio_abs}")
print(f"[INFO] Prompt: {args.prompt}")
payload = {
"model": "moss-audio",
"messages": [
{
"role": "user",
"content": [
{
"type": "audio_url",
"audio_url": {"url": f"file://{audio_abs}"},
},
{
"type": "text",
"text": args.prompt,
},
],
}
],
"max_tokens": 1024,
"temperature": 0.0,
}
print("[INFO] Sending request ...")
t0 = time.time()
resp = requests.post(
f"{args.server_url}/v1/chat/completions",
json=payload,
timeout=300,
)
elapsed = time.time() - t0
if resp.status_code != 200:
print(f"[ERROR] HTTP {resp.status_code}: {resp.text[:500]}")
return
data = resp.json()
content = data["choices"][0]["message"]["content"]
usage = data.get("usage", {})
print("=" * 60)
print("OUTPUT:")
print("=" * 60)
print(content)
print("=" * 60)
print(f"[INFO] Time: {elapsed:.1f}s, prompt_tokens: {usage.get('prompt_tokens', '?')}, "
f"completion_tokens: {usage.get('completion_tokens', '?')}")
if __name__ == "__main__":
main()# 中文音频转写
python test_vllm_client.py
# 英文音频转写
python test_vllm_client.py \
--audio_path MOSS-Audio/test/test_en.mp3 \
--prompt "Please transcribe this audio."
# 韩文音频描述
python test_vllm_client.py \
--audio_path MOSS-Audio/test/test_kr.mp3 \
--prompt "Describe this audio."# 方法一:找到进程并 kill
pkill -f "vllm serve"
# 方法二:释放端口
fuser -k 8000/tcp$ ASCEND_VISIBLE_DEVICES=4 python infer.py --prompt "Please transcribe this audio."| 音频 | Prompt | 输出 | 耗时 | 吞吐 |
|---|---|---|---|---|
| test_zh.mp3 | Transcribe | 遇到我们的时候你才是挑战者。 | 0.7s | 14.0 tok/s |
| test_en.mp3 | Transcribe | I just fucking destroyed them. | 0.6s | 12.1 tok/s |
| test_kr.mp3 | Describe | (详细描述韩语男声 + 管弦乐背景,256 tokens) | 5.7s | 44.6 tok/s |
$ bash infer_vllm.sh 4 8000
$ python test_vllm_client.py| 音频 | Prompt | 输出 | 耗时 |
|---|---|---|---|
| test_zh.mp3 | Transcribe | 遇到我们的时候,你才是挑战者。哇哦。 | 2.9s |
| test_en.mp3 | Transcribe | I just fucking destroy them. | 0.3s |
| test_kr.mp3 | Describe | (详细描述韩语男声 + 管弦乐背景,381 tokens) | 9.3s |
| 维度 | HuggingFace (infer.py) | vLLM-Ascend (infer_vllm.sh) |
|---|---|---|
| 代码来源 | MOSS-Audio/src/modeling_moss_audio.py | vllm/.../moss_audio.py(vLLM 自带) |
| 需要代码修改 | 是(4 处,适配 transformers 5.x) | 否 |
| 推理精度 | bfloat16 | bfloat16 |
| 推理结果 | 正确 | 正确 |
| KV cache | 支持(修复后) | 支持(原生) |
| 连续批处理 | 不支持 | 支持 |
| OpenAI API | 不支持 | 支持 (/v1/chat/completions) |
| 多卡并行 | 不支持 | 支持(--tensor-parallel-size) |
| 启动复杂度 | 直接运行 | 需启动服务器 + 等待初始化 |
| 适用场景 | 单次推理、调试、研究 | 生产服务、高吞吐 |
ImportError: TorchCodec is required for load_with_torchcodec.原因:torchaudio 2.10 需要 torchcodec 模块。
解决:已用 soundfile 替代,见 6.1 修改 audio_io.py。
RuntimeError: The size of tensor a (50) must match the size of tensor b (20) at non-singleton dimension 1原因:transformers 5.x 的 WhisperEncoderLayer.forward() attention mask 处理变化。
解决:用自定义 WhisperEncoderLayer 替代,见 6.2 修改 A。
RuntimeError: The expanded size of the tensor (79) must match the existing size (78) at non-singleton dimension 1.原因:transformers 5.x 的 generate() 在 input_ids 前加 BOS。
解决:自动补零对齐,见 6.2 修改 B。
Output: ToToTo (而不是正常的推理输出)原因:transformers 5.x 不再传 cache_position,导致 prepare_inputs_for_generation 无法判断解码阶段。
解决:用 past_key_values.get_seq_length() > 0 判断,见 6.2 修改 D。
OSError: [Errno 98] Address already in use解决:
fuser -k 8000/tcp
# 或换端口
bash infer_vllm.sh 4 8001Cannot load local files without `--allowed-local-media-path`.解决:infer_vllm.sh 中已添加 --allowed-local-media-path 参数。
{"error":{"message":"The model `default` does not exist."}}解决:客户端请求中 "model" 字段必须与 --served-model-name 一致(默认为 moss-audio)。
--device npu 报错ValueError: Non-integer device ID 'npu' is not supported by npu.原因:--device 参数不需要手动指定,vllm-ascend 插件会自动识别 NPU。
解决:不要传 --device npu,从启动脚本中移除即可。
RuntimeError: NPU out of memory.解决:
npu-smi info 确认 HBM 占用情况如果尝试降级 transformers:
vllm-ascend 0.0.0 requires transformers==5.14.1, but you have transformers 4.57.1 which is incompatible.说明:vllm-ascend 强制要求 5.14.1,不能降级。HuggingFace 推理路径的代码修改就是为了在这个版本约束下工作。如果只需要 HuggingFace 推理(不需要 vLLM),可以在独立的 conda 环境中安装 4.57.1,则无需任何代码修改。
# 0. 进入工作目录
cd /path/to/moss-audio
# 1. 克隆仓库
git clone https://github.com/OpenMOSS/MOSS-Audio.git MOSS-Audio
# 2. 下载模型权重(ModelScope)
modelscope download --model openmoss/MOSS-Audio-4B-Instruct --local_dir MOSS-Audio/weights/MOSS-Audio-4B-Instruct
# 3. 安装项目依赖
pip install -e "MOSS-Audio/.[torch-runtime]" --no-deps
pip install soundfile scipy
# 4. 修改代码(仅 HF 推理需要,见第 6 节)
# - MOSS-Audio/src/audio_io.py
# - MOSS-Audio/src/modeling_moss_audio.py
# 5a. HuggingFace 推理
ASCEND_VISIBLE_DEVICES=4 python infer.py
# 5b. vLLM 推理
bash infer_vllm.sh 4 8000
# 等待启动后,另一个终端:
python test_vllm_client.py