Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
293 changes: 264 additions & 29 deletions tests/v1/core/prefix_cache/test_partial_prefix_cache_hits.py

Large diffs are not rendered by default.

45 changes: 44 additions & 1 deletion tests/v1/core/test_mamba_align_chunk_split.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,14 @@ def _split(
partial_hit: bool = False,
num_prefill_checkpoint_blocks: int = 0,
allow_speculative_checkpoints: bool = False,
retention_interval: int | None = None,
) -> int:
"""Call the real `Scheduler._mamba_block_aligned_split` on a stub self."""
stub = SimpleNamespace(
cache_config=SimpleNamespace(block_size=MAMBA_BLOCK_SIZE),
cache_config=SimpleNamespace(
block_size=MAMBA_BLOCK_SIZE,
prefix_cache_retention_interval=retention_interval,
),
use_eagle=use_eagle,
max_num_scheduled_tokens=16384,
scheduler_config=SimpleNamespace(long_prefill_token_threshold=0),
Expand Down Expand Up @@ -173,6 +177,45 @@ def test_dflash_checkpoint_keeps_intermediate_chunks_aligned_and_joins_prompt_ta
)


def test_dflash_fragmented_budget_stops_at_external_retention_boundary(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A DFlash target chunk cannot jump over an externally retained state.

Seven parallel draft queries leave 4089 target slots in a 4096-token input
budget. The first target step therefore ends at 3584. The next step must
stop after 512 tokens so the recurrent state at token 4096 is materialized
for an external cache connector.
"""
block_size = 512
(request,) = create_requests(1, num_tokens=16384, block_size=ATTN_BLOCK_SIZE)
monkeypatch.setattr(sys.modules[__name__], "MAMBA_BLOCK_SIZE", block_size)

assert (
_split(
request,
4089,
use_eagle=True,
num_prefill_checkpoint_blocks=1,
allow_speculative_checkpoints=True,
retention_interval=4096,
)
== 3584
)
request.num_computed_tokens = 3584
assert (
_split(
request,
4089,
use_eagle=True,
num_prefill_checkpoint_blocks=1,
allow_speculative_checkpoints=True,
retention_interval=4096,
)
== 512
)


def test_glm_mtp_checkpoint_joins_unaligned_prompt_tail(
monkeypatch: pytest.MonkeyPatch,
) -> None:
Expand Down
75 changes: 75 additions & 0 deletions tests/v1/core/test_single_type_kv_cache_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,93 @@
)
from vllm.v1.core.single_type_kv_cache_manager import (
ChunkedLocalAttentionManager,
FullAttentionManager,
MambaManager,
RSWAManager,
SlidingWindowManager,
)
from vllm.v1.kv_cache_interface import (
ChunkedLocalAttentionSpec,
FullAttentionSpec,
MambaSpec,
RSWASpec,
SlidingWindowSpec,
)

pytestmark = pytest.mark.cpu_test


def test_external_computed_blocks_do_not_corrupt_free_pool():
block_size = 4
spec = FullAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
)
block_pool = BlockPool(
num_gpu_blocks=10,
enable_caching=False,
hash_block_size=block_size,
)
manager = FullAttentionManager(
spec,
block_pool=block_pool,
enable_caching=False,
kv_cache_group_id=0,
scheduler_block_size=block_size,
)
request_id = "request"
manager.allocate_new_blocks(
request_id,
num_tokens=3 * block_size,
num_tokens_main_model=3 * block_size,
)
num_free_blocks = block_pool.get_num_free_blocks()

# Speculative allocations can exceed the blocks implied by the eventual
# external computed-token count. This must not request a negative number
# of blocks, which inflates the free-queue counter.
manager.allocate_external_computed_blocks(
request_id,
num_local_computed_tokens=0,
num_external_computed_tokens=block_size,
)

assert block_pool.get_num_free_blocks() == num_free_blocks
assert len(manager.req_to_blocks[request_id]) == 3


def test_mamba_speculative_block_relocation_requires_exclusive_ownership():
spec = MambaSpec(
block_size=4,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="align",
num_speculative_blocks=1,
)
block_pool = BlockPool(num_gpu_blocks=4, enable_caching=True, hash_block_size=4)
manager = MambaManager(
spec,
block_pool=block_pool,
enable_caching=True,
kv_cache_group_id=0,
scheduler_block_size=4,
)
block = block_pool.get_new_blocks(1)[0]
blocks = [block]

manager._relocate_speculative_block(blocks, 0)

assert blocks == [block_pool.null_block, block]
assert block.ref_cnt == 1

pinned_block = block_pool.get_new_blocks(1)[0]
block_pool.touch((pinned_block,))
with pytest.raises(AssertionError, match="exclusively owned and unhashed"):
manager._relocate_speculative_block([pinned_block], 0)


def get_sliding_window_manager(
sliding_window_spec,
block_pool,
Expand Down
94 changes: 90 additions & 4 deletions tests/v1/kv_connector/unit/offloading_connector/test_scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,11 @@
is_store_reachable_swa_chunk,
)
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
from vllm.v1.core.kv_cache_utils import BlockHash, KVCacheBlock
from vllm.v1.core.kv_cache_utils import BlockHash, KVCacheBlock, KVCacheBlockCopy
from vllm.v1.core.sched.output import (
KVConnectorBlockState,
SchedulerOutput,
)
from vllm.v1.kv_cache_interface import (
ChunkedLocalAttentionSpec,
FullAttentionSpec,
Expand Down Expand Up @@ -107,11 +111,16 @@ def test_partial_tail_store_uses_attention_and_recurrent_cow_sources():
req_status = scheduler._req_status["req"]
req_status.group_states[0].block_ids[:] = [11, 12]
req_status.group_states[1].block_ids[:] = [0, 21]
scheduler.manager.prepare_store.side_effect = (
lambda keys, req_context: generate_store_output(keys)
scheduler.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)

output = SimpleNamespace(partial_tail_offloads={"req": [(1, 99, 28)]})
output = SimpleNamespace(
kv_connector_block_state=KVConnectorBlockState(
block_ids={},
boundary_state_offloads={"req": [(1, 99, 28)]},
)
)
jobs = scheduler._build_partial_tail_store_jobs(output)

assert len(jobs) == 1
Expand Down Expand Up @@ -155,6 +164,83 @@ def test_partial_tail_store_uses_attention_and_recurrent_cow_sources():
assert recurrent_event.parent_block_hash is None


def test_aligned_boundary_store_uses_exact_source_with_partial_tail():
scheduler = _make_partial_tail_scheduler()
_make_partial_tail_request(scheduler)
req_status = scheduler._req_status["req"]
req_status.group_states[0].block_ids[:] = [11, 12]
req_status.group_states[1].block_ids[:] = [0, 21]
scheduler.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)

output = SimpleNamespace(
kv_connector_block_state=KVConnectorBlockState(
block_ids={},
boundary_state_offloads={"req": [(1, 98, 16), (1, 99, 28)]},
)
)
jobs = scheduler._build_partial_tail_store_jobs(output)

assert len(jobs) == 2
src_spec = next(
job.src_spec for job in jobs.values() if len(job.src_spec.block_ids) == 1
)
assert isinstance(src_spec, GPULoadStoreSpec)
assert src_spec.block_ids.tolist() == [98]
assert src_spec.group_sizes == [0, 1]
assert src_spec.block_indices == [0, 0]


def test_aligned_boundary_store_flushes_before_cow_destination_reuse():
scheduler = _make_partial_tail_scheduler()
_make_partial_tail_request(scheduler)
scheduler.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)

output = SchedulerOutput.make_empty()
output.kv_connector_block_state = KVConnectorBlockState(
block_ids={},
boundary_state_offloads={"req": [(1, 99, 16)]},
)
meta = scheduler.build_connector_meta(output)
[job_id] = meta.store_jobs

output = SchedulerOutput.make_empty()
output.kv_cache_block_copies = [KVCacheBlockCopy(98, 99)]
meta = scheduler.build_connector_meta(output)

assert meta.jobs_to_flush == {job_id}


def test_normal_store_excludes_align_mode_mamba_sources():
scheduler = _make_partial_tail_scheduler()
request = _make_partial_tail_request(scheduler)
request.num_computed_tokens = 0
request.status = RequestStatus.RUNNING
req_status = scheduler._req_status["req"]
req_status.group_states[0].block_ids[:] = [11]
req_status.group_states[1].block_ids[:] = [99]
req_status.update_offload_keys()
scheduler.manager.prepare_store.side_effect = lambda keys, req_context: (
generate_store_output(keys)
)

output = SimpleNamespace(
num_scheduled_tokens={"req": 16},
finished_req_ids=set(),
)
jobs = scheduler._build_store_jobs(output)

assert len(jobs) == 1
[job] = jobs.values()
src_spec = job.src_spec
assert isinstance(src_spec, GPULoadStoreSpec)
assert src_spec.block_ids.tolist() == [11]
assert src_spec.group_sizes == [1, 0]


def test_partial_lookup_returns_exact_boundary_and_group_load_keys():
scheduler = _make_partial_tail_scheduler()
request = _make_partial_tail_request(scheduler)
Expand Down
38 changes: 37 additions & 1 deletion tests/v1/kv_connector/unit/test_mooncake_store_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import time
from unittest.mock import MagicMock, patch

import pytest
import torch

from vllm.config import set_current_vllm_config
from vllm.distributed.kv_events import BlockStored
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
Expand All @@ -29,6 +32,7 @@
KVCacheConfig,
KVCacheGroupSpec,
KVCacheTensor,
MambaSpec,
)
from vllm.v1.outputs import KVConnectorOutput

Expand Down Expand Up @@ -60,6 +64,30 @@ def _make_kv_cache_config() -> KVCacheConfig:
)


def test_scheduler_requires_align_mode_for_mamba():
vllm_config = _make_vllm_config()
mamba_spec = MambaSpec(
block_size=16,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="none",
)
kv_cache_config = KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[],
kv_cache_groups=[KVCacheGroupSpec(["mamba"], mamba_spec)],
)

with (
patch(
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store."
"scheduler.LookupKeyClient"
),
pytest.raises(AssertionError, match="requires mamba_cache_mode='align'"),
):
scheduler.MooncakeStoreScheduler(vllm_config, kv_cache_config)


def _make_block_stored() -> BlockStored:
return BlockStored(
block_hashes=[b"hash"],
Expand Down Expand Up @@ -95,6 +123,10 @@ def test_scheduler_role_initializes_store_scheduler_only():
mock_worker.assert_not_called()
assert connector.connector_scheduler is mock_scheduler.return_value
assert connector.connector_worker is None
block_pool = MagicMock()

connector.bind_gpu_block_pool(block_pool)
mock_scheduler.return_value.bind_gpu_block_pool.assert_called_once_with(block_pool)


def test_worker_methods_delegate_to_store_worker():
Expand Down Expand Up @@ -235,9 +267,13 @@ def test_update_connector_output_and_take_events():

kv_events = mooncake_store_connector.MooncakeStoreKVEvents(num_workers=1)
kv_events.add_events([event])
connector.update_connector_output(KVConnectorOutput(kv_cache_events=kv_events))
output = KVConnectorOutput(kv_cache_events=kv_events)
connector.update_connector_output(output)

assert connector._kv_cache_events is kv_events
connector.connector_scheduler.update_connector_output.assert_called_once_with(
output
)
assert list(connector.take_events()) == [event]
assert connector._kv_cache_events is None

Expand Down
21 changes: 21 additions & 0 deletions tests/v1/kv_connector/unit/test_mooncake_store_coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,27 @@ def test_store_mask_retention_prefix_stable_as_aligned_length_grows():
assert longer[: len(shorter)] == shorter


def test_store_mask_excludes_mamba_groups_lookup_unaffected():
"""Align-mode mamba block tables are not append-only (interior states are
nulled/freed; speculative blocks relocate), so the positional normal save
must never cover mamba chunks — regardless of retention. Lookups still
probe mamba boundaries: their keys come from the pinned snapshot/CoW
hand-off path instead."""
groups = [
KVCacheGroupSpec(["L0"], _full(16)),
KVCacheGroupSpec(["L1"], _mamba_align(16)),
]
coord = _make_coord(groups, hash_block_size=16)
masks = coord.store_mask(64)
assert masks[0] is None # full attn stays dense
assert masks[1] == [False] * 4

coord = _make_coord(groups, hash_block_size=16, retention_interval=32)
assert coord.store_mask(64)[1] == [False] * 4

assert coord.lookup_mask(64)[1] is None


# ----- Eagle / MTP interaction with load_mask -----


Expand Down
Loading
Loading