[Edge][WP5] Add codec-token streaming mode with on-device decoding

* qwen3_tts_talker_only pipeline (single terminal LLM_AR stage,
  final_output_type "latent") + vllm_omni/deploy/qwen3_tts_talker_only.yaml;
  a terminal talker publishes its per-step codes.audio rows to the client
  (omni_client_multimodal_output_keys).
* /v1/audio/speech/stream: session.config.output_mode="codec_tokens" streams
  codec.start (JSON) + binary frames (<IHB seq/n_frames/flags + int16 rows,
  vllm_omni/entrypoints/openai/codec_stream.py) + codec.done; new input.cancel
  message aborts an in-flight generation for both codec and PCM sessions
  (single reader task + session inbox replaces direct socket reads); optional
  session.config.seed; audio.done gains "cancelled" only when it happened.
* serving_speech._generate_codec_chunks aligns the cumulative code tensor to
  output token ids (drops prefill placeholder/EOS rows) and emits deltas.
* TTS adapters: supports_codec_stream / codec_stream_spec (Qwen3-TTS: 16
  codebooks, 2048 ids, 12.5 Hz, 24 kHz, decoder qwen3_tts_tokenizer_v2_12hz).
* examples/online_serving/text_to_speech/qwen3_tts/edge_decoder_client.py
  decodes locally with Qwen3TTSTokenizerV2Decoder (ramp schedule, 72-frame
  context, cancel/reset), codec_parity_check.py and
  benchmarks/tts/codec_stream_e2e.py compare against the two-stage server.
* docs/serving/codec_token_streaming.md; CPU unit tests for the wire format,
  alignment, session config and handler (frames, unsupported adapter, cancel);
  L3 e2e tests/e2e/online_serving/test_qwen3_tts_codec_stream.py.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
tzhouamandClaude Fable 5.1 committed 2026-09-09 11:10:13 +08:00
1 parent 35e43b9983
commit 49a839ecf9
16 files changed
+1533 -6

No files matched your search

@@ -0,0 +1,129 @@
"""Wire format for codec-token streaming (server → on-device decoder).
Binary frame layout (little-endian):
header ``<IHB`` seq:uint32 n_frames:uint16 flags:uint8 (7 bytes)
body int16[n_frames * codebooks] row-major (frame-major)
Flags: ``FLAG_EOS`` (last frame of the utterance), ``FLAG_SEGMENT_END``
(sentence boundary inside a flush), ``FLAG_RESET`` (client must drop its
decoder state before consuming this frame). An EOS frame may carry
``n_frames == 0``.
Codebook ids are ``< 32768`` for every supported codec (Qwen3-TTS: 2048), so
int16 is lossless. Pure functions only; no engine imports.
"""
from __future__ import annotations
import struct
from typing import Any
import numpy as np
HEADER_FMT = "<IHB"
HEADER_SIZE = struct.calcsize(HEADER_FMT)
FLAG_EOS = 0x1
FLAG_SEGMENT_END = 0x2
FLAG_RESET = 0x4
MAX_FRAMES_PER_PACKET = 0xFFFF
CODEC_STREAM_VERSION = 1
def pack_codec_frame(
seq: int,
codes: Any,
*,
eos: bool = False,
segment_end: bool = False,
reset: bool = False,
codebooks: int | None = None,
) -> bytes:
"""Pack ``codes`` (``[n_frames, codebooks]`` ints, or ``None``/empty) into one binary frame."""
if codes is None:
arr = np.zeros((0, codebooks or 0), dtype=np.int16)
else:
if hasattr(codes, "detach"):
codes = codes.detach().cpu().numpy()
arr = np.asarray(codes)
if arr.ndim == 1:
arr = arr.reshape(1, -1) if arr.size else arr.reshape(0, codebooks or 0)
if arr.ndim != 2:
raise ValueError(f"codes must be 2-D [n_frames, codebooks], got shape {arr.shape}")
if arr.size and (arr.min() < 0 or arr.max() > np.iinfo(np.int16).max):
raise ValueError("codec ids must fit in int16")
arr = arr.astype("<i2", copy=False)
n_frames = int(arr.shape[0])
if n_frames > MAX_FRAMES_PER_PACKET:
raise ValueError(f"too many frames for one packet: {n_frames}")
flags = (FLAG_EOS if eos else 0) | (FLAG_SEGMENT_END if segment_end else 0) | (FLAG_RESET if reset else 0)
return struct.pack(HEADER_FMT, int(seq) & 0xFFFFFFFF, n_frames, flags) + arr.tobytes(order="C")
def unpack_codec_frame(buf: bytes, codebooks: int) -> tuple[int, int, int, np.ndarray]:
"""Inverse of :func:`pack_codec_frame`: ``(seq, n_frames, flags, int16[n_frames, codebooks])``."""
if len(buf) < HEADER_SIZE:
raise ValueError("codec frame shorter than its header")
seq, n_frames, flags = struct.unpack(HEADER_FMT, buf[:HEADER_SIZE])
body = buf[HEADER_SIZE:]
expected = n_frames * codebooks * 2
if len(body) != expected:
raise ValueError(f"codec frame body has {len(body)} bytes, expected {expected} for {n_frames}x{codebooks}")
arr = (
np.frombuffer(body, dtype="<i2").reshape(n_frames, codebooks)
if n_frames
else np.zeros((0, codebooks), dtype=np.int16)
)
return seq, n_frames, flags, arr
def align_codec_rows(codes_cum: Any, token_ids_cum: list[int], codebook_size: int) -> np.ndarray:
"""Keep the codec rows that correspond to real codebook-0 tokens.
Mirrors the talker's full-payload filter: rows are tail-aligned to the
output token ids, the prefill placeholder row (and any row whose token is
not a codebook id, e.g. EOS) is dropped, and rows with out-of-range ids
are dropped. Returns ``int64[n, codebooks]`` (possibly empty).
"""
if codes_cum is None:
return np.zeros((0, 0), dtype=np.int64)
if hasattr(codes_cum, "detach"):
codes_cum = codes_cum.detach().cpu().numpy()
arr = np.asarray(codes_cum)
if arr.ndim != 2 or arr.size == 0:
return np.zeros((0, arr.shape[1] if arr.ndim == 2 else 0), dtype=np.int64)
ids = list(token_ids_cum)
while ids and ids[-1] == -1:
ids.pop()
n = min(arr.shape[0], len(ids))
if n <= 0:
return arr[:0].astype(np.int64)
rows = arr[-n:]
toks = np.asarray(ids[-n:])
tok_ok = (toks >= 0) & (toks < codebook_size)
row_ok = (rows.min(axis=1) >= 0) & (rows.max(axis=1) < codebook_size)
return rows[tok_ok & row_ok].astype(np.int64)
def codec_start_message(
*,
utterance_index: int,
sentence_index: int,
sentence_text: str,
spec: dict[str, Any],
model: str | None,
) -> dict[str, Any]:
return {
"type": "codec.start",
"version": CODEC_STREAM_VERSION,
"utterance_index": utterance_index,
"sentence_index": sentence_index,
"sentence_text": sentence_text,
"model": model,
"codebooks": int(spec["codebooks"]),
"codebook_size": int(spec["codebook_size"]),
"frame_rate_hz": float(spec["frame_rate_hz"]),
"sample_rate": int(spec["sample_rate"]),
"decoder_id": spec.get("decoder_id"),
"header_format": HEADER_FMT,
}
@@ -578,9 +578,26 @@ class StreamingSpeechSessionConfig(BaseModel):
"frames (existing behavior)."
),
)
seed: int | None = Field(default=None, description="Random seed forwarded to each utterance request.")
output_mode: Literal["pcm", "codec_tokens"] = Field(
default="pcm",
description=(
"'pcm' streams decoded audio. 'codec_tokens' streams the talker's codec frames "
"(binary frames described by a 'codec.start' message) for decoding on the client "
"device; requires a talker-only deployment (e.g. deploy config qwen3_tts_talker_only.yaml), "
"stream_audio=true, response_format='pcm' and word_timestamps=false."
),
)
@model_validator(mode="after")
def validate_streaming_constraints(self) -> "StreamingSpeechSessionConfig":
if self.output_mode == "codec_tokens":
if not self.stream_audio:
raise ValueError("output_mode='codec_tokens' requires stream_audio=true.")
if self.word_timestamps:
raise ValueError("output_mode='codec_tokens' does not support word_timestamps.")
if self.response_format != "pcm":
raise ValueError("output_mode='codec_tokens' requires response_format='pcm'.")
if self.stream_audio:
if self.response_format != "pcm":
raise ValueError(
@@ -3251,6 +3251,77 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
):
yield chunk
@staticmethod
def _extract_codec_output(res) -> Any:
"""Return the cumulative ``codes.audio`` tensor from an engine output, or ``None``."""
outputs = getattr(res, "outputs", None)
if not outputs:
return None
mm = getattr(outputs[0], "multimodal_output", None)
if mm is None:
return None
getter = mm.get if hasattr(mm, "get") else None
codes = getter("codes") if getter else None
if codes is None:
return None
if hasattr(codes, "get"):
return codes.get("audio")
return None
async def _generate_codec_chunks(
self,
generator,
request_id: str,
*,
tts_params: dict[str, Any] | None = None,
min_frames: int = 1,
):
"""Yield ``(codes[int64, n, codebooks], eos)`` deltas from a talker-only pipeline.
The AR stage publishes the *cumulative* ``codes.audio`` tensor on every
step (``omni_client_multimodal_output_keys``); this generator aligns the
rows to the output token ids (dropping the prefill placeholder and the
EOS row) and emits only the new rows. The final item always carries
``eos=True`` (possibly with zero frames).
"""
from vllm_omni.entrypoints.openai.codec_stream import align_codec_rows
adapter = self._get_tts_adapter()
spec = getattr(adapter, "codec_stream_spec", None) or {}
codebook_size = int(spec.get("codebook_size", 2048))
usage_acc = SpeechOutputTokenCounter() if (adapter is not None and adapter.validates_generation) else None
token_ids: list[int] = []
sent = 0
finished = False
try:
async for res in generator:
if usage_acc is not None:
usage_acc.observe(res)
outputs = getattr(res, "outputs", None)
if outputs:
new_ids = getattr(outputs[0], "token_ids", None) or []
# DELTA outputs carry per-step ids; CUMULATIVE ones carry the whole prefix.
if len(new_ids) > len(token_ids) and list(new_ids[: len(token_ids)]) == token_ids:
token_ids = list(new_ids)
else:
token_ids.extend(int(t) for t in new_ids)
codes_cum = self._extract_codec_output(res)
done = bool(getattr(res, "finished", False))
if codes_cum is not None:
aligned = align_codec_rows(codes_cum, token_ids, codebook_size)
delta = aligned[sent:]
if delta.shape[0] >= min_frames or (done and delta.shape[0] > 0):
sent = int(aligned.shape[0])
yield delta, done
if done:
finished = True
if done and not finished:
finished = True
yield None, True
finally:
if usage_acc is not None and tts_params is not None and finished:
self._validate_tts_generation(tts_params, usage_acc)
async def _iter_pcm_audio_bytes(self, request: OpenAICreateSpeechRequest):
"""Yield raw PCM bytes for a speech request as soon as chunks are decoded."""
request_id, generator, tts_params = await self._prepare_speech_generation(request)
@@ -53,6 +53,7 @@ Protocol:
import asyncio
import base64
import json
from collections import deque
from contextlib import aclosing
from fastapi import WebSocket, WebSocketDisconnect
@@ -76,6 +77,54 @@ _MAX_CONFIG_MESSAGE_SIZE = 4 * 1024 * 1024 # allow large ref_audio payloads
_MAX_INPUT_TEXT_MESSAGE_SIZE = 128 * 1024
_DISCONNECT = object()
class _SessionInbox:
"""Single-reader message queue for one WebSocket session.
``pump`` is the only coroutine that calls ``websocket.receive_text()``;
messages (or a disconnect marker) are queued and consumed by the session
loop or, during a generation, by ``_iter_with_cancel``.
"""
def __init__(self) -> None:
self._queue: asyncio.Queue[object] = asyncio.Queue()
self._replay: deque[str] = deque()
async def pump(self, websocket: WebSocket) -> None:
try:
while True:
raw = await websocket.receive_text()
await self._queue.put(raw)
except (WebSocketDisconnect, RuntimeError):
await self._queue.put(_DISCONNECT)
except asyncio.CancelledError:
raise
async def get(self, timeout: float | None) -> str:
if self._replay:
return self._replay.popleft()
item = await asyncio.wait_for(self._queue.get(), timeout=timeout)
if item is _DISCONNECT:
raise WebSocketDisconnect(code=1006)
return item # type: ignore[return-value]
async def peek_control(self) -> str:
"""Wait for the next message; classify cancel/disconnect, replay the rest later."""
item = await self._queue.get()
if item is _DISCONNECT:
return "disconnect"
try:
msg = json.loads(item) if isinstance(item, str) and item else {}
except json.JSONDecodeError:
msg = {}
if isinstance(msg, dict) and msg.get("type") == "input.cancel":
return "cancel"
self._replay.append(item) # type: ignore[arg-type]
return "other"
class OmniStreamingSpeechHandler:
"""Handles WebSocket sessions for streaming text-input TTS.
@@ -116,14 +165,17 @@ class OmniStreamingSpeechHandler:
config: StreamingSpeechSessionConfig | None = None
text_parts: list[str] = []
utterance_index = 0
# One reader task owns ``websocket.receive_text()`` for the whole
# session; every consumer reads from the inbox instead. This is what
# lets a generation loop notice ``input.cancel`` (or a disconnect)
# while it streams, without cancelling a socket receive mid-flight.
inbox = _SessionInbox()
reader = asyncio.ensure_future(inbox.pump(websocket))
try:
while True:
try:
raw = await asyncio.wait_for(
websocket.receive_text(),
timeout=self._config_timeout if config is None else self._idle_timeout,
)
raw = await inbox.get(timeout=self._config_timeout if config is None else self._idle_timeout)
except asyncio.TimeoutError:
if config is None:
await self._send_error(websocket, "Timeout waiting for session.config")
@@ -180,6 +232,7 @@ class OmniStreamingSpeechHandler:
full_text,
utterance_index=utterance_index,
sentence_index=0,
inbox=inbox,
)
total_sentences = 1
@@ -192,6 +245,12 @@ class OmniStreamingSpeechHandler:
)
utterance_index += 1
elif msg_type == "input.cancel":
# Nothing is streaming at this point (cancels that arrive
# during generation are handled in ``_iter_with_cancel``).
text_parts.clear()
await websocket.send_json({"type": "input.cancelled", "utterance_index": utterance_index})
elif msg_type == "session.close":
await websocket.close()
return
@@ -210,6 +269,9 @@ class OmniStreamingSpeechHandler:
await self._send_error(websocket, f"Internal error: {e}")
except Exception:
logger.debug("Failed to send error to streaming speech client", exc_info=True)
finally:
if not reader.done():
reader.cancel()
async def _parse_message(self, websocket: WebSocket, raw: str) -> dict | None:
"""Decode one client message, or report why it was rejected.
@@ -257,6 +319,58 @@ class OmniStreamingSpeechHandler:
return config
async def _iter_with_cancel(
self,
websocket: WebSocket,
stream,
request_id: str,
inbox: "_SessionInbox | None",
):
"""Yield items from ``stream`` while watching the session inbox.
``input.cancel`` aborts the engine request and ends the stream (the
``audio.done`` / ``codec.done`` message then carries ``cancelled``);
a disconnect raises ``WebSocketDisconnect`` like a plain send would;
any other message is left queued for the session loop.
"""
self._last_cancelled = False
if inbox is None:
async for item in stream:
yield item
return
next_task = asyncio.ensure_future(stream.__anext__())
msg_task = asyncio.ensure_future(inbox.peek_control())
try:
while True:
done, _ = await asyncio.wait({msg_task, next_task}, return_when=asyncio.FIRST_COMPLETED)
if msg_task in done:
kind = msg_task.result()
if kind == "disconnect":
next_task.cancel()
raise WebSocketDisconnect(code=1006)
if kind == "cancel":
self._last_cancelled = True
try:
await self._speech_service.engine_client.abort(request_id)
except Exception:
logger.debug("Failed to abort request %s on input.cancel", request_id, exc_info=True)
next_task.cancel()
return
msg_task = asyncio.ensure_future(inbox.peek_control())
if next_task not in done:
continue
if next_task in done:
try:
item = next_task.result()
except StopAsyncIteration:
return
yield item
next_task = asyncio.ensure_future(stream.__anext__())
finally:
for task in (msg_task, next_task):
if not task.done():
task.cancel()
async def _generate_and_send(
self,
websocket: WebSocket,
@@ -265,6 +379,7 @@ class OmniStreamingSpeechHandler:
*,
utterance_index: int,
sentence_index: int,
inbox: "_SessionInbox | None" = None,
) -> None:
"""Generate audio for a single sentence and send it over WebSocket.
@@ -272,6 +387,18 @@ class OmniStreamingSpeechHandler:
``sentence_index`` its position inside that flush.
"""
response_format = config.response_format or "wav"
self._last_cancelled = False
if getattr(config, "output_mode", "pcm") == "codec_tokens":
await self._generate_and_send_codec(
websocket,
config,
sentence_text,
utterance_index=utterance_index,
sentence_index=sentence_index,
inbox=inbox,
)
return
# Reject unmet word-timestamps preconditions early with a clear reason.
if config.word_timestamps:
@@ -308,6 +435,7 @@ class OmniStreamingSpeechHandler:
ref_text=config.ref_text,
x_vector_only_mode=config.x_vector_only_mode,
speaker_embedding=config.speaker_embedding,
seed=config.seed,
stream=config.stream_audio,
word_timestamps=config.word_timestamps,
)
@@ -352,7 +480,7 @@ class OmniStreamingSpeechHandler:
tts_params=tts_params,
)
) as stream:
async for chunk in stream:
async for chunk in self._iter_with_cancel(websocket, stream, request_id, inbox):
total_bytes += len(chunk)
await websocket.send_bytes(chunk)
else:
@@ -388,11 +516,116 @@ class OmniStreamingSpeechHandler:
"sentence_index": sentence_index,
"total_bytes": total_bytes,
"error": generation_failed,
# Only present when a client input.cancel stopped the stream
# (keeps the existing audio.done contract unchanged otherwise).
**({"cancelled": True} if getattr(self, "_last_cancelled", False) else {}),
}
)
except Exception:
logger.debug("Failed to send audio.done for sentence %d", sentence_index, exc_info=True)
async def _generate_and_send_codec(
self,
websocket: WebSocket,
config: StreamingSpeechSessionConfig,
sentence_text: str,
*,
utterance_index: int,
sentence_index: int,
inbox: "_SessionInbox | None" = None,
) -> None:
"""Stream the talker's codec frames (no server-side decoding).
Protocol: ``codec.start`` (JSON, codec description) → binary frames
(``codec_stream.pack_codec_frame``) → ``codec.done``. Requires a
talker-only deployment and an adapter with ``supports_codec_stream``.
"""
from vllm_omni.entrypoints.openai.codec_stream import codec_start_message, pack_codec_frame
adapter = self._speech_service._get_tts_adapter()
if adapter is None or not getattr(adapter, "supports_codec_stream", False):
await self._send_error(websocket, "output_mode='codec_tokens' is not supported by the loaded TTS model.")
return
spec = dict(adapter.codec_stream_spec)
request = OpenAICreateSpeechRequest(
input=sentence_text,
model=config.model,
voice=config.voice,
task_type=config.task_type,
language=config.language,
instructions=config.instructions,
response_format="pcm",
speed=config.speed,
max_new_tokens=config.max_new_tokens,
non_streaming_mode=config.non_streaming_mode,
ref_audio=config.ref_audio,
ref_text=config.ref_text,
x_vector_only_mode=config.x_vector_only_mode,
speaker_embedding=config.speaker_embedding,
seed=config.seed,
stream=True,
)
await websocket.send_json(
codec_start_message(
utterance_index=utterance_index,
sentence_index=sentence_index,
sentence_text=sentence_text,
spec=spec,
model=config.model,
)
)
total_frames = 0
seq = 0
generation_failed = False
request_id = None
eos_sent = False
try:
request_id, generator, tts_params = await self._speech_service._prepare_speech_generation(request)
async with aclosing(
self._speech_service._generate_codec_chunks(generator, request_id, tts_params=tts_params)
) as stream:
async for codes, eos in self._iter_with_cancel(websocket, stream, request_id, inbox):
n = 0 if codes is None else int(codes.shape[0])
total_frames += n
await websocket.send_bytes(pack_codec_frame(seq, codes, eos=eos, codebooks=int(spec["codebooks"])))
seq += 1
eos_sent = eos_sent or eos
except WebSocketDisconnect:
if request_id is not None:
try:
await self._speech_service.engine_client.abort(request_id)
except Exception:
logger.debug("Failed to abort codec stream request %s", request_id, exc_info=True)
raise
except Exception as e:
generation_failed = True
logger.error("Codec stream failed for utterance %d: %s", utterance_index, e)
await self._send_error(
websocket, f"Codec stream failed for utterance {utterance_index}: {e}", partial_audio=total_frames > 0
)
finally:
cancelled = bool(getattr(self, "_last_cancelled", False))
if not eos_sent and not generation_failed:
try:
await websocket.send_bytes(pack_codec_frame(seq, None, eos=True, codebooks=int(spec["codebooks"])))
seq += 1
except Exception:
logger.debug("Failed to send terminal codec frame", exc_info=True)
try:
await websocket.send_json(
{
"type": "codec.done",
"utterance_index": utterance_index,
"sentence_index": sentence_index,
"total_frames": total_frames,
"seq_last": seq - 1,
"error": generation_failed,
"cancelled": cancelled,
}
)
except Exception:
logger.debug("Failed to send codec.done", exc_info=True)
async def _stream_audio_with_alignments(
self,
*,
@@ -169,6 +169,13 @@ class TTSModelAdapter(ABC):
#: Target sample rates validated for this adapter's output path. An empty
#: set means that the adapter does not expose per-request resampling.
supported_output_sample_rates: ClassVar[frozenset[int]] = frozenset()
#: Whether the model's talker can be served alone and its codec frames
#: streamed to a client-side decoder (``output_mode="codec_tokens"``).
supports_codec_stream: ClassVar[bool] = False
#: Codec description sent in ``codec.start`` when ``supports_codec_stream``:
#: ``codebooks``, ``codebook_size``, ``frame_rate_hz``, ``sample_rate``,
#: ``decoder_id`` and ``eos_token_id``.
codec_stream_spec: ClassVar[dict[str, Any]] = {}
max_new_tokens_min = 1
@@ -44,6 +44,17 @@ class Qwen3TTSAdapter(ARTTSAdapter):
stage_keys = frozenset({"qwen3_tts"})
name = "qwen3_tts"
supported_output_sample_rates = frozenset({8000, 24000})
# Talker-only deployments (qwen3_tts_talker_only.yaml) stream 16-codebook
# frames at 12.5 Hz for on-device decoding with Qwen3TTSTokenizerV2Decoder.
supports_codec_stream = True
codec_stream_spec = {
"codebooks": 16,
"codebook_size": 2048,
"frame_rate_hz": 12.5,
"sample_rate": 24000,
"decoder_id": "qwen3_tts_tokenizer_v2_12hz",
"eos_token_id": 2150,
}
def _get_model_variant(self) -> str | None:
"""Return the task supported by the loaded Qwen3-TTS checkpoint.