Merge branch 'main' into dev/vllm-align

This commit is contained in:
tzhouam committed 2026-03-13 06:51:22 +00:00
commit d3db476f2d
144 files changed
+17247 -1024

No files matched your search

+9 -10
View File
@@ -140,6 +140,15 @@ class AsyncOmni(OmniBase):
getattr(self, "_inline_engine", None),
)
async def get_supported_tasks(self) -> set[str]:
"""Return supported tasks based on stage output modalities and capabilities."""
tasks: set[str] = set()
if "text" in self.output_modalities or any(stage.is_comprehension for stage in self.stage_list):
tasks.add("generate")
if "audio" in self.output_modalities:
tasks.add("speech")
return tasks
def _create_default_diffusion_stage_cfg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
"""Create default diffusion stage configuration."""
# TODO: here is different from the Omni class. We should merge the two in the future.
@@ -831,16 +840,6 @@ class AsyncOmni(OmniBase):
stage.submit(abort_task)
return None
async def get_supported_tasks(self) -> set[str]:
tasks: set[str] = set()
has_comprehension = any(stage.is_comprehension for stage in self.stage_list)
if has_comprehension:
tasks.add("generate")
for stage in self.stage_list:
if getattr(stage, "final_output_type", None) == "audio":
tasks.add("speech")
return tasks if tasks else {"generate"}
async def get_vllm_config(self) -> VllmConfig:
for stage in self.stage_list:
if stage.is_comprehension:
+25 -35
View File
@@ -15,13 +15,14 @@ import huggingface_hub
import msgspec.msgpack
import torch
import zmq
from omegaconf import OmegaConf
from tqdm.auto import tqdm
from vllm import SamplingParams
from vllm.logger import init_logger
from vllm.utils.network_utils import make_zmq_socket
from vllm.v1.utils import get_engine_client_zmq_addr
from vllm_omni.config.stage_config import StageConfigFactory
from vllm_omni.config.yaml_util import create_config
from vllm_omni.distributed.omni_connectors import (
get_stage_connector_config,
initialize_orchestrator_connectors,
@@ -224,46 +225,35 @@ class OmniBase:
cache_config = self._get_default_cache_config(cache_backend)
return cache_config
def _create_default_diffusion_stage_cfg(self, kwargs: dict[str, Any]) -> dict[str, Any]:
"""Create default diffusion stage configuration."""
# We temporally create a default config for diffusion stage.
# In the future, we should merge the default config with the user-provided config.
# TODO: hack, convert dtype to string to avoid non-premitive omegaconf create error.
def _create_default_diffusion_stage_cfg(self, kwargs: dict[str, Any]) -> list[dict[str, Any]]:
"""Create default diffusion stage configuration.
Uses StageConfigFactory for typed configuration creation while
maintaining backward compatibility with the legacy format.
Args:
kwargs: Engine arguments from CLI/API.
Returns:
List containing a single OmegaConf config for the diffusion stage.
"""
# Normalize dtype
if "dtype" in kwargs and not isinstance(kwargs["dtype"], str):
if not isinstance(kwargs["dtype"], torch.dtype):
raise TypeError(f"Provided dtype must be a string or torch.dtype, got {type(kwargs['dtype']).__name__}")
kwargs["dtype"] = str(kwargs["dtype"]).removeprefix("torch.")
# Normalize cache config before passing to factory
cache_backend = kwargs.get("cache_backend", "none")
cache_config = self._normalize_cache_config(cache_backend, kwargs.get("cache_config", None))
# TODO: hack, calculate devices based on parallel config.
devices = "0"
if "parallel_config" in kwargs:
num_devices = kwargs["parallel_config"].world_size
for i in range(1, num_devices):
devices += f",{i}"
default_stage_cfg = [
{
"stage_id": 0,
"stage_type": "diffusion",
"runtime": {
"process": True,
"devices": devices,
"max_batch_size": 1,
},
"engine_args": OmegaConf.create(
{
**kwargs,
"cache_backend": cache_backend,
"cache_config": cache_config,
}
),
"final_output": True,
"final_output_type": "image",
}
]
default_stage_cfg[0]["engine_args"]["model_stage"] = "diffusion"
return default_stage_cfg
# Update kwargs with normalized values
kwargs_copy = dict(kwargs)
kwargs_copy["cache_backend"] = cache_backend
kwargs_copy["cache_config"] = cache_config
# Use the factory to create default diffusion config
return StageConfigFactory.create_default_diffusion(kwargs_copy)
def _resolve_stage_configs(self, model: str, kwargs: dict[str, Any]) -> tuple[str, list[Any]]:
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
@@ -290,7 +280,7 @@ class OmniBase:
if getattr(cfg, "stage_type", None) != "diffusion":
continue
if not hasattr(cfg, "engine_args") or cfg.engine_args is None:
cfg.engine_args = OmegaConf.create({})
cfg.engine_args = create_config({})
if kwargs.get("lora_path") is not None:
if not hasattr(cfg.engine_args, "lora_path") or cfg.engine_args.lora_path is None:
cfg.engine_args.lora_path = kwargs["lora_path"]
+3 -12
View File
@@ -25,8 +25,6 @@ from vllm_omni.engine.input_processor import OmniInputProcessor, reinject_omni_f
from vllm_omni.engine.output_processor import MultimodalOutputProcessor
from vllm_omni.entrypoints.utils import (
filter_dataclass_kwargs,
load_stage_configs_from_model,
load_stage_configs_from_yaml,
resolve_model_config_path,
)
@@ -43,8 +41,6 @@ class OmniLLM(LLM):
Args:
model: Model name or path to load
stage_configs_path: Optional path to YAML file containing stage
configurations. If None, configurations are loaded from the model.
log_stats: Whether to enable statistics logging
compilation_config: Optional compilation configuration. Can be an
integer (compilation level), dict, or CompilationConfig instance.
@@ -68,7 +64,6 @@ class OmniLLM(LLM):
def __init__(
self,
model: str,
stage_configs_path: str | None = None,
log_stats: bool = False,
compilation_config: int | dict[str, Any] | CompilationConfig | None = None,
hf_overrides: dict[str, Any] | None = None,
@@ -86,13 +81,8 @@ class OmniLLM(LLM):
self.batch_timeout = batch_timeout
self.log_stats: bool = bool(log_stats)
# Load stage configurations
if stage_configs_path is None:
self.config_path = resolve_model_config_path(model)
self.stage_configs = load_stage_configs_from_model(model)
else:
self.config_path = stage_configs_path
self.stage_configs = load_stage_configs_from_yaml(stage_configs_path)
# Resolve model config path for connectors
self.config_path = resolve_model_config_path(model)
# Initialize connectors
self.omni_transfer_config, self.connectors = initialize_orchestrator_connectors(
@@ -154,6 +144,7 @@ class OmniLLM(LLM):
compilation_config=compilation_config_instance,
structured_outputs_config=structured_outputs_instance,
omni_kv_config=omni_kv_config,
hf_overrides=hf_overrides or {},
**filter_dataclass_kwargs(OmniEngineArgs, kwargs),
)
+27 -7
View File
@@ -36,7 +36,12 @@ from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.distributed.omni_connectors import build_stage_connectors
from vllm_omni.distributed.omni_connectors.adapter import try_recv_via_connector
from vllm_omni.distributed.omni_connectors.connectors.base import OmniConnectorBase
from vllm_omni.distributed.ray_utils.utils import kill_ray_actor, start_ray_actor
from vllm_omni.distributed.ray_utils.utils import (
get_ray_task_error,
is_ray_task_alive,
kill_ray_actor,
start_ray_actor,
)
from vllm_omni.engine.arg_utils import AsyncOmniEngineArgs, OmniEngineArgs
from vllm_omni.entrypoints.async_omni_diffusion import AsyncOmniDiffusion
from vllm_omni.entrypoints.async_omni_llm import AsyncOmniLLM
@@ -264,7 +269,10 @@ class OmniStage:
self.engine_args = stage_config.engine_args
self.model_stage = stage_config.engine_args.model_stage
self.requires_multimodal_data = getattr(stage_config.runtime, "requires_multimodal_data", False)
self.engine_input_source = getattr(stage_config, "engine_input_source", [])
# Support both 'input_sources' (new format) and 'engine_input_source' (legacy)
self.engine_input_source = (
getattr(stage_config, "input_sources", None) or getattr(stage_config, "engine_input_source", []) or []
)
self.engine_output_type = getattr(stage_config.engine_args, "engine_output_type", None)
self.engine_outputs = None
self.is_comprehension = getattr(stage_config, "is_comprehension", False)
@@ -303,6 +311,8 @@ class OmniStage:
self._in_q: mp.queues.Queue | ZmqQueue | str | None = None
self._out_q: mp.queues.Queue | ZmqQueue | str | None = None
self._proc: mp.Process | None = None
self._ray_actor: Any | None = None
self._ray_task_ref: Any | None = None
self._shm_threshold_bytes: int = 65536
self._stage_init_timeout: int = stage_init_timeout
# Callback used by the orchestrator's output handler to stash
@@ -544,7 +554,7 @@ class OmniStage:
os.environ["VLLM_LOGGING_PREFIX"] = new_env
if worker_backend == "ray":
if is_async:
self._ray_actor = start_ray_actor(
self._ray_actor, self._ray_task_ref = start_ray_actor(
_stage_worker_async_entry,
ray_placement_group,
self.stage_id,
@@ -556,7 +566,7 @@ class OmniStage:
stage_init_timeout=self._stage_init_timeout,
)
else:
self._ray_actor = start_ray_actor(
self._ray_actor, self._ray_task_ref = start_ray_actor(
_stage_worker,
ray_placement_group,
self.stage_id,
@@ -629,9 +639,10 @@ class OmniStage:
pass
self._out_q = None
if hasattr(self, "_ray_actor") and self._ray_actor:
if self._ray_actor is not None:
kill_ray_actor(self._ray_actor)
self._ray_actor = None
self._ray_task_ref = None
elif self._proc is not None:
try:
self._proc.join(timeout=5)
@@ -695,8 +706,17 @@ class OmniStage:
return None
try:
return self._out_q.get_nowait()
except Exception:
return None
except queue.Empty:
pass
except Exception as e:
logger.error("Unexpected error when collecting OmniStage output queue:", exc_info=e)
self.stop_stage_worker()
raise
if self._proc is not None and not self._proc.is_alive():
raise RuntimeError(f"OmniStage Worker process died unexpectedly with exit code {self._proc.exitcode}")
if self._ray_task_ref is not None and not is_ray_task_alive(self._ray_task_ref, timeout=0):
e = get_ray_task_error(self._ray_task_ref, timeout=0)
raise RuntimeError("OmniStage Ray actor died unexpectedly") from e
def process_engine_inputs(
self,
+31 -186
View File
@@ -19,10 +19,9 @@ from typing import Annotated, Any, cast
import httpx
import vllm.envs as envs
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, UploadFile, WebSocket
from fastapi.responses import JSONResponse, StreamingResponse
from PIL import Image
from pydantic import BaseModel, Field
from starlette.datastructures import State
from starlette.routing import Route
from vllm import SamplingParams
@@ -99,6 +98,7 @@ from vllm_omni.entrypoints.openai.protocol.videos import (
)
from vllm_omni.entrypoints.openai.serving_chat import OmniOpenAIServingChat
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
from vllm_omni.entrypoints.openai.serving_speech_stream import OmniStreamingSpeechHandler
from vllm_omni.entrypoints.openai.serving_video import OmniOpenAIServingVideo
from vllm_omni.inputs.data import OmniDiffusionSamplingParams, OmniSamplingParams, OmniTextPrompt
from vllm_omni.lora.request import LoRARequest
@@ -106,30 +106,6 @@ from vllm_omni.lora.utils import stable_lora_int_id
logger = init_logger(__name__)
router = APIRouter()
profiler_router = APIRouter()
def _should_enable_profiler_endpoints(args: Namespace) -> bool:
# Check upstream vLLM's profiler_config
profiler_config = getattr(args, "profiler_config", None)
if profiler_config is not None:
# profiler_config exists, check if profiler is set
profiler = getattr(profiler_config, "profiler", None)
if profiler is not None:
return True
# TODO: remove this env after refactoring torch profiler to CLI args
env_value = os.environ.get("VLLM_TORCH_PROFILER_DIR")
return env_value is not None
class ProfileRequest(BaseModel):
"""Request model for profiling endpoints."""
stages: list[int] | None = Field(
default=None,
description="List of stage IDs to profile. If None, profiles all stages.",
)
def _remove_route_from_router(
@@ -178,6 +154,10 @@ class _DiffusionServingModels:
def __init__(self, base_model_paths: list[BaseModelPath]) -> None:
self._base_model_paths = base_model_paths
@property
def base_model_paths(self) -> list[BaseModelPath]:
return self._base_model_paths
async def show_available_models(self) -> ModelList:
return ModelList(
data=[
@@ -241,7 +221,10 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
else:
supported_tasks = ("generate",)
if not supported_tasks:
supported_tasks = ("generate",)
# Only default to "generate" when get_supported_tasks is not implemented;
# TTS-only models intentionally return an empty set.
if not hasattr(engine_client, "get_supported_tasks"):
supported_tasks = ("generate",)
# OMNI: Pass supported_tasks to build_app (required by upstream vLLM)
app = build_openai_app(args, supported_tasks)
@@ -252,11 +235,6 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
await omni_init_app_state(engine_client, app.state, args)
# Conditionally register profiler endpoints based on config or env var
if _should_enable_profiler_endpoints(args):
logger.warning("Profiler endpoints are enabled. This should ONLY be used for local development!")
app.include_router(profiler_router)
vllm_config = await engine_client.get_vllm_config()
# Check if pure diffusion mode (vllm_config will be None)
@@ -287,7 +265,6 @@ async def omni_run_server_worker(listen_address, sock, args, client_config=None,
ssl_certfile=args.ssl_certfile,
ssl_ca_certs=args.ssl_ca_certs,
ssl_cert_reqs=args.ssl_cert_reqs,
ssl_ciphers=args.ssl_ciphers,
h11_max_incomplete_event_size=args.h11_max_incomplete_event_size,
h11_max_header_count=args.h11_max_header_count,
**uvicorn_kwargs,
@@ -731,6 +708,10 @@ async def omni_init_app_state(
engine_client, state.openai_serving_models, request_logger=request_logger
)
state.openai_streaming_speech = OmniStreamingSpeechHandler(
speech_service=state.openai_serving_speech,
)
state.openai_serving_video = OmniOpenAIServingVideo(
engine_client,
model_name=served_model_names[0] if served_model_names else None,
@@ -878,113 +859,29 @@ async def list_voices(raw_request: Request):
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Speech API")
# Get all speakers (both model built-in and uploaded)
speakers = sorted(handler.supported_speakers) if handler.supported_speakers else []
# Get uploaded speakers details
uploaded_speakers = []
if hasattr(handler, "uploaded_speakers"):
for voice_name, info in handler.uploaded_speakers.items():
uploaded_speakers.append(
{
"name": info.get("name", voice_name),
"consent": info.get("consent", ""),
"created_at": info.get("created_at", 0),
"file_size": info.get("file_size", 0),
"mime_type": info.get("mime_type", ""),
}
)
return JSONResponse(content={"voices": speakers, "uploaded_voices": uploaded_speakers})
return JSONResponse(content={"voices": speakers})
@router.post(
"/v1/audio/voices",
responses={
HTTPStatus.OK.value: {"model": dict},
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
},
)
async def upload_voice(
raw_request: Request,
audio_sample: UploadFile = File(...),
consent: str = Form(...),
name: str = Form(...),
):
"""Upload a new voice sample for voice cloning.
@router.websocket("/v1/audio/speech/stream")
async def streaming_speech(websocket: WebSocket):
"""WebSocket endpoint for streaming text input TTS.
Uploads an audio file that can be used as a reference for voice cloning
in Base task TTS requests. The voice can then be referenced by name
in subsequent TTS requests.
Args:
audio_sample: Audio file (max 10MB)
consent: Consent recording ID
name: Name for the new voice
raw_request: Raw FastAPI request
Returns:
JSON response with voice information
Accepts text incrementally, splits at sentence boundaries, and
returns audio per sentence. See serving_speech_stream.py for protocol.
"""
handler = Omnispeech(raw_request)
handler = getattr(websocket.app.state, "openai_streaming_speech", None)
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Speech API")
try:
# Upload the voice
result = await handler.upload_voice(audio_sample, consent, name)
return JSONResponse(content={"success": True, "voice": result})
except ValueError as e:
return base(raw_request).create_error_response(message=str(e))
except Exception as e:
logger.exception(f"Failed to upload voice: {e}")
return base(raw_request).create_error_response(message=f"Failed to upload voice: {str(e)}")
@router.delete(
"/v1/audio/voices/{name}",
responses={
HTTPStatus.OK.value: {"model": dict},
HTTPStatus.NOT_FOUND.value: {"model": ErrorResponse},
HTTPStatus.INTERNAL_SERVER_ERROR.value: {"model": ErrorResponse},
},
)
async def delete_voice(name: str, raw_request: Request):
"""Delete an uploaded voice.
Deletes the voice sample and associated metadata. Also removes any
cached voice clone prompts for this voice.
Args:
name: Name of the voice to delete
raw_request: Raw FastAPI request
Returns:
JSON response indicating success or failure
"""
handler = Omnispeech(raw_request)
if handler is None:
return base(raw_request).create_error_response(message="The model does not support Speech API")
try:
# Delete the voice
success = await handler.delete_voice(name)
if not success:
return JSONResponse(
content={"success": False, "error": f"Voice '{name}' not found"},
status_code=HTTPStatus.NOT_FOUND.value,
)
return JSONResponse(content={"success": True, "message": f"Voice '{name}' deleted successfully"})
except ValueError as e:
return base(raw_request).create_error_response(message=str(e))
except Exception as e:
logger.exception(f"Failed to delete voice '{name}': {e}")
return base(raw_request).create_error_response(message=f"Failed to delete voice: {str(e)}")
await websocket.accept()
await websocket.send_json(
{
"type": "error",
"message": "Streaming speech is not available",
}
)
await websocket.close()
return
await handler.handle_session(websocket)
# Health and Model endpoints for diffusion mode
@@ -1626,58 +1523,6 @@ def apply_stage_default_sampling_params(
setattr(sampling_params, param_name, param_value)
@profiler_router.post("/start_profile")
async def start_profile(raw_request: Request, request: ProfileRequest | None = None):
"""Start profiling for the engine.
Args:
request: Optional request body with stages to profile.
- stages: List of stage IDs to profile. If None, profiles all stages.
Example:
POST /start_profile
{"stages": [0, 1]} # Profile only stages 0 and 1
"""
try:
stages = request.stages if request else None
logger.info("Starting profiler for stages: %s", stages if stages else "all")
engine_client = raw_request.app.state.engine_client
result = await engine_client.start_profile(stages=stages)
logger.info("Profiler started.")
return JSONResponse(content=result)
except Exception as e:
logger.exception("Failed to start profiler: %s", e)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to start profiler: {str(e)}"
)
@profiler_router.post("/stop_profile")
async def stop_profile(raw_request: Request, request: ProfileRequest | None = None):
"""Stop profiling for the engine.
Args:
request: Optional request body with stages to stop profiling.
- stages: List of stage IDs to stop profiling. If None, stops all stages.
Example:
POST /stop_profile
{"stages": [0, 1]} # Stop profiling only stages 0 and 1
"""
try:
stages = request.stages if request else None
logger.info("Stopping profiler for stages: %s", stages if stages else "all")
engine_client = raw_request.app.state.engine_client
result = await engine_client.stop_profile(stages=stages)
logger.info("Profiler stopped.")
return JSONResponse(content=result)
except Exception as e:
logger.exception("Failed to stop profiler: %s", e)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value, detail=f"Failed to stop profiler: {str(e)}"
)
async def _run_video_generation(
request: VideoGenerationRequest,
raw_request: Request,
+51 -2
View File
@@ -71,9 +71,9 @@ class OpenAICreateSpeechRequest(BaseModel):
@model_validator(mode="after")
def validate_streaming_constraints(self) -> "OpenAICreateSpeechRequest":
if self.stream:
if self.response_format != "pcm":
if self.response_format not in ("pcm", "wav"):
raise ValueError(
"Streaming (stream=true) requires response_format='pcm'. "
"Streaming (stream=true) requires response_format not in ('pcm', 'wav'). "
f"Got response_format='{self.response_format}'."
)
if self.speed is None:
@@ -100,3 +100,52 @@ class CreateAudio(BaseModel):
class AudioResponse(BaseModel):
audio_data: bytes | str
media_type: str
class StreamingSpeechSessionConfig(BaseModel):
"""Configuration sent as the first WebSocket message for streaming TTS."""
model: str | None = None
voice: str | None = None
task_type: Literal["CustomVoice", "VoiceDesign", "Base"] | None = None
language: str | None = None
instructions: str | None = None
response_format: Literal["wav", "pcm", "flac", "mp3", "aac", "opus"] = "wav"
speed: float | None = Field(default=1.0, ge=0.25, le=4.0)
max_new_tokens: int | None = Field(default=None, ge=1)
initial_codec_chunk_frames: int | None = Field(
default=None,
ge=0,
description="Initial chunk size for reduced TTFA. Overrides stage config for this session.",
)
ref_audio: str | None = None
ref_text: str | None = None
x_vector_only_mode: bool | None = None
stream_audio: bool = Field(
default=False,
description=(
"If true, send raw PCM audio chunks progressively over WebSocket. "
"Requires response_format='pcm'. Speed adjustment is not supported when streaming."
),
)
split_granularity: Literal["sentence", "clause"] = Field(
default="sentence",
description=(
"Text splitting granularity: 'sentence' splits on .!?。!?, "
"'clause' also splits on CJK commas , and semicolons ;."
),
)
@model_validator(mode="after")
def validate_streaming_constraints(self) -> "StreamingSpeechSessionConfig":
if self.stream_audio:
if self.response_format != "pcm":
raise ValueError(
"WebSocket streaming audio (stream_audio=true) requires response_format='pcm'. "
f"Got response_format='{self.response_format}'."
)
if self.speed is None:
self.speed = 1.0
elif self.speed != 1.0:
raise ValueError("Speed adjustment is not supported when stream_audio=true. Set speed=1.0 or omit it.")
return self
+283 -86
View File
@@ -4,6 +4,7 @@ import json
import math
import os
import re
import struct
import time
from pathlib import Path
from typing import Any
@@ -20,6 +21,7 @@ from vllm.utils import random_uuid
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.metadata_manager import MetadataManager
from vllm_omni.entrypoints.openai.protocol.audio import (
AudioResponse,
CreateAudio,
OpenAICreateSpeechRequest,
)
@@ -27,8 +29,8 @@ from vllm_omni.outputs import OmniRequestOutput
logger = init_logger(__name__)
# TTS Configuration (currently supports Qwen3-TTS)
_TTS_MODEL_STAGES: set[str] = {"qwen3_tts"}
# TTS Configuration
_TTS_MODEL_STAGES: set[str] = {"qwen3_tts", "fish_speech_slow_ar"}
_TTS_LANGUAGES: set[str] = {
"Auto",
"Chinese",
@@ -47,6 +49,47 @@ _TTS_MAX_NEW_TOKENS_MIN = 1
_TTS_MAX_NEW_TOKENS_MAX = 4096
def _create_wav_header(sample_rate: int, num_channels: int = 1, bits_per_sample: int = 16) -> bytes:
"""Create a WAV header with placeholder size values for streaming.
Uses 0xFFFFFFFF as placeholder for data size fields, which is accepted
by most audio clients and matches OpenAI's streaming WAV implementation.
Args:
sample_rate: Audio sample rate in Hz
num_channels: Number of audio channels (1 for mono, 2 for stereo)
bits_per_sample: Bits per sample (typically 16)
Returns:
44-byte WAV header as bytes
"""
byte_rate = sample_rate * num_channels * bits_per_sample // 8
block_align = num_channels * bits_per_sample // 8
# Use 0xFFFFFFFF as placeholder for unknown size (streaming)
placeholder_size = 0xFFFFFFFF
# ref https://docs.fileformat.com/audio/wav/
header = struct.pack(
"<4sI4s4sIHHIIHH4sI",
b"RIFF", # ChunkID
placeholder_size, # ChunkSize (placeholder)
b"WAVE", # Format
b"fmt ", # Subchunk1ID
16, # Subchunk1Size (16 for PCM)
1, # AudioFormat (1 for PCM)
num_channels, # NumChannels
sample_rate, # SampleRate
byte_rate, # ByteRate
block_align, # BlockAlign
bits_per_sample, # BitsPerSample
b"data", # Subchunk2ID
placeholder_size, # Subchunk2Size (placeholder)
)
return header
def _sanitize_filename(filename: str) -> str:
"""Sanitize filename to prevent path traversal attacks.
@@ -97,6 +140,10 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
# Find and cache the TTS stage (if any) during initialization
self._tts_stage = self._find_tts_stage()
self._is_tts = self._tts_stage is not None
self._is_fish_speech = (
self._tts_stage is not None and getattr(self._tts_stage, "model_stage", None) == "fish_speech_slow_ar"
)
self._fish_speech_tokenizer = None
# Cache TTS configuration values (computed once, reused per request)
self._max_instructions_length = self._compute_max_instructions_length()
@@ -574,8 +621,8 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
wav_np = np.mean(wav_np, axis=-1)
return wav_np.tolist(), int(sr)
async def _generate_pcm_chunks(self, generator, request_id: str):
"""Generate PCM audio chunks for streaming response.
async def _generate_audio_chunks(self, generator, request_id: str, response_format: str = "pcm"):
"""Generate audio chunks for streaming response.
Handles two audio output modes from the engine:
- Cumulative mode (list): Engine returns growing list of chunks;
@@ -586,12 +633,15 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
Args:
generator: Async generator from the engine
request_id: Request identifier for logging
response_format: Audio format (pcm or wav)
Yields:
Raw PCM bytes for each audio chunk
Raw audio bytes for each chunk (with WAV header for first chunk if wav format)
"""
prev_count = 0
sample_rate_val = 24000
first_chunk = True
try:
async for res in generator:
audio_output, audio_key = self._extract_audio_output(res)
@@ -622,6 +672,18 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
if chunk_np.ndim > 1:
chunk_np = chunk_np.squeeze()
# For WAV format, emit header before first audio chunk
if response_format == "wav" and first_chunk:
# Assert that sample rate has been set from chunk metadata (not just default)
# This ensures the WAV header contains the correct sample rate
assert sr_raw is not None, (
"First audio chunk must include sample rate metadata for WAV streaming"
)
wav_header = _create_wav_header(sample_rate=sample_rate_val, num_channels=1, bits_per_sample=16)
yield wav_header
first_chunk = False
# Convert audio to PCM bytes
audio_obj = CreateAudio(
audio_tensor=chunk_np,
sample_rate=sample_rate_val,
@@ -636,6 +698,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
raise
except Exception as e:
logger.exception("Streaming speech generation failed for %s: %s", request_id, e)
raise
@staticmethod
def _extract_audio_output(res) -> tuple[dict | None, str | None]:
@@ -650,7 +713,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
mm = getattr(ro, "multimodal_output", None) if ro else None
if not mm:
return None, None
key = "audio" if "audio" in mm else 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]:
@@ -721,6 +784,194 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
return params
def _build_fish_speech_prompt(
self,
request: OpenAICreateSpeechRequest,
ref_audio_data: tuple[list[float], int] | None = None,
) -> dict[str, Any]:
"""Build prompt for Fish Speech S2 Pro.
Without voice cloning:
<|im_start|>user\\n<|speaker:0|>{text}<|im_end|>\\n<|im_start|>assistant\\n<|voice|>
With voice cloning (ref_audio + ref_text):
<|im_start|>system\\n<|speaker:0|>{ref_text}<|audio_start|>{semantic_tokens}<|audio_end|><|im_end|>
<|im_start|>user\\n<|speaker:0|>{text}<|im_end|>\\n<|im_start|>assistant\\n<|voice|>
"""
from transformers import AutoTokenizer
if self._fish_speech_tokenizer is None:
model_name = self.engine_client.model_config.model
self._fish_speech_tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
tokenizer = self._fish_speech_tokenizer
model_name = self.engine_client.model_config.model
if ref_audio_data is not None and request.ref_text:
# Voice cloning: encode reference audio and build system message.
from vllm_omni.model_executor.models.fish_speech.dac_encoder import (
encode_reference_audio,
)
wav_samples, sr = ref_audio_data
semantic_token_ids = encode_reference_audio(model_name, wav_samples, sr)
# Build system message with ref text + audio tokens.
audio_start_id = tokenizer.encode("<|audio_start|>", add_special_tokens=False)
audio_end_id = tokenizer.encode("<|audio_end|>", add_special_tokens=False)
# System content: <|speaker:0|>{ref_text}<|audio_start|>{codes}<|audio_end|>
prefix_text = f"<|speaker:0|>{request.ref_text}"
prefix_ids = tokenizer.encode(prefix_text, add_special_tokens=False)
system_content_ids = prefix_ids + audio_start_id + semantic_token_ids + audio_end_id
# Manually build system turn: <|im_start|>system\n{content}<|im_end|>\n
im_start = tokenizer.encode("<|im_start|>", add_special_tokens=False)
im_end = tokenizer.encode("<|im_end|>", add_special_tokens=False)
system_tag = tokenizer.encode("system\n", add_special_tokens=False)
newline = tokenizer.encode("\n", add_special_tokens=False)
system_ids = im_start + system_tag + system_content_ids + im_end + newline
# User turn via chat template.
user_text = f"<|speaker:0|>{request.input}"
user_messages = [{"role": "user", "content": user_text}]
user_ids = tokenizer.apply_chat_template(user_messages, tokenize=True, add_generation_prompt=True)
prompt_ids = system_ids + user_ids
else:
# No voice cloning: simple user message.
user_text = f"<|speaker:0|>{request.input}"
messages = [{"role": "user", "content": user_text}]
prompt_ids = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True)
# Append <|voice|> token to signal voice generation.
voice_token_id = tokenizer.encode("<|voice|>", add_special_tokens=False)
prompt_ids = prompt_ids + voice_token_id
additional_information: dict[str, Any] = {
"text": [request.input],
"max_new_tokens": [request.max_new_tokens or 4096],
}
return {
"prompt_token_ids": prompt_ids,
"additional_information": additional_information,
}
async def _prepare_speech_generation(
self,
request: OpenAICreateSpeechRequest,
) -> tuple[str, Any, dict[str, Any]]:
if self.engine_client.errored:
raise self.engine_client.dead_error
if self._is_fish_speech:
if not request.input or not request.input.strip():
raise ValueError("Input text cannot be empty")
ref_audio_data = None
if request.ref_audio is not None:
if not request.ref_text or not request.ref_text.strip():
raise ValueError("Voice cloning requires 'ref_text' (transcript of the reference audio)")
wav_list, sr = await self._resolve_ref_audio(request.ref_audio)
ref_audio_data = (wav_list, sr)
prompt = self._build_fish_speech_prompt(request, ref_audio_data=ref_audio_data)
tts_params = {}
elif self._is_tts:
validation_error = self._validate_tts_request(request)
if validation_error:
raise ValueError(validation_error)
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]]
ph_len = self._estimate_prompt_len(tts_params)
prompt = {"prompt_token_ids": [1] * ph_len, "additional_information": tts_params}
else:
tts_params = {}
prompt = {"prompt": request.input}
request_id = f"speech-{random_uuid()}"
model_type = (
"fish_speech"
if self._is_fish_speech
else tts_params.get("task_type", ["unknown"])[0]
if self._is_tts
else "generic"
)
logger.info(
"TTS speech request %s: text=%r, model=%s",
request_id,
request.input[:50] + "..." if len(request.input) > 50 else request.input,
model_type,
)
sampling_params_list = self.engine_client.default_sampling_params_list
# Override Stage-0 max_tokens if caller specified max_new_tokens (Fish Speech).
if self._is_fish_speech and request.max_new_tokens is not None and sampling_params_list:
import copy
sampling_params_list = copy.deepcopy(sampling_params_list)
sampling_params_list[0].max_tokens = request.max_new_tokens
generator = self.engine_client.generate(
prompt=prompt,
request_id=request_id,
sampling_params_list=sampling_params_list,
output_modalities=["audio"],
)
return request_id, generator, tts_params
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, _ = await self._prepare_speech_generation(request)
async for chunk in self._generate_pcm_chunks(generator, request_id):
yield chunk
async def _generate_audio_bytes(
self,
request: OpenAICreateSpeechRequest,
) -> tuple[bytes, str]:
request_id, generator, _ = await self._prepare_speech_generation(request)
final_output: OmniRequestOutput | None = None
async for res in generator:
final_output = res
if final_output is None:
raise ValueError("No output generated from the model.")
audio_output, audio_key = self._extract_audio_output(final_output)
if audio_key is None:
raise ValueError("TTS model did not produce audio output.")
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
sample_rate = sr_val.item() if hasattr(sr_val, "item") else int(sr_val)
if isinstance(audio_tensor, list):
import torch
audio_tensor = torch.cat(audio_tensor, dim=-1)
if hasattr(audio_tensor, "float"):
audio_tensor = audio_tensor.float().detach().cpu().numpy()
if audio_tensor.ndim > 1:
audio_tensor = audio_tensor.squeeze()
audio_obj = CreateAudio(
audio_tensor=audio_tensor,
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)
return audio_response.audio_data, audio_response.media_type
async def create_speech(
self,
request: OpenAICreateSpeechRequest,
@@ -742,97 +993,43 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
- ref_text: Transcript of reference audio (Base task)
- x_vector_only_mode: Use speaker embedding only (Base task)
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.
Streaming is supported via stream=True with response_format='pcm' or 'wav'.
Each Code2Wav chunk is yielded as raw audio bytes as soon as it is decoded.
For WAV format, a header with placeholder size values is emitted first.
"""
error_check_ret = await self._check_model(request)
if error_check_ret is not None:
logger.error("Error with model %s", error_check_ret)
return error_check_ret
if self.engine_client.errored:
raise self.engine_client.dead_error
request_id = f"speech-{random_uuid()}"
try:
if self._is_tts:
# Validate TTS parameters
validation_error = self._validate_tts_request(request)
if validation_error:
return self.create_error_response(validation_error)
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}
else:
tts_params = {}
prompt = {"prompt": request.input}
logger.info(
"TTS speech request %s: text=%r, task_type=%s",
request_id,
request.input[:50] + "..." if len(request.input) > 50 else request.input,
tts_params.get("task_type", ["unknown"])[0],
)
sampling_params_list = self.engine_client.default_sampling_params_list
generator = self.engine_client.generate(
prompt=prompt,
request_id=request_id,
sampling_params_list=sampling_params_list,
output_modalities=["audio"],
)
if request.stream:
# Determine response format and media type for streaming
response_format = (request.response_format or "wav").lower()
# Only pcm and wav support streaming without post-processing
if response_format not in ["pcm", "wav"]:
return self.create_error_response(
f"Streaming is only supported for 'pcm' and 'wav' formats. "
f"Got '{response_format}'. For other formats, use stream=False."
)
# Check if speed adjustment is requested (not compatible with streaming)
if request.speed is not None and request.speed != 1.0:
return self.create_error_response(
"Streaming is not supported with speed adjustment. "
"Use stream=False or remove the speed parameter."
)
media_type = "audio/wav" if response_format == "wav" else "audio/pcm"
request_id, generator, _ = await self._prepare_speech_generation(request)
return StreamingResponse(
self._generate_pcm_chunks(generator, request_id),
media_type="audio/pcm",
self._generate_audio_chunks(generator, request_id, response_format),
media_type=media_type,
)
# Non-streaming: collect final output
final_output: OmniRequestOutput | None = None
async for res in generator:
final_output = res
if final_output is None:
return self.create_error_response("No output generated from the model.")
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]
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)
# 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)
if hasattr(audio_tensor, "float"):
audio_tensor = audio_tensor.float().detach().cpu().numpy()
if audio_tensor.ndim > 1:
audio_tensor = audio_tensor.squeeze()
audio_obj = CreateAudio(
audio_tensor=audio_tensor,
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 = self.create_audio(audio_obj)
return Response(content=audio_response.audio_data, media_type=audio_response.media_type)
audio_bytes, media_type = await self._generate_audio_bytes(request)
return Response(content=audio_bytes, media_type=media_type)
except asyncio.CancelledError:
return self.create_error_response("Client disconnected")
@@ -0,0 +1,289 @@
"""WebSocket handler for streaming text input TTS.
Accepts text incrementally via WebSocket, buffers and splits at sentence
boundaries, and generates audio per sentence using the existing TTS pipeline.
Protocol:
Client -> Server:
{"type": "session.config", ...} # Session config (sent once first)
{"type": "input.text", "text": "..."} # Text chunks
{"type": "input.done"} # End of input
Server -> Client:
{"type": "audio.start", "sentence_index": 0, "sentence_text": "...", "format": "wav"}
<binary frame: audio bytes>
{"type": "audio.done", "sentence_index": 0}
{"type": "session.done", "total_sentences": N}
{"type": "error", "message": "..."}
"""
import asyncio
import json
from contextlib import aclosing
from fastapi import WebSocket, WebSocketDisconnect
from pydantic import ValidationError
from vllm.logger import init_logger
from vllm_omni.entrypoints.openai.protocol.audio import (
OpenAICreateSpeechRequest,
StreamingSpeechSessionConfig,
)
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
from vllm_omni.entrypoints.openai.text_splitter import (
SPLIT_CLAUSE,
SPLIT_SENTENCE,
SentenceSplitter,
)
logger = init_logger(__name__)
_DEFAULT_IDLE_TIMEOUT = 30.0 # seconds
_DEFAULT_CONFIG_TIMEOUT = 10.0 # seconds
_PCM_SAMPLE_RATE = 24000
_MAX_CONFIG_MESSAGE_SIZE = 4 * 1024 * 1024 # allow large ref_audio payloads
_MAX_INPUT_TEXT_MESSAGE_SIZE = 128 * 1024
class OmniStreamingSpeechHandler:
"""Handles WebSocket sessions for streaming text-input TTS.
Each WebSocket connection is an independent session. Text arrives
incrementally, is split at sentence boundaries, and audio is generated
per sentence using the existing OmniOpenAIServingSpeech pipeline.
Args:
speech_service: The existing TTS serving instance (reused for
validation and audio generation).
idle_timeout: Max seconds to wait for a message before closing.
config_timeout: Max seconds to wait for the initial session.config.
"""
def __init__(
self,
speech_service: OmniOpenAIServingSpeech,
idle_timeout: float = _DEFAULT_IDLE_TIMEOUT,
config_timeout: float = _DEFAULT_CONFIG_TIMEOUT,
) -> None:
self._speech_service = speech_service
self._idle_timeout = idle_timeout
self._config_timeout = config_timeout
async def handle_session(self, websocket: WebSocket) -> None:
"""Main session loop for a single WebSocket connection."""
await websocket.accept()
try:
# 1. Wait for session.config
config = await self._receive_config(websocket)
if config is None:
return # Error already sent, connection closing
# Validate model if specified
if config.model and hasattr(self._speech_service, "_check_model"):
error = await self._speech_service._check_model(
OpenAICreateSpeechRequest(input="ping", model=config.model)
)
if error is not None:
await self._send_error(websocket, str(error))
return
boundary_re = SPLIT_CLAUSE if config.split_granularity == "clause" else SPLIT_SENTENCE
splitter = SentenceSplitter(boundary_re=boundary_re)
sentence_index = 0
# 2. Receive text chunks until input.done
while True:
try:
raw = await asyncio.wait_for(
websocket.receive_text(),
timeout=self._idle_timeout,
)
except asyncio.TimeoutError:
await self._send_error(websocket, "Idle timeout: no message received")
return
if len(raw) > _MAX_INPUT_TEXT_MESSAGE_SIZE:
await self._send_error(websocket, "input.text message too large")
continue
try:
msg = json.loads(raw)
except json.JSONDecodeError:
await self._send_error(websocket, "Invalid JSON message")
continue
if not isinstance(msg, dict):
await self._send_error(websocket, "WebSocket messages must be JSON objects")
continue
msg_type = msg.get("type")
if msg_type == "input.text":
text = msg.get("text", "")
if not isinstance(text, str):
await self._send_error(websocket, "input.text requires a string value")
continue
sentences = splitter.add_text(text)
for sentence in sentences:
await self._generate_and_send(websocket, config, sentence, sentence_index)
sentence_index += 1
elif msg_type == "input.done":
# Flush remaining buffer
remaining = splitter.flush()
if remaining:
await self._generate_and_send(websocket, config, remaining, sentence_index)
sentence_index += 1
# Send session.done
await websocket.send_json(
{
"type": "session.done",
"total_sentences": sentence_index,
}
)
return
else:
await self._send_error(
websocket,
f"Unknown message type: {msg_type}",
)
except WebSocketDisconnect:
logger.info("Streaming speech: client disconnected")
except Exception as e:
logger.exception("Streaming speech session error: %s", e)
try:
await self._send_error(websocket, f"Internal error: {e}")
except Exception:
logger.debug("Failed to send error to streaming speech client", exc_info=True)
async def _receive_config(self, websocket: WebSocket) -> StreamingSpeechSessionConfig | None:
"""Wait for and validate the session.config message."""
try:
raw = await asyncio.wait_for(
websocket.receive_text(),
timeout=self._config_timeout,
)
except asyncio.TimeoutError:
await self._send_error(websocket, "Timeout waiting for session.config")
return None
if len(raw) > _MAX_CONFIG_MESSAGE_SIZE:
await self._send_error(websocket, "session.config message too large")
return None
try:
msg = json.loads(raw)
except json.JSONDecodeError:
await self._send_error(websocket, "Invalid JSON in session.config")
return None
if not isinstance(msg, dict):
await self._send_error(websocket, "session.config must be a JSON object")
return None
if msg.get("type") != "session.config":
await self._send_error(
websocket,
f"Expected session.config, got: {msg.get('type')}",
)
return None
try:
config = StreamingSpeechSessionConfig(**{k: v for k, v in msg.items() if k != "type"})
except ValidationError as e:
await self._send_error(websocket, f"Invalid session config: {e}")
return None
return config
async def _generate_and_send(
self,
websocket: WebSocket,
config: StreamingSpeechSessionConfig,
sentence_text: str,
sentence_index: int,
) -> None:
"""Generate audio for a single sentence and send it over WebSocket."""
response_format = config.response_format or "wav"
request = OpenAICreateSpeechRequest(
input=sentence_text,
model=config.model,
voice=config.voice,
task_type=config.task_type,
language=config.language,
instructions=config.instructions,
response_format=response_format,
speed=config.speed,
max_new_tokens=config.max_new_tokens,
initial_codec_chunk_frames=config.initial_codec_chunk_frames,
ref_audio=config.ref_audio,
ref_text=config.ref_text,
x_vector_only_mode=config.x_vector_only_mode,
stream=config.stream_audio,
)
start_payload = {
"type": "audio.start",
"sentence_index": sentence_index,
"sentence_text": sentence_text,
"format": response_format,
}
if config.stream_audio and response_format == "pcm":
start_payload["sample_rate"] = _PCM_SAMPLE_RATE
await websocket.send_json(start_payload)
total_bytes = 0
generation_failed = False
request_id = None
try:
if config.stream_audio:
request_id, generator, _ = await self._speech_service._prepare_speech_generation(request)
async with aclosing(self._speech_service._generate_pcm_chunks(generator, request_id)) as stream:
async for chunk in stream:
total_bytes += len(chunk)
await websocket.send_bytes(chunk)
else:
audio_bytes, _ = await self._speech_service._generate_audio_bytes(request)
total_bytes = len(audio_bytes)
await websocket.send_bytes(audio_bytes)
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 streaming speech request %s", request_id, exc_info=True)
raise
except Exception as e:
generation_failed = True
logger.error("Generation failed for sentence %d: %s", sentence_index, e)
await self._send_error(websocket, f"Generation failed for sentence {sentence_index}: {e}")
finally:
try:
await websocket.send_json(
{
"type": "audio.done",
"sentence_index": sentence_index,
"total_bytes": total_bytes,
"error": generation_failed,
}
)
except Exception:
logger.debug("Failed to send audio.done for sentence %d", sentence_index, exc_info=True)
@staticmethod
async def _send_error(websocket: WebSocket, message: str) -> None:
"""Send an error message to the client."""
try:
await websocket.send_json(
{
"type": "error",
"message": message,
}
)
except Exception:
pass # Connection may already be closed; safe to ignore
@@ -0,0 +1,120 @@
"""Multi-language sentence boundary detector for streaming TTS input.
Buffers incoming text and splits at sentence boundaries (English and CJK),
yielding complete sentences for audio generation.
"""
import re
from re import Pattern
# Maximum buffer size (in characters) to prevent unbounded memory growth.
_MAX_BUFFER_SIZE = 100_000 # ~100 KB of text
# Sentence-level: .!? + CJK sentence-ending 。!?
# NOTE: English requires trailing whitespace to confirm a boundary —
# end-of-string is NOT treated as a boundary (that is what flush() is for).
SPLIT_SENTENCE = re.compile(
r"(?<=[.!?])\s+"
r"|(?<=[。!?])"
)
# Clause-level: adds CJK commas , and semicolons ;
SPLIT_CLAUSE = re.compile(
r"(?<=[.!?])\s+"
r"|(?<=[。!?,;])"
)
# Default alias
_SENTENCE_BOUNDARY_RE = SPLIT_SENTENCE
class SentenceSplitter:
"""Incremental sentence splitter for streaming text input.
Buffers text and yields complete sentences when boundaries are detected.
Designed for TTS pipelines where text arrives incrementally (e.g., from STT).
Args:
min_sentence_length: Minimum character length for a sentence.
Sentences shorter than this are kept in the buffer to avoid
splitting on abbreviations like "Dr." or "U.S.".
boundary_re: Custom compiled regex for sentence boundaries.
Use ``SPLIT_SENTENCE`` (default) for sentence-level splitting,
``SPLIT_CLAUSE`` for finer-grained clause-level splitting,
or pass your own ``re.Pattern``.
"""
def __init__(
self,
min_sentence_length: int = 2,
boundary_re: Pattern[str] | None = None,
) -> None:
self._buffer: str = ""
self._min_sentence_length = min_sentence_length
self._boundary_re = boundary_re or _SENTENCE_BOUNDARY_RE
@property
def buffer(self) -> str:
"""Current buffered text."""
return self._buffer
def add_text(self, text: str) -> list[str]:
"""Add text to the buffer and return any complete sentences.
Args:
text: Incoming text chunk.
Returns:
List of complete sentences extracted from the buffer.
May be empty if no sentence boundary was found.
Raises:
ValueError: If the buffer exceeds the maximum size.
"""
if not text:
return []
self._buffer += text
if len(self._buffer) > _MAX_BUFFER_SIZE:
raise ValueError(
f"Text buffer exceeded maximum size ({_MAX_BUFFER_SIZE} chars). "
"Consider adding sentence-ending punctuation to your input."
)
return self._extract_sentences()
def flush(self) -> str | None:
"""Flush remaining buffered text as a final sentence.
Returns:
The remaining buffered text (stripped), or None if buffer is empty.
"""
remaining = self._buffer.strip()
self._buffer = ""
return remaining if remaining else None
def _extract_sentences(self) -> list[str]:
"""Split buffer at sentence boundaries, keeping incomplete text buffered."""
parts = self._boundary_re.split(self._buffer)
if len(parts) <= 1:
# No boundary found — keep everything in buffer
return []
sentences: list[str] = []
carry = ""
# All parts except the last are complete sentences
for i in range(len(parts) - 1):
text = carry + parts[i]
carry = ""
stripped = text.strip()
if len(stripped) >= self._min_sentence_length:
sentences.append(stripped)
elif stripped:
# Too short (e.g. "Dr.") — carry forward to next part
carry = text
# else: empty, skip
# Last part stays in buffer (may be incomplete)
self._buffer = carry + parts[-1]
return sentences
+2 -2
View File
@@ -9,7 +9,7 @@ from collections.abc import Callable
from multiprocessing import shared_memory as _shm
from typing import Any
from omegaconf import OmegaConf
from vllm_omni.config.yaml_util import to_dict as _omega_to_dict
logger = logging.getLogger(__name__)
@@ -315,7 +315,7 @@ def _to_dict(x: Any) -> dict[str, Any]:
try:
if isinstance(x, dict):
return dict(x)
return OmegaConf.to_container(x, resolve=True) # type: ignore[arg-type]
return _omega_to_dict(x)
except Exception:
try:
return dict(x)
+15 -8
View File
@@ -5,11 +5,11 @@ from dataclasses import asdict, fields, is_dataclass
from pathlib import Path
from typing import Any, get_args, get_origin
from omegaconf import OmegaConf
from vllm.logger import init_logger
from vllm.transformers_utils.config import get_config, get_hf_file_to_dict
from vllm.transformers_utils.repo_utils import file_or_path_exists
from vllm_omni.config.yaml_util import create_config, load_yaml_config, merge_configs
from vllm_omni.entrypoints.stage_utils import _to_dict
from vllm_omni.platforms import current_omni_platform
@@ -234,6 +234,11 @@ def resolve_model_config_path(model: str) -> str:
def load_stage_configs_from_model(model: str, base_engine_args: dict | None = None) -> list:
"""Load stage configurations from model's default config file.
.. deprecated::
This is the legacy OmegaConf-based loading path. New code should use
``StageConfigFactory.create_from_model()`` instead. This function will
be removed once all callers are migrated (see PR series [2/N]).
Loads stage configurations based on the model type and device type.
First tries to load a device-specific YAML file from stage_configs/{device_type}/
directory. If not found, falls back to the default config file.
@@ -259,6 +264,9 @@ def load_stage_configs_from_model(model: str, base_engine_args: dict | None = No
def load_stage_configs_from_yaml(config_path: str, base_engine_args: dict | None = None) -> list:
"""Load stage configurations from a YAML file.
.. deprecated::
Legacy OmegaConf-based loader. Will be removed in PR series [2/N].
Args:
config_path: Path to the YAML configuration file
@@ -267,17 +275,17 @@ def load_stage_configs_from_yaml(config_path: str, base_engine_args: dict | None
"""
if base_engine_args is None:
base_engine_args = {}
config_data = OmegaConf.load(config_path)
config_data = load_yaml_config(config_path)
stage_args = config_data.stage_args
global_async_chunk = config_data.get("async_chunk", False)
# Convert any nested dataclass objects to dicts before creating OmegaConf
# Convert any nested dataclass objects to dicts before creating DictConfig
base_engine_args = _convert_dataclasses_to_dict(base_engine_args)
base_engine_args = OmegaConf.create(base_engine_args)
base_engine_args = create_config(base_engine_args)
for stage_arg in stage_args:
base_engine_args_tmp = base_engine_args.copy()
# Update base_engine_args with stage-specific engine_args if they exist
if hasattr(stage_arg, "engine_args") and stage_arg.engine_args is not None:
base_engine_args_tmp = OmegaConf.merge(base_engine_args_tmp, stage_arg.engine_args)
base_engine_args_tmp = create_config(merge_configs(base_engine_args_tmp, stage_arg.engine_args))
stage_type = getattr(stage_arg, "stage_type", "llm")
if hasattr(stage_arg, "runtime") and stage_arg.runtime is not None and stage_type != "diffusion":
runtime_cfg = stage_arg.runtime
@@ -312,7 +320,7 @@ def load_and_resolve_stage_configs(
if not stage_configs:
if default_stage_cfg_factory is not None:
default_stage_cfg = default_stage_cfg_factory()
stage_configs = OmegaConf.create(default_stage_cfg)
stage_configs = create_config(default_stage_cfg)
else:
stage_configs = []
else:
@@ -347,6 +355,7 @@ def get_final_stage_id_for_e2e(
output_modalities = default_modalities
try:
final_stage_id_for_e2e = last_stage_id
for _sid in range(last_stage_id, -1, -1):
if (
getattr(stage_list[_sid], "final_output", False)
@@ -354,8 +363,6 @@ def get_final_stage_id_for_e2e(
):
final_stage_id_for_e2e = _sid
break
if final_stage_id_for_e2e < 0:
final_stage_id_for_e2e = last_stage_id
except Exception as e:
logger.debug(
"[Orchestrator] Failed to determine final stage for E2E; \