[Feature] timestamps for TTS via a forced-aligner pooling (#4795)

Signed-off-by: wjinxu <1299461899@qq.com>
Co-authored-by: xurui <xurui1@modelbest.onaliyun.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-08-12 05:33:34 +00:00
1 parent a15b5b4bcd
commit 9b0df3909a
28 files changed
+850 -627

No files matched your search

+82 -6
View File
@@ -423,7 +423,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
def __init__(self, *args, **kwargs):
self.model_name = kwargs.pop("model_name", None)
self.forced_aligner_config: Any | None = kwargs.pop("forced_aligner_config", None)
# True when the server was launched with --forced-aligner (a pooling
# aligner stage is appended to the pipeline). Gates word_timestamps.
self.forced_aligner_enabled: bool = bool(kwargs.pop("forced_aligner_enabled", False))
super().__init__(*args, **kwargs)
self._init_speaker_storage()
@@ -2186,6 +2188,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
request_start_s: float | None = None,
include_sample_rate: bool = False,
usage_acc: SpeechOutputTokenCounter | None = None,
collect: dict | None = None,
):
"""Generate audio chunks for streaming response.
@@ -2218,6 +2221,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
usage_acc.observe(res)
audio_output, audio_key = self._extract_audio_output(res)
if audio_key is None:
# Stash the aligner's timestamps output for streaming callers.
if collect is not None and self._is_timestamps_output(res):
collect["aligner_res"] = res
continue
sr_raw = audio_output.get("sr")
@@ -2406,6 +2412,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
data = json.dumps(payload, separators=(",", ":"))
yield f"event: speech.audio.error\ndata: {data}\n\n"
@staticmethod
def _is_timestamps_output(res) -> bool:
"""True when ``res`` is the forced-aligner stage's terminal timestamps output."""
from vllm_omni.model_executor.stage_input_processors.forced_aligner import TIMESTAMPS_MODALITY
return getattr(res, "final_output_type", None) == TIMESTAMPS_MODALITY
@staticmethod
def _extract_audio_output(res) -> tuple[dict | None, str | None]:
"""Return (audio_output dict, audio key) or (None, None).
@@ -3332,11 +3345,20 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
stage0_params.extra_args = {}
stage0_params.extra_args.setdefault("tts_local_seed", int(default_seed))
# When word_timestamps is requested, also ask for the aligner stage's
# output so the orchestrator drives the request through the forced-aligner
# stage (final_stage_id extends to it). Harmless if no aligner stage exists.
output_modalities = ["audio"]
if getattr(request, "word_timestamps", False):
from vllm_omni.model_executor.stage_input_processors.forced_aligner import TIMESTAMPS_MODALITY
output_modalities.append(TIMESTAMPS_MODALITY)
generator = self.engine_client.generate(
prompt=prompt,
request_id=request_id,
sampling_params_list=sampling_params_list,
output_modalities=["audio"],
output_modalities=output_modalities,
)
self._track_ref_audio_artifact_warmup(
request_id,
@@ -3345,17 +3367,22 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
return request_id, generator, tts_params
async def _generate_pcm_chunks(self, generator, request_id: str, *, include_sample_rate: bool = False):
async def _generate_pcm_chunks(
self, generator, request_id: str, *, include_sample_rate: bool = False, collect: dict | None = None
):
"""Yield raw PCM byte chunks from the engine generator.
Delegates to ``_generate_audio_chunks`` with ``response_format="pcm"``.
Used by the WebSocket streaming handler and ``_iter_pcm_audio_bytes``.
``collect`` (when given) receives the forced-aligner stage's pooling
output under ``"aligner_res"`` for downstream word-timestamp extraction.
"""
async for chunk in self._generate_audio_chunks(
generator,
request_id,
response_format="pcm",
include_sample_rate=include_sample_rate,
collect=collect,
):
yield chunk
@@ -3375,6 +3402,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
request_id: str | None = None,
usage_out: list[SpeechTokenUsage] | None = None,
has_inline_ref_audio: bool | None = None,
collect: dict | None = None,
) -> tuple[bytes | str, str]:
# ``usage_out`` is an opt-in output channel: when a list is passed, the
# computed SpeechTokenUsage is appended to it. The return stays a
@@ -3398,9 +3426,20 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Non-streaming is FINAL_ONLY, so the stage-0 output carries the full
# token sequence; the counter records its length for output_tokens.
usage_acc = SpeechOutputTokenCounter()
audio_res: OmniRequestOutput | None = None
aligner_res: OmniRequestOutput | None = None
async for res in generator:
final_output = res
usage_acc.observe(res)
# The generator yields both the audio output (Code2Wav) and, with
# a forced-aligner stage, a timestamps output. Keep the audio res
# for the WAV and the aligner res for word timestamps.
if self._is_timestamps_output(res):
aligner_res = res
else:
_, audio_key = self._extract_audio_output(res)
if audio_key is not None:
audio_res = res
if not is_moss:
continue
try:
@@ -3422,10 +3461,26 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if final_output is None:
raise ValueError("No output generated from the model.")
audio_output, audio_key = self._extract_audio_output(final_output)
# Extract audio from the audio-bearing res (not necessarily the last
# yielded one, which may be the aligner's timestamps output).
audio_source = audio_res if audio_res is not None else final_output
audio_output, audio_key = self._extract_audio_output(audio_source)
if audio_key is None:
raise ValueError("TTS model did not produce audio output.")
# Surface forced-aligner word timestamps to the caller (set as a
# response header) when requested and an aligner stage produced them.
if collect is not None and getattr(request, "word_timestamps", False):
from vllm_omni.utils.forced_aligner import extract_word_timestamps
ts = (
extract_word_timestamps(aligner_res, request.input, getattr(request, "language", None))
if aligner_res is not None
else None
)
if ts is not None:
collect["word_timestamps"] = ts
audio_tensor = audio_output[audio_key]
sr_raw = audio_output.get("sr", 24000)
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
@@ -3695,6 +3750,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
"/v1/audio/speech/stream path. Use session.config with "
"stream_audio=true and response_format='pcm'."
)
if request.word_timestamps and not self.forced_aligner_enabled:
# Fail loud instead of silently returning 200 with no timestamps header.
return self.create_error_response(
"word_timestamps=true requires the server to be launched with --forced-aligner."
)
if request.is_raw_audio_stream():
response_format, error = self._validate_speech_streaming_request(
@@ -3739,7 +3799,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
media_type="text/event-stream",
)
audio_bytes, media_type = await self._generate_audio_bytes(request, request_id=request_id)
collect: dict = {}
audio_bytes, media_type = await self._generate_audio_bytes(request, request_id=request_id, collect=collect)
total_ms = (time.perf_counter() - request_start_s) * 1000.0
logger.info(
"[SpeechE2E] request_id=%s stream=false status=ok total_ms=%.2f response_bytes=%d",
@@ -3747,7 +3808,22 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
total_ms,
len(audio_bytes) if isinstance(audio_bytes, (bytes, bytearray)) else len(str(audio_bytes)),
)
return Response(content=audio_bytes, media_type=media_type)
headers = {}
if collect.get("word_timestamps") is not None:
# Default ensure_ascii keeps the header latin-1 encodable (non-ASCII words \uXXXX-escaped).
ts_json = json.dumps(collect["word_timestamps"])
# Cap at 4 KB: oversized headers turn into opaque 502s at common reverse-proxy defaults.
if len(ts_json) <= 4096:
headers["X-Word-Timestamps"] = ts_json
else:
# Marker header so clients can tell an oversized alignment from no alignment.
headers["X-Word-Timestamps-Omitted"] = f"oversize; bytes={len(ts_json)}; limit=4096"
logger.warning(
"X-Word-Timestamps header omitted: %d bytes exceeds the 4 KB budget "
"(use the WebSocket streaming path for long transcripts)",
len(ts_json),
)
return Response(content=audio_bytes, media_type=media_type, headers=headers)
except asyncio.CancelledError:
total_ms = (time.perf_counter() - request_start_s) * 1000.0