Signed-off-by: chickeyton <ngton2014@gmail.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com>
This commit is contained in:
49 files changed
+3056
-1715
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Shared building blocks for ``DuplexModelPlugin`` implementations.
|
||||
|
||||
Everything here depends on the duplex framework contracts
|
||||
(``vllm_omni.engine.duplex.plugin``), so it is imported only from a model's
|
||||
``duplex`` package, never from the turn-based stack.
|
||||
"""
|
||||
@@ -0,0 +1,135 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Data plane for models whose final stage streams cumulative audio and text.
|
||||
|
||||
The stage runner re-sends the whole waveform (and transcript) it has produced
|
||||
so far for one request; the session needs only what is new. This data plane
|
||||
keeps one cursor per request, slices the delta, encodes it for the wire and
|
||||
reports it as one internal ``response.output_audio.delta``-shaped result.
|
||||
Model-specific constants (stage role, runtime metadata, default rate) are
|
||||
class attributes for a subclass to set.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import duplex_resource_request_belongs_to_session
|
||||
from vllm_omni.engine.duplex.plugin import DuplexDataPlane, DuplexDataPlaneContext
|
||||
from vllm_omni.model_executor.common.request_outputs import (
|
||||
audio_sample_count,
|
||||
audio_value,
|
||||
multimodal_output,
|
||||
sample_rate_hz,
|
||||
slice_audio_delta,
|
||||
text_delta,
|
||||
text_value,
|
||||
unwrap_request_output,
|
||||
)
|
||||
|
||||
EncodeAudio = Callable[[object, int, str, float | None], str | None]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _RequestCursor:
|
||||
audio_samples: int = 0
|
||||
text: str = ""
|
||||
terminal: bool = False
|
||||
|
||||
|
||||
class CumulativeAudioTextDataPlane(DuplexDataPlane):
|
||||
"""Project cumulative staged audio/text output into per-request deltas."""
|
||||
|
||||
stage_role: str = "tts"
|
||||
runtime_impl: str = "scheduler_data_plane"
|
||||
uses_model_runner_scheduler: bool = True
|
||||
runner_kv_backed: bool = True
|
||||
owned_runtime: bool = False
|
||||
default_sample_rate_hz: int = 24000
|
||||
|
||||
def __init__(self, encode_audio: EncodeAudio) -> None:
|
||||
self._encode_audio = encode_audio
|
||||
self._requests: dict[str, _RequestCursor] = {}
|
||||
|
||||
# ---- request / session bookkeeping ----
|
||||
|
||||
def begin_request(self, request_id: str) -> None:
|
||||
self._requests.setdefault(request_id, _RequestCursor()).terminal = False
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
if request_id is None:
|
||||
return False
|
||||
state = self._requests.get(request_id)
|
||||
return state is not None and state.terminal
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
self._requests.setdefault(request_id, _RequestCursor()).terminal = True
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
self._requests.pop(request_id, None)
|
||||
|
||||
def close_session(self, session_id: str, *, active_request_id: str | None = None) -> None:
|
||||
if active_request_id is not None:
|
||||
self._requests.pop(active_request_id, None)
|
||||
for request_id in list(self._requests):
|
||||
if duplex_resource_request_belongs_to_session(request_id, session_id):
|
||||
self._requests.pop(request_id, None)
|
||||
|
||||
# ---- projection ----
|
||||
|
||||
def project(self, result: object, *, context: object | None = None) -> Iterator[dict[str, object]]:
|
||||
if not isinstance(result, dict):
|
||||
return
|
||||
outputs = result.get("data_plane_outputs")
|
||||
if not isinstance(outputs, list):
|
||||
return
|
||||
if not isinstance(context, DuplexDataPlaneContext):
|
||||
context = DuplexDataPlaneContext(response_format="wav", modalities=("audio", "text"))
|
||||
for output in outputs:
|
||||
projected = self._project_output(output, context=context)
|
||||
if projected is not None:
|
||||
yield projected
|
||||
|
||||
def _project_output(self, output: object, *, context: DuplexDataPlaneContext) -> dict[str, object] | None:
|
||||
output, completion = unwrap_request_output(output)
|
||||
request_id = getattr(output, "request_id", None)
|
||||
if not isinstance(request_id, str) or not request_id:
|
||||
request_id = None
|
||||
state = self._requests.setdefault(request_id, _RequestCursor()) if request_id is not None else _RequestCursor()
|
||||
multimodal = multimodal_output(output, completion)
|
||||
audio = audio_value(multimodal)
|
||||
audio_delta = slice_audio_delta(audio, state.audio_samples)
|
||||
total_samples = audio_sample_count(audio)
|
||||
if total_samples is not None:
|
||||
state.audio_samples = total_samples
|
||||
|
||||
text = text_value(multimodal, completion)
|
||||
delta_text = text_delta(text, state.text)
|
||||
if text:
|
||||
state.text = text
|
||||
|
||||
rate = sample_rate_hz(multimodal, default=self.default_sample_rate_hz)
|
||||
encoded = self._encode_audio(audio_delta, rate, context.response_format, context.speed)
|
||||
if not encoded and not delta_text:
|
||||
return None
|
||||
delta_samples = audio_sample_count(audio_delta) or 0
|
||||
return {
|
||||
"supported": True,
|
||||
"stage_role": self.stage_role,
|
||||
"is_listen": False,
|
||||
"data_plane_request_id": request_id,
|
||||
"text": delta_text,
|
||||
"audio_data": encoded or "",
|
||||
"audio_format": context.response_format,
|
||||
"sample_rate_hz": rate,
|
||||
"audio_duration_ms": round(delta_samples * 1000 / max(1, rate)),
|
||||
"end_of_turn": False,
|
||||
"uses_model_runner_scheduler": self.uses_model_runner_scheduler,
|
||||
"runner_kv_backed": self.runner_kv_backed,
|
||||
"runtime_impl": self.runtime_impl,
|
||||
"owned_runtime": self.owned_runtime,
|
||||
}
|
||||
|
||||
|
||||
__all__ = ["CumulativeAudioTextDataPlane"]
|
||||
@@ -0,0 +1,63 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Validation of one duplex audio append payload.
|
||||
|
||||
The runner hands a plugin the append as a mapping ``{format, sample_rate_hz,
|
||||
audio}`` (``audio`` base64 ``pcm_f32le``). Models with a fixed input rate and
|
||||
frame size validate it here; the PCM itself is decoded by
|
||||
``vllm_omni.model_executor.common.audio.pcm``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
|
||||
from vllm_omni.model_executor.common.audio.pcm import (
|
||||
decode_pcm_f32le_base64,
|
||||
pcm_f32le_sample_count,
|
||||
)
|
||||
|
||||
|
||||
def payload_audio(payload: object) -> object | None:
|
||||
"""The encoded audio field of an append payload (``audio``, or the older ``data``)."""
|
||||
if not isinstance(payload, Mapping):
|
||||
return None
|
||||
return payload.get("audio") or payload.get("data")
|
||||
|
||||
|
||||
def decode_pcm_f32le_payload(
|
||||
payload: object,
|
||||
*,
|
||||
sample_rate_hz: int,
|
||||
exact_samples: int | None = None,
|
||||
model: str = "duplex",
|
||||
) -> bytes:
|
||||
"""Raw PCM of one append that must be ``pcm_f32le`` at ``sample_rate_hz``.
|
||||
|
||||
``exact_samples`` pins the unit length (a lockstep model takes exactly one
|
||||
frame per append); ``None`` accepts any whole number of samples.
|
||||
"""
|
||||
if not isinstance(payload, Mapping):
|
||||
raise ValueError(f"{model} duplex append payload must be a mapping")
|
||||
if payload.get("format") != "pcm_f32le":
|
||||
raise ValueError(f"{model} duplex append format must be pcm_f32le")
|
||||
if payload.get("sample_rate_hz") != sample_rate_hz:
|
||||
raise ValueError(f"{model} duplex append sample_rate_hz must be {sample_rate_hz}")
|
||||
raw = decode_pcm_f32le_base64(payload_audio(payload), model=model)
|
||||
if exact_samples is not None and pcm_f32le_sample_count(raw) != exact_samples:
|
||||
raise ValueError(f"{model} duplex append must contain exactly {exact_samples} samples")
|
||||
return raw
|
||||
|
||||
|
||||
def payload_sample_count(payload: object) -> int | None:
|
||||
"""Sample count of a ``pcm_f32le`` append, or ``None`` when it is not one (lenient, for budgeting)."""
|
||||
if not isinstance(payload, Mapping) or payload.get("format") != "pcm_f32le":
|
||||
return None
|
||||
try:
|
||||
raw = decode_pcm_f32le_base64(payload_audio(payload))
|
||||
except ValueError:
|
||||
return None
|
||||
return pcm_f32le_sample_count(raw)
|
||||
|
||||
|
||||
__all__ = ["decode_pcm_f32le_payload", "payload_audio", "payload_sample_count"]
|
||||
@@ -0,0 +1,194 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Transactional framing of client PCM into fixed model units.
|
||||
|
||||
A frame-locked model (PersonaPlex: 1920 samples every 80 ms at 24 kHz) takes
|
||||
exactly one frame per append. Clients send arbitrary chunks, so the session
|
||||
runner buffers them here and takes one whole frame out at a time as a
|
||||
*reservation*: committed once the stage accepted the append, rolled back
|
||||
(the bytes go back to the front of the buffer) when it did not.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.plugin import PcmAppendBuffer, PcmAppendReservation
|
||||
from vllm_omni.model_executor.common.audio.pcm import (
|
||||
PCM_F32LE_BYTES_PER_SAMPLE,
|
||||
decode_pcm_f32le_base64,
|
||||
)
|
||||
|
||||
|
||||
class FixedFramePcmAppendReservation(PcmAppendReservation):
|
||||
__slots__ = ("_active", "_owner", "_raw", "operation_id", "payload")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
owner: FixedFramePcmAppendBuffer,
|
||||
operation_id: str,
|
||||
payload: dict[str, object] | None,
|
||||
raw: bytes,
|
||||
) -> None:
|
||||
self._owner = owner
|
||||
self.operation_id = operation_id
|
||||
self.payload = payload
|
||||
self._raw = raw
|
||||
self._active = True
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self._active
|
||||
|
||||
@property
|
||||
def byte_count(self) -> int:
|
||||
return len(self._raw)
|
||||
|
||||
def commit(self) -> None:
|
||||
self._owner._commit_reservation(self)
|
||||
|
||||
def rollback(self) -> None:
|
||||
self._owner._rollback_reservation(self)
|
||||
|
||||
|
||||
class FixedFramePcmAppendBuffer(PcmAppendBuffer):
|
||||
"""Frame ``pcm_f32le`` at one sample rate into ``frame_samples`` units, transactionally."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
sample_rate_hz: int,
|
||||
frame_samples: int,
|
||||
chunk_period_ms: int,
|
||||
model: str = "duplex",
|
||||
) -> None:
|
||||
if sample_rate_hz <= 0 or frame_samples <= 0 or chunk_period_ms <= 0:
|
||||
raise ValueError("FixedFramePcmAppendBuffer needs positive sample_rate_hz, frame_samples, chunk_period_ms")
|
||||
self.sample_rate_hz = int(sample_rate_hz)
|
||||
self.frame_samples = int(frame_samples)
|
||||
self.chunk_period_ms = int(chunk_period_ms)
|
||||
self.model = model
|
||||
self._buffer = bytearray()
|
||||
self._reservations: list[FixedFramePcmAppendReservation] = []
|
||||
|
||||
@property
|
||||
def frame_bytes(self) -> int:
|
||||
return self.frame_samples * PCM_F32LE_BYTES_PER_SAMPLE
|
||||
|
||||
@property
|
||||
def pending_byte_count(self) -> int:
|
||||
return len(self._buffer)
|
||||
|
||||
def has_pending(self) -> bool:
|
||||
return bool(self._buffer)
|
||||
|
||||
def has_reserved(self) -> bool:
|
||||
return any(reservation.active for reservation in self._reservations)
|
||||
|
||||
def clear_force_listen(self) -> None:
|
||||
return
|
||||
|
||||
def clear(self) -> None:
|
||||
for reservation in self._reservations:
|
||||
reservation._active = False
|
||||
self._reservations.clear()
|
||||
self._buffer.clear()
|
||||
|
||||
def prepare_append(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
allow_emit: bool,
|
||||
) -> FixedFramePcmAppendReservation | None:
|
||||
self._require_chunk_period(chunk_period_ms)
|
||||
if any(reservation.active and reservation.operation_id == operation_id for reservation in self._reservations):
|
||||
raise ValueError(f"{self.model} duplicate active operation_id: {operation_id}")
|
||||
self._buffer.extend(self._decode_payload(payload))
|
||||
if not allow_emit or len(self._buffer) < self.frame_bytes:
|
||||
return None
|
||||
return self._reserve_frame(payload, operation_id=operation_id, flush=False)
|
||||
|
||||
def prepare_commit(self, *, operation_id: str, chunk_period_ms: int) -> FixedFramePcmAppendReservation:
|
||||
self._require_chunk_period(chunk_period_ms)
|
||||
if not self._buffer:
|
||||
reservation = FixedFramePcmAppendReservation(owner=self, operation_id=operation_id, payload=None, raw=b"")
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
payload: dict[str, object] = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": self.sample_rate_hz,
|
||||
"audio": "",
|
||||
"final": True,
|
||||
}
|
||||
return self._reserve_frame(payload, operation_id=operation_id, flush=True)
|
||||
|
||||
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
|
||||
reservation = self.prepare_commit(operation_id=f"{self.model}-flush", chunk_period_ms=chunk_period_ms)
|
||||
payload = reservation.payload
|
||||
reservation.commit()
|
||||
return payload
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Internals #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _require_chunk_period(self, chunk_period_ms: int) -> None:
|
||||
if chunk_period_ms != self.chunk_period_ms:
|
||||
raise ValueError(f"{self.model} chunk_period_ms must be {self.chunk_period_ms}")
|
||||
|
||||
def _decode_payload(self, payload: dict[str, object]) -> bytes:
|
||||
if payload.get("format") != "pcm_f32le":
|
||||
raise ValueError(f"{self.model} input format must be pcm_f32le")
|
||||
if payload.get("sample_rate_hz") != self.sample_rate_hz:
|
||||
raise ValueError(f"{self.model} sample_rate_hz must be {self.sample_rate_hz}")
|
||||
return decode_pcm_f32le_base64(payload.get("audio"), model=self.model)
|
||||
|
||||
def _reserve_frame(
|
||||
self,
|
||||
source_payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
flush: bool,
|
||||
) -> FixedFramePcmAppendReservation:
|
||||
frame_bytes = self.frame_bytes
|
||||
consumed_bytes = min(len(self._buffer), frame_bytes) if flush else frame_bytes
|
||||
raw = bytes(self._buffer[:consumed_bytes])
|
||||
del self._buffer[:consumed_bytes]
|
||||
encoded_raw = raw + b"\x00" * (frame_bytes - consumed_bytes)
|
||||
payload = dict(source_payload)
|
||||
payload["type"] = "audio"
|
||||
payload["format"] = "pcm_f32le"
|
||||
payload["sample_rate_hz"] = self.sample_rate_hz
|
||||
payload["audio"] = base64.b64encode(encoded_raw).decode("ascii")
|
||||
reservation = FixedFramePcmAppendReservation(owner=self, operation_id=operation_id, payload=payload, raw=raw)
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
|
||||
def _commit_reservation(self, reservation: FixedFramePcmAppendReservation) -> None:
|
||||
if not reservation.active:
|
||||
return
|
||||
reservation._active = False
|
||||
self._reservations.remove(reservation)
|
||||
|
||||
def _rollback_reservation(self, reservation: FixedFramePcmAppendReservation) -> None:
|
||||
if not reservation.active:
|
||||
return
|
||||
try:
|
||||
index = self._reservations.index(reservation)
|
||||
except ValueError:
|
||||
reservation._active = False
|
||||
return
|
||||
# Later reservations were taken after this one: they go back too, in order.
|
||||
rolled_back = self._reservations[index:]
|
||||
restored = b"".join(item._raw for item in rolled_back if item.active)
|
||||
self._buffer[:0] = restored
|
||||
for item in rolled_back:
|
||||
item._active = False
|
||||
del self._reservations[index:]
|
||||
|
||||
|
||||
__all__ = ["FixedFramePcmAppendBuffer", "FixedFramePcmAppendReservation"]
|
||||
Reference in new issue
Block a user