[Rebase] Rebase to vLLM 0.30.0 (#7820)

Signed-off-by: tzhouam <tzhouam@connect.ust.hk>
Signed-off-by: Gao Han <hgaoaf@connect.ust.hk>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
This commit is contained in:
authored and GitHub committed 2026-09-22 15:52:01 +00:00
1 parent ca14e635f5
commit 59db6a4285
59 files changed
+1032 -300

No files matched your search

+34
View File
@@ -20,6 +20,7 @@ from vllm_omni.benchmarks.data_modules.seed_tts_dataset import (
SeedTTSSampleRequest,
SeedTTSTextSampleRequest,
)
from vllm_omni.benchmarks.patch import patch
from vllm_omni.benchmarks.patch.patch import (
MixRequestFuncOutput,
_add_combined_video_form_references,
@@ -2011,3 +2012,36 @@ def test_image_metrics_persist_stage_durations_from_metrics() -> None:
if __name__ == "__main__":
pytest.main([__file__, "-v", "-s"])
def test_get_samples_forwards_upstream_multimodal_backends_kwarg(mocker: MockerFixture) -> None:
"""The patched ``datasets.get_samples`` must stay call-compatible upstream.
Upstream ``vllm.benchmarks.datasets.get_samples`` takes a keyword-only
``multimodal_backends`` (``vllm/benchmarks/throughput.py`` passes it) and
``patch.py`` rebinds that symbol module-wide, so a non-omni request must
forward the keyword to the original implementation instead of raising
``TypeError`` or silently dropping it.
"""
calls: list[tuple[Namespace, object, dict]] = []
def fake_get_samples_old(args, tokenizer, **kwargs):
calls.append((args, tokenizer, kwargs))
return ["delegated"]
mocker.patch.object(patch, "get_samples_old", fake_get_samples_old)
args = Namespace(
dataset_name="random",
backend="vllm-chat",
dataset_path=None,
hf_name=None,
)
sentinel = object()
mm_backends = ("openai-chat", "openai-audio")
assert patch.get_samples(args, sentinel, multimodal_backends=mm_backends) == ["delegated"]
assert calls == [(args, sentinel, {"multimodal_backends": mm_backends})]
# No upstream kwargs: unchanged legacy delegate call.
assert patch.get_samples(args, sentinel) == ["delegated"]
assert calls[-1] == (args, sentinel, {})
@@ -66,18 +66,25 @@ def _make_generation_scheduler(waiting_request, *, use_v2_model_runner=False):
scheduler.log_stats = False
scheduler.scheduler_config = SimpleNamespace(enable_chunked_prefill=True)
scheduler.num_lookahead_tokens = 0
scheduler.num_spec_tokens = 0
scheduler.dynamic_sd_lookup = None
scheduler.reset_preempted_req_ids = set()
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,
take_new_block_ids=lambda: [],
take_boundary_state_offloads=lambda: {},
)
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.encoder_cache_manager = SimpleNamespace(
get_freed_mm_hashes=lambda: [],
get_manager_metadata=lambda: None,
)
scheduler.connector = None
scheduler.ec_connector = None
scheduler.prev_step_scheduled_req_ids = set()
@@ -137,7 +137,7 @@ def _make_scheduler_stub(requests: list[_Request]) -> SimpleNamespace:
running=list(requests),
waiting=_RequestQueue(),
skipped_waiting=_RequestQueue(),
structured_output_manager=SimpleNamespace(should_advance=lambda _request: False),
structured_output_manager=SimpleNamespace(accept_tokens=lambda _request, _token_ids: True),
transfer_triggered_requests=set(),
active_kv_transfers=set(),
pending_stop_after_extraction=set(),
@@ -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
"""Investigation tests for the num_stale_output_tokens drain (59b9e719).
@@ -89,7 +89,7 @@ def _make_drain_sched(session: Request) -> MagicMock:
sched = MagicMock()
sched.requests = {session.request_id: session}
sched.perf_metrics = None
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
sched._update_request_with_output.return_value = ([42], False)
sched._process_kv_transfer_trigger.return_value = False
sched.chunk_transfer_adapter = MagicMock()
@@ -150,7 +150,7 @@ def _run_resumable_segment_stop(
sched = MagicMock()
sched.requests = {session.request_id: session}
sched.perf_metrics = None
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
def stop_request(request: Request, _token_ids: list[int]):
request.status = RequestStatus.FINISHED_STOPPED
@@ -298,7 +298,7 @@ def test_running_decode_step_without_inter_stage_payload_does_not_raise() -> Non
sched = MagicMock()
sched.requests = {session.request_id: session}
sched.perf_metrics = None
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
sched._update_request_with_output.return_value = ([42], False)
sched._process_kv_transfer_trigger.return_value = False
sched.chunk_transfer_adapter = MagicMock()
@@ -381,7 +381,7 @@ def test_stale_async_frame_is_dropped_before_output_processing() -> None:
sched = MagicMock()
sched.requests = {session.request_id: session}
sched.perf_metrics = None
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
def discard_stale_output(request: Request, token_ids: list[int]) -> tuple[list[int], bool]:
request.async_tokens_to_discard = 0
@@ -1,3 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Unit tests for generation streaming session replacement.
These tests pin the behavior of `_update_request_as_session` against
@@ -20,7 +23,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.engine import EngineCoreEventType
from vllm.v1.engine import EngineCoreEventType, FinishReason
from vllm.v1.metrics.stats import PrefillStats
from vllm.v1.outputs import ModelRunnerOutput
from vllm.v1.request import Request, RequestStatus, StreamingUpdate
@@ -130,7 +133,7 @@ def test_resumable_generation_stop_marks_segment_boundary() -> None:
sched.running = [session]
sched.waiting = MagicMock()
sched.skipped_waiting = MagicMock()
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
# Async scheduling can observe the segment boundary in the next schedule()
# before this model output is applied and defer the same request for finish.
# update_from_output() must not re-arm the resumable request twice.
@@ -171,6 +174,77 @@ def test_resumable_generation_stop_marks_segment_boundary() -> None:
assert sched._pending_finish_reqs == []
@pytest.mark.parametrize("prompt_complete", [False, True])
def test_rejected_grammar_finishes_and_frees_generation_request(prompt_complete: bool) -> None:
session = _make_request(request_id="req-generation-segment")
session.status = RequestStatus.RUNNING
session.resumable = True
session.num_computed_tokens = len(session.prompt_token_ids) if prompt_complete else 1
# schedule() has counted this step's token as in flight; update_from_output()
# must settle it before handling the segment boundary.
session.num_in_flight_tokens = 1
sched = MagicMock()
sched.requests = {session.request_id: session}
sched.perf_metrics = None
sched.chunk_transfer_adapter = SimpleNamespace(
is_done_receiving_chunks=lambda _request_id: True,
segment_finished_requests={session.request_id},
)
sched._async_chunk_transport_enabled.return_value = False
sched._native_data_plane = False
sched._handle_stopped_request.return_value = True
sched._free_request.return_value = (None, None)
sched.chunk_transfer_adapter.cleanup = MagicMock()
sched.running = [session]
sched._remove_stopped_requests_from_queues.side_effect = lambda running, preempted: (
OmniSchedulerMixin._remove_stopped_requests_from_queues(sched, running, preempted)
)
sched.waiting = MagicMock()
sched.skipped_waiting = MagicMock()
sched.structured_output_manager.accept_tokens.return_value = False
sched._pending_finish_reqs = []
sched.recompute_kv_load_failures = False
sched.connector = None
sched.kv_cache_manager.take_events.return_value = None
sched.kv_cache_manager.estimate_cached_tokens.return_value = 0
sched.finished_req_ids_dict = {}
sched.make_stats.return_value = None
scheduler_output = MagicMock(spec=SchedulerOutput)
scheduler_output.num_scheduled_tokens = {session.request_id: 1}
scheduler_output.scheduled_spec_decode_tokens = {}
scheduler_output.num_invalid_spec_tokens = 0
model_runner_output = MagicMock(spec=ModelRunnerOutput)
model_runner_output.sampled_token_ids = [[7]]
model_runner_output.logprobs = None
model_runner_output.prompt_logprobs_dict = {}
model_runner_output.pooler_output = None
model_runner_output.num_nans_in_logits = None
model_runner_output.kv_connector_output = None
model_runner_output.cudagraph_stats = None
model_runner_output.req_id_to_index = {session.request_id: 0}
model_runner_output.routed_experts = None
outputs = OmniGenerationScheduler.update_from_output(
sched,
scheduler_output,
model_runner_output,
)
output = outputs[session.client_index].outputs[0]
assert output.finish_reason == session.get_finished_reason() == FinishReason.ERROR
assert not output.is_segment_finished
assert session.status == RequestStatus.FINISHED_ERROR
assert session.resumable is False
sched._handle_stopped_request.assert_called_once_with(session)
sched._free_request.assert_called_once_with(session)
sched.chunk_transfer_adapter.cleanup.assert_called_once()
assert session not in sched.running
def test_async_chunk_resumable_stop_rearms_connector_polling() -> None:
sched = _AsyncChunkStopSchedulerStub()
session = _make_request(request_id="req-async-chunk-next-segment")
@@ -123,7 +123,7 @@ def _make_finish_sched(request: Request) -> MagicMock:
sched.requests = {request.request_id: request}
sched.perf_metrics = None
sched.defer_block_free = False
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
sched._process_kv_transfer_trigger.return_value = False
sched._maybe_decode_pooling_output.return_value = None
sched._handle_stopped_request.return_value = True
@@ -56,7 +56,7 @@ def _make_sched(request: Request) -> MagicMock:
sched.requests = {request.request_id: request}
sched.perf_metrics = None
sched.defer_block_free = False
sched.structured_output_manager.should_advance.return_value = False
sched.structured_output_manager.accept_tokens.return_value = True
sched._process_kv_transfer_trigger.return_value = False
sched._maybe_decode_pooling_output.return_value = None
sched._handle_stopped_request.return_value = True
+4 -4
View File
@@ -11,7 +11,7 @@ Currently only the **GPU** backend is implemented. The backend is selected with
All functionality is provided by a single script and should be run from the repository root:
| Subcommand | Description |
|--------|------|
| -------- | ------ |
| `scripts/resource_monitor.sh start [--backend gpu\|cpu\|npu] [gpu_ids] [interval]` | Collect data in the background (currently only `gpu`: `nvidia-smi` writes CSV) |
| `scripts/resource_monitor.sh finalize [--backend gpu\|cpu\|npu] [run_id]` | Bundle the current run, generate `report.html`, and print `GPU_MONITOR_BUNDLE_DIR=` / `RESOURCE_MONITOR_BUNDLE_DIR=` |
| `scripts/resource_monitor.sh run [--backend gpu\|cpu\|npu] -- <command>` | Complete everything in one step: `start` -> run your command -> `finalize` |
@@ -23,7 +23,7 @@ All functionality is provided by a single script and should be run from the repo
## Environment Variables (monitoring script only)
| Environment Variable | Description | Default |
|----------|------|--------|
| ---------- | ------ | -------- |
| `RESOURCE_MONITOR_DATA_ROOT` | Root directory for monitoring data | `tests/dfx/stability/gpu_monitor_data` |
| `RESOURCE_MONITOR_INTERVAL` | Sampling interval (seconds) | 5 |
| `RESOURCE_MONITOR_LOG_INTERVAL` | Log print interval (seconds) | 15 |
@@ -83,8 +83,8 @@ echo "Report directory: $GPU_MONITOR_BUNDLE_DIR"
- **Scripts**: `tests/dfx/stability/scripts/resource_monitor.sh` (entry point) and `scripts/generate_report.py` (called by `finalize` to generate HTML).
- **Data directory**: `tests/dfx/stability/gpu_monitor_data/` by default (can be overridden with `RESOURCE_MONITOR_DATA_ROOT`).
- Each run generates `run_<run_id>/gpu_metrics.csv`.
- After `finalize`, you get `gpu_monitor_bundle_<run_id>/` containing `gpu_metrics.csv`, `report.html`, and `README.txt`.
- Each run generates `run_<run_id>/gpu_metrics.csv`.
- After `finalize`, you get `gpu_monitor_bundle_<run_id>/` containing `gpu_metrics.csv`, `report.html`, and `README.txt`.
- **View the report**: open `report.html` in the bundle directory with a browser to inspect memory usage curves and statistics.
The script only generates `report.html` and CSV files. If you need to keep the report, archive or download it from the working directory yourself.
@@ -279,19 +279,19 @@ def _install_native_modules(monkeypatch: pytest.MonkeyPatch, events: list[tuple]
group = SimpleNamespace(get_metadata_builder=lambda _index: SimpleNamespace(reorder_batch_threshold=None))
return [[group], [group]], "cg-support", [4, 8]
# vLLM 0.29 dropped attn_groups and cache_dtype from init_kv_cache: the
# layout now rides on the resolved CacheConfig.kv_cache_layout instead.
# f2aad6aa70 (#56888): first arg is forward_context; return a cache dict.
def init_cache(
runner_kv_caches,
forward_context,
kv_cache_config,
device,
kernel_block_sizes,
vllm_config,
kv_cache_allocation_context=None,
*,
block_tables=None,
):
events.append(("cache", kv_cache_config, kernel_block_sizes))
runner_kv_caches.extend(["cache-0", "cache-1"])
return {"layer-0": "tensor-0", "layer-1": "tensor-1"}
return {"layer-0": "cache-0", "layer-1": "cache-1"}
monkeypatch.setattr(model_runner_backend_module, "init_attn_backend", init_backend)
monkeypatch.setattr(model_runner_backend_module, "init_kv_cache", init_cache)
@@ -431,8 +431,7 @@ def test_initialize_failure_does_not_publish_partial_cache_state(
],
)
def fail_init_cache(runner_kv_caches, *_args, **_kwargs):
runner_kv_caches.append("partial-cache")
def fail_init_cache(forward_context, *_args, **_kwargs):
backend._kv_cache_layer_adapters["layer-0"].kv_cache = "partial-binding"
raise RuntimeError("cache binding failed")
@@ -24,7 +24,16 @@ def producer(monkeypatch):
worker.shutdown = Mock() # No hardware constructor, sockets or listener thread.
worker.is_kv_consumer = False
worker.tp_rank, worker.tp_size = 0, 1
worker.transfer_topo = SimpleNamespace(handshake_target_ranks=lambda size: list(range(size)))
worker.transfer_topo = SimpleNamespace(
handshake_target_ranks=lambda size: list(range(size)),
total_num_kv_heads=1,
)
# vLLM 0.30 send_kv_to_decode also reads the PP size (ce08bb5b34,
# #56033), the MLA/Mamba flags and the head-resharding validator.
worker.pp_size = 1
worker.use_mla = False
worker.kv_cache_config = SimpleNamespace(has_mamba_layers=False)
worker._validate_head_resharding_layout = Mock(return_value=None)
worker.reqs_need_send, worker.finished_sending_reqs = {}, set()
for name in (
"kv_caches_base_addr",
@@ -42,7 +51,9 @@ def producer(monkeypatch):
worker._send_blocks = Mock(return_value=0)
worker.xfer_stats = Mock()
worker._build_transfer_params = AsyncMock(return_value=([1], [2], [16], [], None))
monkeypatch.setattr(mc, "_align_transfer_regions", lambda *_: ([], [], None))
# vLLM ce08bb5b34 (#56033) calls _align_transfer_regions with the
# allow_partial_layers keyword; the stub must accept it.
monkeypatch.setattr(mc, "_align_transfer_regions", lambda *_, **__: ([], [], None))
monkeypatch.setattr(mc, "_validate_asymmetric_region_lengths", lambda **_: None)
monkeypatch.setattr(mc.envs, "VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", 0.05)
connector = object.__new__(mc.MooncakeConnector)
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from collections.abc import Iterator
from types import SimpleNamespace
from unittest.mock import Mock
@@ -526,23 +527,30 @@ def test_drain_after_terminal_request_state_was_popped(monkeypatch):
@pytest.mark.parametrize("prefetch", [False, True])
def test_real_active_connector_starts_required_load_before_polling(prefetch):
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
def test_real_active_connector_starts_required_load_before_polling(prefetch, monkeypatch):
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorBase_V1
from vllm.v1.worker.gpu import kv_connector as native_kv_connector
from vllm_omni.diffusion.diffusion_kv.kv_connector import wait_for_kv_load
active = object.__new__(ActiveKVConnector)
active._disabled = False
active._pending_load_start = False
active.kv_connector = Mock()
active.kv_connector.get_block_ids_with_load_errors.return_value = set()
active._start_load_kv = Mock()
connector = Mock(spec=KVConnectorBase_V1)
connector.get_block_ids_with_load_errors.return_value = set()
# Exercise upstream's compatibility adapter instead of returning an
# unconstrained Mock from the v0.30 get_transfer_results API.
connector.get_transfer_results.side_effect = lambda ids: KVConnectorBase_V1.get_transfer_results(connector, ids)
monkeypatch.setattr(native_kv_connector, "get_kv_transfer_group", lambda: connector)
context = object()
monkeypatch.setattr(native_kv_connector, "is_forward_context_available", lambda: True)
monkeypatch.setattr(native_kv_connector, "get_forward_context", lambda: context)
active = native_kv_connector.ActiveKVConnector(Mock(), {})
completions: Iterator[tuple[set[str], set[str]]] = iter([(set(), {"A0"}), (set(), set())])
def finished(_):
active._start_load_kv.assert_called_once()
return set(), {"A0"}
connector.start_load_kv.assert_called_once_with(context)
return next(completions)
active.kv_connector.get_finished.side_effect = finished
connector.get_finished.side_effect = finished
output = _output(submit=["A0"], required=["A0"], metadata=object())
if prefetch:
result = KVReceiveProgress().prepare(active, output, 1)
@@ -550,3 +558,6 @@ def test_real_active_connector_starts_required_load_before_polling(prefetch):
output.kv_required_request_ids = None
result = wait_for_kv_load(active, output, 1)
assert result.finished_recving == {"A0"}
assert result.finished_sending == set()
connector.get_transfer_results.assert_called_once_with(set())
connector.start_load_kv.assert_called_once_with(context)
@@ -106,11 +106,9 @@ def _native_adapter(num_rows: int = 1):
vllm_config,
device,
)
runner_kv_caches: list[torch.Tensor | list[torch.Tensor]] = []
# vLLM 0.29 dropped attn_groups and cache_dtype here: the layout now
# comes from the resolved CacheConfig.kv_cache_layout inside the call.
# f2aad6aa70 (#56888): init_kv_cache no longer mutates a runner list;
# first arg is forward_context and the allocated caches are returned.
init_kv_cache(
runner_kv_caches,
vllm_config.compilation_config.static_forward_context,
kv_cache_config,
device,
@@ -178,7 +178,13 @@ class TestGlmImageAdaLayerNormZeroQuantization:
def test_accepts_quant_config_parameter(self, mocker: MockerFixture):
"""Verify the class accepts quant_config parameter."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
layer = GlmImageAdaLayerNormZero(
embedding_dim=512,
dim=2560,
@@ -220,7 +226,13 @@ class TestGlmImageAdaLayerNormContinuousQuantization:
def test_accepts_quant_config_parameter(self, mocker: MockerFixture):
"""Verify the class accepts quant_config parameter."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
layer = GlmImageAdaLayerNormContinuous(
embedding_dim=2560,
conditioning_embedding_dim=512,
@@ -260,7 +272,13 @@ class TestGlmImageAttentionQuantization:
def test_accepts_quant_config_parameter(self, mocker: MockerFixture):
"""Verify GlmImageAttention accepts quant_config parameter."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
attn = GlmImageAttention(
dim=2560,
num_heads=64,
@@ -286,7 +304,13 @@ class TestColumnParallelModulesQuantization:
def test_column_parallel_gelu_accepts_quant_config(self, mocker: MockerFixture):
"""Verify ColumnParallelGELU accepts quant_config."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
layer = ColumnParallelGELU(
dim_in=2560,
dim_out=10240,
@@ -297,7 +321,13 @@ class TestColumnParallelModulesQuantization:
def test_column_parallel_silu_accepts_quant_config(self, mocker: MockerFixture):
"""Verify ColumnParallelSiLU accepts quant_config."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
layer = ColumnParallelSiLU(
dim_in=2560,
dim_out=10240,
@@ -312,7 +342,13 @@ class TestGlmImageFeedForwardQuantization:
def test_accepts_quant_config_parameter(self, mocker: MockerFixture):
"""Verify GlmImageFeedForward accepts quant_config parameter."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
ff = GlmImageFeedForward(
dim=2560,
dim_out=2560,
@@ -358,7 +394,13 @@ class TestGlmImageTransformerBlockQuantization:
def test_accepts_quant_config_parameter(self, mocker: MockerFixture):
"""Verify GlmImageTransformerBlock accepts quant_config parameter."""
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
parallel_config = DiffusionParallelConfig(
tensor_parallel_size=1,
sequence_parallel_size=1,
@@ -534,7 +576,13 @@ class TestGlmImageTransformer2DModelQuantization:
"""Verify the model accepts quant_config parameter."""
from vllm_omni.diffusion.data import OmniDiffusionConfig
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
parallel_config = DiffusionParallelConfig(
tensor_parallel_size=1,
sequence_parallel_size=1,
@@ -607,7 +655,13 @@ class TestGlmImageTransformer2DModelQuantization:
"""Verify norm_out (output layer) does NOT use quantization to preserve precision."""
from vllm_omni.diffusion.data import OmniDiffusionConfig
# vLLM 0.30 resolves online quantization in resolve_quant_method():
# a non-None online_quantization_config whose resolve_quant_method_cls()
# returns a target raises on a checkpoint-quantized layer. A bare
# MagicMock satisfies both, so declare no online quantization -- these
# tests only assert the layer accepts and stores a quant_config.
mock_quant_config = mocker.MagicMock()
mock_quant_config.online_quantization_config = None
parallel_config = DiffusionParallelConfig(
tensor_parallel_size=1,
sequence_parallel_size=1,
@@ -1380,6 +1380,8 @@ def test_text_encoder_linear_delegates_quantization_to_vllm_factory():
method = UnquantizedLinearMethod()
quant_config = Mock()
quant_config.get_quant_method.return_value = method
# vLLM 0.30: no online quantization for this checkpoint-quantized layer
quant_config.online_quantization_config = None
prefix = "text_encoder.text_model.layers.0.mlp.gate_up_proj"
with (
@@ -1396,7 +1398,9 @@ def test_text_encoder_linear_delegates_quantization_to_vllm_factory():
)
assert linear.quant_method is method
quant_config.get_quant_method.assert_called_once_with(linear, prefix=prefix)
# vLLM 0.30 resolves the method through resolve_quant_method(), which calls
# get_quant_method(layer, prefix) POSITIONALLY; 0.29 passed prefix= by keyword.
quant_config.get_quant_method.assert_called_once_with(linear, prefix)
def test_distributed_layerwise_offload_stages_vae_component():
@@ -2391,7 +2391,7 @@ def test_generation_scheduler_calls_cleanup_on_finished(monkeypatch, mocker: Moc
scheduler.log_stats = False
scheduler.recompute_kv_load_failures = False
scheduler.structured_output_manager = mocker.MagicMock()
scheduler.structured_output_manager.should_advance.return_value = False
scheduler.structured_output_manager.accept_tokens.return_value = True
scheduler.finished_req_ids_dict = {}
scheduler.kv_cache_manager.take_events.return_value = None
scheduler.kv_cache_manager.estimate_cached_tokens.return_value = 0
@@ -2471,7 +2471,7 @@ def test_ar_scheduler_defers_cleanup_and_queues_save_on_finished(mocker: MockerF
scheduler.log_stats = False
scheduler.recompute_kv_load_failures = False
scheduler.structured_output_manager = mocker.MagicMock()
scheduler.structured_output_manager.should_advance.return_value = False
scheduler.structured_output_manager.accept_tokens.return_value = True
scheduler.finished_req_ids_dict = {}
scheduler.kv_cache_manager = mocker.MagicMock()
scheduler.kv_cache_manager.take_events.return_value = None
@@ -2979,7 +2979,7 @@ def _build_deferred_finish_scheduler(mocker, *, running, pending_finish_reqs):
scheduler.log_stats = False
scheduler.recompute_kv_load_failures = False
scheduler.structured_output_manager = mocker.MagicMock()
scheduler.structured_output_manager.should_advance.return_value = False
scheduler.structured_output_manager.accept_tokens.return_value = True
scheduler.finished_req_ids_dict = {}
scheduler.kv_cache_manager.take_events.return_value = None
scheduler.kv_cache_manager.estimate_cached_tokens.return_value = 0
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
import pytest
import torch
from vllm_omni.model_executor.models.indextts2 import codec as codec_module
@@ -84,10 +85,33 @@ def test_model_asset_resolver_supports_native_checkpoints_layout(tmp_path):
assert preprocess_utils.resolve_model_file(str(tmp_path), "codec.pth") == str(checkpoint)
def test_campplus_falls_back_to_hub_for_local_model_dir(tmp_path, monkeypatch):
import huggingface_hub
def test_campplus_local_dir_does_not_silently_download(tmp_path, monkeypatch):
"""A local bundle missing CAMPPlus must fail closed, not hit the Hub.
origin/main ``load_campplus`` treats ``os.path.isdir(model_path)`` as a
complete local snapshot and raises FileNotFoundError instead of
downloading ``funasr/campplus``. The old test name
``test_campplus_falls_back_to_hub_for_local_model_dir`` encoded the
pre-guard behavior.
"""
from vllm_omni.model_executor.models.indextts2.utils.campplus import dtdnn
class FakeCAMPPlus(torch.nn.Module):
def load_state_dict(self, state, strict=True):
self.loaded_state = (state, strict)
monkeypatch.setattr(dtdnn, "CAMPPlus", lambda **_kwargs: FakeCAMPPlus())
preprocess_utils._campplus_cache.clear()
with pytest.raises(FileNotFoundError, match="CAMPPlus checkpoint is missing from local bundle"):
preprocess_utils.load_campplus(str(tmp_path), torch.device("cpu"))
def test_campplus_falls_back_to_hub_for_repo_id(tmp_path, monkeypatch):
from types import SimpleNamespace
from vllm_omni.model_executor.models.indextts2.utils.campplus import dtdnn
from vllm_omni.transformers_utils import repo_utils
checkpoint = tmp_path / "downloaded-campplus.bin"
checkpoint.touch()
@@ -99,14 +123,16 @@ def test_campplus_falls_back_to_hub_for_local_model_dir(tmp_path, monkeypatch):
monkeypatch.setattr(dtdnn, "CAMPPlus", lambda **_kwargs: FakeCAMPPlus())
monkeypatch.setattr(
huggingface_hub,
"hf_hub_download",
lambda repo_id, filename: downloads.append((repo_id, filename)) or str(checkpoint),
repo_utils,
"hf_api",
lambda: SimpleNamespace(
hf_hub_download=lambda repo_id, filename: downloads.append((repo_id, filename)) or str(checkpoint)
),
)
monkeypatch.setattr(preprocess_utils.torch, "load", lambda *_args, **_kwargs: {"weight": torch.ones(1)})
preprocess_utils._campplus_cache.clear()
model = preprocess_utils.load_campplus(str(tmp_path), torch.device("cpu"))
model = preprocess_utils.load_campplus("IndexTeam/IndexTTS-2", torch.device("cpu"))
assert isinstance(model, FakeCAMPPlus)
assert downloads == [("funasr/campplus", "campplus_cn_common.bin")]
@@ -7,27 +7,37 @@ ModelOpt 0.44's FP32->FP8 E4M3 cast of per-block weight scales can emit
literal NaN bytes (E4M3 encoding 0x7F / 0xFF) when the pre-cast scale
rounds above the FP8 max of 448 after the global-scale division. A
single NaN byte in any per-block weight_scale collapses the FlashInfer
FP4 GEMM output to NaN and the served model emits `!!!!`. The patch
overrides ``ModelOptNvFp4LinearMethod.process_weights_after_loading``
FP4 GEMM output to NaN and the served model emits `!!!!`. On the legacy
pin the patch overrides ``ModelOptNvFp4LinearMethod.process_weights_after_loading``
to scan + clamp those bytes at load time.
These tests cover the behavior of the override on a synthetic layer:
vLLM #49381 replaced that class with the generic ``ModelOptLinearMethod``
(and the ``LinearMethodCls`` attributes) and #52501 made a NaN
weight_scale a hard error there ("... was never loaded (still NaN)"), so on
that pin ``vllm_omni.patch`` self-extinguishes: it installs nothing and
upstream's load-time RuntimeError stays observable. These tests cover both
pins:
- the NaN bytes get clamped to the FP8 E4M3 max byte (0x7E)
- a finite weight_scale is left untouched (no spurious writes)
- the install asserts itself so silent fallback is impossible
- the env-var escape hatch path is reachable
- the NaN bytes get clamped to the FP8 E4M3 max byte (0x7E) [helper]
- a finite weight_scale is left untouched (no spurious writes) [helper]
- the install asserts itself so silent fallback is impossible [either pin]
- the env-var escape hatch path is reachable [either pin]
- on the redesigned pin nothing is installed on ``ModelOptLinearMethod``
and upstream's unloaded-scale RuntimeError is still raised [redesigned]
No GPU is required — the tests construct an in-memory FP8 ``weight_scale``
tensor with planted NaN bytes and call the patched PWAL directly.
tensor with planted NaN bytes and call either the patched helper or the
upstream PWAL directly.
"""
import importlib
import pytest
import torch
# Importing vllm_omni runs vllm_omni.patch, which installs the override
# we are testing. The import must come before any direct reference to
# ``ModelOptNvFp4LinearMethod`` below.
# the clamp target below.
import vllm_omni # noqa: F401
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
@@ -36,6 +46,48 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
FP8_NAN_BYTES = (0x7F, 0xFF)
FP8_MAX_BYTE = 0x7E # encoding of finfo(float8_e4m3fn).max
_MODELOPT_MODULE = "vllm.model_executor.layers.quantization.modelopt"
_LEGACY_NVFP4_LINEAR_METHOD = "ModelOptNvFp4LinearMethod"
_GENERIC_LINEAR_METHOD = "ModelOptLinearMethod"
def _resolve_target(name: str):
"""Return ``vllm.modelopt.<name>`` or None when upstream never had it.
Imports the module eagerly (a missing module is a hard upstream breakage
and must fail loudly); only the *attribute* lookup is tolerant, so
"upstream redesigned the class away" is distinguishable from "the module
moved" without swallowing real errors.
"""
modelopt = importlib.import_module(_MODELOPT_MODULE)
return getattr(modelopt, name, None)
def _resolve_legacy_target():
return _resolve_target(_LEGACY_NVFP4_LINEAR_METHOD)
def _resolve_generic_target():
return _resolve_target(_GENERIC_LINEAR_METHOD)
def _pwfn_source(cls) -> str:
"""Source file of ``cls.process_weights_after_loading``."""
fn = cls.__dict__.get("process_weights_after_loading") or cls.process_weights_after_loading
return getattr(fn, "__code__", None) and fn.__code__.co_filename or ""
def _last_stdout_line(stdout: str) -> str:
"""Last non-empty stdout line of a subprocess.
Importing ``vllm_omni`` runs ``vllm_omni.patch``, whose INFO logs land on
stdout, so a sentinel printed by the child is the *last* line, never the
first (the previous ``stdout.strip().startswith(...)`` form silently broke
as soon as the patch module logged anything).
"""
lines = [line.strip() for line in stdout.strip().splitlines() if line.strip()]
return lines[-1] if lines else ""
def _fp8_tensor_with_nan_bytes(num_blocks: int, nan_indices: list[int]) -> torch.Tensor:
"""Return an FP8 E4M3 tensor where every position is the FP8 max byte
@@ -53,9 +105,8 @@ def _fp8_tensor_with_nan_bytes(num_blocks: int, nan_indices: list[int]) -> torch
def clamp_fn():
"""Return the top-level NaN-clamp helper exposed by vllm_omni.patch.
Skipped when vllm doesn't expose ``ModelOptNvFp4LinearMethod`` (older
pin / unsupported build) and vllm_omni.patch consequently didn't
install the helper either.
Skipped when vllm_omni.patch did not expose the helper (e.g. an
incompatible vllm_omni install).
"""
try:
from vllm_omni.patch import _clamp_nvfp4_weight_scale_nans
@@ -130,36 +181,109 @@ def test_clamps_non_contiguous_weight_scale(clamp_fn):
def test_install_is_self_asserting():
# If the install assert is removed, a future regression could let the
# override silently drop. There are three legitimate end states:
# (a) upstream vLLM already has its own NaN clamp and vllm_omni.patch
# intentionally skipped installing the override (self-extinguish),
# (b) upstream is unpatched and our wrapper is installed,
# (c) the env-var escape hatch is set OR the modelopt import failed,
# (a) upstream vLLM already handles NaN weight_scale itself — either its
# own in-place clamp, or (on the redesigned generic
# ModelOptLinearMethod) a hard rejection — and vllm_omni.patch
# intentionally skipped installing the override,
# (b) upstream is unpatched (legacy per-format class) and our wrapper is
# installed,
# (c) the env-var escape hatch is set OR every modelopt target is missing,
# so nothing is installed by design — nothing to assert.
try:
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptNvFp4LinearMethod,
)
except ImportError:
pytest.skip("vllm.modelopt.ModelOptNvFp4LinearMethod not available")
legacy = _resolve_legacy_target()
if legacy is None and _resolve_generic_target() is None:
pytest.skip("no ModelOpt linear method exposed by this vLLM build")
from vllm_omni.patch import _already_patched_upstream, _clamp_installed
current = ModelOptNvFp4LinearMethod.process_weights_after_loading
name = getattr(current, "__qualname__", "") or getattr(current, "__name__", "")
if _already_patched_upstream:
# Self-extinguish path: presence of our marker here would mean the
# heuristic in vllm_omni.patch failed to detect upstream's clamp.
assert "_patched_nvfp4_pwal" not in name, (
f"vllm_omni override installed despite upstream PWAL already containing a "
f"NaN clamp ({name!r}); self-extinguish heuristic in vllm_omni.patch needs review"
)
# detection failed and we wrapped a class we must not touch.
assert not _clamp_installed, "clamp installed although upstream handles NaN weight_scale"
if legacy is not None:
name = getattr(legacy.process_weights_after_loading, "__qualname__", "") or getattr(
legacy.process_weights_after_loading, "__name__", ""
)
assert "_patched_nvfp4_pwal" not in name, (
f"vllm_omni override installed although upstream handles NaN weight_scale "
f"itself ({name!r}); the self-extinguish detection in vllm_omni.patch needs review"
)
elif _clamp_installed:
assert legacy is not None, "clamp reported installed but the legacy ModelOptNvFp4LinearMethod does not exist"
current = legacy.process_weights_after_loading
name = getattr(current, "__qualname__", "") or getattr(current, "__name__", "")
assert "patched_nvfp4_pwal" in name or "_patched_nvfp4_pwal" in name, (
f"NVFP4 NaN-clamp PWAL override does not appear installed (saw {name!r}); "
"another plugin may have re-patched ModelOptNvFp4LinearMethod"
)
else:
pytest.skip("NaN-clamp not installed by design (env-var escape hatch or import failure)")
pytest.skip("NaN-clamp not installed by design (env-var escape hatch or missing target)")
def test_no_override_on_redesigned_upstream():
"""On the redesigned ModelOpt linear path (#49381) nothing may be installed.
#52501 made any NaN weight_scale a hard load-time error there, so a clamp
would mask it and silently serve a partially loaded model. Assert both that
we installed nothing and that we did not touch the class at all.
"""
generic = _resolve_generic_target()
if generic is None:
pytest.skip("ModelOptLinearMethod not available (legacy pin)")
if _resolve_legacy_target() is not None:
pytest.skip("legacy pin: the per-format override path applies instead")
from vllm_omni.patch import _already_patched_upstream, _clamp_installed
assert not _clamp_installed, (
"the NaN clamp must not be installed on the redesigned generic ModelOptLinearMethod: "
"it would mask upstream's unloaded-weight_scale RuntimeError"
)
assert _already_patched_upstream, (
"vllm_omni.patch must record that upstream itself rejects NaN weight_scale on this pin"
)
assert not hasattr(generic.process_weights_after_loading, "_vllm_omni_wrapped_pwal"), (
"our wrapper is present on ModelOptLinearMethod.process_weights_after_loading"
)
# Stronger identity check than the marker: a monkeypatched wrapper would be
# defined in vllm_omni/patch.py, so the class attribute must still come from
# vLLM itself.
assert "vllm_omni" not in _pwfn_source(generic), (
f"ModelOptLinearMethod.process_weights_after_loading was replaced by {_pwfn_source(generic)}"
)
def _nvfp4_w4a4_method():
"""Build the generic NVFP4 W4A4 linear method exactly as upstream does."""
from types import SimpleNamespace
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptLinearMethod,
resolve,
)
spec, ctx, format_scheme = resolve("NVFP4", SimpleNamespace(group_size=16), "test")
return ModelOptLinearMethod(spec, ctx, format_scheme)
def test_upstream_nan_sentinel_check_still_reachable():
"""Upstream's unloaded-weight_scale guard must survive our import.
Drives the *public* entry point (``ModelOptLinearMethod``), not just the
scheme, so a future re-install of the override on that class would be
caught: a wrapper that clamped first would swallow the RuntimeError.
"""
if _resolve_generic_target() is None:
pytest.skip("ModelOptLinearMethod not available (legacy pin)")
method = _nvfp4_w4a4_method()
layer = torch.nn.Module()
layer.weight_scale = torch.nn.Parameter(
_fp8_tensor_with_nan_bytes(num_blocks=8, nan_indices=list(range(8))),
requires_grad=False,
)
with pytest.raises(RuntimeError, match="never loaded"):
method.process_weights_after_loading(layer)
def test_reload_does_not_nest_wrapper():
@@ -180,15 +304,13 @@ def test_reload_does_not_nest_wrapper():
"""
import importlib
import vllm_omni.patch as p
try:
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptNvFp4LinearMethod,
)
except ImportError:
print("SKIP: modelopt not available")
modelopt = importlib.import_module("vllm.model_executor.layers.quantization.modelopt")
ModelOptNvFp4LinearMethod = getattr(modelopt, "ModelOptNvFp4LinearMethod", None)
if ModelOptNvFp4LinearMethod is None:
print("SKIP: legacy modelopt target not available")
raise SystemExit(0)
if not getattr(p, "_clamp_installed", False):
print("SKIP: clamp not installed (upstream patched or escape hatch)")
print("SKIP: clamp not installed (upstream handles NaN, or escape hatch)")
raise SystemExit(0)
importlib.reload(p)
fn = ModelOptNvFp4LinearMethod.process_weights_after_loading
@@ -199,8 +321,12 @@ def test_reload_does_not_nest_wrapper():
"""
)
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=600)
if result.stdout.strip().startswith("SKIP:"):
pytest.skip(result.stdout.strip())
# The subprocess also emits vLLM's own INFO log lines on stdout (importing
# vllm_omni runs vllm_omni.patch), so the sentinel is the LAST stdout line,
# not the first.
last_line = _last_stdout_line(result.stdout)
if last_line.startswith("SKIP:"):
pytest.skip(last_line)
assert "FLAT" in result.stdout, (
f"reload nested the NVFP4 clamp wrapper — clamp would run twice per load.\n"
f"stdout: {result.stdout}\nstderr: {result.stderr}"
@@ -244,18 +370,21 @@ def test_env_var_escape_hatch_disables_install(env_value, acceptable):
code = textwrap.dedent(
"""
import importlib
import vllm_omni # noqa: F401
import vllm_omni.patch as p
try:
from vllm.model_executor.layers.quantization.modelopt import (
ModelOptNvFp4LinearMethod, # noqa: F401
)
except ImportError:
print("SKIP: modelopt not available")
modelopt = importlib.import_module("vllm.model_executor.layers.quantization.modelopt")
has_target = any(
getattr(modelopt, name, None) is not None
for name in ("ModelOptNvFp4LinearMethod", "ModelOptLinearMethod")
)
if not has_target:
print("SKIP: no modelopt linear method target available")
raise SystemExit(0)
if getattr(p, "_already_patched_upstream", False):
# Upstream vLLM already clamps; vllm_omni.patch deliberately
# skipped installing our wrapper (self-extinguish).
# Upstream handles NaN weight_scale itself (its own clamp, or the
# redesigned generic PWAL's hard rejection); vllm_omni.patch
# deliberately skipped installing our wrapper (self-extinguish).
print("UPSTREAM_PATCHED")
elif getattr(p, "_clamp_installed", False):
print("INSTALLED")
@@ -271,11 +400,11 @@ def test_env_var_escape_hatch_disables_install(env_value, acceptable):
# contention. The subprocess does a single import + flag print, so 600s
# only bounds pathological hangs, not normal runtime.
result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=600, env=env)
if result.stdout.strip().startswith("SKIP:"):
pytest.skip("modelopt not available in subprocess")
state = _last_stdout_line(result.stdout)
if state.startswith("SKIP:"):
pytest.skip(state)
# Exact token match on the final stdout line — not a substring test, since
# "INSTALLED" is a substring of "NOT_INSTALLED".
state = result.stdout.strip().splitlines()[-1] if result.stdout.strip() else ""
assert state in acceptable, (
f"VLLM_OMNI_SKIP_NVFP4_NAN_CLAMP={env_value!r} expected one of {set(acceptable)!r} "
f"but got {state!r}:\nstdout: {result.stdout}\nstderr: {result.stderr}"
+24 -1
View File
@@ -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
import pytest
from vllm.config import CompilationConfig, CompilationMode, DeviceConfig, VllmConfig
@@ -45,3 +45,26 @@ def test_cuda_default_ir_op_priority_with_oink(monkeypatch: pytest.MonkeyPatch)
)
assert priority.rms_norm == ["oink", "vllm_c", "native"]
assert priority.fused_add_rms_norm == ["oink", "vllm_c", "native"]
@pytest.mark.parametrize(
"mode",
[CompilationMode.NONE, CompilationMode.VLLM_COMPILE],
)
def test_cuda_default_ir_op_priority_names_only_registered_providers(mode: CompilationMode) -> None:
"""Every field must name providers that are actually registered.
``IrOpPriorityConfig.with_default`` fills any field it is not given with the
generic ``default`` list, so an override that does not name a field silently
inherits every provider in that list. Upstream added ``gelu_and_mul_sparse``
(implemented by ``triton``/``native`` only), which therefore must not inherit
CUDA's ``["vllm_c", "native"]`` default: ``IrOp._filter_priority_impls``
asserts on unregistered providers and is reached from ``WorkerBase.__init__``
and the omni diffusion forward context.
"""
priority = CudaOmniPlatform.get_default_ir_op_priority(_vllm_config(mode=mode))
assert priority.gelu_and_mul_sparse == ["triton", "native"]
# Scoped context manager: runs the real upstream provider validation for
# every field and restores the previous priorities on exit.
with priority.set_priority():
pass
+11 -3
View File
@@ -44,7 +44,8 @@ def _async_output(req_ids=("req-0",), **overrides) -> OmniAsyncOutput:
return OmniAsyncOutput(**(kwargs | overrides))
def test_async_output_blocking_event_and_routing_masks(monkeypatch) -> None:
@pytest.mark.parametrize("compact_width", [1, 2])
def test_async_output_blocking_event_and_routing_masks(monkeypatch, compact_width) -> None:
event_kwargs = []
monkeypatch.setattr(torch.cuda, "set_stream", lambda _stream: None)
@@ -53,7 +54,12 @@ def test_async_output_blocking_event_and_routing_masks(monkeypatch) -> None:
return _FakeEvent()
monkeypatch.setattr(torch.cuda, "Event", make_event)
masks = SamplingMaskTensors(torch.tensor([[5], [0]], dtype=torch.uint8), torch.tensor([2, 0]), 4)
masks = SamplingMaskTensors(
token_ids=torch.tensor([[0, 2], [0, 0]], dtype=torch.int32)[:, :compact_width],
packed_mask=torch.tensor([[5], [0]], dtype=torch.uint8),
counts=torch.tensor([2, 0]),
vocab_size=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]))
@@ -65,7 +71,9 @@ def test_async_output_blocking_event_and_routing_masks(monkeypatch) -> None:
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]
assert output.sampled_token_ids == [[2], []]
assert output.sampling_masks.to_nested_list() == [[0, 2], []]
np.testing.assert_array_equal(output.sampling_masks.offsets, [0, 2, 2])
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])
@@ -3,6 +3,7 @@
"""MRV2 admission, capture, dispatch and request lifecycle contracts."""
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -164,3 +165,67 @@ def test_capture_contract_uses_model_declaration(stage, declared):
runner._configure_cudagraph_output_contract()
assert runner._model_returns_tuple is declared
assert runner._exclude_full_graph is declared
@pytest.mark.parametrize("runner_kind", ["gpu", "ar", "generation"])
def test_dummy_forward_uses_upstream_execution_state(runner_kind, monkeypatch):
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.model_runner import ExecuteModelState
from vllm_omni.worker_v2.omni_ar_model_runner import OmniARModelRunner
from vllm_omni.worker_v2.omni_generation_model_runner import OmniGenerationModelRunner
runner_cls = {"gpu": OmniGPUModelRunner, "ar": OmniARModelRunner, "generation": OmniGenerationModelRunner}[
runner_kind
]
runner = object.__new__(runner_cls)
hidden = torch.ones(1, 2)
runner.model = MagicMock(
return_value=OmniOutput(text_hidden_states=hidden, multimodal_outputs={})
if runner_kind == "generation"
else hidden
)
runner._dummy_hidden = hidden
runner.model_config = SimpleNamespace()
runner.vllm_config = SimpleNamespace()
runner.req_states = SimpleNamespace()
runner.model_state = MagicMock()
runner.model_state.prepare_inputs.return_value = {}
runner._omni_data_plane = object()
runner.supports_mm_inputs = False
runner.lora_config = None
runner.is_encoder_decoder = False
runner.eplb = MagicMock()
runner.kv_connector = MagicMock()
runner.input_buffers = object()
runner.kv_cache_config = object()
runner.attn_groups = []
input_batch = SimpleNamespace(
input_ids=torch.tensor([1]),
positions=torch.tensor([0]),
num_tokens=1,
num_tokens_after_padding=1,
is_padding=None,
)
runner.prepare_dummy_attn = MagicMock(return_value=((), torch.empty(0)))
runner.gather_batch_req_state = MagicMock(return_value=(None, 1))
batch_desc = SimpleNamespace(
cg_mode=CUDAGraphMode.NONE, num_reqs=1, num_tokens=1, num_active_loras=0, max_query_len=1
)
runner._dispatch_batch_descriptor = MagicMock(return_value=(batch_desc, None))
monkeypatch.setattr(InputBatch, "make_dummy", lambda *args, **kwargs: input_batch)
monkeypatch.setattr("vllm_omni.worker_v2.omni_model_runner.build_slot_mappings_by_layer", lambda *args: {})
for module in ("omni_model_runner", "omni_generation_model_runner"):
monkeypatch.setattr(f"vllm_omni.worker_v2.{module}.set_forward_context", lambda *args, **kwargs: nullcontext())
scheduled = SchedulerOutput.make_empty()
scheduled.num_scheduled_tokens = {"_dummy_req_0": 1}
scheduled.total_num_scheduled_tokens = 1
# Upstream _dummy_run always supplies valid_dummy_state_slots, and the
# result must use the real upstream constructor rather than a mocked state.
assert runner.execute_model(scheduled, dummy_run=True, valid_dummy_state_slots=True) is None
assert isinstance(runner.execute_model_state, ExecuteModelState)
assert runner.execute_model_state.input_batch is input_batch
assert runner.execute_model_state.cudagraph_stats is None
if runner_kind != "generation":
runner.prepare_dummy_attn.assert_called_once_with(input_batch, True)
+32
View File
@@ -353,6 +353,38 @@ def test_rope_shim_propagates_type_error():
_make_safe_get_rope(broken_get_rope)(SimpleNamespace(uses_mrope=False), object())
def test_rope_shim_constructs_sequential_mrope_state():
from vllm.platforms.cpu import CpuPlatform
from vllm.v1.worker.gpu.mm.rope import RopeState, get_rope_state
model = torch.nn.Module()
config = SimpleNamespace(uses_mrope=True, mrope_num_dims=3)
# Exercise the upstream constructor, including its argument contract, while
# keeping the backing buffers on CPU for this unit test.
with (
patch("vllm.platforms.current_platform", CpuPlatform()),
patch("vllm.v1.worker.gpu.buffer_utils.is_uva_available", return_value=False),
):
rope = _make_safe_get_rope(get_rope_state)(
config,
model,
max_num_reqs=2,
max_num_tokens=8,
max_model_len=16,
device=torch.device("cpu"),
)
assert isinstance(rope, RopeState)
assert rope.get_positions(4).shape == (3, 4)
positions, delta = model.get_mrope_input_positions([11, 22, 33, 44], [])
torch.testing.assert_close(positions, torch.arange(4).expand(3, -1))
assert delta == 0
rope.init_prefill_positions(1, model, [11, 22, 33, 44], [])
assert rope.prefill_delta.np[1] == 0
assert rope.prefill_positions._staged_write_indices == [3, 4, 5]
assert rope.prefill_positions._staged_write_contents == [0, 1, 2, 3] * 3
@pytest.mark.parametrize("output_key", [None, ("only_one",)])
def test_mtp_requires_model_declared_output_key(output_key):
state = _make_state()