[Model] Integrate AURA into Full-Duplex Runtime (#7633)
This commit is contained in:
1 parent
d397a2f547
commit
62b15142bd
77 files changed
+7695
-457
No files matched your search
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""AURA-only benchmark helpers. Not imported by the shared OmniInteract path."""
|
||||
@@ -0,0 +1,287 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""OmniInteract sender for video-required, turn-commit duplex sessions.
|
||||
|
||||
The shared harness still streams a 1 FPS soundtrack. This clock is the previous
|
||||
AURA bench: frames are the clock, each append carries a frame, and each
|
||||
annotation WAV is one append at ``question_time`` followed by ``commit``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ANNOTATION_VIDEO_FPS = 2.0
|
||||
_PCM16_SAMPLE_RATE = 16_000
|
||||
_PCM16_BYTES_PER_SAMPLE = 2
|
||||
|
||||
|
||||
def wants_annotation_video_clock(capabilities: object) -> bool:
|
||||
"""True when every append must carry video and a commit is one turn.
|
||||
|
||||
MiniCPM requires audio and is not turn-commit-only, so it stays on the
|
||||
shared soundtrack clock. The check is the session capability set, not the
|
||||
model name.
|
||||
"""
|
||||
if not isinstance(capabilities, dict):
|
||||
return False
|
||||
required = capabilities.get("required_input_modalities") or ()
|
||||
if isinstance(required, str):
|
||||
required = (required,)
|
||||
try:
|
||||
required_set = {str(item) for item in required}
|
||||
except TypeError:
|
||||
return False
|
||||
return "video" in required_set and bool(capabilities.get("supports_turn_commit_only"))
|
||||
|
||||
|
||||
def _parse_clock(value: object) -> float | None:
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return float(value)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return None
|
||||
parts = value.strip().split(":")
|
||||
try:
|
||||
nums = [float(part) for part in parts]
|
||||
except ValueError:
|
||||
return None
|
||||
if len(nums) == 1:
|
||||
return nums[0]
|
||||
if len(nums) == 2:
|
||||
minutes, seconds = nums
|
||||
return minutes * 60.0 + seconds
|
||||
if len(nums) == 3:
|
||||
hours, minutes, seconds = nums
|
||||
return hours * 3600.0 + minutes * 60.0 + seconds
|
||||
return None
|
||||
|
||||
|
||||
def _load_annotation_pcm(path: Path) -> bytes:
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-i",
|
||||
str(path),
|
||||
"-f",
|
||||
"s16le",
|
||||
"-ac",
|
||||
"1",
|
||||
"-ar",
|
||||
str(_PCM16_SAMPLE_RATE),
|
||||
"pipe:1",
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(command, capture_output=True, timeout=60, check=False)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise TimeoutError(f"ffmpeg timed out reading {path}") from exc
|
||||
except FileNotFoundError as exc:
|
||||
raise RuntimeError("ffmpeg is required to read OmniInteract annotation WAV") from exc
|
||||
if result.returncode:
|
||||
error = result.stderr.decode("utf-8", "ignore").strip()
|
||||
raise RuntimeError(f"ffmpeg failed for {path}: {error}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def load_annotation_utterances(video_path: Path) -> list[dict[str, Any]]:
|
||||
"""Annotation WAV files injected at ``question_time``.
|
||||
|
||||
Layout is ``{subset}/annotations/{stem}.json`` and
|
||||
``{subset}/audios/{stem}_{qa}.wav``. The video soundtrack is not used.
|
||||
"""
|
||||
subset_root = video_path.parent.parent
|
||||
annotation_path = subset_root / "annotations" / f"{video_path.stem}.json"
|
||||
if not annotation_path.is_file():
|
||||
raise ValueError(f"Missing OmniInteract annotation for {video_path}: {annotation_path}")
|
||||
annotation = json.loads(annotation_path.read_text(encoding="utf-8"))
|
||||
if not isinstance(annotation, list):
|
||||
raise ValueError(f"OmniInteract annotation is not a list: {annotation_path}")
|
||||
items: list[dict[str, Any]] = []
|
||||
for index, row in enumerate(annotation):
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
at_sec = _parse_clock(row.get("question_time"))
|
||||
audio_path = subset_root / "audios" / f"{video_path.stem}_{index}.wav"
|
||||
if at_sec is None or not audio_path.is_file():
|
||||
continue
|
||||
pcm = _load_annotation_pcm(audio_path)
|
||||
if not pcm:
|
||||
continue
|
||||
items.append({"at_sec": at_sec, "pcm": pcm, "sent": False, "qa_index": index})
|
||||
if not items:
|
||||
raise ValueError(
|
||||
f"No annotation WAV at question_time for {video_path.name}; "
|
||||
f"expected {subset_root / 'audios' / (video_path.stem + '_*.wav')}"
|
||||
)
|
||||
items.sort(key=lambda item: float(item["at_sec"]))
|
||||
return items
|
||||
|
||||
|
||||
def _collector_events(client: Any) -> list[object] | None:
|
||||
events = getattr(getattr(client, "events", None), "events", None)
|
||||
return events if isinstance(events, list) else None
|
||||
|
||||
|
||||
def _response_id(event: dict[str, object]) -> str | None:
|
||||
raw = event.get("response_id")
|
||||
if isinstance(raw, str) and raw:
|
||||
return raw
|
||||
response = event.get("response")
|
||||
if isinstance(response, dict):
|
||||
nested = response.get("id")
|
||||
if isinstance(nested, str) and nested:
|
||||
return nested
|
||||
return None
|
||||
|
||||
|
||||
def _open_response_count(client: Any) -> int | None:
|
||||
"""Responses still occupying the input gate, or None when the client has no event log."""
|
||||
events = _collector_events(client)
|
||||
if events is None:
|
||||
return None
|
||||
open_ids: set[str] = set()
|
||||
anon = 0
|
||||
for event in events:
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
kind = event.get("type")
|
||||
response_id = _response_id(event)
|
||||
if kind == "response.created":
|
||||
if response_id:
|
||||
open_ids.add(response_id)
|
||||
else:
|
||||
anon += 1
|
||||
elif kind in {"response.done", "response.listen"}:
|
||||
if response_id:
|
||||
open_ids.discard(response_id)
|
||||
elif anon:
|
||||
anon -= 1
|
||||
elif open_ids:
|
||||
open_ids.pop()
|
||||
return len(open_ids) + anon
|
||||
|
||||
|
||||
def _terminal_count(client: Any) -> int:
|
||||
events = _collector_events(client) or []
|
||||
return sum(
|
||||
1 for event in events if isinstance(event, dict) and event.get("type") in {"response.done", "response.listen"}
|
||||
)
|
||||
|
||||
|
||||
_VISION_COMMIT_FRAMES = 2
|
||||
|
||||
|
||||
async def stream_annotation_clock(
|
||||
client: Any,
|
||||
frames: Sequence[str | None],
|
||||
playback: Any,
|
||||
*,
|
||||
video_path: Path,
|
||||
fps: float = ANNOTATION_VIDEO_FPS,
|
||||
) -> tuple[int, int, float, float]:
|
||||
"""Send one frame per tick. Speech commits at question_time; vision every two frames.
|
||||
|
||||
Vision-only appends are not sent until they can be committed. The server
|
||||
buffer keeps only the latest frames and will not infer until ``commit``.
|
||||
A commit waits while a response is still open so it does not abort Stage0/1.
|
||||
Clients without an event log (unit stubs) are not gated.
|
||||
"""
|
||||
utterances = await asyncio.to_thread(load_annotation_utterances, video_path)
|
||||
frame_interval_s = 1.0 / fps
|
||||
started_at = time.monotonic()
|
||||
sent_frames = chunks = 0
|
||||
lags: list[float] = []
|
||||
held_frame: str | None = None
|
||||
vision_pending: list[str] = []
|
||||
local_commits = 0
|
||||
terminals_at_start = 0
|
||||
if _collector_events(client) is not None:
|
||||
terminals_at_start = _terminal_count(client)
|
||||
|
||||
def _gate_blocked() -> bool:
|
||||
if _collector_events(client) is None:
|
||||
return False
|
||||
open_responses = _open_response_count(client)
|
||||
if open_responses:
|
||||
return True
|
||||
return local_commits > _terminal_count(client) - terminals_at_start
|
||||
|
||||
async def _commit_vision(frames_to_send: list[str]) -> None:
|
||||
nonlocal chunks, sent_frames, local_commits
|
||||
if not frames_to_send or _gate_blocked():
|
||||
return
|
||||
await client.send(
|
||||
{
|
||||
"type": "input_audio_buffer.append",
|
||||
"is_speech": False,
|
||||
"sample_rate_hz": _PCM16_SAMPLE_RATE,
|
||||
"video_frames": list(frames_to_send),
|
||||
}
|
||||
)
|
||||
chunks += 1
|
||||
sent_frames += len(frames_to_send)
|
||||
await playback.acknowledge(client)
|
||||
await client.commit()
|
||||
local_commits += 1
|
||||
frames_to_send.clear()
|
||||
|
||||
for index, frame in enumerate(frames):
|
||||
if frame:
|
||||
held_frame = frame
|
||||
if not held_frame:
|
||||
continue
|
||||
source_time = index / fps
|
||||
due = [item for item in utterances if not item["sent"] and float(item["at_sec"]) <= source_time]
|
||||
due_at = time.monotonic()
|
||||
if due:
|
||||
vision_pending.clear()
|
||||
for item in due:
|
||||
audio = item["pcm"]
|
||||
assert isinstance(audio, bytes)
|
||||
await client.send(
|
||||
{
|
||||
"type": "input_audio_buffer.append",
|
||||
"audio": base64.b64encode(audio).decode("ascii"),
|
||||
"input_audio_format": "pcm16",
|
||||
"sample_rate_hz": _PCM16_SAMPLE_RATE,
|
||||
"duration_ms": len(audio) * 1000 // (_PCM16_SAMPLE_RATE * _PCM16_BYTES_PER_SAMPLE),
|
||||
"is_speech": True,
|
||||
"video_frames": [held_frame],
|
||||
}
|
||||
)
|
||||
chunks += 1
|
||||
sent_frames += 1
|
||||
await playback.acknowledge(client)
|
||||
item["sent"] = True
|
||||
await client.commit()
|
||||
local_commits += 1
|
||||
else:
|
||||
vision_pending.append(held_frame)
|
||||
if len(vision_pending) > _VISION_COMMIT_FRAMES:
|
||||
vision_pending = vision_pending[-_VISION_COMMIT_FRAMES:]
|
||||
if len(vision_pending) >= _VISION_COMMIT_FRAMES:
|
||||
await _commit_vision(vision_pending)
|
||||
lags.append(max(0.0, time.monotonic() - due_at))
|
||||
await asyncio.sleep(max(0.0, started_at + (index + 1) * frame_interval_s - time.monotonic()))
|
||||
if vision_pending:
|
||||
await _commit_vision(vision_pending)
|
||||
unsent = [item for item in utterances if not item["sent"]]
|
||||
if unsent:
|
||||
logger.warning(
|
||||
"Annotation WAV past the last frame was not injected: video=%s qa=%s",
|
||||
video_path,
|
||||
[item["qa_index"] for item in unsent],
|
||||
)
|
||||
return chunks, sent_frames, sum(lags) / len(lags) if lags else 0.0, max(lags, default=0.0)
|
||||
@@ -0,0 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
__all__ = ["AuraDuplexPlugin"]
|
||||
@@ -0,0 +1,48 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities
|
||||
|
||||
|
||||
def aura_duplex_capabilities(*, max_sessions: int = 1) -> DuplexCapabilities:
|
||||
"""AURA turn-commit duplex capabilities (not MiniCPM resident append)."""
|
||||
supports_multi_session = max_sessions > 1
|
||||
return DuplexCapabilities(
|
||||
supports_model_native_turn_policy=False,
|
||||
supports_barge_in=True,
|
||||
supports_input_append=True,
|
||||
supports_replace_latest_chunk=False,
|
||||
supports_reencode_context=False,
|
||||
supports_turn_commit_only=True,
|
||||
supports_kv_lease=False,
|
||||
supports_core_kv_lease=False,
|
||||
supports_model_internal_state=True,
|
||||
supports_stage_resumption=False,
|
||||
supports_scheduler_native_append=False,
|
||||
supports_core_resumable_request=False,
|
||||
supports_concurrent_turn_requests=True,
|
||||
# Video required, audio optional (vision-only / silent+frames legal).
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
supports_stage_connector_handoff=False,
|
||||
supports_independent_io_streams=True,
|
||||
supports_realtime_endpoint=True,
|
||||
supports_multi_session=supports_multi_session,
|
||||
supports_multi_session_same_replica=supports_multi_session,
|
||||
supports_session_lease=True,
|
||||
supports_session_resume=True,
|
||||
session_admission_mode="engine_managed",
|
||||
supports_audio_truncate=False,
|
||||
requires_model_runner_kv=False,
|
||||
requires_native_stage_role=False,
|
||||
adapter_patterns=["turn_commit"],
|
||||
signal_sources=["client_event", "server_policy"],
|
||||
stage_handoff_transport="stage_connector",
|
||||
chunk_period_ms=1000,
|
||||
target_barge_in_latency_ms=None,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["aura_duplex_capabilities"]
|
||||
@@ -0,0 +1,381 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Project AURA stage outputs into duplex internal events."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
duplex_resource_request_belongs_to_session,
|
||||
duplex_turn_id_from_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexDataPlane, EncodeAudio
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
SILENT_TEXT,
|
||||
is_effectively_silent,
|
||||
is_silent_text_prefix,
|
||||
)
|
||||
from vllm_omni.outputs.duplex import get_duplex_output_decision
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class AuraDataPlaneContext:
|
||||
epoch: int = 0
|
||||
turn_id: int = 0
|
||||
auto_responds: bool = True
|
||||
response_format: str = "wav"
|
||||
speed: float | None = None
|
||||
modalities: tuple[str, ...] = ("text", "audio")
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _RequestState:
|
||||
text_sent: str = ""
|
||||
text_emitted: str = ""
|
||||
audio_offset: int = 0
|
||||
silent: bool = False
|
||||
terminal: bool = False
|
||||
context_committed: bool = False
|
||||
stage_seen: set[int] = field(default_factory=set)
|
||||
|
||||
|
||||
def _unwrap(output: object) -> tuple[object, object | None, int | None]:
|
||||
stage_id = getattr(output, "stage_id", None)
|
||||
inner = getattr(output, "request_output", None)
|
||||
if inner is not None and inner is not output:
|
||||
output = inner
|
||||
outputs = getattr(output, "outputs", None)
|
||||
completion = outputs[0] if isinstance(outputs, list) and outputs else None
|
||||
if stage_id is None:
|
||||
stage_id = getattr(output, "stage_id", None)
|
||||
return output, completion, int(stage_id) if isinstance(stage_id, int) else None
|
||||
|
||||
|
||||
def _strip_think(text: str) -> str:
|
||||
"""Drop Qwen3-VL ``<think>...</think>`` wrappers from assistant text."""
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import _strip_assistant_text
|
||||
|
||||
return _strip_assistant_text(text)
|
||||
|
||||
|
||||
def _text_from(output: object, completion: object | None) -> str:
|
||||
for candidate in (completion, output):
|
||||
if candidate is None:
|
||||
continue
|
||||
for attr in ("cumulative_text", "text"):
|
||||
value = getattr(candidate, attr, None)
|
||||
if isinstance(value, str) and value:
|
||||
return _strip_think(value)
|
||||
return ""
|
||||
|
||||
|
||||
def _multimodal(output: object, completion: object | None) -> dict[str, object]:
|
||||
"""Prefer decision metadata, then completion multimodal payload.
|
||||
|
||||
Empty mappings must not short-circuit: OmniRequestOutput.multimodal_output
|
||||
returns ``{}`` when completion payloads are falsy, which would otherwise
|
||||
hide a real MultimodalPayload on the completion (MiniCPM data-plane does
|
||||
the same ``if not mm`` fallthrough).
|
||||
"""
|
||||
decision = get_duplex_output_decision(output)
|
||||
metadata = getattr(decision, "metadata", None)
|
||||
if isinstance(metadata, Mapping) and metadata:
|
||||
return dict(metadata)
|
||||
for candidate in (
|
||||
getattr(output, "multimodal_output", None),
|
||||
getattr(completion, "multimodal_output", None) if completion is not None else None,
|
||||
):
|
||||
if isinstance(candidate, Mapping) and candidate:
|
||||
return dict(candidate)
|
||||
return {}
|
||||
|
||||
|
||||
def _audio_value(metadata: Mapping[str, object]) -> object | None:
|
||||
"""Extract PCM/latent audio from a multimodal mapping.
|
||||
|
||||
Code2Wav wire payloads use producer key ``model_outputs``; after
|
||||
``MultimodalPayload.from_raw(..., modality_key)`` that becomes ``audio``
|
||||
when modality is audio, or another modality key (e.g. ``text``/``hidden``)
|
||||
when the stage output_modality was wrongly tagged. Accept common aliases and
|
||||
finally the first non-sr tensor so duplex still surfaces Stage3 PCM.
|
||||
"""
|
||||
value = next(
|
||||
(metadata[key] for key in ("audio", "model_outputs", "latent", "hidden", "text") if key in metadata),
|
||||
None,
|
||||
)
|
||||
if value is None:
|
||||
primary = getattr(metadata, "primary_tensor", None)
|
||||
if primary is not None:
|
||||
value = primary
|
||||
if value is None:
|
||||
for key, candidate in metadata.items():
|
||||
if key in {"sr", "sample_rate", "sample_rate_hz", "audio_sample_rate"}:
|
||||
continue
|
||||
if isinstance(candidate, torch.Tensor) or (
|
||||
isinstance(candidate, list) and candidate and isinstance(candidate[0], torch.Tensor)
|
||||
):
|
||||
value = candidate
|
||||
break
|
||||
if isinstance(value, list) and len(value) == 1:
|
||||
return value[0]
|
||||
return value
|
||||
|
||||
|
||||
def _sample_rate(metadata: Mapping[str, object]) -> int:
|
||||
value = metadata.get("sr", metadata.get("sample_rate_hz", 24000))
|
||||
if isinstance(value, list) and value:
|
||||
value = value[0]
|
||||
if hasattr(value, "item"):
|
||||
value = value.item()
|
||||
return int(value) if isinstance(value, int | float) else 24000
|
||||
|
||||
|
||||
def _pcm_sample_count(audio: object) -> int:
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return int(audio.detach().reshape(-1).numel())
|
||||
try:
|
||||
return int(np.asarray(audio, dtype=np.float32).reshape(-1).size)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _flat_audio(audio: object) -> torch.Tensor | np.ndarray | None:
|
||||
if isinstance(audio, torch.Tensor):
|
||||
return audio.detach().reshape(-1)
|
||||
try:
|
||||
return np.asarray(audio, dtype=np.float32).reshape(-1)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _new_audio_samples(audio: object, already_sent: int) -> tuple[torch.Tensor | np.ndarray, int] | None:
|
||||
"""Return only samples not yet sent.
|
||||
|
||||
Code2Wav hands back a growing waveform. A longer buffer is a cumulative
|
||||
snapshot: send the tail. An equal buffer is a duplicate. A shorter buffer
|
||||
is a real delta (or a restart) and is sent whole.
|
||||
"""
|
||||
flat = _flat_audio(audio)
|
||||
if flat is None:
|
||||
return None
|
||||
count = int(flat.numel()) if isinstance(flat, torch.Tensor) else int(flat.size)
|
||||
if count > already_sent:
|
||||
return flat[already_sent:], count
|
||||
if count == already_sent:
|
||||
return None
|
||||
return flat, already_sent + count
|
||||
|
||||
|
||||
def _requested_audio_format(context: object | None) -> tuple[str, float | None]:
|
||||
"""Honor the session response format. Missing context stays PCM16 (Realtime default)."""
|
||||
fmt = getattr(context, "response_format", None)
|
||||
speed = getattr(context, "speed", None)
|
||||
if not isinstance(fmt, str) or not fmt:
|
||||
fmt = "pcm16"
|
||||
if not isinstance(speed, int | float):
|
||||
speed = None
|
||||
return fmt, float(speed) if speed is not None else None
|
||||
|
||||
|
||||
class AuraDataPlaneSession(DuplexDataPlane):
|
||||
"""Map Stage1 text + Stage3 audio (or silent) onto duplex events."""
|
||||
|
||||
def __init__(self, encode_audio: EncodeAudio) -> None:
|
||||
self._encode_audio = encode_audio
|
||||
self._requests: dict[str, _RequestState] = {}
|
||||
self._closed: set[str] = set()
|
||||
|
||||
def begin_request(self, request_id: str) -> None:
|
||||
self._closed.discard(request_id)
|
||||
state = self._requests.setdefault(request_id, _RequestState())
|
||||
state.terminal = False
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
if request_id is None:
|
||||
return False
|
||||
if request_id in self._closed:
|
||||
return True
|
||||
state = self._requests.get(request_id)
|
||||
return state is not None and state.terminal
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
# The shared session already calls this when a turn finishes. Drop the
|
||||
# projector row here so completed turns do not accumulate; the id stays
|
||||
# closed so a late chunk cannot open a second turn.
|
||||
self._requests.pop(request_id, None)
|
||||
self._closed.add(request_id)
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
state = self._requests.get(request_id)
|
||||
if state is not None:
|
||||
state.audio_offset = 0
|
||||
|
||||
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)
|
||||
self._closed = {
|
||||
request_id
|
||||
for request_id in self._closed
|
||||
if not duplex_resource_request_belongs_to_session(request_id, session_id)
|
||||
}
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import drop_session_history
|
||||
|
||||
drop_session_history(session_id)
|
||||
|
||||
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
|
||||
for output in outputs:
|
||||
yield from self.project_output(output, context=context)
|
||||
|
||||
def project_output(self, result: object, *, context: object | None = None) -> Iterator[dict[str, object]]:
|
||||
response_format, speed = _requested_audio_format(context)
|
||||
request_id = getattr(result, "request_id", None)
|
||||
if not isinstance(request_id, str) or not request_id:
|
||||
return
|
||||
if request_id in self._closed:
|
||||
return
|
||||
model_turn_id = duplex_turn_id_from_request_id(request_id)
|
||||
outer_finished = bool(getattr(result, "finished", False))
|
||||
output, completion, stage_id = _unwrap(result)
|
||||
state = self._requests.setdefault(request_id, _RequestState())
|
||||
if stage_id is not None:
|
||||
state.stage_seen.add(stage_id)
|
||||
|
||||
def _event(**fields: object) -> dict[str, object]:
|
||||
payload = dict(fields)
|
||||
if model_turn_id is not None:
|
||||
payload["model_turn_id"] = model_turn_id
|
||||
return payload
|
||||
|
||||
decision = get_duplex_output_decision(result)
|
||||
metadata = dict(getattr(decision, "metadata", {}) or {})
|
||||
if metadata.get("model_listen") or metadata.get("duplex_native_decision") == "listen":
|
||||
state.silent = True
|
||||
# DIRECT_RESPONSE skips aura2tts. The session runner commits
|
||||
# model context from model_context_text; this projector does not.
|
||||
yield _event(
|
||||
stage_role="thinker",
|
||||
is_listen=True,
|
||||
data_plane_request_id=request_id,
|
||||
text="",
|
||||
end_of_turn=True,
|
||||
silent=True,
|
||||
model_context_text=SILENT_TEXT,
|
||||
# Prewarm already reserved Stage2/3 on Stage0 submit. Silent
|
||||
# short-circuit never feeds codec chunks; abort frees those seats.
|
||||
abort_data_plane_request=True,
|
||||
)
|
||||
state.terminal = True
|
||||
return
|
||||
|
||||
text = _text_from(output, completion)
|
||||
if text and text != state.text_sent:
|
||||
state.text_sent = text
|
||||
if is_effectively_silent(text):
|
||||
state.silent = True
|
||||
# Hold deltas that are still a <|silent|> prefix until short-circuit.
|
||||
if not state.silent and not is_silent_text_prefix(text):
|
||||
emit = (
|
||||
text
|
||||
if not state.text_emitted
|
||||
else (text[len(state.text_emitted) :] if text.startswith(state.text_emitted) else text)
|
||||
)
|
||||
if emit:
|
||||
state.text_emitted = text
|
||||
yield _event(
|
||||
stage_role="thinker",
|
||||
is_listen=False,
|
||||
data_plane_request_id=request_id,
|
||||
text=emit,
|
||||
end_of_turn=False,
|
||||
)
|
||||
|
||||
# RequestOutput.finished / envelope finished is the stream EOS.
|
||||
# CompletionOutput.finished is true on every Code2Wav chunk and must
|
||||
# not close the duplex turn (runner would then drop via is_terminal).
|
||||
finished = bool(outer_finished or getattr(output, "finished", False))
|
||||
if (
|
||||
finished
|
||||
and stage_id == 1
|
||||
and not state.silent
|
||||
and not state.context_committed
|
||||
and state.text_sent
|
||||
and not is_effectively_silent(state.text_sent)
|
||||
):
|
||||
state.context_committed = True
|
||||
yield _event(
|
||||
stage_role="thinker",
|
||||
is_listen=False,
|
||||
data_plane_request_id=request_id,
|
||||
text="",
|
||||
end_of_turn=False,
|
||||
model_context_text=state.text_sent,
|
||||
)
|
||||
is_final_audio_stage = stage_id is None or stage_id >= 3
|
||||
mm = _multimodal(output, completion)
|
||||
audio = _audio_value(mm)
|
||||
if audio is not None and not state.silent:
|
||||
sample_rate = _sample_rate(mm)
|
||||
delta = _new_audio_samples(audio, state.audio_offset)
|
||||
encoded = None
|
||||
n = 0
|
||||
if delta is not None:
|
||||
samples, new_offset = delta
|
||||
encoded = self._encode_audio(samples, sample_rate, response_format, speed)
|
||||
if encoded:
|
||||
n = _pcm_sample_count(samples)
|
||||
state.audio_offset = new_offset
|
||||
if encoded:
|
||||
duration_ms = round(n * 1000 / max(1, sample_rate))
|
||||
end_of_turn = bool(finished and is_final_audio_stage)
|
||||
yield _event(
|
||||
stage_role="tts",
|
||||
is_listen=False,
|
||||
data_plane_request_id=request_id,
|
||||
audio=encoded,
|
||||
audio_format=response_format,
|
||||
sample_rate_hz=sample_rate,
|
||||
audio_duration_ms=duration_ms,
|
||||
end_of_turn=end_of_turn,
|
||||
)
|
||||
if end_of_turn:
|
||||
state.terminal = True
|
||||
return
|
||||
|
||||
if finished and is_final_audio_stage and not state.terminal:
|
||||
yield _event(
|
||||
stage_role="tts",
|
||||
is_listen=False,
|
||||
data_plane_request_id=request_id,
|
||||
text="",
|
||||
end_of_turn=True,
|
||||
)
|
||||
state.terminal = True
|
||||
elif finished and state.silent and not state.terminal:
|
||||
yield _event(
|
||||
stage_role="thinker",
|
||||
is_listen=True,
|
||||
data_plane_request_id=request_id,
|
||||
text="",
|
||||
end_of_turn=True,
|
||||
silent=True,
|
||||
model_context_text=SILENT_TEXT,
|
||||
abort_data_plane_request=True,
|
||||
)
|
||||
state.terminal = True
|
||||
|
||||
|
||||
__all__ = ["AuraDataPlaneContext", "AuraDataPlaneSession"]
|
||||
@@ -0,0 +1,128 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Stage1-local SessionHistory for duplex AURA (import from asr2aura / aura2tts)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from threading import Lock
|
||||
|
||||
# Native gateway (AURA_demo-main/gateway/actor.py): keep up to 45 video
|
||||
# rounds, then strip the video payload from the oldest 30. Text stays.
|
||||
# Empty user + <|silent|> after the strip is dropped as a pair.
|
||||
# Total conversation rounds are effectively unbounded (Native default 999).
|
||||
_MAX_VIDEO_ROUNDS = 45
|
||||
_VIDEO_ROUNDS_TO_REMOVE = 30
|
||||
_MAX_CONVERSATION_ROUNDS = 999
|
||||
_SILENT = "<|silent|>"
|
||||
_STORE: dict[str, SessionHistory] = {}
|
||||
_LOCK = Lock()
|
||||
|
||||
|
||||
@dataclass
|
||||
class SessionHistory:
|
||||
"""Per-session chat turns held in the Stage1 process."""
|
||||
|
||||
session_id: str
|
||||
max_video_rounds: int = _MAX_VIDEO_ROUNDS
|
||||
video_rounds_to_remove: int = _VIDEO_ROUNDS_TO_REMOVE
|
||||
max_conversation_rounds: int = _MAX_CONVERSATION_ROUNDS
|
||||
messages: list[dict[str, object]] = field(default_factory=list)
|
||||
pending_user: str | None = None
|
||||
pending_video: object | None = None
|
||||
|
||||
def render_prefix(self) -> str:
|
||||
rendered: list[str] = []
|
||||
for message in self.messages:
|
||||
role = message.get("role")
|
||||
content = message.get("content")
|
||||
if role not in {"user", "assistant"} or not isinstance(content, str):
|
||||
continue
|
||||
body = content
|
||||
if role == "user" and message.get("video") is not None:
|
||||
body = "<|vision_start|><|video_pad|><|vision_end|>" + content
|
||||
if not body:
|
||||
continue
|
||||
rendered.append(f"<|im_start|>{role}\n{body}<|im_end|>\n")
|
||||
return "".join(rendered)
|
||||
|
||||
def retained_videos(self) -> list[object]:
|
||||
"""Committed clips that still have pixels, in prompt order."""
|
||||
return [
|
||||
message["video"]
|
||||
for message in self.messages
|
||||
if message.get("role") == "user" and message.get("video") is not None
|
||||
]
|
||||
|
||||
def begin_user_turn(self, transcript: str, video: object | None = None) -> None:
|
||||
self.pending_user = transcript.strip()
|
||||
self.pending_video = video
|
||||
|
||||
def commit_turn(self, assistant_text: str) -> None:
|
||||
user = self.pending_user or ""
|
||||
video = self.pending_video
|
||||
self.pending_user = None
|
||||
self.pending_video = None
|
||||
text = (assistant_text or "").strip()
|
||||
if not user and video is None:
|
||||
if not text or text == _SILENT:
|
||||
return
|
||||
self.messages.append({"role": "assistant", "content": text})
|
||||
self.prune()
|
||||
return
|
||||
user_message: dict[str, object] = {"role": "user", "content": user}
|
||||
if video is not None:
|
||||
user_message["video"] = video
|
||||
self.messages.append(user_message)
|
||||
self.messages.append({"role": "assistant", "content": text or _SILENT})
|
||||
self.prune()
|
||||
|
||||
def prune(self) -> None:
|
||||
video_indices = [
|
||||
index
|
||||
for index, message in enumerate(self.messages)
|
||||
if message.get("role") == "user" and message.get("video") is not None
|
||||
]
|
||||
if len(video_indices) > self.max_video_rounds:
|
||||
drop: set[int] = set()
|
||||
for index in video_indices[: self.video_rounds_to_remove]:
|
||||
user_message = self.messages[index]
|
||||
user_message["video"] = None
|
||||
text = user_message.get("content")
|
||||
if isinstance(text, str) and text.strip():
|
||||
continue
|
||||
nxt = index + 1
|
||||
if nxt >= len(self.messages) or self.messages[nxt].get("role") != "assistant":
|
||||
continue
|
||||
assistant = self.messages[nxt].get("content")
|
||||
if isinstance(assistant, str) and assistant.strip() in {_SILENT, ""}:
|
||||
drop.add(index)
|
||||
drop.add(nxt)
|
||||
if drop:
|
||||
self.messages = [message for index, message in enumerate(self.messages) if index not in drop]
|
||||
user_count = sum(1 for message in self.messages if message.get("role") == "user")
|
||||
overflow = user_count - self.max_conversation_rounds
|
||||
if overflow > 0:
|
||||
self.messages = self.messages[overflow * 2 :]
|
||||
|
||||
|
||||
def get_or_create_session_history(session_id: str) -> SessionHistory:
|
||||
with _LOCK:
|
||||
history = _STORE.get(session_id)
|
||||
if history is None:
|
||||
history = SessionHistory(session_id=session_id)
|
||||
_STORE[session_id] = history
|
||||
return history
|
||||
|
||||
|
||||
def drop_session_history(session_id: str) -> None:
|
||||
with _LOCK:
|
||||
_STORE.pop(session_id, None)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SessionHistory",
|
||||
"drop_session_history",
|
||||
"get_or_create_session_history",
|
||||
]
|
||||
@@ -0,0 +1,186 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Commit-only PCM buffer for AURA duplex (emit whole utterance on commit)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.pcm_reservation import (
|
||||
commit_ordered_reservation,
|
||||
rollback_ordered_reservation,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import PcmAppendBuffer, PcmAppendReservation
|
||||
|
||||
_SAMPLE_BYTES = 4
|
||||
_DEFAULT_SAMPLE_RATE_HZ = 16000
|
||||
|
||||
|
||||
class AuraPcmAppendReservation(PcmAppendReservation):
|
||||
__slots__ = ("_active", "_owner", "_raw", "_reserved_bytes", "operation_id", "payload")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
owner: AuraPcmAppendBuffer,
|
||||
operation_id: str,
|
||||
payload: dict[str, object] | None,
|
||||
raw: bytes,
|
||||
reserved_bytes: int | None = None,
|
||||
) -> None:
|
||||
self._owner = owner
|
||||
self.operation_id = operation_id
|
||||
self.payload = payload
|
||||
self._raw = raw
|
||||
self._reserved_bytes = len(raw) if reserved_bytes is None else reserved_bytes
|
||||
self._active = True
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
return self._active
|
||||
|
||||
@property
|
||||
def byte_count(self) -> int:
|
||||
return self._reserved_bytes
|
||||
|
||||
def commit(self) -> None:
|
||||
commit_ordered_reservation(self._owner._reservations, self, head_only=False)
|
||||
|
||||
def rollback(self) -> None:
|
||||
rollback_ordered_reservation(
|
||||
self._owner._reservations,
|
||||
self,
|
||||
self._owner._buffer,
|
||||
active_only=True,
|
||||
)
|
||||
|
||||
|
||||
class AuraPcmAppendBuffer(PcmAppendBuffer):
|
||||
"""Accumulate PCM until commit; ignore 1s auto-flush unit semantics."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._buffer = bytearray()
|
||||
self._sample_rate_hz: int | None = None
|
||||
self._frame_queue: list[str] = []
|
||||
self._reservations: list[AuraPcmAppendReservation] = []
|
||||
self._had_speech = False
|
||||
|
||||
@property
|
||||
def pending_byte_count(self) -> int:
|
||||
# Include retained video frame wire sizes so admission/release accounting
|
||||
# stays balanced after the mailbox releases the full append reservation.
|
||||
return len(self._buffer) + sum(len(frame) for frame in self._frame_queue)
|
||||
|
||||
def clear(self) -> None:
|
||||
self._buffer.clear()
|
||||
self._frame_queue.clear()
|
||||
self._reservations.clear()
|
||||
self._had_speech = False
|
||||
|
||||
def clear_force_listen(self) -> None:
|
||||
return
|
||||
|
||||
def has_pending(self) -> bool:
|
||||
return bool(self._buffer) or bool(self._frame_queue)
|
||||
|
||||
def has_reserved(self) -> bool:
|
||||
return any(reservation.active for reservation in self._reservations)
|
||||
|
||||
def prepare_append(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
allow_emit: bool,
|
||||
) -> AuraPcmAppendReservation | None:
|
||||
del chunk_period_ms, allow_emit, operation_id
|
||||
fmt = payload.get("format")
|
||||
sample_rate_hz = payload.get("sample_rate_hz")
|
||||
audio = payload.get("audio")
|
||||
frames_in = payload.get("video_frames")
|
||||
if isinstance(frames_in, list):
|
||||
latest = [frame for frame in frames_in if isinstance(frame, str) and frame]
|
||||
if latest:
|
||||
self._frame_queue = latest[-2:]
|
||||
|
||||
if fmt != "pcm_f32le" or not isinstance(sample_rate_hz, int) or not isinstance(audio, str):
|
||||
self._had_speech = self._had_speech or bool(payload.get("is_speech", False))
|
||||
return None
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
return None
|
||||
if len(raw) % _SAMPLE_BYTES:
|
||||
return None
|
||||
|
||||
if self._sample_rate_hz is not None and self._sample_rate_hz != sample_rate_hz:
|
||||
raise ValueError("AURA duplex audio append sample_rate_hz changed within a session")
|
||||
self._sample_rate_hz = sample_rate_hz
|
||||
self._buffer.extend(raw)
|
||||
self._had_speech = self._had_speech or bool(payload.get("is_speech", True))
|
||||
return None
|
||||
|
||||
def prepare_commit(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
chunk_period_ms: int,
|
||||
) -> AuraPcmAppendReservation:
|
||||
del chunk_period_ms
|
||||
if not self._buffer and not self._frame_queue:
|
||||
reservation = AuraPcmAppendReservation(
|
||||
owner=self,
|
||||
operation_id=operation_id,
|
||||
payload=None,
|
||||
raw=b"",
|
||||
reserved_bytes=0,
|
||||
)
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
|
||||
sample_rate_hz = self._sample_rate_hz or _DEFAULT_SAMPLE_RATE_HZ
|
||||
raw = bytes(self._buffer)
|
||||
self._buffer.clear()
|
||||
payload: dict[str, object] = {
|
||||
"type": "audio",
|
||||
"audio": base64.b64encode(raw).decode("ascii") if raw else "",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": sample_rate_hz,
|
||||
"final": True,
|
||||
# Do not infer speech from non-empty PCM: vision-follow often sends
|
||||
# 10ms zeros with is_speech=False so Stage0/1 treat it as vision-only
|
||||
# rather than a new spoken utterance.
|
||||
"is_speech": self._had_speech,
|
||||
"aura_turn_commit": True,
|
||||
}
|
||||
video_bytes = 0
|
||||
if self._frame_queue:
|
||||
payload["video_frames"] = list(self._frame_queue)
|
||||
video_bytes = sum(len(frame) for frame in self._frame_queue)
|
||||
self._frame_queue.clear()
|
||||
self._had_speech = False
|
||||
reservation = AuraPcmAppendReservation(
|
||||
owner=self,
|
||||
operation_id=operation_id,
|
||||
payload=payload,
|
||||
raw=raw,
|
||||
reserved_bytes=len(raw) + video_bytes,
|
||||
)
|
||||
self._reservations.append(reservation)
|
||||
return reservation
|
||||
|
||||
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
|
||||
reservation = self.prepare_commit(
|
||||
operation_id="flush",
|
||||
chunk_period_ms=chunk_period_ms,
|
||||
)
|
||||
reservation.commit()
|
||||
return reservation.payload
|
||||
|
||||
|
||||
__all__ = ["AuraPcmAppendBuffer", "AuraPcmAppendReservation"]
|
||||
@@ -0,0 +1,520 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""AURA full-duplex model plugin: turn-commit four-stage NewRequest."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import binascii
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pybase64 as base64
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexAppendPlan,
|
||||
DuplexFence,
|
||||
DuplexOutputAction,
|
||||
DuplexOutputDecision,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelPlugin, EncodeAudio
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.capabilities import aura_duplex_capabilities
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import (
|
||||
AuraDataPlaneContext,
|
||||
AuraDataPlaneSession,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.session import AuraServingSessionState
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
DEFAULT_AURA_SYSTEM_PROMPT,
|
||||
SILENT_TEXT,
|
||||
is_effectively_silent,
|
||||
)
|
||||
|
||||
# AURA v1 (Qwen3-VL) silent / ChatML turn-end ids.
|
||||
AURA_SILENT_TOKEN_ID = 151669
|
||||
AURA_IM_END_TOKEN_ID = 151645
|
||||
AURA_SILENT_TOKEN_IDS = frozenset({AURA_SILENT_TOKEN_ID})
|
||||
|
||||
_PRIVATE_KEYS = frozenset(
|
||||
{
|
||||
"aura_system_prompt",
|
||||
"aura_history_revision",
|
||||
}
|
||||
)
|
||||
|
||||
_TTS_EXTRA_KEYS = (
|
||||
"tts_task_type",
|
||||
"tts_language",
|
||||
"tts_speaker",
|
||||
"tts_instruct",
|
||||
"tts_ref_audio",
|
||||
"tts_ref_text",
|
||||
"tts_x_vector_only_mode",
|
||||
)
|
||||
|
||||
|
||||
def _decode_pcm_f32le(payload: Mapping[str, object]) -> tuple[np.ndarray, int]:
|
||||
audio = payload.get("audio")
|
||||
sample_rate_hz = payload.get("sample_rate_hz", 16000)
|
||||
if not isinstance(audio, str) or not isinstance(sample_rate_hz, int):
|
||||
raise ValueError("AURA duplex commit payload requires pcm_f32le audio and sample_rate_hz")
|
||||
try:
|
||||
raw = base64.b64decode(audio, validate=True)
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise ValueError("AURA duplex audio is not valid base64") from exc
|
||||
if len(raw) % 4:
|
||||
raise ValueError("AURA duplex pcm_f32le payload has a partial sample")
|
||||
values = np.frombuffer(raw, dtype="<f4").copy()
|
||||
return values, sample_rate_hz
|
||||
|
||||
|
||||
def _video_frames_to_mm(frames: object) -> dict[str, object]:
|
||||
if not isinstance(frames, list) or not frames:
|
||||
return {}
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
images: list[object] = []
|
||||
for frame in frames:
|
||||
if not isinstance(frame, str) or not frame:
|
||||
continue
|
||||
try:
|
||||
raw = base64.b64decode(frame, validate=True)
|
||||
except (binascii.Error, ValueError):
|
||||
continue
|
||||
try:
|
||||
images.append(np.asarray(Image.open(BytesIO(raw)).convert("RGB")))
|
||||
except Exception:
|
||||
continue
|
||||
if not images:
|
||||
return {}
|
||||
# One <|video_pad|> for the whole clip. Two separate images with one
|
||||
# <|image_pad|> crash Stage1 (mm_items['image'][1]). Qwen3-VL's temporal
|
||||
# patch wants at least two frames; a single sticky frame is duplicated.
|
||||
if len(images) == 1:
|
||||
images = [images[0], images[0]]
|
||||
video = np.stack(images, axis=0)
|
||||
n_frames = int(video.shape[0])
|
||||
metadata = {
|
||||
"fps": 2.0,
|
||||
"duration": n_frames / 2.0,
|
||||
"total_num_frames": n_frames,
|
||||
"frames_indices": list(range(n_frames)),
|
||||
"video_backend": "opencv",
|
||||
"do_sample_frames": False,
|
||||
}
|
||||
return {"video": [(video, metadata)]}
|
||||
|
||||
|
||||
def _completion_token_ids(completion: object | None) -> list[int]:
|
||||
if completion is None:
|
||||
return []
|
||||
for attr in ("token_ids", "cumulative_token_ids"):
|
||||
value = getattr(completion, attr, None)
|
||||
if isinstance(value, list | tuple):
|
||||
out: list[int] = []
|
||||
for item in value:
|
||||
try:
|
||||
out.append(int(item))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if out:
|
||||
return out
|
||||
return []
|
||||
|
||||
|
||||
def _first_completion(output: object) -> object | None:
|
||||
outputs = getattr(output, "outputs", None)
|
||||
if isinstance(outputs, list) and outputs:
|
||||
return outputs[0]
|
||||
return None
|
||||
|
||||
|
||||
class AuraDuplexPlugin(DuplexModelPlugin):
|
||||
"""Turn-commit AURA: one ephemeral four-stage request per utterance."""
|
||||
|
||||
plugin_id = "aura"
|
||||
private_runtime_config_keys = _PRIVATE_KEYS
|
||||
|
||||
def __init__(self, encode_audio: EncodeAudio) -> None:
|
||||
super().__init__(encode_audio)
|
||||
self.data_plane = AuraDataPlaneSession(encode_audio)
|
||||
|
||||
def configure_sampling_params(
|
||||
self,
|
||||
*,
|
||||
runtime_config: dict[str, object],
|
||||
defaults: tuple[object, ...],
|
||||
) -> tuple[object, ...]:
|
||||
del runtime_config
|
||||
configured = list(defaults)
|
||||
if len(configured) > 1 and isinstance(configured[1], SamplingParams):
|
||||
stage1 = configured[1].clone()
|
||||
stop_ids = list(stage1.stop_token_ids or [])
|
||||
for stop_id in (AURA_SILENT_TOKEN_ID, AURA_IM_END_TOKEN_ID):
|
||||
if stop_id not in stop_ids:
|
||||
stop_ids.append(stop_id)
|
||||
stage1.stop_token_ids = stop_ids
|
||||
# 151669 is a stop id: keep it in the completion so decide_output /
|
||||
# aura2tts can see <|silent|> instead of an empty detokenized string.
|
||||
stage1.include_stop_str_in_output = True
|
||||
stage1.skip_special_tokens = False
|
||||
configured[1] = stage1
|
||||
# Codec EOS (2150) and the 240-token cap are defaults for an unset
|
||||
# Talker config. A value already set by yaml or the caller is kept,
|
||||
# even when max_tokens is longer than 240.
|
||||
if len(configured) > 2 and isinstance(configured[2], SamplingParams):
|
||||
stage2 = configured[2].clone()
|
||||
if not stage2.stop_token_ids:
|
||||
stage2.stop_token_ids = [2150]
|
||||
if stage2.max_tokens is None:
|
||||
stage2.max_tokens = 240
|
||||
configured[2] = stage2
|
||||
return tuple(configured)
|
||||
|
||||
def draining_stage_ids(self, *, stage_count: int) -> frozenset[int]:
|
||||
# Talker is stage 2; Code2Wav is the last stage. Stage 0/1 are the
|
||||
# input gate and are idle once a turn is released.
|
||||
if stage_count <= 2:
|
||||
return frozenset()
|
||||
return frozenset(range(2, stage_count))
|
||||
|
||||
def plan_append(
|
||||
self,
|
||||
*,
|
||||
request_id: str,
|
||||
fence: DuplexFence,
|
||||
session_config: dict[str, object],
|
||||
runtime_config: dict[str, object],
|
||||
seq: int,
|
||||
turn_seq: int,
|
||||
payload: object,
|
||||
final: bool,
|
||||
sampling_params: object,
|
||||
) -> DuplexAppendPlan:
|
||||
del request_id, session_config, seq, turn_seq, sampling_params
|
||||
|
||||
def _skip() -> DuplexAppendPlan:
|
||||
return DuplexAppendPlan(
|
||||
prompt={
|
||||
"prompt_token_ids": [0],
|
||||
"additional_information": {
|
||||
"aura_skip_submit": True,
|
||||
"session_id": fence.session_id,
|
||||
"epoch": fence.epoch,
|
||||
"turn_id": fence.turn_id,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if not isinstance(payload, Mapping):
|
||||
if not final:
|
||||
return _skip()
|
||||
raise ValueError("AURA duplex plan_append expects a mapping payload")
|
||||
if not final and not payload.get("aura_turn_commit"):
|
||||
return _skip()
|
||||
|
||||
mm = _video_frames_to_mm(payload.get("video_frames"))
|
||||
audio_b64 = payload.get("audio")
|
||||
is_speech = bool(payload.get("is_speech", True))
|
||||
has_audio = isinstance(audio_b64, str) and bool(audio_b64)
|
||||
if has_audio:
|
||||
wav, sample_rate_hz = _decode_pcm_f32le(payload)
|
||||
else:
|
||||
wav, sample_rate_hz = np.zeros(0, dtype=np.float32), int(payload.get("sample_rate_hz") or 16000)
|
||||
# Vision-follow commits often carry empty or near-silent PCM with
|
||||
# is_speech=False. All-zero audio crashes Qwen3ASRProcessor, and an
|
||||
# empty Stage0 prompt is rejected ("decoder prompt cannot be empty").
|
||||
# Also guard is_speech=True + empty-audio + frames (prompt was "").
|
||||
sample_rate_hz = int(sample_rate_hz or payload.get("sample_rate_hz") or 16000)
|
||||
wav_rms = float(np.sqrt(np.mean(np.square(wav.astype(np.float32, copy=False))))) if wav.size else 0.0
|
||||
near_silent = wav.size == 0 or not np.any(wav) or wav_rms < 1e-3
|
||||
if mm and (not has_audio or (not is_speech and near_silent)):
|
||||
n = max(1600, int(sample_rate_hz) // 10)
|
||||
wav = np.linspace(1e-4, -1e-4, n, dtype=np.float32)
|
||||
has_audio = True
|
||||
if not has_audio and not mm:
|
||||
raise ValueError("AURA duplex commit requires audio and/or video_frames")
|
||||
system_prompt = runtime_config.get("aura_system_prompt", DEFAULT_AURA_SYSTEM_PROMPT)
|
||||
|
||||
additional_information: dict[str, object] = {
|
||||
"aura_system_prompt": system_prompt,
|
||||
"aura_session_id": fence.session_id,
|
||||
"aura_duplex": True,
|
||||
"session_id": fence.session_id,
|
||||
"epoch": fence.epoch,
|
||||
"turn_id": fence.turn_id,
|
||||
# asr2aura ignores Stage0 text when False (placeholder zeros).
|
||||
"is_speech": is_speech,
|
||||
"tts_task_type": runtime_config.get("tts_task_type", "CustomVoice"),
|
||||
"tts_language": runtime_config.get("tts_language", "Chinese"),
|
||||
"tts_speaker": runtime_config.get("tts_speaker", "Vivian"),
|
||||
}
|
||||
item_id = payload.get("realtime_item_id")
|
||||
if isinstance(item_id, str) and item_id:
|
||||
additional_information["realtime_item_id"] = item_id
|
||||
for key in _TTS_EXTRA_KEYS:
|
||||
if key in additional_information:
|
||||
continue
|
||||
value = runtime_config.get(key)
|
||||
if value is not None:
|
||||
additional_information[key] = value
|
||||
if mm:
|
||||
additional_information["deferred_multi_modal_data"] = mm
|
||||
|
||||
asr_prompt = (
|
||||
"<|im_start|>user\n"
|
||||
"<|audio_start|><|audio_pad|><|audio_end|>"
|
||||
"Please transcribe this speech.<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
)
|
||||
multi_modal_data: dict[str, object] = {}
|
||||
if has_audio:
|
||||
multi_modal_data["audio"] = (wav, sample_rate_hz)
|
||||
# Never submit an empty decoder prompt: Stage0 always needs the ASR pad
|
||||
# when audio (or a vision-driven pad) is present.
|
||||
prompt: dict[str, Any] = {
|
||||
"prompt": asr_prompt if has_audio else "",
|
||||
"multi_modal_data": multi_modal_data,
|
||||
"additional_information": additional_information,
|
||||
}
|
||||
return DuplexAppendPlan(prompt=prompt)
|
||||
|
||||
def project_intermediate_output(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
output: object,
|
||||
context: object,
|
||||
) -> bool:
|
||||
"""Project Stage1 thinker text to the client without short-circuiting TTS."""
|
||||
del output, context
|
||||
return stage_id == 1
|
||||
|
||||
def user_transcript(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
output: object,
|
||||
prompt: object,
|
||||
finished: bool,
|
||||
) -> str | None:
|
||||
"""Stage0 ASR text for a spoken turn, so the demo can show what was said.
|
||||
|
||||
Vision-follow sets ``is_speech`` false; that audio is a silent pad and
|
||||
must not open a user bubble. The pipeline still forwards Stage0.
|
||||
"""
|
||||
if stage_id != 0 or not finished:
|
||||
return None
|
||||
info = prompt.get("additional_information") if isinstance(prompt, dict) else None
|
||||
if isinstance(info, dict) and info.get("is_speech") is False:
|
||||
return None
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
_extract_text,
|
||||
_normalize_asr_transcript,
|
||||
is_effectively_silent,
|
||||
)
|
||||
|
||||
text = _normalize_asr_transcript(_extract_text(output))
|
||||
if not text or is_effectively_silent(text):
|
||||
return None
|
||||
return text
|
||||
|
||||
def plan_partial_stage_output(
|
||||
self,
|
||||
orchestrator: Any,
|
||||
stage_id: int,
|
||||
replica_id: int,
|
||||
output: Any,
|
||||
req_state: Any,
|
||||
):
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.sentence_tts import (
|
||||
plan_partial_stage_output,
|
||||
)
|
||||
|
||||
return plan_partial_stage_output(orchestrator, stage_id, replica_id, output, req_state)
|
||||
|
||||
def partial_stage_followup(self, plan: Any, req_state: Any) -> Any:
|
||||
"""Close the Talker stream after a resumable final sentence.
|
||||
|
||||
The sentence text was already forwarded with ``queue_close_after``.
|
||||
Flipping the prompt flag here makes the second submit a close-only
|
||||
sentinel instead of another copy of that sentence.
|
||||
"""
|
||||
if plan is None or not getattr(plan, "queue_close_after", False):
|
||||
return None
|
||||
prompt = getattr(req_state, "prompt", None)
|
||||
info = prompt.get("additional_information") if isinstance(prompt, dict) else None
|
||||
if isinstance(info, dict):
|
||||
info["aura_tts_partial"] = True
|
||||
info["aura_tts_close_only"] = True
|
||||
from vllm_omni.engine.duplex.plugin import PartialStageForward
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.sentence_tts import (
|
||||
SentenceTtsOutput,
|
||||
)
|
||||
|
||||
request_id = str(getattr(plan.output, "request_id", ""))
|
||||
return PartialStageForward(
|
||||
output=SentenceTtsOutput(request_id, ""),
|
||||
is_final_update=True,
|
||||
close_only=True,
|
||||
)
|
||||
|
||||
def commit_model_context(self, *, session_id: str | None, assistant_text: str) -> None:
|
||||
if not isinstance(session_id, str) or not session_id:
|
||||
return
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import get_or_create_session_history
|
||||
|
||||
get_or_create_session_history(session_id).commit_turn(assistant_text or SILENT_TEXT)
|
||||
|
||||
def release_concurrent_turn_requests(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
segment_finished: bool,
|
||||
output: object,
|
||||
context: object,
|
||||
) -> bool:
|
||||
"""After Stage1 text/silent final, next commit may start while TTS drains."""
|
||||
del context
|
||||
if stage_id != 1:
|
||||
return False
|
||||
if segment_finished:
|
||||
return True
|
||||
return bool(getattr(output, "finished", False))
|
||||
|
||||
def decide_output(
|
||||
self,
|
||||
*,
|
||||
stage_id: int,
|
||||
final_stage_id: int,
|
||||
segment_finished: bool,
|
||||
segment_token_ids: tuple[int, ...],
|
||||
segment_output_metadata: dict[str, object],
|
||||
output: object,
|
||||
) -> DuplexOutputDecision | None:
|
||||
del final_stage_id, segment_output_metadata
|
||||
# Stage1 silent → short-circuit TTS/Code2Wav.
|
||||
if stage_id != 1 or not segment_finished:
|
||||
return None
|
||||
completion = _first_completion(output)
|
||||
token_ids = _completion_token_ids(completion) or list(segment_token_ids)
|
||||
text = getattr(completion, "text", None) if completion is not None else None
|
||||
cumulative = getattr(completion, "cumulative_text", None) if completion is not None else None
|
||||
text_blob = " ".join(part for part in (text, cumulative) if isinstance(part, str))
|
||||
# Empty finished Stage1 is silent: stop_token 151669 is often omitted from
|
||||
# token_ids/text unless include_stop_str_in_output is set.
|
||||
is_silent = (
|
||||
any(sid in token_ids for sid in AURA_SILENT_TOKEN_IDS)
|
||||
or (isinstance(text, str) and is_effectively_silent(text))
|
||||
or (isinstance(cumulative, str) and is_effectively_silent(cumulative))
|
||||
or SILENT_TEXT in text_blob
|
||||
)
|
||||
if not is_silent and not token_ids and not text_blob.strip():
|
||||
is_silent = True
|
||||
if not is_silent and token_ids:
|
||||
is_silent = token_ids[0] in AURA_SILENT_TOKEN_IDS or (
|
||||
len(token_ids) > 3 and any(sid in token_ids[:6] for sid in AURA_SILENT_TOKEN_IDS)
|
||||
)
|
||||
if not is_silent:
|
||||
return None
|
||||
return DuplexOutputDecision(
|
||||
action=DuplexOutputAction.DIRECT_RESPONSE,
|
||||
metadata={
|
||||
"duplex_direct_response": True,
|
||||
"model_listen": True,
|
||||
"listen_source": "aura_silent",
|
||||
"silent_text": SILENT_TEXT,
|
||||
},
|
||||
)
|
||||
|
||||
def create_session_state(self) -> AuraServingSessionState:
|
||||
return AuraServingSessionState()
|
||||
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
|
||||
return aura_duplex_capabilities(max_sessions=max_sessions)
|
||||
|
||||
def validate_client_extra_body(self, extra_body: object) -> None:
|
||||
if extra_body is None:
|
||||
return
|
||||
if not isinstance(extra_body, dict):
|
||||
raise ValueError("AURA duplex extra_body must be an object")
|
||||
|
||||
async def prepare_runtime_config(
|
||||
self, config: DuplexSessionConfig, *, model_config: object | None
|
||||
) -> dict[str, object]:
|
||||
del model_config
|
||||
extra = config.extra_body if isinstance(config.extra_body, dict) else {}
|
||||
system_prompt = extra.get("aura_system_prompt") or config.instructions or DEFAULT_AURA_SYSTEM_PROMPT
|
||||
runtime: dict[str, object] = {
|
||||
"aura_system_prompt": str(system_prompt),
|
||||
"instructions": str(system_prompt),
|
||||
"tts_task_type": str(extra.get("tts_task_type") or "CustomVoice"),
|
||||
"tts_language": str(extra.get("tts_language") or "Chinese"),
|
||||
"tts_speaker": str(extra.get("tts_speaker") or "Vivian"),
|
||||
}
|
||||
for key in _TTS_EXTRA_KEYS:
|
||||
if key in runtime:
|
||||
continue
|
||||
if key in extra and extra[key] is not None:
|
||||
runtime[key] = extra[key]
|
||||
return runtime
|
||||
|
||||
def runtime_config_for_update(
|
||||
self,
|
||||
config: DuplexSessionConfig,
|
||||
current: Mapping[str, object],
|
||||
) -> dict[str, object]:
|
||||
updated = dict(current)
|
||||
extra = config.extra_body if isinstance(config.extra_body, dict) else {}
|
||||
# Same precedence as prepare_runtime_config: explicit extra, then
|
||||
# instructions, then the prompt already installed (or the default).
|
||||
# setdefault would keep the creation-time prompt and ignore a later
|
||||
# session.update.instructions.
|
||||
explicit = extra.get("aura_system_prompt") if "aura_system_prompt" in extra else None
|
||||
if isinstance(explicit, str) and explicit:
|
||||
prompt = explicit
|
||||
elif config.instructions:
|
||||
prompt = str(config.instructions)
|
||||
else:
|
||||
current_prompt = current.get("aura_system_prompt")
|
||||
prompt = (
|
||||
str(current_prompt)
|
||||
if isinstance(current_prompt, str) and current_prompt
|
||||
else DEFAULT_AURA_SYSTEM_PROMPT
|
||||
)
|
||||
updated["aura_system_prompt"] = prompt
|
||||
updated["instructions"] = str(config.instructions) if config.instructions else prompt
|
||||
for key in _TTS_EXTRA_KEYS:
|
||||
if key in extra and extra[key] is not None:
|
||||
updated[key] = extra[key]
|
||||
return updated
|
||||
|
||||
def data_plane_context(
|
||||
self,
|
||||
*,
|
||||
epoch: int,
|
||||
turn_id: int,
|
||||
active_response_turn_id: int | None,
|
||||
active_response_id: str | None,
|
||||
auto_responds: bool,
|
||||
response_format: str,
|
||||
speed: float | None,
|
||||
modalities: tuple[str, ...],
|
||||
) -> AuraDataPlaneContext:
|
||||
del active_response_turn_id, active_response_id
|
||||
return AuraDataPlaneContext(
|
||||
epoch=epoch,
|
||||
turn_id=turn_id,
|
||||
auto_responds=auto_responds,
|
||||
response_format=response_format,
|
||||
speed=speed,
|
||||
modalities=modalities,
|
||||
)
|
||||
|
||||
|
||||
__all__ = ["AURA_SILENT_TOKEN_ID", "AuraDuplexPlugin"]
|
||||
@@ -0,0 +1,189 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Stage1 sentence handoff onto Talker. AURA-only; the orchestrator just calls it."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.engine.duplex.plugin import PartialStageForward
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SentenceTtsOutput:
|
||||
"""Stage1 view that exposes only the sentence Talker should speak."""
|
||||
|
||||
def __init__(self, request_id: str, text: str) -> None:
|
||||
self.request_id = request_id
|
||||
self.finished = False
|
||||
self.text = text
|
||||
self.cumulative_text = text
|
||||
self.outputs = [self]
|
||||
self.token_ids: list[int] = []
|
||||
|
||||
|
||||
def _call_decode(decode: Any, token_ids: list[int]) -> str:
|
||||
try:
|
||||
decoded = decode(token_ids, skip_special_tokens=False)
|
||||
except TypeError:
|
||||
decoded = decode(token_ids)
|
||||
return decoded if isinstance(decoded, str) else ""
|
||||
|
||||
|
||||
def decode_growing_token_ids(decode: Any, token_ids: list[int], cache: dict[str, object]) -> str:
|
||||
"""Decode a growing id list, re-decoding only the unstable tail.
|
||||
|
||||
The returned text matches ``decode(token_ids)`` when the tail window is a
|
||||
suffix of that string. Otherwise the full id list is decoded.
|
||||
"""
|
||||
ids = list(token_ids)
|
||||
prev_ids = cache.get("decoded_ids")
|
||||
prev_text = cache.get("decoded_text")
|
||||
overlap_text = cache.get("decoded_overlap_text")
|
||||
candidate: str | None = None
|
||||
if (
|
||||
isinstance(prev_ids, list)
|
||||
and isinstance(prev_text, str)
|
||||
and isinstance(overlap_text, str)
|
||||
and prev_ids
|
||||
and len(ids) > len(prev_ids)
|
||||
and ids[: len(prev_ids)] == prev_ids
|
||||
and prev_text.endswith(overlap_text)
|
||||
and overlap_text
|
||||
):
|
||||
extended = _call_decode(decode, [*prev_ids[-1:], *ids[len(prev_ids) :]])
|
||||
if extended.startswith(overlap_text):
|
||||
candidate = prev_text[: len(prev_text) - len(overlap_text)] + extended
|
||||
window_ids = [*prev_ids[-2:], *ids[len(prev_ids) :]] if len(prev_ids) >= 2 else ids
|
||||
window_text = _call_decode(decode, window_ids)
|
||||
if window_text and not candidate.endswith(window_text):
|
||||
candidate = None
|
||||
if candidate is None:
|
||||
candidate = _call_decode(decode, ids)
|
||||
cache["decoded_ids"] = ids
|
||||
cache["decoded_text"] = candidate
|
||||
cache["decoded_overlap_text"] = _call_decode(decode, ids[-1:]) if ids else ""
|
||||
return candidate
|
||||
|
||||
|
||||
def stage1_tts_text(orchestrator: Any, output: Any, *, cache: dict[str, object] | None = None) -> str:
|
||||
"""Stage1 text for sentence TTS.
|
||||
|
||||
``cumulative_text`` is attached only when the request finishes.
|
||||
Mid-generation chunks still carry ``cumulative_token_ids``.
|
||||
"""
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
_extract_output,
|
||||
_extract_text,
|
||||
)
|
||||
|
||||
completion = _extract_output(output)
|
||||
cumulative = getattr(completion, "cumulative_text", None)
|
||||
if isinstance(cumulative, str) and cumulative:
|
||||
return cumulative
|
||||
token_ids = getattr(completion, "cumulative_token_ids", None)
|
||||
if isinstance(token_ids, list) and token_ids:
|
||||
processor = orchestrator.stage_pools[1].output_processor
|
||||
tokenizer = getattr(processor, "tokenizer", None)
|
||||
decode = getattr(tokenizer, "decode", None)
|
||||
if callable(decode):
|
||||
if cache is None:
|
||||
decoded = _call_decode(decode, list(token_ids))
|
||||
else:
|
||||
decoded = decode_growing_token_ids(decode, list(token_ids), cache)
|
||||
if decoded:
|
||||
return decoded
|
||||
return _extract_text(output)
|
||||
|
||||
|
||||
def plan_partial_stage_output(
|
||||
orchestrator: Any,
|
||||
stage_id: int,
|
||||
replica_id: int,
|
||||
output: Any,
|
||||
req_state: Any,
|
||||
) -> PartialStageForward | None:
|
||||
"""Hand a finished sentence to Talker before Stage1 finishes.
|
||||
|
||||
Same request id as the turn (Code2Wav was prewarmed on it). Text goes
|
||||
through ``aura2tts`` in the orchestrator, not the ``from_stage_1`` SHM
|
||||
edge that clears ``additional_information.text``. Talker stays resumable
|
||||
until Stage1 finishes. The orchestrator submits the returned plan.
|
||||
"""
|
||||
del replica_id
|
||||
if not req_state.session_owned or stage_id != 1:
|
||||
return
|
||||
if stage_id + 1 > req_state.final_stage_id:
|
||||
return
|
||||
next_client = orchestrator.stage_pools[stage_id + 1].stage_client
|
||||
processor = getattr(next_client, "custom_process_input_func", None)
|
||||
if getattr(processor, "__name__", "") != "aura2tts":
|
||||
return
|
||||
if orchestrator._stage_receives_async_chunks(stage_id + 1):
|
||||
return
|
||||
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
_sentence_tts_enabled,
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
if not _sentence_tts_enabled():
|
||||
return
|
||||
|
||||
bridge = req_state.streaming.bridge_states.setdefault("aura_sentence_tts", {})
|
||||
if not isinstance(bridge, dict):
|
||||
bridge = {}
|
||||
req_state.streaming.bridge_states["aura_sentence_tts"] = bridge
|
||||
if bridge.get("closed"):
|
||||
return
|
||||
|
||||
finished = bool(getattr(output, "finished", False))
|
||||
raw_text = stage1_tts_text(orchestrator, output, cache=bridge)
|
||||
# Captured before the chunk helper increments ``emits``.
|
||||
prior_emits = int(bridge.get("emits", 0))
|
||||
chunk = next_duplex_sentence_chunk(bridge, raw_text, finished=finished)
|
||||
close_only = False
|
||||
if chunk is None:
|
||||
if not (finished and int(bridge.get("emits", 0))):
|
||||
return
|
||||
chunk = ""
|
||||
close_only = True
|
||||
if not chunk and not close_only:
|
||||
return
|
||||
|
||||
prompt = req_state.prompt if isinstance(req_state.prompt, dict) else None
|
||||
if prompt is not None:
|
||||
raw_info = prompt.get("additional_information")
|
||||
if not isinstance(raw_info, dict):
|
||||
raw_info = {}
|
||||
prompt["additional_information"] = raw_info
|
||||
# History is committed by the session runner from model_context_text.
|
||||
# Partial and close-only updates must not commit inside aura2tts.
|
||||
raw_info["aura_tts_partial"] = True
|
||||
raw_info["aura_tts_close_only"] = close_only
|
||||
|
||||
view = SentenceTtsOutput(str(getattr(output, "request_id", req_state.request_id)), chunk)
|
||||
# A later sentence on an already-running Talker must stay resumable.
|
||||
# is_final_update=True is a non-resumable end sentinel: it discards this
|
||||
# text and sets streaming_input=False on the in-flight sentence, so
|
||||
# Code2Wav sees a short codec and the user hears a blip.
|
||||
queue_close_after = bool(chunk) and finished and not close_only and prior_emits > 0
|
||||
logger.info(
|
||||
"[AURA] sentence TTS req=%s finished=%s close_only=%s text_len=%d queue_close_after=%s",
|
||||
req_state.request_id,
|
||||
finished,
|
||||
close_only,
|
||||
len(chunk),
|
||||
queue_close_after,
|
||||
)
|
||||
if finished:
|
||||
bridge["closed"] = True
|
||||
return PartialStageForward(
|
||||
output=view,
|
||||
is_final_update=finished and not queue_close_after,
|
||||
close_only=close_only,
|
||||
queue_close_after=queue_close_after,
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from vllm_omni.engine.duplex.plugin import DuplexModelSessionState
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.input import AuraPcmAppendBuffer
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class AuraServingSessionState(DuplexModelSessionState):
|
||||
"""Per-session AURA duplex state (owned by SessionRunner)."""
|
||||
|
||||
audio_buffer: AuraPcmAppendBuffer = field(default_factory=AuraPcmAppendBuffer)
|
||||
input_since_commit: bool = False
|
||||
speech_since_commit: bool = False
|
||||
context_locked: bool = False
|
||||
committed_audio_payload: dict[str, object] | None = None
|
||||
committed_audio_operation_id: str | None = None
|
||||
committed_audio_reserved_bytes: int = 0
|
||||
deferred_response_create: bool = False
|
||||
deferred_precreate_response: bool = False
|
||||
continuation_owner_id: str | None = None
|
||||
continuation_units: int = 0
|
||||
pending_silence_task: asyncio.Task[bool] | None = None
|
||||
pending_silence_owner_id: str | None = None
|
||||
|
||||
def retain_committed_audio(
|
||||
self,
|
||||
payload: dict[str, object],
|
||||
*,
|
||||
operation_id: str | None,
|
||||
reserved_bytes: int = 0,
|
||||
) -> None:
|
||||
self.committed_audio_payload = payload
|
||||
self.committed_audio_operation_id = operation_id
|
||||
self.committed_audio_reserved_bytes += max(0, int(reserved_bytes))
|
||||
|
||||
def clear_committed_audio(self) -> int:
|
||||
reserved_bytes = self.committed_audio_reserved_bytes
|
||||
self.committed_audio_payload = None
|
||||
self.committed_audio_operation_id = None
|
||||
self.committed_audio_reserved_bytes = 0
|
||||
self.deferred_response_create = False
|
||||
self.deferred_precreate_response = False
|
||||
return reserved_bytes
|
||||
|
||||
def clear_continuation(self) -> None:
|
||||
self.continuation_owner_id = None
|
||||
self.continuation_units = 0
|
||||
self.pending_silence_task = None
|
||||
self.pending_silence_owner_id = None
|
||||
|
||||
|
||||
__all__ = ["AuraServingSessionState"]
|
||||
@@ -26,6 +26,7 @@ AURA_OMNI_PIPELINE = PipelineConfig(
|
||||
model_type="aura_omni",
|
||||
default_deploy_config_name="aura_omni.yaml",
|
||||
model_arch="Qwen3ASRForConditionalGeneration",
|
||||
duplex_plugin="vllm_omni.model_executor.models.aura_omni.duplex.plugin.AuraDuplexPlugin",
|
||||
stages=(
|
||||
StagePipelineConfig(
|
||||
stage_id=0,
|
||||
|
||||
@@ -28,6 +28,9 @@ def minicpmo45_native_capabilities(*, max_sessions: int = 1) -> DuplexCapabiliti
|
||||
supports_scheduler_native_append=False,
|
||||
supports_core_resumable_request=True,
|
||||
supports_stage_connector_handoff=True,
|
||||
# Audio-primary: frames may ride an audio unit; video-only is illegal.
|
||||
required_input_modalities=frozenset({"audio"}),
|
||||
optional_input_modalities=frozenset({"video"}),
|
||||
supports_independent_io_streams=True,
|
||||
supports_realtime_endpoint=True,
|
||||
supports_multi_session=supports_multi_session,
|
||||
|
||||
@@ -10,6 +10,10 @@ from dataclasses import dataclass
|
||||
import numpy as np
|
||||
from numpy.typing import NDArray
|
||||
|
||||
from vllm_omni.engine.duplex.pcm_reservation import (
|
||||
commit_ordered_reservation,
|
||||
rollback_ordered_reservation,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import PcmAppendBuffer, PcmAppendReservation
|
||||
|
||||
|
||||
@@ -389,33 +393,23 @@ class MiniCPMO45PcmAppendBuffer(PcmAppendBuffer):
|
||||
return reservation.payload
|
||||
|
||||
def _commit_reservation(self, reservation: MiniCPMO45PcmAppendReservation) -> None:
|
||||
if not reservation._active:
|
||||
return
|
||||
if not self._reservations or self._reservations[0] is not reservation:
|
||||
raise RuntimeError("PCM append reservations must commit in wire order")
|
||||
self._reservations.pop(0)
|
||||
reservation._active = False
|
||||
commit_ordered_reservation(self._reservations, reservation, head_only=True)
|
||||
|
||||
def _rollback_reservation(self, reservation: MiniCPMO45PcmAppendReservation) -> None:
|
||||
if not reservation._active:
|
||||
rolled_back = rollback_ordered_reservation(
|
||||
self._reservations,
|
||||
reservation,
|
||||
self._buffer,
|
||||
active_only=False,
|
||||
)
|
||||
if not rolled_back:
|
||||
return
|
||||
try:
|
||||
index = self._reservations.index(reservation)
|
||||
except ValueError:
|
||||
reservation._active = False
|
||||
return
|
||||
rolled_back = self._reservations[index:]
|
||||
restored = b"".join(item._raw for item in rolled_back)
|
||||
self._buffer[:0] = restored
|
||||
self._prepend_spans([span for item in rolled_back for span in item._spans])
|
||||
restored_groups = [list(item._video_frames) for item in rolled_back if item._video_frames]
|
||||
if restored_groups:
|
||||
self._frame_queue[:0] = restored_groups
|
||||
self._sample_rate_hz = self._sample_rate_hz or reservation._sample_rate_hz
|
||||
self._turn_had_speech = self._turn_had_speech or any(item._turn_had_speech for item in rolled_back)
|
||||
for item in rolled_back:
|
||||
item._active = False
|
||||
del self._reservations[index:]
|
||||
|
||||
def flush(self, *, chunk_period_ms: int) -> dict[str, object] | None:
|
||||
if not self._buffer:
|
||||
|
||||
@@ -1151,9 +1151,18 @@ class Qwen3TTSTalkerForConditionalGeneration(nn.Module):
|
||||
next_text_offset = text_offset
|
||||
|
||||
last_hidden = hs.get("last")
|
||||
if not isinstance(last_hidden, torch.Tensor):
|
||||
raise RuntimeError("Missing hidden_states['last'] in additional_information; postprocess must run.")
|
||||
past_hidden_list.append(last_hidden.to(device=device, dtype=dtype).reshape(1, -1))
|
||||
if isinstance(last_hidden, torch.Tensor):
|
||||
past_hidden = last_hidden.to(device=device, dtype=dtype).reshape(1, -1)
|
||||
else:
|
||||
# Match scalar preprocess(): EOS / async-scheduling races can
|
||||
# arrive before postprocess has written last; zeros are filtered
|
||||
# downstream the same way as the single-request path.
|
||||
logger.warning_once(
|
||||
"Qwen3-TTS batched decode missing last hidden; zero-filling past_hidden "
|
||||
"to match scalar preprocess()"
|
||||
)
|
||||
past_hidden = torch.zeros_like(text_step)
|
||||
past_hidden_list.append(past_hidden)
|
||||
text_step_list.append(text_step)
|
||||
|
||||
info_update: dict[str, Any] = {
|
||||
|
||||
Reference in new issue
Block a user