[Feat][Model] Support encoder-side SWA-bounded replay for DeepSeek-V4.1-Flash (#56227)

Signed-off-by: Yifan Qiao <yifanqiao@inferact.ai>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Woosuk Kwon <woosuk@inferact.ai>
This commit is contained in:
Yifan Qiao
2026-09-18 15:01:24 -07:00
committed by GitHub
co-authored by Claude Fable 5.1 Woosuk Kwon
parent 6aab78f477
commit 1dc2d854c1
30 changed files with 1067 additions and 38 deletions
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""SWA bounded replay in DeepseekV41ModelState: the batch's replay starts reach
the sliding-window builders, and the replayed tokens' slots are padded in the
prefix-cacheable groups only."""
from dataclasses import replace
from types import SimpleNamespace
from unittest.mock import MagicMock
import numpy as np
import pytest
import torch
from vllm.config import CUDAGraphMode
from vllm.models.deepseek_v41.nvidia.model_state import DeepseekV41ModelState
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadataBuilder
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA")
DEVICE = torch.device("cuda")
WINDOW = 4
# Group 0 is prefix-cacheable (compressed KV), group 1 is the replayed window.
KV_CACHE_CONFIG = SimpleNamespace(
kv_cache_groups=[
SimpleNamespace(
kv_cache_spec=SimpleNamespace(prefix_cacheable=True, prefix_replay_tokens=0)
),
SimpleNamespace(
kv_cache_spec=SimpleNamespace(
prefix_cacheable=False, prefix_replay_tokens=WINDOW
)
),
]
)
@pytest.fixture
def state(monkeypatch):
cfg = MagicMock()
cfg.model_config.enable_prompt_embeds = False
cfg.model_config.uses_mrope = False
cfg.model_config.is_multimodal_model = False
cfg.scheduler_config.max_num_seqs = 8
cfg.scheduler_config.max_num_batched_tokens = 64
seen: dict = {}
def prepare_attn(self, input_batch, cg_mode, block_tables, slot_mappings, *a, **kw):
seen["slot_mappings"] = slot_mappings.clone()
seen["extra"] = kw["model_specific_attn_metadata"]
return {}
monkeypatch.setattr(DefaultModelState, "prepare_attn", prepare_attn)
state = DeepseekV41ModelState(
cfg, SimpleNamespace(token_lookback_depth=0), None, DEVICE
)
state.seen = seen # type: ignore[attr-defined]
return state
def _batch(query_lens, seq_lens, idx_mapping, is_prefilling):
num_reqs, num_tokens = len(query_lens), sum(query_lens)
batch = InputBatch.make_dummy(num_reqs, num_tokens, InputBuffers(8, 64, DEVICE))
return replace(
batch,
query_start_loc=torch.tensor(
[0, *np.cumsum(query_lens)], dtype=torch.int32, device=DEVICE
),
idx_mapping_np=np.array(idx_mapping, dtype=np.intp),
is_prefilling_np=np.array(is_prefilling, dtype=np.bool_),
positions=torch.cat(
[torch.arange(s - q, s) for q, s in zip(query_lens, seq_lens)]
).to(DEVICE),
)
def _prepare(state, batch):
slot_mappings = torch.arange(2 * batch.num_tokens, device=DEVICE).view(2, -1)
state.prepare_attn(
batch, CUDAGraphMode.NONE, (), slot_mappings, [], KV_CACHE_CONFIG
)
swa_builder = MagicMock(spec=DeepseekSparseSWAMetadataBuilder)
extra = state.seen["extra"]
replay_start = extra.get_extra_attn_kwargs(swa_builder, batch.num_reqs)[
"replay_start"
]
assert extra.get_extra_attn_kwargs(MagicMock(), batch.num_reqs) == {}
return replay_start.tolist(), state.seen["slot_mappings"]
def test_replayed_tokens_write_only_the_window_group(state):
# Request state 3 resumes a hit at 16: positions 16..19 are replayed.
state.add_request(3, SimpleNamespace(replay_start=16))
state.add_request(1, SimpleNamespace(replay_start=0))
batch = _batch([6, 2], [22, 2], idx_mapping=[3, 1], is_prefilling=[True, True])
replay_start, slots = _prepare(state, batch)
assert replay_start == [16, 0]
padded = [PAD_SLOT_ID] * WINDOW + [4, 5, 6, 7]
assert slots[0].tolist() == padded # compressed KV keeps its cached rows
assert slots[1].tolist() == list(range(8, 16)) # the window is rebuilt
def test_only_prefills_carry_a_replay_start(state):
state.add_request(0, SimpleNamespace(replay_start=16))
# The same request, decoding: its rows sit above the hit.
batch = _batch([1], [40], idx_mapping=[0], is_prefilling=[False])
replay_start, slots = _prepare(state, batch)
assert replay_start == [0]
assert slots.tolist() == [[0], [1]]
@@ -11,6 +11,8 @@ at ``max(pos - (window - 1) - max(left - (window - 1), 0), 0)`` and ends at
``pos + right`` (inclusive).
"""
import inspect
import pytest
import torch
from typing_extensions import TypedDict
@@ -57,10 +59,13 @@ def ref_left_right(
return lefts, rights
def ref_swa_bounds(pos: int, window: int, left: int, right: int) -> tuple[int, int]:
"""Reference [start, end) window bounds for one query token."""
def ref_swa_bounds(
pos: int, window: int, left: int, right: int, replay_start: int = 0
) -> tuple[int, int]:
"""Reference [start, end) window bounds for one query token. Under SWA
bounded replay no window KV exists below ``replay_start``."""
left_add = max(left - (window - 1), 0)
start = max(pos - (window - 1) - left_add, 0)
start = max(pos - (window - 1) - left_add, 0, replay_start)
return start, pos + right + 1
@@ -97,12 +102,14 @@ def ref_swa_slot_rows(
window: int,
max_image_tokens: int,
width: int,
replay_starts: list[int] | None = None,
) -> tuple[list[list[int]], list[int]]:
"""Reference paged slot-id rows and lens for every token in the batch."""
block_table_cpu = block_table.cpu()
lefts, rights = ref_left_right(
seq_lens, query_lens, spans_per_req, max_image_tokens
)
replay_starts = replay_starts or [0] * len(seq_lens)
rows: list[list[int]] = []
lens: list[int] = []
token = 0
@@ -110,7 +117,9 @@ def ref_swa_slot_rows(
prefix_len = seq_len - query_len
for i in range(query_len):
pos = prefix_len + i
start, end = ref_swa_bounds(pos, window, lefts[token], rights[token])
start, end = ref_swa_bounds(
pos, window, lefts[token], rights[token], replay_starts[req]
)
row = []
for p in range(start, end):
blk = int(block_table_cpu[req, p // BLOCK_SIZE])
@@ -139,6 +148,7 @@ def run_swa_kernel(
swa_indices = torch.zeros(num_tokens, 1, width, dtype=torch.int32, device=device)
swa_lens = torch.zeros(num_tokens, dtype=torch.int32, device=device)
is_valid = slot_mapping >= 0
replay_start_t = torch.zeros(len(seq_lens), dtype=torch.int32, device=device)
if with_image:
lefts, rights = ref_left_right(
@@ -164,6 +174,7 @@ def run_swa_kernel(
block_table,
block_table.stride(0),
BLOCK_SIZE,
replay_start_t,
token_offset=0,
HAS_IMAGE=with_image,
TRITON_BLOCK_SIZE=1024,
@@ -289,18 +300,25 @@ def combine_case(
query_lens: list[int],
spans: list[list[tuple[int, int]]],
with_image: bool,
replay_starts: list[int] | None = None,
combine_fn=combine_topk_swa_indices,
):
"""Run combine_topk_swa_indices and return (indices, lens, expected)."""
device = torch.device("cuda")
num_reqs = len(seq_lens)
replay_starts = replay_starts or [0] * num_reqs
query_start_loc = torch.zeros(num_reqs + 1, dtype=torch.int32, device=device)
query_start_loc[1:] = torch.tensor(
query_lens, dtype=torch.int32, device=device
).cumsum(0)
num_tokens = int(query_start_loc[-1])
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
# The builder's gather covers only the context above the replay start.
gather_lens = torch.tensor(
[q + min(s - q, WINDOW - 1) for s, q in zip(seq_lens, query_lens)],
[
q + min(max(s - q - r, 0), WINDOW - 1)
for s, q, r in zip(seq_lens, query_lens, replay_starts)
],
dtype=torch.int32,
device=device,
)
@@ -319,7 +337,14 @@ def combine_case(
else:
left_t = right_t = None
combined_indices, combined_lens = combine_topk_swa_indices(
# V4.1's combine has no image windows (causal SWA only).
has_image = "left_visible" in inspect.signature(combine_fn).parameters
image_kwargs = (
dict(left_visible=left_t, right_visible=right_t, max_image_tokens=MAX_IMG)
if has_image
else {}
)
combined_indices, combined_lens = combine_fn(
topk_indices,
query_start_loc,
seq_lens_t,
@@ -329,9 +354,7 @@ def combine_case(
topk,
M,
N,
left_visible=left_t,
right_visible=right_t,
max_image_tokens=MAX_IMG,
**image_kwargs,
)
# Reference rows.
@@ -342,7 +365,7 @@ def combine_case(
MAX_IMG,
)
topk_cpu = topk_indices.cpu()
width = WINDOW + MAX_IMG
width = WINDOW + (MAX_IMG if has_image else 0)
combined_topk = (topk + width + 127) // 128 * 128
rows = []
lens = []
@@ -354,6 +377,8 @@ def combine_case(
pos = prefix_len + i
topk_len = min((pos + 1) // compress_ratio, topk)
start, end = ref_swa_bounds(pos, WINDOW, lefts[token], rights[token])
# The window never reaches below the gathered buffer.
start = max(start, gather_start)
swa_len = end - start
row = [-1] * combined_topk
for j in range(topk_len):
@@ -388,6 +413,31 @@ def test_combine_topk_swa_with_image_spans(cfg):
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
def test_v41_combine_topk_swa_stops_at_replay_start(cfg):
"""SWA bounded replay: the gathered buffer starts at replay_start, so the
window never indexes below it."""
from vllm.models.deepseek_v41.common.ops.cache_utils import (
combine_topk_swa_indices as combine_v41,
)
# Request 0 replays [16, 40): the windows of its first rows would
# otherwise reach below 16.
indices, lens, rows, exp_lens = combine_case(
cfg["compress_ratio"],
cfg["topk"],
seq_lens=[40, 12],
query_lens=[24, 12],
spans=[[], []],
with_image=False,
replay_starts=[16, 0],
combine_fn=combine_v41,
)
assert lens.cpu().tolist() == exp_lens
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
def test_combine_topk_swa_without_image_unchanged(cfg):
@@ -472,6 +522,7 @@ def make_builder(
DeepseekSparseSWAMetadataBuilder
] = DeepseekSparseSWAMetadataBuilder,
mm_prefix_clamp_sliding_window: bool = True,
bounded_replay: bool = False,
) -> DeepseekSparseSWAMetadataBuilder:
overrides: dict = {"sliding_window": window}
if vision:
@@ -498,6 +549,7 @@ def make_builder(
sliding_window=window,
cache_dtype_str="auto",
model_version="deepseek_v4",
bounded_replay=bounded_replay,
)
return builder_cls(
kv_cache_spec=spec,
@@ -512,11 +564,17 @@ def build_metadata(
seq_lens: list[int],
query_lens: list[int],
mm_req_doc_ranges: dict[int, list[tuple[int, int]]] | None,
replay_starts: list[int] | None = None,
):
device = torch.device("cuda")
query_start_loc, seq_lens_t, _, slot_mapping, block_table = make_batch(
seq_lens, query_lens, device
)
replay_start = (
None
if replay_starts is None
else torch.tensor(replay_starts, dtype=torch.int32, device=device)
)
return builder.build(
0,
CommonAttentionMetadata(
@@ -533,6 +591,7 @@ def build_metadata(
causal=True,
mm_req_doc_ranges=mm_req_doc_ranges,
),
replay_start=replay_start,
)
@@ -653,3 +712,108 @@ def test_v41_image_prefill_uses_causal_swa(compress_ratio, query_len):
assert absolute_keys.tolist() == list(range(lo, hi))
assert paged_lens[token] == hi - lo
assert paged_indices[token, 0, : hi - lo].tolist() == list(range(lo, hi))
# SWA bounded replay: every prefill index path clamps the window at replay_start.
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_replay_start_bounds_prefill_window_and_gather():
"""Paged-direct prefill indices stop at replay_start and the FlashMLA
gather only covers the context the request may see."""
seq_lens = [40, 12, 30]
query_lens = [24, 12, 10]
replay_starts = [12, 0, 0]
builder = make_builder(vision=False)
md = build_metadata(builder, seq_lens, query_lens, None, replay_starts)
assert md.replay_start is not None
assert md.replay_start.cpu().tolist() == replay_starts
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
rows, lens = ref_swa_slot_rows(
seq_lens,
query_lens,
[[], [], []],
block_table,
WINDOW,
MAX_IMG,
WINDOW,
replay_starts=replay_starts,
)
assert md.prefill_swa_lens.cpu().tolist() == lens
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
# Request 0: the first replayed row (pos 16) sees [12, 16]; its last row
# (pos 39) is a full window above the replay start and sees all of it.
assert md.prefill_swa_lens[0].item() == 16 - 12 + 1
assert md.prefill_swa_lens[23].item() == WINDOW
# gather_len = query_len + min(prefix_len - replay_start, WINDOW - 1).
assert md.prefill_gather_lens.cpu().tolist() == [
24 + min(16 - 12, WINDOW - 1),
12,
10 + min(20, WINDOW - 1),
]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_replaying_group_builds_without_replay_start():
"""Graph captures build without model-specific kwargs: a replaying group's
metadata then bounds nothing."""
builder = make_builder(vision=False, bounded_replay=True)
md = build_metadata(builder, [40, 12], [24, 12], None)
assert not md.replay_start.any()
assert md.prefill_swa_lens[0].item() == WINDOW
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_v41_flashinfer_mixed_sparse_indices_respect_replay_start():
from vllm.models.deepseek_v41.common.ops.cache_utils import (
build_flashinfer_mixed_sparse_indices as build_v41,
)
device = torch.device("cuda")
# 1 decode token (req 0) + two prefill requests; req 1 resumes at 16.
seq_lens = [20, 40, 9]
query_lens = [1, 24, 9]
replay_starts = [0, 16, 0]
query_start_loc = torch.tensor([0, 1, 25, 34], dtype=torch.int32, device=device)
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
token_to_req = torch.tensor(
[0] + [1] * 24 + [2] * 9, dtype=torch.int32, device=device
)
block_table = torch.arange(3, dtype=torch.int32, device=device).view(3, 1)
kwargs = dict(
decode_swa_indices=torch.zeros((1, WINDOW), dtype=torch.int32, device=device),
decode_compressed_indices=None,
decode_compressed_topk_lens=None,
prefill_topk_indices=torch.empty((33, 0), dtype=torch.int32, device=device),
query_start_loc=query_start_loc,
seq_lens=seq_lens_t,
token_to_req_indices=token_to_req,
swa_block_table=block_table,
swa_block_size=BLOCK_SIZE,
compressed_block_table=None,
compressed_block_size=BLOCK_SIZE,
window_size=WINDOW,
compress_ratio=1,
topk=0,
)
plain, _ = build_v41(
replay_start=torch.zeros(3, dtype=torch.int32, device=device), **kwargs
)
bounded, _ = build_v41(
replay_start=torch.tensor(replay_starts, dtype=torch.int32, device=device),
**kwargs,
)
rows, _ = ref_swa_slot_rows(
seq_lens,
query_lens,
[[], [], []],
block_table,
WINDOW,
MAX_IMG,
WINDOW,
replay_starts=replay_starts,
)
# Decode row is copied through; prefill rows follow the bounded window.
assert bounded[0].cpu().tolist() == plain[0].cpu().tolist()
assert bounded[1:].cpu().tolist() == rows[1:]
@@ -669,6 +669,7 @@ def test_dsv41_flashinfer_dspark_window_matches_reference(
),
block_table=torch.arange(48, device=device, dtype=torch.int32).view(3, -1),
block_size=128,
replay_start=torch.zeros(3, device=device, dtype=torch.int32),
flashinfer_sparse_index_cache={},
max_decode_query_len=5,
)
@@ -14,6 +14,7 @@ from vllm.models.deepseek_v41.sparse_mla import (
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.compressor_utils import (
CompressedSlotMappingKernel,
get_compressed_slot_mapping,
)
from vllm.v1.attention.backends.mla.indexer import (
BuildPrefillChunkMetadataKernel,
@@ -235,6 +236,28 @@ def test_compressed_slot_mapping_warmup_includes_index_kpool():
assert {(key.compress_ratio, key.block_size) for key in keys} == {(32, 2)}
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_compressed_slot_mapping_inherits_padded_token_slots():
"""A token whose own slot is padded (SWA bounded replay) closes no
compressed state either."""
device = torch.device("cuda")
query_start_loc = torch.tensor([0, 8], dtype=torch.int32, device=device)
seq_lens = torch.tensor([8], dtype=torch.int32, device=device)
block_table = torch.tensor([[3]], dtype=torch.int32, device=device)
slot_mapping = torch.arange(8, dtype=torch.int64, device=device)
slot_mapping[:4] = -1
compressed = get_compressed_slot_mapping(
8,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size=4,
compress_ratio=2,
)
assert compressed.tolist() == [-1, -1, -1, -1, -1, 3 * 4 + 2, -1, 3 * 4 + 3]
def test_index_conversion_warmup_uses_physical_block_stride():
config = SimpleNamespace(
cache_config=SimpleNamespace(block_size=64),
@@ -651,3 +651,67 @@ class TestCompressorRingGroup:
scheduler_block_size=128,
)
assert len(manager.coordinator.single_type_managers) == len(groups)
class TestSWABoundedReplayGrouping:
def test_non_cacheable_swa_leaves_hits_to_the_paged_group(self):
"""Under SWA bounded replay only the paged MLA group hashes (hash
block = its block) and the coordinator probes one spec group."""
config = _shared_layout_config()
config.cache_config.enable_prefix_caching = True
specs: dict[str, KVCacheSpec] = {
"layers.2.attn": MLAAttentionSpec(
block_size=128,
num_kv_heads=1,
head_size=584,
dtype=torch.uint8,
tokens_per_state=2,
alignment=576,
),
}
swa = SlidingWindowMLASpec(
block_size=32,
num_kv_heads=1,
head_size=584,
dtype=torch.uint8,
sliding_window=128,
alignment=576,
bounded_replay=True,
)
for layer in range(4):
specs[f"layers.{layer}.attn.swa_cache"] = swa
groups = get_kv_cache_groups(config, specs)
# The worker reads the replay window off the (packed) group specs to
# arm the window clamp; the wrapper must forward it like cacheability.
assert sorted(
(g.kv_cache_spec.prefix_cacheable, g.kv_cache_spec.prefix_replay_tokens)
for g in groups
) == [(False, 128)] * 4 + [(True, 0)]
kv_cache_config = get_kv_cache_config_from_groups(
config, groups, available_memory=64 * _get_kv_cache_bytes_per_block(groups)
)
manager = KVCacheManager(
generate_scheduler_kv_cache_config([kv_cache_config]),
max_model_len=8192,
enable_caching=True,
hash_block_size=128,
scheduler_block_size=128,
)
assert len(manager.coordinator.attention_groups) == 1
assert isinstance(
manager.coordinator.attention_groups[0].spec, MLAAttentionSpec
)
# Allocating and caching a request goes through every group's manager;
# the 32-token SWA group must skip hashing rather than assert on the
# 128-token hash block.
from tests.v1.core.utils import create_requests
request = create_requests(num_requests=1, num_tokens=256, block_size=128)[0]
assert manager.allocate_slots(request, 256) is not None
request.num_computed_tokens = 256
manager.cache_blocks(request, 256)
for single in manager.coordinator.single_type_managers:
cached = single.num_cached_block.get(request.request_id, 0)
assert cached == (2 if single.kv_cache_spec.prefix_cacheable else 0)
+3 -1
View File
@@ -6,7 +6,7 @@ import copy
from collections.abc import Callable
from dataclasses import replace
from math import lcm
from types import SimpleNamespace
from types import MethodType, SimpleNamespace
from unittest.mock import MagicMock
import pytest
@@ -533,7 +533,9 @@ def test_nixl_hisparse_full_block_import_keeps_a_writable_tail(num_tokens):
kv_cache_manager=manager,
failed_recving_kv_req_ids=set(),
finished_recving_kv_req_ids={request.request_id},
prefix_replay_tokens=0,
)
scheduler._mark_prefix_replay = MethodType(Scheduler._mark_prefix_replay, scheduler)
Scheduler._update_waiting_for_remote_kv(scheduler, request)
assert request.num_tokens - request.num_computed_tokens == 1
assert manager.allocate_slots(request, num_new_tokens=1) is not None
+279
View File
@@ -0,0 +1,279 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""SWA bounded replay: after a prefix hit the scheduler recomputes the tail of
the hit to rebuild the non-cacheable sliding-window group, keeps the hit's
blocks, and hands the worker the replay start."""
import pytest
import torch
from tests.v1.kv_connector.unit.utils import MockKVConfig, create_model_runner_output
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheConfig,
KVCacheGroupSpec,
SlidingWindowMLASpec,
)
from vllm.v1.outputs import ModelRunnerOutput
from vllm.v1.request import RequestStatus
from vllm.v1.structured_output import StructuredOutputManager
from .utils import create_requests, create_scheduler
BLOCK_SIZE = 16
WINDOW = 32
NUM_PROMPT_TOKENS = 100
# 100 tokens -> 6 full blocks cached -> 96-token hit.
HIT_TOKENS = NUM_PROMPT_TOKENS // BLOCK_SIZE * BLOCK_SIZE
FULL, SWA = 0, 1
def _replay_scheduler(
*,
long_prefill_token_threshold: int = 0,
use_kv_connector: MockKVConfig | None = None,
) -> Scheduler:
"""A hybrid layout: one prefix-cacheable full-attention group and one
replayed sliding-window group."""
base = create_scheduler(
block_size=BLOCK_SIZE,
enable_prefix_caching=True,
long_prefill_token_threshold=long_prefill_token_threshold,
use_kv_connector=use_kv_connector,
)
vllm_config = base.vllm_config
kv_cache_config = KVCacheConfig(
num_blocks=10000,
kv_cache_tensors=[],
kv_cache_groups=[
KVCacheGroupSpec(
["full"],
FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
),
),
KVCacheGroupSpec(
["swa"],
SlidingWindowMLASpec(
block_size=BLOCK_SIZE,
num_kv_heads=1,
head_size=64,
dtype=torch.bfloat16,
sliding_window=WINDOW,
bounded_replay=True,
),
),
],
)
scheduler = Scheduler(
vllm_config=vllm_config,
kv_cache_config=kv_cache_config,
block_size=BLOCK_SIZE,
log_stats=True,
structured_output_manager=StructuredOutputManager(vllm_config),
)
scheduler.use_v2_model_runner = True
assert scheduler.prefix_replay_tokens == WINDOW
return scheduler
def _prefill(scheduler: Scheduler, request) -> None:
scheduler.add_request(request)
out = scheduler.schedule()
assert out.num_scheduled_tokens[request.request_id] == request.num_prompt_tokens
scheduler.update_from_output(out, _step_output(out, [request]))
def _step_output(out, requests) -> ModelRunnerOutput:
"""Model output for every scheduled request: a token once its prefill is
done (non-zero, so outputs never extend the all-zero shared prompt in the
cache), nothing while it is still prefilling. schedule() has already
advanced num_computed_tokens past this step's chunk."""
scheduled = [r for r in requests if r.request_id in out.num_scheduled_tokens]
return ModelRunnerOutput(
req_ids=[r.request_id for r in scheduled],
req_id_to_index={r.request_id: i for i, r in enumerate(scheduled)},
sampled_token_ids=[
[1000] if r.num_computed_tokens >= r.num_prompt_tokens else []
for r in scheduled
],
logprobs=None,
prompt_logprobs_dict={},
pooler_output=None,
)
def _new_req_data(out, request):
return next(r for r in out.scheduled_new_reqs if r.req_id == request.request_id)
def test_hit_replays_window_without_reallocating():
scheduler = _replay_scheduler()
expected_replay = WINDOW
first, second = create_requests(
num_requests=2,
num_tokens=NUM_PROMPT_TOKENS,
same_prompt=True,
block_size=BLOCK_SIZE,
)
_prefill(scheduler, first)
manager = scheduler.kv_cache_manager
scheduler.add_request(second)
out = scheduler.schedule()
replay_start = HIT_TOKENS - expected_replay
new_req = _new_req_data(out, second)
assert new_req.num_computed_tokens == replay_start
assert new_req.replay_start == replay_start
assert (
out.num_scheduled_tokens[second.request_id] == NUM_PROMPT_TOKENS - replay_start
)
first_blocks = manager.get_blocks(first.request_id).blocks
second_blocks = manager.get_blocks(second.request_id).blocks
# The full-attention hit is shared (replayed tokens included); only the
# tail block is new.
num_hit_blocks = HIT_TOKENS // BLOCK_SIZE
assert second_blocks[FULL][:num_hit_blocks] == first_blocks[FULL][:num_hit_blocks]
assert all(b.ref_cnt == 2 for b in second_blocks[FULL][:num_hit_blocks])
assert len(second_blocks[FULL]) == num_hit_blocks + 1
# The window group never hits: blocks below the window are null, the
# window (replayed and new tokens) gets fresh blocks.
num_skipped_blocks = (HIT_TOKENS - WINDOW + 1) // BLOCK_SIZE
assert all(b.is_null for b in second_blocks[SWA][:num_skipped_blocks])
num_window_blocks = len(second_blocks[SWA]) - num_skipped_blocks
assert num_window_blocks == -(-NUM_PROMPT_TOKENS // BLOCK_SIZE) - num_skipped_blocks
assert not any(b.is_null for b in second_blocks[SWA][num_skipped_blocks:])
scheduler.update_from_output(out, _step_output(out, [first, second]))
assert second.num_computed_tokens == NUM_PROMPT_TOKENS
def test_replay_only_chunks_make_progress():
"""A chunk cap smaller than the replay window schedules replay-only
chunks; they advance the request instead of stalling it."""
scheduler = _replay_scheduler(long_prefill_token_threshold=BLOCK_SIZE)
first, second = create_requests(
num_requests=2,
num_tokens=NUM_PROMPT_TOKENS,
same_prompt=True,
block_size=BLOCK_SIZE,
)
scheduler.add_request(first)
while first.num_computed_tokens < NUM_PROMPT_TOKENS:
out = scheduler.schedule()
scheduler.update_from_output(out, _step_output(out, [first]))
scheduler.add_request(second)
def full_blocks():
return scheduler.kv_cache_manager.get_blocks(second.request_id).blocks[FULL]
scheduled: list[int] = []
while second.num_computed_tokens < NUM_PROMPT_TOKENS:
out = scheduler.schedule()
if not scheduled:
new_req = _new_req_data(out, second)
assert new_req.num_computed_tokens == HIT_TOKENS - WINDOW
assert new_req.replay_start == HIT_TOKENS - WINDOW
# A replay-only chunk adopts the hit and allocates nothing new.
assert len(full_blocks()) == HIT_TOKENS // BLOCK_SIZE
scheduled.append(out.num_scheduled_tokens[second.request_id])
scheduler.update_from_output(out, _step_output(out, [first, second]))
# 32 replayed + 4 new tokens in 16-token chunks: two replay-only chunks.
assert scheduled == [BLOCK_SIZE, BLOCK_SIZE, NUM_PROMPT_TOKENS - HIT_TOKENS]
assert len(full_blocks()) == -(-NUM_PROMPT_TOKENS // BLOCK_SIZE)
assert second.status == RequestStatus.RUNNING
def test_async_remote_kv_hit_replays_after_load():
"""A KV-connector hit loaded asynchronously carries no window state
either; the replay is applied when the load completes."""
matched = 64
scheduler = _replay_scheduler(
use_kv_connector=MockKVConfig(matched_tokens=matched, is_async=True)
)
request = create_requests(
num_requests=1, num_tokens=NUM_PROMPT_TOKENS, block_size=BLOCK_SIZE
)[0]
scheduler.add_request(request)
out = scheduler.schedule()
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
assert request.request_id not in out.num_scheduled_tokens
scheduler.update_from_output(
out, create_model_runner_output([], finished_recving={request.request_id})
)
out = scheduler.schedule()
new_req = _new_req_data(out, request)
assert new_req.num_computed_tokens == matched - WINDOW
assert new_req.replay_start == matched - WINDOW
assert (
out.num_scheduled_tokens[request.request_id]
== NUM_PROMPT_TOKENS - matched + WINDOW
)
def test_remote_kv_hit_is_taken_in_whole_blocks():
"""A hit ending one token short of a block boundary would put the replay
window's first token in a block the sliding-window group retires, so a
connector hit is cut back to whole blocks."""
matched = 4 * BLOCK_SIZE - 1
scheduler = _replay_scheduler(
use_kv_connector=MockKVConfig(matched_tokens=matched, is_async=True)
)
request = create_requests(
num_requests=1, num_tokens=NUM_PROMPT_TOKENS, block_size=BLOCK_SIZE
)[0]
scheduler.add_request(request)
out = scheduler.schedule()
scheduler.update_from_output(
out, create_model_runner_output([], finished_recving={request.request_id})
)
out = scheduler.schedule()
new_req = _new_req_data(out, request)
hit = 3 * BLOCK_SIZE
assert new_req.replay_start == hit - WINDOW
assert new_req.num_computed_tokens == hit - WINDOW
swa_manager = scheduler.kv_cache_manager.coordinator.single_type_managers[SWA]
swa_blocks = scheduler.kv_cache_manager.get_blocks(request.request_id).blocks[SWA]
assert swa_blocks[new_req.replay_start // BLOCK_SIZE] is not swa_manager._null_block
@pytest.mark.parametrize("via_connector", [False, True])
def test_hit_no_longer_than_window_is_ignored(via_connector):
"""Such a hit would be recomputed in full anyway. It is not adopted (an
async load of it is not even started), so a request has computed tokens
iff it replays."""
if via_connector:
scheduler = _replay_scheduler(
use_kv_connector=MockKVConfig(matched_tokens=WINDOW, is_async=True)
)
request = create_requests(
num_requests=1, num_tokens=NUM_PROMPT_TOKENS, block_size=BLOCK_SIZE
)[0]
else:
scheduler = _replay_scheduler()
first = create_requests(
num_requests=1, num_tokens=WINDOW, same_prompt=True, block_size=BLOCK_SIZE
)[0]
_prefill(scheduler, first)
request = create_requests(
num_requests=1,
num_tokens=NUM_PROMPT_TOKENS,
same_prompt=True,
block_size=BLOCK_SIZE,
req_ids=["long"],
)[0]
scheduler.add_request(request)
out = scheduler.schedule()
new_req = _new_req_data(out, request)
assert request.status == RequestStatus.RUNNING
assert new_req.num_computed_tokens == 0
assert new_req.replay_start == 0
assert out.num_scheduled_tokens[request.request_id] == NUM_PROMPT_TOKENS
@@ -1505,6 +1505,7 @@ def test_failed_load_rezeroes_unwritten_skipped_blocks():
scheduler.kv_cache_manager.cache_blocks = MagicMock()
scheduler.failed_recving_kv_req_ids = {"req-1"}
scheduler.finished_recving_kv_req_ids = {"req-1"}
scheduler.prefix_replay_tokens = 0
request = MagicMock()
request.request_id = "req-1"