[Core][Model] Enable Qwen3-TTS MRV2 and optimize the TTS pipeline (#7781)
Signed-off-by: Sy03 <1370724210@qq.com>
This commit is contained in:
103 files changed
+10232
-661
No files matched your search
@@ -1429,6 +1429,9 @@ stages:
|
||||
assert deploy.async_chunk is True
|
||||
assert deploy.connectors is not None
|
||||
assert deploy.platforms is not None
|
||||
connector = deploy.connectors["connector_of_shared_memory"]
|
||||
assert "async_chunk_batch_min_size" not in connector["extra"]
|
||||
assert "async_chunk_batch_max_wait_ms" not in connector["extra"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("hf_config", "model"),
|
||||
@@ -2704,6 +2707,56 @@ class TestPlatformOverrides:
|
||||
|
||||
assert deploy.stages[0].engine_extras["block_size"] == 128
|
||||
|
||||
@pytest.mark.parametrize("platform", ["cuda", "npu"])
|
||||
def test_recommended_native_runner_platform_defaults(self, platform):
|
||||
filename, pipeline_key = "qwen3_tts_mrv2.yaml", "qwen3_tts"
|
||||
deploy = load_deploy_config(Path(get_deploy_config_path(filename)))
|
||||
deploy = _apply_platform_overrides(deploy, platform=platform)
|
||||
expect_v2 = platform == "cuda"
|
||||
assert deploy.model_runner == ("v2" if expect_v2 else "v1")
|
||||
|
||||
# The selection must reach the live worker-dispatch consumer, not just
|
||||
# the transport-level DeployConfig field.
|
||||
pipeline = resolve_pipeline_config(pipeline_key)
|
||||
stages = merge_pipeline_deploy(pipeline, deploy)
|
||||
assert [stage.yaml_engine_args["use_v2_model_runner"] for stage in stages] == [expect_v2] * len(stages)
|
||||
|
||||
if expect_v2 and pipeline.stages and deploy.async_chunk:
|
||||
# v2 only engages the native plane on stages declaring support.
|
||||
assert all(ps.supports_native_mrv2_data_plane for ps in pipeline.stages)
|
||||
|
||||
@pytest.mark.parametrize("runner,native", [("v1", False), ("v2", False), ("v2", True)])
|
||||
def test_mrv2_undeclared_transport_warns(self, monkeypatch, runner, native):
|
||||
from unittest.mock import Mock
|
||||
|
||||
warning = Mock()
|
||||
monkeypatch.setattr("vllm_omni.config.stage_config.logger.warning", warning)
|
||||
pipeline = PipelineConfig(
|
||||
model_type="custom_pipeline",
|
||||
stages=[
|
||||
StagePipelineConfig(
|
||||
stage_id=0, model_stage="custom_ar", final_output=True, supports_native_mrv2_data_plane=native
|
||||
)
|
||||
],
|
||||
)
|
||||
merge_pipeline_deploy(pipeline, DeployConfig(model_runner=runner))
|
||||
assert warning.call_count == int(runner == "v2" and not native)
|
||||
if warning.called:
|
||||
assert "legacy transport path" in warning.call_args.args[0]
|
||||
|
||||
def test_runner_selection_rejects_engine_extras_override(self):
|
||||
pipeline = PipelineConfig(
|
||||
model_type="runner_selection_reserved",
|
||||
stages=SINGLE_STAGE_PIPE_CFG,
|
||||
)
|
||||
for reserved in ("use_v2_model_runner", "supports_native_mrv2_data_plane"):
|
||||
deploy = DeployConfig(
|
||||
model_runner="v2",
|
||||
stages=[StageDeployConfig(stage_id=0, engine_extras={reserved: False})],
|
||||
)
|
||||
with pytest.raises(ValueError, match=f"{reserved!r} must not be set"):
|
||||
merge_pipeline_deploy(pipeline, deploy)
|
||||
|
||||
def test_npu_overrides(self):
|
||||
deploy_path = Path(get_deploy_config_path("qwen3_omni_moe.yaml"))
|
||||
if not deploy_path.exists():
|
||||
|
||||
@@ -50,8 +50,10 @@ from vllm_omni.config.stage_config import (
|
||||
StageDeployConfig,
|
||||
StageExecutionType,
|
||||
StagePipelineConfig,
|
||||
_apply_platform_overrides,
|
||||
load_deploy_config,
|
||||
merge_pipeline_deploy,
|
||||
resolve_deploy_yaml,
|
||||
)
|
||||
from vllm_omni.diffusion.diffusion_kv.config import DiffusionKVCacheMode
|
||||
from vllm_omni.engine.stage_engine_startup import _serialize_stage_config
|
||||
@@ -783,6 +785,67 @@ def test_joyai_code2wav_waits_for_full_payload():
|
||||
assert code2wav.model_config.requires_full_payload_input is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("model_runner", ["v1", "v2"])
|
||||
def test_deploy_model_runner_selection_propagates_to_every_stage(tmp_path: Path, model_runner: str):
|
||||
deploy_path = tmp_path / "qwen3_tts_runner.yaml"
|
||||
deploy_path.write_text(
|
||||
f"""\
|
||||
pipeline: qwen3_tts
|
||||
model_runner: {model_runner}
|
||||
async_chunk: true
|
||||
stages:
|
||||
- stage_id: 0
|
||||
- stage_id: 1
|
||||
"""
|
||||
)
|
||||
|
||||
deploy = load_deploy_config(deploy_path)
|
||||
pipeline = _resolve_pipeline_or_skip("qwen3_tts")
|
||||
legacy_stages = merge_pipeline_deploy(pipeline, deploy)
|
||||
structured = _from_pipeline_key("qwen3_tts", deploy_config_path=str(deploy_path))
|
||||
expect_v2 = model_runner == "v2"
|
||||
|
||||
assert deploy.model_runner == model_runner
|
||||
assert all(stage.yaml_engine_args["use_v2_model_runner"] is expect_v2 for stage in legacy_stages)
|
||||
assert all(stage.model_config.use_v2_model_runner is expect_v2 for stage in structured.stage_configs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platform", ["npu", "xpu"])
|
||||
def test_mrv2_fails_fast_on_platforms_without_native_workers(platform: str):
|
||||
with pytest.raises(NotImplementedError, match="Model Runner V2"):
|
||||
_apply_platform_overrides(DeployConfig(model_runner="v2"), platform=platform)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("default_name", "mrv2_name"),
|
||||
[
|
||||
("qwen3_tts.yaml", "qwen3_tts_mrv2.yaml"),
|
||||
(
|
||||
"qwen3_tts_high_concurrency.yaml",
|
||||
"qwen3_tts_high_concurrency_mrv2.yaml",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_qwen3_mrv2_profiles_are_explicit_opt_in(default_name: str, mrv2_name: str):
|
||||
assert load_deploy_config(_DEPLOY_DIR / default_name).model_runner == "v1"
|
||||
assert load_deploy_config(_DEPLOY_DIR / mrv2_name).model_runner == "v2"
|
||||
|
||||
|
||||
def test_qwen3_tts_mrv2_retunes_do_not_change_default_mrv1_profile():
|
||||
default = resolve_deploy_yaml(_DEPLOY_DIR / "qwen3_tts_high_concurrency.yaml")
|
||||
mrv2 = resolve_deploy_yaml(_DEPLOY_DIR / "qwen3_tts_high_concurrency_mrv2.yaml")
|
||||
default_extra = default["connectors"]["connector_of_shared_memory"]["extra"]
|
||||
mrv2_extra = mrv2["connectors"]["connector_of_shared_memory"]["extra"]
|
||||
|
||||
# B2 batch stays consistent with the graph buckets; V1 profile untouched.
|
||||
assert default_extra["decode_batch_max_size"] == 1
|
||||
assert mrv2_extra["decode_batch_max_size"] == 2
|
||||
assert mrv2_extra["decode_cudagraph_batch_sizes"] == [1, 2]
|
||||
assert mrv2_extra["code_predictor_prefix_graphs"] is False
|
||||
assert mrv2["stages"][1]["enforce_eager"] is False
|
||||
assert default["stages"][1]["enforce_eager"] is True
|
||||
|
||||
|
||||
def test_vllm_omni_stage_config_public_fields_use_typed_stage_realizations():
|
||||
assert not hasattr(BaseVllmOmniStageConfig, "from_stage_config")
|
||||
assert not hasattr(BaseVllmOmniStageConfig, "to_legacy_stage_config")
|
||||
@@ -879,9 +942,11 @@ def test_sub_config_fields_match_structured_scopes():
|
||||
"limit_mm_per_prompt",
|
||||
"interleave_mm_strings",
|
||||
"media_io_kwargs",
|
||||
"final_output",
|
||||
"active_stream_window",
|
||||
"session_mode",
|
||||
"duplex_max_sessions",
|
||||
"use_v2_model_runner",
|
||||
"enable_sleep_mode",
|
||||
"default_sampling_params",
|
||||
"subtalker_sampling_params",
|
||||
@@ -890,6 +955,7 @@ def test_sub_config_fields_match_structured_scopes():
|
||||
"custom_voice_dir",
|
||||
"task_type",
|
||||
"codec_frame_rate_hz",
|
||||
"supports_native_mrv2_data_plane",
|
||||
"enforce_eager",
|
||||
"max_cudagraph_capture_size",
|
||||
"enable_flashinfer_autotune",
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
"""Test that OmniGenerationScheduler restores chunk-waiting requests
|
||||
even when the OmniNewRequestData rewrapping fails.
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
Regression test: if process_pending_chunks() moves requests into
|
||||
internal deques but restore_queues() is not called due to an exception,
|
||||
those requests are permanently orphaned.
|
||||
"""
|
||||
"""Chunk-lifecycle coverage for OmniGenerationScheduler: restore on error,
|
||||
native terminal state, in-flight no-resubmission, slot release on finish,
|
||||
and single scheduling of a terminal empty-prompt chunk."""
|
||||
|
||||
from collections import deque
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm import SamplingParams
|
||||
from vllm.v1.core.sched.interface import PauseState
|
||||
from vllm.v1.core.sched.request_queue import SchedulingPolicy, create_request_queue
|
||||
from vllm.v1.request import Request, RequestStatus
|
||||
|
||||
from vllm_omni.core.sched.omni_generation_scheduler import OmniGenerationScheduler, _has_async_chunk_payload_to_run
|
||||
from vllm_omni.engine.serialization import serialize_additional_information
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -20,16 +28,20 @@ class FakeAdapter:
|
||||
self.waiting_for_chunk_waiting_requests = deque()
|
||||
self.waiting_for_chunk_running_requests = deque()
|
||||
self.restore_called = False
|
||||
self.done_request_ids = set()
|
||||
|
||||
def process_pending_chunks(self, waiting, running):
|
||||
"""Simulate moving requests out of the scheduler queues."""
|
||||
# Move one request from running into internal deque
|
||||
def process_pending_chunks(self, waiting, running, scheduler_requests=None):
|
||||
if running:
|
||||
req = running.pop()
|
||||
self.waiting_for_chunk_running_requests.append(req)
|
||||
|
||||
def is_done_receiving_chunks(self, request_id):
|
||||
return request_id in self.done_request_ids
|
||||
|
||||
def collect_failed_send_request_ids(self):
|
||||
return {}
|
||||
|
||||
def restore_queues(self, waiting, running, scheduler_requests=None):
|
||||
"""Put requests back."""
|
||||
self.restore_called = True
|
||||
running.extend(self.waiting_for_chunk_running_requests)
|
||||
self.waiting_for_chunk_running_requests = deque()
|
||||
@@ -38,6 +50,131 @@ class FakeAdapter:
|
||||
pass
|
||||
|
||||
|
||||
def _make_generation_scheduler(waiting_request, *, use_v2_model_runner=False):
|
||||
scheduler = OmniGenerationScheduler.__new__(OmniGenerationScheduler)
|
||||
scheduler.max_num_scheduled_tokens = 8
|
||||
scheduler.max_num_running_reqs = 1
|
||||
scheduler._pause_state = PauseState.UNPAUSED
|
||||
scheduler.running = []
|
||||
scheduler.waiting = create_request_queue(SchedulingPolicy.FCFS)
|
||||
scheduler.waiting.add_request(waiting_request)
|
||||
scheduler.skipped_waiting = create_request_queue(SchedulingPolicy.FCFS)
|
||||
scheduler.requests = {waiting_request.request_id: waiting_request}
|
||||
scheduler.policy = SchedulingPolicy.FCFS
|
||||
scheduler.chunk_transfer_adapter = FakeAdapter()
|
||||
scheduler.input_coordinator = None
|
||||
scheduler.log_stats = False
|
||||
scheduler.scheduler_config = SimpleNamespace(enable_chunked_prefill=True)
|
||||
scheduler.num_lookahead_tokens = 0
|
||||
scheduler.kv_cache_manager = SimpleNamespace(
|
||||
new_step_starts=lambda: None,
|
||||
allocate_slots=lambda *args, **kwargs: SimpleNamespace(get_block_ids=lambda: ([1],)),
|
||||
get_num_common_prefix_blocks=lambda request_id: [0],
|
||||
take_new_block_ids=lambda: None,
|
||||
)
|
||||
scheduler.kv_cache_config = SimpleNamespace(kv_cache_groups=[object()])
|
||||
scheduler.use_v2_model_runner = use_v2_model_runner
|
||||
scheduler._retains_state_across_chunks = False
|
||||
scheduler.needs_kv_cache_zeroing = False
|
||||
scheduler.finished_req_ids = set()
|
||||
scheduler.encoder_cache_manager = SimpleNamespace(get_freed_mm_hashes=lambda: [])
|
||||
scheduler.connector = None
|
||||
scheduler.ec_connector = None
|
||||
scheduler.prev_step_scheduled_req_ids = set()
|
||||
scheduler._pending_finish_reqs = []
|
||||
scheduler._consume_pending_connector_output = lambda model_mode: None
|
||||
scheduler._process_pending_input_timeouts = lambda: None
|
||||
scheduler._make_cached_request_data = lambda **kwargs: SimpleNamespace(
|
||||
req_ids=[],
|
||||
resumed_req_ids=[],
|
||||
new_token_ids=[],
|
||||
all_token_ids=[],
|
||||
new_block_ids=[],
|
||||
num_computed_tokens=[],
|
||||
num_output_tokens=[],
|
||||
)
|
||||
scheduler._update_after_schedule = lambda output: None
|
||||
scheduler._wrap_omni_scheduler_output = lambda output: output
|
||||
return scheduler
|
||||
|
||||
|
||||
def _chunk_request(request_id, **kwargs):
|
||||
defaults = dict(
|
||||
request_id=request_id,
|
||||
prompt_token_ids=[1],
|
||||
num_computed_tokens=0,
|
||||
num_in_flight_tokens=0,
|
||||
status=None,
|
||||
sampling_params=None,
|
||||
pooling_params=None,
|
||||
mm_features=None,
|
||||
lora_request=None,
|
||||
prompt_is_token_ids=True,
|
||||
additional_information=None,
|
||||
external_req_id=request_id,
|
||||
prefill_stats=None,
|
||||
record_event=lambda *args, **kwargs: None,
|
||||
)
|
||||
defaults.update(kwargs)
|
||||
return SimpleNamespace(**defaults)
|
||||
|
||||
|
||||
def test_chunk_lifecycle_no_resubmit_and_state_survives_requeue(monkeypatch) -> None:
|
||||
# Native plane: a completed payload without a new chunk is never executed
|
||||
# again; requeued requests keep WAITING_FOR_CHUNK and their token counts.
|
||||
scheduler = _make_generation_scheduler(_chunk_request("unused"))
|
||||
monkeypatch.setattr("vllm_omni.core.sched.omni_generation_scheduler.create_request_queue", create_request_queue)
|
||||
scheduler._native_data_plane = True
|
||||
scheduler.chunk_transfer_adapter = None
|
||||
scheduler.input_coordinator = SimpleNamespace(finished_requests=set(), restore_queues=lambda *args, **kwargs: None)
|
||||
scheduler.running = []
|
||||
scheduler.waiting = create_request_queue(scheduler.policy)
|
||||
scheduler.skipped_waiting = create_request_queue(scheduler.policy)
|
||||
|
||||
completed = Request("completed", [1, 2], SamplingParams(max_tokens=4), pooling_params=None)
|
||||
completed.status = RequestStatus.RUNNING
|
||||
completed.num_computed_tokens = 2
|
||||
scheduler.running = [completed]
|
||||
scheduler.requests = {"completed": completed}
|
||||
scheduler.input_coordinator.finished_requests.add("completed") # terminal payload, no new chunk
|
||||
|
||||
assert scheduler._is_done_receiving_chunks("completed")
|
||||
assert not scheduler._is_done_receiving_chunks("unknown")
|
||||
output = scheduler.schedule()
|
||||
assert not output.num_scheduled_tokens
|
||||
assert scheduler._pending_finish_reqs == [completed]
|
||||
|
||||
completed.status = RequestStatus.WAITING_FOR_CHUNK
|
||||
scheduler._pending_finish_reqs = []
|
||||
scheduler._requeue_completed_native_chunks()
|
||||
assert completed.status == RequestStatus.WAITING_FOR_CHUNK
|
||||
assert completed.num_computed_tokens == 2
|
||||
assert not scheduler.running
|
||||
|
||||
|
||||
def test_generation_scheduler_schedules_terminal_empty_prompt_chunk_once(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
waiting = _chunk_request(
|
||||
"terminal",
|
||||
prompt_token_ids=[],
|
||||
num_prompt_tokens=0,
|
||||
additional_information=serialize_additional_information(
|
||||
{"codes": {"audio": torch.tensor([[1, 2, 3]], dtype=torch.long)}}
|
||||
),
|
||||
)
|
||||
scheduler = _make_generation_scheduler(waiting)
|
||||
scheduler.chunk_transfer_adapter.done_request_ids.add("terminal")
|
||||
scheduler.requests = {"terminal": waiting}
|
||||
assert _has_async_chunk_payload_to_run(waiting)
|
||||
# A terminal codec request with an empty prompt is still scheduled exactly once.
|
||||
monkeypatch.setattr("vllm_omni.core.sched.omni_generation_scheduler.create_request_queue", create_request_queue)
|
||||
|
||||
output = OmniGenerationScheduler.schedule(scheduler)
|
||||
|
||||
assert output.num_scheduled_tokens == {"terminal": 1}
|
||||
assert output.scheduled_new_reqs[0].req_id == "terminal"
|
||||
assert scheduler._pending_finish_reqs == []
|
||||
|
||||
|
||||
class TestRestoreQueuesOnError:
|
||||
"""Verify that restore_queues is called even when rewrapping raises."""
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Tests for ``OmniARScheduler._drop_aborted_queued_requests``.
|
||||
|
||||
``schedule()`` sweeps ``FINISHED_ABORTED`` requests out of the queues before
|
||||
@@ -68,6 +71,7 @@ def test_schedule_sweeps_skipped_waiting_before_upstream_selection(
|
||||
aborted = _StubRequest("req-aborted", RequestStatus.FINISHED_ABORTED)
|
||||
scheduler = _make_scheduler(policy, skipped_waiting=[aborted])
|
||||
scheduler.chunk_transfer_adapter = None
|
||||
scheduler.max_num_running_reqs = 8
|
||||
scheduler.input_coordinator = None
|
||||
scheduler.num_waiting_for_streaming_input = 0
|
||||
scheduler._process_pending_omni_inputs = lambda model_mode: None
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Tests for the AR sampled-token logprob contract."""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -93,6 +96,7 @@ class _Request:
|
||||
self.num_computed_tokens = 0
|
||||
self.num_in_flight_tokens = 0
|
||||
self.num_output_placeholders = 0
|
||||
self.output_token_ids: list[int] = []
|
||||
# vLLM 0.27 (a0c092ee72): Request gained num_stale_output_tokens to
|
||||
# track in-flight outputs discarded at preemption/streaming-stop.
|
||||
self.num_stale_output_tokens = 0
|
||||
@@ -145,6 +149,14 @@ def _make_scheduler_stub(requests: list[_Request]) -> SimpleNamespace:
|
||||
kv_cache_manager=SimpleNamespace(take_events=lambda: None),
|
||||
kv_event_publisher=SimpleNamespace(publish=lambda _events: None),
|
||||
recompute_kv_load_failures=False,
|
||||
_native_data_plane=False,
|
||||
vllm_config=SimpleNamespace(
|
||||
model_config=SimpleNamespace(
|
||||
use_v2_model_runner=False,
|
||||
async_chunk=False,
|
||||
final_output=True,
|
||||
)
|
||||
),
|
||||
)
|
||||
for name in _MIXIN_UPDATE_HELPERS:
|
||||
setattr(scheduler, name, MethodType(getattr(OmniSchedulerMixin, name), scheduler))
|
||||
@@ -167,10 +179,15 @@ def _bind_request_lifecycle(
|
||||
scheduler.requests.pop(request.request_id, None)
|
||||
scheduler.finished_req_ids.add(request.request_id)
|
||||
scheduler.finished_req_ids_dict[request.client_index].add(request.request_id)
|
||||
# vLLM 0.26 contract: (kv_xfer_params, ec_xfer_params)
|
||||
# Current vLLM contract: (kv_xfer_params, ec_xfer_params)
|
||||
return None, None
|
||||
|
||||
scheduler._update_request_with_output = update_request
|
||||
def update_with_history(request, token_ids):
|
||||
accepted, stopped = update_request(request, token_ids)
|
||||
request.output_token_ids.extend(accepted)
|
||||
return accepted, stopped
|
||||
|
||||
scheduler._update_request_with_output = update_with_history
|
||||
scheduler._process_kv_transfer_trigger = lambda _request, _tokens: False
|
||||
scheduler._handle_stopped_request = handle_stopped or (lambda _request: True)
|
||||
scheduler._free_request = free_request
|
||||
@@ -219,6 +236,7 @@ def test_mid_step_stop_trims_logprob_rows_with_token_ids() -> None:
|
||||
(output,) = outputs[0].outputs
|
||||
|
||||
assert output.new_token_ids == [7]
|
||||
assert output.num_generation_tokens == 1
|
||||
assert output.finish_reason is FinishReason.STOP
|
||||
token_rows = np.asarray(output.new_logprobs.logprob_token_ids)
|
||||
value_rows = np.asarray(output.new_logprobs.logprobs)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.core.sched.omni_ar_scheduler import _should_emit_engine_output
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("async_chunk", "final_output", "use_v2", "stopped", "has_control", "expected"),
|
||||
[
|
||||
(True, False, True, False, False, False), # async+v2 suppresses data
|
||||
(True, False, False, False, False, True), # v1 continues to emit
|
||||
(True, False, True, True, False, True), # stopped always emits
|
||||
(True, False, True, False, True, True), # control-only still emits
|
||||
],
|
||||
)
|
||||
def test_async_chunk_intermediate_stage_emits_only_control_outputs(
|
||||
async_chunk: bool,
|
||||
final_output: bool,
|
||||
use_v2: bool,
|
||||
stopped: bool,
|
||||
has_control: bool,
|
||||
expected: bool,
|
||||
) -> None:
|
||||
model_config = SimpleNamespace(
|
||||
async_chunk=async_chunk,
|
||||
final_output=final_output,
|
||||
use_v2_model_runner=use_v2,
|
||||
)
|
||||
|
||||
assert (
|
||||
_should_emit_engine_output(
|
||||
model_config,
|
||||
stopped=stopped,
|
||||
has_control=has_control,
|
||||
)
|
||||
is expected
|
||||
)
|
||||
@@ -17,6 +17,7 @@ import pytest
|
||||
import vllm_omni # noqa: F401 - import for side effects (patch vLLM)
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.core.sched.scheduler import Scheduler as VLLMScheduler
|
||||
from vllm.v1.outputs import ModelRunnerOutput
|
||||
from vllm.v1.engine import FinishReason
|
||||
from vllm.v1.core.sched.request_queue import SchedulingPolicy, create_request_queue
|
||||
@@ -1261,3 +1262,47 @@ def test_context_overflow_emits_an_error_output_with_the_reason() -> None:
|
||||
|
||||
sched._emit_streaming_context_overflow_outputs(outputs)
|
||||
assert len(outputs[2]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("native", [True, False])
|
||||
def test_async_chunk_reserves_parked_slots_during_ar_admission(monkeypatch, native) -> None:
|
||||
sched = _make_scheduler(stage_id=1)
|
||||
parked = SimpleNamespace(request_id="parked")
|
||||
sched.requests = {"parked": parked}
|
||||
sched.waiting = []
|
||||
sched.running = []
|
||||
sched._native_data_plane = native
|
||||
sched.use_v2_model_runner = native
|
||||
sched.max_num_running_reqs = 8
|
||||
sched.input_coordinator = (
|
||||
SimpleNamespace(_waiting_for_chunk_running=[parked], restore_queues=lambda _w, _r: None) if native else None
|
||||
)
|
||||
sched.chunk_transfer_adapter = (
|
||||
None
|
||||
if native
|
||||
else SimpleNamespace(
|
||||
waiting_for_chunk_running_requests=[parked],
|
||||
_held_non_active=[],
|
||||
process_pending_chunks=lambda *_a, **_kw: None,
|
||||
collect_failed_send_request_ids=lambda: {},
|
||||
restore_queues=lambda *_a, **_kw: None,
|
||||
postprocess_scheduler_output=lambda *_a, **_kw: None,
|
||||
)
|
||||
)
|
||||
sched._consume_pending_connector_output = lambda model_mode: None
|
||||
sched._process_pending_input_timeouts = lambda: None
|
||||
sched._should_defer_waiting_admission = lambda: False
|
||||
sched.get_finished_requests_needing_kv_transfer = lambda: {}
|
||||
sched._wrap_omni_scheduler_output = lambda output, **_kwargs: output
|
||||
observed_limits: list[int] = []
|
||||
|
||||
def fake_schedule(self, _throttle_prefills=False):
|
||||
observed_limits.append(self.max_num_running_reqs)
|
||||
return SimpleNamespace(scheduled_new_reqs=[])
|
||||
|
||||
monkeypatch.setattr(VLLMScheduler, "schedule", fake_schedule)
|
||||
|
||||
sched.schedule()
|
||||
|
||||
assert observed_limits == [7 if native else 8]
|
||||
assert sched.max_num_running_reqs == 8
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
@@ -141,6 +144,7 @@ def test_voxcpm2_unified_decode_graph_does_not_defer_without_cuda_graph(monkeypa
|
||||
|
||||
def test_unified_decode_graph_deferral_restores_waiting_queue(monkeypatch) -> None:
|
||||
scheduler = _make_scheduler()
|
||||
scheduler.max_num_running_reqs = 8
|
||||
scheduler.running = [_MockRequest("decode")]
|
||||
original_waiting_req = _MockRequest("waiting", status=RequestStatus.WAITING)
|
||||
deferred_by_upstream = _MockRequest("deferred-by-upstream", status=RequestStatus.WAITING)
|
||||
|
||||
@@ -123,6 +123,9 @@ def _make_fast_path_sched(*, defer_block_free: bool) -> tuple[MagicMock, Request
|
||||
|
||||
sched = MagicMock()
|
||||
sched.max_num_scheduled_tokens = 8
|
||||
sched.max_num_running_reqs = 8
|
||||
sched._native_data_plane = False
|
||||
sched._retains_state_across_chunks = False
|
||||
sched._pause_state = PauseState.UNPAUSED
|
||||
sched.requests = {request.request_id: request}
|
||||
sched.running = [request]
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections import defaultdict
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from vllm.v1.engine import FinishReason
|
||||
@@ -87,7 +91,7 @@ def test_full_payload_coordinator_matches_legacy_gate(monkeypatch, stage_id, asy
|
||||
|
||||
|
||||
def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
|
||||
calls = []
|
||||
calls: list[tuple[Any, ...]] = []
|
||||
scheduler = _Scheduler()
|
||||
scheduler.waiting = ["waiting"]
|
||||
scheduler.running = ["running"]
|
||||
@@ -115,7 +119,7 @@ def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
|
||||
collect_failed_send_request_ids=_collect_failed_sends,
|
||||
)
|
||||
scheduler.input_coordinator = SimpleNamespace(
|
||||
restore_queues=lambda waiting: calls.append(("restore-full", waiting))
|
||||
restore_queues=lambda waiting, running: calls.append(("restore-full", waiting, running))
|
||||
)
|
||||
|
||||
scheduler._process_pending_omni_inputs("ar")
|
||||
@@ -130,7 +134,7 @@ def test_schedule_lifecycle_helpers_process_and_restore_both_input_paths():
|
||||
("chunk-timeouts", omni_scheduler_mixin.DEFAULT_INPUT_WAIT_TIMEOUT_S),
|
||||
("failed-sends",),
|
||||
("restore-chunks", scheduler.waiting, scheduler.running, scheduler.requests),
|
||||
("restore-full", scheduler.waiting),
|
||||
("restore-full", scheduler.waiting, scheduler.running),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Drain ready events once, merging live requests and filtering cancellations."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.core.sched.omni_scheduler_mixin import OmniSchedulerMixin
|
||||
from vllm_omni.outputs import OmniConnectorOutput
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_ready_inbox_coalesces_live_events_and_drops_cancelled(mocker):
|
||||
scheduler = OmniSchedulerMixin()
|
||||
scheduler.requests, scheduler.waiting, scheduler.running = {"r": object()}, [], []
|
||||
coordinator = SimpleNamespace(
|
||||
_async_chunk=True, update_request_metadata=mocker.Mock(), process_pending_chunks=mocker.Mock()
|
||||
)
|
||||
scheduler.input_coordinator = coordinator
|
||||
scheduler._init_omni_connector_output_inbox()
|
||||
scheduler.enqueue_omni_connector_output(OmniConnectorOutput(chunk_ready_req_ids={"r"}))
|
||||
scheduler.enqueue_omni_connector_output(
|
||||
OmniConnectorOutput(
|
||||
chunk_ready_req_ids={"r", "aborted"},
|
||||
chunk_finished_req_ids={"r", "aborted"},
|
||||
request_metadata={"r": {"decode_token_end": 2}, "aborted": {"decode_token_end": 99}},
|
||||
)
|
||||
)
|
||||
scheduler._consume_pending_connector_output(model_mode="ar")
|
||||
coordinator.update_request_metadata.assert_called_once_with(
|
||||
scheduler.requests, {"r": {"decode_token_end": 2}}, model_mode="ar"
|
||||
)
|
||||
coordinator.process_pending_chunks.assert_called_once_with([], [], {"r"}, {"r"})
|
||||
scheduler._consume_pending_connector_output(model_mode="ar")
|
||||
assert coordinator.update_request_metadata.call_count == 1
|
||||
coordinator.process_pending_chunks.assert_called_with([], [], set(), set())
|
||||
@@ -1,3 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Tests for the ``num_waiting_for_streaming_input`` resync placed in
|
||||
``OmniARScheduler.finish_requests`` / ``OmniGenerationScheduler.finish_requests``
|
||||
and in ``OmniARScheduler.schedule``.
|
||||
@@ -128,6 +131,7 @@ def test_ar_schedule_resyncs_before_delegating_upstream(monkeypatch: pytest.Monk
|
||||
scheduler.skipped_waiting = []
|
||||
scheduler.num_waiting_for_streaming_input = 1 # leaked by the status rewrite
|
||||
scheduler.policy = "fcfs"
|
||||
scheduler.max_num_running_reqs = 8
|
||||
|
||||
seen: dict[str, int] = {}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for OmniSchedulingCoordinator.
|
||||
|
||||
These tests use mock request objects and mock queues. They do not require
|
||||
@@ -20,7 +20,9 @@ import torch
|
||||
import vllm_omni.core.sched.omni_scheduling_coordinator as coord_mod
|
||||
from vllm_omni.core.sched.omni_scheduling_coordinator import (
|
||||
OmniSchedulingCoordinator,
|
||||
uses_native_mrv2_data_plane,
|
||||
)
|
||||
from vllm_omni.core.sched.output import OmniChunkRecvHandle
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -56,6 +58,7 @@ def _make_request(req_id: str, status: str = "waiting") -> SimpleNamespace:
|
||||
prompt_token_ids=[],
|
||||
num_prompt_tokens=0,
|
||||
num_computed_tokens=0,
|
||||
num_output_placeholders=0,
|
||||
_all_token_ids=[],
|
||||
_output_token_ids=[],
|
||||
payload_sender_info=None,
|
||||
@@ -83,7 +86,7 @@ class MockQueue:
|
||||
def prepend_requests(self, requests):
|
||||
self._items = list(requests) + self._items
|
||||
|
||||
def remove(self, request):
|
||||
def remove_request(self, request):
|
||||
self._items.remove(request)
|
||||
|
||||
def remove_requests(self, requests):
|
||||
@@ -96,7 +99,47 @@ class MockQueue:
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
class TestCoordinatorUpdateRequestMetadata(unittest.TestCase):
|
||||
class TestNativeMRV2DataPlaneSelection(unittest.TestCase):
|
||||
def test_native_plane_requires_v2_and_async_chunk_capability(self):
|
||||
native = SimpleNamespace(async_chunk=True, supports_native_mrv2_data_plane=True)
|
||||
|
||||
self.assertTrue(uses_native_mrv2_data_plane(native, use_v2_model_runner=True))
|
||||
self.assertFalse(uses_native_mrv2_data_plane(native, use_v2_model_runner=False))
|
||||
self.assertFalse(uses_native_mrv2_data_plane(SimpleNamespace(async_chunk=False), use_v2_model_runner=True))
|
||||
|
||||
|
||||
def test_chunk_registration_ready_and_terminal_lifecycle():
|
||||
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1, async_chunk=True)
|
||||
req = _make_request("internal", status=RequestStatus.WAITING)
|
||||
req.external_req_id = "external"
|
||||
waiting = MockQueue([req])
|
||||
coord.process_pending_chunks(waiting, [], set(), set())
|
||||
assert req.status == RequestStatus.WAITING_FOR_CHUNK
|
||||
[handle] = coord.pending_chunk_registrations
|
||||
assert isinstance(handle, OmniChunkRecvHandle)
|
||||
assert (handle.request_id, handle.external_req_id) == ("internal", "external")
|
||||
coord.restore_queues(waiting, [])
|
||||
coord.process_pending_chunks(waiting, [], {"internal"}, set())
|
||||
assert req.status == RequestStatus.WAITING
|
||||
assert "internal" in coord.requests_with_ready_chunks
|
||||
req.status = RequestStatus.WAITING_FOR_CHUNK
|
||||
coord.process_pending_chunks(waiting, [], set(), {"internal"})
|
||||
assert "internal" in coord.finished_requests
|
||||
|
||||
|
||||
def test_chunk_waiting_removes_request_from_running_list():
|
||||
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1, async_chunk=True)
|
||||
req = _make_request("running", status=RequestStatus.RUNNING)
|
||||
running = [req]
|
||||
|
||||
coord.process_pending_chunks(MockQueue(), running, set(), set())
|
||||
|
||||
assert running == []
|
||||
assert req.status == RequestStatus.WAITING_FOR_CHUNK
|
||||
assert list(coord._waiting_for_chunk_running) == [req]
|
||||
|
||||
|
||||
class TestChunkCoordinatorUpdateRequestMetadata(unittest.TestCase):
|
||||
"""Test update_request_metadata applies scheduling metadata to requests."""
|
||||
|
||||
def test_ar_mode_no_longer_sets_additional_information(self):
|
||||
@@ -382,17 +425,18 @@ class TestTimeoutDetection(unittest.TestCase):
|
||||
self.assertEqual(result, {"r1"})
|
||||
self.assertEqual(len(coord._waiting_for_input), 0)
|
||||
|
||||
def test_free_finished_request_clears_waiting_since(self):
|
||||
"""free_finished_request clears coordinator lifecycle markers."""
|
||||
coord = OmniSchedulingCoordinator(stage_id=1)
|
||||
coord._waiting_since["r1"] = 0.0
|
||||
coord._full_payload_input_received.add("r1")
|
||||
def test_free_finished_request_clears_all_lifecycle_state(self):
|
||||
"""free_finished_request makes stale connector events harmless."""
|
||||
coord = OmniSchedulingCoordinator(scheduler_max_num_seqs=10, stage_id=1)
|
||||
r1, r2 = _make_request("r1"), _make_request("r2")
|
||||
coord.finished_requests.add("r1")
|
||||
coord.requests_with_ready_chunks.add("r1")
|
||||
coord._waiting_for_chunk_running.extend([r1, r2])
|
||||
coord.pending_chunk_registrations = [OmniChunkRecvHandle(request_id="r1"), OmniChunkRecvHandle(request_id="r2")]
|
||||
|
||||
coord.free_finished_request("r1")
|
||||
self.assertNotIn("r1", coord._waiting_since)
|
||||
self.assertNotIn("r1", coord._full_payload_input_received)
|
||||
|
||||
self.assertNotIn("r1", coord.finished_requests)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
self.assertNotIn("r1", coord.requests_with_ready_chunks)
|
||||
self.assertEqual([r.request_id for r in coord._waiting_for_chunk_running], ["r2"])
|
||||
self.assertEqual([h.request_id for h in coord.pending_chunk_registrations], ["r2"])
|
||||
@@ -13,6 +13,7 @@ import os
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import get_asset_path
|
||||
@@ -57,7 +58,12 @@ tts_server_params = [
|
||||
pytest.param(
|
||||
(MODEL, get_cuda_graph_config()),
|
||||
id="no_cuda_graph",
|
||||
)
|
||||
),
|
||||
pytest.param(
|
||||
(MODEL, get_deploy_config_path("qwen3_tts_mrv2.yaml")),
|
||||
id="async_chunk_mrv2",
|
||||
marks=pytest.mark.skipif(not current_platform.is_cuda(), reason="MRV2 validation is CUDA-only"),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import os
|
||||
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
|
||||
|
||||
import pytest
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from tests.helpers.media import get_asset_path
|
||||
@@ -50,7 +51,16 @@ tts_server_params = [
|
||||
server_args=["--trust-remote-code"],
|
||||
),
|
||||
id="async_chunk",
|
||||
)
|
||||
),
|
||||
pytest.param(
|
||||
OmniServerParams(
|
||||
model=MODEL,
|
||||
stage_config_path=get_deploy_config_path("qwen3_tts_mrv2.yaml"),
|
||||
server_args=["--trust-remote-code"],
|
||||
),
|
||||
id="async_chunk_mrv2",
|
||||
marks=pytest.mark.skipif(not current_platform.is_cuda(), reason="MRV2 validation is CUDA-only"),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -311,7 +311,7 @@ def _engine_core_outputs(tag: str, timestamp: float) -> SimpleNamespace:
|
||||
return SimpleNamespace(outputs=[tag], timestamp=timestamp, scheduler_stats=None, finished_requests=None)
|
||||
|
||||
|
||||
def _terminal_engine_core_outputs(request_id: str) -> EngineCoreOutputs:
|
||||
def _terminal_engine_core_outputs(request_id: str, timestamp: float = 1.0) -> EngineCoreOutputs:
|
||||
return EngineCoreOutputs(
|
||||
outputs=[
|
||||
EngineCoreOutput(
|
||||
@@ -320,7 +320,7 @@ def _terminal_engine_core_outputs(request_id: str) -> EngineCoreOutputs:
|
||||
finish_reason=FinishReason.STOP,
|
||||
)
|
||||
],
|
||||
timestamp=1.0,
|
||||
timestamp=timestamp,
|
||||
finished_requests={request_id},
|
||||
)
|
||||
|
||||
@@ -520,6 +520,7 @@ async def _enqueue_add_request(
|
||||
original_prompt,
|
||||
sampling_params_list,
|
||||
final_stage_id: int,
|
||||
final_output_stage_ids: list[int] | None = None,
|
||||
) -> None:
|
||||
orchestrator_fixture.request_sync_q.put_nowait(
|
||||
StageSubmissionMessage(
|
||||
@@ -530,6 +531,7 @@ async def _enqueue_add_request(
|
||||
output_prompt_text=None,
|
||||
sampling_params_list=sampling_params_list,
|
||||
final_stage_id=final_stage_id,
|
||||
final_output_stage_ids=final_output_stage_ids,
|
||||
preprocess_ms=0.0,
|
||||
request_timestamp=time.time(),
|
||||
enqueue_ts=time.perf_counter(),
|
||||
@@ -789,6 +791,10 @@ async def test_run_async_chunk(orchestrator_factory) -> None:
|
||||
|
||||
stage1.push_engine_core_outputs(_engine_core_outputs("stage1-final", 3.0))
|
||||
|
||||
await _wait_for(
|
||||
lambda: orchestrator_fixture.orchestrator.request_states["req-async"].pending_final_output is not None
|
||||
)
|
||||
stage0.push_engine_core_outputs(_engine_core_outputs("stage0-final", 3.1))
|
||||
output_msg = await _get_output_message(orchestrator_fixture)
|
||||
|
||||
assert output_msg.request_id == "req-async"
|
||||
|
||||
@@ -259,6 +259,17 @@ def test_native_text_tpot_only_accepts_positive_finished_metric(
|
||||
assert processor.pop_native_text_metrics("r")["vllm_tpot_ms"] == expected_tpot_ms
|
||||
|
||||
|
||||
def test_suppressed_native_tokens_use_authoritative_count_even_without_stats(monkeypatch):
|
||||
monkeypatch.setattr(VLLMOutputProcessor, "_update_stats_from_output", lambda *args, **kwargs: None)
|
||||
processor = object.__new__(MultimodalOutputProcessor)
|
||||
processor._native_text_metrics_by_request = {}
|
||||
state = _make_state(RequestOutputKind.FINAL_ONLY)
|
||||
processor._update_stats_from_output(
|
||||
state, SimpleNamespace(new_token_ids=[2150], num_generation_tokens=2048), None, None
|
||||
)
|
||||
assert processor.pop_native_text_metrics("r")["num_generation_tokens"] == 2048
|
||||
|
||||
|
||||
def test_delta_drains_output_modality_per_step():
|
||||
"""DELTA drains the mm_type key (output modality) but preserves hidden-state keys."""
|
||||
s = _make_state(RequestOutputKind.DELTA)
|
||||
@@ -616,6 +627,7 @@ def test_no_detokenizer_process_outputs_returns_nonterminal_audio_chunk(monkeypa
|
||||
finish_reason=None,
|
||||
stop_reason=None,
|
||||
kv_transfer_params=None,
|
||||
ec_transfer_params=None,
|
||||
routed_experts=None,
|
||||
num_cached_tokens=0,
|
||||
)
|
||||
@@ -631,6 +643,7 @@ def _make_mm_only_output_processor(monkeypatch):
|
||||
processor = object.__new__(MultimodalOutputProcessor)
|
||||
processor.output_modality = OutputModality.AUDIO
|
||||
processor.request_states = {"r": _make_no_detok_state(RequestOutputKind.DELTA)}
|
||||
processor.tracing_enabled = False
|
||||
monkeypatch.setattr(
|
||||
VLLMOutputProcessor,
|
||||
"process_outputs",
|
||||
@@ -660,6 +673,7 @@ def _audio_engine_output(*, is_segment_finished: bool, is_last_chunk: bool):
|
||||
finish_reason=FinishReason.STOP,
|
||||
stop_reason=None,
|
||||
kv_transfer_params=None,
|
||||
ec_transfer_params=None,
|
||||
routed_experts=None,
|
||||
num_cached_tokens=0,
|
||||
is_segment_finished=is_segment_finished,
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Regression tests for MRv2 Omni AR text detach and generation payload outputs."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.sampling_params import RequestOutputKind
|
||||
from vllm.v1.engine import FinishReason
|
||||
|
||||
from vllm_omni.engine import OmniEngineCoreOutput
|
||||
from vllm_omni.engine.output_modality import OutputModality
|
||||
from vllm_omni.engine.output_processor import (
|
||||
MultimodalOutputProcessor,
|
||||
OmniRequestState,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _Detokenizer:
|
||||
def __init__(self):
|
||||
self.output_token_ids = []
|
||||
self.output_text = ""
|
||||
self.update_calls = []
|
||||
|
||||
def update(self, token_ids, stop):
|
||||
self.update_calls.append((list(token_ids), stop))
|
||||
self.output_token_ids.extend(token_ids)
|
||||
self.output_text += "X" * len(token_ids)
|
||||
return None
|
||||
|
||||
def get_next_output_text(self, finished, delta):
|
||||
return self.output_text
|
||||
|
||||
def num_output_tokens(self):
|
||||
return len(self.output_token_ids)
|
||||
|
||||
|
||||
def _make_processor(output_modality, detokenizer=None):
|
||||
state = OmniRequestState(
|
||||
request_id="r",
|
||||
external_req_id="r",
|
||||
parent_req=None,
|
||||
request_index=0,
|
||||
lora_request=None,
|
||||
output_kind=RequestOutputKind.FINAL_ONLY,
|
||||
prompt="prompt" if detokenizer else None,
|
||||
prompt_token_ids=[1] if detokenizer else [],
|
||||
prompt_embeds=None,
|
||||
logprobs_processor=MagicMock(logprobs=None, cumulative_logprob=None, prompt_logprobs=None)
|
||||
if detokenizer
|
||||
else None,
|
||||
detokenizer=detokenizer,
|
||||
max_tokens_param=None,
|
||||
arrival_time=0.0,
|
||||
queue=None,
|
||||
log_stats=False,
|
||||
stream_interval=1,
|
||||
)
|
||||
processor = MultimodalOutputProcessor(tokenizer=None, log_stats=False, output_modality=output_modality)
|
||||
processor.request_states["r"] = state
|
||||
processor.external_req_ids["r"].append("r")
|
||||
return processor, state
|
||||
|
||||
|
||||
def _rehydrated_output(*, pooling_output=None, finish_reason=FinishReason.STOP):
|
||||
"""Build the post-StagePool shape without violating vLLM's wire schema."""
|
||||
return SimpleNamespace(
|
||||
request_id="r",
|
||||
new_token_ids=[42],
|
||||
pooling_output=pooling_output,
|
||||
finish_reason=finish_reason,
|
||||
stop_reason=None,
|
||||
kv_transfer_params=None,
|
||||
ec_transfer_params=None,
|
||||
routed_experts=None,
|
||||
trace_headers=None,
|
||||
prefill_stats=None,
|
||||
spec_decode_metrics=None,
|
||||
new_sampling_mask=None,
|
||||
num_nans_in_logits=0,
|
||||
multimodal_output=None,
|
||||
is_segment_finished=False,
|
||||
is_non_final_audio_chunk=False,
|
||||
output_type=None,
|
||||
num_generation_tokens=None,
|
||||
finished=True,
|
||||
)
|
||||
|
||||
|
||||
def test_text_tokens_are_detokenized_when_mrv2_ar_output_has_pooling_payload():
|
||||
detokenizer = _Detokenizer()
|
||||
processor, state = _make_processor(OutputModality.LATENT, detokenizer)
|
||||
|
||||
# StagePool has already rehydrated the MRv2 carrier. Use a structural
|
||||
# output here because upstream EngineCoreOutput strictly validates
|
||||
# pooling_output as torch.Tensor | None on construction.
|
||||
output = _rehydrated_output(pooling_output={"hidden": torch.ones(1, 4)})
|
||||
|
||||
processed = processor.process_outputs([output])
|
||||
|
||||
assert detokenizer.update_calls == [([42], True)]
|
||||
completion = processed.request_outputs[0].outputs[0]
|
||||
assert list(completion.token_ids) == [42]
|
||||
assert completion.text == "X"
|
||||
assert not state.mm_accumulated.is_empty
|
||||
|
||||
|
||||
@pytest.mark.parametrize("streaming", [False, True])
|
||||
def test_generation_stage_mm_delivered_only_with_terminal(streaming):
|
||||
# Non-terminal chunks accumulate; the terminal output carries the audio.
|
||||
# When the first output is already terminal it is delivered directly.
|
||||
processor, _ = _make_processor(OutputModality.AUDIO)
|
||||
audio = torch.ones(1, 320)
|
||||
sr = torch.tensor(24000, dtype=torch.int32)
|
||||
mm_output = OmniEngineCoreOutput(
|
||||
request_id="r",
|
||||
new_token_ids=[],
|
||||
multimodal_output={"model_outputs": audio, "sr": sr},
|
||||
finish_reason=None if streaming else FinishReason.STOP,
|
||||
)
|
||||
|
||||
processed = processor.process_outputs([mm_output])
|
||||
if streaming:
|
||||
assert processed.request_outputs == []
|
||||
processed = processor.process_outputs(
|
||||
[OmniEngineCoreOutput(request_id="r", new_token_ids=[], finish_reason=FinishReason.STOP)]
|
||||
)
|
||||
|
||||
assert len(processed.request_outputs) == 1
|
||||
completion = processed.request_outputs[0].outputs[0]
|
||||
assert completion.text == ""
|
||||
assert torch.equal(completion.multimodal_output["audio"], audio)
|
||||
assert completion.multimodal_output["sr"].item() == 24000
|
||||
@@ -0,0 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.request_snapshot import copy_request_snapshot
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_full_snapshot_preserves_fields_aliases_and_isolation():
|
||||
samples = [0.25, 0.5]
|
||||
source = {"prompt_token_ids": [1, 2], "additional_information": {"samples": samples}, "alias": samples}
|
||||
result = copy_request_snapshot(source)
|
||||
assert result == copy.deepcopy(source)
|
||||
assert result["alias"] is result["additional_information"]["samples"]
|
||||
result["alias"].append(0.75)
|
||||
result["prompt_token_ids"][0] = 9
|
||||
assert samples == [0.25, 0.5]
|
||||
assert source["prompt_token_ids"] == [1, 2]
|
||||
@@ -1393,7 +1393,7 @@ class TestConnectRemoteEngineCoresCoordinator:
|
||||
yield mocker.Mock()
|
||||
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.zmq_socket_ctx", return_value=fake_socket_ctx())
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup")
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup", autospec=True)
|
||||
with connect_remote_engine_cores(
|
||||
vllm_config=vllm_config,
|
||||
omni_master_server=omni_master_server,
|
||||
@@ -1428,7 +1428,7 @@ class TestConnectRemoteEngineCoresCoordinator:
|
||||
yield mocker.Mock()
|
||||
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.zmq_socket_ctx", return_value=fake_socket_ctx())
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup")
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup", autospec=True)
|
||||
with connect_remote_engine_cores(
|
||||
vllm_config=vllm_config,
|
||||
omni_master_server=omni_master_server,
|
||||
@@ -1454,7 +1454,7 @@ class TestConnectRemoteEngineCoresCoordinator:
|
||||
yield mocker.Mock()
|
||||
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.zmq_socket_ctx", return_value=fake_socket_ctx())
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup")
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup", autospec=True)
|
||||
|
||||
with connect_remote_diffusion_proc(
|
||||
omni_master_server=omni_master_server,
|
||||
@@ -1466,7 +1466,8 @@ class TestConnectRemoteEngineCoresCoordinator:
|
||||
omni_master_server.get_zmq_addresses.assert_called_once_with(7, replica_id=2)
|
||||
omni_master_server.get_allocation.assert_called_once_with(7, replica_id=2)
|
||||
mock_wait.assert_called_once()
|
||||
_, core_engines, parallel_config, *_ = mock_wait.call_args.args
|
||||
_, core_engines, parallel_config, _, _, launch = mock_wait.call_args.args
|
||||
assert launch.addresses is omni_master_server.get_zmq_addresses.return_value
|
||||
assert core_engines[0].local is False
|
||||
assert parallel_config.data_parallel_size_local == 0
|
||||
|
||||
@@ -1507,7 +1508,7 @@ class TestLaunchOmniCoreEngines:
|
||||
"vllm_omni.engine.stage_engine_startup.CoreEngineProcManager",
|
||||
return_value=local_engine_manager,
|
||||
)
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup")
|
||||
mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup", autospec=True)
|
||||
with _launch_omni_core_engines(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=mocker.Mock(),
|
||||
@@ -1584,7 +1585,7 @@ class TestLaunchOmniCoreEngines:
|
||||
"vllm_omni.engine.stage_engine_startup.CoreEngineProcManager",
|
||||
return_value=mocker.Mock(),
|
||||
)
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup")
|
||||
mock_wait = mocker.patch("vllm_omni.engine.stage_engine_startup.wait_for_engine_startup", autospec=True)
|
||||
with _launch_omni_core_engines(
|
||||
vllm_config=vllm_config,
|
||||
executor_class=mocker.Mock(),
|
||||
|
||||
@@ -8,6 +8,7 @@ import sys
|
||||
import types
|
||||
from dataclasses import fields, replace
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from pydantic.fields import FieldInfo
|
||||
@@ -61,9 +62,14 @@ _DEPLOY_DIR = Path(__file__).parents[2] / "vllm_omni" / "deploy"
|
||||
def _effective_backend_values(config_cls: type, engine_args: dict) -> dict[str, object]:
|
||||
backend_fields = fields(config_cls)
|
||||
backend_field_names = {backend_field.name for backend_field in backend_fields}
|
||||
backend_config = config_cls(
|
||||
**{name: copy.deepcopy(value) for name, value in engine_args.items() if name in backend_field_names}
|
||||
)
|
||||
# This is a schema/normalization comparison, not a Hub download test.
|
||||
with (
|
||||
patch("vllm.engine.arg_utils.get_model_path", side_effect=lambda model, *_: model),
|
||||
patch("vllm_omni.diffusion.data.get_model_path", side_effect=lambda model, *_: model),
|
||||
):
|
||||
backend_config = config_cls(
|
||||
**{name: copy.deepcopy(value) for name, value in engine_args.items() if name in backend_field_names}
|
||||
)
|
||||
effective_values: dict[str, object] = {}
|
||||
for backend_field in backend_fields:
|
||||
value = getattr(backend_config, backend_field.name)
|
||||
@@ -78,6 +84,9 @@ _DIFFUSION_BACKEND_FIELDS = frozenset(field.name for field in fields(OmniDiffusi
|
||||
_TOPOLOGY_ONLY_ENGINE_ARGS = frozenset({"inline_diffusion"})
|
||||
_OMNI_ONLY_LLM_STAGE_ENGINE_FIELDS = frozenset(
|
||||
{
|
||||
"final_output",
|
||||
"use_v2_model_runner",
|
||||
"supports_native_mrv2_data_plane",
|
||||
"active_stream_window",
|
||||
"codec_frame_rate_hz",
|
||||
"custom_voice_dir",
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Terminal audio must not retire a request before upstream terminal metrics."""
|
||||
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.engine.orchestrator import Orchestrator, OrchestratorRequestState
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def build():
|
||||
o = Orchestrator.__new__(Orchestrator)
|
||||
o.stage_pools = [
|
||||
SimpleNamespace(
|
||||
final_output=False, build_stage_metrics=lambda *a, **k: SimpleNamespace(stage_id=0, num_tokens_out=42)
|
||||
),
|
||||
SimpleNamespace(
|
||||
final_output=True, build_stage_metrics=lambda *a, **k: SimpleNamespace(stage_id=1, num_tokens_out=0)
|
||||
),
|
||||
]
|
||||
state = OrchestratorRequestState(
|
||||
request_id="r",
|
||||
final_stage_id=1,
|
||||
final_output_stage_ids={1},
|
||||
stage_submit_ts={0: 0, 1: 0},
|
||||
sampling_params_list=[None, None],
|
||||
)
|
||||
o.request_states = {"r": state}
|
||||
o.output_async_queue = asyncio.Queue()
|
||||
o.async_chunk = True
|
||||
o._pd_pair = None
|
||||
o._cfg_tracker = MagicMock()
|
||||
o._cfg_tracker.is_companion.return_value = False
|
||||
o._cfg_tracker.cleanup_parent.return_value = []
|
||||
o._is_duplex_session_request = lambda s: False
|
||||
o._duplex_output_decision = lambda *a: None
|
||||
o._stage_receives_async_chunks = lambda s: True
|
||||
cleaned = []
|
||||
|
||||
async def cleanup(ids):
|
||||
cleaned.extend(ids)
|
||||
for r in ids:
|
||||
o.request_states.pop(r, None)
|
||||
|
||||
o._cleanup_request_ids = cleanup
|
||||
return o, state, cleaned
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("order", [(0, 1), (1, 0)])
|
||||
async def test_terminal_metrics_precede_final_audio_for_either_arrival_order(order):
|
||||
o, state, cleaned = build()
|
||||
for stage in order:
|
||||
await o._handle_processed_outputs(stage, 0, [SimpleNamespace(request_id="r", finished=True, error=None)])
|
||||
if stage == 1 and not state.finished_stage_ids.issuperset({0, 1}):
|
||||
assert o.output_async_queue.empty()
|
||||
assert "r" in o.request_states
|
||||
assert cleaned == []
|
||||
metrics = o.output_async_queue.get_nowait()
|
||||
final = o.output_async_queue.get_nowait()
|
||||
assert type(metrics).__name__ == "StageMetricsMessage"
|
||||
assert metrics.stage_id == 0 and metrics.metrics.num_tokens_out == 42
|
||||
assert type(final).__name__ == "OutputMessage" and final.finished
|
||||
assert o.output_async_queue.empty()
|
||||
assert cleaned == ["r"]
|
||||
assert state.pending_final_output is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancelled_pending_output_is_not_published_by_late_upstream():
|
||||
o, state, cleaned = build()
|
||||
await o._handle_processed_outputs(1, 0, [SimpleNamespace(request_id="r", finished=True, error=None)])
|
||||
assert state.pending_final_output is not None
|
||||
await o._cleanup_request_ids(["r"])
|
||||
await o._handle_processed_outputs(0, 0, [SimpleNamespace(request_id="r", finished=True, error=None)])
|
||||
assert o.output_async_queue.empty()
|
||||
assert cleaned == ["r"]
|
||||
@@ -0,0 +1,95 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
from collections import OrderedDict
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from vllm_omni.entrypoints.openai.serving_speech import (
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_BYTES,
|
||||
_REF_AUDIO_RESOLVE_CACHE_MAX_ENTRIES,
|
||||
OmniOpenAIServingSpeech,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cache():
|
||||
server = object.__new__(OmniOpenAIServingSpeech)
|
||||
server._diffusion_mode = False
|
||||
server.model_config = None
|
||||
server._ref_audio_resolve_cache = OrderedDict()
|
||||
server._ref_audio_resolve_cache_bytes = 0
|
||||
server._ref_audio_resolve_cache_max_entries = _REF_AUDIO_RESOLVE_CACHE_MAX_ENTRIES
|
||||
server._ref_audio_resolve_cache_max_bytes = _REF_AUDIO_RESOLVE_CACHE_MAX_BYTES
|
||||
server._ref_audio_model_artifact_ready = set()
|
||||
server._request_ref_audio_artifact_keys = {}
|
||||
return server
|
||||
|
||||
|
||||
def _put(cache, key, samples, artifact=None):
|
||||
cache._put_resolved_ref_audio(key, samples, 24000, artifact or key)
|
||||
|
||||
|
||||
def test_compact_storage_and_default_capacity(cache):
|
||||
assert cache._ref_audio_resolve_cache_max_entries == 1024
|
||||
assert cache._ref_audio_resolve_cache_max_bytes == 512 * 1024 * 1024
|
||||
_put(cache, "a", [0.0, 0.25, -0.5, 1.0])
|
||||
value = cache._ref_audio_resolve_cache["a"]
|
||||
assert value[0].dtype == np.float32
|
||||
assert value[2] == cache._ref_audio_resolve_cache_bytes == 16
|
||||
|
||||
|
||||
def test_cached_float32_roundtrip_and_mutation_isolation(cache):
|
||||
source = "data:audio/wav;base64,already-cached"
|
||||
key = hashlib.sha1(source.encode()).hexdigest()
|
||||
values = np.random.default_rng(42).standard_normal(48000).astype(np.float32).tolist()
|
||||
expected = values.copy()
|
||||
_put(cache, key, values)
|
||||
values[0] = 99.0
|
||||
first, sample_rate, _ = asyncio.run(cache._resolve_ref_audio(source))
|
||||
assert first == expected
|
||||
first[0] = 100.0
|
||||
second, _, _ = asyncio.run(cache._resolve_ref_audio(source))
|
||||
assert sample_rate == 24000
|
||||
assert second == expected
|
||||
|
||||
|
||||
def test_entry_eviction_invalidates_artifact_readiness(cache):
|
||||
cache._ref_audio_resolve_cache_max_entries = 2
|
||||
_put(cache, "a", [0.0])
|
||||
cache._ref_audio_model_artifact_ready.add(("a", False))
|
||||
_put(cache, "b", [0.0])
|
||||
_put(cache, "c", [0.0])
|
||||
assert list(cache._ref_audio_resolve_cache) == ["b", "c"]
|
||||
assert ("a", False) not in cache._ref_audio_model_artifact_ready
|
||||
|
||||
|
||||
def test_byte_budget_evicts_and_rejects_oversized_entries(cache):
|
||||
cache._ref_audio_resolve_cache_max_bytes = 16
|
||||
_put(cache, "a", [0.0] * 3)
|
||||
_put(cache, "b", [0.0] * 3)
|
||||
assert list(cache._ref_audio_resolve_cache) == ["b"]
|
||||
assert cache._ref_audio_resolve_cache_bytes == 12
|
||||
_put(cache, "too-large", [0.0] * 5)
|
||||
assert "too-large" not in cache._ref_audio_resolve_cache
|
||||
|
||||
|
||||
def test_replacement_accounts_bytes_and_preserves_referenced_artifact(cache):
|
||||
_put(cache, "a", [0.0] * 3, "same")
|
||||
_put(cache, "alias", [0.0] * 2, "same")
|
||||
cache._ref_audio_model_artifact_ready.add(("same", False))
|
||||
_put(cache, "a", [1.0] * 4, "new")
|
||||
assert cache._ref_audio_resolve_cache_bytes == 24
|
||||
assert ("same", False) in cache._ref_audio_model_artifact_ready
|
||||
|
||||
|
||||
def test_pool_accepts_666_references(cache):
|
||||
for index in range(666):
|
||||
_put(cache, str(index), [0.0] * 8)
|
||||
assert len(cache._ref_audio_resolve_cache) == 666
|
||||
assert cache._ref_audio_resolve_cache_bytes == 666 * 8 * 4
|
||||
@@ -682,6 +682,7 @@ class TestCodePredictorGraphReplay:
|
||||
return_proj_buf=False,
|
||||
)
|
||||
predictor._prefix_graphs_enabled = False
|
||||
predictor._prefix_reprefill_enabled = False
|
||||
predictor._bucket_pos_ids = {1: torch.arange(4).unsqueeze(0)}
|
||||
graph = mocker.Mock()
|
||||
graph_output = torch.zeros(1, 4, 4)
|
||||
@@ -1362,3 +1363,38 @@ class TestCodePredictorFusedProjections:
|
||||
|
||||
with pytest.raises(RuntimeError, match="missing fused parameters"):
|
||||
model.load_weights(weights)
|
||||
|
||||
|
||||
class TestMTPExecutionBuckets:
|
||||
"""Outer MRv2 MTP graph buckets must align with the predictor bucket set."""
|
||||
|
||||
def test_configure_mtp_execution_buckets(self, mocker: MockerFixture, loaded_target_classes) -> None:
|
||||
_ = loaded_target_classes
|
||||
common_mod = sys.modules["vllm_omni.model_executor.models.common.qwen3_code_predictor"]
|
||||
mocker.patch.object(common_mod.current_omni_platform, "is_npu", return_value=False)
|
||||
|
||||
cp_config, _ = _make_tiny_config(loaded_target_classes)
|
||||
vllm_config = _make_vllm_config(mocker, max_num_seqs=4)
|
||||
wrapper = common_mod.CodePredictorWrapper(
|
||||
vllm_config=vllm_config,
|
||||
cp_config=cp_config,
|
||||
wrapper_config=common_mod.CodePredictorWrapperConfig(use_cuda_graphs=False),
|
||||
talker_hidden_size=cp_config.hidden_size,
|
||||
)
|
||||
|
||||
# Default keeps the legacy power-of-two derivation.
|
||||
assert wrapper._execution_batch_buckets is None
|
||||
assert wrapper._batch_bucket_sizes() == [1, 2, 4]
|
||||
|
||||
wrapper.configure_mtp_execution_buckets([3, 1, 3, 0, 9])
|
||||
assert wrapper._batch_bucket_sizes() == [1, 3, 4] # deduplicate/filter declaration and retain max
|
||||
|
||||
with pytest.raises(RuntimeError, match="before the first warmup"):
|
||||
wrapper2 = common_mod.CodePredictorWrapper(
|
||||
vllm_config=vllm_config,
|
||||
cp_config=cp_config,
|
||||
wrapper_config=common_mod.CodePredictorWrapperConfig(use_cuda_graphs=False),
|
||||
talker_hidden_size=cp_config.hidden_size,
|
||||
)
|
||||
wrapper2._bucket_sizes = [1, 2, 4] # stand-in for warmed-up state
|
||||
wrapper2.configure_mtp_execution_buckets([3])
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""
|
||||
Tests for CUDA Graph decoder wrapper numerical equivalence.
|
||||
|
||||
@@ -142,6 +142,28 @@ def test_padded_output_shape_and_length(decoder, wrapper, seq_len):
|
||||
assert graph_out.shape[-1] == expected_len
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
def test_padded_batch_size_uses_larger_capture_bucket(decoder):
|
||||
"""Non-exact batch sizes should replay the next captured batch bucket."""
|
||||
w = CUDAGraphDecoderWrapper(
|
||||
decoder=decoder,
|
||||
capture_sizes=[25],
|
||||
capture_batch_sizes=[1, 4],
|
||||
num_quantizers=NUM_QUANTIZERS,
|
||||
enabled=True,
|
||||
)
|
||||
w.warmup(DEVICE)
|
||||
codes = _random_codes(25, batch_size=3)
|
||||
|
||||
with torch.no_grad():
|
||||
eager_out = decoder(codes)
|
||||
graph_out = w.decode(codes)
|
||||
|
||||
assert (4, 25) in w.graphs
|
||||
assert graph_out.shape == eager_out.shape
|
||||
torch.testing.assert_close(graph_out, eager_out, atol=0, rtol=0)
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "L4"}, num_cards=1)
|
||||
@pytest.mark.parametrize("seq_len", [10, 30, 47, 73, 99])
|
||||
def test_padded_interior_positions_close(decoder, wrapper, seq_len):
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Output metadata must not wait for the preceding model forward on CUDA."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.mark import hardware_test
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import (
|
||||
Qwen3TTSTalkerForConditionalGeneration,
|
||||
)
|
||||
from vllm_omni.worker.gpu_ar_model_runner import _snapshot_tensor_payload_to_cpu_async
|
||||
|
||||
pytestmark = [pytest.mark.core_model]
|
||||
|
||||
|
||||
@hardware_test(res={"cuda": "H100"}, num_cards=1)
|
||||
@pytest.mark.parametrize("validity_device", ["cpu", "cuda"])
|
||||
@torch.inference_mode()
|
||||
def test_output_validity_preserves_values_without_waiting_for_forward(validity_device):
|
||||
talker = Qwen3TTSTalkerForConditionalGeneration.__new__(Qwen3TTSTalkerForConditionalGeneration)
|
||||
talker.vllm_config = SimpleNamespace(model_config=SimpleNamespace(async_chunk=True))
|
||||
hidden = torch.zeros((3, 8), device="cuda")
|
||||
infos = [
|
||||
{
|
||||
"codes": {"audio": torch.zeros((frames, 16), device="cuda", dtype=torch.long)},
|
||||
"meta": {"codec_frame_valid": torch.tensor(valid, device=validity_device)},
|
||||
}
|
||||
for frames, valid in [(2, True), (1, False)]
|
||||
]
|
||||
# Warm allocation paths before checking the stream-ordering contract.
|
||||
talker.make_omni_output(hidden, model_intermediate_buffer=infos)
|
||||
copy_stream = torch.cuda.Stream()
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
preceding_forward = torch.cuda.Event()
|
||||
torch.cuda._sleep(500_000_000)
|
||||
preceding_forward.record()
|
||||
output = talker.make_omni_output(hidden, model_intermediate_buffer=infos)
|
||||
waited_for_forward = preceding_forward.query()
|
||||
validity = output.multimodal_outputs["meta"]["codec_frame_valid"]
|
||||
snapshot = _snapshot_tensor_payload_to_cpu_async(
|
||||
output.multimodal_outputs, copy_stream=copy_stream, pin_memory=True
|
||||
)
|
||||
snapshot.wait()
|
||||
|
||||
assert not waited_for_forward, "output construction synchronized the preceding forward"
|
||||
assert validity.device.type == "cuda"
|
||||
assert validity.dtype == torch.int8
|
||||
cpu_validity = snapshot.payload["meta"]["codec_frame_valid"]
|
||||
assert cpu_validity.device.type == "cpu"
|
||||
assert cpu_validity.tolist() == [1, 1, 0]
|
||||
assert all(info["meta"]["codec_frame_valid"].device.type == validity_device for info in infos)
|
||||
@@ -0,0 +1,100 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Exercise actual stateless decoder capture, not a mocked capture indicator."""
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from tests.helpers.mark import hardware_marks
|
||||
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.configuration_qwen3_tts_tokenizer_v2 import (
|
||||
Qwen3TTSTokenizerV2DecoderConfig,
|
||||
)
|
||||
from vllm_omni.model_executor.models.qwen3_tts.tokenizer_12hz.modeling_qwen3_tts_tokenizer_v2 import (
|
||||
Qwen3TTSTokenizerV2DecoderTransformerModel,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, *hardware_marks(res={"cuda": "L4"}, num_cards=1)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch_size", [1, 2])
|
||||
@pytest.mark.parametrize("input_mode", ["implicit", "positions"])
|
||||
@torch.inference_mode()
|
||||
def test_stateless_decoder_capture_replays_new_inputs(batch_size, input_mode):
|
||||
sequence_length = 8
|
||||
torch.manual_seed(42)
|
||||
config = Qwen3TTSTokenizerV2DecoderConfig(
|
||||
hidden_size=32,
|
||||
latent_dim=16,
|
||||
max_position_embeddings=512,
|
||||
num_attention_heads=4,
|
||||
num_key_value_heads=4,
|
||||
intermediate_size=64,
|
||||
num_hidden_layers=1,
|
||||
num_quantizers=2,
|
||||
sliding_window=16,
|
||||
decoder_dim=32,
|
||||
upsample_rates=(2,),
|
||||
upsampling_ratios=(2,),
|
||||
)
|
||||
config._attn_implementation = "sdpa"
|
||||
model = Qwen3TTSTokenizerV2DecoderTransformerModel._from_config(config).cuda().eval()
|
||||
inputs = torch.randn(batch_size, sequence_length, config.latent_dim, device="cuda")
|
||||
positions = {}
|
||||
if input_mode == "positions":
|
||||
cache_position = torch.arange(sequence_length, device="cuda")
|
||||
positions = {"cache_position": cache_position, "position_ids": cache_position.unsqueeze(0)}
|
||||
stream = torch.cuda.Stream()
|
||||
stream.wait_stream(torch.cuda.current_stream())
|
||||
with torch.cuda.stream(stream):
|
||||
for _ in range(3):
|
||||
model(inputs_embeds=inputs, use_cache=False, **positions)
|
||||
torch.cuda.current_stream().wait_stream(stream)
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
# No wrapper or eager fallback: an illegal capture must fail this test.
|
||||
graph = torch.cuda.CUDAGraph()
|
||||
with torch.cuda.graph(graph):
|
||||
captured_output = model(inputs_embeds=inputs, use_cache=False, **positions).last_hidden_state
|
||||
|
||||
outputs = []
|
||||
for _ in range(3):
|
||||
new_inputs = torch.randn_like(inputs)
|
||||
expected = model(inputs_embeds=new_inputs, use_cache=False, **positions).last_hidden_state
|
||||
if input_mode == "implicit":
|
||||
# Compare the cached mask against the independent live-mask path,
|
||||
# not only against eager execution using the same cached mask.
|
||||
reference = model(
|
||||
inputs_embeds=new_inputs,
|
||||
use_cache=False,
|
||||
position_ids=torch.arange(sequence_length, device="cuda").unsqueeze(0),
|
||||
).last_hidden_state
|
||||
torch.testing.assert_close(expected, reference, atol=1e-5, rtol=1e-4)
|
||||
inputs.copy_(new_inputs)
|
||||
graph.replay()
|
||||
torch.accelerator.synchronize()
|
||||
torch.testing.assert_close(captured_output, expected, atol=1e-5, rtol=1e-4)
|
||||
outputs.append(captured_output.clone())
|
||||
assert not torch.equal(outputs[0], outputs[1]), "replay must consume the new input"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("batch_size", [1, 2])
|
||||
@torch.inference_mode()
|
||||
def test_stateless_codec_wrapper_captures_and_replays_waveform(batch_size):
|
||||
from tests.model_executor.models.qwen3_tts.test_qwen3_tts_incremental_decode import _make_small_decoder
|
||||
from vllm_omni.model_executor.models.qwen3_tts.segmented_graph_wrapper import CUDAGraphDecoderWrapper
|
||||
|
||||
torch.manual_seed(42)
|
||||
decoder = _make_small_decoder().cuda().eval()
|
||||
wrapper = CUDAGraphDecoderWrapper(decoder, num_quantizers=2, async_chunk=False)
|
||||
# Exercise the production capture method, including quantization and
|
||||
# waveform convolutions, without accepting warmup's eager fallback.
|
||||
wrapper._capture_stateless(batch_size, 8, torch.device("cuda"), torch.long)
|
||||
state = wrapper.stateless_states[(batch_size, 8)]
|
||||
for _ in range(3):
|
||||
codes = torch.randint(0, 32, (batch_size, 2, 8), device="cuda")
|
||||
expected = decoder._forward_exact(codes)
|
||||
state["input"]["codes"].copy_(codes)
|
||||
state["graph"].replay()
|
||||
torch.accelerator.synchronize()
|
||||
torch.testing.assert_close(state["output"], expected, atol=1e-5, rtol=1e-4)
|
||||
assert torch.isfinite(state["output"]).all()
|
||||
@@ -1,5 +1,9 @@
|
||||
from collections import OrderedDict
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from collections import OrderedDict, UserDict
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
@@ -36,6 +40,7 @@ def _make_minimal_talker(
|
||||
"""
|
||||
model = Qwen3TTSTalkerForConditionalGeneration.__new__(Qwen3TTSTalkerForConditionalGeneration)
|
||||
model.talker_config = SimpleNamespace(codec_pad_id=7, num_code_groups=16)
|
||||
model._codebook_vocab_size = 2048
|
||||
model._embedding_dtype = torch.bfloat16
|
||||
if tts_pad_embed is None:
|
||||
tts_pad_embed = torch.zeros((1, 4), dtype=torch.bfloat16)
|
||||
@@ -51,6 +56,22 @@ def _make_minimal_talker(
|
||||
return model
|
||||
|
||||
|
||||
def test_postprocess_batch_gathers_each_request_tail():
|
||||
from vllm_omni.model_executor.models.output_templates import OwnedBatchTensor
|
||||
|
||||
model = _make_minimal_talker()
|
||||
hidden = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
|
||||
|
||||
key, values = model.postprocess_batch_mrv2(
|
||||
hidden_states=hidden,
|
||||
last_token_indices=torch.tensor([1, 3]),
|
||||
)
|
||||
|
||||
assert key == ("hidden_states", "last")
|
||||
assert isinstance(values, OwnedBatchTensor) # freshly allocated rows transfer ownership
|
||||
assert torch.equal(values.tensor, torch.tensor([[3.0, 4.0], [7.0, 8.0]]))
|
||||
|
||||
|
||||
def _make_minimal_builder(
|
||||
*,
|
||||
config: SimpleNamespace | None = None,
|
||||
@@ -95,6 +116,7 @@ def _make_minimal_builder(
|
||||
)
|
||||
builder._speaker_cache = None
|
||||
builder._text_tokenizer = None
|
||||
builder._projected_token_cache = {}
|
||||
builder._embedding_dtype = torch.bfloat16
|
||||
builder._ref_audio_artifact_cache_max_entries = 256
|
||||
builder._ref_audio_artifact_cache = OrderedDict()
|
||||
@@ -259,6 +281,30 @@ def test_decode_compacts_long_trailing_text_after_large_offset():
|
||||
assert torch.equal(update["hidden_states"]["trailing_text"], trailing_text[65:])
|
||||
|
||||
|
||||
def test_decode_marks_codec_frame_validity_from_processed_input_token():
|
||||
model = _make_minimal_talker()
|
||||
model.embed_input_ids = lambda input_ids: input_ids.to(torch.float32).reshape(1, 1, 1).expand(1, 1, 4)
|
||||
common = {
|
||||
"input_embeds": None,
|
||||
"text": ["hello"],
|
||||
"task_type": ["CustomVoice"],
|
||||
"hidden_states": {
|
||||
"trailing_text": torch.ones((2, 4)),
|
||||
"last": torch.ones(4),
|
||||
},
|
||||
"meta": {"talker_text_offset": 0},
|
||||
"_omni_is_prefill": False,
|
||||
"_omni_num_computed_tokens": 2,
|
||||
"_omni_prompt_len": 2,
|
||||
}
|
||||
|
||||
_, _, valid_update = model.preprocess(input_ids=torch.tensor([123]), **common)
|
||||
_, _, eos_update = model.preprocess(input_ids=torch.tensor([4198]), **common)
|
||||
|
||||
assert valid_update["meta"]["codec_frame_valid"].item() is True
|
||||
assert eos_update["meta"]["codec_frame_valid"].item() is False
|
||||
|
||||
|
||||
def test_decode_replay_span_embeds_all_tokens_without_mutating_decode_state():
|
||||
model = _make_minimal_talker()
|
||||
|
||||
@@ -286,14 +332,17 @@ def test_decode_replay_span_embeds_all_tokens_without_mutating_decode_state():
|
||||
out_embeds.cpu(),
|
||||
torch.tensor([[101.0] * 4, [202.0] * 4, [303.0] * 4], dtype=torch.bfloat16),
|
||||
)
|
||||
assert update == {"meta": {"codec_streaming": True}}
|
||||
assert update["meta"]["codec_streaming"] is True
|
||||
assert update["meta"]["codec_frame_valid"].item() is False
|
||||
|
||||
|
||||
def test_decode_batch_preprocess_matches_decode_state_updates():
|
||||
@pytest.mark.parametrize("mrv2", [False, True])
|
||||
def test_decode_batch_preprocess_matches_decode_state_updates(mrv2):
|
||||
tts_pad = torch.full((1, 4), -1.0, dtype=torch.bfloat16)
|
||||
model = _make_minimal_talker(tts_pad_embed=tts_pad)
|
||||
|
||||
def fake_embed_input_ids(input_ids):
|
||||
assert not mrv2, "MRV2 must reuse the prepared token embeddings"
|
||||
return input_ids.to(torch.float32).reshape(-1, 1, 1).expand(-1, 1, 4)
|
||||
|
||||
model.embed_input_ids = fake_embed_input_ids
|
||||
@@ -302,7 +351,10 @@ def test_decode_batch_preprocess_matches_decode_state_updates():
|
||||
last_a = torch.full((4,), 2.0, dtype=torch.float32)
|
||||
last_b = torch.full((4,), 3.0, dtype=torch.float32)
|
||||
|
||||
out_ids, out_embeds, past_hidden, text_step, updates = model.preprocess_decode_batch(
|
||||
preprocess = model.preprocess_decode_batch_mrv2 if mrv2 else model.preprocess_decode_batch
|
||||
prepared = torch.tensor([[101.0] * 4, [202.0] * 4], dtype=torch.bfloat16)
|
||||
out_ids, out_embeds, past_hidden, text_step, updates = preprocess(
|
||||
**({"input_embeds": prepared} if mrv2 else {}),
|
||||
input_ids=torch.tensor([101, 202], dtype=torch.long),
|
||||
req_infos=[
|
||||
{
|
||||
@@ -321,15 +373,19 @@ def test_decode_batch_preprocess_matches_decode_state_updates():
|
||||
)
|
||||
|
||||
assert out_ids.tolist() == [101, 202]
|
||||
if mrv2:
|
||||
assert out_embeds.data_ptr() == prepared.data_ptr()
|
||||
assert torch.equal(out_embeds.cpu(), torch.tensor([[101.0] * 4, [202.0] * 4], dtype=torch.bfloat16))
|
||||
assert torch.equal(past_hidden.cpu(), torch.stack([last_a, last_b]).to(torch.bfloat16))
|
||||
assert torch.equal(text_step[0].cpu(), trailing_a[1].to(torch.bfloat16))
|
||||
assert torch.equal(text_step[1].cpu(), tts_pad.reshape(-1).to(torch.bfloat16))
|
||||
assert updates[0]["meta"]["talker_text_offset"] == 2
|
||||
assert updates[0]["meta"]["codec_streaming"] is True
|
||||
assert updates[0]["meta"]["codec_frame_valid"].item() is True
|
||||
assert "hidden_states" not in updates[0]
|
||||
assert updates[1]["meta"]["talker_text_offset"] == 0
|
||||
assert updates[1]["meta"]["codec_streaming"] is False
|
||||
assert updates[1]["meta"]["codec_frame_valid"].item() is True
|
||||
assert updates[1]["hidden_states"]["trailing_text"].numel() == 0
|
||||
|
||||
|
||||
@@ -449,11 +505,11 @@ def test_base_voice_clone_batch_preprocess_encodes_ref_code_by_sample_rate():
|
||||
|
||||
def __call__(self, texts, *, padding=False):
|
||||
self.calls.append((texts, padding))
|
||||
return {"input_ids": [[idx + 1, idx + 2, idx + 3] for idx, _ in enumerate(texts)]}
|
||||
return UserDict({"input_ids": [[1, 2, 3], [2, 3, 4, 5]]})
|
||||
|
||||
text_tok = FakeTextTokenizer()
|
||||
builder._text_tokenizer = text_tok
|
||||
buf = {
|
||||
buf: dict[str, dict[str, Any]] = {
|
||||
"r1": {
|
||||
"task_type": ["Base"],
|
||||
"text": ["one"],
|
||||
@@ -488,9 +544,17 @@ def test_base_voice_clone_batch_preprocess_encodes_ref_code_by_sample_rate():
|
||||
assert buf["r2"][NORMALIZED_REF_AUDIO_KEY][0] is wav2
|
||||
assert len(text_tok.calls) == 2
|
||||
assert torch.equal(buf["r1"][PRECOMPUTED_TEXT_IDS_KEY], torch.tensor([1, 2, 3]))
|
||||
assert torch.equal(buf["r2"][PRECOMPUTED_TEXT_IDS_KEY], torch.tensor([2, 3, 4]))
|
||||
assert torch.equal(buf["r2"][PRECOMPUTED_TEXT_IDS_KEY], torch.tensor([2, 3, 4, 5]))
|
||||
assert torch.equal(buf["r1"][PRECOMPUTED_REF_IDS_KEY], torch.tensor([1, 2, 3]))
|
||||
assert torch.equal(buf["r2"][PRECOMPUTED_REF_IDS_KEY], torch.tensor([2, 3, 4]))
|
||||
assert torch.equal(buf["r2"][PRECOMPUTED_REF_IDS_KEY], torch.tensor([2, 3, 4, 5]))
|
||||
assert (
|
||||
buf["r1"][PRECOMPUTED_TEXT_IDS_KEY].untyped_storage().data_ptr()
|
||||
== buf["r2"][PRECOMPUTED_TEXT_IDS_KEY].untyped_storage().data_ptr()
|
||||
)
|
||||
assert (
|
||||
buf["r1"][PRECOMPUTED_REF_IDS_KEY].untyped_storage().data_ptr()
|
||||
== buf["r2"][PRECOMPUTED_REF_IDS_KEY].untyped_storage().data_ptr()
|
||||
)
|
||||
|
||||
|
||||
def test_base_voice_clone_batch_preprocess_reuses_singleton_normalized_audio_without_speech_tokenizer():
|
||||
@@ -506,7 +570,7 @@ def test_base_voice_clone_batch_preprocess_reuses_singleton_normalized_audio_wit
|
||||
return {"input_ids": [[7, 8, 9] for _ in texts]}
|
||||
|
||||
builder._text_tokenizer = FakeTextTokenizer()
|
||||
buf = {
|
||||
buf: dict[str, dict[str, Any]] = {
|
||||
"r1": {
|
||||
"task_type": ["Base"],
|
||||
"text": ["one"],
|
||||
@@ -539,7 +603,7 @@ def test_base_voice_clone_batch_preprocess_skips_after_initial_prefill_state_exi
|
||||
builder._encode_ref_audio_batch_fn = lambda *a, **kw: (_ for _ in ()).throw(
|
||||
AssertionError("speech tokenizer not expected")
|
||||
)
|
||||
buf = {
|
||||
buf: dict[str, dict[str, Any]] = {
|
||||
"r1": {
|
||||
"task_type": ["Base"],
|
||||
"text": ["one"],
|
||||
@@ -574,7 +638,7 @@ def test_base_voice_clone_batch_preprocess_uses_serving_artifact_cache_key_witho
|
||||
return {"input_ids": [[7, 8, 9] for _ in texts]}
|
||||
|
||||
builder._text_tokenizer = FakeTextTokenizer()
|
||||
buf = {
|
||||
buf: dict[str, dict[str, Any]] = {
|
||||
"r1": {
|
||||
"task_type": ["Base"],
|
||||
"text": ["one"],
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Regression tests for cross-request ``codes.ref`` leakage (#4370).
|
||||
|
||||
``make_omni_output`` used to collapse every request's reference codec
|
||||
@@ -11,11 +11,14 @@ vocoder chunks then decoded with another request's reference voice as
|
||||
context (audible onset timbre deformation at any concurrency > 1).
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.models.qwen3_tts.qwen3_tts_talker import (
|
||||
Qwen3TTSTalkerForConditionalGeneration,
|
||||
_qwen3_tts_gpu_resident_buffer_keys,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
@@ -23,6 +26,18 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
_NUM_CODE_GROUPS = 16
|
||||
|
||||
|
||||
def test_large_tts_prefill_artifacts_stay_gpu_resident_only_on_mrv2() -> None:
|
||||
v1_keys = _qwen3_tts_gpu_resident_buffer_keys(False)
|
||||
v2_keys = _qwen3_tts_gpu_resident_buffer_keys(True)
|
||||
|
||||
assert ("embed", "prefill") not in v1_keys
|
||||
assert ("codes", "ref") not in v1_keys
|
||||
assert ("meta", "codec_frame_valid") not in v1_keys
|
||||
assert ("embed", "prefill") in v2_keys
|
||||
assert ("codes", "ref") in v2_keys
|
||||
assert ("meta", "codec_frame_valid") in v2_keys
|
||||
|
||||
|
||||
def _make_talker() -> Qwen3TTSTalkerForConditionalGeneration:
|
||||
# make_omni_output reads no instance state, so skip __init__ (no real
|
||||
# config / checkpoint needed), same as the preprocess tests.
|
||||
@@ -89,3 +104,42 @@ def test_make_omni_output_keeps_hidden_states_for_replay_spans_without_audio_cod
|
||||
|
||||
assert torch.equal(out.text_hidden_states, hidden)
|
||||
assert out.multimodal_outputs["codes"]["audio"].shape == (1, _NUM_CODE_GROUPS)
|
||||
|
||||
|
||||
def test_make_omni_output_preserves_per_request_codec_frame_validity() -> None:
|
||||
talker = _make_talker()
|
||||
talker.vllm_config = SimpleNamespace(model_config=SimpleNamespace(async_chunk=True))
|
||||
valid = _info(1, None)
|
||||
invalid = _info(1, None)
|
||||
valid["meta"]["codec_frame_valid"] = True
|
||||
invalid["meta"]["codec_frame_valid"] = False
|
||||
|
||||
out = talker.make_omni_output(
|
||||
torch.zeros((2, 8)),
|
||||
model_intermediate_buffer=[valid, invalid],
|
||||
)
|
||||
|
||||
assert out.multimodal_outputs["meta"]["codec_frame_valid"].tolist() == [1, 0]
|
||||
|
||||
|
||||
def test_make_omni_output_publishes_ref_once_for_kv_resumed_first_decode() -> None:
|
||||
talker = _make_talker()
|
||||
talker.vllm_config = SimpleNamespace(
|
||||
model_config=SimpleNamespace(async_chunk=True),
|
||||
)
|
||||
ref_code = torch.ones((5, _NUM_CODE_GROUPS), dtype=torch.long)
|
||||
info = _info(1, ref_code)
|
||||
info["_omni_num_computed_tokens"] = 9
|
||||
info["_omni_prompt_len"] = 5
|
||||
|
||||
first = talker.make_omni_output(
|
||||
torch.zeros((1, 8)),
|
||||
model_intermediate_buffer=[info],
|
||||
)
|
||||
second = talker.make_omni_output(
|
||||
torch.zeros((1, 8)),
|
||||
model_intermediate_buffer=[info],
|
||||
)
|
||||
|
||||
assert first.multimodal_outputs["codes"]["ref"][0] is ref_code
|
||||
assert "ref" not in second.multimodal_outputs["codes"]
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Unit tests for the Qwen3-TTS leading-silence ban (#4966, #5048).
|
||||
|
||||
``compute_logits`` suppresses the checkpoint-derived silence codec vocabulary
|
||||
@@ -59,6 +59,7 @@ def _make_talker(*, ban_frames: int, logits: torch.Tensor, modes=None):
|
||||
object.__setattr__(talker, "_silence_mask", silence_mask)
|
||||
object.__setattr__(talker, "_codec_disallowed_mask", torch.zeros((_VOCAB,), dtype=torch.bool))
|
||||
object.__setattr__(talker, "_batch_req_ids", req_ids)
|
||||
object.__setattr__(talker, "_mrv2_silence_ban_mask", None)
|
||||
object.__setattr__(
|
||||
talker,
|
||||
"_req_x_vector_only",
|
||||
@@ -78,7 +79,26 @@ def _banned(row: torch.Tensor) -> set[int]:
|
||||
return {int(i) for i in torch.nonzero(torch.isinf(row) & (row < 0)).flatten()}
|
||||
|
||||
|
||||
# -------------------- the step gate --------------------
|
||||
def test_mrv2_silence_ban_tracks_batch_order_scope_and_decode_window() -> None:
|
||||
talker = _make_talker(ban_frames=3, logits=torch.zeros((3, _VOCAB)), modes=[True, False, True])
|
||||
with talker.mrv2_sampling_context(
|
||||
req_ids=["req2", "req1", "req0"],
|
||||
num_output_tokens=torch.tensor([3, 0, 1]),
|
||||
):
|
||||
logits = talker.compute_logits(torch.zeros((3, 4)))
|
||||
|
||||
assert _banned(logits[0]) == set()
|
||||
assert _banned(logits[1]) == set()
|
||||
assert _banned(logits[2]) == set(_SILENCE_IDS)
|
||||
|
||||
# Prompt logprobs are computed after sampling and must remain unmasked.
|
||||
assert not torch.isneginf(talker.compute_logits(torch.zeros((3, 4)))).any()
|
||||
|
||||
with talker.mrv2_sampling_context(
|
||||
req_ids=["req2", "req1", "req0"],
|
||||
num_output_tokens=torch.tensor([4, 1, 3]),
|
||||
):
|
||||
assert not torch.isneginf(talker.compute_logits(torch.zeros((3, 4)))).any()
|
||||
|
||||
|
||||
def test_ban_disabled_leaves_logits_unchanged() -> None:
|
||||
|
||||
@@ -7,6 +7,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.model_executor.stage_input_processors import (
|
||||
qwen3_tts as qwen3_tts_processors,
|
||||
)
|
||||
from vllm_omni.model_executor.stage_input_processors.chunk_size_utils import (
|
||||
AdaptiveChunkController,
|
||||
compute_adaptive_emit,
|
||||
@@ -32,7 +35,52 @@ _FRAME = [1, 2, 3, 4]
|
||||
_Q = len(_FRAME)
|
||||
|
||||
|
||||
def _req(rid, *, finished, initial_codec_chunk_frames=None, non_streaming_mode=None, full_utterance_decode=None):
|
||||
@pytest.mark.parametrize("frames", [1, 26])
|
||||
def test_terminal_without_new_frames_does_not_replay_last_chunk(frames):
|
||||
tm = _tm(initial_chunk_frames=1)
|
||||
emitted = 0
|
||||
for count in range(1, frames + 1):
|
||||
payload = _call(tm, "r", n_frames=count)
|
||||
if payload is not None:
|
||||
emitted += payload.codes.audio.numel() // _Q
|
||||
tm.put_req_chunk["r"] += 1
|
||||
terminal = _call(tm, "r", n_frames=frames, finished=True)
|
||||
assert terminal is not None and terminal.meta.finished.item()
|
||||
assert terminal.codes.audio.numel() == 0
|
||||
assert emitted == frames
|
||||
|
||||
|
||||
def test_repeated_nonterminal_callback_does_not_republish_boundary():
|
||||
tm = _tm(initial_chunk_frames=1)
|
||||
first = _call(tm, "r", n_frames=1)
|
||||
assert first is not None
|
||||
tm.put_req_chunk["r"] += 1
|
||||
assert _call(tm, "r", n_frames=1) is None
|
||||
next_chunk = _call(tm, "r", n_frames=26)
|
||||
assert next_chunk.codes.audio.numel() // _Q == 25
|
||||
|
||||
|
||||
def test_terminal_flush_contains_only_frames_not_previously_emitted():
|
||||
tm = _tm(initial_chunk_frames=1)
|
||||
_call(tm, "r", n_frames=1)
|
||||
tm.put_req_chunk["r"] += 1
|
||||
_call(tm, "r", n_frames=26)
|
||||
tm.put_req_chunk["r"] += 1
|
||||
final = _call(tm, "r", n_frames=30, finished=True)
|
||||
assert final.codes.audio.numel() // _Q == 4
|
||||
tm.put_req_chunk["r"] += 1
|
||||
assert _call(tm, "r", n_frames=30, finished=True).codes.audio.numel() == 0
|
||||
|
||||
|
||||
def _req(
|
||||
rid,
|
||||
*,
|
||||
finished,
|
||||
initial_codec_chunk_frames=None,
|
||||
non_streaming_mode=None,
|
||||
full_utterance_decode=None,
|
||||
output_token_ids=None,
|
||||
):
|
||||
entries = {}
|
||||
if initial_codec_chunk_frames is not None:
|
||||
entries["initial_codec_chunk_frames"] = SimpleNamespace(list_data=[initial_codec_chunk_frames])
|
||||
@@ -40,11 +88,11 @@ def _req(rid, *, finished, initial_codec_chunk_frames=None, non_streaming_mode=N
|
||||
entries["non_streaming_mode"] = SimpleNamespace(list_data=[non_streaming_mode])
|
||||
if full_utterance_decode is not None:
|
||||
entries["full_utterance_decode"] = SimpleNamespace(list_data=[full_utterance_decode])
|
||||
ai = SimpleNamespace(entries=entries) if entries else None
|
||||
return SimpleNamespace(
|
||||
external_req_id=rid,
|
||||
is_finished=lambda: finished,
|
||||
additional_information=ai,
|
||||
additional_information=SimpleNamespace(entries=entries) if entries else None,
|
||||
output_token_ids=output_token_ids or [],
|
||||
)
|
||||
|
||||
|
||||
@@ -206,6 +254,112 @@ def test_voicedesign_prompt_mode_with_streaming_keeps_windowed_emit():
|
||||
assert len(p.codes.audio) == _Q * 25
|
||||
|
||||
|
||||
def test_async_chunk_skips_stop_token_zero_frame_without_gpu_value_check():
|
||||
tm = _tm()
|
||||
rid = "r-stop"
|
||||
tm.code_prompt_token_ids[rid] = [_FRAME[:]]
|
||||
|
||||
payload = talker2code2wav_async_chunk(
|
||||
transfer_manager=tm,
|
||||
multimodal_output={"codes": {"audio": torch.zeros((1, _Q), dtype=torch.long)}},
|
||||
request=_req(rid, finished=True, initial_codec_chunk_frames=2, output_token_ids=[2150]),
|
||||
is_finished=True,
|
||||
)
|
||||
|
||||
assert payload is not None
|
||||
assert payload.codes.audio.tolist() == _FRAME
|
||||
assert len(tm.code_prompt_token_ids[rid]) == 1
|
||||
|
||||
|
||||
def test_async_chunk_uses_authoritative_frame_validity_without_token_history():
|
||||
tm = _tm()
|
||||
rid = "r-native-validity"
|
||||
|
||||
payload = talker2code2wav_async_chunk(
|
||||
transfer_manager=tm,
|
||||
multimodal_output={
|
||||
"codes": {"audio": torch.tensor([[1, 2, 3, 4]])},
|
||||
"meta": {"codec_frame_valid": False},
|
||||
},
|
||||
request=_req(rid, finished=False, initial_codec_chunk_frames=1, output_token_ids=[]),
|
||||
is_finished=False,
|
||||
)
|
||||
|
||||
assert payload is None
|
||||
assert tm.code_prompt_token_ids[rid] == []
|
||||
|
||||
|
||||
def test_async_chunk_keeps_final_real_frame_when_eos_was_just_sampled():
|
||||
tm = _tm()
|
||||
rid = "r-final-real-frame"
|
||||
|
||||
payload = talker2code2wav_async_chunk(
|
||||
transfer_manager=tm,
|
||||
multimodal_output={
|
||||
"codes": {"audio": torch.tensor([[1, 2, 3, 4]])},
|
||||
"meta": {"codec_frame_valid": True},
|
||||
},
|
||||
request=_req(rid, finished=True, initial_codec_chunk_frames=1, output_token_ids=[4198]),
|
||||
is_finished=True,
|
||||
)
|
||||
|
||||
assert payload is not None
|
||||
assert payload.codes.audio.tolist() == [1, 2, 3, 4]
|
||||
|
||||
|
||||
def test_async_chunk_batch_matches_scalar_payloads_and_state():
|
||||
batch_builder = getattr(qwen3_tts_processors, "talker2code2wav_async_chunk_batch", None)
|
||||
assert callable(batch_builder), "Qwen3-TTS must provide the native MRv2 batch payload builder"
|
||||
|
||||
scalar_tm = _tm(chunk_frames=4, left_context=3, initial_chunk_frames=1)
|
||||
batch_tm = _tm(chunk_frames=4, left_context=3, initial_chunk_frames=1)
|
||||
requests = [
|
||||
_req("r-batch-0", finished=False, output_token_ids=[7]),
|
||||
_req("r-batch-1", finished=False, output_token_ids=[8]),
|
||||
]
|
||||
ref_code = torch.tensor([[9, 9, 9, 9], [8, 8, 8, 8]], dtype=torch.long)
|
||||
# Request 2 has a multi-token span: the last validity flag wins the chunk.
|
||||
outputs = [
|
||||
{"codes": {"audio": torch.tensor([[1, 2, 3, 4]]), "ref": ref_code}},
|
||||
{
|
||||
"codes": {"audio": torch.tensor([[9, 9, 9, 9], [5, 6, 7, 8]])},
|
||||
"meta": {"codec_frame_valid": torch.tensor([False, True])},
|
||||
},
|
||||
]
|
||||
|
||||
scalar_payloads = [
|
||||
talker2code2wav_async_chunk(
|
||||
transfer_manager=scalar_tm,
|
||||
multimodal_output=output,
|
||||
request=request,
|
||||
is_finished=False,
|
||||
)
|
||||
for request, output in zip(requests, outputs)
|
||||
]
|
||||
batch_payloads = batch_builder(
|
||||
transfer_manager=batch_tm,
|
||||
pooling_outputs=outputs,
|
||||
requests=requests,
|
||||
is_finished=[False, False],
|
||||
)
|
||||
|
||||
assert len(batch_payloads) == len(scalar_payloads)
|
||||
for scalar, batched in zip(scalar_payloads, batch_payloads):
|
||||
assert scalar is not None and batched is not None
|
||||
torch.testing.assert_close(batched.codes.audio, scalar.codes.audio)
|
||||
assert batched.meta.left_context_size == scalar.meta.left_context_size
|
||||
assert batched.meta.finished.item() == scalar.meta.finished.item()
|
||||
assert batched.speaker == scalar.speaker
|
||||
assert batched.language == scalar.language
|
||||
for request in requests:
|
||||
rid = request.external_req_id
|
||||
torch.testing.assert_close(
|
||||
torch.stack(batch_tm.code_prompt_token_ids[rid]),
|
||||
torch.stack(scalar_tm.code_prompt_token_ids[rid]),
|
||||
)
|
||||
torch.testing.assert_close(batch_tm.request_payload["r-batch-0"], scalar_tm.request_payload["r-batch-0"])
|
||||
|
||||
|
||||
_CASES = [
|
||||
# ── IC boundary rule ──────────────────────────────────────────────
|
||||
# initial_codec_chunk_frames only controls the first emitted chunk.
|
||||
@@ -703,35 +857,27 @@ class TestRampHelpers:
|
||||
def test_parse_ramp_mixed_list_returns_none(self):
|
||||
assert parse_chunk_ramp({"codec_chunk_ramp": [4, "x"]}) is None
|
||||
|
||||
def test_parse_ramp_warns_on_tail_mismatch(self, caplog):
|
||||
import logging
|
||||
def test_parse_ramp_warns_on_tail_mismatch(self, monkeypatch):
|
||||
warnings = []
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.stage_input_processors.chunk_size_utils.logger.warning",
|
||||
lambda message, *args: warnings.append(message % args),
|
||||
)
|
||||
|
||||
target_logger = logging.getLogger("vllm_omni.model_executor.stage_input_processors.chunk_size_utils")
|
||||
target_logger.addHandler(caplog.handler)
|
||||
prev_level = target_logger.level
|
||||
target_logger.setLevel(logging.WARNING)
|
||||
try:
|
||||
result = parse_chunk_ramp({"codec_chunk_ramp": [4, 4, 8]}, steady=25)
|
||||
finally:
|
||||
target_logger.removeHandler(caplog.handler)
|
||||
target_logger.setLevel(prev_level)
|
||||
result = parse_chunk_ramp({"codec_chunk_ramp": [4, 4, 8]}, steady=25)
|
||||
assert result == [4, 4, 8]
|
||||
assert "reintroduces" in caplog.text
|
||||
assert any("reintroduces" in message for message in warnings)
|
||||
|
||||
def test_parse_ramp_no_warn_on_tail_match(self, caplog):
|
||||
import logging
|
||||
def test_parse_ramp_no_warn_on_tail_match(self, monkeypatch):
|
||||
warnings = []
|
||||
monkeypatch.setattr(
|
||||
"vllm_omni.model_executor.stage_input_processors.chunk_size_utils.logger.warning",
|
||||
lambda message, *args: warnings.append(message % args),
|
||||
)
|
||||
|
||||
target_logger = logging.getLogger("vllm_omni.model_executor.stage_input_processors.chunk_size_utils")
|
||||
target_logger.addHandler(caplog.handler)
|
||||
prev_level = target_logger.level
|
||||
target_logger.setLevel(logging.WARNING)
|
||||
try:
|
||||
result = parse_chunk_ramp({"codec_chunk_ramp": [4, 4, 8, 16, 25]}, steady=25)
|
||||
finally:
|
||||
target_logger.removeHandler(caplog.handler)
|
||||
target_logger.setLevel(prev_level)
|
||||
result = parse_chunk_ramp({"codec_chunk_ramp": [4, 4, 8, 16, 25]}, steady=25)
|
||||
assert result == [4, 4, 8, 16, 25]
|
||||
assert "reintroduces" not in caplog.text
|
||||
assert warnings == []
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"index,ramp,steady,expected",
|
||||
@@ -1028,6 +1174,7 @@ class TestChunkRampEmission:
|
||||
tm.put_req_chunk[rid] = 2
|
||||
|
||||
tm.code_prompt_token_ids[rid] = []
|
||||
tm._qwen3_tts_emitted_frames.pop(rid, None)
|
||||
tm.ramp_chunk_count.pop(rid, None)
|
||||
|
||||
p_seg2_0 = self._emit(tm, rid, 4)
|
||||
@@ -1051,6 +1198,7 @@ class TestChunkRampEmission:
|
||||
tm.put_req_chunk[rid] = 1
|
||||
|
||||
tm.code_prompt_token_ids[rid] = []
|
||||
tm._qwen3_tts_emitted_frames.pop(rid, None)
|
||||
tm.ramp_chunk_count.pop(rid, None)
|
||||
|
||||
p_seg2_0 = self._emit(tm, rid, 4)
|
||||
@@ -1429,6 +1577,7 @@ class TestAdaptiveEmission:
|
||||
tm.put_req_chunk[rid] = 1
|
||||
|
||||
tm.code_prompt_token_ids[rid] = []
|
||||
tm._qwen3_tts_emitted_frames.pop(rid, None)
|
||||
tm.ramp_chunk_count.pop(rid, None)
|
||||
tm._adaptive_states.pop(rid, None)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Guard against out-of-vocabulary stop ids in min-tokens masking (#4962).
|
||||
|
||||
vLLM's input processor folds the stage tokenizer's EOS id into
|
||||
@@ -19,7 +19,7 @@ from vllm.v1.sample.logits_processor import (
|
||||
MinTokensLogitsProcessor,
|
||||
)
|
||||
|
||||
from vllm_omni.worker.sampling_utils import sanitize_min_tokens_stop_ids
|
||||
from vllm_omni.worker.sampling_utils import sanitize_min_tokens_stop_ids, sanitize_sampling_params_min_tokens_stop_ids
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
@@ -28,6 +28,12 @@ CODEC_EOS = 2150
|
||||
TEXT_EOS = 151645
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _disable_vllm_pin_memory_for_cpu(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Keep the module-level H2D helper in CPU-only mode."""
|
||||
monkeypatch.setattr("vllm.utils.torch_utils.PIN_MEMORY", False)
|
||||
|
||||
|
||||
def _make_min_tokens_proc(stop_token_ids: list[int], eos_token_id: int | None) -> MinTokensLogitsProcessor:
|
||||
"""Build a MinTokensLogitsProcessor with one active request, mirroring
|
||||
the production path (engine folds the tokenizer EOS via
|
||||
@@ -113,3 +119,14 @@ def test_guard_handles_multiple_requests():
|
||||
assert out[0, CODEC_EOS] == -float("inf")
|
||||
assert out[1, 7] == -float("inf")
|
||||
assert int((out == -float("inf")).sum()) == 2
|
||||
|
||||
|
||||
def test_sampling_params_guard_filters_only_unreachable_min_tokens_ids():
|
||||
params = SamplingParams(min_tokens=2, stop_token_ids=[CODEC_EOS])
|
||||
params.update_from_generation_config({}, TEXT_EOS)
|
||||
|
||||
sanitize_sampling_params_min_tokens_stop_ids(params, TALKER_VOCAB)
|
||||
|
||||
assert params.all_stop_token_ids == {CODEC_EOS}
|
||||
assert params.stop_token_ids == [CODEC_EOS]
|
||||
assert params.eos_token_id == TEXT_EOS
|
||||
@@ -1724,3 +1724,16 @@ class TestSendRetry(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"fallback,external,expected", [("r", None, "mapped"), (None, "ext", "ext"), (None, None, None)]
|
||||
)
|
||||
def test_resolve_request_id_requires_internal_or_external_id(fallback, external, expected):
|
||||
host = SimpleNamespace(_request_ids_mapping={"r": "mapped"})
|
||||
request = SimpleNamespace(external_req_id=external)
|
||||
if expected is None:
|
||||
with pytest.raises(ValueError, match="request ID"):
|
||||
OmniConnectorModelRunnerMixin._resolve_external_req_id(host, request, fallback)
|
||||
else:
|
||||
assert OmniConnectorModelRunnerMixin._resolve_external_req_id(host, request, fallback) == expected
|
||||
@@ -770,8 +770,10 @@ def test_accumulate_full_payload_output_keeps_all_zero_qwen3_omni_prefill_placeh
|
||||
def test_full_payload_output_accumulation_hook_matrix():
|
||||
assert _make_full_payload_accumulation_runner(model_stage="thinker")._should_accumulate_full_payload_output()
|
||||
assert _make_full_payload_accumulation_runner(model_stage="talker")._should_accumulate_full_payload_output()
|
||||
assert not _make_full_payload_accumulation_runner(
|
||||
model_stage="code2wav", final_output=True
|
||||
# A stage may publish a user-visible output and still feed another stage
|
||||
# (Qwen3-Omni thinker publishes text while sending audio state to talker).
|
||||
assert _make_full_payload_accumulation_runner(
|
||||
model_stage="thinker", final_output=True
|
||||
)._should_accumulate_full_payload_output()
|
||||
assert not _make_full_payload_accumulation_runner(
|
||||
model_stage="token2audio",
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from vllm.compilation.cuda_graph import CUDAGraphMode
|
||||
|
||||
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dp_size", [1, 2])
|
||||
def test_dispatch_eager_and_manager_paths(monkeypatch, dp_size):
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.cudagraph_manager = None
|
||||
runner.dp_size = dp_size
|
||||
runner.dp_rank = 1
|
||||
|
||||
import vllm.v1.worker.gpu.dp_utils as dp_utils
|
||||
|
||||
expected_tokens = object()
|
||||
sync_calls = []
|
||||
|
||||
def sync_padding(*args, **kwargs):
|
||||
sync_calls.append((args, kwargs))
|
||||
return args[1], expected_tokens
|
||||
|
||||
monkeypatch.setattr(
|
||||
dp_utils,
|
||||
"sync_cudagraph_and_dp_padding",
|
||||
sync_padding,
|
||||
)
|
||||
|
||||
batch_desc, num_tokens_across_dp = runner._dispatch_batch_descriptor(
|
||||
num_reqs=1, num_toks=8, uniform_tok_count=8, num_active_loras=0, use_eager=True, max_query_len=8
|
||||
)
|
||||
assert batch_desc.cg_mode == CUDAGraphMode.NONE
|
||||
if dp_size == 1:
|
||||
assert num_tokens_across_dp is None
|
||||
assert sync_calls == []
|
||||
else:
|
||||
assert num_tokens_across_dp is expected_tokens
|
||||
|
||||
# Non-eager dispatch goes through the cudagraph manager.
|
||||
expected = SimpleNamespace(cg_mode=CUDAGraphMode.PIECEWISE, num_tokens=8, num_reqs=1)
|
||||
dispatch_calls = []
|
||||
|
||||
def dispatch(*args, **kwargs):
|
||||
dispatch_calls.append((args, kwargs))
|
||||
return expected
|
||||
|
||||
runner.cudagraph_manager = SimpleNamespace(dispatch=dispatch)
|
||||
runner.dp_size = 1
|
||||
batch_desc, _ = runner._dispatch_batch_descriptor(
|
||||
num_reqs=1, num_toks=8, uniform_tok_count=8, num_active_loras=0, use_eager=False, max_query_len=8
|
||||
)
|
||||
assert batch_desc is expected
|
||||
assert dispatch_calls == [((1, 8, 8), {"num_active_loras": 0, "max_query_len": 8})]
|
||||
@@ -0,0 +1,34 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm_omni.worker import sampling_utils
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def test_fixed_seed_contract_separates_stage_sampler_from_talker_mtp_rng() -> None:
|
||||
assert hasattr(sampling_utils, "apply_fixed_seed_to_sampling_params")
|
||||
assert hasattr(sampling_utils, "get_tts_local_seed")
|
||||
|
||||
stage_only = SimpleNamespace(seed=None, extra_args=None)
|
||||
sampling_utils.apply_fixed_seed_to_sampling_params(
|
||||
stage_only,
|
||||
17,
|
||||
seed_talker_mtp=False,
|
||||
)
|
||||
assert stage_only.seed == 17
|
||||
assert sampling_utils.get_tts_local_seed(stage_only) is None
|
||||
|
||||
talker = SimpleNamespace(seed=None, extra_args={"preserved": True})
|
||||
sampling_utils.apply_fixed_seed_to_sampling_params(
|
||||
talker,
|
||||
23,
|
||||
seed_talker_mtp=True,
|
||||
)
|
||||
assert talker.seed == 23
|
||||
assert talker.extra_args == {"preserved": True, "tts_local_seed": 23}
|
||||
assert sampling_utils.get_tts_local_seed(talker) == 23
|
||||
@@ -1,5 +1,5 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Characterization tests for ``vllm_omni.worker.base.OmniGPUWorkerBase``.
|
||||
|
||||
Pins the CURRENT behaviour of ``determine_available_memory`` (device-level
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,96 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for OmniIntermediateBuffer lifecycle.
|
||||
|
||||
Retained contracts: wire decode with malformed-payload rejection, slot
|
||||
lifecycle with index migration on reuse, gather in batch order, update merge
|
||||
semantics (cpu/gpu-resident keys), single owned snapshot for
|
||||
update_gpu_tensor_rows, and decode-span merge until ack.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.engine import (
|
||||
AdditionalInformationEntry,
|
||||
AdditionalInformationPayload,
|
||||
PromptEmbedsPayload,
|
||||
)
|
||||
from vllm_omni.worker_v2.model_states.intermediate_buffer import (
|
||||
OmniIntermediateBuffer,
|
||||
_resolve_additional_information,
|
||||
_resolve_prompt_embeds,
|
||||
)
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _make_new_req_data(req_id="r1", **kwargs):
|
||||
kwargs.setdefault("mm_features", [])
|
||||
return SimpleNamespace(req_id=req_id, **kwargs)
|
||||
|
||||
|
||||
def test_wire_decode_passthrough_and_malformed_rejection():
|
||||
tensor = torch.randn(3, 4)
|
||||
assert _resolve_prompt_embeds(tensor) is not None
|
||||
assert _resolve_prompt_embeds(None) is None
|
||||
with pytest.raises(ValueError, match="Failed to decode prompt_embeds payload"):
|
||||
_resolve_prompt_embeds(PromptEmbedsPayload(data=b"\x00", shape=[2, 2], dtype="float32"))
|
||||
|
||||
assert _resolve_additional_information({"key": "val"}) == {"key": "val"}
|
||||
assert _resolve_additional_information(None) == {}
|
||||
payload = AdditionalInformationPayload(
|
||||
entries={
|
||||
"embed.decode": AdditionalInformationEntry(tensor_data=b"\x00", tensor_shape=[2], tensor_dtype="float32")
|
||||
}
|
||||
)
|
||||
with pytest.raises(ValueError, match="Failed to decode additional_information payload"):
|
||||
_resolve_additional_information(payload)
|
||||
|
||||
|
||||
def test_slot_lifecycle_fields_reuse_and_remove_idempotent():
|
||||
buf = OmniIntermediateBuffer(max_num_reqs=4)
|
||||
embeds = torch.randn(2, 8)
|
||||
features = [torch.randn(3, 4)]
|
||||
params = SimpleNamespace(extra_args={"tts_local_seed": 1234})
|
||||
buf.add_request(0, _make_new_req_data("r0", prompt_embeds=embeds, mm_features=features, sampling_params=params))
|
||||
assert torch.equal(buf.buffers[0]["prompt_embeds_cpu"], embeds)
|
||||
assert buf.buffers[0]["mm_features"] is features
|
||||
assert buf.buffers[0]["sampling_params"] is params
|
||||
|
||||
buf.add_request(2, _make_new_req_data("r2"))
|
||||
buf.add_request(3, _make_new_req_data("r3"))
|
||||
batch = SimpleNamespace(idx_mapping_np=[2, 0, 3])
|
||||
assert [g["req_id"] for g in buf.gather(batch)] == ["r2", "r0", "r3"]
|
||||
|
||||
# Slot reuse: req_id mapping migrates; duplicate removal is a no-op.
|
||||
buf.add_request(0, _make_new_req_data("new"))
|
||||
assert buf.req_id_to_index["new"] == 0
|
||||
buf.remove_request(0)
|
||||
buf.remove_request(0)
|
||||
assert "new" not in buf.req_id_to_index
|
||||
assert buf.buffers[0] == {}
|
||||
|
||||
|
||||
def test_update_merge_semantics(monkeypatch):
|
||||
buf = OmniIntermediateBuffer(max_num_reqs=1)
|
||||
buf.add_request(0, _make_new_req_data("r0"))
|
||||
|
||||
buf.update(0, {"hidden": torch.randn(4)})
|
||||
assert buf.buffers[0]["hidden"].device == torch.device("cpu") # default migrates to cpu
|
||||
buf.update(0, {})
|
||||
buf.update(0, {"a": torch.tensor([1.0])})
|
||||
buf.update(0, {"b": torch.tensor([2.0])})
|
||||
assert "a" in buf.buffers[0] and "b" in buf.buffers[0]
|
||||
|
||||
# GPU-resident keys keep values (including list items) off the cpu path.
|
||||
tensor = torch.randn(2)
|
||||
monkeypatch.setattr(torch.Tensor, "cpu", lambda *_a, **_k: pytest.fail("GPU-resident value must not move to CPU"))
|
||||
buf.update(0, {"items": [tensor], "kv": torch.randn(4)}, gpu_resident_keys={"items", "kv"})
|
||||
stored = buf.buffers[0]["items"][0]
|
||||
assert stored is not tensor
|
||||
assert torch.equal(stored, tensor)
|
||||
assert "kv" in buf.buffers[0]
|
||||
@@ -0,0 +1,28 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""CUDA-lane checks for GPU-resident intermediate buffer values."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.worker_v2.model_states.intermediate_buffer import OmniIntermediateBuffer
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cuda]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key,dtype", [(("embed", "prefill"), torch.float32), (("codes", "ref"), torch.long)])
|
||||
def test_gpu_resident_values_stay_on_device_after_update(key, dtype):
|
||||
# Declared gpu-resident keys must keep tensors on device (CLA snapshot real).
|
||||
buffer = OmniIntermediateBuffer(1)
|
||||
value = torch.ones(2, 3, device="cuda", dtype=dtype)
|
||||
buffer.add_request(0, SimpleNamespace(req_id="r1", mm_features=[]))
|
||||
|
||||
buffer.update(0, {key[0]: {key[1]: value}}, {key})
|
||||
|
||||
stored = buffer.buffers[0][key[0]][key[1]]
|
||||
assert stored.device.type == "cuda"
|
||||
assert stored.dtype == dtype
|
||||
assert torch.equal(stored.cpu(), value.cpu())
|
||||
@@ -0,0 +1,253 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""Unit tests for OmniARModelRunner v2: async output staging, snapshot ownership, payload slicing."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.v1.outputs import RoutedExpertsTensors
|
||||
from vllm.v1.worker.gpu.sample.output import SamplerOutput, SamplingMaskTensors
|
||||
|
||||
import vllm_omni.worker_v2.omni_ar_model_runner as omni_ar_model_runner
|
||||
from vllm_omni.worker_v2.omni_ar_model_runner import OmniARModelRunner, OmniAsyncOutput
|
||||
from vllm_omni.worker_v2.output_snapshot import pack_output_snapshot
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _FakeStream:
|
||||
def wait_stream(self, _stream) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class _FakeEvent:
|
||||
def record(self, _stream) -> None:
|
||||
pass
|
||||
|
||||
def synchronize(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _async_output(req_ids=("req-0",), **overrides) -> OmniAsyncOutput:
|
||||
rid2idx = {rid: i for i, rid in enumerate(req_ids)}
|
||||
mro = omni_ar_model_runner.OmniModelRunnerOutput(list(req_ids), rid2idx, None, prompt_logprobs_dict={})
|
||||
sampler_output = SamplerOutput(torch.tensor([[123]]), None, None, None)
|
||||
kwargs = dict(model_runner_output=mro, sampler_output=sampler_output)
|
||||
kwargs.update(num_sampled_tokens=torch.tensor([1] * len(req_ids)), copy_event=_FakeEvent())
|
||||
kwargs.update(main_stream=_FakeStream(), copy_stream=_FakeStream())
|
||||
return OmniAsyncOutput(**(kwargs | overrides))
|
||||
|
||||
|
||||
def test_async_output_blocking_event_and_routing_masks(monkeypatch) -> None:
|
||||
event_kwargs = []
|
||||
monkeypatch.setattr(torch.cuda, "set_stream", lambda _stream: None)
|
||||
|
||||
def make_event(**kwargs):
|
||||
event_kwargs.append(kwargs)
|
||||
return _FakeEvent()
|
||||
|
||||
monkeypatch.setattr(torch.cuda, "Event", make_event)
|
||||
masks = SamplingMaskTensors(torch.tensor([[5], [0]], dtype=torch.uint8), torch.tensor([2, 0]), 4)
|
||||
sampler_output = SamplerOutput(torch.tensor([[2], [0]]), None, None, torch.tensor([1, 0]), None, masks)
|
||||
routed = RoutedExpertsTensors(torch.tensor([[[2, 3]], [[4, 5]]]), torch.tensor([7, 9]))
|
||||
|
||||
output = _async_output(
|
||||
req_ids=["decode", "prefill"],
|
||||
sampler_output=sampler_output,
|
||||
num_sampled_tokens=torch.tensor([1, 0]),
|
||||
copy_event=None, # None → constructor builds the default blocking event
|
||||
routed_experts=routed,
|
||||
).get_output()
|
||||
assert event_kwargs == [{"blocking": True}] # blocking event by default
|
||||
assert output.sampled_token_ids == [[2], []] and output.sampling_masks.cu_num_generated_tokens == [0, 1, 1]
|
||||
np.testing.assert_array_equal(output.routed_experts.routing_data, [[[2, 3]], [[4, 5]]])
|
||||
np.testing.assert_array_equal(output.routed_experts.slot_mapping, [7, 9])
|
||||
np.testing.assert_array_equal(output.sampling_masks.token_ids, [0, 2])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("needs_history", [False, True])
|
||||
def test_last_pp_rank_orchestration_and_kv_resolver(monkeypatch, needs_history) -> None:
|
||||
runner = OmniARModelRunner.__new__(OmniARModelRunner)
|
||||
input_batch = SimpleNamespace(req_ids=["req"], num_reqs=1, seq_lens=torch.tensor([3]))
|
||||
input_batch.idx_mapping, input_batch.query_start_loc = torch.tensor([0]), torch.tensor([0, 1])
|
||||
state = SimpleNamespace(input_batch=input_batch, hidden_states=torch.zeros(1, 2))
|
||||
state.finished_req_ids, state.ec_connector_output, state.routed_experts = {"finished"}, None, None
|
||||
runner.execute_model_state = state
|
||||
runner._kv_extracted_req_ids = runner._last_aux_output = runner._last_multimodal_outputs = None
|
||||
runner.is_last_pp_rank, runner.pp_handler, runner.check_ep_fault = True, None, False
|
||||
runner.model_config = SimpleNamespace(async_chunk=False)
|
||||
runner.vllm_config = SimpleNamespace(model_config=SimpleNamespace(engine_output_type="text"))
|
||||
runner.model_state = SimpleNamespace(postprocess_model_output=MagicMock(return_value=(torch.zeros(1, 2), None)))
|
||||
runner.model_state.intermediate_buffer = SimpleNamespace(buffers={0: {"global_request_id": "global-req"}})
|
||||
runner.req_states = SimpleNamespace(req_id_to_index={"req": 0})
|
||||
runner.req_states.all_token_ids = SimpleNamespace(gpu=torch.tensor([[1]]))
|
||||
runner.req_states.num_computed_tokens = SimpleNamespace(gpu=torch.tensor([0]))
|
||||
runner.req_states.prompt_len = SimpleNamespace(np=np.array([1]), gpu=torch.tensor([1]))
|
||||
runner.main_stream = runner.output_copy_stream = MagicMock()
|
||||
runner.eplb = runner._finalize_native_data_plane_output = runner._reserve_native_data_plane_outputs = MagicMock()
|
||||
sampler_out = (SimpleNamespace(sampled_token_ids=torch.tensor([[2]])), MagicMock(), MagicMock())
|
||||
sampling_active = False
|
||||
|
||||
@contextmanager
|
||||
def sampling_context(*, req_ids, num_output_tokens):
|
||||
nonlocal sampling_active
|
||||
assert needs_history and req_ids == ["req"]
|
||||
sampling_active = True
|
||||
yield
|
||||
sampling_active = False
|
||||
|
||||
runner.model = SimpleNamespace(compute_logits=None, logitsprocs_need_output_token_ids=needs_history)
|
||||
runner.model.mrv2_sampling_context = sampling_context
|
||||
runner.sample = MagicMock(return_value=sampler_out)
|
||||
runner.sample.side_effect = lambda *_: sampler_out if sampling_active is needs_history else pytest.fail()
|
||||
logprobs_mock = MagicMock(side_effect=lambda *_: pytest.fail("inside ctx") if sampling_active else {})
|
||||
runner.prompt_logprobs_worker = SimpleNamespace(compute_prompt_logprobs=logprobs_mock)
|
||||
runner.postprocess_sampled, connector_output = MagicMock(), object()
|
||||
|
||||
def post_forward(finished_req_ids):
|
||||
runner.postprocess_sampled.assert_called_once() # postprocess precedes kv_connector.post_forward
|
||||
assert finished_req_ids == {"finished"}
|
||||
return connector_output
|
||||
|
||||
runner.kv_connector = SimpleNamespace(post_forward=MagicMock(side_effect=post_forward))
|
||||
mock_out = SimpleNamespace(copy_event=None)
|
||||
monkeypatch.setattr(omni_ar_model_runner, "OmniAsyncOutput", MagicMock(return_value=mock_out))
|
||||
|
||||
assert runner.sample_tokens(None) is mock_out
|
||||
built = omni_ar_model_runner.OmniAsyncOutput.call_args.kwargs["model_runner_output"]
|
||||
assert built.kv_connector_output is connector_output
|
||||
assert runner._resolve_global_request_id("req") == "global-req" # from the intermediate buffer
|
||||
assert runner._resolve_global_request_id("unknown") == "unknown" # fallback to the local id
|
||||
|
||||
|
||||
def test_async_mm_snapshot_owns_output_until_copy_finishes() -> None:
|
||||
runner = OmniARModelRunner.__new__(OmniARModelRunner)
|
||||
runner.model_config = SimpleNamespace(async_chunk=True)
|
||||
runner._async_mm_snapshot_slots, runner._async_mm_snapshot_events = [{}], [None]
|
||||
runner._async_mm_snapshot_pending, runner._async_mm_snapshot_cursor = [False], 0
|
||||
waited: list[object] = []
|
||||
runner.main_stream = SimpleNamespace(wait_event=waited.append)
|
||||
source = torch.tensor([[7, 8]], dtype=torch.long)
|
||||
|
||||
snapshot = runner._retain_multimodal_outputs({"codes": {"audio": source}})
|
||||
source.fill_(99)
|
||||
|
||||
# Snapshot owns the data (graph replay cannot overwrite it)...
|
||||
snap = snapshot["codes"]["audio"]
|
||||
assert snap.tolist() == [[7, 8]] and snap.data_ptr() != source.data_ptr()
|
||||
assert runner._last_multimodal_snapshot_slot == 0
|
||||
# ...and slot reuse waits for the previous D2H copy event.
|
||||
runner._release_multimodal_snapshot(0, copy_event := object())
|
||||
runner._retain_multimodal_outputs({"codes": {"audio": torch.zeros(1, 2)}})
|
||||
assert waited == [copy_event]
|
||||
|
||||
|
||||
def test_snapshot_slots_bounded_by_shape_and_packed_grouping_isolation(monkeypatch) -> None:
|
||||
slot: dict[tuple[Any, ...], torch.Tensor] = {}
|
||||
omni_ar_model_runner._copy_mm_to_snapshot_slot(torch.ones(1, 2), slot)
|
||||
omni_ar_model_runner._copy_mm_to_snapshot_slot(torch.ones(4, 2), slot)
|
||||
assert len(slot) == 2 # separate shapes do not share a buffer
|
||||
monkeypatch.setattr(omni_ar_model_runner, "_ASYNC_MM_SNAPSHOT_MAX_BUCKETS_PER_SLOT", 1)
|
||||
bounded: dict[tuple[Any, ...], torch.Tensor] = {}
|
||||
kept = omni_ar_model_runner._copy_mm_to_snapshot_slot(torch.ones(2, 2), bounded)
|
||||
overflow = omni_ar_model_runner._copy_mm_to_snapshot_slot(torch.ones(5, 2), bounded)
|
||||
assert len(bounded) == 1 and overflow.data_ptr() != kept.data_ptr() # overflow clones without evicting
|
||||
|
||||
source = torch.arange(12, dtype=torch.int64).view(3, 4).t()
|
||||
payload = {"noncontiguous": source, "nested": [torch.tensor(7), (torch.tensor([1.5]),)], "meta": "ok"}
|
||||
pack_slot: dict[tuple[Any, ...], torch.Tensor] = {}
|
||||
snapshot = pack_output_snapshot(payload, pack_slot, max_buckets=4)
|
||||
source.fill_(99) # ownership: snapshot keeps pre-mutation values
|
||||
copies = []
|
||||
|
||||
def copy(tensor):
|
||||
copies.append(tensor.numel())
|
||||
return tensor.clone()
|
||||
|
||||
host = snapshot.copy_to_cpu(copy)
|
||||
assert len(copies) == 2 # grouped by dtype (int64, float32), not tensor count
|
||||
assert host["noncontiguous"].tolist() == torch.arange(12).view(3, 4).t().tolist()
|
||||
assert host["nested"][0].item() == 7 and isinstance(host["nested"][1], tuple) and host["meta"] == "ok"
|
||||
pack_output_snapshot(payload, pack_slot, max_buckets=4)
|
||||
assert host["noncontiguous"][0, 0].item() == 0 # repacking must not corrupt published host data
|
||||
|
||||
|
||||
@pytest.mark.parametrize("need_pooler,async_chunk", [(False, False), (False, True), (True, False), (True, True)])
|
||||
def test_guard_graph_replay_for_pooler_copy(need_pooler, async_chunk) -> None:
|
||||
main_stream = MagicMock()
|
||||
omni_ar_model_runner._guard_graph_replay_for_pooler_copy(
|
||||
main_stream, object(), need_pooler=need_pooler, async_chunk=async_chunk
|
||||
)
|
||||
# Non-async pooler copies must gate the next graph replay on the copy event.
|
||||
assert main_stream.wait_event.call_count == (1 if need_pooler and not async_chunk else 0)
|
||||
|
||||
|
||||
def test_build_async_chunk_outputs_slices_padded_axis_and_splits_channels() -> None:
|
||||
# Graph-padded batch: padded_total_tokens > total_tokens; slice by the real token axis.
|
||||
padded_codes = torch.arange(16, dtype=torch.long).reshape(8, 2)
|
||||
build = OmniARModelRunner._build_async_chunk_outputs_from_mm
|
||||
inter_stage, client = build({"codes": {"audio": padded_codes}}, np.array([0, 1, 2]), np.array([1, 1]), 2, 2, 8)
|
||||
assert client is None
|
||||
assert torch.equal(inter_stage[0]["codes.audio"], padded_codes[0:1])
|
||||
assert torch.equal(inter_stage[1]["codes.audio"], padded_codes[1:2])
|
||||
|
||||
codes, audio = torch.arange(16, dtype=torch.long).reshape(4, 4), torch.randn(4, 8)
|
||||
req_codes = [torch.arange(16 * i, 16 * (i + 1), dtype=torch.long).reshape(1, 16) for i in range(2)]
|
||||
inter_stage, client = build(
|
||||
{"codes": {"audio": codes}, "audio": audio}, np.array([0, 2, 4]), np.array([2, 2]), 2, 4
|
||||
)
|
||||
assert "hidden" not in inter_stage[0] and torch.equal(client[1]["audio"], audio[2:]) # channel split
|
||||
assert torch.equal(inter_stage[1]["codes.audio"], codes[2:]) # inter-stage channel
|
||||
# Per-request code lists pass through unsliced.
|
||||
inter_stage, client = build({"codes": {"audio": req_codes}}, np.array([0, 1, 2]), np.array([1, 1]), 2, 2)
|
||||
assert client is None and torch.equal(inter_stage[0]["codes.audio"], req_codes[0])
|
||||
|
||||
|
||||
def test_async_chunk_output_stages_mm_on_copy_stream_before_get_output(monkeypatch) -> None:
|
||||
monkeypatch.setattr(torch.cuda, "set_stream", lambda _stream: None)
|
||||
calls = []
|
||||
|
||||
def copy_mm(mm_outputs, total_tokens, **ctx):
|
||||
calls.append((total_tokens, ctx))
|
||||
return {"codes": {"audio": mm_outputs["codes"]["audio"].clone()}}
|
||||
|
||||
monkeypatch.setattr(omni_ar_model_runner, "_async_copy_mm", copy_mm)
|
||||
source_codes = torch.tensor([[7, 8]], dtype=torch.long)
|
||||
input_batch = SimpleNamespace(query_start_loc_np=np.array([0, 1]), num_scheduled_tokens=[1], num_reqs=1)
|
||||
output = _async_output(
|
||||
multimodal_outputs={"codes": {"audio": source_codes}},
|
||||
input_batch=input_batch,
|
||||
copy_stream=(copy_stream := _FakeStream()),
|
||||
async_chunk=True,
|
||||
)
|
||||
# Staged once on the copy stream during construction, with one resolved pin-memory context for all D2H helpers.
|
||||
[(total_tokens, ctx)] = calls
|
||||
assert total_tokens == 1 and ctx["copy_stream"] is copy_stream and ctx["pin_memory"] is not None
|
||||
assert output._mm_snapshot["codes"]["audio"].device.type == "cpu"
|
||||
source_codes.fill_(99) # a later graph replay cannot leak into the snapshot
|
||||
assert torch.equal(output.get_output().inter_stage_outputs[0]["codes.audio"], torch.tensor([[7, 8]]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("prefill_first", [False, True])
|
||||
@pytest.mark.parametrize("padded", [False, True])
|
||||
def test_request_reference_codes_preserve_local_axis(prefill_first, padded):
|
||||
lengths = np.array([255, 1] if prefill_first else [1, 255])
|
||||
offsets = np.array([0, lengths[0], 256])
|
||||
size = 512 if padded else 256
|
||||
ref = torch.arange(size * 16).reshape(size, 16)
|
||||
refs = [ref, torch.empty(0)] if prefill_first else [torch.empty(0), ref]
|
||||
codes = torch.arange(size * 16).reshape(size, 16)
|
||||
outputs, _ = OmniARModelRunner._build_async_chunk_outputs_from_mm(
|
||||
{"codes": {"audio": codes, "ref": refs}}, offsets, lengths, 2, 256, size
|
||||
)
|
||||
index = 0 if prefill_first else 1
|
||||
assert torch.equal(outputs[index]["codes.ref"], ref)
|
||||
assert outputs[index]["codes.ref"].data_ptr() != ref.data_ptr()
|
||||
for i in range(2):
|
||||
assert torch.equal(outputs[i]["codes.audio"], codes[offsets[i] : offsets[i + 1]])
|
||||
@@ -0,0 +1,481 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""Lifecycle contracts for OmniRunnerDataPlane/NativeOutputWorker."""
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm_omni.worker_v2.delivery import DeliveryCancelledError, DeliveryState, OmniDeliveryManager
|
||||
from vllm_omni.worker_v2.native_output_worker import NativeOutputWorker
|
||||
from vllm_omni.worker_v2.omni_data_plane import OmniRunnerDataPlane
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _complete(plane, payloads, token=21, req="internal"):
|
||||
return plane.complete_outputs(
|
||||
req_ids=[req], inter_stage_outputs=payloads, sampled_token_ids=[[token]] * len(payloads)
|
||||
)
|
||||
|
||||
|
||||
def _new_request(req_id="internal", external_req_id="external"):
|
||||
return SimpleNamespace(
|
||||
req_id=req_id,
|
||||
external_req_id=external_req_id,
|
||||
prompt_token_ids=[10, 11],
|
||||
num_computed_tokens=2,
|
||||
resumable=True,
|
||||
additional_information=SimpleNamespace(entries={}),
|
||||
sampling_params=SimpleNamespace(stop_token_ids=[2150]),
|
||||
)
|
||||
|
||||
|
||||
def _bare_plane(*, delivery_timeout_s=1.0, shutdown_timeout_s=1.0):
|
||||
plane = object.__new__(OmniRunnerDataPlane)
|
||||
plane.__dict__.update(
|
||||
_native_requests={},
|
||||
_native_output_lock=threading.RLock(),
|
||||
_native_send_lock=threading.Lock(),
|
||||
_native_output_error=None,
|
||||
_native_output_error_lock=threading.Lock(),
|
||||
_native_output_closed=False,
|
||||
_native_outputs_in_flight=defaultdict(int),
|
||||
_native_terminal_pending=set(),
|
||||
_put_req_chunk=defaultdict(int),
|
||||
_ramp_chunk_count=defaultdict(int),
|
||||
_delivery_manager=OmniDeliveryManager(
|
||||
delivery_timeout_s=delivery_timeout_s, shutdown_timeout_s=shutdown_timeout_s
|
||||
),
|
||||
)
|
||||
return plane
|
||||
|
||||
|
||||
def _make_plane(replace_send):
|
||||
p = _bare_plane()
|
||||
p.record = SimpleNamespace(batches=[], cleaned=[])
|
||||
if replace_send:
|
||||
p.send_chunks = lambda entries, **_kw: p.record.batches.append(entries) or len(entries)
|
||||
p.get_omni_connector_output, p.cleanup_finished_request = (lambda: None), p.record.cleaned.append
|
||||
return p
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def raw_plane(): # keeps the real connector send path
|
||||
p = _make_plane(replace_send=False)
|
||||
yield p
|
||||
if getattr(p, "_native_output_worker", None) is not None:
|
||||
p._stop_output_worker()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plane():
|
||||
p = _make_plane(replace_send=True)
|
||||
yield p
|
||||
if getattr(p, "_native_output_worker", None) is not None:
|
||||
p._stop_output_worker()
|
||||
|
||||
|
||||
def _gated_connector():
|
||||
# put() blocks its first call until released (or forever without release).
|
||||
conn = SimpleNamespace(
|
||||
put_keys=[], put_started=threading.Event(), release=threading.Event(), close_called=threading.Event()
|
||||
)
|
||||
|
||||
def put(**kwargs):
|
||||
conn.put_keys.append(kwargs["put_key"])
|
||||
if len(conn.put_keys) == 1:
|
||||
conn.put_started.set()
|
||||
assert conn.release.wait(timeout=2)
|
||||
return True, 1, None
|
||||
|
||||
conn.put, conn.close = put, conn.close_called.set
|
||||
return conn
|
||||
|
||||
|
||||
def _start_save_thread(plane, connector):
|
||||
plane.__dict__.update(
|
||||
_omni_connector=connector,
|
||||
_stage_id=0,
|
||||
_next_stage_id=1,
|
||||
_lock=threading.Lock(),
|
||||
_pending_save_reqs={},
|
||||
_pending_save_counts=defaultdict(int),
|
||||
_deferred_send_cleanup=set(),
|
||||
_request_ids_mapping={},
|
||||
_cached_ic={},
|
||||
_send_side_request_payload={},
|
||||
_code_prompt_token_ids=defaultdict(list),
|
||||
_work_available=threading.Event(),
|
||||
_stop_event=threading.Event(),
|
||||
_MAX_SEND_RETRIES=0,
|
||||
_can_send=True,
|
||||
_recv_thread=None,
|
||||
_custom_process_batch_func=lambda **kwargs: kwargs["pooling_outputs"],
|
||||
is_data_transfer_rank=lambda: True,
|
||||
_connector_send_error_sink=plane._record_output_error,
|
||||
)
|
||||
plane._save_thread = threading.Thread(target=plane._save_loop, daemon=True)
|
||||
plane._save_thread.start()
|
||||
|
||||
|
||||
def _stop_save_thread(plane):
|
||||
plane._stop_event.set()
|
||||
plane._work_available.set()
|
||||
plane._save_thread.join(timeout=2)
|
||||
assert not plane._save_thread.is_alive()
|
||||
|
||||
|
||||
class _Output:
|
||||
copy_event = None
|
||||
|
||||
def __init__(self, rid="internal", gate=None, started=None, error=None, payload=None, token=1):
|
||||
self.rid, self.gate, self.started = rid, gate, started
|
||||
self.error, self.payload, self.token = error, payload, token
|
||||
|
||||
def get_output(self):
|
||||
if self.started is not None:
|
||||
self.started.set()
|
||||
if self.gate is not None:
|
||||
assert self.gate.wait(timeout=3)
|
||||
if self.error is not None:
|
||||
raise self.error
|
||||
return SimpleNamespace(
|
||||
req_ids=[self.rid],
|
||||
inter_stage_outputs=[self.payload] if self.payload is not None else None,
|
||||
sampled_token_ids=[[self.token]],
|
||||
)
|
||||
|
||||
|
||||
def test_emit_cohort_one_batch_and_trims_non_resumable_history(plane):
|
||||
plane.send_chunk = lambda *_a, **_kw: pytest.fail("must not fall back to per-request send_chunk")
|
||||
plane.register_request(_new_request("r0", "ext-0"))
|
||||
plane.register_request(_new_request("r1", "ext-1"))
|
||||
emitted = plane.emit_chunks(
|
||||
req_ids=["r0", "r1"],
|
||||
inter_stage_outputs=[{"codes.audio": "c0"}, {"codes.audio": "c1"}],
|
||||
sampled_token_ids=[[21]],
|
||||
terminal_req_ids={"r1"},
|
||||
)
|
||||
assert emitted == 2 and len(plane.record.batches) == 1 # the whole step cohort goes out in one batch
|
||||
(req0, _), (req1, _) = plane.record.batches[0]
|
||||
assert (
|
||||
req0.all_token_ids == [10, 11, 21]
|
||||
and not req0.is_finished()
|
||||
and req1.is_finished()
|
||||
and plane.record.cleaned == ["r1"]
|
||||
)
|
||||
# A non-resumable request omits token history after its first chunk.
|
||||
plane.register_request(_new_request("r2", "ext-2"))
|
||||
state = plane._native_requests["r2"]
|
||||
state.resumable, state.output_token_ids, plane._put_req_chunk["ext-2"] = False, list(range(1024)), 1
|
||||
plane.emit_chunks(
|
||||
req_ids=["r2"], inter_stage_outputs=[{"h": "d"}], sampled_token_ids=[[1024]], terminal_req_ids={"r2"}
|
||||
)
|
||||
request, _ = plane.record.batches[1][0]
|
||||
assert request.output_token_count == 1025 and request.all_token_ids == []
|
||||
|
||||
|
||||
def test_terminal_reserved_abort_and_cleanup_lifecycle(plane):
|
||||
batches, cleaned = plane.record.batches, plane.record.cleaned
|
||||
plane.register_request(_new_request())
|
||||
plane.reserve_outputs(["internal"])
|
||||
plane.reserve_outputs(["internal"])
|
||||
# The terminal defers while reservations are in flight, and is idempotent.
|
||||
assert plane.request_terminal({"internal"}) == 0
|
||||
assert plane.request_terminal({"internal"}) == 0 and batches == []
|
||||
assert _complete(plane, [{"codes.audio": "c0"}]) == 1 and not batches[0][0][0].is_finished()
|
||||
assert _complete(plane, [{"codes.audio": "c1"}], token=22) == 2 # data chunk, then the released terminal
|
||||
chunk, terminal = batches[1][0], batches[2][0]
|
||||
assert chunk[1] == {"codes": {"audio": "c1"}} and chunk[0].output_token_ids == [21, 22]
|
||||
assert terminal[1] is None and terminal[0].is_finished() and cleaned == ["internal"]
|
||||
# Stale terminal/complete after cleanup are no-ops; cleanup ran exactly once.
|
||||
assert plane.request_terminal({"internal"}) == 0 and _complete(plane, [{"codes.audio": "stale"}]) == 0
|
||||
# Abort emits exactly one terminal and silently drops the stale deferred output.
|
||||
plane.register_request(_new_request("ra"))
|
||||
plane.reserve_outputs(["ra"])
|
||||
plane.request_terminal({"ra"})
|
||||
assert plane.abort_requests({"ra"}) == 1
|
||||
request, payload = batches[-1][0]
|
||||
assert request.is_finished() and payload is None and cleaned == ["internal", "ra"]
|
||||
assert (
|
||||
plane.abort_requests({"ra"}) == 0 and _complete(plane, [{"s": 1}], req="ra") == 0
|
||||
) # duplicate abort, stale output
|
||||
assert sum(b[0][0].request_id == "ra" for b in batches) == 1 # terminal exactly once
|
||||
|
||||
|
||||
def test_abort_cannot_overtake_committed_output(plane):
|
||||
in_lock, release, sent = threading.Event(), threading.Event(), threading.Event()
|
||||
|
||||
def gated(entries, _orig=plane._send_chunk_entries, **kw):
|
||||
terminal = entries[0][0].is_finished()
|
||||
if not terminal:
|
||||
in_lock.set()
|
||||
assert release.wait(timeout=2) # hold the committed data send inside _native_send_lock
|
||||
result = _orig(entries, **kw)
|
||||
if terminal:
|
||||
sent.set()
|
||||
return result
|
||||
|
||||
plane._send_chunk_entries = gated
|
||||
plane.register_request(_new_request())
|
||||
plane.reserve_outputs(["internal"])
|
||||
threads = [
|
||||
threading.Thread(target=lambda: _complete(plane, [{"c": 0}])),
|
||||
threading.Thread(target=plane.abort_requests, args=({"internal"},)),
|
||||
]
|
||||
threads[0].start()
|
||||
try:
|
||||
assert in_lock.wait(timeout=2)
|
||||
threads[1].start()
|
||||
overtook = sent.wait(timeout=0.1) # the terminal must not pass the committed data send
|
||||
finally:
|
||||
release.set()
|
||||
for t in threads:
|
||||
if t.ident is not None:
|
||||
t.join(timeout=2)
|
||||
assert not t.is_alive()
|
||||
assert not overtook
|
||||
|
||||
|
||||
def test_output_worker_fifo_and_scheduler_not_blocked(plane):
|
||||
batches, send_started, release_send = [], threading.Event(), threading.Event()
|
||||
|
||||
def send_chunks(entries, **_kw):
|
||||
if not entries[0][0].is_finished():
|
||||
send_started.set()
|
||||
assert release_send.wait(timeout=2)
|
||||
batches.append(entries)
|
||||
return len(entries)
|
||||
|
||||
plane.send_chunks = send_chunks
|
||||
plane._start_output_worker(max_pending_batches=2)
|
||||
plane.register_request(_new_request())
|
||||
plane.reserve_outputs(["internal"])
|
||||
plane.enqueue_outputs(req_ids=["internal"], inter_stage_outputs=[{"c": 0}], sampled_token_ids=[[21]])
|
||||
assert send_started.wait(timeout=2)
|
||||
# A stuck deferred send must not block the scheduler path.
|
||||
assert plane.request_terminal({"internal"}) == 0 and batches == []
|
||||
release_send.set()
|
||||
plane.drain_outputs()
|
||||
assert [e[0].is_finished() for batch in batches for e in batch] == [False, True]
|
||||
|
||||
|
||||
def test_worker_failure_surfaces_and_close_drains_in_order(plane):
|
||||
events = []
|
||||
plane.send_chunks = lambda _e, **_kw: (_ for _ in ()).throw(RuntimeError("enqueue failed"))
|
||||
plane.shutdown_omni_connectors = lambda: events.append("shutdown")
|
||||
plane._start_output_worker(max_pending_batches=2)
|
||||
plane.register_request(_new_request())
|
||||
plane.enqueue_outputs(req_ids=["internal"], inter_stage_outputs=[{"c": 0}], sampled_token_ids=[[21]])
|
||||
with pytest.raises(RuntimeError, match="enqueue failed"):
|
||||
plane.drain_outputs()
|
||||
with pytest.raises(RuntimeError, match="enqueue failed"): # an errored worker rejects new submissions
|
||||
plane.enqueue_outputs(req_ids=["internal"], inter_stage_outputs=[{"c": 1}], sampled_token_ids=[[22]])
|
||||
# close() drains pending batches before shutting connectors down.
|
||||
plane._native_output_error = None
|
||||
|
||||
def send_chunks(entries, **_kw):
|
||||
events.append("send")
|
||||
return len(entries)
|
||||
|
||||
plane.send_chunks = send_chunks
|
||||
plane.enqueue_outputs(req_ids=["internal"], inter_stage_outputs=[{"c": 1}], sampled_token_ids=[[22]])
|
||||
plane.close()
|
||||
assert events == ["send", "shutdown"]
|
||||
|
||||
|
||||
def test_permanent_put_failure_quarantines_and_holds_state(raw_plane):
|
||||
puts = []
|
||||
|
||||
def put(**_kw):
|
||||
puts.append(1)
|
||||
return False, 0, None
|
||||
|
||||
connector = SimpleNamespace(put=put, close=lambda: None)
|
||||
_start_save_thread(raw_plane, connector)
|
||||
raw_plane.register_request(_new_request())
|
||||
raw_plane.reserve_outputs(["internal"])
|
||||
raw_plane.request_terminal({"internal"})
|
||||
with pytest.raises(RuntimeError, match="connector send failed"):
|
||||
raw_plane.complete_outputs(req_ids=["internal"], inter_stage_outputs=[{"c": 0}], sampled_token_ids=[[21]])
|
||||
assert len(puts) == 1 and raw_plane._native_output_error is not None # fail fast, no retry
|
||||
assert raw_plane._native_outputs_in_flight["internal"] == 1 and "internal" in raw_plane._native_terminal_pending
|
||||
with pytest.raises(RuntimeError, match="quarantined"): # the quarantine rejects new tickets
|
||||
raw_plane._delivery_manager.create_ticket(request_id="other", put_key="other_0_0")
|
||||
_stop_save_thread(raw_plane)
|
||||
|
||||
|
||||
def test_delivery_timeout_drops_queued_ticket(raw_plane):
|
||||
raw_plane._delivery_manager = OmniDeliveryManager(delivery_timeout_s=0.05, shutdown_timeout_s=0.5)
|
||||
connector = _gated_connector()
|
||||
_start_save_thread(raw_plane, connector)
|
||||
req = SimpleNamespace(request_id="external")
|
||||
_, first = raw_plane._enqueue_chunk_payload(req, {"c": 1}, wait_for_delivery=True)
|
||||
_, second = raw_plane._enqueue_chunk_payload(req, {"c": 2}, wait_for_delivery=True)
|
||||
assert connector.put_started.wait(timeout=1)
|
||||
with pytest.raises(TimeoutError, match="delivery timed out"):
|
||||
first.wait()
|
||||
assert raw_plane._delivery_manager.is_quarantined
|
||||
connector.release.set()
|
||||
deadline = time.monotonic() + 1
|
||||
while time.monotonic() < deadline and "external" in raw_plane._pending_save_counts: # the save loop drops it
|
||||
time.sleep(0.001)
|
||||
# After quarantine the queued ticket is never put and is marked FAILED.
|
||||
assert connector.put_keys == [first.put_key] and second.state is DeliveryState.FAILED
|
||||
assert "external" not in raw_plane._pending_save_counts and "external" not in raw_plane._pending_save_reqs
|
||||
_stop_save_thread(raw_plane)
|
||||
|
||||
|
||||
def test_close_cancels_waiting_delivery_once_and_shutdown_stays_bounded():
|
||||
# A queued delivery waiter is cancelled exactly once on shutdown.
|
||||
manager = OmniDeliveryManager(delivery_timeout_s=30.0, shutdown_timeout_s=0.5)
|
||||
ticket = manager.create_ticket(request_id="r", put_key="k")
|
||||
manager.shutdown(RuntimeError("close"))
|
||||
manager.shutdown(RuntimeError("again")) # idempotent: cancelled at most once
|
||||
with pytest.raises(DeliveryCancelledError, match="cancelled"):
|
||||
ticket.wait()
|
||||
# A connector put() that cannot be cancelled must not hang shutdown.
|
||||
plane = _bare_plane(delivery_timeout_s=0.05, shutdown_timeout_s=0.2)
|
||||
connector = _gated_connector()
|
||||
_start_save_thread(plane, connector)
|
||||
assert plane._enqueue_chunk_payload(SimpleNamespace(request_id="external"), {"c": 0}, wait_for_delivery=True)[0]
|
||||
assert connector.put_started.wait(timeout=1)
|
||||
start = time.monotonic()
|
||||
with pytest.raises(RuntimeError, match="shutdown exceeded"):
|
||||
plane.shutdown_omni_connectors()
|
||||
assert time.monotonic() - start < 1.5 and connector.close_called.is_set()
|
||||
connector.release.set()
|
||||
_stop_save_thread(plane)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("abort", [False, True])
|
||||
def test_materialization_fences_terminal_and_abort(plane, abort):
|
||||
batches, cleaned, gate, started = plane.record.batches, plane.record.cleaned, threading.Event(), threading.Event()
|
||||
plane._start_output_worker(max_pending_batches=2)
|
||||
materializer = NativeOutputWorker(2)
|
||||
try:
|
||||
plane.register_request(_new_request())
|
||||
plane.reserve_outputs(["internal"])
|
||||
output = materializer.submit(
|
||||
_Output(gate=gate, started=started, payload={"codes.audio": "c0"}, token=21), plane
|
||||
)
|
||||
assert started.wait(timeout=3)
|
||||
assert plane.request_terminal({"internal"}) == 0 # fenced behind the in-flight materialization
|
||||
assert not abort or plane.abort_requests({"internal"}) == 1
|
||||
gate.set()
|
||||
output.get_output()
|
||||
materializer.close()
|
||||
plane.drain_outputs()
|
||||
assert cleaned == ["internal"] and len(batches) == (1 if abort else 2)
|
||||
assert abort or (batches[0][0][1] == {"codes": {"audio": "c0"}} and not batches[0][0][0].is_finished())
|
||||
assert batches[-1][0][0].is_finished()
|
||||
finally:
|
||||
gate.set()
|
||||
materializer.close()
|
||||
|
||||
|
||||
def test_native_worker_fifo_thread_affinity_and_signals():
|
||||
owner, gate = threading.get_ident(), threading.Event()
|
||||
calls: list[tuple[Any, ...]] = []
|
||||
|
||||
def get_signals():
|
||||
calls.append(("signals", threading.get_ident()))
|
||||
return "ready"
|
||||
|
||||
plane = SimpleNamespace(
|
||||
enqueue_outputs=lambda **kw: calls.append(("publish", kw["req_ids"], threading.get_ident())),
|
||||
get_omni_connector_output=get_signals,
|
||||
)
|
||||
worker = NativeOutputWorker(2)
|
||||
try:
|
||||
a = worker.submit(_Output("a", gate=gate, payload={"v": 1}), plane)
|
||||
b = worker.submit(_Output("b", payload={"v": 1}), plane)
|
||||
gate.set()
|
||||
b.get_output() # publication of b implies a already published (FIFO, single worker thread)
|
||||
publishes = [c for c in calls if c[0] == "publish"]
|
||||
assert [c[1] for c in publishes] == [["a"], ["b"]]
|
||||
assert all(c[2] != owner for c in publishes) # published on the worker thread
|
||||
result = a.get_output()
|
||||
assert a.get_output() is result and result.inter_stage_outputs is None # resolution is cached
|
||||
assert result.omni_connector_output == "ready"
|
||||
assert calls[-2:] == [("signals", owner)] * 2 # signals resolve lazily on the caller thread
|
||||
finally:
|
||||
gate.set()
|
||||
worker.close()
|
||||
|
||||
|
||||
def test_native_worker_capacity_error_cache_and_tp_gates():
|
||||
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
|
||||
|
||||
plane = SimpleNamespace(enqueue_outputs=lambda **kw: None, get_omni_connector_output=lambda: None)
|
||||
worker, gate = NativeOutputWorker(1), threading.Event()
|
||||
try:
|
||||
first = worker.submit(_Output("a", gate=gate), plane)
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(worker.submit, _Output("b"), plane)
|
||||
time.sleep(0.05)
|
||||
assert not future.done() # capacity 1: pending materialization is bounded
|
||||
gate.set()
|
||||
second = future.result(3)
|
||||
assert first.get_output().req_ids == ["a"] and second.get_output().req_ids == ["b"]
|
||||
bad = worker.submit(_Output("x", error=ValueError("crash")), plane)
|
||||
finally:
|
||||
gate.set()
|
||||
worker.close()
|
||||
# A failed materialization is cached: repeated reads raise the same error.
|
||||
for _ in range(2):
|
||||
with pytest.raises(ValueError, match="crash"):
|
||||
bad.get_output()
|
||||
runner = SimpleNamespace(
|
||||
_omni_data_plane=object(), vllm_config=SimpleNamespace(parallel_config=SimpleNamespace(tensor_parallel_size=2))
|
||||
)
|
||||
assert OmniGPUModelRunner._uses_native_output_materializer(runner) is False # TP>1 keeps TP consumers
|
||||
runner.vllm_config.parallel_config.tensor_parallel_size = 1
|
||||
assert OmniGPUModelRunner._uses_native_output_materializer(runner) is True
|
||||
|
||||
|
||||
def test_abort_before_first_chunk_cleans_receiver_state():
|
||||
plane = _bare_plane()
|
||||
plane._stage_id, plane._lock, plane._work_available = 1, threading.Lock(), threading.Event()
|
||||
for name in (
|
||||
"_pending_full_payload_send",
|
||||
"_request_ids_mapping",
|
||||
"_pending_save_counts",
|
||||
"_send_side_request_payload",
|
||||
"_code_prompt_token_ids",
|
||||
"_cached_ic",
|
||||
"_adaptive_states",
|
||||
"_kv_pending_transfers",
|
||||
"_get_req_chunk",
|
||||
"_pending_load_reqs",
|
||||
"_local_stage_payload_cache",
|
||||
"_local_request_metadata",
|
||||
):
|
||||
setattr(plane, name, {})
|
||||
for name in (
|
||||
"_deferred_send_cleanup",
|
||||
"_kv_active_transfers",
|
||||
"_kv_completed_transfers",
|
||||
"_kv_triggered_requests",
|
||||
"_finished_load_reqs",
|
||||
"_chunk_ready_req_ids",
|
||||
"_chunk_finished_req_ids",
|
||||
"_chunk_stream_completed",
|
||||
"_stage_recv_req_ids",
|
||||
"_full_payload_pending_broadcast_req_ids",
|
||||
"_async_chunk_updated_req_ids",
|
||||
):
|
||||
setattr(plane, name, set())
|
||||
plane.register_receivers([SimpleNamespace(request_id="r", external_req_id="external")])
|
||||
plane._local_stage_payload_cache["r"] = {"codes": torch.ones(1)}
|
||||
assert "r" in plane._pending_load_reqs and plane._request_ids_mapping["r"] == "external"
|
||||
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
|
||||
@@ -0,0 +1,184 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""OmniGenerationModelRunner contracts: empty-step lifecycle, output partition,
|
||||
CPU-sync vs CUDA-async dispatch, and async-chunk slot recycling."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
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
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _FakeStagedField:
|
||||
def __init__(self, data):
|
||||
self.np = data
|
||||
self._staged = []
|
||||
|
||||
def stage_write_elem(self, idx, value):
|
||||
self._staged.append((idx, value))
|
||||
|
||||
def apply_write(self):
|
||||
for idx, value in self._staged:
|
||||
self.np[idx] = value
|
||||
self._staged.clear()
|
||||
|
||||
|
||||
def _make_runner(model_output, num_reqs=1, prompt_len=10):
|
||||
runner = object.__new__(OmniGenerationModelRunner)
|
||||
runner.device = torch.device("cpu")
|
||||
runner.model_config = MagicMock(hf_text_config=None)
|
||||
del runner.model_config.eos_token_id
|
||||
runner.postprocess = lambda *a, **kw: None
|
||||
runner._gen_model_output = model_output
|
||||
runner._gen_input_batch = SimpleNamespace(
|
||||
num_reqs=num_reqs, req_ids=[f"req-{i}" for i in range(num_reqs)], idx_mapping_np=np.arange(num_reqs)
|
||||
)
|
||||
runner.execute_model_state = SimpleNamespace(finished_req_ids={"finished"}, ec_connector_output=None)
|
||||
runner.kv_connector = SimpleNamespace(post_forward=MagicMock(return_value=None))
|
||||
runner.check_ep_fault = False
|
||||
runner.req_states = MagicMock(
|
||||
prompt_len=SimpleNamespace(np=np.full(num_reqs, prompt_len, dtype=np.int32)),
|
||||
num_computed_tokens=_FakeStagedField(np.zeros(num_reqs, dtype=np.int32)),
|
||||
)
|
||||
return runner
|
||||
|
||||
|
||||
def test_control_only_step_keeps_lifecycle_and_skips_input_construction():
|
||||
runner = object.__new__(OmniGenerationModelRunner)
|
||||
order = []
|
||||
for name in (
|
||||
"_prepare_native_data_plane",
|
||||
"finish_requests",
|
||||
"free_states",
|
||||
"_apply_block_table_staged_writes_if_available",
|
||||
):
|
||||
setattr(runner, name, lambda *args, name=name: order.append(name))
|
||||
for name in ("_handle_async_chunk_updates", "add_requests", "update_requests", "_sync_native_data_plane_payloads"):
|
||||
setattr(runner, name, MagicMock(side_effect=AssertionError("control step built model inputs")))
|
||||
output = object()
|
||||
runner.kv_connector = SimpleNamespace(no_forward=lambda _s: output)
|
||||
runner._merge_ec_connector_no_forward = lambda _s, value: value
|
||||
runner._attach_native_data_plane_signals = lambda value: value
|
||||
scheduler_output = SimpleNamespace(
|
||||
total_num_scheduled_tokens=0, scheduled_new_reqs=[], scheduled_cached_reqs=SimpleNamespace(req_ids=[])
|
||||
)
|
||||
assert runner.execute_model(scheduler_output) is output
|
||||
assert order == [
|
||||
"_prepare_native_data_plane",
|
||||
"finish_requests",
|
||||
"free_states",
|
||||
"_apply_block_table_staged_writes_if_available",
|
||||
]
|
||||
|
||||
|
||||
def test_released_chunk_reuses_scheduler_output_and_slot_recycle_clears_state():
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
|
||||
from vllm_omni.core.sched.output import OmniCachedRequestData
|
||||
|
||||
runner = object.__new__(OmniGenerationModelRunner)
|
||||
runner.model = SimpleNamespace(logits_processor=None)
|
||||
runner._remove_request = MagicMock()
|
||||
req_id_to_index = MagicMock()
|
||||
req_id_to_index.get.return_value = None
|
||||
runner.req_states = SimpleNamespace(
|
||||
add_request=MagicMock(), req_id_to_index=req_id_to_index, apply_staged_writes=MagicMock()
|
||||
)
|
||||
runner.pooling_runner = None
|
||||
runner.encoder_cache = None
|
||||
runner.model_state = SimpleNamespace(
|
||||
add_request=MagicMock(),
|
||||
apply_staged_writes=MagicMock(),
|
||||
remove_request=MagicMock(),
|
||||
intermediate_buffer=SimpleNamespace(remove_request=MagicMock()),
|
||||
)
|
||||
runner.block_tables = SimpleNamespace(append_block_ids=MagicMock())
|
||||
runner.lora_state = SimpleNamespace(add_request=MagicMock())
|
||||
runner.is_last_pp_rank = False
|
||||
runner.adaptive_verification = None
|
||||
runner.sampler = None
|
||||
cached = OmniCachedRequestData(
|
||||
req_ids=["req"],
|
||||
resumed_req_ids=set(),
|
||||
new_token_ids=[[]],
|
||||
all_token_ids={"req": [1]},
|
||||
new_block_ids=[()],
|
||||
num_computed_tokens=[0],
|
||||
num_output_tokens=[0],
|
||||
prompt_token_ids={"req": [1]},
|
||||
additional_information={"req": None},
|
||||
)
|
||||
scheduler_output = SchedulerOutput(
|
||||
scheduled_new_reqs=[],
|
||||
scheduled_cached_reqs=cached,
|
||||
num_scheduled_tokens={"req": 1},
|
||||
total_num_scheduled_tokens=1,
|
||||
scheduled_spec_decode_tokens={},
|
||||
scheduled_encoder_inputs={},
|
||||
num_common_prefix_blocks=[0],
|
||||
finished_req_ids=set(),
|
||||
free_encoder_mm_hashes=[],
|
||||
)
|
||||
runner._handle_async_chunk_updates(scheduler_output)
|
||||
added = runner.model_state.add_request.call_args.args[1]
|
||||
assert (added.req_id, added.prompt_token_ids) == ("req", [1])
|
||||
|
||||
|
||||
def test_sample_tokens_cpu_sync_owns_outputs_and_runs_connector_last():
|
||||
waveform = torch.arange(4, dtype=torch.float32)
|
||||
output = OmniOutput(text_hidden_states=torch.empty(0), multimodal_outputs={"codes": {"audio": [waveform]}})
|
||||
runner = _make_runner(output, num_reqs=1)
|
||||
runner._reserve_native_data_plane_outputs = MagicMock()
|
||||
runner._finalize_native_data_plane_output = MagicMock(side_effect=lambda value: value)
|
||||
|
||||
def post_forward(_finished):
|
||||
assert runner.req_states.num_computed_tokens.np.tolist() == [10]
|
||||
|
||||
runner.kv_connector.post_forward.side_effect = post_forward
|
||||
result = OmniGenerationModelRunner.sample_tokens(runner)
|
||||
assert isinstance(result, OmniModelRunnerOutput)
|
||||
# Reserve precedes finalize; connector runs after token state is applied.
|
||||
runner._reserve_native_data_plane_outputs.assert_called_once_with(["req-0"])
|
||||
runner.kv_connector.post_forward.assert_called_once_with({"finished"})
|
||||
waveform.fill_(-1)
|
||||
assert torch.equal(result.multimodal_outputs[0]["codes.audio"], torch.arange(4, dtype=torch.float32))
|
||||
|
||||
|
||||
def test_sample_tokens_uses_async_output_for_cuda_and_snapshots_req_ids(monkeypatch):
|
||||
from vllm_omni.worker_v2 import omni_generation_model_runner as generation_runner
|
||||
|
||||
output = OmniOutput(text_hidden_states=torch.zeros(1), multimodal_outputs={"model_outputs": [torch.randn(4)]})
|
||||
runner = _make_runner(output, num_reqs=1)
|
||||
runner.device = SimpleNamespace(type="cuda")
|
||||
runner.main_stream = object()
|
||||
runner.output_copy_stream = object()
|
||||
runner.model_config.async_chunk = True
|
||||
runner._release_generation_slots = MagicMock()
|
||||
runner._finalize_native_data_plane_output = MagicMock()
|
||||
monkeypatch.setattr(generation_runner, "_contains_cuda_tensor", lambda _: True)
|
||||
captured = {}
|
||||
|
||||
class _FakeAsyncOutput:
|
||||
def __init__(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(generation_runner, "OmniGenerationAsyncOutput", _FakeAsyncOutput)
|
||||
input_batch = runner._gen_input_batch
|
||||
result = generation_runner.OmniGenerationModelRunner.sample_tokens(runner)
|
||||
|
||||
assert isinstance(result, _FakeAsyncOutput)
|
||||
assert captured["finalize_output"] is runner._finalize_native_data_plane_output
|
||||
assert captured["model_runner_output"].sampled_token_ids == [[]]
|
||||
runner._release_generation_slots.assert_called_once()
|
||||
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"]
|
||||
@@ -0,0 +1,166 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
|
||||
"""MRV2 admission, capture, dispatch and request lifecycle contracts."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from vllm import SamplingParams
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
|
||||
from vllm.v1.worker.gpu.sample.sampler import Sampler
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput
|
||||
from vllm_omni.worker_v2.model_states import init_omni_model_state
|
||||
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState
|
||||
from vllm_omni.worker_v2.omni_model_runner import OmniGPUModelRunner
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
def _make_runner():
|
||||
"""Create an OmniGPUModelRunner without calling __init__."""
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.model = MagicMock()
|
||||
runner.req_states = SimpleNamespace(req_id_to_index={"r1": 0, "r2": 1})
|
||||
runner.execute_model_state = None
|
||||
return runner
|
||||
|
||||
|
||||
def test_add_requests_empty_admission_and_stop_id_sanitization():
|
||||
runner = _make_runner()
|
||||
runner.sampler = Sampler.__new__(Sampler)
|
||||
with patch.object(GPUModelRunner, "add_requests", return_value=None) as parent:
|
||||
runner.add_requests(SchedulerOutput.make_empty())
|
||||
parent.assert_not_called()
|
||||
|
||||
# New requests always go upstream; narrow logits heads sanitize stop ids.
|
||||
sampling_params = SamplingParams(min_tokens=2, stop_token_ids=[2150])
|
||||
sampling_params.update_from_generation_config({}, 151645)
|
||||
runner.model = SimpleNamespace(logits_processor=SimpleNamespace(vocab_size=3072))
|
||||
output = SchedulerOutput.make_empty()
|
||||
output.scheduled_new_reqs = [SimpleNamespace(sampling_params=sampling_params)]
|
||||
runner.add_requests(output)
|
||||
parent.assert_called_once_with(output)
|
||||
assert sampling_params.all_stop_token_ids == {2150}
|
||||
assert sampling_params.eos_token_id == 151645
|
||||
|
||||
|
||||
def test_prepare_native_data_plane_terminal_abort_split_and_warmup_skip():
|
||||
runner = _make_runner()
|
||||
plane = SimpleNamespace(
|
||||
register_request=MagicMock(),
|
||||
register_receivers=MagicMock(),
|
||||
request_terminal=MagicMock(),
|
||||
abort_requests=MagicMock(),
|
||||
)
|
||||
runner._omni_data_plane = plane
|
||||
new_req = SimpleNamespace(req_id="r1")
|
||||
warmup_req = SimpleNamespace(req_id="_warmup_0_")
|
||||
handle = SimpleNamespace(request_id="r2", external_req_id="ext-r2")
|
||||
scheduler_output = SimpleNamespace(
|
||||
scheduled_new_reqs=[new_req, warmup_req],
|
||||
pending_input_registrations=[handle],
|
||||
data_plane_terminal_req_ids={"r0"},
|
||||
finished_req_ids={"r0", "aborted"},
|
||||
)
|
||||
|
||||
runner._prepare_native_data_plane(scheduler_output)
|
||||
|
||||
plane.register_request.assert_called_once_with(new_req) # warmup skipped
|
||||
plane.register_receivers.assert_called_once_with([handle])
|
||||
plane.request_terminal.assert_called_once_with({"r0"})
|
||||
plane.abort_requests.assert_called_once_with({"aborted"})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output_form", ["tuple", "omni"])
|
||||
def test_capture_model_unwraps_exclude_full_and_capture_mtp(output_form):
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
hidden = torch.ones(1, 2)
|
||||
|
||||
def original_forward():
|
||||
if output_form == "tuple":
|
||||
return hidden, {"layers": {}}
|
||||
return OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
|
||||
|
||||
runner.model = SimpleNamespace(forward=original_forward)
|
||||
runner._model_returns_tuple = True
|
||||
runner._exclude_full_graph = True
|
||||
runner.use_aux_hidden_state_outputs = False
|
||||
piecewise = SimpleNamespace(cg_mode=CUDAGraphMode.PIECEWISE)
|
||||
full = SimpleNamespace(cg_mode=CUDAGraphMode.FULL)
|
||||
runner.cudagraph_manager = SimpleNamespace(
|
||||
_capture_descs={CUDAGraphMode.PIECEWISE: [piecewise], CUDAGraphMode.FULL: [full]},
|
||||
_candidates={(1, 0): [piecewise, full]},
|
||||
)
|
||||
runner.model_state = SimpleNamespace(capture_mtp_graphs=MagicMock())
|
||||
runner._dispatch_mtp_batch_descriptor = MagicMock(return_value="desc")
|
||||
|
||||
def assert_unwrapped(_self):
|
||||
assert torch.equal(runner.model.forward(), hidden) # forward unwrapped during capture
|
||||
return 3
|
||||
|
||||
with patch.object(GPUModelRunner, "capture_model", assert_unwrapped):
|
||||
assert runner.capture_model() == 3
|
||||
|
||||
assert runner.model.forward is original_forward # restored after capture
|
||||
assert runner.cudagraph_manager._capture_descs == {CUDAGraphMode.PIECEWISE: [piecewise]}
|
||||
runner.model_state.capture_mtp_graphs.assert_called_once_with(runner._dispatch_mtp_batch_descriptor)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"parallel_config,match",
|
||||
[
|
||||
(dict(pipeline_parallel_size=2, prefill_context_parallel_size=1), "pipeline parallel"),
|
||||
(dict(pipeline_parallel_size=1, prefill_context_parallel_size=2), "prefill context parallelism"),
|
||||
],
|
||||
)
|
||||
def test_mrv2_rejects_parallel_modes_at_startup(parallel_config, match):
|
||||
runner = object.__new__(OmniGPUModelRunner)
|
||||
runner.vllm_config = SimpleNamespace(parallel_config=SimpleNamespace(**parallel_config))
|
||||
with pytest.raises(NotImplementedError, match=match):
|
||||
runner._validate_parallel_support()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"flag,expect_omni",
|
||||
[(None, False), ("has_preprocess", True), ("has_postprocess", True), ("have_multimodal_outputs", True)],
|
||||
)
|
||||
def test_init_model_state_factory_dispatches_omni_only(monkeypatch, flag, expect_omni):
|
||||
upstream = MagicMock(return_value=object())
|
||||
monkeypatch.setattr("vllm_omni.worker_v2.model_states._upstream_init_model_state", upstream)
|
||||
monkeypatch.setattr(OmniModelState, "__init__", lambda *args: None)
|
||||
cfg = SimpleNamespace(model_config=SimpleNamespace(architectures=["CustomModel"]))
|
||||
model = SimpleNamespace(**({flag: True} if flag else {}))
|
||||
state = init_omni_model_state(cfg, model, None, torch.device("cpu"))
|
||||
|
||||
if expect_omni:
|
||||
assert isinstance(state, OmniModelState)
|
||||
upstream.assert_not_called()
|
||||
else:
|
||||
upstream.assert_called_once()
|
||||
assert state is upstream.return_value
|
||||
|
||||
|
||||
def test_finish_requests_notifies_model_and_cleans_only_known_slots(monkeypatch):
|
||||
runner = _make_runner()
|
||||
calls = []
|
||||
runner.model = SimpleNamespace(on_requests_finished=lambda ids: calls.append(set(ids)))
|
||||
runner.model_state = MagicMock()
|
||||
monkeypatch.setattr(GPUModelRunner, "finish_requests", lambda *args: None)
|
||||
runner.finish_requests(SimpleNamespace(finished_req_ids={"released"}, preempted_req_ids={"r1"}))
|
||||
assert calls == [{"released"}]
|
||||
assert sorted(c.args[0] for c in runner.model_state.remove_request.call_args_list) == [0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stage,declared", [("thinker", False), ("custom_ar", True)])
|
||||
def test_capture_contract_uses_model_declaration(stage, declared):
|
||||
runner = _make_runner()
|
||||
runner.model = SimpleNamespace(model_stage=stage, _returns_tuple=declared)
|
||||
runner._configure_cudagraph_output_contract()
|
||||
assert runner._model_returns_tuple is declared
|
||||
assert runner._exclude_full_graph is declared
|
||||
@@ -0,0 +1,361 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
|
||||
"""OmniModelState: mixed-batch reorder, state isolation/slot reuse, MTP
|
||||
graph/eager paths with per-request seed independence, async snapshot ownership."""
|
||||
|
||||
from contextlib import nullcontext
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import torch
|
||||
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
|
||||
from vllm_omni.model_executor.models.output_templates import OmniOutput, OwnedBatchTensor
|
||||
from vllm_omni.worker_v2.model_states.omni_model_state import OmniModelState, _make_safe_get_rope
|
||||
|
||||
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
|
||||
|
||||
|
||||
class _DummyInputBatch:
|
||||
input_ids: SimpleNamespace
|
||||
query_start_loc: torch.Tensor
|
||||
|
||||
def __init__(self, indices, *, num_computed_tokens_cpu=None):
|
||||
self.idx_mapping_np = indices
|
||||
self.num_reqs = len(indices)
|
||||
self.num_scheduled_tokens = [1] * len(indices)
|
||||
self.query_start_loc_np = list(range(len(indices)))
|
||||
if num_computed_tokens_cpu is not None:
|
||||
self.num_computed_tokens_cpu = np.array(num_computed_tokens_cpu, dtype=np.int32)
|
||||
|
||||
|
||||
def _make_state(max_num_reqs=4, has_preprocess=False, has_postprocess=False, have_multimodal_outputs=False):
|
||||
state = object.__new__(OmniModelState)
|
||||
model = MagicMock()
|
||||
model.has_preprocess = has_preprocess
|
||||
model.has_postprocess = has_postprocess
|
||||
model.have_multimodal_outputs = have_multimodal_outputs
|
||||
model.gpu_resident_buffer_keys = set()
|
||||
model.batched_gpu_staging_keys = set()
|
||||
model.mtp_accepts_per_row_generators = False
|
||||
model.mtp_accepts_req_infos = False
|
||||
model.mtp_output_key = ("codes", "audio")
|
||||
model.mtp_validity_key = None
|
||||
model.mtp_sampling_params = {}
|
||||
model.get_mtp_seed = lambda params: (getattr(params, "extra_args", None) or {}).get("test_seed")
|
||||
model.preprocess_batch_mrv2 = None
|
||||
model.preprocess_decode_batch_mrv2 = None
|
||||
model.preprocess_decode_batch = None
|
||||
model.postprocess_batch_mrv2 = None
|
||||
state.model = model
|
||||
state.scheduler_config = SimpleNamespace(max_num_seqs=max_num_reqs)
|
||||
state.vllm_config = SimpleNamespace(model_config=SimpleNamespace(subtalker_sampling_params={}))
|
||||
state.has_preprocess = has_preprocess
|
||||
state.has_postprocess = has_postprocess
|
||||
state.have_multimodal_outputs = have_multimodal_outputs
|
||||
|
||||
from vllm_omni.worker_v2.model_states.intermediate_buffer import OmniIntermediateBuffer
|
||||
|
||||
state.intermediate_buffer = OmniIntermediateBuffer(max_num_reqs)
|
||||
state._static_inputs_embeds = None
|
||||
state._mtp_generators = {}
|
||||
state._mtp_runner = None
|
||||
for name in ("_mtp_input_ids", "_mtp_input_embeds", "_mtp_hidden", "_mtp_text_step", "_mtp_offsets"):
|
||||
setattr(state, name, None)
|
||||
return state
|
||||
|
||||
|
||||
def _add(state, req_id="r1", idx=0, **req_kwargs):
|
||||
with patch.object(DefaultModelState, "add_request", return_value=None):
|
||||
state.add_request(idx, SimpleNamespace(req_id=req_id, mm_features=[], **req_kwargs))
|
||||
|
||||
|
||||
def _fill_buffers(state, *req_ids):
|
||||
for idx, req_id in enumerate(req_ids):
|
||||
state.intermediate_buffer.buffers[idx] = {"req_id": req_id}
|
||||
|
||||
|
||||
def _seeded(seed):
|
||||
return SimpleNamespace(extra_args={"test_seed": seed}, seed=None)
|
||||
|
||||
|
||||
def _init_static(state, bsz, dim=3):
|
||||
state._mtp_input_ids = torch.zeros(bsz, dtype=torch.long)
|
||||
state._mtp_input_embeds = torch.zeros((bsz, dim))
|
||||
state._mtp_hidden = torch.zeros((bsz, dim))
|
||||
state._mtp_text_step = torch.zeros((bsz, dim))
|
||||
state._mtp_offsets = torch.zeros(bsz, dtype=torch.long)
|
||||
|
||||
|
||||
def _mtp_batches(dim=3):
|
||||
return [(0, 0, (torch.ones(dim), torch.ones(dim) * 2)), (1, 1, (torch.ones(dim) * 3, torch.ones(dim) * 4))]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fwd_ctx():
|
||||
with patch("vllm.forward_context.set_forward_context", return_value=nullcontext()):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.parametrize("req_id,expect_validity", [("_warmup_0_", True), ("r1", False)])
|
||||
def test_add_request_declared_validity_only_for_warmup(req_id, expect_validity):
|
||||
# Real requests must not be masked with a fabricated validity key.
|
||||
state = _make_state()
|
||||
state.model.mtp_validity_key = ("meta", "codec_frame_valid")
|
||||
_add(state, req_id, 0)
|
||||
buf = state.intermediate_buffer.buffers[0]
|
||||
assert ("meta" in buf) is expect_validity
|
||||
if expect_validity:
|
||||
assert buf["meta"]["codec_frame_valid"].item() is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["index", "req_id", "unknown"])
|
||||
def test_remove_request_state_isolation(mode):
|
||||
state = _make_state()
|
||||
_add(state, "r1", 0)
|
||||
state._mtp_generators["r1"] = torch.Generator(device="cpu")
|
||||
if mode == "unknown":
|
||||
state.remove_request("missing")
|
||||
assert state.intermediate_buffer.buffers[0]["req_id"] == "r1"
|
||||
assert "r1" in state._mtp_generators
|
||||
return
|
||||
state.remove_request(0 if mode == "index" else "r1")
|
||||
assert state.intermediate_buffer.buffers[0] == {}
|
||||
assert "r1" not in state._mtp_generators # recycled slot inherits no seed stream
|
||||
|
||||
|
||||
def test_output_spans_follow_reordered_mixed_batch():
|
||||
# batch=[2, 0]: prefill (3 tokens) reordered ahead of decode (1 token).
|
||||
state = _make_state(have_multimodal_outputs=True)
|
||||
batch = _DummyInputBatch([2, 0])
|
||||
batch.num_scheduled_tokens = [3, 1]
|
||||
batch.query_start_loc_np = [0, 3]
|
||||
state.intermediate_buffer.buffers[2] = {"req_id": "prefill"}
|
||||
state.intermediate_buffer.buffers[0] = {"req_id": "decode"}
|
||||
seen = {}
|
||||
state.model.make_omni_output = lambda hidden, **kwargs: (
|
||||
seen.update(kwargs) or OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
|
||||
)
|
||||
state.postprocess_model_output(torch.zeros(4, 2), batch, SimpleNamespace())
|
||||
assert seen["request_token_spans"] == [(0, 3), (3, 4)]
|
||||
assert [info["req_id"] for info in seen["model_intermediate_buffer"]] == ["prefill", "decode"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("hook_name", ["preprocess_decode_batch_mrv2", "preprocess_decode_batch", "legacy"])
|
||||
def test_decode_cohort_uses_batch_hook(hook_name):
|
||||
state = _make_state(max_num_reqs=2, has_preprocess=True)
|
||||
state.intermediate_buffer.buffers[0] = {"req_id": "r1", "meta": {"step": 1}}
|
||||
state.intermediate_buffer.buffers[1] = {"req_id": "r2", "meta": {"step": 2}}
|
||||
batch_calls = []
|
||||
|
||||
def preprocess_decode_batch(*, input_ids, input_embeds, req_infos):
|
||||
batch_calls.append(list(req_infos))
|
||||
return (
|
||||
input_ids + 10,
|
||||
input_embeds + 20,
|
||||
torch.tensor([[31.0, 32.0], [41.0, 42.0]]),
|
||||
torch.tensor([[51.0, 52.0], [61.0, 62.0]]),
|
||||
[{"meta": {"step": 11}}, {"meta": {"step": 12}}],
|
||||
)
|
||||
|
||||
if hook_name == "legacy":
|
||||
# Legacy V1 hook without input_embeds is wrapped by the adapter.
|
||||
state.model.preprocess_decode_batch = lambda *, input_ids, req_infos: preprocess_decode_batch(
|
||||
input_ids=input_ids, input_embeds=model_inputs["inputs_embeds"], req_infos=req_infos
|
||||
)
|
||||
else:
|
||||
setattr(state.model, hook_name, preprocess_decode_batch)
|
||||
if hook_name == "preprocess_decode_batch_mrv2":
|
||||
state.model.preprocess_decode_batch = MagicMock(
|
||||
side_effect=AssertionError("MRV2 hook must take precedence")
|
||||
)
|
||||
state.model.preprocess = MagicMock(side_effect=AssertionError("decode requests must use the batch hook"))
|
||||
seen_prepacked = []
|
||||
|
||||
def capture(batches, *_a, prepacked_mtp_inputs=None):
|
||||
seen_prepacked.append(prepacked_mtp_inputs)
|
||||
|
||||
state._run_batched_mtp = capture
|
||||
model_inputs = {
|
||||
"input_ids": torch.tensor([101, 202], dtype=torch.long),
|
||||
"inputs_embeds": torch.tensor([[1.0, 2.0], [3.0, 4.0]]),
|
||||
}
|
||||
state.run_preprocess(
|
||||
_DummyInputBatch([0, 1], num_computed_tokens_cpu=[1, 1]),
|
||||
model_inputs,
|
||||
SimpleNamespace(prompt_len=np.array([1, 1], dtype=np.int32)),
|
||||
)
|
||||
state.model.preprocess.assert_not_called()
|
||||
assert [info["req_id"] for info in batch_calls[0]] == ["r1", "r2"]
|
||||
assert torch.equal(model_inputs["input_ids"], torch.tensor([111, 212]))
|
||||
assert state.intermediate_buffer.buffers[0]["meta"]["step"] == 11
|
||||
assert torch.equal(seen_prepacked[0][0], torch.tensor([[31.0, 32.0], [41.0, 42.0]]))
|
||||
|
||||
|
||||
def test_static_decode_embeddings_refresh_from_input_ids():
|
||||
# FULL-graph replay reads the static buffer: it must hold fresh embeddings.
|
||||
state = _make_state(has_preprocess=True)
|
||||
static_embeds = torch.zeros(1, 4)
|
||||
state._static_inputs_embeds = static_embeds
|
||||
expected = torch.tensor([[1.0, 2.0, 3.0, 4.0]])
|
||||
state.model.embed_input_ids = lambda input_ids: expected.to(input_ids.device)
|
||||
state.model.preprocess = lambda input_ids, input_embeds, **_info: (input_ids, input_embeds, {})
|
||||
state.intermediate_buffer.buffers[0] = {"req_id": "r1"}
|
||||
state.run_preprocess(
|
||||
_DummyInputBatch([0]),
|
||||
{"input_ids": torch.tensor([1049], dtype=torch.long), "inputs_embeds": static_embeds[:1]},
|
||||
)
|
||||
assert torch.equal(static_embeds, expected)
|
||||
original = torch.tensor([[1.0, 2.0]])
|
||||
assert OmniModelState._preprocess_result_needs_writeback(original, original) is False
|
||||
assert OmniModelState._preprocess_result_needs_writeback(original, original.view_as(original)) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("owned", [False, True])
|
||||
def test_batched_postprocess_gpu_snapshot_writeback(owned):
|
||||
# batch=[1, 0]: last-token indices follow the reordered batch, the scalar
|
||||
# hook is not called, and both rows share one snapshot storage so a later
|
||||
# graph replay cannot overwrite published rows. Owned producer batches
|
||||
# skip the extra snapshot while borrowed graph output still gets one.
|
||||
state = _make_state(max_num_reqs=2, has_postprocess=True)
|
||||
state.model.gpu_resident_buffer_keys = {("hidden_states", "last")}
|
||||
_fill_buffers(state, "r0", "r1")
|
||||
state.model.postprocess = MagicMock(side_effect=AssertionError("batch hook must replace scalar postprocess"))
|
||||
calls = []
|
||||
produced = []
|
||||
|
||||
def postprocess_batch(*, hidden_states, last_token_indices):
|
||||
calls.append(last_token_indices.clone())
|
||||
gathered = hidden_states.index_select(0, last_token_indices)
|
||||
produced.append(gathered)
|
||||
if owned:
|
||||
return (("hidden_states", "last"), OwnedBatchTensor(gathered))
|
||||
return (("hidden_states", "last"), gathered)
|
||||
|
||||
state.model.postprocess_batch_mrv2 = postprocess_batch
|
||||
batch = _DummyInputBatch([1, 0])
|
||||
batch.num_scheduled_tokens = [2, 2]
|
||||
batch.query_start_loc_np = [0, 2]
|
||||
batch.query_start_loc = torch.tensor([0, 2, 4], dtype=torch.int32)
|
||||
hidden = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]])
|
||||
state.run_postprocess(hidden, batch)
|
||||
|
||||
state.model.postprocess.assert_not_called()
|
||||
assert torch.equal(calls[0], torch.tensor([1, 3], dtype=torch.int32))
|
||||
first = state.intermediate_buffer.buffers[0]["hidden_states"]["last"]
|
||||
second = state.intermediate_buffer.buffers[1]["hidden_states"]["last"]
|
||||
assert torch.equal(first, hidden[3])
|
||||
assert torch.equal(second, hidden[1])
|
||||
assert first.untyped_storage().data_ptr() == second.untyped_storage().data_ptr()
|
||||
if owned:
|
||||
# Owned output: rows view into the producer batch, no extra snapshot.
|
||||
assert first.untyped_storage().data_ptr() == produced[0].untyped_storage().data_ptr()
|
||||
else:
|
||||
# Borrowed/graph output: the snapshot owns its storage, not the producer.
|
||||
assert first.untyped_storage().data_ptr() != produced[0].untyped_storage().data_ptr()
|
||||
|
||||
|
||||
def test_seed_independence_resolve_once_and_sampling_kwargs():
|
||||
state = _make_state(max_num_reqs=2)
|
||||
# vLLM sampling seed must not produce a talker generator.
|
||||
cpu = torch.device("cpu")
|
||||
assert state._get_mtp_generator("r1", SimpleNamespace(extra_args={}, seed=42), cpu) is None
|
||||
# Same model-local seed reproduces identical uniforms regardless of batch makeup.
|
||||
state._mtp_sample_uniforms = torch.empty((2, 2, 4))
|
||||
assert torch.equal(
|
||||
state._prepare_mtp_sample_uniforms([torch.Generator().manual_seed(11)], 1).clone(),
|
||||
state._prepare_mtp_sample_uniforms([torch.Generator().manual_seed(11)], 1),
|
||||
)
|
||||
# Per-request generators are resolved once per step and ride sampling kwargs.
|
||||
state.model.mtp_sampling_params = {"do_sample": True, "temperature": 0.7}
|
||||
state.model.mtp_accepts_per_row_generators = True
|
||||
_init_static(state, 2)
|
||||
state.intermediate_buffer.buffers[0] = {"req_id": "r0", "sampling_params": _seeded(11)}
|
||||
state.intermediate_buffer.buffers[1] = {"req_id": "r1", "sampling_params": _seeded(22)}
|
||||
resolver = MagicMock(wraps=state._get_mtp_generator)
|
||||
state._get_mtp_generator = resolver
|
||||
|
||||
def mtp(input_ids, input_embeds, last_hidden, text_step, **kwargs):
|
||||
assert (kwargs["do_sample"], kwargs["temperature"]) == (True, 0.7)
|
||||
assert all(isinstance(g, torch.Generator) for g in kwargs["generators"])
|
||||
return input_embeds + 10, torch.tensor([[1, 2, 3], [4, 5, 6]])
|
||||
|
||||
state.model.mtp = mtp
|
||||
state._run_batched_mtp(
|
||||
_mtp_batches(), torch.tensor([101, 202]), torch.zeros(2, 3), _DummyInputBatch([0, 1]), {("codes", "audio")}
|
||||
)
|
||||
assert resolver.call_count == 2
|
||||
assert torch.equal(state.intermediate_buffer.buffers[0]["codes"]["audio"], torch.tensor([[1, 2, 3]]))
|
||||
assert torch.equal(state.intermediate_buffer.buffers[1]["codes"]["audio"], torch.tensor([[4, 5, 6]]))
|
||||
|
||||
|
||||
def test_seeded_mtp_bypasses_outer_graph_runner():
|
||||
state = _make_state(max_num_reqs=2)
|
||||
raw_calls = []
|
||||
|
||||
def mtp(*args, **kwargs):
|
||||
raw_calls.append(kwargs)
|
||||
return args[1], args[0].reshape(-1, 1)
|
||||
|
||||
state.model.mtp = mtp
|
||||
state._mtp_runner = MagicMock(side_effect=AssertionError("seeded sampling must not replay the graph"))
|
||||
generators = [torch.Generator().manual_seed(11), torch.Generator().manual_seed(22)]
|
||||
state._call_mtp_runner(
|
||||
torch.tensor([101, 202]), torch.zeros(2, 3), torch.zeros(2, 3), torch.zeros(2, 3), generators=generators
|
||||
)
|
||||
assert raw_calls == [{"generators": generators}]
|
||||
state._mtp_runner.assert_not_called()
|
||||
|
||||
|
||||
def test_run_batched_mtp_uses_dispatched_graph_descriptor():
|
||||
state = _make_state(max_num_reqs=4)
|
||||
|
||||
class _FakeGraphRunner:
|
||||
def __call__(self, input_ids, input_embeds, last_hidden, text_step, **kwargs):
|
||||
assert input_ids.shape[0] == 4 # graph runs the padded descriptor size
|
||||
return input_embeds + 2, torch.arange(12, dtype=torch.long).reshape(4, 3)
|
||||
|
||||
state._mtp_runner = _FakeGraphRunner()
|
||||
_init_static(state, 4)
|
||||
_fill_buffers(state, "r0", "r1")
|
||||
graph_desc = SimpleNamespace(cg_mode="FULL", num_tokens=4)
|
||||
set_ctx = MagicMock(return_value=nullcontext())
|
||||
with (
|
||||
patch(
|
||||
"vllm_omni.worker_v2.model_states.omni_model_state.current_omni_platform.get_graph_wrapper_cls",
|
||||
return_value=_FakeGraphRunner,
|
||||
),
|
||||
patch("vllm.forward_context.set_forward_context", set_ctx),
|
||||
):
|
||||
state._run_batched_mtp(
|
||||
_mtp_batches(),
|
||||
torch.tensor([101, 202]),
|
||||
torch.zeros(2, 3),
|
||||
_DummyInputBatch([0, 1]),
|
||||
{("codes", "audio")},
|
||||
lambda bsz: graph_desc,
|
||||
)
|
||||
_, kwargs = set_ctx.call_args
|
||||
assert kwargs["batch_descriptor"] is graph_desc
|
||||
assert kwargs["num_tokens"] == 4
|
||||
assert torch.equal(state.intermediate_buffer.buffers[0]["codes"]["audio"], torch.tensor([[0, 1, 2]]))
|
||||
assert torch.equal(state.intermediate_buffer.buffers[1]["codes"]["audio"], torch.tensor([[3, 4, 5]]))
|
||||
|
||||
|
||||
def test_rope_shim_propagates_type_error():
|
||||
# vLLM rope API drift (TypeError) must not be swallowed by the shim.
|
||||
def broken_get_rope(*_args, **_kwargs):
|
||||
raise TypeError("vLLM rope API drift")
|
||||
|
||||
with pytest.raises(TypeError, match="rope API drift"):
|
||||
_make_safe_get_rope(broken_get_rope)(SimpleNamespace(uses_mrope=False), object())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("output_key", [None, ("only_one",)])
|
||||
def test_mtp_requires_model_declared_output_key(output_key):
|
||||
state = _make_state()
|
||||
model = SimpleNamespace(mtp=lambda: None, mtp_output_key=output_key)
|
||||
with pytest.raises(TypeError, match="must declare mtp_output_key"):
|
||||
state._init_mtp_runner(model)
|
||||
Reference in new issue
Block a user