[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,157 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.benchmarks.omniinteract import _session_capabilities, _wants_annotation_video_clock
|
||||
from vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock import (
|
||||
stream_annotation_clock,
|
||||
wants_annotation_video_clock,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _Events:
|
||||
def __init__(self, events):
|
||||
self.events = events
|
||||
|
||||
|
||||
class _Client:
|
||||
def __init__(self, capabilities):
|
||||
self.events = _Events([{"type": "session.created", "session": {"capabilities": capabilities}}])
|
||||
self._client = None
|
||||
|
||||
|
||||
def test_annotation_clock_follows_capabilities_not_model_name():
|
||||
aura = {"required_input_modalities": ["video"], "supports_turn_commit_only": True}
|
||||
minicpm = {"required_input_modalities": ["audio"], "supports_turn_commit_only": False}
|
||||
audio_commit = {"required_input_modalities": ["audio"], "supports_turn_commit_only": True}
|
||||
assert wants_annotation_video_clock(aura)
|
||||
assert not wants_annotation_video_clock(minicpm)
|
||||
assert not wants_annotation_video_clock(audio_commit)
|
||||
assert not wants_annotation_video_clock(None)
|
||||
assert _wants_annotation_video_clock(_Client(minicpm)) is False
|
||||
assert _wants_annotation_video_clock(_Client(aura)) is True
|
||||
assert _session_capabilities(_Client(aura))["required_input_modalities"] == ["video"]
|
||||
|
||||
|
||||
def test_annotation_clock_commits_only_the_due_wav(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Client:
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 0.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
chunks, frames, _, _ = asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["frame-a", "frame-b"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
assert (chunks, frames) == (2, 2)
|
||||
assert sent[0]["is_speech"] is True
|
||||
assert sent[0]["video_frames"] == ["frame-a"]
|
||||
assert sent[1] == {"type": "commit"}
|
||||
# The trailing silent frame is one vision turn, committed after the clip.
|
||||
assert sent[2]["is_speech"] is False
|
||||
assert sent[2]["video_frames"] == ["frame-b"]
|
||||
assert sent[3] == {"type": "commit"}
|
||||
assert sent.count({"type": "commit"}) == 2
|
||||
|
||||
|
||||
def test_annotation_clock_commits_silent_frames_in_pairs(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Client:
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 100.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["f1", "f2", "f3", "f4"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
vision = [event for event in sent if event.get("is_speech") is False]
|
||||
assert [event["video_frames"] for event in vision] == [["f1", "f2"], ["f3", "f4"]]
|
||||
assert sent.count({"type": "commit"}) == 2
|
||||
|
||||
|
||||
def test_annotation_clock_holds_vision_while_a_response_is_open(monkeypatch, tmp_path: Path):
|
||||
video = tmp_path / "videos" / "0002.mp4"
|
||||
video.parent.mkdir()
|
||||
video.write_bytes(b"")
|
||||
sent = []
|
||||
|
||||
class Events:
|
||||
def __init__(self):
|
||||
self.events = [{"type": "response.created", "response": {"id": "resp-open"}}]
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
self.events = Events()
|
||||
|
||||
async def send(self, event):
|
||||
sent.append(event)
|
||||
|
||||
async def commit(self):
|
||||
sent.append({"type": "commit"})
|
||||
|
||||
class Playback:
|
||||
async def acknowledge(self, client):
|
||||
del client
|
||||
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.aura_omni.benchmarks.omniinteract_clock.load_annotation_utterances",
|
||||
lambda path: [{"at_sec": 100.0, "pcm": b"\x01\x00" * 160, "sent": False, "qa_index": 0}],
|
||||
)
|
||||
asyncio.run(
|
||||
stream_annotation_clock(
|
||||
Client(),
|
||||
["f1", "f2", "f3", "f4"],
|
||||
Playback(),
|
||||
video_path=video,
|
||||
fps=2.0,
|
||||
)
|
||||
)
|
||||
assert sent == []
|
||||
@@ -167,7 +167,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
EnvironmentVariableCategory.PUBLIC_OMNI: 29,
|
||||
EnvironmentVariableCategory.INHERITED_VLLM: 20,
|
||||
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 27,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 57,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 59,
|
||||
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 21,
|
||||
EnvironmentVariableCategory.INTERNAL: 2,
|
||||
}
|
||||
@@ -181,7 +181,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
ModelEnvironmentVariableDisposition.PROMOTE: 31,
|
||||
ModelEnvironmentVariableDisposition.REQUEST_SCOPE: 5,
|
||||
ModelEnvironmentVariableDisposition.EXTERNAL: 0,
|
||||
ModelEnvironmentVariableDisposition.INTERNALIZE: 14,
|
||||
ModelEnvironmentVariableDisposition.INTERNALIZE: 16,
|
||||
ModelEnvironmentVariableDisposition.DEPRECATE_REMOVE: 7,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,725 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Public duplex hook: resumable defaults True; ephemeral ids when False."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexStageRequestContext,
|
||||
DuplexStageSubmission,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_submission_resumable_default_preserves_minicpm() -> None:
|
||||
ctx = DuplexStageRequestContext(
|
||||
request_id="r",
|
||||
session_id="s",
|
||||
fence=DuplexFence("s"),
|
||||
stage_id=0,
|
||||
final_stage_id=2,
|
||||
config_generation=0,
|
||||
sampling_params=(SamplingParams(max_tokens=1),),
|
||||
)
|
||||
submission = DuplexStageSubmission(
|
||||
context=ctx,
|
||||
prompt={"prompt_token_ids": [1, 2]},
|
||||
already_submitted=False,
|
||||
)
|
||||
assert submission.resumable is True
|
||||
|
||||
|
||||
def test_stage_request_id_respects_resumable_flag() -> None:
|
||||
fence = DuplexFence("sess", epoch=3, turn_id=9)
|
||||
resumable_id = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=True)
|
||||
ephemeral_id = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=False)
|
||||
assert ephemeral_id == duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert resumable_id != ephemeral_id
|
||||
assert ephemeral_id.endswith("stage0-turn9")
|
||||
from vllm_omni.engine.duplex.contracts import duplex_turn_id_from_request_id
|
||||
|
||||
assert duplex_turn_id_from_request_id(ephemeral_id) == 9
|
||||
assert duplex_turn_id_from_request_id(resumable_id) is None
|
||||
|
||||
|
||||
def test_capabilities_expose_concurrent_turn_requests_default_false() -> None:
|
||||
caps = DuplexCapabilities()
|
||||
assert caps.supports_concurrent_turn_requests is False
|
||||
assert caps.allows_video_without_audio() is False
|
||||
assert caps.required_input_modalities == frozenset({"audio"})
|
||||
assert caps.optional_input_modalities == frozenset({"video"})
|
||||
assert caps.supports_core_resumable_request is False
|
||||
payload = caps.as_dict()
|
||||
assert payload["supports_concurrent_turn_requests"] is False
|
||||
assert payload["required_input_modalities"] == ["audio"]
|
||||
assert payload["optional_input_modalities"] == ["video"]
|
||||
|
||||
|
||||
def test_next_commit_allowed_soft_opens_on_r4_release() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.session import helpers
|
||||
|
||||
caps = DuplexCapabilities(supports_concurrent_turn_requests=True)
|
||||
session = SimpleNamespace(active_response_id="resp", capabilities=caps)
|
||||
tasks = SimpleNamespace(
|
||||
active_response_task=None,
|
||||
has_response_bound_append_tasks=lambda: False,
|
||||
)
|
||||
# Monkeypatch assistant_playback_active via response_in_progress path: active_response_id set.
|
||||
assert helpers.response_in_progress(session, tasks) is True
|
||||
assert helpers.next_commit_allowed(session, tasks, concurrent_turn_requests_released=False) is False
|
||||
assert helpers.next_commit_allowed(session, tasks, concurrent_turn_requests_released=True) is True
|
||||
|
||||
caps_off = DuplexCapabilities(supports_concurrent_turn_requests=False)
|
||||
session_off = SimpleNamespace(active_response_id="resp", capabilities=caps_off)
|
||||
assert helpers.next_commit_allowed(session_off, tasks, concurrent_turn_requests_released=True) is False
|
||||
|
||||
|
||||
def test_active_response_accepts_own_turn_when_concurrent_turn_requests() -> None:
|
||||
"""Approach A: each response owns its turn; draining TTS uses request→response map."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=3)
|
||||
assert session.active_response_accepts_model_turn(3)
|
||||
assert not session.active_response_accepts_model_turn(4)
|
||||
assert not session.active_response_accepts_model_turn(2)
|
||||
session.bind_draining_request("req-old", "resp-old")
|
||||
assert session.response_id_for_request("req-old") == "resp-old"
|
||||
assert session.is_draining_request("req-old")
|
||||
|
||||
# Ending the active response must not wipe older draining bindings.
|
||||
session.bind_draining_request("req-newer-tts", session.active_response_id or "resp-active")
|
||||
ended = session.active_response_id
|
||||
session.end_response(commit_text=False)
|
||||
assert session.is_draining_request("req-old")
|
||||
assert session.response_id_for_request("req-old") == "resp-old"
|
||||
assert not session.is_draining_request("req-newer-tts")
|
||||
session.clear_draining_for_response("resp-old")
|
||||
assert not session.is_draining_request("req-old")
|
||||
del ended
|
||||
|
||||
strict = DuplexEngineSession(
|
||||
session_id="s2",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=False),
|
||||
)
|
||||
strict.begin_response(turn_id=3)
|
||||
assert strict.active_response_accepts_model_turn(3)
|
||||
assert not strict.active_response_accepts_model_turn(4)
|
||||
|
||||
|
||||
def test_draining_request_exempt_from_completed_turn_filter() -> None:
|
||||
"""Draining ownership must win over the model_turn_id < turn_id late-audio guard."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-drain",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-tts", r1)
|
||||
# Overlapping R2 becomes active, then finishes — must not wipe R1 draining.
|
||||
session.begin_response(turn_id=2)
|
||||
session.end_response(commit_text=False)
|
||||
session.turn_id = 2
|
||||
assert session.active_response_id is None
|
||||
assert session.is_draining_request("req-r1-tts")
|
||||
assert session.response_id_for_request("req-r1-tts") == r1
|
||||
draining_response_id = session.response_id_for_request("req-r1-tts")
|
||||
model_turn_id = 1
|
||||
drop = (
|
||||
draining_response_id is None
|
||||
and session.active_response_id is None
|
||||
and model_turn_id is not None
|
||||
and model_turn_id < session.turn_id
|
||||
)
|
||||
assert drop is False
|
||||
|
||||
|
||||
def test_ephemeral_turn_id_parser_accepts_stage_turn_ids() -> None:
|
||||
from vllm_omni.engine.duplex.contracts import duplex_turn_id_from_request_id
|
||||
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0-turn12") == 12
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage2-turn3") == 3
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0_t9") is None
|
||||
assert duplex_turn_id_from_request_id("duplex-s.x.e.0.r.stage0") is None
|
||||
|
||||
|
||||
def test_same_turn_request_ids_skip_other_turns_and_epochs() -> None:
|
||||
from vllm_omni.engine.duplex.contracts import duplex_same_turn_request_ids
|
||||
|
||||
stage3 = "duplex-s.x.e.0.r.stage3-turn4"
|
||||
found = duplex_same_turn_request_ids(
|
||||
stage3,
|
||||
[
|
||||
"duplex-s.x.e.0.r.stage0-turn4",
|
||||
"duplex-s.x.e.0.r.stage1-turn4",
|
||||
"duplex-s.x.e.0.r.stage2-turn4",
|
||||
stage3,
|
||||
"duplex-s.x.e.0.r.stage2-turn5",
|
||||
"duplex-s.x.e.1.r.stage0-turn4",
|
||||
],
|
||||
)
|
||||
assert found == [
|
||||
"duplex-s.x.e.0.r.stage0-turn4",
|
||||
"duplex-s.x.e.0.r.stage1-turn4",
|
||||
"duplex-s.x.e.0.r.stage2-turn4",
|
||||
]
|
||||
from vllm_omni.engine.duplex.contracts import duplex_session_id_from_request_id
|
||||
|
||||
fence_session = "sess id"
|
||||
import base64
|
||||
|
||||
encoded = base64.urlsafe_b64encode(fence_session.encode()).decode("ascii").rstrip("=")
|
||||
assert duplex_session_id_from_request_id(f"duplex-s.{encoded}.e.0.r.stage1-turn2") == fence_session
|
||||
assert duplex_session_id_from_request_id("not-a-request") is None
|
||||
|
||||
|
||||
def test_stale_keys_skip_already_draining_request_ids() -> None:
|
||||
"""Rebinding must not move an older draining Stage2/3 id onto the newer response."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-stale",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-talker", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
# Simulate the concurrent-turn rebind loop: already-draining ids keep R1.
|
||||
for rid in ("req-r1-talker", "req-r2-talker"):
|
||||
if session.is_draining_request(rid):
|
||||
continue
|
||||
session.bind_draining_request(rid, r2)
|
||||
assert session.response_id_for_request("req-r1-talker") == r1
|
||||
assert session.response_id_for_request("req-r2-talker") == r2
|
||||
|
||||
|
||||
def test_end_response_clears_only_own_draining_entries() -> None:
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-end",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
session.bind_draining_request("req-r1", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
session.bind_draining_request("req-r2", r2)
|
||||
session.end_response(commit_text=False)
|
||||
assert session.is_draining_request("req-r1")
|
||||
assert session.response_id_for_request("req-r1") == r1
|
||||
assert not session.is_draining_request("req-r2")
|
||||
|
||||
|
||||
def test_on_stage_failure_resolves_draining_response_before_active() -> None:
|
||||
"""Mirrors runner.on_stage_failure: draining request_id owns the failed done."""
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-fail",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.bind_draining_request("req-r1-talker", r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
|
||||
request_id = "req-r1-talker"
|
||||
draining_response_id = (
|
||||
session.response_id_for_request(request_id) if session.is_draining_request(request_id) else None
|
||||
)
|
||||
response_id = draining_response_id or session.active_response_id
|
||||
assert response_id == r1
|
||||
assert response_id != r2
|
||||
session.clear_draining_for_response(r1)
|
||||
assert not session.is_draining_request(request_id)
|
||||
assert session.active_response_id == r2
|
||||
|
||||
|
||||
def test_concurrent_turn_requests_released_resets_when_new_stage0_binds() -> None:
|
||||
"""After R4 release, a new ephemeral Stage0 bind must clear the gate flag."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
run = SimpleNamespace(concurrent_turn_requests_released=True)
|
||||
# Simulate the concurrent-turn rebind arm in model_channel._append_via_data_plane.
|
||||
concurrent_turn = True
|
||||
if concurrent_turn:
|
||||
run.concurrent_turn_requests_released = False
|
||||
assert run.concurrent_turn_requests_released is False
|
||||
|
||||
|
||||
def test_draining_stage_ids_come_from_the_plugin() -> None:
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
channel = ModelChannel.__new__(ModelChannel)
|
||||
channel._ctx = SimpleNamespace(
|
||||
plugin=SimpleNamespace(draining_stage_ids=lambda *, stage_count: {stage_count - 1}),
|
||||
stage_port=SimpleNamespace(stage_count=5),
|
||||
)
|
||||
assert channel._draining_stage_ids() == frozenset({4})
|
||||
|
||||
channel._ctx.plugin = SimpleNamespace()
|
||||
assert channel._draining_stage_ids() == frozenset()
|
||||
|
||||
|
||||
def test_draining_empty_eos_completes_owning_response_before_shortcut() -> None:
|
||||
"""R2 finishing first must not swallow R1's empty Stage3 EOS."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-empty-eos",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
r1_request = "duplex-s.x.e.0.r.stage3-turn1"
|
||||
still_running = "duplex-s.x.e.0.r.stage1-turn2"
|
||||
session.bind_draining_request(r1_request, r1)
|
||||
session.begin_response(turn_id=2)
|
||||
session.end_response(commit_text=False)
|
||||
session.turn_id = 2
|
||||
assert session.active_response_id is None
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
del request_id
|
||||
return False
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
def __init__(self) -> None:
|
||||
self.cleanups: list[list[str]] = []
|
||||
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del abort
|
||||
self.cleanups.append(list(request_ids))
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
port = _Port()
|
||||
out = _Out()
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=port,
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: None),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": r1_request,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"text": "",
|
||||
"stage_role": "tts",
|
||||
}
|
||||
)
|
||||
)
|
||||
done = [event for event in out.events if event.get("type") == "response.done"]
|
||||
assert done and done[-1].get("response_id") == r1
|
||||
assert port.cleanups == [[r1_request]]
|
||||
assert all(still_running not in ids for ids in port.cleanups)
|
||||
assert not session.is_draining_request(r1_request)
|
||||
|
||||
|
||||
def test_draining_completion_drops_finished_response_books_only() -> None:
|
||||
"""R1 drain finish drops R1 books and leaves the live R2 snapshot."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-drain-books",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
r1 = session.active_response_id
|
||||
assert r1 is not None
|
||||
session.append_assistant_text("from-r1")
|
||||
session.snapshot_active_response_for_drain()
|
||||
r1_request = "duplex-s.x.e.0.r.stage3-turn1"
|
||||
session.bind_draining_request(r1_request, r1)
|
||||
session.begin_response(turn_id=2)
|
||||
r2 = session.active_response_id
|
||||
assert r2 is not None and r2 != r1
|
||||
session.append_assistant_text("from-r2")
|
||||
session.snapshot_active_response_for_drain()
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
del request_id
|
||||
return False
|
||||
|
||||
def close_stream(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del request_ids, abort
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
out = _Out()
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=_Port(),
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: None),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": r1_request,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"text": "",
|
||||
"stage_role": "tts",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert r1 not in session._conversation.assistant_response_snapshots
|
||||
assert r1 not in session._playback.by_response
|
||||
assert f"item_{r1}" not in session._conversation.history_item_placeholders
|
||||
assert r2 in session._conversation.assistant_response_snapshots
|
||||
assert session.active_response_id == r2
|
||||
done = [event for event in out.events if event.get("type") == "response.done"]
|
||||
assert done and done[-1].get("response_id") == r1
|
||||
|
||||
|
||||
def test_stale_continue_does_not_close_the_new_response() -> None:
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-stale-continue",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"], extra_body={"auto_response": True}),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=2)
|
||||
live = session.active_response_id
|
||||
session.epoch = 1
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
out = _Out()
|
||||
cleared: list[bool] = []
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=SimpleNamespace()),
|
||||
stage_port=SimpleNamespace(),
|
||||
model_state=SimpleNamespace(clear_continuation=lambda: cleared.append(True)),
|
||||
services=SimpleNamespace(spawn=lambda *_a, **_k: None),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=0))
|
||||
assert session.active_response_id == live
|
||||
assert out.events == []
|
||||
assert cleared == []
|
||||
|
||||
session.bind_draining_request("duplex-s.x.e.1.r.stage3-turn2", live or "")
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=1))
|
||||
assert session.active_response_id == live
|
||||
assert out.events == []
|
||||
|
||||
session.clear_draining_requests()
|
||||
asyncio.run(channel.maybe_continue_response(expected_epoch=1))
|
||||
assert session.active_response_id is None
|
||||
assert [event.get("type") for event in out.events] == ["response.done"]
|
||||
assert out.events[0].get("response_id") == live
|
||||
|
||||
|
||||
def test_silent_listen_with_continuation_releases_ephemeral_request() -> None:
|
||||
import asyncio
|
||||
from collections.abc import Coroutine
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-silent-continue",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
session.begin_response(turn_id=1)
|
||||
response_id = session.active_response_id
|
||||
request_id = "duplex-s.x.e.0.r.stage1-turn1"
|
||||
session.bind_request(request_id)
|
||||
|
||||
class _Plane:
|
||||
def __init__(self) -> None:
|
||||
self.terminal: list[str] = []
|
||||
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
return request_id in self.terminal
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
self.terminal.append(request_id)
|
||||
|
||||
class _Port:
|
||||
def __init__(self) -> None:
|
||||
self.cleanups: list[list[str]] = []
|
||||
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del abort
|
||||
self.cleanups.append(list(request_ids))
|
||||
|
||||
class _Out:
|
||||
def __init__(self) -> None:
|
||||
self.events: list[dict[str, object]] = []
|
||||
|
||||
def auto_responds(self) -> bool:
|
||||
return False
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
self.events.append(payload)
|
||||
|
||||
port = _Port()
|
||||
out = _Out()
|
||||
spawned: list[Coroutine[Any, Any, None]] = []
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _schedule(*_args: object, **_kwargs: object) -> bool:
|
||||
return False
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=port,
|
||||
model_state=SimpleNamespace(
|
||||
continuation_owner_id=None, continuation_units=0, clear_continuation=lambda: None
|
||||
),
|
||||
services=SimpleNamespace(spawn=lambda coro, **_k: spawned.append(coro)),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
out,
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_schedule,
|
||||
abort_request=_noop,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": request_id,
|
||||
"is_listen": True,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"reason": "model_listen",
|
||||
}
|
||||
)
|
||||
)
|
||||
assert port.cleanups == [[request_id]]
|
||||
assert session.active_request_id is None
|
||||
assert spawned, "silent listen with unused continuation must schedule maybe_continue"
|
||||
asyncio.run(spawned[0])
|
||||
assert port.cleanups == [[request_id]]
|
||||
assert session.active_response_id is None
|
||||
assert [event.get("type") for event in out.events] == ["response.listen", "response.done"]
|
||||
assert out.events[0].get("response_id") == response_id
|
||||
assert out.events[1].get("response_id") == response_id
|
||||
|
||||
|
||||
def test_silent_listen_aborts_data_plane_request_with_full_id() -> None:
|
||||
"""abort_data_plane_request must pass [request_id], not a bare str."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities, DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexEngineSession
|
||||
from vllm_omni.engine.duplex.session.model_channel import ModelChannel
|
||||
|
||||
session = DuplexEngineSession(
|
||||
session_id="s-silent-abort",
|
||||
config=DuplexSessionConfig(model="m", modalities=["text", "audio"]),
|
||||
capabilities=DuplexCapabilities(supports_concurrent_turn_requests=True, supports_core_resumable_request=False),
|
||||
)
|
||||
request_id = "duplex-s.x.e.0.r.stage0-turn7"
|
||||
session.bind_request(request_id)
|
||||
aborts: list[list[str]] = []
|
||||
|
||||
class _Plane:
|
||||
def is_terminal(self, request_id: str | None) -> bool:
|
||||
return False
|
||||
|
||||
def mark_terminal(self, request_id: str) -> None:
|
||||
del request_id
|
||||
|
||||
class _Port:
|
||||
async def cleanup(self, request_ids: list[str], *, abort: bool = False) -> None:
|
||||
del request_ids, abort
|
||||
|
||||
class _Out:
|
||||
def auto_responds(self) -> bool:
|
||||
return True
|
||||
|
||||
def emit(self, payload: dict[str, object]) -> None:
|
||||
del payload
|
||||
|
||||
async def _noop(*_args: object, **_kwargs: object) -> None:
|
||||
return None
|
||||
|
||||
async def _abort(request_ids: list[str], *, notify: bool = False) -> None:
|
||||
del notify
|
||||
aborts.append(list(request_ids))
|
||||
|
||||
channel = ModelChannel(
|
||||
SimpleNamespace(
|
||||
session=session,
|
||||
plugin=SimpleNamespace(data_plane=_Plane()),
|
||||
stage_port=_Port(),
|
||||
model_state=SimpleNamespace(
|
||||
continuation_owner_id=None, continuation_units=0, clear_continuation=lambda: None
|
||||
),
|
||||
services=SimpleNamespace(spawn=lambda coro, **_k: None),
|
||||
run=SimpleNamespace(closing=False),
|
||||
),
|
||||
_Out(),
|
||||
close_from_runtime=_noop,
|
||||
schedule_silence_continuation=_noop,
|
||||
abort_request=_abort,
|
||||
)
|
||||
asyncio.run(
|
||||
channel._send_one_model_output_event(
|
||||
{
|
||||
"data_plane_request_id": request_id,
|
||||
"is_listen": True,
|
||||
"end_of_turn": True,
|
||||
"model_turn_id": 1,
|
||||
"reason": "model_listen",
|
||||
"abort_data_plane_request": True,
|
||||
}
|
||||
)
|
||||
)
|
||||
assert aborts == [[request_id]]
|
||||
assert all(len(item) > 1 for batch in aborts for item in batch), "must not split request id into chars"
|
||||
@@ -242,6 +242,19 @@ def test_history_commit_with_ack_only_policy_defers_unacknowledged_text():
|
||||
assert f"item_{response_id}" in session.pending_history_item_ids
|
||||
|
||||
|
||||
def test_history_commit_with_ack_only_policy_keeps_only_acknowledged_prefix():
|
||||
session = _session(config=DuplexSessionConfig(playback_commit_policy="ack_only"))
|
||||
session.begin_response()
|
||||
session.append_assistant_text("hello world")
|
||||
session.mark_audio_sent(duration_ms=1_000, text_chars=6)
|
||||
session.mark_audio_sent(duration_ms=2_000, text_chars=11)
|
||||
session.acknowledge_playback(played_ms=1_000, committed_ms=1_000)
|
||||
|
||||
committed = session.end_response(commit_text=True)
|
||||
|
||||
assert committed == {"role": "assistant", "content": "hello"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("audio_complete", [False, True])
|
||||
def test_unaligned_response_keeps_empty_turn_before_later_user_input(audio_complete):
|
||||
session = _session(config=DuplexSessionConfig(playback_commit_policy="ack_only"))
|
||||
@@ -469,6 +482,36 @@ def test_cancel_fence_releases_stage_requests_and_advances_identity():
|
||||
session.cancel_fence(DuplexFence("sid-other", epoch=1, turn_id=0), DuplexFence("sid-cancel", epoch=2))
|
||||
|
||||
|
||||
def test_request_resource_keys_are_stage_id_and_request_id():
|
||||
session = _session("sid-keys")
|
||||
session.bind_stage_request(0, "req-a", fence=session.fence)
|
||||
session.bind_stage_request(1, "req-b", fence=session.fence)
|
||||
session.bind_stage_request(2, "req-tts", fence=session.fence)
|
||||
stale_keys = list(session.request_resources.keys())
|
||||
stale_ids = list(dict.fromkeys(rid for _, rid in stale_keys))
|
||||
assert stale_ids == ["req-a", "req-b", "req-tts"]
|
||||
for sid, rid in stale_keys:
|
||||
if sid < 2:
|
||||
session.request_resources.pop((sid, rid), None)
|
||||
assert session.resource_request_ids() == ["req-tts"]
|
||||
with pytest.raises(TypeError, match="unhashable"):
|
||||
dict.fromkeys(rid for _, rid in session.request_resources.items())
|
||||
|
||||
|
||||
def test_release_resources_for_request_ids_keeps_other_ids_on_the_same_fence():
|
||||
session = _session("sid-drain-release")
|
||||
fence = session.fence
|
||||
session.bind_stage_request(2, "drain", fence=fence)
|
||||
session.bind_stage_request(3, "drain", fence=fence)
|
||||
session.bind_stage_request(0, "live", fence=fence)
|
||||
|
||||
released = session.release_resources_for_request_ids(["drain"])
|
||||
|
||||
assert released == ["drain"]
|
||||
assert session.resource_request_ids() == ["live"]
|
||||
assert session.release_resources_for_request_ids([]) == []
|
||||
|
||||
|
||||
# ---- public view ----
|
||||
|
||||
|
||||
@@ -688,3 +731,65 @@ def test_minicpmo_native_capabilities_do_not_overclaim_single_session_deployment
|
||||
|
||||
assert caps["supports_multi_session"] is False
|
||||
assert caps["supports_multi_session_same_replica"] is False
|
||||
|
||||
|
||||
def test_draining_response_stays_ack_admissible_after_next_begin_response() -> None:
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent
|
||||
from vllm_omni.engine.duplex.session.playback_ledger import apply_playback_ack
|
||||
|
||||
session = _session()
|
||||
first = session.begin_response(turn_id=1)
|
||||
session.append_assistant_text("hello")
|
||||
session.mark_audio_sent(400, text_chars=5)
|
||||
session.snapshot_active_response_for_drain()
|
||||
second = session.begin_response(turn_id=2)
|
||||
assert second != first
|
||||
assert session.playback.sent_ms == 0
|
||||
events = apply_playback_ack(
|
||||
session,
|
||||
{
|
||||
"type": "playback.ack",
|
||||
"response_id": first,
|
||||
"item_id": f"item_{first}",
|
||||
"played_ms": 100,
|
||||
"committed_ms": 100,
|
||||
},
|
||||
)
|
||||
assert not any(isinstance(event, ErrorEvent) and event.code == "playback_item_not_found" for event in events)
|
||||
session.mark_audio_sent(900, text_chars=5, response_id=first)
|
||||
assert session.playback_for_response(first).sent_ms == 900
|
||||
assert session.playback.sent_ms == 0
|
||||
|
||||
|
||||
def test_finished_drain_keeps_sent_audio_ackable() -> None:
|
||||
from vllm_omni.engine.duplex.events import ErrorEvent
|
||||
from vllm_omni.engine.duplex.session.playback_ledger import apply_playback_ack
|
||||
|
||||
session = _session()
|
||||
first = session.begin_response(turn_id=1)
|
||||
session.append_assistant_text("hello")
|
||||
session.mark_audio_sent(400, text_chars=5)
|
||||
session.snapshot_active_response_for_drain()
|
||||
second = session.begin_response(turn_id=2)
|
||||
session.release_finished_drain_response(first)
|
||||
assert first in session._conversation.assistant_response_snapshots
|
||||
assert f"item_{first}" in session._conversation.history_item_placeholders
|
||||
events = apply_playback_ack(
|
||||
session,
|
||||
{
|
||||
"type": "playback.ack",
|
||||
"response_id": first,
|
||||
"item_id": f"item_{first}",
|
||||
"played_ms": 400,
|
||||
"committed_ms": 400,
|
||||
},
|
||||
)
|
||||
assert not any(isinstance(event, ErrorEvent) for event in events)
|
||||
assert session.active_response_id == second
|
||||
|
||||
silent = session.begin_response(turn_id=3)
|
||||
session.snapshot_active_response_for_drain()
|
||||
session.begin_response(turn_id=4)
|
||||
session.release_finished_drain_response(silent)
|
||||
assert silent not in session._conversation.assistant_response_snapshots
|
||||
assert f"item_{silent}" not in session._conversation.history_item_placeholders
|
||||
@@ -0,0 +1,49 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.duplex.realtime_events import (
|
||||
RealtimeProjectionState,
|
||||
project_internal_event,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_input_transcribed_is_a_user_transcript_event() -> None:
|
||||
events = project_internal_event(
|
||||
RealtimeProjectionState(session_id="s"),
|
||||
{"type": "input.transcribed", "transcript": " 你好 "},
|
||||
)
|
||||
assert len(events) == 1
|
||||
assert events[0].wire_type == "conversation.item.input_audio_transcription.completed"
|
||||
assert events[0].transcript == "你好"
|
||||
|
||||
|
||||
def test_input_transcribed_updates_the_committed_item() -> None:
|
||||
state = RealtimeProjectionState(session_id="s")
|
||||
project_internal_event(
|
||||
state,
|
||||
{
|
||||
"type": "input.committed",
|
||||
"realtime_item_id": "item_user_1",
|
||||
"is_speech": True,
|
||||
"message": {"role": "user"},
|
||||
},
|
||||
)
|
||||
events = project_internal_event(
|
||||
state,
|
||||
{"type": "input.transcribed", "transcript": "你好", "realtime_item_id": "item_user_1"},
|
||||
)
|
||||
assert events[0].item_id == "item_user_1"
|
||||
item = state.conversation_items["item_user_1"]
|
||||
assert item["content"][0]["transcript"] == "你好"
|
||||
|
||||
|
||||
def test_blank_input_transcribed_emits_nothing() -> None:
|
||||
events = project_internal_event(
|
||||
RealtimeProjectionState(session_id="s"),
|
||||
{"type": "input.transcribed", "transcript": " "},
|
||||
)
|
||||
assert events == []
|
||||
@@ -79,6 +79,39 @@ def test_an_explicit_client_overlap_action_requests_barge_in() -> None:
|
||||
assert decision["reason"] == "client_overlap_action"
|
||||
|
||||
|
||||
def test_turn_mode_keeps_silent_vision_follow_during_overlap() -> None:
|
||||
"""Vision-follow is is_speech=False + a frame; must not drop while TTS plays."""
|
||||
session = _session()
|
||||
session.capabilities = type(session.capabilities)(
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "video_frames": ["frame"], "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "listen"
|
||||
assert decision["reason"] == "vision_follow"
|
||||
assert decision["buffer_audio"] is True
|
||||
assert decision["defer_runtime_append"] is False
|
||||
assert decision["force_listen"] is False
|
||||
|
||||
|
||||
def test_turn_mode_drops_silent_vision_without_capability() -> None:
|
||||
session = _session()
|
||||
assert session.capabilities.allows_video_without_audio() is False
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "video_frames": ["frame"], "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "drop"
|
||||
assert decision["reason"] == "silence_or_noise"
|
||||
|
||||
|
||||
def test_turn_mode_still_drops_silent_overlap_without_vision() -> None:
|
||||
session = _session()
|
||||
payload = {"format": "pcm16", "audio": _pcm16(0.0), "is_speech": False}
|
||||
decision = overlap_policy.decide(session, {"is_speech": False}, payload, auto_responds=False)
|
||||
assert decision["action"] == "drop"
|
||||
assert decision["reason"] == "silence_or_noise"
|
||||
|
||||
|
||||
def test_barge_in_is_deferred_when_the_session_cannot_support_it() -> None:
|
||||
session = _session()
|
||||
session.capabilities = type(session.capabilities)(supports_barge_in=False)
|
||||
|
||||
@@ -196,7 +196,11 @@ class FakePlugin(DuplexModelPlugin):
|
||||
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
|
||||
del max_sessions
|
||||
return DuplexCapabilities(supports_input_append=True, supports_core_resumable_request=True)
|
||||
# Resident Stage0 ids (MiniCPM-shaped); AURA opts out via supports_core_resumable_request=False.
|
||||
return DuplexCapabilities(
|
||||
supports_input_append=True,
|
||||
supports_core_resumable_request=True,
|
||||
)
|
||||
|
||||
def validate_client_extra_body(self, extra_body: object) -> None:
|
||||
pass
|
||||
@@ -409,7 +413,8 @@ async def test_open_answers_with_capabilities_and_emits_session_created() -> Non
|
||||
assert result.session_id == "sid-open"
|
||||
assert result.lease_generation == 0
|
||||
assert result.capabilities == DuplexCapabilities(
|
||||
supports_input_append=True, supports_core_resumable_request=True
|
||||
supports_input_append=True,
|
||||
supports_core_resumable_request=True,
|
||||
)
|
||||
assert result.public_session is not None
|
||||
assert result.public_session["id"] == "sid-open"
|
||||
@@ -1028,6 +1033,40 @@ async def test_append_bytes_are_reserved_at_admission_until_the_runner_dequeues(
|
||||
gate.set()
|
||||
|
||||
|
||||
async def test_append_admission_counts_audio_and_video_frame_bytes() -> None:
|
||||
"""Manager reserves len(audio)+Σlen(frame); video bytes count toward the same limit."""
|
||||
async with Harness.create(max_sessions=1, max_pending_input_bytes_per_session=20) as harness:
|
||||
await harness.open("sid-av")
|
||||
harness.events()
|
||||
session = harness.session("sid-av")
|
||||
runner = harness.manager.runners["sid-av"]
|
||||
gate = asyncio.Event()
|
||||
runner._mailbox.put_nowait(_Internal("wait", {"gate": gate}))
|
||||
runner._on_internal = lambda item: gate.wait() # type: ignore[method-assign]
|
||||
await asyncio.sleep(0)
|
||||
|
||||
# Default caps require audio; attach video to a non-empty audio unit.
|
||||
frame_a = "aaaa"
|
||||
frame_b = "bbbbbb"
|
||||
audio = b"1234"
|
||||
expected = len(audio) + len(frame_a) + len(frame_b)
|
||||
harness.command(
|
||||
"sid-av",
|
||||
AppendAudio(audio=audio, video_frames=(frame_a, frame_b), event_id="evt-av"),
|
||||
)
|
||||
assert session.pending_input_bytes == expected
|
||||
# Second append that would exceed the limit is backpressured.
|
||||
harness.command(
|
||||
"sid-av",
|
||||
AppendAudio(audio=b"x" * 10, video_frames=("yyyyyyyyyy",), event_id="evt-over"),
|
||||
)
|
||||
errors = [event for event in harness.events("sid-av") if isinstance(event, ErrorEvent)]
|
||||
assert [error.code for error in errors] == ["input_backpressure"]
|
||||
assert errors[0].related_event_id == "evt-over"
|
||||
assert session.pending_input_bytes == expected
|
||||
gate.set()
|
||||
|
||||
|
||||
async def test_expired_session_retains_the_admission_slot_until_cleanup_succeeds() -> None:
|
||||
async with Harness.create(max_sessions=1, idle_ttl_s=1.0) as harness:
|
||||
await harness.open("sid-expired")
|
||||
|
||||
@@ -180,7 +180,10 @@ class Harness:
|
||||
segment_token_ids=tuple(segment_token_ids),
|
||||
segment_output_metadata=dict(segment_output_metadata or {}),
|
||||
)
|
||||
return self.runner.on_stage_output(stage_id, output, metrics, request_id=output.request_id, context=context)
|
||||
request_id = getattr(output, "request_id", None)
|
||||
if not isinstance(request_id, str):
|
||||
raise AssertionError("stage output is missing request_id")
|
||||
return self.runner.on_stage_output(stage_id, output, metrics, request_id=request_id, context=context)
|
||||
|
||||
async def deliver_and_settle(self, output: object, **kwargs: Any) -> list[DuplexEvent]:
|
||||
self.deliver(output, **kwargs)
|
||||
@@ -520,6 +523,28 @@ async def test_commit_without_audio_is_rejected() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_silent_commit_acks_without_opening_response() -> None:
|
||||
"""#3: empty is_speech=False commit keeps the silent-ack pair, even auto-respond."""
|
||||
h = await open_harness(auto_response=True)
|
||||
try:
|
||||
# resolve_commit only admits empty silent commits after non-speech was seen.
|
||||
projector = h.runner._require_projector()
|
||||
projector.input_audio_buffer_had_non_speech = True
|
||||
events = await h.run(commands.Commit())
|
||||
assert "error" not in types(events), types(events)
|
||||
assert "input_audio_buffer.committed" in types(events), types(events)
|
||||
assert "response.listen" in types(events), types(events)
|
||||
listen = next(event for event in events if event.type == "response.listen")
|
||||
assert listen.details["reason"] == "silence_or_noise"
|
||||
committed = next(event for event in events if event.type == "input_audio_buffer.committed")
|
||||
assert committed.details.get("empty") is True
|
||||
assert committed.details.get("no_response") is True
|
||||
assert h.port.submissions == []
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_commit_projects_the_user_item_and_does_not_resubmit_consumed_audio() -> None:
|
||||
h = await open_harness()
|
||||
@@ -674,6 +699,45 @@ async def test_stale_epoch_output_is_dropped_after_barge_in() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
async def test_barge_in_aborts_draining_tts_as_well_as_the_active_request() -> None:
|
||||
h = await open_harness()
|
||||
try:
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="he"))
|
||||
h.session.bind_draining_request("duplex-drain-tts", "resp-old")
|
||||
# Draining TTS sits on an older turn fence. cancel_fence only drops
|
||||
# the fence being cancelled, so these bindings must be popped by id.
|
||||
from vllm_omni.engine.duplex.contracts import DuplexFence
|
||||
from vllm_omni.engine.duplex.session.engine_session import DuplexRequestResource
|
||||
|
||||
older = DuplexFence(h.session.session_id, epoch=h.session.epoch, turn_id=h.session.turn_id + 5)
|
||||
h.session.request_resources[(2, "duplex-drain-tts")] = DuplexRequestResource(
|
||||
stage_id=2, request_id="duplex-drain-tts", fence=older, submitted=True
|
||||
)
|
||||
h.session.request_resources[(3, "duplex-drain-tts")] = DuplexRequestResource(
|
||||
stage_id=3, request_id="duplex-drain-tts", fence=older, submitted=True
|
||||
)
|
||||
h.session.request_resources[(1, "still-live")] = DuplexRequestResource(
|
||||
stage_id=1, request_id="still-live", fence=older, submitted=True
|
||||
)
|
||||
events = await h.run(commands.BargeIn())
|
||||
assert h.port.aborts == [[request_id, "duplex-drain-tts"]]
|
||||
assert not h.session.is_draining_request("duplex-drain-tts")
|
||||
done_ids = [
|
||||
event.response["id"]
|
||||
for event in events
|
||||
if getattr(event, "wire_type", "") == "response.done" and isinstance(getattr(event, "response", None), dict)
|
||||
]
|
||||
assert "resp-old" in done_ids
|
||||
assert (2, "duplex-drain-tts") not in h.session.request_resources
|
||||
assert (3, "duplex-drain-tts") not in h.session.request_resources
|
||||
assert (0, request_id) not in h.session.request_resources
|
||||
assert (1, "still-live") in h.session.request_resources
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_response_without_active_response_is_rejected() -> None:
|
||||
h = await open_harness()
|
||||
@@ -778,6 +842,46 @@ async def test_listen_decision_on_a_resumable_request_closes_the_bounded_respons
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_direct_response_listen_still_emits_response_done_after_continuation_clear() -> None:
|
||||
"""AURA-like silent DIRECT_RESPONSE: after continuation budget is spent, emit response.done.
|
||||
|
||||
Non-resumable turn-commit still closes the active response on a listen/direct
|
||||
decision so the client is not left without a terminal event.
|
||||
"""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness()
|
||||
try:
|
||||
h.session.capabilities = replace(h.session.capabilities, supports_core_resumable_request=False)
|
||||
await h.run(append_audio())
|
||||
assert h.port.submissions, "ephemeral Stage0 must submit"
|
||||
request_id = h.port.submissions[-1].context.request_id
|
||||
assert "-turn" in request_id
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="ok"))
|
||||
response_id = h.session.active_response_id
|
||||
assert response_id is not None
|
||||
model_state = h.runner.model_state
|
||||
model_state.continuation_owner_id = f"response:{response_id}"
|
||||
model_state.continuation_units = h.runner.model._AUTO_RESPONSE_MAX_CONTINUATION_UNITS
|
||||
|
||||
listen = listen_output(request_id)
|
||||
listen.finished = True
|
||||
events = await h.deliver_and_settle(
|
||||
listen,
|
||||
stage_id=0,
|
||||
segment_finished=True,
|
||||
segment_token_ids=[11, 12, LISTEN_TOKEN_ID],
|
||||
segment_output_metadata={"meta.listen_token_id": LISTEN_TOKEN_ID},
|
||||
)
|
||||
assert "response.listen" in types(events)
|
||||
done = find(events, "response.done")
|
||||
assert done.response_id == response_id
|
||||
assert h.session.active_response_id is None
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listen_decision_on_a_resumable_request_keeps_the_turn_going() -> None:
|
||||
"""Same unfinished listen, budget left: it must schedule the next unit.
|
||||
@@ -860,6 +964,38 @@ async def test_stage_failure_fails_the_active_response() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stage_failure_on_draining_request_fails_that_response_only() -> None:
|
||||
"""Overlapped: a draining older request failure must not wipe the active response."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness()
|
||||
try:
|
||||
h.session.capabilities = replace(h.session.capabilities, supports_concurrent_turn_requests=True)
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
await h.deliver_and_settle(tts_output(request_id, samples=24000, text="hello"))
|
||||
r1 = h.session.active_response_id
|
||||
assert r1 is not None
|
||||
draining_req = "req-r1-talker-drain"
|
||||
h.session.bind_draining_request(draining_req, r1)
|
||||
# Open a newer active response while R1 TTS is still draining.
|
||||
r2 = h.session.begin_response(turn_id=(h.session.turn_id or 0) + 1)
|
||||
assert h.session.active_response_id == r2
|
||||
assert r2 != r1
|
||||
|
||||
h.runner.on_stage_failure(2, RuntimeError("drain-boom"), request_id=draining_req)
|
||||
events = await h.settle()
|
||||
assert types(events)[0] == "error"
|
||||
done = find(events, "response.done")
|
||||
assert done.response_id == r1
|
||||
assert done.status == "failed"
|
||||
assert h.session.active_response_id == r2
|
||||
assert not h.session.is_draining_request(draining_req)
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Turn mode (no auto response) #
|
||||
# --------------------------------------------------------------------------- #
|
||||
@@ -877,6 +1013,91 @@ async def test_turn_mode_skips_silent_chunks() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_keeps_silent_chunks_with_video_frames() -> None:
|
||||
"""Engine vision-follow buffers silent+frames; MiniCPM commit stays speech-gated."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness(auto_response=False)
|
||||
try:
|
||||
h.session.capabilities = replace(
|
||||
h.session.capabilities,
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
# Minimal 1x1 JPEG (base64) — wire validation only checks non-empty str.
|
||||
frame = (
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS"
|
||||
"Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ"
|
||||
"CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
|
||||
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAA"
|
||||
"AAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIQAxAAAAGfAP/EABQQ"
|
||||
"AQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAQUCf//EABQRAQAAAAAAAAAAAAAAAAAA"
|
||||
"AAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Bf//E"
|
||||
"ABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEABj8Cf//EABQQAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/2gAIAQEAAT8hf//Z"
|
||||
)
|
||||
cmd = commands.AppendAudio(
|
||||
audio=pcm_f32(160, value=0.0),
|
||||
format="pcm_f32le",
|
||||
sample_rate_hz=16000,
|
||||
is_speech=False,
|
||||
video_frames=(frame,),
|
||||
)
|
||||
events = await h.run(cmd)
|
||||
assert "response.listen" not in types(events)
|
||||
assert h.runner.model_state.audio_buffer.has_pending()
|
||||
events = await h.run(commands.Commit(create_response=True))
|
||||
# MiniCPM prepare_commit is speech-gated (no frames-only Stage0).
|
||||
assert "input_audio_buffer.committed" in types(events), types(events)
|
||||
assert h.port.submissions == []
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_keeps_silent_vision_while_response_in_progress() -> None:
|
||||
"""TTS still playing: vision-follow must buffer, not drop as silence_or_noise."""
|
||||
from dataclasses import replace
|
||||
|
||||
h = await open_harness(auto_response=False)
|
||||
try:
|
||||
h.session.capabilities = replace(
|
||||
h.session.capabilities,
|
||||
required_input_modalities=frozenset({"video"}),
|
||||
optional_input_modalities=frozenset({"audio"}),
|
||||
)
|
||||
h.session._response.active_response_id = "resp-tts"
|
||||
frame = (
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS"
|
||||
"Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJ"
|
||||
"CQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
|
||||
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAA"
|
||||
"AAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAA"
|
||||
"AAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIQAxAAAAGfAP/EABQQ"
|
||||
"AQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Bf//EABQRAQAAAAAAAAAAAAAAAAAA"
|
||||
"AAD/2gAIAQIBAT8Bf//EABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEABj8Cf//E"
|
||||
"ABQQAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQEAAT8hf//Z"
|
||||
)
|
||||
events = await h.run(
|
||||
commands.AppendAudio(
|
||||
audio=pcm_f32(160, value=0.0),
|
||||
format="pcm_f32le",
|
||||
sample_rate_hz=16000,
|
||||
is_speech=False,
|
||||
video_frames=(frame,),
|
||||
)
|
||||
)
|
||||
listen_reasons = [
|
||||
getattr(event, "details", {}) or {} for event in events if getattr(event, "type", None) == "response.listen"
|
||||
]
|
||||
assert all(details.get("reason") != "silence_or_noise" for details in listen_reasons)
|
||||
assert h.runner.model_state.audio_buffer.has_pending()
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_turn_mode_commit_with_response_create_starts_one_response() -> None:
|
||||
h = await open_harness(auto_response=False)
|
||||
@@ -1033,7 +1254,7 @@ async def test_conversation_items_can_be_injected_and_deleted() -> None:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
def _stage_metrics_of(event: object) -> dict[str, dict[str, object]]:
|
||||
def _stage_metrics_of(event: DuplexEvent) -> dict[str, dict[str, object]]:
|
||||
"""Per-stage engine metrics as the client reads them off one wire event."""
|
||||
payload = event.to_realtime()
|
||||
metadata = payload.get("metadata")
|
||||
@@ -1081,6 +1302,40 @@ async def test_stage0_metrics_reach_the_response_even_though_its_output_feeds_tt
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_projected_stage1_metrics_reach_the_spoken_audio_event() -> None:
|
||||
"""Thinker text is projected, but its TTFT/TPOT still have to ride the audio event."""
|
||||
h = await open_harness(stage_count=3)
|
||||
try:
|
||||
plugin = h.runner.model._ctx.plugin
|
||||
|
||||
def project_stage1(*, stage_id: int, output: object, context: object) -> bool:
|
||||
del output, context
|
||||
return stage_id == 1
|
||||
|
||||
plugin.project_intermediate_output = project_stage1
|
||||
await h.run(append_audio())
|
||||
request_id = h.stage0_request_id()
|
||||
thinker = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
outputs=[SimpleNamespace(text="hello", token_ids=[7, 8], multimodal_output={})],
|
||||
multimodal_output={},
|
||||
)
|
||||
forwarded = h.deliver(
|
||||
thinker,
|
||||
stage_id=1,
|
||||
segment_finished=False,
|
||||
metrics=stage_stats(stage_id=1, request_id=request_id, num_tokens_out=2, itls_ms=[6.0]),
|
||||
)
|
||||
assert forwarded is False
|
||||
events = await h.deliver_and_settle(tts_output(request_id, samples=24000, text="hello"), stage_id=2)
|
||||
stage_metrics = _stage_metrics_of(find(events, "response.output_audio.delta"))
|
||||
assert stage_metrics["1"]["num_tokens_out"] == 2
|
||||
finally:
|
||||
await close_harness(h)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_stage0_metrics_from_several_units_are_summed_into_one_response() -> None:
|
||||
"""Two pass-through segments before the first audio are one response's tokens."""
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
"""Ephemeral Stage0 bind uses r.stage0-turn{N}, not resumable r.stage0."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.session.manager import DuplexSessionManager
|
||||
|
||||
|
||||
def test_stage0_request_id_ephemeral_when_not_resumable() -> None:
|
||||
fence = DuplexFence("duplex-test", epoch=0, turn_id=3)
|
||||
rid = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=False)
|
||||
expected = duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert rid == expected
|
||||
assert rid.endswith(".r.stage0-turn3")
|
||||
assert not rid.endswith(".r.stage0")
|
||||
|
||||
|
||||
def test_stage0_request_id_resumable_keeps_stable_role() -> None:
|
||||
fence = DuplexFence("duplex-test", epoch=1, turn_id=3)
|
||||
rid = DuplexSessionManager.stage_request_id(fence, stage_id=0, resumable=True)
|
||||
expected = duplex_resource_request_id(fence, "stage0")
|
||||
assert rid == expected
|
||||
assert rid.endswith(".r.stage0")
|
||||
@@ -55,6 +55,7 @@ def _build(
|
||||
stages: int = 1,
|
||||
running_counter: FakeRunningCounter | None = None,
|
||||
runtime_config: DuplexSessionRuntimeConfig | None = None,
|
||||
plugin=None,
|
||||
) -> tuple[DuplexOrchestrator, list[FakeStageClient], asyncio.Queue, asyncio.Queue]:
|
||||
clients = [FakeStageClient(stage_type="llm", final_output=index == stages - 1) for index in range(stages)]
|
||||
pools = _build_stage_pools(
|
||||
@@ -70,7 +71,7 @@ def _build(
|
||||
rpc_async_queue=rpc_q,
|
||||
stage_pools=pools,
|
||||
running_counter=running_counter,
|
||||
plugin=MiniCPMO45DuplexPlugin(_encode_audio),
|
||||
plugin=plugin or MiniCPMO45DuplexPlugin(_encode_audio),
|
||||
duplex_session_config=runtime_config or DuplexSessionRuntimeConfig(reaper_interval_s=0.01),
|
||||
model_config=None,
|
||||
)
|
||||
@@ -197,7 +198,8 @@ async def test_open_preregisters_the_stage0_request_and_close_releases_it() -> N
|
||||
assert request_state.session_owned is True
|
||||
assert request_state.session_id == SESSION_ID
|
||||
assert request_state.fence == DuplexFence(SESSION_ID)
|
||||
assert request_state.streaming.enabled is True
|
||||
# Set on submit from submission.resumable, not again at preregister.
|
||||
assert request_state.streaming.enabled is False
|
||||
# Preregistration reserves the id; nothing is running until an append submits.
|
||||
assert counter.value == 0
|
||||
assert clients[0].add_request_calls == []
|
||||
@@ -211,6 +213,18 @@ async def test_open_preregisters_the_stage0_request_and_close_releases_it() -> N
|
||||
assert orchestrator.session_manager.active_count() == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aura_ephemeral_preregister_disables_streaming() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
orchestrator, _, rpc_q, _ = _build(plugin=AuraDuplexPlugin(_encode_audio))
|
||||
result = await _open(orchestrator, rpc_q)
|
||||
assert result.ok is True
|
||||
request_state = next(iter(orchestrator.request_states.values()))
|
||||
assert request_state.streaming.enabled is False
|
||||
await orchestrator.session_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_open_failure_rolls_back_session_and_reserved_request() -> None:
|
||||
orchestrator, _, rpc_q, _ = _build()
|
||||
@@ -275,6 +289,7 @@ async def test_append_submits_the_resumable_stage0_request_and_counts_it_running
|
||||
assert submitted.resumable is True
|
||||
assert submitted.sampling_params.max_tokens == 20
|
||||
request_state = orchestrator.request_states[request_id]
|
||||
assert request_state.streaming.enabled is True
|
||||
assert request_state.stage_fences[0] == DuplexFence(SESSION_ID)
|
||||
assert 0 in request_state.stage_submit_ts
|
||||
assert counter.value == 1
|
||||
@@ -390,6 +405,31 @@ async def test_forward_failure_closes_the_owning_session() -> None:
|
||||
assert types[-1] == "session.expired"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_aura_forward_failure_keeps_the_session() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
orchestrator, clients, rpc_q, output_q = _build(stages=2, plugin=AuraDuplexPlugin(_encode_audio))
|
||||
await _open(orchestrator, rpc_q)
|
||||
request_id = next(iter(orchestrator.request_states))
|
||||
await _submit(orchestrator, _append_audio())
|
||||
request_state = orchestrator.request_states[request_id]
|
||||
session = orchestrator.session_manager.get(SESSION_ID)
|
||||
assert session is not None
|
||||
|
||||
absorbed = await orchestrator._handle_forward_failure(request_id, 1, request_state, ValueError("stale talker"))
|
||||
await _settle(orchestrator)
|
||||
|
||||
assert absorbed is True
|
||||
assert request_id not in orchestrator.request_states
|
||||
assert SESSION_ID in orchestrator.session_manager.runners
|
||||
assert session.state != DuplexSessionState.CLOSED
|
||||
types = [message.event.type for message in [output_q.get_nowait() for _ in range(output_q.qsize())]]
|
||||
assert "error" in types
|
||||
assert "session.expired" not in types
|
||||
await orchestrator.session_manager.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_request_cleanup_failure_is_deferred_and_retried_by_the_reaper(monkeypatch) -> None:
|
||||
orchestrator, clients, rpc_q, _ = _build()
|
||||
@@ -560,3 +600,53 @@ async def test_turn_plugin_processes_multimodal_prompt_before_stage_submission(m
|
||||
assert not orchestrator.request_states[submitted.request_id].streaming.enabled
|
||||
finally:
|
||||
await _close(orchestrator, rpc_q)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sentence_partial_does_not_legacy_forward_the_full_stage_output() -> None:
|
||||
from vllm_omni.engine.duplex.plugin import PartialStageForward
|
||||
|
||||
orchestrator, *_ = _build(stages=4)
|
||||
forwarded: list[object] = []
|
||||
|
||||
async def record_forward(req_id, stage_id, output, req_state, **kwargs):
|
||||
del req_id, stage_id, req_state, kwargs
|
||||
forwarded.append(output)
|
||||
|
||||
async def no_intercept(*args, **kwargs):
|
||||
del args, kwargs
|
||||
return False
|
||||
|
||||
orchestrator._forward_to_next_stage = record_forward # type: ignore[method-assign]
|
||||
orchestrator._intercept_stage_output = no_intercept # type: ignore[method-assign]
|
||||
orchestrator.async_chunk = True
|
||||
orchestrator._stage_receives_async_chunks = lambda stage_id: False # type: ignore[method-assign]
|
||||
|
||||
full = SimpleNamespace(request_id="r", finished=True, text="FULL")
|
||||
chunk = SimpleNamespace(request_id="r", finished=True, text="CHUNK")
|
||||
req_state = DuplexOrchestratorRequestState(
|
||||
request_id="r",
|
||||
final_stage_id=3,
|
||||
session_owned=True,
|
||||
sampling_params_list=[SimpleNamespace() for _ in range(4)],
|
||||
)
|
||||
orchestrator.plugin.plan_partial_stage_output = lambda *args, **kwargs: PartialStageForward( # type: ignore[method-assign]
|
||||
output=chunk, is_final_update=True
|
||||
)
|
||||
orchestrator.plugin.partial_stage_followup = lambda *args, **kwargs: None # type: ignore[method-assign]
|
||||
|
||||
await orchestrator._route_output(1, 0, full, req_state, None)
|
||||
|
||||
assert forwarded == [chunk]
|
||||
assert req_state.skip_legacy_stage_forward is False
|
||||
|
||||
forwarded.clear()
|
||||
orchestrator.plugin.plan_partial_stage_output = lambda *args, **kwargs: None # type: ignore[method-assign]
|
||||
await orchestrator._route_output(1, 0, full, req_state, None)
|
||||
|
||||
assert forwarded == [full]
|
||||
|
||||
|
||||
def test_default_plugin_declares_no_draining_stages() -> None:
|
||||
plugin = MiniCPMO45DuplexPlugin(_encode_audio)
|
||||
assert plugin.draining_stage_ids(stage_count=4) == frozenset()
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
from vllm.outputs import CompletionOutput, RequestOutput
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex_orchestrator import DuplexOrchestrator
|
||||
from vllm_omni.engine.orchestrator import (
|
||||
Orchestrator,
|
||||
OrchestratorRequestState,
|
||||
@@ -249,6 +250,41 @@ async def test_async_prewarm_skips_outgoing_only_stage(payload_sender_info) -> N
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_prewarm_skips_stage_with_custom_process_input_func() -> None:
|
||||
"""AURA Stage1 has asr2aura: must not be zero-prewarmed under async_chunk.
|
||||
|
||||
The custom-process-input gate lives on DuplexOrchestrator (AURA path), not
|
||||
the turn-based Orchestrator base.
|
||||
"""
|
||||
orchestrator = object.__new__(DuplexOrchestrator)
|
||||
stage0 = FakePrewarmPool("sender")
|
||||
stage1 = FakePrewarmPool("receiver") # would receive chunks if role alone decided
|
||||
stage1.stage_client = SimpleNamespace(custom_process_input_func=lambda *a, **k: None)
|
||||
stage2 = FakePrewarmPool("receiver")
|
||||
orchestrator.stage_pools = [stage0, stage1, stage2]
|
||||
orchestrator._emit_tx_edge = lambda **_kwargs: None
|
||||
orchestrator._on_stage_submitted = MagicMock()
|
||||
req_state = OrchestratorRequestState(
|
||||
request_id="req-prewarm-custom",
|
||||
prompt={"prompt_token_ids": [1, 2]},
|
||||
sampling_params_list=[SamplingParams(max_tokens=1) for _ in range(3)],
|
||||
final_stage_id=2,
|
||||
)
|
||||
|
||||
prewarmed = await orchestrator._prewarm_async_chunk_stages(
|
||||
"req-prewarm-custom",
|
||||
SimpleNamespace(prompt_token_ids=[1, 2], resumable=True),
|
||||
req_state,
|
||||
)
|
||||
|
||||
assert prewarmed is True
|
||||
assert stage1.submitted == []
|
||||
assert len(stage2.submitted) == 1
|
||||
assert 1 not in req_state.stage_submit_ts
|
||||
assert 2 in req_state.stage_submit_ts
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_route_forwards_to_outgoing_only_stage() -> None:
|
||||
orchestrator = object.__new__(Orchestrator)
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import pybase64 as base64
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexCapabilities
|
||||
from vllm_omni.entrypoints.duplex.warmup import (
|
||||
_WARMUP_AUDIO_SECONDS,
|
||||
_WARMUP_FRAME_HEIGHT,
|
||||
_WARMUP_FRAME_WIDTH,
|
||||
_WARMUP_SAMPLE_RATE_HZ,
|
||||
_short_pcm_f32le_b64,
|
||||
_warmup_jpeg_b64,
|
||||
startup_warmup_kind,
|
||||
)
|
||||
|
||||
|
||||
class _Plugin:
|
||||
def __init__(self, required: frozenset[str]) -> None:
|
||||
self._required = required
|
||||
|
||||
def capabilities(self, *, max_sessions: int) -> DuplexCapabilities:
|
||||
del max_sessions
|
||||
return DuplexCapabilities(required_input_modalities=self._required)
|
||||
|
||||
|
||||
def test_video_required_model_warms_up_one_turn_by_default() -> None:
|
||||
plugin = _Plugin(frozenset({"video"}))
|
||||
assert startup_warmup_kind(plugin, 0) == "video_turn"
|
||||
|
||||
|
||||
def test_negative_warmup_frames_disables_the_video_turn() -> None:
|
||||
plugin = _Plugin(frozenset({"video"}))
|
||||
assert startup_warmup_kind(plugin, -1) is None
|
||||
|
||||
|
||||
def test_audio_primary_model_stays_opt_in() -> None:
|
||||
plugin = _Plugin(frozenset({"audio"}))
|
||||
assert startup_warmup_kind(plugin, 0) is None
|
||||
assert startup_warmup_kind(plugin, 4) == "silent_frames"
|
||||
|
||||
|
||||
def test_startup_turn_audio_is_short_and_not_silent() -> None:
|
||||
raw = base64.b64decode(_short_pcm_f32le_b64())
|
||||
assert len(raw) == int(_WARMUP_SAMPLE_RATE_HZ * _WARMUP_AUDIO_SECONDS) * 4
|
||||
assert any(raw)
|
||||
|
||||
|
||||
def test_startup_turn_frame_is_a_camera_sized_jpeg() -> None:
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
image = Image.open(BytesIO(base64.b64decode(_warmup_jpeg_b64())))
|
||||
assert image.size == (_WARMUP_FRAME_WIDTH, _WARMUP_FRAME_HEIGHT)
|
||||
assert image.format == "JPEG"
|
||||
@@ -113,12 +113,23 @@ def test_qwen_config_does_not_inject_reference_voice():
|
||||
assert '"profile": "qwen3-turn"' in page
|
||||
assert '"adapter": "vad"' in page
|
||||
assert '"refAudio": null' in page
|
||||
for name in ("common", "minicpm_native", "qwen3_turn"):
|
||||
for name in ("common", "minicpm_native", "qwen3_turn", "aura_ptt"):
|
||||
assert client.get(f"/static/profiles/{name}.js").status_code == 200
|
||||
with pytest.raises(ValueError, match="ref-audio"):
|
||||
build_app(profile="qwen3-turn", ref_audio="unused.wav")
|
||||
|
||||
|
||||
def test_aura_ptt_config_defaults_and_rejects_ref_audio():
|
||||
client = TestClient(build_app(profile="aura-ptt", model="aurateam/AURA"))
|
||||
page = client.get("/").text
|
||||
assert '"profile": "aura-ptt"' in page
|
||||
assert '"refAudio": null' in page
|
||||
assert "aura_ptt.js" in page
|
||||
assert 'id="pttButton"' in page
|
||||
with pytest.raises(ValueError, match="ref-audio"):
|
||||
build_app(profile="aura-ptt", ref_audio="unused.wav")
|
||||
|
||||
|
||||
def test_config_cannot_close_its_script_element():
|
||||
page = TestClient(build_app(model="</script><script>alert(1)</script>")).get("/").text
|
||||
assert "</script><script>alert(1)" not in page
|
||||
|
||||
@@ -240,3 +240,18 @@ def test_playback_worklet_fades_terminal_drain_to_zero():
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def test_aura_camera_preview_size_is_not_shared() -> None:
|
||||
aura = (STATIC_ROOT / "profiles" / "aura_ptt.js").read_text(encoding="utf-8")
|
||||
app = (STATIC_ROOT / "app.js").read_text(encoding="utf-8")
|
||||
minicpm = (STATIC_ROOT / "profiles" / "minicpm_native.js").read_text(encoding="utf-8")
|
||||
qwen = (STATIC_ROOT / "profiles" / "qwen3_turn.js").read_text(encoding="utf-8")
|
||||
html = (APP_ROOT / "index.html").read_text(encoding="utf-8")
|
||||
|
||||
assert "cameraPreviewLarge: true" in aura
|
||||
assert "cameraPreviewLarge" not in minicpm
|
||||
assert "cameraPreviewLarge" not in qwen
|
||||
assert "profile.cameraPreviewLarge" in app
|
||||
assert "camera-preview-break" not in app
|
||||
assert "width:96px;height:72px" in html
|
||||
@@ -5,7 +5,7 @@ const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const root = path.resolve(__dirname, '../../examples/online_serving/realtime_web/app/static');
|
||||
const context = vm.createContext({ URL });
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn']) {
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn', 'aura_ptt']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(root, `profiles/${name}.js`), 'utf8'), context);
|
||||
}
|
||||
const profiles = context.OmniRealtimeProfiles;
|
||||
@@ -83,6 +83,7 @@ function shell(profileName, adapter = 'stt', options = {}) {
|
||||
class Element {
|
||||
constructor() { this.style = {}; this.listeners = {}; this.children = []; this.value = ''; this.textContent = ''; this.classList = { add() {}, remove() {}, toggle() {} }; }
|
||||
addEventListener(name, callback) { this.listeners[name] = callback; }
|
||||
closest() { return null; }
|
||||
append(...children) { this.children.push(...children); }
|
||||
appendChild(child) { this.children.push(child); }
|
||||
replaceChildren() { this.children = []; }
|
||||
@@ -149,15 +150,16 @@ function shell(profileName, adapter = 'stt', options = {}) {
|
||||
atob: (value) => Buffer.from(value, 'base64').toString('binary'),
|
||||
});
|
||||
ctx.window = ctx;
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn']) {
|
||||
for (const name of ['common', 'minicpm_native', 'qwen3_turn', 'aura_ptt']) {
|
||||
vm.runInContext(fs.readFileSync(path.join(root, `profiles/${name}.js`), 'utf8'), ctx);
|
||||
}
|
||||
// Expose closure controls only in the test VM; production has no test API.
|
||||
const source = fs.readFileSync(path.join(root, 'app.js'), 'utf8').replace(/\}\)\(\);\s*$/, `
|
||||
globalThis.testUI = { startSession, stopSession, handleEvent, playbackDrained,
|
||||
microphoneUploadEnabled, flushCapture, awaitQueue: () => audioChain,
|
||||
microphoneUploadEnabled, flushCapture, setPttHeld, awaitQueue: () => audioChain,
|
||||
capture() { pendingCapture.push(new Int16Array([100, 200])); },
|
||||
state() { return { running, connectionReady, assistantActive }; }
|
||||
setPendingFrame(frame) { cameraPendingFrame = frame; if (profile.stickyCamera) cameraLastFrame = frame; },
|
||||
state() { return { running, connectionReady, assistantActive, pttHeld }; }
|
||||
};
|
||||
})();`);
|
||||
vm.runInContext(source, ctx);
|
||||
@@ -191,6 +193,7 @@ test('shared shell STT sends final commit and starts a fresh second turn only af
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
assert.equal(app.elements.get('cameraButton').hidden, true);
|
||||
assert.equal(app.sockets.flatMap(s => s.sent).some(e => e.type === 'playback.ack'), false);
|
||||
assert.equal(app.elements.get('pttButton').hidden, true);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
@@ -247,6 +250,8 @@ test('an interrupted response disarms the turn watchdog it left armed', async ()
|
||||
test('MiniCPM retains microphone upload while speaking and acknowledges speaker drain', async () => {
|
||||
const app = shell('minicpm-native');
|
||||
await app.ui.startSession();
|
||||
assert.equal(app.elements.get('pttButton').hidden, true);
|
||||
assert.equal(app.elements.get('sendTurnButton').hidden, true);
|
||||
await app.ui.handleEvent({ type: 'response.speak', response_id: 'native-r1' });
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
await app.ui.handleEvent({ type: 'response.output_audio.delta', delta: 'AAAAAA==', response_id: 'native-r1' });
|
||||
@@ -428,6 +433,150 @@ test('the camera retires its oldest image instead of exhausting the session budg
|
||||
assert.equal(plain(p.imageMessages('JPEG')).length, 1);
|
||||
});
|
||||
|
||||
test('AURA PTT profile sets duplex, is_speech append, commit on release, and shell flags', () => {
|
||||
const aura = profiles['aura-ptt']();
|
||||
const url = new URL(aura.url({ ...config, model: 'aurateam/AURA' }, 'http://localhost/'));
|
||||
assert.equal(url.searchParams.get('duplex'), '1');
|
||||
assert.equal(url.searchParams.get('model'), 'aurateam/AURA');
|
||||
assert.equal(aura.pushToTalk, true);
|
||||
assert.equal(aura.clientCommit, false);
|
||||
assert.equal(aura.camera, true);
|
||||
assert.equal(aura.stickyCamera, true);
|
||||
assert.equal(aura.cameraIntervalMs, 500);
|
||||
assert.equal(aura.visionFollowWhileSpeaking, true);
|
||||
assert.equal(aura.halfDuplex, false);
|
||||
assert.equal(aura.playbackAck, true);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: true }).is_speech, true);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: false }).is_speech, false);
|
||||
assert.equal(aura.append('PCM', 'JPEG', { isSpeech: false }).video_frames[0], 'JPEG');
|
||||
assert.deepEqual(plain(aura.commitMessages()), [
|
||||
{ type: 'input_audio_buffer.commit', create_response: true },
|
||||
]);
|
||||
assert.equal(aura.ack('r1', 50).type, 'playback.ack');
|
||||
const [update] = aura.initialMessages({}, 'Be brief');
|
||||
assert.equal(update.session.instructions, 'Be brief');
|
||||
assert.equal(update.session.extra_body.auto_response, true);
|
||||
});
|
||||
|
||||
test('AURA does not open a second bubble for the same sentence after response.done', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
const sentence = '你好,我看到一个戴眼镜、穿黑T恤的男生正对着镜头说话呢。';
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.delta', response_id: 'r1', delta: sentence,
|
||||
});
|
||||
await app.ui.handleEvent({ type: 'response.done', response_id: 'r1' });
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.done', response_id: 'r2', transcript: sentence,
|
||||
});
|
||||
const turns = [...app.elements.get('conversation').children].filter((row) => row.children.length);
|
||||
assert.equal(turns.length, 1);
|
||||
assert.equal(turns[0].children[1].textContent, sentence);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
function visionAppends(app) {
|
||||
return app.sockets[0].sent.filter(e => e.type === 'input_audio_buffer.append' && e.is_speech === false);
|
||||
}
|
||||
|
||||
test('AURA shell holds speech until PTT and opens one vision turn per two frames', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
assert.equal(app.elements.get('pttButton').hidden, false);
|
||||
assert.equal(app.elements.get('sendTurnButton').hidden, true);
|
||||
assert.equal(app.elements.get('cameraButton').hidden, false);
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), false);
|
||||
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.some(e => e.type === 'input_audio_buffer.append'), false);
|
||||
|
||||
app.ui.setPendingFrame('IDLE1');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 0, 'one frame must not open a turn');
|
||||
app.ui.setPendingFrame('IDLE2');
|
||||
app.ui.flushCapture();
|
||||
const idle = visionAppends(app).at(-1);
|
||||
assert.equal(idle.is_speech, false);
|
||||
assert.deepEqual(idle.video_frames, ['IDLE1', 'IDLE2'], 'two frames gate the turn and both go out as one clip');
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
assert.equal(app.ui.state().assistantActive, false);
|
||||
|
||||
app.ui.setPttHeld(true);
|
||||
assert.equal(app.ui.microphoneUploadEnabled(), true);
|
||||
app.ui.setPendingFrame('FRAME1');
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
const speech = app.sockets[0].sent.find(e => e.type === 'input_audio_buffer.append' && e.is_speech === true);
|
||||
assert.equal(speech.video_frames[0], 'FRAME1');
|
||||
assert.equal(visionAppends(app).length, 1, 'speech must not wait for a second frame');
|
||||
|
||||
app.ui.setPttHeld(false);
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
assert.equal(app.ui.state().pttHeld, false);
|
||||
|
||||
await app.ui.handleEvent({ type: 'response.created', response: { id: 'aura-r1' } });
|
||||
app.ui.setPendingFrame('LOCKED1');
|
||||
app.ui.flushCapture();
|
||||
app.ui.setPendingFrame('LOCKED2');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 1, 'open text turn blocks the next vision commit');
|
||||
|
||||
await app.ui.handleEvent({
|
||||
type: 'response.output_audio_transcript.done', response_id: 'aura-r1', transcript: '看到了。',
|
||||
});
|
||||
assert.equal(app.ui.state().assistantActive, true, 'text end must not wait for playback');
|
||||
app.ui.flushCapture();
|
||||
assert.deepEqual(visionAppends(app).at(-1).video_frames, ['LOCKED1', 'LOCKED2']);
|
||||
assert.equal(app.sockets[0].sent.at(-1).type, 'input_audio_buffer.commit');
|
||||
|
||||
await app.ui.handleEvent({ type: 'response.created', response: { id: 'aura-r2' } });
|
||||
app.ui.setPendingFrame('SILENT1');
|
||||
app.ui.flushCapture();
|
||||
app.ui.setPendingFrame('SILENT2');
|
||||
app.ui.flushCapture();
|
||||
assert.equal(visionAppends(app).length, 2);
|
||||
await app.ui.handleEvent({ type: 'response.listen', response_id: 'aura-r2' });
|
||||
app.ui.flushCapture();
|
||||
assert.deepEqual(visionAppends(app).at(-1).video_frames, ['SILENT1', 'SILENT2']);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
test('AURA hold-to-talk stops local playback and does not cancel the response', async () => {
|
||||
const app = shell('aura-ptt', 'stt', { realPlayback: true });
|
||||
await app.ui.startSession();
|
||||
receive(app, { type: 'response.created', response: { id: 'old' } });
|
||||
receive(app, audioChunk('old'));
|
||||
await app.ui.awaitQueue();
|
||||
const player = app.nodes.find(node => node.name === 'fullduplex-pcm-playback').player;
|
||||
for (let index = 0; index < 75; index++) renderPlayback(player);
|
||||
assert.ok(renderPlayback(player).some(sample => sample !== 0));
|
||||
const sentBefore = app.sockets[0].sent.length;
|
||||
app.ui.setPttHeld(true);
|
||||
assertSilent(player);
|
||||
const extra = app.sockets[0].sent.slice(sentBefore);
|
||||
assert.ok(extra.every(event => event.type === 'playback.ack'), 'hold must not abort the server response');
|
||||
receive(app, audioChunk('old'));
|
||||
await app.ui.awaitQueue();
|
||||
assertSilent(player);
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
test('AURA sticky camera reuses the last frame on speech without a fresh pending', async () => {
|
||||
const app = shell('aura-ptt');
|
||||
await app.ui.startSession();
|
||||
app.ui.setPendingFrame('STICKY');
|
||||
app.ui.setPttHeld(true);
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.at(-1).video_frames[0], 'STICKY');
|
||||
// Pending cleared; sticky last frame still available for the next speech flush.
|
||||
app.ui.capture();
|
||||
app.ui.flushCapture();
|
||||
assert.equal(app.sockets[0].sent.at(-1).video_frames[0], 'STICKY');
|
||||
await app.ui.stopSession({ terminal: false });
|
||||
});
|
||||
|
||||
// Exercise the real WebSocket dispatch queue together with the actual playback
|
||||
// processor: sending a clear message alone does not prove the speaker is silent.
|
||||
function receive(app, event) {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CPU tests for AuraDataPlaneSession (unwrap runner envelope; do not drop audio)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
|
||||
|
||||
def _encode_audio(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del sample_rate, fmt, speed
|
||||
if audio is None:
|
||||
return None
|
||||
return "encoded-audio"
|
||||
|
||||
|
||||
def test_project_unwraps_data_plane_outputs_and_emits_audio_then_done() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage0-turn1"
|
||||
plane.begin_request(request_id)
|
||||
audio = np.zeros(16, dtype=np.float32)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=3,
|
||||
outputs=[
|
||||
SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=True,
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
],
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [output]}))
|
||||
assert events, "project must not silently drop the runner envelope"
|
||||
assert any(event.get("audio") == "encoded-audio" for event in events)
|
||||
assert events[-1].get("end_of_turn") is True
|
||||
assert events[0].get("data_plane_request_id") == request_id
|
||||
|
||||
|
||||
def test_project_sends_only_the_new_tail_of_a_growing_waveform() -> None:
|
||||
seen: list[int] = []
|
||||
|
||||
def encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
del sample_rate, fmt, speed
|
||||
count = int(np.asarray(audio).reshape(-1).size)
|
||||
seen.append(count)
|
||||
return f"pcm-{count}"
|
||||
|
||||
plane = AuraDataPlaneSession(encode)
|
||||
request_id = "duplex-s.abc.e.0.r.stage3-turn1"
|
||||
plane.begin_request(request_id)
|
||||
|
||||
def chunk(n: int, *, finished: bool) -> SimpleNamespace:
|
||||
audio = np.arange(n, dtype=np.float32)
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=finished,
|
||||
stage_id=3,
|
||||
outputs=[
|
||||
SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=False,
|
||||
multimodal_output={"audio": audio, "sr": 24000},
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
first = list(plane.project_output(chunk(8, finished=False)))
|
||||
second = list(plane.project_output(chunk(12, finished=True)))
|
||||
assert seen == [8, 4]
|
||||
assert first[0]["audio_duration_ms"] == round(8 * 1000 / 24000)
|
||||
assert second[0]["audio_duration_ms"] == round(4 * 1000 / 24000)
|
||||
assert second[-1].get("end_of_turn") is True
|
||||
|
||||
|
||||
def test_project_holds_silent_token_prefix() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn1"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|sil", cumulative_text="<|sil", finished=False)],
|
||||
)
|
||||
assert list(plane.project({"data_plane_outputs": [partial]})) == []
|
||||
|
||||
|
||||
def test_project_emits_chinese_brackets_immediately() -> None:
|
||||
"""[沉默] is ordinary text — do not hold as a <|silent|> prefix."""
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1_t2"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="[", cumulative_text="[", finished=False)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [partial]}))
|
||||
assert len(events) == 1
|
||||
assert events[0].get("text") == "["
|
||||
|
||||
|
||||
def test_project_flushes_held_silent_prefix_when_text_becomes_speech() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn3"
|
||||
plane.begin_request(request_id)
|
||||
partial = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|", cumulative_text="<|", finished=False)],
|
||||
)
|
||||
assert list(plane.project({"data_plane_outputs": [partial]})) == []
|
||||
spoken = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|hello", cumulative_text="<|hello", finished=False)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [spoken]}))
|
||||
assert len(events) == 1
|
||||
assert events[0].get("text") == "<|hello"
|
||||
|
||||
|
||||
def test_project_marks_finished_silent_text_as_listen() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1_t4"
|
||||
plane.begin_request(request_id)
|
||||
final = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="<|silent|>", cumulative_text="<|silent|>", finished=True)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [final]}))
|
||||
assert any(e.get("silent") and e.get("is_listen") for e in events)
|
||||
assert any(e.get("abort_data_plane_request") is True for e in events)
|
||||
|
||||
|
||||
def test_project_finished_spoken_turn_carries_model_context() -> None:
|
||||
plane = AuraDataPlaneSession(_encode_audio)
|
||||
request_id = "duplex-s.abc.e.0.r.stage1-turn5"
|
||||
plane.begin_request(request_id)
|
||||
final = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[SimpleNamespace(text="你好。", cumulative_text="你好。", finished=True)],
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [final]}))
|
||||
context = [event for event in events if event.get("model_context_text")]
|
||||
assert context and context[-1]["model_context_text"] == "你好。"
|
||||
assert context[-1].get("is_listen") is False
|
||||
assert context[-1].get("text") == ""
|
||||
@@ -0,0 +1,115 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""Aura duplex data-plane must surface Code2Wav MultimodalPayload audio."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import (
|
||||
AuraDataPlaneSession,
|
||||
_audio_value,
|
||||
_multimodal,
|
||||
)
|
||||
from vllm_omni.outputs.mm_outputs import MultimodalPayload
|
||||
|
||||
|
||||
def _encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del sample_rate, fmt, speed
|
||||
if audio is None:
|
||||
return None
|
||||
return "encoded-audio"
|
||||
|
||||
|
||||
def test_audio_value_accepts_from_raw_audio_key() -> None:
|
||||
raw = {"model_outputs": [torch.zeros(8)], "sr": [torch.tensor(24000)]}
|
||||
mm = MultimodalPayload.from_raw(raw, "audio")
|
||||
assert mm is not None
|
||||
assert "audio" in mm
|
||||
audio = _audio_value(dict(mm))
|
||||
assert isinstance(audio, torch.Tensor)
|
||||
assert int(audio.numel()) == 8
|
||||
|
||||
|
||||
def test_audio_value_accepts_wrongly_tagged_text_key() -> None:
|
||||
# If stage output_modality is wrong, from_raw remaps model_outputs → "text".
|
||||
raw = {"model_outputs": torch.zeros(4), "sr": torch.tensor(24000)}
|
||||
mm = MultimodalPayload.from_raw(raw, "text")
|
||||
assert mm is not None
|
||||
audio = _audio_value(dict(mm))
|
||||
assert isinstance(audio, torch.Tensor)
|
||||
|
||||
|
||||
def test_multimodal_skips_empty_outer_dict_and_reads_completion() -> None:
|
||||
mm = MultimodalPayload.from_dict({"audio": torch.zeros(3), "sr": torch.tensor(24000)})
|
||||
completion = SimpleNamespace(multimodal_output=mm)
|
||||
# Empty Mapping on the outer object must not hide completion payload.
|
||||
outer = SimpleNamespace(multimodal_output={})
|
||||
got = _multimodal(outer, completion)
|
||||
assert "audio" in got
|
||||
|
||||
|
||||
def test_project_emits_audio_from_multimodal_completion() -> None:
|
||||
plane = AuraDataPlaneSession(_encode)
|
||||
request_id = "duplex-s.test.e.0.r.stage0-turn0"
|
||||
plane.begin_request(request_id)
|
||||
mm = MultimodalPayload.from_raw(
|
||||
{"model_outputs": [torch.zeros(16)], "sr": [torch.tensor(24000)]},
|
||||
"audio",
|
||||
)
|
||||
completion = SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=False,
|
||||
multimodal_output=mm,
|
||||
)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=3,
|
||||
outputs=[completion],
|
||||
multimodal_output={},
|
||||
)
|
||||
events = list(plane.project({"data_plane_outputs": [output]}))
|
||||
assert events, "project must emit TTS audio for MultimodalPayload"
|
||||
assert any(event.get("audio") == "encoded-audio" for event in events)
|
||||
|
||||
|
||||
def test_streaming_chunk_completion_finished_is_not_turn_eos() -> None:
|
||||
"""Code2Wav chunks set CompletionOutput.finished; that must not EOT.
|
||||
|
||||
Runner._send_one_model_output_event drops is_terminal request ids before
|
||||
emit. Marking terminal (or end_of_turn) on the first 8-frame chunk made
|
||||
WS response.* never leave the engine.
|
||||
"""
|
||||
plane = AuraDataPlaneSession(_encode)
|
||||
request_id = "duplex-s.test.e.0.r.stage0-turn0"
|
||||
plane.begin_request(request_id)
|
||||
mm = MultimodalPayload.from_raw(
|
||||
{"model_outputs": [torch.zeros(16)], "sr": [torch.tensor(24000)]},
|
||||
"audio",
|
||||
)
|
||||
completion = SimpleNamespace(
|
||||
text="",
|
||||
cumulative_text="",
|
||||
finished=True,
|
||||
multimodal_output=mm,
|
||||
)
|
||||
output = SimpleNamespace(
|
||||
request_id=request_id,
|
||||
finished=False,
|
||||
stage_id=3,
|
||||
outputs=[completion],
|
||||
multimodal_output={},
|
||||
)
|
||||
events: list[dict[str, object]] = []
|
||||
for event in plane.project({"data_plane_outputs": [output]}):
|
||||
assert plane.is_terminal(request_id) is False
|
||||
events.append(event)
|
||||
assert events
|
||||
assert events[0].get("audio") == "encoded-audio"
|
||||
assert events[0].get("end_of_turn") is False
|
||||
assert plane.is_terminal(request_id) is False
|
||||
@@ -0,0 +1,598 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CPU contract tests for AURA duplex plugin seams."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from vllm.sampling_params import SamplingParams
|
||||
|
||||
from vllm_omni.engine.duplex.config import DuplexSessionConfig
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexStageRequestContext,
|
||||
DuplexStageSubmission,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
duplex_resource_request_id,
|
||||
)
|
||||
from vllm_omni.engine.duplex.plugin import load_duplex_plugin
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import (
|
||||
AuraDataPlaneContext,
|
||||
AuraDataPlaneSession,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import (
|
||||
drop_session_history,
|
||||
get_or_create_session_history,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.input import AuraPcmAppendBuffer
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import (
|
||||
AURA_SILENT_TOKEN_ID,
|
||||
AuraDuplexPlugin,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import SILENT_TEXT
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _encode_audio(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str | None:
|
||||
del audio, sample_rate, fmt, speed
|
||||
return "ZmFrZQ=="
|
||||
|
||||
|
||||
def test_load_aura_duplex_plugin_and_sampling_arity() -> None:
|
||||
plugin = load_duplex_plugin(
|
||||
"vllm_omni.model_executor.models.aura_omni.duplex.plugin.AuraDuplexPlugin",
|
||||
_encode_audio,
|
||||
)
|
||||
assert isinstance(plugin, AuraDuplexPlugin)
|
||||
assert plugin.plugin_id == "aura"
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=4096),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
assert len(configured) == 4
|
||||
assert configured[2].stop_token_ids == [2150]
|
||||
assert configured[2].max_tokens == 4096
|
||||
stage1_stops = set(configured[1].stop_token_ids or [])
|
||||
assert {151669, 151645}.issubset(stage1_stops)
|
||||
assert 248070 not in stage1_stops
|
||||
caps = plugin.capabilities(max_sessions=1)
|
||||
assert caps.supports_turn_commit_only is True
|
||||
assert caps.supports_core_resumable_request is False
|
||||
assert caps.supports_concurrent_turn_requests is True
|
||||
assert caps.required_input_modalities == frozenset({"video"})
|
||||
assert caps.optional_input_modalities == frozenset({"audio"})
|
||||
assert caps.allows_video_without_audio() is True
|
||||
assert caps.validate_append_modalities(has_audio=True, has_video=False) == (
|
||||
"This duplex model requires video_frames on input_audio_buffer.append"
|
||||
)
|
||||
assert caps.validate_append_modalities(has_audio=True, has_video=True) is None
|
||||
assert caps.validate_append_modalities(has_audio=False, has_video=True) is None
|
||||
|
||||
|
||||
def test_commit_only_buffer_emits_on_commit() -> None:
|
||||
buf = AuraPcmAppendBuffer()
|
||||
samples = np.zeros(1600, dtype="<f4")
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(samples.tobytes()).decode("ascii"),
|
||||
"is_speech": True,
|
||||
"video_frames": ["aGVsbG8="],
|
||||
}
|
||||
reservation = buf.prepare_append(
|
||||
payload,
|
||||
operation_id="op1",
|
||||
chunk_period_ms=1000,
|
||||
allow_emit=True,
|
||||
)
|
||||
assert reservation is None
|
||||
assert buf.has_pending()
|
||||
commit = buf.prepare_commit(operation_id="c1", chunk_period_ms=1000)
|
||||
assert commit.payload is not None
|
||||
assert commit.payload.get("final") is True
|
||||
assert commit.payload.get("aura_turn_commit") is True
|
||||
assert commit.payload.get("video_frames") == ["aGVsbG8="]
|
||||
commit.commit()
|
||||
|
||||
|
||||
def test_commit_reservation_includes_video_bytes() -> None:
|
||||
buf = AuraPcmAppendBuffer()
|
||||
pcm = np.zeros(1600, dtype="<f4").tobytes()
|
||||
frames = ["aGVsbG8=", "d29ybGQ="]
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(pcm).decode("ascii"),
|
||||
"is_speech": True,
|
||||
"video_frames": frames,
|
||||
}
|
||||
assert (
|
||||
buf.prepare_append(
|
||||
payload,
|
||||
operation_id="op1",
|
||||
chunk_period_ms=1000,
|
||||
allow_emit=True,
|
||||
)
|
||||
is None
|
||||
)
|
||||
pending = buf.pending_byte_count
|
||||
assert pending == len(pcm) + sum(len(frame) for frame in frames)
|
||||
commit = buf.prepare_commit(operation_id="c1", chunk_period_ms=1000)
|
||||
assert buf.pending_byte_count == 0
|
||||
assert commit.byte_count == pending
|
||||
commit.commit()
|
||||
assert buf.pending_byte_count == 0
|
||||
assert not buf.has_reserved()
|
||||
|
||||
|
||||
def test_plan_append_commit_builds_stage0_prompt() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
samples = np.zeros(800, dtype="<f4")
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": base64.b64encode(samples.tobytes()).decode("ascii"),
|
||||
"final": True,
|
||||
"aura_turn_commit": True,
|
||||
"is_speech": True,
|
||||
}
|
||||
fence = DuplexFence("sess-1", epoch=2, turn_id=5)
|
||||
plan = plugin.plan_append(
|
||||
request_id="req",
|
||||
fence=fence,
|
||||
session_config={},
|
||||
runtime_config={"aura_system_prompt": "sys"},
|
||||
seq=1,
|
||||
turn_seq=1,
|
||||
payload=payload,
|
||||
final=True,
|
||||
sampling_params=SamplingParams(max_tokens=8),
|
||||
)
|
||||
info = plan.prompt["additional_information"]
|
||||
assert info["aura_duplex"] is True
|
||||
assert info["session_id"] == "sess-1"
|
||||
assert "audio" in plan.prompt["multi_modal_data"]
|
||||
assert "prompt_token_ids" not in plan.prompt
|
||||
|
||||
|
||||
def test_video_frames_to_mm_packs_one_video() -> None:
|
||||
"""Two JPEG frames are one video clip, not two image items."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import _video_frames_to_mm
|
||||
|
||||
frames: list[str] = []
|
||||
for color in ((255, 0, 0), (0, 255, 0)):
|
||||
buf = BytesIO()
|
||||
Image.new("RGB", (8, 8), color).save(buf, format="JPEG")
|
||||
frames.append(base64.b64encode(buf.getvalue()).decode("ascii"))
|
||||
mm = _video_frames_to_mm(frames)
|
||||
assert list(mm.keys()) == ["video"]
|
||||
assert len(mm["video"]) == 1
|
||||
video, metadata = mm["video"][0]
|
||||
assert np.asarray(video).shape == (2, 8, 8, 3)
|
||||
assert metadata["total_num_frames"] == 2
|
||||
assert metadata["do_sample_frames"] is False
|
||||
|
||||
|
||||
def test_plan_append_vision_empty_audio_never_leaves_empty_prompt() -> None:
|
||||
"""Frames + empty/near-silent audio must still get a Stage0 ASR pad."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image
|
||||
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
img = Image.new("RGB", (32, 32), (8, 16, 24))
|
||||
buf = BytesIO()
|
||||
img.save(buf, format="JPEG")
|
||||
frame = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||
fence = DuplexFence("sess-v", epoch=0, turn_id=1)
|
||||
near = np.linspace(1e-5, -1e-5, 80, dtype="<f4")
|
||||
cases = [
|
||||
("empty_speech_true", True, ""),
|
||||
("empty_speech_false", False, ""),
|
||||
("near_silent", False, base64.b64encode(near.tobytes()).decode("ascii")),
|
||||
]
|
||||
for name, is_speech, audio in cases:
|
||||
payload = {
|
||||
"type": "audio",
|
||||
"format": "pcm_f32le",
|
||||
"sample_rate_hz": 16000,
|
||||
"audio": audio,
|
||||
"final": True,
|
||||
"aura_turn_commit": True,
|
||||
"is_speech": is_speech,
|
||||
"video_frames": [frame],
|
||||
}
|
||||
plan = plugin.plan_append(
|
||||
request_id="req",
|
||||
fence=fence,
|
||||
session_config={},
|
||||
runtime_config={},
|
||||
seq=1,
|
||||
turn_seq=1,
|
||||
payload=payload,
|
||||
final=True,
|
||||
sampling_params=SamplingParams(max_tokens=8),
|
||||
)
|
||||
assert plan.prompt.get("prompt"), f"{name}: Stage0 prompt must be non-empty"
|
||||
assert "audio" in plan.prompt["multi_modal_data"], f"{name}: padded audio required"
|
||||
assert "deferred_multi_modal_data" in plan.prompt["additional_information"]
|
||||
|
||||
|
||||
def test_project_intermediate_output_targets_stage1_only() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.project_intermediate_output(stage_id=1, output=object(), context=object()) is True
|
||||
assert plugin.project_intermediate_output(stage_id=0, output=object(), context=object()) is False
|
||||
assert plugin.project_intermediate_output(stage_id=3, output=object(), context=object()) is False
|
||||
|
||||
|
||||
def test_release_concurrent_turn_requests_on_stage1_final() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.release_concurrent_turn_requests(stage_id=1, segment_finished=True, output=object(), context=object())
|
||||
assert not plugin.release_concurrent_turn_requests(
|
||||
stage_id=1, segment_finished=False, output=object(), context=object()
|
||||
)
|
||||
finished = type("Out", (), {"finished": True})()
|
||||
assert plugin.release_concurrent_turn_requests(
|
||||
stage_id=1, segment_finished=False, output=finished, context=object()
|
||||
)
|
||||
assert not plugin.release_concurrent_turn_requests(
|
||||
stage_id=2, segment_finished=True, output=object(), context=object()
|
||||
)
|
||||
|
||||
|
||||
def test_configure_sampling_keeps_silent_stop_visible() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=4096),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
stage1 = configured[1]
|
||||
assert isinstance(stage1, SamplingParams)
|
||||
assert stage1.include_stop_str_in_output is True
|
||||
assert stage1.skip_special_tokens is False
|
||||
assert AURA_SILENT_TOKEN_ID in (stage1.stop_token_ids or [])
|
||||
|
||||
|
||||
def test_configure_sampling_keeps_explicit_talker_limits() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
defaults = (
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=500, stop_token_ids=[7]),
|
||||
SamplingParams(max_tokens=16),
|
||||
)
|
||||
configured = plugin.configure_sampling_params(runtime_config={}, defaults=defaults)
|
||||
stage2 = configured[2]
|
||||
assert isinstance(stage2, SamplingParams)
|
||||
assert stage2.max_tokens == 500
|
||||
assert stage2.stop_token_ids == [7]
|
||||
unset = plugin.configure_sampling_params(
|
||||
runtime_config={},
|
||||
defaults=(
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=16),
|
||||
SamplingParams(max_tokens=None),
|
||||
SamplingParams(max_tokens=16),
|
||||
),
|
||||
)
|
||||
assert unset[2].max_tokens == 240
|
||||
assert unset[2].stop_token_ids == [2150]
|
||||
|
||||
|
||||
def test_decide_output_silent_short_circuits() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
|
||||
class _Completion:
|
||||
text = SILENT_TEXT
|
||||
token_ids = [AURA_SILENT_TOKEN_ID]
|
||||
finished = True
|
||||
|
||||
class _Output:
|
||||
outputs = [_Completion()]
|
||||
|
||||
decision = plugin.decide_output(
|
||||
stage_id=1,
|
||||
final_stage_id=3,
|
||||
segment_finished=True,
|
||||
segment_token_ids=(AURA_SILENT_TOKEN_ID,),
|
||||
segment_output_metadata={},
|
||||
output=_Output(),
|
||||
)
|
||||
assert decision is not None
|
||||
assert decision.metadata.get("model_listen") is True
|
||||
|
||||
|
||||
def test_decide_output_chinese_silence_is_not_special_token() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
|
||||
class _Completion:
|
||||
text = "[沉默]"
|
||||
token_ids = [58, 107107, 60]
|
||||
finished = True
|
||||
|
||||
class _Output:
|
||||
outputs = [_Completion()]
|
||||
|
||||
assert (
|
||||
plugin.decide_output(
|
||||
stage_id=1,
|
||||
final_stage_id=3,
|
||||
segment_finished=True,
|
||||
segment_token_ids=(58, 107107, 60),
|
||||
segment_output_metadata={},
|
||||
output=_Output(),
|
||||
)
|
||||
is None
|
||||
)
|
||||
|
||||
|
||||
def test_ephemeral_request_id_includes_turn() -> None:
|
||||
fence = DuplexFence("s", epoch=1, turn_id=7)
|
||||
resumable = duplex_resource_request_id(fence, "stage0")
|
||||
ephemeral = duplex_ephemeral_stage_request_id(fence, stage_id=0)
|
||||
assert ephemeral.endswith("stage0-turn7")
|
||||
assert resumable != ephemeral
|
||||
fence2 = DuplexFence("s", epoch=1, turn_id=8)
|
||||
assert duplex_ephemeral_stage_request_id(fence, stage_id=0) != duplex_ephemeral_stage_request_id(fence2, stage_id=0)
|
||||
|
||||
|
||||
def test_stage_submission_defaults_resumable_true() -> None:
|
||||
ctx = DuplexStageRequestContext(
|
||||
request_id="r",
|
||||
session_id="s",
|
||||
fence=DuplexFence("s"),
|
||||
stage_id=0,
|
||||
final_stage_id=3,
|
||||
config_generation=0,
|
||||
sampling_params=(SamplingParams(max_tokens=1),),
|
||||
)
|
||||
submission = DuplexStageSubmission(
|
||||
context=ctx,
|
||||
prompt={"prompt_token_ids": [0]},
|
||||
already_submitted=False,
|
||||
)
|
||||
assert submission.resumable is True
|
||||
|
||||
|
||||
def test_data_plane_close_session_drops_history() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import get_or_create_session_history
|
||||
|
||||
drop_session_history("close-hist")
|
||||
get_or_create_session_history("close-hist").begin_user_turn("hi")
|
||||
AuraDataPlaneSession(encode_audio=_encode_audio).close_session("close-hist")
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import _STORE
|
||||
|
||||
assert "close-hist" not in _STORE
|
||||
|
||||
|
||||
def test_session_history_strips_oldest_silent_videos() -> None:
|
||||
drop_session_history("hist-ut")
|
||||
history = get_or_create_session_history("hist-ut")
|
||||
history.max_video_rounds = 2
|
||||
history.video_rounds_to_remove = 1
|
||||
for index in range(3):
|
||||
history.begin_user_turn("", video=(f"clip-{index}",))
|
||||
history.commit_turn(SILENT_TEXT)
|
||||
kept = [message["video"] for message in history.messages if message.get("video") is not None]
|
||||
assert kept == [("clip-1",), ("clip-2",)]
|
||||
assert not any(message.get("video") == ("clip-0",) for message in history.messages)
|
||||
drop_session_history("hist-ut")
|
||||
|
||||
|
||||
def test_pipeline_declares_aura_duplex_plugin() -> None:
|
||||
from vllm_omni.model_executor.models.aura_omni.pipeline import AURA_OMNI_PIPELINE
|
||||
|
||||
assert AURA_OMNI_PIPELINE.duplex_plugin == (
|
||||
"vllm_omni.model_executor.models.aura_omni.duplex.plugin.AuraDuplexPlugin"
|
||||
)
|
||||
|
||||
|
||||
def test_project_output_uses_requested_format_and_chunk_duration() -> None:
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def encode(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
seen["fmt"] = fmt
|
||||
seen["rate"] = sample_rate
|
||||
seen["speed"] = speed
|
||||
del audio
|
||||
return "AAAA"
|
||||
|
||||
plane = AuraDataPlaneSession(encode)
|
||||
|
||||
class _Output:
|
||||
request_id = "aura-turn"
|
||||
finished = False
|
||||
stage_id = 3
|
||||
multimodal_output = {"audio": np.zeros(4800, dtype=np.float32), "sr": 24000}
|
||||
|
||||
events = list(plane.project_output(_Output(), context=AuraDataPlaneContext(response_format="pcm16", speed=1.0)))
|
||||
assert seen["fmt"] == "pcm16"
|
||||
assert events[0]["audio_format"] == "pcm16"
|
||||
assert events[0]["audio_duration_ms"] == 200
|
||||
assert events[0]["sample_rate_hz"] == 24000
|
||||
|
||||
def encode_wav(audio: object, sample_rate: int, fmt: str, speed: float | None) -> str:
|
||||
del audio, sample_rate, speed
|
||||
assert fmt == "wav"
|
||||
return "V0FW"
|
||||
|
||||
plane_wav = AuraDataPlaneSession(encode_wav)
|
||||
wav_events = list(plane_wav.project_output(_Output(), context=AuraDataPlaneContext(response_format="wav")))
|
||||
assert wav_events[0]["audio_format"] == "wav"
|
||||
|
||||
|
||||
def test_instructions_update_replaces_effective_prompt() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
current = {"aura_system_prompt": "creation default", "instructions": "creation default"}
|
||||
updated = plugin.runtime_config_for_update(
|
||||
DuplexSessionConfig(model="aurateam/AURA", instructions="be brief"),
|
||||
current,
|
||||
)
|
||||
assert updated["aura_system_prompt"] == "be brief"
|
||||
assert updated["instructions"] == "be brief"
|
||||
kept = plugin.runtime_config_for_update(
|
||||
DuplexSessionConfig(
|
||||
model="aurateam/AURA",
|
||||
extra_body={"aura_system_prompt": "explicit"},
|
||||
instructions="ignored when explicit",
|
||||
),
|
||||
updated,
|
||||
)
|
||||
assert kept["aura_system_prompt"] == "explicit"
|
||||
|
||||
|
||||
def test_plan_partial_stage_output_hands_a_sentence_to_talker() -> None:
|
||||
def aura2tts() -> None:
|
||||
return None
|
||||
|
||||
class _Pool:
|
||||
stage_client = SimpleNamespace(custom_process_input_func=aura2tts)
|
||||
|
||||
orchestrator = SimpleNamespace(
|
||||
stage_pools={2: _Pool()},
|
||||
_stage_receives_async_chunks=lambda stage_id: False,
|
||||
)
|
||||
req_state = SimpleNamespace(
|
||||
session_owned=True,
|
||||
final_stage_id=3,
|
||||
request_id="req-1",
|
||||
prompt={"additional_information": {}},
|
||||
streaming=SimpleNamespace(bridge_states={}),
|
||||
)
|
||||
sentence = "这是一段用来直接测试句子级语音交接而且长度已经超过三十个字的内容。"
|
||||
output = SimpleNamespace(
|
||||
finished=False,
|
||||
request_id="req-1",
|
||||
outputs=[SimpleNamespace(cumulative_text=sentence)],
|
||||
)
|
||||
|
||||
plan = AuraDuplexPlugin(_encode_audio).plan_partial_stage_output(orchestrator, 1, 0, output, req_state)
|
||||
|
||||
assert plan is not None
|
||||
assert plan.close_only is False
|
||||
assert plan.is_final_update is False
|
||||
assert plan.output.text == sentence.strip()
|
||||
assert req_state.prompt["additional_information"]["aura_tts_partial"] is True
|
||||
assert AuraDuplexPlugin(_encode_audio).plan_partial_stage_output(orchestrator, 0, 0, output, req_state) is None
|
||||
|
||||
|
||||
def _sentence_plan_fixture() -> tuple[SimpleNamespace, SimpleNamespace]:
|
||||
def aura2tts() -> None:
|
||||
return None
|
||||
|
||||
class _Pool:
|
||||
stage_client = SimpleNamespace(custom_process_input_func=aura2tts)
|
||||
|
||||
orchestrator = SimpleNamespace(
|
||||
stage_pools={2: _Pool()},
|
||||
_stage_receives_async_chunks=lambda stage_id: False,
|
||||
)
|
||||
req_state = SimpleNamespace(
|
||||
session_owned=True,
|
||||
final_stage_id=3,
|
||||
request_id="req-1",
|
||||
prompt={"additional_information": {}},
|
||||
streaming=SimpleNamespace(bridge_states={}),
|
||||
)
|
||||
return orchestrator, req_state
|
||||
|
||||
|
||||
def _stage1_output(text: str, *, finished: bool) -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
finished=finished,
|
||||
request_id="req-1",
|
||||
outputs=[SimpleNamespace(cumulative_text=text)],
|
||||
)
|
||||
|
||||
|
||||
def test_finished_remainder_stays_resumable_until_close_sentinel() -> None:
|
||||
"""A second sentence at Stage1 finish must not be the Talker end sentinel.
|
||||
|
||||
The first sentence is already a resumable Talker request. Marking the
|
||||
remainder ``is_final_update`` makes ``StreamingUpdate.from_request``
|
||||
return None, which aborts that in-flight sentence before Code2Wav has a
|
||||
full codec group.
|
||||
"""
|
||||
orchestrator, req_state = _sentence_plan_fixture()
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
first = "我看到你身后是一个很明亮的办公室环境,天花板上能看到白色的管道和通风口,"
|
||||
full = first + "远处还有办公桌和绿植。"
|
||||
opened = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(first, finished=False), req_state)
|
||||
assert opened is not None
|
||||
assert opened.is_final_update is False
|
||||
assert opened.queue_close_after is False
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is False
|
||||
|
||||
tail = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(full, finished=True), req_state)
|
||||
assert tail is not None
|
||||
assert tail.close_only is False
|
||||
assert tail.queue_close_after is True
|
||||
assert tail.is_final_update is False
|
||||
assert tail.output.text == "远处还有办公桌和绿植。"
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is False
|
||||
|
||||
followup = plugin.partial_stage_followup(tail, req_state)
|
||||
assert followup is not None
|
||||
assert followup.is_final_update is True
|
||||
assert followup.close_only is True
|
||||
assert followup.output.text == ""
|
||||
assert req_state.prompt["additional_information"]["aura_tts_close_only"] is True
|
||||
|
||||
|
||||
def test_single_finished_sentence_is_one_non_resumable_submit() -> None:
|
||||
orchestrator, req_state = _sentence_plan_fixture()
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
sentence = "你好,我看到一个戴眼镜、穿黑T恤的男生正对着镜头说话呢。"
|
||||
plan = plugin.plan_partial_stage_output(orchestrator, 1, 0, _stage1_output(sentence, finished=True), req_state)
|
||||
assert plan is not None
|
||||
assert plan.queue_close_after is False
|
||||
assert plan.is_final_update is True
|
||||
assert plan.close_only is False
|
||||
assert plugin.partial_stage_followup(plan, req_state) is None
|
||||
|
||||
|
||||
def test_aura_draining_stages_are_declared_by_the_plugin() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
assert plugin.draining_stage_ids(stage_count=4) == frozenset({2, 3})
|
||||
assert plugin.draining_stage_ids(stage_count=2) == frozenset()
|
||||
|
||||
|
||||
def test_spoken_stage0_text_is_the_user_transcript() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
output = SimpleNamespace(
|
||||
finished=True,
|
||||
outputs=[
|
||||
SimpleNamespace(text="language Chinese<asr_text>你好", cumulative_text="language Chinese<asr_text>你好")
|
||||
],
|
||||
)
|
||||
prompt = {"additional_information": {"is_speech": True}}
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=True) == "你好"
|
||||
|
||||
|
||||
def test_vision_follow_stage0_text_is_not_shown_as_user_speech() -> None:
|
||||
plugin = AuraDuplexPlugin(_encode_audio)
|
||||
output = SimpleNamespace(finished=True, text="嗯")
|
||||
prompt = {"additional_information": {"is_speech": False}}
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=True) is None
|
||||
assert plugin.user_transcript(stage_id=1, output=output, prompt=prompt, finished=True) is None
|
||||
assert plugin.user_transcript(stage_id=0, output=output, prompt=prompt, finished=False) is None
|
||||
@@ -0,0 +1,62 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Growing Stage1 token ids must decode to the same text as one full decode."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.sentence_tts import decode_growing_token_ids
|
||||
|
||||
|
||||
def _assert_matches_full(decode, ids: list[int]) -> None:
|
||||
cache: dict[str, object] = {}
|
||||
for end in range(1, len(ids) + 1):
|
||||
got = decode_growing_token_ids(decode, ids[:end], cache)
|
||||
assert got == decode(ids[:end])
|
||||
|
||||
|
||||
def test_growing_decode_matches_full_decode_for_concat_pieces() -> None:
|
||||
vocab = {1: "你", 2: "好", 3: "。", 4: "世", 5: "界"}
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
return "".join(vocab[token_id] for token_id in token_ids)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 3, 4, 5])
|
||||
|
||||
|
||||
def test_growing_decode_matches_full_decode_when_the_previous_piece_changes() -> None:
|
||||
"""Token 9 rewrites the previous character. The tail window must reject a bad splice."""
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
chars: list[str] = []
|
||||
for token_id in token_ids:
|
||||
if token_id == 9:
|
||||
if chars:
|
||||
chars.pop()
|
||||
chars.append("X")
|
||||
else:
|
||||
chars.append(chr(96 + token_id))
|
||||
return "".join(chars)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 9, 3])
|
||||
|
||||
|
||||
def test_growing_decode_matches_wordpiece_spacing() -> None:
|
||||
vocab = {1: "hello", 2: "##world", 3: "。"}
|
||||
|
||||
def decode(token_ids: list[int], skip_special_tokens: bool = False) -> str:
|
||||
del skip_special_tokens
|
||||
parts: list[str] = []
|
||||
for index, token_id in enumerate(token_ids):
|
||||
piece = vocab[token_id]
|
||||
if piece.startswith("##"):
|
||||
parts.append(piece[2:])
|
||||
else:
|
||||
if index:
|
||||
parts.append(" ")
|
||||
parts.append(piece)
|
||||
return "".join(parts)
|
||||
|
||||
_assert_matches_full(decode, [1, 2, 3, 1])
|
||||
@@ -389,6 +389,38 @@ def test_decode_batch_preprocess_matches_decode_state_updates(mrv2):
|
||||
assert updates[1]["hidden_states"]["trailing_text"].numel() == 0
|
||||
|
||||
|
||||
def test_decode_batch_zero_fills_missing_last_hidden(monkeypatch):
|
||||
tts_pad = torch.full((1, 4), -1.0, dtype=torch.bfloat16)
|
||||
model = _make_minimal_talker(tts_pad_embed=tts_pad)
|
||||
|
||||
def fake_embed_input_ids(input_ids):
|
||||
return input_ids.to(torch.float32).reshape(-1, 1, 1).expand(-1, 1, 4)
|
||||
|
||||
model.embed_input_ids = fake_embed_input_ids
|
||||
warnings: list[tuple[object, ...]] = []
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker.logger.warning_once",
|
||||
lambda *args, **kwargs: warnings.append(args),
|
||||
)
|
||||
trailing = torch.arange(8, dtype=torch.float32).reshape(2, 4)
|
||||
|
||||
_, _, past_hidden, _, _ = model.preprocess_decode_batch(
|
||||
input_ids=torch.tensor([101], dtype=torch.long),
|
||||
req_infos=[
|
||||
{
|
||||
"text": ["hello"],
|
||||
"task_type": ["CustomVoice"],
|
||||
"hidden_states": {"trailing_text": trailing},
|
||||
"meta": {"talker_text_offset": 0},
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
assert torch.equal(past_hidden.cpu(), torch.zeros((1, 4), dtype=torch.bfloat16))
|
||||
assert len(warnings) == 1
|
||||
assert "zero-filling" in str(warnings[0][0])
|
||||
|
||||
|
||||
def _stub_text_embedding(device_param: torch.nn.Parameter):
|
||||
"""Build a lambda that emulates ``nn.Embedding`` for the ``_device()`` helper.
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -10,6 +10,9 @@ from vllm_omni.model_executor.models.qwen3_tts.prompt_embeds_builder import (
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
SILENT_TEXT,
|
||||
_estimate_tts_prompt_len_from_token_ids,
|
||||
_estimate_tts_prompt_len_official,
|
||||
_normalize_asr_transcript,
|
||||
asr2aura,
|
||||
aura2tts,
|
||||
)
|
||||
@@ -166,7 +169,7 @@ def test_aura2tts_supports_custom_voice_mode():
|
||||
assert tts_input["additional_information"]["task_type"] == ["CustomVoice"]
|
||||
assert tts_input["additional_information"]["speaker"] == ["Vivian"]
|
||||
assert "ref_audio" not in tts_input["additional_information"]
|
||||
assert len(tts_input["prompt_token_ids"]) == 14
|
||||
assert len(tts_input["prompt_token_ids"]) > 0
|
||||
|
||||
|
||||
def test_aura2tts_passes_token_ids_to_qwen3_tts_when_enabled():
|
||||
@@ -196,3 +199,109 @@ def test_aura2tts_passes_token_ids_to_qwen3_tts_when_enabled():
|
||||
|
||||
def test_aura2tts_drops_silent_response():
|
||||
assert aura2tts([_source_output(SILENT_TEXT)]) == []
|
||||
assert aura2tts([_source_output(f"{SILENT_TEXT}<|im_end|>")]) == []
|
||||
|
||||
|
||||
def test_aura2tts_customvoice_uses_official_prompt_len_not_aura_token_count():
|
||||
text = "当然可以,我正看着你呢。"
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_task_type": ["CustomVoice"],
|
||||
"tts_speaker": ["Vivian"],
|
||||
"tts_language": ["Chinese"],
|
||||
}
|
||||
}
|
||||
aura_token_ids = list(range(80))
|
||||
tts_info = {
|
||||
"task_type": ["CustomVoice"],
|
||||
"language": ["Chinese"],
|
||||
"instruct": [""],
|
||||
"text": [text],
|
||||
"speaker": ["Vivian"],
|
||||
}
|
||||
official = _estimate_tts_prompt_len_official(tts_info, task_type="CustomVoice")
|
||||
if official is None:
|
||||
pytest.skip("Qwen3-TTS tokenizer unavailable for official prompt_len")
|
||||
old_heuristic = _estimate_tts_prompt_len_from_token_ids(
|
||||
aura_token_ids,
|
||||
task_type="CustomVoice",
|
||||
language="Chinese",
|
||||
instruct="",
|
||||
)
|
||||
assert official != old_heuristic
|
||||
|
||||
[tts_input] = aura2tts(
|
||||
[_source_output(text, token_ids=aura_token_ids)],
|
||||
prompt=[prompt],
|
||||
)
|
||||
assert len(tts_input["prompt_token_ids"]) == official
|
||||
assert tts_input["additional_information"]["instruct"] == [""]
|
||||
|
||||
|
||||
def test_aura2tts_strips_im_end_from_spoken_text():
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_ref_audio": ["ref.wav"],
|
||||
"tts_ref_text": ["Reference transcript sample."],
|
||||
}
|
||||
}
|
||||
[tts_input] = aura2tts([_source_output("你好。<|im_end|>")], prompt=[prompt])
|
||||
assert tts_input["additional_information"]["text"] == ["你好。"]
|
||||
|
||||
|
||||
def test_aura2tts_does_not_treat_chinese_silence_as_special_token():
|
||||
# [沉默] is not <|silent|>; prompt/session must instruct the real token.
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"tts_ref_audio": ["ref.wav"],
|
||||
"tts_ref_text": ["Reference transcript sample."],
|
||||
}
|
||||
}
|
||||
assert len(aura2tts([_source_output("[沉默]")], prompt=[prompt])) == 1
|
||||
|
||||
|
||||
def test_normalize_asr_transcript_strips_qwen3_asr_markup() -> None:
|
||||
raw = "language Chinese<asr_text>出现《古韵》这本书的时候,提醒我。"
|
||||
assert _normalize_asr_transcript(raw) == "出现《古韵》这本书的时候,提醒我。"
|
||||
assert _normalize_asr_transcript("出现古韵这本书的时候提醒我。") == "出现古韵这本书的时候提醒我。"
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_batches_until_min_chars(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.delenv("VLLM_AURA_SENTENCE_TTS", raising=False)
|
||||
monkeypatch.delenv("VLLM_AURA_SENTENCE_TTS_MIN_CHARS", raising=False)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
state: dict[str, object] = {}
|
||||
first = "甲" * 12 + "。"
|
||||
assert next_duplex_sentence_chunk(state, first, finished=False) is None
|
||||
second = first + "乙" * 20 + "。"
|
||||
chunk = next_duplex_sentence_chunk(state, second, finished=False)
|
||||
assert chunk is not None
|
||||
assert chunk.startswith("甲" * 12)
|
||||
assert "乙" * 20 in chunk
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_holds_think_silent_and_flushes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_AURA_SENTENCE_TTS", "1")
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
assert next_duplex_sentence_chunk({}, "<think>still thinking", finished=False) is None
|
||||
assert next_duplex_sentence_chunk({}, "<|silent|>", finished=True) is None
|
||||
assert next_duplex_sentence_chunk({}, '<tool_call>{"a":1}</tool_call>', finished=False) is None
|
||||
|
||||
state: dict[str, object] = {}
|
||||
assert next_duplex_sentence_chunk(state, "你好。", finished=False) is None
|
||||
assert next_duplex_sentence_chunk(state, "你好。", finished=True) == "你好。"
|
||||
|
||||
|
||||
def test_next_duplex_sentence_chunk_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setenv("VLLM_AURA_SENTENCE_TTS", "0")
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
next_duplex_sentence_chunk,
|
||||
)
|
||||
|
||||
assert next_duplex_sentence_chunk({}, "甲" * 40 + "。", finished=False) is None
|
||||
@@ -0,0 +1,273 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Logic-equivalent checks adapted from AURA_026_p0exp stage processor tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.history import (
|
||||
drop_session_history,
|
||||
get_or_create_session_history,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.aura_omni import (
|
||||
SILENT_TEXT,
|
||||
asr2aura,
|
||||
aura2tts,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _source_output(text: str, request_id: str = "r0") -> SimpleNamespace:
|
||||
return SimpleNamespace(
|
||||
request_id=request_id,
|
||||
outputs=[SimpleNamespace(text=text, token_ids=[1, 2, 3])],
|
||||
)
|
||||
|
||||
|
||||
def test_asr2aura_carries_video_and_transcript() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_system_prompt": "sys",
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("What is happening now?")], prompt=[prompt])
|
||||
assert "What is happening now?" in next_input["prompt"]
|
||||
assert next_input["multi_modal_data"].get("image") == ["frame"]
|
||||
|
||||
|
||||
def test_asr2aura_supports_video_only_observation() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("")], prompt=[prompt])
|
||||
assert next_input["multi_modal_data"].get("image") == ["frame"]
|
||||
|
||||
|
||||
def test_asr2aura_duplex_empty_transcript_is_not_a_vision_user_turn() -> None:
|
||||
drop_session_history("duplex-vision")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-vision",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("noise")], prompt=[prompt])
|
||||
assert "[vision]" not in next_input["prompt"]
|
||||
history = get_or_create_session_history("duplex-vision")
|
||||
history.commit_turn("saw a book")
|
||||
assert all(message.get("content") != "[vision]" for message in history.messages)
|
||||
assert [message["role"] for message in history.messages] == ["assistant"]
|
||||
drop_session_history("duplex-vision")
|
||||
|
||||
|
||||
def test_asr2aura_duplex_history_videos_match_prompt_pads() -> None:
|
||||
"""Retained clips then this clip: one <|video_pad|> each, same order as mm data."""
|
||||
drop_session_history("duplex-pads")
|
||||
history = get_or_create_session_history("duplex-pads")
|
||||
history.begin_user_turn("看着手", video=("clip-a", {"fps": 2.0}))
|
||||
history.commit_turn("好的")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-pads",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"video": [("clip-b", {"fps": 2.0})]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("")], prompt=[prompt])
|
||||
text = next_input["prompt"]
|
||||
assert text.count("<|video_pad|>") == 2
|
||||
assert "clip-a" not in text and "clip-b" not in text
|
||||
assert next_input["multi_modal_data"]["video"] == [
|
||||
("clip-a", {"fps": 2.0}),
|
||||
("clip-b", {"fps": 2.0}),
|
||||
]
|
||||
assert text.index("<|video_pad|>") < text.rindex("<|im_start|>user")
|
||||
drop_session_history("duplex-pads")
|
||||
|
||||
|
||||
def test_asr2aura_duplex_uses_session_history_prefix() -> None:
|
||||
drop_session_history("duplex-hist")
|
||||
history = get_or_create_session_history("duplex-hist")
|
||||
history.begin_user_turn("prev")
|
||||
history.commit_turn("prev-answer")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-hist",
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("next question")], prompt=[prompt])
|
||||
assert "prev-answer" in next_input["prompt"]
|
||||
assert "next question" in next_input["prompt"]
|
||||
drop_session_history("duplex-hist")
|
||||
|
||||
|
||||
def test_asr2aura_vision_follow_keeps_previous_assistant_in_prefix() -> None:
|
||||
drop_session_history("duplex-watch")
|
||||
history = get_or_create_session_history("duplex-watch")
|
||||
history.begin_user_turn("盯着滑鼠")
|
||||
history.commit_turn("好的,出现的时候我会说")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-watch",
|
||||
"is_speech": False,
|
||||
"deferred_multi_modal_data": {"image": ["frame"]},
|
||||
},
|
||||
"multi_modal_data": {},
|
||||
}
|
||||
[next_input] = asr2aura([_source_output("noise")], prompt=[prompt])
|
||||
assert "好的,出现的时候我会说" in next_input["prompt"]
|
||||
drop_session_history("duplex-watch")
|
||||
|
||||
|
||||
def test_aura2tts_drops_silent_response() -> None:
|
||||
prompt = {"additional_information": {"tts_task_type": "CustomVoice"}}
|
||||
assert aura2tts([_source_output(SILENT_TEXT)], prompt=[prompt]) == []
|
||||
|
||||
|
||||
def test_aura2tts_duplex_does_not_commit_history() -> None:
|
||||
"""Stage1 history has one owner: commit_model_context. aura2tts must not write a second row."""
|
||||
drop_session_history("duplex-silent")
|
||||
history = get_or_create_session_history("duplex-silent")
|
||||
history.begin_user_turn("look")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"session_id": "duplex-silent",
|
||||
"tts_task_type": "CustomVoice",
|
||||
}
|
||||
}
|
||||
assert aura2tts([_source_output(SILENT_TEXT)], prompt=[prompt]) == []
|
||||
assert all(message.get("role") != "assistant" for message in history.messages)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
AuraDuplexPlugin(encode_audio=lambda *_a, **_k: None).commit_model_context(
|
||||
session_id="duplex-silent",
|
||||
assistant_text="只記一次",
|
||||
)
|
||||
assert [message["role"] for message in history.messages] == ["user", "assistant"]
|
||||
assert history.messages[-1]["content"] == "只記一次"
|
||||
drop_session_history("duplex-silent")
|
||||
|
||||
|
||||
def test_aura2tts_skips_history_on_sentence_partial() -> None:
|
||||
drop_session_history("duplex-partial")
|
||||
history = get_or_create_session_history("duplex-partial")
|
||||
history.begin_user_turn("look")
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_duplex": True,
|
||||
"aura_tts_partial": True,
|
||||
"session_id": "duplex-partial",
|
||||
"tts_task_type": "CustomVoice",
|
||||
"tts_speaker": "Vivian",
|
||||
}
|
||||
}
|
||||
assert len(aura2tts([_source_output("你好,这是一句测试。")], prompt=[prompt])) == 1
|
||||
assert all(message.get("role") != "assistant" for message in history.messages)
|
||||
drop_session_history("duplex-partial")
|
||||
|
||||
|
||||
def test_aura2tts_close_only_does_not_repeat_the_sentence() -> None:
|
||||
prompt = {
|
||||
"additional_information": {
|
||||
"aura_tts_partial": True,
|
||||
"aura_tts_close_only": True,
|
||||
"tts_task_type": "CustomVoice",
|
||||
"tts_speaker": "Vivian",
|
||||
}
|
||||
}
|
||||
[request] = aura2tts([_source_output("上一句不該再送。")], prompt=[prompt])
|
||||
info = request["additional_information"]
|
||||
assert info["text"] == [""]
|
||||
assert info["max_new_tokens"] == [1]
|
||||
assert request["prompt_token_ids"] == [0]
|
||||
|
||||
|
||||
def test_duplex_interception_commits_silent_history_without_aura2tts() -> None:
|
||||
"""Silent Stage1 uses DIRECT_RESPONSE; history must commit on the data-plane path."""
|
||||
from vllm.outputs import CompletionOutput
|
||||
|
||||
from vllm_omni.engine.duplex.contracts import (
|
||||
DuplexFence,
|
||||
DuplexOutputAction,
|
||||
DuplexOutputDecision,
|
||||
duplex_ephemeral_stage_request_id,
|
||||
)
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.data_plane import AuraDataPlaneSession
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
from vllm_omni.outputs.duplex import attach_duplex_output_decision
|
||||
|
||||
drop_session_history("duplex-silent-dp")
|
||||
history = get_or_create_session_history("duplex-silent-dp")
|
||||
history.begin_user_turn("look")
|
||||
fence = DuplexFence("duplex-silent-dp", epoch=0, turn_id=1)
|
||||
request_id = duplex_ephemeral_stage_request_id(fence, stage_id=1)
|
||||
output = OmniRequestOutput(
|
||||
request_id=request_id,
|
||||
finished=True,
|
||||
stage_id=1,
|
||||
outputs=[
|
||||
CompletionOutput(
|
||||
index=0,
|
||||
text=SILENT_TEXT,
|
||||
token_ids=[151669],
|
||||
cumulative_logprob=None,
|
||||
logprobs=None,
|
||||
)
|
||||
],
|
||||
)
|
||||
attach_duplex_output_decision(
|
||||
output,
|
||||
DuplexOutputDecision(
|
||||
action=DuplexOutputAction.DIRECT_RESPONSE,
|
||||
metadata={"model_listen": True, "duplex_direct_response": True},
|
||||
),
|
||||
)
|
||||
plane = AuraDataPlaneSession(encode_audio=lambda *_a, **_k: None)
|
||||
events = list(plane.project_output(output))
|
||||
assert events and events[0].get("silent") is True
|
||||
assert events[0].get("model_context_text") == SILENT_TEXT
|
||||
assert events[0].get("abort_data_plane_request") is True
|
||||
assert history.pending_user == "look"
|
||||
from vllm_omni.model_executor.models.aura_omni.duplex.plugin import AuraDuplexPlugin
|
||||
|
||||
AuraDuplexPlugin(encode_audio=lambda *_a, **_k: None).commit_model_context(
|
||||
session_id="duplex-silent-dp",
|
||||
assistant_text=str(events[0]["model_context_text"]),
|
||||
)
|
||||
assert history.pending_user is None
|
||||
assert history.messages[-1]["content"] == SILENT_TEXT
|
||||
drop_session_history("duplex-silent-dp")
|
||||
|
||||
|
||||
def test_proactive_silent_ticks_do_not_evict_a_real_turn() -> None:
|
||||
drop_session_history("duplex-silent-ticks")
|
||||
history = get_or_create_session_history("duplex-silent-ticks")
|
||||
history.begin_user_turn("真正的問題")
|
||||
history.commit_turn("真正的回答")
|
||||
for _ in range(20):
|
||||
history.begin_user_turn("")
|
||||
history.commit_turn("<|silent|>")
|
||||
assert history.messages[0]["content"] == "真正的問題"
|
||||
assert history.messages[1]["content"] == "真正的回答"
|
||||
assert len(history.messages) == 2
|
||||
drop_session_history("duplex-silent-ticks")
|
||||
@@ -11,6 +11,7 @@ which a re-implementation cannot satisfy.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import dataclasses
|
||||
|
||||
import pytest
|
||||
@@ -78,7 +79,9 @@ def test_a_duplex_command_error_is_a_realtime_protocol_error() -> None:
|
||||
|
||||
def test_the_duplex_append_command_is_built_from_the_shared_decoder() -> None:
|
||||
defaults = protocol.RealtimeInputDefaults()
|
||||
event = {"event_id": "event_1", "audio": "", "format": "pcm16", "duration_ms": 40}
|
||||
# Empty ``audio`` is rejected (need bytes and/or video_frames); use silence.
|
||||
silence = base64.b64encode(b"\x00\x00").decode("ascii")
|
||||
event = {"event_id": "event_1", "audio": silence, "format": "pcm16", "duration_ms": 40}
|
||||
|
||||
decoded = protocol.decode_audio_append(event, defaults=defaults)
|
||||
command = duplex_codec.build_append_audio(event, defaults=defaults)
|
||||
|
||||
Reference in new issue
Block a user