[CI] Ignore ruff D209, rejoin the docstrings it split, and silence incompatible-rule warnings (#57212)
Signed-off-by: Harry Mellor <19981378+hmellor@users.noreply.github.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
1085b64425
commit
651a88c09a
@@ -80,8 +80,7 @@ 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,8 +863,7 @@ 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
|
||||
|
||||
@@ -872,8 +871,7 @@ 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,8 +117,7 @@ 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
|
||||
@@ -188,8 +187,7 @@ 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,8 +1583,7 @@ _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]
|
||||
|
||||
@@ -2035,8 +2034,7 @@ 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,
|
||||
@@ -2106,8 +2104,7 @@ 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,
|
||||
@@ -2157,8 +2154,7 @@ 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
|
||||
@@ -2387,8 +2383,7 @@ 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
|
||||
@@ -2934,8 +2929,7 @@ 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
|
||||
@@ -3029,8 +3023,7 @@ 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
|
||||
@@ -3572,8 +3565,7 @@ 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
|
||||
@@ -3625,8 +3617,7 @@ 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
|
||||
@@ -4263,8 +4254,7 @@ 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,
|
||||
@@ -4503,8 +4493,7 @@ 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
|
||||
@@ -4518,14 +4507,12 @@ 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(
|
||||
@@ -4582,8 +4569,7 @@ 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
|
||||
@@ -4712,8 +4698,7 @@ 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(
|
||||
@@ -4726,8 +4711,7 @@ 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,8 +80,7 @@ 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
|
||||
|
||||
@@ -148,8 +148,7 @@ 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,
|
||||
)
|
||||
@@ -195,8 +194,7 @@ 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,
|
||||
)
|
||||
@@ -276,8 +274,7 @@ 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,
|
||||
)
|
||||
@@ -313,8 +310,7 @@ 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,
|
||||
)
|
||||
@@ -359,8 +355,7 @@ 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]],
|
||||
@@ -388,8 +383,7 @@ 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,
|
||||
)
|
||||
@@ -463,8 +457,7 @@ 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)
|
||||
@@ -511,8 +504,7 @@ 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,
|
||||
)
|
||||
@@ -593,8 +585,7 @@ 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,
|
||||
)
|
||||
@@ -628,8 +619,7 @@ 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,
|
||||
)
|
||||
@@ -682,8 +672,7 @@ 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,
|
||||
)
|
||||
@@ -719,8 +708,7 @@ 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={
|
||||
@@ -762,8 +750,7 @@ 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,
|
||||
)
|
||||
@@ -804,8 +791,7 @@ 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,
|
||||
)
|
||||
@@ -840,8 +826,7 @@ 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,
|
||||
)
|
||||
@@ -886,8 +871,7 @@ 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,
|
||||
)
|
||||
@@ -959,8 +943,7 @@ _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
|
||||
@@ -996,8 +979,7 @@ 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
|
||||
|
||||
@@ -1050,8 +1032,7 @@ 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
|
||||
|
||||
@@ -19,15 +19,13 @@ 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",
|
||||
@@ -107,8 +105,7 @@ 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 = (
|
||||
@@ -134,8 +131,7 @@ 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)
|
||||
@@ -143,8 +139,7 @@ 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)
|
||||
|
||||
@@ -167,8 +162,7 @@ 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)
|
||||
|
||||
|
||||
@@ -50,8 +50,7 @@ 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")
|
||||
@@ -72,8 +71,7 @@ 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,
|
||||
@@ -106,8 +104,7 @@ 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,8 +176,7 @@ 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()
|
||||
@@ -200,8 +199,7 @@ 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"):
|
||||
@@ -216,8 +214,7 @@ 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()
|
||||
|
||||
@@ -131,8 +131,7 @@ 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,8 +237,7 @@ 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"),
|
||||
|
||||
@@ -212,8 +212,7 @@ 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)
|
||||
|
||||
@@ -199,8 +199,7 @@ 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,8 +77,7 @@ 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,
|
||||
@@ -693,8 +692,7 @@ 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()
|
||||
@@ -705,8 +703,7 @@ 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,8 +33,7 @@ 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(
|
||||
@@ -144,8 +143,7 @@ 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
|
||||
@@ -192,8 +190,7 @@ 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)),
|
||||
@@ -217,8 +214,7 @@ 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)),
|
||||
@@ -238,8 +234,7 @@ 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)),
|
||||
@@ -280,8 +275,7 @@ 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)]
|
||||
@@ -327,8 +321,7 @@ 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)]
|
||||
@@ -358,8 +351,7 @@ 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)
|
||||
@@ -393,8 +385,7 @@ 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)]
|
||||
@@ -407,8 +398,7 @@ 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)
|
||||
@@ -422,8 +412,7 @@ 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)]
|
||||
@@ -431,8 +420,7 @@ 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
|
||||
@@ -442,8 +430,7 @@ 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
|
||||
@@ -452,8 +439,7 @@ 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
|
||||
@@ -464,8 +450,7 @@ 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)]
|
||||
@@ -503,8 +488,7 @@ 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)),
|
||||
@@ -525,8 +509,7 @@ 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)
|
||||
@@ -567,8 +550,7 @@ 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,8 +1,7 @@
|
||||
# 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
|
||||
@@ -283,8 +282,7 @@ 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(
|
||||
@@ -352,8 +350,7 @@ 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])
|
||||
@@ -386,8 +383,7 @@ 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,
|
||||
@@ -466,8 +462,7 @@ 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,
|
||||
@@ -538,8 +533,7 @@ 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,
|
||||
@@ -810,8 +804,7 @@ 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,8 +536,7 @@ 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(),
|
||||
@@ -713,8 +712,7 @@ 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,8 +432,7 @@ 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"
|
||||
@@ -574,8 +573,7 @@ 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")
|
||||
|
||||
@@ -591,8 +589,7 @@ 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
|
||||
|
||||
|
||||
@@ -1014,8 +1011,7 @@ 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,
|
||||
@@ -1143,8 +1139,7 @@ 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,
|
||||
@@ -1205,8 +1200,7 @@ 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)
|
||||
@@ -1234,8 +1228,7 @@ 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)
|
||||
@@ -1275,8 +1268,7 @@ 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)
|
||||
|
||||
@@ -1604,8 +1596,7 @@ 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]
|
||||
@@ -2115,8 +2106,7 @@ 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(
|
||||
@@ -2330,8 +2320,7 @@ 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)
|
||||
@@ -3006,8 +2995,7 @@ 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]
|
||||
@@ -3032,8 +3020,7 @@ 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()
|
||||
@@ -3823,8 +3810,7 @@ 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,
|
||||
@@ -3981,8 +3967,7 @@ 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)
|
||||
@@ -4004,8 +3989,7 @@ 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)
|
||||
@@ -4401,8 +4385,7 @@ 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,
|
||||
{
|
||||
@@ -4510,8 +4493,7 @@ 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)
|
||||
@@ -4560,8 +4542,7 @@ 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),
|
||||
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)
|
||||
@@ -4750,8 +4731,7 @@ 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])
|
||||
|
||||
|
||||
@@ -692,8 +692,7 @@ 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()
|
||||
@@ -747,8 +746,7 @@ 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.
|
||||
@@ -766,8 +764,7 @@ 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,8 +777,7 @@ 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
|
||||
)
|
||||
@@ -815,8 +811,7 @@ 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
|
||||
@@ -825,8 +820,7 @@ 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]
|
||||
@@ -837,8 +831,7 @@ 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,8 +110,7 @@ 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)
|
||||
@@ -126,8 +125,7 @@ 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):
|
||||
|
||||
@@ -555,8 +555,7 @@ 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],
|
||||
|
||||
@@ -318,8 +318,7 @@ 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())
|
||||
@@ -3146,8 +3145,7 @@ 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(
|
||||
|
||||
@@ -281,8 +281,7 @@ 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,
|
||||
)
|
||||
@@ -336,8 +335,7 @@ 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,
|
||||
)
|
||||
@@ -442,8 +440,7 @@ 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,
|
||||
)
|
||||
@@ -842,8 +839,7 @@ 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,
|
||||
)
|
||||
@@ -1159,8 +1155,7 @@ 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(
|
||||
@@ -1244,8 +1239,7 @@ 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
|
||||
@@ -1276,8 +1270,7 @@ 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(
|
||||
@@ -1316,8 +1309,7 @@ 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 (
|
||||
@@ -1348,8 +1340,7 @@ 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 (
|
||||
@@ -1392,8 +1383,7 @@ 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,
|
||||
)
|
||||
@@ -1474,8 +1464,7 @@ 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).
|
||||
@@ -1503,8 +1492,7 @@ 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
|
||||
@@ -1964,8 +1952,7 @@ 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]
|
||||
@@ -1992,8 +1979,7 @@ 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]
|
||||
@@ -2010,8 +1996,7 @@ 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,
|
||||
@@ -2151,8 +2136,7 @@ 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
|
||||
@@ -2253,8 +2237,7 @@ 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,8 +24,7 @@ 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] = {}
|
||||
@@ -594,8 +593,7 @@ 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 = []
|
||||
@@ -633,8 +631,7 @@ 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,
|
||||
)
|
||||
@@ -701,8 +698,7 @@ 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
|
||||
@@ -896,8 +892,7 @@ 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
|
||||
)
|
||||
@@ -916,8 +911,7 @@ 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,
|
||||
@@ -966,8 +960,7 @@ 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,
|
||||
@@ -981,8 +974,7 @@ 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
|
||||
)
|
||||
@@ -1166,8 +1158,7 @@ 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.
|
||||
@@ -1301,8 +1292,7 @@ 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,8 +115,7 @@ 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
|
||||
|
||||
|
||||
@@ -174,8 +173,7 @@ 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)
|
||||
|
||||
@@ -194,8 +192,7 @@ 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)
|
||||
|
||||
@@ -290,8 +287,7 @@ 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(
|
||||
@@ -332,8 +328,7 @@ 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:
|
||||
@@ -439,8 +434,7 @@ 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()
|
||||
@@ -485,8 +479,7 @@ 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")
|
||||
@@ -596,8 +589,7 @@ 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")
|
||||
|
||||
@@ -622,8 +614,7 @@ 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.
|
||||
@@ -681,8 +672,7 @@ 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]] = []
|
||||
@@ -722,8 +712,7 @@ 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]] = []
|
||||
@@ -745,8 +734,7 @@ 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 = {}
|
||||
@@ -779,8 +767,7 @@ 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 = {}
|
||||
@@ -802,8 +789,7 @@ 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"}
|
||||
@@ -819,8 +805,7 @@ 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
|
||||
@@ -837,8 +822,7 @@ 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"}
|
||||
|
||||
@@ -863,8 +847,7 @@ 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.
|
||||
@@ -910,8 +893,7 @@ 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()
|
||||
@@ -953,8 +935,7 @@ 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
|
||||
@@ -1025,8 +1006,7 @@ 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)
|
||||
|
||||
@@ -1043,8 +1023,7 @@ 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)
|
||||
|
||||
@@ -1059,8 +1038,7 @@ 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)
|
||||
|
||||
@@ -1093,8 +1071,7 @@ 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.
|
||||
@@ -1110,8 +1087,7 @@ 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"),
|
||||
@@ -1139,8 +1115,7 @@ 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")
|
||||
@@ -1155,8 +1130,7 @@ 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],
|
||||
@@ -1179,8 +1153,7 @@ 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],
|
||||
@@ -1221,8 +1194,7 @@ 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"),
|
||||
@@ -1254,8 +1226,7 @@ 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
|
||||
@@ -1291,13 +1262,11 @@ 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"
|
||||
@@ -1318,8 +1287,7 @@ 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],),
|
||||
@@ -1342,8 +1310,7 @@ 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
|
||||
@@ -1385,8 +1352,7 @@ 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):
|
||||
@@ -1611,8 +1577,7 @@ 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,8 +171,7 @@ 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,8 +213,7 @@ 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
|
||||
@@ -251,8 +250,7 @@ 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
|
||||
@@ -311,8 +309,7 @@ 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)
|
||||
|
||||
@@ -321,8 +321,7 @@ 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,
|
||||
@@ -511,8 +510,7 @@ 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,
|
||||
|
||||
@@ -704,8 +704,7 @@ 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,8 +129,7 @@ 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,8 +235,7 @@ 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),
|
||||
@@ -271,8 +270,7 @@ 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),
|
||||
|
||||
Reference in New Issue
Block a user