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(vllm_guide): explain EmbedsPrompt/streaming partial/SPK/concurrency setting (#3011)
qiulangb201dfa94bbb
diff --git a/docs/vllm_guide.md b/docs/vllm_guide.mdindex 6b810297c..9ca4c825b 100644--- a/docs/vllm_guide.md+++ b/docs/vllm_guide.md@@ -63,7 +63,7 @@ FunASR's vLLM integration splits the ASR model into two independently running co```┌──────────────────────────────────────────────────────────────┐-│ FunASR + vLLM Inference Architecture │+│ FunASR + vLLM Inference Architecture │├──────────────────────────────────────────────────────────────┤│ ││ ┌─────────────── PyTorch (single GPU) ───────────┐ │@@ -75,12 +75,12 @@ FunASR's vLLM integration splits the ASR model into two independently running co│ │ ▼ ││ │ Audio Embeddings ││ │ │ │-│ │ Text Prompt ──→ Tokenize ──→ Embed │+│ │ Text Prompt ──→ Tokenize ──→ Embed ││ │ (system/user/ │ ││ │ hotwords/language) │ ││ │ ▼ ││ │ [Concat Embeddings] │-│ └─────────────────────────────────┼─────────────┘ │+│ └─────────────────────────────────┼─────────────┘ ││ │ ││ ▼ EmbedsPrompt ││ ┌─────────────── vLLM Engine ────────────────────┐ │@@ -89,7 +89,7 @@ FunASR's vLLM integration splits the ASR model into two independently running co│ │ KV Cache management + CUDA Graph │ ││ │ Tensor Parallel (multi-GPU) │ ││ │ │ │-│ │ Qwen3-0.6B / Llama-2B (LLM decoding) │ │+│ │ Qwen3-0.6B / Llama-2B (LLM decoding) │ ││ │ │ ││ └────────────────────┬───────────────────────────┘ ││ │ │@@ -98,7 +98,7 @@ FunASR's vLLM integration splits the ASR model into two independently running co│ │ ││ ┌────────────────────┼──────────────────────────┐ ││ │ (Optional) CTC Decoder ──→ Forced Alignment │ │-│ │ ──→ Character-level timestamps │ │+│ │ ──→ Character-level timestamps │ ││ └───────────────────────────────────────────────┘ │└──────────────────────────────────────────────────────────────┘```@@ -126,7 +126,7 @@ FunASR's vLLM integration splits the ASR model into two independently running co### Key Implementation Details1. **Weight separation**: LLM weights are extracted from `model.pt` and converted to HuggingFace format for vLLM loading-2. **EmbedsPrompt**: Audio embeddings and text embeddings are concatenated and fed to vLLM as a single prompt embedding+2. **EmbedsPrompt**: a vLLM input mode that feeds **precomputed embedding vectors** (rather than the usual token IDs) directly as the prompt (enabled via `enable_prompt_embeds=True`). Fun-ASR-Nano requires it because the audio, after the adaptor, is a sequence of continuous vectors — not tokens — so the audio embeddings and text embeddings are concatenated along the sequence dimension and submitted to vLLM as a whole3. **use_low_frame_rate**: Fun-ASR-Nano's adaptor output must be truncated to the correct token count via a formula (critical for consistency)4. **Batch encode**: Multiple audio files pass through `extract_fbank` → `audio_encoder` → `audio_adaptor` in a single forward pass5. **CTC timestamps**: Encoder output is retained; after text generation, forced alignment yields character-level timing@@ -143,7 +143,7 @@ Offline SDK inference splits the ASR pipeline into two stages executed independe```┌─────────────────────────────────────────────────────────────────────┐-│ Stage 1: Audio Encoding (PyTorch, single GPU) │+│ Stage 1: Audio Encoding (PyTorch, single GPU) │├─────────────────────────────────────────────────────────────────────┤│ ││ Audio file list ──→ Group (batch of 8) ──→ Frontend (Fbank) │@@ -156,7 +156,7 @@ Offline SDK inference splits the ASR pipeline into two stages executed independe│ │ (dim transform + LFR trunc) ││ │ │ ││ └─── Shared text prompt encoding ────┐ ▼ │-│ (system/hotwords/language) │ audio_embeds │+│ (system/hotwords/language) │ audio_embeds ││ │ │ │ ││ ▼ │ ▼ ││ prefix_emb ──→ [concat: prefix | audio | suffix] │@@ -171,16 +171,16 @@ Offline SDK inference splits the ASR pipeline into two stages executed independe├─────────────────────────────────────────────────────────────────────┤│ ││ EmbedsPrompt × N ──→ vLLM Continuous Batching │-│ (PagedAttention + CUDA Graph) │+│ (PagedAttention + CUDA Graph) ││ │ ││ ▼ │-│ Generated token_ids × N │+│ Generated token_ids × N ││ │ ││ ▼ │-│ Decode + post-processing (strip special tokens) │+│ Decode + post-processing (strip special tokens) ││ │ ││ ▼ │-│ (Optional) CTC Forced Alignment → char timestamps│+│ (Optional) CTC Forced Alignment → char timestamps│└─────────────────────────────────────────────────────────────────────┘```@@ -307,6 +307,7 @@ for result in engine.streaming_generate("audio.wav", language="中文"):| 1.5–3.0 s | Partially correct || > 3.0 s | Accurate output |+> **Note: `repetition_penalty` cannot be used with EmbedsPrompt.** Here the prompt is a sequence of embedding vectors with no corresponding token IDs, whereas `repetition_penalty` needs the prompt's token IDs to down-weight already-seen tokens in the logits; applying it under EmbedsPrompt **indexes out of bounds and triggers a CUDA device-side assert**.---@@ -320,7 +321,7 @@ Client serve_vllm.py│── HTTP / OpenAI / WebSocket ─────────→││ ││ ┌────┴────────────────────────┐- │ │ 1. Receive complete audio │+ │ │ 1. Receive complete audio ││ │ 2. Dynamic VAD (≤60 s/seg) ││ │ 3. vLLM batch all segments ││ │ 4. CTC timestamps (per-char)│@@ -346,6 +347,11 @@ CUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/--gpu-memory-utilization 0.5```+> **About [`CUDA_VISIBLE_DEVICES`](https://docs.vllm.ai/en/v0.4.3/serving/env_vars.html)**: the `=0` in the examples is just an illustrative value ("use GPU 0"), **not a fixed requirement**. It selects which GPUs are visible to this process (indexed as in `nvidia-smi`), a single GPU machine does not need to set it.+>+> - **Single GPU**: small models like 0.6B / 1.7B can run several instances on one card — point multiple processes at the same GPU (e.g. all `=0`) sharing it via MPS, or split across cards with process A `=0`, B `=1` (see §6.7).+>+### 5.3 Protocol 1: HTTP REST — `POST /asr`The most feature-complete interface, supporting speaker diarization, timestamps, and hotwords.@@ -525,18 +531,18 @@ asyncio.run(offline_ws("audio.wav"))```Client (microphone / audio stream) serve_realtime_ws.py│ │- │── WebSocket PCM16 16 kHz ──────────→│+ │── WebSocket PCM16 16 kHz ───────────→││ (~100 ms per frame, continuous) ││ │- │ ┌────┴─────────────────────────┐+ │ ┌────┴──────────────────────────┐│ │ Real-time loop: ││ │ ├─ Dynamic VAD (60 ms chunk) ││ │ ├─ Endpoint → vLLM decode ││ │ ├─ No endpoint → partial ││ │ └─ Streaming SPK assignment │- │ └────┬─────────────────────────┘+ │ └────┬──────────────────────────┘│ │- │←── JSON real-time push ─────────────│+ │←── JSON real-time push ──────────────│```**Characteristics**:@@ -584,7 +590,7 @@ Client Server│── START ───────→││←─ started ──────││── [audio] ─────→│- │←─ {partial} ────│+ │←─ {partial} ────│ #refer to 6.5│── [audio] ─────→││←─ {sentences+partial} ─│ (VAD cut a sentence)│── STOP ────────→│@@ -630,6 +636,40 @@ async def stream(audio_path):asyncio.run(stream("audio.wav"))```+### 6.5 Partial preview mechanism and long-sentence behavior++**What partial is and how it's produced**+While the user is speaking, the streaming service periodically (default `decode_interval≈0.48s` in `serve_realtime_ws.py`) decodes "the current sentence from its start up to now," emitting **provisional text** (the `partial` field in the protocol, which may be overwritten by later refreshes), until VAD detects the sentence end and locks it into `sentences`. This lets the user see text as they speak.++> Note: `serve_vllm.py`'s `/ws` (§5) has **no partial** and only returns at sentence end; use `serve_realtime_ws.py` for live preview.++**Principle: why each partial re-encodes the whole segment from the start**+Fun-ASR-Nano's acoustic encoder (SenseVoice) is a **full-context, non-streaming** encoder — each frame's representation depends on the context of the entire segment. When the sentence continues and the audio grows, the context of the earlier frames changes, so **the previously computed encoding no longer holds**. It therefore cannot cache history and encode only the new frames the way a streaming / causal encoder would; it must run the whole "start → now" segment through the encoder again.++**Resulting behavior: partial gets slower on long sentences (O(L²))**+Because each refresh re-encodes from the sentence start, the longer a sentence, the longer each partial's audio and the more refreshes occur — so **total encoding work grows quadratically with sentence length**. In practice a ~29 s continuous utterance is fully re-encoded a dozen-plus times, with single-pass encoder time climbing from tens to hundreds of milliseconds. (The §4 SDK streaming "each chunk contains all audio from the start to now" is the same mechanism; long files behave the same way.)++**Usage guidance**+- Normal conversational speech has natural pauses, so VAD splits it into relatively short utterances and each partial's cost is naturally bounded — **usually nothing to worry about**.+- Only **very long, pauseless continuous speech** (e.g. reading aloud) makes a single utterance keep growing and the partial preview progressively slower — this is an inherent property of the full-context encoder, **not a configuration issue**. If your scenario has such audio and is sensitive to preview latency, you can bound the partial encoding window in code (e.g. encode only the last few seconds); this is a **code change, not a config option**, and it does not affect locked sentences (which still run on the full audio, with identical final transcripts).++### 6.6 Cost of speaker diarization (SPK) and how to disable it++At startup, `serve_realtime_ws.py` **loads the SPK model by default** (hardcoded to `iic/speech_eres2netv2_sv_zh-cn_16k-common`) and runs speaker assignment for each VAD-completed sentence during streaming. Note:++- **SPK is of limited effectiveness on Fun-ASR-Nano** (see #2944); most real-time ASR scenarios do not need speaker separation.+- **Streaming SPK is expensive and grows with the session**: each sentence re-clusters **all historical embeddings** (**O(N²)**, more expensive per sentence as the session grows) and **synchronously blocks the event loop**; the session also **re-clusters everything again** at the end, so the per-sentence clustering during streaming is overwritten by the final result — redundant as far as the final output is concerned. This is especially pronounced under long sessions + high concurrency.+- **Disabling currently requires a code change**: `spk_model` is loaded by default and hardcoded in `serve_realtime_ws.py`, with no flag.+- **Recommendation**: don't load `spk_model` when speaker separation isn't needed; if diarization is required, take labels from the final result, or use a Paraformer + cam++ pipeline.++### 6.7 Production concurrency and multi-process deployment++`serve_realtime_ws.py` is a **single-asyncio-event-loop** service: both `decode()` (timed partial) and `add_audio()` (decode triggered at VAD sentence end) **synchronously block** the entire event loop — while any one connection is decoding, all others pause sending/receiving. Therefore:++- **The single-process concurrency ceiling comes from event-loop serialization, not GPU compute.** Under high concurrency GPU utilization stays low and the encoder runs at ~86× real time; mistaking this for insufficient GPU and adding cards or tensor parallelism yields little (TP only splits the LLM, not the standalone encoder).+- **The right way to scale (currently) = multiple independent processes on one card + CUDA MPS + nginx round-robin**: each process has its own GIL and CUDA context, sidestepping the single-loop serialization; MPS lets the processes truly share the GPU concurrently and fill the idle compute; nginx round-robins across the WebSocket backends. Beyond a single card's headroom, scale out horizontally (one instance per card + a load balancer).+- **Sustainable concurrency has no universal "supports N connections" number.** The ceiling is set not by the number of connections but by **how many are speaking at the same moment** — each speaking connection triggers a partial decode roughly once per second, all serialized on that single event loop. It mainly varies with: **① silence ratio** — in real turn-taking users spend most of the time listening, so far fewer are decoding simultaneously than are connected, whereas a continuous monologue keeps nearly every connection decoding; **② sentence length** — longer sentences make each partial encode more expensive (see 6.5's O(L²)), raising load at the same connection count. So the same "single L20 + multi-process + MPS" setup can sustain dozens of connections under turn-taking-like load but markedly fewer under long, pauseless speech. **Any "supports X connections" figure holds only for the traffic profile it was measured under** — benchmark with your own real traffic (sentence length, pauses, continuous or not) rather than treating someone else's number as your spec.+---## 7. Dynamic VADdiff --git a/docs/vllm_guide_zh.md b/docs/vllm_guide_zh.mdindex 8f3286f7d..32cc640f9 100644--- a/docs/vllm_guide_zh.md+++ b/docs/vllm_guide_zh.md@@ -36,7 +36,7 @@先安装 vLLM,按 NVIDIA 驱动的 CUDA 版本选对应版本;vLLM 会自动钉定并安装匹配的 torch / torchaudio / torchvision 三件套,所以不要自己装 torch/torchaudio——三者 ABI 锁死,必须是互相编译匹配的同一组(如 torch 2.10.0 ↔ torchaudio 2.10.0 ↔ torchvision 0.25.0),只能随 vLLM 一起来。-```+```bash# 1) 先装 vLLM。按 `nvidia-smi` 显示的 CUDA 版本(驱动支持的最高 CUDA,不是 runtime CUDA)选版本,# vLLM 会带来匹配的 torch/torchaudio/torchvision。# 驱动 CUDA 12.x -> pip install vllm==0.19.1 (附带 torch 2.10 / cu128)@@ -53,7 +53,7 @@ cd /path/to/FunASR && pip install -e .**硬件**:GPU ≥ 8GB VRAM,CUDA ≥ 11.8。推荐 16GB+。-为什么不要单独执行 pip install torch torchaudio? torch/torchaudio/torchvision 的版本由 vLLM 版本决定—— 每个大版本会一起升级(见 vLLM 的 requirements/cuda.txt)。手动安装会拉到最新 wheel,可能是为比你驱动更新的 CUDA runtime 编译的;PyTorch 会在 CUDA 初始化阶段、FunASR 启动前就报 The NVIDIA driver on your system is too old。让 vLLM 统一钉定这三件套即可避免。若仍遇到该错误,请安装其 CUDA 构建与 nvidia-smi 显示的 CUDA 匹配的 vLLM 版本(如 CUDA 12.x 用 vllm==0.19.1),或先升级 NVIDIA 驱动。+为什么不要单独执行 `pip install torch torchaudio` ? torch/torchaudio/torchvision 的版本由 vLLM 版本决定—— 每个大版本会一起升级(见 vLLM 的 [requirements/cuda.txt](https://github.com/vllm-project/vllm/blob/main/requirements/cuda.txt))。手动安装会拉到最新 wheel,可能是为比你驱动更新的 CUDA runtime 编译的;PyTorch 会在 CUDA 初始化阶段、FunASR 启动前就报 The NVIDIA driver on your system is too old。让 vLLM 统一钉定这三件套即可避免。若仍遇到该错误,请安装其 CUDA 构建与 nvidia-smi 显示的 CUDA 匹配的 vLLM 版本(如 CUDA 12.x 用 vllm==0.19.1),或先升级 NVIDIA 驱动。---@@ -77,12 +77,12 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ │ ▼ ││ │ Audio Embeddings ││ │ │ │-│ │ Text Prompt ──→ Tokenize ──→ Embed │+│ │ Text Prompt ──→ Tokenize ──→ Embed ││ │ (system/user/ │ ││ │ hotwords/language) │ ││ │ ▼ ││ │ [Concat Embeddings] │-│ └─────────────────────────────────┼─────────────┘ │+│ └─────────────────────────────────┼─────────────┘ ││ │ ││ ▼ EmbedsPrompt ││ ┌─────────────── vLLM Engine ────────────────────┐ │@@ -91,7 +91,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ │ KV Cache 管理 + CUDA Graph │ ││ │ Tensor Parallel (多卡) │ ││ │ │ │-│ │ Qwen3-0.6B / Llama-2B (LLM 解码) │ │+│ │ Qwen3-0.6B / Llama-2B (LLM 解码) │ ││ │ │ ││ └────────────────────┬───────────────────────────┘ ││ │ │@@ -99,8 +99,8 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ Generated Text ││ │ ││ ┌────────────────────┼──────────────────────────┐ │-│ │ (可选) CTC Decoder ──→ Forced Alignment │ │-│ │ ──→ 字级别时间戳 │ │+│ │ (可选) CTC Decoder ──→ Forced Alignment │ │+│ │ ──→ 字级别时间戳 │ ││ └───────────────────────────────────────────────┘ │└──────────────────────────────────────────────────────────────┘```@@ -128,7 +128,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:### 关键实现细节1. **权重分离**:从 `model.pt` 提取 LLM 权重,转为 HuggingFace 格式供 vLLM 加载-2. **EmbedsPrompt**:音频 embedding + 文本 embedding 拼接后作为 prompt embedding 送入 vLLM+2. **EmbedsPrompt**:直接把**已算好的 embedding 向量**(而非通常的 token ID)作为 prompt 送入 vLLM(开关 `enable_prompt_embeds=True`)。Fun-ASR-Nano 必须用它,因为音频经 adaptor 得到的是连续向量、不是 token,需把音频 embedding 与文本 embedding 在序列维拼接后整体送入 vLLM3. **use_low_frame_rate**:Fun-ASR-Nano 的 adaptor 输出需按公式截断到正确 token 数(一致性关键)4. **batch encode**:多条音频通过 `extract_fbank` → `audio_encoder` → `audio_adaptor` 一次前向5. **CTC 时间戳**:保留 encoder_out,生成文本后做 forced alignment 得到字级别时间@@ -149,7 +149,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ 阶段 1: 音频编码(PyTorch, 单 GPU) │├─────────────────────────────────────────────────────────────────────┤│ │-│ 音频文件列表 ──→ 分组(每 8 条)──→ Frontend(Fbank) │+│ 音频文件列表 ──→ 分组(每 8 条)──→ Frontend(Fbank) ││ │ │ ││ │ ▼ ││ │ SenseVoice Encoder │@@ -174,16 +174,16 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:├─────────────────────────────────────────────────────────────────────┤│ ││ EmbedsPrompt × N ──→ vLLM Continuous Batching │-│ (PagedAttention + CUDA Graph) │+│ (PagedAttention + CUDA Graph) ││ │ ││ ▼ │-│ Generated token_ids × N │+│ Generated token_ids × N ││ │ ││ ▼ │-│ Decode + 后处理(去特殊标记、清洗) │+│ Decode + 后处理(去特殊标记、清洗) ││ │ ││ ▼ │-│ (可选) CTC Forced Alignment → 字级别时间戳 │+│ (可选) CTC Forced Alignment → 字级别时间戳 │└─────────────────────────────────────────────────────────────────────┘```@@ -273,8 +273,8 @@ python demo_vllm.py --input audio.wav --hotwords 张三 北京 --output results.│ 累积重编码(每个 chunk 包含从头到当前的全部音频)▼┌──────────────────────┐-│ Stage 1: 前 10 chunk │ ← 无 prev_text,批量生成-│ 找到稳定输出 │+│ Stage 1: 前 10 chunk │ ← 无 prev_text,批量生成+│ 找到稳定输出 │└──────────┬───────────┘▼┌──────────────────────┐@@ -302,6 +302,8 @@ for result in engine.streaming_generate("audio.wav", language="中文"):print(f"[{result['audio_duration_ms']:.0f}ms] 确认: {result['fixed_text']}")```+**注意:EmbedsPrompt 下不能用 `repetition_penalty`。** 此时 prompt 是 embedding 向量、没有对应的 token ID,而 `repetition_penalty` 要靠 prompt 的 token ID 在 logits 上给已出现的词降分;用在 EmbedsPrompt 上会**索引越界、触发 CUDA device-side assert**。+### 输出特性| 累积音频 | 输出质量 |@@ -315,7 +317,7 @@ for result in engine.streaming_generate("audio.wav", language="中文"):## 5. 离线语音识别服务-### 3.1 服务架构+### 5.1 服务架构```客户端 serve_vllm.py@@ -323,11 +325,11 @@ for result in engine.streaming_generate("audio.wav", language="中文"):│── HTTP/OpenAI/WebSocket ──────────────→││ ││ ┌────┴────────────────────────┐- │ │ 1. 接收完整音频文件 │- │ │ 2. 动态 VAD 分段(≤60s/段) │- │ │ 3. vLLM batch 推理所有段 │- │ │ 4. CTC 时间戳(逐字) │- │ │ 5. 说话人分离(可选) │+ │ │ 1. 接收完整音频文件 │+ │ │ 2. 动态 VAD 分段(≤60s/段) │+ │ │ 3. vLLM batch 推理所有段 │+ │ │ 4. CTC 时间戳(逐字) │+ │ │ 5. 说话人分离(可选) ││ └────┬────────────────────────┘│ ││←── JSON 结果 ─────────────────────────│@@ -340,7 +342,7 @@ for result in engine.streaming_generate("audio.wav", language="中文"):- 自动输出字级别时间戳- SPK 说话人分离默认关闭,客户端可开启-### 3.2 启动服务+### 5.2 启动服务```bashCUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/serve_vllm.py \@@ -349,7 +351,11 @@ CUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/--gpu-memory-utilization 0.5```-### 3.3 协议一:HTTP REST — `POST /asr`+> **关于 `CUDA_VISIBLE_DEVICES`**:这是[vllm的一个环境变量](https://docs.vllm.ai/en/v0.4.3/serving/env_vars.html) ,示例中的 `=0` 只是"用第 0 张卡"的示例值,**不是固定写法**,它选择本进程可见的 GPU(编号同 `nvidia-smi`),单卡机器也不需要设置。+>+> **单卡多实例**:0.6B / 1.7B 这类小模型一张卡可起多个实例,多进程可都指向同一张卡(如都 `=0`)+ MPS 共享;分卡则进程 A `=0`、B `=1`(见 §6.7)。++### 5.3 协议一:HTTP REST — `POST /asr`功能最全的接口,支持 SPK、时间戳、热词。@@ -413,7 +419,7 @@ const resp = await fetch("http://localhost:8899/asr", { method: "POST", body: foconst result = await resp.json();```-### 3.4 协议二:OpenAI Whisper 兼容 — `POST /v1/audio/transcriptions`+### 5.4 协议二:OpenAI Whisper 兼容 — `POST /v1/audio/transcriptions`兼容 OpenAI Whisper API 标准,可直接用 OpenAI SDK 接入。@@ -466,7 +472,7 @@ curl -X POST http://localhost:8899/v1/audio/transcriptions \-F "[email protected]" -F "model=fun-asr-nano" -F "response_format=verbose_json"```-### 3.5 协议三:WebSocket — `ws://host:port/ws`+### 5.5 协议三:WebSocket — `ws://host:port/ws`离线服务的 WebSocket 接口,发送完整音频后获取结果。STOP 时自动进行说话人聚类,结果中包含 `spk` 字段。@@ -524,7 +530,7 @@ asyncio.run(offline_ws("audio.wav"))## 6. 流式语音识别服务-### 4.1 服务架构+### 6.1 服务架构```客户端(麦克风/音频流) serve_realtime_ws.py@@ -535,7 +541,7 @@ asyncio.run(offline_ws("audio.wav"))│ ┌────┴─────────────────────────┐│ │ 实时循环: ││ │ ├─ 动态 VAD(60ms chunk) │- │ │ ├─ 检测到端点 → vLLM 解码 │+ │ │ ├─ 检测到端点 → vLLM 解码 ││ │ ├─ 未结束 → partial 预览 ││ │ └─ 说话人流式分配 ││ └────┬─────────────────────────┘@@ -550,14 +556,14 @@ asyncio.run(offline_ws("audio.wav"))- 流式说话人分配 + STOP 时全局重聚类- 首字延迟 ~480ms-### 4.2 启动服务+### 6.2 启动服务```bashCUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/serve_realtime_ws.py \--port 10095 --language 中文 --hotword-file 热词列表```-### 4.3 WebSocket 协议+### 6.3 WebSocket 协议**连接**:`ws://host:10095`@@ -588,7 +594,7 @@ Client Server│── START ───────→││←─ started ──────││── [audio] ─────→│- │←─ {partial} ────│+ │←─ {partial} ────│ # partial 的原理是注意事项见 6.5│── [audio] ─────→││←─ {sentences+partial} ─│ (VAD 切了一句)│── STOP ────────→│@@ -596,7 +602,7 @@ Client Server│←─ stopped ─────│```-### 4.4 客户端调用+### 6.4 客户端调用**Python CLI**:```bash@@ -634,6 +640,40 @@ async def stream(audio_path):asyncio.run(stream("audio.wav"))```+### 6.5 partial 预览机制与长句特性++**partial 是什么、怎么产生的**+流式服务在用户说话过程中会周期性地(`serve_realtime_ws.py` 默认 `decode_interval≈0.48s`)对"当前这句话从句首到现在"的音频解码一次,输出**临时文字**(即协议里的 `partial` 字段,可被后续刷新覆盖),直到 VAD 判定句尾才锁定进 `sentences`。这让用户边说边看到字。++> 注:`serve_vllm.py`(§5)的 `/ws` **没有 partial**、只在句尾返回;要实时预览请用 `serve_realtime_ws.py`。++**原理:为什么每次 partial 都从句首整段重编**+Fun-ASR-Nano 的声学编码器(SenseVoice)是**全上下文、非流式**编码器——每一帧的表示都依赖整段音频的前后文。当这句话又往下说了一截、音频变长时,先前那些帧的上下文随之改变,**之前算出的编码不再成立**,因此无法像流式 / 因果编码器那样"缓存历史、只算新增帧",只能把"句首→当前"的整段重新过一遍编码器。++**由此带来的特性:长句的 partial 会越来越慢(O(L²))**+正因每次都从句首重编,一句话越长,单次 partial 要编的音频越长、刷新次数也越多——**总编码量随句长二次增长**。实测一句约 29s 的连续发言会被完整重编十余次,单次 encoder 耗时从几十毫秒爬到数百毫秒。(§4 SDK 流式"每个 chunk 包含从头到当前的全部音频"是同一机制,长文件同理。)++**使用建议**+- 正常对话语音有自然停顿,VAD 会把它切成一句句较短的语音,每句 partial 的开销自然受限,**通常无需关注**。+- 只有**超长、不停顿的连续语音**(如长篇朗读)会让单句不断变长、partial 预览逐渐变慢——这是全上下文编码器的固有特性,**不是配置问题**。若你的场景确有此类音频且对预览延迟敏感,可在代码侧限制 partial 的编码窗口(如只编最近若干秒);这属于**代码改动、非配置项**,且不影响锁定句(仍走完整音频、最终转写不变)。++### 6.6 说话人分离(SPK)的代价与关闭++`serve_realtime_ws.py` 启动时**默认加载** SPK 模型(目前写死为 `iic/speech_eres2netv2_sv_zh-cn_16k-common`),并在流式中对每个 VAD 完成句调用一次说话人分配。需要注意:++- **Fun-ASR-Nano 上 SPK 效果有限**(见 #2944),多数实时 ASR 场景并不需要说话人分离。+- **流式 SPK 代价高且随会话变长**:每句对**全部历史 embedding** 做一次全量重聚类(**O(N²)**,会话越长每句越贵),且**同步阻塞事件循环**;而会话结束时还会**全量重聚一遍**,流式期间每句的聚类结果会被最终结果覆盖——对最终输出而言属于重复计算。长会话 + 高并发下尤其明显。+- **目前关闭需改代码**:spk_model 在 `serve_realtime_ws.py` 中默认加载、且写死,没有开关.+- **建议**:不需要说话人分离时不加载 spk_model;确需 diarization 时,从最终结果取标签,或改用 Paraformer + cam++ 方案。++### 6.7 生产并发与多进程部署++`serve_realtime_ws.py` 是**单 asyncio 事件循环**服务:`decode()`(定时 partial)与 `add_audio()`(VAD 句尾触发解码)都**同步阻塞**整个事件循环——任一路在解码时,其余连接全部暂停收发。因此:++- **单进程并发墙来自事件循环串行,不是 GPU 算力**。+- **目前扩展可行方案 = 单卡多个独立进程 + CUDA MPS + nginx 轮询**:每个进程有独立的 GIL 与 CUDA 上下文,绕开单循环串行;MPS 让多进程真正并发共享 GPU、填满空闲算力;nginx 在多个 WebSocket 后端间轮询。超过单卡余量后,再横向加卡(每卡一实例 + 负载均衡)。+- **可持续并发没有通用的"支持 N 路"数字**:决定上限的不是在线连接数,而是**同一时刻有多少路正在"说话"**——每路只要在说,就每约 1 秒触发一次 partial 解码,全部串行在那个单事件循环上。它主要随两点变化:**① 停顿 / 静音占比**——真实一问一答中用户大半时间在听、不出声,同时解码的路数远少于在线连接数;连续独白则几乎每路都在持续解码,负载高得多。**② 句长**——句子越长,单次 partial 的编码越贵(见 6.5 的 O(L²)),同样路数下负载更高。因此同一套"单卡 L20 + 多进程 + MPS",在接近真实 turn-taking 的负载下可稳定支撑数十路,而在长句、连续不停顿的负载下会显著更低。**任何"支持 X 路"的数字都只在它被测出来的那种话务下成立**——请按自己的真实话务(句长、停顿、是否连续说话)压测确定,别把别处测出的某个并发数当成自己的规格。+---## 7. 动态 VADdiff --git a/docs/vllm_guide_zh_v2.md b/docs/vllm_guide_zh_v2.mdindex 63f493dfb..32cc640f9 100644--- a/docs/vllm_guide_zh_v2.md+++ b/docs/vllm_guide_zh_v2.md@@ -53,7 +53,7 @@ cd /path/to/FunASR && pip install -e .**硬件**:GPU ≥ 8GB VRAM,CUDA ≥ 11.8。推荐 16GB+。-为什么不要单独执行 pip install torch torchaudio? torch/torchaudio/torchvision 的版本由 vLLM 版本决定—— 每个大版本会一起升级(见 vLLM 的 requirements/cuda.txt)。手动安装会拉到最新 wheel,可能是为比你驱动更新的 CUDA runtime 编译的;PyTorch 会在 CUDA 初始化阶段、FunASR 启动前就报 The NVIDIA driver on your system is too old。让 vLLM 统一钉定这三件套即可避免。若仍遇到该错误,请安装其 CUDA 构建与 nvidia-smi 显示的 CUDA 匹配的 vLLM 版本(如 CUDA 12.x 用 vllm==0.19.1),或先升级 NVIDIA 驱动。+为什么不要单独执行 `pip install torch torchaudio` ? torch/torchaudio/torchvision 的版本由 vLLM 版本决定—— 每个大版本会一起升级(见 vLLM 的 [requirements/cuda.txt](https://github.com/vllm-project/vllm/blob/main/requirements/cuda.txt))。手动安装会拉到最新 wheel,可能是为比你驱动更新的 CUDA runtime 编译的;PyTorch 会在 CUDA 初始化阶段、FunASR 启动前就报 The NVIDIA driver on your system is too old。让 vLLM 统一钉定这三件套即可避免。若仍遇到该错误,请安装其 CUDA 构建与 nvidia-smi 显示的 CUDA 匹配的 vLLM 版本(如 CUDA 12.x 用 vllm==0.19.1),或先升级 NVIDIA 驱动。---@@ -77,12 +77,12 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ │ ▼ ││ │ Audio Embeddings ││ │ │ │-│ │ Text Prompt ──→ Tokenize ──→ Embed │+│ │ Text Prompt ──→ Tokenize ──→ Embed ││ │ (system/user/ │ ││ │ hotwords/language) │ ││ │ ▼ ││ │ [Concat Embeddings] │-│ └─────────────────────────────────┼─────────────┘ │+│ └─────────────────────────────────┼─────────────┘ ││ │ ││ ▼ EmbedsPrompt ││ ┌─────────────── vLLM Engine ────────────────────┐ │@@ -91,7 +91,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ │ KV Cache 管理 + CUDA Graph │ ││ │ Tensor Parallel (多卡) │ ││ │ │ │-│ │ Qwen3-0.6B / Llama-2B (LLM 解码) │ │+│ │ Qwen3-0.6B / Llama-2B (LLM 解码) │ ││ │ │ ││ └────────────────────┬───────────────────────────┘ ││ │ │@@ -99,8 +99,8 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ Generated Text ││ │ ││ ┌────────────────────┼──────────────────────────┐ │-│ │ (可选) CTC Decoder ──→ Forced Alignment │ │-│ │ ──→ 字级别时间戳 │ │+│ │ (可选) CTC Decoder ──→ Forced Alignment │ │+│ │ ──→ 字级别时间戳 │ ││ └───────────────────────────────────────────────┘ │└──────────────────────────────────────────────────────────────┘```@@ -128,7 +128,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:### 关键实现细节1. **权重分离**:从 `model.pt` 提取 LLM 权重,转为 HuggingFace 格式供 vLLM 加载-2. **EmbedsPrompt**:音频 embedding + 文本 embedding 拼接后作为 prompt embedding 送入 vLLM+2. **EmbedsPrompt**:直接把**已算好的 embedding 向量**(而非通常的 token ID)作为 prompt 送入 vLLM(开关 `enable_prompt_embeds=True`)。Fun-ASR-Nano 必须用它,因为音频经 adaptor 得到的是连续向量、不是 token,需把音频 embedding 与文本 embedding 在序列维拼接后整体送入 vLLM3. **use_low_frame_rate**:Fun-ASR-Nano 的 adaptor 输出需按公式截断到正确 token 数(一致性关键)4. **batch encode**:多条音频通过 `extract_fbank` → `audio_encoder` → `audio_adaptor` 一次前向5. **CTC 时间戳**:保留 encoder_out,生成文本后做 forced alignment 得到字级别时间@@ -149,7 +149,7 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:│ 阶段 1: 音频编码(PyTorch, 单 GPU) │├─────────────────────────────────────────────────────────────────────┤│ │-│ 音频文件列表 ──→ 分组(每 8 条)──→ Frontend(Fbank) │+│ 音频文件列表 ──→ 分组(每 8 条)──→ Frontend(Fbank) ││ │ │ ││ │ ▼ ││ │ SenseVoice Encoder │@@ -174,16 +174,16 @@ FunASR 的 vLLM 集成将 ASR 模型拆分为两部分独立运行:├─────────────────────────────────────────────────────────────────────┤│ ││ EmbedsPrompt × N ──→ vLLM Continuous Batching │-│ (PagedAttention + CUDA Graph) │+│ (PagedAttention + CUDA Graph) ││ │ ││ ▼ │-│ Generated token_ids × N │+│ Generated token_ids × N ││ │ ││ ▼ │-│ Decode + 后处理(去特殊标记、清洗) │+│ Decode + 后处理(去特殊标记、清洗) ││ │ ││ ▼ │-│ (可选) CTC Forced Alignment → 字级别时间戳 │+│ (可选) CTC Forced Alignment → 字级别时间戳 │└─────────────────────────────────────────────────────────────────────┘```@@ -273,8 +273,8 @@ python demo_vllm.py --input audio.wav --hotwords 张三 北京 --output results.│ 累积重编码(每个 chunk 包含从头到当前的全部音频)▼┌──────────────────────┐-│ Stage 1: 前 10 chunk │ ← 无 prev_text,批量生成-│ 找到稳定输出 │+│ Stage 1: 前 10 chunk │ ← 无 prev_text,批量生成+│ 找到稳定输出 │└──────────┬───────────┘▼┌──────────────────────┐@@ -302,6 +302,8 @@ for result in engine.streaming_generate("audio.wav", language="中文"):print(f"[{result['audio_duration_ms']:.0f}ms] 确认: {result['fixed_text']}")```+**注意:EmbedsPrompt 下不能用 `repetition_penalty`。** 此时 prompt 是 embedding 向量、没有对应的 token ID,而 `repetition_penalty` 要靠 prompt 的 token ID 在 logits 上给已出现的词降分;用在 EmbedsPrompt 上会**索引越界、触发 CUDA device-side assert**。+### 输出特性| 累积音频 | 输出质量 |@@ -315,7 +317,7 @@ for result in engine.streaming_generate("audio.wav", language="中文"):## 5. 离线语音识别服务-### 3.1 服务架构+### 5.1 服务架构```客户端 serve_vllm.py@@ -323,11 +325,11 @@ for result in engine.streaming_generate("audio.wav", language="中文"):│── HTTP/OpenAI/WebSocket ──────────────→││ ││ ┌────┴────────────────────────┐- │ │ 1. 接收完整音频文件 │- │ │ 2. 动态 VAD 分段(≤60s/段) │- │ │ 3. vLLM batch 推理所有段 │- │ │ 4. CTC 时间戳(逐字) │- │ │ 5. 说话人分离(可选) │+ │ │ 1. 接收完整音频文件 │+ │ │ 2. 动态 VAD 分段(≤60s/段) │+ │ │ 3. vLLM batch 推理所有段 │+ │ │ 4. CTC 时间戳(逐字) │+ │ │ 5. 说话人分离(可选) ││ └────┬────────────────────────┘│ ││←── JSON 结果 ─────────────────────────│@@ -340,7 +342,7 @@ for result in engine.streaming_generate("audio.wav", language="中文"):- 自动输出字级别时间戳- SPK 说话人分离默认关闭,客户端可开启-### 3.2 启动服务+### 5.2 启动服务```bashCUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/serve_vllm.py \@@ -349,7 +351,11 @@ CUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/--gpu-memory-utilization 0.5```-### 3.3 协议一:HTTP REST — `POST /asr`+> **关于 `CUDA_VISIBLE_DEVICES`**:这是[vllm的一个环境变量](https://docs.vllm.ai/en/v0.4.3/serving/env_vars.html) ,示例中的 `=0` 只是"用第 0 张卡"的示例值,**不是固定写法**,它选择本进程可见的 GPU(编号同 `nvidia-smi`),单卡机器也不需要设置。+>+> **单卡多实例**:0.6B / 1.7B 这类小模型一张卡可起多个实例,多进程可都指向同一张卡(如都 `=0`)+ MPS 共享;分卡则进程 A `=0`、B `=1`(见 §6.7)。++### 5.3 协议一:HTTP REST — `POST /asr`功能最全的接口,支持 SPK、时间戳、热词。@@ -413,7 +419,7 @@ const resp = await fetch("http://localhost:8899/asr", { method: "POST", body: foconst result = await resp.json();```-### 3.4 协议二:OpenAI Whisper 兼容 — `POST /v1/audio/transcriptions`+### 5.4 协议二:OpenAI Whisper 兼容 — `POST /v1/audio/transcriptions`兼容 OpenAI Whisper API 标准,可直接用 OpenAI SDK 接入。@@ -466,7 +472,7 @@ curl -X POST http://localhost:8899/v1/audio/transcriptions \-F "[email protected]" -F "model=fun-asr-nano" -F "response_format=verbose_json"```-### 3.5 协议三:WebSocket — `ws://host:port/ws`+### 5.5 协议三:WebSocket — `ws://host:port/ws`离线服务的 WebSocket 接口,发送完整音频后获取结果。STOP 时自动进行说话人聚类,结果中包含 `spk` 字段。@@ -524,7 +530,7 @@ asyncio.run(offline_ws("audio.wav"))## 6. 流式语音识别服务-### 4.1 服务架构+### 6.1 服务架构```客户端(麦克风/音频流) serve_realtime_ws.py@@ -535,7 +541,7 @@ asyncio.run(offline_ws("audio.wav"))│ ┌────┴─────────────────────────┐│ │ 实时循环: ││ │ ├─ 动态 VAD(60ms chunk) │- │ │ ├─ 检测到端点 → vLLM 解码 │+ │ │ ├─ 检测到端点 → vLLM 解码 ││ │ ├─ 未结束 → partial 预览 ││ │ └─ 说话人流式分配 ││ └────┬─────────────────────────┘@@ -550,14 +556,14 @@ asyncio.run(offline_ws("audio.wav"))- 流式说话人分配 + STOP 时全局重聚类- 首字延迟 ~480ms-### 4.2 启动服务+### 6.2 启动服务```bashCUDA_VISIBLE_DEVICES=0 python examples/industrial_data_pretraining/fun_asr_nano/serve_realtime_ws.py \--port 10095 --language 中文 --hotword-file 热词列表```-### 4.3 WebSocket 协议+### 6.3 WebSocket 协议**连接**:`ws://host:10095`@@ -588,7 +594,7 @@ Client Server│── START ───────→││←─ started ──────││── [audio] ─────→│- │←─ {partial} ────│+ │←─ {partial} ────│ # partial 的原理是注意事项见 6.5│── [audio] ─────→││←─ {sentences+partial} ─│ (VAD 切了一句)│── STOP ────────→│@@ -596,7 +602,7 @@ Client Server│←─ stopped ─────│```-### 4.4 客户端调用+### 6.4 客户端调用**Python CLI**:```bash@@ -634,6 +640,40 @@ async def stream(audio_path):asyncio.run(stream("audio.wav"))```+### 6.5 partial 预览机制与长句特性++**partial 是什么、怎么产生的**+流式服务在用户说话过程中会周期性地(`serve_realtime_ws.py` 默认 `decode_interval≈0.48s`)对"当前这句话从句首到现在"的音频解码一次,输出**临时文字**(即协议里的 `partial` 字段,可被后续刷新覆盖),直到 VAD 判定句尾才锁定进 `sentences`。这让用户边说边看到字。++> 注:`serve_vllm.py`(§5)的 `/ws` **没有 partial**、只在句尾返回;要实时预览请用 `serve_realtime_ws.py`。++**原理:为什么每次 partial 都从句首整段重编**+Fun-ASR-Nano 的声学编码器(SenseVoice)是**全上下文、非流式**编码器——每一帧的表示都依赖整段音频的前后文。当这句话又往下说了一截、音频变长时,先前那些帧的上下文随之改变,**之前算出的编码不再成立**,因此无法像流式 / 因果编码器那样"缓存历史、只算新增帧",只能把"句首→当前"的整段重新过一遍编码器。++**由此带来的特性:长句的 partial 会越来越慢(O(L²))**+正因每次都从句首重编,一句话越长,单次 partial 要编的音频越长、刷新次数也越多——**总编码量随句长二次增长**。实测一句约 29s 的连续发言会被完整重编十余次,单次 encoder 耗时从几十毫秒爬到数百毫秒。(§4 SDK 流式"每个 chunk 包含从头到当前的全部音频"是同一机制,长文件同理。)++**使用建议**+- 正常对话语音有自然停顿,VAD 会把它切成一句句较短的语音,每句 partial 的开销自然受限,**通常无需关注**。+- 只有**超长、不停顿的连续语音**(如长篇朗读)会让单句不断变长、partial 预览逐渐变慢——这是全上下文编码器的固有特性,**不是配置问题**。若你的场景确有此类音频且对预览延迟敏感,可在代码侧限制 partial 的编码窗口(如只编最近若干秒);这属于**代码改动、非配置项**,且不影响锁定句(仍走完整音频、最终转写不变)。++### 6.6 说话人分离(SPK)的代价与关闭++`serve_realtime_ws.py` 启动时**默认加载** SPK 模型(目前写死为 `iic/speech_eres2netv2_sv_zh-cn_16k-common`),并在流式中对每个 VAD 完成句调用一次说话人分配。需要注意:++- **Fun-ASR-Nano 上 SPK 效果有限**(见 #2944),多数实时 ASR 场景并不需要说话人分离。+- **流式 SPK 代价高且随会话变长**:每句对**全部历史 embedding** 做一次全量重聚类(**O(N²)**,会话越长每句越贵),且**同步阻塞事件循环**;而会话结束时还会**全量重聚一遍**,流式期间每句的聚类结果会被最终结果覆盖——对最终输出而言属于重复计算。长会话 + 高并发下尤其明显。+- **目前关闭需改代码**:spk_model 在 `serve_realtime_ws.py` 中默认加载、且写死,没有开关.+- **建议**:不需要说话人分离时不加载 spk_model;确需 diarization 时,从最终结果取标签,或改用 Paraformer + cam++ 方案。++### 6.7 生产并发与多进程部署++`serve_realtime_ws.py` 是**单 asyncio 事件循环**服务:`decode()`(定时 partial)与 `add_audio()`(VAD 句尾触发解码)都**同步阻塞**整个事件循环——任一路在解码时,其余连接全部暂停收发。因此:++- **单进程并发墙来自事件循环串行,不是 GPU 算力**。+- **目前扩展可行方案 = 单卡多个独立进程 + CUDA MPS + nginx 轮询**:每个进程有独立的 GIL 与 CUDA 上下文,绕开单循环串行;MPS 让多进程真正并发共享 GPU、填满空闲算力;nginx 在多个 WebSocket 后端间轮询。超过单卡余量后,再横向加卡(每卡一实例 + 负载均衡)。+- **可持续并发没有通用的"支持 N 路"数字**:决定上限的不是在线连接数,而是**同一时刻有多少路正在"说话"**——每路只要在说,就每约 1 秒触发一次 partial 解码,全部串行在那个单事件循环上。它主要随两点变化:**① 停顿 / 静音占比**——真实一问一答中用户大半时间在听、不出声,同时解码的路数远少于在线连接数;连续独白则几乎每路都在持续解码,负载高得多。**② 句长**——句子越长,单次 partial 的编码越贵(见 6.5 的 O(L²)),同样路数下负载更高。因此同一套"单卡 L20 + 多进程 + MPS",在接近真实 turn-taking 的负载下可稳定支撑数十路,而在长句、连续不停顿的负载下会显著更低。**任何"支持 X 路"的数字都只在它被测出来的那种话务下成立**——请按自己的真实话务(句长、停顿、是否连续说话)压测确定,别把别处测出的某个并发数当成自己的规格。+---## 7. 动态 VAD