Add pydocstyle to the ruff rules (#52136)

Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com>
Signed-off-by: Harry Mellor <hej.mellor@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Harry Mellor
2026-09-16 16:44:29 +00:00
committed by GitHub
co-authored by Claude Opus 5
parent 804e5377aa
commit 8c1557a79c
2002 changed files with 15024 additions and 14269 deletions
@@ -59,6 +59,7 @@ class PredictableLlamaModel(nn.Module, EagleModelMixin):
Returns:
If aux_hidden_state_layers is set: (hidden_states, aux_hidden_states)
Otherwise: hidden_states
"""
# Determine sequence length
if inputs_embeds is not None:
@@ -25,8 +25,7 @@ SAMPLE_PROMPTS = (
def check_vllm_server(url: str, timeout=5, retries=3) -> bool:
"""
Checks if the vLLM server is ready by sending a GET request to the
"""Checks if the vLLM server is ready by sending a GET request to the
/health endpoint.
Args:
@@ -36,6 +35,7 @@ def check_vllm_server(url: str, timeout=5, retries=3) -> bool:
Returns:
bool: True if the server is ready, False otherwise.
"""
for attempt in range(retries):
try:
@@ -81,8 +81,7 @@ def run_simple_prompt(
def main():
"""
This script demonstrates how to accept two optional string arguments
"""This script demonstrates how to accept two optional string arguments
("service_url" and "file_name") from the command line, each with a
default value of an empty string, using the argparse module.
"""
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Integration edge-case tests for MultiConnector (NixlConnector + OffloadingConnector).
"""Integration edge-case tests for MultiConnector (NixlConnector + OffloadingConnector).
Tests cover:
- Output correctness across block-size boundaries (proxy vs direct prefill).
@@ -18,9 +18,7 @@ logger.setLevel(logging.DEBUG)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Lifespan context manager to handle startup and shutdown events.
"""
"""Lifespan context manager to handle startup and shutdown events."""
# Startup: Initialize client pools for prefiller and decoder services
app.state.prefill_clients = []
app.state.decode_clients = []
@@ -132,8 +130,7 @@ def parse_args():
def get_next_client(app, service_type: str):
"""
Get the next client in round-robin fashion.
"""Get the next client in round-robin fashion.
Args:
app: The FastAPI app instance
@@ -141,6 +138,7 @@ def get_next_client(app, service_type: str):
Returns:
The next client to use
"""
if service_type == "prefill":
client_idx = next(app.state.prefill_iterator)
@@ -155,9 +153,7 @@ def get_next_client(app, service_type: str):
async def send_request_to_service(
client_info: dict, endpoint: str, req_data: dict, request_id: str
):
"""
Send a request to a service using a client from the pool.
"""
"""Send a request to a service using a client from the pool."""
req_data = req_data.copy()
req_data["kv_transfer_params"] = {
"do_remote_decode": True,
@@ -200,9 +196,7 @@ async def send_request_to_service(
async def stream_service_response(
client_info: dict, endpoint: str, req_data: dict, request_id: str
):
"""
Asynchronously stream response from a service using a client from the pool.
"""
"""Asynchronously stream response from a service using a client from the pool."""
headers = {
"Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
"X-Request-Id": request_id,
@@ -80,7 +80,8 @@ def _split_hnd_cache(spec) -> torch.Tensor:
def _packed_nhd_cache(spec) -> torch.Tensor:
"""Logical (num_blocks, heads, block_size, 2 * head_size) over an NHD
physical layout — the FlashAttention/FlashInfer/Triton/Flex form."""
physical layout — the FlashAttention/FlashInfer/Triton/Flex form.
"""
return torch.zeros(
NUM_BLOCKS,
spec.block_size,
@@ -863,7 +863,8 @@ def test_parallelism_agnostic_excluded(kv_cache_groups: list[KVCacheGroupSpec]):
)
def test_canonical_layout_gate(kv_cache_groups, certified):
"""The canonical layout certifies portability group by group; none of
these shapes are portable in the direct layout."""
these shapes are portable in the direct layout.
"""
assert not _parallelism_agnostic(kv_cache_groups)
assert _parallelism_agnostic(kv_cache_groups, canonical=True) is certified
@@ -871,7 +872,8 @@ def test_canonical_layout_gate(kv_cache_groups, certified):
def test_canonical_layout_certifies_v2_model_runner():
"""Canonical bytes are certified per layer against live tensor strides at
registration, so the static gate must not depend on the model-runner
version — the v2 runner is the case the canonical layout exists for."""
version — the v2 runner is the case the canonical layout exists for.
"""
groups = _groups(_full_attention_spec())
assert _parallelism_agnostic(groups, canonical=True, v2=True)
@@ -117,7 +117,8 @@ def _spec_cls_with_metric_definitions(
metric_definitions: dict[str, Any],
) -> type:
"""Build a fake offloading spec class reporting the given metric
definitions, so tests don't need to patch the real CPU spec."""
definitions, so tests don't need to patch the real CPU spec.
"""
class _FakeOffloadingSpec:
@staticmethod
@@ -187,7 +188,8 @@ def test_build_kv_connector_stats_with_empty_dict():
def test_build_kv_connector_stats_reconstructs_offload_stats():
"""Test that OffloadingConnector stats are properly reconstructed with
correct data."""
correct data.
"""
serialized_data = {
_StatsKey.TYPES: {
LOAD_BYTES: _MetricType.COUNTER,
@@ -1583,7 +1583,8 @@ _SCAN_BEHAVIOR = {
@pytest.mark.parametrize("result", list(LookupResult))
def test_scan_behavior_declared_for_every_lookup_result(result: LookupResult):
"""Whether a result keeps a sliding-window streak alive decides how wide
the demanded chunk set gets, so every member needs deliberate behavior."""
the demanded chunk set gets, so every member needs deliberate behavior.
"""
assert result in _SCAN_BEHAVIOR, f"{result} has no declared scan behavior"
expected_lookups, expected_end = _SCAN_BEHAVIOR[result]
@@ -2034,7 +2035,8 @@ def test_request_level_policy_stores_all_blocks(request_runner, async_scheduling
def test_loads_do_not_populate_fence_index(request_runner):
"""Loads don't populate _block_id_to_pending_jobs (protected by
delay_free_blocks while in flight)."""
delay_free_blocks while in flight).
"""
runner = request_runner(
blocks_per_chunk=3,
block_size=4,
@@ -2104,7 +2106,8 @@ def test_fence_at_update_state_after_alloc(request_runner):
def test_fence_at_build_store_jobs(request_runner):
"""A new prefill (no load -> update_state_after_alloc returns early)
reusing a finished request's pending-store block is flushed by
_build_store_jobs's fence."""
_build_store_jobs's fence.
"""
runner = request_runner(
blocks_per_chunk=1,
block_size=4,
@@ -2154,7 +2157,8 @@ def test_fence_at_build_store_jobs(request_runner):
@pytest.mark.parametrize("async_scheduling", [True, False])
def test_complete_store_called_per_job(request_runner, async_scheduling: bool):
"""complete_store fires per-job, not deferred to request finish.
Each call carries only that store's keys."""
Each call carries only that store's keys.
"""
tokens_per_block = 4
blocks_per_chunk = 3
tokens_per_chunk = tokens_per_block * blocks_per_chunk
@@ -2383,7 +2387,8 @@ def test_offload_prompt_only(request_runner, async_scheduling: bool):
@pytest.mark.parametrize("async_scheduling", [True, False])
def test_reset_cache(request_runner, async_scheduling: bool):
"""reset_cache flushes in-flight loads, calls manager.reset_cache(), resets
next_stored_chunk_idx for active requests and clears job tracking."""
next_stored_chunk_idx for active requests and clears job tracking.
"""
block_size = 4
blocks_per_chunk = 3
tokens_per_chunk = block_size * blocks_per_chunk
@@ -2929,7 +2934,8 @@ def test_stale_sliding_window_block_after_prepare_store_failure(
@pytest.mark.parametrize("async_scheduling", [True, False])
def test_skip_reading_prefix_cache(request_runner, async_scheduling: bool):
"""When skip_reading_prefix_cache=True, the offloading connector must not
load any blocks from CPU even if a matching prefix is cached there."""
load any blocks from CPU even if a matching prefix is cached there.
"""
block_size = 4
blocks_per_chunk = 3
tokens_per_chunk = block_size * blocks_per_chunk
@@ -3023,7 +3029,8 @@ def test_max_load_tokens_limits_external_load(request_runner, async_scheduling:
class TestEagle:
"""Tests for Eagle/MTP speculative decoding support in the offloading
connector scheduler — both _lookup() unit tests and integration tests."""
connector scheduler — both _lookup() unit tests and integration tests.
"""
# -------------------------------------------------------------------
# Helpers
@@ -3565,7 +3572,8 @@ class TestEagle:
self, request_runner, async_scheduling: bool
):
"""Eagle sliding-window group stores all prompt blocks but excludes
the trailing chunk while decoding."""
the trailing chunk while decoding.
"""
block_size = 4
sliding_window = 8
num_gpu_blocks = 100
@@ -3617,7 +3625,8 @@ class TestEagle:
self, request_runner, async_scheduling: bool
):
"""An eagle group with a single-block prompt stores it at the end of
prefill: prompt blocks are stable, so no tail is held back."""
prefill: prompt blocks are stable, so no tail is held back.
"""
block_size = 4
blocks_per_chunk = 1
tokens_per_chunk = block_size * blocks_per_chunk
@@ -4254,7 +4263,8 @@ def test_request_finished_mixed_full_attn_and_sliding_window(
def test_chunked_local_attention_reports_its_chunk_window():
"""Llama 4 uses chunked local attention, which used to trip the
FullAttentionSpec assert and kill the engine at startup."""
FullAttentionSpec assert and kill the engine at startup.
"""
spec = ChunkedLocalAttentionSpec(
block_size=16,
num_kv_heads=2,
@@ -4493,7 +4503,8 @@ def test_retention_interval_zero_stores_only_replay_boundary(
def _shared_kv_mtp_config():
"""Speculative config for a shared-group MTP model: eagle-family method
whose drafter layer merges into a target KV-cache group, so no group
self-identifies as a drafter group (issue #52735)."""
self-identifies as a drafter group (issue #52735).
"""
spec = MagicMock(name="shared_kv_mtp_spec")
spec.use_eagle.return_value = True
spec.use_eagle_block_drop.return_value = True
@@ -4507,12 +4518,14 @@ def _shared_kv_mtp_config():
class TestSharedGroupMTPOffload:
"""Regression tests for issue #52735: OffloadingConnector must keep
serving when speculative decoding is enabled but no KV-cache group is
annotated as a drafter group (shared-group MTP models)."""
annotated as a drafter group (shared-group MTP models).
"""
def test_no_annotation_marks_no_groups(self, request_runner):
"""Spec decode on + zero annotated groups must NOT mark every group
as a drafter group; the full store->load roundtrip must match the
non-speculative behavior of test_two_groups_full_and_sliding_window."""
non-speculative behavior of test_two_groups_full_and_sliding_window.
"""
block_size = 4
kv_cache_groups = [
KVCacheGroupSpec(
@@ -4569,7 +4582,8 @@ class TestSharedGroupMTPOffload:
class TestMambaHybridOffloadServing:
"""Store->finish->lookup flows on a full-attention + mamba-align hybrid,
with a manager that only HITs keys that were actually stored. Guards the
two collapse routes of issue #52735."""
two collapse routes of issue #52735.
"""
BLOCK = 4
MAMBA_BLOCK = 16
@@ -4698,7 +4712,8 @@ class TestMambaHybridOffloadServing:
"""Route 1 of #52735: with spec decode on and no drafter annotation,
serving must equal the non-speculative baseline (was 0 before the
fix: the all-groups fallback marked the mamba group as a drafter and
the volatile-tail pop consumed its only servable chunk)."""
the volatile-tail pop consumed its only servable chunk).
"""
baseline = self._roundtrip_served_tokens(self._make_scheduler(None))
assert baseline == 16
served = self._roundtrip_served_tokens(
@@ -4711,7 +4726,8 @@ class TestMambaHybridOffloadServing:
group must not drag the confirmed boundary below a coarser sibling's
chunk granularity. The widened query makes the volatile-tail pop
land on an extra queried chunk, holding the boundary at 16 tokens
(was 0 before the fix: 4 hits -> pop -> 12 tokens < mamba chunk)."""
(was 0 before the fix: 4 hits -> pop -> 12 tokens < mamba chunk).
"""
scheduler = self._make_scheduler(None, mamba_eagle=True)
assert [c.is_eagle_group for c in scheduler.config.kv_group_configs] == [
True,
@@ -80,7 +80,8 @@ def _allocate_kv_caches(
def _single_rank_vllm_config(total_kv_heads: int):
"""A one-rank (TP=1) parallel config, as canonical mappings are derived
from it."""
from it.
"""
vllm_config = MagicMock()
parallel_config = vllm_config.parallel_config
parallel_config.tensor_parallel_size = 1
@@ -98,9 +99,7 @@ def _make_worker(
replicated_layout: bool = False,
rank: int = 0,
):
"""
Create an OffloadingConnectorWorker with mocked dependencies.
"""
"""Create an OffloadingConnectorWorker with mocked dependencies."""
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.worker import (
OffloadingConnectorWorker,
)
@@ -475,8 +475,7 @@ class RequestRunner:
complete_transfers: bool,
post_step_fn: Callable[[], None] | None = None,
):
"""
Runs multiple engine (scheduler + worker) steps.
"""Runs multiple engine (scheduler + worker) steps.
Assumes a single request is running.
Args:
@@ -484,8 +483,8 @@ class RequestRunner:
complete_transfers: complete transfers immediately
post_step_fn: optional callback invoked after each step's
update_from_output(), before the next schedule().
"""
"""
tokens_iter = iter(decoded_tokens)
token_id = next(tokens_iter, None)
prev_scheduler_output = None
@@ -617,8 +616,7 @@ class RequestRunner:
expected_flushed: tuple[int | tuple[int, int], ...] = (),
post_step_fn: Callable[[], None] | None = None,
):
"""
Runs multiple engine (scheduler + worker) steps.
"""Runs multiple engine (scheduler + worker) steps.
Assumes a single request is running.
Args:
@@ -634,8 +632,8 @@ class RequestRunner:
A GPU block is either a (group_idx: int, request_block_offset: int)
or just request_block_offset: int.
The latter case is a convenience for representing all groups.
"""
"""
expected_stored_gpu_blocks = self._to_gpu_blocks(expected_stored)
expected_loaded_gpu_blocks = self._to_gpu_blocks(expected_loaded)
expected_flushed_gpu_blocks = self._to_gpu_blocks(expected_flushed)
@@ -148,7 +148,8 @@ def test_multiturn_lifecycle():
(do_remote_decode=True). Finishes LENGTH_CAPPED with remote_block_ids.
Turn 2: P receives remote_block_ids from D. P pulls KV from D because
remote_block_ids is not None and external tokens > 0. Computes only
new tokens, finishes LENGTH_CAPPED."""
new tokens, finishes LENGTH_CAPPED.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -194,7 +195,8 @@ def test_multiturn_lifecycle():
def test_first_turn_no_remote_blocks():
"""First turn: P has no remote_block_ids from D yet.
Standard local prefill, returns kv_transfer_params for future turns."""
Standard local prefill, returns kv_transfer_params for future turns.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -274,7 +276,8 @@ def test_abort_p_side_non_length_capped():
def test_remote_blocks_exceed_prompt_tokens():
"""D provides more remote tokens than P's prompt needs.
P caps external tokens to prompt length."""
P caps external tokens to prompt length.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -310,7 +313,8 @@ def test_remote_blocks_exceed_prompt_tokens():
def test_p_node_pulls_partial_last_block_from_d():
"""D sends remote_block_ids with partially filled last block.
remote_num_tokens < len(remote_block_ids) * block_size.
P pulls only remote_num_tokens worth of external tokens."""
P pulls only remote_num_tokens worth of external tokens.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -355,7 +359,8 @@ def test_p_node_pulls_partial_last_block_from_d():
def test_add_new_req_to_recv_populates_remote_meta():
"""add_new_req_to_recv correctly populates RemoteMeta for P-node
bi-directional KV pull from D."""
bi-directional KV pull from D.
"""
meta = NixlConnectorMetadata()
kv_params = {
"remote_block_ids": [[0, 1, 2]],
@@ -383,7 +388,8 @@ def test_add_new_req_to_recv_populates_remote_meta():
def test_build_connector_meta_recv_entries():
"""P-node scheduler: do_remote_decode=True + remote_block_ids →
_reqs_need_recv populated, build_connector_meta produces reqs_to_recv."""
_reqs_need_recv populated, build_connector_meta produces reqs_to_recv.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -457,7 +463,8 @@ def test_p_node_pull_kv_from_d(dist_init):
)
def test_p_node_pull_then_send_kv(dist_init):
"""Full P-node bi-directional: pull KV from D → prefill →
send KV back to D via notification."""
send KV back to D via notification.
"""
connector, worker = _make_connector_with_fake_worker()
meta = _make_p_node_recv_metadata("req-p2", [10, 11], [20, 21])
_do_load_kv(connector, meta)
@@ -504,7 +511,8 @@ def test_p_node_deferred_pull_on_no_handshake(dist_init):
def test_d_node_request_finished_returns_kv_params():
"""D-node request_finished returns kv_transfer_params with
do_remote_decode=True, remote_block_ids, remote_num_tokens
for P to pull. These params go directly to P node."""
for P to pull. These params go directly to P node.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -585,7 +593,8 @@ def test_d_node_request_finished_remote_num_tokens():
def test_d_node_partial_last_block_remote_num_tokens():
"""D-node: remote_num_tokens < len(remote_block_ids) * block_size
when last block is partially filled."""
when last block is partially filled.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -619,7 +628,8 @@ def test_no_double_read_blocks_after_reschedule():
bidirectional request (once on initial schedule, once after
WAITING_FOR_REMOTE_KVS → reschedule). The _remote_blocks_processed
flag must prevent the request from being added to _reqs_need_recv
twice, which would cause P to read D's blocks twice."""
twice, which would cause P to read D's blocks twice.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -672,7 +682,8 @@ def test_remote_num_tokens_bounded_by_blocks():
"""Edge case 2: D-node request_finished must return
remote_num_tokens <= len(remote_block_ids) * block_size.
request.num_tokens includes the last sampled token which has no KV
in the cache, so remote_num_tokens must use num_computed_tokens."""
in the cache, so remote_num_tokens must use num_computed_tokens.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -708,7 +719,8 @@ def test_remote_num_tokens_bounded_by_blocks():
def test_kv_recompute_threshold_skips_small_transfer():
"""Edge case 3: When remote tokens are below kv_recompute_threshold,
P should skip the remote pull and compute locally instead of
entering WAITING_FOR_REMOTE_KVS."""
entering WAITING_FOR_REMOTE_KVS.
"""
threshold = 256
vllm_config = create_vllm_config(
kv_connector_extra_config={
@@ -750,7 +762,8 @@ def test_p_node_finished_holds_blocks_for_d():
"""Edge case 4: P-node finishes with FINISHED_LENGTH_CAPPED and
do_remote_decode=True. P must hold blocks (delay_free=True) and
return kv_transfer_params with do_remote_prefill=True so D can
read P's blocks."""
read P's blocks.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -791,7 +804,8 @@ def test_p_node_finished_holds_blocks_for_d():
def test_cache_miss_first_turn_no_remote_pull():
"""Edge case 5: First turn with do_remote_decode=True but no
remote_block_ids (cache MISS). P should prefill locally with
num_external_tokens=0 and not enter WAITING_FOR_REMOTE_KVS."""
num_external_tokens=0 and not enter WAITING_FOR_REMOTE_KVS.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -826,7 +840,8 @@ def test_cache_miss_first_turn_no_remote_pull():
def test_partial_remote_tokens_less_than_prompt():
"""Edge case 6: D's remote_num_tokens covers only part of P's
prompt. P should pull remote_num_tokens worth of external tokens
and compute the rest locally."""
and compute the rest locally.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -871,7 +886,8 @@ def test_partial_remote_tokens_less_than_prompt():
def test_remote_blocks_processed_flag_persists():
"""Edge case 7: After recv completes and request is rescheduled,
the _remote_blocks_processed flag in kv_transfer_params prevents
the bidirectional path from re-entering _reqs_need_recv."""
the bidirectional path from re-entering _reqs_need_recv.
"""
vllm_config = create_vllm_config(
kv_connector_extra_config=BIDIR_KV_EXTRA_CONFIG,
)
@@ -943,7 +959,8 @@ _REMOTE = FakeNixlConnectorWorker.REMOTE_ENGINE_ID
)
def test_turn2_deadline_gate(dist_init, offset, expiry_delta, expect_declined):
"""P declines on the turn-2 readback if the deadline is known,
near-expiry and a handshake clock offset is known"""
near-expiry and a handshake clock offset is known
"""
connector, worker = _make_connector_with_fake_worker()
worker._engine_clock_offset[_REMOTE] = offset
expiry_time = None if expiry_delta is None else time.perf_counter() + expiry_delta
@@ -979,7 +996,8 @@ def test_turn2_deadline_gate(dist_init, offset, expiry_delta, expect_declined):
)
def test_turn2_full_prefix_hit_with_expired_deadline_skips_gate(dist_init):
"""A full local prefix hit issues no READ. The expiry gate must be skipped
even when D's deadline is expired."""
even when D's deadline is expired.
"""
connector, worker = _make_connector_with_fake_worker()
worker._engine_clock_offset[_REMOTE] = 0.0
@@ -1032,7 +1050,8 @@ def test_d_node_request_finished_exports_blocks_expiry_time():
def test_handshake_listener_appends_perf_counter_frame():
"""The handshake reply carries a 2nd frame with the listener's live
perf_counter."""
perf_counter.
"""
import threading
import msgspec
@@ -1,8 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
test that invalid blocks are evicted from prefix cache to prevent pollution.
"""test that invalid blocks are evicted from prefix cache to prevent pollution.
verifies that when sync-loading fails, invalid blocks are removed from the
prefix cache hash table so future requests cannot match and reuse corrupted data.
@@ -39,7 +38,7 @@ def _make_get_num_new_matched_tokens(
@pytest.fixture
def fail_scheduler():
"""scheduler with kv_load_failure_policy='fail'"""
"""Scheduler with kv_load_failure_policy='fail'."""
vllm_config = create_vllm_config()
vllm_config.kv_transfer_config.kv_load_failure_policy = "fail"
return create_scheduler(vllm_config)
@@ -48,8 +47,7 @@ def fail_scheduler():
def test_invalid_blocks_evicted_prevents_cache_pollution(
fail_scheduler: Scheduler,
):
"""
verify invalid blocks are evicted to prevent future cache hits.
"""Verify invalid blocks are evicted to prevent future cache hits.
scenario:
1. request 1 loads externally-computed blocks (sync mode)
+12 -6
View File
@@ -19,13 +19,15 @@ class _StubLMCacheMPConnector:
test only asserts on the connector *name* and the ``extra_config`` dict
produced by ``VllmConfig``, never instantiates the connector, so a bare
placeholder class is sufficient. Not subclassing ``SupportsHMA`` mirrors
the real connector's HMA support (it does not support HMA either)."""
the real connector's HMA support (it does not support HMA either).
"""
@pytest.fixture
def stub_lmcache_mp_connector(monkeypatch):
"""Replace the lazy loader so VllmConfig.__post_init__ does not import
``lmcache_mp_connector`` (and thus ``lmcache``) during config tests."""
``lmcache_mp_connector`` (and thus ``lmcache``) during config tests.
"""
monkeypatch.setitem(
KVConnectorFactory._registry,
"LMCacheMPConnector",
@@ -105,7 +107,8 @@ def _build_config(
enable_cumem_allocator: bool = False,
) -> VllmConfig:
"""Build a VllmConfig that exercises _verify_kv_transfer_compat without
requiring a real model (avoids HF downloads in CI)."""
requiring a real model (avoids HF downloads in CI).
"""
from types import SimpleNamespace
kv_transfer_config = (
@@ -131,7 +134,8 @@ def test_kv_connector_rejects_expandable_segments(monkeypatch, kv_connector):
invalidated when expandable_segments lets the CUDA VMM allocator remap
the underlying physical pages. We can't enumerate every connector that
does this (especially OOT ones), so reject the combination whenever any
connector is configured."""
connector is configured.
"""
monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
with pytest.raises(ValueError, match="expandable_segments"):
_build_config(kv_connector=kv_connector)
@@ -139,7 +143,8 @@ def test_kv_connector_rejects_expandable_segments(monkeypatch, kv_connector):
def test_kv_connector_allows_expandable_segments_with_sleep_mode(monkeypatch):
"""Sleep mode routes KV allocations through CuMemAllocator's pool, which
auto-disables expandable_segments (see #40812)."""
auto-disables expandable_segments (see #40812).
"""
monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
_build_config(kv_connector="NixlConnector", enable_sleep_mode=True)
@@ -162,7 +167,8 @@ def test_kv_connector_allows_other_alloc_conf(monkeypatch):
def test_no_kv_connector_ignores_expandable_segments(monkeypatch):
"""The expandable_segments check only applies when a KV connector is
configured."""
configured.
"""
monkeypatch.setenv("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
_build_config(kv_connector=None)
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Unit tests for DecodeBenchConnector.
"""Unit tests for DecodeBenchConnector.
Tests the functionality of the DecodeBenchConnector which fills KV cache
with dummy values for decode performance benchmarking.
@@ -32,14 +32,14 @@ def _make_get_num_new_matched_tokens(
@pytest.fixture
def fail_scheduler():
"""scheduler with kv_load_failure_policy='fail'"""
"""Scheduler with kv_load_failure_policy='fail'."""
vllm_config = create_vllm_config()
vllm_config.kv_transfer_config.kv_load_failure_policy = "fail"
return create_scheduler(vllm_config)
def test_error_propagation_sync_load(fail_scheduler: Scheduler):
"""test invalid_block_ids with fail policy -> FINISHED_ERROR (sync load)"""
"""Test invalid_block_ids with fail policy -> FINISHED_ERROR (sync load)."""
num_prompt_blocks = 100
num_external_computed_blocks = 99
invalid_block_idx = 50
@@ -93,7 +93,7 @@ def test_error_propagation_sync_load(fail_scheduler: Scheduler):
def test_error_propagation_async_load(fail_scheduler: Scheduler):
"""test invalid_block_ids with fail policy -> FINISHED_ERROR (async load)"""
"""Test invalid_block_ids with fail policy -> FINISHED_ERROR (async load)."""
num_prompt_blocks = 100
num_external_computed_blocks = 99
invalid_block_idx = 50
@@ -29,12 +29,12 @@ class InputCase(NamedTuple):
def _check_path_len(path):
"""Return the latest length in path"""
"""Return the latest length in path."""
return len(list(path.iterdir()))
def _list_path(path):
"""Return the list of foldername (hashes generated) under the path"""
"""Return the list of foldername (hashes generated) under the path."""
return list(path.iterdir())
@@ -47,8 +47,7 @@ def run_test(
expected_len: int,
info: str,
):
"""
One individual test to process the prompt and output base on 1 set of input
"""One individual test to process the prompt and output base on 1 set of input
Then check if the length in the storage path matches the expected length
`info` introduces details or purpose of the individual test
"""
@@ -67,9 +66,7 @@ def run_test(
def process_prompt(processor, llm: LLM, question: str, image_urls: list[Image]):
"""
Form the prompt based on the text and image input, then llm generate output
"""
"""Form the prompt based on the text and image input, then llm generate output."""
placeholders = [
{
"type": "image_url",
@@ -120,8 +117,7 @@ def process_prompt(processor, llm: LLM, question: str, image_urls: list[Image]):
),
)
def test_shared_storage_connector_hashes(tmp_path, attn_backend):
"""
Tests that ExampleConnector saves KV to the storage locations
"""Tests that ExampleConnector saves KV to the storage locations
with proper hashes; that are unique for inputs with identical text but
different images (same size), or same multiple images but different orders.
"""
@@ -50,7 +50,8 @@ def _make_flexkv_module(
impl_mock: MagicMock,
) -> tuple[types.ModuleType, types.ModuleType]:
"""Build a fake ``flexkv`` package hierarchy that returns *impl_mock*
when ``FlexKVConnectorV1Impl`` is instantiated."""
when ``FlexKVConnectorV1Impl`` is instantiated.
"""
flexkv_mod = types.ModuleType("flexkv")
integration_mod = types.ModuleType("flexkv.integration")
vllm_mod = types.ModuleType("flexkv.integration.vllm")
@@ -71,7 +72,8 @@ def _make_flexkv_module(
def _install_flexkv_mock(impl_mock: MagicMock):
"""Insert fake flexkv modules into sys.modules and return a context that
cleans them up afterwards."""
cleans them up afterwards.
"""
flexkv_mod, adapter_mod = _make_flexkv_module(impl_mock)
mods = {
"flexkv": flexkv_mod,
@@ -104,7 +106,8 @@ def _build_connector(vllm_config: VllmConfig, impl_mock: MagicMock):
class TestFlexKVConnectorImportError:
"""FlexKVConnectorV1 should fail with a helpful message when flexkv is
absent."""
absent.
"""
def test_import_error_message(self):
from vllm.distributed.kv_transfer.kv_connector.v1.flexkv_connector import (
@@ -176,7 +176,8 @@ def test_engine_unwraps_handshake_metadata_for_legacy_connector(
) -> None:
"""Engine core always asks workers for `(pp_rank, tp_rank)`-keyed metadata,
then unwraps to `{tp_rank: metadata}` for a connector that has not opted
into PP-aware handshake (single-PP producer, all `pp_rank == 0`)."""
into PP-aware handshake (single-PP producer, all `pp_rank == 0`).
"""
metadata_0 = _Metadata()
metadata_1 = _Metadata()
connector = _LegacyConnector()
@@ -199,7 +200,8 @@ def test_engine_rejects_pp_producer_for_legacy_connector(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A connector that has not opted into PP-aware handshake must not silently
drop metadata from `pp_rank > 0`; engine core init raises instead."""
drop metadata from `pp_rank > 0`; engine core init raises instead.
"""
connector = _LegacyConnector()
with pytest.raises(ValueError, match="does not support PP-disaggregated"):
@@ -214,7 +216,8 @@ def test_engine_passes_handshake_metadata_through_for_pp_aware_connector(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A PP-aware connector receives the full `(pp_rank, tp_rank)`-keyed dict
unchanged."""
unchanged.
"""
metadata_0 = _Metadata()
metadata_1 = _Metadata()
connector = _PPAwareConnector()
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for resource management in hf3fs_client.py: constructor failure cleanup
"""Tests for resource management in hf3fs_client.py: constructor failure cleanup
and idempotent close(). Tests use mock to replace real I/O operations
(hf3fs_fuse.io, SharedMemory, os, CUDA).
Requires hf3fs_fuse.io to be installed; skipped otherwise.
@@ -132,7 +131,8 @@ class TestHf3fsClientResourceManagement:
def test_close_idempotent_and_handles_cleared(self, tmp_path):
"""Multiple close() calls must not raise; deregister_fd called exactly
once, all handles set to None, shm.close() invoked."""
once, all handles set to None, shm.close() invoked.
"""
client, shm_r, shm_w = self._make_client(tmp_path)
with (
@@ -238,7 +238,8 @@ class TestHf3fsClientResourceManagement:
def test_constructor_failure_does_not_close_unallocated_shm(self, tmp_path):
"""Failure before SharedMemory is created must not raise AttributeError
or TypeError from cleanup."""
or TypeError from cleanup.
"""
with (
patch(f"{self._MOD}.HF3FS_AVAILABLE", True),
patch(f"{self._MOD}.register_fd"),
@@ -1,9 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for HF3FS KV Connector high-level components:
- TestHf3fsMockClient : file-backed mock client I/O correctness
- TestHF3FSKVConnectorStats: metric collection, aggregation, serialisation
"""Tests for HF3FS KV Connector high-level components:
- TestHf3fsMockClient : file-backed mock client I/O correctness
- TestHF3FSKVConnectorStats: metric collection, aggregation, serialisation
"""
import os
@@ -1,10 +1,9 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for HF3FS metadata server data structures and allocation logic:
- RankFileMetadata : page allocation / release primitives
- KeyMetadata : per-key rank-page tracking and completion detection
- GlobalMetadataState : coordinated allocation with cache-hit semantics
"""Tests for HF3FS metadata server data structures and allocation logic:
- RankFileMetadata : page allocation / release primitives
- KeyMetadata : per-key rank-page tracking and completion detection
- GlobalMetadataState : coordinated allocation with cache-hit semantics
"""
import pytest
@@ -1,8 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
Tests for correctness in invalid block handling.
"""Tests for correctness in invalid block handling.
These tests verify correct behavior in three scenarios:
1. Sync recompute case: Blocks should not be freed for running requests
@@ -42,7 +41,7 @@ def _make_get_num_new_matched_tokens(
@pytest.fixture
def fail_scheduler():
"""scheduler with kv_load_failure_policy='fail'"""
"""Scheduler with kv_load_failure_policy='fail'."""
vllm_config = create_vllm_config()
vllm_config.kv_transfer_config.kv_load_failure_policy = "fail"
return create_scheduler(vllm_config)
@@ -50,7 +49,7 @@ def fail_scheduler():
@pytest.fixture
def recompute_scheduler():
"""scheduler with kv_load_failure_policy='recompute'"""
"""Scheduler with kv_load_failure_policy='recompute'."""
vllm_config = create_vllm_config()
vllm_config.kv_transfer_config.kv_load_failure_policy = "recompute"
return create_scheduler(vllm_config)
@@ -59,8 +58,7 @@ def recompute_scheduler():
def test_sync_recompute_blocks_not_freed_for_running_requests(
recompute_scheduler: Scheduler,
):
"""
Test sync recompute case - blocks must not be freed for running requests.
"""Test sync recompute case - blocks must not be freed for running requests.
When a running request has invalid blocks and retry_policy is 'recompute':
1. Request should remain in RUNNING state
@@ -180,8 +178,7 @@ def test_sync_recompute_blocks_not_freed_for_running_requests(
def test_sync_fail_invalid_blocks_evicted(fail_scheduler: Scheduler):
"""
Test sync fail case - invalid blocks must be evicted from cache.
"""Test sync fail case - invalid blocks must be evicted from cache.
When a request fails with policy='fail' and has invalid blocks from sync loading:
1. Request should be finished with FINISHED_ERROR
@@ -296,8 +293,7 @@ def test_sync_fail_invalid_blocks_evicted(fail_scheduler: Scheduler):
def test_async_recompute_blocks_not_cached_when_invalid(
recompute_scheduler: Scheduler,
):
"""
Test async recompute case - invalid blocks not cached after transfer.
"""Test async recompute case - invalid blocks not cached after transfer.
When async KV loading has invalid blocks and retry_policy is 'recompute':
1. Blocks are allocated but not cached yet
@@ -212,7 +212,8 @@ class TestUpdateConnectorOutput:
self, mock_connector
):
"""Test that method returns early when kv_cache_events is not
LMCacheKVEvents."""
LMCacheKVEvents.
"""
# Create a mock object that is not LMCacheKVEvents
fake_events = MagicMock()
connector_output = KVConnectorOutput(kv_cache_events=fake_events)
@@ -675,8 +676,7 @@ class TestIntegrationScenarios:
assert mock_connector._kv_cache_events is None
def test_lmcache_kv_events_aggregation(self):
"""
Test LMCacheKVEvents aggregation across TP ranks using
"""Test LMCacheKVEvents aggregation across TP ranks using
KVOutputAggregator (used by MultiprocExecutor).
"""
from vllm.distributed.kv_transfer.kv_connector.utils import KVOutputAggregator
@@ -179,7 +179,6 @@ class FakeMooncakeWrapper:
def test_align_transfer_regions_uses_layer_name_occurrences():
"""Repeated layer names should align by occurrence order."""
local_regions = [
TransferRegion(
layer_name="model.layers.1.self_attn",
@@ -232,7 +231,6 @@ def test_align_transfer_regions_uses_layer_name_occurrences():
@pytest.mark.asyncio
async def test_build_transfer_params_separates_prefill_pp_layers():
"""Each producer PP stage should send only its registered layer shard."""
worker = MooncakeConnectorWorker.__new__(MooncakeConnectorWorker)
worker.async_zmq_ctx = MagicMock()
worker.is_kv_consumer = True
@@ -368,7 +366,6 @@ async def test_send_kv_to_decode_aligns_consumer_regions_by_layer_metadata(
monkeypatch,
):
"""Producer sends its PP layer shard to the matching consumer layer address."""
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
@@ -447,7 +444,6 @@ async def test_send_kv_to_decode_aligns_consumer_regions_by_layer_metadata(
def test_basic_interface():
"""Unit test for basic MooncakeConnector interface functionality."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -497,7 +493,6 @@ def test_basic_interface():
def test_prompt_less_than_block_size():
"""Test that we can handle case where prompt is < block."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -536,7 +531,6 @@ def test_prompt_less_than_block_size():
@pytest.fixture
def bootstrap_server():
"""Fixture to launch and cleanup a Mooncake Bootstrap HTTP Server."""
port = get_open_port()
server = MooncakeBootstrapServer("127.0.0.1", port)
server.start()
@@ -546,12 +540,10 @@ def bootstrap_server():
@pytest.mark.asyncio
async def test_bootstrap_server(bootstrap_server: MooncakeBootstrapServer):
"""
Tests the bootstrap server's api for worker registration and querying.
"""Tests the bootstrap server's api for worker registration and querying.
Validates DP/TP/PP rank indexing and error handling for duplicate registrations.
"""
import httpx
base_url = f"http://127.0.0.1:{bootstrap_server.port}"
@@ -716,13 +708,11 @@ def test_get_mooncake_bootstrap_addr_selects_expected_host(
def test_scheduler_request_finished():
"""
Tests the scheduler-side logic when a request finishes.
"""Tests the scheduler-side logic when a request finishes.
Differentiates between 'Finished' (requires transfer)
and 'Aborted' (immediate free).
"""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
)
@@ -751,7 +741,6 @@ def test_scheduler_request_finished():
@contextlib.contextmanager
def patch_worker_dependencies():
"""Helper to mock all distributed and network dependencies for Worker tests."""
with (
patch(
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_connector.TransferEngine",
@@ -820,7 +809,6 @@ async def test_receive_kv_selects_remote_pp_workers(
expected_addrs: list[str],
):
"""Decode workers should not hard-code producer pp_rank 0."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -875,7 +863,6 @@ async def test_receive_kv_selects_remote_pp_workers(
def test_resolve_need_send_accounts_for_remote_tp_fanout():
"""Producer-side completion waits for every paired consumer TP pull."""
worker = MooncakeConnectorWorker.__new__(MooncakeConnectorWorker)
worker.async_zmq_ctx = MagicMock()
worker.is_kv_consumer = True
@@ -960,13 +947,11 @@ async def test_heterogeneous_pp_waits_for_consumer_without_shared_layers():
FakeMooncakeWrapper,
)
async def test_kv_producer(monkeypatch):
"""
Simulates a Producer Worker (Prefiller) receiving a transfer request
"""Simulates a Producer Worker (Prefiller) receiving a transfer request
from a Consumer (Decoder).
Verifies memory offset calculation: ptr = base_addr + block_id * block_len.
"""
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
@@ -1133,12 +1118,10 @@ async def test_kv_producer(monkeypatch):
@pytest.mark.asyncio
async def test_kv_consumuer(monkeypatch):
"""
Simulates a Consumer Worker (Decoder) initiating a pull from a Producer.
"""Simulates a Consumer Worker (Decoder) initiating a pull from a Producer.
Verifies that MooncakeXferMetadata is correctly serialized and sent via ZMQ.
"""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -1211,7 +1194,6 @@ async def test_kv_consumuer(monkeypatch):
@pytest.mark.asyncio
async def test_worker_get_finished_timeout(monkeypatch):
"""Tests the cleanup mechanism for requests."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
)
@@ -1263,7 +1245,6 @@ async def test_worker_get_finished_timeout(monkeypatch):
)
def test_register_kv_caches(layout: KVCacheLayout, separate_kv_head_groups: bool):
"""Tests the memory registration logic with the underlying Mooncake engine."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -1344,7 +1325,6 @@ def test_register_kv_caches(layout: KVCacheLayout, separate_kv_head_groups: bool
def test_register_kv_caches_supports_mixed_mla_and_eagle_shapes():
"""Mixed MLA+Eagle caches should register by byte length, not shape."""
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_consumer"
)
@@ -1408,8 +1388,7 @@ def test_register_kv_caches_supports_mixed_mla_and_eagle_shapes():
)
@pytest.mark.parametrize("d_tp_size", [1, 4], ids=["p_tp2_d_tp1", "p_tp2_d_tp4"])
async def test_kv_producer_heterogeneous_tp(monkeypatch, d_tp_size):
"""
Tests heterogeneous TP support in the producer transfer path.
"""Tests heterogeneous TP support in the producer transfer path.
Verifies correct pointer and offset calculation when producer TP=2
sends to consumer with TP=1 (P>D) or TP=4 (P<D).
@@ -1418,7 +1397,6 @@ async def test_kv_producer_heterogeneous_tp(monkeypatch, d_tp_size):
- P TP=2 > D TP=1: one D rank receives; dst_offset based on P rank
- P TP=2 < D TP=4: two D ranks receive; src_offset based on D rank
"""
P_TP_SIZE = 2
P_TP_RANK = 0
LOCAL_BLOCK_LEN = 4096
@@ -217,7 +217,6 @@ def test_metadata_hma_block_ids():
)
async def test_build_transfer_params_multi_group_trimming(monkeypatch):
"""_build_transfer_params trims per-group blocks when local > remote."""
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
@@ -314,7 +313,6 @@ async def test_build_transfer_params_multi_group_trimming(monkeypatch):
)
async def test_build_transfer_params_group_count_mismatch(monkeypatch):
"""_build_transfer_params reports an error when group counts differ."""
monkeypatch.setenv("VLLM_MOONCAKE_ABORT_REQUEST_TIMEOUT", "5")
vllm_config = create_vllm_config(
kv_connector="MooncakeConnector", kv_role="kv_producer"
@@ -199,7 +199,8 @@ def _bare_worker() -> MooncakeConnectorWorker:
"""Construct a MooncakeConnectorWorker skipping __init__ (full init requires
a live TransferEngine). Only the attributes touched by the methods under
test are populated; role flags and async_zmq_ctx keep __del__'s shutdown
path a no-op."""
path a no-op.
"""
worker = MooncakeConnectorWorker.__new__(MooncakeConnectorWorker)
worker.xfer_stats = MooncakeKVConnectorStats()
worker.engine = MagicMock()
@@ -77,7 +77,8 @@ def test_store_tp_does_not_override_backend_kv_cache_layout(extra_config):
def _make_kv_cache_config() -> KVCacheConfig:
"""Single-group full-attention KVCacheConfig — enough for the connector
constructor's validate() pass."""
constructor's validate() pass.
"""
spec = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
return KVCacheConfig(
num_blocks=4,
@@ -692,7 +693,8 @@ def _poll_lookup(client, req_id, num_tokens=128, block_hashes=(), timeout=5.0):
def _gated_recv(gate: threading.Event, value: int):
"""Mock recv side-effect that blocks until ``gate`` is set, so the
executor's lookup can be held pending deterministically."""
executor's lookup can be held pending deterministically.
"""
def recv():
gate.wait()
@@ -703,7 +705,8 @@ def _gated_recv(gate: threading.Event, value: int):
def test_lookup_key_client_non_block_lookup_async():
"""Non-blocking lookup defers to the executor: None first, hit once the
Future resolves."""
Future resolves.
"""
vllm_config = _make_vllm_config()
with patch(
@@ -33,7 +33,8 @@ def _mamba_align(block_size=32):
def _make_coord(groups, hash_block_size, use_eagle=False, retention_interval=None):
"""Construct a coordinator using the natural LCM of group block sizes as
the scheduler block size — mirrors ``resolve_kv_cache_block_sizes`` for
the test fixtures."""
the test fixtures.
"""
block_sizes = [g.kv_cache_spec.block_size for g in groups]
scheduler_block_size = lcm(*block_sizes)
return MooncakeStoreCoordinator(
@@ -143,7 +144,8 @@ def test_coordinator_single_full_attention_no_hits():
def test_coordinator_single_swa_tautological_pool_masks_pre_window():
"""SWA tautological-pool: hit_length spans full prefix, mask is
tail-window only."""
tail-window only.
"""
groups = [KVCacheGroupSpec(["L0"], _swa(block_size=16, sliding_window=32))]
coord = _make_coord(groups, hash_block_size=16)
hs = _hashes(4) # 4 chunks * 16 tokens
@@ -190,7 +192,8 @@ def test_coordinator_hybrid_hole_in_full_clips_both():
def test_coordinator_group_block_size_double_hash():
"""Group block_size=32 over hash_block_size=16 hashes: adjacent
hashes merge before pool lookup."""
hashes merge before pool lookup.
"""
groups = [
KVCacheGroupSpec(["L0"], _full(16)),
KVCacheGroupSpec(["L1"], _full(32)),
@@ -214,7 +217,8 @@ def test_coordinator_group_block_size_double_hash():
def test_coordinator_fine_grained_partial_tail_hit():
"""K3 shape: FA + mamba-align, block_size=32 over hash_block_size=16. When
both groups have the sub-block boundary hash, the reconciled hit lands on
the hash boundary (48), not the block boundary (32)."""
the hash boundary (48), not the block boundary (32).
"""
groups = [
KVCacheGroupSpec(["L0"], _full(32)),
KVCacheGroupSpec(["L1"], _mamba_align(32)),
@@ -234,7 +238,8 @@ def test_coordinator_fine_grained_partial_tail_hit():
def test_coordinator_fine_grained_clips_when_one_group_missing_tail():
"""If only one group has the sub-block boundary, min-convergence clips the
reconciled hit back to the block boundary (32)."""
reconciled hit back to the block boundary (32).
"""
groups = [
KVCacheGroupSpec(["L0"], _full(32)),
KVCacheGroupSpec(["L1"], _mamba_align(32)),
@@ -275,7 +280,8 @@ def test_store_mask_swa_only_window_around_each_lcm_boundary():
"""Hybrid full-attn(block=32) + SWA(block=8, sw=8). lcm=32. With
aligned=64 the SWA group should mark exactly the blocks ending at 32
and 64 (i.e. blocks 3 and 7 at block_size=8); the rest can never
participate in any future hit."""
participate in any future hit.
"""
full = _full(32)
swa = _swa(block_size=8, sliding_window=8)
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
@@ -321,7 +327,8 @@ def test_store_mask_swa_does_not_double_scale_under_dcp():
def test_store_mask_swa_wider_window_covers_more_blocks_per_lcm():
"""Same hybrid layout but sliding_window=16 (= 2 SWA blocks). Each lcm
boundary should now span two SWA tail blocks."""
boundary should now span two SWA tail blocks.
"""
full = _full(32)
swa = _swa(block_size=8, sliding_window=16)
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
@@ -351,7 +358,8 @@ def test_store_mask_dsv4_5_groups_full_mla_plus_4_swa():
"""DSV4-shaped: full-MLA(B=256) + 4 SWA groups with B in {64, 64, 4, 8}
and varied sliding windows. lcm=256, hash_block_size=4. Two lcm segments
(aligned_len=512). Validates that the tile-once strategy produces the
expected per-segment tail-window pattern, repeated."""
expected per-segment tail-window pattern, repeated.
"""
full_mla = _full(block_size=256)
swa_64_sw128 = _swa(block_size=64, sliding_window=128)
swa_64_sw512 = _swa(block_size=64, sliding_window=512)
@@ -385,7 +393,8 @@ def test_store_mask_dsv4_5_groups_full_mla_plus_4_swa():
def test_store_mask_fast_path_all_block_sizes_equal_lcm():
"""When every non-full-attn group already aligns to lcm_block_size, the
fast path returns all-True without invoking find_longest_cache_hit."""
fast path returns all-True without invoking find_longest_cache_hit.
"""
full = _full(block_size=64)
swa = _swa(block_size=64, sliding_window=128)
groups = [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
@@ -398,7 +407,8 @@ def test_store_mask_fast_path_all_block_sizes_equal_lcm():
def test_store_mask_fast_path_single_attention_group():
"""Two groups sharing the same SWA spec collapse to one attention group;
no lcm filter applies, every chunk is True."""
no lcm filter applies, every chunk is True.
"""
swa = _swa(block_size=16, sliding_window=32)
groups = [KVCacheGroupSpec(["L0"], swa), KVCacheGroupSpec(["L1"], swa)]
coord = _make_coord(groups, hash_block_size=16)
@@ -412,7 +422,8 @@ def test_store_mask_fast_path_single_attention_group():
def _retention_groups():
"""Hybrid full-attn(block=32) + SWA(block=8, sw=8); lcm=32. The SWA group
densely keeps one tail block per 32-token boundary."""
densely keeps one tail block per 32-token boundary.
"""
full = _full(32)
swa = _swa(block_size=8, sliding_window=8)
return [KVCacheGroupSpec(["L0"], full), KVCacheGroupSpec(["L1"], swa)]
@@ -420,7 +431,8 @@ def _retention_groups():
def test_store_mask_dense_default_matches_every_lcm_boundary():
"""retention_interval=None (default) keeps the SWA tail at every lcm
boundary: tokens 32/64/96/128 -> chunks 3/7/11/15."""
boundary: tokens 32/64/96/128 -> chunks 3/7/11/15.
"""
coord = _make_coord(_retention_groups(), hash_block_size=8)
masks = coord.store_mask(128)
assert masks[0] is None
@@ -430,7 +442,8 @@ def test_store_mask_dense_default_matches_every_lcm_boundary():
def test_store_mask_retention_interval_sparsifies_swa_tails():
"""retention_interval=64 keeps an SWA tail once per 64-token segment
(chunks 7 and 15) instead of every 32 tokens, dropping the mid-segment
boundaries at 32 and 96."""
boundaries at 32 and 96.
"""
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=64)
masks = coord.store_mask(128)
assert masks[0] is None # full attn unaffected
@@ -439,7 +452,8 @@ def test_store_mask_retention_interval_sparsifies_swa_tails():
def test_store_mask_retention_interval_zero_keeps_only_replay_boundary():
"""retention_interval=0 drops all segment tails; only the latest replay
boundary (capped at num_prompt-1, aligned down to lcm) is retained."""
boundary (capped at num_prompt-1, aligned down to lcm) is retained.
"""
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=0)
# No replay info -> nothing reachable for the SWA group.
assert coord.store_mask(128)[1] == [False] * 16
@@ -450,7 +464,8 @@ def test_store_mask_retention_interval_zero_keeps_only_replay_boundary():
def test_store_mask_retention_interval_keeps_segment_and_replay_tails():
"""Sparse segment tails (interval=64 -> chunks 7,15) plus the replay
boundary tail (num_prompt=100 -> chunk 11) coexist."""
boundary tail (num_prompt=100 -> chunk 11) coexist.
"""
coord = _make_coord(_retention_groups(), hash_block_size=8, retention_interval=64)
masks = coord.store_mask(128, num_prompt_tokens=100)
assert masks[1] == [i in (7, 11, 15) for i in range(16)]
@@ -488,7 +503,8 @@ def test_store_mask_excludes_mamba_groups_lookup_unaffected():
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."""
hand-off path instead.
"""
groups = [
KVCacheGroupSpec(["L0"], _full(16)),
KVCacheGroupSpec(["L1"], _mamba_align(16)),
@@ -509,7 +525,8 @@ def test_store_mask_excludes_mamba_groups_lookup_unaffected():
def test_lookup_with_eagle_pops_last_full_attention_block():
"""Sanity: with use_eagle, find_longest_cache_hit drops the last block.
Pairs with the load_mask test below to lock the round-trip contract."""
Pairs with the load_mask test below to lock the round-trip contract.
"""
groups = [KVCacheGroupSpec(["L0"], _full(16))]
coord = _make_coord(groups, hash_block_size=16, use_eagle=True)
hs = _hashes(4)
@@ -550,7 +567,8 @@ def test_load_mask_with_eagle_does_not_double_prune_full_attention():
def test_load_mask_with_eagle_hybrid_full_plus_swa():
"""Hybrid (FullAttn + SWA) with eagle: load_mask must cover every chunk
in [0, token_len) for the FullAttn group; SWA group keeps its
tail-window mask."""
tail-window mask.
"""
groups = [
KVCacheGroupSpec(["L0"], _full(16)),
KVCacheGroupSpec(["L1"], _swa(16, 32)),
@@ -1,7 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""End-to-end save->lookup test for MooncakeStoreConnector on a hybrid
(SWA + Full) attention config, using a dict-backed mock store."""
(SWA + Full) attention config, using a dict-backed mock store.
"""
import sys
import threading
@@ -147,8 +148,7 @@ def _build_worker_with_dict_store(vllm_config, kv_cache_config, store):
def test_e2e_swa_plus_full_save_then_lookup_hits():
"""
E2E: build a SWA+Full hybrid worker, save all blocks via the sending
"""E2E: build a SWA+Full hybrid worker, save all blocks via the sending
thread (synchronously), then verify lookup returns the full hit length.
Also verify that evicting SWA's early blocks (outside its window) still
allows a full hit because the window covers the tail.
@@ -283,7 +283,8 @@ def test_e2e_swa_plus_full_save_then_lookup_hits():
def test_recv_skips_swa_blocks_before_window():
"""Producer stored every block for both groups; consumer must only fetch
SWA blocks within the sliding window, not the head."""
SWA blocks within the sliding window, not the head.
"""
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
# sliding_window=32, block_size=16 → 2 contiguous blocks within window.
swa = SlidingWindowSpec(
@@ -351,7 +352,8 @@ def test_recv_skips_swa_blocks_before_window():
def test_chunked_token_database_hash_block_size_smaller_than_block_size():
"""DSv4-style: hash_block_size=4, group block_size=16 — process_tokens
keys each chunk by its ending fine hash, including a partial tail."""
keys each chunk by its ending fine hash, including a partial tail.
"""
md = KeyMetadata("m", 0, 0, 0, 0, group_id=3)
db = ChunkedTokenDatabase(md, block_size=16, hash_block_size=4)
db.set_kv_caches_base_addr([0])
@@ -384,7 +386,8 @@ def test_sub_block_partial_tail_offload_reads_cow_block():
"""Sub-block prompt (the 900/128/1536 shape, scaled to 12/4/16): the
partial tail is offloaded for both groups under the boundary sub-hash. The
full-attention block is read from the request block table; the mamba block
is the core-provided CoW target, not block_ids."""
is the core-provided CoW target, not block_ids.
"""
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
mamba = MambaSpec(
block_size=16,
@@ -463,7 +466,8 @@ def test_sub_block_partial_tail_offload_reads_cow_block():
def test_offload_syncs_event_before_put():
"""An offload-carrying meta synchronizes its CoW-fence event before the
store put reads the blocks, then completes in one pass and drains the
completion counter."""
completion counter.
"""
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
mamba = MambaSpec(
block_size=16,
@@ -534,7 +538,8 @@ def test_sub_block_partial_tail_offload_covers_smaller_group_blocks():
offload must persist every FA block up to the boundary — the normal save
floors to the lcm, so those blocks are otherwise never written and the
consumer's per-group lookup would miss. The mamba boundary block still
reads the core-provided CoW target."""
reads the core-provided CoW target.
"""
full = FullAttentionSpec(block_size=4, num_kv_heads=8, head_size=64, dtype=None)
mamba = MambaSpec(
block_size=16,
@@ -805,7 +810,8 @@ def test_ring_scratch_group_is_never_stored_and_does_not_block_hits():
"""A per-request ring group (CircularBufferSpec, capacity as block_size)
sits beside the paged group: worker setup tolerates its block size (the
DeepSeek-V4.1 compressor ring is 8 rows), saving a request stores paged
blocks only, and lookup hits on the paged group alone."""
blocks only, and lookup hits on the paged group alone.
"""
full = FullAttentionSpec(block_size=16, num_kv_heads=8, head_size=64, dtype=None)
ring = CircularBufferSpec(
block_size=8, num_kv_heads=1, head_size=64, head_size_v=0, dtype=torch.uint8
@@ -536,7 +536,8 @@ def _make_pending_load_unfinished_request(
def _make_pending_load_scheduler_output() -> SimpleNamespace:
"""scheduler_output for a step where req-0 is parked on a pending load
(not in scheduled_new_reqs or scheduled_cached_reqs)."""
(not in scheduled_new_reqs or scheduled_cached_reqs).
"""
return SimpleNamespace(
finished_req_ids=set(),
preempted_req_ids=set(),
@@ -712,7 +713,8 @@ def test_running_request_not_in_resumed_req_ids_appends_blocks():
def test_resumed_request_in_resumed_req_ids_replaces_blocks():
"""A request the scheduler marks resumed gets the FULL block table in
new_block_ids and must REPLACE the tracker's blocks (not append), even if
a stale tracker from before preemption is still present."""
a stale tracker from before preemption is still present.
"""
scheduler = _make_bare_scheduler()
_make_resumed_unfinished_request(
scheduler,
@@ -432,7 +432,8 @@ def _patch_worker_runtime(
def test_pool_key_to_string_without_prefix_is_unchanged():
"""Default (empty) cache_prefix keeps keys byte-identical to the
historical unprefixed format so existing deployments keep their hits."""
historical unprefixed format so existing deployments keep their hits.
"""
key = PoolKey(KeyMetadata("test-model", 0, 0, 0, 0), "deadbeef")
assert (
key.to_string() == "test-model@tp_rank:0@pcp0@dcp0@pp_rank:0@group:0@deadbeef"
@@ -573,7 +574,8 @@ def test_tp_shared_receiving_reads_each_local_store_shard():
def test_pool_key_cache_prefix_namespaces_and_disambiguates():
"""A non-empty cache_prefix is prepended, and two instances with
different prefixes never collide on identical block hashes."""
different prefixes never collide on identical block hashes.
"""
md_a = KeyMetadata("test-model", 0, 0, 0, 0, cache_prefix="depA")
md_b = KeyMetadata("test-model", 0, 0, 0, 0, cache_prefix="depB")
@@ -589,7 +591,8 @@ def test_pool_key_cache_prefix_namespaces_and_disambiguates():
def test_default_local_buffer_size_matches_pr40900():
"""PR-40900 shipped a 4 GiB default for local_buffer_size; the dual-mode
patch preserves it (and the JSON key) so unchanged PR-40900 configs work."""
patch preserves it (and the JSON key) so unchanged PR-40900 configs work.
"""
assert worker.DEFAULT_LOCAL_BUFFER_SIZE == 4 * 1024**3
@@ -1011,7 +1014,8 @@ def test_store_sending_thread_skips_null_sparse_group_blocks():
def test_partial_tail_offload_skips_cap_omitted_mamba_group():
"""A Mamba group omitted by the handoff cap must not fall back to the
connector's positional block table."""
connector's positional block table.
"""
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheGroupSpec,
@@ -1139,7 +1143,8 @@ def test_partial_tail_put_failure_activates_pressure_gate():
def test_normal_save_excludes_mamba_group_and_null_blocks():
"""The positional normal save must never cover mamba chunks (align-mode
block tables are not append-only) and must skip chunks whose block is the
reserved null block, for any group."""
reserved null block, for any group.
"""
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheGroupSpec,
@@ -1200,7 +1205,8 @@ def test_normal_save_excludes_mamba_group_and_null_blocks():
def test_block_aligned_snapshot_offload_uses_provided_block():
"""A block-aligned hand-off (sparse-retention mamba checkpoint) uploads
exactly the core-pinned block under the boundary-end hash key; the
positional block table entry for that chunk must be ignored."""
positional block table entry for that chunk must be ignored.
"""
store = MagicMock()
store.batch_is_exist.side_effect = lambda keys: [0] * len(keys)
store.batch_put_from_multi_buffers.side_effect = lambda keys, *a: [256] * len(keys)
@@ -1228,7 +1234,8 @@ def test_block_aligned_snapshot_offload_uses_provided_block():
def test_mixed_snapshot_and_sub_block_offloads():
"""A retention snapshot and the prompt-end sub-block CoW tail can arrive
in one hand-off; the sub-block path covers FA gap blocks but reads the
mamba boundary only from the CoW block, never positionally."""
mamba boundary only from the CoW block, never positionally.
"""
store = MagicMock()
store.batch_is_exist.side_effect = lambda keys: [0] * len(keys)
store.batch_put_from_multi_buffers.side_effect = lambda keys, *a: [256] * len(keys)
@@ -1268,7 +1275,8 @@ def test_mixed_snapshot_and_sub_block_offloads():
def test_snapshot_offload_skips_null_handoff_block():
"""A hand-off the core could not materialize (null block) carries no
committed state; persisting it would poison the boundary key."""
committed state; persisting it would poison the boundary key.
"""
store = MagicMock()
thread = _make_partial_tail_send_thread(store)
@@ -1596,7 +1604,8 @@ def test_store_sending_thread_passes_replicate_config_when_preferred_segment_set
def test_store_sending_thread_passes_default_replicate_config_when_no_preferred_segment(): # noqa: E501
"""Without a preferred_segment the SendingThread still forwards a
(default-constructed) ReplicateConfig so the C++ side always sees a
well-defined config object."""
well-defined config object.
"""
store = MagicMock()
store.batch_is_exist.side_effect = lambda keys: [0] * len(keys)
store.batch_put_from_multi_buffers.return_value = [256, 256]
@@ -2106,7 +2115,8 @@ def test_recv_thread_stops_after_first_failing_disk_offload_sub_batch():
def test_recv_thread_skips_split_when_budget_holds_all_keys():
"""PR-36 removed the count-based split trigger; with budget for 3 keys,
all three should be requested in a single call."""
all three should be requested in a single call.
"""
store = MagicMock()
store.batch_get_into_multi_buffers.return_value = [256, 256, 256]
thread = _make_store_recving_thread(
@@ -2320,7 +2330,8 @@ def test_requester_worker_init_skips_disk_budget_when_offload_disabled(
monkeypatch,
):
"""enable_offload=False zeroes out the disk budget so we don't generate
redundant owner GET-RPCs."""
redundant owner GET-RPCs.
"""
store = MagicMock()
store.setup.return_value = 0
_install_fake_mooncake(monkeypatch, store)
@@ -2995,7 +3006,8 @@ def test_requester_worker_group_semantics_string_true_enables(
def test_store_sending_thread_clamps_token_len_to_lcm():
"""Partial chunks past the last lcm boundary aren't stored — cache hits
are always lcm-aligned (mirrors HybridKVCacheCoordinator)."""
are always lcm-aligned (mirrors HybridKVCacheCoordinator).
"""
store = MagicMock()
store.batch_is_exist.return_value = [0, 0]
store.batch_put_from_multi_buffers.return_value = [256, 256]
@@ -3020,7 +3032,8 @@ def test_store_sending_thread_clamps_token_len_to_lcm():
def test_store_sending_thread_skips_when_token_len_below_lcm():
"""Requests shorter than lcm_block_size cannot produce any aligned chunk,
so neither the existence check nor the put should be issued."""
so neither the existence check nor the put should be issued.
"""
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheGroupSpec
store = MagicMock()
@@ -3810,7 +3823,8 @@ def test_lookup_full_hit_with_eagle_pops_once_not_twice():
"""Eagle already leaves the last block for the drafter, so a
full-prompt re-derivation must never fire for eagle-governed hits:
firing would anchor the search one block lower and pop a second
block, regressing the hit by an extra producer boundary."""
block, regressing the hit by an extra producer boundary.
"""
worker = _make_bare_worker(block_size=16)
worker.coord = mooncake_store_worker.MooncakeStoreCoordinator(
worker._kv_cache_groups,
@@ -3967,7 +3981,8 @@ def test_lookup_full_hit_swa_degrades_when_no_stored_boundary_is_usable():
the full hit into 48, whose SWA window needs the never-written block 1,
so every load failed and the recompute re-entered the same lookup. The
re-derivation must report that no stored boundary below the request end
is usable."""
is usable.
"""
from vllm.v1.kv_cache_interface import KVCacheGroupSpec, SlidingWindowSpec
worker = _make_bare_worker(block_size=16)
@@ -3989,7 +4004,8 @@ def test_lookup_full_hit_swa_degrades_when_no_stored_boundary_is_usable():
def test_lookup_swa_single_group_returns_full_when_tail_window_present():
"""Single-SWA, sliding_window=32 (= 2 blocks): producer stored only the
tail. Coordinator-driven lookup returns full prefix even though the
pre-window blocks are absent."""
pre-window blocks are absent.
"""
from vllm.v1.kv_cache_interface import KVCacheGroupSpec, SlidingWindowSpec
worker = _make_bare_worker(block_size=16)
@@ -4385,7 +4401,8 @@ def test_config_defaults_to_embedded():
def test_config_pr40900_unchanged(tmp_path):
"""A literal PR-40900 config (no mode, no enable_offload, no preferred_segment)
parses without raising and resolves to embedded mode."""
parses without raising and resolves to embedded mode.
"""
config_path = _write_mooncake_config(
tmp_path,
{
@@ -4493,7 +4510,8 @@ def test_config_zero_local_buffer():
def test_topology_standalone_store_with_disk_offload(tmp_path, monkeypatch):
"""standalone-store + disk: global_segment_size=0, enable_offload=True,
preferred_segment set. Assert setup() positional args, ReplicateConfig
wiring, and that the disk-offload buffer budget is allocated."""
wiring, and that the disk-offload buffer budget is allocated.
"""
store = MagicMock()
store.setup.return_value = 0
fake_replicate_config_cls = _install_fake_mooncake(monkeypatch, store)
@@ -4540,9 +4558,10 @@ def test_topology_standalone_store_with_disk_offload(tmp_path, monkeypatch):
def test_topology_embedded_cpu_only(tmp_path, monkeypatch):
"""embedded + CPU-only: no mode key (defaults to embedded),
"""Embedded + CPU-only: no mode key (defaults to embedded),
global_segment_size>0, enable_offload absent, no preferred_segment.
This is the PR-40900 baseline recipe."""
This is the PR-40900 baseline recipe.
"""
store = MagicMock()
store.setup.return_value = 0
fake_replicate_config_cls = _install_fake_mooncake(monkeypatch, store)
@@ -4731,7 +4750,8 @@ def test_store_worker_close_swallows_store_errors():
def test_blob_block_hashes_wire_roundtrip():
"""The lookup wire format sends a ``hash_len`` frame plus the raw hashes
concatenated back-to-back; the server rebuilds them through a zero-copy
``BlobBlockHashes`` view over the frame buffer."""
``BlobBlockHashes`` view over the frame buffer.
"""
hashes = [BlockHash(bytes([i]) * 16) for i in range(5)]
hash_len = len(hashes[0])
@@ -294,7 +294,6 @@ def create_vllm_config(
def test_write_mode_saves_local_block_ids():
"""Write mode records local block ids in MoRIIOConnectorMetadata.reqs_to_save."""
# Setup Scheduler and Request
vllm_config = create_vllm_config(role="kv_producer")
scheduler = create_scheduler(vllm_config)
@@ -405,7 +404,6 @@ def test_write_mode_with_chunked_prefill_saves_local_block_ids():
def test_read_mode_loads_remote_block_ids():
"""Read mode loads remote block ids into local cache mapping."""
# Setup Scheduler and Request
vllm_config = create_vllm_config(role="kv_consumer", read_mode=True)
scheduler = create_scheduler(vllm_config)
@@ -631,7 +629,6 @@ def test_register_kv_caches(mock_parallel_groups):
)
def test_moriio_handshake_returns_metadata(mock_parallel_groups):
"""MoRIIO handshake socket returns valid agent metadata over ZMQ."""
ROLE = "kv_consumer"
vllm_config = create_vllm_config(role=ROLE)
# Create test kv cache tensors using KVCacheSpec layout
@@ -695,7 +692,8 @@ def test_moriio_handshake_returns_metadata(mock_parallel_groups):
def test_resolve_host_ip_prefers_extra_config():
"""An explicit ``host_ip`` in kv_connector_extra_config overrides get_ip()
(so an external router can advertise a routable/internal address); an
absent or empty value falls back to get_ip()."""
absent or empty value falls back to get_ip().
"""
assert resolve_host_ip({"host_ip": "10.0.0.7"}) == "10.0.0.7"
fallback = get_ip()
@@ -749,7 +747,8 @@ def _read_scheduler(
def test_hma_blocks_per_sw_two_groups():
"""A Full + SlidingWindow config runs with HMA and computes block budgets
correctly"""
correctly
"""
scheduler = _read_scheduler(_make_hybrid_kv_cache_config())
assert scheduler._is_hma_required is True
# cdiv(32, 16) + 1 == 3 for the sliding-window group, 0 for full attention.
@@ -767,7 +766,8 @@ def test_hma_blocks_per_sw_two_groups():
def test_is_hma_required(swa_enabled, disable_hma, expected_is_hma):
"""_is_hma_required tracks both the KV cache groups and the
--disable-hybrid-kv-cache-manager flag. When HMA is off,
get_exchange_clipped_blocks must be a no-op."""
get_exchange_clipped_blocks must be a no-op.
"""
config = (
_make_hybrid_kv_cache_config() if swa_enabled else _make_test_kv_cache_config()
)
@@ -780,7 +780,8 @@ def test_is_hma_required(swa_enabled, disable_hma, expected_is_hma):
def test_non_sliding_window_hybrid_is_rejected():
"""A hybrid group that is not sliding-window (e.g. chunked-local
attention) must fail closed rather than be silently mistransferred."""
attention) must fail closed rather than be silently mistransferred.
"""
full_spec = FullAttentionSpec(
block_size=16, num_kv_heads=4, head_size=64, dtype=torch.float16
)
@@ -814,7 +815,8 @@ def test_non_sliding_window_hybrid_is_rejected():
def test_token_count_basis_uses_full_attention_group():
"""Chunked-prefill token counting must use an unclipped full-attention
group (blocks_per_sw == 0), not a clipped sliding-window group."""
group (blocks_per_sw == 0), not a clipped sliding-window group.
"""
scheduler = _read_scheduler(_make_hybrid_kv_cache_config())
# Group 0 is the full-attention group
assert scheduler._full_attn_group_idx == 0
@@ -823,7 +825,8 @@ def test_token_count_basis_uses_full_attention_group():
def test_get_exchange_clipped_blocks_clips_only_sw_group():
"""get_exchange_clipped_blocks keeps the full attn group intact and clips the
sliding-window group to its window tail."""
sliding-window group to its window tail.
"""
scheduler = _read_scheduler(_make_hybrid_kv_cache_config())
full = [10, 11, 12, 13, 14]
sw = [20, 21, 22, 23, 24]
@@ -834,7 +837,8 @@ def test_get_exchange_clipped_blocks_clips_only_sw_group():
def test_metadata_hma_block_ids_preserved_per_group():
"""add_new_req stores per-group (BlockIds) block lists unchanged for both
read and write, so the hybrid group structure is retained."""
read and write, so the hybrid group structure is retained.
"""
metadata = MoRIIOConnectorMetadata()
# Assume:
@@ -110,7 +110,8 @@ def make_meta(*, p_tp: int, p_dp: int, remote_dp_rank: int, host: str = "phost0"
def build_decode_workers(cfg: PDConfig) -> list:
"""Decode workers that issue reads for one prefill instance. A TP decode
instance reads from every tp rank; a DP decode instance from each dp-rank
worker. Reused across requests so per-worker round-robin state advances."""
worker. Reused across requests so per-worker round-robin state advances.
"""
if cfg.d_tp > 1:
return [
make_decode_worker(world_size=cfg.d_tp, tp_rank=r, dp_rank=0)
@@ -125,7 +126,8 @@ def prefill_target_multiset(cfg: PDConfig, rounds: int) -> Counter:
"""Drive the REAL _resolve_read_source over a fair input stream; tally which
prefill GPU each read targets. The only modelled assumption is the proxy
contract -- each owner dp-rank delivered equally (``for owner_dp in
range(p_dp)``); no proxy algorithm is reproduced."""
range(p_dp)``); no proxy algorithm is reproduced.
"""
workers = build_decode_workers(cfg)
hits: Counter = Counter()
for _ in range(rounds):
@@ -171,7 +171,7 @@ def test_register_finished_partial_tail_notifies_every_connector():
@pytest.fixture
def mc() -> MultiConnector:
"""MultiConnector using two mocked connectors"""
"""MultiConnector using two mocked connectors."""
mock_connector_config = {
"kv_connector": "MockConnector",
"kv_role": "kv_both",
@@ -215,8 +215,7 @@ def _compare_directories(dir1: Path, dir2: Path) -> bool:
def test_multi_example_connector_consistency():
"""
Tests that MultiConnector with two ExampleConnectors saves
"""Tests that MultiConnector with two ExampleConnectors saves
identical KV cache data to separate storage locations.
"""
storage_1_path = Path("storage_1/")
@@ -455,8 +454,7 @@ def test_engine_id_conflict():
def test_multi_connector_handle_preemptions_integration():
"""
Integration test: verify MultiConnector delegates handle_preemptions
"""Integration test: verify MultiConnector delegates handle_preemptions
to all sub-connectors.
Uses TestExampleConnector which logs all method calls to temp files.
@@ -557,7 +555,8 @@ class TestMultiConnectorStats:
def test_build_kv_connector_stats_reconstructs_nixl_stats(self):
"""Test that NixlConnector stats are properly reconstructed with
correct data."""
correct data.
"""
serialized_data = {
"NixlConnector": {
"transfer_duration": [1.5, 2.3],
@@ -863,9 +862,7 @@ class TestMultiConnectorStats:
def test_multi_connector_overrides_all_base_methods():
"""
Ensure MultiConnector overrides all public methods from KVConnectorBase_V1.
"""
"""Ensure MultiConnector overrides all public methods from KVConnectorBase_V1."""
# These are fine to inherit from KVConnectorBase_V1
# TODO(https://github.com/vllm-project/vllm/pull/31811): Remove
# get_kv_connector_kv_cache_events from INHERITED_OK once implemented.
@@ -1045,12 +1042,10 @@ def _make_multi_connector(connector_names: list[str]) -> MultiConnector:
def test_multi_connector_hma_support_detection():
"""
At runtime, _all_support_hma is True only when every sub-connector
"""At runtime, _all_support_hma is True only when every sub-connector
implements SupportsHMA. Test all combinations of HMA / non-HMA
sub-connectors.
"""
assert supports_hma(MultiConnector)
# -- All non-HMA connectors => _all_support_hma is False --
@@ -1092,8 +1087,7 @@ def test_divergent_local_hybrid_hit_capability_is_conservative():
not torch.cuda.is_available(), reason="Requires GPU to instantiate LLM"
)
def test_multi_connector_mixed_hma_disables_hybrid_kv_cache(monkeypatch):
"""
When MultiConnector wraps a mix of HMA (NixlConnector) and non-HMA
"""When MultiConnector wraps a mix of HMA (NixlConnector) and non-HMA
(MockConnector) sub-connectors, verify that:
1. The scheduler's MultiConnector has _all_support_hma == False.
2. vLLM auto-disables the hybrid KV cache manager (no preference expressed by user)
@@ -84,8 +84,7 @@ from .utils import (
@pytest.fixture(scope="module", autouse=True)
def clear_kv_transfer():
"""
The test cases in this file use `VLLM_ENABLE_V1_MULTIPROCESSING=0`,
"""The test cases in this file use `VLLM_ENABLE_V1_MULTIPROCESSING=0`,
causing the global variable `_KV_CONNECTOR_AGENT`
to be assigned but never deleted.
@@ -245,7 +244,6 @@ nixl_agent = FakeNixlWrapper
def test_basic_interface():
"""Unit test for basic NixlConnector interface functionality."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -284,8 +282,7 @@ def test_basic_interface():
def test_prompt_less_than_block_size():
"""
Test that we can handle case where prompt is < block.
"""Test that we can handle case where prompt is < block.
In this case, the P worker will still send remote_block_ids of the
partial block. The D worker should schedule an async read
@@ -321,7 +318,8 @@ def test_abort_immediately_remote_prefill_enqueues_empty_recv():
"""A remote-prefill request added with abort_immediately=True should
be added to the scheduler's waiting queue then immediately aborted, so the
NIXL connector's request_finished hook enqueues an empty recv to notify
the prefill instance to free its blocks."""
the prefill instance to free its blocks.
"""
from vllm.v1.request import RequestStatus
scheduler = create_scheduler(create_vllm_config())
@@ -407,7 +405,6 @@ def test_prefill_exports_cached_tokens_in_kv_transfer_params():
)
def test_kv_transfer_handshake(dist_init):
"""Unit test for basic NixlConnector interface functionality."""
# Test setup, we creates a scheduler that contains a NixlConnector
# of role SCHEDULER, and expect it to be serving NixlAgentMetadata from
# all workers of the instance.
@@ -830,7 +827,6 @@ class TestNixlHandshake:
prefill_tp_size,
):
"""Test that NixlConnector's start_load_kv should be non-blocking."""
vllm_config = create_vllm_config()
vllm_config.parallel_config.tensor_parallel_size = decode_tp_size
@@ -885,8 +881,7 @@ class TestNixlHandshake:
def test_prefill_tp_size_greater_than_decode_tp_size(
self, local_tp_size: int, default_vllm_config, dist_init, monkeypatch
):
"""
Verify remote TP > local TP handshake succeeds with different
"""Verify remote TP > local TP handshake succeeds with different
remote configurations.
"""
monkeypatch.setattr(
@@ -959,8 +954,7 @@ class TestNixlHandshake:
def test_prefill_tp_size_greater_than_decode_tp_size_mla(
self, default_vllm_config, dist_init
):
"""
Verify remote TP > local TP handshake succeeds with different
"""Verify remote TP > local TP handshake succeeds with different
remote configurations for an MLA model.
"""
vllm_config = create_vllm_config()
@@ -1066,7 +1060,6 @@ class TestNixlHandshake:
dist_init,
):
"""Test that multiple start_load_kv calls should occur concurrently."""
vllm_config = create_vllm_config()
# Test worker role in decode server.
@@ -1127,8 +1120,7 @@ class TestNixlHandshake:
def test_handshake_fails_on_kv_cache_layout_mismatch(
self, default_vllm_config, dist_init
):
"""
Verify that adding a remote agent fails if kv_cache_layout differs.
"""Verify that adding a remote agent fails if kv_cache_layout differs.
This test is only relevant for heterogeneous TP.
"""
vllm_config = create_vllm_config()
@@ -1185,8 +1177,7 @@ class TestNixlHandshake:
def test_handshake_succeed_on_kv_cache_layout_mismatch_with_experimental(
self, default_vllm_config, dist_init
):
"""
Verify that adding a remote agent fails if kv_cache_layout differs.
"""Verify that adding a remote agent fails if kv_cache_layout differs.
This test is only relevant for heterogeneous TP.
"""
vllm_config = create_vllm_config(enable_permute_local_kv=True)
@@ -1624,11 +1615,9 @@ def test_reqs_to_send_deadline_rebased_to_worker_clock(default_vllm_config, dist
def test_kv_connector_stats_aggregation():
"""
Test KV transfer stats aggregation across TP ranks using
"""Test KV transfer stats aggregation across TP ranks using
KVOutputAggregator (used by MultiprocExecutor).
"""
# Create KVOutputAggregator for 3 workers (simulating TP=3), same thing
# done in MultiprocExecutor.execute_model
aggregator = KVOutputAggregator(expected_finished_count=3)
@@ -1691,11 +1680,9 @@ def test_kv_connector_stats_aggregation():
def test_multi_kv_connector_stats_aggregation():
"""
Test MultiKVConnectorStats aggregation across TP ranks using
"""Test MultiKVConnectorStats aggregation across TP ranks using
KVOutputAggregator (used by MultiprocExecutor).
"""
aggregator = KVOutputAggregator(expected_finished_count=3)
from dataclasses import dataclass
@@ -1836,8 +1823,7 @@ def test_scheduler_kv_connector_stats_aggregation():
FakeNixlWrapper,
)
def test_abort_timeout_on_prefiller(monkeypatch, distributed_executor_backend):
"""
Test lifecycle of an aborted Remote Prefill request hitting the timeout.
"""Test lifecycle of an aborted Remote Prefill request hitting the timeout.
-----> P
| {process request}
<-/--- | {result is NOT delivered, eg proxy is down}
@@ -2123,8 +2109,7 @@ def test_register_kv_caches(
layout,
separate_kv_head_groups,
):
"""
Test that register_kv_caches() properly calls nixl_wrapper methods with
"""Test that register_kv_caches() properly calls nixl_wrapper methods with
correct data.
This test verifies:
@@ -2133,7 +2118,6 @@ def test_register_kv_caches(
2. nixl_wrapper.get_xfer_descs() is called with blocks_data containing
block layout info
"""
vllm_config = create_vllm_config(attention_backend=attn_backend)
vllm_config.cache_config.kv_cache_layout = layout
@@ -2361,17 +2345,14 @@ class FakePlatform(Platform):
@classmethod
def get_nixl_supported_devices(cls) -> dict[str, tuple[str, ...]]:
"""
Returns a mapping from device_type to a tuple of supported
"""Returns a mapping from device_type to a tuple of supported
kv_buffer_device for nixl.
"""
return {"oot": ("oot",)}
@classmethod
def get_nixl_memory_type(cls) -> str | None:
"""
Returns the nixl memory type for the current platform.
"""
"""Returns the nixl memory type for the current platform."""
return "VRAM"
@@ -2384,8 +2365,7 @@ class FakePlatform(Platform):
def test_kv_buffer_to_nixl_memory_types(
default_vllm_config, dist_init, kv_buffer_device, nixl_memory_type
):
"""
Test that register_kv_caches() passes the correct memory types from the
"""Test that register_kv_caches() passes the correct memory types from the
config to the nixl_wrapper.
"""
vllm_config = create_vllm_config()
@@ -2657,8 +2637,7 @@ def test_transfer_topology_unregister():
FakeNixlWrapper,
)
def test_aborted_request_removed_from_worker_in_batch(default_vllm_config, dist_init):
"""
Create and schedule a request so that P adds it to in-batch tracking via
"""Create and schedule a request so that P adds it to in-batch tracking via
the real scheduler, then simulate an abort (request not in next scheduler
iteration) and verify the worker no longer tracks it as in-batch.
"""
@@ -3167,7 +3146,8 @@ def test_split_read_failure_defers_report_until_last_handle(
request — nor invalidate its blocks — while the sibling xfer is still in
flight: a posted READ cannot be aborted and would DMA into blocks the
scheduler could free and reuse. The report happens exactly once, when the
last handle is terminal."""
last handle is terminal.
"""
request_id = "split_read_partial_failure"
err_handle, live_handle = 11, 22
connector, worker, wrapper = _make_split_read_connector(
@@ -3562,15 +3542,16 @@ def test_compatibility_hash_validation(
should_fail,
enforce_handshake_compat,
):
"""
Test NIXL compatibility hash validation during handshake.
"""Test NIXL compatibility hash validation during handshake.
Parameters:
Parameters
----------
mismatch_type: description of what is being tested
config_overrides: dict of config to override for the remote instance
version_override: version dict e.g. {"vllm_version": "0.6.1"}
should_fail: whether the handshake should fail
enforce_handshake_compat: whether to enforce compatibility checking
"""
local_vllm_config = create_vllm_config(
model="facebook/opt-125m",
@@ -3698,8 +3679,7 @@ def test_compatibility_hash_validation(
FakeNixlWrapper,
)
def test_handshake_decode_errors(default_vllm_config, dist_init, error_scenario):
"""
Test that msgspec decode errors are properly handled during handshake.
"""Test that msgspec decode errors are properly handled during handshake.
Tests both DecodeError and ValidationError for both decoders:
- NixlHandshakePayload decoder
@@ -281,7 +281,8 @@ def test_update_state_after_alloc_tracks_cached_blocks_per_group():
"""Hybrid SWA+FA requests can have different prefix-cache-hit counts per
KV cache group. Each group's count must be tracked independently rather
than collapsed to a single scalar, or DCP read-phase alignment
(local_num_computed_blocks) would misalign one of the groups."""
(local_num_computed_blocks) would misalign one of the groups.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.pull_scheduler import (
NixlPullConnectorScheduler,
)
@@ -335,7 +336,8 @@ def test_full_local_hit_is_not_awaited_by_the_scheduler():
owed to the producer -- so the worker must not report it in
finished_recving. Doing so trips `assert RequestStatus.is_finished` in
_update_from_kv_xfer_finished, which only tolerates a finished recv for a
request that is parked or already done."""
request that is parked or already done.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.pull_scheduler import (
NixlPullConnectorScheduler,
)
@@ -440,7 +442,8 @@ def test_apply_dcp_prefix_caching_matches_global_logical_positions(
"""_apply_dcp_prefix_caching must operate on logical block IDs (DCP
interleaves at logical-block granularity) and always return equal-length
local/remote slices, so a later, unconditional _apply_prefix_caching
trim is a guaranteed no-op rather than double-processing the read."""
trim is a guaranteed no-op rather than double-processing the read.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
NixlConnectorWorker,
)
@@ -839,7 +842,8 @@ def test_apply_prefix_caching_ssm_prefix_cache_hit(
def test_apply_prefix_caching_ssm_unpairable_slots_rejected():
"""Local SSM slots can only exceed the remote ones by the position D
recomputes itself. A larger excess means the lists aren't
position-aligned: fail loudly rather than transfer into wrong slots."""
position-aligned: fail loudly rather than transfer into wrong slots.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
NixlConnectorWorker,
)
@@ -1029,8 +1033,7 @@ def test_fewer_blocks_with_hma(monkeypatch, model_name, sw_size):
@pytest.mark.cpu_test
def test_nixl_metadata_hma_block_ids_structure():
"""
Test that NixlConnectorMetadata correctly stores block IDs for multiple
"""Test that NixlConnectorMetadata correctly stores block IDs for multiple
KV cache groups when HMA is enabled.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
@@ -1156,7 +1159,8 @@ def test_nixl_region_sort_preserves_pipeline_layer_order():
@pytest.mark.cpu_test
def test_get_block_descs_ids_hybrid_ssm():
"""Test _compute_desc_ids uses per-group strides for hybrid
FA+SSM when ratio=1 (no kernel block size mismatch)."""
FA+SSM when ratio=1 (no kernel block size mismatch).
"""
from vllm.v1.kv_cache_interface import FullAttentionSpec, MambaSpec
worker = _make_mock_worker_for_desc_ids(
@@ -1240,7 +1244,8 @@ def test_get_block_descs_ids_uses_per_region_pool_capacity():
@pytest.mark.cpu_test
def test_get_block_descs_ids_kernel_block_mismatch():
"""Test _compute_desc_ids uses different strides for FA
(kernel blocks) vs SSM (logical blocks) when ratio > 1."""
(kernel blocks) vs SSM (logical blocks) when ratio > 1.
"""
from vllm.v1.kv_cache_interface import FullAttentionSpec, MambaSpec
ratio = 4
@@ -1271,7 +1276,8 @@ def test_get_block_descs_ids_kernel_block_mismatch():
def test_get_block_descs_ids_hetero_block_size_hybrid():
"""With a block-size ratio, FA desc ids are ratio-expanded while SSM
desc ids keep the unexpanded logical stride (state blocks are never
sub-split)."""
sub-split).
"""
from vllm.v1.kv_cache_interface import FullAttentionSpec, MambaSpec
worker = _make_mock_worker_for_desc_ids(
@@ -1310,7 +1316,8 @@ def _bind_worker_method(worker, name):
@pytest.mark.cpu_test
def test_map_block_ids_for_block_size_ratio_hybrid():
"""Attention groups expand to remote granularity and clip to the remote
coverage; mamba state blocks pass through 1:1."""
coverage; mamba state blocks pass through 1:1.
"""
from unittest.mock import MagicMock
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
@@ -1341,7 +1348,8 @@ def test_map_block_ids_for_block_size_ratio_hybrid():
@pytest.mark.cpu_test
def test_post_process_zeroes_untransferred_tail():
"""The untransferred sub-blocks of the last local block are zeroed on
receive; mamba state caches are untouched by the attention permute."""
receive; mamba state caches are untouched by the attention permute.
"""
from unittest.mock import MagicMock
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
@@ -1384,7 +1392,8 @@ def test_post_process_zeroes_untransferred_tail():
@pytest.mark.cpu_test
def test_nixl_metadata_hybrid_ssm_block_ids():
"""Test NixlConnectorMetadata correctly stores block IDs for FA + SSM
groups with different block counts (kernel mismatch active)."""
groups with different block counts (kernel mismatch active).
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
NixlConnectorMetadata,
)
@@ -1465,7 +1474,8 @@ def _make_fake_kv_cache_manager():
@pytest.mark.cpu_test
def test_zeroing_block_ids_cover_only_loaded_attention_blocks():
"""Only zero-recorded (attention) groups contribute, sliced to the
externally-loaded token range; Mamba state blocks are never zeroed."""
externally-loaded token range; Mamba state blocks are never zeroed.
"""
manager = _make_fake_kv_cache_manager()
# Tokens [0, 16) are locally cached; the load covers tokens [16, 56).
@@ -1493,7 +1503,8 @@ def test_scheduler_filters_connector_loaded_blocks_from_zeroing():
@pytest.mark.cpu_test
def test_failed_load_rezeroes_unwritten_skipped_blocks():
"""A failed async load leaves zeroing-skipped blocks unwritten beyond
the valid prefix; they must be zeroed before local recompute."""
the valid prefix; they must be zeroed before local recompute.
"""
from unittest.mock import MagicMock
from vllm.v1.core.sched.scheduler import Scheduler
@@ -1953,7 +1964,8 @@ def test_logical_to_kernel_block_ids_with_remote_ratio(
def test_exchange_clipped_blocks_ssm_single_state():
"""In single-state cache modes, SSM lists are reduced to the running
state slot: speculative scratch slots, null placeholders and the previous
step's state carry nothing. Attention groups pass through untouched."""
step's state carry nothing. Attention groups pass through untouched.
"""
sched = make_nixl_scheduler(has_mamba=True, is_hma_required=True)
sched.blocks_per_sw = [0, 0]
sched._ssm_spec_blocks = [None, 2]
@@ -1980,7 +1992,8 @@ def test_exchange_clipped_blocks_ssm_single_state():
@pytest.mark.cpu_test
def test_exchange_clipped_blocks_ssm_positional_states():
"""In "all" mode every position holds a state, so only the speculative
slots go; placeholders stay to keep the list position-indexed."""
slots go; placeholders stay to keep the list position-indexed.
"""
sched = make_nixl_scheduler(has_mamba=True, is_hma_required=True)
sched.blocks_per_sw = [0, 0]
sched._ssm_spec_blocks = [None, 2]
@@ -1997,7 +2010,8 @@ def _make_hybrid_mla_kv_cache_config(num_blocks: int = 4):
"""KimiLinear-shaped config: one MLA group and two KDA (GDN-typed
MambaSpec) groups whose layers share the same HMA tensors, with a
mamba-aligned unified page and an MLA kernel block smaller than the
logical block."""
logical block.
"""
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.kv_cache_interface import (
KVCacheConfig,
@@ -2137,7 +2151,8 @@ def test_register_kv_caches_hybrid_mla_dual_purpose_regions():
"""Hybrid MLA+KDA registration: HMA tensors shared by both layer types
must be flagged as MLA regions even when a KDA layer registers them
first, expose TP-independent kernel-granularity block lens, and build
FA + mamba descriptors for every region."""
FA + mamba descriptors for every region.
"""
from unittest.mock import MagicMock
from vllm.config import set_current_vllm_config
@@ -2238,7 +2253,8 @@ def test_register_kv_caches_hybrid_mla_dual_purpose_regions():
def test_push_write_hybrid_mla_replicates_attention():
"""Hybrid MLA+SSM push with P_TP < D_TP: attention blocks must be
written to every covered D rank (replicated MLA latent) while SSM state
is written per-rank through the split handles."""
is written per-rank through the split handles.
"""
import threading
from collections import defaultdict
from unittest.mock import MagicMock
@@ -24,7 +24,8 @@ from .utils import create_vllm_config
class _RecordingNixl:
"""Minimal NIXL wrapper stand-in that records descriptor lists and
prepared transfers so tests can resolve desc ids to byte ranges."""
prepared transfers so tests can resolve desc ids to byte ranges.
"""
def __init__(self, *args, **kwargs):
self.dlists: dict[int, np.ndarray] = {}
@@ -593,7 +594,8 @@ def _register_remote_agents(worker, metadata, tp_size):
def _owned_byte_ranges(worker, group_logical_ids):
"""Byte ranges owned by a request: for each HMA region tensor, every
logical block id of every group maps to one unified page."""
logical block id of every group maps to one unified page.
"""
unified_page = worker._test_unified_page
bases = [t.data_ptr() for t in worker._test_tensors]
owned = []
@@ -631,7 +633,8 @@ def test_hetero_ppl_multi_read_writes_stay_within_request_blocks():
(kernel 4, ppl=3) vs remote (P, TP2) logical blocks of 8 tokens (ppl=2),
equal kernel pages, tp_ratio=-2 multi-read with replicated MLA and
TP-sharded KDA state. Every local descriptor of the request's reads must
stay within its own blocks."""
stay within its own blocks.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
NixlConnectorMetadata,
)
@@ -698,7 +701,8 @@ def _resolve(
"""Resolve a desc id to (region, kind, token_start) where kind is 'attn'
(desc-page sized, sub-block-aligned, in the request's attention blocks)
or 'mamba'. token_start is the request-relative token offset, so local
and remote are comparable even when their kernel blocks differ in size."""
and remote are comparable even when their kernel blocks differ in size.
"""
addr, length, _ = (int(x) for x in desc_arr[int(idx)])
for region, base in enumerate(bases):
off = addr - base
@@ -892,7 +896,8 @@ def _run_hetero_case(
def test_hetero_ppl_token_alignment_sweep(local_block, remote_block, num_tokens):
"""Sweep prompt lengths across block-boundary residues for several
hetero-ppl geometries; assert neighbor-safety, token alignment, and
coverage of every transferred kernel block."""
coverage of every transferred kernel block.
"""
_run_hetero_case(
local_block, kernel=4, remote_block=remote_block, num_tokens=num_tokens
)
@@ -911,7 +916,8 @@ def test_hetero_ppl_with_block_size_ratio(num_tokens):
2). The transfer is clipped at remote sub-block granularity by the
pairing and front-trimmed by _apply_prefix_caching, so the
untransferred tail can span both a partial block and whole blocks —
the case each of the two former zeroing paths handled only half of."""
the case each of the two former zeroing paths handled only half of.
"""
_run_hetero_case(
local_block=24,
kernel=8,
@@ -960,7 +966,8 @@ def test_mla_hybrid_large_ppl_geometry(num_tokens):
"""KimiLinear-scale MLA-hybrid geometry (TP8 prefill -> TP1 decode):
decode (local) logical block 5760 / kernel 64 (ppl=90), prefill
(remote) logical block 768 (ppl=12), tp_ratio=-8 multi-read with
replicated MLA and 8-way TP-sharded KDA state."""
replicated MLA and 8-way TP-sharded KDA state.
"""
_run_hetero_case(
local_block=5760,
kernel=64,
@@ -974,7 +981,8 @@ def test_mla_hybrid_large_ppl_geometry(num_tokens):
def test_mismatched_mla_kernel_page_rejected_for_mla_hybrid():
"""The MLA per-token page is TP-independent, so kernel block lengths
differing by anything other than the block-size ratio must fail the
handshake loudly rather than transfer at mismatched geometry."""
handshake loudly rather than transfer at mismatched geometry.
"""
worker = _make_mla_hybrid_worker(
local_block_size=12, kernel_block_size=4, num_logical_blocks=8
)
@@ -1158,7 +1166,8 @@ def test_csa_linear_registration_discovers_shared_regions():
def test_csa_linear_scratch_descs_follow_the_pages_they_overlay():
"""The scratch ring is addressed by the regions it actually registered in,
not by inferring that it must sit on the MLA pages: overlaying the main KV
pages instead moves its descriptors with it."""
pages instead moves its descriptors with it.
"""
worker = _make_csa_linear_ple_worker(scratch_aliases="main_kv")
# Same MLA regions as before, but the ring now lives in the non-MLA ones.
@@ -1292,7 +1301,8 @@ def test_csa_linear_remote_ple_is_copied_whole():
def _make_ring_worker():
"""Paged MLA group plus a per-layer ring group, no Mamba: the shape of a
model whose sliding-window KV lives in per-request rings."""
model whose sliding-window KV lives in per-request rings.
"""
from unittest.mock import MagicMock
from vllm.config import set_current_vllm_config
@@ -115,7 +115,8 @@ class _BlocksMock:
def _stub_sw_clipping(scheduler) -> None:
"""Make ``get_exchange_clipped_blocks`` a passthrough so tests don't
need the full sliding-window machinery."""
need the full sliding-window machinery.
"""
scheduler.get_exchange_clipped_blocks = lambda block_ids, clip_ssm=True: block_ids
@@ -173,7 +174,8 @@ class TestPushScheduler:
def test_p_side_request_finished_stages_blocks(self):
"""P scheduler pushes blocks into both _finished_request_blocks (lease)
and _newly_finished_push_blocks (metadata for next step)."""
and _newly_finished_push_blocks (metadata for next step).
"""
sched = make_nixl_push_scheduler()
_stub_sw_clipping(sched)
@@ -192,7 +194,8 @@ class TestPushScheduler:
def test_build_connector_meta_drains_both_sides(self):
"""meta.push_registrations and meta.push_finished_blocks are filled
from the staging dicts and the staging dicts are cleared."""
from the staging dicts and the staging dicts are cleared.
"""
sched = make_nixl_push_scheduler()
_stub_sw_clipping(sched)
@@ -287,7 +290,8 @@ class TestPushScheduler:
def test_registration_watchdog_expires(self, caplog):
"""Stale D registrations whose deadline has passed are dropped at
``build_connector_meta`` time."""
``build_connector_meta`` time.
"""
# Watchdog logs a WARNING when it drops the stale entry; that's
# what this test is verifying, so silence it in the test report.
caplog.set_level(
@@ -328,7 +332,8 @@ class TestPushScheduler:
class _StubWriterWorker(NixlPushConnectorWorker):
"""Construct a worker without invoking ``__init__`` so we can drive
the matching/notif logic without bringing up NIXL or torch."""
the matching/notif logic without bringing up NIXL or torch.
"""
@classmethod
def fresh(cls) -> _StubWriterWorker:
@@ -434,7 +439,8 @@ class TestPushWriterRegSend:
"""``_do_send_reg_notif``: the PUSH_REG goes to every handshaked agent of
the P engine, and the agent map is read under ``_handshake_lock`` so the
send can't race the handshake done-callback's insert or a concurrent
stale-engine eviction (X1)."""
stale-engine eviction (X1).
"""
def _reg_send_worker(self) -> tuple[_StubWriterWorker, list]:
w = _StubWriterWorker.fresh()
@@ -479,7 +485,8 @@ class TestPushWriterRegSend:
def test_agent_read_is_serialized_with_handshake_lock(self):
"""While another thread holds ``_handshake_lock`` (as the handshake
done-callback does while writing ``_remote_agents``), the writer's
check-then-send must not run ahead of the critical section."""
check-then-send must not run ahead of the critical section.
"""
w, failures = self._reg_send_worker()
w._remote_agents["prefill-engine"] = {(0, 0): "agent-0"}
rd = _registration_data("req-1")
@@ -589,7 +596,8 @@ class TestPushWriterMatching:
class TestPushWriterStartLoadKv:
def test_finished_blocks_inbox_matches_stashed_registration(self):
"""Run the writer-loop's finished-blocks drain against a
pre-populated _pending_d_registrations entry."""
pre-populated _pending_d_registrations entry.
"""
w = _StubWriterWorker.fresh()
w._pending_d_registrations["req-C"] = _registration_data("req-C")
@@ -614,7 +622,8 @@ class TestPushWriterStartLoadKv:
def test_start_load_kv_enqueues_to_writer(self):
"""``start_load_kv`` should hand registrations + finished blocks
to the writer queues without doing matching itself."""
to the writer queues without doing matching itself.
"""
w = _StubWriterWorker.fresh()
# Stub heartbeats to a no-op; tests don't exercise the heartbeat
# path here.
@@ -672,7 +681,8 @@ def test_do_start_push_kv_defers_then_writes_when_handshake_ready():
NIXL op from the writer or the executor callback); once it resolves the
request is re-queued on ``_deferred_push_inbox`` with the wake set; and on
re-drive with the handshake ready the WRITE is issued with a correct
ReqMeta."""
ReqMeta.
"""
w = _StubWriterWorker.fresh()
w._logical_to_kernel_block_ids = lambda x, ratio: x
xfer_calls: list[dict[str, Any]] = []
@@ -712,7 +722,8 @@ def test_do_start_push_kv_defers_then_writes_when_handshake_ready():
def test_do_start_push_kv_drops_request_on_handshake_failure():
"""Handshake raises: the request is dropped (not re-queued, no WRITE) and
the failure is logged. Blocks are reclaimed by the lease/watchdog, matching
the old blocking behaviour."""
the old blocking behaviour.
"""
w = _StubWriterWorker.fresh()
w._logical_to_kernel_block_ids = lambda x, ratio: x
xfer_calls: list[dict[str, Any]] = []
@@ -734,7 +745,8 @@ def test_do_start_push_kv_drops_request_on_handshake_failure():
def test_writer_loop_drains_deferred_push_inbox():
"""The writer loop drains ``_deferred_push_inbox`` and re-drives
``_do_start_push_kv`` for each entry (event-driven, no polling)."""
``_do_start_push_kv`` for each entry (event-driven, no polling).
"""
w = _StubWriterWorker.fresh()
w.nixl_wrapper = MagicMock()
w.nixl_wrapper.get_new_notifs.return_value = {}
@@ -767,7 +779,8 @@ def test_writer_loop_drains_deferred_push_inbox():
def _eviction_worker(engine_ttl: float) -> NixlPushConnectorWorker:
"""A push worker wired to drive the base ``_ensure_handshake`` eviction
path (``_evict_stale_engines`` + ``_cleanup_remote_engine``)."""
path (``_evict_stale_engines`` + ``_cleanup_remote_engine``).
"""
w = _StubWriterWorker.fresh()
w._engine_ttl = engine_ttl
w._engine_last_active = {}
@@ -789,7 +802,8 @@ def _eviction_worker(engine_ttl: float) -> NixlPushConnectorWorker:
def test_active_push_refreshes_engine_last_active():
"""The base ``_ensure_handshake`` refreshes liveness only on a new
handshake, so an active push to an already-connected engine must refresh
``_engine_last_active`` itself or it is reaped mid-stream (S1)."""
``_engine_last_active`` itself or it is reaped mid-stream (S1).
"""
w = _eviction_worker(engine_ttl=3600.0)
# Already-connected D -> _ensure_handshake returns None, WRITE runs inline.
w._remote_agents["decode-engine"] = {(0, 0): "agent-decode"}
@@ -805,7 +819,8 @@ def test_active_push_refreshes_engine_last_active():
def test_stale_engine_evicted_on_push():
"""A push drives ``_ensure_handshake`` -> ``_evict_stale_engines``, so a D
engine silent past its TTL is reaped -- no _remote_agents / NIXL agent leak
across D scale up/down (S1)."""
across D scale up/down (S1).
"""
w = _eviction_worker(engine_ttl=30.0)
w._remote_agents["D-old"] = {(0, 0): "agent-D-old"}
w._engine_last_active["D-old"] = time.perf_counter() - 10_000.0
@@ -822,7 +837,8 @@ def test_stale_engine_evicted_on_push():
def test_cleanup_remote_engine_pops_under_handshake_lock():
"""Regression (X1): eviction must not remove ``_remote_agents`` entries
while another thread is inside the lock's critical section (e.g. the
push writer reading the map to send a registration)."""
push writer reading the map to send a registration).
"""
w = _eviction_worker(engine_ttl=30.0)
w._remote_agents["D-old"] = {(0, 0): "agent-D-old"}
@@ -847,7 +863,8 @@ def test_cleanup_remote_engine_pops_under_handshake_lock():
class TestPushWriterNotifs:
def test_get_new_notifs_processes_forwarded_completion_notif(self):
"""Non-PUSH_REG notifs forwarded by the writer thread are drained
on the engine main thread inside ``_get_new_notifs``."""
on the engine main thread inside ``_get_new_notifs``.
"""
w = _StubWriterWorker.fresh()
# Pretend the writer thread already forwarded a completion notif
# for a request whose KV is being received.
@@ -893,7 +910,8 @@ class TestPushWriterNotifs:
@staticmethod
def _pollable_worker() -> _StubWriterWorker:
"""Stub worker with the extra base-worker state the real
``get_transfer_results`` needs to poll ``_sending_transfers``."""
``get_transfer_results`` needs to poll ``_sending_transfers``.
"""
w = _StubWriterWorker.fresh()
w.transfer_topo = MagicMock()
w.nixl_wrapper = MagicMock()
@@ -935,7 +953,8 @@ class TestPushWriterNotifs:
@pytest.mark.parametrize(("pp_size", "is_hma"), [(1, False), (2, True)])
def test_completed_push_send_waits_for_consumer_notif(self, pp_size, is_hma):
"""P-side sends are completed by consumer notifs / lease expiry,
not by local WRITE-handle completion."""
not by local WRITE-handle completion.
"""
w = self._pollable_worker()
w.pp_size = pp_size
w._is_hma_required = is_hma
@@ -1006,7 +1025,8 @@ class TestPushSchedulerNegative:
def test_request_finished_unfinished_status_does_not_stage(self):
"""If a request is still RUNNING, request_finished must not stash
blocks for the worker (no push needed)."""
blocks for the worker (no push needed).
"""
sched = make_nixl_push_scheduler()
_stub_sw_clipping(sched)
@@ -1023,7 +1043,8 @@ class TestPushSchedulerNegative:
def test_request_finished_empty_blocks_does_not_arm_lease(self):
"""Empty block-id groups should still complete cleanly without
arming the lease/finished maps."""
arming the lease/finished maps.
"""
sched = make_nixl_push_scheduler()
_stub_sw_clipping(sched)
@@ -1038,7 +1059,8 @@ class TestPushSchedulerNegative:
def test_update_connector_output_unknown_request_is_noop(self):
"""Idempotent cleanup: clearing a request that was never staged
must not raise or mutate other state."""
must not raise or mutate other state.
"""
sched = make_nixl_push_scheduler()
_stub_sw_clipping(sched)
@@ -1071,7 +1093,8 @@ class TestPushWriterNegative:
def test_pop_matching_registration_no_match_when_base_ids_differ(self):
"""A registration whose base id (after stripping the random suffix)
does NOT match the lookup request_id must not be popped."""
does NOT match the lookup request_id must not be popped.
"""
w = _StubWriterWorker.fresh()
# Two unrelated requests: different base UUIDs, so stripping the
# trailing ``-<8 hex>`` suffix still yields different base ids.
@@ -1087,7 +1110,8 @@ class TestPushWriterNegative:
def test_handle_push_reg_with_non_dict_payload_is_dropped(self, caplog):
"""msgpack-encoded non-dict payload (e.g. a list) should be
dropped without raising."""
dropped without raising.
"""
caplog.set_level(
logging.CRITICAL,
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
@@ -1115,7 +1139,8 @@ class TestPushWriterNegative:
def test_handle_push_reg_idempotent_for_same_request_id(self):
"""Receiving the same PUSH_REG twice (e.g. P retries after a
flake) keeps the entry staged exactly once and never fires."""
flake) keeps the entry staged exactly once and never fires.
"""
w = _StubWriterWorker.fresh()
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(
_registration_data("req-dup")
@@ -1130,7 +1155,8 @@ class TestPushWriterNegative:
"""``get_transfer_results`` must enqueue every completed request
in ``done_sending`` so the writer can drop stale matching state.
Unlike the happy-path test, this verifies the *cardinality*: N
completed requests -> N evictions, in order."""
completed requests -> N evictions, in order.
"""
w = _StubWriterWorker.fresh()
with patch.object(
NixlPushConnectorWorker.__mro__[1],
@@ -1153,7 +1179,8 @@ class TestPushWriterNegative:
def test_empty_transfer_results_do_not_enqueue_eviction(self):
"""If there's nothing newly done, no eviction should be enqueued.
The wake event IS still set because ``get_finished`` always wakes
the writer to drain notifs."""
the writer to drain notifs.
"""
w = _StubWriterWorker.fresh()
with patch.object(
NixlPushConnectorWorker.__mro__[1],
@@ -1194,7 +1221,8 @@ class TestPushWriterNegative:
def test_get_new_notifs_unknown_request_is_logged_and_skipped(self, caplog):
"""A completion notif for a request the worker doesn't know
about should be logged but not crash."""
about should be logged but not crash.
"""
caplog.set_level(
logging.CRITICAL,
logger=("vllm.distributed.kv_transfer.kv_connector.v1.nixl.push_worker"),
@@ -1226,7 +1254,8 @@ class TestPushWriterNegative:
def test_get_new_notifs_extends_lease_on_heartbeat(self):
"""``HB:`` notifs forwarded by the writer thread must extend the
leases of tracked P-side requests on the engine main thread, and
ignore request IDs that aren't being tracked."""
ignore request IDs that aren't being tracked.
"""
w = _StubWriterWorker.fresh()
w.transfer_topo = MagicMock()
# _handle_heartbeat reads ``self._lease_extension`` (set in the
@@ -1262,11 +1291,13 @@ class TestPushWriterNegative:
class TestPushPipelineParallel:
"""PP-sharded producer: per-stage completion counting, pp_size plumbing,
and remote-region slicing."""
and remote-region slicing.
"""
def test_completion_waits_for_one_notif_per_pp_stage(self):
"""Each PP stage WRITEs its own layers and sends one notif; D must
collect pp_size notifs before reporting the recv done."""
collect pp_size notifs before reporting the recv done.
"""
w = _StubWriterWorker.fresh()
w.transfer_topo = MagicMock()
request_id = "req-pp-2"
@@ -1287,7 +1318,8 @@ class TestPushPipelineParallel:
def test_req_meta_reads_pp_size_from_kv_transfer_params(self):
"""D learns the producer's pp_size from kv_transfer_params (forwarded
by the proxy) and defaults to 1 when absent."""
by the proxy) and defaults to 1 when absent.
"""
metadata = NixlConnectorMetadata()
params = {
"remote_block_ids": ([0],),
@@ -1310,7 +1342,8 @@ class TestPushPipelineParallel:
this worker holds only a contiguous layer slice; add_remote_agent
trims the remote region list to [offset : offset + num_local_regions]
before building descriptors. We stop right after the slice via a
sentinel on the next collaborator call."""
sentinel on the next collaborator call.
"""
block_len = 4096 * 16
w = _StubWriterWorker.fresh() # seeds writer-thread state for teardown
w.pp_size = 2
@@ -1352,7 +1385,8 @@ class TestPushWriterMlaReplication:
"""MLA latent KV is replicated across D's TP ranks, so when D_TP > P_TP
(``tp_ratio < 0``) the producer must *WRITE* the latent into every D rank
it handshook -- not write one and merely notify the rest, which would
leave the un-written ranks decoding against stale KV."""
leave the un-written ranks decoding against stale KV.
"""
@staticmethod
def _mla_worker_writing_to(d_ranks):
@@ -1577,7 +1611,8 @@ class TestPushPrefixCaching:
def test_partial_prefix_hit_end_trims_producer_blocks(self):
"""D registered only its 2 uncomputed suffix blocks; P finished the
full 5-block sequence. P must WRITE its LAST 2 blocks into D's slots."""
full 5-block sequence. P must WRITE its LAST 2 blocks into D's slots.
"""
w, _ = self._worker_driving_xfer()
reg = _registration_data("req-pc", local_block_ids=([500, 501],))
@@ -171,7 +171,8 @@ def test_gpu_memory_nixl_hma(model_name, sw_size):
@pytest.mark.parametrize("model_name", ["google/gemma-3-1b-it"])
def test_gpu_memory_no_nixl_baseline(model_name):
"""Same workload without NixlConnector. Comparing driver-level memory
between this and test_gpu_memory_nixl_hma isolates UCX/NIXL impact."""
between this and test_gpu_memory_nixl_hma isolates UCX/NIXL impact.
"""
from vllm import LLM, SamplingParams
from vllm.distributed.parallel_state import cleanup_dist_env_and_memory
@@ -213,7 +213,8 @@ def _multi_connector_config(swa_enabled: bool = False):
def test_nixl_wins_load_over_cpu_offload():
"""When NixlConnector (index 0) has matched tokens from a remote prefill, it should
win the load: Nixl metadata tracks the recv while CPU offload metadata has no load
scheduled."""
scheduled.
"""
vllm_config, kv_cache_config = _multi_connector_config()
scheduler = create_scheduler(vllm_config, kv_cache_config=kv_cache_config)
mc = scheduler.connector
@@ -250,7 +251,8 @@ def test_nixl_wins_load_over_cpu_offload():
@patch(NIXL_WRAPPER_PATCH, FakeNixlWrapper)
def test_cpu_offload_wins_when_nixl_has_no_match():
"""When NixlConnector returns 0 matched tokens and SimpleCPUOffloadConnector has a
CPU cache hit, the CPU offload connector (index 1) wins the load."""
CPU cache hit, the CPU offload connector (index 1) wins the load.
"""
vllm_config, kv_cache_config = _multi_connector_config()
scheduler = create_scheduler(vllm_config, kv_cache_config=kv_cache_config)
mc = scheduler.connector
@@ -309,7 +311,8 @@ def test_cpu_offload_wins_when_nixl_has_no_match():
def test_request_finished_no_async_save(swa_enabled: bool):
"""A normal request (no P/D) produces no async save from either connector.
MultiConnector returns (False, None) via both request_finished and
request_finished_all_groups, and cleans up _requests_to_connector."""
request_finished_all_groups, and cleans up _requests_to_connector.
"""
from vllm.v1.request import RequestStatus
vllm_config, kv_cache_config = _multi_connector_config(swa_enabled=swa_enabled)
@@ -76,7 +76,7 @@ _EVENT_DRAIN_TIMEOUT = 60
class MockSubscriber:
"""Helper class to receive and verify published events"""
"""Helper class to receive and verify published events."""
def __init__(
self,
@@ -121,7 +121,7 @@ class MockSubscriber:
return cpu_stored_events
def close(self):
"""Clean up resources"""
"""Clean up resources."""
self.sub.close()
@@ -261,9 +261,7 @@ def test_cpu_offloading(
cpu_block_size: int | None,
uses_hma: bool,
) -> None:
"""
Tests OffloadingConnector with CPUOffloadingSpec.
"""
"""Tests OffloadingConnector with CPUOffloadingSpec."""
# configure OffloadingConnector (spec_name=CPUOffloadingSpec by default)
extra_config: dict = {"cpu_bytes_to_use": 500 << 20}
if cpu_block_size is not None:
@@ -323,7 +321,8 @@ def test_cpu_offloading(
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
def test_cpu_offloading_metrics() -> None:
"""Verify that offloading Prometheus metrics (new flat and deprecated
labeled) are emitted after stores and loads."""
labeled) are emitted after stores and loads.
"""
extra_config: dict = {
"cpu_bytes_to_use": 500 << 20,
"block_size": CPU_BLOCK_SIZES,
@@ -512,7 +511,8 @@ def test_tiering_offloading() -> None:
def test_fs_tiering_offloading(tmp_path) -> None:
"""Tests OffloadingConnector with TieringOffloadingSpec
+ fs secondary tier."""
+ fs secondary tier.
"""
extra_config: dict = {
"cpu_bytes_to_use": 1 << 30,
"block_size": CPU_BLOCK_SIZES,
@@ -20,7 +20,6 @@ pytestmark = pytest.mark.cpu_test
def test_basic_lifecycle():
"""Test lifecycle of a Remote Decode request."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -117,7 +116,6 @@ def test_basic_lifecycle():
def test_short_prompt_lifecycle():
"""Test lifecycle of a Remote Decode request with short prompt."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -164,7 +162,6 @@ def test_short_prompt_lifecycle():
def test_prefix_cache_lifecycle():
"""Test that remote decode params still work with a prefix cache hit."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -224,7 +221,6 @@ def test_prefix_cache_lifecycle():
def test_abort_during_kv_transfer():
"""Test aborting request does not release blocks for remote decode."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -30,7 +30,6 @@ def _num_waiting_requests(scheduler) -> int:
def test_basic_lifecycle():
"""Test lifecycle of a remote prefill."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -151,7 +150,6 @@ def test_basic_lifecycle():
def test_interleaved_lifecycle():
"""Test Remote Prefills Work Well With Other Requests."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -249,13 +247,11 @@ def test_interleaved_lifecycle():
def test_no_spurious_prefix_caching():
"""
With P/D, blocks can be allocated but uncomputed for
"""With P/D, blocks can be allocated but uncomputed for
multiple engine steps. This test confirms that we do
not accidentally have cache hits against uncomputed
blocks.
"""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -320,7 +316,6 @@ def test_no_spurious_prefix_caching():
def test_full_block_prompt():
"""Test that we handle a prompt that is the full block size."""
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
@@ -394,11 +389,9 @@ def test_full_block_prompt():
def test_cannot_schedule_after_recv():
"""
Test that we can handle no schedule after recv due to not
"""Test that we can handle no schedule after recv due to not
enough remaining KV blocks.
"""
# NOTE: the KVCacheManager will use 1 null block.
# So there are 5 total working blocks.
TOTAL_NUM_BLOCKS = 6
@@ -501,11 +494,9 @@ def test_cannot_schedule_after_recv():
def test_cannot_recv():
"""
Test that we can handle no schedule KV block transfer due to not
"""Test that we can handle no schedule KV block transfer due to not
enough remaining KV blocks.
"""
# NOTE: the KVCacheManager will use 1 null block.
# So there are 5 total working blocks.
TOTAL_NUM_BLOCKS = 6
@@ -713,7 +704,8 @@ def test_async_load_reserves_blocks_for_inflight():
def test_async_loads_both_admitted_when_pool_fits():
"""Sanity: with a pool large enough, the reservation gate admits both async
loads (it is not over-conservative)."""
loads (it is not over-conservative).
"""
vllm_config = create_vllm_config()
BLOCK_SIZE = vllm_config.cache_config.block_size
scheduler = create_scheduler(vllm_config, num_blocks=64)
@@ -129,7 +129,8 @@ def _make_ring_kv_cache_config(num_blocks: int = 16) -> KVCacheConfig:
def test_ring_scratch_group_is_accepted_and_never_offloaded() -> None:
"""The ring group's capacity is not a token granularity, it holds no
hashed blocks, and it never participates in CPU hits."""
hashed blocks, and it never participates in CPU hits.
"""
vllm_config = create_vllm_config(
kv_connector="SimpleCPUOffloadConnector",
kv_role="kv_both",
@@ -235,7 +235,8 @@ class TestMambaPlanSplitHandles:
def test_hetero_block_size_splits(self):
"""With a block-size ratio, single-source FA sub-block descs pass
through whole; SSM descs are unexpanded and split per source."""
through whole; SSM descs are unexpanded and split per source.
"""
plan = TPMapping(
source_ranks_per_group=((0,), (0, 1)),
all_source_ranks=(0, 1),
@@ -270,7 +271,8 @@ class TestMambaPlanSplitHandles:
def test_hetero_block_size_head_sharded_asserts(self):
"""Head-sharded FA reads (multiple FA sources) are incompatible with
a block-size mismatch and must fail loudly."""
a block-size mismatch and must fail loudly.
"""
plan = TPMapping(
source_ranks_per_group=((0, 1), (0, 1)),
all_source_ranks=(0, 1),
-1
View File
@@ -261,7 +261,6 @@ def create_model_runner_output(
kv_connector_worker_meta: KVConnectorWorkerMetadata | None = None,
) -> ModelRunnerOutput:
"""Make dummy model runner output for testing."""
# Make request data.
req_ids = [req.request_id for req in reqs]
req_id_to_index = {req_id: idx for idx, req_id in enumerate(req_ids)}