[Full Duplex] Feat: Support Full-Duplex realtime runtime & add MiniCPM-o 4.5 demo (#3907)
Signed-off-by: Sy03 <1370724210@qq.com> Signed-off-by: lishunyang12 <lishunyang03@gmail.com> Signed-off-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: lishunyang12 <lishunyang03@gmail.com> Co-authored-by: Yueqian Lin <linyueqian@outlook.com> Co-authored-by: StormMelody <22371184@zju.edu.cn> Co-authored-by: Gao Han <hgaoaf@connect.ust.hk> Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
142 files changed
+48389
-1013
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import pytest
|
||||
import torch
|
||||
from pytest_mock import MockerFixture
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.engine import EngineCoreRequest
|
||||
@@ -64,6 +65,48 @@ def test_build_add_request_message_preserves_additional_information(mocker: Mock
|
||||
output_processor.add_request.assert_not_called()
|
||||
|
||||
|
||||
def test_build_add_request_message_preserves_model_intermediate_buffer(mocker: MockerFixture):
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
params = SamplingParams(max_tokens=8)
|
||||
engine.default_sampling_params_list = [params]
|
||||
engine.stage_metadata = [StageRuntimeInfo(final_output=False, final_output_type=None, stage_type="llm")]
|
||||
engine.supported_tasks = ("speech",)
|
||||
|
||||
input_processor = mocker.Mock()
|
||||
input_processor.process_inputs.return_value = _make_engine_core_request()
|
||||
engine.input_processor = input_processor
|
||||
|
||||
output_processor = mocker.Mock()
|
||||
engine.output_processors = [output_processor]
|
||||
|
||||
hidden = torch.arange(6, dtype=torch.float32).reshape(2, 3)
|
||||
prompt = {
|
||||
"prompt_token_ids": [1, 1, 1],
|
||||
"model_intermediate_buffer": {
|
||||
"ids": {"tts": [11, 12]},
|
||||
"hidden_states": {"tts": hidden},
|
||||
},
|
||||
}
|
||||
|
||||
msg = engine._build_add_request_message(
|
||||
request_id="req-1",
|
||||
prompt=prompt,
|
||||
sampling_params_list=[params],
|
||||
final_stage_id=0,
|
||||
arrival_time=0.0,
|
||||
)
|
||||
|
||||
request = msg.prompt
|
||||
assert isinstance(request, OmniEngineCoreRequest)
|
||||
assert request.additional_information is not None
|
||||
assert request.additional_information.entries["global_request_id"].list_data == ["req-1"]
|
||||
assert request.additional_information.entries["omni_final_stage_id"].scalar_data == 0
|
||||
assert isinstance(request.model_intermediate_buffer, dict)
|
||||
info = request.model_intermediate_buffer
|
||||
assert info["ids"]["tts"] == [11, 12]
|
||||
assert torch.equal(info["hidden_states"]["tts"], hidden)
|
||||
|
||||
|
||||
def test_build_add_request_message_with_resumable_streaming(mocker: MockerFixture):
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
params = SamplingParams(max_tokens=8)
|
||||
|
||||
@@ -4,13 +4,33 @@ Focuses on the critical behavior: when the orchestrator thread dies,
|
||||
subsequent attempts to collect output raise RuntimeError.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import queue
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from vllm_omni.engine.async_engine_utils import weak_shutdown_async_omni_engine
|
||||
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
|
||||
from vllm_omni.engine.messages import ErrorMessage, OutputMessage
|
||||
from vllm_omni.engine.messages import (
|
||||
CollectiveRPCResultMessage,
|
||||
ErrorMessage,
|
||||
OutputMessage,
|
||||
)
|
||||
from vllm_omni.engine.rpc_result_router import CorrelatedRpcClient
|
||||
from vllm_omni.experimental.fullduplex.engine.duplex_control_client import (
|
||||
DuplexControlClient,
|
||||
DuplexControlRequestError,
|
||||
)
|
||||
from vllm_omni.experimental.fullduplex.engine.messages import (
|
||||
AppendDuplexInputMessage,
|
||||
DuplexControlResultMessage,
|
||||
DuplexFence,
|
||||
SignalDuplexTurnMessage,
|
||||
)
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
@@ -26,6 +46,33 @@ def _make_engine(output_queue, mocker: MockerFixture, *, thread_alive: bool = Tr
|
||||
return engine
|
||||
|
||||
|
||||
def test_weak_shutdown_closes_rpc_router_before_joining_orchestrator(mocker: MockerFixture):
|
||||
request_queue = mocker.MagicMock()
|
||||
output_queue = mocker.MagicMock()
|
||||
rpc_output_queue = mocker.MagicMock()
|
||||
router = mocker.MagicMock()
|
||||
orchestrator_thread = mocker.MagicMock()
|
||||
orchestrator_thread.is_alive.return_value = True
|
||||
|
||||
def assert_router_closed_before_join(*args, **kwargs):
|
||||
router.close.assert_called_once_with()
|
||||
|
||||
orchestrator_thread.join.side_effect = assert_router_closed_before_join
|
||||
|
||||
weak_shutdown_async_omni_engine(
|
||||
orchestrator_thread,
|
||||
request_queue,
|
||||
output_queue,
|
||||
rpc_output_queue,
|
||||
router,
|
||||
)
|
||||
|
||||
request_queue.sync_q.put.assert_called_once()
|
||||
assert request_queue.sync_q.put.call_args.kwargs["timeout"] > 0
|
||||
orchestrator_thread.join.assert_called_once()
|
||||
assert orchestrator_thread.join.call_args.kwargs["timeout"] > 0
|
||||
|
||||
|
||||
def test_try_get_output_raises_after_orchestrator_dies(mocker: MockerFixture):
|
||||
"""Draining remaining results then hitting an empty queue with a dead
|
||||
orchestrator must raise RuntimeError so callers know the pipeline is gone."""
|
||||
@@ -56,18 +103,17 @@ def test_try_get_output_raises_after_orchestrator_dies(mocker: MockerFixture):
|
||||
@pytest.mark.asyncio
|
||||
async def test_try_get_output_async_raises_after_orchestrator_dies(mocker: MockerFixture):
|
||||
"""Same scenario as above but for the async variant."""
|
||||
mock_queue = mocker.MagicMock()
|
||||
mock_queue.sync_q.get_nowait.side_effect = [
|
||||
raw_queue = queue.Queue()
|
||||
raw_queue.put_nowait(
|
||||
OutputMessage(
|
||||
request_id="r1",
|
||||
stage_id=0,
|
||||
engine_outputs=OmniRequestOutput(request_id="r1"),
|
||||
finished=False,
|
||||
),
|
||||
queue.Empty,
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
engine = _make_engine(mock_queue, mocker, thread_alive=True)
|
||||
engine = _make_engine(SimpleNamespace(sync_q=raw_queue), mocker, thread_alive=True)
|
||||
|
||||
assert (await engine.try_get_output_async()).request_id == "r1"
|
||||
|
||||
@@ -102,12 +148,495 @@ async def test_fatal_error_message_surfaces_through_try_get_output_async(mocker:
|
||||
"""Async variant of the fatal error message test."""
|
||||
fatal_msg = ErrorMessage(error="Orchestrator thread crashed", fatal=True)
|
||||
|
||||
mock_queue = mocker.MagicMock()
|
||||
mock_queue.sync_q.get_nowait.return_value = fatal_msg
|
||||
raw_queue = queue.Queue()
|
||||
raw_queue.put_nowait(fatal_msg)
|
||||
|
||||
engine = _make_engine(mock_queue, mocker, thread_alive=False)
|
||||
engine = _make_engine(SimpleNamespace(sync_q=raw_queue), mocker, thread_alive=False)
|
||||
|
||||
msg = await engine.try_get_output_async()
|
||||
assert msg is not None
|
||||
assert msg.type == "error"
|
||||
assert msg.fatal is True
|
||||
|
||||
|
||||
def test_output_remains_on_shared_output_path(mocker: MockerFixture):
|
||||
raw_queue = queue.Queue()
|
||||
raw_queue.put_nowait(
|
||||
OutputMessage(
|
||||
request_id="legacy-duplex-request",
|
||||
stage_id=0,
|
||||
engine_outputs=OmniRequestOutput(request_id="legacy-duplex-request"),
|
||||
finished=False,
|
||||
)
|
||||
)
|
||||
engine = _make_engine(SimpleNamespace(sync_q=raw_queue), mocker)
|
||||
|
||||
output = engine.try_get_output(timeout=0.01)
|
||||
|
||||
assert output.request_id == "legacy-duplex-request"
|
||||
|
||||
|
||||
def test_duplex_control_client_uses_engine_owned_correlated_transport():
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine._duplex_control_client = None
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(queue.Queue(), queue.Queue())
|
||||
|
||||
try:
|
||||
client = engine._get_duplex_control_client()
|
||||
|
||||
assert isinstance(client, DuplexControlClient)
|
||||
assert client._transport is engine._correlated_rpc_client
|
||||
assert not hasattr(engine, "_submit_rpc_and_wait")
|
||||
finally:
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_duplex_control_api_requires_explicit_fence():
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
|
||||
with pytest.raises(TypeError, match="fence"):
|
||||
engine.open_duplex_session("sid")
|
||||
with pytest.raises(TypeError, match="fence"):
|
||||
engine.append_duplex_input("sid", mode="append_audio_chunk", payload={})
|
||||
with pytest.raises(TypeError, match="fence"):
|
||||
engine.signal_duplex_turn("sid", event="turn.end")
|
||||
with pytest.raises(TypeError, match="fence"):
|
||||
engine.close_duplex_session("sid")
|
||||
|
||||
|
||||
def test_open_duplex_session_waits_for_control_ack(mocker: MockerFixture):
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
control_result = DuplexControlResultMessage(
|
||||
control_id="ctrl-1",
|
||||
fence=DuplexFence("sid"),
|
||||
operation="open",
|
||||
session_id="sid",
|
||||
ok=False,
|
||||
stage_results=[{"stage_id": 0, "replica_id": 0, "result": {"supported": False}}],
|
||||
unsupported_count=1,
|
||||
error_count=0,
|
||||
)
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
mocker.patch("vllm_omni.engine.async_omni_engine.uuid.uuid4", return_value=SimpleNamespace(hex="ctrl-1"))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(engine.open_duplex_session, "sid", fence=DuplexFence("sid"), timeout=1)
|
||||
msg = request_q.get(timeout=1)
|
||||
assert msg.type == "open_duplex_session"
|
||||
assert msg.control_id == "ctrl-1"
|
||||
rpc_q.put(control_result)
|
||||
with pytest.raises(DuplexControlRequestError) as exc_info:
|
||||
pending.result(timeout=1)
|
||||
|
||||
assert exc_info.value.result["unsupported_count"] == 1
|
||||
assert exc_info.value.result["stage_results"][0]["result"]["supported"] is False
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_signal_duplex_turn_message_carries_next_fence(mocker: MockerFixture):
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
cancelled_fence = DuplexFence("sid-cancel", epoch=4, turn_id=2)
|
||||
next_fence = DuplexFence("sid-cancel", epoch=5, turn_id=2)
|
||||
control_result = DuplexControlResultMessage(
|
||||
control_id="ctrl-signal",
|
||||
fence=cancelled_fence,
|
||||
operation="signal",
|
||||
session_id="sid-cancel",
|
||||
ok=True,
|
||||
stage_results=[],
|
||||
)
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
mocker.patch("vllm_omni.engine.async_omni_engine.uuid.uuid4", return_value=SimpleNamespace(hex="ctrl-signal"))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(
|
||||
engine.signal_duplex_turn,
|
||||
"sid-cancel",
|
||||
event="input.cancel",
|
||||
fence=cancelled_fence,
|
||||
next_fence=next_fence,
|
||||
session_config={"temperature": 0.0},
|
||||
timeout=1,
|
||||
)
|
||||
msg = request_q.get(timeout=1)
|
||||
assert isinstance(msg, SignalDuplexTurnMessage)
|
||||
assert msg.fence == cancelled_fence
|
||||
assert msg.next_fence == next_fence
|
||||
assert msg.session_config == {"temperature": 0.0}
|
||||
rpc_q.put(control_result)
|
||||
assert pending.result(timeout=1)["ok"] is True
|
||||
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_async_append_does_not_stop_executor_callable(mocker: MockerFixture):
|
||||
entered = threading.Event()
|
||||
release = threading.Event()
|
||||
completed = threading.Event()
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
|
||||
def blocking_append(*args, **kwargs):
|
||||
del args, kwargs
|
||||
entered.set()
|
||||
release.wait(timeout=1)
|
||||
completed.set()
|
||||
return {}
|
||||
|
||||
mocker.patch.object(engine, "append_duplex_input", side_effect=blocking_append)
|
||||
task = asyncio.create_task(
|
||||
engine.append_duplex_input_async(
|
||||
"sid-executor-cancel",
|
||||
mode="append_audio_chunk",
|
||||
payload=b"audio",
|
||||
fence=DuplexFence("sid-executor-cancel"),
|
||||
)
|
||||
)
|
||||
assert await asyncio.to_thread(entered.wait, 1)
|
||||
|
||||
task.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await task
|
||||
release.set()
|
||||
|
||||
assert await asyncio.to_thread(completed.wait, 1)
|
||||
|
||||
|
||||
def test_duplex_controls_route_out_of_order_without_global_lock():
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
first_fence = DuplexFence("sid", epoch=1)
|
||||
second_fence = DuplexFence("sid", epoch=2)
|
||||
first = AppendDuplexInputMessage(
|
||||
control_id="first",
|
||||
fence=first_fence,
|
||||
session_id="sid",
|
||||
expected_epoch=1,
|
||||
mode="audio",
|
||||
payload=b"first",
|
||||
)
|
||||
second = AppendDuplexInputMessage(
|
||||
control_id="second",
|
||||
fence=second_fence,
|
||||
session_id="sid",
|
||||
expected_epoch=2,
|
||||
mode="audio",
|
||||
payload=b"second",
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
client = engine._get_duplex_control_client()
|
||||
first_result = executor.submit(client.execute, first, timeout=1)
|
||||
second_result = executor.submit(client.execute, second, timeout=1)
|
||||
submitted = {request_q.get(timeout=1).control_id, request_q.get(timeout=1).control_id}
|
||||
assert submitted == {"first", "second"}
|
||||
rpc_q.put(
|
||||
DuplexControlResultMessage(
|
||||
control_id="second",
|
||||
fence=second_fence,
|
||||
operation="append",
|
||||
session_id="sid",
|
||||
ok=True,
|
||||
stage_results=[],
|
||||
)
|
||||
)
|
||||
rpc_q.put(
|
||||
DuplexControlResultMessage(
|
||||
control_id="first",
|
||||
fence=first_fence,
|
||||
operation="append",
|
||||
session_id="sid",
|
||||
ok=True,
|
||||
stage_results=[],
|
||||
)
|
||||
)
|
||||
|
||||
assert first_result.result(timeout=1)["fence"] == first_fence
|
||||
assert second_result.result(timeout=1)["fence"] == second_fence
|
||||
|
||||
assert not hasattr(engine, "_rpc_lock")
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_terminal_rpc_router_rejects_without_enqueuing_new_control():
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
pending_message = AppendDuplexInputMessage(
|
||||
control_id="pending",
|
||||
fence=DuplexFence("sid"),
|
||||
session_id="sid",
|
||||
mode="audio",
|
||||
payload=b"audio",
|
||||
)
|
||||
message = AppendDuplexInputMessage(
|
||||
control_id="after-fatal",
|
||||
fence=DuplexFence("sid"),
|
||||
session_id="sid",
|
||||
mode="audio",
|
||||
payload=b"audio",
|
||||
)
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(engine._get_duplex_control_client().execute, pending_message, timeout=1)
|
||||
assert request_q.get(timeout=1).control_id == "pending"
|
||||
rpc_q.put(ErrorMessage(error="orchestrator failed", fatal=True))
|
||||
with pytest.raises(RuntimeError, match="orchestrator failed"):
|
||||
pending.result(timeout=1)
|
||||
|
||||
with pytest.raises(RuntimeError, match="orchestrator failed"):
|
||||
engine._get_duplex_control_client().execute(message, timeout=1)
|
||||
|
||||
assert request_q.empty()
|
||||
finally:
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_collective_and_duplex_results_share_router_without_swapping(mocker: MockerFixture):
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
fence = DuplexFence("sid")
|
||||
duplex = AppendDuplexInputMessage(
|
||||
control_id="duplex-control",
|
||||
fence=fence,
|
||||
session_id="sid",
|
||||
mode="audio",
|
||||
payload=b"audio",
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.async_omni_engine.uuid.uuid4", return_value=SimpleNamespace(hex="collective-rpc"))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||
duplex_result = executor.submit(engine._get_duplex_control_client().execute, duplex, timeout=1)
|
||||
collective_result = executor.submit(engine.collective_rpc, "health", timeout=1)
|
||||
submitted_types = {request_q.get(timeout=1).type, request_q.get(timeout=1).type}
|
||||
assert submitted_types == {"append_duplex_input", "collective_rpc"}
|
||||
rpc_q.put(
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id="collective-rpc",
|
||||
method="health",
|
||||
stage_ids=[0],
|
||||
results=["healthy"],
|
||||
)
|
||||
)
|
||||
rpc_q.put(
|
||||
DuplexControlResultMessage(
|
||||
control_id="duplex-control",
|
||||
fence=fence,
|
||||
operation="append",
|
||||
session_id="sid",
|
||||
ok=True,
|
||||
stage_results=[],
|
||||
)
|
||||
)
|
||||
|
||||
assert collective_result.result(timeout=1) == ["healthy"]
|
||||
assert duplex_result.result(timeout=1)["fence"] == fence
|
||||
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_collective_rpc_preserves_request_queue_backpressure(mocker: MockerFixture):
|
||||
class SignallingQueue(queue.Queue):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(maxsize=1)
|
||||
self.put_attempted = threading.Event()
|
||||
|
||||
def put(self, item, block=True, timeout=None):
|
||||
self.put_attempted.set()
|
||||
return super().put(item, block=block, timeout=timeout)
|
||||
|
||||
request_q = SignallingQueue()
|
||||
request_q.put("queue-is-full")
|
||||
request_q.put_attempted.clear()
|
||||
rpc_q = queue.Queue()
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
mocker.patch("vllm_omni.engine.async_omni_engine.uuid.uuid4", return_value=SimpleNamespace(hex="blocked-rpc"))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(engine.collective_rpc, "health", timeout=1)
|
||||
assert request_q.put_attempted.wait(timeout=1)
|
||||
assert not pending.done()
|
||||
|
||||
assert request_q.get(timeout=1) == "queue-is-full"
|
||||
assert request_q.get(timeout=1).rpc_id == "blocked-rpc"
|
||||
rpc_q.put(
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id="blocked-rpc",
|
||||
method="health",
|
||||
stage_ids=[0],
|
||||
results=["healthy"],
|
||||
)
|
||||
)
|
||||
assert pending.result(timeout=1) == ["healthy"]
|
||||
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_open_duplex_session_raises_on_stage_control_error(mocker: MockerFixture):
|
||||
request_q = queue.Queue()
|
||||
rpc_q = queue.Queue()
|
||||
control_result = DuplexControlResultMessage(
|
||||
control_id="ctrl-error",
|
||||
fence=DuplexFence("sid"),
|
||||
operation="open",
|
||||
session_id="sid",
|
||||
ok=False,
|
||||
stage_results=[{"stage_id": 0, "replica_id": 0, "result": {"supported": False, "error": "boom"}}],
|
||||
unsupported_count=1,
|
||||
error_count=1,
|
||||
)
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine.request_queue = SimpleNamespace(sync_q=request_q)
|
||||
engine.rpc_output_queue = SimpleNamespace(sync_q=rpc_q)
|
||||
engine._correlated_rpc_client = CorrelatedRpcClient(request_q, rpc_q)
|
||||
engine._duplex_control_client = None
|
||||
mocker.patch("vllm_omni.engine.async_omni_engine.uuid.uuid4", return_value=SimpleNamespace(hex="ctrl-error"))
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(engine.open_duplex_session, "sid", fence=DuplexFence("sid"), timeout=1)
|
||||
request_q.get(timeout=1)
|
||||
rpc_q.put(control_result)
|
||||
with pytest.raises(RuntimeError, match="duplex open failed"):
|
||||
pending.result(timeout=1)
|
||||
engine._correlated_rpc_client.close()
|
||||
|
||||
|
||||
def test_shutdown_does_not_race_runtime_cleanup_with_live_orchestrator(mocker: MockerFixture):
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine._shutdown_called = False
|
||||
engine._weak_finalizer = None
|
||||
engine.request_queue = mocker.MagicMock()
|
||||
engine.request_queue.sync_q.put.side_effect = queue.Full
|
||||
engine.output_queue = mocker.MagicMock()
|
||||
engine.rpc_output_queue = mocker.MagicMock()
|
||||
engine._correlated_rpc_client = mocker.MagicMock()
|
||||
engine.orchestrator_thread = mocker.MagicMock()
|
||||
engine.orchestrator_thread.is_alive.return_value = True
|
||||
engine._runtime = mocker.MagicMock()
|
||||
|
||||
engine.shutdown()
|
||||
|
||||
engine.request_queue.sync_q.put.assert_called_once()
|
||||
assert engine.request_queue.sync_q.put.call_args.kwargs["timeout"] > 0
|
||||
assert engine.orchestrator_thread.join.call_args_list[0].kwargs["timeout"] > 0
|
||||
engine._correlated_rpc_client.close.assert_called_once_with()
|
||||
engine.request_queue.close.assert_called_once_with()
|
||||
engine.output_queue.close.assert_called_once_with()
|
||||
engine.rpc_output_queue.close.assert_called_once_with()
|
||||
engine._runtime.shutdown.assert_not_called()
|
||||
|
||||
|
||||
def test_shutdown_releases_runtime_after_orchestrator_stops(mocker: MockerFixture):
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine._shutdown_called = False
|
||||
engine._weak_finalizer = None
|
||||
engine.request_queue = mocker.MagicMock()
|
||||
engine.output_queue = mocker.MagicMock()
|
||||
engine.rpc_output_queue = mocker.MagicMock()
|
||||
engine._correlated_rpc_client = mocker.MagicMock()
|
||||
engine.orchestrator_thread = mocker.MagicMock()
|
||||
engine.orchestrator_thread.is_alive.side_effect = [True, False]
|
||||
engine._runtime = mocker.MagicMock()
|
||||
|
||||
engine.shutdown()
|
||||
|
||||
engine.orchestrator_thread.join.assert_called_once()
|
||||
engine._runtime.shutdown.assert_called_once_with()
|
||||
|
||||
|
||||
def test_shutdown_defers_runtime_release_until_live_orchestrator_stops(mocker: MockerFixture):
|
||||
orchestrator_stopped = threading.Event()
|
||||
runtime_released = threading.Event()
|
||||
|
||||
class ControllableOrchestratorThread:
|
||||
def __init__(self) -> None:
|
||||
self.join_timeouts: list[float | None] = []
|
||||
|
||||
def is_alive(self) -> bool:
|
||||
return not orchestrator_stopped.is_set()
|
||||
|
||||
def join(self, timeout: float | None = None) -> None:
|
||||
self.join_timeouts.append(timeout)
|
||||
if timeout is None:
|
||||
orchestrator_stopped.wait()
|
||||
|
||||
engine = object.__new__(AsyncOmniEngine)
|
||||
engine._shutdown_called = False
|
||||
engine._weak_finalizer = None
|
||||
engine.request_queue = mocker.MagicMock()
|
||||
engine.output_queue = mocker.MagicMock()
|
||||
engine.rpc_output_queue = mocker.MagicMock()
|
||||
engine._correlated_rpc_client = mocker.MagicMock()
|
||||
engine.orchestrator_thread = ControllableOrchestratorThread()
|
||||
engine._runtime = mocker.MagicMock()
|
||||
engine._runtime.shutdown.side_effect = runtime_released.set
|
||||
|
||||
try:
|
||||
engine.shutdown()
|
||||
|
||||
engine._runtime.shutdown.assert_not_called()
|
||||
orchestrator_stopped.set()
|
||||
assert runtime_released.wait(timeout=1)
|
||||
engine._runtime.shutdown.assert_called_once_with()
|
||||
assert engine.orchestrator_thread.join_timeouts[0] is not None
|
||||
assert engine.orchestrator_thread.join_timeouts[-1] is None
|
||||
finally:
|
||||
orchestrator_stopped.set()
|
||||
|
||||
|
||||
def test_weak_shutdown_is_bounded_when_request_queue_is_full(mocker: MockerFixture):
|
||||
request_queue = mocker.MagicMock()
|
||||
request_queue.sync_q.put.side_effect = queue.Full
|
||||
output_queue = mocker.MagicMock()
|
||||
rpc_output_queue = mocker.MagicMock()
|
||||
router = mocker.MagicMock()
|
||||
orchestrator_thread = mocker.MagicMock()
|
||||
orchestrator_thread.is_alive.return_value = True
|
||||
|
||||
weak_shutdown_async_omni_engine(
|
||||
orchestrator_thread,
|
||||
request_queue,
|
||||
output_queue,
|
||||
rpc_output_queue,
|
||||
router,
|
||||
)
|
||||
|
||||
request_queue.sync_q.put.assert_called_once()
|
||||
assert request_queue.sync_q.put.call_args.kwargs["timeout"] > 0
|
||||
orchestrator_thread.join.assert_called_once()
|
||||
assert orchestrator_thread.join.call_args.kwargs["timeout"] > 0
|
||||
request_queue.close.assert_called_once_with()
|
||||
output_queue.close.assert_called_once_with()
|
||||
rpc_output_queue.close.assert_called_once_with()
|
||||
@@ -0,0 +1,104 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.messages import (
|
||||
CollectiveRPCRequestMessage,
|
||||
CollectiveRPCResultMessage,
|
||||
ErrorMessage,
|
||||
)
|
||||
from vllm_omni.engine.rpc_result_router import CorrelatedRpcClient
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _request(rpc_id: str) -> CollectiveRPCRequestMessage:
|
||||
return CollectiveRPCRequestMessage(
|
||||
rpc_id=rpc_id,
|
||||
method="health",
|
||||
timeout=1,
|
||||
args=(),
|
||||
kwargs={},
|
||||
stage_ids=None,
|
||||
)
|
||||
|
||||
|
||||
def test_correlated_rpc_client_unregisters_timeout_before_late_result() -> None:
|
||||
request_queue: queue.Queue = queue.Queue()
|
||||
result_queue: queue.Queue = queue.Queue()
|
||||
client = CorrelatedRpcClient(request_queue, result_queue)
|
||||
|
||||
try:
|
||||
with pytest.raises(TimeoutError, match="first timed out"):
|
||||
client.execute(
|
||||
("collective", "first"),
|
||||
_request("first"),
|
||||
timeout=0.01,
|
||||
timeout_message="first timed out",
|
||||
)
|
||||
assert request_queue.get_nowait().rpc_id == "first"
|
||||
|
||||
result_queue.put(
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id="first",
|
||||
method="health",
|
||||
stage_ids=[0],
|
||||
results=["late"],
|
||||
)
|
||||
)
|
||||
result_queue.put(
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id="second",
|
||||
method="health",
|
||||
stage_ids=[0],
|
||||
results=["current"],
|
||||
)
|
||||
)
|
||||
current = client.execute(
|
||||
("collective", "second"),
|
||||
_request("second"),
|
||||
timeout=1,
|
||||
timeout_message="second timed out",
|
||||
)
|
||||
|
||||
assert isinstance(current, CollectiveRPCResultMessage)
|
||||
assert current.results == ["current"]
|
||||
finally:
|
||||
client.close()
|
||||
|
||||
|
||||
def test_correlated_rpc_client_rejects_after_fatal_without_enqueuing() -> None:
|
||||
request_queue: queue.Queue = queue.Queue()
|
||||
result_queue: queue.Queue = queue.Queue()
|
||||
client = CorrelatedRpcClient(request_queue, result_queue)
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as executor:
|
||||
pending = executor.submit(
|
||||
client.execute,
|
||||
("collective", "pending"),
|
||||
_request("pending"),
|
||||
timeout=1,
|
||||
timeout_message="unexpected timeout",
|
||||
)
|
||||
assert request_queue.get(timeout=1).rpc_id == "pending"
|
||||
result_queue.put(ErrorMessage(error="orchestrator failed", fatal=True))
|
||||
with pytest.raises(RuntimeError, match="orchestrator failed"):
|
||||
pending.result(timeout=1)
|
||||
|
||||
with pytest.raises(RuntimeError, match="orchestrator failed"):
|
||||
client.execute(
|
||||
("collective", "after-fatal"),
|
||||
_request("after-fatal"),
|
||||
timeout=1,
|
||||
timeout_message="unexpected timeout",
|
||||
)
|
||||
assert request_queue.empty()
|
||||
finally:
|
||||
client.close()
|
||||
@@ -0,0 +1,102 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
REPO_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _assert_isolated_import_succeeds(script: str) -> None:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-c", script],
|
||||
cwd=REPO_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_stable_engine_imports_do_not_load_experimental_duplex() -> None:
|
||||
_assert_isolated_import_succeeds("""
|
||||
import sys
|
||||
|
||||
import vllm_omni.engine.async_omni_engine
|
||||
import vllm_omni.engine.orchestrator
|
||||
import vllm_omni.entrypoints.async_omni
|
||||
|
||||
loaded = sorted(
|
||||
name
|
||||
for name in sys.modules
|
||||
if name == "vllm_omni.experimental.fullduplex"
|
||||
or name.startswith("vllm_omni.experimental.fullduplex.")
|
||||
)
|
||||
if loaded:
|
||||
raise SystemExit("stable imports loaded experimental duplex: " + ", ".join(loaded))
|
||||
""")
|
||||
|
||||
|
||||
def test_stable_engine_does_not_expose_duplex_contract_modules() -> None:
|
||||
_assert_isolated_import_succeeds("""
|
||||
import importlib.util
|
||||
|
||||
from vllm_omni.engine import messages
|
||||
|
||||
legacy_modules = (
|
||||
"vllm_omni.engine.duplex_contracts",
|
||||
"vllm_omni.engine.duplex_lease",
|
||||
"vllm_omni.engine.resumable",
|
||||
)
|
||||
present = [name for name in legacy_modules if importlib.util.find_spec(name) is not None]
|
||||
if present:
|
||||
raise SystemExit("stable duplex modules still exist: " + ", ".join(present))
|
||||
|
||||
duplex_exports = sorted(name for name in vars(messages) if name.startswith("Duplex"))
|
||||
if duplex_exports:
|
||||
raise SystemExit("stable messages still expose duplex contracts: " + ", ".join(duplex_exports))
|
||||
""")
|
||||
|
||||
|
||||
def test_stable_outputs_do_not_declare_duplex_decision_field() -> None:
|
||||
_assert_isolated_import_succeeds("""
|
||||
import dataclasses
|
||||
|
||||
from vllm_omni.outputs import OmniRequestOutput
|
||||
|
||||
fields = {field.name for field in dataclasses.fields(OmniRequestOutput)}
|
||||
if "duplex_output_decision" in fields:
|
||||
raise SystemExit("stable output declares duplex_output_decision")
|
||||
""")
|
||||
|
||||
|
||||
def test_stable_model_executor_does_not_expose_duplex_helper_module() -> None:
|
||||
_assert_isolated_import_succeeds("""
|
||||
import importlib.util
|
||||
|
||||
if importlib.util.find_spec("vllm_omni.model_executor.duplex") is not None:
|
||||
raise SystemExit("stable model_executor still exposes duplex helper module")
|
||||
""")
|
||||
|
||||
|
||||
def test_runtime_package_does_not_bundle_the_browser_demo() -> None:
|
||||
assert not (REPO_ROOT / "vllm_omni" / "experimental" / "fullduplex" / "web").exists()
|
||||
|
||||
|
||||
def test_experimental_engine_uses_canonical_contract_module_names() -> None:
|
||||
engine_dir = REPO_ROOT / "vllm_omni" / "experimental" / "fullduplex" / "engine"
|
||||
core_dir = REPO_ROOT / "vllm_omni" / "experimental" / "fullduplex" / "core"
|
||||
|
||||
assert (engine_dir / "contracts.py").is_file()
|
||||
assert (engine_dir / "lease.py").is_file()
|
||||
assert (engine_dir / "messages.py").is_file()
|
||||
assert not (engine_dir / "duplex_lease.py").exists()
|
||||
assert not (engine_dir / "duplex_types.py").exists()
|
||||
assert not (core_dir / "identity.py").exists()
|
||||
@@ -11,6 +11,7 @@ import pytest
|
||||
|
||||
from vllm_omni.distributed.omni_coordinator.messages import ReplicaStatus
|
||||
from vllm_omni.engine.membership_controller import MembershipController
|
||||
from vllm_omni.engine.stage_pool import StagePool
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -45,10 +46,10 @@ class FakePool:
|
||||
def attach_load_balancer(self, lb):
|
||||
self.lb = lb
|
||||
|
||||
def add_client(self, input_addr, client):
|
||||
self.added.append((input_addr, client))
|
||||
def add_client(self, input_addr, client, *, replica_id=None):
|
||||
self.added.append((input_addr, client, replica_id))
|
||||
self.clients.append(client)
|
||||
return len(self.clients) - 1
|
||||
return len(self.clients) - 1 if replica_id is None else replica_id
|
||||
|
||||
def invalidate_addr(self, input_addr):
|
||||
self.invalidated.append(input_addr)
|
||||
@@ -155,4 +156,35 @@ async def test_do_register_offloads_remote_factory(monkeypatch):
|
||||
|
||||
assert factory_thread_ids
|
||||
assert factory_thread_ids[0] != threading.get_ident()
|
||||
assert pool.added[0][0] == "tcp://stage-0-replica-1"
|
||||
assert pool.added[0] == ("tcp://stage-0-replica-1", pool.clients[0], 1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unregister_then_register_restores_coordinator_replica_slot(monkeypatch):
|
||||
class Client:
|
||||
def __init__(self, input_addr: str) -> None:
|
||||
self.client_addresses = {"input_address": input_addr}
|
||||
self.shutdown_calls = 0
|
||||
|
||||
def shutdown(self) -> None:
|
||||
self.shutdown_calls += 1
|
||||
|
||||
old_clients = [Client("tcp://old-0"), Client("tcp://old-1")]
|
||||
replacement = Client("tcp://new-1")
|
||||
pool = StagePool(0, old_clients)
|
||||
|
||||
def factory(stage_id: int, replica_id: int):
|
||||
assert (stage_id, replica_id) == (0, 1)
|
||||
return replacement
|
||||
|
||||
controller = _controller(monkeypatch, pool, FakeHub(), remote_replica_factory=factory)
|
||||
await controller.handle_unregister(0, "tcp://old-0")
|
||||
await controller.handle_unregister(0, "tcp://old-1")
|
||||
|
||||
await controller.handle_register(0, 1)
|
||||
await controller.drain_tasks(timeout=1)
|
||||
|
||||
assert pool.clients == [None, replacement]
|
||||
assert pool.get_replica_id_by_addr("tcp://new-1") == 1
|
||||
assert pool.get_replica_id_by_addr("tcp://old-1") is None
|
||||
assert pool.available_replica_ids() == [1]
|
||||
@@ -0,0 +1,46 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.outputs.mm_outputs import MultimodalPayload
|
||||
from vllm_omni.outputs.multimodal_accumulation import (
|
||||
drain_delta_payload,
|
||||
is_non_final_delta_audio_chunk,
|
||||
replace_snapshot_keys,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_chunk_accumulation_policy_replaces_snapshots_and_drains_delta_state():
|
||||
accumulated = MultimodalPayload.from_dict(
|
||||
{
|
||||
"audio": torch.tensor([1.0]),
|
||||
"meta.tts_is_last_chunk": torch.tensor([0]),
|
||||
"meta.turn_end": torch.tensor([0]),
|
||||
"meta.stable_request_value": "keep",
|
||||
}
|
||||
)
|
||||
incoming = MultimodalPayload.from_dict(
|
||||
{
|
||||
"audio": torch.tensor([2.0]),
|
||||
"meta.tts_is_last_chunk": torch.tensor([1]),
|
||||
"meta.turn_end": torch.tensor([1]),
|
||||
}
|
||||
)
|
||||
assert accumulated is not None
|
||||
assert incoming is not None
|
||||
|
||||
replace_snapshot_keys(accumulated, incoming)
|
||||
merged = accumulated.merged_with(incoming)
|
||||
|
||||
assert not is_non_final_delta_audio_chunk(merged, "audio")
|
||||
|
||||
drain_delta_payload(merged)
|
||||
|
||||
assert "audio" not in merged
|
||||
assert "meta.tts_is_last_chunk" not in merged
|
||||
assert "meta.turn_end" not in merged
|
||||
assert merged.metadata["meta.stable_request_value"] == "keep"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -38,6 +38,7 @@ class FakeStageClient:
|
||||
self.custom_process_input_func = None
|
||||
self.next_inputs = list(next_inputs or [])
|
||||
self.add_request_calls: list[tuple[Any, ...]] = []
|
||||
self.decoded_source_tokens: str | None = None
|
||||
self._engine_core_outputs = queue.Queue()
|
||||
|
||||
async def add_request_async(self, *args, **_kwargs) -> None:
|
||||
@@ -50,6 +51,9 @@ class FakeStageClient:
|
||||
return SimpleNamespace(outputs=[])
|
||||
|
||||
def process_engine_inputs(self, _source_outputs, prompt=None, streaming_context=None):
|
||||
decoder = getattr(streaming_context, "source_token_decoder", None)
|
||||
if callable(decoder):
|
||||
self.decoded_source_tokens = decoder([11, 12], skip_special_tokens=True)
|
||||
return list(self.next_inputs)
|
||||
|
||||
async def abort_requests_async(self, _request_ids: list[str]) -> None:
|
||||
@@ -66,6 +70,9 @@ class FakeStageClient:
|
||||
|
||||
|
||||
class FakeOutputProcessor:
|
||||
def __init__(self, tokenizer=None) -> None:
|
||||
self.tokenizer = tokenizer
|
||||
|
||||
def add_request(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
@@ -108,6 +115,11 @@ def _request_output(request_id: str) -> RequestOutput:
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_forward_text_prompt_uses_target_stage_input_processor() -> None:
|
||||
class SourceTokenizer:
|
||||
def decode(self, token_ids, *, skip_special_tokens):
|
||||
assert skip_special_tokens is True
|
||||
return ":".join(str(token_id) for token_id in token_ids)
|
||||
|
||||
stage0 = FakeStageClient(final_output=True)
|
||||
stage1 = FakeStageClient(
|
||||
final_output=True,
|
||||
@@ -117,7 +129,7 @@ async def test_forward_text_prompt_uses_target_stage_input_processor() -> None:
|
||||
StagePool(
|
||||
0,
|
||||
[stage0],
|
||||
output_processor=FakeOutputProcessor(),
|
||||
output_processor=FakeOutputProcessor(tokenizer=SourceTokenizer()),
|
||||
stage_vllm_config=SimpleNamespace(model_config=SimpleNamespace(max_model_len=64)),
|
||||
),
|
||||
StagePool(
|
||||
@@ -150,6 +162,8 @@ async def test_forward_text_prompt_uses_target_stage_input_processor() -> None:
|
||||
|
||||
assert input_processor.calls
|
||||
assert input_processor.calls[0]["prompt"] == {"prompt": "hello", "multi_modal_data": {"video": ["frame"]}}
|
||||
assert stage1.decoded_source_tokens == "11:12"
|
||||
assert req_state.streaming.source_token_decoder is None
|
||||
assert stage1.add_request_calls
|
||||
submitted_request = stage1.add_request_calls[0][0]
|
||||
assert submitted_request.prompt_token_ids == [101, 102]
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Regression tests for OmniRequestState multimodal DELTA drain and consolidation guard."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
@@ -10,9 +11,11 @@ import torch
|
||||
from vllm.outputs import PoolingRequestOutput
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine import FinishReason
|
||||
from vllm.v1.engine.output_processor import OutputProcessor as VLLMOutputProcessor
|
||||
|
||||
from vllm_omni.outputs import output_processor
|
||||
from vllm_omni.outputs.output_modality import OutputModalityNames
|
||||
from vllm_omni.outputs.output_processor import OmniRequestState
|
||||
from vllm_omni.outputs.output_processor import MultimodalOutputProcessor, OmniRequestState
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -62,6 +65,65 @@ def test_init_empty_dict():
|
||||
assert _make_state(RequestOutputKind.DELTA).mm_accumulated == {}
|
||||
|
||||
|
||||
def test_streaming_update_resets_native_text_metrics_for_next_segment():
|
||||
state = _make_state(RequestOutputKind.DELTA)
|
||||
state.native_text_stats.num_generation_tokens = 12
|
||||
state.native_text_stats.first_token_ts = 10.0
|
||||
state.native_text_stats.last_token_ts = 10.2
|
||||
|
||||
state.apply_streaming_update(
|
||||
SimpleNamespace(
|
||||
final=False,
|
||||
prompt=None,
|
||||
prompt_token_ids=[],
|
||||
arrival_time=20.0,
|
||||
)
|
||||
)
|
||||
|
||||
assert state.native_text_stats.arrival_time == 20.0
|
||||
assert state.native_text_stats.num_generation_tokens == 0
|
||||
assert state.native_text_stats.first_token_ts == 0.0
|
||||
assert state.native_text_stats.last_token_ts == 0.0
|
||||
|
||||
|
||||
def test_native_text_tpot_snapshot_matches_vllm_finished_metric_definition():
|
||||
calculate = getattr(output_processor, "_mean_time_per_output_token_ms", None)
|
||||
assert calculate is not None
|
||||
stats = SimpleNamespace(
|
||||
num_generation_tokens=4,
|
||||
first_token_ts=10.0,
|
||||
last_token_ts=10.045,
|
||||
)
|
||||
|
||||
assert calculate(stats) == pytest.approx(15.0)
|
||||
|
||||
|
||||
def test_native_text_metrics_include_segment_generation_token_count(monkeypatch):
|
||||
monkeypatch.setattr(VLLMOutputProcessor, "_update_stats_from_output", lambda *args, **kwargs: None)
|
||||
processor = object.__new__(MultimodalOutputProcessor)
|
||||
processor._native_text_metrics_by_request = {}
|
||||
processor.lora_states = {}
|
||||
state = _make_state(RequestOutputKind.DELTA)
|
||||
state.is_prefilling = False
|
||||
iteration_stats = MagicMock()
|
||||
|
||||
def update_native_stats(_output, _timestamp, _was_prefilling, native_stats, *_args):
|
||||
native_stats.num_generation_tokens = 27
|
||||
native_stats.first_token_ts = 10.0
|
||||
native_stats.last_token_ts = 10.26
|
||||
|
||||
iteration_stats.update_from_output.side_effect = update_native_stats
|
||||
|
||||
processor._update_stats_from_output(
|
||||
state,
|
||||
SimpleNamespace(),
|
||||
10.26,
|
||||
iteration_stats,
|
||||
)
|
||||
|
||||
assert processor.pop_native_text_metrics("r")["num_generation_tokens"] == 27
|
||||
|
||||
|
||||
def test_delta_drains_output_modality_per_step():
|
||||
"""DELTA drains the mm_type key (output modality) but preserves hidden-state keys."""
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
@@ -172,6 +234,145 @@ def test_finish_consolidation_drains_mm_delta():
|
||||
assert AUDIO not in s.mm_accumulated # drained
|
||||
|
||||
|
||||
def test_delta_drains_audio_chunk_metadata_per_step():
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
segment_text = "你好"
|
||||
segment_utf8 = torch.tensor(list(segment_text.encode("utf-8")), dtype=torch.uint8)
|
||||
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(5),
|
||||
"meta.duplex_epoch": torch.tensor([7], dtype=torch.int32),
|
||||
"meta.duplex_turn_id": torch.tensor([1], dtype=torch.int32),
|
||||
"meta.llm_output_text_utf8": segment_utf8,
|
||||
"meta.audio_text_total_chars": torch.tensor([len(segment_text)], dtype=torch.int32),
|
||||
"meta.tts_is_last_chunk": torch.tensor([0], dtype=torch.int32),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
result1 = s.make_request_output([1], None, FinishReason.STOP, None)
|
||||
assert result1 is not None and not isinstance(result1, PoolingRequestOutput)
|
||||
meta1 = result1.outputs[0].multimodal_output["meta"]
|
||||
assert bytes(meta1["llm_output_text_utf8"].tolist()).decode("utf-8") == segment_text
|
||||
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(3),
|
||||
"meta.duplex_epoch": torch.tensor([8], dtype=torch.int32),
|
||||
"meta.duplex_turn_id": torch.tensor([2], dtype=torch.int32),
|
||||
"meta.llm_output_text_utf8": segment_utf8,
|
||||
"meta.audio_text_total_chars": torch.tensor([len(segment_text)], dtype=torch.int32),
|
||||
"meta.tts_is_last_chunk": torch.tensor([1], dtype=torch.int32),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
result2 = s.make_request_output([2], None, FinishReason.STOP, None)
|
||||
|
||||
assert result2 is not None and not isinstance(result2, PoolingRequestOutput)
|
||||
meta2 = result2.outputs[0].multimodal_output["meta"]
|
||||
assert bytes(meta2["llm_output_text_utf8"].tolist()).decode("utf-8") == segment_text
|
||||
assert meta2["audio_text_total_chars"].tolist() == [len(segment_text)]
|
||||
assert meta2["duplex_epoch"].tolist() == [8]
|
||||
assert meta2["duplex_turn_id"].tolist() == [2]
|
||||
|
||||
|
||||
def test_cumulative_audio_replaces_chunk_metadata_per_step():
|
||||
s = _make_state(RequestOutputKind.CUMULATIVE)
|
||||
segment_text = "你好"
|
||||
segment_utf8 = torch.tensor(list(segment_text.encode("utf-8")), dtype=torch.uint8)
|
||||
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(5),
|
||||
"meta.duplex_epoch": torch.tensor([7], dtype=torch.int32),
|
||||
"meta.duplex_turn_id": torch.tensor([1], dtype=torch.int32),
|
||||
"meta.llm_output_text_utf8": segment_utf8,
|
||||
"meta.audio_text_total_chars": torch.tensor([len(segment_text)], dtype=torch.int32),
|
||||
"meta.tts_is_last_chunk": torch.tensor([0], dtype=torch.int32),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
result1 = s.make_request_output([1], None, None, None)
|
||||
assert result1 is not None and not isinstance(result1, PoolingRequestOutput)
|
||||
assert result1.outputs[0].multimodal_output["audio"].shape[0] == 5
|
||||
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(3),
|
||||
"meta.duplex_epoch": torch.tensor([8], dtype=torch.int32),
|
||||
"meta.duplex_turn_id": torch.tensor([2], dtype=torch.int32),
|
||||
"meta.llm_output_text_utf8": segment_utf8,
|
||||
"meta.audio_text_total_chars": torch.tensor([len(segment_text)], dtype=torch.int32),
|
||||
"meta.tts_is_last_chunk": torch.tensor([1], dtype=torch.int32),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
result2 = s.make_request_output([2], None, None, None)
|
||||
|
||||
assert result2 is not None and not isinstance(result2, PoolingRequestOutput)
|
||||
output = result2.outputs[0].multimodal_output
|
||||
assert output["audio"].shape[0] == 8
|
||||
meta = output["meta"]
|
||||
assert bytes(meta["llm_output_text_utf8"].tolist()).decode("utf-8") == segment_text
|
||||
assert meta["audio_text_total_chars"].tolist() == [len(segment_text)]
|
||||
assert meta["duplex_epoch"].tolist() == [8]
|
||||
assert meta["duplex_turn_id"].tolist() == [2]
|
||||
assert meta["tts_is_last_chunk"].tolist() == [1]
|
||||
|
||||
|
||||
def test_delta_audio_non_final_tts_chunk_overrides_spurious_finish():
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(5),
|
||||
"meta.tts_is_last_chunk": torch.tensor([0]),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
|
||||
result = s.make_request_output([1], None, FinishReason.STOP, None)
|
||||
|
||||
assert result is not None and not isinstance(result, PoolingRequestOutput)
|
||||
assert result.finished is False
|
||||
assert result.outputs[0].finish_reason is None
|
||||
assert result.outputs[0].multimodal_output["meta"]["tts_is_last_chunk"].tolist() == [0]
|
||||
assert torch.equal(result.outputs[0].multimodal_output[AUDIO], torch.ones(5))
|
||||
|
||||
|
||||
def test_delta_audio_final_tts_chunk_keeps_finish():
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
"model_outputs": torch.ones(5),
|
||||
"meta.tts_is_last_chunk": torch.tensor([1]),
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
|
||||
result = s.make_request_output([151645], None, FinishReason.STOP, None)
|
||||
|
||||
assert result is not None and not isinstance(result, PoolingRequestOutput)
|
||||
assert result.finished is True
|
||||
assert result.outputs[0].finish_reason == "stop"
|
||||
|
||||
|
||||
def test_delta_audio_non_final_tts_chunk_accepts_nested_meta():
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
s.add_multimodal_tensor(
|
||||
{
|
||||
AUDIO: torch.ones(5),
|
||||
"meta": {"tts_is_last_chunk": torch.tensor([0])},
|
||||
},
|
||||
mm_type=AUDIO,
|
||||
)
|
||||
|
||||
result = s.make_request_output([1], None, FinishReason.STOP, None)
|
||||
|
||||
assert result is not None and not isinstance(result, PoolingRequestOutput)
|
||||
assert result.finished is False
|
||||
assert result.outputs[0].multimodal_output["meta"]["tts_is_last_chunk"].tolist() == [0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mm_type", [AUDIO, "hidden"])
|
||||
def test_final_only_consolidates_drainable_keys(mm_type):
|
||||
"""FINAL_ONLY never drains per-step, so modality keys and hidden state
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import queue
|
||||
from typing import Literal
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.messages import (
|
||||
CollectiveRPCResultMessage,
|
||||
EngineQueueMessage,
|
||||
ErrorMessage,
|
||||
)
|
||||
from vllm_omni.engine.rpc_result_router import RpcResultRouter
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class GenericCorrelatedResultMessage(EngineQueueMessage, kw_only=True):
|
||||
type: Literal["generic_correlated_result"] = "generic_correlated_result"
|
||||
namespace: str
|
||||
correlation_id: str
|
||||
|
||||
@property
|
||||
def rpc_correlation_key(self) -> tuple[str, str]:
|
||||
return (self.namespace, self.correlation_id)
|
||||
|
||||
|
||||
def _generic_result(correlation_id: str) -> GenericCorrelatedResultMessage:
|
||||
return GenericCorrelatedResultMessage(
|
||||
namespace="plugin",
|
||||
correlation_id=correlation_id,
|
||||
)
|
||||
|
||||
|
||||
def test_rpc_result_router_routes_out_of_order_results_by_correlation_id():
|
||||
source: queue.Queue = queue.Queue()
|
||||
router = RpcResultRouter(source)
|
||||
first = router.register(("plugin", "first"))
|
||||
second = router.register(("plugin", "second"))
|
||||
|
||||
source.put(_generic_result("second"))
|
||||
source.put(_generic_result("first"))
|
||||
|
||||
assert first.get(timeout=1).correlation_id == "first"
|
||||
assert second.get(timeout=1).correlation_id == "second"
|
||||
router.close()
|
||||
|
||||
|
||||
def test_rpc_result_router_drops_only_the_late_result_after_unregister():
|
||||
source: queue.Queue = queue.Queue()
|
||||
router = RpcResultRouter(source)
|
||||
expired = router.register(("plugin", "expired"))
|
||||
active = router.register(("collective", "active"))
|
||||
router.unregister(("plugin", "expired"), expired)
|
||||
|
||||
source.put(_generic_result("expired"))
|
||||
source.put(
|
||||
CollectiveRPCResultMessage(
|
||||
rpc_id="active",
|
||||
method="health",
|
||||
stage_ids=[0],
|
||||
results=["ok"],
|
||||
)
|
||||
)
|
||||
|
||||
assert active.get(timeout=1).rpc_id == "active"
|
||||
assert expired.empty()
|
||||
router.close()
|
||||
|
||||
|
||||
def test_rpc_result_router_broadcasts_fatal_errors_to_pending_waiters():
|
||||
source: queue.Queue = queue.Queue()
|
||||
router = RpcResultRouter(source)
|
||||
plugin = router.register(("plugin", "one"))
|
||||
collective = router.register(("collective", "two"))
|
||||
|
||||
source.put(ErrorMessage(error="orchestrator failed", fatal=True))
|
||||
|
||||
assert plugin.get(timeout=1).error == "orchestrator failed"
|
||||
assert collective.get(timeout=1).error == "orchestrator failed"
|
||||
with pytest.raises(RuntimeError, match="orchestrator failed"):
|
||||
router.register(("plugin", "after-failure"))
|
||||
router.close()
|
||||
|
||||
|
||||
def test_rpc_result_router_does_not_broadcast_uncorrelated_nonfatal_errors():
|
||||
source: queue.Queue = queue.Queue()
|
||||
router = RpcResultRouter(source)
|
||||
waiter = router.register(("plugin", "active"))
|
||||
|
||||
source.put(ErrorMessage(error="request failed", fatal=False, request_id="other"))
|
||||
source.put(_generic_result("active"))
|
||||
|
||||
assert waiter.get(timeout=1).correlation_id == "active"
|
||||
router.close()
|
||||
|
||||
|
||||
def test_rpc_result_router_close_unblocks_waiters_and_stops_consumer():
|
||||
source: queue.Queue = queue.Queue()
|
||||
router = RpcResultRouter(source)
|
||||
waiter = router.register(("plugin", "pending"))
|
||||
|
||||
router.close()
|
||||
|
||||
result = waiter.get(timeout=1)
|
||||
assert isinstance(result, ErrorMessage)
|
||||
assert result.fatal is True
|
||||
assert result.error == "RPC result router closed"
|
||||
assert not router._thread.is_alive()
|
||||
with pytest.raises(RuntimeError, match="router is closed"):
|
||||
router.register(("plugin", "after-close"))
|
||||
Reference in new issue
Block a user