[Core] Refactor omni prefix cache into Manager/Controller (#6654)

Signed-off-by: ZhengWG <zwg0606@gmail.com>
Co-authored-by: amy-why-3459 <wuhaiyan17@huawei.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-09-19 21:23:59 +08:00
1 parent ea84055507
commit 470ec60848
25 files changed
+5710 -2149

No files matched your search

File diff suppressed because it is too large. Load diff
-119
View File
@@ -1,119 +0,0 @@
import pytest
import torch
from vllm_omni.core.prefix_cache import OmniTensorPrefixCache
# `cpu` is the lane selector, not a hardware claim: the only Buildkite steps that
# reach tests/ select `core_model and cpu`, and they run on GPU hardware (l4_1).
# Marking this `cuda` collects it nowhere. Real hardware need is the skipif below.
pytestmark = [
pytest.mark.core_model,
pytest.mark.cpu,
pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a CUDA device"),
]
NUM_BLOCKS = 10
BLOCK_SIZE = 4
HIDDEN_SIZE = 2
DTYPE = torch.float32
def get_omni_pcache() -> OmniTensorPrefixCache:
"""Build an OmniTensorPrefixCache, but don't init mm tensors."""
return OmniTensorPrefixCache(
num_blocks=NUM_BLOCKS,
block_size=BLOCK_SIZE,
hidden_size=HIDDEN_SIZE,
hs_dtype=DTYPE,
)
def test_drain_ready_async_writes_is_a_noop_before_the_event_is_ready(monkeypatch):
"""drain_ready_async_writes() must not touch the cache while the
scheduled D2H's event has not completed, and must consume it exactly
once after it has.
Real GPU timing (e.g. via torch.cuda._sleep to stall the copy stream)
was tried and found unreliable on this box: cross-stream wait_stream/
wait_event did not reliably delay event.query() from reporting ready
immediately, likely a virtualization/driver quirk of this cloud GPU.
Forcing the event's query() result directly tests the branching logic
in drain_ready_async_writes/_consume_pending_write deterministically,
independent of real CUDA scheduling behavior.
"""
cache = get_omni_pcache()
mm_key = "codes.audio"
cache.maybe_init_missing_mm_cache_keys({mm_key: torch.zeros(4, HIDDEN_SIZE)}, seq_len=4)
num_tokens = 4
slot_mapping_gpu = torch.arange(8, 8 + num_tokens, dtype=torch.int64, device="cuda")
mm_gpu = {
mm_key: torch.arange(num_tokens * HIDDEN_SIZE, dtype=torch.float32, device="cuda").reshape(
num_tokens, HIDDEN_SIZE
)
}
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=mm_gpu,
slot_mapping_gpu=slot_mapping_gpu,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
pending_event = cache._pending_write.event
rows = cache.mm_outputs_cache[mm_key].view(-1, HIDDEN_SIZE)
monkeypatch.setattr(pending_event, "query", lambda: False)
assert cache.drain_ready_async_writes() == 0
assert torch.all(rows[8 : 8 + num_tokens] == 0)
assert cache._pending_write is not None
monkeypatch.setattr(pending_event, "query", lambda: True)
assert cache.drain_ready_async_writes() == 1
assert torch.equal(rows[8 : 8 + num_tokens], mm_gpu[mm_key].cpu())
assert cache._pending_write is None
# Nothing pending anymore: a second drain is a no-op, not a re-scatter.
assert cache.drain_ready_async_writes() == 0
def test_schedule_async_write_consumes_previous_pending_write_first():
"""Scheduling step N+1's write must first consume (scatter) step N's
pending write, even if the caller never explicitly called
drain_ready_async_writes() in between -- otherwise step N's data would
be silently dropped when overwritten by step N+1's pending write."""
cache = get_omni_pcache()
mm_key = "codes.audio"
cache.maybe_init_missing_mm_cache_keys({mm_key: torch.zeros(4, HIDDEN_SIZE)}, seq_len=4)
num_tokens = 4
first_slots = torch.arange(8, 8 + num_tokens, dtype=torch.int64, device="cuda")
first_gpu = {mm_key: torch.full((num_tokens, HIDDEN_SIZE), 1.0, device="cuda")}
second_slots = torch.arange(12, 12 + num_tokens, dtype=torch.int64, device="cuda")
second_gpu = {mm_key: torch.full((num_tokens, HIDDEN_SIZE), 2.0, device="cuda")}
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=first_gpu,
slot_mapping_gpu=first_slots,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
torch.accelerator.synchronize()
# This call's internal _consume_pending_write() must flush the FIRST
# write before the second one is scheduled; the caller never drained.
cache.schedule_async_write(
hidden_states_gpu=None,
multimodal_outputs_gpu=second_gpu,
slot_mapping_gpu=second_slots,
num_tokens_unpadded=num_tokens,
num_tokens_padded=num_tokens,
)
torch.accelerator.synchronize()
cache.drain_ready_async_writes()
rows = cache.mm_outputs_cache[mm_key].view(-1, HIDDEN_SIZE)
assert torch.all(rows[8:12] == 1.0)
assert torch.all(rows[12:16] == 2.0)
@@ -0,0 +1,182 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CPU tests for PrefixCacheRunnerMixin: one-shot construction, policy
snapshot identity/isolation, and the shared save/materialize gates.
No vLLM and no GPU required (same shim as test_prefix_cache.py)."""
import sys
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any
import pytest
import torch
try: # pragma: no cover - shim only matters on vllm-less dev machines
import vllm # noqa: F401
except ModuleNotFoundError:
_root = Path(__file__).resolve().parents[2]
for _pkg in ("vllm_omni", "vllm_omni.core"):
if _pkg not in sys.modules:
_m = ModuleType(_pkg)
_m.__path__ = [str(_root / _pkg.replace(".", "/"))]
sys.modules[_pkg] = _m
import logging
_vllm = ModuleType("vllm")
_vllm_logger = ModuleType("vllm.logger")
setattr(_vllm_logger, "init_logger", logging.getLogger)
setattr(_vllm, "logger", _vllm_logger)
sys.modules["vllm"] = _vllm
sys.modules["vllm.logger"] = _vllm_logger
from vllm_omni.core.prefix_cache.interface import PrefixCacheConfig, StageCacheOutputs
from vllm_omni.core.prefix_cache.runner_mixin import PrefixCacheRunnerMixin
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
BLOCK_SIZE = 4
def _patch_pp(monkeypatch, is_last: bool) -> None:
"""Route the mixin's call-time get_pp_group import to a fake rank."""
mod = ModuleType("vllm.distributed.parallel_state")
setattr(mod, "get_pp_group", lambda: SimpleNamespace(is_last_rank=is_last))
if "vllm.distributed" not in sys.modules:
monkeypatch.setitem(sys.modules, "vllm.distributed", ModuleType("vllm.distributed"))
monkeypatch.setitem(sys.modules, "vllm.distributed.parallel_state", mod)
def _full_attention_groups():
"""A single-group config that passes check_prefix_cache_kv_groups.
Real FullAttentionSpec when vllm is installed; otherwise a stand-in
registered under the import path the check resolves at call time.
"""
try:
from vllm.v1.kv_cache_interface import FullAttentionSpec
except ModuleNotFoundError:
iface = sys.modules.get("vllm.v1.kv_cache_interface")
if iface is None:
iface = ModuleType("vllm.v1.kv_cache_interface")
class _FullAttentionSpecStub:
pass
setattr(iface, "FullAttentionSpec", _FullAttentionSpecStub)
sys.modules["vllm.v1"] = ModuleType("vllm.v1")
sys.modules["vllm.v1.kv_cache_interface"] = iface
FullAttentionSpec = getattr(iface, "FullAttentionSpec")
return [SimpleNamespace(kv_cache_spec=FullAttentionSpec.__new__(FullAttentionSpec))]
class _FakeBlockTables:
"""Group-0 table whose layout attrs pass check_prefix_cache_block_layout."""
def __init__(self):
self.block_tables = [object()]
def __getitem__(self, idx):
return SimpleNamespace()
class _Runner(PrefixCacheRunnerMixin):
def __init__(self, cfg: PrefixCacheConfig | None = None):
# Any: tests swap in _CacheStub for the manager.
self.omni_prefix_cache: Any = None
self._omni_prefix_cache_cfg = cfg
self.input_batch = SimpleNamespace(block_table=_FakeBlockTables(), req_ids=[])
self.kv_cache_config = SimpleNamespace(kv_cache_groups=_full_attention_groups())
self.is_pooling_model = False
def _cfg() -> PrefixCacheConfig:
return PrefixCacheConfig(num_blocks=8, block_size=BLOCK_SIZE)
def _sched():
return SimpleNamespace(scheduled_new_reqs=(), finished_req_ids=set(), num_scheduled_tokens={})
class _CacheStub:
def __init__(self):
self.save_calls = []
self.materialize_calls = []
self.outs = StageCacheOutputs(hidden_states=None, mm_outputs={})
def save_outputs(self, hidden, mm, *, num_tokens_unpadded, num_tokens_padded):
self.save_calls.append((hidden, mm, num_tokens_unpadded, num_tokens_padded))
return 7
def materialize(self, step_id, req_ids):
self.materialize_calls.append((step_id, req_ids))
return self.outs
def test_step_begin_builds_once_and_registers_snapshot_policy(monkeypatch):
_patch_pp(monkeypatch, is_last=True)
r = _Runner(_cfg())
r._snapshot_prefix_cache_model_policy(
SimpleNamespace(requires_full_prefix_cached_hidden_states=True, deferred_prefix_cache_mm_keys=("k",))
)
r._prefix_cache_step_begin(_sched())
mgr = r.omni_prefix_cache
assert mgr is not None and r._omni_prefix_cache_cfg is None
assert mgr._policy is r._omni_cache_policy # the load-time snapshot, same object
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is mgr # one-shot
def test_default_policy_isolated_per_instance():
a, b = _Runner(), _Runner()
a._snapshot_prefix_cache_model_policy(SimpleNamespace(requires_full_prefix_cached_hidden_states=False))
assert a._omni_cache_policy.needs_full_hidden_states is False
assert a._model_needs_full_prefix_hidden_states() is False
assert b._omni_cache_policy.needs_full_hidden_states is True # class default untouched
assert PrefixCacheRunnerMixin._omni_cache_policy.needs_full_hidden_states is True
def test_non_last_rank_consumes_cfg_without_building(monkeypatch):
_patch_pp(monkeypatch, is_last=False)
r = _Runner(_cfg())
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is None and r._omni_prefix_cache_cfg is None
def test_disabled_cache_step_begin_is_a_noop():
r = _Runner(cfg=None) # enable_prefix_caching off: nothing staged
r._prefix_cache_step_begin(_sched())
assert r.omni_prefix_cache is None
def test_save_step_gates_and_passthrough(monkeypatch):
r = _Runner()
stub = _CacheStub()
hidden = torch.zeros(2, 2)
def save():
return r._prefix_cache_save_step(hidden, None, num_tokens_unpadded=2, num_tokens_padded=2)
_patch_pp(monkeypatch, is_last=True)
assert save() is None # cache off
r.omni_prefix_cache = stub
r.is_pooling_model = True
assert save() is None # pooling stage never writes
r.is_pooling_model = False
_patch_pp(monkeypatch, is_last=False)
assert save() is None # not the last PP rank
_patch_pp(monkeypatch, is_last=True)
assert save() == 7
assert stub.save_calls == [(hidden, {}, 2, 2)] # empty mm stays {}
def test_materialize_requires_explicit_step_and_snapshot_req_ids():
r = _Runner()
stub = _CacheStub()
r.omni_prefix_cache = stub
assert r._prefix_cache_materialize(None, ["a"]) == (None, None)
assert stub.materialize_calls == [] # step_id None: nothing to consume
hidden = {"a": torch.zeros(1, 2)}
stub.outs = StageCacheOutputs(hidden_states=hidden, mm_outputs={})
assert r._prefix_cache_materialize(7, ["a"]) == (hidden, None) # empty mm -> None
assert stub.materialize_calls == [(7, ["a"])]
+100 -12
View File
@@ -24,29 +24,40 @@ _MODEL = "Qwen/Qwen3-Omni-30B-A3B-Instruct"
_CI_DEPLOY = get_deploy_config_path("ci/qwen3_omni_moe.yaml")
# For prefix caching checks against we enable it on the thinker and talker via CLI override
# and enable prompt token details so that we can determine if any tokens were cached.
# We also explicitly set block size so that we can make sure the cached token counts are a
# multiple of the block size.
# Prefix cache is opt-in on the deploy YAML. CI overlay also pins
# ``async_chunk: False``; the existing server keeps ``--no-async-chunk``.
# Production Qwen YAML is ``async_chunk: true``, so a sibling server boots
# with ``--async-chunk`` and the same cache overrides (async output builder).
BLOCK_SIZE = 16
_PREFIX_CACHE_SERVER_ARGS = [
"--block-size",
str(BLOCK_SIZE),
"--stage-overrides",
'{"0": {"enable_prefix_caching": true}, "1": {"enable_prefix_caching": true}}',
"--enable-prompt-tokens-details",
]
test_params = [
pytest.param(
OmniServerParams(
model=_MODEL,
stage_config_path=_CI_DEPLOY,
use_stage_cli=True,
server_args=[
"--no-async-chunk",
"--block-size",
str(BLOCK_SIZE),
"--stage-overrides",
'{"0": {"enable_prefix_caching": true}, "1": {"enable_prefix_caching": true}}',
"--enable-prompt-tokens-details",
],
server_args=["--no-async-chunk", *_PREFIX_CACHE_SERVER_ARGS],
),
id="default",
)
]
prefix_cache_async_chunk_params = [
pytest.param(
OmniServerParams(
model=_MODEL,
stage_config_path=_CI_DEPLOY,
use_stage_cli=True,
server_args=["--async-chunk", *_PREFIX_CACHE_SERVER_ARGS],
),
id="prefix_cache_async_chunk",
)
]
def get_system_prompt():
@@ -245,6 +256,83 @@ def test_thinker_prefix_caching_audio_output(omni_server, online_client) -> None
_run_prefix_cache_check(online_client, request_config)
def _assert_omni_payload_complete(resp) -> None:
"""Async-chunk + prefix-cache must still deliver a full downstream payload."""
assert resp.success
assert resp.text_content
has_audio = bool(resp.audio_bytes) or bool(resp.audio_data)
assert has_audio
@pytest.mark.advanced_model
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", prefix_cache_async_chunk_params, indirect=True)
def test_thinker_prefix_caching_async_chunk_identical(omni_server, online_client) -> None:
"""Production path: ``async_chunk: true`` plus thinker/talker prefix cache.
Two identical streaming requests. The second must report a block-aligned
cache hit and still produce text + audio (async output builder).
"""
messages = dummy_messages_from_mix_data(
system_prompt=get_system_prompt(),
content_text=get_prompt(),
)
request_config = {
"model": omni_server.model,
"messages": messages,
"stream": True,
"stream_options": {"include_usage": True},
}
first_response, cached_response = _run_prefix_cache_check(online_client, request_config)
_assert_omni_payload_complete(first_response)
_assert_omni_payload_complete(cached_response)
@pytest.mark.advanced_model
@pytest.mark.core_model
@pytest.mark.omni
@hardware_test(res={"cuda": "H100", "rocm": "MI325"}, num_cards=2)
@pytest.mark.parametrize("omni_server", prefix_cache_async_chunk_params, indirect=True)
def test_thinker_prefix_caching_async_chunk_shared_image_prefix(omni_server, online_client) -> None:
"""Shared image / system prefix, different user text — not a full-prompt replay.
The second request must still hit cached tokens (block-aligned, less than
its prompt). A merge that only works when ``hit_upto == prompt_len`` would
fail this.
"""
image_data_url = f"data:image/jpeg;base64,{generate_synthetic_image(224, 224)['base64']}"
first_messages = dummy_messages_from_mix_data(
system_prompt=get_system_prompt(),
image_data_url=image_data_url,
content_text=get_prompt("text_image"),
)
second_messages = dummy_messages_from_mix_data(
system_prompt=get_system_prompt(),
image_data_url=image_data_url,
content_text="How many squares are in this image? Answer in 20 words.",
)
first_cfg = {
"model": omni_server.model,
"messages": first_messages,
"stream": True,
"stream_options": {"include_usage": True},
"modalities": ["text"],
}
second_cfg = {**first_cfg, "messages": second_messages}
first_response = online_client.send_omni_request(first_cfg, request_num=1)[0]
cached_response = online_client.send_omni_request(second_cfg, request_num=1)[0]
assert first_response.success and cached_response.success
assert first_response.text_content and cached_response.text_content
num_cached = cached_response.cached_tokens
num_prompt = cached_response.prompt_tokens
assert num_cached is not None and num_prompt is not None
assert num_cached > 0
assert num_cached % BLOCK_SIZE == 0
assert num_cached < num_prompt
@pytest.mark.advanced_model
@pytest.mark.core_model
@pytest.mark.omni
@@ -74,7 +74,9 @@ def test_ar_runner_without_model_hook_stays_on_normal_path():
assert "exceptException" not in compact_request_source
set_context_source = source[source.index("def _set_runner_assisted_full_attention_metadata_context") :]
set_context_source = set_context_source[: set_context_source.index("def _deferred_prefix_cache_mm_keys")]
set_context_source = set_context_source[
: set_context_source.index("def _prepare_prefix_cache_pooler_payload_sources")
]
assert "except Exception" not in set_context_source
@@ -0,0 +1,158 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""NPU prefix-cache wiring: save_outputs -> sid -> materialize on CPU.
The NPU runner consumes the prefix cache in eager mode (no CUDA streams) and
hands the step id across execute_model()/sample_tokens() as the LAST field of
its positionally-packed ``ExecuteModelState``. Neither path runs in CUDA CI,
so a hit-read change can silently break them (`vllm_ascend` imports keep the
runner modules out of reach of a plain unit test).
Two layers of protection, both pure CPU:
1. AST characterization of the ``ExecuteModelState`` field order in the NPU
and GPU runners — the pack/unpack sites pass fields positionally, so a
reorder or drop of ``prefix_cache_step_id`` corrupts the sid without any
import-time error.
2. The eager-mode facade contract the NPU runner relies on: controller
auto-selects eager when CUDA is unavailable, and save -> materialize
returns byte-identical rows for both the miss and the hit-merge paths.
"""
import ast
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
from vllm_omni.core.prefix_cache.interface import PrefixCacheConfig
from vllm_omni.core.prefix_cache.manager import OmniPrefixCacheManager
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
_REPO_ROOT = Path(__file__).resolve().parents[3]
_NPU_RUNNER = _REPO_ROOT / "vllm_omni/platforms/npu/worker/npu_ar_model_runner.py"
_GPU_RUNNER = _REPO_ROOT / "vllm_omni/worker/gpu_ar_model_runner.py"
NUM_BLOCKS = 16
BLOCK_SIZE = 4
HIDDEN = 8
DTYPE = torch.float32
def _named_tuple_fields(path: Path, class_name: str) -> list[str]:
tree = ast.parse(path.read_text())
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef) and node.name == class_name:
return [stmt.target.id for stmt in node.body if isinstance(stmt, ast.AnnAssign)]
raise AssertionError(f"{class_name} not found in {path}")
def test_execute_model_state_keeps_prefix_cache_sid_last():
"""Both runners pack ExecuteModelState positionally: the sid must stay
the LAST field, and the NPU field order is pinned exactly — a reorder
passes import and every CUDA test, then ships the wrong value as the
sid on hardware."""
npu_fields = _named_tuple_fields(_NPU_RUNNER, "ExecuteModelState")
assert npu_fields == [
"scheduler_output",
"logits",
"spec_decode_metadata",
"spec_decode_common_attn_metadata",
"hidden_states",
"sample_hidden_states",
"aux_hidden_states",
"attn_metadata",
"positions",
"ec_connector_output",
"cudagraph_stats",
"batch_desc",
"multimodal_outputs",
"prefix_cache_step_id",
]
gpu_fields = _named_tuple_fields(_GPU_RUNNER, "ExecuteModelState")
assert gpu_fields[-1] == "prefix_cache_step_id"
class _FakeView:
"""Minimal group-view double (mirrors tests/core/test_prefix_cache)."""
def __init__(self):
self.block_size = BLOCK_SIZE
self.num_blocks = NUM_BLOCKS
self.req_blocks: dict[str, list[int]] = {}
self.order: list[str] = []
self.computed: dict[str, int] = {}
def slots_for(self, req_id, token_start, token_end):
blocks = self.req_blocks[req_id]
return torch.tensor(
[blocks[p // BLOCK_SIZE] * BLOCK_SIZE + p % BLOCK_SIZE for p in range(token_start, token_end)],
dtype=torch.long,
)
def batch_req_ids(self) -> list[str]:
return list(self.order)
def step_slots_cpu(self, req_ids, num_scheduled) -> torch.Tensor:
parts = []
for r in req_ids:
n = int(num_scheduled.get(r, 0))
if n > 0:
start = self.computed.get(r, 0)
parts.append(self.slots_for(r, start, start + n))
return torch.cat(parts) if parts else torch.empty((0,), dtype=torch.long)
def _run_step(mgr, view, req_id, blocks, start_pos, sched, *, hit=0, finished=()):
"""One NPU-shaped step: new_step_starts -> save_outputs -> sid."""
view.order = [req_id]
view.req_blocks[req_id] = blocks
view.computed[req_id] = start_pos
slots = view.slots_for(req_id, start_pos, start_pos + sched)
hidden = slots.to(DTYPE).unsqueeze(1).expand(sched, HIDDEN).clone()
sched_out = SimpleNamespace(
scheduled_new_reqs=[
SimpleNamespace(req_id=req_id, num_computed_tokens=hit, block_ids=[list(blocks)]),
],
finished_req_ids=set(finished),
num_scheduled_tokens={req_id: sched},
)
mgr.new_step_starts(sched_out)
return mgr.save_outputs(hidden, {}, num_tokens_unpadded=sched, num_tokens_padded=sched)
def _expected_rows(slots: torch.Tensor) -> torch.Tensor:
return slots.to(DTYPE).unsqueeze(1).expand(slots.numel(), HIDDEN)
def _make_npu_mode_manager(monkeypatch) -> tuple[OmniPrefixCacheManager, _FakeView]:
# The NPU condition: no CUDA -> the controller must auto-select eager
# (submit() completes copy+scatter synchronously), exactly how
# npu_model_runner builds the manager with the default eager=None.
monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
view = _FakeView()
config = PrefixCacheConfig(num_blocks=NUM_BLOCKS, block_size=BLOCK_SIZE)
return OmniPrefixCacheManager(config, view), view
def test_npu_mode_auto_selects_eager_and_roundtrips(monkeypatch):
mgr, view = _make_npu_mode_manager(monkeypatch)
assert mgr._controller._eager is True
sid = _run_step(mgr, view, "a", [0, 1], 0, 8)
outs = mgr.materialize(sid, ["a"])
assert torch.equal(outs.hidden_states["a"], _expected_rows(view.slots_for("a", 0, 8)))
def test_npu_mode_hit_merges_cached_prefix(monkeypatch):
"""The hit-read path in eager mode: consumer's merged output must be
[cached prefix rows + this step's rows], byte-identical."""
mgr, view = _make_npu_mode_manager(monkeypatch)
s1 = _run_step(mgr, view, "a", [0, 1], 0, 8)
mgr.materialize(s1, ["a"])
s2 = _run_step(mgr, view, "b", [0, 1, 2], 8, 4, hit=8, finished=["a"])
merged = mgr.materialize(s2, ["b"]).hidden_states["b"]
assert merged.shape == (12, HIDDEN)
assert torch.equal(merged[:8], _expected_rows(view.slots_for("b", 0, 8)))
assert torch.equal(merged[8:], _expected_rows(view.slots_for("b", 8, 12)))
@@ -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 of ``OmniGPUModelRunner.initialize_metadata_builders``.
Upstream ``FlashAttentionMetadataBuilder`` pre-allocates ``scheduler_metadata``
@@ -19,14 +19,12 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
from vllm_omni.worker.gpu_model_runner import OmniGPUModelRunner
pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
# The class ``super().initialize_metadata_builders`` dispatches to.
_UPSTREAM_RUNNER = OmniGPUModelRunner.__mro__[1]
def _builder(*, prealloc: int | None, max_num_splits: int) -> SimpleNamespace:
sm = None if prealloc is None else torch.zeros(prealloc, dtype=torch.int32)
@@ -36,10 +34,14 @@ def _builder(*, prealloc: int | None, max_num_splits: int) -> SimpleNamespace:
def _make_runner(monkeypatch, *, max_num_seqs: int, builders: list) -> OmniGPUModelRunner:
# Stub the upstream initialize_metadata_builders; our fake runner already
# carries the attn_groups the Omni override iterates over.
monkeypatch.setattr(_UPSTREAM_RUNNER, "initialize_metadata_builders", lambda self, *a, **k: None)
monkeypatch.setattr(GPUModelRunner, "initialize_metadata_builders", lambda self, *a, **k: None)
runner = object.__new__(OmniGPUModelRunner)
runner.scheduler_config = SimpleNamespace(max_num_seqs=max_num_seqs)
runner.cache_config = SimpleNamespace(enable_prefix_caching=False) # skip omni_prefix_cache branch
runner.vllm_config = SimpleNamespace(kv_transfer_config=None)
runner.model_config = SimpleNamespace()
runner.is_pooling_model = False
runner.speculative_config = None
runner.attn_groups = [[SimpleNamespace(metadata_builders=builders)]]
return runner
+30 -11
View File
@@ -18,6 +18,7 @@ from vllm.sampling_params import SamplingParams
from vllm.v1.worker import gpu_input_batch
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
from vllm_omni.core.prefix_cache import ModelCachePolicy
from vllm_omni.entrypoints.openai.protocol.audio import OpenAICreateSpeechRequest
from vllm_omni.entrypoints.openai.serving_speech import OmniOpenAIServingSpeech
from vllm_omni.entrypoints.openai.tts_adapters.base import PreparedRequest
@@ -37,6 +38,8 @@ pytestmark = [pytest.mark.core_model, pytest.mark.cpu]
def _make_runner(engine_output_type: str | None, downstream_req_ids: set[str]) -> GPUARModelRunner:
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.vllm_config = SimpleNamespace(
model_config=SimpleNamespace(engine_output_type=engine_output_type),
)
@@ -57,6 +60,8 @@ def _mtp_runner(*, async_scheduling: bool, buffers: dict[str, dict]) -> tuple[GP
return torch.tensor([[11, 12, 13]], dtype=torch.long)
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.use_async_scheduling = async_scheduling
runner.model = SimpleNamespace(post_sample_talker_mtp=post_sample_talker_mtp)
runner.requests = {req_id: SimpleNamespace() for req_id in buffers}
@@ -143,6 +148,8 @@ def test_post_sample_talker_mtp_uses_gpu_token_with_async_scheduling() -> None:
def test_post_sample_talker_mtp_skips_shape_validation_without_duplex_rows() -> None:
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.use_async_scheduling = False
runner.model = SimpleNamespace(
post_sample_talker_mtp=lambda **_: pytest.fail("hook must not run"),
@@ -178,6 +185,8 @@ def test_post_sample_talker_mtp_rejects_invalid_selected_token_shape(
error_match: str,
) -> None:
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.use_async_scheduling = False
runner.model = SimpleNamespace(
post_sample_talker_mtp=lambda **_: pytest.fail("hook must not run"),
@@ -265,6 +274,8 @@ def test_speech_extra_params_reach_model_sampler_as_sampling_metadata(monkeypatc
received = []
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.input_batch = input_batch
runner.model = SimpleNamespace(
prefer_model_sampler=True,
@@ -323,6 +334,8 @@ def test_sparse_mm_req_ids_requires_sparse_audio_marker():
def test_runner_assisted_full_attention_metadata_request_is_opt_in():
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.model = object()
runner.scheduler_config = SimpleNamespace(max_num_seqs=16)
@@ -377,6 +390,8 @@ def test_runner_assisted_full_attention_metadata_request_and_context_hooks():
calls.append(("context", {"enabled": enabled, "num_reqs": num_reqs}))
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.model = Model()
runner.scheduler_config = SimpleNamespace(max_num_seqs=8)
@@ -466,6 +481,8 @@ def test_omni_async_gpu_model_runner_output_reraises_background_exception():
def _make_async_output_runner(engine_output_type: str = "audio"):
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
model_config = SimpleNamespace(
engine_output_type=engine_output_type,
async_chunk=True,
@@ -642,10 +659,11 @@ def test_async_omni_output_guard_requires_safe_conditions():
assert GPUARModelRunner._should_use_async_omni_output(runner)
# Prefix cache no longer forces the sync output path; leftover mm is
# snapshotted at save so the builder can materialize a step late.
runner.omni_prefix_cache = object()
assert not GPUARModelRunner._should_use_async_omni_output(runner)
assert GPUARModelRunner._should_use_async_omni_output(runner)
runner.omni_prefix_cache = None
runner.model.has_postprocess = True
assert not GPUARModelRunner._should_use_async_omni_output(runner)
@@ -656,6 +674,7 @@ def test_async_omni_output_guard_requires_safe_conditions():
def test_build_omni_output_skips_hidden_when_model_opts_out(monkeypatch):
runner = _make_async_output_runner(engine_output_type="latent")
runner.model.omni_pooler_payload_include_hidden = False
runner._pooler_payload_include_hidden_flag = False
monkeypatch.setattr(
GPUARModelRunner,
@@ -699,6 +718,7 @@ def test_build_omni_output_skips_hidden_when_model_opts_out(monkeypatch):
def test_build_omni_output_splits_mm_by_scheduled_tokens_when_hidden_is_tail_only(monkeypatch):
runner = _make_async_output_runner(engine_output_type="latent")
runner.model.omni_pooler_payload_include_hidden = False
runner._pooler_payload_include_hidden_flag = False
runner._async_chunk = False
runner.requests = {"r1": object(), "r2": object(), "r3": object()}
@@ -745,6 +765,7 @@ def test_build_omni_output_splits_mm_by_hidden_len_when_scheduled_is_padded(monk
"""Thinker mm rows align to hidden_states.shape[0], not padded scheduled count."""
runner = _make_async_output_runner(engine_output_type="latent")
runner.model.omni_pooler_payload_include_hidden = False
runner._pooler_payload_include_hidden_flag = False
runner._async_chunk = False
runner.requests = {"r1": object(), "r2": object(), "r3": object()}
@@ -790,6 +811,7 @@ def test_build_omni_output_splits_mm_by_hidden_len_when_scheduled_is_padded(monk
def test_async_snapshot_payload_omits_hidden_when_model_opts_out():
runner = _make_async_output_runner()
runner.model.omni_pooler_payload_include_hidden = False
runner._pooler_payload_include_hidden_flag = False
payload = GPUARModelRunner._build_omni_async_snapshot_payload(
runner,
@@ -819,6 +841,8 @@ def test_runner_assisted_full_attention_metadata_refresh_pads_buffers():
self.commits.append(num_reqs_padded)
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
block_table = BlockTable()
runner.input_batch = SimpleNamespace(
num_computed_tokens_cpu=torch.tensor([10, 20, 99, 99], dtype=torch.int32),
@@ -846,6 +870,8 @@ def test_runner_assisted_full_attention_metadata_refresh_pads_buffers():
@pytest.mark.parametrize("query_start_loc_attr", ["method", "tensor_attr"])
def test_sample_tokens_tail_only_prefix_cache_uses_staged_cpu_hidden_states(monkeypatch, query_start_loc_attr):
runner = object.__new__(GPUARModelRunner)
runner._omni_cache_policy = ModelCachePolicy(needs_full_hidden_states=True)
runner._pooler_payload_include_hidden_flag = True
runner.execute_model_state = ExecuteModelState(
SimpleNamespace(
total_num_scheduled_tokens=3,
@@ -908,12 +934,11 @@ def test_sample_tokens_tail_only_prefix_cache_uses_staged_cpu_hidden_states(monk
)
monkeypatch.setattr(GPUARModelRunner, "eplb_step", lambda self: None)
monkeypatch.setattr(GPUARModelRunner, "_resolve_pooler_payload_req_ids", lambda self, req_ids: ("audio", req_ids))
monkeypatch.setattr(GPUARModelRunner, "_deferred_prefix_cache_mm_keys", lambda self: set())
monkeypatch.setattr(GPUARModelRunner, "_model_needs_full_prefix_hidden_states", lambda self: False)
monkeypatch.setattr(
GPUARModelRunner,
"_maybe_get_combined_prefix_cache_tensors",
lambda *args, **kwargs: (None, None),
"_prepare_prefix_cache_pooler_payload_sources",
lambda self, **kwargs: (kwargs["staged_hidden_states_cpu"], None, None),
)
monkeypatch.setattr(GPUARModelRunner, "_process_additional_information_updates", lambda *args, **kwargs: None)
monkeypatch.setattr(GPUARModelRunner, "_should_accumulate_full_payload_output", lambda self: False)
@@ -946,8 +971,6 @@ def test_build_omni_output_falls_back_to_mm_cpu_without_prefix_merge(monkeypatch
lambda self, req_ids: ("latent", req_ids),
)
monkeypatch.setattr(GPUARModelRunner, "_model_needs_full_prefix_hidden_states", lambda self: False)
monkeypatch.setattr(GPUARModelRunner, "_deferred_prefix_cache_mm_keys", lambda self: {"codes.audio"})
monkeypatch.setattr(GPUARModelRunner, "_stage_deferred_prefix_cache_mm_outputs", lambda *args, **kwargs: None)
monkeypatch.setattr(
GPUARModelRunner,
"_prepare_prefix_cache_pooler_payload_sources",
@@ -1095,8 +1118,6 @@ def test_build_omni_output_filters_multimodal_by_partial_downstream_batch(monkey
lambda self, req_ids: ("latent", ["r1", "r3"]),
)
monkeypatch.setattr(GPUARModelRunner, "_model_needs_full_prefix_hidden_states", lambda self: False)
monkeypatch.setattr(GPUARModelRunner, "_deferred_prefix_cache_mm_keys", lambda self: {"codes.audio"})
monkeypatch.setattr(GPUARModelRunner, "_stage_deferred_prefix_cache_mm_outputs", lambda *args, **kwargs: None)
monkeypatch.setattr(
GPUARModelRunner,
"_prepare_prefix_cache_pooler_payload_sources",
@@ -1172,8 +1193,6 @@ def test_build_omni_output_uses_combined_prefix_cache_mm_payload_for_partial_dow
lambda self, req_ids: ("latent", ["r1", "r3"]),
)
monkeypatch.setattr(GPUARModelRunner, "_model_needs_full_prefix_hidden_states", lambda self: False)
monkeypatch.setattr(GPUARModelRunner, "_deferred_prefix_cache_mm_keys", lambda self: {"codes.audio"})
monkeypatch.setattr(GPUARModelRunner, "_stage_deferred_prefix_cache_mm_outputs", lambda *args, **kwargs: None)
monkeypatch.setattr(
GPUARModelRunner,
"_prepare_prefix_cache_pooler_payload_sources",