[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:
28 files changed
+850
-627
No files matched your search
@@ -237,9 +237,8 @@ class OmniServeCommand(CLISubcommand):
|
||||
"VoiceDesign, or Base, while diffusion models may use it to select "
|
||||
"task-specific weights. If omitted, the model default is used.",
|
||||
)
|
||||
# Forced aligner / word timestamps. --forced-aligner is the opt-in
|
||||
# toggle; heavier knobs (gpu_memory_utilization, dtype, max_model_len)
|
||||
# live in the deploy YAML passed via --forced-aligner-config.
|
||||
# Forced aligner / word timestamps. Either flag opts in (--forced-aligner-config
|
||||
# alone works when its YAML sets the model); heavier knobs live in that YAML.
|
||||
omni_config_group.add_argument(
|
||||
"--forced-aligner",
|
||||
type=str,
|
||||
@@ -260,6 +259,13 @@ class OmniServeCommand(CLISubcommand):
|
||||
"flag, when set, overrides the YAML model field."
|
||||
),
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--forced-aligner-device",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Device(s) for the forced-aligner stage (e.g. '2'). Defaults to "
|
||||
"sharing an existing stage's GPU when unset.",
|
||||
)
|
||||
omni_config_group.add_argument(
|
||||
"--deploy-config",
|
||||
type=str,
|
||||
|
||||
@@ -1127,7 +1127,11 @@ async def omni_init_app_state(
|
||||
state.openai_serving_models,
|
||||
request_logger=request_logger,
|
||||
model_name=model_name,
|
||||
forced_aligner_config=build_forced_aligner_config(args),
|
||||
forced_aligner_enabled=build_forced_aligner_config(
|
||||
getattr(args, "forced_aligner", None),
|
||||
getattr(args, "forced_aligner_config", None),
|
||||
)
|
||||
is not None,
|
||||
)
|
||||
|
||||
# Warm up speech pipeline (CUDA Graph capture, torch.compile) so the first
|
||||
|
||||
@@ -161,10 +161,12 @@ class OpenAICreateSpeechRequest(BaseModel):
|
||||
word_timestamps: bool = Field(
|
||||
default=False,
|
||||
description=(
|
||||
"When true, the server runs a shared forced aligner alongside the streamed "
|
||||
"audio and emits per-chunk word timestamps. Requires the server to be "
|
||||
"launched with --forced-aligner pointing at an aligner model. No effect "
|
||||
"when streaming is off."
|
||||
"When true, non-streaming responses carry per-word timestamps in the "
|
||||
"X-Word-Timestamps header (JSON list of {word, start_ms, end_ms}, "
|
||||
"ASCII-escaped; replaced by X-Word-Timestamps-Omitted past 4 KB). "
|
||||
"Requires the server to be launched with --forced-aligner (400 otherwise). "
|
||||
"Not supported with stream=true; for streaming use the WebSocket "
|
||||
"/v1/audio/speech/stream path."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -61,8 +61,7 @@ from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
StreamingSpeechSessionConfig,
|
||||
)
|
||||
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
|
||||
from vllm_omni.utils.forced_aligner import ForcedAlignerLoadError
|
||||
from vllm_omni.utils.forced_aligner import align as forced_align
|
||||
from vllm_omni.utils.forced_aligner import extract_word_timestamps
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -273,7 +272,7 @@ class OmniStreamingSpeechHandler:
|
||||
|
||||
# Reject unmet word-timestamps preconditions early with a clear reason.
|
||||
if config.word_timestamps:
|
||||
if self._speech_service.forced_aligner_config is None:
|
||||
if not self._speech_service.forced_aligner_enabled:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"word_timestamps=true but the server was launched without "
|
||||
@@ -285,7 +284,8 @@ class OmniStreamingSpeechHandler:
|
||||
await self._send_error(
|
||||
websocket,
|
||||
"word_timestamps=true requires stream_audio=true and "
|
||||
"response_format='pcm' (the aligner consumes raw PCM).",
|
||||
"response_format='pcm' (timestamps ride the per-sentence "
|
||||
"PCM audio.chunk stream).",
|
||||
)
|
||||
return
|
||||
|
||||
@@ -395,19 +395,20 @@ class OmniStreamingSpeechHandler:
|
||||
) -> int:
|
||||
"""Stream PCM as JSON ``audio.chunk`` frames, aligned per sentence.
|
||||
|
||||
Forward each PCM chunk live (``timestamps: null``) while buffering the
|
||||
sentence audio, then run the forced aligner once over the whole
|
||||
sentence and emit a final empty-audio ``audio.chunk`` with the word
|
||||
timestamps. On aligner failure timestamps is ``null``; for silence it
|
||||
is ``[]`` (audio always flows regardless).
|
||||
Forward each PCM chunk live (``timestamps: null``). The forced-aligner
|
||||
pipeline stage (appended when the server is launched with
|
||||
``--forced-aligner``) consumes the synthesized audio internally and its
|
||||
pooling output rides the same generator, so once the audio finishes we
|
||||
pull the word timestamps straight off that aligner output and emit a
|
||||
final empty-audio ``audio.chunk`` carrying them. Timestamps is ``null``
|
||||
when the aligner produced none; audio always flows regardless.
|
||||
"""
|
||||
aligner_config = self._speech_service.forced_aligner_config
|
||||
assert aligner_config is not None # gated by the precondition check
|
||||
|
||||
sentence_audio = bytearray()
|
||||
audio_bytes_seen = 0
|
||||
total_bytes = 0
|
||||
sample_rate = _PCM_SAMPLE_RATE
|
||||
chunk_id = 0
|
||||
# Receives the aligner stage's pooling output from the generator.
|
||||
collect: dict = {}
|
||||
|
||||
async def send_chunk(
|
||||
chunk: bytes,
|
||||
@@ -437,62 +438,30 @@ class OmniStreamingSpeechHandler:
|
||||
generator,
|
||||
request_id,
|
||||
include_sample_rate=True,
|
||||
collect=collect,
|
||||
)
|
||||
) as stream:
|
||||
async for chunk, chunk_sample_rate in stream:
|
||||
sample_rate = chunk_sample_rate
|
||||
chunk_start_ms = int(round((len(sentence_audio) / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
sentence_audio.extend(chunk)
|
||||
chunk_end_ms = int(round((len(sentence_audio) / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
chunk_start_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
audio_bytes_seen += len(chunk)
|
||||
chunk_end_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
total_bytes += len(chunk)
|
||||
# Audio first, timestamps after the whole sentence is aligned.
|
||||
await send_chunk(chunk, chunk_sample_rate, None, chunk_start_ms, chunk_end_ms)
|
||||
|
||||
# Single alignment pass over the full sentence, then emit timestamps.
|
||||
# A load/config failure is permanent, so surface the reason once; audio
|
||||
# has already streamed, so the trailing frame still carries null.
|
||||
try:
|
||||
timestamps_payload = await self._align_sentence(
|
||||
audio=bytes(sentence_audio),
|
||||
text=sentence_text,
|
||||
sample_rate=sample_rate,
|
||||
config=aligner_config,
|
||||
language=language,
|
||||
)
|
||||
except ForcedAlignerLoadError as exc:
|
||||
await self._send_error(websocket, f"forced aligner unavailable: {exc}")
|
||||
timestamps_payload = None
|
||||
sentence_end_ms = int(round((len(sentence_audio) / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
# Pull word timestamps off the aligner stage's pooling output (it rode
|
||||
# the same generator); extract_word_timestamps re-segments the sentence
|
||||
# text for the word strings when the aligner output doesn't carry them.
|
||||
aligner_res = collect.get("aligner_res")
|
||||
timestamps_payload = (
|
||||
extract_word_timestamps(aligner_res, sentence_text, language) if aligner_res is not None else None
|
||||
)
|
||||
sentence_end_ms = int(round((audio_bytes_seen / _BYTES_PER_SAMPLE / sample_rate) * 1000.0))
|
||||
await send_chunk(b"", sample_rate, timestamps_payload, 0, sentence_end_ms)
|
||||
|
||||
return total_bytes
|
||||
|
||||
@staticmethod
|
||||
async def _align_sentence(
|
||||
*,
|
||||
audio: bytes,
|
||||
text: str,
|
||||
sample_rate: int,
|
||||
config,
|
||||
language: str | None = None,
|
||||
) -> list[dict] | None:
|
||||
"""Convert a sentence alignment into JSON word-timestamp dicts.
|
||||
|
||||
Returns ``None`` on aligner failure, ``[]`` when it ran but produced no
|
||||
tokens. Monotonic, non-overlapping bounds are guaranteed by the decoder.
|
||||
``language`` is forwarded to word segmentation.
|
||||
"""
|
||||
aligned = await forced_align(
|
||||
audio=audio,
|
||||
text=text,
|
||||
sample_rate=sample_rate,
|
||||
config=config,
|
||||
language=language,
|
||||
)
|
||||
if aligned is None:
|
||||
return None
|
||||
return [{"word": ts.word, "start_ms": ts.start_ms, "end_ms": ts.end_ms} for ts in aligned]
|
||||
|
||||
@staticmethod
|
||||
async def _send_error(websocket: WebSocket, message: str) -> None:
|
||||
"""Send an error message to the client."""
|
||||
|
||||
Reference in new issue
Block a user