[Qwen3TTS][Feat] Streaming output (#1438)
Signed-off-by: pablo <pablo@agigo.ai> Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com> Co-authored-by: pablo <pablo@agigo.ai> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
8 files changed
+382
-112
No files matched your search
@@ -10,14 +10,13 @@ from urllib.request import urlopen
|
||||
import numpy as np
|
||||
import soundfile as sf
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response
|
||||
from fastapi.responses import Response, StreamingResponse
|
||||
from vllm.entrypoints.openai.engine.serving import OpenAIServing
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils import random_uuid
|
||||
|
||||
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
|
||||
from vllm_omni.entrypoints.openai.protocol.audio import (
|
||||
AudioResponse,
|
||||
CreateAudio,
|
||||
OpenAICreateSpeechRequest,
|
||||
)
|
||||
@@ -253,6 +252,85 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
wav_np, sr = await loop.run_in_executor(None, _fetch_sync)
|
||||
return wav_np.tolist(), sr
|
||||
|
||||
async def _generate_pcm_chunks(self, generator, request_id: str):
|
||||
"""Generate PCM audio chunks for streaming response.
|
||||
|
||||
Handles two audio output modes from the engine:
|
||||
- Cumulative mode (list): Engine returns growing list of chunks;
|
||||
we emit only the new tail on each iteration.
|
||||
- Per-step mode (tensor): Engine returns single tensor per iteration;
|
||||
we emit it directly.
|
||||
|
||||
Args:
|
||||
generator: Async generator from the engine
|
||||
request_id: Request identifier for logging
|
||||
|
||||
Yields:
|
||||
Raw PCM bytes for each audio chunk
|
||||
"""
|
||||
prev_count = 0
|
||||
sample_rate_val = 24000
|
||||
try:
|
||||
async for res in generator:
|
||||
audio_output, audio_key = self._extract_audio_output(res)
|
||||
if audio_key is None:
|
||||
continue
|
||||
|
||||
sr_raw = audio_output.get("sr")
|
||||
if sr_raw is not None:
|
||||
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
|
||||
sample_rate_val = sr_val.item() if hasattr(sr_val, "item") else int(sr_val)
|
||||
|
||||
audio_val = audio_output[audio_key]
|
||||
if isinstance(audio_val, list):
|
||||
# Cumulative mode: each update grows the list; emit only new tail.
|
||||
new_chunks = audio_val[prev_count:]
|
||||
prev_count = len(audio_val)
|
||||
else:
|
||||
# Per-step mode: each update is a single tensor; emit directly.
|
||||
if audio_val is not None:
|
||||
new_chunks = [audio_val]
|
||||
prev_count += 1
|
||||
else:
|
||||
new_chunks = []
|
||||
|
||||
for chunk_tensor in new_chunks:
|
||||
chunk_np = (
|
||||
chunk_tensor.float().detach().cpu().numpy() if hasattr(chunk_tensor, "float") else chunk_tensor
|
||||
)
|
||||
if chunk_np.ndim > 1:
|
||||
chunk_np = chunk_np.squeeze()
|
||||
audio_obj = CreateAudio(
|
||||
audio_tensor=chunk_np,
|
||||
sample_rate=sample_rate_val,
|
||||
response_format="pcm",
|
||||
speed=1.0,
|
||||
stream_format="audio",
|
||||
base64_encode=False,
|
||||
)
|
||||
yield self.create_audio(audio_obj).audio_data
|
||||
except asyncio.CancelledError:
|
||||
logger.info("Streaming request %s cancelled by client", request_id)
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception("Streaming speech generation failed for %s: %s", request_id, e)
|
||||
|
||||
@staticmethod
|
||||
def _extract_audio_output(res) -> tuple[dict | None, str | None]:
|
||||
"""Return (audio_output dict, audio key) or (None, None).
|
||||
|
||||
Returns the raw dict so callers can apply their own extraction strategy:
|
||||
streaming needs per-chunk delta slicing; non-streaming needs full concatenation.
|
||||
"""
|
||||
mm = getattr(res, "multimodal_output", None)
|
||||
if not mm:
|
||||
ro = getattr(res, "request_output", None)
|
||||
mm = getattr(ro, "multimodal_output", None) if ro else None
|
||||
if not mm:
|
||||
return None, None
|
||||
key = "audio" if "audio" in mm else ("model_outputs" if "model_outputs" in mm else None)
|
||||
return mm, key
|
||||
|
||||
def _build_tts_params(self, request: OpenAICreateSpeechRequest) -> dict[str, Any]:
|
||||
"""Build TTS parameters from request.
|
||||
|
||||
@@ -300,6 +378,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
else:
|
||||
params["max_new_tokens"] = [2048]
|
||||
|
||||
# VoiceDesign requires non_streaming_mode (match offline script behaviour).
|
||||
# CustomVoice and Base rely on the model default (True and False respectively).
|
||||
if params["task_type"][0] == "VoiceDesign":
|
||||
params["non_streaming_mode"] = [True]
|
||||
|
||||
return params
|
||||
|
||||
async def create_speech(
|
||||
@@ -323,9 +406,9 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
- ref_text: Transcript of reference audio (Base task)
|
||||
- x_vector_only_mode: Use speaker embedding only (Base task)
|
||||
|
||||
NOTE: Streaming audio generation is not currently supported.
|
||||
Streaming is supported via stream=True with response_format='pcm'.
|
||||
Each Code2Wav chunk is yielded as raw PCM bytes as soon as it is decoded.
|
||||
"""
|
||||
|
||||
error_check_ret = await self._check_model(request)
|
||||
if error_check_ret is not None:
|
||||
logger.error("Error with model %s", error_check_ret)
|
||||
@@ -343,23 +426,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if validation_error:
|
||||
return self.create_error_response(validation_error)
|
||||
|
||||
# Must use prompt_token_ids (not text prompt): the AR Talker
|
||||
# operates on codec tokens; text token IDs exceed codec vocab.
|
||||
# model.preprocess replaces all embeddings, so placeholder value
|
||||
# is irrelevant -- but length must match to avoid excess padding.
|
||||
tts_params = self._build_tts_params(request)
|
||||
|
||||
if request.ref_audio is not None:
|
||||
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
|
||||
tts_params["ref_audio"] = [[wav_list, sr]]
|
||||
|
||||
# Prompt length must match model-side embeddings; values are placeholders.
|
||||
ph_len = self._estimate_prompt_len(tts_params)
|
||||
prompt = {
|
||||
"prompt_token_ids": [1] * ph_len,
|
||||
"additional_information": tts_params,
|
||||
}
|
||||
prompt = {"prompt_token_ids": [1] * ph_len, "additional_information": tts_params}
|
||||
else:
|
||||
# Fallback for unsupported models
|
||||
tts_params = {}
|
||||
prompt = {"prompt": request.input}
|
||||
|
||||
@@ -379,6 +454,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
output_modalities=["audio"],
|
||||
)
|
||||
|
||||
if request.stream:
|
||||
return StreamingResponse(
|
||||
self._generate_pcm_chunks(generator, request_id),
|
||||
media_type="audio/pcm",
|
||||
)
|
||||
|
||||
# Non-streaming: collect final output
|
||||
final_output: OmniRequestOutput | None = None
|
||||
async for res in generator:
|
||||
final_output = res
|
||||
@@ -386,55 +468,34 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
|
||||
if final_output is None:
|
||||
return self.create_error_response("No output generated from the model.")
|
||||
|
||||
# Extract audio from output
|
||||
# Audio can be in final_output.multimodal_output or final_output.request_output.multimodal_output
|
||||
# Support both "audio" and "model_outputs" keys for compatibility with different models
|
||||
audio_output = None
|
||||
if hasattr(final_output, "multimodal_output") and final_output.multimodal_output:
|
||||
audio_output = final_output.multimodal_output
|
||||
if not audio_output and hasattr(final_output, "request_output"):
|
||||
if final_output.request_output and hasattr(final_output.request_output, "multimodal_output"):
|
||||
audio_output = final_output.request_output.multimodal_output
|
||||
|
||||
# Check for audio data using either "audio" or "model_outputs" key
|
||||
audio_key = None
|
||||
if audio_output:
|
||||
if "audio" in audio_output:
|
||||
audio_key = "audio"
|
||||
elif "model_outputs" in audio_output:
|
||||
audio_key = "model_outputs"
|
||||
|
||||
if not audio_output or audio_key is None:
|
||||
audio_output, audio_key = self._extract_audio_output(final_output)
|
||||
if audio_key is None:
|
||||
return self.create_error_response("TTS model did not produce audio output.")
|
||||
|
||||
audio_tensor = audio_output[audio_key]
|
||||
sample_rate = audio_output.get("sr", 24000)
|
||||
if hasattr(sample_rate, "item"):
|
||||
sample_rate = sample_rate.item()
|
||||
sr_raw = audio_output.get("sr", 24000)
|
||||
sr_val = sr_raw[-1] if isinstance(sr_raw, list) and sr_raw else sr_raw
|
||||
sample_rate = sr_val.item() if hasattr(sr_val, "item") else int(sr_val)
|
||||
|
||||
# Streaming accumulates chunks as a list; concat first.
|
||||
# async_chunk mode accumulates chunks as a list; concat first.
|
||||
if isinstance(audio_tensor, list):
|
||||
import torch
|
||||
|
||||
audio_tensor = torch.cat(audio_tensor, dim=-1)
|
||||
# Convert tensor to numpy
|
||||
if hasattr(audio_tensor, "float"):
|
||||
audio_tensor = audio_tensor.float().detach().cpu().numpy()
|
||||
|
||||
# Squeeze batch dimension if present, but preserve channel dimension for stereo
|
||||
if audio_tensor.ndim > 1:
|
||||
audio_tensor = audio_tensor.squeeze()
|
||||
|
||||
audio_obj = CreateAudio(
|
||||
audio_tensor=audio_tensor,
|
||||
sample_rate=int(sample_rate),
|
||||
sample_rate=sample_rate,
|
||||
response_format=request.response_format or "wav",
|
||||
speed=request.speed or 1.0,
|
||||
stream_format=request.stream_format,
|
||||
base64_encode=False,
|
||||
)
|
||||
|
||||
audio_response: AudioResponse = self.create_audio(audio_obj)
|
||||
audio_response = self.create_audio(audio_obj)
|
||||
return Response(content=audio_response.audio_data, media_type=audio_response.media_type)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
|
||||
Reference in new issue
Block a user