[Core] Extend the shared multi-stage execution framework for mixed V1/MRv2 pipelines (#8184)
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
42 files changed
+1792
-85
No files matched your search
@@ -169,7 +169,7 @@ def test_inventory_matches_reviewed_snapshot_counts():
|
||||
EnvironmentVariableCategory.PLATFORM_EXTERNAL: 29,
|
||||
EnvironmentVariableCategory.MODEL_SPECIFIC: 66,
|
||||
EnvironmentVariableCategory.BENCHMARK_TRANSITIONAL: 21,
|
||||
EnvironmentVariableCategory.INTERNAL: 2,
|
||||
EnvironmentVariableCategory.INTERNAL: 6,
|
||||
}
|
||||
|
||||
disposition_counts = Counter(
|
||||
|
||||
@@ -822,6 +822,62 @@ def test_mrv2_fails_fast_on_platforms_without_native_workers(platform: str):
|
||||
_apply_platform_overrides(DeployConfig(model_runner="v2"), platform=platform)
|
||||
|
||||
|
||||
def _qwen3_omni_pipeline() -> PipelineConfig:
|
||||
from dataclasses import replace
|
||||
|
||||
pipeline = _resolve_pipeline_or_skip("qwen3_omni_moe", Qwen3OmniMoeConfig())
|
||||
return replace(pipeline, stages=tuple(replace(s, supports_native_mrv2_data_plane=True) for s in pipeline.stages))
|
||||
|
||||
|
||||
def test_stage_model_runner_overrides_deploy_runner(tmp_path: Path):
|
||||
deploy_path = tmp_path / "qwen3_omni_mixed_runner.yaml"
|
||||
deploy_path.write_text(
|
||||
"""\
|
||||
model_runner: v1
|
||||
async_chunk: true
|
||||
stages:
|
||||
- stage_id: 0
|
||||
- stage_id: 1
|
||||
model_runner: v2
|
||||
- stage_id: 2
|
||||
model_runner: v2
|
||||
"""
|
||||
)
|
||||
deploy = load_deploy_config(deploy_path)
|
||||
assert [stage.model_runner for stage in deploy.stages] == [None, "v2", "v2"]
|
||||
|
||||
pipeline = _qwen3_omni_pipeline()
|
||||
legacy = merge_pipeline_deploy(pipeline, deploy)
|
||||
assert [stage.yaml_engine_args["use_v2_model_runner"] for stage in legacy] == [False, True, True]
|
||||
# The test pipeline declares native support; only v2 stages use it.
|
||||
assert [stage.yaml_engine_args["supports_native_mrv2_data_plane"] for stage in legacy] == [True, True, True]
|
||||
|
||||
structured = VllmOmniConfig.from_pipeline_config(pipeline, deploy_config_path=str(deploy_path))
|
||||
assert [stage.model_config.use_v2_model_runner for stage in structured.stage_configs] == [False, True, True]
|
||||
|
||||
|
||||
def test_platform_v1_fallback_overrides_stage_v2():
|
||||
deploy = DeployConfig(
|
||||
stages=[StageDeployConfig(stage_id=0), StageDeployConfig(stage_id=1, model_runner="v2")],
|
||||
platforms={"rocm": {"model_runner": "v1"}},
|
||||
)
|
||||
deploy = _apply_platform_overrides(deploy, platform="rocm")
|
||||
assert deploy.model_runner == "v1"
|
||||
assert deploy.stages[1].model_runner is None
|
||||
|
||||
|
||||
def test_downstream_mrv2_stage_requires_turn_sessions():
|
||||
stages = [StageDeployConfig(stage_id=0), StageDeployConfig(stage_id=1, model_runner="v2")]
|
||||
with pytest.raises(ValueError, match="session_mode 'turn' only"):
|
||||
merge_pipeline_deploy(_qwen3_omni_pipeline(), DeployConfig(stages=stages, session_mode="duplex"))
|
||||
|
||||
|
||||
def test_v1_downstream_stage_keeps_duplex_sessions():
|
||||
deploy = DeployConfig(stages=[StageDeployConfig(stage_id=0)], session_mode="duplex")
|
||||
stages = merge_pipeline_deploy(_qwen3_omni_pipeline(), deploy)
|
||||
assert not any(stage.yaml_engine_args["use_v2_model_runner"] for stage in stages)
|
||||
|
||||
|
||||
def test_qwen3_tts_high_concurrency_mrv2_profile_is_explicit_opt_in():
|
||||
assert load_deploy_config(_DEPLOY_DIR / "qwen3_tts_high_concurrency.yaml").model_runner == "v1"
|
||||
assert load_deploy_config(_DEPLOY_DIR / "qwen3_tts_high_concurrency_mrv2.yaml").model_runner == "v2"
|
||||
@@ -2220,3 +2276,12 @@ def test_mps_stays_in_runtime_instead_of_engine_arguments():
|
||||
assert stage.runtime_config.cuda_mps
|
||||
args = build_engine_args_dict_from_omni_stage_config(stage, model="test-model")
|
||||
assert "cuda_mps" not in args
|
||||
|
||||
|
||||
def test_platform_stage_overlay_rejects_invalid_model_runner():
|
||||
deploy = DeployConfig(
|
||||
stages=[StageDeployConfig(stage_id=0)],
|
||||
platforms={"cuda": {"stages": [{"stage_id": 0, "model_runner": "v3"}]}},
|
||||
)
|
||||
with pytest.raises(ValueError, match="model_runner must be 'v1' or 'v2'"):
|
||||
_apply_platform_overrides(deploy, platform="cuda")
|
||||
@@ -25,8 +25,8 @@ class FakeAdapter:
|
||||
"""Minimal mock of OmniChunkTransferAdapter tracking restore calls."""
|
||||
|
||||
def __init__(self):
|
||||
self.waiting_for_chunk_waiting_requests = deque()
|
||||
self.waiting_for_chunk_running_requests = deque()
|
||||
self.waiting_for_chunk_waiting_requests: deque = deque()
|
||||
self.waiting_for_chunk_running_requests: deque = deque()
|
||||
self.restore_called = False
|
||||
self.done_request_ids = set()
|
||||
|
||||
@@ -249,3 +249,103 @@ class TestRestoreQueuesOnError:
|
||||
|
||||
assert adapter.restore_called is True
|
||||
assert "req-B" in running
|
||||
|
||||
|
||||
def test_first_chunk_express_slack_guard_tracks_emitted_audio(monkeypatch):
|
||||
"""Express steps wait while a ready later chunk's stream is close to underrun."""
|
||||
import vllm_omni.core.sched.omni_generation_scheduler as module
|
||||
|
||||
scheduler = OmniGenerationScheduler.__new__(OmniGenerationScheduler)
|
||||
scheduler._first_chunk_express = True
|
||||
scheduler._express_min_slack_s = 0.5
|
||||
scheduler._express_skipped_for_slack = 0
|
||||
scheduler._stream_audio = {}
|
||||
scheduler._chunk_started = {"started", "idle"}
|
||||
ready = SimpleNamespace(
|
||||
request_id="started", num_in_flight_tokens=0, prompt_token_ids=[0] * 28, num_computed_tokens=0
|
||||
)
|
||||
# Started, but no chunk to decode now: never blocks an express step.
|
||||
idle = SimpleNamespace(request_id="idle", num_in_flight_tokens=0, prompt_token_ids=[0] * 28, num_computed_tokens=28)
|
||||
scheduler.running = [ready, idle]
|
||||
scheduler.waiting = []
|
||||
clock = [100.0]
|
||||
monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
|
||||
|
||||
# No measured audio credit: do not delay the ready stream.
|
||||
assert not scheduler._continuations_have_slack()
|
||||
# 1 s of audio at t=100; at t=100.2 it holds 0.8 s, at t=100.7 only 0.3 s.
|
||||
scheduler._record_stream_audio("started", {"model_outputs": torch.zeros(24000), "sr": torch.tensor(24000)})
|
||||
scheduler._record_stream_audio("started", {"model_outputs": torch.zeros(0), "sr": torch.tensor(24000)})
|
||||
clock[0] = 100.2
|
||||
assert scheduler._continuations_have_slack()
|
||||
clock[0] = 100.7
|
||||
assert not scheduler._continuations_have_slack()
|
||||
# Another second emitted: slack is back to 1.3 s.
|
||||
scheduler._record_stream_audio("started", {"model_outputs": torch.zeros(24000), "sr": torch.tensor(24000)})
|
||||
assert scheduler._continuations_have_slack()
|
||||
assert scheduler._stream_audio["started"] == [100.0, 2.0]
|
||||
|
||||
|
||||
def _express_scheduler():
|
||||
continuation = Request("continuation", [1, 2], SamplingParams(max_tokens=4), pooling_params=None)
|
||||
first = Request("first", [1], SamplingParams(max_tokens=4), pooling_params=None)
|
||||
scheduler = _make_generation_scheduler(continuation, use_v2_model_runner=True)
|
||||
scheduler.waiting.add_request(first)
|
||||
scheduler.requests[first.request_id] = first
|
||||
scheduler.max_num_running_reqs = 4
|
||||
scheduler._native_data_plane = True
|
||||
scheduler.chunk_transfer_adapter = None
|
||||
scheduler.input_coordinator = SimpleNamespace(
|
||||
_async_chunk=True, finished_requests=set(), restore_queues=lambda *args, **kwargs: None
|
||||
)
|
||||
scheduler._first_chunk_express = True
|
||||
scheduler._last_step_express = False
|
||||
scheduler._chunk_started = {"continuation"}
|
||||
scheduler._express_min_slack_s = 0
|
||||
scheduler._stream_audio = {}
|
||||
return scheduler, continuation, first
|
||||
|
||||
|
||||
def test_express_schedules_only_first_chunks_then_allows_continuations():
|
||||
scheduler, continuation, first = _express_scheduler()
|
||||
output = scheduler.schedule()
|
||||
assert output.num_scheduled_tokens == {"first": 1}
|
||||
assert scheduler._last_step_express
|
||||
assert continuation in list(scheduler.waiting)
|
||||
# Another first chunk arrives before the continuation runs.
|
||||
first.num_computed_tokens = len(first.prompt_token_ids)
|
||||
second = Request("second", [1], SamplingParams(max_tokens=4), pooling_params=None)
|
||||
scheduler.waiting.add_request(second)
|
||||
scheduler.requests[second.request_id] = second
|
||||
output = scheduler.schedule()
|
||||
assert not scheduler._last_step_express
|
||||
assert "continuation" in output.num_scheduled_tokens
|
||||
|
||||
|
||||
def test_express_does_not_delay_continuation_for_unready_first_chunk():
|
||||
scheduler, continuation, first = _express_scheduler()
|
||||
first.num_in_flight_tokens = 1
|
||||
output = scheduler.schedule()
|
||||
assert not scheduler._last_step_express
|
||||
assert output.num_scheduled_tokens == {"continuation": 2}
|
||||
|
||||
|
||||
def test_express_slack_guard_is_used_by_schedule():
|
||||
scheduler, continuation, first = _express_scheduler()
|
||||
scheduler._express_min_slack_s = 0.5
|
||||
scheduler._express_skipped_for_slack = 0
|
||||
output = scheduler.schedule()
|
||||
assert not scheduler._last_step_express
|
||||
assert "continuation" in output.num_scheduled_tokens
|
||||
|
||||
|
||||
def test_express_cancel_cleans_playback_state(monkeypatch):
|
||||
from vllm.v1.core.sched.scheduler import Scheduler
|
||||
|
||||
scheduler, continuation, _ = _express_scheduler()
|
||||
scheduler.input_coordinator = None
|
||||
scheduler._stream_audio["continuation"] = [1.0, 2.0]
|
||||
monkeypatch.setattr(Scheduler, "_free_request", lambda *args: (None, None))
|
||||
scheduler._free_request(continuation)
|
||||
assert "continuation" not in scheduler._chunk_started
|
||||
assert "continuation" not in scheduler._stream_audio
|
||||
@@ -118,6 +118,8 @@ def test_resumable_generation_stop_marks_segment_boundary() -> None:
|
||||
session.num_in_flight_tokens = 1
|
||||
|
||||
sched = MagicMock()
|
||||
sched._first_chunk_express = False
|
||||
sched._express_min_slack_s = 0.0
|
||||
sched.requests = {session.request_id: session}
|
||||
sched.perf_metrics = None
|
||||
sched.chunk_transfer_adapter = SimpleNamespace(
|
||||
@@ -185,6 +187,8 @@ def test_rejected_grammar_finishes_and_frees_generation_request(prompt_complete:
|
||||
session.num_in_flight_tokens = 1
|
||||
|
||||
sched = MagicMock()
|
||||
sched._first_chunk_express = False
|
||||
sched._express_min_slack_s = 0.0
|
||||
sched.requests = {session.request_id: session}
|
||||
sched.perf_metrics = None
|
||||
sched.chunk_transfer_adapter = SimpleNamespace(
|
||||
|
||||
@@ -120,6 +120,8 @@ def _make_finish_sched(request: Request) -> MagicMock:
|
||||
"""MagicMock scheduler driving the real ``update_from_output`` through a
|
||||
finishing request; ``_free_request`` reports EC transfer params."""
|
||||
sched = MagicMock()
|
||||
sched._first_chunk_express = False
|
||||
sched._express_min_slack_s = 0.0
|
||||
sched.requests = {request.request_id: request}
|
||||
sched.perf_metrics = None
|
||||
sched.defer_block_free = False
|
||||
|
||||
@@ -53,6 +53,8 @@ def _make_request() -> Request:
|
||||
|
||||
def _make_sched(request: Request) -> MagicMock:
|
||||
sched = MagicMock()
|
||||
sched._first_chunk_express = False
|
||||
sched._express_min_slack_s = 0.0
|
||||
sched.requests = {request.request_id: request}
|
||||
sched.perf_metrics = None
|
||||
sched.defer_block_free = False
|
||||
|
||||
@@ -175,7 +175,7 @@ def test_finished_request_attachment_keeps_ar_abort_policy_explicit(
|
||||
):
|
||||
scheduler = _Scheduler()
|
||||
scheduler.finished_req_ids_dict = defaultdict(set, {2: {"req-finished"}})
|
||||
outputs = {}
|
||||
outputs: dict = {}
|
||||
|
||||
scheduler._attach_finished_request_sets(
|
||||
outputs,
|
||||
@@ -207,3 +207,26 @@ def test_output_helper_preserves_required_nan_counter_default():
|
||||
output = scheduler._make_omni_engine_output(request, new_token_ids=[])
|
||||
|
||||
assert output.num_nans_in_logits == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("role", "coordinated"), [("sender", False), ("receiver", True), (None, True)])
|
||||
def test_native_downstream_sender_stage_does_not_wait_for_chunks(role, coordinated):
|
||||
"""An orchestrator-fed downstream stage (MiniCPM-o's Talker) owns only an
|
||||
outgoing connector; the native plane must not park it for input chunks."""
|
||||
scheduler = _Scheduler()
|
||||
model_config = object.__new__(OmniModelConfig)
|
||||
model_config.stage_id = 1
|
||||
model_config.async_chunk = True
|
||||
model_config.requires_full_payload_input = False
|
||||
model_config.supports_native_mrv2_data_plane = True
|
||||
model_config.use_v2_model_runner = True
|
||||
model_config.stage_connector_config = {"name": "SharedMemoryConnector", "extra": {"role": role} if role else {}}
|
||||
scheduler.vllm_config = object.__new__(VllmConfig)
|
||||
scheduler.vllm_config.model_config = model_config
|
||||
scheduler.vllm_config.scheduler_config = object.__new__(SchedulerConfig)
|
||||
scheduler.vllm_config.scheduler_config.max_num_seqs = 1
|
||||
scheduler._init_omni_io_scheduling_state()
|
||||
|
||||
assert scheduler._native_data_plane
|
||||
assert (scheduler.input_coordinator is not None) is coordinated
|
||||
assert scheduler._async_chunk_transport_enabled() is coordinated
|
||||
@@ -64,7 +64,7 @@ class _MoveableModule(nn.Module):
|
||||
return [True, True, True]
|
||||
|
||||
|
||||
def _run_pipeline_init(monkeypatch, *, enable_cpu_offload, loader_device):
|
||||
def _run_pipeline_init(monkeypatch, *, enable_cpu_offload, loader_device, diffusion_offload_config=None):
|
||||
import vllm_omni.diffusion.models.qwen_image.pipeline_qwen_image as pipe_mod
|
||||
from vllm_omni.diffusion.models.qwen_image.pipeline_qwen_image import QwenImagePipeline
|
||||
|
||||
@@ -110,14 +110,21 @@ def _run_pipeline_init(monkeypatch, *, enable_cpu_offload, loader_device):
|
||||
tf_model_config={},
|
||||
quantization_config=None,
|
||||
enable_cpu_offload=enable_cpu_offload,
|
||||
diffusion_offload_config=diffusion_offload_config,
|
||||
enable_diffusion_pipeline_profiler=False,
|
||||
)
|
||||
return QwenImagePipeline(od_config=od_config)
|
||||
|
||||
|
||||
def test_pipeline_cpu_offload_parks_encoder_vae_on_cpu(monkeypatch):
|
||||
@pytest.mark.parametrize("compact", [False, True])
|
||||
def test_pipeline_cpu_offload_parks_encoder_vae_on_cpu(monkeypatch, compact):
|
||||
"""#7555: cpu_offload keeps BF16 encoder/VAE off the GPU during DiT init."""
|
||||
pipe = _run_pipeline_init(monkeypatch, enable_cpu_offload=True, loader_device="cuda")
|
||||
pipe = _run_pipeline_init(
|
||||
monkeypatch,
|
||||
enable_cpu_offload=not compact,
|
||||
loader_device="cuda",
|
||||
diffusion_offload_config={"mode": "module", "components": ["dit"]} if compact else None,
|
||||
)
|
||||
assert pipe.text_encoder.placed_device.type == "cpu"
|
||||
assert pipe.vae.placed_device.type == "cpu"
|
||||
assert pipe.transformer.probe_device_type == "cuda"
|
||||
|
||||
@@ -224,7 +224,7 @@ def test_streaming_payload_can_replace_placeholder_prompt(mocker: MockerFixture)
|
||||
|
||||
def test_turn_start_replacement_ignores_accumulated_prompt_capacity(mocker: MockerFixture) -> None:
|
||||
request = _streaming_request(mocker, num_computed_tokens=4064)
|
||||
payload = {
|
||||
payload: dict = {
|
||||
"ids": {"prompt": [1]},
|
||||
"meta": {
|
||||
"replace_streaming_prompt": True,
|
||||
@@ -336,7 +336,7 @@ def test_streaming_window_builds_one_chunk_recompute_recipe(mocker: MockerFixtur
|
||||
num_output_placeholders=1,
|
||||
update_block_hashes=mocker.Mock(),
|
||||
)
|
||||
payload = {
|
||||
payload: dict = {
|
||||
"ids": {"prompt": [1]},
|
||||
"meta": {
|
||||
"next_stage_prompt_len": 10,
|
||||
@@ -406,7 +406,7 @@ def test_streaming_window_appends_until_capacity_then_recomputes(mocker: MockerF
|
||||
num_output_placeholders=0,
|
||||
update_block_hashes=mocker.Mock(),
|
||||
)
|
||||
second = {
|
||||
second: dict = {
|
||||
"ids": {"prompt": [1]},
|
||||
"meta": {
|
||||
"next_stage_prompt_len": 12,
|
||||
@@ -432,7 +432,7 @@ def test_streaming_window_appends_until_capacity_then_recomputes(mocker: MockerF
|
||||
request._all_token_ids.extend([201, 202, 203])
|
||||
request._output_token_ids.extend([201, 202, 203])
|
||||
request.num_computed_tokens = 4017
|
||||
third = {
|
||||
third: dict = {
|
||||
"ids": {"prompt": [2]},
|
||||
"meta": {
|
||||
"next_stage_prompt_len": 60,
|
||||
@@ -458,7 +458,7 @@ def test_streaming_window_appends_until_capacity_then_recomputes(mocker: MockerF
|
||||
request._all_token_ids.extend([301])
|
||||
request._output_token_ids.extend([301])
|
||||
request.num_computed_tokens = 76
|
||||
fourth = {
|
||||
fourth: dict = {
|
||||
"ids": {"prompt": [3]},
|
||||
"meta": {
|
||||
"next_stage_prompt_len": 8,
|
||||
@@ -1806,7 +1806,7 @@ def test_sender_only_adapter_does_not_park_or_clear_requests(build_adapter):
|
||||
request = _req("req-1", RequestStatus.WAITING)
|
||||
request.additional_information = {"tts_token_ids": torch.tensor([1])}
|
||||
waiting_queue = DummyWaitingQueue([request])
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
|
||||
adapter.load_async(request)
|
||||
adapter.process_pending_chunks(
|
||||
@@ -1846,7 +1846,7 @@ def test_fifo_promotion(build_adapter):
|
||||
adapter, _ = build_adapter(stage_id=1, model_mode="generation", max_num_seqs=2, active_stream_window=2)
|
||||
reqs = [_req(f"req-{idx}", RequestStatus.WAITING) for idx in range(1, 5)]
|
||||
waiting_queue = DummyWaitingQueue(reqs)
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
|
||||
adapter.process_pending_chunks(waiting_queue, running_queue)
|
||||
|
||||
@@ -1876,7 +1876,7 @@ def test_non_active_waiting_request_is_held_off_scheduler(build_adapter):
|
||||
active = _req("req-active", RequestStatus.WAITING)
|
||||
non_active = _req("req-non-active", RequestStatus.WAITING)
|
||||
waiting_queue = DummyWaitingQueue([active, non_active])
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
|
||||
adapter.process_pending_chunks(waiting_queue, running_queue)
|
||||
|
||||
@@ -1911,7 +1911,7 @@ def test_finished_releases_slot(build_adapter):
|
||||
req_1 = _req("req-1", RequestStatus.WAITING)
|
||||
req_2 = _req("req-2", RequestStatus.WAITING)
|
||||
waiting_queue = DummyWaitingQueue([req_1, req_2])
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
|
||||
adapter.process_pending_chunks(waiting_queue, running_queue)
|
||||
assert list(adapter._active_streams) == ["req-1"]
|
||||
@@ -2004,7 +2004,7 @@ def test_cleanup_receiver_releases_multiple_slots_in_sequence(build_adapter):
|
||||
adapter, _ = build_adapter(stage_id=1, model_mode="generation", max_num_seqs=2, active_stream_window=2)
|
||||
reqs = [_req(f"req-{idx}", RequestStatus.WAITING) for idx in range(1, 5)]
|
||||
waiting_queue = DummyWaitingQueue(reqs)
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
|
||||
adapter.process_pending_chunks(waiting_queue, running_queue)
|
||||
assert list(adapter._active_streams) == ["req-1", "req-2"]
|
||||
@@ -2364,7 +2364,7 @@ def test_finish_requests_releases_active_stream_slot(build_adapter):
|
||||
aborted = _req("req-aborted", RequestStatus.RUNNING)
|
||||
waiting = _req("req-waiting", RequestStatus.WAITING)
|
||||
waiting_queue = DummyWaitingQueue([waiting])
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
adapter._active_streams[aborted.request_id] = aborted
|
||||
adapter._held_non_active.append(aborted)
|
||||
|
||||
@@ -2488,7 +2488,7 @@ def test_restore_queues_skips_requests_missing_from_scheduler_requests(build_ada
|
||||
zombie = _req("req-zombie", RequestStatus.WAITING_FOR_CHUNK)
|
||||
live = _req("req-live", RequestStatus.WAITING_FOR_CHUNK)
|
||||
waiting_queue = DummyWaitingQueue()
|
||||
running_queue = []
|
||||
running_queue: list = []
|
||||
adapter.waiting_for_chunk_waiting_requests = deque([zombie, live])
|
||||
adapter.waiting_for_chunk_running_requests = deque([zombie, live])
|
||||
|
||||
@@ -2522,7 +2522,7 @@ class _HashableRequest(SimpleNamespace):
|
||||
# double needs it too.
|
||||
num_stale_output_tokens = 0
|
||||
|
||||
def __hash__(self):
|
||||
def __hash__(self): # type: ignore[override] # Test requests are hashable by request ID.
|
||||
return hash(self.request_id)
|
||||
|
||||
def __eq__(self, other):
|
||||
@@ -2540,6 +2540,8 @@ def test_generation_scheduler_calls_cleanup_on_finished(monkeypatch, mocker: Moc
|
||||
from vllm_omni.core.sched.omni_generation_scheduler import OmniGenerationScheduler
|
||||
|
||||
scheduler = mocker.MagicMock()
|
||||
scheduler._first_chunk_express = False
|
||||
scheduler._express_min_slack_s = 0.0
|
||||
scheduler.chunk_transfer_adapter = adapter_mock
|
||||
scheduler.connector = None
|
||||
scheduler.ec_connector = None
|
||||
|
||||
@@ -294,3 +294,280 @@ def test_consumed_bad_payload_removes_lock_file(connector, monkeypatch):
|
||||
assert not os.path.exists(f"/dev/shm/shm_{key}_lockfile.lock")
|
||||
connector.reap_consumed()
|
||||
assert key not in connector._pending_keys
|
||||
|
||||
|
||||
# ── Arrival wakeups ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _stage_connector(stage_id):
|
||||
return SharedMemoryConnector({"stage_id": stage_id})
|
||||
|
||||
|
||||
def test_wakeup_discovery_only_scans_deployment_directory(monkeypatch, tmp_path):
|
||||
from vllm_omni.distributed.omni_connectors.connectors import shm_connector as module
|
||||
|
||||
directory = tmp_path / "deployment"
|
||||
monkeypatch.setattr(module, "_wakeup_directory", lambda: str(directory))
|
||||
original_scandir = os.scandir
|
||||
scanned = []
|
||||
|
||||
def scoped_scandir(path):
|
||||
# A parent-directory scan would recreate the performance regression.
|
||||
assert os.fspath(path) == str(directory)
|
||||
scanned.append(path)
|
||||
return original_scandir(path)
|
||||
|
||||
monkeypatch.setattr(module.glob.os, "scandir", scoped_scandir)
|
||||
sender, receiver = _stage_connector(86), _stage_connector(87)
|
||||
try:
|
||||
generation = receiver.get_wakeup_generation()
|
||||
assert generation is not None
|
||||
assert os.path.dirname(receiver._wake_path) == str(directory)
|
||||
sender._wake_receiver(87)
|
||||
assert receiver.wait_for_change(generation, timeout=0.5)
|
||||
assert scanned
|
||||
finally:
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_missing_wakeup_directory_keeps_payload_transport_working(monkeypatch, tmp_path):
|
||||
from vllm_omni.distributed.omni_connectors.connectors import shm_connector as module
|
||||
|
||||
directory = tmp_path / "missing"
|
||||
monkeypatch.setattr(module, "_wakeup_directory", lambda: str(directory))
|
||||
sender, receiver = _stage_connector(88), _stage_connector(89)
|
||||
key = f"wake_{uuid.uuid4().hex}"
|
||||
try:
|
||||
assert sender.put("88", "89", key, {"value": 1})[0]
|
||||
assert not directory.exists()
|
||||
assert receiver.get("88", "89", key)[0] == {"value": 1}
|
||||
finally:
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_put_wakes_waiting_receiver():
|
||||
sender, receiver = _stage_connector(70), _stage_connector(71)
|
||||
try:
|
||||
generation = receiver.get_wakeup_generation()
|
||||
assert generation is not None
|
||||
start = time.monotonic()
|
||||
assert receiver.wait_for_change(generation, timeout=0.05) is False
|
||||
assert time.monotonic() - start >= 0.04 # no arrival: blocks for the timeout
|
||||
|
||||
key = f"wake_{uuid.uuid4().hex}"
|
||||
sender.put("70", "71", key, {"value": 1})
|
||||
start = time.monotonic()
|
||||
assert receiver.wait_for_change(generation, timeout=5) is True
|
||||
assert time.monotonic() - start < 0.5
|
||||
assert receiver.get("70", "71", key)[0] == {"value": 1}
|
||||
# Drained: the next wait blocks again.
|
||||
assert receiver.wait_for_change(receiver.get_wakeup_generation(), timeout=0.02) is False
|
||||
finally:
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_receiver_does_not_spin_after_sender_closes():
|
||||
sender, receiver = _stage_connector(72), _stage_connector(73)
|
||||
try:
|
||||
receiver.get_wakeup_generation()
|
||||
sender.put("72", "73", f"wake_{uuid.uuid4().hex}", {"value": 1})
|
||||
sender.close() # the only external writer goes away
|
||||
generation = receiver.get_wakeup_generation()
|
||||
receiver.wait_for_change(generation, timeout=1)
|
||||
generation = receiver.get_wakeup_generation()
|
||||
start = time.monotonic()
|
||||
assert receiver.wait_for_change(generation, timeout=0.05) is False
|
||||
assert time.monotonic() - start >= 0.04
|
||||
finally:
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_wakeups_can_be_disabled_and_close_unlinks_fifo(monkeypatch):
|
||||
receiver = _stage_connector(74)
|
||||
assert receiver.get_wakeup_generation() is not None
|
||||
path = receiver._wake_path
|
||||
assert os.path.exists(path)
|
||||
receiver.close()
|
||||
assert not os.path.exists(path)
|
||||
|
||||
monkeypatch.setenv("VLLM_OMNI_SHM_WAKEUP", "0")
|
||||
sender, receiver = _stage_connector(75), _stage_connector(76)
|
||||
try:
|
||||
assert receiver.get_wakeup_generation() is None # caller keeps its timed poll
|
||||
key = f"wake_{uuid.uuid4().hex}"
|
||||
assert sender.put("75", "76", key, {"value": 2})[0]
|
||||
assert receiver.get("75", "76", key)[0] == {"value": 2}
|
||||
finally:
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
|
||||
def _sibling_receiver(stage_id, ready, result):
|
||||
receiver = _stage_connector(stage_id)
|
||||
generation = receiver.get_wakeup_generation()
|
||||
ready.set()
|
||||
start = time.monotonic()
|
||||
woke = receiver.wait_for_change(generation, timeout=5)
|
||||
result.put((woke, time.monotonic() - start))
|
||||
receiver.close()
|
||||
|
||||
|
||||
def _sibling_sender(stage_id, key):
|
||||
sender = _stage_connector(stage_id - 1)
|
||||
sender.put(str(stage_id - 1), str(stage_id), key, {"value": 3})
|
||||
|
||||
|
||||
def test_sibling_stage_processes_share_wakeups():
|
||||
# Stage engine processes are siblings under the launching process.
|
||||
import multiprocessing
|
||||
|
||||
ctx = multiprocessing.get_context("fork")
|
||||
ready, result = ctx.Event(), ctx.Queue()
|
||||
key = f"wake_{uuid.uuid4().hex}"
|
||||
receiver = ctx.Process(target=_sibling_receiver, args=(78, ready, result))
|
||||
receiver.start()
|
||||
assert ready.wait(5)
|
||||
time.sleep(0.05)
|
||||
sender = ctx.Process(target=_sibling_sender, args=(78, key))
|
||||
sender.start()
|
||||
sender.join(5)
|
||||
woke, waited = result.get(timeout=5)
|
||||
receiver.join(5)
|
||||
assert woke and waited < 1.0
|
||||
cleanup = SharedMemoryConnector({})
|
||||
cleanup.cleanup(key)
|
||||
|
||||
|
||||
def test_same_stage_receivers_are_independent_across_close_and_restart():
|
||||
sender = _stage_connector(80)
|
||||
first, second = _stage_connector(81), _stage_connector(81)
|
||||
replacement = None
|
||||
try:
|
||||
first_generation = first.get_wakeup_generation()
|
||||
second_generation = second.get_wakeup_generation()
|
||||
assert first._wake_path != second._wake_path
|
||||
sender._wake_receiver(81)
|
||||
assert first.wait_for_change(first_generation, timeout=0.5)
|
||||
assert second.wait_for_change(second_generation, timeout=0.5)
|
||||
second_generation = second.get_wakeup_generation()
|
||||
first.close()
|
||||
assert first.get_wakeup_generation() is None
|
||||
assert os.path.exists(second._wake_path)
|
||||
replacement = _stage_connector(81)
|
||||
replacement_generation = replacement.get_wakeup_generation()
|
||||
sender._wake_receiver(81)
|
||||
assert second.wait_for_change(second_generation, timeout=0.5)
|
||||
assert replacement.wait_for_change(replacement_generation, timeout=0.5)
|
||||
finally:
|
||||
sender.close()
|
||||
first.close()
|
||||
second.close()
|
||||
if replacement is not None:
|
||||
replacement.close()
|
||||
|
||||
|
||||
def test_partial_receiver_open_closes_fd_and_removes_only_own_fifo(monkeypatch, tmp_path):
|
||||
import errno
|
||||
|
||||
from vllm_omni.distributed.omni_connectors.connectors import shm_connector as module
|
||||
|
||||
monkeypatch.setattr(module, "_wakeup_directory", lambda: str(tmp_path))
|
||||
receiver = _stage_connector(82)
|
||||
peer_path = tmp_path / "stage_82_peer"
|
||||
os.mkfifo(peer_path, 0o600)
|
||||
original_open = os.open
|
||||
opened = []
|
||||
|
||||
def fail_hold_open(path, flags, *args, **kwargs):
|
||||
if flags & os.O_WRONLY:
|
||||
raise OSError(errno.EMFILE, "injected fd exhaustion")
|
||||
fd = original_open(path, flags, *args, **kwargs)
|
||||
opened.append(fd)
|
||||
return fd
|
||||
|
||||
monkeypatch.setattr(module.os, "open", fail_hold_open)
|
||||
try:
|
||||
assert receiver.get_wakeup_generation() is None
|
||||
assert list(tmp_path.iterdir()) == [peer_path]
|
||||
assert len(opened) == 1
|
||||
with pytest.raises(OSError, match="Bad file descriptor"):
|
||||
os.fstat(opened[0])
|
||||
finally:
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_wakeup_ignores_stale_fifo_and_non_fifo_paths(monkeypatch, tmp_path):
|
||||
from vllm_omni.distributed.omni_connectors.connectors import shm_connector as module
|
||||
|
||||
monkeypatch.setattr(module, "_wakeup_directory", lambda: str(tmp_path))
|
||||
sender, receiver = _stage_connector(83), _stage_connector(84)
|
||||
plain = tmp_path / "84_plain"
|
||||
plain.write_text("unchanged")
|
||||
(tmp_path / "84_link").symlink_to(plain)
|
||||
os.mkfifo(tmp_path / "84_stale", 0o600)
|
||||
try:
|
||||
generation = receiver.get_wakeup_generation()
|
||||
sender._wake_receiver(84)
|
||||
assert receiver.wait_for_change(generation, timeout=0.5)
|
||||
assert plain.read_text() == "unchanged"
|
||||
assert (tmp_path / "84_stale").exists()
|
||||
finally:
|
||||
sender.close()
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_waiter_does_not_read_fd_reused_after_close(monkeypatch, tmp_path):
|
||||
from vllm_omni.distributed.omni_connectors.connectors import shm_connector as module
|
||||
|
||||
receiver = _stage_connector(85)
|
||||
generation = receiver.get_wakeup_generation()
|
||||
read_fd = receiver._wake_read_fd
|
||||
path = tmp_path / "unrelated_ipc"
|
||||
path.write_bytes(b"untouched")
|
||||
reused = []
|
||||
|
||||
def close_during_select(*args):
|
||||
receiver.close()
|
||||
fd = os.open(path, os.O_RDONLY)
|
||||
if fd != read_fd:
|
||||
os.dup2(fd, read_fd)
|
||||
os.close(fd)
|
||||
reused.append(read_fd)
|
||||
return [read_fd], [], []
|
||||
|
||||
monkeypatch.setattr(module.select, "select", close_during_select)
|
||||
try:
|
||||
assert not receiver.wait_for_change(generation, timeout=0.1)
|
||||
assert os.lseek(read_fd, 0, os.SEEK_CUR) == 0
|
||||
finally:
|
||||
for fd in reused:
|
||||
os.close(fd)
|
||||
receiver.close()
|
||||
|
||||
|
||||
def test_deployment_scope_survives_different_worker_parents(monkeypatch):
|
||||
config = {"stage_id": 1, "extra": {"wakeup_scope": uuid.uuid4().hex}}
|
||||
monkeypatch.setattr(os, "getppid", lambda: 111)
|
||||
receiver = SharedMemoryConnector(config)
|
||||
monkeypatch.setattr(os, "getppid", lambda: 222)
|
||||
sender = SharedMemoryConnector(config)
|
||||
try:
|
||||
generation = receiver.get_wakeup_generation()
|
||||
sender._wake_receiver(1)
|
||||
assert receiver.wait_for_change(generation, timeout=0.1)
|
||||
directory = receiver._wake_directory
|
||||
finally:
|
||||
receiver.close()
|
||||
sender.close()
|
||||
assert not os.path.exists(directory)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value,expected", [("bad", 0.005), ("nan", 0.005), ("-1", 0.005), ("20", 0.02)])
|
||||
def test_receive_poll_interval_validation(monkeypatch, value, expected):
|
||||
from vllm_omni.distributed.omni_connectors.model_runner.omni_connector_payload_transport import _recv_poll_seconds
|
||||
|
||||
monkeypatch.setenv("VLLM_OMNI_CONNECTOR_RECV_POLL_MS", value)
|
||||
assert _recv_poll_seconds() == expected
|
||||
@@ -519,6 +519,40 @@ async def test_async_chunk_prewarm_without_prompt_token_ids_fails_only_that_requ
|
||||
orchestrator_fixture.thread.join(timeout=5)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_streaming_input_to_mrv2_downstream_stage_fails_with_client_error(orchestrator_factory) -> None:
|
||||
"""A downstream MRv2 native-data-plane stage supports turn-based requests
|
||||
only: a resumable (realtime) request must fail up front, not hang."""
|
||||
stage0 = FakeStageClient(stage_type="llm", final_output=False)
|
||||
stage1 = FakeStageClient(stage_type="llm", final_output=True)
|
||||
v1 = SimpleNamespace(model_config=SimpleNamespace(max_model_len=64))
|
||||
mrv2 = SimpleNamespace(
|
||||
model_config=SimpleNamespace(max_model_len=64, use_v2_model_runner=True, supports_native_mrv2_data_plane=True)
|
||||
)
|
||||
fixture = orchestrator_factory([stage0, stage1], stage_vllm_configs=[v1, mrv2], async_chunk=True)
|
||||
|
||||
try:
|
||||
await _enqueue_add_request(
|
||||
fixture,
|
||||
request_id="req-stream",
|
||||
prompt=SimpleNamespace(request_id="req-stream", prompt_token_ids=[1, 2], resumable=True),
|
||||
original_prompt={"prompt": "stream"},
|
||||
sampling_params_list=[_sampling_params(), _sampling_params()],
|
||||
final_stage_id=1,
|
||||
)
|
||||
|
||||
error_msg = await _wait_for_error_message(fixture, request_id="req-stream")
|
||||
assert error_msg.fatal is False
|
||||
assert error_msg.status_code == 400
|
||||
assert "stage 1 runs on model_runner v2" in error_msg.error
|
||||
assert stage0.add_request_calls == [] and stage1.add_request_calls == []
|
||||
assert fixture.thread.is_alive()
|
||||
finally:
|
||||
if fixture.thread.is_alive():
|
||||
fixture.request_sync_q.put_nowait(ShutdownRequestMessage())
|
||||
fixture.thread.join(timeout=5)
|
||||
|
||||
|
||||
# ───────── Direct unit tests for the fault-isolation helpers ─────────
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.utils.device_copy import to_device_nonblocking
|
||||
|
||||
pytestmark = pytest.mark.core_model
|
||||
|
||||
|
||||
@pytest.mark.cpu
|
||||
def test_tensor_copy_cpu_preserves_view_and_dtype():
|
||||
source = torch.arange(12, dtype=torch.float64).reshape(3, 4).T
|
||||
result = to_device_nonblocking(source, "cpu")
|
||||
assert result is source
|
||||
assert result.dtype == torch.float64
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_tensor_copy_cuda_handles_pageable_and_pinned_sources():
|
||||
if not torch.cuda.is_available():
|
||||
pytest.skip("CUDA required")
|
||||
source = torch.arange(12, dtype=torch.float32).reshape(3, 4).T
|
||||
for host in (source, source.pin_memory()):
|
||||
result = to_device_nonblocking(host, "cuda")
|
||||
torch.testing.assert_close(result.cpu(), host)
|
||||
assert to_device_nonblocking(result, result.device) is result
|
||||
@@ -607,6 +607,39 @@ def test_update_additional_information_deserializes_new_request_payload():
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replace_payload", [False, True])
|
||||
def test_resumed_streaming_payload_converts_to_typed_model_input(replace_payload):
|
||||
from vllm_omni.core.sched.output import OmniNewRequestData
|
||||
from vllm_omni.data_entry_keys import to_struct
|
||||
|
||||
runner = _make_runner(req_ids=("r1",), hidden_size=4)
|
||||
runner.model.replace_runtime_additional_information = replace_payload
|
||||
payload = {
|
||||
"codes": {"audio": torch.tensor([1, 2])},
|
||||
"meta": {"req_id": ["r1"], "stream_finished": torch.tensor(False)},
|
||||
}
|
||||
new_req = OmniNewRequestData(
|
||||
req_id="r1",
|
||||
prompt_token_ids=[1, 2],
|
||||
mm_features=[],
|
||||
sampling_params=None,
|
||||
pooling_params=None,
|
||||
block_ids=([],),
|
||||
num_computed_tokens=0,
|
||||
lora_request=None,
|
||||
model_intermediate_buffer=payload,
|
||||
)
|
||||
|
||||
OmniGPUModelRunner._update_streaming_input_additional_info(runner, new_req, "r1")
|
||||
# CosyVoice and other typed-payload consumers perform this conversion
|
||||
# after the runner adds its resume metadata.
|
||||
result = to_struct(runner.model_intermediate_buffer["r1"])
|
||||
assert result.meta.resumable is True
|
||||
assert result.meta.num_processed_tokens == 0
|
||||
assert result.meta.req_id == ["r1"]
|
||||
torch.testing.assert_close(result.codes.audio, payload["codes"]["audio"])
|
||||
|
||||
|
||||
def test_streaming_new_request_marker_replaces_terminal_chunk_snapshot():
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
|
||||
@@ -1222,3 +1255,30 @@ def test_decode_batch_without_mtp_rejects_incomplete_outputs(monkeypatch, invali
|
||||
with pytest.raises(ValueError, match="decode preprocessing"):
|
||||
runner._preprocess(scheduled, 2)
|
||||
assert torch.equal(runner.inputs_embeds.gpu, before)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("supports_boundaries", [False, True])
|
||||
def test_multimodal_embeddings_receive_opt_in_host_request_boundaries(supports_boundaries):
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
received = {}
|
||||
|
||||
def embed(ids, **kwargs):
|
||||
received.update(kwargs)
|
||||
return ids
|
||||
|
||||
runner.model = SimpleNamespace(supports_embed_input_ids_query_start_loc=supports_boundaries, embed_input_ids=embed)
|
||||
runner.input_batch = SimpleNamespace(num_reqs=3)
|
||||
runner.query_start_loc = SimpleNamespace(cpu=torch.tensor([0, 6, 7, 11, 999]))
|
||||
runner.input_ids = SimpleNamespace(gpu=torch.arange(16))
|
||||
mm = [torch.ones(2, 4), torch.ones(1, 4)]
|
||||
mask = torch.tensor([True] * 4 + [False] * 3 + [True] * 3 + [False])
|
||||
|
||||
result = runner._embed_multimodal_input_ids(11, mm, mask)
|
||||
|
||||
torch.testing.assert_close(result, torch.arange(11))
|
||||
assert received["multimodal_embeddings"] is mm
|
||||
assert received["is_multimodal"] is mask
|
||||
if supports_boundaries:
|
||||
assert received["query_start_loc"] == [0, 6, 7, 11]
|
||||
else:
|
||||
assert "query_start_loc" not in received
|
||||
@@ -94,3 +94,25 @@ def test_update_merge_semantics(monkeypatch):
|
||||
assert stored is not tensor
|
||||
assert torch.equal(stored, tensor)
|
||||
assert "kv" in buf.buffers[0]
|
||||
|
||||
|
||||
def test_add_request_merges_orchestrator_model_intermediate_buffer():
|
||||
"""Stage bridges such as MiniCPM-o's llm2tts hand over ``model_intermediate_buffer``."""
|
||||
buf = OmniIntermediateBuffer(max_num_reqs=2)
|
||||
hidden = torch.randn(3, 4)
|
||||
data = _make_new_req_data(
|
||||
"talker-1",
|
||||
additional_information={"meta": {"a": 1}},
|
||||
model_intermediate_buffer={
|
||||
"ids": {"tts": [1, 2, 3]},
|
||||
"hidden_states": {"tts": hidden},
|
||||
"meta": {"next_stage_prompt_len": 5},
|
||||
"request_id": "thinker-1",
|
||||
},
|
||||
)
|
||||
buf.add_request(0, data)
|
||||
info = buf.buffers[0]
|
||||
assert info["ids"]["tts"] == [1, 2, 3]
|
||||
assert torch.equal(info["hidden_states"]["tts"], hidden)
|
||||
assert info["meta"] == {"a": 1, "next_stage_prompt_len": 5}
|
||||
assert info["request_id"] == "thinker-1" and info["req_id"] == "talker-1"
|
||||
@@ -185,6 +185,7 @@ def _start_save_thread(plane, connector):
|
||||
_send_side_request_payload={},
|
||||
_code_prompt_token_ids=defaultdict(list),
|
||||
_work_available=threading.Event(),
|
||||
_save_work_available=threading.Event(),
|
||||
_stop_event=threading.Event(),
|
||||
_MAX_SEND_RETRIES=0,
|
||||
_can_send=True,
|
||||
@@ -199,7 +200,7 @@ def _start_save_thread(plane, connector):
|
||||
|
||||
def _stop_save_thread(plane):
|
||||
plane._stop_event.set()
|
||||
plane._work_available.set()
|
||||
plane._save_work_available.set()
|
||||
plane._save_thread.join(timeout=2)
|
||||
assert not plane._save_thread.is_alive()
|
||||
|
||||
@@ -551,3 +552,71 @@ def test_abort_before_first_chunk_cleans_receiver_state():
|
||||
assert plane.abort_requests({"r"}) == 0
|
||||
assert plane.abort_requests({"r"}) == 0
|
||||
assert not plane._pending_load_reqs and not plane._request_ids_mapping and not plane._local_stage_payload_cache
|
||||
|
||||
|
||||
def test_ar_receiver_accumulates_rows_and_replaces_chunk_metadata():
|
||||
# A V1 upstream sender stamps scalar flags on every chunk; they describe
|
||||
# the latest chunk and must not be concatenated like decode rows.
|
||||
plane = _bare_plane()
|
||||
plane._send_side_request_payload = {}
|
||||
|
||||
def chunk(rows, finished):
|
||||
return {
|
||||
"embed": {"decode": torch.ones((rows, 2))},
|
||||
"meta": {"finished": torch.tensor(finished), "is_segment_finished": torch.tensor(False)},
|
||||
}
|
||||
|
||||
plane._accumulate_payload("ext", chunk(1, False))
|
||||
merged = plane._accumulate_payload("ext", chunk(2, True))
|
||||
|
||||
assert merged["embed"]["decode"].shape == (3, 2)
|
||||
assert merged["meta"]["finished"].item() is True
|
||||
assert merged["meta"]["is_segment_finished"].ndim == 0
|
||||
|
||||
|
||||
def test_terminal_without_processor_payload_still_sends_finish_marker(raw_plane, monkeypatch):
|
||||
# Qwen3-Omni's Talker processor returns None on the terminal call when the
|
||||
# last frames ended exactly on a chunk boundary; Code2Wav must still learn
|
||||
# that the stream finished, as with the V1 chunk adapter.
|
||||
raw_plane._async_chunk = True
|
||||
raw_plane._omni_connector = object()
|
||||
raw_plane._request_ids_mapping = {}
|
||||
raw_plane._custom_process_func = lambda transfer_manager, multimodal_output, request, is_finished=False: None
|
||||
raw_plane._custom_process_batch_func = None
|
||||
monkeypatch.setattr(raw_plane, "is_data_transfer_rank", lambda: True)
|
||||
enqueued = []
|
||||
|
||||
def enqueue(request, payload, **_kw):
|
||||
enqueued.append((request.request_id, payload))
|
||||
return True, None
|
||||
|
||||
monkeypatch.setattr(raw_plane, "_enqueue_chunk_payload", enqueue)
|
||||
raw_plane.register_request(_new_request())
|
||||
|
||||
_complete(raw_plane, [{"codes": {"audio": torch.ones((1, 16))}}])
|
||||
assert enqueued == [] # a non-terminal None payload sends nothing
|
||||
assert raw_plane.request_terminal({"internal"}) == 1
|
||||
[(req_id, payload)] = enqueued
|
||||
assert req_id == "internal"
|
||||
assert payload["meta"]["finished"].item() is True
|
||||
|
||||
|
||||
def test_payload_builders_see_stage_model_config(monkeypatch):
|
||||
# Producer-side builders (Qwen3-Omni's Thinker reads
|
||||
# hf_config.talker_config.accept_hidden_layer) resolve the stage config
|
||||
# through _get_model_config(), as they do on the V1 runner mixin.
|
||||
from vllm_omni.model_executor.stage_input_processors.qwen3_omni import _get_accept_hidden_layer_index
|
||||
|
||||
def init_connectors(self, *, model_config):
|
||||
self._async_chunk = True
|
||||
self._custom_process_func = None
|
||||
|
||||
monkeypatch.setattr(OmniRunnerDataPlane, "init_omni_connectors", init_connectors)
|
||||
monkeypatch.setattr(OmniRunnerDataPlane, "_start_output_worker", lambda self, **_kw: None)
|
||||
model_config = SimpleNamespace(hf_config=SimpleNamespace(talker_config=SimpleNamespace(accept_hidden_layer=24)))
|
||||
vllm_config = SimpleNamespace(model_config=model_config)
|
||||
|
||||
plane = OmniRunnerDataPlane(vllm_config, model_config)
|
||||
|
||||
assert plane._get_model_config() is model_config
|
||||
assert _get_accept_hidden_layer_index(plane) == 24
|
||||
@@ -13,7 +13,7 @@ import torch
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.outputs import OmniModelRunnerOutput
|
||||
from vllm_omni.worker_v2.omni_generation_model_runner import OmniGenerationModelRunner
|
||||
from vllm_omni.worker_v2.omni_generation_model_runner import OmniGenerationModelRunner, check_exact_input_shape
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -182,3 +182,16 @@ def test_sample_tokens_uses_async_output_for_cuda_and_snapshots_req_ids(monkeypa
|
||||
output_req_ids = captured["model_runner_output"].req_ids
|
||||
input_batch.req_ids[0] = "reused" # snapshot must insulate the published output
|
||||
assert output_req_ids == ["req-0"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exact", [True, False])
|
||||
def test_exact_input_shape_models_reject_padded_batches(exact):
|
||||
# Qwen3-Omni Code2Wav splits input_ids by seq_token_counts (#6712).
|
||||
model = SimpleNamespace(requires_exact_input_shape=exact)
|
||||
check_exact_input_shape(model, torch.zeros(32, dtype=torch.long), 32)
|
||||
check_exact_input_shape(model, None, 16)
|
||||
if exact:
|
||||
with pytest.raises(RuntimeError, match="exact input shape"):
|
||||
check_exact_input_shape(model, torch.zeros(48, dtype=torch.long), 32)
|
||||
else:
|
||||
check_exact_input_shape(model, torch.zeros(48, dtype=torch.long), 32)
|
||||
@@ -181,6 +181,84 @@ def test_capture_contract_uses_model_declaration(stage, declared):
|
||||
runner._configure_cudagraph_output_contract()
|
||||
assert runner._model_returns_tuple is declared
|
||||
assert runner._exclude_full_graph is declared
|
||||
assert runner._full_graph_aux_outputs is False
|
||||
|
||||
|
||||
def _aux_output(num_tokens):
|
||||
hidden = torch.arange(num_tokens * 2, dtype=torch.float32).reshape(num_tokens, 2)
|
||||
return hidden, {"hidden_states": {"layers": {0: hidden + 1, 24: hidden + 2}}}
|
||||
|
||||
|
||||
def test_full_graph_aux_contract_keeps_full_and_round_trips_leaves():
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
|
||||
runner._configure_cudagraph_output_contract()
|
||||
assert runner._full_graph_aux_outputs and not runner._exclude_full_graph
|
||||
|
||||
calls = []
|
||||
|
||||
def forward(num_tokens=3):
|
||||
calls.append(num_tokens)
|
||||
return _aux_output(num_tokens)
|
||||
|
||||
runner.model.forward = forward
|
||||
original_forward = runner.model.forward
|
||||
runner.use_aux_hidden_state_outputs = False
|
||||
full = SimpleNamespace(cg_mode=CUDAGraphMode.FULL)
|
||||
runner.cudagraph_manager = SimpleNamespace(_capture_descs={CUDAGraphMode.FULL: [full]}, _candidates={})
|
||||
runner.model_state = SimpleNamespace()
|
||||
captured = {}
|
||||
|
||||
def capture(_self):
|
||||
# The graph manager stores (hidden, leaves) in its aux buffers.
|
||||
assert runner.use_aux_hidden_state_outputs is True
|
||||
hidden, leaves = runner.model.forward(4)
|
||||
captured["hidden"], captured["leaves"] = hidden, leaves
|
||||
assert [tuple(leaf.shape) for leaf in leaves] == [(4, 2), (4, 2)]
|
||||
runner.model.forward(2) # smaller capture, same structure
|
||||
return 1
|
||||
|
||||
with patch.object(GPUModelRunner, "capture_model", capture):
|
||||
assert runner.capture_model() == 1
|
||||
assert runner.model.forward is original_forward and runner.use_aux_hidden_state_outputs is False
|
||||
assert runner.cudagraph_manager._capture_descs == {CUDAGraphMode.FULL: [full]} # FULL kept
|
||||
|
||||
hidden, aux = runner._split_fullgraph_output((captured["hidden"], captured["leaves"]))
|
||||
reference_hidden, reference_aux = _aux_output(4)
|
||||
assert torch.equal(hidden, reference_hidden)
|
||||
assert set(aux["hidden_states"]["layers"]) == {0, 24}
|
||||
assert torch.equal(aux["hidden_states"]["layers"][24], reference_aux["hidden_states"]["layers"][24])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"aux",
|
||||
[
|
||||
{}, # no leaves
|
||||
{"layers": {0: torch.zeros(5, 2)}}, # leaf not on the token axis
|
||||
{"layers": {0: 1.0}}, # non-tensor leaf
|
||||
],
|
||||
)
|
||||
def test_full_graph_aux_contract_rejects_invalid_outputs(aux):
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
|
||||
runner._configure_cudagraph_output_contract()
|
||||
with pytest.raises(RuntimeError, match="supports_mrv2_full_graph_aux_outputs"):
|
||||
runner._flatten_capture_aux_output((torch.zeros(3, 2), aux))
|
||||
|
||||
|
||||
def test_full_graph_aux_contract_rejects_structure_change():
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
|
||||
runner._configure_cudagraph_output_contract()
|
||||
runner._flatten_capture_aux_output((torch.zeros(3, 2), {"layers": {0: torch.zeros(3, 2)}}))
|
||||
with pytest.raises(RuntimeError, match="structure changed"):
|
||||
runner._flatten_capture_aux_output((torch.zeros(3, 2), {"layers": {1: torch.zeros(3, 2)}}))
|
||||
|
||||
|
||||
def test_full_graph_output_without_contract_is_hidden_only():
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
hidden = torch.ones(2, 2)
|
||||
assert runner._split_fullgraph_output(hidden) == (hidden, None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("runner_kind", ["gpu", "ar", "generation"])
|
||||
@@ -202,6 +280,7 @@ def test_dummy_forward_uses_upstream_execution_state(runner_kind, monkeypatch):
|
||||
else hidden
|
||||
)
|
||||
runner._dummy_hidden = hidden
|
||||
runner.model.requires_request_ids = False
|
||||
runner.model_config = SimpleNamespace()
|
||||
runner.vllm_config = SimpleNamespace()
|
||||
runner.req_states = SimpleNamespace()
|
||||
|
||||
@@ -19,6 +19,8 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _DummyInputBatch:
|
||||
is_prefilling_np: np.ndarray
|
||||
|
||||
input_ids: SimpleNamespace
|
||||
query_start_loc: torch.Tensor
|
||||
|
||||
@@ -592,3 +594,58 @@ def test_first_audio_marker_requires_accepted_delivery(monkeypatch, accepted):
|
||||
# A missing route must leave the normal codec path responsible for frame 0;
|
||||
# otherwise it skips the frame and the orchestrator waits forever for it.
|
||||
assert outputs["meta"]["first_audio"].tolist() == ["r0" in accepted, "r1" in accepted]
|
||||
|
||||
|
||||
class _FakeEvent:
|
||||
def record(self, stream=None) -> None:
|
||||
self.stream = stream
|
||||
|
||||
|
||||
def test_publish_sampled_embeddings_for_rows_whose_sample_is_kept(monkeypatch) -> None:
|
||||
monkeypatch.setattr(torch.cuda, "Event", _FakeEvent)
|
||||
state = _make_state()
|
||||
state.model.publishes_sampled_embeddings = True
|
||||
state.model.embed_input_ids = lambda ids: ids.to(torch.float32).reshape(-1, 1).repeat(1, 3)
|
||||
# Rows: final prefill chunk, decode, non-final prefill chunk, one-chunk prefill.
|
||||
batch = SimpleNamespace(
|
||||
num_reqs=4,
|
||||
num_scheduled_tokens=[4, 1, 2, 6],
|
||||
num_computed_prefill_tokens_np=np.array([2, 9, 0, 0], dtype=np.int32),
|
||||
prefill_len_np=np.array([6, 9, 5, 6], dtype=np.int32),
|
||||
is_prefilling_np=np.array([True, False, True, True]),
|
||||
)
|
||||
extra, _done = state.publish_sampled_embeddings(batch, torch.tensor([[11], [12], [13], [14]]))
|
||||
sampled = extra["embed"]["sampled"]
|
||||
# A non-final prefill chunk's sample is discarded, so it publishes nothing.
|
||||
assert [tuple(row.shape) for row in sampled] == [(1, 3), (1, 3), (0,), (1, 3)]
|
||||
assert [row.tolist() for row in sampled if row.numel()] == [[[v] * 3] for v in (11.0, 12.0, 14.0)]
|
||||
|
||||
# Speculative steps sample several tokens per row: not published.
|
||||
assert state.publish_sampled_embeddings(batch, torch.tensor([[11, 1], [12, 1], [13, 1], [14, 1]])) is None
|
||||
|
||||
|
||||
def test_publish_sampled_embeddings_is_opt_in() -> None:
|
||||
state = _make_state()
|
||||
state.model.publishes_sampled_embeddings = False
|
||||
assert state.publish_sampled_embeddings(SimpleNamespace(num_reqs=1), torch.tensor([[1]])) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefilling", [False, True])
|
||||
def test_identity_preprocess_skips_only_decode_rows(prefilling):
|
||||
state = _make_state(has_preprocess=True)
|
||||
state._decode_preprocess_is_identity = True
|
||||
state._decode_preprocess = None
|
||||
state.intermediate_buffer.buffers[0] = {"req_id": "r1"}
|
||||
seen = []
|
||||
|
||||
def preprocess(input_ids, input_embeds, **info):
|
||||
seen.append(info["req_id"])
|
||||
return input_ids, input_embeds, {}
|
||||
|
||||
state.model.preprocess = preprocess
|
||||
batch = _DummyInputBatch([0])
|
||||
batch.is_prefilling_np = np.array([prefilling])
|
||||
embeds = torch.ones(1, 4)
|
||||
state.run_preprocess(batch, {"input_ids": torch.tensor([1]), "inputs_embeds": embeds})
|
||||
assert seen == (["r1"] if prefilling else [])
|
||||
assert torch.equal(embeds, torch.ones(1, 4))
|
||||
@@ -0,0 +1,79 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Generic model opt-in contracts; no model checkpoints required."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
|
||||
from vllm_omni.worker_v2.omni_ar_model_runner import _merge_payload_trees
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_device_output_hook_receives_live_batch_and_request_state():
|
||||
state = object.__new__(OmniModelState)
|
||||
state.have_multimodal_outputs = True
|
||||
batch, requests, buffers = object(), object(), [{"req_id": "r"}]
|
||||
hidden = torch.ones(1, 2)
|
||||
seen = []
|
||||
|
||||
def make_output(value, **kwargs):
|
||||
seen.append((value, kwargs))
|
||||
return OmniOutput(text_hidden_states=value, multimodal_outputs={"codes": {"audio": value}})
|
||||
|
||||
state.model = SimpleNamespace(make_omni_output_mrv2=make_output)
|
||||
state.intermediate_buffer = SimpleNamespace(gather=lambda value: buffers)
|
||||
result_hidden, payload = state.postprocess_model_output(hidden, batch, requests)
|
||||
assert result_hidden is hidden
|
||||
assert payload["codes"]["audio"] is hidden
|
||||
assert seen == [(hidden, {"input_batch": batch, "req_states": requests, "model_intermediate_buffer": buffers})]
|
||||
|
||||
|
||||
def test_sampled_embeddings_merge_preserves_sibling_fields_and_input():
|
||||
prefill, sampled = torch.ones(2, 3), torch.zeros(1, 3)
|
||||
base = {"embed": {"prefill": prefill}, "meta": {"finished": False}}
|
||||
merged = _merge_payload_trees(base, {"embed": {"sampled": [sampled]}})
|
||||
assert merged["embed"]["prefill"] is prefill
|
||||
assert merged["embed"]["sampled"] == [sampled]
|
||||
assert "sampled" not in base["embed"]
|
||||
assert merged["meta"] == {"finished": False}
|
||||
|
||||
|
||||
def test_custom_sampler_falls_back_to_parent(monkeypatch):
|
||||
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
|
||||
state = object.__new__(OmniModelState)
|
||||
state.model = SimpleNamespace()
|
||||
sampler, marker = object(), object()
|
||||
monkeypatch.setattr(DefaultModelState, "custom_sampler", lambda self, original: (original, marker))
|
||||
assert state.custom_sampler(sampler) == (sampler, marker)
|
||||
|
||||
|
||||
def test_logits_vocab_is_adopted_before_parent_sampler_initialization(monkeypatch):
|
||||
import vllm.v1.worker.gpu.model_runner as upstream
|
||||
|
||||
from vllm_omni.worker_v2 import omni_model_runner as module
|
||||
|
||||
runner = object.__new__(module.OmniGPUModelRunner)
|
||||
runner.vocab_size = 100
|
||||
runner.req_states = SimpleNamespace(vocab_size=100)
|
||||
runner.model_config = SimpleNamespace(model_arch_config=SimpleNamespace(vocab_size=100))
|
||||
model = SimpleNamespace(logits_vocab_size=32)
|
||||
original_initializer = upstream.init_model_state
|
||||
sentinel = object()
|
||||
monkeypatch.setattr(module, "init_omni_model_state", lambda *args: sentinel)
|
||||
|
||||
def load(parent):
|
||||
assert upstream.init_model_state(None, model, None, None) is sentinel
|
||||
assert parent.vocab_size == parent.req_states.vocab_size == 32
|
||||
assert parent.model_config.model_arch_config.vocab_size == 32
|
||||
raise RuntimeError("stop before sampler allocation")
|
||||
|
||||
monkeypatch.setattr(upstream.GPUModelRunner, "load_model", load)
|
||||
with pytest.raises(RuntimeError, match="stop before sampler allocation"):
|
||||
runner.load_model()
|
||||
assert upstream.init_model_state is original_initializer
|
||||
@@ -0,0 +1,45 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Small CUDA correctness checks for shared stage output contracts."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.worker.gpu_generation_model_runner import _HostCopyBatch
|
||||
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cuda]
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_host_copy_batch_preserves_noncontiguous_outputs_on_current_stream():
|
||||
stream = torch.cuda.Stream()
|
||||
with torch.cuda.stream(stream):
|
||||
source = torch.arange(24, device="cuda", dtype=torch.float32).reshape(4, 6)
|
||||
copies = _HostCopyBatch(pin_memory=True)
|
||||
first = copies.copy(source.t())
|
||||
second = copies.copy(source + 10)
|
||||
copies.wait()
|
||||
assert first.is_contiguous() and first.is_pinned()
|
||||
assert torch.equal(first, torch.arange(24, dtype=torch.float32).reshape(4, 6).t())
|
||||
assert torch.equal(second, torch.arange(24, dtype=torch.float32).reshape(4, 6) + 10)
|
||||
copies.wait() # no outstanding copies
|
||||
|
||||
|
||||
@pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required")
|
||||
def test_aux_pytree_tracks_replayed_graph_values():
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.model = SimpleNamespace(_returns_tuple=True, supports_mrv2_full_graph_aux_outputs=True)
|
||||
runner._configure_cudagraph_output_contract()
|
||||
source = torch.ones((4, 3), device="cuda")
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
captured = runner._flatten_capture_aux_output((source * 2, {"layers": [source + 1, source + 2]}))
|
||||
source.fill_(7)
|
||||
graph.replay()
|
||||
hidden, aux = runner._split_fullgraph_output(captured)
|
||||
assert torch.equal(hidden, torch.full_like(source, 14))
|
||||
assert torch.equal(aux["layers"][0], torch.full_like(source, 8))
|
||||
assert torch.equal(aux["layers"][1], torch.full_like(source, 9))
|
||||
Reference in new issue
Block a user