Merge vLLM-Omni v0.29.0rc1 into edge-infer/omni-0.29.0

The pair for vLLM v0.29.0: rc1's docs pin vllm==0.29.0 and a static scan of
rc1's vllm.* imports against the v0.29.0 tree finds nothing missing, while
our 0.28-based tree needs seven modules v0.29.0 no longer has
(vllm.inputs.preprocess, entrypoints.launcher, openai.cli_args,
openai.engine.protocol, serve.utils.server_utils, layers.batch_invariant,
models.hunyuan_v1).

Ten files conflicted. Upstream's structure is the base everywhere; the
fork's features are re-attached to it:
- deploy_profile / apply_deploy_profile run before rc1's resolve_omni_config
  pops deploy_config (async_omni_engine, cli/serve); the deploy-profile
  selector and the resolve_model_config_path chain it needs stay in
  entrypoints/utils.py; stage_overrides takes rc1's dict type.
- config_factory keeps the lazy diffusion output-type import; the diffusion
  registry import in rc1's new config/resolver.py is made lazy for the same
  WP6 reason (TTS path must not load diffusion).
- requirements: our core/media split kept; rc1's transformers>=5.13 floor
  and kernels==0.16.1 applied in core.txt / media.txt.
- TTS: rc1's split_granularity and bounded seed plus our output_mode=
  codec_tokens, _SessionInbox cancel handling and codec DELTA accumulation;
  our private _conditioning_cache_salt is superseded by rc1's public
  tts_adapters/base.py::conditioning_cache_salt.
- stage_runtime: rc1's single ExitStack G2 path (lock released before READY)
  replaces our two-path block, with the four worker_phase names the init
  profiler consumes still emitted; _cpu_placed / host admission kept.

Not yet run against vLLM 0.29.0: the tests listed in the W6 record.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
tzhouamandClaude Fable 5.1 committed 2026-09-18 09:57:20 +08:00
commit 33de5d8629
513 files changed
+35146 -10927

No files matched your search

@@ -33,6 +33,7 @@ def test_duplex_session_runtime_defaults_are_typed_and_immutable(tmp_path) -> No
assert deploy.duplex_session.max_pending_turns_per_session == 4
assert deploy.duplex_session.max_sessions == 1
assert deploy.duplex_session.completed_append_cache_size == 256
assert deploy.duplex_session.server_vad_model_path is None
with pytest.raises(FrozenInstanceError):
deploy.duplex_session.idle_ttl_s = 1.0 # type: ignore[misc]
@@ -46,6 +47,29 @@ def test_duplex_session_runtime_accepts_disabled_idle_expiry(tmp_path) -> None:
assert deploy.duplex_session.idle_ttl_s is None
def test_duplex_session_runtime_accepts_local_server_vad_model(tmp_path) -> None:
deploy_path = tmp_path / "duplex.yaml"
deploy_path.write_text(
"duplex_session:\n server_vad_model_path: /models/silero_vad.onnx\nstages: []\n",
encoding="utf-8",
)
deploy = load_deploy_config(deploy_path)
assert deploy.duplex_session.server_vad_model_path == "/models/silero_vad.onnx"
def test_duplex_session_runtime_rejects_empty_server_vad_model_path(tmp_path) -> None:
deploy_path = tmp_path / "duplex.yaml"
deploy_path.write_text(
"duplex_session:\n server_vad_model_path: ''\nstages: []\n",
encoding="utf-8",
)
with pytest.raises(ValueError, match="server_vad_model_path"):
load_deploy_config(deploy_path)
@pytest.mark.parametrize(
("name", "value"),
[
+9 -5
View File
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
Tests for Omni config utils. For stability, these tests should largely be
invariant to the specific attributes of vLLM config except in cases where we
@@ -63,7 +66,7 @@ def test_full_payload_capability_reaches_omni_model_config(monkeypatch):
class ConnectorWorker:
model_runner_cls = ConnectorRunner
worker_module.ConnectorWorker = ConnectorWorker
setattr(worker_module, "ConnectorWorker", ConnectorWorker)
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
monkeypatch.setattr(OmniEngineArgs, "_ensure_omni_models_registered", lambda _self: None)
@@ -95,7 +98,7 @@ def test_stage_without_connector_configuration_accepts_plain_runner(monkeypatch)
class WorkerWithoutConnector:
model_runner_cls = object
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
args = OmniEngineArgs(
@@ -113,7 +116,7 @@ def test_full_payload_capability_requires_selected_worker_connector(monkeypatch)
class WorkerWithoutConnector:
model_runner_cls = object
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
with pytest.raises(ValueError, match="does not provide an Omni connector model runner"):
@@ -130,7 +133,7 @@ def test_full_payload_capability_validates_platform_selected_worker(monkeypatch)
class WorkerWithoutConnector:
model_runner_cls = object
worker_module.WorkerWithoutConnector = WorkerWithoutConnector
setattr(worker_module, "WorkerWithoutConnector", WorkerWithoutConnector)
monkeypatch.setitem(sys.modules, worker_module.__name__, worker_module)
monkeypatch.setattr(
current_omni_platform,
@@ -293,7 +296,7 @@ def test_remote_tokenizer_subfolder_download_does_not_report_failure(tmp_path, m
baseline_config = Mock()
warning = mocker.patch("vllm_omni.engine.arg_utils.logger.warning")
monkeypatch.setattr("huggingface_hub.snapshot_download", lambda *args, **kwargs: str(tmp_path))
monkeypatch.setattr("huggingface_hub.HfApi.snapshot_download", lambda *args, **kwargs: str(tmp_path))
monkeypatch.setattr(OmniEngineArgs, "_patch_empty_hf_config", lambda *args, **kwargs: None)
monkeypatch.setattr(EngineArgs, "create_model_config", lambda _self: baseline_config)
monkeypatch.setattr(
@@ -339,6 +342,7 @@ def test_patch_missing_local_hf_config(tmp_path):
def test_non_missing_local_hf_config_error_reaches_parent_loader(tmp_path, monkeypatch, config_entry):
"""Non-missing config errors must reach vLLM's normal loader."""
config_path = tmp_path / "config.json"
loader_error: Exception
if config_entry == "malformed":
config_path.write_text("{not valid json", encoding="utf-8")
loader_error = json.JSONDecodeError("invalid config", "{not valid json", 1)
+39 -184
View File
@@ -11,7 +11,7 @@ import types
import pytest
from vllm_omni.diffusion.data import AttentionConfig, AttentionSpec, normalize_omni_diffusion_kwargs
from vllm_omni.diffusion.data import AttentionConfig
from vllm_omni.engine import async_omni_engine as async_omni_engine_module
from vllm_omni.engine.async_omni_engine import AsyncOmniEngine
from vllm_omni.engine.stage_init_utils import (
@@ -926,10 +926,7 @@ def test_remote_replicas_use_distinct_init_group_keys():
replica.launch_mode = "remote"
replica.metadata.runtime_cfg = None
assert [runtime._replica_init_group_key(replica) for replica in plan.replicas] == [
"remote:1:0",
"remote:1:1",
]
assert runtime._init_group_keys(plan.replicas) == ["remote:1:0", "remote:1:1"]
def test_initialize_stages_cleans_up_successful_replicas_after_partial_multi_replica_failure(monkeypatch):
@@ -1596,73 +1593,58 @@ def test_model_path_resolver_is_generic_and_model_owned(tmp_path):
assert "model_path_resolver" not in engine_args
def test_build_stage0_input_processor_uses_omni_input_preprocessor(monkeypatch):
def test_build_stage0_input_processor_uses_omni_renderer_subclass(monkeypatch):
from vllm.renderers import BaseRenderer
import vllm_omni.engine.stage_init_utils as init_mod
from vllm_omni.inputs.preprocess import OmniRenderer, omni_renderer_cls
class DummyInputProcessor:
def __init__(self, vllm_config, renderer=None):
self.vllm_config = vllm_config
self.renderer = renderer or object()
self.input_preprocessor = None
class _Base(BaseRenderer):
def __init__(self, config, tokenizer):
self.config, self.tokenizer = config, tokenizer
class DummyOmniInputPreprocessor:
def __init__(self, vllm_config, renderer=None):
self.vllm_config = vllm_config
self.renderer = renderer
def render_messages(self, messages, params): # pragma: no cover - abstract stub
raise NotImplementedError
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
monkeypatch.setattr(init_mod, "OmniInputPreprocessor", DummyOmniInputPreprocessor)
input_processor = build_stage0_input_processor(
types.SimpleNamespace(model_config=types.SimpleNamespace(try_get_generation_config=lambda: {}))
)
assert isinstance(input_processor.input_preprocessor, DummyOmniInputPreprocessor)
assert input_processor.input_preprocessor.renderer is input_processor.renderer
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(
monkeypatch,
):
import vllm_omni.engine.stage_init_utils as init_mod
token_only_renderer = object()
config = types.SimpleNamespace(model_config=types.SimpleNamespace(try_get_generation_config=lambda: {}))
built = omni_renderer_cls(_Base)(config, "tok")
seen = {}
class DummyInputProcessor:
def __init__(self, vllm_config, renderer=None):
if renderer is None:
raise AssertionError("skip_tokenizer_init must supply a renderer")
seen["renderer"] = renderer
self.renderer = renderer
self.input_preprocessor = None
class DummyOmniInputPreprocessor:
def __init__(self, vllm_config, renderer=None):
seen["preprocessor_renderer"] = renderer
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
monkeypatch.setattr(
init_mod,
"_build_token_only_renderer",
lambda _config: token_only_renderer,
)
monkeypatch.setattr(
init_mod,
"OmniInputPreprocessor",
DummyOmniInputPreprocessor,
)
monkeypatch.setattr(init_mod, "build_omni_renderer", lambda cfg: built if cfg is config else None)
processor = build_stage0_input_processor(config)
assert seen["renderer"] is built
assert isinstance(processor.renderer, OmniRenderer)
assert isinstance(processor.renderer, _Base)
assert not hasattr(processor, "input_preprocessor")
def test_build_stage0_input_processor_does_not_resolve_tokenizer_when_skipped(monkeypatch):
import vllm_omni.engine.stage_init_utils as init_mod
original = object()
class DummyInputProcessor:
def __init__(self, vllm_config, renderer=None):
assert renderer is original
self.renderer = renderer
def _must_not_resolve(_cfg):
raise AssertionError("tokenizer must not be resolved when skip_tokenizer_init=True")
monkeypatch.setattr(init_mod, "InputProcessor", DummyInputProcessor)
monkeypatch.setattr(init_mod, "_build_token_only_renderer", lambda _: original)
monkeypatch.setattr(init_mod, "build_omni_renderer", _must_not_resolve)
config = types.SimpleNamespace(
model_config=types.SimpleNamespace(
skip_tokenizer_init=True,
try_get_generation_config=lambda: {},
)
model_config=types.SimpleNamespace(skip_tokenizer_init=True, try_get_generation_config=lambda: {})
)
build_stage0_input_processor(config)
assert seen["renderer"] is token_only_renderer
assert seen["preprocessor_renderer"] is token_only_renderer
processor = build_stage0_input_processor(config)
assert processor.renderer is original
def test_inject_kv_stage_info_infers_sender_tp_topology():
@@ -1732,133 +1714,6 @@ def test_inject_kv_stage_info_infers_receiver_tp_topology():
assert stage1.engine_args["omni_kv_config"]["rank_mapping"] == {"from_tp": 4, "to_tp": 2}
def test_resolve_stage_configs_injects_global_diffusion_attention_when_missing(monkeypatch):
import vllm_omni.engine.async_omni_engine as engine_mod
engine = object.__new__(AsyncOmniEngine)
stage_cfg = types.SimpleNamespace(
stage_type="diffusion",
engine_args=types.SimpleNamespace(
diffusion_attention_config=None,
lora_path=None,
lora_scale=None,
enable_sleep_mode=None,
quantization_config=None,
),
)
monkeypatch.setattr(
engine_mod,
"load_and_resolve_stage_configs",
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
)
_config_path, stage_configs = engine._resolve_stage_configs(
model="dummy-model",
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
trust_remote_code=False,
)
diffusion_attention_config = stage_configs[0].engine_args.diffusion_attention_config
assert isinstance(diffusion_attention_config, AttentionConfig)
assert diffusion_attention_config.default is not None
assert diffusion_attention_config.default.backend == "FLASH_ATTN"
def test_resolve_stage_configs_preserves_stage_diffusion_attention(monkeypatch):
import vllm_omni.engine.async_omni_engine as engine_mod
engine = object.__new__(AsyncOmniEngine)
existing_attention = AttentionConfig(default=AttentionSpec(backend="TORCH_SDPA"))
stage_cfg = types.SimpleNamespace(
stage_type="diffusion",
engine_args=types.SimpleNamespace(
diffusion_attention_config=existing_attention,
lora_path=None,
lora_scale=None,
enable_sleep_mode=None,
quantization_config=None,
),
)
monkeypatch.setattr(
engine_mod,
"load_and_resolve_stage_configs",
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
)
_config_path, stage_configs = engine._resolve_stage_configs(
model="dummy-model",
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
trust_remote_code=False,
)
assert stage_configs[0].engine_args.diffusion_attention_config is existing_attention
def test_resolve_stage_configs_does_not_inject_over_stage_diffusion_attention_backend(monkeypatch):
import vllm_omni.engine.async_omni_engine as engine_mod
engine = object.__new__(AsyncOmniEngine)
stage_cfg = types.SimpleNamespace(
stage_type="diffusion",
engine_args=types.SimpleNamespace(
diffusion_attention_backend="TORCH_SDPA",
diffusion_attention_config=None,
lora_path=None,
lora_scale=None,
enable_sleep_mode=None,
quantization_config=None,
),
)
monkeypatch.setattr(
engine_mod,
"load_and_resolve_stage_configs",
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
)
_config_path, stage_configs = engine._resolve_stage_configs(
model="dummy-model",
kwargs={"diffusion_attention_backend": "FLASH_ATTN"},
trust_remote_code=False,
)
engine_args = stage_configs[0].engine_args
assert engine_args.diffusion_attention_backend == "TORCH_SDPA"
assert engine_args.diffusion_attention_config is None
normalized = normalize_omni_diffusion_kwargs(vars(engine_args))
assert normalized["diffusion_attention_config"].default.backend == "TORCH_SDPA"
def test_resolve_stage_configs_does_not_inject_diffusion_attention_into_llm_stage(monkeypatch):
import vllm_omni.engine.async_omni_engine as engine_mod
engine = object.__new__(AsyncOmniEngine)
stage_cfg = types.SimpleNamespace(
stage_type="llm",
engine_args=types.SimpleNamespace(
attention_config={"backend": "FLASH_ATTN"},
enable_sleep_mode=None,
),
)
monkeypatch.setattr(
engine_mod,
"load_and_resolve_stage_configs",
lambda *args, **kwargs: ("dummy-config", [stage_cfg], None),
)
_config_path, stage_configs = engine._resolve_stage_configs(
model="dummy-model",
kwargs={"diffusion_attention_backend": "TORCH_SDPA"},
trust_remote_code=False,
)
assert stage_configs[0].engine_args.attention_config == {"backend": "FLASH_ATTN"}
assert not hasattr(stage_configs[0].engine_args, "diffusion_attention_config")
def test_extract_legacy_stage_metadata_rocm_does_not_inject_diffusion_attention(monkeypatch):
"""ROCm default attention logic only applies to LLM stages, not diffusion."""
from vllm_omni.engine.stage_init_utils import extract_legacy_stage_metadata
+13 -6
View File
@@ -2665,7 +2665,10 @@ async def test_duplex_reaper_loop_waits_between_ticks():
@pytest.mark.asyncio
async def test_duplex_reaper_loop_survives_one_cleanup_failure():
@pytest.mark.parametrize("first_cleanup_delay", [0.0, 0.05], ids=["immediate", "delayed"])
async def test_duplex_reaper_loop_survives_one_cleanup_failure(first_cleanup_delay: float) -> None:
recovered = asyncio.Event()
class _Plane:
def __init__(self) -> None:
self.calls = 0
@@ -2673,7 +2676,9 @@ async def test_duplex_reaper_loop_survives_one_cleanup_failure():
async def reap_expired(self) -> int:
self.calls += 1
if self.calls == 1:
await asyncio.sleep(first_cleanup_delay)
raise RuntimeError("transient cleanup failure")
recovered.set()
return 0
orchestrator = object.__new__(Orchestrator)
@@ -2682,11 +2687,13 @@ async def test_duplex_reaper_loop_survives_one_cleanup_failure():
orchestrator._shutdown_event = asyncio.Event()
task = asyncio.create_task(orchestrator._duplex_reaper_loop())
await asyncio.sleep(0.035)
orchestrator._shutdown_event.set()
await task
assert orchestrator.duplex_control_plane.calls >= 2
try:
# Wait for recovery itself, including when cleanup exceeds the old 35 ms window.
await asyncio.wait_for(recovered.wait(), timeout=5.0)
assert orchestrator.duplex_control_plane.calls >= 2
finally:
orchestrator._shutdown_event.set()
await asyncio.wait_for(task, timeout=5.0)
@pytest.mark.asyncio
@@ -16,7 +16,7 @@ from types import SimpleNamespace
import janus
import pytest
from vllm.sampling_params import SamplingParams
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.v1.engine.exceptions import EngineDeadError
from vllm.v1.serial_utils import MsgpackEncoder
@@ -33,11 +33,16 @@ from vllm_omni.engine.orchestrator import (
cleanup_request_artifact_dirs,
)
from vllm_omni.engine.stage_pool import StageUnavailableError
from vllm_omni.errors import OmniClientError
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.model_executor.stage_input_processors import (
joyai_vl_interaction as joyai_bridge,
)
from vllm_omni.outputs import OmniRequestOutput
from .test_orchestrator import (
FakeOutputProcessor,
FakeRunningCounter,
FakeStageClient,
OrchestratorFixture,
_build_harness,
@@ -45,6 +50,7 @@ from .test_orchestrator import (
_build_stage_pools,
_engine_core_outputs,
_enqueue_add_request,
_get_output_message,
_wait_for,
)
@@ -935,6 +941,139 @@ async def test_diffusion_client_error_output_propagates_status_code(orchestrator
orchestrator_fixture.thread.join(timeout=5)
@pytest.mark.asyncio
@pytest.mark.parametrize("event_driven", [False, True], ids=["legacy", "event-driven"])
@pytest.mark.parametrize("first_speaker", ["Ryan", "not-a-real-speaker"])
async def test_joyai_tts_request_validation_keeps_orchestrator_running(
orchestrator_factory,
monkeypatch: pytest.MonkeyPatch,
first_speaker: str,
event_driven: bool,
) -> None:
"""Check that the same orchestrator can handle the next valid request."""
monkeypatch.setenv("VLLM_OMNI_EVENT_DRIVEN_ORCH", "1" if event_driven else "0")
# Use a fixed token count so the test does not need tokenizer files.
class FakeTokenizer:
def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:
return list(range(12))
talker_model_config = SimpleNamespace(
max_model_len=64,
hf_config=SimpleNamespace(
talker_config=SimpleNamespace(spk_id={"vivian": 0, "ryan": 1}, codec_language_id={}, spk_is_dialect={})
),
)
monkeypatch.setattr(joyai_bridge, "cached_tokenizer_from_config", lambda _: FakeTokenizer())
# Use the real bridge so speaker validation is part of the test.
class JoyAITalkerStage(FakeStageClient):
def process_engine_inputs(self, source_outputs, prompt=None, streaming_context=None):
self.bridge_inputs = joyai_bridge.joyai_action_to_tts(
source_outputs, prompt, self.requires_multimodal_data, target_model_config=talker_model_config
)
return self.bridge_inputs
stage0 = FakeStageClient(stage_type="llm", final_output=False)
stage1 = JoyAITalkerStage(stage_type="llm", final_output=True)
stage0_processor, stage1_processor = FakeOutputProcessor(), FakeOutputProcessor()
fixture = orchestrator_factory(
[stage0, stage1],
output_processors=[stage0_processor, stage1_processor],
stage_vllm_configs=[
SimpleNamespace(model_config=SimpleNamespace(max_model_len=64)),
SimpleNamespace(model_config=talker_model_config),
],
)
counter = FakeRunningCounter()
fixture.orchestrator._running_counter = counter
# With a valid speaker, task_type should be changed from Base to CustomVoice.
# An unknown speaker should cause a request error.
first_info = {"tts_task_type": "Base", "speaker": "Vivian", "tts_speaker": first_speaker}
talker_submissions = 0
# Send both requests to the same orchestrator. The second uses the default Vivian voice.
for index, (request_id, info) in enumerate((("first", first_info), ("good", {})), start=1):
await _enqueue_add_request(
fixture,
request_id=request_id,
prompt=SimpleNamespace(request_id=request_id, prompt_token_ids=[1, 2]),
original_prompt={"additional_information": info},
sampling_params_list=[_sampling_params(), _sampling_params()],
final_stage_id=1,
)
await _wait_for(lambda: len(stage0.add_request_calls) == index and counter.value == 1)
stage0_processor.request_outputs = [_build_request_output(request_id, text="</response> Hello.")]
stage0.push_engine_core_outputs(_engine_core_outputs(f"{request_id}-raw", float(index)))
if request_id == "first" and first_speaker == "not-a-real-speaker":
# Reject this request before Talker runs, while keeping the engine alive.
error = await _wait_for_error_message(fixture, request_id=request_id)
assert error.status_code == 400 and error.error_type == "BadRequestError"
assert error.fatal is False and error.stage_id == 1
assert "not-a-real-speaker" in error.error
assert stage1.add_request_calls == []
else:
talker_submissions += 1
await _wait_for(lambda: len(stage1.add_request_calls) == talker_submissions or fixture.result_future.done())
assert not fixture.result_future.done()
assert stage1.add_request_calls[-1][0].request_id == request_id
metadata = stage1.bridge_inputs[0]["additional_information"]
assert metadata["task_type"] == ["CustomVoice"]
assert metadata["speaker"] == [first_speaker if request_id == "first" else "Vivian"]
# Finish the valid request and check its final output.
stage1_processor.request_outputs = [_build_request_output(request_id, text="Completed.")]
stage1.push_engine_core_outputs(_engine_core_outputs(f"{request_id}-talker", float(index)))
output = await _get_output_message(fixture)
assert output.request_id == request_id and output.stage_id == 1
assert output.finished is True
assert output.engine_outputs.outputs[0].text == "Completed."
# Wait for full cleanup before sending the next request.
await _wait_for(lambda: request_id not in fixture.orchestrator.request_states and counter.value == 0)
assert all(pool.get_bound_replica_id(request_id) is None for pool in fixture.orchestrator.stage_pools)
assert fixture.thread.is_alive() and not fixture.result_future.done()
@pytest.mark.asyncio
async def test_streaming_input_processor_client_error_does_not_forward_terminal_update() -> None:
"""Do not send a second update after the first one fails and clears the request."""
processor_calls = []
class FailingStage(FakeStageClient):
def process_engine_inputs(self, *args, **kwargs):
processor_calls.append((args, kwargs))
raise OmniClientError("Input rejected")
orchestrator, queues = _build_bare_orchestrator(
_build_stage_pools([[FakeStageClient()], [FailingStage(final_output=True)]])
)
state = OrchestratorRequestState(
request_id="bad-stream",
prompt={"prompt_token_ids": [1]},
sampling_params_list=[SamplingParams(output_kind=RequestOutputKind.CUMULATIVE), _sampling_params()],
final_stage_id=1,
)
state.streaming.enabled = True
assert state.duplex_identity is None
orchestrator.request_states[state.request_id] = state
try:
await orchestrator._route_output(0, 0, _build_request_output(state.request_id), state, stage_metrics=None)
assert len(processor_calls) == 1
error = queues[1].sync_q.get_nowait()
assert isinstance(error, ErrorMessage)
assert error.request_id == state.request_id
assert error.stage_id == 1
assert error.status_code == 400
assert error.fatal is False
assert queues[1].sync_q.empty()
assert state.request_id not in orchestrator.request_states
assert all(pool.get_bound_replica_id(state.request_id) is None for pool in orchestrator.stage_pools)
finally:
for q in queues:
q.close()
@pytest.mark.asyncio
async def test_duplex_input_processor_failure_is_request_scoped(orchestrator_factory, monkeypatch) -> None:
class FailingStage(FakeStageClient):
+105 -33
View File
@@ -1,7 +1,10 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for parallel stage initialization (CPU-only).
Covers the pure/lock logic added for ``parallel_stage_init``:
* init-group device keying (resolved physical set; parallel unique keys),
* init-group device keying (overlap components; parallel unique keys),
* admission control arithmetic + graph reserve,
* SH/EX device phase locks (real flock on a temp dir),
* the phase-locked executor wrapper ordering,
@@ -18,6 +21,7 @@ import inspect
import os
import subprocess
import threading
import time
import types
from pathlib import Path
@@ -37,7 +41,9 @@ from vllm_omni.engine.stage_init_utils import (
LogicalStageInitPlan,
ReplicaInitPlan,
device_init_lock_path,
device_overlap_group_keys,
open_device_lock_file,
parse_physical_device_ids,
)
from vllm_omni.engine.stage_phase_lock import (
DeviceLockTimeoutError,
@@ -46,6 +52,7 @@ from vllm_omni.engine.stage_phase_lock import (
wrap_executor_with_phase_locks,
)
from vllm_omni.engine.stage_runtime import StageRuntime
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -104,49 +111,114 @@ def _fake_vllm_config(util: float, *, model="m", dtype="bf16", cudagraph_mode="F
# --------------------------------------------------------------------------- #
# A1: init-group device key
# --------------------------------------------------------------------------- #
def test_init_group_key_resolves_physical_devices_serial():
@pytest.mark.parametrize(
("devices", "expected"),
[
("0", {0}),
("1,0,1", {0, 1}),
(" 2, 3 ", {2, 3}),
(None, None),
("", None),
("GPU-uuid", None),
],
)
def test_parse_physical_device_ids(devices, expected):
assert parse_physical_device_ids(devices) == expected
@pytest.mark.parametrize(
("device_sets", "expected"),
[
# equal / disjoint
([{0}, {1}, {0}], ["device-group:0", "device-group:1", "device-group:0"]),
# unequal overlap, canonical order
([{0, 1}, {0}, {2}], ["device-group:0,1", "device-group:0,1", "device-group:2"]),
# transitive: {0,1} ~ {1,2} ~ {2}
([{0, 1}, {1, 2}, {2}], ["device-group:0,1,2"] * 3),
# unresolved may touch any GPU -> everything serial
([{0}, None, {1}], ["device-group:*"] * 3),
([], []),
],
)
def test_device_overlap_group_keys(device_sets, expected):
sets = [None if s is None else frozenset(s) for s in device_sets]
assert device_overlap_group_keys(sets) == expected
def test_init_group_keys_serial_groups_by_device_overlap():
runtime = _runtime(parallel_stage_init=False)
runtime._init_visible_devices_baseline = None # no CUDA_VISIBLE_DEVICES mapping
r0 = _llm_replica(0, 0, "0")
r1 = _llm_replica(1, 0, "1")
r0b = _llm_replica(2, 0, "0")
k0 = runtime._replica_init_group_key(r0)
k1 = runtime._replica_init_group_key(r1)
k0b = runtime._replica_init_group_key(r0b)
keys = runtime._init_group_keys(
[_llm_replica(0, 0, "0,1"), _llm_replica(1, 0, "0"), _llm_replica(2, 0, "2"), _llm_replica(3, 0, "1,0")]
)
assert k0 == "device:0"
assert k1 == "device:1"
# Different physical devices -> different groups (parallel).
assert k0 != k1
# Same physical device -> same group (serialized under LOCK_EX).
assert k0 == k0b
assert keys == ["device-group:0,1", "device-group:0,1", "device-group:2", "device-group:0,1"]
def test_init_group_key_parallel_is_unique_per_replica():
runtime = _runtime(parallel_stage_init=True)
runtime._init_visible_devices_baseline = None
# Both on the SAME device, but parallel mode must give distinct keys so they
# run concurrently, coordinated by the child SH/EX locks + admission.
keys = [
runtime._replica_init_group_key(_llm_replica(0, 0, "0")),
runtime._replica_init_group_key(_llm_replica(0, 1, "0")),
runtime._replica_init_group_key(_llm_replica(1, 0, "0")),
]
assert keys == ["parallel:0:0", "parallel:0:1", "parallel:1:0"]
assert len(set(keys)) == 3
def test_init_group_key_remote_and_diffusion_unchanged():
def test_init_group_keys_fixed_for_parallel_remote_and_diffusion():
runtime = _runtime(parallel_stage_init=True)
remote = _llm_replica(1, 0, "0")
remote.launch_mode = "remote"
remote.metadata.runtime_cfg = None
assert runtime._replica_init_group_key(remote) == "remote:1:0"
diffusion = _llm_replica(2, 0, "0")
diffusion.metadata.stage_type = "diffusion"
assert runtime._replica_init_group_key(diffusion) == "inline:diffusion"
# Same device everywhere; parallel mode still keys per replica (child SH/EX locks coordinate).
keys = runtime._init_group_keys([_llm_replica(0, 0, "0"), _llm_replica(0, 1, "0"), remote, diffusion])
assert keys == ["parallel:0:0", "parallel:0:1", "remote:1:0", "inline:diffusion"]
def test_unresolved_devices_collapse_serial_groups_and_warn(caplog):
runtime = _runtime(parallel_stage_init=False)
with caplog.at_level("WARNING"):
keys = runtime._init_group_keys([_llm_replica(0, 0, "0"), _llm_replica(1, 0, "GPU-uuid")])
assert keys == ["device-group:*", "device-group:*"]
assert "Stage-1 replica 0" in caplog.text
assert "GPU-uuid" in caplog.text
def _stage_plans(*devices: str) -> list[LogicalStageInitPlan]:
return [
LogicalStageInitPlan(stage_idx=i, stage_id=i, replicas=[_llm_replica(i, 0, dev)])
for i, dev in enumerate(devices)
]
def test_overlapping_device_stages_initialize_sequentially(monkeypatch):
monkeypatch.delenv(current_omni_platform.device_control_env_var, raising=False)
runtime = _runtime(parallel_stage_init=False)
in_flight, peak = 0, 0
guard = threading.Lock()
def _initialize_replica(plan, _timeout):
nonlocal in_flight, peak
with guard:
in_flight += 1
peak = max(peak, in_flight)
time.sleep(0.05)
with guard:
in_flight -= 1
return object()
monkeypatch.setattr(runtime, "_initialize_replica", _initialize_replica)
runtime._initialize_stage_replicas(_stage_plans("0,1", "0"), stage_init_timeout=5)
assert peak == 1
def test_disjoint_device_stages_initialize_in_parallel(monkeypatch):
monkeypatch.delenv(current_omni_platform.device_control_env_var, raising=False)
runtime = _runtime(parallel_stage_init=False)
barrier = threading.Barrier(2, timeout=2) # breaks unless both inits are in flight together
def _initialize_replica(_plan, _timeout):
barrier.wait()
return object()
monkeypatch.setattr(runtime, "_initialize_replica", _initialize_replica)
runtime._initialize_stage_replicas(_stage_plans("0", "1"), stage_init_timeout=5)
# --------------------------------------------------------------------------- #
+43 -1
View File
@@ -376,14 +376,26 @@ class TestSingleStageModeDetection:
mocker: MockerFixture,
*,
stage_cfgs: list[Any] | None = None,
resolved_config_path: str = "/fake/path",
patch_deploy_config: bool = True,
**kwargs: Any,
) -> AsyncOmniEngine:
mock_stage_configs = stage_cfgs or [_make_stage_cfg(0)]
if patch_deploy_config:
mocker.patch.object(
StageConfigFactory,
"get_pipeline_config",
return_value=None,
)
mocker.patch(
"vllm_omni.engine.async_omni_engine.load_deploy_config",
return_value=SimpleNamespace(duplex_session=DuplexSessionRuntimeConfig()),
)
mocker.patch.object(
AsyncOmniEngine,
"_resolve_stage_configs",
return_value=("/fake/path", mock_stage_configs),
return_value=(resolved_config_path, mock_stage_configs),
)
mocker.patch.object(AsyncOmniEngine, "_bootstrap_orchestrator")
mock_thread_cls = mocker.patch("threading.Thread")
@@ -445,6 +457,8 @@ class TestSingleStageModeDetection:
engine = self._make_engine_no_thread(
mocker,
deploy_config="/fake/duplex.yaml",
resolved_config_path="/fake/duplex.yaml",
patch_deploy_config=False,
)
get_pipeline_config.assert_called_once_with(
@@ -455,6 +469,30 @@ class TestSingleStageModeDetection:
load_deploy_config.assert_called_once_with("/fake/duplex.yaml")
assert engine.duplex_session_config is duplex_session
def test_auto_discovered_deploy_loads_duplex_runtime_config(
self,
mocker: MockerFixture,
) -> None:
deploy_path = "/resolved/qwen3_omni_moe.yaml"
duplex_session = DuplexSessionRuntimeConfig(server_vad_model_path="/models/silero_vad.onnx")
mocker.patch(
"vllm_omni.engine.async_omni_engine.StageConfigFactory.get_pipeline_config",
return_value=None,
)
load_deploy_config = mocker.patch(
"vllm_omni.engine.async_omni_engine.load_deploy_config",
return_value=SimpleNamespace(duplex_session=duplex_session),
)
engine = self._make_engine_no_thread(
mocker,
resolved_config_path=deploy_path,
patch_deploy_config=False,
)
load_deploy_config.assert_called_once_with(deploy_path)
assert engine.duplex_session_config is duplex_session
def test_single_stage_mode_without_stage_id_has_no_filter(self, mocker: MockerFixture):
engine = self._make_engine_no_thread(
mocker,
@@ -518,6 +556,10 @@ class TestEndpointRestrictionsTrustRemoteCode:
StageConfigFactory.try_infer_model_type.cache_clear()
def _make_engine_no_thread(self, mocker: MockerFixture, **kwargs: Any) -> AsyncOmniEngine:
mocker.patch(
"vllm_omni.engine.async_omni_engine.load_deploy_config",
return_value=SimpleNamespace(duplex_session=DuplexSessionRuntimeConfig()),
)
mocker.patch.object(
AsyncOmniEngine,
"_resolve_stage_configs",
+40
View File
@@ -11,6 +11,7 @@ from pathlib import Path
import pytest
from pydantic.fields import FieldInfo
from transformers import Qwen3OmniMoeConfig
from vllm.config import CacheConfig as VllmCacheConfig
from vllm.config import CompilationConfig as VllmCompilationConfig
from vllm.config import LoadConfig as VllmLoadConfig
@@ -19,6 +20,7 @@ from vllm.config import ProfilerConfig as VllmProfilerConfig
from vllm.config import SchedulerConfig as VllmSchedulerConfig
from vllm.engine.arg_utils import EngineArgs
from tests.helpers.stage_config import get_deploy_config_path, modify_stage_config
from vllm_omni.config.omni_config import (
_LLM_STAGE_ENGINE_FIELDS,
OmniStageCacheConfig,
@@ -155,6 +157,44 @@ def test_qwen3_omni_preserves_explicit_moe_backend():
assert engine_args["moe_backend"] == "flashinfer"
def test_qwen3_omni_preserves_explicit_auto_moe_backend():
engine_args = {
"model_arch": "Qwen3OmniMoeForConditionalGeneration",
"moe_backend": "auto",
}
stage_init_utils._maybe_set_qwen3_omni_moe_backend(engine_args)
assert engine_args["moe_backend"] == "auto"
def test_qwen3_omni_nvfp4_ci_config_preserves_auto_moe_backend(tmp_path):
"""The NVFP4 CI deploy opts stage 0 into vLLM's auto backend selection."""
hf_config = Qwen3OmniMoeConfig(enable_audio_output=True)
pipeline = resolve_pipeline_config("qwen3_omni_moe", hf_config)
assert pipeline is not None
nvfp4_deploy = modify_stage_config(
get_deploy_config_path("ci/qwen3_omni_moe.yaml"),
updates={"stages": {0: {"moe_backend": "auto"}}},
)
deploy = load_deploy_config(nvfp4_deploy)
legacy_stages = merge_pipeline_deploy(pipeline, copy.deepcopy(deploy))
omni_config = VllmOmniConfig.from_pipeline_config(
pipeline,
user_deploy_config=copy.deepcopy(deploy),
cli_overrides={"model": str(tmp_path)},
)
for stage_id, expected_backend in ((0, "auto"), (1, "triton")):
legacy_stage = next(stage for stage in legacy_stages if stage.stage_id == stage_id)
typed_stage = omni_config.stage_by_id(stage_id)
for engine_args in (
build_engine_args_dict(legacy_stage.to_omegaconf(), str(tmp_path)),
build_engine_args_dict_from_omni_stage_config(typed_stage, str(tmp_path)),
):
assert engine_args["moe_backend"] == expected_backend
def _engine_arg_inputs(tmp_path: Path) -> tuple[PipelineConfig, DeployConfig, str]:
parent_model = tmp_path / "parent-model"
stage_model = tmp_path / "stage-model"
@@ -0,0 +1,149 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Check replica startup ordering without model-loading timing assumptions."""
import contextlib
import fcntl
import os
import threading
from collections.abc import Iterator
from pathlib import Path
import pytest
from pytest_mock import MockerFixture
from vllm.config import VllmConfig
from vllm.sampling_params import SamplingParams
from vllm.v1.engine.utils import CoreEngineProcManager, EngineZmqAddresses
from vllm_omni.config.stage_config import StageConfig
from vllm_omni.engine import stage_init_utils, stage_runtime
from vllm_omni.engine.stage_engine_startup import StageReplicaResources
from vllm_omni.engine.stage_init_utils import LogicalStageInitPlan, ReplicaInitPlan, StageMetadata
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@pytest.fixture
def launch_runtime(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, mocker: MockerFixture
) -> Iterator[stage_runtime.StageRuntime]:
runtime = stage_runtime.StageRuntime(
stage_configs=[],
model="dummy-model",
config_path="dummy-config",
stage_init_timeout=5,
async_chunk=False,
)
# These are virtual device IDs: only the real per-device file locking and
# scheduling run. No model, CUDA context, or engine process is created.
monkeypatch.setattr(runtime, "_resolve_replica_physical_devices", lambda _stage, cfg: cfg["devices"])
monkeypatch.setattr(
stage_init_utils, "device_init_lock_path", lambda device: str(tmp_path / f"device-{device}.lock")
)
mocker.patch.object(
stage_runtime.StageEngineCoreClientBase,
"make_async_mp_client",
return_value=mocker.Mock(spec=stage_runtime.StageClient),
)
monkeypatch.setenv("VLLM_OMNI_TEST_LAUNCH_ENV", "parent")
yield runtime
if runtime._stage_init_executor is not None:
runtime._stage_init_executor.shutdown(wait=True)
def _plan(stage_id: int, device: str) -> LogicalStageInitPlan:
metadata = StageMetadata(
stage_id=stage_id,
stage_type="llm",
engine_output_type="text",
is_comprehension=False,
requires_multimodal_data=False,
engine_input_source=[],
final_output=False,
final_output_type=None,
default_sampling_params=SamplingParams(),
custom_process_input_func=None,
model_stage="dummy",
runtime_cfg={"devices": device, "env": {"VLLM_OMNI_TEST_LAUNCH_ENV": str(stage_id)}},
)
replica = ReplicaInitPlan(
replica_id=0,
num_replicas=1,
launch_mode="local",
stage_cfg=StageConfig(stage_id=stage_id, model_stage="dummy", yaml_runtime=metadata.runtime_cfg),
metadata=metadata,
stage_connector_spec={},
omni_kv_connector=(None, None, None),
stage_vllm_config=VllmConfig(),
executor_class=object,
engine_args_dict={},
)
return LogicalStageInitPlan(stage_idx=stage_id, stage_id=stage_id, replicas=[replica])
def _resources(mocker: MockerFixture) -> StageReplicaResources:
return StageReplicaResources(
manager=mocker.Mock(spec=CoreEngineProcManager),
addresses=EngineZmqAddresses(inputs=["unused-input"], outputs=["unused-output"]),
)
def test_distinct_devices_spawn_before_either_is_ready(
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
) -> None:
spawned = [threading.Event(), threading.Event()]
@contextlib.contextmanager
def launch(*, stage_id: int, stage_visible_devices: str, **_kwargs: object) -> Iterator[StageReplicaResources]:
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == str(stage_id)
spawned[stage_id].set()
yield _resources(mocker)
# The device remains exclusively locked throughout loading/profiling,
# even though another device's replica must be able to start.
with open(stage_init_utils.device_init_lock_path(int(stage_visible_devices)), "r+") as lock:
with pytest.raises(BlockingIOError):
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
assert spawned[1 - stage_id].wait(5), "A different device's spawn was blocked by the READY wait"
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
clients = launch_runtime._initialize_stage_replicas([_plan(0, "0"), _plan(1, "1")], 5)
assert all(clients[stage][0] is not None for stage in (0, 1))
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
def test_same_device_waits_for_ready_before_next_spawn(
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
) -> None:
events: list[tuple[int, str]] = []
@contextlib.contextmanager
def launch(*, stage_id: int, **_kwargs: object) -> Iterator[StageReplicaResources]:
events.append((stage_id, "spawn"))
yield _resources(mocker)
events.append((stage_id, "ready"))
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
launch_runtime._initialize_stage_replicas([_plan(0, "0"), _plan(1, "0")], 5)
assert events == [(0, "spawn"), (0, "ready"), (1, "spawn"), (1, "ready")]
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
def test_ready_failure_cleans_up_resources_and_releases_device(
launch_runtime: stage_runtime.StageRuntime, monkeypatch: pytest.MonkeyPatch, mocker: MockerFixture
) -> None:
manager = mocker.Mock(spec=CoreEngineProcManager)
resources = StageReplicaResources(manager=manager, addresses=EngineZmqAddresses(inputs=[], outputs=[]))
@contextlib.contextmanager
def launch(**_kwargs: object) -> Iterator[StageReplicaResources]:
yield resources
raise RuntimeError("READY handshake failed")
monkeypatch.setattr(stage_runtime, "launch_stage_replica", launch)
with pytest.raises(RuntimeError, match="READY handshake failed"):
launch_runtime._initialize_local_llm_replica(_plan(0, "0").replicas[0], 5)
manager.shutdown.assert_called_once_with()
assert os.environ["VLLM_OMNI_TEST_LAUNCH_ENV"] == "parent"
with open(stage_init_utils.device_init_lock_path(0), "r+") as lock:
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)