[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:
1 parent
35e43b9983
commit
49a839ecf9
16 files changed
+1533
-6
No files matched your search
@@ -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,
|
||||
*,
|
||||
|
||||
Reference in new issue
Block a user