Merge main and preserve event-driven defaults in shared engine bases

Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
Sy03 committed 2026-09-16 20:14:33 +08:00
commit d2bb944863
371 files changed
+43235 -38379

No files matched your search

+16 -700
View File
@@ -20,31 +20,17 @@ from vllm import TokensPrompt
from vllm.engine.protocol import EngineClient, StreamingInput
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
from vllm.outputs import CompletionOutput, PoolingRequestOutput
from vllm.plugins.io_processors import get_io_processor
from vllm.outputs import PoolingRequestOutput
from vllm.pooling_params import PoolingParams
from vllm.renderers.inputs.preprocess import extract_prompt_components
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.tasks import SupportedTask
from vllm.utils import random_uuid
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.data import CuMemTag, OmniACK, OmniSleepTask, OmniWakeTask
from vllm_omni.engine.duplex.lease import DuplexLeaseActivity
from vllm_omni.engine.duplex.messages import (
DuplexFence,
DuplexSessionLifecycleMessage,
)
from vllm_omni.engine.messages import ErrorMessage, OutputMessage
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.engine.messages import ErrorMessage
from vllm_omni.entrypoints.async_omni_base import ABORT_TIMEOUT_S, AsyncOmniBase
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.duplex_request_client import (
DuplexRequestClient,
DuplexRequestOutputPort,
)
from vllm_omni.entrypoints.omni_base import (
OmniBase,
OmniEngineDeadError,
)
from vllm_omni.errors import client_error_metadata
from vllm_omni.inputs.data import OmniSamplingParams
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
@@ -58,73 +44,9 @@ if TYPE_CHECKING:
from vllm_omni.inputs.data import OmniInteractionPrompt, OmniPromptType
logger = init_logger(__name__)
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
# Blocking-wait interval for the event-driven final-output drain
# (selected by VLLM_OMNI_EVENT_DRIVEN_ORCH or the engine pipeline default): a
# message wakes the drain immediately via
# the janus queue's condition variable; this timeout only bounds how often the
# orchestrator liveness check runs while the pipeline is idle.
_FINAL_OUTPUT_BLOCKING_WAIT_S = 1.0
class AsyncEventResolver:
"""
A generic signal aggregator designed for synchronized handshakes in
distributed or multi-stage environments. Supports waiting for a specified
number (expected_count) of worker signals in both inline and multiprocess modes.
"""
def __init__(self, orchestrator=None):
self._pending_tasks: dict[str, dict] = {}
self.orchestrator = orchestrator
self._lock = asyncio.Lock()
def watch_task(self, task_id: str, expected_count: int = 1) -> asyncio.Future:
loop = asyncio.get_running_loop()
fut = loop.create_future()
self._pending_tasks[task_id] = {
"future": fut,
"expected_count": expected_count,
"received": [],
"start_time": time.time(),
}
return fut
async def resolve(self, ack: OmniACK):
tid = getattr(ack, "task_id", None)
if tid is None and isinstance(ack, dict):
tid = ack.get("task_id")
async with self._lock:
task_info = self._pending_tasks.get(tid)
if task_info is None:
logger.warning(f"Received stray ACK for task_id {tid}. Task might have timed out.")
return
task_info["received"].append(ack)
current_count = len(task_info["received"])
expected = task_info["expected_count"]
orchestrator = self.orchestrator
if orchestrator and hasattr(orchestrator, "metrics") and orchestrator.metrics:
freed = getattr(ack, "freed_bytes", 0)
if freed == 0 and isinstance(ack, dict):
freed = ack.get("freed_bytes", 0)
orchestrator.metrics.record_vram_reclaimed(freed)
logger.info(f"[Resolver] Task {tid} progress: {current_count}/{expected} ACKs received.")
if current_count >= expected:
self._pending_tasks.pop(tid)
fut = task_info["future"]
if not fut.done():
elapsed = time.time() - task_info["start_time"]
logger.info(f"[Resolver] Task {tid} completed successfully in {elapsed:.2f}s.")
fut.set_result(task_info["received"])
class AsyncOmni(EngineClient, OmniBase):
class AsyncOmni(AsyncOmniBase, EngineClient):
"""Asynchronous unified entry point for multi-stage pipelines using AsyncOmniEngine.
This is the refactored version that uses AsyncOmniEngine instead of
@@ -153,8 +75,13 @@ class AsyncOmni(EngineClient, OmniBase):
... print(output)
"""
def __init__(self, *args: Any, model: str = "", **kwargs: Any) -> None:
OmniBase.__init__(self, model=model, **kwargs)
def _create_engine(self, **engine_kwargs: Any) -> AsyncOmniEngine:
return AsyncOmniEngine(**engine_kwargs)
def __init__(self, model: str = "", *args: Any, **kwargs: Any) -> None:
tts_max_instructions_length = kwargs.get("tts_max_instructions_length", None)
AsyncOmniBase.__init__(self, *args, model=model, **kwargs)
self.tts_max_instructions_length = tts_max_instructions_length
self._pause_cond: asyncio.Condition = asyncio.Condition()
self._paused: bool = False
# In-flight EngineCore submits (non-streaming add_request, or each
@@ -171,294 +98,6 @@ class AsyncOmni(EngineClient, OmniBase):
self._sleeping_tags: set[str] = set()
self._stage_sleeping_tags: dict[int, set[str]] = {}
self._level2_sleeping: bool = False
self._duplex_request_client: DuplexRequestClient | None = None
self.duplex_lifecycle_events: asyncio.Queue[DuplexSessionLifecycleMessage] = asyncio.Queue()
self.final_output_task: asyncio.Task | None = None
self.event_resolver = AsyncEventResolver(orchestrator=self)
self.config_path = self.engine.config_path
self.tts_max_instructions_length = kwargs.get("tts_max_instructions_length", None)
self.input_processor = self.engine.input_processor
self.endpoint_restrictions = self.engine.endpoint_restrictions
self.duplex_session_config = self.engine.duplex_session_config
self.duplex_serving_adapter_path = self.engine.duplex_serving_adapter_path
stage_index = self._get_comprehension_stage_index()
if stage_index is None:
self.io_processor = None
else:
vllm_config = self.engine.stage_vllm_configs[stage_index]
io_processor_plugin = vllm_config.model_config.io_processor_plugin
renderer = self.renderer
if renderer is None:
from vllm.renderers import renderer_from_config
renderer = renderer_from_config(vllm_config)
self.io_processor = get_io_processor(vllm_config, renderer, io_processor_plugin)
def _resolve_transfer_replica(self, stage_id: int, request_id: str) -> int | None:
"""Look up the sticky-routed replica for (stage_id, request_id).
Used as the ``replica_resolver`` callback by ``OrchestratorAggregator``
to label transfer_* metrics without plumbing replica ids through
``TransferEdgeStats`` / ``StageRequestStats`` / connector adapters.
Returns None when stage_id is out of range or the request hasn't been
bound to a replica yet — the metric emit then defensive-skips.
"""
pools = getattr(self.engine, "stage_pools", None)
if pools is None or not (0 <= stage_id < len(pools)):
return None
return pools[stage_id].get_bound_replica_id(request_id)
def _get_comprehension_stage_index(self) -> int | None:
fallback_idx: int | None = None
for idx, stage_client in enumerate(self.engine.stage_clients):
stage_vllm_config = self.engine.stage_vllm_configs[idx]
if stage_vllm_config is None:
continue
if fallback_idx is None:
fallback_idx = idx
if stage_client.is_comprehension:
return idx
return fallback_idx
@property
def renderer(self):
"""Return the renderer from the engine input processor when available."""
if self.input_processor is None:
return None
return self.input_processor.renderer
@property
def vllm_config(self):
"""Return the vLLM config for the comprehension stage when present."""
stage_index = self._get_comprehension_stage_index()
if stage_index is None:
return None
return self.engine.stage_vllm_configs[stage_index]
async def get_vllm_config(self) -> Any:
"""Compatibility helper for call sites expecting async vllm config access."""
return self.vllm_config
def get_diffusion_od_config(self) -> Any | None:
"""Return the diffusion-stage config when the pipeline has one."""
saw_diffusion_stage = False
for stage_client in self.engine.stage_clients:
if getattr(stage_client, "stage_type", None) != "diffusion":
continue
saw_diffusion_stage = True
od_config = getattr(stage_client, "od_config", None)
if od_config is not None:
return od_config
inner_engine = getattr(stage_client, "_engine", None)
od_config = getattr(inner_engine, "od_config", None)
if od_config is not None:
return od_config
# Out-of-process diffusion clients don't carry od_config (it lives in the
# worker); fall back to the engine's model_class_name resolution.
if saw_diffusion_stage:
return self.engine.get_diffusion_od_config()
return None
@property
def model_config(self):
"""Return the model config for the comprehension stage when present."""
vllm_config = self.vllm_config
if vllm_config is None:
return None
return vllm_config.model_config
@staticmethod
def _get_unique_request_id(external_request_id: str):
"""Get a random new request ID for this request; at the server level,
this is usually set by the calling entrypoint, but in direct calls, we
need to set it explicitly since we do not allow empty IDs.
NOTE: in the upstream vLLM, this is done in the InputProcessor's
`assign_request_id`.
"""
uuid = random_uuid()
prefix = "" if not external_request_id else f"{external_request_id}-"
return f"{prefix}{uuid:.8}"
async def open_duplex_session_async(
self,
session_id: str,
*,
session_mode: str = "duplex",
capabilities: dict[str, object] | None = None,
session_config: dict[str, object] | None = None,
runtime_config: dict[str, object] | None = None,
fence: DuplexFence,
timeout: float | None = 10.0,
) -> dict[str, object]:
"""Open an engine-level duplex session when the backend supports it."""
return await self._get_duplex_request_client().open(
session_id,
session_mode=session_mode,
capabilities=capabilities,
session_config=session_config,
runtime_config=runtime_config,
fence=fence,
timeout=timeout,
)
async def append_duplex_input_async(
self,
session_id: str,
*,
mode: str,
payload: object,
operation_id: str | None = None,
final: bool = False,
expected_epoch: int | None = None,
fence: DuplexFence,
timeout: float | None = 10.0,
collect_outputs: bool = True,
) -> dict[str, object]:
"""Append input to an engine-level duplex session."""
return await self._get_duplex_request_client().append(
session_id,
mode=mode,
payload=payload,
operation_id=operation_id,
final=final,
expected_epoch=expected_epoch,
fence=fence,
timeout=timeout,
collect_outputs=collect_outputs,
)
async def collect_duplex_data_plane_outputs_async(
self,
request_id: str,
*,
response_stage_id: int | None = None,
timeout: float | None = 10.0,
) -> list[OmniRequestOutput]:
"""Collect the next duplex data-plane output batch for a live request."""
return await self._get_duplex_request_client().collect_registered_outputs(
request_id,
response_stage_id=response_stage_id,
timeout=timeout,
)
async def signal_duplex_turn_async(
self,
session_id: str,
*,
event: str,
fence: DuplexFence,
next_fence: DuplexFence | None = None,
session_config: dict[str, object] | None = None,
runtime_config: dict[str, object] | None = None,
timeout: float | None = 10.0,
) -> dict[str, object]:
"""Send a turn/control signal to an engine-level duplex session."""
return await self._get_duplex_request_client().signal(
session_id,
event=event,
fence=fence,
next_fence=next_fence,
session_config=session_config,
runtime_config=runtime_config,
timeout=timeout,
)
async def close_duplex_session_async(
self,
session_id: str,
*,
reason: str = "client_close",
fence: DuplexFence,
timeout: float | None = 10.0,
) -> dict[str, object]:
"""Close an engine-level duplex session."""
return await self._get_duplex_request_client().close(
session_id,
reason=reason,
fence=fence,
timeout=timeout,
)
async def touch_duplex_session_async(
self,
session_id: str,
*,
fence: DuplexFence,
activity: DuplexLeaseActivity,
timeout: float | None = 10.0,
) -> dict[str, object]:
return await self._get_duplex_request_client().touch(
session_id,
fence=fence,
activity=activity,
timeout=timeout,
)
async def resume_duplex_session_async(
self,
session_id: str,
*,
fence: DuplexFence,
expected_lease_generation: int,
timeout: float | None = 10.0,
) -> dict[str, object]:
return await self._get_duplex_request_client().resume(
session_id,
fence=fence,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
)
def _get_duplex_request_client(self) -> DuplexRequestClient:
client = getattr(self, "_duplex_request_client", None)
if client is None:
engine = getattr(self, "engine", None)
client = DuplexRequestClient(
engine,
DuplexRequestOutputPort(
request_states=getattr(self, "request_states", {}),
num_stages=getattr(engine, "num_stages", 1),
log_stats=getattr(self, "log_stats", False),
start_output_handler=self._final_output_handler,
process_single_result=self._process_single_result,
),
)
self._duplex_request_client = client
return client
@staticmethod
def _duplex_data_plane_request_info(result: dict[str, object]) -> tuple[str | None, int | None]:
return DuplexRequestClient.request_info(result)
async def _collect_duplex_data_plane_outputs(
self,
request_id: str,
req_state: ClientRequestState,
*,
response_stage_id: int | None,
timeout: float | None,
) -> list[OmniRequestOutput]:
return await self._get_duplex_request_client().collect_outputs(
request_id,
req_state,
response_stage_id=response_stage_id,
timeout=timeout,
)
@classmethod
def _is_direct_duplex_data_plane_response(cls, output: object) -> bool:
return DuplexRequestClient.is_direct_response(output)
@classmethod
def _duplex_multimodal_output(cls, output: object) -> dict[str, object]:
return DuplexRequestClient.multimodal_output(output)
# ==================== Generate Method ====================
@@ -662,12 +301,12 @@ class AsyncOmni(EngineClient, OmniBase):
except (asyncio.CancelledError, GeneratorExit):
self._record_request_failure_once(request_id, reason="client_disconnect")
await self._abort_internal_requests(request_id)
await self._abort_internal_requests(request_id, timeout=ABORT_TIMEOUT_S)
logger.info(f"[AsyncOmni] Request {request_id} aborted.")
raise
except Exception as e:
self._record_request_failure_once(request_id, reason="stage_error")
await self._abort_internal_requests(request_id)
await self._abort_internal_requests(request_id, timeout=ABORT_TIMEOUT_S)
logger.info(f"[AsyncOmni] Request {request_id} failed (input error): {e}")
raise
finally:
@@ -855,200 +494,6 @@ class AsyncOmni(EngineClient, OmniBase):
"""
raise NotImplementedError("AsyncOmni.encode is not implemented.")
# ==================== Processing Methods ====================
async def _process_orchestrator_results(
self,
request_id: str,
metrics: OrchestratorMetrics,
final_stage_id_for_e2e: int,
req_start_ts: dict[str, float],
wall_start_ts: float,
) -> AsyncGenerator[OmniRequestOutput, None]:
"""Read results from the Orchestrator (via the request's asyncio.Queue)
and yield OmniRequestOutput objects.
The Orchestrator handles all stage-to-stage transfers. This method
only processes final outputs that arrive on the per-request queue.
"""
req_state = self.request_states.get(request_id)
if req_state is None:
return
while True:
result = await req_state.queue.get()
if isinstance(result, ErrorMessage):
logger.error(
"[AsyncOmni] Orchestrator error for req=%s stage-%s: %s",
request_id,
result.stage_id,
result.error,
)
if result.fatal:
raise OmniEngineDeadError(
result.error,
error_stage_id=result.stage_id,
)
self._raise_nonfatal_error_message(result)
if not isinstance(result, OutputMessage):
logger.warning("[AsyncOmni] Dropping unexpected per-request message %r", result)
continue
stage_id = result.stage_id
self._check_engine_output_error(result, request_id, stage_id)
# Process the result (constructs OmniRequestOutput)
output_to_yield = self._process_single_result(
result,
stage_id,
metrics,
req_start_ts,
wall_start_ts,
final_stage_id_for_e2e,
)
if output_to_yield:
# Set the external request ID back to the user yielded input
output_to_yield.request_id = req_state.external_request_id or output_to_yield.request_id
logger.debug(
"[AsyncOmni] req=%s stage-%s yielding final_output_type=%s",
request_id,
stage_id,
getattr(output_to_yield, "final_output_type", None),
)
yield output_to_yield
# The Orchestrator sets "finished" when the final stage is done
if result.finished:
break
# ==================== Output Handler ====================
def _final_output_handler(self) -> None:
"""Start the final output handler if not already running.
This handler reads messages from the Orchestrator output queue and
routes them to per-request asyncio.Queues.
"""
if self.final_output_task is not None:
return
engine = self.engine
# Event-driven drain (explicit env value or the engine pipeline default): block on the
# queue's condition variable in a dedicated thread instead of the
# get_nowait + 1 ms sleep cadence. Same flag as the orchestrator-side
# event-driven loop (vllm_omni/engine/orchestrator.py).
from vllm_omni.engine.orchestrator import _event_driven_orch_enabled
event_driven_drain = _event_driven_orch_enabled(
default=bool(getattr(engine, "_event_driven_orch_default", False))
) and hasattr(engine, "get_output_blocking_async")
async def _final_output_loop():
"""Background coroutine that dispatches final outputs to request queues."""
try:
while True:
if event_driven_drain:
msg = await engine.get_output_blocking_async(timeout=_FINAL_OUTPUT_BLOCKING_WAIT_S)
if msg is None:
# Timed out with the orchestrator alive; loop for
# the periodic liveness check.
continue
else:
msg = await engine.try_get_output_async()
if msg is None:
await asyncio.sleep(_FINAL_OUTPUT_IDLE_SLEEP_S)
continue
if isinstance(msg, dict) and msg.get("type") == "ack":
ack_data = msg.get("ack")
tid = getattr(ack_data, "task_id", "unknown")
logger.info(f"[{self._name}] Intercepted wrapped ACK for task {tid}")
await self.event_resolver.resolve(ack_data)
continue
if isinstance(msg, OmniACK):
logger.info(f"[{self._name}] Intercepted raw ACK object: {msg.task_id}")
await self.event_resolver.resolve(msg)
continue
if hasattr(msg, "task_id"):
tid = getattr(msg, "task_id")
logger.info(f"[{self._name}] Intercepted task-ID object: {tid}")
await self.event_resolver.resolve(msg)
continue
if getattr(msg, "type", None) == "duplex_session_lifecycle":
await self.duplex_lifecycle_events.put(msg)
continue
if isinstance(msg, ErrorMessage):
# Route request-scoped errors to that request's queue and
# keep the loop alive. A request whose stage replica died
# and was evicted gets a fatal error delivered here; only
# that request fails (its consumer raises), the server
# stays up for other stages/requests (#4285). A fatal
# error without a request_id is a genuine engine-wide
# death and falls through to the except handler below.
if msg.request_id is not None:
req_state = self.request_states.get(msg.request_id)
if req_state is not None:
await req_state.queue.put(msg)
else:
logger.warning(
"[%s] dropping error for unknown req %s",
self._name,
msg.request_id,
)
continue
if not msg.fatal:
continue
should_continue, _, stage_id, req_state = self._handle_output_message(msg)
if should_continue:
continue
req_state.stage_id = stage_id
# Route to the per-request queue
await req_state.queue.put(msg)
except asyncio.CancelledError:
raise
except OmniEngineDeadError as e:
logger.error("[AsyncOmni] Engine dead: %s", e)
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
error=str(e),
fatal=True,
request_id=req_state.request_id,
stage_id=e.error_stage_id,
)
await req_state.queue.put(error_msg)
except EngineDeadError as e:
logger.error("[AsyncOmni] Engine dead: %s", e)
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
error=str(e),
fatal=True,
request_id=req_state.request_id,
)
await req_state.queue.put(error_msg)
except Exception as e:
logger.exception("[AsyncOmni] final_output_loop failed.")
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
request_id=req_state.request_id,
error=str(e),
)
await req_state.queue.put(error_msg)
self.final_output_task = None
self.final_output_task = asyncio.create_task(_final_output_loop())
logger.debug("[AsyncOmni] Final output handler started")
# ==================== Control Methods ====================
async def collective_rpc(
@@ -1123,14 +568,14 @@ class AsyncOmni(EngineClient, OmniBase):
return all(bool(item) for item in result)
return bool(result)
async def abort(self, request_id: str | Iterable[str]) -> None:
async def abort(self, request_id: str | Iterable[str], *, timeout: float | None = None) -> None:
"""Abort request(s) via the Orchestrator."""
request_ids = [request_id] if isinstance(request_id, str) else list(request_id)
# Map the external user request IDs to internal IDs used by the Orchestrator.
# NOTE: If the user request_id matches multiple requests, all of them will be
# aborted. This is also what happens in this case in vLLM's output processor.
internal_ids = [s.request_id for s in self.request_states.values() if s.external_request_id in request_ids]
await self._abort(internal_ids)
await self._abort(internal_ids, timeout=timeout)
async def submit_interaction_async(
self,
@@ -1172,86 +617,6 @@ class AsyncOmni(EngineClient, OmniBase):
if self.log_stats:
logger.info("[AsyncOmni] Queued interaction for request %s", request_id)
async def _abort_internal_requests(self, request_id: str | Iterable[str]):
"""Abort request(s) via the Orchestrator given internal request IDs,
which take the format <external_request_id>-<UUID>.
"""
request_ids = [request_id] if isinstance(request_id, str) else list(request_id)
# Request IDs are already internal, so we just need to get the matching states.
internal_req_ids = [rid for rid in request_ids if rid in self.request_states]
await self._abort(internal_req_ids)
async def _abort(self, request_ids: list[str]) -> None:
"""Abort request IDs via the engine and enqueue terminal abort outputs.
Waits for orchestrator abort acknowledgment, enqueues any AR terminal
abort outputs (partial tokens) into each request's asyncio queue, then
cancels the input pump. Frontend ``request_states`` stay registered so
``generate()`` can consume the terminal message in
``_process_orchestrator_results`` and run normal cleanup.
When ``abort_async`` returns no output for an active request (OP not
registered yet, unbound replica, or orchestrator id drop), enqueue a
synthetic finished abort so ``generate()`` cannot hang on ``queue.get``.
"""
abort_outputs = await self.engine.abort_async(request_ids) or []
delivered: set[str] = set()
for output_msg in abort_outputs:
req_id = getattr(output_msg, "request_id", None)
if req_id is None:
continue
state = self.request_states.get(req_id)
if state is None:
logger.debug("[AsyncOmni] Dropping abort output for unknown req %s", req_id)
continue
await state.queue.put(output_msg)
delivered.add(req_id)
for rid in request_ids:
state = self.request_states.get(rid)
if state is not None and rid not in delivered:
queue = getattr(state, "queue", None)
if queue is not None:
await state.queue.put(self._synthetic_abort_output_message(rid))
delivered.add(rid)
for rid in request_ids:
self._record_request_failure_once(rid, reason="client_abort")
state = self.request_states.get(rid)
input_stream_task = getattr(state, "input_stream_task", None)
if input_stream_task is not None and not input_stream_task.done():
input_stream_task.cancel()
if self.log_stats:
logger.info("[AsyncOmni] Aborted request(s) %s", ",".join(request_ids))
@staticmethod
def _synthetic_abort_output_message(request_id: str) -> OutputMessage:
"""Terminal abort OutputMessage used when the engine returned none."""
engine_output = OmniRequestOutput(
request_id=request_id,
finished=True,
stage_id=0,
final_output_type="text",
outputs=[
CompletionOutput(
index=0,
text="",
token_ids=[],
cumulative_logprob=None,
logprobs=None,
finish_reason="abort",
stop_reason=None,
)
],
)
return OutputMessage(
request_id=request_id,
stage_id=0,
replica_id=None,
engine_outputs=engine_output,
metrics=None,
finished=True,
stage_submit_ts=None,
)
def _split_stage_ids_by_type(self, stage_ids: list[int] | None = None) -> tuple[list[int], list[int]]:
"""Split stage ids into AR/LLM (EngineCore) vs diffusion (worker RPC)."""
n_stages = len(self.engine.stage_clients)
@@ -1681,42 +1046,6 @@ class AsyncOmni(EngineClient, OmniBase):
# ==================== Properties ====================
@property
def is_running(self) -> bool:
"""Check if the engine is running."""
orchestrator_alive = self.engine.is_alive()
task_alive = self.final_output_task is not None and not self.final_output_task.done()
return orchestrator_alive and task_alive
@property
def errored(self) -> bool:
"""Whether the engine is in a process-fatal error state.
Delegates to ``OmniBase.errored``, which is true only when the
orchestrator thread is dead; per-stage liveness is reported via
``check_health`` instead. Redeclared here to satisfy the
``EngineClient`` abstract-property requirement (Python's ABC
mechanism does not resolve abstract methods from sibling MRO
entries).
"""
return OmniBase.errored.fget(self) # type: ignore[union-attr]
@property
def _name(self) -> str:
return "AsyncOrchestrator"
@property
def is_stopped(self) -> bool:
"""EngineClient abstract property implementation."""
return self.errored
@property
def dead_error(self) -> BaseException:
"""EngineClient abstract property implementation."""
return OmniEngineDeadError()
# ==================== EngineClient Interface ====================
async def get_input_preprocessor(self) -> InputProcessor:
"""Get input preprocessor."""
return self.input_processor
@@ -1777,16 +1106,3 @@ class AsyncOmni(EngineClient, OmniBase):
async def get_supported_tasks(self) -> tuple[SupportedTask, ...]:
"""Return the task set exposed by the orchestrator-backed engine."""
return tuple(self.engine.supported_tasks)
async def check_health(self) -> None:
"""Check engine health by verifying the Orchestrator process is alive."""
OmniBase.check_health(self)
# ==================== Shutdown ====================
def shutdown(self, timeout: float | None = None) -> None:
"""Shutdown the engine."""
if self.final_output_task is not None:
self.final_output_task.cancel()
self.final_output_task = None
OmniBase.shutdown(self)
+559
View File
@@ -0,0 +1,559 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""AsyncOmniBase: the asyncio-side foundation shared by ``AsyncOmni`` and ``DuplexOmni``.
Owns the engine output pump (one consumer of the engine output queue that
routes messages to per-request queues, ACK resolvers, or a subclass hook),
engine-dead fan-out, health/shutdown, and the config accessors. Turn-based
request handling lives in ``AsyncOmni``; duplex sessions in ``DuplexOmni``.
"""
from __future__ import annotations
import asyncio
import os
import time
from collections.abc import AsyncGenerator, Iterable
from typing import Any
from vllm.logger import init_logger
from vllm.outputs import CompletionOutput
from vllm.plugins.io_processors import get_io_processor
from vllm.utils import random_uuid
from vllm.v1.engine.exceptions import EngineDeadError
from vllm_omni.diffusion.data import OmniACK
from vllm_omni.engine.messages import ErrorMessage, OutputMessage
from vllm_omni.entrypoints.omni_base import (
OmniBase,
OmniEngineDeadError,
)
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.outputs import OmniRequestOutput
logger = init_logger(__name__)
_FINAL_OUTPUT_IDLE_SLEEP_S = 0.001
# Blocking-wait interval for the event-driven final-output drain
# (explicit env value or the engine pipeline default): a message wakes the drain immediately via
# the janus queue's condition variable; this timeout only bounds how often the
# orchestrator liveness check runs while the pipeline is idle.
_FINAL_OUTPUT_BLOCKING_WAIT_S = 1.0
# Shared DELETE / generate() cleanup abort bound. Env is the documented knob.
ABORT_TIMEOUT_S = float(os.environ.get("VLLM_OMNI_ABORT_TIMEOUT", 2.0))
class AsyncEventResolver:
"""
A generic signal aggregator designed for synchronized handshakes in
distributed or multi-stage environments. Supports waiting for a specified
number (expected_count) of worker signals in both inline and multiprocess modes.
"""
def __init__(self, orchestrator=None):
self._pending_tasks: dict[str, dict] = {}
self.orchestrator = orchestrator
self._lock = asyncio.Lock()
def watch_task(self, task_id: str, expected_count: int = 1) -> asyncio.Future:
loop = asyncio.get_running_loop()
fut = loop.create_future()
self._pending_tasks[task_id] = {
"future": fut,
"expected_count": expected_count,
"received": [],
"start_time": time.time(),
}
return fut
async def resolve(self, ack: OmniACK):
tid = getattr(ack, "task_id", None)
if tid is None and isinstance(ack, dict):
tid = ack.get("task_id")
async with self._lock:
task_info = self._pending_tasks.get(tid)
if task_info is None:
logger.warning(f"Received stray ACK for task_id {tid}. Task might have timed out.")
return
task_info["received"].append(ack)
current_count = len(task_info["received"])
expected = task_info["expected_count"]
orchestrator = self.orchestrator
if orchestrator and hasattr(orchestrator, "metrics") and orchestrator.metrics:
freed = getattr(ack, "freed_bytes", 0)
if freed == 0 and isinstance(ack, dict):
freed = ack.get("freed_bytes", 0)
orchestrator.metrics.record_vram_reclaimed(freed)
logger.info(f"[Resolver] Task {tid} progress: {current_count}/{expected} ACKs received.")
if current_count >= expected:
self._pending_tasks.pop(tid)
fut = task_info["future"]
if not fut.done():
elapsed = time.time() - task_info["start_time"]
logger.info(f"[Resolver] Task {tid} completed successfully in {elapsed:.2f}s.")
fut.set_result(task_info["received"])
class AsyncOmniBase(OmniBase):
"""Shared asyncio foundation of the async entrypoints (see module docstring)."""
def __init__(self, *args: Any, model: str = "", **kwargs: Any) -> None:
OmniBase.__init__(self, model=model, **kwargs)
self.final_output_task: asyncio.Task | None = None
self.event_resolver = AsyncEventResolver(orchestrator=self)
self.config_path = self.engine.config_path
self.input_processor = self.engine.input_processor
self.endpoint_restrictions = self.engine.endpoint_restrictions
stage_index = self._get_comprehension_stage_index()
if stage_index is None:
self.io_processor = None
else:
vllm_config = self.engine.stage_vllm_configs[stage_index]
io_processor_plugin = vllm_config.model_config.io_processor_plugin
renderer = self.renderer
if renderer is None:
from vllm.renderers import renderer_from_config
renderer = renderer_from_config(vllm_config)
self.io_processor = get_io_processor(vllm_config, renderer, io_processor_plugin)
# ==================== Subclass seam ====================
def _route_engine_message(self, msg: Any) -> bool:
"""Consume an engine output message the subclass owns (return True when consumed)."""
del msg
return False
def _on_engine_dead(self, error: str) -> None:
"""Seam: the output pump is ending because the engine died (default: nothing).
``DuplexOmni`` ends every session handle here; turn-based requests are
already failed through their per-request queues.
"""
del error
def _resolve_transfer_replica(self, stage_id: int, request_id: str) -> int | None:
"""Look up the sticky-routed replica for (stage_id, request_id).
Used as the ``replica_resolver`` callback by ``OrchestratorAggregator``
to label transfer_* metrics without plumbing replica ids through
``TransferEdgeStats`` / ``StageRequestStats`` / connector adapters.
Returns None when stage_id is out of range or the request hasn't been
bound to a replica yet — the metric emit then defensive-skips.
"""
pools = getattr(self.engine, "stage_pools", None)
if pools is None or not (0 <= stage_id < len(pools)):
return None
return pools[stage_id].get_bound_replica_id(request_id)
def _get_comprehension_stage_index(self) -> int | None:
fallback_idx: int | None = None
for idx, stage_client in enumerate(self.engine.stage_clients):
stage_vllm_config = self.engine.stage_vllm_configs[idx]
if stage_vllm_config is None:
continue
if fallback_idx is None:
fallback_idx = idx
if stage_client.is_comprehension:
return idx
return fallback_idx
@property
def renderer(self):
"""Return the renderer from the engine input processor when available."""
if self.input_processor is None:
return None
return self.input_processor.renderer
@property
def vllm_config(self):
"""Return the vLLM config for the comprehension stage when present."""
stage_index = self._get_comprehension_stage_index()
if stage_index is None:
return None
return self.engine.stage_vllm_configs[stage_index]
async def get_vllm_config(self) -> Any:
"""Compatibility helper for call sites expecting async vllm config access."""
return self.vllm_config
def get_diffusion_od_config(self) -> Any | None:
"""Return the diffusion-stage config when the pipeline has one."""
saw_diffusion_stage = False
for stage_client in self.engine.stage_clients:
if getattr(stage_client, "stage_type", None) != "diffusion":
continue
saw_diffusion_stage = True
od_config = getattr(stage_client, "od_config", None)
if od_config is not None:
return od_config
inner_engine = getattr(stage_client, "_engine", None)
od_config = getattr(inner_engine, "od_config", None)
if od_config is not None:
return od_config
# Out-of-process diffusion clients don't carry od_config (it lives in the
# worker); fall back to the engine's model_class_name resolution.
if saw_diffusion_stage:
return self.engine.get_diffusion_od_config()
return None
@property
def model_config(self):
"""Return the model config for the comprehension stage when present."""
vllm_config = self.vllm_config
if vllm_config is None:
return None
return vllm_config.model_config
@staticmethod
def _get_unique_request_id(external_request_id: str):
"""Get a random new request ID for this request; at the server level,
this is usually set by the calling entrypoint, but in direct calls, we
need to set it explicitly since we do not allow empty IDs.
NOTE: in the upstream vLLM, this is done in the InputProcessor's
`assign_request_id`.
"""
uuid = random_uuid()
prefix = "" if not external_request_id else f"{external_request_id}-"
return f"{prefix}{uuid:.8}"
# ==================== Processing Methods ====================
async def _process_orchestrator_results(
self,
request_id: str,
metrics: OrchestratorMetrics,
final_stage_id_for_e2e: int,
req_start_ts: dict[str, float],
wall_start_ts: float,
) -> AsyncGenerator[OmniRequestOutput, None]:
"""Read results from the Orchestrator (via the request's asyncio.Queue)
and yield OmniRequestOutput objects.
The Orchestrator handles all stage-to-stage transfers. This method
only processes final outputs that arrive on the per-request queue.
"""
req_state = self.request_states.get(request_id)
if req_state is None:
return
while True:
result = await req_state.queue.get()
if isinstance(result, ErrorMessage):
logger.error(
"[AsyncOmni] Orchestrator error for req=%s stage-%s: %s",
request_id,
result.stage_id,
result.error,
)
if result.fatal:
raise OmniEngineDeadError(
result.error,
error_stage_id=result.stage_id,
)
self._raise_nonfatal_error_message(result)
if not isinstance(result, OutputMessage):
logger.warning("[AsyncOmni] Dropping unexpected per-request message %r", result)
continue
stage_id = result.stage_id
self._check_engine_output_error(result, request_id, stage_id)
# Process the result (constructs OmniRequestOutput)
output_to_yield = self._process_single_result(
result,
stage_id,
metrics,
req_start_ts,
wall_start_ts,
final_stage_id_for_e2e,
)
if output_to_yield:
# Set the external request ID back to the user yielded input
output_to_yield.request_id = req_state.external_request_id or output_to_yield.request_id
logger.debug(
"[AsyncOmni] req=%s stage-%s yielding final_output_type=%s",
request_id,
stage_id,
getattr(output_to_yield, "final_output_type", None),
)
yield output_to_yield
# The Orchestrator sets "finished" when the final stage is done
if result.finished:
break
# ==================== Output Handler ====================
def _final_output_handler(self) -> None:
"""Start the final output handler if not already running.
This handler reads messages from the Orchestrator output queue and
routes them to per-request asyncio.Queues.
"""
if self.final_output_task is not None:
return
engine = self.engine
# Event-driven drain (explicit env value or the engine pipeline default): block on the
# queue's condition variable in a dedicated thread instead of the
# get_nowait + 1 ms sleep cadence. Same flag as the orchestrator-side
# event-driven loop (vllm_omni/engine/orchestrator.py).
from vllm_omni.engine.orchestrator import _event_driven_orch_enabled
event_driven_drain = _event_driven_orch_enabled(
default=bool(getattr(engine, "_event_driven_orch_default", False))
) and hasattr(engine, "get_output_blocking_async")
async def _final_output_loop():
"""Background coroutine that dispatches final outputs to request queues."""
try:
while True:
if event_driven_drain:
msg = await engine.get_output_blocking_async(timeout=_FINAL_OUTPUT_BLOCKING_WAIT_S)
if msg is None:
# Timed out with the orchestrator alive; loop for
# the periodic liveness check.
continue
else:
msg = await engine.try_get_output_async()
if msg is None:
await asyncio.sleep(_FINAL_OUTPUT_IDLE_SLEEP_S)
continue
if self._route_engine_message(msg):
continue
if isinstance(msg, dict) and msg.get("type") == "ack":
ack_data = msg.get("ack")
tid = getattr(ack_data, "task_id", "unknown")
logger.info(f"[{self._name}] Intercepted wrapped ACK for task {tid}")
await self.event_resolver.resolve(ack_data)
continue
if isinstance(msg, OmniACK):
logger.info(f"[{self._name}] Intercepted raw ACK object: {msg.task_id}")
await self.event_resolver.resolve(msg)
continue
if hasattr(msg, "task_id"):
tid = getattr(msg, "task_id")
logger.info(f"[{self._name}] Intercepted task-ID object: {tid}")
await self.event_resolver.resolve(msg)
continue
if isinstance(msg, ErrorMessage):
# Route request-scoped errors to that request's queue and
# keep the loop alive. A request whose stage replica died
# and was evicted gets a fatal error delivered here; only
# that request fails (its consumer raises), the server
# stays up for other stages/requests (#4285). A fatal
# error without a request_id is a genuine engine-wide
# death and falls through to the except handler below.
if msg.request_id is not None:
req_state = self.request_states.get(msg.request_id)
if req_state is not None:
await req_state.queue.put(msg)
else:
logger.warning(
"[%s] dropping error for unknown req %s",
self._name,
msg.request_id,
)
continue
if not msg.fatal:
continue
should_continue, _, stage_id, req_state = self._handle_output_message(msg)
if should_continue:
continue
req_state.stage_id = stage_id
# Route to the per-request queue
await req_state.queue.put(msg)
except asyncio.CancelledError:
raise
except OmniEngineDeadError as e:
logger.error("[%s] Engine dead: %s", self._name, e)
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
error=str(e),
fatal=True,
request_id=req_state.request_id,
stage_id=e.error_stage_id,
)
await req_state.queue.put(error_msg)
self._on_engine_dead(str(e))
except EngineDeadError as e:
logger.error("[%s] Engine dead: %s", self._name, e)
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
error=str(e),
fatal=True,
request_id=req_state.request_id,
)
await req_state.queue.put(error_msg)
self._on_engine_dead(str(e))
except Exception as e:
logger.exception("[%s] final_output_loop failed.", self._name)
for req_state in list(self.request_states.values()):
error_msg = ErrorMessage(
request_id=req_state.request_id,
error=str(e),
)
await req_state.queue.put(error_msg)
self.final_output_task = None
self._on_engine_dead(str(e))
self.final_output_task = asyncio.create_task(_final_output_loop())
logger.debug("[AsyncOmni] Final output handler started")
async def _abort_internal_requests(
self,
request_id: str | Iterable[str],
*,
timeout: float = ABORT_TIMEOUT_S,
):
"""Abort request(s) via the Orchestrator given internal request IDs,
which take the format <external_request_id>-<UUID>.
"""
request_ids = [request_id] if isinstance(request_id, str) else list(request_id)
# Request IDs are already internal, so we just need to get the matching states.
internal_req_ids = [rid for rid in request_ids if rid in self.request_states]
try:
# Unbind generate() if abort_async blocks in the executor.
await asyncio.wait_for(self._abort(internal_req_ids, timeout=timeout), timeout=timeout)
except TimeoutError:
logger.warning(
"[AsyncOmni] Timed out aborting %s after %.1fs; "
"engine abort is best-effort until the current batch drains",
",".join(internal_req_ids),
timeout,
)
except Exception:
logger.exception("[AsyncOmni] Cleanup abort failed for %s", ",".join(internal_req_ids))
async def _abort(self, request_ids: list[str], *, timeout: float | None = None) -> None:
"""Abort request IDs via the engine and enqueue terminal abort outputs.
Waits for orchestrator abort acknowledgment, enqueues any AR terminal
abort outputs (partial tokens) into each request's asyncio queue, then
cancels the input pump. Frontend ``request_states`` stay registered so
``generate()`` can consume the terminal message in
``_process_orchestrator_results`` and run normal cleanup.
When ``abort_async`` returns no output for an active request (OP not
registered yet, unbound replica, or orchestrator id drop), enqueue a
synthetic finished abort so ``generate()`` cannot hang on ``queue.get``.
"""
abort_outputs = await self.engine.abort_async(request_ids, timeout=timeout) or []
delivered: set[str] = set()
for output_msg in abort_outputs:
req_id = getattr(output_msg, "request_id", None)
if req_id is None:
continue
state = self.request_states.get(req_id)
if state is None:
logger.debug("[AsyncOmni] Dropping abort output for unknown req %s", req_id)
continue
await state.queue.put(output_msg)
delivered.add(req_id)
for rid in request_ids:
state = self.request_states.get(rid)
if state is not None and rid not in delivered:
queue = getattr(state, "queue", None)
if queue is not None:
await state.queue.put(self._synthetic_abort_output_message(rid))
delivered.add(rid)
for rid in request_ids:
self._record_request_failure_once(rid, reason="client_abort")
state = self.request_states.get(rid)
input_stream_task = getattr(state, "input_stream_task", None)
if input_stream_task is not None and not input_stream_task.done():
input_stream_task.cancel()
if self.log_stats:
logger.info("[AsyncOmni] Aborted request(s) %s", ",".join(request_ids))
@staticmethod
def _synthetic_abort_output_message(request_id: str) -> OutputMessage:
"""Terminal abort OutputMessage used when the engine returned none."""
engine_output = OmniRequestOutput(
request_id=request_id,
finished=True,
stage_id=0,
final_output_type="text",
outputs=[
CompletionOutput(
index=0,
text="",
token_ids=[],
cumulative_logprob=None,
logprobs=None,
finish_reason="abort",
stop_reason=None,
)
],
)
return OutputMessage(
request_id=request_id,
stage_id=0,
replica_id=None,
engine_outputs=engine_output,
metrics=None,
finished=True,
stage_submit_ts=None,
)
@property
def is_running(self) -> bool:
"""Check if the engine is running."""
orchestrator_alive = self.engine.is_alive()
task_alive = self.final_output_task is not None and not self.final_output_task.done()
return orchestrator_alive and task_alive
@property
def _name(self) -> str:
return type(self).__name__
@property
def is_stopped(self) -> bool:
"""EngineClient abstract property implementation."""
return self.errored
@property
def dead_error(self) -> BaseException:
"""EngineClient abstract property implementation."""
return OmniEngineDeadError()
# ==================== EngineClient Interface ====================
async def check_health(self) -> None:
"""Check engine health by verifying the Orchestrator process is alive."""
OmniBase.check_health(self)
# ==================== Shutdown ====================
def shutdown(self, timeout: float | None = None) -> None:
"""Shutdown the engine."""
if self.final_output_task is not None:
self.final_output_task.cancel()
self.final_output_task = None
OmniBase.shutdown(self)
@@ -206,8 +206,10 @@ def add_seed_tts_cli_args(parser: argparse.ArgumentParser) -> None:
"--seed-tts-turns-per-session",
type=int,
default=1,
help="Group this many Seed-TTS target texts into one Realtime session. "
"The first row's reference audio and transcript are reused for every turn.",
help="Group this many Seed-TTS target texts into one benchmark request. "
"The first row's reference audio and transcript are reused for every turn. "
"A model-native duplex session takes its target text once, in the session "
"context, so each turn runs in its own session.",
)
group.add_argument(
"--seed-tts-root",
@@ -28,8 +28,28 @@ from vllm_omni.entrypoints.cli.benchmark.base import OmniBenchmarkSubcommandBase
def _common(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--dataset", default=DEFAULT_DATASET)
parser.add_argument("--split", default="all")
parser.add_argument(
"--dataset",
default=DEFAULT_DATASET,
help=(
"Hugging Face dataset id, a JSON/JSONL manifest, or a local Hugging Face "
"dataset mirror. A local directory must use a single configuration whose "
"data files are named after the RTD_*/PR_* splits "
"(data/<SPLIT>-00000-of-00001.parquet); a single .parquet file is also "
"accepted. --split filters the rows by their preserved split identity, so "
"rows without identity fail loudly."
),
)
parser.add_argument(
"--split",
default="all",
help=(
"Restrict to one split (e.g. RTD_OCR) or 'all'. A mistyped split name "
"raises a clear error listing the splits actually observed in the data. "
"Rows from a manifest or an iterable without split/subset/config identity "
"keep the requested split as an override rather than being rejected."
),
)
parser.add_argument("--family", choices=("all", "rtd", "pr"), default="all")
parser.add_argument("--media-root")
parser.add_argument("--limit", type=int)
@@ -100,6 +120,8 @@ def run(args: argparse.Namespace) -> int:
limit=args.limit,
ids=args.ids,
)
if not samples:
raise ValueError("no samples selected; check --dataset/--split/--family/--ids/--limit")
if args.action == "generate":
if args.concurrency < 1:
raise ValueError("--concurrency must be at least 1")
+4 -1
View File
@@ -712,7 +712,10 @@ class OmniServeCommand(CLISubcommand):
"--cache-backend",
type=str,
default="none",
help="Cache backend for diffusion models, options: 'tea_cache', 'cache_dit', 'mag_cache', 'step_cache'",
help=(
"Cache backend for diffusion models, options: 'tea_cache', "
"'cache_dit', 'mag_cache', 'sea_cache', 'step_cache'"
),
)
omni_config_group.add_argument(
"--cache-config",
+9 -2
View File
@@ -1,6 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from .websocket import DuplexWebSocketActor
"""Thin websocket serving for engine-resident duplex sessions.
__all__ = ["DuplexWebSocketActor"]
The session logic lives in ``vllm_omni.engine.duplex`` and is reached through
``vllm_omni.entrypoints.duplex_omni.DuplexOmni``; this package only speaks the
OpenAI Realtime wire protocol over ``/v1/realtime?duplex=1``.
"""
from .serving import OmniDuplexSessionHandler
__all__ = ["OmniDuplexSessionHandler"]
-220
View File
@@ -1,220 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import base64
import binascii
import io
import math
import wave
import numpy as np
try:
from audioop import alaw2lin, lin2alaw, lin2ulaw, ulaw2lin
except ImportError: # pragma: no cover - audioop is removed in newer Python.
alaw2lin = lin2alaw = lin2ulaw = ulaw2lin = None
MIN_INPUT_SAMPLE_RATE_HZ = 8_000
MAX_INPUT_SAMPLE_RATE_HZ = 192_000
def validate_input_sample_rate_hz(sample_rate_hz: object) -> int:
if (
isinstance(sample_rate_hz, bool)
or not isinstance(sample_rate_hz, int | float)
or (isinstance(sample_rate_hz, float) and not math.isfinite(sample_rate_hz))
):
raise ValueError("sample_rate_hz must be a finite integer")
rate = int(sample_rate_hz)
if rate != sample_rate_hz:
raise ValueError("sample_rate_hz must be an integer")
if not MIN_INPUT_SAMPLE_RATE_HZ <= rate <= MAX_INPUT_SAMPLE_RATE_HZ:
raise ValueError(f"sample_rate_hz must be between {MIN_INPUT_SAMPLE_RATE_HZ} and {MAX_INPUT_SAMPLE_RATE_HZ}")
return rate
def resample_pcm16_mono(raw: bytes, *, source_rate_hz: int, target_rate_hz: int) -> bytes:
if source_rate_hz <= 0 or target_rate_hz <= 0 or source_rate_hz == target_rate_hz:
return raw
# Import lazily so the generic Duplex audio module does not pull in the
# OpenAI API server while the Duplex stack itself is being imported.
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
samples = np.frombuffer(raw, dtype="<i2")
rate_gcd = math.gcd(source_rate_hz, target_rate_hz)
reduced_factor = max(source_rate_hz // rate_gcd, target_rate_hz // rate_gcd)
if reduced_factor > StreamingAudioResampler._max_polyphase_factor:
# The FIR size scales with the reduced ratio. Keep unusual client
# rates bounded while common audio rates use the high-quality path.
if samples.size <= 1:
return raw
target_size = max(1, int(round(samples.size * target_rate_hz / source_rate_hz)))
source_x = np.linspace(0.0, 1.0, num=samples.size, endpoint=True)
target_x = np.linspace(0.0, 1.0, num=target_size, endpoint=True)
resampled = np.interp(target_x, source_x, samples)
return np.clip(resampled, -32_768, 32_767).astype("<i2").tobytes()
resampler = StreamingAudioResampler(source_rate_hz, target_rate_hz)
normalized = samples.astype(np.float32) * np.float32(1.0 / 32768.0)
resampled = resampler.process(normalized, final=True)
return np.clip(np.rint(resampled * 32768.0), -32768, 32767).astype("<i2").tobytes()
def decode_g711_ulaw(raw: bytes) -> bytes:
if ulaw2lin is not None:
return ulaw2lin(raw, 2)
data = np.frombuffer(raw, dtype=np.uint8)
value = np.bitwise_not(data).astype(np.int16)
sign = value & 0x80
exponent = (value >> 4) & 0x07
mantissa = value & 0x0F
sample = ((mantissa << 3) + 0x84) << exponent
return np.where(sign != 0, -(sample - 0x84), sample - 0x84).astype("<i2").tobytes()
def decode_g711_alaw(raw: bytes) -> bytes:
if alaw2lin is not None:
return alaw2lin(raw, 2)
data = np.bitwise_xor(np.frombuffer(raw, dtype=np.uint8), 0x55).astype(np.int16)
sign = data & 0x80
exponent = (data >> 4) & 0x07
mantissa = data & 0x0F
sample = np.where(exponent == 0, (mantissa << 4) + 8, ((mantissa << 4) + 0x108) << (exponent - 1))
return np.where(sign != 0, sample, -sample).astype("<i2").tobytes()
def encode_g711_ulaw(raw: bytes) -> bytes:
if lin2ulaw is not None:
return lin2ulaw(raw, 2)
pcm = np.clip(np.frombuffer(raw, dtype="<i2").astype(np.int32), -32635, 32635)
sign = np.where(pcm < 0, 0x80, 0)
magnitude = np.abs(pcm) + 0x84
exponent = np.zeros_like(magnitude)
for exp in range(7):
exponent = np.where(magnitude > (0xFF << exp), exp + 1, exponent)
mantissa = (magnitude >> (exponent + 3)) & 0x0F
return (np.bitwise_not(sign | (exponent << 4) | mantissa) & 0xFF).astype(np.uint8).tobytes()
def encode_g711_alaw(raw: bytes) -> bytes:
if lin2alaw is not None:
return lin2alaw(raw, 2)
pcm = np.frombuffer(raw, dtype="<i2").astype(np.int32)
sign = np.where(pcm >= 0, 0x80, 0x00)
magnitude = np.abs(pcm)
exponent = np.zeros_like(magnitude)
for exp in range(1, 8):
exponent = np.where(magnitude >= (1 << (exp + 7)), exp, exponent)
mantissa = np.where(
exponent == 0,
(magnitude >> 4) & 0x0F,
(magnitude >> (exponent + 3)) & 0x0F,
)
return ((sign | (exponent << 4) | mantissa) ^ 0x55).astype(np.uint8).tobytes()
def wav_payload_to_pcm16(raw: bytes) -> tuple[bytes | None, int | None]:
try:
with wave.open(io.BytesIO(raw), "rb") as wav_file:
channels = wav_file.getnchannels()
sample_width = wav_file.getsampwidth()
sample_rate_hz = wav_file.getframerate()
frames = wav_file.readframes(wav_file.getnframes())
if sample_width != 2:
return None, sample_rate_hz
if channels <= 1:
return frames, sample_rate_hz
pcm = np.frombuffer(frames, dtype="<i2").reshape(-1, channels)
mono = np.mean(pcm.astype(np.float32), axis=1)
return np.clip(mono, -32768, 32767).astype("<i2").tobytes(), sample_rate_hz
except (EOFError, ValueError, wave.Error):
return None, None
def encode_float32_mono_wav_base64(
samples: np.ndarray,
*,
sample_rate_hz: int,
) -> str:
"""Package normalized mono float32 samples as a PCM16 WAV data payload."""
rate = validate_input_sample_rate_hz(sample_rate_hz)
normalized = np.ascontiguousarray(samples, dtype=np.float32).reshape(-1)
pcm16 = np.clip(np.rint(normalized * 32768.0), -32768, 32767).astype("<i2")
with io.BytesIO() as buffer:
with wave.open(buffer, "wb") as wav_file:
wav_file.setnchannels(1)
wav_file.setsampwidth(2)
wav_file.setframerate(rate)
wav_file.writeframes(pcm16.tobytes())
return base64.b64encode(buffer.getvalue()).decode("ascii")
def convert_input_audio_with_rate(
audio: object,
fmt: object,
*,
sample_rate_hz: int | float | None = None,
target_sample_rate_hz: int = 16_000,
) -> tuple[object, object, int | float | None]:
if not isinstance(audio, str) or not isinstance(fmt, str):
return audio, fmt, sample_rate_hz
normalized = fmt.lower()
if normalized not in {"pcm16", "pcm_s16le", "s16le", "g711_ulaw", "g711_alaw"}:
return audio, fmt, sample_rate_hz
if isinstance(sample_rate_hz, int | float):
sample_rate_hz = validate_input_sample_rate_hz(sample_rate_hz)
try:
raw = base64.b64decode(audio.strip(), validate=False)
except (binascii.Error, ValueError):
return audio, fmt, sample_rate_hz
if normalized == "g711_ulaw":
raw = decode_g711_ulaw(raw)
sample_rate_hz = sample_rate_hz if isinstance(sample_rate_hz, int | float) else 8_000
elif normalized == "g711_alaw":
raw = decode_g711_alaw(raw)
sample_rate_hz = sample_rate_hz if isinstance(sample_rate_hz, int | float) else 8_000
elif len(raw) % 2:
return audio, fmt, sample_rate_hz
if isinstance(sample_rate_hz, int | float) and int(sample_rate_hz) != target_sample_rate_hz:
raw = resample_pcm16_mono(
raw,
source_rate_hz=int(sample_rate_hz),
target_rate_hz=target_sample_rate_hz,
)
sample_rate_hz = target_sample_rate_hz
pcm = np.frombuffer(raw, dtype="<i2").astype(np.float32) / 32768.0
encoded = base64.b64encode(np.ascontiguousarray(pcm, dtype="<f4").tobytes()).decode("ascii")
return encoded, "pcm_f32le", sample_rate_hz
def convert_output_audio(
audio: str,
*,
source_fmt: str,
target_fmt: str,
source_sample_rate_hz: int | None = None,
target_sample_rate_hz: int | None = None,
) -> tuple[str, str, int | None]:
target = target_fmt.lower()
if target not in {"g711_ulaw", "g711_alaw"}:
return audio, source_fmt, source_sample_rate_hz
try:
raw = base64.b64decode(audio, validate=False)
except (binascii.Error, ValueError):
return audio, source_fmt, source_sample_rate_hz
source = source_fmt.lower()
if source == "wav":
pcm_raw, wav_rate = wav_payload_to_pcm16(raw)
if pcm_raw is None:
return audio, source_fmt, source_sample_rate_hz
raw = pcm_raw
source_sample_rate_hz = source_sample_rate_hz or wav_rate
elif source not in {"pcm", "pcm16", "pcm_s16le", "s16le"} or len(raw) % 2:
return audio, source_fmt, source_sample_rate_hz
target_rate = target_sample_rate_hz or 8_000
if source_sample_rate_hz is not None:
raw = resample_pcm16_mono(raw, source_rate_hz=source_sample_rate_hz, target_rate_hz=target_rate)
encoded = encode_g711_ulaw(raw) if target == "g711_ulaw" else encode_g711_alaw(raw)
return base64.b64encode(encoded).decode("ascii"), target, target_rate
@@ -0,0 +1,55 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Audio encoding for duplex model output (entrypoint layer, injected into ``DuplexOmniEngine``)."""
from __future__ import annotations
import numpy as np
from vllm.logger import init_logger
logger = init_logger(__name__)
def encode_audio(
audio_data: object,
sample_rate_hz: int,
response_format: str,
speed: float | None,
) -> str | None:
"""Encode a model audio tensor/array into base64 in ``response_format``.
Moved from the serving runtime bridge; uses the shared ``AudioMixin``
encoder directly instead of going through the chat service.
"""
if audio_data is None:
return None
try:
import torch
from vllm_omni.entrypoints.openai.audio_utils_mixin import AudioMixin
from vllm_omni.entrypoints.openai.protocol.audio import CreateAudio
if isinstance(audio_data, torch.Tensor):
audio_tensor = audio_data.detach().cpu().float().numpy()
else:
audio_tensor = np.asarray(audio_data, dtype=np.float32)
if audio_tensor.ndim > 1:
audio_tensor = audio_tensor.reshape(-1)
audio_response = AudioMixin().create_audio(
CreateAudio(
audio_tensor=audio_tensor,
sample_rate=sample_rate_hz,
response_format=response_format,
speed=float(speed) if isinstance(speed, int | float) and speed > 0 else 1.0,
stream_format="audio",
base64_encode=True,
)
)
return str(audio_response.audio_data)
except Exception:
logger.exception("Failed to encode duplex data-plane audio output")
return None
__all__ = ["encode_audio"]
@@ -1,34 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from vllm.logger import init_logger
logger = init_logger(__name__)
def should_enable_duplex_endpoint(
stage_configs: list | None,
*,
config_path: str | None = None,
) -> bool:
"""Enable the realtime session handler for explicitly configured deployments."""
if stage_configs:
for stage in stage_configs:
session_mode = (
stage.get("session_mode") if isinstance(stage, dict) else getattr(stage, "session_mode", None)
)
if session_mode == "duplex":
return True
if config_path:
try:
from vllm_omni.config.stage_config import resolve_deploy_yaml
raw_config = resolve_deploy_yaml(config_path)
if raw_config.get("session_mode") == "duplex" or isinstance(raw_config.get("duplex_session"), dict):
return True
except Exception as exc:
logger.warning("Failed to inspect realtime session configuration from %s: %s", config_path, exc)
return False
__all__ = ["should_enable_duplex_endpoint"]
@@ -1,302 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncGenerator
from functools import partial
from typing import Any
from vllm.entrypoints.openai.chat_completion.protocol import ChatCompletionRequest
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
from vllm.logger import init_logger
from vllm_omni.entrypoints.duplex.protocol import DuplexSession
logger = init_logger(__name__)
class ChatFallbackProjectorMixin:
"""Project generic chat completion output into duplex response events."""
async def _run_response(self, session: DuplexSession, send_json) -> None:
response_id = session.begin_response()
epoch = session.epoch
request_id = f"duplex-{session.session_id}-{epoch}-{session.input_commit_seq}"
session.bind_request(f"chatcmpl-{request_id}")
await send_json(
self._response_created_payload(
session,
response_id,
epoch=epoch,
request_id=session.active_request_id,
)
)
try:
request = self._build_chat_request(session, request_id)
result = await self._chat_service.create_chat_completion(request, raw_request=None)
if isinstance(result, ErrorResponse):
error = result.error
await send_json(
{
"type": "error",
"error": error.message if error else "Chat request failed",
"code": error.type if error else "chat_error",
}
)
session.end_response(commit_text=False)
return
if hasattr(result, "__aiter__"):
await self._drain_streaming_response(session, result, epoch, response_id, send_json)
else:
await self._emit_full_response(session, result, epoch, response_id, send_json)
if session.epoch == epoch:
final_stage_metrics = session.accumulate_response_stage_metrics(None)
should_commit = self._should_commit_response_to_history(session, response_id)
committed_message = session.end_response(commit_text=should_commit)
if should_commit:
session.register_history_item(f"item_{response_id}", committed_message)
done_payload: dict[str, object] = {
"type": "response.done",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"committed": committed_message is not None,
"playback": session.playback.as_dict(),
}
if final_stage_metrics:
done_payload["vllm_omni"] = {"stage_metrics": final_stage_metrics}
await send_json(done_payload)
except asyncio.CancelledError:
raise
except Exception as exc:
logger.exception("Duplex response failed: %s", exc)
session.end_response(commit_text=False)
await send_json(
{
"type": "error",
"session_id": session.session_id,
"response_id": response_id,
"error": str(exc),
"code": "response_error",
}
)
def _build_chat_request(self, session: DuplexSession, request_id: str) -> ChatCompletionRequest:
response_config = session.response_config
messages: list[dict[str, object]] = []
if response_config.instructions:
messages.append({"role": "system", "content": response_config.instructions})
messages.extend(session.history)
kwargs: dict[str, Any] = {
"model": response_config.model or self._chat_service.model_config.model,
"messages": messages,
"stream": True,
}
if response_config.temperature is not None:
kwargs["temperature"] = response_config.temperature
if response_config.max_tokens is not None:
kwargs["max_tokens"] = response_config.max_tokens
model_extra = dict(response_config.extra_body)
model_extra.pop("native_duplex", None)
model_extra.pop("minicpmo45_native_duplex", None)
tools = model_extra.pop("realtime_response_tools", model_extra.pop("realtime_tools", None))
tool_choice = model_extra.pop(
"realtime_response_tool_choice",
model_extra.pop("realtime_tool_choice", None),
)
for protocol_key in (
"realtime_response_conversation",
"realtime_response_metadata",
"realtime_response_prompt",
):
model_extra.pop(protocol_key, None)
kwargs.update(model_extra)
if "audio" in response_config.modalities:
audio_options = kwargs.get("audio")
audio_options = dict(audio_options) if isinstance(audio_options, dict) else {}
# Chat defaults to WAV. Request the session's internal output format
# explicitly rather than relabeling the returned bytes as PCM.
audio_options["format"] = response_config.response_format
kwargs["audio"] = audio_options
if isinstance(tools, list):
kwargs["tools"] = tools
if isinstance(tool_choice, str | dict):
kwargs["tool_choice"] = tool_choice
request = ChatCompletionRequest(**kwargs)
object.__setattr__(request, "modalities", response_config.modalities)
object.__setattr__(request, "request_id", request_id)
object.__setattr__(
request,
"chat_template_kwargs",
{"use_tts_template": response_config.use_tts_template},
)
return request
async def _drain_streaming_response(
self,
session: DuplexSession,
result: AsyncGenerator[str, None],
epoch: int,
response_id: str,
send_json,
) -> None:
async for raw_chunk in result:
if session.epoch != epoch:
return
for payload in self._parse_sse_payloads(raw_chunk):
if payload == "[DONE]":
continue
if isinstance(payload, dict):
await self._emit_chat_payload(session, payload, epoch, response_id, send_json)
async def _emit_full_response(
self,
session: DuplexSession,
result: Any,
epoch: int,
response_id: str,
send_json,
) -> None:
if hasattr(result, "model_dump"):
payload = result.model_dump(mode="json", exclude_unset=True)
else:
payload = {"response": str(result)}
await self._emit_chat_payload(session, payload, epoch, response_id, send_json)
def _parse_sse_payloads(self, raw_chunk: str) -> list[dict[str, object] | str]:
payloads: list[dict[str, object] | str] = []
for line in raw_chunk.splitlines():
line = line.strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if not data:
continue
if data == "[DONE]":
payloads.append(data)
continue
try:
parsed = json.loads(data)
except json.JSONDecodeError:
logger.debug("Skipping non-JSON duplex stream payload: %s", data)
continue
if isinstance(parsed, dict):
payloads.append(parsed)
return payloads
async def _emit_chat_payload(
self,
session: DuplexSession,
payload: dict[str, object],
epoch: int,
response_id: str,
send_json,
) -> None:
if session.epoch != epoch or session.active_response_id != response_id:
return
metrics = payload.get("metrics")
stage_metrics = metrics.get("stage_metrics") if isinstance(metrics, dict) else None
if isinstance(stage_metrics, dict):
session.replace_response_stage_metric_snapshots(stage_metrics)
modality = payload.get("modality")
if modality not in {None, "text", "audio"}:
await send_json(
{
"type": "error",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"code": "unsupported_response_modality",
"error": f"Unsupported chat response modality: {modality}",
}
)
return
choices = payload.get("choices")
if not isinstance(choices, list):
await send_json(
{
"type": "response.message",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"payload": payload,
}
)
return
for choice in choices:
if not isinstance(choice, dict):
continue
delta = choice.get("delta")
message = choice.get("message")
content = None
if isinstance(delta, dict):
content = delta.get("content")
elif isinstance(message, dict):
content = message.get("content")
if isinstance(content, str) and content:
if modality != "audio":
session.append_assistant_text(content)
await send_json(
{
"type": "response.text.delta",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"delta": content,
}
)
audio_content = content if modality == "audio" else None
if isinstance(message, dict):
message_audio = message.get("audio")
if isinstance(message_audio, dict):
audio_content = message_audio.get("data")
if isinstance(audio_content, str) and audio_content:
# The OpenAI package imports duplex serving during initialization.
# Defer this import until chat fallback has finished loading.
from vllm_omni.entrypoints.openai.protocol.audio import AudioChunkMetadata
audio_metadata = AudioChunkMetadata.model_validate(choice.get("audio_metadata"))
duration_ms = session.record_generated_audio(
response_id,
frame_count=audio_metadata.frame_count,
sample_rate_hz=audio_metadata.sample_rate_hz,
)
if duration_ms is None:
return
await send_json(
{
"type": "response.output_audio.delta",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"audio": audio_content,
"format": audio_metadata.format,
"sample_rate_hz": audio_metadata.sample_rate_hz,
"channels": audio_metadata.channels,
"audio_duration_ms": duration_ms,
},
on_accepted=partial(session.mark_audio_sent, duration_ms, response_id=response_id),
)
finish_reason = choice.get("finish_reason")
if finish_reason is not None and modality != "audio":
await send_json(
{
"type": "response.output_item.done",
"session_id": session.session_id,
"response_id": response_id,
"epoch": epoch,
"finish_reason": finish_reason,
"modality": modality,
}
)
@@ -1,41 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
class CommitAction(str, Enum):
"""How one native audio commit participates in response scheduling."""
START_AUTO_RESPONSE = "start_auto_response"
DEFER_ACTIVE_RESPONSE = "defer_active_response"
COMMIT_ONLY = "commit_only"
@dataclass(frozen=True, slots=True)
class CommitSnapshot:
auto_responds: bool
speech_since_commit: bool
active_response_id: str | None
overlap_speech_ms: int
native_response_in_progress: bool
playback_active: bool
def decide_commit_action(snapshot: CommitSnapshot) -> CommitAction:
"""Choose response scheduling from an immutable session snapshot."""
if snapshot.auto_responds:
if snapshot.speech_since_commit:
return CommitAction.START_AUTO_RESPONSE
return CommitAction.COMMIT_ONLY
if snapshot.native_response_in_progress and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
if snapshot.playback_active and snapshot.overlap_speech_ms > 0:
return CommitAction.DEFER_ACTIVE_RESPONSE
return CommitAction.COMMIT_ONLY
__all__ = ["CommitAction", "CommitSnapshot", "decide_commit_action"]
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,147 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import json
from typing import Any
from uuid import uuid4
from fastapi import WebSocket
from vllm_omni.entrypoints.duplex import realtime_state as _state
from vllm_omni.entrypoints.duplex.realtime_input import (
RealtimeInputTranslator,
)
from vllm_omni.entrypoints.duplex.realtime_output import (
RealtimeOutputProjector,
)
REALTIME_ERROR_TYPES_BY_CODE = _state.REALTIME_ERROR_TYPES_BY_CODE
REALTIME_INPUT_AUDIO_FORMATS = _state.REALTIME_INPUT_AUDIO_FORMATS
REALTIME_OUTPUT_AUDIO_FORMATS = _state.REALTIME_OUTPUT_AUDIO_FORMATS
RealtimeSessionState = _state.RealtimeSessionState
_RealtimeResponseState = _state._RealtimeResponseState
class NativeRealtimeSessionProtocol(
RealtimeInputTranslator,
RealtimeOutputProjector,
_state.RealtimeStateOwner,
):
"""Compatibility facade for one native Realtime protocol session.
Input translation, output projection, and mutable state have separate
owners. The facade retains the established import path and private helper
surface used by serving and protocol contract tests.
"""
def __init__(self, query_params: Any) -> None:
self._state = RealtimeSessionState.from_query_params(query_params)
def bind_sender(self, send_realtime_json) -> None:
self._send_realtime_json = send_realtime_json
def bind_native_input_append(self, enabled: bool) -> None:
"""Use the serving-selected input path, independent of interruption policy."""
self._native_input_append = enabled
def _default_session_payload(self) -> dict[str, object]:
payload: dict[str, object] = {
"model": self._default_model,
"session_id": self._default_session_id,
}
if self._default_extra_body:
payload["extra_body"] = dict(self._default_extra_body)
return payload
async def receive_internal_event_text(self, websocket: WebSocket) -> str:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
if not self._opened and not self._resume_only and not self._autostarted_default_session and self._default_model:
self._opened = True
self._autostarted_default_session = True
return json.dumps(self._session_create_from_realtime(self._default_session_payload()))
while True:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
await self.wait_for_realtime_turn_detection_update()
raw = await websocket.receive_text()
try:
event = json.loads(raw)
except json.JSONDecodeError:
return raw
if not isinstance(event, dict):
return raw
if not self._opened and event.get("type") == "session.resume":
self._opened = True
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
return json.dumps(translated)
if not self._opened and self._resume_only:
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
return json.dumps(translated)
if not self._opened and event.get("type") != "session.update":
self._opened = True
await self._pending_outbound.put(self._session_create_from_realtime(self._default_session_payload()))
translated = await self._to_duplex_event(event)
if translated is not None:
await self._send_realtime_input_ack(event)
await self._pending_outbound.put(translated)
return json.dumps(await self._pending_outbound.get())
translated = await self._to_duplex_event(event)
if translated is None:
if not self._pending_outbound.empty():
return json.dumps(await self._pending_outbound.get())
continue
await self._send_realtime_input_ack(event)
return json.dumps(translated)
def encode_outbound_event(self, data: dict[str, Any]) -> list[dict[str, object]]:
payloads = self._from_duplex_event(data)
for payload in payloads:
self._attach_event_id(payload)
return payloads
@staticmethod
def _attach_event_id(payload: dict[str, object]) -> None:
payload.setdefault("event_id", f"event_{uuid4().hex}")
async def _send_realtime_payload(self, payload: dict[str, object]) -> None:
self._attach_event_id(payload)
if (
self._hold_realtime_output_until_session_created
and payload.get("type") != "error"
and payload.get("type") != "session.created"
):
self._held_realtime_payloads.append(payload)
return
if self._send_realtime_json is None:
raise RuntimeError("Native Realtime sender is not bound")
await self._send_realtime_json(payload)
@staticmethod
def _realtime_error_payload(
code: str,
message: str,
*,
event_id: object | None = None,
param: object | None = None,
) -> dict[str, object]:
error: dict[str, object] = {
"type": REALTIME_ERROR_TYPES_BY_CODE.get(code, "invalid_request_error"),
"code": code,
"message": message,
}
if isinstance(event_id, str) and event_id:
error["event_id"] = event_id
if isinstance(param, str) and param:
error["param"] = param
return {"type": "error", "error": error}
@@ -1,245 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
REALTIME_INPUT_AUDIO_FORMATS = {
"pcm16",
"pcm_s16le",
"s16le",
"pcm_f32le",
"g711_ulaw",
"g711_alaw",
}
REALTIME_OUTPUT_AUDIO_FORMATS = {
"pcm16",
"pcm_s16le",
"s16le",
"wav",
"pcm",
"g711_ulaw",
"g711_alaw",
}
REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ = 24_000
REALTIME_PCM_F32_DEFAULT_SAMPLE_RATE_HZ = 16_000
REALTIME_G711_DEFAULT_SAMPLE_RATE_HZ = 8_000
_RealtimeProtocolConfig = tuple[str, int, str, int | None, float]
_PendingTurnDetectionUpdate = tuple[
bool,
dict[str, object] | None,
asyncio.Event,
_RealtimeProtocolConfig,
]
def realtime_default_sample_rate_hz(fmt: object) -> int | None:
if not isinstance(fmt, str):
return None
normalized = fmt.lower()
if normalized in {"pcm16", "pcm_s16le", "s16le", "pcm", "audio/pcm"}:
return REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ
if normalized in {"pcm_f32le", "audio/pcm_f32le"}:
return REALTIME_PCM_F32_DEFAULT_SAMPLE_RATE_HZ
if normalized in {"g711_ulaw", "g711_alaw", "audio/g711_ulaw", "audio/g711_alaw"}:
return REALTIME_G711_DEFAULT_SAMPLE_RATE_HZ
return None
REALTIME_ERROR_TYPES_BY_CODE = {
"bad_event": "invalid_request_error",
"bad_audio": "invalid_request_error",
"config_timeout": "invalid_request_error",
"invalid_json": "invalid_request_error",
"event_too_large": "invalid_request_error",
"unknown_event": "invalid_request_error",
"internal_error": "server_error",
"runtime_open_failed": "server_error",
"runtime_open_unsupported": "server_error",
"runtime_append_failed": "server_error",
"runtime_append_task_failed": "server_error",
"runtime_signal_failed": "server_error",
"runtime_close_failed": "server_error",
"runtime_abort_failed": "server_error",
"runtime_data_plane_stream_failed": "server_error",
"runtime_data_plane_text_without_audio": "server_error",
"response_error": "server_error",
"chat_error": "server_error",
"server_vad_initialization_failed": "server_error",
"server_vad_inference_failed": "server_error",
"duplex_session_busy": "rate_limit_error",
"resource_exhausted": "rate_limit_error",
"input_backpressure": "rate_limit_error",
"response_already_active": "invalid_request_error",
"response_not_active": "invalid_request_error",
"response_create_without_input": "invalid_request_error",
"input_audio_buffer_empty": "invalid_request_error",
"server_vad_manual_commit_unsupported": "invalid_request_error",
"missing_item_id": "invalid_request_error",
"item_not_found": "invalid_request_error",
"playback_item_mismatch": "invalid_request_error",
"playback_item_not_found": "invalid_request_error",
"playback_ack_too_late": "invalid_request_error",
"unsupported_audio_format": "invalid_request_error",
"unsupported_ref_audio_path": "invalid_request_error",
"ref_audio_required": "invalid_request_error",
"model_update_unsupported": "invalid_request_error",
"voice_update_after_audio_unsupported": "invalid_request_error",
"ref_audio_update_unsupported": "invalid_request_error",
"native_text_append_unsupported": "invalid_request_error",
"runtime_native_stage_role_required": "server_error",
"runtime_native_runner_kv_required": "server_error",
}
@dataclass(slots=True)
class _RealtimeResponseState:
item_id: str
transcript_parts: list[str] = field(default_factory=list)
text_parts: list[str] = field(default_factory=list)
audio_duration_ms: int | None = None
audio_text_marks: list[dict[str, int]] = field(default_factory=list)
audio_delta_emitted: bool = False
audio_done_emitted: bool = False
audio_part_added: bool = False
audio_part_done: bool = False
text_part_added: bool = False
text_part_done: bool = False
output_text_done: bool = False
output_item_done: bool = False
conversation_item_done: bool = False
speak_emitted: bool = False
done_emitted: bool = False
@property
def transcript(self) -> str:
return "".join(self.transcript_parts)
@property
def text(self) -> str:
return "".join(self.text_parts)
@dataclass(slots=True)
class RealtimeSessionState:
"""Single mutable authority for one Realtime protocol session."""
_opened: bool = False
_autostarted_default_session: bool = False
_resume_only: bool = False
_pending_outbound: asyncio.Queue[dict[str, object]] = field(default_factory=asyncio.Queue)
_held_realtime_payloads: list[dict[str, object]] = field(default_factory=list)
_hold_realtime_output_until_session_created: bool = True
_default_model: object | None = None
_default_session_id: object | None = None
_default_extra_body: dict[str, object] = field(default_factory=dict)
_input_audio_format: str = "pcm16"
_input_sample_rate_hz: int = REALTIME_PCM_DEFAULT_SAMPLE_RATE_HZ
_output_audio_format: str = "pcm16"
_overlap_silence_rms: float = 0.003
_turn_detection: dict[str, object] | None = None
_native_input_append: bool = False
_pending_turn_detection_update: _PendingTurnDetectionUpdate | None = None
_send_realtime_json: Any = None
_initial_session_update: bool = False
_input_speech_started: bool = False
_response_states: dict[str | int, _RealtimeResponseState] = field(default_factory=dict)
_item_truncation_cursors: dict[str, tuple[int, int]] = field(default_factory=dict)
_active_response_id: str | None = None
_last_response_id: str | None = None
_conversation_items: dict[str, dict[str, object]] = field(default_factory=dict)
_last_conversation_item_id: str | None = None
_output_sample_rate_hz: int | None = None
_active_input_item_id: str | None = None
_input_audio_buffer_has_audio: bool = False
_input_audio_buffer_had_non_speech: bool = False
_input_audio_buffer_transcript_parts: list[str] = field(default_factory=list)
_turn_detection_configured: bool = False
@classmethod
def from_query_params(cls, query_params: Any) -> RealtimeSessionState:
if hasattr(query_params, "query_params"):
query_params = query_params.query_params
getter = query_params.get if hasattr(query_params, "get") else None
# Canonical query param plus the deprecated model-prefixed alias;
# both seed the canonical extra_body key.
native_duplex = None
if getter is not None:
native_duplex = getter("native_duplex")
if native_duplex is None:
native_duplex = getter("minicpmo45_native_duplex")
resume_only = getter("resume") if getter is not None else None
autostart = getter("autostart") if getter is not None else None
default_extra_body = {}
if str(native_duplex).strip().lower() in {"1", "true", "yes", "on"}:
default_extra_body["native_duplex"] = True
return cls(
_resume_only=(
str(resume_only).strip().lower() in {"1", "true", "yes", "on"}
or str(autostart).strip().lower() in {"0", "false", "no", "off"}
),
_default_model=getter("model") if getter is not None else None,
_default_session_id=(getter("session_id") if getter is not None else None),
_default_extra_body=default_extra_body,
)
_StateValue = TypeVar("_StateValue")
class _RealtimeStateField(Generic[_StateValue]):
"""Explicit descriptor binding one protocol attribute to session state."""
def __set_name__(self, owner: type, name: str) -> None:
del owner
self._name = name
def __get__(self, instance: Any, owner: type | None = None) -> _StateValue | _RealtimeStateField[_StateValue]:
del owner
if instance is None:
return self
return getattr(instance._state, self._name)
def __set__(self, instance: Any, value: _StateValue) -> None:
setattr(instance._state, self._name, value)
class RealtimeStateOwner:
"""Declare the mutable state surface shared by input/output projectors."""
_state: RealtimeSessionState
_opened: bool = _RealtimeStateField()
_autostarted_default_session: bool = _RealtimeStateField()
_resume_only: bool = _RealtimeStateField()
_pending_outbound: asyncio.Queue[dict[str, object]] = _RealtimeStateField()
_held_realtime_payloads: list[dict[str, object]] = _RealtimeStateField()
_hold_realtime_output_until_session_created: bool = _RealtimeStateField()
_default_model: object | None = _RealtimeStateField()
_default_session_id: object | None = _RealtimeStateField()
_default_extra_body: dict[str, object] = _RealtimeStateField()
_input_audio_format: str = _RealtimeStateField()
_input_sample_rate_hz: int = _RealtimeStateField()
_output_audio_format: str = _RealtimeStateField()
_overlap_silence_rms: float = _RealtimeStateField()
_turn_detection: dict[str, object] | None = _RealtimeStateField()
_native_input_append: bool = _RealtimeStateField()
_pending_turn_detection_update: _PendingTurnDetectionUpdate | None = _RealtimeStateField()
_send_realtime_json: Any = _RealtimeStateField()
_initial_session_update: bool = _RealtimeStateField()
_input_speech_started: bool = _RealtimeStateField()
_response_states: dict[str | int, _RealtimeResponseState] = _RealtimeStateField()
_item_truncation_cursors: dict[str, tuple[int, int]] = _RealtimeStateField()
_active_response_id: str | None = _RealtimeStateField()
_last_response_id: str | None = _RealtimeStateField()
_conversation_items: dict[str, dict[str, object]] = _RealtimeStateField()
_last_conversation_item_id: str | None = _RealtimeStateField()
_output_sample_rate_hz: int | None = _RealtimeStateField()
_active_input_item_id: str | None = _RealtimeStateField()
_input_audio_buffer_has_audio: bool = _RealtimeStateField()
_input_audio_buffer_had_non_speech: bool = _RealtimeStateField()
_input_audio_buffer_transcript_parts: list[str] = _RealtimeStateField()
_turn_detection_configured: bool = _RealtimeStateField()
@@ -1,331 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Iterable, Mapping, MutableMapping
from dataclasses import dataclass, field
from importlib import import_module
from typing import Any, Protocol
class ServingRuntimeConfigError(ValueError):
"""A model serving plugin rejected client-visible runtime configuration."""
def __init__(self, message: str, *, code: str = "invalid_duplex_runtime_config") -> None:
super().__init__(message)
self.code = code
def reject_changed_runtime_value(
new_value: object,
current_value: object,
*,
message: str,
code: str,
error_cls: type[ServingRuntimeConfigError] = ServingRuntimeConfigError,
) -> None:
if new_value != current_value:
raise error_cls(message, code=code)
class PcmAppendReservation(Protocol):
operation_id: str
payload: dict[str, object] | None
@property
def active(self) -> bool: ...
@property
def byte_count(self) -> int: ...
def commit(self) -> None: ...
def rollback(self) -> None: ...
class PcmAppendBuffer(Protocol):
@property
def pending_byte_count(self) -> int: ...
def clear(self) -> None: ...
def clear_force_listen(self) -> None: ...
def has_pending(self) -> bool: ...
def has_reserved(self) -> bool: ...
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> PcmAppendReservation | None: ...
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> PcmAppendReservation: ...
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None: ...
class ServingRuntimeSessionState(Protocol):
audio_buffer: PcmAppendBuffer
input_since_commit: bool
speech_since_commit: bool
native_context_locked: bool
committed_audio_payload: dict[str, object] | None
committed_audio_operation_id: str | None
committed_audio_reserved_bytes: int
deferred_response_create: bool
deferred_precreate_response: bool
data_plane_task: asyncio.Task[None] | None
data_plane_restart_requested: bool
continuation_owner_id: str | None
continuation_units: int
pending_silence_task: asyncio.Task[bool] | None
pending_silence_owner_id: str | None
silence_continuation_scheduler: Callable[..., Awaitable[bool]] | None
def retain_committed_audio(
self,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None: ...
def clear_committed_audio(self) -> int: ...
def clear_continuation(self) -> None: ...
class _TurnBasedPcmAppendBuffer:
"""Empty native-audio buffer for chat-fallback sessions.
Turn-based sessions keep input audio in ``DuplexSession`` and never use
the model-native append path. The runner still shares lifecycle and
cancellation code with native sessions, so it needs an inert buffer for
those common operations.
"""
@property
def pending_byte_count(self) -> int:
return 0
def clear(self) -> None:
return None
def clear_force_listen(self) -> None:
return None
def has_pending(self) -> bool:
return False
def has_reserved(self) -> bool:
return False
def prepare_append(
self,
payload: dict[str, object],
*,
operation_id: str,
chunk_period_ms: int,
allow_emit: bool,
) -> PcmAppendReservation | None:
del payload, operation_id, chunk_period_ms, allow_emit
raise RuntimeError("Model-native audio append is not enabled for this session")
def prepare_commit(
self,
*,
operation_id: str,
chunk_period_ms: int,
) -> PcmAppendReservation:
del operation_id, chunk_period_ms
raise RuntimeError("Model-native audio append is not enabled for this session")
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
del chunk_period_ms
return None
@dataclass(slots=True)
class TurnBasedServingSessionState:
"""Runner-local state for sessions served through chat fallback."""
audio_buffer: PcmAppendBuffer = field(default_factory=_TurnBasedPcmAppendBuffer)
input_since_commit: bool = False
speech_since_commit: bool = False
native_context_locked: bool = False
committed_audio_payload: dict[str, object] | None = None
committed_audio_operation_id: str | None = None
committed_audio_reserved_bytes: int = 0
deferred_response_create: bool = False
deferred_precreate_response: bool = False
data_plane_task: asyncio.Task[None] | None = None
data_plane_restart_requested: bool = False
continuation_owner_id: str | None = None
continuation_units: int = 0
pending_silence_task: asyncio.Task[bool] | None = None
pending_silence_owner_id: str | None = None
silence_continuation_scheduler: Callable[..., Awaitable[bool]] | None = None
def retain_committed_audio(
self,
payload: dict[str, object],
*,
operation_id: str | None,
reserved_bytes: int = 0,
) -> None:
self.committed_audio_payload = payload
self.committed_audio_operation_id = operation_id
self.committed_audio_reserved_bytes += max(0, int(reserved_bytes))
def clear_committed_audio(self) -> int:
reserved_bytes = self.committed_audio_reserved_bytes
self.committed_audio_payload = None
self.committed_audio_operation_id = None
self.committed_audio_reserved_bytes = 0
self.deferred_response_create = False
self.deferred_precreate_response = False
return reserved_bytes
def clear_continuation(self) -> None:
self.continuation_owner_id = None
self.continuation_units = 0
self.pending_silence_task = None
self.pending_silence_owner_id = None
class RuntimeDataPlane(Protocol):
def begin_request(self, request_id: str) -> None: ...
def is_terminal(self, request_id: str | None) -> bool: ...
def mark_terminal(self, request_id: str) -> None: ...
def close_stream(self, request_id: str) -> None: ...
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None: ...
def project(self, result: object, *, context: object | None = None) -> Iterable[dict[str, object]]: ...
class ServingRuntimeAdapter(Protocol):
adapter_id: str
session_states: MutableMapping[str, ServingRuntimeSessionState]
data_plane: RuntimeDataPlane
clean_response_done_prefix: str
interrupted_tts_prefix: str
private_runtime_config_keys: frozenset[str]
collect_outputs_on_append: bool
def create_session_state(self) -> ServingRuntimeSessionState: ...
def session_state(self, session_id: str) -> ServingRuntimeSessionState: ...
def remove_session_state(self, session_id: str) -> None: ...
def is_enabled(self, config: object) -> bool: ...
def capabilities(self, *, max_sessions: int) -> object: ...
def validate_client_extra_body(self, extra_body: object) -> None: ...
async def prepare_runtime_config(self, config: object, *, model_config: Any) -> dict[str, object]: ...
def runtime_config_for_update(
self,
config: object,
current: Mapping[str, object],
) -> dict[str, object]: ...
def data_plane_context(
self,
*,
epoch: int,
turn_id: int,
active_response_turn_id: int | None,
active_response_id: str | None,
auto_responds: bool,
response_format: str,
speed: float | None,
modalities: tuple[str, ...],
) -> object: ...
def load_serving_runtime_adapter(
path: str,
encode_audio,
) -> ServingRuntimeAdapter:
module_name, separator, attribute_name = path.rpartition(".")
if not separator:
raise ValueError(f"Invalid duplex serving runtime adapter path: {path!r}")
adapter_type = getattr(import_module(module_name), attribute_name)
return validate_serving_runtime_adapter(adapter_type(encode_audio))
def validate_serving_runtime_adapter(adapter: object) -> ServingRuntimeAdapter:
required_methods = (
"create_session_state",
"session_state",
"remove_session_state",
"is_enabled",
"capabilities",
"validate_client_extra_body",
"prepare_runtime_config",
"runtime_config_for_update",
"data_plane_context",
)
missing = [name for name in required_methods if not callable(getattr(adapter, name, None))]
if missing:
raise TypeError(f"Duplex serving runtime adapter is missing callable method(s): {', '.join(missing)}")
if not isinstance(getattr(adapter, "adapter_id", None), str) or not adapter.adapter_id:
raise TypeError("Duplex serving runtime adapter must declare adapter_id")
if not isinstance(getattr(adapter, "session_states", None), MutableMapping):
raise TypeError("Duplex serving runtime adapter must declare mutable session_states")
for prefix_name in ("clean_response_done_prefix", "interrupted_tts_prefix"):
if not isinstance(getattr(adapter, prefix_name, None), str):
raise TypeError(f"Duplex serving runtime adapter must declare {prefix_name}")
private_keys = getattr(adapter, "private_runtime_config_keys", None)
if not isinstance(private_keys, frozenset) or any(not isinstance(key, str) for key in private_keys):
raise TypeError("Duplex serving runtime adapter must declare private_runtime_config_keys as frozenset[str]")
data_plane = getattr(adapter, "data_plane", None)
if data_plane is None:
raise TypeError("Duplex serving runtime adapter must declare data_plane")
data_plane_methods = (
"begin_request",
"is_terminal",
"mark_terminal",
"close_stream",
"close_session",
"project",
)
missing_data_plane_methods = [name for name in data_plane_methods if not callable(getattr(data_plane, name, None))]
if missing_data_plane_methods:
raise TypeError(
"Duplex serving runtime adapter data_plane is missing callable method(s): "
+ ", ".join(missing_data_plane_methods)
)
return adapter # type: ignore[return-value]
def payload_turn_id(payload: object) -> int | None:
if not isinstance(payload, Mapping):
return None
return coerce_int(payload.get("duplex_turn_id", payload.get("model_turn_id")))
def coerce_int(value: object) -> int | None:
try:
return int(value) if value is not None else None
except (TypeError, ValueError):
return None
File diff suppressed because it is too large. Load diff
-528
View File
@@ -1,528 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
import hashlib
import threading
import time
from collections.abc import Mapping
from dataclasses import dataclass, replace
from pathlib import Path
from typing import TYPE_CHECKING, Literal, Protocol
import numpy as np
from vllm.transformers_utils.repo_utils import try_get_local_file
if TYPE_CHECKING:
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
SILERO_VAD_REPO_ID = "istupakov/silero-vad-onnx"
SILERO_VAD_REVISION = "8b14476858ef240c50b3884bb38cc67290c1cc70"
SILERO_VAD_FILENAME = "silero_vad.onnx"
SILERO_VAD_SHA256 = "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3"
SILERO_VAD_MIN_THRESHOLD = 0.15
SILERO_VAD_DEFAULT_MIN_SPEECH_DURATION_MS = 96
_SERVER_VAD_FIELDS = {
"type",
"threshold",
"prefix_padding_ms",
"silence_duration_ms",
"create_response",
"interrupt_response",
"min_speech_duration_ms",
}
@dataclass(frozen=True, slots=True)
class ServerVADConfig:
"""Validated OpenAI-compatible ``server_vad`` session configuration."""
type: Literal["server_vad"] = "server_vad"
threshold: float = 0.5
prefix_padding_ms: int = 300
silence_duration_ms: int = 500
create_response: bool = True
# Omission is resolved from runtime capabilities before the session is opened.
interrupt_response: bool | None = None
min_speech_duration_ms: int | None = None
@classmethod
def from_value(cls, value: object) -> ServerVADConfig:
if not isinstance(value, dict):
raise ValueError("turn_detection must be null or an object")
unknown = sorted(set(value) - _SERVER_VAD_FIELDS)
if unknown:
raise ValueError(f"Unknown server_vad field(s): {', '.join(unknown)}")
vad_type = value.get("type")
if vad_type != "server_vad":
raise ValueError("turn_detection.type must be 'server_vad'")
threshold = value.get("threshold", 0.5)
if isinstance(threshold, bool) or not isinstance(threshold, int | float) or not 0 <= threshold <= 1:
raise ValueError("server_vad.threshold must be a number between 0 and 1")
prefix_padding_ms = value.get("prefix_padding_ms", 300)
if isinstance(prefix_padding_ms, bool) or not isinstance(prefix_padding_ms, int) or prefix_padding_ms < 0:
raise ValueError("server_vad.prefix_padding_ms must be a non-negative integer")
silence_duration_ms = value.get("silence_duration_ms", 500)
if (
isinstance(silence_duration_ms, bool)
or not isinstance(silence_duration_ms, int)
or silence_duration_ms <= 0
):
raise ValueError("server_vad.silence_duration_ms must be a positive integer")
create_response = value.get("create_response", True)
if not isinstance(create_response, bool):
raise ValueError("server_vad.create_response must be a boolean")
interrupt_response = value.get("interrupt_response")
if "interrupt_response" in value and not isinstance(interrupt_response, bool):
raise ValueError("server_vad.interrupt_response must be a boolean")
min_speech_duration_ms = value.get("min_speech_duration_ms")
if min_speech_duration_ms is not None and (
isinstance(min_speech_duration_ms, bool)
or not isinstance(min_speech_duration_ms, int | float)
or not np.isfinite(float(min_speech_duration_ms))
or min_speech_duration_ms < 0
):
raise ValueError("server_vad.min_speech_duration_ms must be a non-negative number")
return cls(
type=vad_type,
threshold=float(threshold),
prefix_padding_ms=prefix_padding_ms,
silence_duration_ms=silence_duration_ms,
create_response=create_response,
interrupt_response=interrupt_response,
min_speech_duration_ms=(int(min_speech_duration_ms) if min_speech_duration_ms is not None else None),
)
def as_dict(self) -> dict[str, object]:
result: dict[str, object] = {
"type": self.type,
"threshold": self.threshold,
"prefix_padding_ms": self.prefix_padding_ms,
"silence_duration_ms": self.silence_duration_ms,
"create_response": self.create_response,
}
if self.interrupt_response is not None:
result["interrupt_response"] = self.interrupt_response
if self.min_speech_duration_ms is not None:
result["min_speech_duration_ms"] = self.min_speech_duration_ms
return result
def parse_session_turn_detection(
payload: Mapping[str, object],
) -> tuple[bool, ServerVADConfig | None]:
"""Extract and validate OpenAI-compatible turn detection aliases."""
configured_values: list[tuple[str, object]] = []
if "turn_detection" in payload:
configured_values.append(("turn_detection", payload["turn_detection"]))
audio = payload.get("audio")
if isinstance(audio, Mapping):
audio_input = audio.get("input")
if isinstance(audio_input, Mapping) and "turn_detection" in audio_input:
configured_values.append(("audio.input.turn_detection", audio_input["turn_detection"]))
if not configured_values:
return False, None
first_path, first_value = configured_values[0]
first_config = None if first_value is None else ServerVADConfig.from_value(first_value)
for field_path, value in configured_values[1:]:
config = None if value is None else ServerVADConfig.from_value(value)
if first_config is not None and config is not None:
# An omitted option must not conflict with an explicit alias value.
if first_config.interrupt_response is None:
first_config = replace(first_config, interrupt_response=config.interrupt_response)
if config.interrupt_response is None:
config = replace(config, interrupt_response=first_config.interrupt_response)
if config != first_config:
raise ValueError(f"{first_path} and {field_path} must not specify conflicting values")
return True, first_config
class SpeechDetectorBackend(Protocol):
"""Detector contract; per-stream state is owned by the pipeline."""
frame_samples: int
def new_state(self) -> object: ...
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]: ...
class SpeechDetectorBackendProvider(Protocol):
def get(self) -> SpeechDetectorBackend: ...
@dataclass(frozen=True, slots=True)
class SpeechEndpointDecision:
speech_started: bool = False
speech_stopped: bool = False
audio_start_ms: int | None = None
audio_end_ms: int | None = None
endpoint_delay_ms: int | None = None
class SpeechEndpointPolicy(Protocol):
@property
def speech_active(self) -> bool: ...
def update(
self,
probability: float,
*,
frame_start_sample: int,
frame_samples: int,
) -> SpeechEndpointDecision: ...
def reset(self) -> None: ...
class ThresholdEndpointPolicy:
"""Apply threshold and trailing-silence endpoint rules."""
def __init__(self, config: ServerVADConfig, *, sample_rate_hz: int) -> None:
self.config = config
self.sample_rate_hz = sample_rate_hz
self._speech_active = False
self._candidate_samples = 0
self._candidate_start_sample: int | None = None
self._silence_samples = 0
@property
def speech_active(self) -> bool:
return self._speech_active
def update(
self,
probability: float,
*,
frame_start_sample: int,
frame_samples: int,
) -> SpeechEndpointDecision:
if probability >= self.config.threshold:
self._silence_samples = 0
if not self._speech_active:
if self._candidate_samples == 0:
self._candidate_start_sample = frame_start_sample
self._candidate_samples += frame_samples
min_speech_duration_ms = self.config.min_speech_duration_ms or 0
min_speech_samples = max(1, round(min_speech_duration_ms * self.sample_rate_hz / 1000))
if self._candidate_samples < min_speech_samples:
return SpeechEndpointDecision()
self._speech_active = True
detected_start_sample = (
self._candidate_start_sample if self._candidate_start_sample is not None else frame_start_sample
)
detected_start_ms = round(detected_start_sample * 1000 / self.sample_rate_hz)
self._candidate_samples = 0
self._candidate_start_sample = None
return SpeechEndpointDecision(
speech_started=True,
audio_start_ms=max(0, detected_start_ms - self.config.prefix_padding_ms),
)
return SpeechEndpointDecision()
if not self._speech_active:
self._candidate_samples = 0
self._candidate_start_sample = None
return SpeechEndpointDecision()
# Match Silero v6.2's streaming VAD hysteresis: activation uses the
# configured threshold, while potential speech end starts only below
# ``max(threshold - 0.15, 0.01)``. Once a silence candidate exists,
# intermediate frames keep elapsed time moving but cannot themselves
# close the turn.
negative_threshold = max(self.config.threshold - SILERO_VAD_MIN_THRESHOLD, 0.01)
below_negative_threshold = probability < negative_threshold
if not below_negative_threshold and self._silence_samples == 0:
return SpeechEndpointDecision()
self._silence_samples += frame_samples
if not below_negative_threshold:
return SpeechEndpointDecision()
silence_limit = max(1, round(self.config.silence_duration_ms * self.sample_rate_hz / 1000))
if self._silence_samples < silence_limit:
return SpeechEndpointDecision()
# OpenAI defines ``audio_end_ms`` as the end of the audio sent to the
# model, including the trailing silence used for endpoint detection.
audio_end_sample = frame_start_sample + frame_samples
endpoint_delay_ms = round(self._silence_samples * 1000 / self.sample_rate_hz)
self.reset()
return SpeechEndpointDecision(
speech_stopped=True,
audio_end_ms=max(0, round(audio_end_sample * 1000 / self.sample_rate_hz)),
endpoint_delay_ms=endpoint_delay_ms,
)
def reset(self) -> None:
self._speech_active = False
self._candidate_samples = 0
self._candidate_start_sample = None
self._silence_samples = 0
@dataclass(frozen=True, slots=True)
class ServerVADFrame:
samples: np.ndarray
decision: SpeechEndpointDecision
@dataclass(frozen=True, slots=True)
class ServerVADBatch:
frames: tuple[ServerVADFrame, ...]
inference_ms: float
class ServerVADPipeline:
"""Frame continuous 16 kHz audio and apply acoustic endpointing.
The pipeline retains only input-resampling residuals, a partial frame,
detector state, and timing counters. Commit-eligible prefix and utterance
audio remain session-owned.
"""
sample_rate_hz = 16_000
def __init__(
self,
backend: SpeechDetectorBackend,
config: ServerVADConfig,
*,
endpoint_policy: SpeechEndpointPolicy | None = None,
) -> None:
self.backend = backend
self.config = config
self.endpoint_policy = endpoint_policy or ThresholdEndpointPolicy(
config,
sample_rate_hz=self.sample_rate_hz,
)
self._input_resampler: StreamingAudioResampler | None = None
self._source_sample_rate_hz: int | None = None
self._scratch = np.empty(0, dtype=np.float32)
self._detector_state = backend.new_state()
self._processed_samples = 0
self._stream_start_ms = 0
@property
def speech_active(self) -> bool:
return self.endpoint_policy.speech_active
@property
def source_sample_rate_hz(self) -> int | None:
return self._source_sample_rate_hz
@property
def scratch_bytes(self) -> int:
resampler_bytes = self._input_resampler.scratch_bytes if self._input_resampler is not None else 0
return int(self._scratch.nbytes) + resampler_bytes
async def push_pcm16(
self,
samples: bytes,
*,
source_sample_rate_hz: int,
) -> ServerVADBatch:
"""Normalize chunked mono PCM16 input and run endpoint detection."""
if isinstance(source_sample_rate_hz, bool) or source_sample_rate_hz not in {16_000, 24_000}:
raise ValueError("server_vad PCM16 input sample rate must be 16000 or 24000 Hz")
if len(samples) % np.dtype("<i2").itemsize:
raise ValueError("server_vad PCM16 input contains an incomplete sample")
pcm16 = np.frombuffer(samples, dtype="<i2")
if self._source_sample_rate_hz is not None and source_sample_rate_hz != self._source_sample_rate_hz:
raise ValueError("server_vad input sample rate cannot change within a continuous audio stream")
if pcm16.size and self._source_sample_rate_hz is None:
from vllm_omni.entrypoints.openai.audio_utils_mixin import StreamingAudioResampler
self._input_resampler = (
None
if source_sample_rate_hz == self.sample_rate_hz
else StreamingAudioResampler(source_sample_rate_hz, self.sample_rate_hz)
)
self._source_sample_rate_hz = source_sample_rate_hz
normalized = np.ascontiguousarray(pcm16, dtype=np.float32) * np.float32(1.0 / 32768.0)
if self._input_resampler is not None:
normalized = self._input_resampler.process(normalized)
return await self.push(normalized)
async def push(self, samples: np.ndarray) -> ServerVADBatch:
normalized = np.ascontiguousarray(samples, dtype=np.float32).reshape(-1)
return await asyncio.to_thread(self._push_sync, normalized)
def _push_sync(self, samples: np.ndarray) -> ServerVADBatch:
started_at = time.perf_counter()
if self._scratch.size:
samples = np.concatenate((self._scratch, samples))
frame_samples = int(self.backend.frame_samples)
complete_samples = samples.size - samples.size % frame_samples
# Retained state must not keep the whole input chunk alive through a view.
self._scratch = samples[complete_samples:].copy()
results: list[ServerVADFrame] = []
for offset in range(0, complete_samples, frame_samples):
frame = np.ascontiguousarray(samples[offset : offset + frame_samples], dtype=np.float32)
frame_start = self._processed_samples
probability, self._detector_state = self.backend.infer(frame, self._detector_state)
probability = min(1.0, max(0.0, float(probability)))
decision = self.endpoint_policy.update(
probability,
frame_start_sample=frame_start,
frame_samples=frame_samples,
)
if decision.speech_started and decision.audio_start_ms is not None:
# Prefix audio before the most recent reset is no longer available.
decision = replace(decision, audio_start_ms=max(self._stream_start_ms, decision.audio_start_ms))
self._processed_samples += frame_samples
results.append(
ServerVADFrame(
samples=frame,
decision=decision,
)
)
return ServerVADBatch(
frames=tuple(results),
inference_ms=(time.perf_counter() - started_at) * 1000,
)
def reset(self) -> None:
"""Discard stream state while preserving the session-relative audio clock."""
self._stream_start_ms = round(self._processed_samples * 1000 / self.sample_rate_hz)
self._input_resampler = None
self._source_sample_rate_hz = None
self._scratch = np.empty(0, dtype=np.float32)
self._detector_state = self.backend.new_state()
self.endpoint_policy.reset()
@dataclass(frozen=True, slots=True)
class _SileroVADState:
model_state: np.ndarray
context: np.ndarray
class SileroVADBackend:
"""Shared ONNX Runtime Silero v6.2 detector running on CPU."""
sample_rate_hz = 16_000
frame_samples = 512
context_samples = 64
model_state_shape = (2, 1, 128)
def __init__(self, model_path: str | Path) -> None:
try:
import onnxruntime as ort
except ImportError as exc: # pragma: no cover - platform packaging supplies ORT.
raise RuntimeError("server_vad requires ONNX Runtime") from exc
session_options = ort.SessionOptions()
session_options.inter_op_num_threads = 1
session_options.intra_op_num_threads = 1
self.model_path = Path(model_path)
self._session = ort.InferenceSession(
str(self.model_path),
providers=["CPUExecutionProvider"],
sess_options=session_options,
)
input_names = {item.name for item in self._session.get_inputs()}
if "input" not in input_names or "sr" not in input_names or "state" not in input_names:
raise RuntimeError(f"Unsupported Silero ONNX input contract: {sorted(input_names)}")
self._warm_up()
def _warm_up(self) -> None:
self.infer(np.zeros(self.frame_samples, dtype=np.float32), self.new_state())
def new_state(self) -> _SileroVADState:
return _SileroVADState(
model_state=np.zeros(self.model_state_shape, dtype=np.float32),
context=np.zeros((1, self.context_samples), dtype=np.float32),
)
def infer(self, frame: np.ndarray, state: object) -> tuple[float, object]:
if not isinstance(state, _SileroVADState):
raise TypeError("Silero detector state must be created by SileroVADBackend.new_state()")
model_state = np.ascontiguousarray(state.model_state, dtype=np.float32)
context = np.ascontiguousarray(state.context, dtype=np.float32)
if model_state.shape != self.model_state_shape:
raise ValueError(f"Silero model state must have shape {self.model_state_shape}, got {model_state.shape}")
expected_context_shape = (1, self.context_samples)
if context.shape != expected_context_shape:
raise ValueError(f"Silero context must have shape {expected_context_shape}, got {context.shape}")
audio = np.ascontiguousarray(frame, dtype=np.float32).reshape(1, -1)
if audio.shape[1] != self.frame_samples:
raise ValueError(
f"Silero detector frame must contain exactly {self.frame_samples} samples, got {audio.shape[1]}"
)
model_input = np.concatenate((context, audio), axis=1)
inputs = {
"input": model_input,
"state": model_state,
"sr": np.asarray(self.sample_rate_hz, dtype=np.int64),
}
# ONNX Runtime permits concurrent Run calls on one CPU session. Stream
# state is explicit, so independent pipelines can safely share the session.
output = self._session.run(None, inputs)
if len(output) < 2:
raise RuntimeError("Silero ONNX model did not return probability and model state")
probability = float(np.asarray(output[0]).reshape(-1)[0])
next_state = _SileroVADState(
model_state=np.ascontiguousarray(output[1], dtype=np.float32),
context=np.ascontiguousarray(model_input[:, -self.context_samples :], dtype=np.float32),
)
return probability, next_state
class SileroVADBackendProvider:
"""Resolve, verify, and load one Silero model instance per process."""
def __init__(self, *, model_path: str | None = None) -> None:
self.model_path = model_path
self._backend: SileroVADBackend | None = None
self._lock = threading.Lock()
def get(self) -> SileroVADBackend:
if self._backend is not None:
return self._backend
with self._lock:
if self._backend is None:
path = self._resolve_local_artifact()
self._verify_checksum(path)
self._backend = SileroVADBackend(path)
return self._backend
def _resolve_local_artifact(self) -> Path:
if self.model_path:
path = Path(self.model_path).expanduser()
if path.is_file():
return path
raise RuntimeError(f"Configured Silero VAD model does not exist: {path}")
cached = try_get_local_file(
model=SILERO_VAD_REPO_ID,
file_name=SILERO_VAD_FILENAME,
revision=SILERO_VAD_REVISION,
)
if isinstance(cached, Path) and cached.is_file():
return cached
raise RuntimeError(
"Silero VAD artifact is not available locally. Pre-download the pinned artifact "
"or configure duplex_session.server_vad_model_path."
)
def _verify_checksum(self, path: Path) -> None:
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != SILERO_VAD_SHA256:
raise RuntimeError(f"Silero VAD checksum mismatch for {path}: expected {SILERO_VAD_SHA256}, got {digest}")
File diff suppressed because it is too large. Load diff
@@ -180,7 +180,6 @@ class DuplexEventJournal:
@dataclass(frozen=True)
class DuplexSessionAttachmentCreated:
session_id: str
incarnation: int
attachment_generation: int
resume_token: ResumeToken = field(repr=False)
@@ -188,7 +187,6 @@ class DuplexSessionAttachmentCreated:
@dataclass(frozen=True)
class DuplexSessionResumeResult:
session_id: str
incarnation: int
attachment_generation: int
resume_token: ResumeToken = field(repr=False)
replay_entries: tuple[JournalEntry, ...] = ()
@@ -198,14 +196,12 @@ class DuplexSessionResumeResult:
@dataclass
class _DuplexSessionAttachmentState:
session_id: str
incarnation: int
credential: DuplexResumeCredential
journal: DuplexEventJournal
attachment: DuplexTransportAttachment | None
attachment_generation: int
outbound_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
recovery_token_digest: bytes | None = field(default=None, repr=False)
grace_task: asyncio.Task[None] | None = field(default=None, repr=False)
class DuplexSessionAttachmentRegistry:
@@ -214,18 +210,14 @@ class DuplexSessionAttachmentRegistry:
*,
replay_ttl_s: float,
replay_max_bytes_per_session: int,
disconnect_grace_s: float = 30.0,
clock: Callable[[], float] | None = None,
) -> None:
if replay_ttl_s <= 0:
raise ValueError("replay_ttl_s must be positive")
if replay_max_bytes_per_session <= 0:
raise ValueError("replay_max_bytes_per_session must be positive")
if disconnect_grace_s <= 0:
raise ValueError("disconnect_grace_s must be positive")
self._replay_ttl_s = replay_ttl_s
self._replay_max_bytes_per_session = replay_max_bytes_per_session
self._disconnect_grace_s = disconnect_grace_s
self._clock = clock or time.monotonic
self._sessions: dict[str, _DuplexSessionAttachmentState] = {}
self._lock = asyncio.Lock()
@@ -237,7 +229,6 @@ class DuplexSessionAttachmentRegistry:
self,
session_id: str,
*,
incarnation: int,
send: Callable[[dict[str, object]], Awaitable[None]],
close: Callable[[str], Awaitable[None]],
) -> DuplexSessionAttachmentCreated:
@@ -248,7 +239,6 @@ class DuplexSessionAttachmentRegistry:
generation = 1
self._sessions[session_id] = _DuplexSessionAttachmentState(
session_id=session_id,
incarnation=incarnation,
credential=DuplexResumeCredential.from_token(token),
journal=DuplexEventJournal(
max_bytes=self._replay_max_bytes_per_session,
@@ -264,7 +254,6 @@ class DuplexSessionAttachmentRegistry:
)
return DuplexSessionAttachmentCreated(
session_id=session_id,
incarnation=incarnation,
attachment_generation=generation,
resume_token=token,
)
@@ -309,33 +298,39 @@ class DuplexSessionAttachmentRegistry:
async with self._lock:
return self._require(session_id).journal.acknowledge(sequence)
async def detach(
self,
session_id: str,
*,
attachment_generation: int,
on_grace_expired: Callable[[], Awaitable[None]] | None = None,
) -> bool:
async def detach(self, session_id: str, *, attachment_generation: int | None = None) -> bool:
"""Drop the current transport; the engine lease owns the disconnect grace.
``attachment_generation`` names the connection asking to detach, so a
socket that already lost a takeover cannot detach the winner. ``None``
means "whichever connection is attached right now" and is for callers
that only know the session (the outbound pump, whose send just failed).
Returns whether this call is the one that detached: an already-detached
session answers ``False`` so a second disconnect signal for the same
socket cannot restart the engine's disconnect grace window.
"""
async with self._lock:
state = self._sessions.get(session_id)
if state is None or state.attachment_generation != attachment_generation:
if state is None or state.attachment is None:
return False
if attachment_generation is not None and state.attachment_generation != attachment_generation:
return False
state.attachment = None
if state.grace_task is not None:
state.grace_task.cancel()
state.grace_task = (
asyncio.create_task(
self._run_disconnect_grace(
state,
attachment_generation=attachment_generation,
callback=on_grace_expired,
)
)
if on_grace_expired is not None
else None
)
return True
async def has_attachment(self, session_id: str) -> bool:
"""Whether some connection is attached right now, whoever it is.
A resume that failed to activate has no generation of its own, so it
cannot ask ``is_current_attachment``. What it needs to know before
rolling the engine lease back into its disconnect grace is only whether
it would be rolling back somebody else's live attachment.
"""
async with self._lock:
state = self._sessions.get(session_id)
return state is not None and state.attachment is not None
async def is_current_attachment(self, session_id: str, attachment_generation: int) -> bool:
async with self._lock:
state = self._sessions.get(session_id)
@@ -349,25 +344,19 @@ class DuplexSessionAttachmentRegistry:
self,
session_id: str,
*,
incarnation: int,
resume_token: str,
last_received_server_event_seq: int,
) -> None:
"""Validate transport credentials before any engine resume control."""
async with self._lock:
state = self._require(session_id)
self._validate_resume_identity(
state,
incarnation=incarnation,
resume_token=resume_token,
)
self._validate_resume_identity(state, resume_token=resume_token)
state.journal.replay_after(last_received_server_event_seq)
async def resume(
self,
session_id: str,
*,
incarnation: int,
resume_token: str,
last_received_server_event_seq: int,
send: Callable[[dict[str, object]], Awaitable[None]],
@@ -380,18 +369,11 @@ class DuplexSessionAttachmentRegistry:
async with self._lock:
if self._sessions.get(session_id) is not state:
raise KeyError(f"unknown duplex attachment session: {session_id}")
used_recovery = self._validate_resume_identity(
state,
incarnation=incarnation,
resume_token=resume_token,
)
used_recovery = self._validate_resume_identity(state, resume_token=resume_token)
replay_entries = state.journal.replay_after(last_received_server_event_seq)
accepted_token_digest = (
state.recovery_token_digest if used_recovery else bytes(state.credential.token_digest)
)
if state.grace_task is not None:
state.grace_task.cancel()
state.grace_task = None
state.recovery_token_digest = None
rotated_token = state.credential.rotate()
replaced = state.attachment
@@ -407,53 +389,53 @@ class DuplexSessionAttachmentRegistry:
await send(dict(activation_payload_factory(rotated_token, attachment_generation)))
for entry in replay_entries:
await send(dict(entry.payload))
except Exception:
async with self._lock:
if (
self._sessions.get(session_id) is state
and state.attachment_generation == attachment_generation
):
state.attachment = None
state.recovery_token_digest = accepted_token_digest
except (Exception, asyncio.CancelledError):
# CancelledError derives from BaseException, so an
# ``except Exception`` here would let a cancellation during
# activation or replay skip the rollback: the dead
# attachment would stay current while the token it rotated
# past is gone, leaving the session attached to an unusable
# transport with no way back. Both failures take the same
# path deliberately, so they cannot drift apart.
await self._rollback_resume(
session_id,
state=state,
attachment_generation=attachment_generation,
accepted_token_digest=accepted_token_digest,
)
raise
return DuplexSessionResumeResult(
session_id=session_id,
incarnation=incarnation,
attachment_generation=attachment_generation,
resume_token=rotated_token,
replay_entries=replay_entries,
replaced_attachment=replaced,
)
async def _rollback_resume(
self,
session_id: str,
*,
state: _DuplexSessionAttachmentState,
attachment_generation: int,
accepted_token_digest: bytes,
) -> None:
"""Undo a resume whose activation never reached the client.
Generation-checked: a later resume that already took over must keep its
attachment. Restoring ``recovery_token_digest`` is what lets the caller
retry with the token it presented, which ``resume`` had rotated past.
"""
async with self._lock:
if self._sessions.get(session_id) is state and state.attachment_generation == attachment_generation:
state.attachment = None
state.recovery_token_digest = accepted_token_digest
async def close(self, session_id: str) -> DuplexTransportAttachment | None:
async with self._lock:
state = self._sessions.pop(session_id, None)
if state is not None and state.grace_task is not None:
state.grace_task.cancel()
return state.attachment if state is not None else None
async def _run_disconnect_grace(
self,
state: _DuplexSessionAttachmentState,
*,
attachment_generation: int,
callback: Callable[[], Awaitable[None]] | None,
) -> None:
try:
await asyncio.sleep(self._disconnect_grace_s)
except asyncio.CancelledError:
return
async with self._lock:
if (
self._sessions.get(state.session_id) is not state
or state.attachment is not None
or state.attachment_generation != attachment_generation
):
return
state.grace_task = None
if callback is not None:
await callback()
def _require(self, session_id: str) -> _DuplexSessionAttachmentState:
state = self._sessions.get(session_id)
if state is None:
@@ -461,14 +443,7 @@ class DuplexSessionAttachmentRegistry:
return state
@staticmethod
def _validate_resume_identity(
state: _DuplexSessionAttachmentState,
*,
incarnation: int,
resume_token: str,
) -> bool:
if incarnation != state.incarnation:
raise ValueError(f"duplex attachment incarnation mismatch: expected {state.incarnation}, got {incarnation}")
def _validate_resume_identity(state: _DuplexSessionAttachmentState, *, resume_token: str) -> bool:
if state.credential.verify(resume_token):
return False
recovery_digest = state.recovery_token_digest
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -43,10 +43,11 @@ async def _warmup_duplex_realtime(app, args, warmup_frames: int) -> None:
model_name = served
else:
model_name = args.model
adapter = getattr(getattr(app.state, "openai_serving_duplex", None), "_serving_runtime_adapter", None)
frame_samples = int(getattr(adapter, "silence_continuation_samples", 16000))
# One silence unit as the engine-side plugin defines it (DuplexOmniEngine.plugin).
plugin = getattr(getattr(app.state.engine_client, "engine", None), "plugin", None)
frame_samples = int(getattr(plugin, "silence_continuation_samples", 16000))
silence = base64.b64encode(bytes(frame_samples * 4)).decode("ascii")
from vllm_omni.experimental.fullduplex.client import build_realtime_url
from vllm_omni.clients.duplex import build_realtime_url
url = (
build_realtime_url(f"ws://127.0.0.1:{args.port}/v1/realtime", model_name, autostart=False)
+42 -248
View File
@@ -1,266 +1,60 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""WebSocket transport helpers for the duplex Realtime handler.
The ordered session mailbox and the per-session task handles that used to be
defined here now live engine-side (``vllm_omni.engine.duplex.session.runner``).
"""
from __future__ import annotations
import asyncio
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
from collections.abc import Awaitable, Callable
from contextlib import suppress
from fastapi import WebSocketDisconnect
from fastapi import WebSocket, WebSocketDisconnect
INPUT_EVENTS = frozenset(
{
"input.text.append",
"input_audio_buffer.append",
"input.commit",
"input_audio_buffer.commit",
"response.create",
}
)
#: Largest client frame accepted before it is parsed (base64 audio + video frames).
MAX_EVENT_BYTES = 15 * 1024 * 1024
_INPUT_EVENT_ALIASES = {
"signal_turn": "turn.signal",
"close_session": "session.close",
"audio.playback_ack": "playback.ack",
"input_text.append": "input.text.append",
"push_text": "input.text.append",
"input.audio.append": "input_audio_buffer.append",
"push_chunk": "input_audio_buffer.append",
}
_WAV_AUDIO_ALIASES = frozenset({"input.audio.append", "push_chunk"})
SendJson = Callable[[dict[str, object]], Awaitable[None]]
CloseFn = Callable[[str], Awaitable[None]]
def normalize_duplex_input_event(event: dict[str, object]) -> dict[str, object]:
"""Normalize compatibility aliases before an event enters the mailbox."""
event_type = event.get("type")
if not isinstance(event_type, str):
return event
canonical_type = _INPUT_EVENT_ALIASES.get(event_type)
if canonical_type is None:
return event
normalized = dict(event)
normalized["type"] = canonical_type
if event_type in _WAV_AUDIO_ALIASES:
normalized.setdefault("format", "wav")
return normalized
async def receive_text_with_timeout(websocket: WebSocket, timeout_s: float | None) -> str | None:
"""Receive one text frame; ``None`` on idle timeout. Disconnects propagate."""
if timeout_s is None or timeout_s <= 0:
return await websocket.receive_text()
try:
return await asyncio.wait_for(websocket.receive_text(), timeout=timeout_s)
except TimeoutError:
return None
MODEL_OUTPUT_EVENTS = frozenset(
{
"response.created",
"response.listen",
"response.speak",
"response.output_item.added",
"response.content_part.added",
"response.output_audio.delta",
"response.output_audio.done",
"response.output_text.delta",
"response.output_text.done",
"response.text.delta",
"response.text.done",
"response.message",
"response.output_item.done",
"response.content_part.done",
"response.done",
"runtime.control",
}
)
DOMAIN_TERMINAL_EVENTS = frozenset(
{
"response.done",
"response.listen",
"audio.cancelled",
"input.cancelled",
"session.closed",
}
)
def attachment_callbacks(websocket: WebSocket) -> tuple[SendJson, CloseFn]:
"""``send`` / ``close`` callables for a ``DuplexSessionAttachmentRegistry`` attachment.
A send on a socket that already closed surfaces as ``WebSocketDisconnect``
so the caller's disconnect path runs instead of a generic failure.
"""
def is_input_event(event_type: object) -> bool:
return isinstance(event_type, str) and event_type in INPUT_EVENTS
@dataclass(frozen=True, slots=True)
class DuplexAppendTaskMeta:
epoch: int
mode: str
final: bool
response_bound: bool
@dataclass
class DuplexSessionTasks:
"""Connection-independent task handles for one resumable session."""
native_append_tasks: dict[asyncio.Task[bool], DuplexAppendTaskMeta] = field(default_factory=dict)
native_append_tail: asyncio.Task[bool] | None = None
active_response_task: asyncio.Task[None] | None = None
def track_append_task(
self,
task: asyncio.Task[bool],
*,
epoch: int,
mode: str,
final: bool,
response_bound: bool,
) -> None:
self.native_append_tasks[task] = DuplexAppendTaskMeta(epoch, mode, final, response_bound)
task.add_done_callback(self.native_append_tasks.pop)
def has_response_bound_append_tasks(self) -> bool:
return any(meta.response_bound for meta in self.native_append_tasks.values())
async def cancel_append_tasks(self, timeout_s: float = 0.25, *, response_bound_only: bool = False) -> bool:
tasks = [
task for task, meta in self.native_append_tasks.items() if not response_bound_only or meta.response_bound
]
if not tasks:
return False
cancelled_tail = self.native_append_tail if self.native_append_tail in tasks else None
for task in tasks:
task.cancel()
async def attachment_send(payload: dict[str, object]) -> None:
try:
await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), timeout=timeout_s)
except TimeoutError:
pass
if cancelled_tail is not None and self.native_append_tail is cancelled_tail:
self.native_append_tail = None
return True
await websocket.send_json(payload)
except RuntimeError as exc:
message = str(exc)
if "after sending 'websocket.close'" in message or "response already completed" in message:
raise WebSocketDisconnect(code=1006) from exc
raise
async def attachment_close(reason: str) -> None:
close = getattr(websocket, "close", None)
if callable(close):
with suppress(Exception):
await close(code=1000, reason=reason)
return attachment_send, attachment_close
@dataclass
class DuplexWebSocketActor:
"""Own ordered WebSocket I/O queues, but no domain identity."""
websocket: Any
current_epoch: Callable[[], int | None] | None = None
session_closed: Callable[[], bool] | None = None
output_queue: asyncio.Queue[dict[str, object] | None] = field(default_factory=asyncio.Queue)
mailbox: asyncio.Queue[dict[str, object]] = field(default_factory=asyncio.Queue)
outbound_protocol: Any | None = None
tasks: DuplexSessionTasks = field(default_factory=DuplexSessionTasks)
closing: bool = False
close_reason: str | None = None
stale_output_dropped: int = 0
_queued_input_events: int = 0
@property
def native_append_tasks(self) -> dict[asyncio.Task[bool], DuplexAppendTaskMeta]:
return self.tasks.native_append_tasks
@property
def active_response_task(self) -> asyncio.Task[None] | None:
return self.tasks.active_response_task
@active_response_task.setter
def active_response_task(self, task: asyncio.Task[None] | None) -> None:
self.tasks.active_response_task = task
@property
def native_append_tail(self) -> asyncio.Task[bool] | None:
return self.tasks.native_append_tail
@native_append_tail.setter
def native_append_tail(self, task: asyncio.Task[bool] | None) -> None:
self.tasks.native_append_tail = task
async def enqueue_event(self, event: dict[str, object]) -> None:
if is_input_event(event.get("type")):
self._queued_input_events += 1
await self.mailbox.put(event)
async def next_event(self) -> dict[str, object]:
event = await self.mailbox.get()
if is_input_event(event.get("type")):
self._queued_input_events = max(0, self._queued_input_events - 1)
self.mailbox.task_done()
return event
def has_queued_input_events(self) -> bool:
return self._queued_input_events > 0
async def send_json(self, payload: dict[str, object]) -> None:
await self.output_queue.put(payload)
async def close_writer(self) -> None:
await self.output_queue.put(None)
async def writer_loop(self) -> None:
while True:
payload = await self.output_queue.get()
try:
if payload is None:
return
raw_realtime = payload.pop("_realtime_raw", False) is True
if not raw_realtime and self._is_stale_model_output(payload):
self.stale_output_dropped += 1
continue
try:
if raw_realtime:
await self.websocket.send_json(payload)
elif self.outbound_protocol is not None:
for projected in self.outbound_protocol.encode_outbound_event(payload):
await self.websocket.send_json(projected)
else:
await self.websocket.send_json(payload)
except (WebSocketDisconnect, RuntimeError):
return
finally:
self.output_queue.task_done()
def _is_stale_model_output(self, payload: dict[str, object]) -> bool:
event_type = payload.get("type")
if event_type in DOMAIN_TERMINAL_EVENTS:
return False
if event_type not in MODEL_OUTPUT_EVENTS:
return False
if self.closing and event_type not in {"response.listen", "runtime.control"}:
return True
expected_epoch = self.current_epoch() if self.current_epoch is not None else None
if (
self.session_closed is not None
and self.session_closed()
and event_type
not in {
"response.listen",
"runtime.control",
}
):
return True
epoch = payload.get("epoch")
return isinstance(epoch, int) and isinstance(expected_epoch, int) and epoch != expected_epoch
def track_append_task(
self,
task: asyncio.Task[bool],
*,
epoch: int,
mode: str,
final: bool,
response_bound: bool,
) -> None:
self.tasks.track_append_task(
task,
epoch=epoch,
mode=mode,
final=final,
response_bound=response_bound,
)
def has_response_bound_append_tasks(self) -> bool:
return self.tasks.has_response_bound_append_tasks()
async def cancel_append_tasks(self, timeout_s: float = 0.25, *, response_bound_only: bool = False) -> bool:
return await self.tasks.cancel_append_tasks(timeout_s, response_bound_only=response_bound_only)
__all__ = [
"DOMAIN_TERMINAL_EVENTS",
"DuplexAppendTaskMeta",
"DuplexSessionTasks",
"DuplexWebSocketActor",
"is_input_event",
]
__all__ = ["MAX_EVENT_BYTES", "CloseFn", "SendJson", "attachment_callbacks", "receive_text_with_timeout"]
+476
View File
@@ -0,0 +1,476 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""DuplexOmni: the Python API for full-duplex models.
Sessions run inside the engine (``DuplexSessionRunner`` on the orchestrator
loop of ``DuplexOrchestrator``). This class opens / resumes / closes them and
pipes typed ``DuplexCommand`` objects in and typed ``DuplexEvent`` objects out
through a ``DuplexSessionHandle``. It holds no session state beyond the
handle registry, so the websocket handler and ``InlineDuplexClient`` are both
thin consumers of the same surface.
Example::
omni = DuplexOmni(model="openbmb/MiniCPM-o-4_5", trust_remote_code=True)
async with await omni.open_session({"modalities": ["audio", "text"]}) as session:
async def consume():
async for event in session.events():
if isinstance(event, AudioDelta):
play(event.audio)
task = asyncio.create_task(consume())
await session.submit(AppendAudio(audio=pcm_bytes, format="pcm16", sample_rate_hz=16000))
await session.submit(Commit())
"""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator, Mapping, Sequence
from contextlib import suppress
from typing import Any
from uuid import uuid4
from vllm.logger import init_logger
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
from vllm_omni.engine.duplex import commands as duplex_commands
from vllm_omni.engine.duplex.commands import DuplexCommand
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig, ResponseCreateOptions
from vllm_omni.engine.duplex.events import DuplexEvent, SessionClosed
from vllm_omni.engine.duplex.messages import (
DuplexControlResultMessage,
DuplexSessionError,
DuplexSessionEventMessage,
)
from vllm_omni.engine.duplex_omni_engine import DuplexOmniEngine
from vllm_omni.entrypoints.async_omni import AsyncOmni
logger = init_logger(__name__)
_DEFAULT_CONTROL_TIMEOUT_S = 10.0
class DuplexSessionHandle:
"""Client-side view of one engine-resident duplex session.
Connection-independent: a websocket may detach and a later one resume the
same handle. ``events()`` is single-consumer at any given time but may be
re-entered after the previous iterator was closed (resume).
"""
def __init__(self, omni: DuplexOmni, session_id: str) -> None:
self._omni = omni
#: Allocated by ``DuplexOmni.open_session``; unique for the engine's lifetime.
self.session_id = session_id
self.capabilities: DuplexCapabilities = DuplexCapabilities()
self.public_session: dict[str, object] = {}
self.lease_generation: int = 0
self._outbox: asyncio.Queue[DuplexEvent | None] = asyncio.Queue()
self._closed = False
self._close_reason: str | None = None
self._closed_event = asyncio.Event()
self._consumer_active = False
# ---- state ----
@property
def closed(self) -> bool:
return self._closed
@property
def close_reason(self) -> str | None:
return self._close_reason
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"DuplexSessionHandle(session_id={self.session_id!r}, closed={self._closed})"
# ---- input ----
async def submit(self, command: DuplexCommand) -> None:
"""Enqueue one command in caller order; rejections arrive as ``ErrorEvent`` on ``events()``."""
if self._closed:
raise DuplexSessionError(
f"duplex session {self.session_id} is closed", code="session_closed", session_id=self.session_id
)
await self._omni.engine.submit_command_async(self.session_id, command)
async def append_audio(
self,
audio: bytes,
*,
format: str = "pcm16",
sample_rate_hz: int | None = None,
is_speech: bool | None = None,
video_frames: Sequence[str] | None = None,
duration_ms: int | None = None,
audio_end_ms: int | None = None,
hints: Mapping[str, object] | None = None,
) -> None:
await self.submit(
duplex_commands.AppendAudio(
audio=audio,
format=format,
sample_rate_hz=sample_rate_hz,
is_speech=is_speech,
video_frames=tuple(video_frames or ()),
duration_ms=duration_ms,
audio_end_ms=audio_end_ms,
hints=dict(hints or {}),
)
)
async def append_text(self, text: str) -> None:
await self.submit(duplex_commands.AppendText(text=text))
async def commit(
self,
*,
final: bool = True,
create_response: bool | None = None,
is_speech: bool | None = None,
) -> None:
await self.submit(duplex_commands.Commit(final=final, create_response=create_response, is_speech=is_speech))
async def create_response(self, options: ResponseCreateOptions | Mapping[str, object] | None = None) -> None:
if isinstance(options, ResponseCreateOptions):
payload: dict[str, object] = {
key: value
for key, value in (
("instructions", options.instructions),
("voice", options.voice),
("output_audio_format", options.response_format),
("temperature", options.temperature),
("max_output_tokens", options.max_tokens),
("speed", options.speed),
("modalities", list(options.modalities) if options.modalities is not None else None),
)
if value is not None
}
if options.extra_body:
payload["extra_body"] = dict(options.extra_body)
else:
payload = dict(options or {})
await self.submit(duplex_commands.CreateResponse(options=payload))
async def clear_input(self) -> None:
await self.submit(duplex_commands.ClearInput())
async def cancel_input(self) -> None:
await self.submit(duplex_commands.CancelInput())
async def cancel_response(self, response_id: str | None = None) -> None:
await self.submit(duplex_commands.CancelResponse(response_id=response_id))
async def barge_in(self) -> None:
await self.submit(duplex_commands.BargeIn())
async def clear_output_audio(self, response_id: str | None = None) -> None:
await self.submit(duplex_commands.ClearOutputAudio(response_id=response_id))
async def signal_turn(self, event: str, payload: Mapping[str, object] | None = None) -> None:
await self.submit(duplex_commands.SignalTurn(event=event, signal_payload=dict(payload or {})))
async def update(self, session_patch: Mapping[str, object]) -> None:
await self.submit(duplex_commands.UpdateSession(patch=dict(session_patch)))
async def ack_playback(
self,
played_ms: int,
*,
response_id: str | None = None,
item_id: str | None = None,
committed_ms: int | None = None,
) -> None:
await self.submit(
duplex_commands.AckPlayback(
played_ms=int(played_ms),
committed_ms=int(committed_ms) if committed_ms is not None else None,
response_id=response_id,
item_id=item_id,
)
)
async def heartbeat(self) -> None:
await self.submit(duplex_commands.Heartbeat())
async def create_item(self, item: Mapping[str, object], *, previous_item_id: str | None = None) -> None:
await self.submit(duplex_commands.CreateItem(item=dict(item), previous_item_id=previous_item_id))
async def delete_item(self, item_id: str) -> None:
await self.submit(duplex_commands.DeleteItem(item_id=item_id))
async def truncate_item(self, item_id: str, *, audio_end_ms: int, content_index: int = 0) -> None:
await self.submit(
duplex_commands.TruncateItem(item_id=item_id, audio_end_ms=int(audio_end_ms), content_index=content_index)
)
async def close(self, *, reason: str = "client_close", timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S) -> None:
if self._closed:
return
await self._omni.close_session(self.session_id, reason=reason, timeout=timeout)
# ---- output ----
async def events(self) -> AsyncIterator[DuplexEvent]:
"""Ordered public events; ends after ``session.closed`` / ``session.expired``."""
if self._consumer_active:
raise RuntimeError(f"duplex session {self.session_id} already has an active events() consumer")
self._consumer_active = True
try:
while True:
if self._closed and self._outbox.empty():
return
event = await self._outbox.get()
if event is None:
if self._closed and self._outbox.empty():
return
continue
yield event
if event.is_terminal:
return
finally:
self._consumer_active = False
async def wait_closed(self) -> str:
await self._closed_event.wait()
return self._close_reason or "closed"
async def __aenter__(self) -> DuplexSessionHandle:
return self
async def __aexit__(self, exc_type, exc, traceback) -> None:
try:
await self.close()
except DuplexSessionError:
pass
# ---- internals used by DuplexOmni ----
def _adopt(self, result: DuplexControlResultMessage) -> None:
if result.capabilities is not None:
self.capabilities = result.capabilities
if result.public_session:
self.public_session = dict(result.public_session)
if result.lease_generation is not None:
self.lease_generation = int(result.lease_generation)
def _deliver(self, event: DuplexEvent) -> None:
self._outbox.put_nowait(event)
if isinstance(event, SessionClosed): # SessionExpired is a SessionClosed
self._mark_closed(event.reason or event.type)
def _mark_closed(self, reason: str) -> None:
if self._closed:
return
self._closed = True
self._close_reason = reason
self._closed_event.set()
self._outbox.put_nowait(None)
class DuplexOmni(AsyncOmni):
"""Async Python API for full-duplex models (see module docstring).
Construct it like ``AsyncOmni``. The pipeline must declare
``duplex_plugin`` and the deploy config ``session_mode: duplex``; the
engine raises at startup otherwise. There is no ``generate()``: duplex
serving is session-only.
"""
engine: DuplexOmniEngine
def _create_engine(self, **engine_kwargs: Any) -> DuplexOmniEngine:
from vllm_omni.entrypoints.duplex.audio_encoding import encode_audio
return DuplexOmniEngine(duplex_audio_encoder=encode_audio, **engine_kwargs)
def __init__(self, model: str = "", *args: Any, **kwargs: Any) -> None:
super().__init__(*args, model=model, **kwargs)
self._handles: dict[str, DuplexSessionHandle] = {}
# ---- deployment facts ----
@property
def duplex_session_config(self) -> DuplexSessionRuntimeConfig:
return self.engine.duplex_session_config
@property
def duplex_capabilities(self) -> DuplexCapabilities:
return self.engine.duplex_capabilities
@property
def sessions(self) -> Mapping[str, DuplexSessionHandle]:
return dict(self._handles)
def active_session_count(self) -> int:
return sum(1 for handle in self._handles.values() if not handle.closed)
# ---- session lifecycle ----
@staticmethod
def _resolve_session_config(
config: DuplexSessionConfig | Mapping[str, object] | None,
*,
model: str,
) -> DuplexSessionConfig:
"""Build the normalized session config the engine will own (the one parse/normalize site).
A ``session_id`` / ``id`` key inside a Realtime session object is
ignored: Realtime clients echo the session object back, and the server
allocates every session id.
"""
if config is None:
resolved = DuplexSessionConfig(model=model)
elif isinstance(config, DuplexSessionConfig):
resolved = config
elif isinstance(config, Mapping):
resolved = DuplexSessionConfig.from_realtime(config, model=model)
else:
raise TypeError(f"unsupported duplex session config: {type(config).__name__}")
if resolved.model is None:
resolved.model = model
return resolved.normalized()
async def open_session(
self,
config: DuplexSessionConfig | Mapping[str, object] | None = None,
*,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexSessionHandle:
"""Open an engine-resident session and return its handle.
The session id is always allocated here (``duplex-<uuid4 hex>``; never
reused, so the id alone identifies a session) and the handle is
registered before the open RPC, so the first event (``session.created``,
which announces the id) can never arrive before it exists.
"""
session_id = f"duplex-{uuid4().hex}"
session_config = self._resolve_session_config(config, model=self.model)
handle = DuplexSessionHandle(self, session_id)
self._handles[session_id] = handle
self._final_output_handler()
try:
result = await self.engine.open_session_async(session_id, session_config, timeout=timeout)
except BaseException:
if self._handles.get(session_id) is handle:
self._handles.pop(session_id, None)
# Dropping the handle only forgets the id here. The engine may still
# be admitting this session -- a control timeout unregisters the RPC
# waiter but cannot cancel the manager's open -- so a late admission
# would hold an admission slot and a Stage0 reservation until idle
# expiry. Send the compensating close; the manager applies it
# immediately if the session already landed, and records it for the
# open to honour on arrival if not.
with suppress(Exception):
await self.engine.close_session_async(session_id, reason="open_abandoned", timeout=timeout)
raise
handle._adopt(result)
return handle
def get_session(self, session_id: str) -> DuplexSessionHandle | None:
return self._handles.get(session_id)
async def resume_session(
self,
session_id: str,
*,
expected_lease_generation: int,
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> DuplexSessionHandle:
"""Engine lease resume (CAS on the lease generation); returns the existing handle."""
handle = self._require_handle(session_id)
result = await self.engine.resume_session_async(
session_id,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
)
# The result carries the engine's current public session (state,
# epoch, turn ...), which a resumed client must see, not the open-time snapshot.
handle._adopt(result)
return handle
async def touch_session(
self,
session_id: str,
*,
activity: str = "heartbeat",
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> None:
self._require_handle(session_id)
await self.engine.touch_session_async(session_id, activity=activity, timeout=timeout)
async def detach_session(self, session_id: str, *, timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S) -> None:
"""Start the engine-owned disconnect grace; expiry arrives as ``session.expired``."""
await self.touch_session(session_id, activity="detach", timeout=timeout)
async def close_session(
self,
session_id: str,
*,
reason: str = "client_close",
timeout: float | None = _DEFAULT_CONTROL_TIMEOUT_S,
) -> None:
handle = self._handles.get(session_id)
if handle is None or handle.closed:
return
try:
await self.engine.close_session_async(session_id, reason=reason, timeout=timeout)
except Exception:
# The engine refused or lost the close: the handle is unusable
# either way, and it must not shadow the id in ``sessions``.
handle._mark_closed(reason)
self._handles.pop(session_id, None)
raise
# The manager emits session.closed after the stage cleanup, but the
# event travels on the output queue: wait for it so ``events()`` ends
# with the typed SessionClosed rather than an abrupt stop.
try:
await asyncio.wait_for(handle.wait_closed(), timeout=timeout)
except asyncio.TimeoutError:
logger.warning("[DuplexOmni] session.closed for %s did not arrive in time", session_id)
handle._mark_closed(reason)
self._handles.pop(session_id, None)
async def close_all_sessions(self, *, reason: str = "shutdown") -> None:
for session_id in list(self._handles):
try:
await self.close_session(session_id, reason=reason)
except Exception:
logger.exception("[DuplexOmni] failed to close session %s", session_id)
def _require_handle(self, session_id: str) -> DuplexSessionHandle:
handle = self._handles.get(session_id)
if handle is None or handle.closed:
raise DuplexSessionError(
f"unknown or closed duplex session: {session_id}", code="unknown_session", session_id=session_id
)
return handle
# ---- engine output routing ----
def _route_engine_message(self, msg: object) -> bool:
if not isinstance(msg, DuplexSessionEventMessage):
return False
handle = self._handles.get(msg.session_id)
if handle is None:
logger.debug("[DuplexOmni] dropping event for unknown session %s", msg.session_id)
return True
handle._deliver(msg.event)
if handle.closed:
self._handles.pop(msg.session_id, None)
return True
def _on_engine_dead(self, error: str) -> None:
for handle in list(self._handles.values()):
handle._mark_closed(f"engine_dead: {error}")
self._handles.clear()
def shutdown(self, timeout: float | None = None) -> None:
for handle in list(self._handles.values()):
handle._mark_closed("shutdown")
self._handles.clear()
super().shutdown(timeout)
__all__ = ["DuplexOmni", "DuplexSessionHandle"]
@@ -1,383 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from __future__ import annotations
import asyncio
import time
from collections.abc import Callable, MutableMapping
from typing import Protocol
from vllm_omni.engine.duplex.contracts import (
duplex_data_plane_request_info,
duplex_resource_request_id,
)
from vllm_omni.engine.duplex.lease import DuplexLeaseActivity
from vllm_omni.engine.duplex.messages import DuplexFence
from vllm_omni.engine.messages import ErrorMessage, OutputMessage
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.metrics.stats import OrchestratorAggregator as OrchestratorMetrics
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.outputs.duplex import get_duplex_output_decision
class DuplexEnginePort(Protocol):
"""Engine control methods required by the experimental request client.
The protocol keeps request preregistration and output collection testable
without coupling this component to ``AsyncOmniEngine``.
"""
async def open_duplex_session_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
async def append_duplex_input_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
async def signal_duplex_turn_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
async def close_duplex_session_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
async def touch_duplex_session_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
async def resume_duplex_session_async(self, session_id: str, **kwargs) -> dict[str, object]: ...
class DuplexRequestOutputPort:
"""Narrow output-processing surface owned by the AsyncOmni entrypoint."""
def __init__(
self,
*,
request_states: MutableMapping[str, ClientRequestState],
num_stages: int,
log_stats: bool,
start_output_handler: Callable[[], object],
process_single_result: Callable[..., OmniRequestOutput | None],
) -> None:
self.request_states = request_states
self.num_stages = num_stages
self.log_stats = log_stats
self._start_output_handler = start_output_handler
self._process_single_result = process_single_result
def start_output_handler(self) -> None:
self._start_output_handler()
def process_single_result(self, *args, **kwargs) -> OmniRequestOutput | None:
return self._process_single_result(*args, **kwargs)
class DuplexRequestClient:
"""Owns duplex request identity, preregistration and output collection."""
def __init__(self, engine: DuplexEnginePort, output_port: DuplexRequestOutputPort) -> None:
self.engine = engine
self.output_port = output_port
@staticmethod
def request_info(result: dict[str, object]) -> tuple[str | None, int | None]:
return duplex_data_plane_request_info(result)
async def open(
self,
session_id: str,
*,
session_mode: str,
capabilities: dict[str, object] | None,
session_config: dict[str, object] | None,
runtime_config: dict[str, object] | None,
fence: DuplexFence,
timeout: float | None,
) -> dict[str, object]:
# Lifecycle expiry messages share the engine output channel. Start its
# sole dispatcher before open so an idle session can be reaped even if
# it never submits an append request.
self.output_port.start_output_handler()
kwargs: dict[str, object] = {
"session_mode": session_mode,
"capabilities": capabilities,
"session_config": session_config,
"fence": fence,
"timeout": timeout,
}
if runtime_config is not None:
kwargs["runtime_config"] = runtime_config
return await self.engine.open_duplex_session_async(session_id, **kwargs)
async def append(
self,
session_id: str,
*,
mode: str,
payload: object,
operation_id: str | None,
final: bool,
expected_epoch: int | None,
fence: DuplexFence,
timeout: float | None,
collect_outputs: bool,
) -> dict[str, object]:
kwargs: dict[str, object] = {
"mode": mode,
"payload": payload,
"final": final,
"expected_epoch": expected_epoch,
"timeout": timeout,
"fence": fence,
}
if operation_id is not None:
kwargs["operation_id"] = operation_id
expected_request_id = duplex_resource_request_id(fence, "stage0")
request_state = self.output_port.request_states.get(expected_request_id)
created_request_state = request_state is None
if request_state is None:
request_state = ClientRequestState(expected_request_id)
self.output_port.request_states[expected_request_id] = request_state
if request_state.metrics is None:
wall_start_ts = time.time()
request_state.metrics = OrchestratorMetrics(
self.output_port.num_stages,
self.output_port.log_stats,
wall_start_ts,
max(0, self.output_port.num_stages - 1),
)
request_state.request_arrival_ts = wall_start_ts
self.output_port.start_output_handler()
try:
result = await self.engine.append_duplex_input_async(session_id, **kwargs)
except BaseException:
if created_request_state and request_state.queue.empty():
self.output_port.request_states.pop(expected_request_id, None)
raise
request_id, response_stage_id = duplex_data_plane_request_info(result)
if request_id is None:
if created_request_state and request_state.queue.empty():
self.output_port.request_states.pop(expected_request_id, None)
return result
if request_id != expected_request_id:
if created_request_state and request_state.queue.empty():
self.output_port.request_states.pop(expected_request_id, None)
raise RuntimeError(
f"duplex data-plane request id mismatch: expected {expected_request_id!r}, got {request_id!r}"
)
if not collect_outputs:
return result
outputs = await self.collect_outputs(
request_id,
request_state,
response_stage_id=response_stage_id,
timeout=timeout,
)
if outputs:
result = dict(result)
result["data_plane_outputs"] = outputs
return result
async def collect_registered_outputs(
self,
request_id: str,
*,
response_stage_id: int | None,
timeout: float | None,
) -> list[OmniRequestOutput]:
self.output_port.start_output_handler()
request_state = self.output_port.request_states.get(request_id)
if request_state is None:
return []
return await self.collect_outputs(
request_id,
request_state,
response_stage_id=response_stage_id,
timeout=timeout,
)
async def signal(
self,
session_id: str,
*,
event: str,
fence: DuplexFence,
next_fence: DuplexFence | None,
session_config: dict[str, object] | None,
runtime_config: dict[str, object] | None,
timeout: float | None,
) -> dict[str, object]:
kwargs: dict[str, object] = {"event": event, "fence": fence, "timeout": timeout}
if next_fence is not None:
kwargs["next_fence"] = next_fence
if session_config is not None:
kwargs["session_config"] = session_config
if runtime_config is not None:
kwargs["runtime_config"] = runtime_config
result = await self.engine.signal_duplex_turn_async(session_id, **kwargs)
if event in {"barge_in", "input.cancel", "response.cancel"}:
self.output_port.request_states.pop(duplex_resource_request_id(fence, "stage0"), None)
return result
async def close(
self,
session_id: str,
*,
reason: str,
fence: DuplexFence,
timeout: float | None,
) -> dict[str, object]:
result = await self.engine.close_duplex_session_async(
session_id,
reason=reason,
fence=fence,
timeout=timeout,
)
self.output_port.request_states.pop(duplex_resource_request_id(fence, "stage0"), None)
return result
async def touch(
self,
session_id: str,
*,
fence: DuplexFence,
activity: DuplexLeaseActivity,
timeout: float | None,
) -> dict[str, object]:
return await self.engine.touch_duplex_session_async(
session_id,
fence=fence,
activity=activity,
timeout=timeout,
)
async def resume(
self,
session_id: str,
*,
fence: DuplexFence,
expected_lease_generation: int,
timeout: float | None,
) -> dict[str, object]:
return await self.engine.resume_duplex_session_async(
session_id,
fence=fence,
expected_lease_generation=expected_lease_generation,
timeout=timeout,
)
async def collect_outputs(
self,
request_id: str,
request_state: ClientRequestState,
*,
response_stage_id: int | None,
timeout: float | None,
) -> list[OmniRequestOutput]:
deadline = None if timeout is None else time.monotonic() + timeout
wall_start_ts = request_state.request_arrival_ts or time.time()
final_stage_id = response_stage_id if response_stage_id is not None else max(0, self.output_port.num_stages - 1)
num_stages = max(self.output_port.num_stages, final_stage_id + 1)
metrics = getattr(request_state, "metrics", None) or OrchestratorMetrics(
num_stages,
self.output_port.log_stats,
wall_start_ts,
final_stage_id,
)
stage_event_cursor = metrics.stage_event_cursor(request_id)
request_start_ts = {request_id: wall_start_ts}
outputs: list[OmniRequestOutput] = []
while True:
remaining = None if deadline is None else max(0.0, deadline - time.monotonic())
if remaining == 0.0:
break
try:
message = await asyncio.wait_for(request_state.queue.get(), timeout=remaining)
except asyncio.TimeoutError:
break
if isinstance(message, ErrorMessage):
raise RuntimeError(message.error)
if not isinstance(message, OutputMessage):
continue
engine_outputs = message.engine_outputs
is_response_stage = response_stage_id is None or message.stage_id >= response_stage_id
is_direct_response = self.is_direct_response(engine_outputs)
output_to_collect = None
if isinstance(engine_outputs, OmniRequestOutput):
output_to_collect = engine_outputs
if message.metrics is not None:
existing_metrics = dict(output_to_collect.metrics)
metrics.process_stage_metrics(
result={"metrics": message.metrics},
stage_type="",
stage_id=message.stage_id,
req_id=request_id,
engine_outputs=engine_outputs,
finished=message.finished,
final_output_type=engine_outputs.final_output_type,
output_to_yield=output_to_collect,
event_cursor=stage_event_cursor,
)
generated_metrics = dict(output_to_collect.metrics)
existing_stage_metrics = existing_metrics.get("stage_metrics")
generated_stage_metrics = generated_metrics.get("stage_metrics")
if isinstance(existing_stage_metrics, dict) and isinstance(generated_stage_metrics, dict):
generated_metrics["stage_metrics"] = {
**existing_stage_metrics,
**generated_stage_metrics,
}
output_to_collect.metrics = {
**existing_metrics,
**generated_metrics,
}
elif is_response_stage:
output_to_collect = self.output_port.process_single_result(
message,
message.stage_id,
metrics,
request_start_ts,
wall_start_ts,
final_stage_id,
stage_event_cursor,
)
if output_to_collect is not None and (is_response_stage or is_direct_response):
if message.finished:
output_to_collect.finished = True
outputs.append(output_to_collect)
if message.finished or outputs:
break
return outputs
@classmethod
def is_direct_response(cls, output: object) -> bool:
multimodal_output = cls.multimodal_output(output)
if not multimodal_output:
return False
return multimodal_output.get("duplex_direct_response") is True or multimodal_output.get(
"duplex_native_decision"
) in {"listen", "speak"}
@classmethod
def multimodal_output(cls, output: object) -> dict[str, object]:
if isinstance(output, OmniRequestOutput):
decision = get_duplex_output_decision(output)
if decision is not None:
return dict(decision.metadata)
private_output = getattr(output, "_multimodal_output", None)
multimodal_output = output.multimodal_output
if isinstance(multimodal_output, dict) and multimodal_output:
return multimodal_output
inner_output = getattr(output, "request_output", None)
if inner_output is not None and inner_output is not output:
inner_multimodal_output = cls.multimodal_output(inner_output)
if inner_multimodal_output:
return inner_multimodal_output
if isinstance(private_output, dict):
return private_output
return multimodal_output if isinstance(multimodal_output, dict) else {}
multimodal_output = getattr(output, "multimodal_output", None)
if isinstance(multimodal_output, dict):
return multimodal_output
outputs = getattr(output, "outputs", None)
completion = outputs[0] if isinstance(outputs, list) and outputs else None
multimodal_output = getattr(completion, "multimodal_output", None) if completion is not None else None
return multimodal_output if isinstance(multimodal_output, dict) else {}
__all__ = ["DuplexEnginePort", "DuplexRequestClient", "DuplexRequestOutputPort"]
+5 -1
View File
@@ -7,12 +7,13 @@ import copy
import time
import uuid
from collections.abc import Callable, Generator, Iterable, Sequence
from typing import TYPE_CHECKING, Literal, overload
from typing import TYPE_CHECKING, Any, Literal, overload
from tqdm.auto import tqdm
from vllm.logger import init_logger
from vllm.sampling_params import RequestOutputKind
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.engine.messages import OutputMessage
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.omni_base import OmniBase
@@ -28,6 +29,9 @@ logger = init_logger(__name__)
class Omni(OmniBase):
"""Synchronous entrypoint for offline generation."""
def _create_engine(self, **engine_kwargs: Any) -> AsyncOmniEngine:
return AsyncOmniEngine(**engine_kwargs)
def _maybe_force_final_only_for_llm_stages(
self,
sampling_params_list: Sequence[OmniSamplingParams],
+11 -7
View File
@@ -19,13 +19,13 @@ from vllm.transformers_utils.runai_utils import is_runai_obj_uri
from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.config.stage_config import merge_sampling_constraints
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.engine.messages import (
EngineQueueMessage,
ErrorMessage,
OutputMessage,
StageMetricsMessage,
)
from vllm_omni.engine.omni_engine_base import OmniEngineBase
from vllm_omni.entrypoints.client_request_state import ClientRequestState
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
from vllm_omni.entrypoints.utils import coerce_param_message_types, get_final_stage_id_for_e2e
@@ -66,7 +66,7 @@ class OmniEngineDeadError(EngineDeadError):
self.error_stage_id = error_stage_id
def _weak_shutdown_engine(engine: AsyncOmniEngine) -> None:
def _weak_shutdown_engine(engine: OmniEngineBase) -> None:
"""Best-effort engine cleanup for GC finalization."""
try:
engine.shutdown()
@@ -206,13 +206,13 @@ class OmniBase(PDDisaggregationMixin):
self.tts_batch_max_items: int = kwargs.pop("tts_batch_max_items", 32)
logger.info("[%s] Initializing with model %s", self.__class__.__name__, model)
# Construct transfer_metrics first so we can hand it to AsyncOmniEngine
# Construct transfer_metrics first so we can hand it to the engine
# (which forwards it to the Orchestrator background thread for
# TX-side emit; see Orchestrator._forward_to_next_stage).
# TX-side emit; see OrchestratorBase._forward_to_next_stage).
self.transfer_metrics = OmniTransferMetrics(model_name=model, log_stats=log_stats)
self.prom_metrics = OmniPrometheusMetrics(model_name=model, log_stats=log_stats)
st = time.time()
self.engine = AsyncOmniEngine(
self.engine = self._create_engine(
model=model,
init_timeout=init_timeout,
stage_init_timeout=stage_init_timeout,
@@ -224,8 +224,8 @@ class OmniBase(PDDisaggregationMixin):
self._shutdown_called = False
self._weak_finalizer = weakref.finalize(self, _weak_shutdown_engine, self.engine)
et = time.time()
logger.info("[%s] AsyncOmniEngine initialized in %.2f seconds", self.__class__.__name__, et - st)
# Authoritative: ``AsyncOmniEngine`` resolves (pipeline + deploy YAML +
logger.info("[%s] %s initialized in %.2f seconds", self.__class__.__name__, type(self.engine).__name__, et - st)
# Authoritative: the engine resolves (pipeline + deploy YAML +
# CLI overrides) through ``StageConfigFactory`` and stores the final
# value on ``engine.async_chunk``; mirror it here so ``--no-async-chunk``
# (explicit ``False``) is not fallen-back-through by ``or``.
@@ -253,6 +253,10 @@ class OmniBase(PDDisaggregationMixin):
# PD disaggregation state (detects if a prefill/decode stage pair is configured)
self._init_pd_state()
def _create_engine(self, **engine_kwargs: Any) -> OmniEngineBase:
"""Construct this entrypoint's engine (``AsyncOmniEngine`` for turn-based use)."""
raise NotImplementedError
@property
def num_stages(self) -> int:
return self.engine.num_stages
+212 -39
View File
@@ -86,10 +86,10 @@ from vllm.v1.engine.exceptions import EngineDeadError, EngineGenerateError
from vllm_omni.config.endpoint_policy import (
shutdown_unsupported_routes,
)
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.duplex.capability import should_enable_duplex_endpoint
from vllm_omni.entrypoints.async_omni import ABORT_TIMEOUT_S, AsyncOmni
from vllm_omni.entrypoints.duplex.serving import OmniDuplexSessionHandler
from vllm_omni.entrypoints.duplex.warmup import _warmup_duplex_realtime
from vllm_omni.entrypoints.duplex_omni import DuplexOmni
from vllm_omni.entrypoints.openai import app_state as openai_app_state
from vllm_omni.entrypoints.openai.app_state import (
ENDPOINT_LOAD_METRICS_FORMAT_HEADER_LABEL,
@@ -201,6 +201,8 @@ from vllm_omni.utils.tracking_parser import TrackingArgumentParser, TrackingName
logger = init_logger(__name__)
router = APIRouter()
VIDEO_ABORT_TIMEOUT_S = ABORT_TIMEOUT_S
profiler_router = APIRouter()
@@ -438,6 +440,23 @@ async def build_async_omni(
yield async_omni
def _is_duplex_model(model: str, kwargs: dict[str, Any]) -> bool:
"""Whether ``model``'s pipeline declares a ``duplex_plugin`` (served by ``DuplexOmni``).
Resolution errors propagate: a duplex model whose pipeline or deploy
config cannot be resolved must fail startup rather than silently start a
turn-based server.
"""
from vllm_omni.config.config_factory import StageConfigFactory
pipeline_config = StageConfigFactory.get_pipeline_config(
model=model,
trust_remote_code=bool(kwargs.get("trust_remote_code")),
deploy_config_path=kwargs.get("deploy_config"),
)
return bool(pipeline_config is not None and getattr(pipeline_config, "duplex_plugin", None))
@asynccontextmanager
async def build_async_omni_from_stage_config(
args: TrackingNamespace,
@@ -499,7 +518,12 @@ async def build_async_omni_from_stage_config(
kwargs.pop("robot_openpi_idle_timeout", None)
model = kwargs.pop("model", None) or args.model
kwargs.setdefault("log_stats", not args.disable_log_stats)
async_omni = AsyncOmni(model=model, **kwargs)
if _is_duplex_model(model, kwargs):
# A duplex model is always served in duplex mode: sessions over
# /v1/realtime?duplex=1, no turn-based HTTP routes.
async_omni = DuplexOmni(model=model, **kwargs)
else:
async_omni = AsyncOmni(model=model, **kwargs)
# # Don't keep the dummy data in memory
# await async_llm.reset_mm_cache()
@@ -510,6 +534,134 @@ async def build_async_omni_from_stage_config(
async_omni.shutdown()
async def _init_duplex_app_state(
engine_client: DuplexOmni,
state: State,
args: Namespace,
base_model_paths: list[BaseModelPath],
vllm_config: Any,
request_logger: RequestLogger | None,
) -> None:
"""Minimal app state for a duplex server: only the surfaces a duplex session backs."""
state.vllm_config = vllm_config
state.diffusion_engine = None
state.openai_serving_models = OpenAIServingModels(
engine_client=engine_client, # type: ignore[arg-type]
base_model_paths=base_model_paths,
lora_modules=None,
)
state.serving_tokenization = None
state.serving_tokens = None
# Replaced by the chat init below when the model serves chat.
state.online_renderer = None
for attribute in (
"openai_serving_chat_batch",
"openai_serving_completion",
"openai_serving_responses",
"openai_serving_embedding",
"openai_serving_pooling",
"openai_serving_classification",
"openai_serving_scores",
"openai_serving_transcription",
"openai_serving_translation",
"openai_serving_speech",
"openai_serving_audio_generate",
"openai_serving_video",
"openai_streaming_speech",
"openai_streaming_video",
"openai_streaming_video_output",
"openai_serving_realtime",
"openai_serving_realtime_robot",
"anthropic_serving_messages",
):
setattr(state, attribute, None)
state.openai_serving_duplex = OmniDuplexSessionHandler(duplex_omni=engine_client)
# One engine, both surfaces. ``DuplexOmni`` extends ``AsyncOmni``, so the
# ordinary chat service runs on it unchanged: a chat request is a turn-based
# request on the same pipeline, not a session, and costs no admission slot.
state.openai_serving_chat = await _init_duplex_chat(engine_client, state, args, request_logger)
state.enable_server_load_tracking = getattr(args, "enable_server_load_tracking", False)
state.server_load_metrics = 0
if state.openai_serving_chat is not None:
logger.info(
"Duplex mode: serving %s over /v1/realtime?duplex=1 and /v1/chat/completions",
engine_client.model,
)
else:
logger.info(
"Duplex mode: serving %s over /v1/realtime?duplex=1 only "
"(/v1/chat/completions unavailable: the model does not declare supports_chat_completions)",
engine_client.model,
)
async def _init_duplex_chat(
engine_client: DuplexOmni,
state: State,
args: Namespace,
request_logger: RequestLogger | None,
) -> OmniOpenAIServingChat | None:
"""The ordinary chat service, on a duplex engine, when the model allows it.
Gated on ``DuplexCapabilities.supports_chat_completions`` so the decision
stays the model's: a duplex model that should not answer chat requests says
so in its plugin, and the route reports "not available" rather than
answering badly. ``endpoint_restrictions`` remains the per-deployment
opt-out on top of this.
"""
if not engine_client.duplex_capabilities.supports_chat_completions:
return None
supported_tasks: set[str] = {"generate"}
if hasattr(engine_client, "get_supported_tasks"):
supported_tasks = set(await engine_client.get_supported_tasks())
if "generate" not in supported_tasks:
return None
resolved_chat_template = load_chat_template(args.chat_template)
if resolved_chat_template is None:
try:
tokenizer = await engine_client.get_tokenizer()
except Exception as exc:
logger.debug("Could not inspect tokenizer chat_template before duplex chat init: %s", exc)
tokenizer = None
if tokenizer is None or getattr(tokenizer, "chat_template", None) is None:
resolved_chat_template = _load_model_chat_template_json(args.model)
state.online_renderer = OnlineRenderer(
model_config=engine_client.model_config,
renderer=engine_client.renderer,
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
trust_request_chat_template=args.trust_request_chat_template,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
default_chat_template_kwargs=args.default_chat_template_kwargs,
)
return OmniOpenAIServingChat(
engine_client=engine_client,
models=state.openai_serving_models,
response_role=args.response_role,
online_renderer=state.online_renderer,
request_logger=request_logger,
chat_template=resolved_chat_template,
chat_template_content_format=args.chat_template_content_format,
default_chat_template_kwargs=args.default_chat_template_kwargs,
trust_request_chat_template=args.trust_request_chat_template,
return_tokens_as_token_ids=args.return_tokens_as_token_ids,
enable_auto_tools=args.enable_auto_tool_choice,
exclude_tools_when_tool_choice_none=args.exclude_tools_when_tool_choice_none,
tool_parser=args.tool_call_parser,
reasoning_parser=args.structured_outputs_config.reasoning_parser,
enable_prompt_tokens_details=args.enable_prompt_tokens_details,
enable_force_include_usage=args.enable_force_include_usage,
enable_log_outputs=args.enable_log_outputs,
enable_log_deltas=args.enable_log_deltas,
)
async def omni_init_app_state(
engine_client: EngineClient,
state: State,
@@ -560,6 +712,13 @@ async def omni_init_app_state(
state.stage_configs = engine_client.stage_configs if hasattr(engine_client, "stage_configs") else None
model_name = served_model_names[0] if served_model_names else args.model
# Duplex mode: a duplex model is served through DuplexOmni only. Sessions
# run over /v1/realtime?duplex=1; every turn-based HTTP route reports
# "not available".
if isinstance(engine_client, DuplexOmni):
await _init_duplex_app_state(engine_client, state, args, base_model_paths, vllm_config, request_logger)
return
# Pure Diffusion mode: use simplified initialization logic
if is_pure_diffusion:
state.vllm_config = None
@@ -940,17 +1099,6 @@ async def omni_init_app_state(
else None
)
state.openai_serving_duplex = None
if state.openai_serving_chat is not None and should_enable_duplex_endpoint(
state.stage_configs,
config_path=getattr(engine_client, "config_path", None) or getattr(args, "deploy_config", None),
):
state.openai_serving_duplex = OmniDuplexSessionHandler(
chat_service=state.openai_serving_chat,
served_model_name=model_name,
log_stats=state.log_stats,
duplex_session_config=getattr(engine_client, "duplex_session_config", None),
serving_runtime_adapter_path=getattr(engine_client, "duplex_serving_adapter_path", None),
)
state.openai_serving_realtime = OpenAIServingRealtime(
engine_client=engine_client,
models=state.openai_serving_models,
@@ -1475,14 +1623,7 @@ async def streaming_video_output(websocket: WebSocket):
@router.websocket("/v1/realtime")
async def realtime_websocket(websocket: WebSocket):
"""WebSocket endpoint for OpenAI-style realtime interactions."""
# Hold real clients until the startup duplex warmup finishes (the warmup
# connection marks itself with vllm_omni_warmup=1 and passes through).
warmup_done = getattr(websocket.app.state, "duplex_warmup_done", None)
if warmup_done is not None and not warmup_done.is_set() and websocket.query_params.get("vllm_omni_warmup") != "1":
try:
await asyncio.wait_for(warmup_done.wait(), timeout=120)
except (TimeoutError, asyncio.TimeoutError):
logger.warning("Duplex warmup still running after 120 s; admitting the client anyway.")
await _wait_for_duplex_warmup(websocket)
duplex_handler = getattr(websocket.app.state, "openai_serving_duplex", None)
duplex_query = websocket.query_params.get("duplex")
use_duplex_realtime = duplex_handler is not None and (
@@ -1502,6 +1643,32 @@ async def realtime_websocket(websocket: WebSocket):
await connection.handle_connection()
async def _wait_for_duplex_warmup(websocket: WebSocket) -> None:
"""Hold real clients until the startup duplex warmup finishes.
The warmup connection marks itself with ``vllm_omni_warmup=1`` and passes through.
"""
warmup_done = getattr(websocket.app.state, "duplex_warmup_done", None)
if warmup_done is not None and not warmup_done.is_set() and websocket.query_params.get("vllm_omni_warmup") != "1":
try:
await asyncio.wait_for(warmup_done.wait(), timeout=120)
except (TimeoutError, asyncio.TimeoutError):
logger.warning("Duplex warmup still running after 120 s; admitting the client anyway.")
@router.websocket("/v1/duplex")
async def duplex_websocket(websocket: WebSocket):
"""Alias of ``/v1/realtime?duplex=1``: the same Realtime duplex session protocol."""
await _wait_for_duplex_warmup(websocket)
handler = getattr(websocket.app.state, "openai_serving_duplex", None)
if handler is None:
await websocket.accept()
await websocket.send_json({"type": "error", "error": "Duplex API is not available", "code": "unsupported"})
await websocket.close()
return
await handler.handle_realtime_session(websocket)
@router.websocket("/v1/realtime/robot/openpi")
async def realtime_robot_openpi(websocket: WebSocket):
"""WebSocket endpoint for robot policy inference via OpenPI messages."""
@@ -1532,18 +1699,6 @@ async def realtime_robot_openpi(websocket: WebSocket):
await connection.handle_connection()
@router.websocket("/v1/duplex")
async def duplex_websocket(websocket: WebSocket):
"""WebSocket endpoint for vLLM-Omni duplex session control."""
handler = getattr(websocket.app.state, "openai_serving_duplex", None)
if handler is None:
await websocket.accept()
await websocket.send_json({"type": "error", "error": "Duplex API is not available", "code": "unsupported"})
await websocket.close()
return
await handler.handle_session(websocket)
# RL Rollout serving (RFC #3747, P0)
@@ -2518,11 +2673,11 @@ async def retrieve_video(video_id: str) -> VideoResponse | JSONResponse:
@router.delete("/v1/videos/{video_id}")
async def delete_video(video_id: str) -> VideoDeleteResponse:
async def delete_video(video_id: str, raw_request: Request) -> VideoDeleteResponse:
"""Delete a stored video job and any generated output.
If the job is still queued or running, this endpoint first attempts to
cancel the in-flight generation task before removing the stored metadata.
In-flight jobs get a bounded engine abort, then frontend cancel. The job
is re-read afterwards so a completed save is not orphaned.
Args:
video_id: Identifier of the video job to delete.
@@ -2539,19 +2694,37 @@ async def delete_video(video_id: str) -> VideoDeleteResponse:
raise HTTPException(status_code=404, detail="Video not found")
if job.status in (VideoGenerationStatus.QUEUED, VideoGenerationStatus.IN_PROGRESS):
handler = raw_request.app.state.openai_serving_video
try:
await asyncio.wait_for(handler.abort_request(video_id), timeout=VIDEO_ABORT_TIMEOUT_S)
except asyncio.TimeoutError:
logger.warning(
"Timed out aborting video request %s after %.1fs; "
"engine abort is best-effort until the current batch drains",
video_id,
VIDEO_ABORT_TIMEOUT_S,
)
except Exception:
logger.exception("Failed to abort in-flight video request %s", video_id)
task = await VIDEO_TASKS.get(video_id)
if task is not None:
task.cancel()
try:
await asyncio.wait_for(task, timeout=2.0)
# Cancel cleanup may spend a full abort budget; +2s covers scheduling slack.
await asyncio.wait_for(task, timeout=VIDEO_ABORT_TIMEOUT_S + 2.0)
except asyncio.TimeoutError:
raise HTTPException(status_code=409, detail="Cancellation in progress. Please try again later.")
except asyncio.CancelledError:
pass
job = await VIDEO_STORE.get(video_id)
if job is None:
return VideoDeleteResponse(id=video_id, deleted=True)
if job.status in (VideoGenerationStatus.QUEUED, VideoGenerationStatus.IN_PROGRESS):
await VIDEO_STORE.pop(video_id)
return VideoDeleteResponse(id=job.id, deleted=True)
elif job.status is VideoGenerationStatus.FAILED:
if job.status is VideoGenerationStatus.FAILED:
if job.file_name is not None:
try:
await STORAGE_MANAGER.delete(video_id)
@@ -21,7 +21,6 @@ LONGEVITY:
See ``openai/README.md`` (utils vs helpers, no overlap).
"""
import math
from io import BytesIO
import numpy as np
@@ -36,6 +35,9 @@ from vllm_omni.entrypoints.openai.protocol.audio import (
CreateAudio,
)
# Re-exported: serving_speech and the audio tests import it from here.
from vllm_omni.utils.audio_resample import StreamingAudioResampler # noqa: F401
try:
import soundfile
except ImportError:
@@ -44,155 +46,6 @@ except ImportError:
logger = init_logger(__name__)
class StreamingAudioResampler:
"""Stateful polyphase resampler for streaming mono float audio.
Retains filter state so output is invariant to input chunk boundaries.
"""
_half_filter_width = 10
_kaiser_beta = 5.0
_max_polyphase_factor = 2_048
def __init__(self, source_rate: int, target_rate: int):
if source_rate <= 0 or target_rate <= 0:
raise ValueError("Audio sample rates must be positive")
self.source_rate = source_rate
self.target_rate = target_rate
rate_gcd = math.gcd(source_rate, target_rate)
self._up = target_rate // rate_gcd
self._down = source_rate // rate_gcd
if max(self._up, self._down) > self._max_polyphase_factor:
raise ValueError("source and target sample rates have an unsupported resampling ratio")
self._half_len, self._phase_kernels = self._design_polyphase_filter()
self._history_samples = self._phase_kernels.shape[1] - 1
self.reset()
def _design_polyphase_filter(self) -> tuple[int, np.ndarray]:
if self._up == self._down:
return 0, np.ones((1, 1), dtype=np.float32)
max_rate = max(self._up, self._down)
half_len = self._half_filter_width * max_rate
offsets = np.arange(-half_len, half_len + 1, dtype=np.float64)
cutoff = 1.0 / max_rate
taps = cutoff * np.sinc(cutoff * offsets)
taps *= np.kaiser(taps.size, self._kaiser_beta)
taps /= np.sum(taps)
taps *= self._up
taps = np.ascontiguousarray(taps, dtype=np.float32)
phases = [taps[phase :: self._up] for phase in range(self._up)]
phase_width = max(phase.size for phase in phases)
kernels = np.zeros((self._up, phase_width), dtype=np.float32)
for phase_index, phase in enumerate(phases):
kernels[phase_index, -phase.size :] = phase[::-1]
return half_len, kernels
@property
def scratch_bytes(self) -> int:
pending_samples = self._ceil_div(self._input_samples * self._up, self._down) - self._output_samples
return max(0, pending_samples) * np.dtype(np.float32).itemsize
@staticmethod
def _ceil_div(numerator: int, denominator: int) -> int:
return -(-numerator // denominator)
def _render_outputs(
self,
combined: np.ndarray,
*,
first_output: int,
output_count: int,
input_start: int,
) -> np.ndarray:
if output_count <= 0:
return np.empty(0, dtype=np.float32)
output_indexes = np.arange(first_output, first_output + output_count, dtype=np.int64)
filter_indexes = output_indexes * self._down + self._half_len
source_indexes = filter_indexes // self._up
phases = filter_indexes % self._up
windows = np.lib.stride_tricks.sliding_window_view(
combined,
self._phase_kernels.shape[1],
)
selected_windows = windows[source_indexes - input_start]
return np.sum(
selected_windows * self._phase_kernels[phases],
axis=1,
dtype=np.float32,
)
def _push(self, chunk: np.ndarray) -> np.ndarray:
if chunk.size == 0:
return np.empty(0, dtype=np.float32)
if self._flushed:
raise RuntimeError("cannot process audio after the resampler has been finalized; call reset first")
combined = np.concatenate((self._history, chunk))
next_input_samples = self._input_samples + chunk.size
stable_output_samples = max(
0,
self._ceil_div(next_input_samples * self._up - self._half_len, self._down),
)
output = self._render_outputs(
combined,
first_output=self._output_samples,
output_count=stable_output_samples - self._output_samples,
input_start=self._input_samples,
)
if self._history_samples:
self._history = combined[-self._history_samples :].copy()
self._input_samples = next_input_samples
self._output_samples = stable_output_samples
return output
def _flush(self) -> np.ndarray:
if self._flushed:
return np.empty(0, dtype=np.float32)
total_output_samples = self._ceil_div(self._input_samples * self._up, self._down)
output_count = total_output_samples - self._output_samples
if output_count:
last_output = total_output_samples - 1
last_source_index = (last_output * self._down + self._half_len) // self._up
right_padding = max(0, last_source_index - self._input_samples + 1)
combined = np.concatenate((self._history, np.zeros(right_padding, dtype=np.float32)))
output = self._render_outputs(
combined,
first_output=self._output_samples,
output_count=output_count,
input_start=self._input_samples,
)
else:
output = np.empty(0, dtype=np.float32)
self._output_samples = total_output_samples
self._flushed = True
return output
def process(self, audio: np.ndarray, *, final: bool = False) -> np.ndarray:
chunk = np.asarray(audio, dtype=np.float32)
if chunk.ndim != 1:
raise ValueError(f"Streaming audio resampling only supports mono audio, got shape {chunk.shape}")
chunk = np.ascontiguousarray(chunk, dtype=np.float32)
output = self._push(chunk)
if not final:
return output
tail = self._flush()
if not output.size:
return tail
if not tail.size:
return output
return np.concatenate((output, tail))
def reset(self) -> None:
self._history = np.zeros(self._history_samples, dtype=np.float32)
self._input_samples = 0
self._output_samples = 0
self._flushed = False
class AudioMixin:
"""Mixin class to add audio-related utilities."""
+34 -15
View File
@@ -53,6 +53,7 @@ from vllm_omni.entrypoints.openai.speech_usage import (
qwen3_tts_input_token_details,
)
from vllm_omni.entrypoints.openai.tts_adapters import (
OutputPolicy,
SpeechServingContext,
TTSGenerationError,
all_tts_stage_keys,
@@ -396,6 +397,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
self._max_instructions_length = self._compute_max_instructions_length()
self._tts_tokenizer = None
# Per-request output policy from the adapter's PreparedRequest. Keyed
# by request_id so concurrent speech requests cannot overwrite each
# other. Stored only for non-streaming requests and consumed (popped)
# by the non-streaming accumulator in `_generate_audio_bytes`.
self._speech_output_policies: dict[str, OutputPolicy] = {}
# Batch configuration
self._batch_max_items: int = getattr(self.engine_client, "tts_batch_max_items", 32)
@@ -1872,6 +1878,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
tts_params = prepared.tts_params
model_type = prepared.model_type
qwen3_ref_audio_warmup_artifact_key = prepared.warmup_artifact_key
output_policy = prepared.output_policy
else:
# Qwen omni models (Qwen3-Omni, Qwen2.5-Omni) use a "talker"
# stage whose preprocess requires chat-templated tokens. The
@@ -1893,6 +1900,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
)
tts_params = {}
prompt = {"prompt": request.input}
output_policy = OutputPolicy()
if model_type is None:
if self._is_tts:
@@ -1962,6 +1970,13 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
qwen3_ref_audio_warmup_artifact_key,
x_vector_only=self._tts_x_vector_only(tts_params),
)
# Only the non-streaming path consumes output policies (in
# `_generate_audio_bytes`); streaming never reads them. Store late —
# after every fallible step above — and skip streaming requests
# entirely, so no caller has to discard entries (request ids are
# unique per request, so a stranded entry would never be reclaimed).
if not request.is_streaming():
self._speech_output_policies[request_id] = output_policy
return request_id, generator, tts_params
async def _generate_pcm_chunks(
@@ -2041,13 +2056,17 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
artifact_ready = False
try:
# MOSS-TTS-Nano emits delta chunks per yield (single-stage,
# async_chunk=false). The engine surfaces each yield as its own
# RequestOutput, so we need to accumulate across the async-for loop —
# final_output alone only carries the last (often empty) sentinel.
is_moss = self._tts_model_type == "moss_tts_nano"
moss_chunks: list[Any] = []
moss_sample_rate: int | None = None
# Sparse-audio models (MOSS-TTS-Nano, Gepard) emit delta chunks per
# yield with async_chunk=false. The engine surfaces each yield as its
# own RequestOutput, so we accumulate across the async-for loop when
# the adapter asks for it — final_output alone may only carry the
# last (often empty) sentinel. Prefer the engine's own concatenated
# waveform when FINAL_ONLY already produced one.
accumulate_nonstreaming = self._speech_output_policies.pop(
request_id, OutputPolicy()
).accumulate_nonstreaming
delta_chunks: list[Any] = []
delta_sample_rate: int | None = None
final_output: OmniRequestOutput | None = None
# Non-streaming is FINAL_ONLY, so the stage-0 output carries the full
@@ -2067,7 +2086,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
_, audio_key = self._extract_audio_output(res)
if audio_key is not None:
audio_res = res
if not is_moss:
if not accumulate_nonstreaming:
continue
try:
step_audio, step_key = self._extract_audio_output(res)
@@ -2080,11 +2099,11 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
candidates = chunk if isinstance(chunk, list) else [chunk]
for cand in candidates:
if hasattr(cand, "numel") and cand.numel() > 0:
moss_chunks.append(cand)
delta_chunks.append(cand)
sr_step = step_audio.get("sr")
if sr_step is not None:
sr_val_step = sr_step[-1] if isinstance(sr_step, list) and sr_step else sr_step
moss_sample_rate = int(sr_val_step.item()) if hasattr(sr_val_step, "item") else int(sr_val_step)
delta_sample_rate = int(sr_val_step.item()) if hasattr(sr_val_step, "item") else int(sr_val_step)
if final_output is None:
raise ValueError("No output generated from the model.")
@@ -2117,7 +2136,7 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
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 is_moss:
if accumulate_nonstreaming:
# Prefer the engine's own consolidated audio when present. After the
# vllm 0.20 rebase non-stream requests resolve to FINAL_ONLY, so
# final_output already carries the full concatenated waveform; the
@@ -2133,12 +2152,12 @@ class OmniOpenAIServingSpeech(OpenAIServing, AudioMixin):
if final_audio is not None:
audio_tensor = final_audio
elif moss_chunks:
audio_tensor = torch.cat(moss_chunks, dim=-1)
elif delta_chunks:
audio_tensor = torch.cat(delta_chunks, dim=-1)
else:
audio_tensor = np.zeros((0,), dtype=np.float32)
if moss_sample_rate is not None:
sample_rate = moss_sample_rate
if delta_sample_rate is not None:
sample_rate = delta_sample_rate
elif isinstance(audio_tensor, list):
async_chunk = bool(getattr(self.engine_client.model_config, "async_chunk", False))
if async_chunk:
+24 -3
View File
@@ -6,7 +6,7 @@ from __future__ import annotations
import copy
import math
import time
from collections.abc import Mapping
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass
from functools import cached_property
from http import HTTPStatus
@@ -19,9 +19,10 @@ from PIL import Image
from vllm.engine.protocol import EngineClient
from vllm.logger import init_logger
from vllm_omni.diffusion.data import is_diffusion_request_started_output
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
from vllm_omni.diffusion.utils.media_utils import count_mp4_frames, normalize_preencode_batch_frames
from vllm_omni.entrypoints.async_omni import AsyncOmni
from vllm_omni.entrypoints.async_omni import ABORT_TIMEOUT_S, AsyncOmni
from vllm_omni.entrypoints.openai.protocol.videos import (
VideoAction,
VideoData,
@@ -256,6 +257,9 @@ class OmniOpenAIServingVideo:
def shutdown(self) -> None:
self._video_frame_converter.shutdown()
async def abort_request(self, request_id: str) -> None:
await self._engine_client.abort(request_id, timeout=ABORT_TIMEOUT_S)
async def _run_and_extract(
self,
request: VideoGenerationRequest,
@@ -264,6 +268,7 @@ class OmniOpenAIServingVideo:
reference_image: ReferenceImage | None = None,
reference_video: ReferenceVideo | None = None,
reference_audio: ReferenceAudio | None = None,
on_started: Callable[[], Awaitable[None]] | None = None,
) -> VideoGenerationArtifacts:
"""Run the generation pipeline and extract video/audio/profiler outputs."""
prompt: OmniTextPrompt = OmniTextPrompt(prompt=request.prompt, modalities=["video"])
@@ -444,7 +449,12 @@ class OmniOpenAIServingVideo:
gen_params.seed,
)
result = await self._run_generation(prompt, gen_params, reference_id)
result = await self._run_generation(
prompt,
gen_params,
reference_id,
on_started=on_started,
)
multimodal_output = self._extract_multimodal_output(result)
metadata = multimodal_output.get("metadata") if isinstance(multimodal_output, dict) else {}
common_metadata = metadata.get("common") if isinstance(metadata, dict) else {}
@@ -528,6 +538,7 @@ class OmniOpenAIServingVideo:
reference_image: ReferenceImage | None = None,
reference_video: ReferenceVideo | None = None,
reference_audio: ReferenceAudio | None = None,
on_started: Callable[[], Awaitable[None]] | None = None,
) -> tuple[bytes, dict[str, float], float, VideoAction | None, dict[str, object]]:
"""Generate a video and return raw MP4 bytes, bypassing base64 encoding."""
artifacts = await self._run_and_extract(
@@ -536,6 +547,7 @@ class OmniOpenAIServingVideo:
reference_image=reference_image,
reference_video=reference_video,
reference_audio=reference_audio,
on_started=on_started,
)
if len(artifacts.videos) > 1:
logger.warning(
@@ -641,6 +653,8 @@ class OmniOpenAIServingVideo:
prompt: OmniTextPrompt,
gen_params: OmniDiffusionSamplingParams,
request_id: str,
*,
on_started: Callable[[], Awaitable[None]] | None = None,
) -> object:
stage_configs = self._stage_configs or getattr(self._engine_client, "stage_configs", None)
@@ -660,6 +674,7 @@ class OmniOpenAIServingVideo:
# Common generation logic for both paths
engine_client = cast(AsyncOmni, self._engine_client)
gen_params.emit_request_lifecycle = on_started is not None
sampling_params_list = build_stage_sampling_params_list(
list(stage_configs),
get_default_sampling_params_list(engine_client),
@@ -668,11 +683,17 @@ class OmniOpenAIServingVideo:
)
result = None
started_notified = False
async for output in engine_client.generate(
prompt=prompt,
request_id=request_id,
sampling_params_list=sampling_params_list,
):
if is_diffusion_request_started_output(output):
if on_started is not None and not started_notified:
await on_started()
started_notified = True
continue
result = output
if result is None:
@@ -30,7 +30,6 @@ from collections.abc import Mapping
from typing import Any
from vllm_omni.entrypoints.openai.video_stream_base import (
_BAD_FRAME,
_DEFAULT_CONFIG_TIMEOUT,
_DEFAULT_IDLE_TIMEOUT,
PrewarmedFrame,
@@ -62,22 +61,19 @@ class QwenOmniStreamingVideoHandler(OmniStreamingVideoHandlerBase):
message_history: list[dict[str, Any]],
query_text: str,
prewarmed_frames: Mapping[str, PrewarmedFrame],
*,
frame_indices: list[int] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
n_buf = len(frame_buffer)
if n_buf <= config.num_frames:
frames = list(frame_buffer)
else:
stride = max(1, n_buf // config.num_frames)
idx = [i * stride for i in range(config.num_frames - 1)] + [n_buf - 1]
frames = [frame_buffer[i] for i in idx]
prewarmed = prewarmed_frames or {}
if frame_indices is None:
frame_indices = self._sample_frame_indices(frame_buffer, config.num_frames, prewarmed)
user_content: list[dict] = []
for frame_b64 in frames:
for index in frame_indices:
frame_b64 = frame_buffer[index]
cached = prewarmed.get(frame_b64)
if cached is _BAD_FRAME:
continue
if cached is not None:
# The shared selector excludes failed decodes before this point.
assert isinstance(cached, tuple)
pil, pil_uuid = cached
user_content.append(
{
@@ -110,6 +110,7 @@ from vllm_omni.entrypoints.openai.tts_adapters import ( # noqa: E402,F401
covo_audio,
dots_tts,
fish_speech,
gepard,
glm_tts,
higgs_audio_v2,
higgs_audio_v3,
@@ -0,0 +1,168 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Gepard-1.0 serving adapter for ``/v1/audio/speech``.
Zero-shot only: the trained ``null_prefix`` is the default voice. Prompt IDs
are assembled with the same layout helper the offline path uses. Frame budget
rides ``SamplingParams.max_tokens`` (one token = one 1024-sample frame).
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from vllm.utils.async_utils import make_async
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
from vllm_omni.entrypoints.openai.tts_adapters.base import (
ARTTSAdapter,
OutputPolicy,
PreparedRequest,
apply_max_new_tokens,
conditioning_cache_salt,
)
if TYPE_CHECKING:
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
from vllm_omni.model_executor.models.gepard.configuration_gepard import GepardConfig
_DEFAULT_VOICE = "default"
# Declared schema fields Gepard does not consume. Rejecting them here is
# load-bearing: the pydantic model silently drops undeclared keys, so a
# declared-but-ignored field would otherwise succeed and mislead.
_UNSUPPORTED_OPTIONAL_FIELDS: tuple[tuple[str, str], ...] = (
("ref_audio", "ref_audio"),
("ref_text", "ref_text"),
("ref_audio_2", "ref_audio_2"),
("speaker_embedding", "speaker_embedding"),
("x_vector_only_mode", "x_vector_only_mode"),
("task_type", "task_type"),
("non_streaming_mode", "non_streaming_mode"),
("instructions", "instructions"),
("language", "language"),
("ambient_sound", "ambient_sound"),
("duration_seconds", "duration_seconds"),
("initial_codec_chunk_frames", "initial_codec_chunk_frames"),
)
@register_tts_adapter
class GepardAdapter(ARTTSAdapter):
name = "gepard"
stage_keys = frozenset({"gepard"})
model_archs = frozenset({"GepardTalkerForConditionalGeneration"})
def __init__(self, ctx) -> None:
super().__init__(ctx)
self._tokenizer: Any = None
self._gepard_config: GepardConfig | None = None
self._build_prompt_async = make_async(self._build_prompt, executor=getattr(ctx.server, "_tts_executor", None))
def _load_supported_speakers(self) -> set[str]:
return {_DEFAULT_VOICE}
def validate(self, request: OpenAICreateSpeechRequest) -> str | None:
if not request.input or not request.input.strip():
return "Input text cannot be empty"
if request.voice is not None:
voice = request.voice.lower()
if voice != _DEFAULT_VOICE:
return (
f"Invalid voice '{request.voice}'. Supported: {_DEFAULT_VOICE}. "
"Voice cloning from reference audio is not available yet."
)
if request.speed is not None and request.speed != 1.0:
return "Gepard does not support 'speed' adjustments; audio is rendered at the native 22.05 kHz rate"
if request.extra_params:
keys = ", ".join(sorted(request.extra_params))
return (
f"Gepard does not accept extra_params (got: {keys}). "
"Sampling is fixed in-model; temperature/top_p/top_k cannot be overridden."
)
if request.word_timestamps:
return "Gepard does not support 'word_timestamps'; there is no forced-aligner stage in this pipeline"
fmt = (request.response_format or "").lower()
if fmt == "opus":
return (
"Gepard does not support 'response_format'='opus'; "
"native 22.05 kHz is not an Opus sample rate (8000, 12000, 16000, 24000, 48000)"
)
if request.max_new_tokens is not None:
if request.max_new_tokens < self.max_new_tokens_min or request.max_new_tokens > self.max_new_tokens_max:
return f"max_new_tokens must be between {self.max_new_tokens_min} and {self.max_new_tokens_max} frames"
for attr, field in _UNSUPPORTED_OPTIONAL_FIELDS:
if getattr(request, attr, None) is not None:
return f"Gepard does not support '{field}'"
return None
def apply_sampling_overrides(
self,
sampling_params_list: list,
request: OpenAICreateSpeechRequest,
prompt: dict | None = None,
request_id: str | None = None,
) -> list:
return apply_max_new_tokens(sampling_params_list, request)
async def build(
self,
request: OpenAICreateSpeechRequest,
sampling_params_list: list,
has_inline_ref_audio: bool,
) -> PreparedRequest:
tts_params: dict = {}
prompt = await self._build_prompt_async(request.input)
prompt["cache_salt"] = conditioning_cache_salt(request, tts_params)
return PreparedRequest(
prompt=prompt,
tts_params=tts_params,
model_type=self.name,
output_policy=OutputPolicy(accumulate_nonstreaming=True),
)
def _build_prompt(self, text: str) -> dict[str, Any]:
from vllm_omni.model_executor.models.gepard.prompt import build_gepard_prompt_ids
prompt_token_ids = build_gepard_prompt_ids(self._tokenize(text), config=self._config())
return {
"prompt_token_ids": prompt_token_ids,
"additional_information": {"text": [text]},
}
def _model_config(self) -> Any:
engine = self.ctx.engine_client
assert engine is not None
return engine.model_config
def _config(self) -> GepardConfig:
if self._gepard_config is None:
from vllm_omni.model_executor.models.gepard.configuration_gepard import GepardConfig
model_config = self._model_config()
self._gepard_config = GepardConfig.from_checkpoint(
model_config.model, revision=getattr(model_config, "revision", None)
)
return self._gepard_config
def _tokenize(self, text: str) -> list[int]:
tokenizer = self._tokenizer
if tokenizer is None:
from transformers import AutoTokenizer
model_config = self._model_config()
tokenizer = AutoTokenizer.from_pretrained(
model_config.model,
revision=getattr(model_config, "revision", None),
trust_remote_code=True,
)
self._tokenizer = tokenizer
return tokenizer(text, add_special_tokens=False)["input_ids"]
@@ -13,6 +13,7 @@ from vllm.inputs import tokens_input
from vllm_omni.entrypoints.openai.tts_adapters import register_tts_adapter
from vllm_omni.entrypoints.openai.tts_adapters.base import (
ARTTSAdapter,
OutputPolicy,
PreparedRequest,
apply_max_new_tokens,
conditioning_cache_salt,
@@ -23,6 +24,8 @@ if TYPE_CHECKING:
class _MossTTSAdapterBase(ARTTSAdapter):
accumulate_nonstreaming: bool = False
def __init__(self, ctx) -> None:
super().__init__(ctx)
self._moss_variant = None if self.name == "moss_tts_nano" else self._detect_moss_variant()
@@ -369,7 +372,12 @@ class _MossTTSAdapterBase(ARTTSAdapter):
prompt = tokens_input(prompt_token_ids=[1])
prompt["additional_information"] = tts_params
prompt["cache_salt"] = conditioning_cache_salt(request, tts_params)
return PreparedRequest(prompt=prompt, tts_params=tts_params, model_type=self.name)
return PreparedRequest(
prompt=prompt,
tts_params=tts_params,
model_type=self.name,
output_policy=OutputPolicy(accumulate_nonstreaming=self.accumulate_nonstreaming),
)
def apply_sampling_overrides(
self,
@@ -385,6 +393,7 @@ class _MossTTSAdapterBase(ARTTSAdapter):
class MossTTSNanoAdapter(_MossTTSAdapterBase):
stage_keys = frozenset({"moss_tts_nano"})
name = "moss_tts_nano"
accumulate_nonstreaming = True
@register_tts_adapter
@@ -22,6 +22,7 @@ class VoxtralTTSAdapter(ARTTSAdapter):
def __init__(self, ctx) -> None:
super().__init__(ctx)
self._build_prompt_async = make_async(self._build_prompt, executor=getattr(ctx.server, "_tts_executor", None))
self._encoder_loaded = None
def _build_prompt(self, request: "OpenAICreateSpeechRequest") -> dict[str, Any]:
"""Build a Voxtral prompt for either a preset voice or inline reference audio."""
@@ -31,13 +32,24 @@ class VoxtralTTSAdapter(ARTTSAdapter):
ref_audio = request.ref_audio
if not request.voice and not ref_audio:
raise ValueError("Voxtral requires either a voice name or ref_audio.")
if isinstance(ref_audio, str) and ref_audio.startswith("data:"):
_, _, ref_audio = ref_audio.partition(",")
if ref_audio is not None and not self._encoder_loaded:
validation_error = (
"Voice cloning with 'ref_audio' requires the full Voxtral checkpoint "
"with encoder weights. The open-source variant only supports "
"preset voices via the 'voice' parameter."
)
raise ValueError(validation_error)
server = self.ctx.server
if server._tts_tokenizer is None:
from vllm.tokenizers import cached_tokenizer_from_config
server._tts_tokenizer = cached_tokenizer_from_config(self.ctx.engine_client.model_config).instruct
if isinstance(ref_audio, str) and ref_audio.startswith("data:"):
_, _, ref_audio = ref_audio.partition(",")
if request.voice is not None:
tokenized = server._tts_tokenizer.encode_speech_request(
SpeechRequest(input=request.input, voice=request.voice)
@@ -45,6 +57,7 @@ class VoxtralTTSAdapter(ARTTSAdapter):
prompt = tokens_input(prompt_token_ids=tokenized.tokens)
prompt["additional_information"] = {"voice": [request.voice]}
return prompt
tokenized = server._tts_tokenizer.encode_speech_request(SpeechRequest(input=request.input, ref_audio=ref_audio))
audio = tokenized.audios[0]
return {
@@ -84,6 +97,12 @@ class VoxtralTTSAdapter(ARTTSAdapter):
async def build(
self, request: "OpenAICreateSpeechRequest", sampling_params_list: list, has_inline_ref_audio: bool
) -> PreparedRequest:
# Cache encoder_loaded property to avoid RPC call on every request with ref_audio
if self._encoder_loaded is None:
loaded = await self.ctx.server.engine_client.collective_rpc("encoder_loaded")
# Flatten results before checking if encoder loaded property is set
self._encoder_loaded = any(sum(loaded, []))
prompt = await self._build_prompt_async(request)
return PreparedRequest(prompt=prompt, tts_params={}, model_type="voxtral_tts")
@@ -330,9 +330,12 @@ async def _run_video_generation_job(
_cleanup_video_references(reference_video, reference_audio, control_path)
return
await VIDEO_STORE.update_fields(video_id, {"status": VideoGenerationStatus.IN_PROGRESS})
started_at = time.perf_counter()
try:
async def _mark_started() -> None:
await VIDEO_STORE.update_fields(video_id, {"status": VideoGenerationStatus.IN_PROGRESS})
video_bytes, stage_durations, peak_memory_mb, action, video_metadata = _unpack_video_generation_result(
await handler.generate_video_bytes(
request,
@@ -340,6 +343,7 @@ async def _run_video_generation_job(
reference_image=reference_image,
reference_video=reference_video,
reference_audio=reference_audio,
on_started=_mark_started,
)
)
@@ -93,8 +93,10 @@ class VideoStreamPipelineHooks(Protocol):
message_history: list[dict[str, Any]],
query_text: str,
prewarmed_frames: Mapping[str, PrewarmedFrame],
*,
frame_indices: list[int] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""Build OpenAI-style messages and the current user message."""
"""Build messages using the supplied frame selection, or sample if omitted."""
...
def on_turn_complete(
@@ -179,6 +181,8 @@ class OmniStreamingVideoHandler:
message_history: list[dict[str, Any]],
query_text: str,
prewarmed_frames: Mapping[str, PrewarmedFrame],
*,
frame_indices: list[int] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
raise NotImplementedError
@@ -639,6 +643,9 @@ class OmniStreamingVideoHandler:
ChatCompletionRequest,
)
# Select once from this turn's snapshot so prompt images and the
# consumed event refer to exactly the same frames, including decode failures.
frame_indices = self._sample_frame_indices(frame_buffer, config.num_frames, prewarmed_frames)
messages, user_message = self.build_engine_prompt(
config,
frame_buffer,
@@ -646,6 +653,7 @@ class OmniStreamingVideoHandler:
message_history,
query_text,
prewarmed_frames,
frame_indices=frame_indices,
)
request_kwargs: dict[str, Any] = {
@@ -678,7 +686,7 @@ class OmniStreamingVideoHandler:
await self._send_error(websocket, f"Preprocess failed: {e}")
return
decoded_ready_ts_ms = _time.monotonic() * 1000
selected_metadata = self._sample_frame_metadata(frame_metadata or [], config.num_frames)
selected_metadata = [frame_metadata[index] for index in frame_indices] if frame_metadata else []
model_selected_ts_ms = _time.monotonic() * 1000
await websocket.send_json({"type": "response.start"})
@@ -1071,15 +1079,19 @@ class OmniStreamingVideoHandler:
pass
@staticmethod
def _sample_frame_metadata(
frame_metadata: list[dict[str, Any]],
def _sample_frame_indices(
frame_buffer: list[str],
num_frames: int,
) -> list[dict[str, Any]]:
if len(frame_metadata) <= num_frames:
return list(frame_metadata)
stride = max(1, len(frame_metadata) // num_frames)
indices = [index * stride for index in range(num_frames - 1)] + [len(frame_metadata) - 1]
return [frame_metadata[index] for index in indices]
prewarmed_frames: Mapping[str, PrewarmedFrame],
) -> list[int]:
"""Stride-sample with the last frame, then drop known bad frames without refilling."""
n_buf = len(frame_buffer)
if n_buf <= num_frames:
indices = list(range(n_buf))
else:
stride = max(1, n_buf // num_frames)
indices = [index * stride for index in range(num_frames - 1)] + [n_buf - 1]
return [index for index in indices if prewarmed_frames.get(frame_buffer[index]) is not _BAD_FRAME]
@staticmethod
async def _send_frame_ack(