[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests
- Drop dead model modules, keeping files live imports require - Remove anthropic, cohere, codegen entrypoints and batch STT modes - Delete unused attention backends, MoE experts, and NPU/XPU util leaves - Strip dead third_party trees and ROCm leaves with no CUDA path - Remove mooncake EC connectors: dependency missing since branch base - Re-audit verified by full import sweep and Qwen3.5 smoke test Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,194 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Integration tests for SimpleCPUOffloadConnector with real models."""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from vllm import LLM, SamplingParams, TokensPrompt
|
||||
from vllm.config import KVTransferConfig
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("Requires CUDA or ROCm", allow_module_level=True)
|
||||
|
||||
# Small models for default CI / local runs (accuracy only).
|
||||
SMALL_MODELS = [
|
||||
"meta-llama/Llama-3.2-1B-Instruct",
|
||||
"google/gemma-3-1b-it",
|
||||
]
|
||||
|
||||
# Large models for optional perf runs only (slow to load and execute).
|
||||
PERF_MODELS = [
|
||||
"meta-llama/Llama-3.1-8B",
|
||||
"openai/gpt-oss-20b",
|
||||
]
|
||||
|
||||
|
||||
def _make_llm(model: str, lazy: bool, cpu_bytes_to_use: int) -> LLM:
|
||||
kv_transfer_config = KVTransferConfig(
|
||||
kv_connector="SimpleCPUOffloadConnector",
|
||||
kv_role="kv_both",
|
||||
kv_connector_extra_config={
|
||||
"cpu_bytes_to_use": cpu_bytes_to_use,
|
||||
"lazy_offload": lazy,
|
||||
},
|
||||
)
|
||||
return LLM(
|
||||
model=model,
|
||||
kv_cache_memory_bytes=40 << 30, # 40 GiB
|
||||
disable_hybrid_kv_cache_manager=False,
|
||||
enable_prefix_caching=True,
|
||||
kv_transfer_config=kv_transfer_config,
|
||||
)
|
||||
|
||||
|
||||
def _flush_gpu_cache(llm: LLM, sampling_params: SamplingParams, seed: int = 0):
|
||||
"""Generate enough filler requests to allocate the entire GPU KV cache.
|
||||
|
||||
This pushes all prior blocks through the free queue so that the lazy
|
||||
cursor offloads them to CPU before they are evicted.
|
||||
"""
|
||||
cache_config = llm.llm_engine.vllm_config.cache_config
|
||||
num_gpu_blocks = cache_config.num_gpu_blocks
|
||||
block_size = cache_config.block_size
|
||||
# Use 1.2x GPU capacity to give the lazy cursor enough scheduling steps
|
||||
# to walk past all target blocks near the tail of the free queue.
|
||||
assert num_gpu_blocks is not None
|
||||
total_tokens_needed = int(num_gpu_blocks * block_size * 1.5)
|
||||
|
||||
# Use token-id prompts so each filler is unique (no prefix sharing).
|
||||
# Split into multiple requests to stay under max_model_len.
|
||||
max_tokens_per_req = 4096
|
||||
num_fillers = (total_tokens_needed + max_tokens_per_req - 1) // max_tokens_per_req
|
||||
batch_size = 10
|
||||
for i in range(0, num_fillers, batch_size):
|
||||
batch_end = min(i + batch_size, num_fillers)
|
||||
filler_prompts = []
|
||||
for j in range(i, batch_end):
|
||||
ids = [seed * num_fillers + j + 1] * max_tokens_per_req
|
||||
filler_prompts.append(TokensPrompt(prompt_token_ids=ids))
|
||||
llm.generate(filler_prompts, sampling_params, use_tqdm=False)
|
||||
|
||||
|
||||
def _accuracy_test(llm: LLM, lazy: bool = False):
|
||||
"""Verify that CPU-loaded KV produces correct output."""
|
||||
sampling_params = SamplingParams(max_tokens=1, temperature=0)
|
||||
prompt = "hi " * 2000 + "Let's count to ten. One, two, three, "
|
||||
|
||||
# Cold run — populate GPU cache and trigger CPU offload
|
||||
cold_output = llm.generate(prompt, sampling_params, use_tqdm=False)[0]
|
||||
|
||||
# CPU hit runs
|
||||
test_count = 10
|
||||
success_count = 0
|
||||
expected = cold_output.outputs[0].text
|
||||
for i in range(test_count):
|
||||
if lazy:
|
||||
_flush_gpu_cache(llm, sampling_params, seed=i)
|
||||
time.sleep(2) # let engine core drain pending transfers
|
||||
|
||||
# Reset GPU prefix cache so next run must load from CPU
|
||||
if not llm.reset_prefix_cache():
|
||||
print(f"GPU prefix cache reset failed for iteration {i}")
|
||||
|
||||
output = llm.generate(prompt, sampling_params, use_tqdm=False)[0]
|
||||
if output.outputs[0].text == expected:
|
||||
success_count += 1
|
||||
|
||||
assert success_count >= 0.5 * test_count, (
|
||||
f"Accuracy too low: {success_count}/{test_count} matched '{expected}'"
|
||||
)
|
||||
|
||||
|
||||
def _latency_test(llm: LLM, lazy: bool = False):
|
||||
"""Verify CPU cache hit is faster than cold compute."""
|
||||
sampling_params = SamplingParams(max_tokens=1, seed=42)
|
||||
prompt_token_ids = [0] * 10001
|
||||
|
||||
num_times_cpu_better = 0
|
||||
num_tests = 10
|
||||
for i in range(num_tests):
|
||||
prompt_token_ids[0] = i
|
||||
prompts = [TokensPrompt(prompt_token_ids=prompt_token_ids)]
|
||||
|
||||
# Cold
|
||||
time.sleep(2) # let engine core drain pending transfers
|
||||
if not llm.reset_prefix_cache():
|
||||
print(f"GPU prefix cache reset failed for iteration {i}")
|
||||
start = time.time()
|
||||
llm.generate(prompts, sampling_params, use_tqdm=False)
|
||||
cold_time = time.time() - start
|
||||
|
||||
if lazy:
|
||||
_flush_gpu_cache(llm, sampling_params, seed=i)
|
||||
else:
|
||||
# Eager mode: GPU hit ensures store completion is processed.
|
||||
llm.generate(prompts, sampling_params, use_tqdm=False)
|
||||
|
||||
time.sleep(2) # let engine core drain pending transfers
|
||||
if not llm.reset_prefix_cache():
|
||||
print(f"GPU prefix cache reset failed for iteration {i}")
|
||||
|
||||
# CPU hit
|
||||
start = time.time()
|
||||
llm.generate(prompts, sampling_params, use_tqdm=False)
|
||||
cpu_time = time.time() - start
|
||||
|
||||
if cpu_time < cold_time:
|
||||
num_times_cpu_better += 1
|
||||
|
||||
assert num_times_cpu_better >= 0.8 * num_tests, (
|
||||
f"CPU hit only faster {num_times_cpu_better}/{num_tests} times"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.optional
|
||||
@pytest.mark.slow_test
|
||||
@pytest.mark.parametrize("model", SMALL_MODELS)
|
||||
def test_simple_cpu_offload_accuracy(model: str):
|
||||
"""Store to CPU, reset GPU, load from CPU; verify output matches baseline."""
|
||||
llm = _make_llm(model, False, 1 << 30) # 1GB
|
||||
try:
|
||||
_accuracy_test(llm, lazy=False)
|
||||
finally:
|
||||
del llm
|
||||
|
||||
|
||||
@pytest.mark.optional
|
||||
@pytest.mark.slow_test
|
||||
@pytest.mark.parametrize("model", PERF_MODELS)
|
||||
def test_simple_cpu_offload_perf_latency(model: str):
|
||||
"""CPU KV hit should beat cold prefill on long context (large models only)."""
|
||||
llm = _make_llm(model, False, 10 << 30) # 10GB
|
||||
try:
|
||||
_latency_test(llm, lazy=False)
|
||||
finally:
|
||||
del llm
|
||||
|
||||
|
||||
@pytest.mark.optional
|
||||
@pytest.mark.slow_test
|
||||
@pytest.mark.parametrize("model", SMALL_MODELS)
|
||||
def test_simple_cpu_offload_accuracy_lazy(model: str):
|
||||
"""Lazy mode: flush GPU cache to trigger CPU offload, then verify hit."""
|
||||
# CPU must be larger than GPU KV cache to avoid evicting offloaded blocks.
|
||||
llm = _make_llm(model, True, 80 << 30) # 80GB
|
||||
try:
|
||||
_accuracy_test(llm, lazy=True)
|
||||
finally:
|
||||
del llm
|
||||
|
||||
|
||||
@pytest.mark.optional
|
||||
@pytest.mark.slow_test
|
||||
@pytest.mark.parametrize("model", PERF_MODELS)
|
||||
def test_simple_cpu_offload_perf_latency_lazy(model: str):
|
||||
"""Lazy mode: CPU KV hit should beat cold prefill (large models only)."""
|
||||
# CPU must be larger than GPU KV cache to avoid evicting offloaded blocks.
|
||||
llm = _make_llm(model, True, 80 << 30) # 80GB
|
||||
try:
|
||||
_latency_test(llm, lazy=True)
|
||||
finally:
|
||||
del llm
|
||||
@@ -1,799 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""KV cache event emission tests for SimpleCPUOffloadScheduler.
|
||||
|
||||
Verifies that BlockStored/BlockRemoved events carry the correct storage
|
||||
medium (MEDIUM_CPU / MEDIUM_STORAGE) and per-group metadata when
|
||||
``enable_kv_cache_events`` is set, and that no events are emitted when it
|
||||
is unset.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.v1.simple_kv_offload.test_scheduler import (
|
||||
_BYTES_PER_BLOCK,
|
||||
BLOCK_SIZE,
|
||||
DTYPE,
|
||||
HEAD_SIZE,
|
||||
NUM_KV_HEADS,
|
||||
SchedulerFixture,
|
||||
_alloc_and_register,
|
||||
_allocate_cp_gpu_blocks,
|
||||
_allocate_gpu_blocks,
|
||||
_make_cp_request,
|
||||
_make_kv_cache_config,
|
||||
_make_scratch_kv_cache_config,
|
||||
_make_vllm_config,
|
||||
make_request,
|
||||
make_scheduler_output,
|
||||
simulate_store_completion,
|
||||
)
|
||||
from vllm import SamplingParams
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.distributed.kv_events import (
|
||||
MEDIUM_CPU,
|
||||
MEDIUM_STORAGE,
|
||||
BlockRemoved,
|
||||
BlockStored,
|
||||
)
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.utils.hashing import sha256
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
get_block_hash,
|
||||
get_request_block_hasher,
|
||||
make_block_hash_with_group_id,
|
||||
maybe_convert_block_hash,
|
||||
)
|
||||
from vllm.v1.core.single_type_kv_cache_manager import register_all_kvcache_specs
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheTensor,
|
||||
MambaSpec,
|
||||
SlidingWindowSpec,
|
||||
)
|
||||
from vllm.v1.request import Request
|
||||
from vllm.v1.simple_kv_offload.manager import (
|
||||
SimpleCPUOffloadScheduler,
|
||||
StoreRequestState,
|
||||
)
|
||||
|
||||
|
||||
def _make_mixed_kv_cache_config(
|
||||
num_blocks: int,
|
||||
sliding_window: int | None = None,
|
||||
with_mamba: bool = False,
|
||||
mamba_block_size: int = BLOCK_SIZE,
|
||||
) -> KVCacheConfig:
|
||||
"""Build a KVCacheConfig with a FullAttention group plus optional
|
||||
SlidingWindow and Mamba groups for per-group metadata tests."""
|
||||
register_all_kvcache_specs(vllm_config=None)
|
||||
groups = []
|
||||
tensors = []
|
||||
|
||||
# Group 0 is always FullAttention (the scheduler requires one FA group).
|
||||
fa_layers = ["layer_fa"]
|
||||
fa_spec = FullAttentionSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
)
|
||||
groups.append(KVCacheGroupSpec(fa_layers, fa_spec))
|
||||
fa_bytes = _BYTES_PER_BLOCK * num_blocks
|
||||
tensors.append(
|
||||
KVCacheTensor(
|
||||
size=fa_bytes,
|
||||
layers=fa_layers,
|
||||
layer_stride=fa_bytes,
|
||||
block_stride=_BYTES_PER_BLOCK,
|
||||
)
|
||||
)
|
||||
|
||||
if sliding_window is not None:
|
||||
sw_layers = ["layer_sw"]
|
||||
sw_spec = SlidingWindowSpec(
|
||||
block_size=BLOCK_SIZE,
|
||||
num_kv_heads=NUM_KV_HEADS,
|
||||
head_size=HEAD_SIZE,
|
||||
dtype=DTYPE,
|
||||
sliding_window=sliding_window,
|
||||
)
|
||||
groups.append(KVCacheGroupSpec(sw_layers, sw_spec))
|
||||
sw_bytes = _BYTES_PER_BLOCK * num_blocks
|
||||
tensors.append(
|
||||
KVCacheTensor(
|
||||
size=sw_bytes,
|
||||
layers=sw_layers,
|
||||
layer_stride=sw_bytes,
|
||||
block_stride=_BYTES_PER_BLOCK,
|
||||
)
|
||||
)
|
||||
|
||||
if with_mamba:
|
||||
m_layers = ["layer_m"]
|
||||
m_spec = MambaSpec(
|
||||
block_size=mamba_block_size,
|
||||
shapes=((NUM_KV_HEADS, HEAD_SIZE, HEAD_SIZE),),
|
||||
dtypes=(DTYPE,),
|
||||
mamba_cache_mode="align",
|
||||
)
|
||||
groups.append(KVCacheGroupSpec(m_layers, m_spec))
|
||||
m_bytes = _BYTES_PER_BLOCK * num_blocks
|
||||
tensors.append(
|
||||
KVCacheTensor(
|
||||
size=m_bytes,
|
||||
layers=m_layers,
|
||||
layer_stride=m_bytes,
|
||||
block_stride=_BYTES_PER_BLOCK,
|
||||
)
|
||||
)
|
||||
|
||||
return KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=tensors,
|
||||
kv_cache_groups=groups,
|
||||
)
|
||||
|
||||
|
||||
def make_events_scheduler(
|
||||
num_cpu_blocks: int = 8,
|
||||
num_gpu_blocks: int = 16,
|
||||
num_groups: int = 1,
|
||||
lazy: bool = False,
|
||||
disk_capacity_bytes: int = 0,
|
||||
dcp_world_size: int = 1,
|
||||
kv_cache_config: KVCacheConfig | None = None,
|
||||
enable_events: bool = True,
|
||||
) -> SchedulerFixture:
|
||||
"""Build a SimpleCPUOffloadScheduler with kv cache events enabled."""
|
||||
if kv_cache_config is None:
|
||||
kv_cache_config = _make_kv_cache_config(num_gpu_blocks, num_groups)
|
||||
vllm_config = _make_vllm_config()
|
||||
if enable_events:
|
||||
vllm_config.kv_events_config = KVEventsConfig(enable_kv_cache_events=True)
|
||||
vllm_config.parallel_config.decode_context_parallel_size = dcp_world_size
|
||||
|
||||
virtual_block_size = BLOCK_SIZE * dcp_world_size
|
||||
cpu_capacity_bytes = _BYTES_PER_BLOCK * num_cpu_blocks * num_groups
|
||||
|
||||
sched = SimpleCPUOffloadScheduler(
|
||||
vllm_config=vllm_config,
|
||||
kv_cache_config=kv_cache_config,
|
||||
cpu_capacity_bytes=cpu_capacity_bytes,
|
||||
scheduler_block_size=virtual_block_size,
|
||||
hash_block_size=virtual_block_size,
|
||||
lazy_offload=lazy,
|
||||
disk_capacity_bytes=disk_capacity_bytes,
|
||||
)
|
||||
|
||||
gpu_block_pool = BlockPool(
|
||||
num_gpu_blocks=num_gpu_blocks,
|
||||
enable_caching=True,
|
||||
hash_block_size=virtual_block_size,
|
||||
)
|
||||
sched.bind_gpu_block_pool(gpu_block_pool)
|
||||
return SchedulerFixture(
|
||||
scheduler=sched,
|
||||
gpu_block_pool=gpu_block_pool,
|
||||
vllm_config=vllm_config,
|
||||
kv_cache_config=kv_cache_config,
|
||||
num_groups=num_groups,
|
||||
)
|
||||
|
||||
|
||||
def _do_eager_store(
|
||||
fix: SchedulerFixture,
|
||||
num_blocks: int = 2,
|
||||
lora_request: LoRARequest | None = None,
|
||||
) -> tuple[object, Request]:
|
||||
"""Run an eager store of ``num_blocks`` and complete it.
|
||||
|
||||
Returns (meta, req) for further assertions.
|
||||
"""
|
||||
sched = fix.scheduler
|
||||
if lora_request is not None:
|
||||
# lora_request must be set in the constructor so block_hashes
|
||||
# (computed in __init__) include the lora extra_keys.
|
||||
req = Request(
|
||||
request_id="req-lora",
|
||||
prompt_token_ids=list(range(num_blocks * BLOCK_SIZE + 1)),
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
pooling_params=None,
|
||||
mm_features=None,
|
||||
lora_request=lora_request,
|
||||
block_hasher=get_request_block_hasher(BLOCK_SIZE, sha256),
|
||||
)
|
||||
else:
|
||||
req = make_request(num_blocks=num_blocks)
|
||||
kv_blocks = _alloc_and_register(fix, req, num_blocks)
|
||||
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
|
||||
block_ids = kv_blocks.get_block_ids()
|
||||
sched_out = make_scheduler_output(
|
||||
{req.request_id: num_blocks * BLOCK_SIZE},
|
||||
new_reqs={req.request_id: block_ids},
|
||||
)
|
||||
meta = sched.build_connector_meta(sched_out)
|
||||
assert meta.store_event >= 0
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
return meta, req
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# events disabled -> no events
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_events_disabled_no_events() -> None:
|
||||
"""When enable_kv_cache_events is False, take_events returns nothing."""
|
||||
fix = make_events_scheduler(enable_events=False)
|
||||
sched = fix.scheduler
|
||||
assert sched.enable_kv_cache_events is False
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
events = list(sched.take_events())
|
||||
assert events == [], f"expected no events, got {events}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# eager store emits BlockStored with per-group metadata
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_block_stored_per_group_metadata_full_attention() -> None:
|
||||
"""BlockStored carries medium, group_idx, kind, sliding_window, block_size,
|
||||
and the correct block hash."""
|
||||
fix = make_events_scheduler()
|
||||
sched = fix.scheduler
|
||||
assert sched.kv_event_medium == MEDIUM_CPU
|
||||
_, req = _do_eager_store(fix, num_blocks=2)
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2
|
||||
ev = stored[0]
|
||||
assert ev.medium == MEDIUM_CPU
|
||||
assert ev.group_idx == 0
|
||||
assert ev.kv_cache_spec_kind == "full_attention"
|
||||
assert ev.kv_cache_spec_sliding_window is None
|
||||
assert ev.block_size == BLOCK_SIZE
|
||||
assert ev.locality == "LOCAL"
|
||||
expected_hash_0 = maybe_convert_block_hash(
|
||||
get_block_hash(make_block_hash_with_group_id(req.block_hashes[0], 0))
|
||||
)
|
||||
assert ev.block_hashes == [expected_hash_0]
|
||||
assert ev.parent_block_hash is None
|
||||
assert req.prompt_token_ids is not None
|
||||
assert ev.token_ids == req.prompt_token_ids[0:BLOCK_SIZE]
|
||||
|
||||
# Second block's parent_block_hash equals the first block's hash.
|
||||
ev1 = stored[1]
|
||||
expected_hash_1 = maybe_convert_block_hash(
|
||||
get_block_hash(make_block_hash_with_group_id(req.block_hashes[1], 0))
|
||||
)
|
||||
assert ev1.block_hashes == [expected_hash_1]
|
||||
assert ev1.parent_block_hash == expected_hash_0
|
||||
assert ev1.token_ids == req.prompt_token_ids[BLOCK_SIZE : 2 * BLOCK_SIZE]
|
||||
|
||||
|
||||
def test_eager_store_lora_metadata() -> None:
|
||||
"""BlockStored carries lora_id and lora_name from req.lora_request."""
|
||||
fix = make_events_scheduler()
|
||||
sched = fix.scheduler
|
||||
|
||||
_do_eager_store(
|
||||
fix,
|
||||
num_blocks=1,
|
||||
lora_request=LoRARequest(
|
||||
lora_name="test-lora",
|
||||
lora_int_id=42,
|
||||
lora_path="/fake/lora/path",
|
||||
),
|
||||
)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 1
|
||||
ev = stored[0]
|
||||
assert ev.lora_id == 42, f"expected lora_id=42, got {ev.lora_id}"
|
||||
assert ev.lora_name == "test-lora", (
|
||||
f"expected lora_name='test-lora', got {ev.lora_name!r}"
|
||||
)
|
||||
assert ev.extra_keys is not None, "expected extra_keys for lora request"
|
||||
assert any(keys is not None and "test-lora" in keys for keys in ev.extra_keys), (
|
||||
f"expected 'test-lora' in extra_keys, got {ev.extra_keys}"
|
||||
)
|
||||
assert len(ev.token_ids) == BLOCK_SIZE
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# disk mode -> MEDIUM_STORAGE
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_disk_mode_medium_storage_on_block_stored() -> None:
|
||||
"""disk_capacity_bytes>0 sets kv_event_medium=STORAGE on BlockStored."""
|
||||
fix = make_events_scheduler(
|
||||
disk_capacity_bytes=_BYTES_PER_BLOCK * 8,
|
||||
enable_events=True,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
assert sched.kv_event_medium == MEDIUM_STORAGE
|
||||
_do_eager_store(fix, num_blocks=1)
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 1
|
||||
assert stored[0].medium == MEDIUM_STORAGE
|
||||
assert stored[0].locality == "LOCAL"
|
||||
|
||||
|
||||
def test_finished_eager_store_emits_all_storage_events() -> None:
|
||||
"""Finished stores preserve and announce every registered hash."""
|
||||
fix = make_events_scheduler(
|
||||
disk_capacity_bytes=_BYTES_PER_BLOCK * 8,
|
||||
enable_events=True,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
req = make_request(num_blocks=2)
|
||||
kv_blocks = _alloc_and_register(fix, req, num_blocks=2)
|
||||
gpu_blocks = kv_blocks.blocks[0]
|
||||
primary_hashes = []
|
||||
for gpu_block in gpu_blocks:
|
||||
assert gpu_block.block_hash is not None
|
||||
primary_hashes.append(gpu_block.block_hash)
|
||||
|
||||
fine_grained_req = Request(
|
||||
request_id="req-finished-fine-grained-hash",
|
||||
prompt_token_ids=req.prompt_token_ids,
|
||||
sampling_params=req.sampling_params,
|
||||
pooling_params=None,
|
||||
mm_features=None,
|
||||
block_hasher=get_request_block_hasher(BLOCK_SIZE // 2, sha256),
|
||||
)
|
||||
secondary_hash = make_block_hash_with_group_id(fine_grained_req.block_hashes[0], 0)
|
||||
fix.gpu_block_pool._insert_block_hash(
|
||||
secondary_hash, gpu_blocks[0], num_tokens=BLOCK_SIZE // 2
|
||||
)
|
||||
|
||||
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
|
||||
sched.request_finished_all_groups(req, kv_blocks.get_block_ids())
|
||||
meta = sched.build_connector_meta(make_scheduler_output({}))
|
||||
assert meta.store_event >= 0
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
|
||||
primary_cpu_block = sched.cpu_block_pool.cached_block_hash_to_block.get_one_block(
|
||||
primary_hashes[0]
|
||||
)
|
||||
secondary_cpu_block = sched.cpu_block_pool.cached_block_hash_to_block.get_one_block(
|
||||
secondary_hash
|
||||
)
|
||||
assert primary_cpu_block is not None
|
||||
assert secondary_cpu_block is primary_cpu_block
|
||||
|
||||
stored = [e for e in sched.take_events() if isinstance(e, BlockStored)]
|
||||
primary_event_hashes = [
|
||||
maybe_convert_block_hash(get_block_hash(block_hash))
|
||||
for block_hash in primary_hashes
|
||||
]
|
||||
secondary_event_hash = maybe_convert_block_hash(get_block_hash(secondary_hash))
|
||||
by_hash = {event.block_hashes[0]: event for event in stored}
|
||||
assert set(by_hash) == {*primary_event_hashes, secondary_event_hash}
|
||||
assert req.prompt_token_ids is not None
|
||||
assert (
|
||||
by_hash[primary_event_hashes[0]].token_ids == req.prompt_token_ids[:BLOCK_SIZE]
|
||||
)
|
||||
assert (
|
||||
by_hash[primary_event_hashes[1]].token_ids
|
||||
== req.prompt_token_ids[BLOCK_SIZE : 2 * BLOCK_SIZE]
|
||||
)
|
||||
assert by_hash[primary_event_hashes[1]].parent_block_hash == primary_event_hashes[0]
|
||||
secondary_event = by_hash[secondary_event_hash]
|
||||
assert secondary_event.medium == MEDIUM_STORAGE
|
||||
assert secondary_event.block_size == 0
|
||||
assert secondary_event.token_ids == []
|
||||
assert secondary_event.parent_block_hash is None
|
||||
|
||||
sched.cpu_block_pool.evict_blocks({primary_cpu_block.block_id})
|
||||
removed = [
|
||||
event for event in sched.take_events() if isinstance(event, BlockRemoved)
|
||||
]
|
||||
assert {event.block_hashes[0] for event in removed} == {
|
||||
primary_event_hashes[0],
|
||||
secondary_event_hash,
|
||||
}
|
||||
assert all(event.medium == MEDIUM_STORAGE for event in removed)
|
||||
|
||||
|
||||
def test_secondary_hash_block_stored_metadata() -> None:
|
||||
"""Secondary hashes carry their own token range and block size."""
|
||||
fix = make_events_scheduler(
|
||||
disk_capacity_bytes=_BYTES_PER_BLOCK * 8,
|
||||
enable_events=True,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
sched.hash_block_size = BLOCK_SIZE // 2
|
||||
req = Request(
|
||||
request_id="req-secondary-hash",
|
||||
prompt_token_ids=list(range(BLOCK_SIZE + 1)),
|
||||
sampling_params=SamplingParams(max_tokens=1),
|
||||
pooling_params=None,
|
||||
mm_features=None,
|
||||
block_hasher=get_request_block_hasher(BLOCK_SIZE // 2, sha256),
|
||||
)
|
||||
req.num_computed_tokens = BLOCK_SIZE
|
||||
gpu_block = fix.gpu_block_pool.get_new_blocks(1)[0]
|
||||
primary_hash = make_block_hash_with_group_id(req.block_hashes[1], 0)
|
||||
secondary_hash = make_block_hash_with_group_id(req.block_hashes[0], 0)
|
||||
fix.gpu_block_pool._insert_block_hash(
|
||||
primary_hash, gpu_block, num_tokens=BLOCK_SIZE
|
||||
)
|
||||
fix.gpu_block_pool._insert_block_hash(
|
||||
secondary_hash, gpu_block, num_tokens=BLOCK_SIZE // 2
|
||||
)
|
||||
state = StoreRequestState(
|
||||
request=req,
|
||||
block_ids=([gpu_block.block_id],),
|
||||
num_stored_blocks=[0],
|
||||
)
|
||||
|
||||
gpu_block_ids, advanced_per_group, block_meta = sched._select_eager_blocks_to_store(
|
||||
state,
|
||||
([gpu_block.block_id],),
|
||||
)
|
||||
assert gpu_block_ids == [gpu_block.block_id]
|
||||
assert advanced_per_group == [1]
|
||||
assert block_meta is not None
|
||||
assert set(block_meta[0]) == {primary_hash, secondary_hash}
|
||||
|
||||
cpu_block = sched.cpu_block_pool.get_new_blocks(1)[0]
|
||||
sched._process_store_completion(
|
||||
gpu_block_ids,
|
||||
[cpu_block.block_id],
|
||||
block_meta,
|
||||
)
|
||||
|
||||
primary_event_hash = maybe_convert_block_hash(get_block_hash(primary_hash))
|
||||
secondary_event_hash = maybe_convert_block_hash(get_block_hash(secondary_hash))
|
||||
stored = [event for event in sched.take_events() if isinstance(event, BlockStored)]
|
||||
by_hash = {event.block_hashes[0]: event for event in stored}
|
||||
assert set(by_hash) == {primary_event_hash, secondary_event_hash}
|
||||
assert by_hash[primary_event_hash].block_size == BLOCK_SIZE
|
||||
assert req.prompt_token_ids is not None
|
||||
assert by_hash[primary_event_hash].token_ids == req.prompt_token_ids[:BLOCK_SIZE]
|
||||
assert by_hash[secondary_event_hash].block_size == BLOCK_SIZE // 2
|
||||
assert (
|
||||
by_hash[secondary_event_hash].token_ids
|
||||
== req.prompt_token_ids[: BLOCK_SIZE // 2]
|
||||
)
|
||||
|
||||
primary_cpu_block = sched.cpu_block_pool.cached_block_hash_to_block.get_one_block(
|
||||
primary_hash
|
||||
)
|
||||
secondary_cpu_block = sched.cpu_block_pool.cached_block_hash_to_block.get_one_block(
|
||||
secondary_hash
|
||||
)
|
||||
assert primary_cpu_block is not None
|
||||
assert secondary_cpu_block is primary_cpu_block
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# BlockRemoved relabeled to correct medium
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_block_removed_relabeled_medium_cpu() -> None:
|
||||
"""Evicted BlockRemoved (emitted as GPU by BlockPool) is relabeled CPU."""
|
||||
# 5 total = 4 usable (null_block takes 1). Fill 4, then store 2 more to
|
||||
# evict 2 LRU blocks, producing BlockRemoved events.
|
||||
fix = make_events_scheduler(num_cpu_blocks=5, num_gpu_blocks=16)
|
||||
sched = fix.scheduler
|
||||
|
||||
# Fill CPU with 4 blocks (2 + 2).
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
# Drain store events so they don't clutter the eviction check.
|
||||
list(sched.take_events())
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
list(sched.take_events())
|
||||
|
||||
# Now store 2 more -> evicts 2 LRU blocks -> BlockRemoved emitted by pool
|
||||
# with MEDIUM_GPU, then relabeled by scheduler.take_events().
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
events = list(sched.take_events())
|
||||
|
||||
removed = [e for e in events if isinstance(e, BlockRemoved)]
|
||||
assert len(removed) >= 2, (
|
||||
f"expected >=2 BlockRemoved from eviction, got {len(removed)}"
|
||||
)
|
||||
for ev in removed:
|
||||
assert ev.medium == MEDIUM_CPU, (
|
||||
f"BlockRemoved should be relabeled CPU, got {ev.medium}"
|
||||
)
|
||||
assert ev.locality == "LOCAL", (
|
||||
f"BlockRemoved should be LOCAL, got {ev.locality}"
|
||||
)
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# lazy store emits BlockStored
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_lazy_store_emits_block_stored() -> None:
|
||||
"""Lazy-mode store completion also emits BlockStored with MEDIUM_CPU."""
|
||||
fix = make_events_scheduler(num_cpu_blocks=8, num_gpu_blocks=8, lazy=True)
|
||||
sched = fix.scheduler
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
|
||||
# Allocate, hash, free -> hashed blocks in free queue.
|
||||
req = make_request(num_blocks=2)
|
||||
gpu_blocks = []
|
||||
for blk in gpu_pool.get_new_blocks(2):
|
||||
gpu_blocks.append(blk)
|
||||
gpu_pool.cache_full_blocks(
|
||||
request=req,
|
||||
blocks=gpu_blocks,
|
||||
num_cached_blocks=0,
|
||||
num_full_blocks=2,
|
||||
block_size=BLOCK_SIZE,
|
||||
kv_cache_group_id=0,
|
||||
)
|
||||
gpu_pool.free_blocks(gpu_blocks)
|
||||
|
||||
# Push hashed blocks to LRU head (8 total - 1 null = 7 usable; 2 freed
|
||||
# hashed + 5 other free -> consume 5 fillers).
|
||||
fillers = gpu_pool.get_new_blocks(5)
|
||||
|
||||
meta = sched.build_connector_meta(make_scheduler_output({}))
|
||||
assert meta.store_event >= 0
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
gpu_pool.free_blocks(fillers)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2, f"expected 2 BlockStored, got {len(stored)}"
|
||||
for ev in stored:
|
||||
assert ev.medium == MEDIUM_CPU
|
||||
assert ev.group_idx == 0
|
||||
assert ev.kv_cache_spec_kind == "full_attention"
|
||||
assert ev.locality == "LOCAL"
|
||||
assert ev.token_ids == []
|
||||
assert ev.parent_block_hash is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# cp_world_size scales block_size for non-Mamba
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_cp_world_size_scales_block_size() -> None:
|
||||
"""block_size on BlockStored = spec.block_size * cp_world_size (FA)."""
|
||||
fix = make_events_scheduler(dcp_world_size=2)
|
||||
sched = fix.scheduler
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
vbs = BLOCK_SIZE * 2
|
||||
assert sched.cp_world_size == 2
|
||||
|
||||
req = _make_cp_request(num_blocks=1, virtual_block_size=vbs)
|
||||
gpu_blocks = _allocate_cp_gpu_blocks(gpu_pool, req, 1, vbs)
|
||||
kv_blocks = KVCacheBlocks(blocks=(gpu_blocks,))
|
||||
req.num_computed_tokens = vbs
|
||||
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
|
||||
sched_out = make_scheduler_output(
|
||||
{req.request_id: vbs},
|
||||
new_reqs={req.request_id: kv_blocks.get_block_ids()},
|
||||
)
|
||||
meta = sched.build_connector_meta(sched_out)
|
||||
assert meta.store_event >= 0
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 1
|
||||
# spec.block_size=BLOCK_SIZE, cp_world_size=2 -> BLOCK_SIZE * 2
|
||||
assert stored[0].block_size == BLOCK_SIZE * 2
|
||||
assert stored[0].locality == "LOCAL"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Mamba block_size NOT scaled by cp_world_size
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_mamba_block_size_not_scaled() -> None:
|
||||
"""Mamba group: block_size = spec.block_size (no cp scaling).
|
||||
|
||||
With cp_world_size=2, scheduler_block_size=hash_block_size=32. The
|
||||
coordinator constraints force Mamba spec.block_size=32 (must divide
|
||||
scheduler_block_size and be a multiple of hash_block_size). The event
|
||||
block_size for Mamba must be 32 (spec.block_size * 1), NOT 64
|
||||
(spec.block_size * cp_world_size) -- that is the bug this guards.
|
||||
"""
|
||||
kv_cfg = _make_mixed_kv_cache_config(
|
||||
num_blocks=16, with_mamba=True, mamba_block_size=32
|
||||
)
|
||||
fix = make_events_scheduler(
|
||||
num_cpu_blocks=8,
|
||||
num_gpu_blocks=16,
|
||||
kv_cache_config=kv_cfg,
|
||||
dcp_world_size=2,
|
||||
num_groups=2,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
|
||||
cpu_pool = sched.cpu_block_pool
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
|
||||
cpu_blk = cpu_pool.get_new_blocks(1)[0]
|
||||
gpu_blk = gpu_pool.get_new_blocks(1)[0]
|
||||
|
||||
raw_hash = make_request(num_blocks=1).block_hashes[0]
|
||||
mamba_hash = make_block_hash_with_group_id(raw_hash, group_id=1)
|
||||
gpu_blk._block_hash = mamba_hash # type: ignore[attr-defined]
|
||||
|
||||
sched._process_store_completion(
|
||||
gpu_block_ids=[gpu_blk.block_id],
|
||||
cpu_block_ids=[cpu_blk.block_id],
|
||||
)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 1
|
||||
ev = stored[0]
|
||||
assert ev.group_idx == 1
|
||||
assert ev.kv_cache_spec_kind == "mamba"
|
||||
assert ev.kv_cache_spec_sliding_window is None
|
||||
assert ev.locality == "LOCAL"
|
||||
assert ev.block_size == 32, (
|
||||
f"Mamba block_size should be unscaled (32), got {ev.block_size}"
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# multi-group FA+SW stores carry correct group_idx and kind
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_multi_group_fa_block_stored_group_idx() -> None:
|
||||
"""Two distinct groups (FA + SW): each BlockStored carries its group_idx
|
||||
and kind. HybridKVCacheCoordinator requires >=2 distinct spec groups, so
|
||||
we use FA (group 0) + SlidingWindow (group 1)."""
|
||||
kv_cfg = _make_mixed_kv_cache_config(num_blocks=16, sliding_window=32)
|
||||
fix = make_events_scheduler(
|
||||
num_cpu_blocks=8,
|
||||
num_gpu_blocks=16,
|
||||
kv_cache_config=kv_cfg,
|
||||
num_groups=2,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
|
||||
cpu_pool = sched.cpu_block_pool
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
raw_hash = make_request(num_blocks=1).block_hashes[0]
|
||||
|
||||
# Store one block for each group via direct _process_store_completion.
|
||||
for gidx in (0, 1):
|
||||
cpu_blk = cpu_pool.get_new_blocks(1)[0]
|
||||
gpu_blk = gpu_pool.get_new_blocks(1)[0]
|
||||
gpu_blk._block_hash = make_block_hash_with_group_id( # type: ignore
|
||||
raw_hash, group_id=gidx
|
||||
)
|
||||
sched._process_store_completion(
|
||||
gpu_block_ids=[gpu_blk.block_id],
|
||||
cpu_block_ids=[cpu_blk.block_id],
|
||||
)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2
|
||||
by_group = {ev.group_idx: ev for ev in stored}
|
||||
assert set(by_group) == {0, 1}
|
||||
assert by_group[0].kv_cache_spec_kind == "full_attention"
|
||||
assert by_group[0].kv_cache_spec_sliding_window is None
|
||||
assert by_group[1].kv_cache_spec_kind == "sliding_window"
|
||||
assert by_group[1].kv_cache_spec_sliding_window == 32
|
||||
for ev in stored:
|
||||
assert ev.locality == "LOCAL"
|
||||
|
||||
|
||||
def test_disk_mode_block_removed_relabeled_storage() -> None:
|
||||
"""Disk mode: evicted BlockRemoved relabeled to MEDIUM_STORAGE."""
|
||||
fix = make_events_scheduler(
|
||||
num_cpu_blocks=5,
|
||||
num_gpu_blocks=16,
|
||||
disk_capacity_bytes=_BYTES_PER_BLOCK * 5,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
assert sched.kv_event_medium == MEDIUM_STORAGE
|
||||
|
||||
# Fill disk with 4 blocks (2 + 2).
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
list(sched.take_events())
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
list(sched.take_events())
|
||||
|
||||
# Store 2 more -> evicts 2 LRU blocks -> BlockRemoved relabeled STORAGE.
|
||||
_do_eager_store(fix, num_blocks=2)
|
||||
events = list(sched.take_events())
|
||||
|
||||
removed = [e for e in events if isinstance(e, BlockRemoved)]
|
||||
assert len(removed) >= 2, (
|
||||
f"expected >=2 BlockRemoved from eviction, got {len(removed)}"
|
||||
)
|
||||
for ev in removed:
|
||||
assert ev.medium == MEDIUM_STORAGE, (
|
||||
f"BlockRemoved should be relabeled STORAGE, got {ev.medium}"
|
||||
)
|
||||
assert ev.locality == "LOCAL", (
|
||||
f"BlockRemoved should be LOCAL, got {ev.locality}"
|
||||
)
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2
|
||||
for ev in stored:
|
||||
assert ev.medium == MEDIUM_STORAGE
|
||||
|
||||
|
||||
def test_mamba_align_skips_positional_event_metadata() -> None:
|
||||
"""Mamba align emits events only from explicit boundary handoffs."""
|
||||
vbs = BLOCK_SIZE * 2
|
||||
kv_cfg = _make_mixed_kv_cache_config(
|
||||
num_blocks=16, with_mamba=True, mamba_block_size=32
|
||||
)
|
||||
fix = make_events_scheduler(
|
||||
num_cpu_blocks=8,
|
||||
num_gpu_blocks=16,
|
||||
kv_cache_config=kv_cfg,
|
||||
dcp_world_size=2,
|
||||
num_groups=2,
|
||||
)
|
||||
sched = fix.scheduler
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
|
||||
req = _make_cp_request(num_blocks=4, virtual_block_size=vbs)
|
||||
fa_blocks = _allocate_cp_gpu_blocks(gpu_pool, req, 2, vbs, group_id=0)
|
||||
mamba_blocks = _allocate_cp_gpu_blocks(gpu_pool, req, 2, vbs, group_id=1)
|
||||
kv_blocks = KVCacheBlocks(blocks=(fa_blocks, mamba_blocks))
|
||||
req.num_computed_tokens = 4 * vbs
|
||||
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
|
||||
|
||||
block_ids = kv_blocks.get_block_ids()
|
||||
sched_out = make_scheduler_output(
|
||||
{req.request_id: 4 * vbs},
|
||||
new_reqs={req.request_id: block_ids},
|
||||
)
|
||||
meta = sched.build_connector_meta(sched_out)
|
||||
assert meta.store_event >= 0
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
|
||||
events = list(sched.take_events())
|
||||
stored = [e for e in events if isinstance(e, BlockStored)]
|
||||
assert len(stored) == 2
|
||||
assert {ev.group_idx for ev in stored} == {0}
|
||||
assert req.prompt_token_ids is not None
|
||||
for idx, ev in enumerate(stored):
|
||||
assert ev.block_size == vbs
|
||||
assert ev.token_ids == req.prompt_token_ids[idx * vbs : (idx + 1) * vbs]
|
||||
expected_hash = maybe_convert_block_hash(
|
||||
get_block_hash(make_block_hash_with_group_id(req.block_hashes[idx], 0))
|
||||
)
|
||||
assert ev.block_hashes == [expected_hash]
|
||||
|
||||
|
||||
def test_scratch_group_store_emits_events_for_cacheable_groups_only() -> None:
|
||||
"""Event metadata is resolved only for prefix-cacheable groups.
|
||||
|
||||
A scratch group (GLM-5.3-Flash kpool tail) has a block size that does not
|
||||
divide the hash block size, so viewing the request hashes at its block
|
||||
size is impossible; the store must skip it and still emit BlockStored
|
||||
for the attention blocks.
|
||||
"""
|
||||
fix = make_events_scheduler(kv_cache_config=_make_scratch_kv_cache_config(16))
|
||||
sched = fix.scheduler
|
||||
gpu_pool = fix.gpu_block_pool
|
||||
num_blocks = 2
|
||||
|
||||
req = make_request(num_blocks=num_blocks)
|
||||
fa_blocks = _allocate_gpu_blocks(gpu_pool, req, num_blocks, group_id=0)
|
||||
scratch_block = gpu_pool.get_new_blocks(1)
|
||||
kv_blocks = KVCacheBlocks(blocks=(fa_blocks, scratch_block))
|
||||
req.num_computed_tokens = num_blocks * BLOCK_SIZE
|
||||
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
|
||||
sched_out = make_scheduler_output(
|
||||
{req.request_id: num_blocks * BLOCK_SIZE},
|
||||
new_reqs={req.request_id: kv_blocks.get_block_ids()},
|
||||
)
|
||||
meta = sched.build_connector_meta(sched_out)
|
||||
assert sorted(meta.store_gpu_blocks) == sorted(b.block_id for b in fa_blocks)
|
||||
simulate_store_completion(sched, meta.store_event)
|
||||
|
||||
events = list(sched.take_events())
|
||||
assert len(events) == num_blocks
|
||||
assert all(isinstance(e, BlockStored) for e in events)
|
||||
assert {e.group_idx for e in events} == {0}
|
||||
assert all(len(e.token_ids) == BLOCK_SIZE for e in events)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,751 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Worker-side unit tests for SimpleCPUOffloadConnector.
|
||||
|
||||
Covers the GPU->CPU store cross-stream synchronization: the store copy must be
|
||||
ordered after the compute stream that writes the KV blocks, otherwise it can
|
||||
read partially written / stale blocks and silently corrupt the CPU cache.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from contextlib import nullcontext
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if not current_platform.is_cuda_alike():
|
||||
pytest.skip("Requires CUDA or ROCm", allow_module_level=True)
|
||||
|
||||
from tests.v1.attention.utils import dense_kv_cache_tensor, dense_kv_cache_views
|
||||
from tests.v1.kv_connector.unit.test_kv_connector_lifecycle import (
|
||||
_make_empty_scheduler_output,
|
||||
)
|
||||
from vllm.config import CacheConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
|
||||
SimpleCPUOffloadConnector,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_planning import (
|
||||
get_kv_cache_config_from_groups,
|
||||
is_kv_cache_spec_uniform,
|
||||
)
|
||||
from vllm.v1.core.kv_cache_utils import resolve_kv_cache_block_sizes
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
FullAttentionSpec,
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheLayout,
|
||||
KVCacheSpec,
|
||||
KVCacheTensor,
|
||||
MLAAttentionSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.copy_backend import DmaCopyBackend
|
||||
from vllm.v1.simple_kv_offload.cuda_mem_ops import (
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
|
||||
build_params,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.disk_backend import DiskBackend
|
||||
from vllm.v1.simple_kv_offload.metadata import (
|
||||
SimpleCPUOffloadMetadata,
|
||||
SimpleCPUOffloadWorkerMetadata,
|
||||
)
|
||||
from vllm.v1.simple_kv_offload.worker import SimpleCPUOffloadWorker
|
||||
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
|
||||
from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin
|
||||
from vllm.v1.worker.utils import allocate_kv_cache
|
||||
|
||||
NUM_BLOCKS = 64
|
||||
BLOCK_BYTES = 4096
|
||||
ITERS = 30
|
||||
# Keep the compute stream busy so the KV write lands late; this makes the
|
||||
# store-vs-compute race deterministic instead of timing-dependent.
|
||||
SLEEP_CYCLES = 50_000_000
|
||||
|
||||
|
||||
def _make_worker(
|
||||
kv_cache_config: KVCacheConfig | None, cpu_capacity_bytes: int
|
||||
) -> SimpleCPUOffloadWorker:
|
||||
return SimpleCPUOffloadWorker(None, kv_cache_config, cpu_capacity_bytes)
|
||||
|
||||
|
||||
def _make_backend() -> tuple[DmaCopyBackend, torch.Tensor, torch.Tensor]:
|
||||
gpu = {"k": torch.zeros((NUM_BLOCKS, BLOCK_BYTES), dtype=torch.int8, device="cuda")}
|
||||
cpu = {
|
||||
"k": torch.zeros(
|
||||
(NUM_BLOCKS, BLOCK_BYTES), dtype=torch.int8, device="cpu", pin_memory=True
|
||||
)
|
||||
}
|
||||
low_pri, _ = torch.cuda.Stream.priority_range()
|
||||
backend = DmaCopyBackend()
|
||||
backend.init(
|
||||
gpu,
|
||||
cpu,
|
||||
gpu["k"].device,
|
||||
torch.cuda.Stream(priority=low_pri),
|
||||
torch.cuda.Stream(priority=low_pri),
|
||||
)
|
||||
return backend, gpu["k"], cpu["k"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_v2", [False, True])
|
||||
def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
|
||||
"""A finished request's final store must drain without another model step."""
|
||||
backend, gpu, cpu = _make_backend()
|
||||
worker = _make_worker(None, 0)
|
||||
worker._backend = backend
|
||||
connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
|
||||
connector.worker_handler = worker
|
||||
output = _make_empty_scheduler_output()
|
||||
output.kv_connector_metadata = SimpleCPUOffloadMetadata(
|
||||
store_event=0, store_gpu_blocks=[0], store_cpu_blocks=[0]
|
||||
)
|
||||
module = "vllm.v1.worker.kv_connector_model_runner_mixin"
|
||||
monkeypatch.setattr(f"{module}.get_kv_transfer_group", lambda: connector)
|
||||
monkeypatch.setattr(f"{module}.set_forward_context", lambda *a: nullcontext())
|
||||
monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
|
||||
try:
|
||||
gpu.fill_(91)
|
||||
if use_v2:
|
||||
active = ActiveKVConnector.__new__(ActiveKVConnector)
|
||||
active.kv_connector = connector
|
||||
active._disabled = False
|
||||
active._pending_load_kwargs = None
|
||||
module = "vllm.v1.worker.gpu.kv_connector"
|
||||
monkeypatch.setattr(f"{module}.is_forward_context_available", lambda: True)
|
||||
monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
|
||||
result = active.no_forward(output)
|
||||
else:
|
||||
result = KVConnectorModelRunnerMixin.kv_connector_no_forward(output, None)
|
||||
completion = (
|
||||
result.kv_connector_output.kv_connector_worker_meta
|
||||
if result.kv_connector_output is not None
|
||||
else None
|
||||
)
|
||||
deadline = time.monotonic() + 5
|
||||
while completion is None and time.monotonic() < deadline:
|
||||
connector.get_finished(set())
|
||||
completion = connector.build_connector_worker_meta()
|
||||
time.sleep(0.001)
|
||||
assert completion is not None, "CPU store never completed on the empty step"
|
||||
assert isinstance(completion, SimpleCPUOffloadWorkerMetadata)
|
||||
assert completion.completed_store_events == {0: 1}
|
||||
assert torch.equal(cpu[0], gpu[0].cpu())
|
||||
finally:
|
||||
backend.shutdown()
|
||||
|
||||
|
||||
def test_deferred_store_waits_for_draft_forward(monkeypatch):
|
||||
"""Target completion must not submit the store before draft finalization."""
|
||||
backend, gpu, cpu = _make_backend()
|
||||
worker = _make_worker(None, 0)
|
||||
worker._backend = backend
|
||||
connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
|
||||
connector.worker_handler = worker
|
||||
output = _make_empty_scheduler_output()
|
||||
output.kv_connector_metadata = SimpleCPUOffloadMetadata(
|
||||
store_event=0, store_gpu_blocks=[0], store_cpu_blocks=[0]
|
||||
)
|
||||
module = "vllm.v1.worker.kv_connector_model_runner_mixin"
|
||||
monkeypatch.setattr(f"{module}.get_kv_transfer_group", lambda: connector)
|
||||
monkeypatch.setattr(f"{module}.has_kv_transfer_group", lambda: True)
|
||||
monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
|
||||
launch = MagicMock(wraps=backend.launch_copy)
|
||||
monkeypatch.setattr(backend, "launch_copy", launch)
|
||||
try:
|
||||
with KVConnectorModelRunnerMixin._get_kv_connector_output(
|
||||
output, defer_finalize=True
|
||||
):
|
||||
gpu.fill_(17)
|
||||
launch.assert_not_called()
|
||||
gpu.fill_(91)
|
||||
KVConnectorModelRunnerMixin.finalize_kv_connector()
|
||||
assert launch.call_count == 1
|
||||
completion = None
|
||||
deadline = time.monotonic() + 5
|
||||
while completion is None and time.monotonic() < deadline:
|
||||
connector.get_finished(set())
|
||||
completion = connector.build_connector_worker_meta()
|
||||
time.sleep(0.001)
|
||||
assert completion is not None
|
||||
assert completion.completed_store_events == {0: 1}
|
||||
assert torch.equal(cpu[0], gpu[0].cpu())
|
||||
assert launch.call_count == 1
|
||||
finally:
|
||||
backend.shutdown()
|
||||
|
||||
|
||||
def _drive_store(
|
||||
backend: DmaCopyBackend,
|
||||
gpu: torch.Tensor,
|
||||
cpu: torch.Tensor,
|
||||
*,
|
||||
with_barrier: bool,
|
||||
) -> int:
|
||||
"""Run ITERS store cycles; return how many landed corrupted in the CPU pool.
|
||||
|
||||
Each cycle writes a unique value on a compute stream (after a deliberate
|
||||
delay) and then issues the GPU->CPU store. The store is issued *after* the
|
||||
write in host program order, mirroring the connector's deferred-store
|
||||
assumption. Only the compute-done event creates a real device-side
|
||||
happens-before edge.
|
||||
"""
|
||||
block_ids = list(range(gpu.shape[0]))
|
||||
compute_stream = torch.cuda.Stream()
|
||||
corrupt = 0
|
||||
for it in range(ITERS):
|
||||
val = (it % 126) + 1 # 1..126; distinct from the zero-initialized pool
|
||||
with torch.cuda.stream(compute_stream):
|
||||
torch.cuda._sleep(SLEEP_CYCLES)
|
||||
gpu.fill_(val)
|
||||
|
||||
wait_event = None
|
||||
if with_barrier:
|
||||
wait_event = torch.Event()
|
||||
wait_event.record(compute_stream)
|
||||
|
||||
store_events: list[tuple[int, torch.Event]] = []
|
||||
backend.launch_copy(
|
||||
block_ids,
|
||||
block_ids,
|
||||
is_store=True,
|
||||
event_idx=it,
|
||||
events_list=store_events,
|
||||
wait_event=wait_event,
|
||||
)
|
||||
|
||||
deadline = time.time() + 10.0
|
||||
while not store_events and time.time() < deadline:
|
||||
time.sleep(0.0005)
|
||||
assert store_events, "background copy was never enqueued"
|
||||
store_events[0][1].synchronize()
|
||||
|
||||
if int((cpu[:, 0].to(torch.int32) != val).sum().item()):
|
||||
corrupt += 1
|
||||
|
||||
# Drain the compute stream before returning: in the no-barrier control
|
||||
# phase the store never waits on compute, so the host loop runs far ahead
|
||||
# and leaves a backlog of sleep+fill kernels in flight. Without this, the
|
||||
# leftover control-phase fills race the barrier phase's fill->copy window
|
||||
# on the shared gpu tensor and flakily corrupt one iteration.
|
||||
compute_stream.synchronize()
|
||||
return corrupt
|
||||
|
||||
|
||||
def test_store_orders_after_compute_write():
|
||||
"""The store must wait for the compute event; without it, it races.
|
||||
|
||||
Asserts both directions so the test is self-validating: the no-barrier
|
||||
control must actually corrupt (proving the race window is exercised), and
|
||||
the fixed path with the compute-done event must be clean.
|
||||
"""
|
||||
backend, gpu, cpu = _make_backend()
|
||||
try:
|
||||
control = _drive_store(backend, gpu, cpu, with_barrier=False)
|
||||
fixed = _drive_store(backend, gpu, cpu, with_barrier=True)
|
||||
finally:
|
||||
backend.shutdown()
|
||||
|
||||
assert control > 0, (
|
||||
"no-barrier store did not race the compute write; the test no longer "
|
||||
"exercises the hazard it is meant to guard"
|
||||
)
|
||||
assert fixed == 0, f"store raced compute even with the barrier: {fixed} corrupt"
|
||||
|
||||
|
||||
class _RecordingBackend:
|
||||
"""Captures launch_copy calls without touching the GPU."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def launch_copy(
|
||||
self,
|
||||
src_blocks,
|
||||
dst_blocks,
|
||||
is_store,
|
||||
event_idx,
|
||||
events_list,
|
||||
wait_event=None,
|
||||
) -> None:
|
||||
self.calls.append({"is_store": is_store, "wait_event": wait_event})
|
||||
|
||||
|
||||
def test_transfer_hooks_pass_wait_event_for_store_only():
|
||||
"""wait_for_save gates stores on a compute-done event; start_load_kv does not."""
|
||||
worker = _make_worker(
|
||||
kv_cache_config=None,
|
||||
cpu_capacity_bytes=0,
|
||||
)
|
||||
recording = _RecordingBackend()
|
||||
worker._backend = recording
|
||||
worker._connector_metadata = SimpleCPUOffloadMetadata(
|
||||
load_event=0,
|
||||
load_gpu_blocks=[0],
|
||||
load_cpu_blocks=[0],
|
||||
store_event=1,
|
||||
store_gpu_blocks=[1],
|
||||
store_cpu_blocks=[1],
|
||||
)
|
||||
|
||||
worker.start_load_kv()
|
||||
worker.wait_for_save()
|
||||
|
||||
store_calls = [c for c in recording.calls if c["is_store"]]
|
||||
load_calls = [c for c in recording.calls if not c["is_store"]]
|
||||
assert len(store_calls) == 1
|
||||
assert len(load_calls) == 1
|
||||
assert isinstance(store_calls[0]["wait_event"], torch.Event)
|
||||
assert load_calls[0]["wait_event"] is None
|
||||
|
||||
|
||||
def test_build_params_src_access_order():
|
||||
"""build_params defaults to ANY and honors an explicit STREAM override."""
|
||||
gpu = {"k": torch.zeros((4, 64), dtype=torch.int8, device="cuda")}
|
||||
cpu = {"k": torch.zeros((4, 64), dtype=torch.int8, device="cpu")}
|
||||
stream = torch.cuda.Stream()
|
||||
|
||||
default = build_params(gpu, cpu, stream)
|
||||
assert default.attrs.srcAccessOrder == CU_MEMCPY_SRC_ACCESS_ORDER_ANY
|
||||
|
||||
ordered = build_params(
|
||||
gpu, cpu, stream, src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_STREAM
|
||||
)
|
||||
assert ordered.attrs.srcAccessOrder == CU_MEMCPY_SRC_ACCESS_ORDER_STREAM
|
||||
|
||||
|
||||
@pytest.mark.parametrize("layout", list(KVCacheLayout))
|
||||
def test_register_shared_kv_cache_storage(monkeypatch, layout: KVCacheLayout):
|
||||
num_blocks = 4
|
||||
num_layers = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=2,
|
||||
head_size=2,
|
||||
dtype=torch.float16,
|
||||
)
|
||||
raw = torch.zeros(
|
||||
num_blocks * num_layers * spec.page_size_bytes,
|
||||
dtype=torch.int8,
|
||||
device="cuda",
|
||||
)
|
||||
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
|
||||
layer_names = [f"layer.{i}" for i in range(num_layers)]
|
||||
cache_config = MagicMock(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
dense_kv_cache_tensor(
|
||||
raw, spec, num_blocks, num_layers, layout, layer_names
|
||||
)
|
||||
],
|
||||
)
|
||||
worker = _make_worker(
|
||||
kv_cache_config=cache_config,
|
||||
cpu_capacity_bytes=raw.nbytes,
|
||||
)
|
||||
worker._backend = MagicMock()
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
|
||||
worker.register_kv_caches(
|
||||
{f"layer.{layer_idx}": cache for layer_idx, cache in enumerate(caches)}
|
||||
)
|
||||
|
||||
assert worker.gpu_kv_caches is not None
|
||||
if layout.is_layer_compact and not layout.is_block_compact:
|
||||
expected_regions = num_layers * spec.num_heads
|
||||
expected_block_bytes = spec.page_size_bytes // spec.num_heads
|
||||
elif layout.is_layer_compact:
|
||||
expected_regions = num_layers
|
||||
expected_block_bytes = spec.page_size_bytes
|
||||
else:
|
||||
expected_regions = 1
|
||||
expected_block_bytes = spec.page_size_bytes * num_layers
|
||||
assert len(worker.gpu_kv_caches) == expected_regions
|
||||
assert {cache.shape for cache in worker.gpu_kv_caches.values()} == {
|
||||
(num_blocks, expected_block_bytes)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("num_layers", [1, 2])
|
||||
def test_explicit_cpu_blocks_bound_live_worker_allocation(monkeypatch, num_layers):
|
||||
"""Different live KV strides must honor the same explicit CPU pool size."""
|
||||
num_blocks = 4
|
||||
names = [f"layer.{i}" for i in range(num_layers)]
|
||||
raw = torch.zeros(
|
||||
num_layers * num_blocks * BLOCK_BYTES, dtype=torch.int8, device="cuda"
|
||||
)
|
||||
config = KVCacheConfig(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=raw.nbytes,
|
||||
layers=names,
|
||||
layer_stride=num_blocks * BLOCK_BYTES,
|
||||
block_stride=BLOCK_BYTES,
|
||||
)
|
||||
],
|
||||
kv_cache_groups=[],
|
||||
)
|
||||
caches = dict(zip(names, raw.view(num_layers, num_blocks, BLOCK_BYTES)))
|
||||
worker = SimpleCPUOffloadWorker(None, config, 8 * BLOCK_BYTES, num_cpu_blocks=4)
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
try:
|
||||
worker.register_kv_caches(caches)
|
||||
assert worker.num_cpu_blocks == 4
|
||||
assert worker.cpu_kv_caches is not None
|
||||
assert all(t.shape[0] == 4 for t in worker.cpu_kv_caches.values())
|
||||
assert sum(t.nbytes for t in worker.cpu_kv_caches.values()) <= 8 * BLOCK_BYTES
|
||||
finally:
|
||||
if worker._backend is not None:
|
||||
worker._backend.shutdown()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"capacity_bytes, count, local_capacity",
|
||||
[(8 * BLOCK_BYTES, 5, 4), (BLOCK_BYTES, 1, 0)],
|
||||
)
|
||||
def test_explicit_cpu_blocks_reject_heavier_worker_before_allocation(
|
||||
capacity_bytes, count, local_capacity
|
||||
):
|
||||
"""A count that fits the scheduler's stage must fail on a smaller worker."""
|
||||
names = ["layer.0", "layer.1"]
|
||||
raw = torch.zeros(2 * 4 * BLOCK_BYTES, dtype=torch.int8, device="cuda")
|
||||
config = KVCacheConfig(
|
||||
num_blocks=4,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=raw.nbytes,
|
||||
layers=names,
|
||||
layer_stride=4 * BLOCK_BYTES,
|
||||
block_stride=BLOCK_BYTES,
|
||||
)
|
||||
],
|
||||
kv_cache_groups=[],
|
||||
)
|
||||
worker = SimpleCPUOffloadWorker(None, config, capacity_bytes, num_cpu_blocks=count)
|
||||
caches = dict(zip(names, raw.view(2, 4, BLOCK_BYTES)))
|
||||
with pytest.raises(ValueError, match=f"local offload capacity {local_capacity}"):
|
||||
worker.register_kv_caches(caches)
|
||||
assert worker.cpu_kv_caches is None
|
||||
|
||||
|
||||
def test_register_kv_cache_storage_with_trailing_padding(monkeypatch):
|
||||
num_blocks = 4
|
||||
block_bytes = 32
|
||||
cache_bytes = num_blocks * block_bytes
|
||||
raw = torch.zeros(4096, dtype=torch.int8, device="cuda")
|
||||
cache = raw[:cache_bytes].view(num_blocks, block_bytes)
|
||||
worker = _make_worker(
|
||||
kv_cache_config=MagicMock(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
KVCacheTensor(
|
||||
size=cache_bytes,
|
||||
layers=["layer.0"],
|
||||
layer_stride=cache_bytes,
|
||||
block_stride=block_bytes,
|
||||
)
|
||||
],
|
||||
),
|
||||
cpu_capacity_bytes=cache_bytes,
|
||||
)
|
||||
worker._backend = MagicMock()
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
|
||||
worker.register_kv_caches({"layer.0": cache})
|
||||
|
||||
assert worker.gpu_kv_caches is not None
|
||||
assert list(worker.gpu_kv_caches) == ["layer.0"]
|
||||
assert worker.gpu_kv_caches["layer.0"].shape == (num_blocks, block_bytes)
|
||||
|
||||
|
||||
def test_register_separate_kv_head_groups(monkeypatch):
|
||||
# LHBNC hoists the K/V head groups outside the block dim, so each layer's
|
||||
# blocks are registered as one region per group (K, V).
|
||||
layout = KVCacheLayout.LHBNC
|
||||
num_blocks = 4
|
||||
num_layers = 2
|
||||
spec = FullAttentionSpec(
|
||||
block_size=2,
|
||||
num_kv_heads=2,
|
||||
head_size=2,
|
||||
dtype=torch.float16,
|
||||
num_head_slots=2,
|
||||
state_content_bytes=2 * 2 * 2,
|
||||
)
|
||||
raw = torch.zeros(
|
||||
num_blocks * num_layers * spec.page_size_bytes,
|
||||
dtype=torch.int8,
|
||||
device="cuda",
|
||||
)
|
||||
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
|
||||
layer_names = [f"layer.{i}" for i in range(num_layers)]
|
||||
worker = _make_worker(
|
||||
kv_cache_config=MagicMock(
|
||||
num_blocks=num_blocks,
|
||||
kv_cache_tensors=[
|
||||
dense_kv_cache_tensor(
|
||||
raw, spec, num_blocks, num_layers, layout, layer_names
|
||||
)
|
||||
],
|
||||
),
|
||||
cpu_capacity_bytes=raw.nbytes,
|
||||
)
|
||||
worker._backend = MagicMock()
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
|
||||
worker.register_kv_caches(
|
||||
{f"layer.{layer_idx}": cache for layer_idx, cache in enumerate(caches)}
|
||||
)
|
||||
|
||||
assert worker.gpu_kv_caches is not None
|
||||
assert len(worker.gpu_kv_caches) == num_layers * spec.num_heads
|
||||
per_group_block_bytes = (
|
||||
spec.num_kv_heads * spec.block_size * spec.head_size * spec.dtype.itemsize
|
||||
)
|
||||
assert {cache.shape for cache in worker.gpu_kv_caches.values()} == {
|
||||
(num_blocks, per_group_block_bytes)
|
||||
}
|
||||
|
||||
|
||||
def _dsa_specs(num_layers: int, block_size: int) -> dict[str, KVCacheSpec]:
|
||||
"""A DSA model's per-layer specs (DeepSeek-V3.2, GLM-5.2).
|
||||
|
||||
Each decoder layer contributes an MLA latent cache and the indexer's key
|
||||
cache, whose pages differ in size (``MLAAttentionSpec`` off ``head_size``:
|
||||
512 + 64 for the latent, 128 fp8 keys + one fp32 scale per 128 elements for
|
||||
the indexer). Both are ``MLAAttentionSpec`` with the same block size, so the
|
||||
hybrid allocator puts them in one ``UniformTypeKVCacheSpecs`` cache group.
|
||||
See ``DeepseekV32IndexerCache.get_kv_cache_spec`` and
|
||||
``MLAAttention.get_kv_cache_spec``.
|
||||
"""
|
||||
specs: dict[str, KVCacheSpec] = {}
|
||||
for i in range(num_layers):
|
||||
specs[f"model.layers.{i}.self_attn.attn"] = MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=512 + 64,
|
||||
dtype=torch.uint8,
|
||||
cache_dtype_str="fp8",
|
||||
)
|
||||
specs[f"model.layers.{i}.self_attn.indexer.k_cache"] = MLAAttentionSpec(
|
||||
block_size=block_size,
|
||||
num_kv_heads=1,
|
||||
head_size=128 + 128 // 128 * 4,
|
||||
dtype=torch.uint8,
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def test_register_mixed_page_sizes_in_one_cache_group(monkeypatch):
|
||||
"""Sparse-MLA models mix page sizes inside one cache group.
|
||||
|
||||
The MLA latent and indexer key caches of a layer have different page sizes,
|
||||
so the allocation has no single per-layer block size to reinterpret it with:
|
||||
``num_layers * (mla_page + indexer_page)`` is not a multiple of either page.
|
||||
Registration must derive each region from the placement metadata instead.
|
||||
"""
|
||||
num_layers = 4
|
||||
block_size = 64
|
||||
specs = _dsa_specs(num_layers, block_size)
|
||||
# Differing head sizes make the specs non-identical but same-type, which is
|
||||
# what lands both caches of a layer in one group.
|
||||
assert not is_kv_cache_spec_uniform(specs)
|
||||
assert UniformTypeKVCacheSpecs.is_uniform_type(specs)
|
||||
group = KVCacheGroupSpec(
|
||||
list(specs),
|
||||
UniformTypeKVCacheSpecs(block_size=block_size, kv_cache_specs=specs),
|
||||
)
|
||||
|
||||
# DEEPSEEK_V32_INDEXER declares no supported layouts, so resolution lands on
|
||||
# the default preference: layer-outermost, one region per layer.
|
||||
layout = KVCacheLayout.LBNHC
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.cache_config = CacheConfig()
|
||||
vllm_config.cache_config.kv_cache_layout = layout.name
|
||||
vllm_config.cache_config.num_gpu_blocks_override = None
|
||||
vllm_config.attention_config.hisparse_config = None
|
||||
vllm_config.kv_transfer_config = None
|
||||
|
||||
pages = [spec.page_size_bytes for spec in specs.values()]
|
||||
num_blocks = 4
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
vllm_config, [group], sum(pages) * num_blocks
|
||||
)
|
||||
assert kv_cache_config.num_blocks == num_blocks
|
||||
assert len(set(pages)) > 1, "the mixed page sizes are what this test covers"
|
||||
|
||||
kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
|
||||
worker = _make_worker(
|
||||
kv_cache_config=kv_cache_config,
|
||||
cpu_capacity_bytes=sum(pages) * num_blocks,
|
||||
)
|
||||
worker._backend = MagicMock()
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
assert worker.gpu_kv_caches is not None
|
||||
# One region per layer, each with that layer's own page as its block stride.
|
||||
assert sorted(worker.gpu_kv_caches) == sorted(specs)
|
||||
assert {name: cache.shape[1] for name, cache in worker.gpu_kv_caches.items()} == {
|
||||
name: spec.page_size_bytes for name, spec in specs.items()
|
||||
}
|
||||
assert all(cache.shape[0] == num_blocks for cache in worker.gpu_kv_caches.values())
|
||||
|
||||
# Every registered region must alias the bytes the model writes through, or
|
||||
# offloaded blocks would be copied from the wrong place.
|
||||
for name, cache in kv_caches.items():
|
||||
region = worker.gpu_kv_caches[name]
|
||||
assert region.data_ptr() == cache.data_ptr()
|
||||
assert region.stride(0) == specs[name].page_size_bytes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rank_blocks", [1, 5])
|
||||
def test_register_mixed_page_sizes_odd_block_counts(monkeypatch, rank_blocks):
|
||||
"""Registration holds at block counts that are not powers of two.
|
||||
|
||||
``num_blocks`` comes out of ``available_memory // bytes_per_block``, so
|
||||
any integer is reachable. Registration derives regions from the config's
|
||||
own block count and strides, and the CPU pool rounds down from the same
|
||||
per-block byte total; none of it assumes anything about how the count
|
||||
was reached.
|
||||
"""
|
||||
num_layers = 4
|
||||
block_size = 64
|
||||
specs = _dsa_specs(num_layers, block_size)
|
||||
group = KVCacheGroupSpec(
|
||||
list(specs),
|
||||
UniformTypeKVCacheSpecs(block_size=block_size, kv_cache_specs=specs),
|
||||
)
|
||||
layout = KVCacheLayout.LBNHC
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.cache_config = CacheConfig()
|
||||
vllm_config.cache_config.kv_cache_layout = layout.name
|
||||
vllm_config.cache_config.num_gpu_blocks_override = None
|
||||
vllm_config.attention_config.hisparse_config = None
|
||||
vllm_config.kv_transfer_config = None
|
||||
|
||||
pages = [spec.page_size_bytes for spec in specs.values()]
|
||||
kv_cache_config = get_kv_cache_config_from_groups(
|
||||
vllm_config, [group], sum(pages) * rank_blocks
|
||||
)
|
||||
assert kv_cache_config.num_blocks == rank_blocks
|
||||
|
||||
kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
|
||||
worker = _make_worker(
|
||||
kv_cache_config=kv_cache_config,
|
||||
cpu_capacity_bytes=sum(pages) * rank_blocks,
|
||||
)
|
||||
worker._backend = MagicMock()
|
||||
monkeypatch.setattr("vllm.v1.simple_kv_offload.worker.PIN_MEMORY", False)
|
||||
|
||||
worker.register_kv_caches(kv_caches)
|
||||
|
||||
assert worker.gpu_kv_caches is not None
|
||||
assert {n: c.shape for n, c in worker.gpu_kv_caches.items()} == {
|
||||
name: (rank_blocks, spec.page_size_bytes) for name, spec in specs.items()
|
||||
}
|
||||
assert worker.num_cpu_blocks == rank_blocks
|
||||
|
||||
|
||||
def test_mixed_page_byte_placement_is_dcp_invariant():
|
||||
"""DCP scales a block's token span, not its byte placement.
|
||||
|
||||
``get_kv_cache_config_from_groups`` never reads
|
||||
``decode_context_parallel_size``, so every placement field registration
|
||||
derives regions from is identical at dcp=1 and dcp=2. What DCP scales is
|
||||
the block's token span, reported by ``resolve_kv_cache_block_sizes``;
|
||||
checking that it doubles proves DCP was actually in effect, or the
|
||||
identity above would be trivially true.
|
||||
"""
|
||||
specs = _dsa_specs(4, block_size=128)
|
||||
|
||||
placements = []
|
||||
for dcp_size in (1, 2):
|
||||
group = KVCacheGroupSpec(
|
||||
list(specs),
|
||||
UniformTypeKVCacheSpecs(block_size=128, kv_cache_specs=specs),
|
||||
)
|
||||
vllm_config = MagicMock()
|
||||
vllm_config.cache_config = CacheConfig()
|
||||
vllm_config.cache_config.block_size = 128
|
||||
vllm_config.cache_config.kv_cache_layout = KVCacheLayout.LBNHC.name
|
||||
vllm_config.cache_config.num_gpu_blocks_override = None
|
||||
vllm_config.parallel_config.decode_context_parallel_size = dcp_size
|
||||
vllm_config.attention_config.hisparse_config = None
|
||||
vllm_config.kv_transfer_config = None
|
||||
|
||||
page_bytes = sum(spec.page_size_bytes for spec in specs.values())
|
||||
config = get_kv_cache_config_from_groups(vllm_config, [group], page_bytes * 4)
|
||||
scheduler_block_size, _ = resolve_kv_cache_block_sizes(config, vllm_config)
|
||||
assert scheduler_block_size == 128 * dcp_size
|
||||
placements.append(
|
||||
[
|
||||
(t.size, tuple(t.layers), t.layer_stride, t.block_stride, t.offset)
|
||||
for t in config.kv_cache_tensors
|
||||
]
|
||||
)
|
||||
|
||||
assert placements[0] == placements[1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("block_bytes", "use_page_cache", "expect_ok"),
|
||||
[
|
||||
(4096, True, True), # aligned control
|
||||
(3 * 512, True, True), # 512-aligned only: fine for buffered I/O
|
||||
(3 * 512, False, False), # O_DIRECT keeps enforcing 4096 alignment
|
||||
],
|
||||
)
|
||||
def test_disk_backend_alignment_only_required_for_direct_io(
|
||||
tmp_path, monkeypatch, block_bytes: int, use_page_cache: bool, expect_ok: bool
|
||||
):
|
||||
"""The 4096 stride assert belongs to O_DIRECT; page-cache I/O must not hit it.
|
||||
|
||||
Hybrid models (e.g. 101 per-rank cache tensors) sum to a block stride that
|
||||
is 512- but not 4096-aligned, which previously made disk offload unbootable
|
||||
even with use_page_cache=True.
|
||||
"""
|
||||
# Host pinning is a separate lifecycle concern with its own tests; the
|
||||
# alignment gate must not depend on registration state, so stub both ends.
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.simple_kv_offload.disk_backend.pin_tensor", lambda t: None
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"vllm.v1.simple_kv_offload.disk_backend.unpin_tensor",
|
||||
lambda t: None,
|
||||
raising=False, # harmless on branches without teardown-side unpins
|
||||
)
|
||||
num_blocks = 4
|
||||
gpu = {"k": torch.zeros((num_blocks, block_bytes), dtype=torch.int8, device="cuda")}
|
||||
backend = DiskBackend()
|
||||
disk_path = tmp_path / "kv-offload.bin"
|
||||
|
||||
def _init() -> None:
|
||||
backend.init(
|
||||
gpu,
|
||||
gpu["k"].device,
|
||||
torch.cuda.Stream(),
|
||||
torch.cuda.Stream(),
|
||||
str(disk_path),
|
||||
num_blocks,
|
||||
block_bytes,
|
||||
use_page_cache=use_page_cache,
|
||||
)
|
||||
|
||||
if not expect_ok:
|
||||
with pytest.raises(AssertionError, match="not aligned"):
|
||||
_init()
|
||||
return
|
||||
|
||||
_init()
|
||||
try:
|
||||
assert disk_path.stat().st_size == num_blocks * block_bytes
|
||||
finally:
|
||||
backend.shutdown()
|
||||
Reference in New Issue
Block a user