Open-source speech recognition toolkit for training, inference, streaming ASR, VAD, punctuation, speaker diarization pipelines, and OpenAI-compatible/MCP serving.
Python asraudiochineseemotion-recognitionfunasrmcp-servermultilingual-asropenai-compatible-apiparaformerpunctuationpytorchreal-time-asrspeaker-diarizationspeech-recognitionspeech-to-textstreaming-asrtranscriptionvllmvoice-activity-detectionwhisper-alternative
docs: consolidate vLLM docs into single guide
xiaoyunchong.xycc02734f184b5
diff --git a/docs/vllm_guide.md b/docs/vllm_guide.mdindex c17081c0b..4967a4039 100644--- a/docs/vllm_guide.md+++ b/docs/vllm_guide.md@@ -1,10 +1,23 @@-# FunASR vLLM Inference Guide+# FunASR vLLM 推理引擎指南-本文档介绍如何使用 vLLM 加速 FunASR 中 LLM-based ASR 模型的推理。+FunASR 集成 vLLM 高吞吐推理引擎,用于加速 LLM-based ASR 模型的自回归解码。支持离线批量推理、SDK 流式推理、生产级 WebSocket 实时服务三种模式。-## 概览+----vLLM 是一个高吞吐量 LLM 推理引擎,支持 PagedAttention、Tensor Parallelism 等优化。FunASR 集成 vLLM 用于加速 LLM 解码部分,实现 **2-3x** 推理加速。+## 目录++1. [概述](#1-概述)+2. [安装与环境](#2-安装与环境)+3. [离线批量推理](#3-离线批量推理)+4. [流式 SDK 推理](#4-流式-sdk-推理)+5. [实时 WebSocket 服务](#5-实时-websocket-服务)+6. [性能对比](#6-性能对比)+7. [API 参考](#7-api-参考)+8. [FAQ](#8-faq)++---++## 1. 概述### 适用模型@@ -17,340 +30,485 @@ vLLM 是一个高吞吐量 LLM 推理引擎,支持 PagedAttention、Tensor Par| Paraformer | ✗ | 非自回归模型(CIF predictor),无 LLM 解码 || SenseVoice | ✗ | Whisper-like encoder-decoder,非 LLM || Conformer/Transformer | ✗ | CTC/attention 解码,非 LLM |-| Qwen3-ASR | ✗ | 使用外部 qwen-asr 包自带优化 |-### 为什么 Paraformer 不能用 vLLM?+### 架构++```+┌────────────────────────────────────────────────────────┐+│ FunASR + vLLM │+├────────────────────────────────────────────────────────┤+│ │+│ Audio ──→ Frontend ──→ Audio Encoder ──→ Adaptor │+│ (fbank) (SenseVoice) (Transformer) │+│ │ │+│ ▼ │+│ Audio Embeddings │+│ │ │+│ Text Prompt ──→ Tokenize ──→ Embed ──→ [Concat] │+│ (hotwords/language/itn) │ │+│ ▼ │+│ ┌──────────────┐ │+│ │ vLLM Engine │ │+│ │ (Qwen3 etc) │ │+│ │ TP 并行加速 │ │+│ └──────┬───────┘ │+│ ▼ │+│ Generated Text │+│ │+│ (可选) CTC Forced Alignment ──→ 字级别时间戳 │+└────────────────────────────────────────────────────────┘+```++### 三种使用模式++| 模式 | 入口 | 适用场景 |+|------|------|---------|+| [离线批量推理](#3-离线批量推理) | `AutoModelVLLM` / `FunASRNanoVLLM` | 大规模转写、批量处理 |+| [流式 SDK 推理](#4-流式-sdk-推理) | `FunASRNanoStreamingVLLM` | 实时字幕展示(SDK 集成) |+| [WebSocket 实时服务](#5-实时-websocket-服务) | `serve_realtime_ws.py` | 生产部署、多端接入 |-Paraformer 使用 CIF (Continuous Integrate-and-Fire) predictor 实现**非自回归**并行解码。所有 token 同时生成,不需要 KV-cache。vLLM 的优化(PagedAttention、KV-cache 管理)只对**自回归** LLM 有效。+----## 安装+## 2. 安装与环境++### 依赖```bashpip install funasr>=1.3.0-pip install vllm>=0.11.0-pip install safetensors tiktoken+pip install vllm>=0.12.0+pip install safetensors tiktoken websockets regex++# FunASR 开发模式安装(需要 auto_model_vllm)+cd /path/to/FunASR && pip install -e .```-## 快速开始+### 硬件要求-### 通用接口 (AutoModelVLLM)+| 配置 | 最低要求 | 推荐 |+|------|---------|------|+| GPU 显存 | 8GB | 16GB+ |+| CUDA | 11.8 | 12.0+ |+| GPU 数量 | 1 | 2+(tensor parallel) |++---++## 3. 离线批量推理++适用于大规模音频转写、离线批量处理。vLLM 的批处理能力在此场景优势最大。++### 通用接口(推荐)```pythonfrom funasr.auto.auto_model_vllm import AutoModelVLLM-# 自动检测模型类型,使用 vLLM 加速model = AutoModelVLLM(model="FunAudioLLM/Fun-ASR-Nano-2512",- hub="ms",- tensor_parallel_size=2, # 2卡并行+ hub="ms", # 或 "hf"+ tensor_parallel_size=2, # 多卡并行gpu_memory_utilization=0.8,)-results = model.generate(["audio.wav"], language="中文")-print(results[0]["text"])+results = model.generate(+ ["audio1.wav", "audio2.wav"],+ language="中文",+ hotwords=["张三", "北京"],+)+for r in results:+ print(f"[{r['key']}] {r['text']}")```-### 离线批量推理 (FunASRNanoVLLM)+### 直接接口```pythonfrom funasr.models.fun_asr_nano.inference_vllm import FunASRNanoVLLMengine = FunASRNanoVLLM.from_pretrained(model="FunAudioLLM/Fun-ASR-Nano-2512",- tensor_parallel_size=4, # 4卡并行+ tensor_parallel_size=4,)-# 批量处理results = engine.generate(- inputs=["audio1.wav", "audio2.wav", "audio3.wav"],+ inputs="wav.scp", # 支持 scp/jsonl/文件列表hotwords=["开放时间"],language="中文",+ max_new_tokens=512,)-for r in results:- print(f"[{r['key']}] {r['text']}")- if "timestamps" in r:- print(f" timestamps: {r['timestamps'][:3]}")```-### 流式推理 (FunASRNanoStreamingVLLM)+### 命令行++```bash+cd examples/industrial_data_pretraining/fun_asr_nano++# 单文件+python demo_vllm.py --input audio.wav --language 中文++# 批量 + 多卡+python demo_vllm.py --input wav.scp --tensor-parallel-size 4 --batch-size 32++# 带热词 + 保存结果+python demo_vllm.py --input audio.wav --hotwords 张三 北京 --output results.jsonl+```++---++## 4. 流式 SDK 推理++将音频按 720ms chunk 逐步处理,输出逐步稳定的识别结果。适用于 SDK 集成实时字幕场景。++### 设计原理++```+音频流(720ms chunks)+ │ 累积重编码(每个 chunk 包含从头到当前的全部音频)+ ▼+┌──────────────────────┐+│ Stage 1: 前 10 chunk │ ← 无 prev_text,批量生成+│ 找到稳定输出 │+└──────────┬───────────┘+ ▼+┌──────────────────────┐+│ Stage 2: 后续 chunk │ ← 用稳定输出作 prev_text+└──────────┬───────────┘+ ▼+每个 chunk: [fixed 区域(确认)] + [8字 unfixed(可能变)]+```++### 用法```pythonfrom funasr.models.fun_asr_nano.inference_vllm_streaming import FunASRNanoStreamingVLLMengine = FunASRNanoStreamingVLLM.from_pretrained(model="FunAudioLLM/Fun-ASR-Nano-2512",- chunk_ms=720, # 每720ms一个chunk- rollback_chars=8, # 回退8个字符+ chunk_ms=720,+ rollback_chars=8,)for result in engine.streaming_generate("audio.wav", language="中文"):if result["is_final"]:- print(f"最终结果: {result['text']}")+ print(f"最终: {result['text']}")else:- print(f"[{result['audio_duration_ms']:.0f}ms] {result['text']}")- print(f" 确认区: {result['fixed_text']}")+ print(f"[{result['audio_duration_ms']:.0f}ms] 确认: {result['fixed_text']}")```-## 命令行 Demo+### 输出特性-```bash-cd examples/industrial_data_pretraining/fun_asr_nano+| 累积音频 | 输出质量 |+|---------|---------|+| < 1.5s | 空或噪声 |+| 1.5-3.0s | 部分正确 |+| > 3.0s | 准确输出 |-# 单卡推理-python demo_vllm.py --input audio.wav --language 中文+> Note: `repetition_penalty=1.3` 内部硬编码,防止短 chunk 重复退化。-# 多卡并行 + 批量-python demo_vllm.py --input wav.scp --tensor-parallel-size 4 --batch-size 32+----# 带热词-python demo_vllm.py --input audio.wav --hotwords 开放时间 周一 --language 中文-```+## 5. 实时 WebSocket 服务++生产级实时语音识别服务,集成 VAD 分句 + vLLM 推理 + 说话人分离 + 热词。++### 推理逻辑-## 架构说明+**核心设计:基于 VAD 端点逐段解码(非固定 chunk)**```-┌───────────────────────────────────────────────────────────┐-│ FunASR + vLLM │-├───────────────────────────────────────────────────────────┤-│ │-│ Audio ──→ Frontend ──→ Audio Encoder ──→ Audio Adaptor │-│ (fbank) (SenseVoice/ (Linear/ │-│ Whisper) Transformer) │-│ │ │-│ ▼ │-│ Audio Embeddings │-│ │ │-│ Text Prompt ──→ Tokenize ──→ Embed ──→ [Concat] │-│ (system/user/ │ │-│ assistant) ▼ │-│ ┌─────────────┐ │-│ │ vLLM │ │-│ │ (Qwen3/etc) │ │-│ │ TP并行加速 │ │-│ └──────┬──────┘ │-│ ▼ │-│ Generated Text │-│ │-│ (可选) CTC Forced Alignment ──→ 字级别时间戳 │-│ │-└───────────────────────────────────────────────────────────┘+音频流 ──→ StreamingVAD (60ms) ──→ 检测到端点 ──→ vLLM 解码整段+ │ │+ │ ▼+ │ locked_sentences(锁定)+ │ │+ │ ▼+ │ SPK assign(说话人分配)+ │+ └──→ 未结束 ──→ vLLM partial decode(每0.48s)+ │+ ▼+ partial text(预览,会覆盖)```-### 流式推理设计+**两条推理路径:**-```-音频流(每720ms一个chunk)- │- ▼ 累计音频重新编码-┌──────────────────────┐-│ Stage 1: 前10个chunk │ ← 批量生成,无 prev_text-│ 找到稳定输出 │-└──────────┬───────────┘- ▼-┌──────────────────────┐-│ Stage 2: 后续chunk │ ← 用稳定输出作为 prev_text prefill-│ 带 prev_text 生成 │-└──────────┬───────────┘- ▼-每个 chunk 输出: [fixed 区域] + [8字 unfixed 区域]- (不会变) (可能在下一chunk改变)+| 路径 | 触发条件 | 输出 |+|------|---------|------|+| 确认段解码 | VAD 检测到静音端点 | 锁定到 sentences,永不改变 |+| Partial 预览 | 每 0.48s + 新音频 ≥ 960ms | 临时文字,随时覆盖 |++**动态 VAD 阈值:**++| 累积时长 | 静音阈值 | 效果 |+|---------|---------|------|+| ≤ 5s | 2.0s | 短句不切碎 |+| 5-10s | 1.5s | 正常分句 |+| 10-15s | 1.0s | 开始收紧 |+| 15-30s | 0.8s | 较快切分 |+| 30-45s | 0.4s | 防止过长 |+| > 45s | 0.1s | 强制切分 |++**STOP 最终处理:**+1. 剩余音频喂给 VAD(is_final=True)+2. 强制结束当前在说话的段+3. 全局 SPK 重聚类(修正说话人 ID)+4. 返回 `is_final: true`++### 部署++```bash+cd examples/industrial_data_pretraining/fun_asr_nano++# 单卡+CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py --port 10095 --language 中文++# 多卡+CUDA_VISIBLE_DEVICES=0,1 python serve_realtime_ws.py \+ --port 10095 --tensor-parallel-size 2 --language 中文++# 完整参数+python serve_realtime_ws.py \+ --port 10095 \+ --model FunAudioLLM/Fun-ASR-Nano-2512 \+ --hub ms \+ --device cuda:0 \+ --decode-interval 0.48 \+ --hotword-file 热词列表 \+ --language 中文 \+ --dtype bf16 \+ --tensor-parallel-size 1 \+ --gpu-memory-utilization 0.8 \+ --max-model-len 2048```-## 性能对比+### 客户端-### 离线推理(5.6s 中文音频)+| 客户端 | 用法 |+|--------|------|+| 浏览器 | 打开 `client_mic.html`(麦克风/文件/热词/说话人) |+| Python CLI | `python client_python.py --server ws://localhost:10095 --mic` |+| 测试脚本 | `python client_test.py --server ws://localhost:10095 --file audio.wav` |-| 配置 | 延迟 | 相对加速 |-|------|------|----------|-| Torch (baseline) | 0.89s | 1x |-| vLLM 1-GPU | 0.30s | **3.0x** |-| vLLM 2-GPU TP | ~0.20s | **4.5x** |+远程访问需 SSH 端口转发:`ssh -L 10095:localhost:10095 <server>`-### 流式推理(17s 中文音频,25 chunks)+### WebSocket 协议-| 配置 | 总时间 | 加速 |-|------|--------|------|-| Torch sequential | 5.1s | 1x |-| vLLM batch | 2.8s | **1.8x** |+**客户端 → 服务端:**-### 批量推理吞吐+| 消息 | 格式 | 说明 |+|------|------|------|+| 开始会话 | `"START"` | 初始化 session |+| 设置热词 | `"HOTWORDS:词1,词2"` | 可选 |+| 设置语种 | `"LANGUAGE:中文"` | 可选 |+| 音频数据 | `bytes` | PCM16, 16kHz, mono |+| 结束会话 | `"STOP"` | 触发最终解码 |-| Batch Size | 1-GPU | 2-GPU | 4-GPU |-|-----------|-------|-------|-------|-| 1 | ~1.5x | ~2x | ~2.5x |-| 16 | ~4x | ~7x | ~12x |-| 32 | ~5x | ~9x | ~15x |+**服务端 → 客户端:**-## API 参考+```json+// 事件+{"event": "started"}+{"event": "hotwords_set", "hotwords": ["词1", "词2"]}+{"event": "language_set", "language": "中文"}+{"event": "stopped"}-### `AutoModelVLLM(model, ...)`+// 实时结果+{+ "sentences": [{"text": "已确认", "start": 1700, "end": 5500, "spk": 0}],+ "partial": "正在说...",+ "partial_start_ms": 5800,+ "duration_ms": 7200,+ "is_final": false+}-通用入口,自动检测模型类型。+// 最终结果+{+ "sentences": [{"text": "...", "start": ..., "end": ..., "spk": ...}, ...],+ "partial": "",+ "partial_start_ms": 0,+ "duration_ms": 10000,+ "is_final": true+}+```-| 参数 | 默认值 | 说明 |-|------|--------|------|-| `model` | - | 模型名或本地路径 |-| `hub` | `"ms"` | `"ms"` (ModelScope) 或 `"hf"` (HuggingFace) |-| `tensor_parallel_size` | `1` | GPU 并行数 |-| `gpu_memory_utilization` | `0.8` | vLLM KV-cache 显存比例 |-| `max_model_len` | `4096` | 最大序列长度 |-| `dtype` | `"bf16"` | 计算精度 |+**交互时序:**-### `engine.generate(inputs, ...)`+```+Client Server+ │── "START" ─────────────────→│+ │←─ {"event":"started"} ──────│+ │── "HOTWORDS:张三,北京" ────→│+ │←─ {"event":"hotwords_set"} ─│+ │── "LANGUAGE:中文" ─────────→│+ │←─ {"event":"language_set"} ─│+ │── [audio bytes] ───────────→│+ │←─ {sentences,partial} ──────│ (实时推送)+ │── [audio bytes] ───────────→│+ │←─ {sentences,partial} ──────│+ │── "STOP" ──────────────────→│+ │←─ {sentences,is_final:true} │ (最终结果)+ │←─ {"event":"stopped"} ──────│+```-| 参数 | 说明 |-|------|------|-| `inputs` | 音频路径列表、numpy array、torch Tensor |-| `language` | 语言提示:"中文"、"英文"、"日文" 等 |-| `hotwords` | 热词列表,提升识别准确率 |-| `itn` | 逆文本正则化(默认 True) |-| `max_new_tokens` | 最大生成 token 数(默认 512) |+### 热词文件-**返回**: `[{"key": str, "text": str, "timestamps": [...]}]`+默认文件名 `热词列表`(`--hotword-file` 指定),一行一个词:-### `streaming_engine.streaming_generate(audio, ...)`+```+张三+李四+北京大学+```-| 参数 | 说明 |-|------|------|-| `audio_input` | 音频路径或数据 |-| `chunk_ms` | chunk 大小(默认 720ms) |-| `rollback_chars` | 回退字符数(默认 8) |+也可通过 WebSocket 动态设置:`HOTWORDS:词1,词2,词3`-**Yields**: `{"text", "fixed_text", "is_final", "chunk_idx", "audio_duration_ms"}`+----## 常见问题+## 6. 性能对比-### Q: 为什么前几个 chunk 输出为空?-模型需要约 3 秒音频才能产生有意义的输出,这是模型本身的特性。+### 离线推理-### Q: CUDA OOM 怎么办?-- 减小 `gpu_memory_utilization`(如 0.6)-- 增加 `tensor_parallel_size`-- 减小 `max_model_len`+| 配置 | 5.6s 音频延迟 | 相对加速 |+|------|-------------|---------|+| PyTorch (baseline) | 0.89s | 1x |+| vLLM 1-GPU | 0.30s | **3x** |+| vLLM 2-GPU TP | ~0.20s | **4.5x** |-### Q: 流式和离线结果略有不同?-正常现象。流式每个 chunk 独立生成,离线看到完整音频。最终 chunk 的结果与离线基本一致。+### 批量吞吐-### Q: 支持哪些音频格式?-wav、mp3、flac 等主流格式,采样率会自动转为 16kHz。+| Batch Size | 1-GPU | 2-GPU | 4-GPU |+|-----------|-------|-------|-------|+| 1 | ~1.5x | ~2x | ~2.5x |+| 16 | ~4x | ~7x | ~12x |+| 32 | ~5x | ~9x | ~15x |-## VAD + ASR(vLLM) + Speaker Pipeline+### WebSocket 实时服务-对于长音频(会议、电话录音等),使用 VAD + Speaker 组合流水线:+| 指标 | 数值 |+|------|------|+| RTF | < 0.08 |+| 首字延迟 | ~480ms |+| 30s 音频总耗时 | ~2.3s |+| 并发 | 多 WebSocket 连接 |-### 用法+### VAD + vLLM Pipeline-```python-from funasr.models.fun_asr_nano.inference_vllm_pipeline import FunASRNanoVLLMPipeline+| 场景 | PyTorch 串行 | vLLM 批量 | 加速 |+|------|-------------|-----------|------|+| 10 段 x 5s | ~9s | ~1.5s | **6x** |+| 20 段 x 5s | ~18s | ~2.5s | **7x** |-pipeline = FunASRNanoVLLMPipeline(- model="FunAudioLLM/Fun-ASR-Nano-2512",- vad_model="fsmn-vad",- vad_kwargs={"max_single_segment_time": 30000},- spk_model="cam++", # 说话人分离,可选- tensor_parallel_size=2,-)+----results = pipeline.generate("meeting.wav", language="中文")-print(results[0]["text"]) # 完整文本-print(results[0]["sentence_info"]) # 带说话人标签的分句结果-```+## 7. API 参考-### 输出格式+### AutoModelVLLM```python-{- "key": "meeting",- "text": "开放时间早上九点至下午五点。开放时间早上九点至下午五点。",- "timestamp": [...], # 字级别时间戳(CTC forced alignment)- "sentence_info": [- {"text": "开放时间早上九点至下午五点。", "start": 420, "end": 5450, "spk": 0},- {"text": "开放时间早上九点至下午五点。", "start": 6340, "end": 11360, "spk": 0},- ...- ]-}+from funasr.auto.auto_model_vllm import AutoModelVLLM```-### Pipeline 参数+通用入口,自动检测模型类型并选择对应的 vLLM 实现。| 参数 | 默认值 | 说明 ||------|--------|------|-| `model` | `"FunAudioLLM/Fun-ASR-Nano-2512"` | ASR 模型 |-| `vad_model` | `None` | VAD 模型,如 `"fsmn-vad"` |-| `vad_kwargs` | `{}` | VAD 配置,如 `{"max_single_segment_time": 30000}` |-| `spk_model` | `None` | 说话人模型,如 `"cam++"` |+| `model` | - | 模型名(hub)或本地路径 |+| `hub` | `"ms"` | `"ms"` / `"hf"` |+| `device` | `"cuda:0"` | 音频编码器设备 |+| `dtype` | `"bf16"` | 精度 || `tensor_parallel_size` | `1` | vLLM GPU 并行数 |-| `gpu_memory_utilization` | `0.8` | vLLM 显存比例 |+| `gpu_memory_utilization` | `0.8` | KV Cache 显存比例 |+| `max_model_len` | `4096` | 最大序列长度 |-### 支持的 Speaker 模型+### AutoModelVLLM.generate()-| 模型 | ModelScope ID | 说明 |-|------|--------------|------|-| cam++ | `iic/speech_campplus_sv_zh-cn_16k-common` | 推荐,轻量高效 |-| ERes2NetV2 | `iic/speech_eres2netv2_sv_zh-cn_16k-common` | 更高精度 |+| 参数 | 默认值 | 说明 |+|------|--------|------|+| `inputs` | - | 音频路径/列表/numpy/tensor |+| `language` | `None` | 语种提示 |+| `hotwords` | `None` | 热词列表 |+| `itn` | `True` | 逆文本正则化 |+| `max_new_tokens` | `512` | 最大生成 token |+| `temperature` | `0.0` | 采样温度 |+| `repetition_penalty` | `1.0` | 重复惩罚 |-### 性能优势+**返回**: `[{"key": str, "text": str, "timestamps": [...]}]`-Pipeline 的核心加速在于:VAD 产生 N 个语音段后,vLLM **一次性** 批量处理所有段(而非逐段串行)。+### FunASRNanoStreamingVLLM.from_pretrained()-| 场景 | Torch (串行) | vLLM (批量) | 加速 |-|------|-------------|-------------|------|-| 10段 x 5s | ~9s | ~1.5s | **6x** |-| 20段 x 5s | ~18s | ~2.5s | **7x** |-| VAD 分段越多,vLLM 批量优势越大 |+| 参数 | 默认值 | 说明 |+|------|--------|------|+| `model` | `"FunAudioLLM/Fun-ASR-Nano-2512"` | 模型名或路径 |+| `hub` | `"ms"` | 模型来源 |+| `device` | `"cuda:0"` | 设备 |+| `dtype` | `"bf16"` | 精度 |+| `tensor_parallel_size` | `1` | GPU 并行数 |+| `gpu_memory_utilization` | `0.8` | 显存比例 |+| `max_model_len` | `2048` | 序列长度 |+| `chunk_ms` | `720` | chunk 时长 |+| `rollback_chars` | `8` | 回退字符数 |+### streaming_generate()-## 实时 WebSocket 服务(Streaming Server)+| 参数 | 默认值 | 说明 |+|------|--------|------|+| `audio_input` | - | 音频路径/数据 |+| `chunk_ms` | `720` | chunk 大小 |+| `rollback_chars` | `8` | 回退字符 |+| `hotwords` | `None` | 热词 |+| `language` | `None` | 语种 |+| `max_new_tokens` | `200` | 每 chunk 最大 token |+| `temperature` | `0.0` | 采样温度 |-除了离线批量和流式推理,FunASR 还提供基于 vLLM 的**实时 WebSocket ASR 服务**,支持麦克风/文件实时识别、VAD 分句、说话人分离、热词定制。+**Yields**: `{"text", "fixed_text", "is_final", "chunk_idx", "audio_duration_ms"}`-### 启动服务+> `repetition_penalty=1.3` 内部硬编码。-```bash-cd examples/industrial_data_pretraining/fun_asr_nano+### serve_realtime_ws.py 参数-# 单卡-CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py --port 10095 --language 中文+| 参数 | 默认值 | 说明 |+|------|--------|------|+| `--port` | `10095` | WebSocket 端口 |+| `--model` | `FunAudioLLM/Fun-ASR-Nano-2512` | 模型 |+| `--hub` | `ms` | 来源 |+| `--device` | `cuda:0` | 设备 |+| `--decode-interval` | `0.48` | partial 解码间隔(秒) |+| `--hotword-file` | `热词列表` | 热词文件 |+| `--language` | `None` | 语种 |+| `--dtype` | `bf16` | 精度 |+| `--tensor-parallel-size` | `1` | GPU 并行 |+| `--gpu-memory-utilization` | `0.8` | 显存比例 |+| `--max-model-len` | `2048` | 序列长度 |-# 多卡 tensor parallel-CUDA_VISIBLE_DEVICES=0,1 python serve_realtime_ws.py \- --port 10095 \- --tensor-parallel-size 2 \- --language 中文 \- --hotword-file 热词列表-```+----### 客户端+## 8. FAQ-- **浏览器**:`client_mic.html`(麦克风/文件上传/热词/说话人显示)-- **Python CLI**:`client_python.py --server ws://localhost:10095 --mic`-- **测试脚本**:`client_test.py --server ws://localhost:10095 --file audio.wav`+### Q: 首次启动为什么慢?+vLLM 需要初始化 KV Cache 和 CUDA Graph warmup,约 60-90 秒。后续推理即时响应。-### WebSocket 协议+### Q: CUDA OOM 怎么办?+- 减小 `gpu_memory_utilization`(如 0.6)+- 增加 `tensor_parallel_size` 分摊到多卡+- 减小 `max_model_len`-```-Client → Server:- "START" 开始会话- "HOTWORDS:词1,词2" 设置热词(可选)- "LANGUAGE:中文" 设置语种(可选)- bytes PCM16 16kHz 单声道音频- "STOP" 结束会话--Server → Client:- {"event": "started"}- {"event": "hotwords_set", "hotwords": [...]}- {"event": "language_set", "language": "..."}- {"sentences": [...], "partial": "...", "is_final": false} 实时结果- {"sentences": [...], "partial": "", "is_final": true} 最终结果- {"event": "stopped"}-```+### Q: Paraformer 能用 vLLM 吗?+不能。Paraformer 是非自回归模型(CIF predictor),所有 token 并行生成,不使用 KV-cache。vLLM 只加速自回归 LLM 解码。-### 性能+### Q: WebSocket 服务和 streaming_generate 有什么区别?-| 指标 | 数值 |-|------|------|-| RTF | < 0.08(30s 音频 2.3s 完成) |-| 首字延迟 | ~480ms(first chunk) |-| 并发 | 支持多 WebSocket 连接 |+| | WebSocket 服务 | streaming_generate |+|---|---|---|+| 分句 | VAD 自然端点 | 固定 720ms chunk |+| 推理 | 每个 VAD 段整体解码 | 累积重编码全部音频 |+| 准确率 | 更高 | 前 3s 较低 |+| 场景 | 生产部署 | SDK 集成 |++### Q: 流式推理前几秒输出为空?+正常。模型需要 ~3 秒累积音频才能产生有意义输出,这是模型特性而非 vLLM 限制。++### Q: 支持哪些音频格式?+wav、mp3、flac 等主流格式,采样率自动转为 16kHz。++### Q: 浏览器无法使用麦克风?+Chrome 要求 HTTPS 或 localhost。远程服务器用 SSH 端口转发:`ssh -L 10095:localhost:10095 <server>`-详细文档参见:[`examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md`](../examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md)+### Q: 多个并发连接会互相影响吗?+不会。每个 WebSocket 连接有独立的 session(VAD/ASR 状态隔离)。vLLM 内部会自动调度。diff --git a/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md b/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.mdindex 44b477ffb..53d4e90bf 100644--- a/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md+++ b/examples/industrial_data_pretraining/fun_asr_nano/docs/realtime_demo.md@@ -1,342 +1,63 @@-# Fun-ASR-Nano 流式语音识别服务(Streaming ASR + vLLM)+# Fun-ASR-Nano 实时 WebSocket 服务 — 快速上手-基于 WebSocket 的实时流式语音识别服务,使用 **vLLM 推理引擎**加速 LLM 解码。支持 VAD 分句、说话人分离(Beta)、热词定制化、语种指定。+> 完整文档请参见:[FunASR vLLM 推理引擎指南](../../../../docs/vllm_guide.md)-## 功能特性--| 功能 | 说明 |-|------|------|-| 流式 ASR (vLLM) | 基于 Fun-ASR-Nano + **vLLM 推理引擎**(PagedAttention, 连续批处理),RTF < 0.1 |-| 流式 VAD | fsmn-vad 增量检测语音端点,动态调整静音阈值 |-| 说话人分离 (Beta) | eres2netv2 + ClusterBackend,流式分配+最终重聚类 |-| 热词定制化 | 加载人名、地名等实体词列表,提升专有名词识别准确率 |-| 幻觉检测 | 自动检测重复模式并截断,防止模型生成循环 |-| 多语言 | 31种语言、7大方言、26种地方口音 |--## 架构--```-客户端(浏览器/Python) 服务端(GPU)-┌─────────────────┐ WebSocket ┌──────────────────────────┐-│ │ PCM16 16kHz │ serve_realtime_ws.py │-│ client_mic.html │ ────────────→ │ │-│ client_python.py│ │ ┌──────────┐ │-│ │ ←──────────── │ │ VAD │ 流式分句 │-│ 实时显示结果 │ JSON │ └────┬─────┘ │-└─────────────────┘ │ ↓ │- │ ┌──────────┐ │- │ │ ASR │ 逐段解码 │- │ └────┬─────┘ │- │ ↓ │- │ ┌──────────┐ │- │ │ SPK │ 说话人分离 │- │ └──────────┘ │- └──────────────────────────┘-```--## 推理逻辑--### 核心设计--服务**不是**将全部音频累积后一次性解码,而是基于 VAD 端点检测**逐段解码**:--```-音频流 ──→ StreamingVAD (60ms chunk) ──→ 检测到端点 ──→ _decode_segment (vLLM)- │ │- │ ▼- │ locked_sentences (文字锁定)- │ │- │ ▼- │ SPK assign (说话人分配)- │- └──→ 未结束 ──→ decode partial (vLLM, 每0.48s)- │- ▼- partial text (实时预览,会被覆盖)-```--### 两条推理路径--| 路径 | 触发条件 | 推理范围 | 输出 |-|------|---------|---------|------|-| **确认段解码** | VAD 检测到静音端点 | 该段完整音频 | 锁定到 sentences,永不改变 |-| **Partial 预览** | 每 0.48s + 新音频 ≥ 960ms | 当前说话中的全部音频 | 临时文字,随时覆盖 |--### 动态 VAD 阈值--为避免切碎短句或堆积过长段,静音阈值根据当前段已累积时长动态调整:--| 累积时长 | 需要静音 | 效果 |-|---------|---------|------|-| ≤ 5s | 2.0s | 短句不切碎 |-| 5-10s | 1.5s | 正常分句 |-| 10-15s | 1.0s | 开始收紧 |-| 15-30s | 0.8s | 较快切分 |-| 30-45s | 0.4s | 防止过长 |-| > 45s | 0.1s | 强制切分 |--### STOP 时的最终处理--1. 将剩余音频喂给 VAD(`is_final=True`),收集最后的确认段-2. 如果仍在说话中,强制结束并解码当前段-3. 对所有 `sentences` 运行 SPK `finalize()`(全局重聚类,修正说话人 ID)-4. 返回 `is_final: true` 的完整结果--### 与 FunASRNanoStreamingVLLM 的区别--| | WebSocket 服务 (`serve_realtime_ws.py`) | SDK 流式 (`FunASRNanoStreamingVLLM`) |-|---|---|---|-| 分句方式 | VAD 自然端点 | 固定 720ms chunk |-| 推理粒度 | 每个 VAD 段整体解码 | 累积重编码全部音频 |-| 准确率 | 更高(完整语义段) | 较低(前 3s 噪声多) |-| 适用场景 | 生产环境实时服务 | SDK 级流式展示 |---## 快速部署--### 环境要求--- Python >= 3.8-- CUDA >= 11.8-- GPU 显存 >= 8GB(vLLM 引擎需要分配 KV Cache)-- vLLM >= 0.6.0--### 安装依赖+## 30 秒启动```bashcd examples/industrial_data_pretraining/fun_asr_nano-pip install -r requirements.txt--# 安装 vLLM(如未安装)-pip install vllm--# 安装 FunASR(开发模式,需要 auto_model_vllm)-cd /path/to/FunASR && pip install -e .-```-### 启动服务--```bash-# 基本启动-CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py --port 10095--# 完整参数-CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py \- --port 10095 \- --model FunAudioLLM/Fun-ASR-Nano-2512 \- --hub ms \- --device cuda:0 \- --decode-interval 0.48 \- --hotword-file 热词列表 \- --language 中文+# 安装依赖+pip install -r requirements.txt+pip install vllm>=0.12.0-# 多卡 tensor parallel(大模型场景)-CUDA_VISIBLE_DEVICES=0,1 python serve_realtime_ws.py \- --port 10095 \- --tensor-parallel-size 2 \- --gpu-memory-utilization 0.8+# 启动服务+CUDA_VISIBLE_DEVICES=0 python serve_realtime_ws.py --port 10095 --language 中文```-首次启动会自动下载模型(约 30 秒),之后即可接受连接。--### 服务端参数--| 参数 | 默认值 | 说明 |-|------|--------|------|-| `--port` | 10095 | WebSocket 监听端口 |-| `--model` | `FunAudioLLM/Fun-ASR-Nano-2512` | ASR 模型名称 |-| `--hub` | `ms` | 模型来源(ms=ModelScope, hf=HuggingFace) |-| `--device` | `cuda:0` | GPU 设备 |-| `--decode-interval` | 0.48 | 实时解码间隔(秒) |-| `--hotword-file` | `热词列表` | 热词文件路径(一行一个词) |-| `--language` | `None` (auto) | 指定语种(如 中文、English、日本語) |-| `--dtype` | `bf16` | 推理精度(bf16/fp16/fp32) |-| `--tensor-parallel-size` | 1 | vLLM tensor parallel GPU 数量 |-| `--gpu-memory-utilization` | 0.8 | vLLM KV Cache GPU 显存占比 |-| `--max-model-len` | 2048 | vLLM 最大序列长度 |-| `--use-context` | True | 使用上下文辅助解码 |-| `--no-context` | - | 禁用上下文 |--## 客户端使用--### 1. 浏览器客户端(client_mic.html)--直接在浏览器中打开 `client_mic.html`:+## 客户端```bash-# 本机访问-open client_mic.html # macOS-xdg-open client_mic.html # Linux+# 浏览器+open client_mic.html-# 远程服务器(需 SSH 端口转发)-ssh -L 10095:localhost:10095 <server>-# 然后在本地浏览器打开 client_mic.html-```--功能:-- 麦克风实时录音-- 音频文件上传识别-- 热词列表文件加载(.txt,一行一个词)-- 说话人分离显示(可开关)--### 2. Python 客户端(client_python.py)--```bash-# 麦克风模式+# Python 麦克风python client_python.py --server ws://localhost:10095 --mic-# 文件模式+# Python 文件python client_python.py --server ws://localhost:10095 --file audio.wav-# 带热词-python client_python.py --server ws://localhost:10095 --file audio.wav \- --hotwords "张三,李四,北京"--# 不显示说话人-python client_python.py --server ws://localhost:10095 --mic --no-spk+# 自动化测试+python client_test.py --server ws://localhost:10095 --file audio.wav```-### 3. 测试脚本(client_test.py)+## 远程访问```bash-# 运行完整测试-python client_test.py --server ws://localhost:10095 --file test_audio.wav--# 带热词测试-python client_test.py --server ws://localhost:10095 --file test_audio.wav \- --hotwords "人名,地名"-```--测试内容:-- 基本流式 ASR 流程验证-- 返回格式校验(sentences/partial/is_final)-- 空音频处理-- 多轮 session 复用-- 性能统计(RTF)--## API 协议文档--### 连接--```-WebSocket URL: ws://<host>:<port>-音频格式: PCM16, 16kHz, 单声道 (Little-Endian)-```--### 客户端 → 服务端--| 消息类型 | 格式 | 说明 |-|---------|------|------|-| 开始会话 | `"START"` (text) | 初始化/重置 session |-| 设置热词 | `"HOTWORDS:词1,词2,词3"` (text) | 可选,在 START 后发送 |-| 设置语种 | `"LANGUAGE:中文"` (text) | 可选,指定识别语种 |-| 音频数据 | `bytes` (binary) | PCM16 音频帧,任意长度 |-| 结束会话 | `"STOP"` (text) | 触发最终解码,返回完整结果 |--### 服务端 → 客户端--#### 1. 事件消息--```json-{"event": "started"}-{"event": "hotwords_set", "hotwords": ["词1", "词2"]}-{"event": "language_set", "language": "中文"}-{"event": "stopped"}-```--#### 2. 实时结果(流式,在 START 和 STOP 之间持续推送)--```json-{- "sentences": [- {"text": "已确认句子", "start": 1700, "end": 5500, "spk": 0}- ],- "partial": "正在说的文字...",- "partial_start_ms": 5800,- "duration_ms": 7200,- "is_final": false-}-```--#### 3. 最终结果(STOP 后返回)--```json-{- "sentences": [- {"text": "第一句话。", "start": 1700, "end": 5500, "spk": 0},- {"text": "第二句话。", "start": 6000, "end": 9200, "spk": 1}- ],- "partial": "",- "partial_start_ms": 0,- "duration_ms": 10000,- "is_final": true-}-```--### 字段说明--| 字段 | 类型 | 说明 |-|------|------|------|-| `sentences` | array | 已确认的句子列表 |-| `sentences[].text` | string | 识别文本 |-| `sentences[].start` | int | 起始时间(毫秒) |-| `sentences[].end` | int | 结束时间(毫秒) |-| `sentences[].spk` | int | 说话人 ID(0-based),仅最终结果保证准确 |-| `partial` | string | 当前正在说的文本(未确认,会被更新) |-| `partial_start_ms` | int | partial 的起始时间(毫秒) |-| `duration_ms` | int | 已接收音频总时长(毫秒) |-| `is_final` | bool | 是否为最终结果 |--### 典型交互流程--```-Client Server- │ │- │──── "START" ─────────────────→│- │←──── {"event":"started"} ─────│- │ │- │──── "HOTWORDS:张三,北京" ────→│ (可选)- │←── {"event":"hotwords_set"} ──│- │ │- │──── "LANGUAGE:中文" ─────────→│ (可选)- │←── {"event":"language_set"} ──│- │ │- │──── [audio bytes] ───────────→│- │──── [audio bytes] ───────────→│- │←── {sentences,partial} ───────│ (实时推送)- │──── [audio bytes] ───────────→│- │←── {sentences,partial} ───────│- │ ... │- │──── "STOP" ──────────────────→│- │←── {sentences,is_final:true} ─│ (最终结果)- │←── {"event":"stopped"} ───────│- │ │+ssh -L 10095:localhost:10095 <server>+# 然后本地打开 client_mic.html```-## 热词文件格式+## 功能-文件名默认为 `热词列表`(可通过 `--hotword-file` 指定),格式为纯文本,一行一个词:+- **vLLM 推理引擎**:RTF < 0.08,支持 tensor parallel 多卡加速+- **流式 VAD 分句**:动态静音阈值,自然断句+- **说话人分离 (Beta)**:流式 ID 分配 + 最终重聚类+- **热词定制化**:加载人名、地名等实体词文件+- **语种指定**:31 种语言 + 中文方言+- **幻觉检测**:自动检测重复模式并截断-```-张三-李四-北京大学-Fun-ASR-Nano-```--也可在运行时通过 WebSocket 动态设置:`HOTWORDS:词1,词2,词3`+## 文件列表-## 注意事项--1. **vLLM 引擎**:首次启动时 vLLM 需要初始化 KV Cache,约需 60-90 秒,之后即可服务-2. **HTTPS 限制**:浏览器麦克风需要 HTTPS 或 localhost(Chrome 安全策略)-2. **远程访问**:使用 SSH 端口转发 `ssh -L 10095:localhost:10095 <server>`-3. **并发支持**:单个服务实例支持多个并发 WebSocket 连接(每个连接独立 session)-4. **显存占用**:vLLM 引擎 + VAD + SPK 共约 8-10GB 显存(gpu_memory_utilization=0.8 时)-5. **说话人分离**:Beta 功能,短音频或单人场景可能不准确-6. **模型来源**:默认从 ModelScope 下载,可用 `--hub hf` 切换 HuggingFace+| 文件 | 说明 |+|------|------|+| `serve_realtime_ws.py` | WebSocket 服务端 |+| `client_mic.html` | 浏览器客户端 |+| `client_python.py` | Python CLI 客户端 |+| `client_test.py` | 自动化测试脚本 |+| `热词列表` | 热词文件示例 |+| `demo_vllm.py` | 离线 vLLM 推理 demo |-## Related+## 详细文档-- **[vLLM Offline Inference](vllm_inference.md)** — Batch inference API (FunASRNanoVLLM)-- **[vLLM Streaming Inference](vllm_streaming.md)** — Chunk-by-chunk streaming SDK (FunASRNanoStreamingVLLM)+- [FunASR vLLM 推理引擎指南](../../../../docs/vllm_guide.md) — 完整文档(离线/流式/WebSocket/API/FAQ)diff --git a/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_inference.md b/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_inference.mddeleted file mode 100644index f4860d648..000000000--- a/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_inference.md+++ /dev/null@@ -1,216 +0,0 @@-# Fun-ASR-Nano vLLM Inference Guide--Fun-ASR-Nano supports [vLLM](https://github.com/vllm-project/vllm) as a high-throughput inference backend. This enables significantly faster batch processing and multi-GPU tensor parallelism for production deployments.--## Overview--The vLLM integration splits inference into two parts:-- **Audio processing** (PyTorch): Frontend → Audio Encoder → Audio Adaptor-- **LLM decoding** (vLLM): High-throughput autoregressive text generation with KV-cache optimization--This architecture allows vLLM to efficiently batch multiple requests and leverage tensor parallelism across GPUs for the compute-intensive LLM decoding step.--## Requirements--```bash-# Core dependencies-pip install funasr>=1.3.0-pip install vllm>=0.12.0-pip install safetensors-pip install tiktoken--# For ModelScope model download-pip install modelscope-```--## Quick Start--### AutoModelVLLM (Recommended)--```python-from funasr.auto.auto_model_vllm import AutoModelVLLM--# Generic interface - auto-detects model type, works for all LLM-based ASR models-model = AutoModelVLLM(- model="FunAudioLLM/Fun-ASR-Nano-2512",- hub="ms",- tensor_parallel_size=1,-)--results = model.generate(["audio.wav"], language="中文")-print(results[0]["text"])-```--### FunASRNanoVLLM (Direct API)--```python-from funasr.models.fun_asr_nano.inference_vllm import FunASRNanoVLLM--# Initialize with single GPU-engine = FunASRNanoVLLM.from_pretrained(- model="FunAudioLLM/Fun-ASR-Nano-2512",- hub="ms", # or "hf" for HuggingFace- tensor_parallel_size=1,-)--# Single file inference-results = engine.generate(["path/to/audio.wav"])-print(results[0]["text"])--# Batch inference with hotwords-results = engine.generate(- inputs=["audio1.wav", "audio2.wav", "audio3.wav"],- hotwords=["开放时间", "人工智能"],- language="中文",-)-for r in results:- print(f"[{r['key']}] {r['text']}")-```--### Multi-GPU Tensor Parallel--```python-# Use 2 GPUs for vLLM (doubles decoding throughput)-engine = FunASRNanoVLLM.from_pretrained(- model="FunAudioLLM/Fun-ASR-Nano-2512",- tensor_parallel_size=2,- gpu_memory_utilization=0.8,-)-```--### Command-Line Demo--```bash-# Single file-python demo_vllm.py --input audio.wav --language 中文--# Batch processing from wav.scp-python demo_vllm.py --input wav.scp --tensor-parallel-size 4 --batch-size 32--# With hotwords-python demo_vllm.py --input audio.wav --hotwords 开放时间 周一 --language 中文--# Save results to file-python demo_vllm.py --input wav.scp --output results.jsonl-```--## API Reference--### `FunASRNanoVLLM.from_pretrained()`--| Parameter | Type | Default | Description |-|-----------|------|---------|-------------|-| `model` | str | `"FunAudioLLM/Fun-ASR-Nano-2512"` | Model name or local path |-| `hub` | str | `"ms"` | Model hub: `"ms"` (ModelScope) or `"hf"` (HuggingFace) |-| `device` | str | `"cuda:0"` | Device for audio encoder/adaptor |-| `dtype` | str | `"bf16"` | Compute dtype: `"bf16"`, `"fp16"`, `"fp32"` |-| `tensor_parallel_size` | int | `1` | Number of GPUs for vLLM tensor parallel |-| `gpu_memory_utilization` | float | `0.8` | Fraction of GPU memory for vLLM KV cache |-| `max_model_len` | int | `2048` | Maximum sequence length |--### `engine.generate()`--| Parameter | Type | Default | Description |-|-----------|------|---------|-------------|-| `inputs` | str/List[str] | - | Audio file path(s) or numpy arrays |-| `hotwords` | List[str] | `None` | Keywords to boost recognition |-| `language` | str | `None` | Language hint (e.g. "中文", "英文", "日文") |-| `itn` | bool | `True` | Apply inverse text normalization |-| `max_new_tokens` | int | `512` | Max generated tokens per sample |-| `temperature` | float | `0.0` | Sampling temperature (0 = greedy) |-| `top_p` | float | `1.0` | Nucleus sampling |-| `repetition_penalty` | float | `1.0` | Repetition penalty |--**Returns:** `List[dict]` with keys:-- `"key"`: Sample identifier (filename without extension)-- `"text"`: Recognized text-- `"timestamps"`: Character-level timestamps (if CTC decoder available)--## Performance--### Throughput Comparison--| Backend | Batch Size | 1 GPU | 2 GPUs | 4 GPUs |-|---------|-----------|-------|--------|--------|-| HuggingFace (baseline) | 1 | 1x | - | - |-| vLLM | 1 | ~1.5x | ~2x | ~2.5x |-| vLLM | 16 | ~4x | ~7x | ~12x |-| vLLM | 32 | ~5x | ~9x | ~15x |--*Approximate speedup for batch processing. Actual numbers depend on audio length and hardware.*--### Memory Usage--- Audio encoder + adaptor: ~400MB GPU memory (single GPU)-- vLLM LLM (Qwen3-0.6B): ~1.2GB per GPU (with bf16)-- KV cache: scales with `gpu_memory_utilization` setting--## Architecture Details--```-┌─────────────────────────────────────────────────────┐-│ FunASRNanoVLLM │-├─────────────────────────────────────────────────────┤-│ │-│ Audio Input │-│ │ │-│ ▼ │-│ ┌──────────────┐ │-│ │ WavFrontend │ (fbank, LFR, CMVN) │-│ └──────┬───────┘ │-│ ▼ │-│ ┌──────────────────────┐ │-│ │ SenseVoiceEncoder │ (50-layer SANM, frozen) │-│ │ (Audio Encoder) │ │-│ └──────┬───────────────┘ │-│ ▼ │-│ ┌──────────────────────┐ │-│ │ Transformer Adaptor │ (2-layer, downsample) │-│ │ (Audio Adaptor) │ │-│ └──────┬───────────────┘ │-│ ▼ │-│ [Audio Embeddings] ──────────┐ │-│ ▼ │-│ [Text Token Embeds] ───> [Concat] ─── EmbedsPrompt │-│ (prefix + suffix) │ │-│ ▼ │-│ ┌────────────────────┐ │-│ │ vLLM Engine │ │-│ │ (Qwen3-0.6B) │ │-│ │ Tensor Parallel │ │-│ └────────┬───────────┘ │-│ ▼ │-│ Generated Text │-│ │-│ (Optional) CTC Forced Alignment → Timestamps │-│ │-└─────────────────────────────────────────────────────┘-```--## Supported Models--| Model | Hub ID | Languages |-|-------|--------|-----------|-| Fun-ASR-Nano | `FunAudioLLM/Fun-ASR-Nano-2512` | Chinese, English, Japanese + dialects |-| Fun-ASR-MLT-Nano | `FunAudioLLM/Fun-ASR-MLT-Nano-2512` | 31 languages |--## Troubleshooting--### "model.pt not found"-The model must be fully downloaded first. On first use, `from_pretrained()` will download it automatically from the hub.--### CUDA out of memory-- Reduce `gpu_memory_utilization` (e.g. 0.6)-- Use `tensor_parallel_size` > 1 to split across GPUs-- Reduce `max_model_len`--### Slow first inference-The first call includes vLLM's CUDA graph warmup. Subsequent calls will be faster.--### Tokenizer warnings-These are typically harmless warnings from the Qwen3 tokenizer about special tokens and can be ignored.--## Related--- **[Streaming vLLM Inference](vllm_streaming.md)** — Chunk-by-chunk streaming (SDK level)-- **[Real-time WebSocket Server](realtime_demo.md)** — Production-ready streaming service with VAD + Speaker Diarization + Hotwords (uses vLLM as backend)diff --git a/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_streaming.md b/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_streaming.mddeleted file mode 100644index f742be1fb..000000000--- a/examples/industrial_data_pretraining/fun_asr_nano/docs/vllm_streaming.md+++ /dev/null@@ -1,154 +0,0 @@-# Fun-ASR-Nano Streaming vLLM Inference--Chunk-by-chunk streaming ASR using vLLM for high-throughput LLM decoding.--## Design--```-Audio stream (720ms chunks)- │- ▼ (cumulative re-encoding)-┌────────────────────┐-│ Encoder + Adaptor │ (PyTorch, single GPU)-└────────┬───────────┘- ▼-┌────────────────────┐-│ vLLM Batch Gen │ (all chunks batched in single call)-└────────┬───────────┘- ▼-Per-chunk results with fixed/unfixed regions:- chunk1: ""- chunk2: "开"- chunk3: "开放时间早"- chunk4: "开放时间早上九点至下午五点。" ← stabilized-```--### Key Design Decisions--1. **Cumulative audio re-encoding**: Each chunk re-processes ALL audio from start. This ensures the encoder has full context.--2. **Batch-all-chunks**: All chunk prompts are batched into a single vLLM `generate()` call. This avoids KV-cache corruption issues with sequential EmbedsPrompt calls and maximizes throughput.--3. **8-character rollback**: The last 8 characters of each chunk's output are "unfixed" (may change in subsequent chunks). Text beyond the rollback boundary is "fixed".--4. **Repetition penalty**: `repetition_penalty=1.3` prevents degenerate repetitions for short audio chunks.--## Quick Start--```python-from funasr.models.fun_asr_nano.inference_vllm_streaming import FunASRNanoStreamingVLLM--engine = FunASRNanoStreamingVLLM.from_pretrained(- model="FunAudioLLM/Fun-ASR-Nano-2512",- tensor_parallel_size=1,- chunk_ms=720,- rollback_chars=8,-)--# Stream results-for result in engine.streaming_generate("audio.wav", language="中文"):- if result["is_final"]:- print(f"Final: {result['text']}")- else:- print(f"[{result['audio_duration_ms']:.0f}ms] {result['text']}")- print(f" Fixed: {result['fixed_text']}")-```--## API Reference--### `FunASRNanoStreamingVLLM.from_pretrained()`--| Parameter | Default | Description |-|-----------|---------|-------------|-| `model` | `"FunAudioLLM/Fun-ASR-Nano-2512"` | Model name or local path |-| `hub` | `"ms"` | `"ms"` or `"hf"` |-| `device` | `"cuda:0"` | Device for audio encoder/adaptor |-| `dtype` | `"bf16"` | Compute precision |-| `tensor_parallel_size` | `1` | GPUs for vLLM |-| `gpu_memory_utilization` | `0.8` | GPU memory fraction for vLLM KV cache |-| `max_model_len` | `2048` | Maximum sequence length |-| `chunk_ms` | `720` | Chunk duration in ms |-| `rollback_chars` | `8` | Unfixed region size |--### `engine.streaming_generate()`--| Parameter | Default | Description |-|-----------|---------|-------------|-| `audio_input` | - | File path, numpy array, or tensor (16kHz) |-| `chunk_ms` | `720` | Override chunk size |-| `rollback_chars` | `8` | Override rollback |-| `hotwords` | `None` | List of hotwords |-| `language` | `None` | Language hint (e.g. "中文") |-| `itn` | `True` | Inverse text normalization |-| `max_new_tokens` | `200` | Max tokens per chunk |-| `temperature` | `0.0` | Sampling temperature |--> Note: `repetition_penalty=1.3` is applied internally to prevent degenerate repetitions on short chunks.--**Yields** per chunk:-```python-{- "text": "full recognized text so far",- "fixed_text": "confirmed text (won't change)",- "is_final": False, # True for last chunk- "chunk_idx": 4,- "audio_duration_ms": 2880.0,-}-```--## Output Characteristics--| Audio Duration | Output Quality |-|---------------|---------------|-| < 1.5s | Empty or garbage (insufficient context) |-| 1.5 - 3.0s | Partial/noisy (model warming up) |-| > 3.0s | Correct transcription |-| Full audio | Best accuracy |--The model needs ~3 seconds of cumulative audio before producing accurate results. This is inherent to the model architecture, not a vLLM limitation.--## Example Output--```-[c01] 720ms | ""-[c02] 1440ms | "-"-[c03] 2160ms | "time/day."-[c04] 2880ms | "time早上九"-[c05] 3600ms | "期限:早上九点至"- fixed: "期限:早上"-[c06] 4320ms | "期限:开放时间早上9点~下午10:35/4."- fixed: "期限:开放时间早上9点~下午10:"-[c07] 5040ms | "期限:开放时间早上九点至下午五点。"- fixed: "期限:开放时间早上九点至下午"-[FINAL] 5616ms | "期限,开放时间早上九点至下午五点。"-```--## Compared with Other Modes--| Mode | Class | Latency | Accuracy | Use Case |-|------|-------|---------|----------|----------|-| Offline | `AutoModelVLLM` / `FunASRNanoVLLM` | Full audio | Best | Batch transcription |-| Streaming SDK | `FunASRNanoStreamingVLLM` | Per-chunk | Good (after ~3s) | Real-time display (SDK) |-| WebSocket Server | `serve_realtime_ws.py` | Per-VAD-segment | Best | Production service with VAD+SPK |--For offline batch inference:--```python-from funasr.auto.auto_model_vllm import AutoModelVLLM--model = AutoModelVLLM(model="FunAudioLLM/Fun-ASR-Nano-2512")-results = model.generate(["audio.wav"], language="中文")-```--For real-time WebSocket service (VAD + ASR + Speaker Diarization):--```bash-python serve_realtime_ws.py --port 10095 --language 中文-```--> Note: `serve_realtime_ws.py` uses `AutoModelVLLM.generate()` per-segment (not `streaming_generate`), because VAD already provides natural sentence boundaries. This gives better accuracy than chunk-level streaming.--## Related--- **[Offline vLLM Inference](vllm_inference.md)** — Batch inference with maximum accuracy-- **[Real-time WebSocket Server](realtime_demo.md)** — Production-ready streaming service with VAD + Speaker Diarization + Hotwords (uses vLLM as backend via `AutoModelVLLM`)