Merge main and preserve dispatch backlog across monitor windows
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
commit
ea7de7e3de
769 files changed
+73802
-22805
No files matched your search
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Engine components for vLLM-Omni.
|
||||
"""
|
||||
@@ -134,10 +137,19 @@ class OmniEngineCoreOutput(EngineCoreOutput):
|
||||
# pooling_output is inherited from EngineCoreOutput as torch.Tensor | None
|
||||
# and retains its original vLLM semantics for pooling/embedding tasks.
|
||||
multimodal_output: dict[str, torch.Tensor] | None = None
|
||||
# Bytes-serialized carrier for a dict-shaped pooling_output (MR V2 cross-stage
|
||||
# hidden/codec handoff). vLLM strictly decodes ``pooling_output`` as a
|
||||
# ``torch.Tensor``, so a per-request dict payload cannot ride that field. The
|
||||
# producer (OmniARScheduler) sets ``pooling_output=None`` and serializes the
|
||||
# dict here; the consumer (StagePool._poll_stage_raw) rehydrates it back into
|
||||
# ``pooling_output`` after decode. Tensor pooling outputs are unaffected.
|
||||
pooling_output_payload: AdditionalInformationPayload | None = None
|
||||
# Finished flag for streaming input segment
|
||||
is_segment_finished: bool | None = False
|
||||
# Streaming update prompt length
|
||||
new_prompt_len_snapshot: int | None = None
|
||||
# Authoritative segment count when the native plane suppresses token IPC.
|
||||
num_generation_tokens: int | None = None
|
||||
|
||||
|
||||
class OmniEngineCoreOutputs(EngineCoreOutputs):
|
||||
|
||||
@@ -181,15 +181,16 @@ class OmniEngineArgs(EngineArgs):
|
||||
(e.g. ["text", "audio"]). If None, all modalities supported by
|
||||
the model are used.
|
||||
log_stats: Whether to log engine statistics. Defaults to False.
|
||||
custom_pipeline_args: Dictionary of arguments for custom pipeline
|
||||
initialization (e.g., ``{"pipeline_class": "my.Module"}``).
|
||||
Passed through to the diffusion stage engine.
|
||||
custom_pipeline_args: Dictionary of arguments passed through to the
|
||||
diffusion pipeline. When it contains ``pipeline_class``, it triggers
|
||||
custom pipeline initialization.
|
||||
"""
|
||||
|
||||
stage_id: int = 0
|
||||
model_stage: str = "thinker"
|
||||
model_arch: str | None = None
|
||||
engine_output_type: str | None = None
|
||||
final_output: bool = False
|
||||
hf_config_name: str | None = None
|
||||
custom_process_next_stage_input_func: str | None = None
|
||||
requires_full_payload_input: bool = False
|
||||
@@ -199,6 +200,8 @@ class OmniEngineArgs(EngineArgs):
|
||||
async_chunk: bool = False
|
||||
session_mode: str = "turn"
|
||||
retains_state_across_chunks: bool = False
|
||||
use_v2_model_runner: bool = False
|
||||
supports_native_mrv2_data_plane: bool = False
|
||||
# WS-A: Stage-1 active stream slots. 0 = legacy preempt-everything.
|
||||
# Must be declared here so engine_args dict propagation does not silently
|
||||
# drop the value when constructing OmniEngineArgs from kwargs.
|
||||
@@ -220,6 +223,12 @@ class OmniEngineArgs(EngineArgs):
|
||||
# Diffusion request-mode batch admission (forwarded to OmniDiffusionConfig).
|
||||
request_batch_max_wait_ms: float = 0.0
|
||||
fa_deterministic: bool = False
|
||||
# Tensor-parallel degree for the diffusion text encoder (forwarded to
|
||||
# DiffusionParallelConfig via the generic diffusion fallback). Declared
|
||||
# here so ``from_cli_args`` field filtering keeps ``--text-encoder-tp-size``
|
||||
# for library callers (#7564); registered pipelines may consume it through
|
||||
# their own stage_cli_aliases or deploy YAML.
|
||||
text_encoder_tp_size: int | None = None
|
||||
|
||||
@classmethod
|
||||
def _add_omni_specific_args(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
|
||||
@@ -423,6 +432,8 @@ class OmniEngineArgs(EngineArgs):
|
||||
async_chunk=self.async_chunk,
|
||||
session_mode=self.session_mode,
|
||||
retains_state_across_chunks=self.retains_state_across_chunks,
|
||||
use_v2_model_runner=self.use_v2_model_runner,
|
||||
supports_native_mrv2_data_plane=self.supports_native_mrv2_data_plane,
|
||||
active_stream_window=self.active_stream_window,
|
||||
duplex_max_sessions=self.duplex_max_sessions,
|
||||
model_stage=self.model_stage,
|
||||
@@ -430,6 +441,7 @@ class OmniEngineArgs(EngineArgs):
|
||||
worker_type=self.worker_type,
|
||||
pooling_output_decoder=self.pooling_output_decoder,
|
||||
engine_output_type=self.engine_output_type,
|
||||
final_output=self.final_output,
|
||||
hf_config_name=self.hf_config_name,
|
||||
custom_process_next_stage_input_func=self.custom_process_next_stage_input_func,
|
||||
requires_full_payload_input=self.requires_full_payload_input,
|
||||
|
||||
@@ -1,218 +1,44 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Compatibility re-export: the Realtime audio codec moved out of the duplex engine.
|
||||
|
||||
Decoding PCM / G.711 / WAV, resampling and re-encoding are wire-format work with
|
||||
no duplex session in them, so the implementation now lives in
|
||||
``vllm_omni.protocol.realtime.audio`` where a non-duplex Realtime surface can
|
||||
use it too. Duplex code reaches it through ``vllm_omni.protocol.duplex``, the
|
||||
one door the engine uses --- which is also where a duplex-specific conversion
|
||||
would be introduced. Import from there in new code.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import io
|
||||
import math
|
||||
import wave
|
||||
from vllm_omni.protocol.duplex import (
|
||||
MAX_INPUT_SAMPLE_RATE_HZ,
|
||||
MIN_INPUT_SAMPLE_RATE_HZ,
|
||||
convert_input_audio_with_rate,
|
||||
convert_output_audio,
|
||||
decode_g711_alaw,
|
||||
decode_g711_ulaw,
|
||||
encode_float32_mono_wav_base64,
|
||||
encode_g711_alaw,
|
||||
encode_g711_ulaw,
|
||||
resample_pcm16_mono,
|
||||
validate_input_sample_rate_hz,
|
||||
wav_payload_to_pcm16,
|
||||
)
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.utils.audio_resample import StreamingAudioResampler
|
||||
|
||||
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
|
||||
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
|
||||
__all__ = [
|
||||
"MAX_INPUT_SAMPLE_RATE_HZ",
|
||||
"MIN_INPUT_SAMPLE_RATE_HZ",
|
||||
"convert_input_audio_with_rate",
|
||||
"convert_output_audio",
|
||||
"decode_g711_alaw",
|
||||
"decode_g711_ulaw",
|
||||
"encode_float32_mono_wav_base64",
|
||||
"encode_g711_alaw",
|
||||
"encode_g711_ulaw",
|
||||
"resample_pcm16_mono",
|
||||
"validate_input_sample_rate_hz",
|
||||
"wav_payload_to_pcm16",
|
||||
]
|
||||
+110
-128
@@ -1,41 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Typed commands accepted by a duplex session.
|
||||
"""The command vocabulary one duplex session accepts, plus its mailbox rendering.
|
||||
|
||||
``DuplexSessionHandle.submit()`` takes one of these; the websocket handler and
|
||||
``InlineDuplexClient`` build them with :func:`command_from_realtime` from the
|
||||
OpenAI Realtime client event vocabulary. Every command can also render the
|
||||
session-internal mailbox payload (``payload()``), which is the dictionary
|
||||
vocabulary the session runner bodies were written against.
|
||||
``InlineDuplexClient`` build them with :func:`command_from_realtime`.
|
||||
|
||||
The *wire* half of each command --- which client event it decodes from and what
|
||||
fields survive decoding --- now lives in ``vllm_omni.protocol.duplex.commands``,
|
||||
which carries the whole vocabulary: the eight Tier 1 classes re-exported from
|
||||
``vllm_omni.protocol.realtime.commands``, the two Tier 2 ones and the seven
|
||||
Tier 3 ones. The engine imports that module and never the Tier 1 one directly,
|
||||
so a command that later grows a duplex extension changes one file
|
||||
(RFC #6592 P0a).
|
||||
|
||||
The *engine* half stays here, because it is not wire contract at all:
|
||||
``payload()`` renders the session-internal mailbox dictionary the runner bodies
|
||||
were written against, and its ``type`` is the mailbox channel rather than the
|
||||
client event. Those two genuinely differ --- ``session.update`` and
|
||||
``conversation.item.create`` / ``.delete`` / ``.truncate`` all travel on the
|
||||
``turn.signal`` channel --- which is why the halves are separated instead of
|
||||
the classes being relocated wholesale.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from vllm_omni.protocol.duplex import RealtimeProtocolError
|
||||
from vllm_omni.protocol.duplex import commands as _duplex_wire
|
||||
from vllm_omni.protocol.duplex.commands import RealtimeCommand
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.realtime_commands import RealtimeInputDefaults
|
||||
from vllm_omni.protocol.duplex import RealtimeInputDefaults
|
||||
|
||||
|
||||
class DuplexCommandError(ValueError):
|
||||
"""A client payload could not be turned into a command."""
|
||||
class DuplexCommandError(RealtimeProtocolError):
|
||||
"""A client payload could not be turned into a duplex command.
|
||||
|
||||
def __init__(self, message: str, *, code: str = "bad_event", event_id: str | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.event_id = event_id
|
||||
The duplex name for a Realtime protocol error: same ``code`` /
|
||||
``event_id`` contract, so the error envelope is rendered identically
|
||||
whichever consumer raised it.
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexCommand:
|
||||
class DuplexCommand(RealtimeCommand):
|
||||
"""A Realtime command as the duplex engine handles it.
|
||||
|
||||
Adds the mailbox channel (``type``) and its rendering on top of the wire
|
||||
command; every concrete class below pairs this with its protocol twin.
|
||||
"""
|
||||
|
||||
#: Mailbox event type this command renders to (see ``payload()``).
|
||||
type: ClassVar[str] = ""
|
||||
#: Client correlation id (OpenAI ``event_id``), echoed on error events.
|
||||
event_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
"""Render the session-internal mailbox dictionary."""
|
||||
@@ -56,19 +77,23 @@ class DuplexCommand:
|
||||
return data
|
||||
|
||||
|
||||
# ---- GA commands ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AppendAudio(DuplexCommand):
|
||||
class UpdateSession(DuplexCommand, _duplex_wire.UpdateSession):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "session.update"
|
||||
data["payload"] = dict(data.pop("patch", {}) or {})
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AppendAudio(DuplexCommand, _duplex_wire.AppendAudio):
|
||||
type: ClassVar[str] = "input_audio_buffer.append"
|
||||
#: Raw audio bytes in ``format`` at ``sample_rate_hz`` (base64 only on the wire).
|
||||
audio: bytes
|
||||
format: str = "pcm16"
|
||||
sample_rate_hz: int | None = None
|
||||
is_speech: bool | None = None
|
||||
video_frames: tuple[str, ...] = ()
|
||||
duration_ms: int | None = None
|
||||
audio_end_ms: int | None = None
|
||||
#: Model-neutral hints carried through from the wire (rms, vad, transcript hints ...).
|
||||
hints: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -90,21 +115,8 @@ class AppendAudio(DuplexCommand):
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AppendText(DuplexCommand):
|
||||
type: ClassVar[str] = "input.text.append"
|
||||
text: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Commit(DuplexCommand):
|
||||
class Commit(DuplexCommand, _duplex_wire.Commit):
|
||||
type: ClassVar[str] = "input_audio_buffer.commit"
|
||||
final: bool = True
|
||||
#: ``None`` means "no explicit request": the runner decides on commit (auto-response
|
||||
#: sessions answer on their own); ``True`` / ``False`` force it.
|
||||
create_response: bool | None = None
|
||||
is_speech: bool | None = None
|
||||
#: Realtime conversation item created for this commit (wire correlation only).
|
||||
realtime_item_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -114,10 +126,18 @@ class Commit(DuplexCommand):
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CreateResponse(DuplexCommand):
|
||||
class ClearInput(DuplexCommand, _duplex_wire.ClearInput):
|
||||
type: ClassVar[str] = "input_audio_buffer.clear"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClearOutputAudio(DuplexCommand, _duplex_wire.ClearOutputAudio):
|
||||
type: ClassVar[str] = "output_audio_buffer.clear"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CreateResponse(DuplexCommand, _duplex_wire.CreateResponse):
|
||||
type: ClassVar[str] = "response.create"
|
||||
#: Raw Realtime ``response`` object (instructions, voice, modalities, ...).
|
||||
options: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -128,84 +148,13 @@ class CreateResponse(DuplexCommand):
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClearInput(DuplexCommand):
|
||||
type: ClassVar[str] = "input_audio_buffer.clear"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelInput(DuplexCommand):
|
||||
type: ClassVar[str] = "input.cancel"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelResponse(DuplexCommand):
|
||||
class CancelResponse(DuplexCommand, _duplex_wire.CancelResponse):
|
||||
type: ClassVar[str] = "response.cancel"
|
||||
response_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class BargeIn(DuplexCommand):
|
||||
type: ClassVar[str] = "barge_in"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ClearOutputAudio(DuplexCommand):
|
||||
type: ClassVar[str] = "output_audio_buffer.clear"
|
||||
#: Explicit response to clear; ``None`` targets the active/last response.
|
||||
response_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SignalTurn(DuplexCommand):
|
||||
"""Generic ``turn.signal`` (local turn transitions such as ``user_started``)."""
|
||||
|
||||
class CreateItem(DuplexCommand, _duplex_wire.CreateItem):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
event: str
|
||||
signal_payload: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
signal_payload = data.pop("signal_payload", None)
|
||||
if isinstance(signal_payload, Mapping) and signal_payload:
|
||||
data["payload"] = dict(signal_payload)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class UpdateSession(DuplexCommand):
|
||||
"""``session.update``: a Realtime ``session`` object patch."""
|
||||
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
patch: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
data["event"] = "session.update"
|
||||
data["payload"] = dict(data.pop("patch", {}) or {})
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AckPlayback(DuplexCommand):
|
||||
type: ClassVar[str] = "playback.ack"
|
||||
played_ms: int
|
||||
committed_ms: int | None = None
|
||||
response_id: str | None = None
|
||||
item_id: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Heartbeat(DuplexCommand):
|
||||
type: ClassVar[str] = "session.heartbeat"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CreateItem(DuplexCommand):
|
||||
"""``conversation.item.create`` (history injection or function-call output)."""
|
||||
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item: Mapping[str, object]
|
||||
previous_item_id: str | None = None
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -219,9 +168,8 @@ class CreateItem(DuplexCommand):
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DeleteItem(DuplexCommand):
|
||||
class DeleteItem(DuplexCommand, _duplex_wire.DeleteItem):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item_id: str
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -231,11 +179,8 @@ class DeleteItem(DuplexCommand):
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TruncateItem(DuplexCommand):
|
||||
class TruncateItem(DuplexCommand, _duplex_wire.TruncateItem):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
item_id: str
|
||||
audio_end_ms: int
|
||||
content_index: int = 0
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
@@ -248,15 +193,51 @@ class TruncateItem(DuplexCommand):
|
||||
return data
|
||||
|
||||
|
||||
# ---- duplex extension commands ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CloseSession(DuplexCommand):
|
||||
"""Graceful close requested through the command stream (``session.close``)."""
|
||||
class AppendText(DuplexCommand, _duplex_wire.AppendText):
|
||||
type: ClassVar[str] = "input.text.append"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CancelInput(DuplexCommand, _duplex_wire.CancelInput):
|
||||
type: ClassVar[str] = "input.cancel"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class BargeIn(DuplexCommand, _duplex_wire.BargeIn):
|
||||
type: ClassVar[str] = "barge_in"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SignalTurn(DuplexCommand, _duplex_wire.SignalTurn):
|
||||
type: ClassVar[str] = "turn.signal"
|
||||
|
||||
def payload(self) -> dict[str, object]:
|
||||
data = DuplexCommand.payload(self)
|
||||
signal_payload = data.pop("signal_payload", None)
|
||||
if isinstance(signal_payload, Mapping) and signal_payload:
|
||||
data["payload"] = dict(signal_payload)
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AckPlayback(DuplexCommand, _duplex_wire.AckPlayback):
|
||||
type: ClassVar[str] = "playback.ack"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Heartbeat(DuplexCommand, _duplex_wire.Heartbeat):
|
||||
type: ClassVar[str] = "session.heartbeat"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class CloseSession(DuplexCommand, _duplex_wire.CloseSession):
|
||||
type: ClassVar[str] = "session.close"
|
||||
reason: str = "client_close"
|
||||
|
||||
|
||||
#: Realtime client event types that map onto commands (wire vocabulary).
|
||||
REALTIME_COMMAND_TYPES: frozenset[str] = frozenset(
|
||||
{
|
||||
"input_audio_buffer.append",
|
||||
@@ -300,7 +281,6 @@ def command_from_realtime(
|
||||
|
||||
|
||||
__all__ = [
|
||||
"REALTIME_COMMAND_TYPES",
|
||||
"AckPlayback",
|
||||
"AppendAudio",
|
||||
"AppendText",
|
||||
@@ -317,6 +297,8 @@ __all__ = [
|
||||
"DuplexCommand",
|
||||
"DuplexCommandError",
|
||||
"Heartbeat",
|
||||
"REALTIME_COMMAND_TYPES",
|
||||
"RealtimeCommand",
|
||||
"SignalTurn",
|
||||
"TruncateItem",
|
||||
"UpdateSession",
|
||||
|
||||
@@ -111,6 +111,8 @@ class DuplexCapabilities:
|
||||
#: seeding a text prompt has no representation and the turn never
|
||||
#: completes. ``text_turn_priming_units`` is how many silence units such a
|
||||
#: seeded turn must be given to generate on -- it still speaks per unit.
|
||||
supports_image_input: bool = False
|
||||
supports_text_only_turn: bool = False
|
||||
supports_chat_completions: bool = False
|
||||
text_turn_priming_units: int = 0
|
||||
requires_model_runner_kv: bool = False
|
||||
@@ -149,11 +151,13 @@ class DuplexCapabilities:
|
||||
"supports_session_resume": self.supports_session_resume,
|
||||
"session_admission_mode": self.session_admission_mode,
|
||||
"supports_audio_truncate": self.supports_audio_truncate,
|
||||
"supports_image_input": self.supports_image_input,
|
||||
"supports_text_only_turn": self.supports_text_only_turn,
|
||||
"requires_model_runner_kv": self.requires_model_runner_kv,
|
||||
"requires_native_stage_role": self.requires_native_stage_role,
|
||||
# Every duplex model is model-native and appends audio chunks (§7 D4);
|
||||
# kept on the wire as constants for clients that still read them.
|
||||
"implementation_level": "model_native_duplex",
|
||||
"implementation_level": (
|
||||
"model_native_duplex" if self.supports_model_native_turn_policy else "turn_based_duplex"
|
||||
),
|
||||
"adapter_patterns": self.adapter_patterns,
|
||||
"input_modes": ["append_audio_chunk"],
|
||||
"signal_sources": self.signal_sources,
|
||||
@@ -169,6 +173,8 @@ class DuplexPlaybackCursor:
|
||||
sent_ms: int = 0
|
||||
played_ms: int = 0
|
||||
committed_ms: int = 0
|
||||
text_requires_complete_audio: bool = False
|
||||
audio_complete: bool = False
|
||||
|
||||
def acknowledge(self, played_ms: int, committed_ms: int | None = None) -> None:
|
||||
self.played_ms = max(self.played_ms, max(0, int(played_ms)))
|
||||
@@ -188,7 +194,11 @@ class DuplexPlaybackCursor:
|
||||
}
|
||||
|
||||
def snapshot(self) -> DuplexPlaybackView:
|
||||
return DuplexPlaybackView(**self.as_dict())
|
||||
return DuplexPlaybackView(
|
||||
**self.as_dict(),
|
||||
text_requires_complete_audio=self.text_requires_complete_audio,
|
||||
audio_complete=self.audio_complete,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -197,6 +207,8 @@ class DuplexPlaybackView:
|
||||
sent_ms: int = 0
|
||||
played_ms: int = 0
|
||||
committed_ms: int = 0
|
||||
text_requires_complete_audio: bool = False
|
||||
audio_complete: bool = False
|
||||
|
||||
def as_dict(self) -> dict[str, int]:
|
||||
return {
|
||||
@@ -310,16 +322,21 @@ class DuplexSessionConfig:
|
||||
if isinstance(source.get("extra_body"), dict):
|
||||
config.extra_body = dict(source["extra_body"])
|
||||
extra = config.extra_body
|
||||
if isinstance(extra.get("overlap_policy"), str):
|
||||
config.overlap_policy = cls._normalize_overlap_policy(extra["overlap_policy"])
|
||||
if isinstance(extra.get("overlap_short_ack_ms"), int | float):
|
||||
config.overlap_short_ack_ms = max(0, int(extra["overlap_short_ack_ms"]))
|
||||
if isinstance(extra.get("overlap_barge_in_ms"), int | float):
|
||||
config.overlap_barge_in_ms = max(0, int(extra["overlap_barge_in_ms"]))
|
||||
if isinstance(extra.get("overlap_silence_rms"), int | float):
|
||||
config.overlap_silence_rms = max(0.0, float(extra["overlap_silence_rms"]))
|
||||
if isinstance(extra.get("playback_commit_policy"), str):
|
||||
config.playback_commit_policy = cls._normalize_playback_commit_policy(extra["playback_commit_policy"])
|
||||
overlap_policy = extra.get("overlap_policy")
|
||||
if isinstance(overlap_policy, str):
|
||||
config.overlap_policy = cls._normalize_overlap_policy(overlap_policy)
|
||||
short_ack_ms = extra.get("overlap_short_ack_ms")
|
||||
if isinstance(short_ack_ms, int | float):
|
||||
config.overlap_short_ack_ms = max(0, int(short_ack_ms))
|
||||
barge_in_ms = extra.get("overlap_barge_in_ms")
|
||||
if isinstance(barge_in_ms, int | float):
|
||||
config.overlap_barge_in_ms = max(0, int(barge_in_ms))
|
||||
silence_rms = extra.get("overlap_silence_rms")
|
||||
if isinstance(silence_rms, int | float):
|
||||
config.overlap_silence_rms = max(0.0, float(silence_rms))
|
||||
playback_commit_policy = extra.get("playback_commit_policy")
|
||||
if isinstance(playback_commit_policy, str):
|
||||
config.playback_commit_policy = cls._normalize_playback_commit_policy(playback_commit_policy)
|
||||
return config
|
||||
|
||||
@classmethod
|
||||
@@ -339,26 +356,26 @@ class DuplexSessionConfig:
|
||||
``_session_create_from_realtime``.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
RealtimeInputDefaults,
|
||||
DUPLEX_REALTIME_CAPABILITIES,
|
||||
duplex_response_format,
|
||||
)
|
||||
from vllm_omni.engine.duplex.turn_detection import normalize_turn_detection_session_payload
|
||||
from vllm_omni.protocol.duplex import (
|
||||
RealtimeInputDefaults,
|
||||
input_audio_transcription_config,
|
||||
json_safe_realtime_payload,
|
||||
realtime_max_output_tokens,
|
||||
realtime_overlap_fields,
|
||||
validate_realtime_session_audio_formats,
|
||||
)
|
||||
from vllm_omni.engine.duplex.turn_detection import (
|
||||
normalize_turn_detection_session_payload,
|
||||
validate_realtime_turn_detection,
|
||||
validate_session_payload,
|
||||
)
|
||||
|
||||
payload: dict[str, object] = dict(session_payload)
|
||||
format_error = validate_realtime_session_audio_formats(payload)
|
||||
if format_error is not None:
|
||||
raise DuplexConfigError(format_error, code="unsupported_audio_format")
|
||||
turn_detection_error = validate_realtime_turn_detection(payload)
|
||||
if turn_detection_error is not None:
|
||||
raise DuplexConfigError(turn_detection_error, code="unsupported_turn_detection", param="turn_detection")
|
||||
# One session check for every consumer (ENTRY-INV-002): the same
|
||||
# capability object ``translate_realtime_command`` uses, so a session
|
||||
# object is accepted or refused identically whichever door it came in.
|
||||
rejection = validate_session_payload(payload, capabilities=DUPLEX_REALTIME_CAPABILITIES)
|
||||
if rejection is not None:
|
||||
raise DuplexConfigError(rejection.message, code=rejection.code, param=rejection.param)
|
||||
normalize_turn_detection_session_payload(payload)
|
||||
defaults = RealtimeInputDefaults().with_session_payload(payload)
|
||||
payload.update(realtime_overlap_fields(payload))
|
||||
@@ -446,9 +463,9 @@ class DuplexSessionConfig:
|
||||
when the patch changes something a live session cannot change.
|
||||
``audio_started`` is ``playback.generated_ms > 0 or playback.sent_ms > 0``.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
from vllm_omni.engine.duplex.realtime_commands import duplex_response_format
|
||||
from vllm_omni.protocol.duplex import (
|
||||
REALTIME_OUTPUT_AUDIO_FORMATS,
|
||||
duplex_response_format,
|
||||
input_audio_transcription_config,
|
||||
json_safe_realtime_payload,
|
||||
parse_realtime_audio_format,
|
||||
@@ -629,11 +646,10 @@ class ResponseCreateOptions:
|
||||
for options a model-native duplex session cannot apply per response.
|
||||
Private runtime keys in ``extra_body`` are dropped.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
from vllm_omni.engine.duplex.realtime_commands import duplex_response_format
|
||||
from vllm_omni.protocol.duplex import (
|
||||
REALTIME_OUTPUT_AUDIO_FORMATS,
|
||||
duplex_response_format,
|
||||
parse_realtime_audio_format,
|
||||
realtime_max_output_tokens,
|
||||
)
|
||||
|
||||
payload: dict[str, object] = dict(response_payload)
|
||||
@@ -665,11 +681,12 @@ class ResponseCreateOptions:
|
||||
response_format = payload.get("output_audio_format") or payload.get("response_format")
|
||||
if response_format is None and isinstance(audio_output, dict):
|
||||
response_format = audio_output.get("format")
|
||||
response_format, _ = parse_realtime_audio_format(response_format)
|
||||
if isinstance(response_format, str) and response_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
response_format = duplex_response_format(response_format)
|
||||
parsed_format, _ = parse_realtime_audio_format(response_format)
|
||||
output_audio_format: str | None
|
||||
if isinstance(parsed_format, str) and parsed_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
output_audio_format = str(duplex_response_format(parsed_format))
|
||||
else:
|
||||
response_format = None
|
||||
output_audio_format = None
|
||||
temperature = (
|
||||
float(cast("int | float", payload["temperature"]))
|
||||
if isinstance(payload.get("temperature"), int | float)
|
||||
@@ -687,9 +704,9 @@ class ResponseCreateOptions:
|
||||
else payload.get("max_tokens")
|
||||
)
|
||||
if "max_response_output_tokens" in payload or "max_output_tokens" in payload or "max_tokens" in payload:
|
||||
max_tokens = realtime_max_output_tokens(max_tokens)
|
||||
token_limit = realtime_max_output_tokens(max_tokens)
|
||||
else:
|
||||
max_tokens = None
|
||||
token_limit = None
|
||||
modalities = payload.get("modalities") or payload.get("output_modalities")
|
||||
if isinstance(modalities, list) and all(isinstance(item, str) for item in modalities):
|
||||
modalities = tuple(modalities)
|
||||
@@ -717,9 +734,9 @@ class ResponseCreateOptions:
|
||||
return cls(
|
||||
instructions=instructions,
|
||||
voice=voice,
|
||||
response_format=response_format,
|
||||
response_format=output_audio_format,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
max_tokens=token_limit,
|
||||
speed=speed,
|
||||
modalities=modalities,
|
||||
extra_body=response_extra,
|
||||
@@ -761,6 +778,8 @@ def realtime_item_to_history_message(item: object) -> dict[str, object] | None:
|
||||
part_type = part.get("type")
|
||||
if part_type in {"input_text", "text", "output_text"} and isinstance(part.get("text"), str):
|
||||
text_chunks.append(str(part["text"]))
|
||||
elif part_type == "input_image" and isinstance(part.get("image_url"), str):
|
||||
audio_chunks.append({"type": "image_url", "image_url": {"url": part["image_url"]}})
|
||||
elif part_type in {"input_audio", "audio"}:
|
||||
audio = part.get("audio") or part.get("data")
|
||||
fmt = part.get("format") if isinstance(part.get("format"), str) else "wav"
|
||||
@@ -782,14 +801,14 @@ def realtime_item_to_history_message(item: object) -> dict[str, object] | None:
|
||||
|
||||
def realtime_max_output_tokens(value: object) -> int | None:
|
||||
"""Normalize Realtime max output tokens (``"inf"`` -> ``None``)."""
|
||||
from vllm_omni.engine.duplex.realtime_commands import realtime_max_output_tokens as _impl
|
||||
from vllm_omni.protocol.duplex import realtime_max_output_tokens as _impl
|
||||
|
||||
return _impl(value)
|
||||
|
||||
|
||||
def input_audio_transcription_config(session_payload: Mapping[str, object]) -> dict[str, object] | None:
|
||||
"""Return the ``input_audio_transcription`` object of a Realtime session payload."""
|
||||
from vllm_omni.engine.duplex.realtime_commands import input_audio_transcription_config as _impl
|
||||
from vllm_omni.protocol.duplex import input_audio_transcription_config as _impl
|
||||
|
||||
return _impl(session_payload)
|
||||
|
||||
|
||||
@@ -1,677 +1,79 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Typed events emitted by a duplex session.
|
||||
"""The event vocabulary one duplex session speaks, assembled from two layers.
|
||||
|
||||
Every public event is a frozen dataclass with explicit fields. The Realtime
|
||||
wire JSON is *derived* from those fields by :meth:`DuplexEvent.to_realtime`,
|
||||
which is pure: it never consults session state. The stateful part (response /
|
||||
item ids, content-part bookkeeping) lives in
|
||||
``vllm_omni.engine.duplex.realtime_events`` on the session runner and is
|
||||
consumed when the events are *constructed*.
|
||||
The classes themselves no longer live here. ``vllm_omni.protocol.duplex.events``
|
||||
carries the whole vocabulary --- 22 Tier 1 classes re-exported from
|
||||
``vllm_omni.protocol.realtime.events``, 8 Tier 2 ones and 12 Tier 3 ones --- so
|
||||
a non-duplex Realtime consumer can take the Tier 1 half and its wire rendering
|
||||
without the duplex session control plane (RFC #6592 P0a). The engine imports
|
||||
the duplex module and never the Tier 1 one directly.
|
||||
|
||||
``session_id`` / ``epoch`` are bound by
|
||||
``DuplexSessionManager.emit`` when an event leaves the runner; producers
|
||||
(projector, serving handshake helpers) build events with the defaults.
|
||||
What is genuinely engine-side stays: :data:`DOMAIN_TERMINAL_EVENTS` and
|
||||
:data:`MODEL_OUTPUT_EVENTS` are the session runner's epoch-filter policy, not
|
||||
wire contract --- they name *internal* event types, and which of them may never
|
||||
be dropped as stale is a runtime decision.
|
||||
|
||||
``DuplexEvent`` is re-exported as the name the engine and the clients already
|
||||
use. It is an alias of
|
||||
:class:`~vllm_omni.protocol.realtime.events.RealtimeEvent`, not a subclass,
|
||||
because an event has no engine-internal half --- what the session emits is
|
||||
exactly what the socket sends. A *command* does have one (``payload()`` renders
|
||||
the runner's mailbox), which is why ``DuplexCommand`` is a real class.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import ClassVar, cast
|
||||
from uuid import uuid4
|
||||
from vllm_omni.protocol.duplex.errors import REALTIME_ERROR_TYPES_BY_CODE
|
||||
from vllm_omni.protocol.duplex.events import (
|
||||
AudioDelta,
|
||||
AudioDone,
|
||||
ContentPartAdded,
|
||||
ContentPartDone,
|
||||
DuplexEvent,
|
||||
DuplexRawEvent,
|
||||
ErrorEvent,
|
||||
FunctionCallArgumentsDelta,
|
||||
FunctionCallArgumentsDone,
|
||||
InputCleared,
|
||||
InputCommitted,
|
||||
InputTranscriptionCompleted,
|
||||
ItemAdded,
|
||||
ItemCreated,
|
||||
ItemDeleted,
|
||||
ItemDone,
|
||||
ItemRetrieved,
|
||||
ItemTruncated,
|
||||
Listen,
|
||||
OutputAudioCleared,
|
||||
OutputItemAdded,
|
||||
OutputItemDone,
|
||||
OverlapDecision,
|
||||
PlaybackAcknowledged,
|
||||
RateLimitsUpdated,
|
||||
ResponseCreated,
|
||||
ResponseDone,
|
||||
SessionClosed,
|
||||
SessionCreated,
|
||||
SessionExpired,
|
||||
SessionHeartbeatAck,
|
||||
SessionReplaced,
|
||||
SessionResumed,
|
||||
SessionResyncRequired,
|
||||
SessionUpdated,
|
||||
Speak,
|
||||
SpeechStarted,
|
||||
SpeechStopped,
|
||||
TextDelta,
|
||||
TextDone,
|
||||
TranscriptDelta,
|
||||
TranscriptDone,
|
||||
TurnEvent,
|
||||
error_event,
|
||||
new_event_id,
|
||||
)
|
||||
|
||||
|
||||
def new_event_id() -> str:
|
||||
return f"event_{uuid4().hex}"
|
||||
|
||||
|
||||
#: OpenAI Realtime ``error.type`` for each internal error code.
|
||||
REALTIME_ERROR_TYPES_BY_CODE: dict[str, str] = {
|
||||
"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_append_failed": "server_error",
|
||||
"runtime_append_task_failed": "server_error",
|
||||
"runtime_signal_failed": "server_error",
|
||||
"runtime_abort_failed": "server_error",
|
||||
"runtime_data_plane_stream_failed": "server_error",
|
||||
"runtime_data_plane_text_without_audio": "server_error",
|
||||
"resource_exhausted": "rate_limit_error",
|
||||
"session_exists": "invalid_request_error",
|
||||
"session_closed": "invalid_request_error",
|
||||
"unknown_session": "invalid_request_error",
|
||||
"invalid_duplex_runtime_config": "invalid_request_error",
|
||||
"instructions_update_unsupported": "invalid_request_error",
|
||||
"persona_update_unsupported": "invalid_request_error",
|
||||
"voice_update_unsupported": "invalid_request_error",
|
||||
"unsupported_nemotron_duplex_mode": "invalid_request_error",
|
||||
"unsupported_native_response_options": "invalid_request_error",
|
||||
"runtime_touch_failed": "server_error",
|
||||
"engine_error": "server_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",
|
||||
"text_only_turn_unsupported": "invalid_request_error",
|
||||
"commit_aborted": "server_error",
|
||||
"input_audio_buffer_empty": "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_turn_detection": "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",
|
||||
"invalid_video_frames": "invalid_request_error",
|
||||
"invalid_function_call_output": "invalid_request_error",
|
||||
"server_vad_unavailable": "server_error",
|
||||
}
|
||||
|
||||
_IDENTITY_FIELDS = frozenset({"session_id", "epoch", "event_id"})
|
||||
|
||||
|
||||
def _wire_value(value: object) -> object:
|
||||
if isinstance(value, Mapping):
|
||||
return {str(k): _wire_value(v) for k, v in value.items()}
|
||||
if isinstance(value, tuple | list):
|
||||
return [_wire_value(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexEvent:
|
||||
"""Base of every public session event."""
|
||||
|
||||
#: Realtime ``type`` this class renders to.
|
||||
wire_type: ClassVar[str] = ""
|
||||
#: Fields that are omitted from the wire object when ``None``.
|
||||
optional_wire_fields: ClassVar[frozenset[str]] = frozenset()
|
||||
|
||||
session_id: str = ""
|
||||
epoch: int | None = None
|
||||
#: Server event id (OpenAI ``event_id``); generated at construction.
|
||||
event_id: str = field(default_factory=new_event_id)
|
||||
|
||||
# ---- identity ----
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return self.wire_type
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return False
|
||||
|
||||
# ---- generic accessors (None when the class has no such field) ----
|
||||
|
||||
@property
|
||||
def response_id(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def audio(self) -> bytes | None:
|
||||
return None
|
||||
|
||||
# ---- wire rendering (pure) ----
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
data: dict[str, object] = {}
|
||||
for f in fields(self):
|
||||
if f.name in _IDENTITY_FIELDS:
|
||||
continue
|
||||
value = getattr(self, f.name)
|
||||
if value is None and f.name in self.optional_wire_fields:
|
||||
continue
|
||||
data[f.name] = _wire_value(value)
|
||||
return data
|
||||
|
||||
def to_realtime(self) -> dict[str, object]:
|
||||
"""The Realtime wire JSON object for this event (derived from the fields)."""
|
||||
return {"type": self.wire_type, "event_id": self.event_id, **self._wire_fields()}
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return f"{type(self).__name__}(type={self.wire_type!r}, session_id={self.session_id!r}, epoch={self.epoch!r})"
|
||||
|
||||
|
||||
# ---- session lifecycle ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionCreated(DuplexEvent):
|
||||
wire_type = "session.created"
|
||||
optional_wire_fields = frozenset({"attachment_generation", "resume_token"})
|
||||
|
||||
session: Mapping[str, object] = field(default_factory=dict)
|
||||
#: Transport resume credentials (set by the websocket handler when resume is supported).
|
||||
attachment_generation: int | None = None
|
||||
resume_token: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionUpdated(DuplexEvent):
|
||||
wire_type = "session.updated"
|
||||
|
||||
session: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionResumed(SessionCreated):
|
||||
wire_type = "session.resumed"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionReplaced(DuplexEvent):
|
||||
"""A newer connection took the session over (sent to the replaced socket)."""
|
||||
|
||||
wire_type = "session.replaced"
|
||||
|
||||
attachment_generation: int = 0
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionResyncRequired(DuplexEvent):
|
||||
"""The replay journal cannot bridge the gap; the client must start over."""
|
||||
|
||||
wire_type = "session.resync_required"
|
||||
|
||||
reason: str = "journal_gap"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, **DuplexEvent._wire_fields(self)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionClosed(DuplexEvent):
|
||||
wire_type = "session.closed"
|
||||
|
||||
reason: str = "closed"
|
||||
#: The session-internal close event (kept for clients that inspect it).
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def is_terminal(self) -> bool:
|
||||
return True
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "reason": self.reason, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionExpired(SessionClosed):
|
||||
wire_type = "session.expired"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "reason": self.reason}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SessionHeartbeatAck(DuplexEvent):
|
||||
wire_type = "session.heartbeat_ack"
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TurnEvent(DuplexEvent):
|
||||
"""Turn-state transition (``turn.event``)."""
|
||||
|
||||
wire_type = "turn.event"
|
||||
|
||||
event: str = ""
|
||||
turn_state: str = ""
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"session_id": self.session_id, "event": self.event, "turn_state": self.turn_state, "epoch": self.epoch}
|
||||
|
||||
|
||||
# ---- response lifecycle ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class _ResponseEvent(DuplexEvent):
|
||||
"""Events addressed to one response (and usually one output item / content part)."""
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
content_index: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ResponseCreated(DuplexEvent):
|
||||
wire_type = "response.created"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
response: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Listen(DuplexEvent):
|
||||
"""The model decided to keep listening (no spoken response for this turn)."""
|
||||
|
||||
wire_type = "response.listen"
|
||||
optional_wire_fields = frozenset({"response_id"})
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
response: dict[str, object] = {
|
||||
"object": "realtime.response",
|
||||
"status": "listening",
|
||||
"metadata": _wire_value(self.details),
|
||||
}
|
||||
data: dict[str, object] = {"session_id": self.session_id, "epoch": self.epoch, "response": response}
|
||||
if self.response_id:
|
||||
response["id"] = self.response_id
|
||||
data["response_id"] = self.response_id
|
||||
return data
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class Speak(_ResponseEvent):
|
||||
wire_type = "response.speak"
|
||||
|
||||
metadata: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OverlapDecision(DuplexEvent):
|
||||
wire_type = "overlap.decision"
|
||||
|
||||
policy: str | None = None
|
||||
action: str | None = None
|
||||
reason: str | None = None
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"session_id": self.session_id,
|
||||
"epoch": self.epoch,
|
||||
"policy": self.policy,
|
||||
"action": self.action,
|
||||
"reason": self.reason,
|
||||
"metadata": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputItemAdded(DuplexEvent):
|
||||
wire_type = "response.output_item.added"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputItemDone(OutputItemAdded):
|
||||
wire_type = "response.output_item.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ContentPartAdded(_ResponseEvent):
|
||||
wire_type = "response.content_part.added"
|
||||
|
||||
part: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ContentPartDone(ContentPartAdded):
|
||||
wire_type = "response.content_part.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AudioDelta(_ResponseEvent):
|
||||
wire_type = "response.output_audio.delta"
|
||||
optional_wire_fields = frozenset({"sample_rate_hz", "metadata"})
|
||||
|
||||
#: Base64 audio in ``format``.
|
||||
delta: str = ""
|
||||
format: str = "pcm16"
|
||||
sample_rate_hz: int | None = None
|
||||
metadata: Mapping[str, object] | None = None
|
||||
|
||||
@property
|
||||
def audio(self) -> bytes | None:
|
||||
try:
|
||||
return base64.b64decode(self.delta)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class AudioDone(_ResponseEvent):
|
||||
wire_type = "response.output_audio.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TranscriptDelta(_ResponseEvent):
|
||||
wire_type = "response.output_audio_transcript.delta"
|
||||
|
||||
delta: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.delta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TranscriptDone(_ResponseEvent):
|
||||
wire_type = "response.output_audio_transcript.done"
|
||||
|
||||
transcript: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.transcript
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TextDelta(_ResponseEvent):
|
||||
wire_type = "response.output_text.delta"
|
||||
|
||||
delta: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.delta
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class TextDone(_ResponseEvent):
|
||||
wire_type = "response.output_text.done"
|
||||
|
||||
text: str = "" # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class FunctionCallArgumentsDelta(DuplexEvent):
|
||||
wire_type = "response.function_call_arguments.delta"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
call_id: str = ""
|
||||
delta: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class FunctionCallArgumentsDone(DuplexEvent):
|
||||
wire_type = "response.function_call_arguments.done"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
output_index: int = 0
|
||||
call_id: str = ""
|
||||
arguments: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ResponseDone(DuplexEvent):
|
||||
wire_type = "response.done"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
response: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def status(self) -> str | None:
|
||||
value = self.response.get("status")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class RateLimitsUpdated(DuplexEvent):
|
||||
wire_type = "rate_limits.updated"
|
||||
|
||||
rate_limits: tuple[Mapping[str, object], ...] = ()
|
||||
|
||||
|
||||
# ---- input buffer / conversation ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputCommitted(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.committed"
|
||||
|
||||
previous_item_id: str | None = None
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
#: The session-internal ``input.committed`` event.
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"previous_item_id": self.previous_item_id,
|
||||
"item_id": self.item_id,
|
||||
"event": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputCleared(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.cleared"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SpeechStarted(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.speech_started"
|
||||
|
||||
audio_start_ms: int = 0
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class SpeechStopped(DuplexEvent):
|
||||
wire_type = "input_audio_buffer.speech_stopped"
|
||||
|
||||
audio_end_ms: int = 0
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class _ItemEvent(DuplexEvent):
|
||||
previous_item_id: str | None = None
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemAdded(_ItemEvent):
|
||||
wire_type = "conversation.item.added"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemCreated(_ItemEvent):
|
||||
wire_type = "conversation.item.created"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemDone(_ItemEvent):
|
||||
wire_type = "conversation.item.done"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemRetrieved(DuplexEvent):
|
||||
wire_type = "conversation.item.retrieved"
|
||||
|
||||
item: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def item_id(self) -> str | None:
|
||||
value = self.item.get("id")
|
||||
return value if isinstance(value, str) else None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemDeleted(DuplexEvent):
|
||||
wire_type = "conversation.item.deleted"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"item_id": self.item_id, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ItemTruncated(DuplexEvent):
|
||||
wire_type = "conversation.item.truncated"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
content_index: int = 0
|
||||
audio_end_ms: int = 0
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {
|
||||
"item_id": self.item_id,
|
||||
"content_index": self.content_index,
|
||||
"audio_end_ms": self.audio_end_ms,
|
||||
"event": _wire_value(self.details),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class InputTranscriptionCompleted(DuplexEvent):
|
||||
wire_type = "conversation.item.input_audio_transcription.completed"
|
||||
|
||||
item_id: str | None = None # type: ignore[assignment]
|
||||
content_index: int = 0
|
||||
transcript: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.transcript
|
||||
|
||||
|
||||
# ---- playback / control ----
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class OutputAudioCleared(DuplexEvent):
|
||||
wire_type = "output_audio_buffer.cleared"
|
||||
|
||||
response_id: str | None = None # type: ignore[assignment]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class PlaybackAcknowledged(DuplexEvent):
|
||||
wire_type = "playback.acknowledged"
|
||||
|
||||
#: The session-internal ``playback.acknowledged`` event (cursor, committed_ms ...).
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"event": _wire_value(self.details)}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class ErrorEvent(DuplexEvent):
|
||||
wire_type = "error"
|
||||
|
||||
code: str = "internal_error"
|
||||
message: str = ""
|
||||
#: Client ``event_id`` this error answers (OpenAI ``error.event_id``).
|
||||
related_event_id: str | None = None
|
||||
param: str | None = None
|
||||
#: Extra keys merged into the wire ``error`` object (``retryable`` ...).
|
||||
extra: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def error_type(self) -> str:
|
||||
return REALTIME_ERROR_TYPES_BY_CODE.get(self.code, "invalid_request_error")
|
||||
|
||||
@property
|
||||
def error(self) -> dict[str, object]:
|
||||
error: dict[str, object] = {"type": self.error_type, "code": self.code, "message": self.message}
|
||||
if self.related_event_id:
|
||||
error["event_id"] = self.related_event_id
|
||||
if self.param:
|
||||
error["param"] = self.param
|
||||
error.update(cast("Mapping[str, object]", _wire_value(self.extra)))
|
||||
return error
|
||||
|
||||
@property
|
||||
def text(self) -> str | None:
|
||||
return self.message
|
||||
|
||||
def _wire_fields(self) -> dict[str, object]:
|
||||
return {"error": self.error}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True, kw_only=True)
|
||||
class DuplexRawEvent(DuplexEvent):
|
||||
"""A session-internal event with no dedicated Realtime type (``duplex.<internal type>``)."""
|
||||
|
||||
wire_type = "duplex.raw"
|
||||
|
||||
internal_type: str = ""
|
||||
details: Mapping[str, object] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return f"duplex.{self.internal_type}"
|
||||
|
||||
def to_realtime(self) -> dict[str, object]:
|
||||
return {"type": self.type, "event_id": self.event_id, "event": _wire_value(self.details)}
|
||||
|
||||
|
||||
def error_event(
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
event_id: object | None = None,
|
||||
param: object | None = None,
|
||||
extra: Mapping[str, object] | None = None,
|
||||
) -> ErrorEvent:
|
||||
"""Build the error event for an internal code; ``event_id`` is the *client* event id."""
|
||||
return ErrorEvent(
|
||||
code=code,
|
||||
message=message,
|
||||
related_event_id=event_id if isinstance(event_id, str) and event_id else None,
|
||||
param=param if isinstance(param, str) and param else None,
|
||||
extra=dict(extra or {}),
|
||||
)
|
||||
|
||||
|
||||
#: Internal events that terminate a response/session and must never be dropped as stale.
|
||||
DOMAIN_TERMINAL_EVENTS = frozenset(
|
||||
{
|
||||
"response.done",
|
||||
@@ -682,7 +84,6 @@ DOMAIN_TERMINAL_EVENTS = frozenset(
|
||||
}
|
||||
)
|
||||
|
||||
#: Internal streaming model-output events subject to epoch/close stale filtering.
|
||||
MODEL_OUTPUT_EVENTS = frozenset(
|
||||
{
|
||||
"response.created",
|
||||
@@ -705,13 +106,11 @@ MODEL_OUTPUT_EVENTS = frozenset(
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DOMAIN_TERMINAL_EVENTS",
|
||||
"MODEL_OUTPUT_EVENTS",
|
||||
"REALTIME_ERROR_TYPES_BY_CODE",
|
||||
"AudioDelta",
|
||||
"AudioDone",
|
||||
"ContentPartAdded",
|
||||
"ContentPartDone",
|
||||
"DOMAIN_TERMINAL_EVENTS",
|
||||
"DuplexEvent",
|
||||
"DuplexRawEvent",
|
||||
"ErrorEvent",
|
||||
@@ -727,11 +126,13 @@ __all__ = [
|
||||
"ItemRetrieved",
|
||||
"ItemTruncated",
|
||||
"Listen",
|
||||
"MODEL_OUTPUT_EVENTS",
|
||||
"OutputAudioCleared",
|
||||
"OutputItemAdded",
|
||||
"OutputItemDone",
|
||||
"OverlapDecision",
|
||||
"PlaybackAcknowledged",
|
||||
"REALTIME_ERROR_TYPES_BY_CODE",
|
||||
"RateLimitsUpdated",
|
||||
"ResponseCreated",
|
||||
"ResponseDone",
|
||||
|
||||
@@ -123,6 +123,11 @@ class DuplexModelSessionState(ABC):
|
||||
continuation_units: int
|
||||
pending_silence_task: asyncio.Task[bool] | None
|
||||
pending_silence_owner_id: str | None
|
||||
# Deadline-aligned silence continuation state: the monotonic submission
|
||||
# time of the most recent native input unit and the next silence
|
||||
# continuation deadline. A real (non-silence) input resets the chain.
|
||||
last_native_submit_monotonic: float | None
|
||||
silence_deadline_monotonic: float | None
|
||||
|
||||
@abstractmethod
|
||||
def retain_committed_audio(
|
||||
@@ -174,6 +179,7 @@ class DuplexModelPlugin(ABC):
|
||||
two halves is impossible by construction.
|
||||
"""
|
||||
|
||||
projects_intermediate_outputs: bool = False
|
||||
plugin_id: str = ""
|
||||
private_runtime_config_keys: frozenset[str] = frozenset()
|
||||
#: Samples per silence unit the runner appends to keep a model turn going.
|
||||
@@ -194,6 +200,16 @@ class DuplexModelPlugin(ABC):
|
||||
defaults: tuple[object, ...],
|
||||
) -> tuple[object, ...]: ...
|
||||
|
||||
def prepare_prompt_config(
|
||||
self, config: dict[str, object], *, state: DuplexModelSessionState, payload: dict[str, object]
|
||||
) -> dict[str, object]:
|
||||
"""Add model-owned context before planning an append on the session loop."""
|
||||
return config
|
||||
|
||||
async def prepare_append_plan(self, **kwargs) -> DuplexAppendPlan:
|
||||
"""Prepare a plan; plugins may offload expensive work on owned snapshots."""
|
||||
return self.plan_append(**kwargs)
|
||||
|
||||
@abstractmethod
|
||||
def plan_append(
|
||||
self,
|
||||
@@ -307,10 +323,16 @@ def payload_turn_id(payload: object) -> int | None:
|
||||
|
||||
|
||||
def coerce_int(value: object) -> int | None:
|
||||
try:
|
||||
return int(value) if value is not None else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if isinstance(value, bool):
|
||||
return int(value)
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float | str | bytes | bytearray):
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
__all__ = [
|
||||
|
||||
@@ -3,26 +3,31 @@
|
||||
|
||||
"""OpenAI Realtime client events -> :class:`DuplexCommand` (stateless).
|
||||
|
||||
This is the mapping half of the former ``entrypoints/duplex/realtime_input.py``
|
||||
translator. Everything that needed per-session state in the old translator
|
||||
(input-buffer emptiness for commits, response-id fallbacks for cancels,
|
||||
conversation-item lookups, VAD) is resolved by the session runner through the
|
||||
helpers on :class:`~vllm_omni.engine.duplex.realtime_events.RealtimeProjectionState`;
|
||||
This module is the *duplex binding* of the shared Realtime codec. Parsing,
|
||||
validating and decoding a client event is not duplex-specific and lives in
|
||||
``vllm_omni.protocol.realtime``, reached through ``vllm_omni.protocol.duplex``;
|
||||
what lives here is the part that is: which
|
||||
:class:`~vllm_omni.engine.duplex.commands.DuplexCommand` a decoded event
|
||||
becomes, what the duplex engine can serve
|
||||
(:data:`DUPLEX_REALTIME_CAPABILITIES`), and the mapping between a Realtime
|
||||
output format and the duplex ``response_format`` vocabulary.
|
||||
|
||||
Everything that needs per-session state (input-buffer emptiness for commits,
|
||||
response-id fallbacks for cancels, conversation-item lookups, VAD) is resolved
|
||||
by the session runner through the helpers on
|
||||
:class:`~vllm_omni.engine.duplex.realtime_events.RealtimeProjectionState`;
|
||||
the commands produced here carry the raw client intent only.
|
||||
|
||||
The shared names re-exported at the bottom are a compatibility surface for
|
||||
existing importers. The canonical definitions are in
|
||||
``vllm_omni.protocol.realtime`` and there is exactly one of each.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any, cast
|
||||
from uuid import uuid4
|
||||
from typing import cast
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.engine.duplex.audio import convert_input_audio_with_rate
|
||||
from vllm_omni.engine.duplex.commands import (
|
||||
AckPlayback,
|
||||
AppendAudio,
|
||||
@@ -44,93 +49,58 @@ from vllm_omni.engine.duplex.commands import (
|
||||
TruncateItem,
|
||||
UpdateSession,
|
||||
)
|
||||
|
||||
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",
|
||||
}
|
||||
|
||||
#: Wire hint keys copied verbatim from a client append onto the internal payload.
|
||||
REALTIME_INPUT_HINT_KEYS = (
|
||||
"duration_ms",
|
||||
"audio_duration_ms",
|
||||
"audio_start_ms",
|
||||
"audio_end_ms",
|
||||
"is_speech",
|
||||
"speech",
|
||||
"speech_probability",
|
||||
"vad",
|
||||
"overlap_action",
|
||||
"overlap",
|
||||
"force_barge_in",
|
||||
"force_listen",
|
||||
"text",
|
||||
"transcript",
|
||||
from vllm_omni.protocol.duplex import (
|
||||
REALTIME_INPUT_AUDIO_FORMATS,
|
||||
REALTIME_INPUT_HINT_KEYS,
|
||||
REALTIME_OUTPUT_AUDIO_FORMATS,
|
||||
RealtimeInputDefaults,
|
||||
RealtimeProtocolCapabilities,
|
||||
RealtimeProtocolError,
|
||||
apply_realtime_session_defaults,
|
||||
copy_realtime_input_hints,
|
||||
decode_audio_append,
|
||||
input_audio_transcription_config,
|
||||
input_explicitly_non_speech,
|
||||
input_looks_like_speech,
|
||||
input_transcript_from_item,
|
||||
is_supported_realtime_input_format,
|
||||
json_safe_realtime_payload,
|
||||
normalize_conversation_item,
|
||||
parse_realtime_audio_format,
|
||||
realtime_audio_format_object,
|
||||
realtime_max_output_tokens,
|
||||
realtime_output_format,
|
||||
realtime_overlap_fields,
|
||||
text_chars_for_audio_ms_from_marks,
|
||||
truncate_realtime_item_content,
|
||||
validate_conversation_item_audio_formats,
|
||||
validate_realtime_item_truncate,
|
||||
validate_realtime_response_audio_formats,
|
||||
validate_realtime_session_audio_formats,
|
||||
validate_realtime_video_frames,
|
||||
validate_session_payload,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RealtimeInputDefaults:
|
||||
"""Session-level wire defaults an append may omit (derived from the session object)."""
|
||||
def _validate_duplex_turn_detection(session_payload: Mapping[str, object]) -> str | None:
|
||||
"""The duplex engine's answer for ``turn_detection`` on a session object.
|
||||
|
||||
input_audio_format: str = "pcm16"
|
||||
input_sample_rate_hz: int = 16000
|
||||
output_audio_format: str = "pcm16"
|
||||
output_sample_rate_hz: int | None = None
|
||||
overlap_silence_rms: float = 0.003
|
||||
Imported lazily: the validator lives with the Silero VAD backend, and a
|
||||
connection that never sends a session object should not pay for loading it.
|
||||
"""
|
||||
from vllm_omni.engine.duplex.turn_detection import validate_realtime_turn_detection
|
||||
|
||||
def with_session_payload(self, session_payload: Mapping[str, object]) -> RealtimeInputDefaults:
|
||||
"""Return defaults updated from a Realtime ``session`` object (session.update)."""
|
||||
values = apply_realtime_session_defaults(self, session_payload)
|
||||
return values
|
||||
return validate_realtime_turn_detection(session_payload)
|
||||
|
||||
|
||||
# ---- audio format helpers ----
|
||||
|
||||
|
||||
def parse_realtime_audio_format(raw_format: object) -> tuple[object, int | None]:
|
||||
def normalize_format(fmt: str) -> str:
|
||||
normalized = fmt.lower()
|
||||
if normalized in {"audio/pcm", "pcm"}:
|
||||
return "pcm16"
|
||||
if normalized in {"audio/wav", "wav"}:
|
||||
return "wav"
|
||||
if normalized in {"audio/pcm16", "pcm16", "pcm_s16le", "s16le"}:
|
||||
return "pcm16"
|
||||
if normalized in {"audio/pcm_f32le", "pcm_f32le", "f32le"}:
|
||||
return "pcm_f32le"
|
||||
if normalized in {"audio/g711_ulaw", "g711_ulaw", "g711-ulaw", "ulaw", "mulaw"}:
|
||||
return "g711_ulaw"
|
||||
if normalized in {"audio/g711_alaw", "g711_alaw", "g711-alaw", "alaw"}:
|
||||
return "g711_alaw"
|
||||
return fmt
|
||||
|
||||
if isinstance(raw_format, str):
|
||||
return normalize_format(raw_format), None
|
||||
if not isinstance(raw_format, dict):
|
||||
return raw_format, None
|
||||
rate = raw_format.get("rate") or raw_format.get("sample_rate_hz") or raw_format.get("sample_rate")
|
||||
sample_rate_hz = int(rate) if isinstance(rate, int | float) and rate > 0 else None
|
||||
fmt = raw_format.get("type") or raw_format.get("format")
|
||||
if not isinstance(fmt, str):
|
||||
return raw_format, sample_rate_hz
|
||||
return normalize_format(fmt), sample_rate_hz
|
||||
#: What the duplex engine can serve, for the shared session-object validator.
|
||||
DUPLEX_REALTIME_CAPABILITIES = RealtimeProtocolCapabilities(
|
||||
validate_turn_detection=_validate_duplex_turn_detection,
|
||||
)
|
||||
|
||||
|
||||
def duplex_response_format(realtime_format: str) -> str:
|
||||
"""A Realtime output format -> the duplex ``response_format`` vocabulary."""
|
||||
normalized = realtime_format.lower()
|
||||
if normalized in {"pcm16", "pcm_s16le", "s16le"}:
|
||||
return "pcm"
|
||||
@@ -141,433 +111,6 @@ def duplex_response_format(realtime_format: str) -> str:
|
||||
return "wav"
|
||||
|
||||
|
||||
def realtime_output_format(duplex_format: object) -> str:
|
||||
if isinstance(duplex_format, str) and duplex_format.lower() in {"g711_ulaw", "g711_alaw"}:
|
||||
return duplex_format.lower()
|
||||
if isinstance(duplex_format, str) and duplex_format.lower() == "pcm":
|
||||
return "pcm16"
|
||||
return str(duplex_format or "wav")
|
||||
|
||||
|
||||
def is_supported_realtime_input_format(fmt: object) -> bool:
|
||||
return isinstance(fmt, str) and fmt.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
|
||||
|
||||
def realtime_audio_format_object(fmt: object, *, sample_rate_hz: int | None = None) -> dict[str, object]:
|
||||
if isinstance(fmt, str) and fmt.lower() in {"pcm16", "pcm_s16le", "s16le", "pcm"}:
|
||||
payload: dict[str, object] = {"type": "audio/pcm"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "pcm_f32le":
|
||||
payload = {"type": "audio/pcm_f32le"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "g711_ulaw":
|
||||
payload = {"type": "audio/g711_ulaw"}
|
||||
elif isinstance(fmt, str) and fmt.lower() == "g711_alaw":
|
||||
payload = {"type": "audio/g711_alaw"}
|
||||
else:
|
||||
payload = {"type": "audio/wav"}
|
||||
if sample_rate_hz is not None:
|
||||
payload["rate"] = int(sample_rate_hz)
|
||||
return payload
|
||||
|
||||
|
||||
def validate_realtime_session_audio_formats(session_payload: Mapping[str, object]) -> str | None:
|
||||
audio_config = session_payload.get("audio")
|
||||
input_format: object = session_payload.get("input_audio_format")
|
||||
if input_format is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
input_format = audio_input.get("format")
|
||||
parsed_input, _ = parse_realtime_audio_format(input_format)
|
||||
if input_format is not None and not (
|
||||
isinstance(parsed_input, str) and parsed_input.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported input_audio_format: {input_format}"
|
||||
|
||||
output_format: object = session_payload.get("output_audio_format") or session_payload.get("response_format")
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
parsed_output, _ = parse_realtime_audio_format(output_format)
|
||||
if output_format is not None and not (
|
||||
isinstance(parsed_output, str) and parsed_output.lower() in REALTIME_OUTPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported output_audio_format: {output_format}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_realtime_response_audio_formats(response_payload: Mapping[str, object]) -> str | None:
|
||||
output_format: object = response_payload.get("output_audio_format") or response_payload.get("response_format")
|
||||
audio_config = response_payload.get("audio")
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
parsed_output, _ = parse_realtime_audio_format(output_format)
|
||||
if output_format is not None and not (
|
||||
isinstance(parsed_output, str) and parsed_output.lower() in REALTIME_OUTPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported output_audio_format: {output_format}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_conversation_item_audio_formats(item: object) -> str | None:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
return None
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
if part.get("type") not in {"input_audio", "audio"}:
|
||||
continue
|
||||
raw_format = part.get("format")
|
||||
parsed_format, _ = parse_realtime_audio_format(raw_format)
|
||||
if raw_format is not None and not (
|
||||
isinstance(parsed_format, str) and parsed_format.lower() in REALTIME_INPUT_AUDIO_FORMATS
|
||||
):
|
||||
return f"Unsupported input_audio format in conversation.item.create: {raw_format}"
|
||||
return None
|
||||
|
||||
|
||||
def apply_realtime_session_defaults(
|
||||
defaults: RealtimeInputDefaults,
|
||||
session_payload: Mapping[str, object],
|
||||
) -> RealtimeInputDefaults:
|
||||
"""Derive the wire defaults a Realtime ``session`` object declares."""
|
||||
input_format: object = session_payload.get("input_audio_format")
|
||||
audio_config = session_payload.get("audio")
|
||||
if input_format is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
input_format = audio_input.get("format")
|
||||
input_format, input_rate = parse_realtime_audio_format(input_format)
|
||||
# Any: heterogeneous field values splatted into ``dataclasses.replace`` below.
|
||||
updates: dict[str, Any] = {}
|
||||
if isinstance(input_format, str) and input_format.lower() in REALTIME_INPUT_AUDIO_FORMATS:
|
||||
updates["input_audio_format"] = input_format
|
||||
output_format: object = session_payload.get("output_audio_format") or session_payload.get("response_format")
|
||||
output_rate_raw: object | None = None
|
||||
if output_format is None and isinstance(audio_config, dict):
|
||||
audio_output = audio_config.get("output")
|
||||
if isinstance(audio_output, dict):
|
||||
output_format = audio_output.get("format")
|
||||
output_rate_raw = audio_output.get("sample_rate_hz") or audio_output.get("sample_rate")
|
||||
output_format, output_rate = parse_realtime_audio_format(output_format)
|
||||
if output_rate is None and isinstance(output_rate_raw, int | float) and output_rate_raw > 0:
|
||||
output_rate = int(output_rate_raw)
|
||||
if isinstance(output_format, str) and output_format.lower() in REALTIME_OUTPUT_AUDIO_FORMATS:
|
||||
updates["output_audio_format"] = realtime_output_format(output_format)
|
||||
sample_rate = session_payload.get("sample_rate_hz") or session_payload.get("sample_rate")
|
||||
if sample_rate is None and isinstance(audio_config, dict):
|
||||
audio_input = audio_config.get("input")
|
||||
if isinstance(audio_input, dict):
|
||||
sample_rate = audio_input.get("sample_rate_hz") or audio_input.get("sample_rate")
|
||||
if sample_rate is None:
|
||||
sample_rate = input_rate
|
||||
if isinstance(sample_rate, int | float) and sample_rate > 0:
|
||||
updates["input_sample_rate_hz"] = int(sample_rate)
|
||||
if isinstance(output_rate, int | float) and output_rate > 0:
|
||||
updates["output_sample_rate_hz"] = int(output_rate)
|
||||
overlap_fields = realtime_overlap_fields(session_payload)
|
||||
overlap_silence_rms = overlap_fields.get("overlap_silence_rms")
|
||||
if isinstance(overlap_silence_rms, int | float):
|
||||
updates["overlap_silence_rms"] = max(0.0, float(overlap_silence_rms))
|
||||
return replace(defaults, **updates) if updates else defaults
|
||||
|
||||
|
||||
def realtime_overlap_fields(session_payload: Mapping[str, object]) -> dict[str, object]:
|
||||
fields: dict[str, object] = {}
|
||||
if isinstance(session_payload.get("overlap_policy"), str):
|
||||
fields["overlap_policy"] = session_payload["overlap_policy"]
|
||||
for key in ("overlap_short_ack_ms", "overlap_barge_in_ms", "overlap_silence_rms"):
|
||||
value = session_payload.get(key)
|
||||
if isinstance(value, int | float):
|
||||
fields[key] = value
|
||||
if isinstance(session_payload.get("playback_commit_policy"), str):
|
||||
fields["playback_commit_policy"] = session_payload["playback_commit_policy"]
|
||||
return fields
|
||||
|
||||
|
||||
def json_safe_realtime_payload(payload: Mapping[str, object]) -> dict[str, object]:
|
||||
clean: dict[str, object] = {}
|
||||
for key, value in payload.items():
|
||||
if key == "extra_body":
|
||||
continue
|
||||
if isinstance(value, str | int | float | bool) or value is None:
|
||||
clean[key] = value
|
||||
elif isinstance(value, dict):
|
||||
clean[key] = json_safe_realtime_payload(value)
|
||||
elif isinstance(value, list):
|
||||
clean[key] = [
|
||||
(json_safe_realtime_payload(item) if isinstance(item, dict) else item)
|
||||
for item in value
|
||||
if isinstance(item, str | int | float | bool | dict) or item is None
|
||||
]
|
||||
return clean
|
||||
|
||||
|
||||
def input_audio_transcription_config(session_payload: Mapping[str, object]) -> dict[str, object] | None:
|
||||
transcription = session_payload.get("input_audio_transcription")
|
||||
if isinstance(transcription, dict):
|
||||
return transcription
|
||||
audio_config = session_payload.get("audio")
|
||||
if not isinstance(audio_config, dict):
|
||||
return None
|
||||
audio_input = audio_config.get("input")
|
||||
if not isinstance(audio_input, dict):
|
||||
return None
|
||||
transcription = audio_input.get("transcription")
|
||||
return transcription if isinstance(transcription, dict) else None
|
||||
|
||||
|
||||
def realtime_max_output_tokens(value: object) -> int | None:
|
||||
"""Normalize Realtime max output tokens (``"inf"`` -> ``None``)."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip().lower() in {"inf", "infinity", "unlimited"}:
|
||||
return None
|
||||
if isinstance(value, int) and value > 0:
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
# ---- speech hints ----
|
||||
|
||||
|
||||
def input_explicitly_non_speech(event: Mapping[str, object]) -> bool:
|
||||
for key in ("is_speech", "speech"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, bool):
|
||||
return not value
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
value = vad.get("is_speech")
|
||||
if isinstance(value, bool):
|
||||
return not value
|
||||
probability = vad.get("speech_probability", vad.get("probability"))
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) < 0.5
|
||||
probability = event.get("speech_probability")
|
||||
return isinstance(probability, int | float) and float(probability) < 0.5
|
||||
|
||||
|
||||
def input_looks_like_speech(
|
||||
event: Mapping[str, object],
|
||||
*,
|
||||
audio: object,
|
||||
fmt: object,
|
||||
overlap_silence_rms: float,
|
||||
) -> bool:
|
||||
if input_explicitly_non_speech(event):
|
||||
return False
|
||||
for key in ("is_speech", "speech"):
|
||||
value = event.get(key)
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
probability = vad.get("speech_probability", vad.get("probability"))
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
probability = event.get("speech_probability")
|
||||
if isinstance(probability, int | float):
|
||||
return float(probability) >= 0.5
|
||||
if fmt != "pcm_f32le":
|
||||
return True
|
||||
if isinstance(audio, bytes | bytearray):
|
||||
raw = bytes(audio)
|
||||
elif isinstance(audio, str):
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return True
|
||||
else:
|
||||
return True
|
||||
if len(raw) < 4 or len(raw) % 4 != 0:
|
||||
return True
|
||||
samples = np.frombuffer(raw, dtype=np.float32)
|
||||
if samples.size == 0:
|
||||
return False
|
||||
rms = float(np.sqrt(np.mean(np.square(samples.astype(np.float32)))))
|
||||
threshold = event.get("overlap_silence_rms")
|
||||
if not isinstance(threshold, int | float):
|
||||
vad = event.get("vad")
|
||||
if isinstance(vad, dict):
|
||||
threshold = vad.get("silence_rms")
|
||||
silence_rms = float(threshold) if isinstance(threshold, int | float) else overlap_silence_rms
|
||||
return rms >= max(0.0, silence_rms)
|
||||
|
||||
|
||||
def copy_realtime_input_hints(source: Mapping[str, object], target: dict[str, object]) -> None:
|
||||
for key in REALTIME_INPUT_HINT_KEYS:
|
||||
if key in source:
|
||||
target[key] = source[key]
|
||||
|
||||
|
||||
def validate_realtime_video_frames(video_frames: object, max_slice_nums: object) -> str | None:
|
||||
"""Validate omni-duplex camera frames on input_audio_buffer.append.
|
||||
|
||||
Wire contract matches the official MiniCPM-o duplex loop: one base
|
||||
base64 JPEG per ~1 s audio chunk, optionally followed by that unit's
|
||||
stacked composite tiling the sub-frames captured inside it (at most 2
|
||||
images either way). A caller-supplied ``max_slice_nums`` is rejected rather
|
||||
than silently ignored: slicing is Stage 0's decision here, and Stage 0
|
||||
already applies the official HD suggestion for a stacked unit
|
||||
(``max_slice_nums=[2, 1]``). The wire simply does not let the client choose
|
||||
it.
|
||||
"""
|
||||
if max_slice_nums not in (None, 1):
|
||||
return "max_slice_nums is not selectable on the wire; Stage0 slices stacked units itself"
|
||||
if not isinstance(video_frames, list):
|
||||
return "video_frames must be a list of base64-encoded images"
|
||||
frames = [frame for frame in video_frames if frame is not None]
|
||||
if len(frames) > 2:
|
||||
return "video_frames carries more than 2 frames for one append; send ~1 frame per 1 s chunk"
|
||||
for frame in frames:
|
||||
if not isinstance(frame, str) or not frame:
|
||||
return "video_frames entries must be non-empty base64 strings"
|
||||
if len(frame) > 4_000_000:
|
||||
return "video_frames entry exceeds 4MB base64; reduce capture resolution or JPEG quality"
|
||||
try:
|
||||
header = base64.b64decode(frame[:64] + "=" * (-len(frame[:64]) % 4))
|
||||
except (binascii.Error, ValueError):
|
||||
return "video_frames entries must be valid base64"
|
||||
if not (header.startswith(b"\xff\xd8") or header.startswith(b"\x89PNG")):
|
||||
return "video_frames entries must be JPEG or PNG images"
|
||||
return None
|
||||
|
||||
|
||||
# ---- conversation items ----
|
||||
|
||||
|
||||
def normalize_conversation_item(item: Mapping[str, object]) -> dict[str, object]:
|
||||
normalized = dict(item)
|
||||
normalized.setdefault("id", f"item_{uuid4().hex}")
|
||||
normalized.setdefault("object", "realtime.item")
|
||||
normalized.setdefault("type", "message")
|
||||
normalized.setdefault("status", "completed")
|
||||
if "role" not in normalized and normalized.get("type") == "message":
|
||||
normalized["role"] = "user"
|
||||
if not isinstance(normalized.get("content"), list):
|
||||
normalized["content"] = []
|
||||
return normalized
|
||||
|
||||
|
||||
def text_chars_for_audio_ms_from_marks(
|
||||
audio_end_ms: int,
|
||||
text_len: int,
|
||||
marks: list[object],
|
||||
*,
|
||||
final_ms: object | None = None,
|
||||
) -> int:
|
||||
if text_len <= 0:
|
||||
return 0
|
||||
clean_marks: list[tuple[int, int]] = []
|
||||
for mark in marks:
|
||||
if not isinstance(mark, dict):
|
||||
continue
|
||||
raw_text_chars = mark.get("text_chars")
|
||||
raw_audio_end_ms = mark.get("audio_end_ms", mark.get("audio_ms"))
|
||||
if not isinstance(raw_text_chars, int | float) or not isinstance(raw_audio_end_ms, int | float):
|
||||
continue
|
||||
clean_marks.append((max(0, int(raw_audio_end_ms)), min(text_len, max(0, int(raw_text_chars)))))
|
||||
if not clean_marks:
|
||||
return 0 if audio_end_ms <= 0 else text_len
|
||||
clean_marks.sort(key=lambda item: item[0])
|
||||
audio_end_ms = max(0, int(audio_end_ms))
|
||||
if audio_end_ms <= 0:
|
||||
return 0
|
||||
previous_ms = 0
|
||||
previous_chars = 0
|
||||
for mark_ms, mark_chars in clean_marks:
|
||||
mark_ms = max(previous_ms, mark_ms)
|
||||
mark_chars = max(previous_chars, min(text_len, mark_chars))
|
||||
if audio_end_ms <= mark_ms:
|
||||
if mark_ms <= previous_ms:
|
||||
return mark_chars
|
||||
ratio = (audio_end_ms - previous_ms) / max(1, mark_ms - previous_ms)
|
||||
return int(previous_chars + (mark_chars - previous_chars) * max(0.0, min(1.0, ratio)))
|
||||
previous_ms = mark_ms
|
||||
previous_chars = mark_chars
|
||||
if isinstance(final_ms, int | float) and int(final_ms) > previous_ms:
|
||||
if audio_end_ms >= int(final_ms):
|
||||
return text_len
|
||||
ratio = (audio_end_ms - previous_ms) / max(1, int(final_ms) - previous_ms)
|
||||
return int(previous_chars + (text_len - previous_chars) * max(0.0, min(1.0, ratio)))
|
||||
return text_len if audio_end_ms >= previous_ms else previous_chars
|
||||
|
||||
|
||||
def truncate_realtime_item_content(item: dict[str, object], *, content_index: int, audio_end_ms: int) -> None:
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list) or not content:
|
||||
return
|
||||
index = max(0, int(content_index))
|
||||
if index >= len(content):
|
||||
return
|
||||
part = content[index]
|
||||
if not isinstance(part, dict):
|
||||
return
|
||||
transcript = part.get("transcript")
|
||||
if not isinstance(transcript, str) or not transcript:
|
||||
return
|
||||
marks = part.get("audio_text_marks")
|
||||
if isinstance(marks, list):
|
||||
keep_chars = text_chars_for_audio_ms_from_marks(
|
||||
audio_end_ms,
|
||||
len(transcript),
|
||||
marks,
|
||||
final_ms=part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms"),
|
||||
)
|
||||
part["transcript"] = transcript[:keep_chars].rstrip()
|
||||
return
|
||||
duration_ms = part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms")
|
||||
if isinstance(duration_ms, int | float) and duration_ms > 0:
|
||||
keep_chars = int(len(transcript) * max(0.0, min(1.0, int(audio_end_ms) / float(duration_ms))))
|
||||
part["transcript"] = transcript[:keep_chars].rstrip()
|
||||
elif audio_end_ms <= 0:
|
||||
part["transcript"] = ""
|
||||
|
||||
|
||||
def validate_realtime_item_truncate(item: Mapping[str, object], *, content_index: int, audio_end_ms: int) -> str | None:
|
||||
if item.get("type") != "message" or item.get("role") != "assistant":
|
||||
return "conversation.item.truncate only supports assistant message items"
|
||||
if audio_end_ms < 0:
|
||||
return "conversation.item.truncate requires non-negative audio_end_ms"
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list) or not content:
|
||||
return None
|
||||
index = max(0, int(content_index))
|
||||
if index >= len(content):
|
||||
return f"conversation.item.truncate content_index out of range: {content_index}"
|
||||
part = content[index]
|
||||
if not isinstance(part, dict):
|
||||
return "conversation.item.truncate target content part is invalid"
|
||||
if part.get("type") not in {"audio", "output_audio"}:
|
||||
return "conversation.item.truncate target content part must be audio"
|
||||
duration_ms = part.get("audio_duration_ms") or part.get("duration_ms") or part.get("audio_ms")
|
||||
if isinstance(duration_ms, int | float) and int(duration_ms) >= 0 and audio_end_ms > int(duration_ms):
|
||||
return "conversation.item.truncate audio_end_ms exceeds item audio duration"
|
||||
return None
|
||||
|
||||
|
||||
def input_transcript_from_item(item: Mapping[str, object]) -> str:
|
||||
content = item.get("content")
|
||||
if not isinstance(content, list):
|
||||
return ""
|
||||
parts: list[str] = []
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
for key in ("transcript", "text"):
|
||||
value = part.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
if part.get("type") in {"input_audio", "audio", "audio_transcript", "transcript"}:
|
||||
parts.append(value)
|
||||
break
|
||||
return "".join(parts).strip()
|
||||
|
||||
|
||||
# ---- append / item audio conversion ----
|
||||
|
||||
|
||||
@@ -577,67 +120,21 @@ def build_append_audio(
|
||||
defaults: RealtimeInputDefaults,
|
||||
hints_source: Mapping[str, object] | None = None,
|
||||
) -> AppendAudio:
|
||||
"""Validate, convert (to 16 kHz ``pcm_f32le`` base64) and pack one audio append.
|
||||
|
||||
Speech classification without VAD (``is_speech`` on the command) uses the
|
||||
explicit wire hints and the RMS fallback exactly like the old translator.
|
||||
"""
|
||||
event_id = cast("str", event.get("event_id")) if isinstance(event.get("event_id"), str) else None
|
||||
audio = event.get("audio") or event.get("delta")
|
||||
fmt, format_rate = parse_realtime_audio_format(
|
||||
event.get("format") or event.get("input_audio_format") or defaults.input_audio_format
|
||||
)
|
||||
sample_rate_hz = (
|
||||
event.get("sample_rate_hz") or event.get("sample_rate") or format_rate or defaults.input_sample_rate_hz
|
||||
)
|
||||
if not is_supported_realtime_input_format(fmt):
|
||||
raise DuplexCommandError(
|
||||
f"Unsupported input_audio_format: {fmt}",
|
||||
code="unsupported_audio_format",
|
||||
event_id=event_id,
|
||||
)
|
||||
"""Decode one audio append (shared codec) and pack it as the duplex command."""
|
||||
try:
|
||||
audio, fmt, sample_rate_hz = convert_input_audio_with_rate(
|
||||
audio,
|
||||
fmt,
|
||||
sample_rate_hz=sample_rate_hz if isinstance(sample_rate_hz, int | float) else None,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise DuplexCommandError(str(exc), code="bad_event", event_id=event_id) from exc
|
||||
hints: dict[str, object] = {}
|
||||
if hints_source is not None:
|
||||
copy_realtime_input_hints(hints_source, hints)
|
||||
copy_realtime_input_hints(event, hints)
|
||||
looks_like_speech = input_looks_like_speech(
|
||||
{**(hints_source or {}), **event},
|
||||
audio=audio,
|
||||
fmt=fmt,
|
||||
overlap_silence_rms=defaults.overlap_silence_rms,
|
||||
)
|
||||
video_frames: tuple[str, ...] = ()
|
||||
raw_frames = event.get("video_frames")
|
||||
if raw_frames is not None:
|
||||
frames_error = validate_realtime_video_frames(raw_frames, event.get("max_slice_nums"))
|
||||
if frames_error is not None:
|
||||
raise DuplexCommandError(frames_error, code="invalid_video_frames", event_id=event_id)
|
||||
if isinstance(raw_frames, list):
|
||||
video_frames = tuple(frame for frame in raw_frames if isinstance(frame, str) and frame)
|
||||
duration_ms = hints.get("duration_ms", hints.get("audio_duration_ms"))
|
||||
audio_end_ms = hints.get("audio_end_ms")
|
||||
try:
|
||||
audio_bytes = base64.b64decode(audio, validate=True) if isinstance(audio, str) and audio else b""
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise DuplexCommandError("input audio is not valid base64", code="bad_audio", event_id=event_id) from exc
|
||||
decoded = decode_audio_append(event, defaults=defaults, hints_source=hints_source)
|
||||
except RealtimeProtocolError as exc:
|
||||
raise DuplexCommandError(str(exc), code=exc.code, event_id=exc.event_id) from exc
|
||||
return AppendAudio(
|
||||
event_id=event_id,
|
||||
audio=audio_bytes,
|
||||
format=str(fmt),
|
||||
sample_rate_hz=int(sample_rate_hz) if isinstance(sample_rate_hz, int | float) else None,
|
||||
is_speech=looks_like_speech,
|
||||
video_frames=video_frames,
|
||||
duration_ms=int(duration_ms) if isinstance(duration_ms, int | float) else None,
|
||||
audio_end_ms=int(audio_end_ms) if isinstance(audio_end_ms, int | float) else None,
|
||||
hints=hints,
|
||||
event_id=decoded.event_id,
|
||||
audio=decoded.audio,
|
||||
format=decoded.format,
|
||||
sample_rate_hz=decoded.sample_rate_hz,
|
||||
is_speech=decoded.is_speech,
|
||||
video_frames=decoded.video_frames,
|
||||
duration_ms=decoded.duration_ms,
|
||||
audio_end_ms=decoded.audio_end_ms,
|
||||
hints=decoded.hints,
|
||||
)
|
||||
|
||||
|
||||
@@ -664,14 +161,9 @@ def translate_realtime_command(
|
||||
if event_type == "session.update":
|
||||
session = payload.get("session")
|
||||
session_payload: Mapping[str, object] = session if isinstance(session, dict) else payload
|
||||
format_error = validate_realtime_session_audio_formats(session_payload)
|
||||
if format_error is not None:
|
||||
raise DuplexCommandError(format_error, code="unsupported_audio_format", event_id=event_id)
|
||||
from vllm_omni.engine.duplex.turn_detection import validate_realtime_turn_detection
|
||||
|
||||
turn_detection_error = validate_realtime_turn_detection(session_payload)
|
||||
if turn_detection_error is not None:
|
||||
raise DuplexCommandError(turn_detection_error, code="unsupported_turn_detection", event_id=event_id)
|
||||
rejection = validate_session_payload(session_payload, capabilities=DUPLEX_REALTIME_CAPABILITIES)
|
||||
if rejection is not None:
|
||||
raise DuplexCommandError(rejection.message, code=rejection.code, event_id=event_id)
|
||||
return UpdateSession(event_id=event_id, patch=dict(session_payload))
|
||||
|
||||
if event_type == "conversation.item.create":
|
||||
@@ -855,7 +347,10 @@ def translate_realtime_command(
|
||||
raise DuplexCommandError(f"Unknown duplex event type: {event_type}", code="unknown_event", event_id=event_id)
|
||||
|
||||
|
||||
#: Names this module used to define, re-exported so existing importers keep
|
||||
#: working. The canonical definitions live in ``vllm_omni.protocol.realtime``.
|
||||
__all__ = [
|
||||
"DUPLEX_REALTIME_CAPABILITIES",
|
||||
"REALTIME_INPUT_AUDIO_FORMATS",
|
||||
"REALTIME_INPUT_HINT_KEYS",
|
||||
"REALTIME_OUTPUT_AUDIO_FORMATS",
|
||||
|
||||
@@ -15,6 +15,12 @@ carries the input-side bookkeeping the old input translator kept (input buffer
|
||||
flags, conversation items, response-id fallbacks); the ``resolve_*`` /
|
||||
``note_*`` helpers give the runner the same behaviour for the corresponding
|
||||
commands.
|
||||
|
||||
What is *not* here is the model- and runtime-agnostic half of the codec ---
|
||||
audio format negotiation, conversation-item shape and truncation, transcript
|
||||
extraction, audio conversion. That lives in ``vllm_omni.protocol.realtime`` so
|
||||
a non-duplex Realtime surface can use it without the duplex session; this
|
||||
module is the duplex consumer of it (RFC #6592 P0a).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,7 +30,6 @@ from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from uuid import uuid4
|
||||
|
||||
from vllm_omni.engine.duplex.audio import convert_output_audio
|
||||
from vllm_omni.engine.duplex.commands import (
|
||||
AppendAudio,
|
||||
CancelResponse,
|
||||
@@ -74,10 +79,11 @@ from vllm_omni.engine.duplex.events import (
|
||||
TranscriptDone,
|
||||
error_event,
|
||||
)
|
||||
from vllm_omni.engine.duplex.realtime_commands import (
|
||||
from vllm_omni.engine.duplex.realtime_commands import build_append_audio
|
||||
from vllm_omni.protocol.duplex import (
|
||||
RealtimeInputDefaults,
|
||||
apply_realtime_session_defaults,
|
||||
build_append_audio,
|
||||
convert_output_audio,
|
||||
copy_realtime_input_hints,
|
||||
input_looks_like_speech,
|
||||
input_transcript_from_item,
|
||||
@@ -321,7 +327,7 @@ def _response_done_output_item(
|
||||
)
|
||||
if text:
|
||||
content.append(_response_item_text_content_part(text=text))
|
||||
item = {
|
||||
item: dict[str, object] = {
|
||||
"id": item_id,
|
||||
"object": "realtime.item",
|
||||
"type": "message",
|
||||
@@ -790,7 +796,7 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
item_id = _response_item_id(state, response_id)
|
||||
modalities = event.get("modalities")
|
||||
has_audio_modality = not isinstance(modalities, list) or "audio" in modalities
|
||||
item = {
|
||||
item: dict[str, object] = {
|
||||
"id": item_id,
|
||||
"object": "realtime.item",
|
||||
"type": "message",
|
||||
@@ -894,13 +900,13 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
item_id = (
|
||||
event_item_id if isinstance(event_item_id, str) and event_item_id else _pop_pending_commit_item_id(state)
|
||||
)
|
||||
item = state.conversation_items.get(item_id)
|
||||
events = []
|
||||
if item is None:
|
||||
committed_item = state.conversation_items.get(item_id)
|
||||
commit_events: list[DuplexEvent] = []
|
||||
if committed_item is None:
|
||||
message = event.get("message")
|
||||
no_response = event.get("no_response") is True
|
||||
is_speech = event.get("is_speech")
|
||||
item = {
|
||||
created_commit_item: dict[str, object] = {
|
||||
"id": item_id,
|
||||
"object": "realtime.item",
|
||||
"type": "message",
|
||||
@@ -912,17 +918,18 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
else _user_item_content_from_duplex_message(message)
|
||||
),
|
||||
}
|
||||
state.conversation_items[item_id] = item
|
||||
events.extend(_conversation_item_added_events(state, item))
|
||||
item["status"] = "completed"
|
||||
events.append(
|
||||
committed_item = created_commit_item
|
||||
state.conversation_items[item_id] = committed_item
|
||||
commit_events.extend(_conversation_item_added_events(state, committed_item))
|
||||
committed_item["status"] = "completed"
|
||||
commit_events.append(
|
||||
InputCommitted(previous_item_id=_previous_item_id(state, item_id), item_id=item_id, details=event)
|
||||
)
|
||||
transcription_event = _input_audio_transcription_completed_event(item_id, item)
|
||||
transcription_event = _input_audio_transcription_completed_event(item_id, committed_item)
|
||||
if transcription_event is not None:
|
||||
events.append(transcription_event)
|
||||
events.append(_conversation_item_done_event(state, item))
|
||||
return events
|
||||
commit_events.append(transcription_event)
|
||||
commit_events.append(_conversation_item_done_event(state, committed_item))
|
||||
return commit_events
|
||||
if event_type == "input.cancelled":
|
||||
return [InputCleared()]
|
||||
if event_type == "audio.cancelled":
|
||||
@@ -939,15 +946,25 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
if not isinstance(response_id, str) or not response_id:
|
||||
return events
|
||||
if response_is_done(state, response_id):
|
||||
# Generation may finish long before the client drains its audio.
|
||||
# A later barge-in still needs to stop that queued playback, but
|
||||
# must not produce a second response.done for the completed turn.
|
||||
playback = event.get("playback")
|
||||
if (
|
||||
not events
|
||||
and isinstance(playback, Mapping)
|
||||
and _int_or(playback.get("sent_ms")) > _int_or(playback.get("committed_ms"))
|
||||
):
|
||||
events.append(OutputAudioCleared(response_id=response_id))
|
||||
return events
|
||||
committed_ms = event.get("committed_ms")
|
||||
if isinstance(committed_ms, int | float):
|
||||
item_id = _response_item_id(state, response_id)
|
||||
committed_audio_ms = max(0, int(committed_ms))
|
||||
state.item_truncation_cursors[item_id] = (0, committed_audio_ms)
|
||||
item = state.conversation_items.get(item_id)
|
||||
if item is not None:
|
||||
truncate_realtime_item_content(item, content_index=0, audio_end_ms=committed_audio_ms)
|
||||
cancelled_item = state.conversation_items.get(item_id)
|
||||
if cancelled_item is not None:
|
||||
truncate_realtime_item_content(cancelled_item, content_index=0, audio_end_ms=committed_audio_ms)
|
||||
events.extend(_realtime_audio_done_events(state, event, response_id))
|
||||
events.extend(
|
||||
_realtime_response_terminal_events(
|
||||
@@ -962,48 +979,49 @@ def _project(state: RealtimeProjectionState, event: dict[str, object]) -> list[D
|
||||
state.active_response_id = None
|
||||
return events
|
||||
if event_type == "conversation.item.created":
|
||||
item = event.get("item")
|
||||
if isinstance(item, dict) and isinstance(item.get("id"), str):
|
||||
item_id = str(item["id"])
|
||||
already_known = item_id in state.conversation_items
|
||||
state.conversation_items[item_id] = item
|
||||
created_raw = event.get("item")
|
||||
if isinstance(created_raw, dict) and isinstance(created_raw.get("id"), str):
|
||||
created_item_id = str(created_raw["id"])
|
||||
created_item = cast("dict[str, object]", created_raw)
|
||||
already_known = created_item_id in state.conversation_items
|
||||
state.conversation_items[created_item_id] = created_item
|
||||
if already_known:
|
||||
if item.get("status") == "completed":
|
||||
return [_conversation_item_done_event(state, item)]
|
||||
if created_item.get("status") == "completed":
|
||||
return [_conversation_item_done_event(state, created_item)]
|
||||
return []
|
||||
events = _conversation_item_added_events(state, item)
|
||||
if item.get("status") == "completed":
|
||||
events.append(_conversation_item_done_event(state, item))
|
||||
return events
|
||||
return [ItemCreated(item=item if isinstance(item, Mapping) else {})]
|
||||
created_events = _conversation_item_added_events(state, created_item)
|
||||
if created_item.get("status") == "completed":
|
||||
created_events.append(_conversation_item_done_event(state, created_item))
|
||||
return created_events
|
||||
return [ItemCreated(item=created_raw if isinstance(created_raw, Mapping) else {})]
|
||||
if event_type == "conversation.item.deleted":
|
||||
item_id = event.get("item_id")
|
||||
if isinstance(item_id, str):
|
||||
_remove_conversation_item(state, item_id)
|
||||
return [ItemDeleted(item_id=_str_or_none(item_id), details=event)]
|
||||
deleted_item_id = event.get("item_id")
|
||||
if isinstance(deleted_item_id, str):
|
||||
_remove_conversation_item(state, deleted_item_id)
|
||||
return [ItemDeleted(item_id=_str_or_none(deleted_item_id), details=event)]
|
||||
if event_type == "conversation.item.truncated":
|
||||
item_id = event.get("item_id")
|
||||
truncated_item_id = event.get("item_id")
|
||||
audio_end_ms = event.get("audio_end_ms")
|
||||
content_index = event.get("content_index", 0)
|
||||
if isinstance(item_id, str):
|
||||
item = state.conversation_items.get(item_id)
|
||||
if item is not None:
|
||||
if isinstance(truncated_item_id, str):
|
||||
truncated_item = state.conversation_items.get(truncated_item_id)
|
||||
if truncated_item is not None:
|
||||
truncate_realtime_item_content(
|
||||
item,
|
||||
truncated_item,
|
||||
content_index=_int_or(content_index),
|
||||
audio_end_ms=_int_or(audio_end_ms),
|
||||
)
|
||||
return [
|
||||
ItemTruncated(
|
||||
item_id=_str_or_none(item_id),
|
||||
item_id=_str_or_none(truncated_item_id),
|
||||
content_index=_int_or(content_index),
|
||||
audio_end_ms=_int_or(audio_end_ms),
|
||||
details=event,
|
||||
)
|
||||
]
|
||||
if event_type == "conversation.item.retrieved":
|
||||
item = event.get("item")
|
||||
return [ItemRetrieved(item=item if isinstance(item, Mapping) else {})]
|
||||
retrieved_item = event.get("item")
|
||||
return [ItemRetrieved(item=retrieved_item if isinstance(retrieved_item, Mapping) else {})]
|
||||
if event_type == "response.output_item.done":
|
||||
response_id = event.get("response_id")
|
||||
return _realtime_response_terminal_events(
|
||||
@@ -1038,7 +1056,7 @@ def _function_call_done_events(state: RealtimeProjectionState, event: dict[str,
|
||||
arguments = str(arguments)
|
||||
response_id = f"resp_{uuid4().hex}"
|
||||
item_id = f"item_{uuid4().hex}"
|
||||
item = {
|
||||
item: dict[str, object] = {
|
||||
"id": item_id,
|
||||
"object": "realtime.item",
|
||||
"type": "function_call",
|
||||
@@ -1312,7 +1330,11 @@ def resolve_cancel_response(state: RealtimeProjectionState, command: CancelRespo
|
||||
def resolve_clear_output_audio(state: RealtimeProjectionState, command: ClearOutputAudio) -> ResolvedControl:
|
||||
payload: dict[str, object] = {"type": "output_audio_buffer.clear", "reason": "output_audio_buffer.clear"}
|
||||
response_id = command.response_id or state.active_response_id or state.last_response_id
|
||||
if response_is_done(state, response_id):
|
||||
# A completed response can still own queued playback. Clear the latest
|
||||
# response in the engine, while keeping late clears away from newer turns.
|
||||
if response_is_done(state, response_id) and (
|
||||
state.active_response_id is not None or response_id != state.last_response_id
|
||||
):
|
||||
return ResolvedControl(payloads=[], events=[OutputAudioCleared(response_id=_str_or_none(response_id))])
|
||||
if isinstance(response_id, str) and response_id:
|
||||
payload["response_id"] = response_id
|
||||
@@ -1354,7 +1376,6 @@ def resolve_truncate_item(state: RealtimeProjectionState, command: TruncateItem)
|
||||
payloads=[], events=[error_event("bad_event", truncate_error, event_id=command.event_id)]
|
||||
)
|
||||
state.item_truncation_cursors[command.item_id] = (command.content_index, command.audio_end_ms)
|
||||
truncate_realtime_item_content(item, content_index=command.content_index, audio_end_ms=command.audio_end_ms)
|
||||
ack_payload: dict[str, object] = {
|
||||
"type": "playback.ack",
|
||||
"item_id": command.item_id,
|
||||
@@ -1425,7 +1446,7 @@ def resolve_create_item(state: RealtimeProjectionState, command: CreateItem) ->
|
||||
],
|
||||
)
|
||||
ack_events = register_user_item(state, item) if item_type == "message" and role == "user" else []
|
||||
signal_payload = {
|
||||
signal_payload: dict[str, object] = {
|
||||
"type": "turn.signal",
|
||||
"event": "conversation.item.create",
|
||||
"payload": {"item": item},
|
||||
@@ -1438,12 +1459,15 @@ def resolve_create_item(state: RealtimeProjectionState, command: CreateItem) ->
|
||||
if not isinstance(content, list):
|
||||
return ResolvedControl(payloads=[], events=ack_events)
|
||||
text_chunks: list[str] = []
|
||||
image_parts: list[Mapping[str, object]] = []
|
||||
audio_payloads: list[dict[str, object]] = []
|
||||
for part in content:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
if part.get("type") in {"input_text", "text"} and isinstance(part.get("text"), str):
|
||||
text_chunks.append(str(part["text"]))
|
||||
if part.get("type") == "input_image":
|
||||
image_parts.append(part)
|
||||
if part.get("type") in {"input_audio", "audio"}:
|
||||
audio = part.get("audio") or part.get("data")
|
||||
if not isinstance(audio, str) or not audio:
|
||||
@@ -1488,12 +1512,28 @@ def resolve_create_item(state: RealtimeProjectionState, command: CreateItem) ->
|
||||
}
|
||||
if transcript:
|
||||
commit_payload["transcript"] = transcript
|
||||
return ResolvedControl(payloads=[*audio_payloads, commit_payload], events=ack_events)
|
||||
if not text_chunks:
|
||||
payloads: list[dict[str, object]] = []
|
||||
if image_parts:
|
||||
# The audio leaves as buffered appends that the commit seals, and
|
||||
# that commit registers *this* item id against the spoken message.
|
||||
# Images cannot ride it: the commit would overwrite them. So they
|
||||
# travel as their own item, stored ahead of the audio describing
|
||||
# them, under an id derived from the one the client named.
|
||||
image_item = dict(item)
|
||||
image_item["id"] = f"{item_id}_image"
|
||||
image_item["status"] = "completed"
|
||||
image_item["content"] = list(image_parts)
|
||||
payloads.append({**signal_payload, "payload": {"item": image_item}})
|
||||
payloads.extend([*audio_payloads, commit_payload])
|
||||
return ResolvedControl(payloads=payloads, events=ack_events)
|
||||
if not text_chunks and not image_parts:
|
||||
return ResolvedControl(payloads=[], events=ack_events)
|
||||
text_item = dict(item)
|
||||
text_item["status"] = "completed"
|
||||
signal_payload["payload"] = {"item": text_item}
|
||||
# An image is content in its own right, not a decoration on text. Dropping
|
||||
# the payload here would still ack the item to the client, so the picture
|
||||
# would be silently missing from every prompt that followed.
|
||||
stored_item = dict(item)
|
||||
stored_item["status"] = "completed"
|
||||
signal_payload["payload"] = {"item": stored_item}
|
||||
return ResolvedControl(payloads=[signal_payload], events=ack_events)
|
||||
|
||||
|
||||
|
||||
@@ -53,8 +53,11 @@ class AppendAttempt:
|
||||
retained_committed_payload: dict[str, object] | None
|
||||
#: Response reserved before submission, to be failed if submission does not happen.
|
||||
precreated_response_id: str | None
|
||||
#: Commits timing state once the runtime accepts the append (before any
|
||||
#: returned output event can clear the continuation chain).
|
||||
on_append_accepted: Callable[[float], None] | None = None
|
||||
#: Last chance to call the append off, checked once the predecessor is done.
|
||||
before_append: Callable[[], bool] | None
|
||||
before_append: Callable[[], bool] | None = None
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Compensation #
|
||||
@@ -107,8 +110,7 @@ class AppendAttempt:
|
||||
try:
|
||||
predecessor_ok = await predecessor
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if current is not None and current.cancelling():
|
||||
if helpers.task_is_cancelling(asyncio.current_task()):
|
||||
raise
|
||||
predecessor_ok = False
|
||||
except Exception:
|
||||
@@ -140,6 +142,7 @@ class AppendAttempt:
|
||||
),
|
||||
final=self.final,
|
||||
expected_epoch=self.epoch,
|
||||
on_append_accepted=self.on_append_accepted,
|
||||
)
|
||||
if append_ok:
|
||||
model_state.context_locked = True
|
||||
@@ -155,8 +158,10 @@ class AppendAttempt:
|
||||
self.ctx.run.runtime_closed = True
|
||||
return False
|
||||
if not emitted_response and session.epoch == self.epoch:
|
||||
if session.active_request_id == helpers.stage0_request_id(session, self.epoch):
|
||||
session.clear_request(self.request_id)
|
||||
# Only if the session still points at this append's request:
|
||||
# ``clear_request`` compares before it clears, and the id
|
||||
# carries a turn suffix when the core request is not resumable.
|
||||
session.clear_request(self.request_id)
|
||||
if self.final:
|
||||
self.out.emit_events([session.signal_turn(DuplexTurnEventType.USER_STARTED.value)])
|
||||
return append_ok
|
||||
|
||||
@@ -113,6 +113,19 @@ class SessionControl:
|
||||
except ValueError as exc:
|
||||
self._out.emit_error("bad_audio", str(exc))
|
||||
return None
|
||||
if result.speech_started or result.speech_stopped:
|
||||
logger.info(
|
||||
"Duplex VAD session=%s started=%s stopped=%s active=%s probability=%.3f "
|
||||
"start_ms=%s end_ms=%s commit=%s",
|
||||
self._ctx.session.session_id,
|
||||
result.speech_started,
|
||||
result.speech_stopped,
|
||||
result.speech_active,
|
||||
result.speech_probability,
|
||||
result.audio_start_ms,
|
||||
result.audio_end_ms,
|
||||
result.should_commit,
|
||||
)
|
||||
apply_turn_detection_result(event, result)
|
||||
return result
|
||||
|
||||
@@ -310,6 +323,47 @@ class SessionControl:
|
||||
name="duplex-continue",
|
||||
)
|
||||
return
|
||||
item_payload = item if isinstance(item, dict) else None
|
||||
raw_parts = item_payload.get("content", []) if item_payload is not None else []
|
||||
parts: list[object] = [part for part in raw_parts] if isinstance(raw_parts, list) else []
|
||||
images = [p for p in parts if isinstance(p, dict) and p.get("type") == "input_image"]
|
||||
if images:
|
||||
if item_payload is None or item_payload.get("role") != "user":
|
||||
self._out.emit_error("invalid_image", "input_image is supported only in user messages")
|
||||
return
|
||||
if not session.capabilities.supports_image_input:
|
||||
self._out.emit_error("unsupported", "This model does not support input_image conversation items")
|
||||
return
|
||||
from vllm_omni.engine.duplex.realtime_commands import validate_realtime_video_frames
|
||||
|
||||
urls: list[str] = []
|
||||
for part in images:
|
||||
url = part.get("image_url")
|
||||
if not isinstance(url, str) or not url.startswith(
|
||||
("data:image/jpeg;base64,", "data:image/png;base64,")
|
||||
):
|
||||
self._out.emit_error("invalid_image", "input_image requires a JPEG or PNG base64 data URL")
|
||||
return
|
||||
error = validate_realtime_video_frames([url.split(",", 1)[1]], None)
|
||||
if error:
|
||||
self._out.emit_error("invalid_image", error)
|
||||
return
|
||||
urls.append(url)
|
||||
existing: list[str] = []
|
||||
for history_message in session.history:
|
||||
content = history_message.get("content")
|
||||
if not isinstance(content, list):
|
||||
continue
|
||||
for part in content:
|
||||
if not isinstance(part, dict) or part.get("type") != "image_url":
|
||||
continue
|
||||
image_url = part.get("image_url")
|
||||
nested_url = image_url.get("url") if isinstance(image_url, dict) else None
|
||||
if isinstance(nested_url, str):
|
||||
existing.append(nested_url)
|
||||
if len(existing) + len(urls) > 8 or sum(map(len, existing + urls)) > 4 * 1024 * 1024:
|
||||
self._out.emit_error("input_backpressure", "Image context exceeds 8 images or 4 MiB; delete old items")
|
||||
return
|
||||
message = realtime_item_to_history_message(item)
|
||||
item_id = item.get("id") if isinstance(item, dict) else None
|
||||
if message is not None:
|
||||
|
||||
@@ -20,7 +20,7 @@ import time
|
||||
from collections.abc import Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from types import MappingProxyType
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from uuid import uuid4
|
||||
|
||||
from vllm_omni.engine.duplex.config import (
|
||||
@@ -53,6 +53,42 @@ def _default_lease() -> DuplexLeaseState:
|
||||
return DuplexLeaseState(config=DuplexLeaseConfig(), generation=0, last_activity=time.monotonic())
|
||||
|
||||
|
||||
def _object_dict(**fields: object) -> dict[str, object]:
|
||||
return dict(fields)
|
||||
|
||||
|
||||
def _as_int(value: object, default: int = 0) -> int:
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
return int(value)
|
||||
return default
|
||||
|
||||
|
||||
def _as_optional_int(value: object) -> int | None:
|
||||
if value is None or isinstance(value, bool):
|
||||
return None
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _copy_mapping(value: object) -> dict[str, object] | None:
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
return {str(key): item for key, item in value.items()}
|
||||
|
||||
|
||||
def _copy_list(value: object) -> list[object] | None:
|
||||
if not isinstance(value, list):
|
||||
return None
|
||||
return [item for item in value]
|
||||
|
||||
|
||||
@dataclass
|
||||
class InputBufferState:
|
||||
commit_seq: int = 0
|
||||
@@ -624,7 +660,7 @@ class DuplexEngineSession:
|
||||
input_audio_part["transcript"] = transcript
|
||||
self._bind_active_response_to_input_commit(self._input.commit_seq + 1)
|
||||
self._input.commit_seq += 1
|
||||
message = {"role": "user", "content": [input_audio_part]}
|
||||
message = _object_dict(role="user", content=[input_audio_part])
|
||||
if transcript:
|
||||
message["transcript"] = transcript
|
||||
self._conversation.messages.append(message)
|
||||
@@ -694,7 +730,7 @@ class DuplexEngineSession:
|
||||
self._response.stage_metric_tpot_weighted_ms.clear()
|
||||
self._response.stage_metric_tpot_weight.clear()
|
||||
|
||||
def stash_stage_metrics(self, stage_metrics: Mapping[object, object] | None) -> None:
|
||||
def stash_stage_metrics(self, stage_metrics: Mapping[Any, Any] | None) -> None:
|
||||
"""Hold a stage snapshot until a response exists to attribute it to.
|
||||
|
||||
A stage that hands its output to the next stage instead of the client
|
||||
@@ -706,9 +742,10 @@ class DuplexEngineSession:
|
||||
"""
|
||||
if not isinstance(stage_metrics, Mapping):
|
||||
return
|
||||
snapshot = {
|
||||
str(stage_id): dict(values) for stage_id, values in stage_metrics.items() if isinstance(values, Mapping)
|
||||
}
|
||||
snapshot: dict[str, dict[str, object]] = {}
|
||||
for stage_id, values in stage_metrics.items():
|
||||
if isinstance(values, Mapping):
|
||||
snapshot[str(stage_id)] = {str(key): value for key, value in values.items()}
|
||||
if not snapshot:
|
||||
return
|
||||
if self.active_response_id is not None:
|
||||
@@ -718,7 +755,7 @@ class DuplexEngineSession:
|
||||
|
||||
def accumulate_response_stage_metrics(
|
||||
self,
|
||||
stage_metrics: Mapping[object, object] | None,
|
||||
stage_metrics: Mapping[Any, Any] | None,
|
||||
) -> dict[str, dict[str, object]]:
|
||||
if self.active_response_id is None:
|
||||
return copy.deepcopy(self._response.stage_metrics)
|
||||
@@ -762,7 +799,9 @@ class DuplexEngineSession:
|
||||
for name in additive_fields:
|
||||
value = raw_values.get(name)
|
||||
if isinstance(value, int | float) and not isinstance(value, bool):
|
||||
current[name] = current.get(name, 0) + value
|
||||
previous = current.get(name, 0)
|
||||
addend = previous if isinstance(previous, int | float) and not isinstance(previous, bool) else 0
|
||||
current[name] = addend + value
|
||||
for name in first_positive_fields:
|
||||
value = raw_values.get(name)
|
||||
current_value = current.get(name)
|
||||
@@ -776,7 +815,8 @@ class DuplexEngineSession:
|
||||
for list_name, mean_name in interval_fields:
|
||||
values = raw_values.get(list_name)
|
||||
if isinstance(values, list):
|
||||
combined = list(current.get(list_name, []))
|
||||
existing = current.get(list_name, [])
|
||||
combined = list(existing) if isinstance(existing, list) else []
|
||||
combined.extend(
|
||||
value for value in values if isinstance(value, int | float) and not isinstance(value, bool)
|
||||
)
|
||||
@@ -805,7 +845,7 @@ class DuplexEngineSession:
|
||||
|
||||
def replace_response_stage_metric_snapshots(
|
||||
self,
|
||||
stage_metrics: Mapping[object, object] | None,
|
||||
stage_metrics: Mapping[Any, Any] | None,
|
||||
) -> dict[str, dict[str, object]]:
|
||||
"""Merge cumulative chat snapshots by replacing each stage's latest value."""
|
||||
if self.active_response_id is None or not isinstance(stage_metrics, Mapping):
|
||||
@@ -839,8 +879,12 @@ class DuplexEngineSession:
|
||||
*,
|
||||
text_chars: int | None = None,
|
||||
audio_text_marks: list[dict[str, object]] | None = None,
|
||||
text_requires_complete_audio: bool = False,
|
||||
audio_complete: bool = False,
|
||||
) -> None:
|
||||
playback = self._playback.current
|
||||
playback.text_requires_complete_audio |= text_requires_complete_audio
|
||||
playback.audio_complete |= audio_complete
|
||||
if duration_ms is not None:
|
||||
playback.generated_ms = max(playback.generated_ms, duration_ms)
|
||||
playback.sent_ms = max(playback.sent_ms, duration_ms)
|
||||
@@ -925,9 +969,9 @@ class DuplexEngineSession:
|
||||
response_input_commit_seq = self.input_commit_seq
|
||||
response_history_is_late = self.input_commit_seq > response_input_commit_seq
|
||||
assistant_text = "".join(self._response.assistant_text_buffer).strip()
|
||||
message = None
|
||||
message: dict[str, object] | None = None
|
||||
if assistant_text:
|
||||
self._conversation.last_assistant_full_message = {"role": "assistant", "content": assistant_text}
|
||||
self._conversation.last_assistant_full_message = _object_dict(role="assistant", content=assistant_text)
|
||||
self._conversation.last_assistant_audio_text_marks = list(self._response.assistant_audio_text_marks)
|
||||
if response_id is not None:
|
||||
self._conversation.assistant_response_snapshots[response_id] = (
|
||||
@@ -943,7 +987,7 @@ class DuplexEngineSession:
|
||||
else:
|
||||
committed_text = ""
|
||||
if commit_text and committed_text:
|
||||
message = {"role": "assistant", "content": committed_text}
|
||||
message = _object_dict(role="assistant", content=committed_text)
|
||||
item_id = f"item_{response_id}" if response_id is not None else None
|
||||
if item_id is not None and item_id in self._conversation.history_item_placeholders:
|
||||
self._store_history_item_message(item_id, message)
|
||||
@@ -985,6 +1029,16 @@ class DuplexEngineSession:
|
||||
last_message, audio_text_marks, _ = response_snapshot
|
||||
self._conversation.pending_item_ids[item_id] = copy.deepcopy(last_message)
|
||||
self._conversation.pending_item_input_commit_seqs[item_id] = response_snapshot[2]
|
||||
playback = self._playback_cursor_for_item_id(item_id)
|
||||
if (
|
||||
item_id in self._conversation.history_item_placeholders
|
||||
and playback is not None
|
||||
and playback.text_requires_complete_audio
|
||||
):
|
||||
# Keep the assistant turn between its user inputs even when
|
||||
# unaligned audio cannot establish any heard text. A later
|
||||
# full playback ACK fills this same slot from the snapshot.
|
||||
self._store_history_item_message(item_id, _object_dict(role="assistant", content=""))
|
||||
if audio_text_marks:
|
||||
self._conversation.pending_item_audio_text_marks[item_id] = list(copy.deepcopy(audio_text_marks))
|
||||
pending_audio_ms = self._conversation.pending_truncations_ms.get(item_id)
|
||||
@@ -1029,10 +1083,10 @@ class DuplexEngineSession:
|
||||
self._conversation.assistant_response_snapshots.pop(response_id, None)
|
||||
if message is None:
|
||||
return pending is not None or removed_placeholder
|
||||
try:
|
||||
self._conversation.messages.remove(message)
|
||||
except ValueError:
|
||||
pass
|
||||
# Distinct response items can have identical (including empty) content.
|
||||
self._conversation.messages = [
|
||||
candidate for candidate in self._conversation.messages if candidate is not message
|
||||
]
|
||||
return True
|
||||
|
||||
def truncate_history_item(
|
||||
@@ -1078,8 +1132,8 @@ class DuplexEngineSession:
|
||||
self._conversation.pending_truncations_ms.pop(item_id, None)
|
||||
return True
|
||||
|
||||
message = self._conversation.item_ids.get(item_id)
|
||||
if message is None:
|
||||
stored_message = self._conversation.item_ids.get(item_id)
|
||||
if stored_message is None:
|
||||
pending = self._conversation.pending_item_ids.get(item_id)
|
||||
if pending is None:
|
||||
self._conversation.pending_truncations_ms[item_id] = max(0, int(audio_end_ms))
|
||||
@@ -1113,6 +1167,7 @@ class DuplexEngineSession:
|
||||
if item_id.startswith("item_"):
|
||||
self._conversation.assistant_response_snapshots.pop(item_id.removeprefix("item_"), None)
|
||||
return True
|
||||
message = stored_message
|
||||
changed = self._truncate_message_to_audio_ms(
|
||||
message,
|
||||
audio_end_ms=audio_end_ms,
|
||||
@@ -1122,10 +1177,9 @@ class DuplexEngineSession:
|
||||
if changed and self._message_text_len(message) <= 0:
|
||||
self._conversation.item_ids.pop(item_id, None)
|
||||
self._conversation.item_audio_text_marks.pop(item_id, None)
|
||||
try:
|
||||
self._conversation.messages.remove(message)
|
||||
except ValueError:
|
||||
pass
|
||||
self._conversation.messages = [
|
||||
candidate for candidate in self._conversation.messages if candidate is not message
|
||||
]
|
||||
if item_id.startswith("item_"):
|
||||
self._conversation.assistant_response_snapshots.pop(item_id.removeprefix("item_"), None)
|
||||
elif changed and item_id.startswith("item_"):
|
||||
@@ -1209,12 +1263,20 @@ class DuplexEngineSession:
|
||||
sent_ms = max(self.playback.sent_ms, self.playback.generated_ms)
|
||||
committed_ms = self.playback.committed_ms
|
||||
policy = playback_commit_policy or self.config.playback_commit_policy
|
||||
commit_all = policy == DuplexPlaybackCommitPolicy.COMMIT_ALL_ON_DONE.value
|
||||
if self.playback.text_requires_complete_audio:
|
||||
# Unaligned text has no spoken prefix to cut at, so history gets
|
||||
# the whole answer or none of it. Under commit_all_on_done that
|
||||
# choice is the whole answer --- which is also the only thing a
|
||||
# client that never acks playback can be credited with.
|
||||
if commit_all:
|
||||
return assistant_text
|
||||
keep_chars = self._text_chars_for_audio_ms(committed_ms, len(assistant_text))
|
||||
return assistant_text[:keep_chars].rstrip()
|
||||
if sent_ms <= 0 or committed_ms >= sent_ms:
|
||||
return assistant_text
|
||||
if committed_ms <= 0:
|
||||
if policy == DuplexPlaybackCommitPolicy.COMMIT_ALL_ON_DONE.value:
|
||||
return assistant_text
|
||||
return ""
|
||||
return assistant_text if commit_all else ""
|
||||
keep_chars = self._text_chars_for_audio_ms(committed_ms, len(assistant_text))
|
||||
if keep_chars <= 0:
|
||||
return ""
|
||||
@@ -1233,6 +1295,11 @@ class DuplexEngineSession:
|
||||
audio_end_ms = max(0, int(audio_end_ms))
|
||||
marks = marks if marks is not None else self._response.assistant_audio_text_marks
|
||||
playback = playback or self._playback.current
|
||||
if playback.text_requires_complete_audio:
|
||||
# Unaligned streams cannot establish a spoken prefix. A terminal
|
||||
# boundary plus its playback ACK can establish the whole answer.
|
||||
total_ms = max(playback.sent_ms, playback.generated_ms)
|
||||
return text_len if playback.audio_complete and total_ms > 0 and audio_end_ms >= total_ms else 0
|
||||
if not marks:
|
||||
sent_ms = max(1, playback.sent_ms, playback.generated_ms)
|
||||
return int(text_len * max(0.0, min(1.0, audio_end_ms / sent_ms)))
|
||||
@@ -1307,11 +1374,9 @@ class DuplexEngineSession:
|
||||
elif event_type == DuplexTurnEventType.ASSISTANT_DONE.value:
|
||||
self.transition_turn(DuplexTurnState.IDLE)
|
||||
elif event_type == DuplexTurnEventType.PLAYBACK_ACK.value:
|
||||
played_ms = int(payload.get("played_ms", 0) or 0)
|
||||
committed_ms = payload.get("committed_ms")
|
||||
self.acknowledge_playback(
|
||||
played_ms,
|
||||
int(committed_ms) if isinstance(committed_ms, int | float) else None,
|
||||
_as_int(payload.get("played_ms", 0)),
|
||||
_as_optional_int(payload.get("committed_ms")),
|
||||
)
|
||||
elif event_type == DuplexTurnEventType.BARGE_IN.value:
|
||||
self.transition_turn(DuplexTurnState.BARGE_IN)
|
||||
@@ -1346,29 +1411,45 @@ class DuplexEngineSession:
|
||||
"playback": self.playback.as_dict(),
|
||||
"capabilities": self.capabilities.as_dict(),
|
||||
}
|
||||
if isinstance(self.config.extra_body.get("realtime_tools"), list):
|
||||
payload["tools"] = self.config.extra_body["realtime_tools"]
|
||||
if isinstance(self.config.extra_body.get("realtime_tool_choice"), str | dict):
|
||||
payload["tool_choice"] = self.config.extra_body["realtime_tool_choice"]
|
||||
if isinstance(self.config.extra_body.get("realtime_metadata"), dict):
|
||||
payload["metadata"] = dict(self.config.extra_body["realtime_metadata"])
|
||||
if isinstance(self.config.extra_body.get("realtime_include"), list):
|
||||
payload["include"] = list(self.config.extra_body["realtime_include"])
|
||||
if isinstance(self.config.extra_body.get("realtime_prompt"), dict):
|
||||
payload["prompt"] = dict(self.config.extra_body["realtime_prompt"])
|
||||
if isinstance(self.config.extra_body.get("realtime_input_audio_transcription"), dict):
|
||||
payload["input_audio_transcription"] = dict(self.config.extra_body["realtime_input_audio_transcription"])
|
||||
if isinstance(self.config.extra_body.get("realtime_input_audio_noise_reduction"), dict):
|
||||
payload["input_audio_noise_reduction"] = dict(
|
||||
self.config.extra_body["realtime_input_audio_noise_reduction"]
|
||||
)
|
||||
if isinstance(self.config.extra_body.get("realtime_audio"), dict):
|
||||
payload["audio"] = dict(self.config.extra_body["realtime_audio"])
|
||||
if isinstance(self.config.extra_body.get("realtime_tracing"), str | dict):
|
||||
payload["tracing"] = self.config.extra_body["realtime_tracing"]
|
||||
raw_realtime_session = self.config.extra_body.get("realtime_session_payload")
|
||||
if isinstance(raw_realtime_session, dict):
|
||||
for key, value in raw_realtime_session.items():
|
||||
extra_body = self.config.extra_body
|
||||
realtime_tools = _copy_list(extra_body.get("realtime_tools"))
|
||||
if realtime_tools is not None:
|
||||
payload["tools"] = realtime_tools
|
||||
realtime_tool_choice = extra_body.get("realtime_tool_choice")
|
||||
if isinstance(realtime_tool_choice, str):
|
||||
payload["tool_choice"] = realtime_tool_choice
|
||||
else:
|
||||
copied_tool_choice = _copy_mapping(realtime_tool_choice)
|
||||
if copied_tool_choice is not None:
|
||||
payload["tool_choice"] = copied_tool_choice
|
||||
realtime_metadata = _copy_mapping(extra_body.get("realtime_metadata"))
|
||||
if realtime_metadata is not None:
|
||||
payload["metadata"] = realtime_metadata
|
||||
realtime_include = _copy_list(extra_body.get("realtime_include"))
|
||||
if realtime_include is not None:
|
||||
payload["include"] = realtime_include
|
||||
realtime_prompt = _copy_mapping(extra_body.get("realtime_prompt"))
|
||||
if realtime_prompt is not None:
|
||||
payload["prompt"] = realtime_prompt
|
||||
realtime_transcription = _copy_mapping(extra_body.get("realtime_input_audio_transcription"))
|
||||
if realtime_transcription is not None:
|
||||
payload["input_audio_transcription"] = realtime_transcription
|
||||
realtime_noise_reduction = _copy_mapping(extra_body.get("realtime_input_audio_noise_reduction"))
|
||||
if realtime_noise_reduction is not None:
|
||||
payload["input_audio_noise_reduction"] = realtime_noise_reduction
|
||||
realtime_audio = _copy_mapping(extra_body.get("realtime_audio"))
|
||||
if realtime_audio is not None:
|
||||
payload["audio"] = realtime_audio
|
||||
realtime_tracing = extra_body.get("realtime_tracing")
|
||||
if isinstance(realtime_tracing, str):
|
||||
payload["tracing"] = realtime_tracing
|
||||
else:
|
||||
copied_tracing = _copy_mapping(realtime_tracing)
|
||||
if copied_tracing is not None:
|
||||
payload["tracing"] = copied_tracing
|
||||
copied_session = _copy_mapping(extra_body.get("realtime_session_payload"))
|
||||
if copied_session is not None:
|
||||
for key, value in copied_session.items():
|
||||
if key not in payload and key != "extra_body":
|
||||
payload[key] = value
|
||||
return payload
|
||||
|
||||
@@ -13,14 +13,16 @@ Functions, not a component, because there is nothing here to own.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import binascii
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexPlaybackCommitPolicy
|
||||
from vllm_omni.engine.duplex.contracts import DuplexFence, duplex_resource_request_id
|
||||
from vllm_omni.engine.duplex.contracts import DuplexFence
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent, OverlapDecision, error_event
|
||||
from vllm_omni.engine.duplex.plugin import payload_turn_id
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping
|
||||
@@ -29,13 +31,38 @@ if TYPE_CHECKING:
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexCommittedInput, DuplexEngineSession
|
||||
|
||||
|
||||
def task_is_cancelling(task: asyncio.Task[object] | None) -> bool:
|
||||
"""True when *task* has a pending cancellation (Python 3.11+ ``Task.cancelling``)."""
|
||||
if task is None:
|
||||
return False
|
||||
cancelling = getattr(task, "cancelling", None)
|
||||
return bool(cancelling()) if callable(cancelling) else False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Questions about the session #
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def stage0_request_id(session: DuplexEngineSession, epoch: int) -> str:
|
||||
return duplex_resource_request_id(DuplexFence(session.session_id, epoch=epoch), "stage0")
|
||||
def append_fence(session: DuplexEngineSession, payload: object, *, epoch: int | None = None) -> DuplexFence:
|
||||
"""The fence one append is submitted under.
|
||||
|
||||
A model without a resumable core request gets one stage request per turn,
|
||||
so the turn this resolves to is part of the request id. The runner names
|
||||
that id when it queues the append and the model channel names it again
|
||||
when it submits, and the two must not disagree --- otherwise the session
|
||||
binds a request id it never submitted.
|
||||
"""
|
||||
turn_id = payload_turn_id(payload)
|
||||
if turn_id is None:
|
||||
turn_id = session.active_response_turn_id
|
||||
if turn_id is None:
|
||||
turn_id = session.turn_id
|
||||
return DuplexFence(
|
||||
session.session_id,
|
||||
epoch=session.epoch if epoch is None else epoch,
|
||||
turn_id=turn_id,
|
||||
)
|
||||
|
||||
|
||||
def response_in_progress(session: DuplexEngineSession, tasks: DuplexSessionTasks) -> bool:
|
||||
|
||||
@@ -408,8 +408,11 @@ class DuplexSessionManager:
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def stage_request_id(fence: DuplexFence, *, stage_id: int) -> str:
|
||||
return duplex_resource_request_id(fence, f"stage{stage_id}")
|
||||
def stage_request_id(fence: DuplexFence, *, stage_id: int, resumable: bool = True) -> str:
|
||||
role = f"stage{stage_id}"
|
||||
if not resumable:
|
||||
role += f"-turn{fence.turn_id}"
|
||||
return duplex_resource_request_id(fence, role)
|
||||
|
||||
def ensure_stage_request(
|
||||
self,
|
||||
@@ -422,7 +425,9 @@ class DuplexSessionManager:
|
||||
if stage_id >= self.stage_port.stage_count:
|
||||
return None
|
||||
effective_fence = fence or session.fence
|
||||
request_id = self.stage_request_id(effective_fence, stage_id=stage_id)
|
||||
request_id = self.stage_request_id(
|
||||
effective_fence, stage_id=stage_id, resumable=session.capabilities.supports_core_resumable_request
|
||||
)
|
||||
session.reserve_stage_request(stage_id, request_id, fence=effective_fence)
|
||||
context = DuplexStageRequestContext(
|
||||
request_id=request_id,
|
||||
|
||||
@@ -22,6 +22,8 @@ tracked task, and aborting a stage request in the background.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable, Mapping
|
||||
from dataclasses import replace
|
||||
@@ -42,8 +44,8 @@ from vllm_omni.engine.duplex.contracts import (
|
||||
from vllm_omni.engine.duplex.plugin import (
|
||||
DuplexRuntimeConfigError,
|
||||
coerce_int,
|
||||
payload_turn_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session import helpers
|
||||
from vllm_omni.engine.duplex.session.context import DuplexSessionContext, StageOutput
|
||||
from vllm_omni.engine.duplex.session.emitter import SessionEmitter
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession, DuplexFenceMismatchError
|
||||
@@ -113,6 +115,13 @@ class ModelChannel:
|
||||
) -> dict[str, object]:
|
||||
session = self._ctx.session
|
||||
response_config = session.response_config
|
||||
if not session.capabilities.supports_core_resumable_request and self.should_commit_response_to_history(
|
||||
session, response_id
|
||||
):
|
||||
# Committed-turn models can receive the next utterance before the
|
||||
# speaker drains. Reserve the response's chronological slot now;
|
||||
# an ACK fills it later without moving it past newer user input.
|
||||
session.reserve_history_item(f"item_{response_id}")
|
||||
payload: dict[str, object] = {
|
||||
"type": "response.created",
|
||||
"session_id": session.session_id,
|
||||
@@ -146,12 +155,16 @@ class ModelChannel:
|
||||
operation_id: str | None = None,
|
||||
final: bool,
|
||||
expected_epoch: int | None = None,
|
||||
on_append_accepted: Callable[[float], None] | None = None,
|
||||
) -> tuple[bool, bool]:
|
||||
session = self._ctx.session
|
||||
if not session.capabilities.supports_input_append:
|
||||
return True, False
|
||||
if expected_epoch is not None and session.epoch != expected_epoch:
|
||||
return True, False
|
||||
# Anchor the submission time before the RPC; the acceptance callback
|
||||
# commits timing state only if the append actually submitted.
|
||||
submit_time = time.monotonic()
|
||||
try:
|
||||
result = await self._append_via_data_plane(
|
||||
payload,
|
||||
@@ -169,6 +182,10 @@ class ModelChannel:
|
||||
return True, False
|
||||
if expected_epoch is not None and session.epoch != expected_epoch:
|
||||
return True, False
|
||||
# Commit timing state before returned output events can clear the
|
||||
# silence-continuation chain (e.g. a terminal turn-end).
|
||||
if on_append_accepted is not None:
|
||||
on_append_accepted(submit_time)
|
||||
request_id, _ = duplex_data_plane_request_info(result)
|
||||
if request_id is not None:
|
||||
self._ctx.plugin.data_plane.begin_request(request_id)
|
||||
@@ -193,22 +210,13 @@ class ModelChannel:
|
||||
session = self._ctx.session
|
||||
if self._ctx.stage_port.stage_count == 0:
|
||||
raise RuntimeError("duplex_data_plane_has_no_stage")
|
||||
payload_turn = payload_turn_id(payload)
|
||||
fence = DuplexFence(
|
||||
session.session_id,
|
||||
epoch=session.epoch,
|
||||
turn_id=(
|
||||
payload_turn
|
||||
if payload_turn is not None
|
||||
else (
|
||||
session.active_response_turn_id if session.active_response_turn_id is not None else session.turn_id
|
||||
)
|
||||
),
|
||||
)
|
||||
fence = helpers.append_fence(session, payload)
|
||||
lease_operation_id = f"append:{operation_id or uuid.uuid4().hex}"
|
||||
operation_started = False
|
||||
stage_id = 0
|
||||
request_id = self._ctx.manager.stage_request_id(fence, stage_id=stage_id)
|
||||
request_id = self._ctx.manager.stage_request_id(
|
||||
fence, stage_id=stage_id, resumable=session.capabilities.supports_core_resumable_request
|
||||
)
|
||||
try:
|
||||
session.begin_lease_operation(fence, lease_operation_id)
|
||||
operation_started = True
|
||||
@@ -217,10 +225,17 @@ class ModelChannel:
|
||||
request_context = self._ctx.manager.ensure_stage_request(session, stage_id=stage_id, fence=fence)
|
||||
if request_context is None:
|
||||
raise RuntimeError("duplex_data_plane_has_no_stage")
|
||||
append_plan = self._ctx.plugin.plan_append(
|
||||
prompt_payload: dict[str, object] = (
|
||||
{str(key): value for key, value in payload.items()} if isinstance(payload, Mapping) else {}
|
||||
)
|
||||
append_plan = await self._ctx.plugin.prepare_append_plan(
|
||||
request_id=request_id,
|
||||
fence=fence,
|
||||
session_config=dict(request_context.session_config),
|
||||
session_config=self._ctx.plugin.prepare_prompt_config(
|
||||
{**request_context.session_config, "conversation": list(session.history)},
|
||||
state=self._ctx.model_state,
|
||||
payload=prompt_payload,
|
||||
),
|
||||
runtime_config=dict(request_context.runtime_config),
|
||||
seq=reservation.update.seq,
|
||||
turn_seq=reservation.update.turn_seq,
|
||||
@@ -228,6 +243,10 @@ class ModelChannel:
|
||||
final=final,
|
||||
sampling_params=request_context.stage_sampling_params,
|
||||
)
|
||||
# Preparation may yield while cancellation or session teardown runs.
|
||||
# Never submit the worker's stale result to the model.
|
||||
if session.epoch != fence.epoch or session.state != DuplexSessionState.OPEN:
|
||||
raise DuplexFenceMismatchError(session.fence, fence)
|
||||
if not isinstance(append_plan, DuplexAppendPlan):
|
||||
raise TypeError("duplex plugin plan_append() must return DuplexAppendPlan")
|
||||
submission = DuplexStageSubmission(
|
||||
@@ -270,7 +289,7 @@ class ModelChannel:
|
||||
"seq": update.seq,
|
||||
"turn_id": update.turn_id,
|
||||
"turn_seq": update.turn_seq,
|
||||
"resumable": True,
|
||||
"resumable": session.capabilities.supports_core_resumable_request,
|
||||
},
|
||||
}
|
||||
],
|
||||
@@ -404,7 +423,7 @@ class ModelChannel:
|
||||
engine_output.finished = True
|
||||
engine_output = attach_duplex_output_decision(engine_output, item.decision)
|
||||
elif isinstance(output, OmniRequestOutput):
|
||||
engine_output = output
|
||||
engine_output = copy.copy(output)
|
||||
if finished:
|
||||
engine_output.finished = True
|
||||
else:
|
||||
@@ -416,6 +435,9 @@ class ModelChannel:
|
||||
stage_id=item.stage_id,
|
||||
final_output_type=final_output_type if isinstance(final_output_type, str) else "audio",
|
||||
)
|
||||
engine_output.stage_id = item.stage_id
|
||||
if self._ctx.plugin.projects_intermediate_outputs and item.stage_id < item.context.final_stage_id:
|
||||
engine_output.finished = False
|
||||
snapshot = self.stage_metrics_snapshot(item.stage_id, item.metrics, output)
|
||||
if snapshot is not None:
|
||||
existing = engine_output.metrics if isinstance(engine_output.metrics, dict) else {}
|
||||
@@ -452,6 +474,11 @@ class ModelChannel:
|
||||
await self._close_from_runtime(close_reason)
|
||||
return
|
||||
finished = self._data_plane_outputs_finished(drain_result)
|
||||
if finished and not session.capabilities.supports_core_resumable_request:
|
||||
if self._ctx.run.stream_request_id == item.request_id:
|
||||
self._ctx.run.stream_request_id = None
|
||||
await self._ctx.stage_port.cleanup([item.request_id])
|
||||
return
|
||||
if finished and emitted_response and not self._out.auto_responds():
|
||||
# A finished, emitted response releases the per-request projector
|
||||
# cursor on its way out and offers the model another
|
||||
@@ -750,8 +777,9 @@ class ModelChannel:
|
||||
response_id = session.begin_response(turn_id=model_turn_id)
|
||||
response_created = True
|
||||
self._out.emit(self.response_created_payload(response_id, epoch=session.epoch))
|
||||
stage_metrics = model_result.get("stage_metrics")
|
||||
response_stage_metrics = session.accumulate_response_stage_metrics(
|
||||
model_result.get("stage_metrics") if isinstance(model_result.get("stage_metrics"), Mapping) else None
|
||||
stage_metrics if isinstance(stage_metrics, Mapping) else None
|
||||
)
|
||||
if response_created:
|
||||
speak_payload = {
|
||||
@@ -796,6 +824,8 @@ class ModelChannel:
|
||||
mark_duration_ms,
|
||||
text_chars=mark_text_chars if mark_duration_ms is not None else None,
|
||||
audio_text_marks=audio_text_marks,
|
||||
text_requires_complete_audio=model_result.get("text_requires_complete_audio") is True,
|
||||
audio_complete=model_result.get("audio_complete") is True,
|
||||
)
|
||||
payload = {
|
||||
"type": "response.output_audio.delta",
|
||||
@@ -895,10 +925,10 @@ class ModelChannel:
|
||||
*,
|
||||
audio_offset_ms: int,
|
||||
text_offset_chars: int,
|
||||
) -> list[dict[str, int]] | None:
|
||||
) -> list[dict[str, object]] | None:
|
||||
if not audio_text_marks:
|
||||
return None
|
||||
normalized: list[dict[str, int]] = []
|
||||
normalized: list[dict[str, object]] = []
|
||||
for raw_mark in audio_text_marks:
|
||||
if not isinstance(raw_mark, dict):
|
||||
continue
|
||||
|
||||
@@ -21,6 +21,7 @@ orchestrator loop (the session is never touched from another thread):
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Awaitable, Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
@@ -28,7 +29,6 @@ from typing import TYPE_CHECKING, TypeVar
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine.duplex.audio import convert_input_audio_with_rate
|
||||
from vllm_omni.engine.duplex.commands import (
|
||||
AckPlayback,
|
||||
AppendAudio,
|
||||
@@ -71,7 +71,6 @@ from vllm_omni.engine.duplex.plugin import (
|
||||
DuplexModelPlugin,
|
||||
DuplexModelSessionState,
|
||||
PcmAppendReservation,
|
||||
payload_turn_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.realtime_events import (
|
||||
RealtimeProjectionState,
|
||||
@@ -103,6 +102,7 @@ from vllm_omni.engine.duplex.turn_detection import (
|
||||
TurnDetectionResult,
|
||||
)
|
||||
from vllm_omni.metrics.stats import StageRequestStats
|
||||
from vllm_omni.protocol.duplex import convert_input_audio_with_rate
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import ModelConfig
|
||||
@@ -126,6 +126,38 @@ class _Internal:
|
||||
_CANCEL_EVENTS = frozenset({"input.cancel", "response.cancel", "barge_in", "output_audio_buffer.clear"})
|
||||
|
||||
|
||||
def compute_silence_continuation_deadline(
|
||||
*,
|
||||
chunk_period_s: float,
|
||||
now: float,
|
||||
last_submit: float | None,
|
||||
current_deadline: float | None,
|
||||
) -> tuple[float, float]:
|
||||
"""Return the silence continuation schedule ``(delay_s, next_silence_deadline)``.
|
||||
|
||||
The first continuation anchors to the latest accepted append's submission
|
||||
time (``last_submit + chunk_period_s``), falling back to ``now`` when no
|
||||
submission exists. Later continuations advance from the current deadline
|
||||
instead of from ``now``, so pipeline processing time does not accumulate
|
||||
as timer drift. When the schedule is more than one period overdue it is
|
||||
stale: one continuation submits immediately and the schedule restarts
|
||||
from ``now`` (``next_silence_deadline = now + chunk_period_s``) instead of
|
||||
firing a burst of catch-ups.
|
||||
|
||||
``delay_s`` is the wait before this continuation and
|
||||
``next_silence_deadline`` the deadline for the following one.
|
||||
"""
|
||||
if current_deadline is None:
|
||||
base = last_submit if last_submit is not None else now
|
||||
deadline = base + chunk_period_s
|
||||
else:
|
||||
deadline = current_deadline
|
||||
if now - deadline > chunk_period_s:
|
||||
deadline = now
|
||||
delay_s = max(0.0, deadline - now)
|
||||
return delay_s, deadline + chunk_period_s
|
||||
|
||||
|
||||
class DuplexSessionRunner:
|
||||
"""Owns one ``DuplexEngineSession`` on the orchestrator loop (see module docstring)."""
|
||||
|
||||
@@ -218,7 +250,8 @@ class DuplexSessionRunner:
|
||||
if stage_id < context.final_stage_id:
|
||||
decision = self.model.decide_output(stage_id, output, context)
|
||||
consume = decision is not None or stage_id >= context.final_stage_id
|
||||
if not consume:
|
||||
project_intermediate = self.plugin.projects_intermediate_outputs and stage_id == 0
|
||||
if not consume and not project_intermediate:
|
||||
# Stage0 text without a direct decision feeds the TTS stage as before.
|
||||
# Its metrics still have to reach the client: before sessions moved
|
||||
# into the engine the orchestrator published them as a standalone
|
||||
@@ -241,7 +274,7 @@ class DuplexSessionRunner:
|
||||
decision=decision,
|
||||
)
|
||||
)
|
||||
return True
|
||||
return consume
|
||||
|
||||
def on_stage_failure(self, stage_id: int, exc: BaseException) -> None:
|
||||
"""A stage rejected this session's request: fail the active response now.
|
||||
@@ -401,12 +434,11 @@ class DuplexSessionRunner:
|
||||
worker.cancel()
|
||||
await asyncio.gather(worker, return_exceptions=True)
|
||||
|
||||
def spawn(self, coro: Awaitable[None], *, name: str) -> asyncio.Task[None]:
|
||||
def spawn(self, coro: Awaitable[None], *, name: str) -> None:
|
||||
task = asyncio.ensure_future(coro)
|
||||
task.set_name(name)
|
||||
self._background_tasks.add(task)
|
||||
task.add_done_callback(self._background_tasks.discard)
|
||||
return task
|
||||
|
||||
async def offload(self, fn: Callable[..., _OffloadT], *args: object, **kwargs: object) -> _OffloadT:
|
||||
loop = self._loop or asyncio.get_running_loop()
|
||||
@@ -506,14 +538,14 @@ class DuplexSessionRunner:
|
||||
elif isinstance(command, ClearInput):
|
||||
self._on_clear_input()
|
||||
elif isinstance(command, CancelResponse):
|
||||
resolved = resolve_cancel_response(projector, command)
|
||||
self._emit_events(resolved.events)
|
||||
for payload in resolved.payloads:
|
||||
control = resolve_cancel_response(projector, command)
|
||||
self._emit_events(control.events)
|
||||
for payload in control.payloads:
|
||||
await self._on_cancel(payload)
|
||||
elif isinstance(command, ClearOutputAudio):
|
||||
resolved = resolve_clear_output_audio(projector, command)
|
||||
self._emit_events(resolved.events)
|
||||
for payload in resolved.payloads:
|
||||
control = resolve_clear_output_audio(projector, command)
|
||||
self._emit_events(control.events)
|
||||
for payload in control.payloads:
|
||||
await self._on_cancel(payload)
|
||||
elif isinstance(command, CancelInput | BargeIn):
|
||||
await self._on_cancel(command.payload())
|
||||
@@ -531,7 +563,8 @@ class DuplexSessionRunner:
|
||||
return
|
||||
payload = command.payload()
|
||||
if command.event in _CANCEL_EVENTS:
|
||||
normalized = dict(payload.get("payload") or {})
|
||||
inner = payload.get("payload")
|
||||
normalized: dict[str, object] = dict(inner) if isinstance(inner, Mapping) else {}
|
||||
normalized.update(payload)
|
||||
normalized["type"] = command.event
|
||||
await self._on_cancel(normalized)
|
||||
@@ -544,19 +577,19 @@ class DuplexSessionRunner:
|
||||
elif isinstance(command, Heartbeat):
|
||||
self._on_heartbeat(command)
|
||||
elif isinstance(command, CreateItem):
|
||||
resolved = resolve_create_item(projector, command)
|
||||
self._emit_events(resolved.events)
|
||||
for payload in resolved.payloads:
|
||||
control = resolve_create_item(projector, command)
|
||||
self._emit_events(control.events)
|
||||
for payload in control.payloads:
|
||||
await self._run_internal_payload(payload)
|
||||
elif isinstance(command, DeleteItem):
|
||||
resolved = resolve_delete_item(projector, command)
|
||||
self._emit_events(resolved.events)
|
||||
for payload in resolved.payloads:
|
||||
control = resolve_delete_item(projector, command)
|
||||
self._emit_events(control.events)
|
||||
for payload in control.payloads:
|
||||
await self.control.on_turn_signal(payload)
|
||||
elif isinstance(command, TruncateItem):
|
||||
resolved = resolve_truncate_item(projector, command)
|
||||
self._emit_events(resolved.events)
|
||||
for payload in resolved.payloads:
|
||||
control = resolve_truncate_item(projector, command)
|
||||
self._emit_events(control.events)
|
||||
for payload in control.payloads:
|
||||
await self._run_internal_payload(payload)
|
||||
elif isinstance(command, CloseSession):
|
||||
await self._on_close_command(command.reason)
|
||||
@@ -743,7 +776,7 @@ class DuplexSessionRunner:
|
||||
sr_raw = event.get("sample_rate_hz") or event.get("sample_rate")
|
||||
sample_rate_hz = sr_raw if isinstance(sr_raw, int | float) else 16000
|
||||
try:
|
||||
audio, fmt, sample_rate_hz = await self.offload(
|
||||
converted: tuple[object, object, int | float | None] = await self.offload(
|
||||
convert_input_audio_with_rate,
|
||||
audio,
|
||||
fmt,
|
||||
@@ -752,13 +785,25 @@ class DuplexSessionRunner:
|
||||
except ValueError as exc:
|
||||
self._emit_error("bad_event", str(exc))
|
||||
return
|
||||
audio, fmt, converted_rate = converted
|
||||
if converted_rate is not None:
|
||||
sample_rate_hz = converted_rate
|
||||
if isinstance(fmt, str) and fmt.lower() in {"pcm16", "pcm_s16le", "s16le"}:
|
||||
self._emit_error("bad_audio", "input_audio_buffer.append pcm16 audio could not be decoded")
|
||||
return
|
||||
event["audio"] = audio
|
||||
event["format"] = fmt
|
||||
event["sample_rate_hz"] = sample_rate_hz
|
||||
client_force_listen = bool(event.get("force_listen", False))
|
||||
vad_result = await self.control.run_turn_detection(event)
|
||||
if (
|
||||
vad_result is not None
|
||||
and not session.capabilities.supports_core_resumable_request
|
||||
and not client_force_listen
|
||||
):
|
||||
# VAD's force_listen hint controls native model decoding. Committed
|
||||
# turn models already buffer speech; it must not suppress barge-in.
|
||||
event.pop("force_listen", None)
|
||||
projector = self._require_projector()
|
||||
self._emit_events(note_input_append(projector, event, vad_result=vad_result))
|
||||
if self.run.closing or session.state != DuplexSessionState.OPEN:
|
||||
@@ -863,8 +908,11 @@ class DuplexSessionRunner:
|
||||
return
|
||||
if pcm_reservation.byte_count == 0:
|
||||
session.release_input_bytes(raw_audio_bytes)
|
||||
payload = pcm_reservation.payload
|
||||
await self._start_append(payload, final=False, pcm_reservation=pcm_reservation)
|
||||
append_payload = pcm_reservation.payload
|
||||
if append_payload is None:
|
||||
self._maybe_schedule_vad_commit(vad_result)
|
||||
return
|
||||
await self._start_append(append_payload, final=False, pcm_reservation=pcm_reservation)
|
||||
self._maybe_schedule_vad_commit(vad_result)
|
||||
|
||||
def _maybe_schedule_vad_commit(self, vad_result: TurnDetectionResult | None) -> None:
|
||||
@@ -918,17 +966,30 @@ class DuplexSessionRunner:
|
||||
operation_id: str | None = None,
|
||||
retained_committed_payload: dict[str, object] | None = None,
|
||||
silence_continuation: bool = False,
|
||||
on_append_accepted: Callable[[float], None] | None = None,
|
||||
before_append: Callable[[], bool] | None = None,
|
||||
) -> asyncio.Task[bool]:
|
||||
session = self.session
|
||||
model_state = self.model_state
|
||||
if not silence_continuation:
|
||||
self._mark_pending_silence_superseded()
|
||||
if on_append_accepted is None:
|
||||
# A real (non-silence) input re-anchors the silence pacing
|
||||
# chain: its submission becomes the anchor and the stored
|
||||
# deadline is cleared until the next continuation sets one.
|
||||
def _reanchor_chain(submit_time: float) -> None:
|
||||
model_state.last_native_submit_monotonic = submit_time
|
||||
model_state.silence_deadline_monotonic = None
|
||||
|
||||
on_append_accepted = _reanchor_chain
|
||||
append_epoch = session.epoch
|
||||
append_turn_id = payload_turn_id(payload)
|
||||
if append_turn_id is None:
|
||||
append_turn_id = session.turn_id
|
||||
request_id = helpers.stage0_request_id(self.session, append_epoch)
|
||||
append_fence = helpers.append_fence(session, payload, epoch=append_epoch)
|
||||
append_turn_id = append_fence.turn_id
|
||||
request_id = self.ctx.manager.stage_request_id(
|
||||
append_fence,
|
||||
stage_id=0,
|
||||
resumable=session.capabilities.supports_core_resumable_request,
|
||||
)
|
||||
if final or precreate_response:
|
||||
session.bind_request(request_id)
|
||||
if precreate_response:
|
||||
@@ -936,6 +997,14 @@ class DuplexSessionRunner:
|
||||
if precreate_response and session.active_response_id is None:
|
||||
response_id = session.begin_response(turn_id=append_turn_id)
|
||||
self.emit(self.model.response_created_payload(response_id, epoch=append_epoch))
|
||||
if final and not session.capabilities.supports_core_resumable_request:
|
||||
logger.info(
|
||||
"Duplex committed turn session=%s request=%s response=%s audio_bytes=%s",
|
||||
session.session_id,
|
||||
request_id,
|
||||
session.active_response_id,
|
||||
helpers.audio_payload_size_bytes(payload),
|
||||
)
|
||||
attempt = AppendAttempt(
|
||||
ctx=self.ctx,
|
||||
out=self.out,
|
||||
@@ -949,6 +1018,7 @@ class DuplexSessionRunner:
|
||||
operation_id=operation_id,
|
||||
retained_committed_payload=retained_committed_payload,
|
||||
precreated_response_id=session.active_response_id if precreate_response else None,
|
||||
on_append_accepted=on_append_accepted,
|
||||
before_append=before_append,
|
||||
)
|
||||
|
||||
@@ -990,8 +1060,7 @@ class DuplexSessionRunner:
|
||||
try:
|
||||
return await predecessor
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if current is not None and current.cancelling():
|
||||
if helpers.task_is_cancelling(asyncio.current_task()):
|
||||
raise
|
||||
return False
|
||||
except Exception:
|
||||
@@ -1019,8 +1088,7 @@ class DuplexSessionRunner:
|
||||
if not await pending_silence:
|
||||
return False
|
||||
except asyncio.CancelledError:
|
||||
current = asyncio.current_task()
|
||||
if current is not None and current.cancelling():
|
||||
if helpers.task_is_cancelling(asyncio.current_task()):
|
||||
raise
|
||||
return False
|
||||
except Exception:
|
||||
@@ -1032,29 +1100,60 @@ class DuplexSessionRunner:
|
||||
append_tail = self.tasks.append_tail
|
||||
if (append_tail is None or append_tail.done()) and self._real_input_waiting():
|
||||
return False
|
||||
continuation_delay_s = max(0.0, float(session.capabilities.chunk_period_ms or 1000) / 1000.0)
|
||||
if continuation_delay_s > 0:
|
||||
await asyncio.sleep(continuation_delay_s)
|
||||
if (
|
||||
self.tasks.append_tail is not append_tail
|
||||
or ((append_tail is None or append_tail.done()) and self._real_input_waiting())
|
||||
or self.model.silence_continuation_is_stale(
|
||||
chunk_period_s = max(0.0, float(session.capabilities.chunk_period_ms or 1000) / 1000.0)
|
||||
# Snapshot the anchor after any wait for pending silence. A real append
|
||||
# accepted between the snapshot and this continuation's submission
|
||||
# re-anchors the chain; _still_valid() then skips the stale unit.
|
||||
anchor = model_state.last_native_submit_monotonic
|
||||
# Align the next silence unit to submission_time_N + chunk_period and
|
||||
# sleep only the remaining budget. The deadline is stored by the
|
||||
# acceptance callback when the append actually submits, so skipped or
|
||||
# stale continuations never advance the clock.
|
||||
delay_s, next_silence_deadline = compute_silence_continuation_deadline(
|
||||
chunk_period_s=chunk_period_s,
|
||||
now=time.monotonic(),
|
||||
last_submit=anchor,
|
||||
current_deadline=model_state.silence_deadline_monotonic,
|
||||
)
|
||||
if delay_s > 0:
|
||||
await asyncio.sleep(delay_s)
|
||||
if (
|
||||
self.tasks.append_tail is not append_tail
|
||||
or ((append_tail is None or append_tail.done()) and self._real_input_waiting())
|
||||
or self.model.silence_continuation_is_stale(
|
||||
request_id=request_id,
|
||||
response_id=response_id,
|
||||
response_owned=response_owned,
|
||||
expected_epoch=expected_epoch,
|
||||
expected_model_turn_id=expected_model_turn_id,
|
||||
)
|
||||
):
|
||||
return False
|
||||
|
||||
def _still_valid() -> bool:
|
||||
return (
|
||||
# The anchor changed (a real append was accepted) after this
|
||||
# continuation was planned; the unit is outdated.
|
||||
model_state.last_native_submit_monotonic == anchor
|
||||
and not self._real_input_waiting()
|
||||
and not self.model.silence_continuation_is_stale(
|
||||
request_id=request_id,
|
||||
response_id=response_id,
|
||||
response_owned=response_owned,
|
||||
expected_epoch=expected_epoch,
|
||||
expected_model_turn_id=expected_model_turn_id,
|
||||
)
|
||||
):
|
||||
return False
|
||||
)
|
||||
|
||||
def _still_valid() -> bool:
|
||||
return not self._real_input_waiting() and not self.model.silence_continuation_is_stale(
|
||||
request_id=request_id,
|
||||
response_id=response_id,
|
||||
response_owned=response_owned,
|
||||
expected_epoch=expected_epoch,
|
||||
expected_model_turn_id=expected_model_turn_id,
|
||||
def _on_append_accepted(submit_time: float) -> None:
|
||||
# Commit timing state once the runtime accepts the append. If the
|
||||
# submission is more than one chunk period past the planned
|
||||
# deadline, the schedule is stale: restart from the actual
|
||||
# submission. Small delays keep the planned cadence so ordinary
|
||||
# jitter does not accumulate as drift.
|
||||
model_state.last_native_submit_monotonic = submit_time
|
||||
model_state.silence_deadline_monotonic = (
|
||||
submit_time + chunk_period_s if submit_time > next_silence_deadline else next_silence_deadline
|
||||
)
|
||||
|
||||
model_state.pending_silence_owner_id = owner_id
|
||||
@@ -1062,6 +1161,7 @@ class DuplexSessionRunner:
|
||||
dict(payload) if isinstance(payload, dict) else {},
|
||||
final=False,
|
||||
silence_continuation=True,
|
||||
on_append_accepted=_on_append_accepted,
|
||||
before_append=_still_valid,
|
||||
)
|
||||
return task is not None
|
||||
@@ -1213,7 +1313,7 @@ class DuplexSessionRunner:
|
||||
{
|
||||
"type": "audio.cancelled",
|
||||
"session_id": session.session_id,
|
||||
"response_id": session.active_response_id,
|
||||
"response_id": event.get("response_id") or session.active_response_id,
|
||||
"reason": cancel_reason,
|
||||
"cancelled_epoch": session.epoch,
|
||||
"epoch": session.epoch,
|
||||
@@ -1447,6 +1547,10 @@ class DuplexSessionRunner:
|
||||
retained_committed_payload=committed_payload,
|
||||
)
|
||||
return
|
||||
if session.unanswered_user_items() and session.capabilities.supports_text_only_turn:
|
||||
session.reset_unanswered_user_items()
|
||||
await self._start_append({"type": "conversation"}, final=True, precreate_response=True)
|
||||
return
|
||||
if session.unanswered_user_items():
|
||||
# Conversation items are context, not a turn. A model-native model
|
||||
# decides to speak from the audio it hears, and there is no audio
|
||||
@@ -1525,13 +1629,16 @@ class DuplexSessionRunner:
|
||||
if deferred_payload is None:
|
||||
commit_reservation.commit()
|
||||
return False
|
||||
retained_payload: dict[str, object]
|
||||
if model_state.committed_audio_payload is not None:
|
||||
deferred_payload = overlap_policy.merge_audio_payloads(
|
||||
retained_payload = overlap_policy.merge_audio_payloads(
|
||||
model_state.committed_audio_payload,
|
||||
deferred_payload,
|
||||
)
|
||||
else:
|
||||
retained_payload = deferred_payload
|
||||
model_state.retain_committed_audio(
|
||||
deferred_payload,
|
||||
retained_payload,
|
||||
operation_id=commit_reservation.operation_id,
|
||||
reserved_bytes=commit_reservation.byte_count,
|
||||
)
|
||||
|
||||
@@ -428,11 +428,17 @@ class SileroStreamingVAD:
|
||||
|
||||
if self._speech_active:
|
||||
contained_speech = True
|
||||
if probability >= self.config.threshold:
|
||||
# Confirmed speech cancels a pending endpoint. Otherwise a
|
||||
# brief pause can age through resumed speech and split the
|
||||
# utterance at the next low-probability frame.
|
||||
self._silence_samples = 0
|
||||
continue
|
||||
below_negative_threshold = probability < negative_threshold
|
||||
if not below_negative_threshold and self._silence_samples == 0:
|
||||
continue
|
||||
# A silence candidate is running: louder frames keep its clock
|
||||
# moving but cannot themselves close the turn.
|
||||
# Scores inside the hysteresis band keep the pending timer,
|
||||
# but cannot themselves close the turn.
|
||||
self._silence_samples += self._WINDOW_SAMPLES
|
||||
if not below_negative_threshold or self._silence_samples < min_silence_samples:
|
||||
continue
|
||||
|
||||
@@ -12,6 +12,8 @@ and applies the session-owned policy.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import time as _time
|
||||
from collections.abc import Coroutine
|
||||
from dataclasses import dataclass, field
|
||||
@@ -20,6 +22,7 @@ from typing import TYPE_CHECKING, Any
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config.stage_config import DuplexSessionRuntimeConfig
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexOutputContext,
|
||||
@@ -77,6 +80,7 @@ class DuplexOrchestrator(Orchestrator, DuplexStagePort):
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
self._prompt_processing_lock = threading.Lock()
|
||||
self.plugin = plugin
|
||||
self.duplex_session_config = duplex_session_config
|
||||
self.session_manager = DuplexSessionManager(
|
||||
@@ -288,7 +292,9 @@ class DuplexOrchestrator(Orchestrator, DuplexStagePort):
|
||||
fence=context.fence,
|
||||
config_generation=context.config_generation,
|
||||
)
|
||||
request_state.streaming.enabled = True
|
||||
request_state.streaming.enabled = self.plugin.capabilities(
|
||||
max_sessions=self.duplex_session_config.max_sessions
|
||||
).supports_core_resumable_request
|
||||
self.request_states[context.request_id] = request_state
|
||||
elif isinstance(request_state, DuplexOrchestratorRequestState):
|
||||
if request_state.config_generation != context.config_generation:
|
||||
@@ -301,18 +307,49 @@ class DuplexOrchestrator(Orchestrator, DuplexStagePort):
|
||||
self._sync_bridge_state(request_state, context)
|
||||
self.session_manager.register_request(context.request_id, context.session_id)
|
||||
|
||||
def _upgrade_processed_stage_request(self, request, raw_prompt):
|
||||
request = super()._upgrade_processed_stage_request(request, raw_prompt)
|
||||
if not self.plugin.capabilities(
|
||||
max_sessions=self.duplex_session_config.max_sessions
|
||||
).supports_core_resumable_request and not isinstance(request, OmniEngineCoreRequest):
|
||||
request = OmniEngineCoreRequest.from_request(request)
|
||||
return request
|
||||
|
||||
def _process_turn_prompt(self, *args, **kwargs):
|
||||
# Input processors own mutable caches. Hold a thread lock even if the
|
||||
# awaiting session is cancelled while its preprocessing is still running.
|
||||
with self._prompt_processing_lock:
|
||||
return self._build_next_stage_request(*args, **kwargs)
|
||||
|
||||
async def submit(self, submission: DuplexStageSubmission) -> DuplexStageSubmissionResult:
|
||||
context = submission.context
|
||||
request_state = self.request_states.get(context.request_id)
|
||||
if not isinstance(request_state, DuplexOrchestratorRequestState):
|
||||
raise RuntimeError(f"duplex request was not preregistered: {context.request_id}")
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=context.request_id,
|
||||
prompt=dict(submission.prompt),
|
||||
params=context.stage_sampling_params,
|
||||
model_config=self.stage_pools[context.stage_id].stage_vllm_config.model_config,
|
||||
resumable=True,
|
||||
)
|
||||
if self.plugin.capabilities(
|
||||
max_sessions=self.duplex_session_config.max_sessions
|
||||
).supports_core_resumable_request:
|
||||
request = build_engine_core_request_from_tokens(
|
||||
request_id=context.request_id,
|
||||
prompt=dict(submission.prompt),
|
||||
params=context.stage_sampling_params,
|
||||
model_config=self.stage_pools[context.stage_id].stage_vllm_config.model_config,
|
||||
resumable=True,
|
||||
)
|
||||
else:
|
||||
# Use the ordinary multimodal input processor for turn-model plugins.
|
||||
# Its CPU preprocessing runs off the session/orchestrator event loop.
|
||||
request = await asyncio.to_thread(
|
||||
self._process_turn_prompt,
|
||||
context.request_id,
|
||||
context.stage_id,
|
||||
dict(submission.prompt),
|
||||
context.stage_sampling_params,
|
||||
resumable=False,
|
||||
)
|
||||
if self.request_states.get(context.request_id) is not request_state:
|
||||
raise RuntimeError("duplex request cancelled during input preprocessing")
|
||||
request_state.prompt = dict(submission.prompt)
|
||||
request.external_req_id = request.request_id
|
||||
pool = self.stage_pools[context.stage_id]
|
||||
if submission.already_submitted:
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Engine runtime error types."""
|
||||
|
||||
|
||||
class NativeKVHandoffError(RuntimeError):
|
||||
"""One request lost its producer binding or transfer metadata."""
|
||||
@@ -61,11 +61,12 @@ from vllm_omni.engine.stage_client import StageClient
|
||||
from vllm_omni.engine.stage_init_utils import build_stage0_input_processor
|
||||
from vllm_omni.engine.stage_pool import StagePool
|
||||
from vllm_omni.engine.stage_runtime import (
|
||||
OmniClientConfig,
|
||||
StageRuntimeInfo,
|
||||
create_stage_runtime,
|
||||
)
|
||||
from vllm_omni.entrypoints.pd_utils import PDDisaggregationMixin
|
||||
from vllm_omni.entrypoints.utils import parse_stage_overrides
|
||||
from vllm_omni.entrypoints.utils import prepare_stage_config_inputs
|
||||
from vllm_omni.inputs.data import OmniSamplingParams
|
||||
from vllm_omni.metrics.prometheus import OmniRequestCounter
|
||||
|
||||
@@ -122,6 +123,7 @@ class OmniEngineBase:
|
||||
_transfer_emitter: Any = None
|
||||
_prom_metrics: Any = None
|
||||
_enable_orch_monitor: bool = False
|
||||
_client_config: OmniClientConfig | None = None
|
||||
# Lazily created by get_output_blocking_async().
|
||||
_output_drain_executor: concurrent.futures.ThreadPoolExecutor | None = None
|
||||
|
||||
@@ -136,6 +138,7 @@ class OmniEngineBase:
|
||||
log_stats: bool = False,
|
||||
tokenizer: str | None = None,
|
||||
trust_remote_code: bool | None = None,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
self.model = model
|
||||
@@ -155,6 +158,7 @@ class OmniEngineBase:
|
||||
# --log-stats CLI flag set by the user via OmniBase.
|
||||
self._log_stats = log_stats
|
||||
self._enable_orch_monitor = bool(kwargs.pop("enable_orch_monitor", False))
|
||||
self._client_config = client_config
|
||||
|
||||
logger.info(f"[OmniEngine] Initializing with model {model}")
|
||||
|
||||
@@ -166,6 +170,8 @@ class OmniEngineBase:
|
||||
_stage_id_kwarg = kwargs.get("stage_id")
|
||||
if isinstance(_stage_id_kwarg, int) and not single_stage_mode:
|
||||
single_stage_mode = True
|
||||
if client_config is not None and int(client_config.get("client_count", 1)) > 1 and single_stage_mode:
|
||||
raise ValueError("Multiple API servers cannot be combined with single-stage distributed mode")
|
||||
|
||||
self.single_stage_mode: bool = single_stage_mode
|
||||
self._single_stage_id_filter: int | None = (
|
||||
@@ -271,8 +277,16 @@ class OmniEngineBase:
|
||||
)
|
||||
|
||||
self.num_stages = len(self.stage_configs)
|
||||
stage0_args = getattr(self.stage_configs[0], "engine_args", None) if self.num_stages > 0 else None
|
||||
self.async_chunk = bool(getattr(stage0_args, "async_chunk", False))
|
||||
self.async_chunk = any(
|
||||
bool(
|
||||
getattr(
|
||||
getattr(stage, "connector_config", None),
|
||||
"async_chunk",
|
||||
getattr(getattr(stage, "engine_args", None), "async_chunk", False),
|
||||
)
|
||||
)
|
||||
for stage in self.stage_configs
|
||||
)
|
||||
self.stage_pools: list[StagePool] = []
|
||||
self.stage_clients: list[StageClient] = [] # logical-stage view for external readers
|
||||
self.input_processor: InputProcessor | None = None
|
||||
@@ -370,6 +384,7 @@ class OmniEngineBase:
|
||||
omni_lb_policy=self._omni_lb_policy,
|
||||
request_queue=self.request_queue,
|
||||
log_stats=self._log_stats,
|
||||
client_config=self._client_config,
|
||||
)
|
||||
self._runtime.initialize()
|
||||
|
||||
@@ -888,24 +903,15 @@ class OmniEngineBase:
|
||||
) -> tuple[str, list[Any]]:
|
||||
"""Resolve stage configs and inject defaults shared by orchestrator/headless."""
|
||||
|
||||
for legacy_arg in ("stage_configs_path", "stage_configs"):
|
||||
if legacy_arg in kwargs:
|
||||
raise ValueError(f"`{legacy_arg}` is no longer supported; use `deploy_config` instead.")
|
||||
|
||||
# log_stats is captured by __init__; its CLI-only negative alias must
|
||||
# not cross into per-stage structured config ownership validation.
|
||||
kwargs.pop("disable_log_stats", None)
|
||||
deploy_config_path = kwargs.pop("deploy_config", None)
|
||||
strategy_config_path = kwargs.pop("strategy_config", None)
|
||||
# CLI callers arrive pre-parsed; offline Python callers may use the
|
||||
# JSON-string form documented in recipes.
|
||||
stage_overrides = parse_stage_overrides(kwargs.pop("stage_overrides", None))
|
||||
|
||||
# ``diffusion_streaming_output`` is the public AsyncOmni/serve kwarg;
|
||||
# stage configs know the field as ``streaming_output``. Mirror only a
|
||||
# truthy value so the CLI's False default does not override deploy YAML.
|
||||
if kwargs.get("diffusion_streaming_output") and kwargs.get("streaming_output") is None:
|
||||
kwargs["streaming_output"] = True
|
||||
config_inputs = prepare_stage_config_inputs(
|
||||
model,
|
||||
kwargs,
|
||||
trust_remote_code=trust_remote_code,
|
||||
)
|
||||
kwargs = config_inputs.kwargs
|
||||
deploy_config_path = config_inputs.deploy_config_path
|
||||
strategy_config_path = config_inputs.strategy_config_path
|
||||
stage_overrides = config_inputs.stage_overrides
|
||||
|
||||
resolution = cast(
|
||||
_ConfigResolutionResult,
|
||||
|
||||
@@ -38,6 +38,7 @@ from vllm_omni.diffusion.data import is_diffusion_request_started_output
|
||||
from vllm_omni.distributed.omni_connectors.utils.config import stage_receives_chunks
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
from vllm_omni.engine.cfg_companion_tracker import CfgCompanionTracker
|
||||
from vllm_omni.engine.errors import NativeKVHandoffError
|
||||
from vllm_omni.engine.membership_controller import MembershipController
|
||||
from vllm_omni.engine.messages import (
|
||||
AbortRequestMessage,
|
||||
@@ -199,6 +200,8 @@ class OrchestratorRequestState:
|
||||
final_stage_id: int = -1
|
||||
final_output_stage_ids: set[int] = field(default_factory=set)
|
||||
finished_final_output_stage_ids: set[int] = field(default_factory=set)
|
||||
finished_stage_ids: set[int] = field(default_factory=set)
|
||||
pending_final_output: OutputMessage | None = None
|
||||
|
||||
# Wall-clock timestamp when the client-facing engine request was accepted.
|
||||
request_timestamp: float = 0.0
|
||||
@@ -219,6 +222,7 @@ class OrchestratorRequestState:
|
||||
session_owned: bool = False
|
||||
running_counter_registered: bool = False
|
||||
request_artifact_dirs: set[str] = field(default_factory=set)
|
||||
native_kv_transfer_id: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -770,20 +774,21 @@ class OrchestratorBase:
|
||||
float(kv_wait_s),
|
||||
)
|
||||
req_state = self.request_states.get(getattr(eco, "request_id", None))
|
||||
if req_state is None or not req_state.streaming.enabled:
|
||||
if req_state is None:
|
||||
continue
|
||||
segment_finished = bool(getattr(eco, "is_segment_finished", False))
|
||||
raw_mm = self._completion_multimodal_output(eco, None)
|
||||
req_state.streaming.segments[stage_id] = StreamingSegmentState(
|
||||
finished=segment_finished,
|
||||
token_ids=(self._coerce_int_list(getattr(eco, "new_token_ids", None)) if segment_finished else []),
|
||||
output_metadata=(dict(raw_mm) if segment_finished and isinstance(raw_mm, dict) else {}),
|
||||
)
|
||||
req_state.streaming.new_prompt_len_snapshot = getattr(
|
||||
eco,
|
||||
"new_prompt_len_snapshot",
|
||||
None,
|
||||
)
|
||||
if req_state.streaming.enabled:
|
||||
segment_finished = bool(getattr(eco, "is_segment_finished", False))
|
||||
raw_mm = self._completion_multimodal_output(eco, None)
|
||||
req_state.streaming.segments[stage_id] = StreamingSegmentState(
|
||||
finished=segment_finished,
|
||||
token_ids=(self._coerce_int_list(getattr(eco, "new_token_ids", None)) if segment_finished else []),
|
||||
output_metadata=(dict(raw_mm) if segment_finished and isinstance(raw_mm, dict) else {}),
|
||||
)
|
||||
req_state.streaming.new_prompt_len_snapshot = getattr(
|
||||
eco,
|
||||
"new_prompt_len_snapshot",
|
||||
None,
|
||||
)
|
||||
if await self._apply_raw_terminal_stage_finish(stage_id, eco, req_state):
|
||||
raw_terminal_request_ids.add(req_state.request_id)
|
||||
await self._report_duplex_session_request_error(stage_id, replica_id, eco, req_state)
|
||||
@@ -794,6 +799,11 @@ class OrchestratorBase:
|
||||
iteration_stats=iteration_stats,
|
||||
)
|
||||
if self._stat_logger is not None and (raw_outputs.scheduler_stats is not None or iteration_stats is not None):
|
||||
key = (stage_id, replica_id)
|
||||
if key not in self._stage_replica_to_engine_idx:
|
||||
engine_idx = len(self._stage_replica_to_engine_idx)
|
||||
self._stat_logger.register_replica(engine_idx, str(stage_id), str(replica_id))
|
||||
self._stage_replica_to_engine_idx[key] = engine_idx
|
||||
self._stat_logger.record(
|
||||
raw_outputs.scheduler_stats,
|
||||
iteration_stats,
|
||||
@@ -1373,6 +1383,16 @@ class OrchestratorBase:
|
||||
try:
|
||||
await dispatch()
|
||||
return True
|
||||
except NativeKVHandoffError as e:
|
||||
await self._fail_request_client_error(
|
||||
req_id,
|
||||
stage_id,
|
||||
str(e),
|
||||
status_code=HTTPStatus.BAD_GATEWAY.value,
|
||||
error_type="NativeKVHandoffError",
|
||||
release_owners=True,
|
||||
)
|
||||
return False
|
||||
except StageUnavailableError as e:
|
||||
# No specific replica to evict: the stage already has no live
|
||||
# replica or the chosen slot was evicted. Fail just this request.
|
||||
@@ -1504,18 +1524,19 @@ class OrchestratorBase:
|
||||
``is_segment_finished=False``, but vLLM's output processor may remove the
|
||||
request state before that EngineCoreOutput is processed.
|
||||
|
||||
Only update ``finished_final_output_stage_ids`` here. Request cleanup stays
|
||||
in ``_route_output`` so downstream async-chunk stages can still deliver
|
||||
outputs after stage-0 session end.
|
||||
Record raw stage completion here. Client completion is
|
||||
resolved after this raw batch passes through the output processor, so a
|
||||
real processed output wins over the swallowed-terminal fallback.
|
||||
"""
|
||||
if getattr(eco, "finish_reason", None) is None:
|
||||
return False
|
||||
if getattr(eco, "is_segment_finished", False):
|
||||
return False
|
||||
|
||||
req_state.finished_stage_ids.add(stage_id)
|
||||
final_output_stage_ids = req_state.final_output_stage_ids or {req_state.final_stage_id}
|
||||
if stage_id not in final_output_stage_ids:
|
||||
return False
|
||||
return True
|
||||
req_state.finished_final_output_stage_ids.add(stage_id)
|
||||
return True
|
||||
|
||||
@@ -1568,16 +1589,23 @@ class OrchestratorBase:
|
||||
replica_id: int,
|
||||
request_ids: set[str],
|
||||
) -> None:
|
||||
"""Finish streaming requests whose raw terminal had no processed output."""
|
||||
"""Finish requests whose raw terminal had no processed output."""
|
||||
pool = self.stage_pools[stage_id]
|
||||
if not pool.final_output:
|
||||
return
|
||||
|
||||
for request_id in request_ids:
|
||||
req_state = self.request_states.get(request_id)
|
||||
if req_state is None or req_state.session_owned:
|
||||
continue
|
||||
|
||||
pending = req_state.pending_final_output
|
||||
if pending is not None:
|
||||
if set(req_state.stage_submit_ts).issubset(req_state.finished_stage_ids):
|
||||
req_state.pending_final_output = None
|
||||
await self.output_async_queue.put(pending)
|
||||
await self._cleanup_request_ids([request_id, *self._cfg_tracker.cleanup_parent(request_id)])
|
||||
# A real terminal output is pending; do not replace it with
|
||||
# the swallowed-output fallback before upstream completion.
|
||||
continue
|
||||
if not pool.final_output:
|
||||
continue
|
||||
final_output_stage_ids = req_state.final_output_stage_ids or {req_state.final_stage_id}
|
||||
if not final_output_stage_ids.issubset(req_state.finished_final_output_stage_ids):
|
||||
continue
|
||||
@@ -1651,27 +1679,41 @@ class OrchestratorBase:
|
||||
await self._cleanup_request_ids([req_id])
|
||||
return
|
||||
|
||||
if finished and not segment_finished:
|
||||
req_state.finished_stage_ids.add(stage_id)
|
||||
|
||||
request_finished = False
|
||||
if finished and self.stage_pools[stage_id].final_output and not segment_finished:
|
||||
req_state.finished_final_output_stage_ids.add(stage_id)
|
||||
final_output_stage_ids = req_state.final_output_stage_ids or {req_state.final_stage_id}
|
||||
request_finished = final_output_stage_ids.issubset(req_state.finished_final_output_stage_ids)
|
||||
if req_state.session_owned:
|
||||
# Session-owned outputs are delivered to their session through
|
||||
# ``_intercept_stage_output`` below, never to a request queue.
|
||||
# Session-owned outputs are delivered through the session interceptor.
|
||||
pass
|
||||
elif self.stage_pools[stage_id].final_output:
|
||||
await self.output_async_queue.put(
|
||||
OutputMessage(
|
||||
request_id=req_id,
|
||||
stage_id=stage_id,
|
||||
replica_id=replica_id,
|
||||
engine_outputs=output,
|
||||
metrics=stage_metrics,
|
||||
finished=request_finished,
|
||||
stage_submit_ts=submit_ts,
|
||||
)
|
||||
message = OutputMessage(
|
||||
request_id=req_id,
|
||||
stage_id=stage_id,
|
||||
replica_id=replica_id,
|
||||
engine_outputs=output,
|
||||
metrics=stage_metrics,
|
||||
finished=request_finished,
|
||||
stage_submit_ts=submit_ts,
|
||||
)
|
||||
if (
|
||||
request_finished
|
||||
and self.async_chunk
|
||||
and not req_state.streaming.enabled
|
||||
and not set(req_state.stage_submit_ts).issubset(req_state.finished_stage_ids)
|
||||
):
|
||||
# Direct chunk delivery can finish the decoder before the
|
||||
# upstream engine's terminal output/metrics reaches this loop.
|
||||
# Keep request state until those messages are routed, otherwise
|
||||
# the frontend publishes incomplete usage and loses stop reasons.
|
||||
req_state.pending_final_output = message
|
||||
request_finished = False
|
||||
else:
|
||||
await self.output_async_queue.put(message)
|
||||
elif stage_metrics is not None:
|
||||
await self.output_async_queue.put(
|
||||
StageMetricsMessage(
|
||||
@@ -1739,6 +1781,12 @@ class OrchestratorBase:
|
||||
is_final_update=True,
|
||||
)
|
||||
|
||||
pending = req_state.pending_final_output
|
||||
if pending is not None and set(req_state.stage_submit_ts).issubset(req_state.finished_stage_ids):
|
||||
req_state.pending_final_output = None
|
||||
await self.output_async_queue.put(pending)
|
||||
request_finished = True
|
||||
|
||||
if request_finished and not req_state.session_owned:
|
||||
await self._cleanup_request_ids([req_id, *self._cfg_tracker.cleanup_parent(req_id)])
|
||||
|
||||
@@ -2203,12 +2251,13 @@ class OrchestratorBase:
|
||||
req_id,
|
||||
req_state,
|
||||
diffusion_prompt,
|
||||
submit_kwargs={
|
||||
"kv_sender_info": self._build_kv_sender_info(
|
||||
list(getattr(next_client, "engine_input_source", None) or [src_stage_id]),
|
||||
request_id=req_id,
|
||||
)
|
||||
},
|
||||
submit_kwargs=self._diffusion_submit_kwargs(
|
||||
req_id,
|
||||
src_stage_id,
|
||||
next_client,
|
||||
req_state,
|
||||
output,
|
||||
),
|
||||
params_override=self._maybe_clone_diffusion_params_for_cfg(req_id, params),
|
||||
)
|
||||
self._on_stage_submitted(
|
||||
@@ -2462,12 +2511,12 @@ class OrchestratorBase:
|
||||
_t_submit_start = _time.perf_counter()
|
||||
|
||||
if next_pool.stage_type == "diffusion":
|
||||
submit_kwargs = {
|
||||
"kv_sender_info": self._build_kv_sender_info(
|
||||
list(getattr(next_pool.stage_client, "engine_input_source", None) or [next_stage_id - 1]),
|
||||
request_id=request_id,
|
||||
)
|
||||
}
|
||||
submit_kwargs = self._diffusion_submit_kwargs(
|
||||
request_id,
|
||||
next_stage_id - 1,
|
||||
next_pool.stage_client,
|
||||
req_state,
|
||||
)
|
||||
submitted = await self._dispatch_or_fail_request(
|
||||
lambda: next_pool.submit_initial(
|
||||
request_id,
|
||||
@@ -2480,8 +2529,6 @@ class OrchestratorBase:
|
||||
operation="async-chunk prewarm",
|
||||
)
|
||||
else:
|
||||
import copy
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.adapter import compute_talker_prompt_ids_length
|
||||
|
||||
try:
|
||||
@@ -2504,7 +2551,9 @@ class OrchestratorBase:
|
||||
|
||||
original_prompt = req_state.prompt
|
||||
if isinstance(original_prompt, dict):
|
||||
base_input = copy.deepcopy(original_prompt)
|
||||
from vllm_omni.engine.request_snapshot import copy_request_snapshot
|
||||
|
||||
base_input = copy_request_snapshot(original_prompt)
|
||||
else:
|
||||
base_input = {}
|
||||
|
||||
@@ -2564,6 +2613,67 @@ class OrchestratorBase:
|
||||
|
||||
return True
|
||||
|
||||
def _maybe_attach_native_kv_transfer_params(
|
||||
self,
|
||||
req_state: OrchestratorRequestState,
|
||||
prompt: Any,
|
||||
) -> None:
|
||||
source_stage_id = 0
|
||||
if source_stage_id + 1 > req_state.final_stage_id:
|
||||
return
|
||||
config = getattr(self.stage_pools[source_stage_id].stage_vllm_config, "kv_transfer_config", None)
|
||||
if getattr(config, "kv_role", None) != "kv_producer":
|
||||
return
|
||||
if self.stage_pools[source_stage_id + 1].stage_type != "diffusion":
|
||||
return
|
||||
|
||||
from vllm_omni.diffusion.diffusion_kv.kv_connector import build_source_kv_transfer_params, mint_transfer_id
|
||||
|
||||
transfer_id = mint_transfer_id(req_state.request_id)
|
||||
req_state.native_kv_transfer_id = transfer_id
|
||||
params = build_source_kv_transfer_params(
|
||||
transfer_id=transfer_id,
|
||||
remote_engine_id=None,
|
||||
remote_bootstrap_addr=None,
|
||||
)
|
||||
for sampling in (req_state.sampling_params_list[source_stage_id], prompt.sampling_params):
|
||||
sampling.extra_args = {**(sampling.extra_args or {}), "kv_transfer_params": params}
|
||||
|
||||
def _diffusion_submit_kwargs(
|
||||
self,
|
||||
request_id: str,
|
||||
source_stage_id: int,
|
||||
next_client: Any,
|
||||
req_state: OrchestratorRequestState,
|
||||
output: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
source_stage_ids = list(getattr(next_client, "engine_input_source", None) or [source_stage_id])
|
||||
if req_state.native_kv_transfer_id is None:
|
||||
return {"kv_sender_info": self._build_kv_sender_info(source_stage_ids, request_id=request_id)}
|
||||
if output is None:
|
||||
raise NativeKVHandoffError("Native KV handoff requires one completed AR source")
|
||||
from vllm_omni.diffusion.diffusion_kv.kv_connector import (
|
||||
bootstrap_addr_from_kv_transfer_config,
|
||||
build_target_kv_transfer_params,
|
||||
)
|
||||
|
||||
source = self.stage_pools[source_stage_id].get_bound_client(request_id)
|
||||
config = getattr(getattr(source, "vllm_config", None), "kv_transfer_config", None)
|
||||
if source is None or config is None:
|
||||
raise NativeKVHandoffError(
|
||||
f"Native KV handoff for {request_id}: bound AR replica or its KV configuration is unavailable"
|
||||
)
|
||||
params = getattr(output, "kv_transfer_params", None)
|
||||
if not params or "num_transfer_tokens" not in params:
|
||||
raise NativeKVHandoffError("AR source completed without native KV transfer metadata")
|
||||
return {
|
||||
"kv_transfer_params": build_target_kv_transfer_params(
|
||||
source_params=params,
|
||||
remote_engine_id=config.engine_id,
|
||||
remote_bootstrap_addr=bootstrap_addr_from_kv_transfer_config(config),
|
||||
)
|
||||
}
|
||||
|
||||
def _build_kv_sender_info(
|
||||
self,
|
||||
sender_stage_ids: list[int],
|
||||
@@ -2687,6 +2797,7 @@ class Orchestrator(OrchestratorBase):
|
||||
request_artifact_dirs=set(msg.request_artifact_dirs or ()),
|
||||
)
|
||||
self.request_states[request_id] = req_state
|
||||
self._maybe_attach_native_kv_transfer_params(req_state, prompt)
|
||||
self._register_running_request(req_state)
|
||||
req_state.streaming.enabled = bool(getattr(prompt, "resumable", False))
|
||||
req_state.stage_submit_ts[stage_id] = _time.time()
|
||||
|
||||
@@ -182,8 +182,8 @@ class OrchestratorMonitor:
|
||||
|
||||
self._loop_idle = 0
|
||||
self._loop_active = 0
|
||||
self._dispatch_queue_size = 0
|
||||
self._dispatch_queue_high_water = 0
|
||||
# Queued work carries into the next window even without new arrivals.
|
||||
self._dispatch_queue_high_water = self._dispatch_queue_size
|
||||
self._window_start_mono = now_mono
|
||||
|
||||
def _log_summary(self, output_path: str) -> None:
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Full request snapshots with a fast path for immutable scalar leaves."""
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
_ATOMIC_TYPES = frozenset((type(None), bool, int, float, complex, str, bytes))
|
||||
|
||||
|
||||
def copy_request_snapshot(value: Any, memo: dict[int, Any] | None = None) -> Any:
|
||||
"""Deep-copy all fields, preserving aliases and isolating mutable containers.
|
||||
|
||||
Plain numeric/text trees do not need generic object dispatch or an identity
|
||||
lookup for each immutable scalar. Subclasses and other objects retain their
|
||||
regular deepcopy contracts. No model fields are filtered or shared here.
|
||||
"""
|
||||
kind = type(value)
|
||||
if kind in _ATOMIC_TYPES:
|
||||
return value
|
||||
if memo is None:
|
||||
memo = {}
|
||||
key = id(value)
|
||||
if key in memo:
|
||||
return memo[key]
|
||||
if kind is list:
|
||||
atomic = all(type(item) in _ATOMIC_TYPES for item in value)
|
||||
result = value.copy() if atomic else []
|
||||
memo[key] = result
|
||||
if not atomic:
|
||||
result.extend(copy_request_snapshot(item, memo) for item in value)
|
||||
elif kind is dict:
|
||||
result = {}
|
||||
memo[key] = result
|
||||
for k, item in value.items():
|
||||
result[copy_request_snapshot(k, memo)] = copy_request_snapshot(item, memo)
|
||||
else:
|
||||
return copy.deepcopy(value, memo)
|
||||
# Keep sources alive for the duration of a copy, including custom deepcopy
|
||||
# implementations that mutate a source container while being visited.
|
||||
memo.setdefault(id(memo), []).append(value)
|
||||
return result
|
||||
@@ -287,8 +287,13 @@ def check_admission(
|
||||
|
||||
|
||||
def _diffusion_utilization(replica: Any) -> float | None:
|
||||
"""Best-effort gpu_memory_utilization for a diffusion replica from raw args."""
|
||||
"""Resolve a diffusion replica's memory budget from typed or legacy config."""
|
||||
stage_cfg = getattr(replica, "stage_cfg", None)
|
||||
cache_config = getattr(stage_cfg, "cache_config", None)
|
||||
util = getattr(cache_config, "gpu_memory_utilization", None)
|
||||
if util is not None:
|
||||
return float(util)
|
||||
|
||||
engine_args = getattr(stage_cfg, "engine_args", None)
|
||||
if isinstance(engine_args, dict):
|
||||
util = engine_args.get("gpu_memory_utilization")
|
||||
|
||||
@@ -19,7 +19,7 @@ import vllm.v1.engine as _vllm_engine_module
|
||||
import vllm.v1.engine.core_client as _vllm_core_client_module
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
from vllm.v1.engine.core_client import AsyncMPClient, DPLBAsyncMPClient
|
||||
from vllm.v1.engine.core_client import AsyncMPClient, DPLBAsyncMPClient, MPClient
|
||||
from vllm.v1.engine.exceptions import EngineDeadError
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.utils.config import (
|
||||
@@ -232,6 +232,9 @@ class StageEngineCoreClientBase(StageClientBase):
|
||||
if self.resources.engine_dead:
|
||||
raise EngineDeadError(f"Stage-{self.stage_id} engine core is dead")
|
||||
|
||||
def _apply_ready_response(self, payload: bytes) -> None:
|
||||
MPClient._apply_ready_response(self, payload)
|
||||
|
||||
# ==================== Overrides ====================
|
||||
|
||||
async def add_request_async(self, request: EngineCoreRequest) -> None:
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""
|
||||
Stage Core Process for vLLM-Omni V1 architecture.
|
||||
|
||||
@@ -27,6 +30,7 @@ from vllm.v1.engine.utils import (
|
||||
EngineZmqAddresses,
|
||||
SignalCallback,
|
||||
)
|
||||
from vllm.v1.executor.uniproc_executor import UniProcExecutor
|
||||
|
||||
from vllm_omni.distributed.omni_coordinator import create_stage_coord_client
|
||||
from vllm_omni.engine import OmniEngineCoreRequest
|
||||
@@ -75,6 +79,24 @@ def _signal_exit_code(signum: int) -> int:
|
||||
return _SIGNAL_EXIT_BASE + signum
|
||||
|
||||
|
||||
def _bind_native_data_plane_ready_sink(model_executor: Any, scheduler: Any) -> bool:
|
||||
"""Bind the TP1 in-process runner control plane directly to its scheduler."""
|
||||
if not isinstance(model_executor, UniProcExecutor):
|
||||
return False
|
||||
parallel_config = model_executor.vllm_config.parallel_config
|
||||
if parallel_config.tensor_parallel_size != 1 or parallel_config.pipeline_parallel_size != 1:
|
||||
return False
|
||||
driver_worker = getattr(model_executor, "driver_worker", None)
|
||||
worker = getattr(driver_worker, "worker", None)
|
||||
model_runner = getattr(worker, "model_runner", None)
|
||||
data_plane = getattr(model_runner, "_omni_data_plane", None)
|
||||
sink = getattr(scheduler, "enqueue_omni_connector_output", None)
|
||||
if data_plane is None or not callable(sink):
|
||||
return False
|
||||
data_plane.set_omni_connector_output_sink(sink)
|
||||
return True
|
||||
|
||||
|
||||
class StageEngineCoreProc(EngineCoreProc):
|
||||
"""Stage-specific engine core process for vLLM-Omni.
|
||||
|
||||
@@ -83,6 +105,11 @@ class StageEngineCoreProc(EngineCoreProc):
|
||||
``EngineCoreProc.run_engine_core()``.
|
||||
"""
|
||||
|
||||
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if _bind_native_data_plane_ready_sink(self.model_executor, self.scheduler):
|
||||
logger.info("Bound native MRv2 connector readiness directly to the scheduler inbox.")
|
||||
|
||||
def preprocess_add_request(self, request: OmniEngineCoreRequest) -> tuple[Any, int]:
|
||||
"""Preserve omni payloads when vLLM builds its scheduler request."""
|
||||
scheduler_request, current_wave = super().preprocess_add_request(request)
|
||||
|
||||
@@ -13,10 +13,12 @@ import threading
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing import connection
|
||||
from multiprocessing.process import BaseProcess
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import msgspec
|
||||
import torch
|
||||
import zmq
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.config import VllmConfig
|
||||
@@ -33,6 +35,7 @@ from vllm.v1.engine.utils import (
|
||||
)
|
||||
from vllm.v1.executor import Executor
|
||||
|
||||
from vllm_omni.config.omni_config import BaseVllmOmniStageConfig
|
||||
from vllm_omni.distributed.omni_connectors.utils import initialization
|
||||
from vllm_omni.engine import stage_init_utils
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
@@ -67,11 +70,13 @@ def _serialize_stage_config(stage_config: Any) -> Any:
|
||||
"""Convert a stage config to msgpack-friendly builtins."""
|
||||
if stage_config is None or isinstance(stage_config, (str, bytes, int, float, bool)):
|
||||
return stage_config
|
||||
if isinstance(stage_config, torch.dtype):
|
||||
return str(stage_config).removeprefix("torch.")
|
||||
|
||||
if OmegaConf.is_config(stage_config):
|
||||
return _serialize_stage_config(OmegaConf.to_container(stage_config, resolve=True))
|
||||
|
||||
if dataclasses.is_dataclass(stage_config):
|
||||
if dataclasses.is_dataclass(stage_config) and not isinstance(stage_config, type):
|
||||
return _serialize_stage_config(dataclasses.asdict(stage_config))
|
||||
|
||||
if isinstance(stage_config, dict):
|
||||
@@ -1134,6 +1139,8 @@ def launch_stage_replica(
|
||||
stage_visible_devices: str | None = None,
|
||||
spawn_device_lock: threading.Lock | None = None,
|
||||
omni_parallel_stage_init: bool = False,
|
||||
num_api_servers: int = 1,
|
||||
watched_frontend_processes: list[BaseProcess] | None = None,
|
||||
) -> Iterator[StageReplicaResources]:
|
||||
"""Launch a local LLM stage replica.
|
||||
|
||||
@@ -1144,6 +1151,8 @@ def launch_stage_replica(
|
||||
keep the same returned resource bundle.
|
||||
"""
|
||||
if omni_master_server is not None:
|
||||
if num_api_servers != 1:
|
||||
raise ValueError("Multiple API servers are not supported with distributed stage launch")
|
||||
with _launch_omni_core_engines(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
@@ -1169,7 +1178,16 @@ def launch_stage_replica(
|
||||
|
||||
from vllm_omni.engine.stage_engine_core_proc_manager import StageEngineCoreProcManager
|
||||
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
if num_api_servers > 1:
|
||||
# Multi-API Omni is intentionally local-only. IPC paths avoid the
|
||||
# bind-after-allocation race of tcp://host:0 and are stable for every
|
||||
# stage, including stages that are not used by APIServerProcessManager.
|
||||
addresses = EngineZmqAddresses(
|
||||
inputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
|
||||
outputs=[get_open_zmq_ipc_path() for _ in range(num_api_servers)],
|
||||
)
|
||||
else:
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
handshake_address = get_open_zmq_ipc_path()
|
||||
engines_to_handshake = [CoreEngine(index=0, local=True)]
|
||||
with scoped_spawn_device_env(stage_visible_devices, spawn_device_lock, stage_id=stage_id, replica_id=replica_id):
|
||||
@@ -1193,18 +1211,21 @@ def launch_stage_replica(
|
||||
manager=engine_manager,
|
||||
addresses=addresses,
|
||||
)
|
||||
engine_launch = CoreEngineLaunch(
|
||||
engine_manager=engine_manager,
|
||||
coordinator=None,
|
||||
addresses=addresses,
|
||||
tensor_queue=None,
|
||||
)
|
||||
if watched_frontend_processes is not None:
|
||||
engine_launch.watched_frontend_processes = watched_frontend_processes
|
||||
wait_for_engine_startup(
|
||||
handshake_socket,
|
||||
engines_to_handshake,
|
||||
vllm_config.parallel_config,
|
||||
False, # coordinated_dp
|
||||
vllm_config.cache_config,
|
||||
CoreEngineLaunch(
|
||||
engine_manager=engine_manager,
|
||||
coordinator=None,
|
||||
addresses=addresses,
|
||||
tensor_queue=None,
|
||||
),
|
||||
engine_launch,
|
||||
)
|
||||
|
||||
|
||||
@@ -1403,7 +1424,7 @@ def get_headless_replica_devices(
|
||||
omni_dp_size_local: int,
|
||||
) -> list[str | None]:
|
||||
"""Return per-replica device slices for a headless stage."""
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", None)
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", None))
|
||||
devices_str: str | None = None
|
||||
if runtime_cfg is not None:
|
||||
devices_str = (
|
||||
@@ -1509,10 +1530,11 @@ def launch_headless_diffusion_replicas(
|
||||
stage_id,
|
||||
)
|
||||
|
||||
# Headless diffusion startup and its downstream helpers still consume the
|
||||
# legacy StageConfig shape; switch this with the coordinated RFC #4021
|
||||
# stage-init cutover.
|
||||
metadata = stage_init_utils.extract_legacy_stage_metadata(stage_cfg)
|
||||
metadata = (
|
||||
stage_init_utils.extract_stage_metadata_from_omni_stage_config(stage_cfg)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else stage_init_utils.extract_legacy_stage_metadata(stage_cfg)
|
||||
)
|
||||
if omni_conn_cfg:
|
||||
inject_omni_kv_config(stage_cfg, omni_conn_cfg, omni_from, omni_to)
|
||||
# Headless single-stage launch must still infer cross-stage TP topology
|
||||
|
||||
@@ -402,6 +402,11 @@ def _tp_size_for_stage(stage_configs: Sequence[Any], stage_id: Any) -> int | Non
|
||||
for stage_cfg in stage_configs:
|
||||
if str(getattr(stage_cfg, "stage_id", None)) not in id_strs:
|
||||
continue
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig):
|
||||
try:
|
||||
return max(1, int(stage_cfg.parallel_config.tensor_parallel_size))
|
||||
except (TypeError, ValueError):
|
||||
return 1
|
||||
engine_args = getattr(stage_cfg, "engine_args", None)
|
||||
if engine_args is None:
|
||||
return 1
|
||||
@@ -489,11 +494,15 @@ def inject_kv_stage_info(stage_cfg: Any, stage_id: int, stage_configs: Sequence[
|
||||
rank mappings automatically.
|
||||
"""
|
||||
try:
|
||||
engine_args = stage_cfg.engine_args
|
||||
if hasattr(engine_args, "get"):
|
||||
omni_kv = engine_args.get("omni_kv_config", None)
|
||||
connector_config = getattr(stage_cfg, "connector_config", None)
|
||||
if connector_config is not None:
|
||||
omni_kv = connector_config.omni_kv_config
|
||||
else:
|
||||
omni_kv = getattr(engine_args, "omni_kv_config", None)
|
||||
engine_args = stage_cfg.engine_args
|
||||
if hasattr(engine_args, "get"):
|
||||
omni_kv = engine_args.get("omni_kv_config", None)
|
||||
else:
|
||||
omni_kv = getattr(engine_args, "omni_kv_config", None)
|
||||
|
||||
if omni_kv is None:
|
||||
return
|
||||
@@ -504,7 +513,11 @@ def inject_kv_stage_info(stage_cfg: Any, stage_id: int, stage_configs: Sequence[
|
||||
if "stage_id" not in omni_kv:
|
||||
omni_kv["stage_id"] = stage_id
|
||||
|
||||
engine_input_source = getattr(stage_cfg, "engine_input_source", None)
|
||||
engine_input_source = (
|
||||
getattr(stage_cfg, "input_sources", None)
|
||||
if connector_config is not None
|
||||
else getattr(stage_cfg, "engine_input_source", None)
|
||||
)
|
||||
if engine_input_source is not None:
|
||||
if hasattr(omni_kv, "setdefault"):
|
||||
omni_kv.setdefault("engine_input_source", list(engine_input_source))
|
||||
@@ -703,17 +716,16 @@ def _resolve_omni_metadata_hook(path: str | None) -> Callable | None:
|
||||
def extract_stage_metadata_from_omni_stage_config(
|
||||
stage_config: BaseVllmOmniStageConfig,
|
||||
) -> StageMetadata:
|
||||
"""Project one typed stage config into metadata for a future cutover.
|
||||
|
||||
This projection is not used by production startup yet. Current replica
|
||||
layout, engine-argument, remote-diffusion, and platform setup paths still
|
||||
require the legacy StageConfig/OmegaConf shape.
|
||||
"""
|
||||
"""Project one typed stage config into production runtime metadata."""
|
||||
stage_type: Literal["llm", "diffusion"] = "diffusion" if stage_config.stage_type == StageType.DIFFUSION else "llm"
|
||||
sampling_params_cls = SamplingParams if stage_type == "llm" else OmniDiffusionSamplingParams
|
||||
sampling_params: OmniSamplingParams = sampling_params_cls(
|
||||
**(stage_config.model_config.default_sampling_params or {})
|
||||
)
|
||||
pooling_config = stage_config.pooling_config
|
||||
if stage_type == "llm" and (pooling_config.runner or "").lower() == "pooling":
|
||||
sampling_params: OmniSamplingParams | PoolingParams = (
|
||||
copy.deepcopy(pooling_config.default_pooling_params) or PoolingParams()
|
||||
)
|
||||
else:
|
||||
sampling_params_cls = SamplingParams if stage_type == "llm" else OmniDiffusionSamplingParams
|
||||
sampling_params = sampling_params_cls(**(stage_config.model_config.default_sampling_params or {}))
|
||||
custom_process_input_func = _resolve_omni_metadata_hook(stage_config.custom_process_input_func)
|
||||
|
||||
if stage_type == "diffusion":
|
||||
@@ -878,7 +890,9 @@ def _get_local_llm_parallel_sizes(
|
||||
unset.
|
||||
"""
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
engine_args = getattr(stage_cfg, "parallel_config", None)
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
tp_size = int(_get_attr_or_item(engine_args, "tensor_parallel_size", 1) or 1)
|
||||
pp_size = int(_get_attr_or_item(engine_args, "pipeline_parallel_size", 1) or 1)
|
||||
local_dp_size = _get_attr_or_item(engine_args, "data_parallel_size_local", None)
|
||||
@@ -889,9 +903,12 @@ def _get_local_llm_parallel_sizes(
|
||||
|
||||
def get_stage_devices_per_replica(stage_cfg: Any, engine_args: Any | None = None) -> int:
|
||||
"""Return the number of devices consumed by one replica of *stage_cfg*."""
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
if getattr(stage_cfg, "stage_type", "llm") == "diffusion":
|
||||
typed_parallel_config = getattr(stage_cfg, "parallel_config", None)
|
||||
if typed_parallel_config is not None:
|
||||
return max(1, int(typed_parallel_config.world_size))
|
||||
if engine_args is None:
|
||||
engine_args = getattr(stage_cfg, "engine_args", {})
|
||||
parallel_config = _get_attr_or_item(engine_args, "parallel_config")
|
||||
if parallel_config is None:
|
||||
return 1
|
||||
@@ -933,7 +950,7 @@ def compute_replica_layout(
|
||||
"""
|
||||
replicas_per_stage: list[int] = []
|
||||
for stage_cfg in stage_configs:
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", {})
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", {}))
|
||||
num_replicas = int(
|
||||
runtime_cfg.get("num_replicas", 1)
|
||||
if hasattr(runtime_cfg, "get")
|
||||
@@ -948,7 +965,7 @@ def compute_replica_layout(
|
||||
num_replicas = replicas_per_stage[stage_id]
|
||||
if num_replicas <= 1:
|
||||
continue
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", {})
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", {}))
|
||||
devices_str = (
|
||||
runtime_cfg.get("devices") if hasattr(runtime_cfg, "get") else getattr(runtime_cfg, "devices", None)
|
||||
)
|
||||
@@ -1086,15 +1103,31 @@ def _project_omni_stage_engine_args(
|
||||
diffusion_stage = cast(VllmOmniDiffusionStageConfig, stage_config)
|
||||
engine_args.update(_project_omni_config_fields(diffusion_stage.diffusion_config))
|
||||
|
||||
model_excluded_fields = {
|
||||
"default_sampling_params",
|
||||
"has_sampling_extra_args",
|
||||
}
|
||||
runtime_excluded_fields = {"devices", "num_replicas", "env", "num_gpus"}
|
||||
if not is_diffusion:
|
||||
# These values configure OmniDiffusionConfig or its worker process;
|
||||
# OmniEngineArgs has no matching fields for LLM stages.
|
||||
model_excluded_fields.update(
|
||||
{
|
||||
"disable_autocast",
|
||||
"enable_multithread_weight_load",
|
||||
"num_weight_load_threads",
|
||||
}
|
||||
)
|
||||
runtime_excluded_fields.add("log_level")
|
||||
|
||||
for config, excluded_fields in (
|
||||
(
|
||||
stage_config.model_config,
|
||||
frozenset({"default_sampling_params", "has_sampling_extra_args"}),
|
||||
frozenset(model_excluded_fields),
|
||||
),
|
||||
(
|
||||
stage_config.runtime_config,
|
||||
frozenset({"devices", "num_replicas", "env", "num_gpus"})
|
||||
| (frozenset({"additional_config"}) if is_diffusion else frozenset()),
|
||||
frozenset(runtime_excluded_fields) | (frozenset({"additional_config"}) if is_diffusion else frozenset()),
|
||||
),
|
||||
):
|
||||
engine_args.update(
|
||||
@@ -1103,6 +1136,11 @@ def _project_omni_stage_engine_args(
|
||||
exclude=excluded_fields,
|
||||
)
|
||||
)
|
||||
pooling_config = stage_config.pooling_config
|
||||
if pooling_config.runner is not None:
|
||||
engine_args["runner"] = pooling_config.runner
|
||||
if pooling_config.pooling_output_decoder is not None:
|
||||
engine_args["pooling_output_decoder"] = pooling_config.pooling_output_decoder
|
||||
|
||||
if is_diffusion:
|
||||
for config, field_map in (
|
||||
@@ -1151,6 +1189,8 @@ def _project_omni_stage_engine_args(
|
||||
engine_args["async_chunk"] = connector_config.async_chunk
|
||||
if connector_config.omni_kv_config is not None:
|
||||
engine_args["omni_kv_config"] = copy.deepcopy(connector_config.omni_kv_config)
|
||||
if connector_config.kv_transfer_config is not None:
|
||||
engine_args["kv_transfer_config"] = copy.deepcopy(connector_config.kv_transfer_config)
|
||||
|
||||
if is_diffusion:
|
||||
engine_args["parallel_config"] = _project_omni_config_fields(
|
||||
@@ -1330,11 +1370,9 @@ def build_engine_args_dict(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
cli_tokenizer: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build engine arguments through the stable production entry point.
|
||||
"""Preserve the legacy engine-argument API for compatibility callers.
|
||||
|
||||
Production inputs still use the legacy stage representation. Keep that
|
||||
compatibility choice behind this function so callers do not bind directly
|
||||
to a representation-specific implementation.
|
||||
Typed runtime stages use ``build_engine_args_dict_from_omni_stage_config``.
|
||||
"""
|
||||
return build_legacy_engine_args_dict(
|
||||
stage_config,
|
||||
@@ -1350,13 +1388,7 @@ def build_engine_args_dict_from_omni_stage_config(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
cli_tokenizer: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Project one typed stage config into backend engine arguments.
|
||||
|
||||
This projection is prepared for the RFC #4021 stage-init cutover. Current
|
||||
production startup reaches the legacy implementation through
|
||||
``build_engine_args_dict`` while strategy and startup-plan inputs still
|
||||
use the legacy representation.
|
||||
"""
|
||||
"""Project one typed production stage config into backend engine arguments."""
|
||||
engine_args_dict = _project_omni_stage_engine_args(stage_config)
|
||||
_apply_rocm_attention_backend(engine_args_dict, stage_config.stage_type)
|
||||
return _finalize_engine_args_dict(
|
||||
@@ -1391,7 +1423,7 @@ def _check_stage_device_layout(stage_config: Any, engine_args_dict: dict[str, An
|
||||
"""
|
||||
from vllm_omni.config.composable_parallel import StrategyApplyError, check_device_layout
|
||||
|
||||
runtime = getattr(stage_config, "runtime", None)
|
||||
runtime = getattr(stage_config, "runtime_config", getattr(stage_config, "runtime", None))
|
||||
devices = _get_attr_or_item(runtime, "devices", None) if runtime is not None else None
|
||||
if devices is None:
|
||||
# No explicit placement -> vLLM assigns devices itself; nothing to check.
|
||||
@@ -1445,6 +1477,8 @@ def build_vllm_config(
|
||||
stage_connector_spec: dict[str, Any] | None = None,
|
||||
engine_args_dict: dict[str, Any] | None = None,
|
||||
headless: bool = False,
|
||||
api_process_count: int = 1,
|
||||
api_process_rank: int = 0,
|
||||
) -> tuple[Any, type]:
|
||||
"""Build engine args, then create VllmConfig and executor_class.
|
||||
|
||||
@@ -1452,13 +1486,18 @@ def build_vllm_config(
|
||||
(vllm_config, executor_class)
|
||||
"""
|
||||
if engine_args_dict is None:
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_config,
|
||||
model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_config, model, stage_connector_spec=stage_connector_spec
|
||||
)
|
||||
if isinstance(stage_config, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(stage_config, model, stage_connector_spec=stage_connector_spec)
|
||||
)
|
||||
|
||||
filtered_engine_args_dict = filter_dataclass_kwargs(OmniEngineArgs, engine_args_dict)
|
||||
if api_process_count != 1 or api_process_rank != 0:
|
||||
filtered_engine_args_dict["_api_process_count"] = api_process_count
|
||||
filtered_engine_args_dict["_api_process_rank"] = api_process_rank
|
||||
|
||||
# _to_dict serializes dataclass fields (e.g. StructuredOutputsConfig) into
|
||||
# plain dicts. When OmniEngineArgs is instantiated with the dict, these
|
||||
@@ -1715,6 +1754,7 @@ def acquire_device_locks(
|
||||
stage_id: int,
|
||||
engine_args_dict: dict[str, Any],
|
||||
stage_init_timeout: int,
|
||||
locked_devices: set[int] | None = None,
|
||||
) -> list[int]:
|
||||
"""Acquire exclusive file locks on devices needed by this stage.
|
||||
|
||||
@@ -1769,8 +1809,7 @@ def acquire_device_locks(
|
||||
f"but only {len(physical_devices)} device(s) are available: {physical_devices}"
|
||||
)
|
||||
|
||||
num_devices_to_lock = num_devices_per_stage
|
||||
devices_to_lock = sorted(physical_devices[:num_devices_to_lock])
|
||||
devices_to_lock = sorted(set(physical_devices[:num_devices_per_stage]) - (locked_devices or set()))
|
||||
|
||||
logger.debug(
|
||||
"Parallel config: TP=%d, PP=%d, DP=%d, PCP=%d, SP=%d, CFG=%d; will lock %d devices: %s",
|
||||
@@ -1780,7 +1819,7 @@ def acquire_device_locks(
|
||||
prefill_context_parallel_size,
|
||||
sequence_parallel_size,
|
||||
cfg_parallel_size,
|
||||
num_devices_to_lock,
|
||||
len(devices_to_lock),
|
||||
devices_to_lock,
|
||||
)
|
||||
|
||||
@@ -1798,6 +1837,8 @@ def acquire_device_locks(
|
||||
record_lock_holder_pid(lock_fd, lock_writable)
|
||||
lock_acquired = True
|
||||
lock_fds.append(lock_fd)
|
||||
if locked_devices is not None:
|
||||
locked_devices.add(device_id)
|
||||
logger.debug("Acquired exclusive lock for device %s", device_id)
|
||||
except BlockingIOError:
|
||||
os.close(lock_fd)
|
||||
@@ -1926,9 +1967,25 @@ def build_diffusion_config(
|
||||
metadata: StageMetadata,
|
||||
) -> Any:
|
||||
"""Build diffusion config for a stage."""
|
||||
from vllm_omni.config.omni_config import extract_diffusion_stage_config_kwargs
|
||||
|
||||
engine_args_dict = build_engine_args_dict(stage_cfg, model)
|
||||
od_config = OmniDiffusionConfig.from_kwargs(**engine_args_dict)
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(stage_cfg, model)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(stage_cfg, model)
|
||||
)
|
||||
stage_id = engine_args_dict.get("stage_id", metadata.stage_id)
|
||||
diffusion_kwargs = extract_diffusion_stage_config_kwargs(
|
||||
engine_args_dict,
|
||||
stage_id=stage_id,
|
||||
include_engine_adapter_metadata=True,
|
||||
)
|
||||
od_config = OmniDiffusionConfig(**{name: value for name, value in diffusion_kwargs.items() if value is not None})
|
||||
|
||||
for dimension in ("height", "width"):
|
||||
value = getattr(metadata.default_sampling_params, dimension, None)
|
||||
if isinstance(value, int) and value > 0:
|
||||
od_config.additional_config.setdefault(f"diffusion_kv_profile_{dimension}", value)
|
||||
|
||||
num_devices_per_stage = od_config.parallel_config.world_size
|
||||
device_control_env = current_omni_platform.device_control_env_var
|
||||
|
||||
@@ -15,6 +15,7 @@ from vllm.logger import init_logger
|
||||
from vllm.v1.engine import EngineCoreOutputs
|
||||
from vllm.v1.metrics.stats import IterationStats
|
||||
|
||||
from vllm_omni.data_entry_keys import flatten_payload
|
||||
from vllm_omni.distributed.omni_coordinator import (
|
||||
LoadBalancer,
|
||||
OmniCoordClientForHub,
|
||||
@@ -22,6 +23,7 @@ from vllm_omni.distributed.omni_coordinator import (
|
||||
ReplicaStatus,
|
||||
)
|
||||
from vllm_omni.distributed.omni_coordinator.load_balancer import Task
|
||||
from vllm_omni.engine.serialization import deserialize_additional_information
|
||||
from vllm_omni.engine.stage_client import (
|
||||
StagePoolClient,
|
||||
StagePoolDiffusionClient,
|
||||
@@ -1136,8 +1138,30 @@ class StagePool:
|
||||
# gauges for that interval.
|
||||
if not outputs.outputs and outputs.scheduler_stats is None and not outputs.finished_requests:
|
||||
return None
|
||||
self._rehydrate_pooling_output_payloads(outputs)
|
||||
return outputs
|
||||
|
||||
@staticmethod
|
||||
def _rehydrate_pooling_output_payloads(outputs: EngineCoreOutputs) -> None:
|
||||
"""Restore dict-shaped pooling_output from its bytes carrier (MR V2).
|
||||
|
||||
vLLM decodes EngineCoreOutput.pooling_output as a torch.Tensor, so MR
|
||||
V2 runners ship the per-request dict handoff via ``pooling_output_payload``
|
||||
with ``pooling_output=None``. Decode it back here so downstream stage-input
|
||||
processors see the same ``pooling_output`` shape as the legacy runner.
|
||||
"""
|
||||
for eco in outputs.outputs:
|
||||
payload = getattr(eco, "pooling_output_payload", None)
|
||||
if payload is None:
|
||||
continue
|
||||
if getattr(eco, "pooling_output", None) is None:
|
||||
# deserialize_* returns the nested OmniPayload form; the producer
|
||||
# serialized a flat (dotted-key) pooler dict, and downstream
|
||||
# consumers (e.g. talker2code2wav_full_payload) read flat keys like
|
||||
# "codes.audio". Re-flatten to restore the exact on-wire shape.
|
||||
eco.pooling_output = flatten_payload(deserialize_additional_information(payload))
|
||||
eco.pooling_output_payload = None
|
||||
|
||||
async def process_llm_raw_outputs(
|
||||
self,
|
||||
replica_id: int,
|
||||
|
||||
+491
-152
@@ -6,19 +6,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import contextlib
|
||||
import copy
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable, Iterator, Mapping, Sequence
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, cast
|
||||
from contextlib import AbstractContextManager, contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from multiprocessing.process import BaseProcess
|
||||
from typing import Any, TypedDict, cast
|
||||
|
||||
import janus
|
||||
from omegaconf import OmegaConf
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.config.omni_config import BaseVllmOmniStageConfig, VllmOmniDiffusionStageConfig
|
||||
from vllm_omni.distributed.omni_connectors.utils.initialization import (
|
||||
resolve_omni_kv_config_for_stage,
|
||||
)
|
||||
@@ -46,14 +47,17 @@ from vllm_omni.engine.stage_engine_startup import (
|
||||
from vllm_omni.engine.stage_init_utils import (
|
||||
LogicalStageInitPlan,
|
||||
ReplicaInitPlan,
|
||||
StageMetadata,
|
||||
_inject_inferred_kv_tp_topology,
|
||||
acquire_device_locks,
|
||||
build_engine_args_dict,
|
||||
build_engine_args_dict_from_omni_stage_config,
|
||||
build_llm_stage_output_processor,
|
||||
build_vllm_config,
|
||||
compute_replica_layout,
|
||||
device_overlap_group_keys,
|
||||
extract_legacy_stage_metadata,
|
||||
extract_stage_metadata_from_omni_stage_config,
|
||||
get_stage_connector_spec,
|
||||
inject_kv_stage_info,
|
||||
inject_omni_kv_connector_config,
|
||||
@@ -92,6 +96,44 @@ class StageRemoteFactoryContext:
|
||||
executor_class: type | None = None
|
||||
|
||||
|
||||
class OmniClientConfig(TypedDict, total=False):
|
||||
"""Per-frontend transport/configuration passed across process boundaries."""
|
||||
|
||||
client_count: int
|
||||
client_index: int
|
||||
stage_addresses: dict[int | str, dict[int | str, dict[str, Any]]]
|
||||
input_address: str
|
||||
output_address: str
|
||||
stats_update_address: str
|
||||
actual_address_pipe: Any
|
||||
tensor_queue: Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class StageEngineLaunch:
|
||||
"""Engine resources handed to a local client or the serving parent.
|
||||
|
||||
Successful launch transfers resource ownership to the caller. Startup or
|
||||
attachment failures are rolled back by ``launch_stage_engines``.
|
||||
"""
|
||||
|
||||
client_configs: list[OmniClientConfig]
|
||||
resources: list[StageReplicaResources]
|
||||
watched_frontend_processes: list[BaseProcess] = field(default_factory=list)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
seen: set[int] = set()
|
||||
for stage_resources in reversed(self.resources):
|
||||
for resource in (stage_resources.manager, stage_resources.coordinator):
|
||||
if resource is None or id(resource) in seen:
|
||||
continue
|
||||
seen.add(id(resource))
|
||||
try:
|
||||
resource.shutdown()
|
||||
except Exception:
|
||||
logger.warning("[StageEngineLaunch] resource shutdown failed", exc_info=True)
|
||||
|
||||
|
||||
def _build_load_balancer_factory(policy: str) -> Callable[[], LoadBalancer]:
|
||||
try:
|
||||
normalized = LoadBalancingPolicy(policy)
|
||||
@@ -123,13 +165,14 @@ class StageRuntime:
|
||||
self,
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
stage_init_timeout: int,
|
||||
async_chunk: bool,
|
||||
tokenizer: str | None = None,
|
||||
parallel_stage_init: bool = False,
|
||||
log_stats: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> None:
|
||||
self._stage_configs = stage_configs
|
||||
self._model = model
|
||||
@@ -144,6 +187,14 @@ class StageRuntime:
|
||||
self._parallel_stage_init = parallel_stage_init
|
||||
self._log_stats = log_stats
|
||||
self._num_stages = len(stage_configs)
|
||||
self._client_count = int((client_config or {}).get("client_count", 1))
|
||||
self._client_index = int((client_config or {}).get("client_index", 0))
|
||||
if self._client_count < 1:
|
||||
raise ValueError(f"client_count must be >= 1, got {self._client_count}")
|
||||
if self._client_index != -1 and not 0 <= self._client_index < self._client_count:
|
||||
raise ValueError(f"client_index must be in [0, {self._client_count}), got {self._client_index}")
|
||||
self._external_stage_addresses = (client_config or {}).get("stage_addresses")
|
||||
self._api_process_rank = self._client_index
|
||||
|
||||
# Populated by initialize()
|
||||
self.stage_pools: list[StagePool] = []
|
||||
@@ -262,6 +313,205 @@ class StageRuntime:
|
||||
self._cleanup_after_initialize_failure()
|
||||
raise exc
|
||||
|
||||
@contextmanager
|
||||
def launch_stage_engines(
|
||||
self,
|
||||
num_api_servers: int = 1,
|
||||
*,
|
||||
stage_plans: Sequence[LogicalStageInitPlan] | None = None,
|
||||
stage_init_timeout: int | None = None,
|
||||
) -> Iterator[StageEngineLaunch]:
|
||||
"""Launch EngineCore stages for local or subprocess client attachment.
|
||||
|
||||
The regular runtime supplies a replica plan from its device-group
|
||||
scheduler; the serving parent resolves the whole pipeline here. Both
|
||||
use the same device locks, spawn, readiness and rollback machinery.
|
||||
One client completes readiness before attachment, preserving the
|
||||
existing in-process frontend. Multiple clients attach in the caller's
|
||||
``with`` body before readiness completes on context exit.
|
||||
"""
|
||||
if self._external_stage_addresses is not None:
|
||||
raise ValueError("A runtime attached to external stage engines cannot launch engines")
|
||||
if num_api_servers < 1:
|
||||
raise ValueError(f"num_api_servers must be >= 1, got {num_api_servers}")
|
||||
timeout = self._stage_init_timeout if stage_init_timeout is None else stage_init_timeout
|
||||
resolve_plans = stage_plans is None
|
||||
if stage_plans is None:
|
||||
self._client_count = num_api_servers
|
||||
self._api_process_rank = -1 if num_api_servers > 1 else self._client_index
|
||||
self._init_visible_devices_baseline = os.environ.get(current_omni_platform.device_control_env_var)
|
||||
stage_plans = self._prepare_stage_plans()
|
||||
|
||||
unsupported = [
|
||||
plan.stage_id
|
||||
for plan in stage_plans
|
||||
if any(replica.metadata.stage_type == "diffusion" for replica in plan.replicas)
|
||||
]
|
||||
if unsupported:
|
||||
raise ValueError(
|
||||
"--api-server-count currently supports EngineCore stages only; "
|
||||
f"diffusion stage(s) are not supported: {unsupported}"
|
||||
)
|
||||
if any(replica.launch_mode != "local" for plan in stage_plans for replica in plan.replicas):
|
||||
raise ValueError("--api-server-count is not supported with remote or headless stages")
|
||||
|
||||
if num_api_servers > 1:
|
||||
parallel_configs: list[Any] = []
|
||||
for plan in stage_plans:
|
||||
for replica in plan.replicas:
|
||||
if replica.stage_vllm_config is None or replica.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
|
||||
parallel_configs.append(replica.stage_vllm_config.parallel_config)
|
||||
if any(getattr(parallel_config, "enable_fault_tolerance", False) for parallel_config in parallel_configs):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-fault-tolerance")
|
||||
if any(getattr(parallel_config, "enable_elastic_ep", False) for parallel_config in parallel_configs):
|
||||
raise ValueError("--api-server-count > 1 cannot be combined with --enable-elastic-ep")
|
||||
if any(
|
||||
getattr(parallel_config, "data_parallel_size", 1) != 1 or getattr(parallel_config, "use_ray", False)
|
||||
for parallel_config in parallel_configs
|
||||
):
|
||||
raise ValueError(
|
||||
"--api-server-count > 1 currently supports one local process group per replica; "
|
||||
"intra-replica data parallelism and Ray backends are not supported"
|
||||
)
|
||||
|
||||
if resolve_plans and self._parallel_stage_init:
|
||||
self._reject_unguardable_executors(stage_plans)
|
||||
self._run_stage_admission(stage_plans)
|
||||
|
||||
client_configs: list[OmniClientConfig] = [
|
||||
OmniClientConfig(
|
||||
client_count=num_api_servers,
|
||||
client_index=client_index,
|
||||
stage_addresses={},
|
||||
)
|
||||
for client_index in range(num_api_servers)
|
||||
]
|
||||
entered_contexts: list[AbstractContextManager[StageReplicaResources]] = []
|
||||
resources: list[StageReplicaResources] = []
|
||||
watched_frontend_processes: list[BaseProcess] = []
|
||||
# launch_stage_replica performs its readiness handshake in __exit__,
|
||||
# after API workers are started, so initialization locks must remain
|
||||
# held until all launch contexts have exited.
|
||||
lock_fds: list[int] = []
|
||||
locked_devices: set[int] = set()
|
||||
launch: StageEngineLaunch | None = None
|
||||
exited_contexts = 0
|
||||
|
||||
try:
|
||||
for plan in stage_plans:
|
||||
for replica in plan.replicas:
|
||||
if replica.stage_vllm_config is None or replica.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing its engine configuration")
|
||||
if replica.engine_args_dict is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} is missing engine args")
|
||||
|
||||
physical_devices = self._resolve_replica_physical_devices(
|
||||
replica.metadata.stage_id,
|
||||
replica.metadata.runtime_cfg,
|
||||
)
|
||||
if not self._parallel_stage_init:
|
||||
with self._scoped_spawn_device_env(physical_devices):
|
||||
lock_fds.extend(
|
||||
acquire_device_locks(
|
||||
replica.metadata.stage_id,
|
||||
replica.engine_args_dict,
|
||||
timeout,
|
||||
locked_devices,
|
||||
)
|
||||
)
|
||||
|
||||
launch_context = launch_stage_replica(
|
||||
vllm_config=replica.stage_vllm_config,
|
||||
executor_class=replica.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
stage_id=replica.metadata.stage_id,
|
||||
replica_id=replica.replica_id,
|
||||
stage_config=replica.stage_cfg,
|
||||
omni_master_server=self._get_omni_master_server(),
|
||||
omni_coordinator_address=self._get_coordinator_address(),
|
||||
stage_visible_devices=physical_devices,
|
||||
spawn_device_lock=self._spawn_device_lock,
|
||||
omni_parallel_stage_init=self._parallel_stage_init,
|
||||
num_api_servers=num_api_servers,
|
||||
watched_frontend_processes=watched_frontend_processes if num_api_servers > 1 else None,
|
||||
)
|
||||
# Environment overlays are process-global. Serialize spawn;
|
||||
# parallel initialization waits for READY outside this lock.
|
||||
with self._replica_launch_lock:
|
||||
with stage_runtime_env(replica.metadata.stage_id, replica.metadata.runtime_cfg):
|
||||
stage_resources = launch_context.__enter__()
|
||||
entered_contexts.append(launch_context)
|
||||
if stage_resources is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no resources")
|
||||
resources.append(stage_resources)
|
||||
if num_api_servers == 1:
|
||||
exited_contexts += 1
|
||||
launch_context.__exit__(None, None, None)
|
||||
addresses = stage_resources.addresses
|
||||
# The generic resource bundle allows no addresses (e.g.
|
||||
# diffusion), but EngineCore attachment requires them.
|
||||
if addresses is None:
|
||||
raise RuntimeError(f"LLM stage {plan.stage_id} launcher returned no addresses")
|
||||
# Unlike the single-client handshake, only stage 0 is
|
||||
# handed to APIServerProcessManager for address updates.
|
||||
# Other stages must already expose connectable endpoints.
|
||||
if num_api_servers > 1 and any(
|
||||
address.startswith("tcp://") and address.rsplit(":", 1)[-1] == "0"
|
||||
for address in (*addresses.inputs, *addresses.outputs)
|
||||
):
|
||||
raise RuntimeError(
|
||||
f"Stage {plan.stage_id} returned deferred TCP addresses; "
|
||||
"multi-API launch requires fixed ports or IPC addresses"
|
||||
)
|
||||
if len(addresses.inputs) != num_api_servers or len(addresses.outputs) != num_api_servers:
|
||||
raise RuntimeError(
|
||||
f"Stage {plan.stage_id} returned {len(addresses.inputs)} input and "
|
||||
f"{len(addresses.outputs)} output addresses for {num_api_servers} API servers"
|
||||
)
|
||||
|
||||
if num_api_servers == 1 and lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
lock_fds.clear()
|
||||
locked_devices.clear()
|
||||
|
||||
for client_index, client_config in enumerate(client_configs):
|
||||
stage_addresses = client_config["stage_addresses"]
|
||||
replica_addresses = stage_addresses.setdefault(plan.stage_id, {})
|
||||
replica_addresses[replica.replica_id] = {
|
||||
"input_address": addresses.inputs[client_index],
|
||||
"output_address": addresses.outputs[client_index],
|
||||
}
|
||||
if addresses.frontend_stats_publish_address is not None:
|
||||
replica_addresses[replica.replica_id]["stats_update_address"] = (
|
||||
addresses.frontend_stats_publish_address
|
||||
)
|
||||
|
||||
launch = StageEngineLaunch(
|
||||
client_configs=client_configs,
|
||||
resources=resources,
|
||||
watched_frontend_processes=watched_frontend_processes,
|
||||
)
|
||||
yield launch
|
||||
|
||||
while exited_contexts < len(entered_contexts):
|
||||
entered_context = entered_contexts[exited_contexts]
|
||||
exited_contexts += 1
|
||||
entered_context.__exit__(None, None, None)
|
||||
except BaseException as exc:
|
||||
if launch is not None:
|
||||
launch.shutdown()
|
||||
else:
|
||||
StageEngineLaunch(client_configs=client_configs, resources=resources).shutdown()
|
||||
exc_info = (type(exc), exc, exc.__traceback__)
|
||||
for pending_context in reversed(entered_contexts[exited_contexts:]):
|
||||
with contextlib.suppress(BaseException):
|
||||
pending_context.__exit__(*exc_info)
|
||||
raise
|
||||
finally:
|
||||
if lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for pool in self.stage_pools:
|
||||
for client in pool.clients:
|
||||
@@ -288,6 +538,7 @@ class StageRuntime:
|
||||
replicas_per_stage,
|
||||
replica_devices_map,
|
||||
)
|
||||
self._validate_native_kv_topology(stage_plans)
|
||||
return stage_plans
|
||||
|
||||
def _finalize_initialized_stages(
|
||||
@@ -336,6 +587,113 @@ class StageRuntime:
|
||||
|
||||
# ---- Internal methods ----
|
||||
|
||||
def _validate_native_kv_topology(self, plans: list[LogicalStageInitPlan]) -> None:
|
||||
"""Reject unsupported native AR->DiT graphs before launching any Worker."""
|
||||
if not any(plan.replicas[0].metadata.stage_type == "diffusion" for plan in plans):
|
||||
return # Native LLM prefill/decode is outside this path.
|
||||
roles = {}
|
||||
for plan in plans:
|
||||
replica = plan.replicas[0]
|
||||
if replica.stage_vllm_config is not None:
|
||||
config = getattr(replica.stage_vllm_config, "kv_transfer_config", None)
|
||||
elif isinstance(replica.stage_cfg, VllmOmniDiffusionStageConfig):
|
||||
config = (
|
||||
replica.stage_cfg.connector_config.kv_transfer_config
|
||||
or replica.stage_cfg.diffusion_config.kv_transfer_config
|
||||
)
|
||||
else:
|
||||
args = getattr(replica.stage_cfg, "engine_args", {})
|
||||
config = (
|
||||
args.get("kv_transfer_config")
|
||||
if isinstance(args, Mapping)
|
||||
else getattr(args, "kv_transfer_config", None)
|
||||
)
|
||||
if config is not None:
|
||||
roles[plan.stage_id] = config.get("kv_role") if isinstance(config, Mapping) else config.kv_role
|
||||
if not roles:
|
||||
return
|
||||
if (
|
||||
self._async_chunk
|
||||
or len(plans) != 2
|
||||
or roles != {0: "kv_producer", 1: "kv_consumer"}
|
||||
or plans[0].replicas[0].metadata.stage_type != "llm"
|
||||
or plans[1].replicas[0].metadata.stage_type != "diffusion"
|
||||
or list(plans[1].replicas[0].metadata.engine_input_source or []) != [0]
|
||||
):
|
||||
raise ValueError(
|
||||
"Native AR-to-DiT KV transfer currently supports only a two-stage "
|
||||
"0 (kv_producer) -> 1 (diffusion kv_consumer, engine_input_source=[0]) "
|
||||
"pipeline with async_chunk=False"
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _prepare_replica_stage_config(
|
||||
stage_cfg: Any,
|
||||
*,
|
||||
stage_id: int,
|
||||
stage_type: str,
|
||||
replica_id: int,
|
||||
num_replicas: int,
|
||||
) -> tuple[Any, bool]:
|
||||
"""Isolate replica config and assign the native DiT KV identity."""
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig):
|
||||
native_kv = stage_cfg.connector_config.kv_transfer_config
|
||||
if native_kv is None and isinstance(stage_cfg, VllmOmniDiffusionStageConfig):
|
||||
native_kv = stage_cfg.diffusion_config.kv_transfer_config
|
||||
else:
|
||||
native_kv = (
|
||||
stage_cfg.engine_args.get("kv_transfer_config")
|
||||
if isinstance(stage_cfg.engine_args, Mapping)
|
||||
else getattr(stage_cfg.engine_args, "kv_transfer_config", None)
|
||||
)
|
||||
# Keep the logical stage's device pool and native KV identity
|
||||
# intact; each replica owns its config throughout startup.
|
||||
replica_cfg = copy.deepcopy(stage_cfg) if num_replicas > 1 or native_kv else stage_cfg
|
||||
if native_kv and stage_type == "diffusion":
|
||||
if isinstance(replica_cfg, VllmOmniDiffusionStageConfig):
|
||||
kv_config = (
|
||||
replica_cfg.connector_config.kv_transfer_config or replica_cfg.diffusion_config.kv_transfer_config
|
||||
)
|
||||
assert kv_config is not None
|
||||
kv_config.engine_id = f"{kv_config.engine_id}-s{stage_id}-r{replica_id}"
|
||||
else:
|
||||
kv_config = replica_cfg.engine_args["kv_transfer_config"]
|
||||
kv_config["engine_id"] = f"{kv_config['engine_id']}-s{stage_id}-r{replica_id}"
|
||||
return replica_cfg, bool(native_kv)
|
||||
|
||||
@staticmethod
|
||||
def _prepare_replica_vllm_config(
|
||||
stage_vllm_config: Any,
|
||||
replica_cfg: Any,
|
||||
replica_metadata: StageMetadata,
|
||||
*,
|
||||
native_kv: bool,
|
||||
) -> Any:
|
||||
"""Assign native AR KV identity and the producer bootstrap endpoint."""
|
||||
if not native_kv or stage_vllm_config is None:
|
||||
return stage_vllm_config
|
||||
replica_vllm_config = copy.deepcopy(stage_vllm_config)
|
||||
kv_config = replica_vllm_config.kv_transfer_config
|
||||
kv_config.engine_id = f"{kv_config.engine_id}-s{replica_metadata.stage_id}-r{replica_metadata.replica_id}"
|
||||
if kv_config.kv_connector == "MooncakeConnector" and kv_config.kv_role == "kv_producer":
|
||||
extra = kv_config.kv_connector_extra_config
|
||||
port = int(extra.get("bootstrap_port", 8998)) + replica_metadata.replica_id
|
||||
extra["bootstrap_addr"] = f"http://{kv_config.kv_ip}:{port}"
|
||||
if isinstance(replica_cfg, BaseVllmOmniStageConfig):
|
||||
runtime_cfg = replica_cfg.runtime_config
|
||||
runtime_cfg.env = {
|
||||
**(runtime_cfg.env or {}),
|
||||
"VLLM_MOONCAKE_BOOTSTRAP_PORT": str(port),
|
||||
}
|
||||
else:
|
||||
runtime_cfg = copy.deepcopy(replica_metadata.runtime_cfg or {})
|
||||
runtime_cfg["env"] = {
|
||||
**(runtime_cfg.get("env") or {}),
|
||||
"VLLM_MOONCAKE_BOOTSTRAP_PORT": str(port),
|
||||
}
|
||||
replica_metadata.runtime_cfg = runtime_cfg
|
||||
return replica_vllm_config
|
||||
|
||||
def _build_logical_stage_init_plans(
|
||||
self,
|
||||
omni_transfer_config: Any,
|
||||
@@ -345,12 +703,12 @@ class StageRuntime:
|
||||
"""Build startup plans for every logical stage and replica."""
|
||||
stage_plans: list[LogicalStageInitPlan] = []
|
||||
|
||||
# RFC #4021 transition boundary: stage planning still relies on legacy
|
||||
# StageConfig.runtime and StageConfig.engine_args for replica and engine
|
||||
# setup. Keep metadata extraction on the legacy path until the
|
||||
# coordinated stage-init cutover.
|
||||
for stage_idx, stage_cfg in enumerate(self._stage_configs):
|
||||
base_metadata = extract_legacy_stage_metadata(stage_cfg)
|
||||
base_metadata = (
|
||||
extract_stage_metadata_from_omni_stage_config(stage_cfg)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else extract_legacy_stage_metadata(stage_cfg)
|
||||
)
|
||||
stage_id = int(base_metadata.stage_id)
|
||||
if stage_id != stage_idx:
|
||||
raise ValueError(
|
||||
@@ -374,14 +732,20 @@ class StageRuntime:
|
||||
executor_class = None
|
||||
engine_args_dict = None
|
||||
if base_metadata.stage_type != "diffusion":
|
||||
# The stable adapter entry point still receives the same
|
||||
# legacy stage object as replica planning. Its implementation
|
||||
# switches only at the coordinated RFC #4021 cutover.
|
||||
engine_args_dict = build_engine_args_dict(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
engine_args_dict = (
|
||||
build_engine_args_dict_from_omni_stage_config(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
)
|
||||
if isinstance(stage_cfg, BaseVllmOmniStageConfig)
|
||||
else build_engine_args_dict(
|
||||
stage_cfg,
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
cli_tokenizer=self._tokenizer,
|
||||
)
|
||||
)
|
||||
inject_omni_kv_connector_config(
|
||||
engine_args_dict,
|
||||
@@ -398,15 +762,36 @@ class StageRuntime:
|
||||
self._model,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
engine_args_dict=engine_args_dict,
|
||||
api_process_count=self._client_count,
|
||||
api_process_rank=self._api_process_rank,
|
||||
)
|
||||
|
||||
for replica_id in range(num_replicas):
|
||||
replica_cfg = copy.deepcopy(stage_cfg) if replica_id > 0 else stage_cfg
|
||||
replica_cfg, native_kv = self._prepare_replica_stage_config(
|
||||
stage_cfg,
|
||||
stage_id=stage_id,
|
||||
stage_type=base_metadata.stage_type,
|
||||
replica_id=replica_id,
|
||||
num_replicas=num_replicas,
|
||||
)
|
||||
if stage_idx in replica_devices_map:
|
||||
replica_cfg.runtime.devices = replica_devices_map[stage_idx][replica_id]
|
||||
devices = replica_devices_map[stage_idx][replica_id]
|
||||
runtime_cfg = getattr(replica_cfg, "runtime_config", getattr(replica_cfg, "runtime", None))
|
||||
if runtime_cfg is not None:
|
||||
runtime_cfg.devices = devices
|
||||
|
||||
replica_metadata = extract_legacy_stage_metadata(replica_cfg)
|
||||
replica_metadata = (
|
||||
extract_stage_metadata_from_omni_stage_config(replica_cfg)
|
||||
if isinstance(replica_cfg, BaseVllmOmniStageConfig)
|
||||
else extract_legacy_stage_metadata(replica_cfg)
|
||||
)
|
||||
replica_metadata.replica_id = replica_id
|
||||
replica_vllm_config = self._prepare_replica_vllm_config(
|
||||
stage_vllm_config,
|
||||
replica_cfg,
|
||||
replica_metadata,
|
||||
native_kv=native_kv,
|
||||
)
|
||||
if launch_mode == "remote" and replica_metadata.stage_type != "diffusion":
|
||||
replica_metadata.runtime_cfg = None
|
||||
replicas.append(
|
||||
@@ -418,7 +803,7 @@ class StageRuntime:
|
||||
metadata=replica_metadata,
|
||||
stage_connector_spec=stage_connector_spec,
|
||||
omni_kv_connector=omni_kv_connector,
|
||||
stage_vllm_config=stage_vllm_config,
|
||||
stage_vllm_config=replica_vllm_config,
|
||||
executor_class=executor_class,
|
||||
engine_args_dict=copy.deepcopy(engine_args_dict) if engine_args_dict is not None else None,
|
||||
)
|
||||
@@ -720,122 +1105,70 @@ class StageRuntime:
|
||||
stage_init_timeout: int,
|
||||
) -> StagePoolClient:
|
||||
"""Initialize one local LLM replica using vLLM's launch/attach pattern."""
|
||||
resources: StageReplicaResources | None = None
|
||||
stage_client = None
|
||||
lock_fds: list[int] = []
|
||||
try:
|
||||
physical_devices = self._resolve_replica_physical_devices(
|
||||
plan.metadata.stage_id,
|
||||
plan.metadata.runtime_cfg,
|
||||
)
|
||||
if physical_devices:
|
||||
logger.info(
|
||||
"[stage_init] Stage-%s set runtime devices: %s",
|
||||
plan.metadata.stage_id,
|
||||
physical_devices,
|
||||
)
|
||||
vllm_config = plan.stage_vllm_config
|
||||
executor_class = plan.executor_class
|
||||
if vllm_config is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing vllm_config")
|
||||
if executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing executor_class")
|
||||
if plan.engine_args_dict is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing engine args")
|
||||
# G3 device locks: in the default (serial) path the parent holds a
|
||||
# per-device LOCK_EX across the whole child init. When parallel stage
|
||||
# init is enabled the engine-core child takes phased SH/EX locks
|
||||
# itself (see stage_phase_lock), so the parent must NOT also hold the
|
||||
# lock here — it would self-deadlock while waiting for the child's
|
||||
# READY handshake.
|
||||
if not self._parallel_stage_init:
|
||||
g3_start = time.perf_counter()
|
||||
with self._scoped_spawn_device_env(physical_devices):
|
||||
lock_fds = acquire_device_locks(
|
||||
plan.metadata.stage_id,
|
||||
plan.engine_args_dict,
|
||||
stage_init_timeout,
|
||||
)
|
||||
logger.debug(
|
||||
"[stage_init] Stage-%s G3 device-lock acquire took %.3fs",
|
||||
plan.metadata.stage_id,
|
||||
time.perf_counter() - g3_start,
|
||||
)
|
||||
|
||||
launch_cm = launch_stage_replica(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
log_stats=self._log_stats,
|
||||
stage_id=plan.metadata.stage_id,
|
||||
replica_id=plan.replica_id,
|
||||
stage_config=plan.stage_cfg,
|
||||
omni_master_server=self._get_omni_master_server(),
|
||||
omni_coordinator_address=self._get_coordinator_address(),
|
||||
stage_visible_devices=physical_devices,
|
||||
spawn_device_lock=self._spawn_device_lock,
|
||||
omni_parallel_stage_init=self._parallel_stage_init,
|
||||
)
|
||||
# Only process spawning and the runtime.env overlay need the global
|
||||
# launch lock. The launch context's exit waits for READY: holding the
|
||||
# lock there serializes model loading and compilation even across
|
||||
# different GPUs. Default initialization keeps its per-device EX
|
||||
# locks until READY; parallel_stage_init uses child phase locks.
|
||||
g2_start = time.perf_counter()
|
||||
with ExitStack() as launch_stack:
|
||||
with self._replica_launch_lock:
|
||||
g2_locked = time.perf_counter()
|
||||
with stage_runtime_env(plan.metadata.stage_id, plan.metadata.runtime_cfg):
|
||||
resources = launch_stack.enter_context(launch_cm)
|
||||
g2_spawned = time.perf_counter()
|
||||
logger.debug(
|
||||
"[stage_init] Stage-%s G2 launch-lock wait=%.3fs, spawn=%.3fs, READY=%.3fs",
|
||||
plan.metadata.stage_id,
|
||||
g2_locked - g2_start,
|
||||
g2_spawned - g2_locked,
|
||||
time.perf_counter() - g2_spawned,
|
||||
external_addresses = self._get_external_client_addresses(
|
||||
plan.metadata.stage_id,
|
||||
plan.replica_id,
|
||||
)
|
||||
if external_addresses is not None:
|
||||
if plan.stage_vllm_config is None or plan.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
|
||||
return cast(
|
||||
StagePoolClient,
|
||||
StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=plan.stage_vllm_config,
|
||||
executor_class=plan.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=external_addresses,
|
||||
client_count=self._client_count,
|
||||
client_index=self._client_index,
|
||||
),
|
||||
)
|
||||
|
||||
logger.info("[StageRuntime] Stage %s engine startup completed", plan.metadata.stage_id)
|
||||
if resources is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no resources")
|
||||
if resources.addresses is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} launcher returned no addresses")
|
||||
stage_client = StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=self._client_addresses_from_zmq(resources.addresses),
|
||||
engine_manager=resources.manager,
|
||||
coordinator=resources.coordinator,
|
||||
if plan.stage_vllm_config is None or plan.executor_class is None:
|
||||
raise RuntimeError(f"LLM stage {plan.metadata.stage_id} is missing its engine configuration")
|
||||
stage_plan = LogicalStageInitPlan(
|
||||
stage_idx=plan.metadata.stage_id,
|
||||
stage_id=plan.metadata.stage_id,
|
||||
replicas=[plan],
|
||||
)
|
||||
with self.launch_stage_engines(
|
||||
stage_plans=[stage_plan],
|
||||
stage_init_timeout=stage_init_timeout,
|
||||
) as launch:
|
||||
resources = launch.resources[0]
|
||||
return cast(
|
||||
StagePoolClient,
|
||||
StageEngineCoreClientBase.make_async_mp_client(
|
||||
vllm_config=plan.stage_vllm_config,
|
||||
executor_class=plan.executor_class,
|
||||
log_stats=self._log_stats,
|
||||
metadata=plan.metadata,
|
||||
client_addresses=self._client_addresses_from_zmq(resources.addresses),
|
||||
engine_manager=resources.manager,
|
||||
coordinator=resources.coordinator,
|
||||
),
|
||||
)
|
||||
|
||||
logger.info("[StageRuntime] Stage %s initialized", plan.metadata.stage_id)
|
||||
return cast(StagePoolClient, stage_client)
|
||||
except Exception:
|
||||
if stage_client is not None:
|
||||
try:
|
||||
stage_client.shutdown()
|
||||
except Exception as cleanup_error:
|
||||
logger.warning(
|
||||
"[StageRuntime] Failed to cleanup stage %s after init failure: %s",
|
||||
plan.metadata.stage_id,
|
||||
cleanup_error,
|
||||
)
|
||||
else:
|
||||
self._cleanup_launched_resources(
|
||||
stage_id=plan.metadata.stage_id,
|
||||
resources=resources,
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
if lock_fds:
|
||||
release_device_locks(lock_fds)
|
||||
|
||||
def _get_coordinator_address(self) -> str | None:
|
||||
"""Return coordinator router address. Overridden by DistStageRuntime."""
|
||||
return None
|
||||
|
||||
def _get_external_client_addresses(self, stage_id: int, replica_id: int) -> dict[str, Any] | None:
|
||||
if self._external_stage_addresses is None:
|
||||
return None
|
||||
stage_addresses = self._external_stage_addresses.get(stage_id)
|
||||
if stage_addresses is None:
|
||||
stage_addresses = self._external_stage_addresses.get(str(stage_id))
|
||||
if stage_addresses is None:
|
||||
raise ValueError(f"Missing external addresses for stage {stage_id}")
|
||||
replica_addresses = stage_addresses.get(replica_id)
|
||||
if replica_addresses is None:
|
||||
replica_addresses = stage_addresses.get(str(replica_id))
|
||||
if replica_addresses is None:
|
||||
raise ValueError(f"Missing external addresses for stage {stage_id} replica {replica_id}")
|
||||
return dict(replica_addresses)
|
||||
|
||||
def _get_omni_master_server(self) -> OmniMasterServer | None:
|
||||
"""Return the master server for local distributed launches, if any."""
|
||||
return None
|
||||
@@ -859,17 +1192,25 @@ class StageRuntime:
|
||||
raise RuntimeError("Omni KV connector requires source and destination stages")
|
||||
inject_omni_kv_config(plan.stage_cfg, omni_conn_cfg, omni_from, omni_to)
|
||||
inject_kv_stage_info(plan.stage_cfg, plan.metadata.stage_id, self._stage_configs)
|
||||
engine_args = getattr(plan.stage_cfg, "engine_args", {})
|
||||
inline_diffusion = (
|
||||
engine_args.get("inline_diffusion", False)
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "inline_diffusion", False)
|
||||
)
|
||||
custom_pipeline_args = (
|
||||
engine_args.get("custom_pipeline_args")
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "custom_pipeline_args", None)
|
||||
)
|
||||
if isinstance(plan.stage_cfg, BaseVllmOmniStageConfig):
|
||||
inline_diffusion = plan.stage_cfg.stage_pipeline_config.inline_diffusion
|
||||
custom_pipeline_args = getattr(
|
||||
getattr(plan.stage_cfg, "diffusion_config", None),
|
||||
"custom_pipeline_args",
|
||||
None,
|
||||
)
|
||||
else:
|
||||
engine_args = getattr(plan.stage_cfg, "engine_args", {})
|
||||
inline_diffusion = (
|
||||
engine_args.get("inline_diffusion", False)
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "inline_diffusion", False)
|
||||
)
|
||||
custom_pipeline_args = (
|
||||
engine_args.get("custom_pipeline_args")
|
||||
if hasattr(engine_args, "get")
|
||||
else getattr(engine_args, "custom_pipeline_args", None)
|
||||
)
|
||||
client, resources = launch_diffusion_stage_replica(
|
||||
model=self._model,
|
||||
stage_config=plan.stage_cfg,
|
||||
@@ -966,7 +1307,7 @@ class DistStageRuntime(StageRuntime):
|
||||
self,
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
stage_init_timeout: int,
|
||||
async_chunk: bool,
|
||||
@@ -1028,7 +1369,7 @@ class DistStageRuntime(StageRuntime):
|
||||
|
||||
for idx, stage_cfg in enumerate(self._stage_configs):
|
||||
stage_id = int(getattr(stage_cfg, "stage_id", idx))
|
||||
runtime_cfg = getattr(stage_cfg, "runtime", None)
|
||||
runtime_cfg = getattr(stage_cfg, "runtime_config", getattr(stage_cfg, "runtime", None))
|
||||
if runtime_cfg is None:
|
||||
continue
|
||||
if stage_id == target_stage_id:
|
||||
@@ -1100,13 +1441,9 @@ class DistStageRuntime(StageRuntime):
|
||||
if registered_stage_cfg is None:
|
||||
raise ValueError(f"Remote stage {plan.metadata.stage_id} registered without stage config")
|
||||
|
||||
# Remote diffusion registration still transports the legacy mapping
|
||||
# shape. Reconstruct and project that shape until its RFC #4021 cutover.
|
||||
metadata = (
|
||||
extract_legacy_stage_metadata(OmegaConf.create(registered_stage_cfg))
|
||||
if plan.metadata.stage_type == "diffusion"
|
||||
else copy.deepcopy(plan.metadata)
|
||||
)
|
||||
# Registration is transport-only: the head-side typed plan remains
|
||||
# authoritative for metadata and topology.
|
||||
metadata = extract_stage_metadata_from_omni_stage_config(plan.stage_cfg)
|
||||
metadata.replica_id = plan.replica_id
|
||||
ctx = StageRemoteFactoryContext(
|
||||
stage_id=plan.metadata.stage_id,
|
||||
@@ -1303,7 +1640,7 @@ class DistStageRuntime(StageRuntime):
|
||||
def create_stage_runtime(
|
||||
stage_configs: list[Any],
|
||||
model: str,
|
||||
config_path: str,
|
||||
config_path: str | None,
|
||||
*,
|
||||
single_stage_mode: bool,
|
||||
stage_init_timeout: int,
|
||||
@@ -1319,6 +1656,7 @@ def create_stage_runtime(
|
||||
omni_lb_policy: str = "random",
|
||||
request_queue: janus.Queue[EngineQueueMessage] | None = None,
|
||||
log_stats: bool = False,
|
||||
client_config: OmniClientConfig | None = None,
|
||||
) -> StageRuntime:
|
||||
"""Factory: select StageRuntime or DistStageRuntime."""
|
||||
if single_stage_mode:
|
||||
@@ -1350,4 +1688,5 @@ def create_stage_runtime(
|
||||
tokenizer=tokenizer,
|
||||
parallel_stage_init=parallel_stage_init,
|
||||
log_stats=log_stats,
|
||||
client_config=client_config,
|
||||
)
|
||||
Reference in new issue
Block a user