[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"])]