Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-03 21:59:03 +07:00
1012 changed files with 61873 additions and 14499 deletions
@@ -5,7 +5,9 @@
from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.layers.mamba.abstract import MambaBase
from vllm.model_executor.layers.mamba.linear.minimax_linear_attn import (
MiniMaxText01LinearAttention,
)
@@ -19,6 +21,32 @@ from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionBackend
@pytest.mark.parametrize(("use_replayssm", "expected_blocks"), [(False, 3), (True, 0)])
def test_replayssm_does_not_reserve_speculative_state_blocks(
use_replayssm, expected_blocks
):
layer = SimpleNamespace(
get_state_shape=lambda: ((2,),),
get_state_dtype=lambda: (torch.float32,),
mamba_type=MambaAttentionBackendEnum.MAMBA2,
is_kv_cache_tp_replicated=False,
)
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(
mamba_block_size=1,
mamba_page_size_padded=None,
mamba_cache_mode="none",
use_replayssm=use_replayssm,
),
num_speculative_tokens=3,
)
spec = MambaBase.get_kv_cache_spec(layer, vllm_config)
assert spec is not None
assert spec.num_speculative_blocks == expected_blocks
@pytest.mark.parametrize(
"layer_class, init_kwargs, expected_backend, expected_mamba_type",
[
@@ -0,0 +1,159 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Equivalence tests for the AITER MLA page-index expansion kernel.
`_expand_page_indices_kernel` turns a block table into the per-token flat page
indices the AITER MLA decode kernel consumes (it always runs with page_size=1
internally, so `kv_buffer` is flattened and each token needs its own index).
The kernel was parallelised over token chunks as well as requests; at
concurrency 1 the previous `(num_reqs,)` grid put a single workgroup in a serial
loop over the whole sequence. These tests pin the result to a straightforward
PyTorch expansion so the parallelisation cannot change what is produced.
Both block-table strides are passed by the caller, so a non-contiguous view is
covered explicitly rather than assumed away.
"""
import pytest
import torch
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
_expand_page_indices_kernel,
)
def _reference(block_table, cu_num_tokens, kernel_block_size, out_len, device):
"""Per-token flat index, written the obvious way."""
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
num_reqs = cu_num_tokens.numel() - 1
for r in range(num_reqs):
start = int(cu_num_tokens[r])
end = int(cu_num_tokens[r + 1])
n = end - start
if n <= 0:
continue
tok = torch.arange(n, device=device)
blk = tok // kernel_block_size
off = tok % kernel_block_size
out[start:end] = block_table[r, blk].to(torch.int64) * kernel_block_size + off
return out
def _run(block_table, cu_num_tokens, kernel_block_size, out_len, device):
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
num_reqs = cu_num_tokens.numel() - 1
max_tokens_per_req = block_table.shape[1] * kernel_block_size
num_chunks = max(1, -(-max_tokens_per_req // 1024))
_expand_page_indices_kernel[(num_reqs, num_chunks)](
out,
block_table,
block_table.stride(0),
block_table.stride(1),
cu_num_tokens,
KERNEL_BLOCK_SIZE=kernel_block_size,
BLOCK_SIZE=1024,
)
return out
def _make(seq_lens, kernel_block_size, device, noncontig=False):
num_reqs = len(seq_lens)
max_blocks = (
max(1, max((s + kernel_block_size - 1) // kernel_block_size for s in seq_lens))
+ 2
)
width = max_blocks * 2 if noncontig else max_blocks
torch.manual_seed(0)
bt = torch.randint(0, 10_000, (num_reqs, width), dtype=torch.int64, device=device)
if noncontig:
bt = bt[:, ::2]
assert not bt.is_contiguous()
cu = torch.zeros(num_reqs + 1, dtype=torch.int64, device=device)
cu[1:] = torch.tensor(seq_lens, dtype=torch.int64, device=device).cumsum(0)
return bt, cu, int(cu[-1])
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
@pytest.mark.parametrize(
"seq_lens", [[1], [128], [4096], [1, 1], [4096, 7], [37, 4096, 1], [1024] * 8]
)
@pytest.mark.parametrize("kernel_block_size", [1, 16, 64])
def test_matches_reference(seq_lens, kernel_block_size):
bt, cu, total = _make(seq_lens, kernel_block_size, "cuda")
got = _run(bt, cu, kernel_block_size, total, "cuda")
want = _reference(bt, cu, kernel_block_size, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
@pytest.mark.parametrize("kernel_block_size", [1, 16])
def test_non_contiguous_block_table(kernel_block_size):
"""Column stride != 1 must be honoured, not assumed away."""
bt, cu, total = _make([4096, 37], kernel_block_size, "cuda", noncontig=True)
got = _run(bt, cu, kernel_block_size, total, "cuda")
want = _reference(bt, cu, kernel_block_size, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_ragged_batch_leaves_other_rows_untouched():
"""A short request must not have its tail written by a longer one's chunks."""
kbs = 16
bt, cu, total = _make([4096, 1, 512], kbs, "cuda")
out = torch.full((total + 8,), -999, dtype=torch.int64, device="cuda")
num_chunks = max(1, -(-(bt.shape[1] * kbs) // 1024))
_expand_page_indices_kernel[(3, num_chunks)](
out,
bt,
bt.stride(0),
bt.stride(1),
cu,
KERNEL_BLOCK_SIZE=kbs,
BLOCK_SIZE=1024,
)
want = _reference(bt, cu, kbs, total, "cuda")
torch.testing.assert_close(out[:total], want, atol=0, rtol=0)
# The slack past the last request must be untouched.
assert torch.all(out[total:] == -999)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_zero_length_request_writes_nothing():
"""A zero-token request in a padded batch must produce no stores."""
kbs = 16
bt, cu, total = _make([256, 0, 128], kbs, "cuda")
got = _run(bt, cu, kbs, total, "cuda")
want = _reference(bt, cu, kbs, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
assert int(cu[2] - cu[1]) == 0
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_over_provisioned_chunks_do_not_change_result():
"""Extra chunks must be inert.
Each program covers `chunk_idx * BLOCK_SIZE + [0, BLOCK_SIZE)`, so the grid
has to span the request: 8192 tokens need at least ceil(8192/1024) == 8
chunks, and fewer would simply leave the tail unwritten. The caller sizes
the grid from `block_table.shape[1] * kernel_block_size`, an upper bound
over the batch, so in a ragged batch most requests get more chunks than
they need. That over-provisioning is the case worth pinning: the surplus
programs must return early and change nothing.
"""
kbs = 1
bt, cu, total = _make([8192], kbs, "cuda")
ref = _reference(bt, cu, kbs, total, "cuda")
required = -(-total // 1024)
for num_chunks in (required, required * 2, required * 8):
out = torch.full((total,), -1, dtype=torch.int64, device="cuda")
_expand_page_indices_kernel[(1, num_chunks)](
out,
bt,
bt.stride(0),
bt.stride(1),
cu,
KERNEL_BLOCK_SIZE=kbs,
BLOCK_SIZE=1024,
)
torch.testing.assert_close(out, ref, atol=0, rtol=0)
@@ -208,12 +208,14 @@ def test_builder_plans_only_rows_dispatched_to_mqa(monkeypatch, use_mha, num_dec
assert builder.state.plan_calls[0][1].tolist() == expected_lens
def test_plan_uses_state_params(monkeypatch):
@pytest.mark.parametrize("kv_dtype", [torch.bfloat16, torch.float8_e4m3fn])
def test_plan_uses_state_params(monkeypatch, kv_dtype):
"""The NoPE/rope dims and scale live on the builder state, not the layer.
Without a device batch layout plan() takes exact per-row KV lengths and
rebuilds the schedule on every call; the indptrs are always full-size
with zero-query padding rows past num_tokens.
with zero-query padding rows past num_tokens. An fp8 cache plans as
float8_e4m3fn.
"""
wrapper = FakeWrapper()
plan_info = [0] * sm90_mod._PLAN_INFO_LEN
@@ -226,7 +228,7 @@ def test_plan_uses_state_params(monkeypatch):
state.device = torch.device("cpu")
state.wrapper = wrapper
state.num_heads = 4
state.kv_dtype = torch.bfloat16
state.kv_dtype = kv_dtype
state.kv_lora_rank = HEAD
state.qk_rope_head_dim = 64
state.sm_scale = 576**-0.5
@@ -249,7 +251,7 @@ def test_plan_uses_state_params(monkeypatch):
assert (heads, ckv, kpe, page, causal) == (4, HEAD, 64, 1, False)
assert scale == 576**-0.5
assert kwargs["q_data_type"] == torch.bfloat16
assert kwargs["kv_data_type"] == torch.bfloat16
assert kwargs["kv_data_type"] == kv_dtype
# Replanning a smaller batch must clear the previous rows' lengths.
state.plan(1, torch.tensor([TOPK], dtype=torch.int32), None, None)
@@ -339,6 +341,14 @@ def test_kv_lens_host_empty():
_NO_KPOOL = object()
@pytest.mark.parametrize(
"spec_dtype,expected_kv_dtype",
[
(torch.bfloat16, torch.bfloat16),
(torch.uint8, torch.float8_e4m3fn),
],
ids=["bf16", "fp8"],
)
@pytest.mark.parametrize(
"index_kpool,prefill_lens",
[
@@ -348,9 +358,12 @@ _NO_KPOOL = object()
],
ids=["kpool4", "kpool_none", "no_kpool_attr"],
)
def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens):
def test_builder_kpool_from_model_config(
monkeypatch, index_kpool, prefill_lens, spec_dtype, expected_kv_dtype
):
"""The builder took kpool from the KV cache spec, whose tokens_per_state is
1, so the tail pool was never read."""
1, so the tail pool was never read. The state plans the cache's logical
dtype: uint8 fp8 storage becomes float8_e4m3fn."""
monkeypatch.setattr(
sm90_mod.FlashInferMLASparseMetadataBuilder,
"__init__",
@@ -358,14 +371,15 @@ def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens)
)
class _RecordingState:
def __init__(self, *_args, **kwargs):
def __init__(self, *args, **kwargs):
self.kv_dtype = args[2]
self.index_topk = kwargs["index_topk"]
self.index_kpool = kwargs["index_kpool"]
monkeypatch.setattr(sm90_mod, "_SM90State", _RecordingState)
impl, _ = make_impl(64)
spec = MLAAttentionSpec(
block_size=BLOCK_SIZE, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
block_size=BLOCK_SIZE, num_kv_heads=1, head_size=576, dtype=spec_dtype
)
assert spec.tokens_per_state == 1
hf_config = SimpleNamespace(index_topk=2048)
@@ -384,6 +398,7 @@ def test_builder_kpool_from_model_config(monkeypatch, index_kpool, prefill_lens)
builder = FlashInferMLASparseSM90Builder(
spec, ["attn"], vllm_config, torch.device("cpu")
)
assert builder.state.kv_dtype == expected_kv_dtype
# req0: prefill chunk ending at context 42295; req1: context <= topk.
cam = SimpleNamespace(
num_reqs=2,
+119 -2
View File
@@ -17,6 +17,7 @@ from tests.v1.attention.utils import (
)
from vllm.config import SpeculativeConfig
from vllm.config.compilation import CUDAGraphMode
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.gdn_attn import (
GDNAttentionMetadata,
GDNAttentionMetadataBuilder,
@@ -65,6 +66,17 @@ GDN_BUILD_TEST_CASES = {
expected_num_prefill_tokens=0,
expected_num_spec_decodes=2,
),
# Padded (CUDA graph) sequences trail the spec decodes
"pure_spec_decode_with_padding": GDNBuildTestCase(
seq_lens=[50, 30, 16],
query_lens=[3, 3, 0],
num_decode_draft_tokens=[2, 2, -1],
num_speculative_tokens=2,
expected_num_decodes=0,
expected_num_prefills=0,
expected_num_prefill_tokens=0,
expected_num_spec_decodes=2,
),
# No speculative config at all — standard decode path
"pure_regular_decode": GDNBuildTestCase(
seq_lens=[40, 30, 20],
@@ -143,8 +155,9 @@ def _create_gdn_builder(
model_name="Qwen/Qwen3.5-0.8B",
block_size=BLOCK_SIZE,
)
if full_cuda_graph:
vllm_config.compilation_config.cudagraph_mode = CUDAGraphMode.FULL_AND_PIECEWISE
vllm_config.compilation_config.cudagraph_mode = (
CUDAGraphMode.FULL_AND_PIECEWISE if full_cuda_graph else CUDAGraphMode.NONE
)
if num_speculative_tokens > 0:
vllm_config.speculative_config = SpeculativeConfig(
method="ngram",
@@ -197,6 +210,8 @@ def test_gdn_build_classification(test_case: GDNBuildTestCase):
assert meta.num_prefills == test_case.expected_num_prefills
assert meta.num_prefill_tokens == test_case.expected_num_prefill_tokens
assert meta.num_spec_decodes == test_case.expected_num_spec_decodes
if meta.spec_state_indices_tensor is not None:
assert len(meta.spec_state_indices_tensor) == meta.num_spec_decodes
@pytest.mark.parametrize("mamba_cache_mode", ["none", "align"])
@@ -367,3 +382,105 @@ def test_cudagraph_capture_batch_stays_decode_only():
assert staged is not None
assert staged.data_ptr() == builder.non_spec_state_indices_tensor.data_ptr()
torch.testing.assert_close(staged, common_attn_metadata.block_table_tensor[:, 0])
def _create_checkpoint_builder_and_batch(
num_spec: int, prefix_match_unit: int = 16
) -> tuple[GDNAttentionMetadataBuilder, CommonAttentionMetadata, dict]:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B",
block_size=BLOCK_SIZE,
)
if num_spec > 0:
vllm_config.speculative_config = SpeculativeConfig(
method="ngram",
num_speculative_tokens=num_spec,
)
vllm_config.cache_config.mamba_cache_mode = "align"
vllm_config.cache_config.prefix_match_unit = prefix_match_unit
mamba_spec = MambaSpec(
block_size=64,
shapes=((16, 64),),
dtypes=(torch.float16,),
mamba_cache_mode="align",
num_speculative_blocks=num_spec,
num_prefill_checkpoint_blocks=1,
prefill_checkpoint_alignment=16,
)
builder = GDNAttentionMetadataBuilder(
kv_cache_spec=mamba_spec,
layer_names=["layer.0"],
vllm_config=vllm_config,
device=DEVICE,
)
batch = BatchSpec(
seq_lens=[65, 100, 100], query_lens=[3 if num_spec else 1, 100, 99]
)
common = create_common_attn_metadata(batch, 64, DEVICE, arange_block_indices=True)
table = common.block_table_tensor + 1
if num_spec:
table = torch.cat([table, torch.zeros(3, num_spec, dtype=table.dtype)], dim=1)
common = common.replace(block_table_tensor=table)
kwargs = {}
if num_spec:
kwargs = dict(
num_decode_draft_tokens_cpu=torch.tensor([2, -1, -1], dtype=torch.int32),
num_accepted_tokens=torch.ones(3, dtype=torch.int32),
)
return builder, common, kwargs
@pytest.mark.parametrize("num_spec", [0, 3])
@pytest.mark.parametrize("prefix_match_unit, expected_offset", [(16, 96), (8, 96)])
def test_checkpoint_metadata_preserves_non_spec_order(
num_spec, prefix_match_unit, expected_offset
):
"""Only eligible non-spec rows get a checkpoint in their reserved page."""
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
builder, common, kwargs = _create_checkpoint_builder_and_batch(
num_spec, prefix_match_unit
)
actual = builder.build(0, common, **kwargs)
assert actual.checkpoint is not None
offsets = [expected_offset, 0] if num_spec else [0, expected_offset, 0]
slots = [common.block_table_tensor[1, 0].item(), NULL_BLOCK_ID]
if not num_spec:
slots.insert(0, NULL_BLOCK_ID)
torch.testing.assert_close(
actual.checkpoint.checkpoint_offsets, torch.tensor(offsets, dtype=torch.int32)
)
torch.testing.assert_close(
actual.checkpoint.state_indices, torch.tensor(slots, dtype=torch.int32)
)
@pytest.mark.parametrize("num_spec", [0, 3])
def test_update_block_table_regathers_checkpoint(num_spec):
"""Checkpoint pages come from the target group's block table, not the
source group's (otherwise the target group's checkpoint page is never
written while the prefix cache treats it as valid)."""
src, common, kwargs = _create_checkpoint_builder_and_batch(num_spec)
dst, _, _ = _create_checkpoint_builder_and_batch(num_spec)
ref, _, _ = _create_checkpoint_builder_and_batch(num_spec)
other_table = common.block_table_tensor + 100
other = common.replace(block_table_tensor=other_table)
dst.mamba_aligned_state_indices = mamba_get_block_table_tensor(
other_table, other.seq_lens, dst.kv_cache_spec, "align"
)
source = src.build(0, common, **kwargs)
expected = ref.build(0, other, **kwargs)
actual = dst.update_block_table(source, other_table, other.slot_mapping)
assert source.checkpoint is not None and expected.checkpoint is not None
assert actual.checkpoint is not None
torch.testing.assert_close(
actual.checkpoint.state_indices, expected.checkpoint.state_indices
)
torch.testing.assert_close(
actual.checkpoint.checkpoint_offsets, expected.checkpoint.checkpoint_offsets
)
assert not torch.equal(
actual.checkpoint.state_indices, source.checkpoint.state_indices
)
@@ -15,6 +15,7 @@ from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4SparseMLABackend as DeepseekV41SparseMLABackend,
)
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla import indexer as indexer_module
from vllm.v1.attention.backends.mla.compressor_utils import (
CompressedSlotMappingKernel,
get_compressed_slot_mapping,
@@ -24,6 +25,7 @@ from vllm.v1.attention.backends.mla.indexer import (
DeepseekV4IndexerBackend,
DeepseekV32IndexerMetadataBuilder,
DeepseekV41IndexerBackend,
get_max_prefill_buffer_size,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
ConvertReqIndexToGlobalIndexKernel,
@@ -294,6 +296,78 @@ def test_index_conversion_warmup_uses_physical_block_stride():
assert {key.block_stride_rows for key in keys} == {4096}
def test_zero_token_pcp_rank_participates_in_compressed_mapping_gather(monkeypatch):
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.compress_ratio = 4
builder.use_pcp = True
builder.pcp_world_size = 4
builder.pcp_rank = 0
builder.kernel_block_size = None
builder.kv_cache_spec = SimpleNamespace(block_size=64, num_states=64)
builder.compressed_slot_mapping_buffer = torch.zeros(8, dtype=torch.int64)
def fake_get_compressed_slot_mapping(
num_tokens,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size,
compress_ratio,
out,
):
assert num_tokens == 0
assert block_size == 64
assert compress_ratio == 4
out.fill_(-1)
return out[:num_tokens]
gathered_slot_mapping = torch.tensor([123, -1, -1, -1], dtype=torch.int64)
class FakePCPGroup:
def __init__(self):
self.calls = 0
def all_gather(self, tensor, dim=0):
self.calls += 1
assert dim == 0
torch.testing.assert_close(tensor, torch.tensor([-1]))
return gathered_slot_mapping
fake_pcp_group = FakePCPGroup()
monkeypatch.setattr(
indexer_module,
"get_compressed_slot_mapping",
fake_get_compressed_slot_mapping,
)
monkeypatch.setattr(indexer_module, "get_pcp_group", lambda: fake_pcp_group)
query_start_loc = torch.tensor([0, 0], dtype=torch.int32)
seq_lens = torch.tensor([16], dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc,
seq_lens=seq_lens,
seq_lens_cpu_upper_bound=seq_lens,
num_reqs=1,
num_actual_tokens=0,
max_query_len=0,
max_seq_len=16,
block_table_tensor=torch.tensor([[0]], dtype=torch.int32),
slot_mapping=torch.tensor([11, 22, 33, 44], dtype=torch.int64),
causal=True,
)
metadata = builder.build(common_prefix_len=0, common_attn_metadata=common)
assert fake_pcp_group.calls == 1
assert metadata.num_decodes == 0
assert metadata.num_decode_tokens == 0
assert metadata.num_prefills == 0
assert metadata.num_prefill_tokens == 0
torch.testing.assert_close(metadata.slot_mapping, gathered_slot_mapping)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_indexer_builder_deepseek_v4_compressed_slot_mapping_uses_num_states():
"""Regression test: DeepseekV4 compression path must compute slot_mapping from
@@ -377,3 +451,43 @@ def test_indexer_builder_deepseek_v4_compressed_slot_mapping_uses_num_states():
device=device,
)
torch.testing.assert_close(valid_slots, expected)
@pytest.mark.parametrize("compress_ratio", [1, 4])
def test_indexer_prefill_budget_matches_compressed_workspace(compress_ratio):
"""The chunker budget is in compressed rows, like the K-gather workspace."""
max_model_len = 1024
kv_cache_spec = MLAAttentionSpec(
block_size=256,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
tokens_per_state=compress_ratio,
)
vllm_config = create_vllm_config(max_model_len=max_model_len)
max_num_blocks = kv_cache_spec.max_num_blocks_per_req(vllm_config, max_model_len)
block_table_width = get_block_table_width(max_num_blocks, kv_cache_spec.block_size)
builder = DeepseekV32IndexerMetadataBuilder(
kv_cache_spec=kv_cache_spec,
layer_names=["dummy"],
vllm_config=vllm_config,
device=torch.device("cpu"),
block_table_width=block_table_width,
)
workspace_rows = get_max_prefill_buffer_size(vllm_config) // compress_ratio
assert builder.max_prefill_buffer_size == workspace_rows
# Overflows the workspace unless the chunker splits.
num_reqs = 3 * (workspace_rows // (max_model_len // compress_ratio)) + 1
compressed_seq_lens = torch.full((num_reqs,), max_model_len // compress_ratio)
query_lens = torch.ones(num_reqs, dtype=torch.int64)
chunks = builder._split_indexer_prefill_chunks(
compressed_seq_lens,
query_lens,
builder.max_prefill_buffer_size,
max_logits_bytes=10**15,
)
assert len(chunks) > 1
for req_slice, _ in chunks:
assert int(compressed_seq_lens[req_slice].sum()) <= workspace_rows
@@ -0,0 +1,58 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for BaseMambaAttentionMetadataBuilder batch classification."""
from types import SimpleNamespace
from tests.v1.attention.utils import MockMambaBuilder
from vllm.config.compilation import CUDAGraphMode
def _make_vllm_config(
max_model_len: int,
max_num_seqs: int,
num_speculative_tokens: int = 0,
block_size: int | None = None,
):
"""Create a minimal mock VllmConfig with only the fields the builder
accesses, avoiding any model download / HF config inspection."""
speculative_config = (
SimpleNamespace(
num_speculative_tokens=num_speculative_tokens,
parallel_drafting=False,
)
if num_speculative_tokens > 0
else None
)
return SimpleNamespace(
cache_config=SimpleNamespace(
block_size=block_size,
mamba_cache_mode="none",
use_replayssm=False,
replayssm_buffer_len=16,
),
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.FULL,
max_cudagraph_capture_size=None,
),
speculative_config=speculative_config,
num_speculative_tokens=num_speculative_tokens,
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
scheduler_config=SimpleNamespace(max_num_seqs=max_num_seqs),
model_config=SimpleNamespace(max_model_len=max_model_len),
)
def test_mamba_single_token_prompt_runs_as_prefill():
seq_lens = [8, 9, 1]
config = _make_vllm_config(256, len(seq_lens), block_size=16)
metadata = MockMambaBuilder.build_mamba_metadata(
config,
seq_lens=seq_lens,
query_lens=[1] * len(seq_lens),
is_prefilling=[False, False, True],
)
assert metadata.num_decodes == 2
assert metadata.num_prefills == 1
assert metadata.has_initial_states_p.tolist() == [False]
@@ -1,466 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Regression test for https://github.com/vllm-project/vllm/issues/34865.
When multiple KV cache groups share the same MambaSpec (as in Nemotron
hybrid models), the metadata caching optimization reuses metadata from
an earlier group via update_block_table(). In 'all' mode with CUDA graphs,
update_block_table() must copy block_idx_last_scheduled_token and
block_idx_last_computed_token to the *current* builder's persistent
buffers, otherwise CUDA graph replay reads stale values from uninitialized
buffers.
"""
from types import SimpleNamespace
import torch
from tests.v1.attention.utils import MockMambaBuilder
from vllm.config.compilation import CUDAGraphMode
from vllm.v1.attention.backends.mamba_attn import BaseMambaAttentionMetadata
from vllm.v1.kv_cache_interface import MambaSpec
def _make_vllm_config(
max_model_len: int,
max_num_seqs: int,
num_speculative_tokens: int = 0,
block_size: int | None = None,
):
"""Create a minimal mock VllmConfig with only the fields the builder
accesses, avoiding any model download / HF config inspection."""
speculative_config = (
SimpleNamespace(
num_speculative_tokens=num_speculative_tokens,
parallel_drafting=False,
)
if num_speculative_tokens > 0
else None
)
return SimpleNamespace(
cache_config=SimpleNamespace(
block_size=block_size,
mamba_cache_mode="all",
use_replayssm=False,
replayssm_buffer_len=16,
),
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.FULL,
max_cudagraph_capture_size=None,
),
speculative_config=speculative_config,
num_speculative_tokens=num_speculative_tokens,
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
scheduler_config=SimpleNamespace(max_num_seqs=max_num_seqs),
model_config=SimpleNamespace(max_model_len=max_model_len),
)
def test_mamba_single_token_prompt_runs_as_prefill():
seq_lens = [8, 9, 1]
config = _make_vllm_config(256, len(seq_lens), block_size=16)
metadata = MockMambaBuilder.build_mamba_metadata(
config,
seq_lens=seq_lens,
query_lens=[1] * len(seq_lens),
is_prefilling=[False, False, True],
)
assert metadata.num_decodes == 2
assert metadata.num_prefills == 1
assert metadata.has_initial_states_p.tolist() == [False]
def test_update_block_table_copies_block_idx_to_persistent_buffers():
"""update_block_table() must write block_idx tensors to the current
builder's persistent buffers, not leave them pointing to a different
builder's buffers."""
block_size = 16
max_model_len = 256
num_reqs = 4
device = torch.device("cpu")
vllm_config = _make_vllm_config(max_model_len, num_reqs)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
)
# Two builders simulating two KV cache groups with the same MambaSpec.
builder_a = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
builder_b = MockMambaBuilder(spec, ["layer1"], vllm_config, device)
# Sanity: each builder has its own persistent buffer.
assert (
builder_a.block_idx_last_scheduled_token.data_ptr()
!= builder_b.block_idx_last_scheduled_token.data_ptr()
)
# Construct decode-only metadata as if builder_a.build() produced it.
max_blocks = max_model_len // block_size
seq_lens = torch.full((num_reqs,), 64, dtype=torch.int32, device=device)
block_idx_vals = (seq_lens - 1) // block_size # [3, 3, 3, 3]
builder_a.block_idx_last_scheduled_token[:num_reqs].copy_(block_idx_vals)
builder_a.block_idx_last_computed_token[:num_reqs].copy_(block_idx_vals)
metadata_a = BaseMambaAttentionMetadata(
num_prefills=0,
num_prefill_tokens=0,
num_decodes=num_reqs,
num_decode_tokens=num_reqs,
num_reqs=num_reqs,
has_initial_states_p=None,
query_start_loc_p=None,
num_computed_tokens_p=None,
state_indices_tensor_p=None,
query_start_loc_d=None,
num_accepted_tokens=None,
state_indices_tensor_d=builder_a.state_indices_tensor_d[:num_reqs],
block_idx_last_scheduled_token=(
builder_a.block_idx_last_scheduled_token[:num_reqs]
),
block_idx_first_scheduled_token_p=None,
block_idx_last_computed_token=(
builder_a.block_idx_last_computed_token[:num_reqs]
),
block_idx_last_scheduled_token_prev_step=None,
seq_lens=seq_lens,
)
# Call update_block_table on builder_b (simulates the metadata caching
# optimization reusing metadata from builder_a's group).
blk_table = torch.randint(
0, 100, (num_reqs, max_blocks), dtype=torch.int32, device=device
)
slot_mapping = torch.zeros(num_reqs, dtype=torch.int64, device=device)
metadata_b = builder_b.update_block_table(metadata_a, blk_table, slot_mapping)
# block_idx tensors must live in builder_b's persistent buffers.
def shares_storage(tensor, buffer):
return (
tensor.untyped_storage().data_ptr() == buffer.untyped_storage().data_ptr()
)
assert shares_storage(
metadata_b.block_idx_last_scheduled_token,
builder_b.block_idx_last_scheduled_token,
), "block_idx_last_scheduled_token not in builder_b's persistent buffer"
assert shares_storage(
metadata_b.block_idx_last_computed_token,
builder_b.block_idx_last_computed_token,
), "block_idx_last_computed_token not in builder_b's persistent buffer"
# Must NOT point to builder_a's buffers.
assert not shares_storage(
metadata_b.block_idx_last_scheduled_token,
builder_a.block_idx_last_scheduled_token,
), "block_idx_last_scheduled_token still points to builder_a's buffer"
# Values must be correct (copied from metadata_a).
torch.testing.assert_close(
metadata_b.block_idx_last_scheduled_token,
block_idx_vals,
)
torch.testing.assert_close(
metadata_b.block_idx_last_computed_token,
block_idx_vals,
)
def test_state_indices_tensor_d_includes_num_speculative_blocks():
"""Regression test for https://github.com/vllm-project/vllm/issues/39809
bug 1: with mamba_cache_mode='all' and speculative decoding enabled,
the cudagraph buffer for state_indices_tensor_d must allocate the same
per-request column count as the runtime block table, which includes
num_speculative_blocks trailing scratch columns."""
block_size = 16
max_model_len = 256
max_num_seqs = 4
num_speculative_tokens = 1
num_speculative_blocks = 2
device = torch.device("cpu")
vllm_config = _make_vllm_config(
max_model_len,
max_num_seqs,
num_speculative_tokens=num_speculative_tokens,
)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
num_speculative_blocks=num_speculative_blocks,
)
builder = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
expected_cols = (max_model_len // block_size) + num_speculative_blocks
assert builder.state_indices_tensor_d.shape == (max_num_seqs, expected_cols)
def test_block_idx_cudagraph_capture_padded_by_num_reqs():
"""Regression test for https://github.com/vllm-project/vllm/issues/39809
bug 2: with mamba_cache_mode='all' and spec decode, _update_metadata_for
_cudagraph_capture must slice block_idx_last_{scheduled,computed}_token
by the request count (padded_bs == num_reqs), not by num_decode_tokens.
Past num_decodes, the slice must be zero-filled."""
block_size = 16
max_model_len = 256
max_num_seqs = 8
num_speculative_tokens = 1
device = torch.device("cpu")
vllm_config = _make_vllm_config(
max_model_len,
max_num_seqs,
num_speculative_tokens=num_speculative_tokens,
)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
num_speculative_blocks=2,
)
builder = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
builder.block_idx_last_scheduled_token.fill_(-1)
builder.block_idx_last_computed_token.fill_(-1)
num_decodes = 2
num_reqs = 3
num_decode_tokens = num_decodes * (1 + num_speculative_tokens)
seq_lens = torch.full((num_reqs,), 64, dtype=torch.int32, device=device)
block_idx_vals = torch.tensor([3, 5], dtype=torch.int32, device=device)
state_indices_d = torch.zeros(
(num_decodes, builder.state_indices_tensor_d.shape[1]),
dtype=torch.int32,
device=device,
)
query_start_loc_d = torch.arange(
num_decodes + 1, dtype=torch.int32, device=device
) * (1 + num_speculative_tokens)
num_accepted_tokens = torch.ones(num_decodes, dtype=torch.int32, device=device)
metadata = BaseMambaAttentionMetadata(
num_prefills=0,
num_prefill_tokens=0,
num_decodes=num_decodes,
num_decode_tokens=num_decode_tokens,
num_reqs=num_reqs,
has_initial_states_p=None,
query_start_loc_p=None,
num_computed_tokens_p=None,
state_indices_tensor_p=None,
state_indices_tensor_d=state_indices_d,
query_start_loc_d=query_start_loc_d,
num_accepted_tokens=num_accepted_tokens,
block_idx_last_scheduled_token=block_idx_vals,
block_idx_first_scheduled_token_p=None,
block_idx_last_computed_token=block_idx_vals,
block_idx_last_scheduled_token_prev_step=None,
seq_lens=seq_lens,
)
out = builder._update_metadata_for_cudagraph_capture(metadata)
assert out.block_idx_last_scheduled_token.shape == (num_reqs,)
assert out.block_idx_last_computed_token.shape == (num_reqs,)
torch.testing.assert_close(
out.block_idx_last_scheduled_token[:num_decodes], block_idx_vals
)
torch.testing.assert_close(
out.block_idx_last_computed_token[:num_decodes], block_idx_vals
)
assert torch.all(out.block_idx_last_scheduled_token[num_decodes:] == 0)
assert torch.all(out.block_idx_last_computed_token[num_decodes:] == 0)
def test_block_idx_prev_step_persistent_buffer_allocated():
"""With mamba_cache_mode='all' + spec decode, the builder must allocate
block_idx_last_scheduled_token_prev_step as a persistent buffer with the
same shape as the existing block_idx_last_{scheduled,computed}_token
buffers, so cudagraph capture records a stable pointer for the prev-step
input anchor consumed by mamba_mixer2's input gather."""
block_size = 16
max_model_len = 256
max_num_seqs = 8
num_speculative_tokens = 1
device = torch.device("cpu")
vllm_config = _make_vllm_config(
max_model_len,
max_num_seqs,
num_speculative_tokens=num_speculative_tokens,
)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
num_speculative_blocks=2,
)
builder = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
assert hasattr(builder, "block_idx_last_scheduled_token_prev_step")
assert builder.block_idx_last_scheduled_token_prev_step.shape == (max_num_seqs,)
assert builder.block_idx_last_scheduled_token_prev_step.dtype == torch.int32
def test_block_idx_prev_step_persistent_buffer_skipped_without_spec_decode():
"""Without spec decode, the prev-step buffer is unused and must not be
allocated — the input anchor reduces to last_computed_token."""
block_size = 16
max_model_len = 256
max_num_seqs = 8
device = torch.device("cpu")
vllm_config = _make_vllm_config(
max_model_len, max_num_seqs, num_speculative_tokens=0
)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
)
builder = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
assert not hasattr(builder, "block_idx_last_scheduled_token_prev_step")
def test_block_idx_prev_step_cudagraph_capture_uses_persistent_buffer():
"""_update_metadata_for_cudagraph_capture must copy the prev-step anchor
into the builder's persistent buffer (so cudagraph replay reads from the
same underlying memory), pad past num_decodes with zero, and return a
slice of the persistent buffer in the metadata."""
block_size = 16
max_model_len = 256
max_num_seqs = 8
num_speculative_tokens = 1
device = torch.device("cpu")
vllm_config = _make_vllm_config(
max_model_len,
max_num_seqs,
num_speculative_tokens=num_speculative_tokens,
)
spec = MambaSpec(
block_size=block_size,
shapes=((1,), (1,)),
dtypes=(torch.float32,),
mamba_cache_mode="all",
num_speculative_blocks=2,
)
builder = MockMambaBuilder(spec, ["layer0"], vllm_config, device)
builder.block_idx_last_scheduled_token.fill_(-1)
builder.block_idx_last_computed_token.fill_(-1)
builder.block_idx_last_scheduled_token_prev_step.fill_(-1)
num_decodes = 2
num_reqs = 3
num_decode_tokens = num_decodes * (1 + num_speculative_tokens)
seq_lens = torch.full((num_reqs,), 64, dtype=torch.int32, device=device)
block_idx_vals = torch.tensor([3, 5], dtype=torch.int32, device=device)
prev_step_vals = torch.tensor([2, 4], dtype=torch.int32, device=device)
state_indices_d = torch.zeros(
(num_decodes, builder.state_indices_tensor_d.shape[1]),
dtype=torch.int32,
device=device,
)
query_start_loc_d = torch.arange(
num_decodes + 1, dtype=torch.int32, device=device
) * (1 + num_speculative_tokens)
num_accepted_tokens = torch.ones(num_decodes, dtype=torch.int32, device=device)
metadata = BaseMambaAttentionMetadata(
num_prefills=0,
num_prefill_tokens=0,
num_decodes=num_decodes,
num_decode_tokens=num_decode_tokens,
num_reqs=num_reqs,
has_initial_states_p=None,
query_start_loc_p=None,
num_computed_tokens_p=None,
state_indices_tensor_p=None,
state_indices_tensor_d=state_indices_d,
query_start_loc_d=query_start_loc_d,
num_accepted_tokens=num_accepted_tokens,
block_idx_last_scheduled_token=block_idx_vals,
block_idx_first_scheduled_token_p=None,
block_idx_last_computed_token=block_idx_vals,
block_idx_last_scheduled_token_prev_step=prev_step_vals,
seq_lens=seq_lens,
)
out = builder._update_metadata_for_cudagraph_capture(metadata)
# Output field exists and is identity-shared with the persistent buffer.
assert out.block_idx_last_scheduled_token_prev_step is not None
assert (
out.block_idx_last_scheduled_token_prev_step.untyped_storage().data_ptr()
== builder.block_idx_last_scheduled_token_prev_step.untyped_storage().data_ptr()
), (
"prev-step buffer must live in the builder's persistent buffer, not "
"in the caller-provided tensor"
)
# Padded by num_reqs (not num_decode_tokens) — same fix as bug 2 for the
# other block_idx_* fields.
assert out.block_idx_last_scheduled_token_prev_step.shape == (num_reqs,)
# First num_decodes values: input values copied through.
torch.testing.assert_close(
out.block_idx_last_scheduled_token_prev_step[:num_decodes],
prev_step_vals,
)
# Tail values past num_decodes: zero-filled padding for cudagraph capture.
assert torch.all(out.block_idx_last_scheduled_token_prev_step[num_decodes:] == 0)
def test_num_state_writes_p_matches_block_idx_tensors():
"""The prefill state save sizes its batched copy from
num_state_writes_p instead of reading the block index tensors back from
the GPU, so the host count must equal what those tensors say."""
# (block_size, seq_lens, query_lens, is_prefilling)
cases = [
# block-aligned and unaligned computed tokens, and a chunked prefill
(16, [64, 33, 17], [48, 17, 1], [True, True, True]),
(32, [200, 100, 64], [200, 36, 64], [True, True, True]),
# decode rows ahead of the prefills
(16, [40, 41, 100, 200], [1, 1, 60, 200], [False, False, True, True]),
# prefills that stay inside their first block: nothing to write
(16, [65, 66, 67], [1, 2, 3], [True, True, True]),
]
for block_size, seq_lens, query_lens, is_prefilling in cases:
metadata = MockMambaBuilder.build_mamba_metadata(
_make_vllm_config(4096, len(seq_lens), block_size=block_size),
seq_lens=seq_lens,
query_lens=query_lens,
is_prefilling=is_prefilling,
)
num_reqs, num_prefills = metadata.num_reqs, metadata.num_prefills
block_idx_last_p = metadata.block_idx_last_scheduled_token[
num_reqs - num_prefills : num_reqs
]
expected = int(
(block_idx_last_p - metadata.block_idx_first_scheduled_token_p)
.clamp(min=0)
.sum()
)
assert metadata.num_state_writes_p == expected, (
f"seq_lens={seq_lens} query_lens={query_lens} block_size={block_size}"
)
@@ -511,14 +511,14 @@ class TestMLAPrefillBackendParsing:
def test_valid_string_parses_to_enum(self):
config = AttentionConfig(
mla_prefill_backend="FLASH_ATTN", # type: ignore[arg-type]
mla_prefill_backend="FLASH_ATTN",
)
assert config.mla_prefill_backend == MLAPrefillBackendEnum.FLASH_ATTN
def test_invalid_string_raises_error(self):
with pytest.raises(ValueError, match="Unknown MLA prefill backend"):
AttentionConfig(
mla_prefill_backend="NONEXISTENT", # type: ignore[arg-type]
mla_prefill_backend="NONEXISTENT",
)
@@ -16,6 +16,8 @@ from tests.v1.attention.utils import (
create_common_attn_metadata,
create_vllm_config,
)
from vllm.config import SpeculativeConfig
from vllm.config.compilation import CUDAGraphMode
from vllm.config.mamba import MambaBackendEnum
from vllm.v1.kv_cache_interface import MambaSpec
@@ -191,9 +193,12 @@ REPLAYSSM_BUILD_CASES = {
def _make_mamba_spec(
buffer_len: int,
mamba_backend: MambaBackendEnum,
num_speculative_tokens: int = 0,
) -> MambaSpec:
ring_buffer_len = buffer_len + (
1 if mamba_backend == MambaBackendEnum.FLASHINFER else 0
1 + num_speculative_tokens
if mamba_backend == MambaBackendEnum.FLASHINFER
else 0
)
shapes = (
(1, 1),
@@ -214,6 +219,7 @@ def _create_replayssm_builder(
mamba_cache_mode: str = "none",
*,
mamba_backend: MambaBackendEnum = MambaBackendEnum.TRITON,
num_speculative_tokens: int = 0,
) -> MockMambaBuilder:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B", block_size=BLOCK_SIZE
@@ -224,21 +230,32 @@ def _create_replayssm_builder(
vllm_config.cache_config.replayssm_buffer_len = buffer_len
vllm_config.cache_config.mamba_cache_mode = mamba_cache_mode
vllm_config.mamba_config.backend = mamba_backend
if num_speculative_tokens > 0:
# Triton ReplaySSM requires exact synchronous CPU metadata.
vllm_config.scheduler_config.async_scheduling = False
vllm_config.speculative_config = SpeculativeConfig(
method="ngram",
num_speculative_tokens=num_speculative_tokens,
)
return MockMambaBuilder(
_make_mamba_spec(buffer_len, mamba_backend),
_make_mamba_spec(buffer_len, mamba_backend, num_speculative_tokens),
["layer0"],
vllm_config,
DEVICE,
)
def _build(builder: MockMambaBuilder, case: ReplaySSMBuildCase):
def _build(
builder: MockMambaBuilder,
case: ReplaySSMBuildCase,
num_accepted_tokens: torch.Tensor | None = None,
):
batch = BatchSpec(seq_lens=case.seq_lens, query_lens=case.query_lens)
common = create_common_attn_metadata(batch, BLOCK_SIZE, DEVICE).replace(
is_prefilling=torch.tensor(case.is_prefilling, dtype=torch.bool),
replayssm_decode_base_cpu=torch.tensor(case.decode_base, dtype=torch.int32),
)
return builder.build(0, common)
return builder.build(0, common, num_accepted_tokens=num_accepted_tokens)
@pytest.mark.parametrize(
@@ -270,21 +287,60 @@ def test_resumed_request_differs_from_fresh():
assert meta.is_flush_d.tolist()[:2] == [0, 0]
def test_flashinfer_replayssm_scratch_metadata_fresh_decode():
checkpointing_ssu = pytest.importorskip("flashinfer.mamba.checkpointing_ssu")
if not hasattr(checkpointing_ssu, "allocate_checkpointing_ssu_scratch"):
pytest.skip("FlashInfer does not expose ReplaySSM scratch allocation")
def test_spec_decode_single_token_chunk_synthesizes_acceptance_metadata():
builder = _create_replayssm_builder(16, num_speculative_tokens=3)
case = REPLAYSSM_BUILD_CASES["leftover_prompt_one_token_flush"]
builder = _create_replayssm_builder(16, mamba_backend=MambaBackendEnum.FLASHINFER)
case = REPLAYSSM_BUILD_CASES["fresh_decode"]
meta = _build(builder, case)
assert meta.write_pos_d is None
assert meta.is_flush_d is None
assert meta.bc_pre_scratch is None
assert meta.replayssm_scratch is not None
assert [tensor.shape for tensor in meta.replayssm_scratch] == [
(1, 1, 32, 8),
(1, 1, 16),
(1, 1, 32, 8),
]
assert meta.query_start_loc_d is not None
assert meta.query_start_loc_d.tolist() == [0, 1]
assert meta.num_accepted_tokens is not None
assert meta.num_accepted_tokens.tolist() == [1]
def test_flashinfer_replayssm_state_indices_are_stable_for_full_cudagraph():
checkpointing_ssu = pytest.importorskip("flashinfer.mamba.checkpointing_ssu")
if not hasattr(checkpointing_ssu, "allocate_checkpointing_ssu_scratch"):
pytest.skip("requires FlashInfer ReplaySSM autotuning support")
builder = _create_replayssm_builder(
16,
mamba_backend=MambaBackendEnum.FLASHINFER,
num_speculative_tokens=3,
)
builder.compilation_config.cudagraph_mode = CUDAGraphMode.FULL
first = _build(
builder,
ReplaySSMBuildCase(
seq_lens=[106, 106],
query_lens=[1, 1],
is_prefilling=[False, False],
decode_base=[100, 100],
buffer_len=16,
expected_write_pos=[],
expected_is_flush=[],
),
)
first_indices = first.replayssm_state_indices_d
assert first_indices is not None
assert first_indices.is_contiguous()
first_ptr = first_indices.data_ptr()
second = _build(
builder,
ReplaySSMBuildCase(
seq_lens=[122, 122],
query_lens=[1, 1],
is_prefilling=[False, False],
decode_base=[116, 116],
buffer_len=16,
expected_write_pos=[],
expected_is_flush=[],
),
)
second_indices = second.replayssm_state_indices_d
assert second_indices is not None
assert second_indices.data_ptr() == first_ptr
assert torch.equal(second_indices, second.state_indices_tensor_d[:, 0])
@@ -56,12 +56,21 @@ class _ExpandPageIndicesKernel:
self,
page_indices,
block_table_tensor,
stride,
stride_0,
stride_1,
paged_kv_indptr,
*,
KERNEL_BLOCK_SIZE,
BLOCK_SIZE,
):
# Both block-table strides are passed explicitly: the kernel no longer
# assumes the column stride is 1. This stand-in indexes the tensor
# directly so torch applies the strides for it, but the values are
# checked against the tensor actually handed in -- a caller passing the
# wrong stride is exactly the bug the parameter exists to prevent, and
# silently ignoring them here would hide it.
assert stride_0 == block_table_tensor.stride(0)
assert stride_1 == block_table_tensor.stride(1)
self.kernel_block_size = KERNEL_BLOCK_SIZE
for req_idx in range(self.grid[0]):
out_start = int(paged_kv_indptr[req_idx].item())
@@ -1052,7 +1061,14 @@ def test_decode_expands_kernel_block_page_indices(monkeypatch):
metadata.paged_kv_indices[: expected_indices.numel()],
expected_indices,
)
assert expand_kernel.grid == (seq_lens.numel(),)
# The launch now carries a second grid dimension over token chunks, so
# the expansion is spread across the context instead of one workgroup
# walking it serially. The width comes from the block-table upper bound
# on tokens per request, which is available host-side and so costs no
# device sync; derived here rather than hard-coded so the assertion
# still describes the launch if the chunk size changes.
expected_chunks = max(1, -(-block_table.shape[1] * kernel_block_size // 1024))
assert expand_kernel.grid == (seq_lens.numel(), expected_chunks)
assert expand_kernel.kernel_block_size == kernel_block_size
@@ -8,6 +8,7 @@ import torch
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.attention.backends.mla import rocm_aiter_mla_sparse as sparse_mod
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
_use_rocm_sparse_triton,
@@ -26,6 +27,26 @@ def _store_sparse_kv_row_offset_kernel(slot_ptr, output_ptr, stride: tl.constexp
tl.store(output_ptr, _sparse_kv_row_offset(slot, stride))
def _fit_kpool_indices_reference(
token_indices: torch.Tensor, topk_tokens: int
) -> torch.Tensor:
history = token_indices[:, :topk_tokens]
tail = token_indices[:, topk_tokens:]
valid_history = (history >= 0).sum(dim=1)
valid_tail = (tail >= 0).sum(dim=1)
keep_history = torch.minimum(valid_history, topk_tokens - valid_tail)
columns = torch.arange(topk_tokens, device=token_indices.device).unsqueeze(0)
tail_offsets = columns - keep_history.unsqueeze(1)
tail_values = torch.gather(
tail, 1, tail_offsets.clamp(min=0, max=tail.shape[1] - 1)
)
output = torch.where(columns < keep_history.unsqueeze(1), history, tail_values)
valid_output = columns < (keep_history + valid_tail).unsqueeze(1)
return torch.where(valid_output, output, -1)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
def test_fit_kpool_indices_preserves_tail_and_best_history():
token_indices = torch.tensor(
[
@@ -34,6 +55,7 @@ def test_fit_kpool_indices_preserves_tail_and_best_history():
[-1, -1, -1, -1, -1, -1, -1, -1],
],
dtype=torch.int32,
device="cuda",
)
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=6)
@@ -45,6 +67,28 @@ def test_fit_kpool_indices_preserves_tail_and_best_history():
]
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
@pytest.mark.parametrize(
("num_tokens", "topk_tokens", "tail_width"),
[(1, 4, 1), (7, 6, 2), (13, 128, 128), (3, 2048, 128)],
)
def test_fit_kpool_indices_matches_eager_reference(num_tokens, topk_tokens, tail_width):
"""The Triton fit must reproduce the eager packing rule exactly."""
set_random_seed(topk_tokens + num_tokens)
width = topk_tokens + tail_width
token_indices = torch.randint(0, 4096, (num_tokens, width), dtype=torch.int32)
valid = torch.rand((num_tokens, width)) < 0.5
valid[0] = False
valid[-1] = True
token_indices = torch.where(valid, token_indices, -1).cuda()
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=topk_tokens)
torch.testing.assert_close(
fitted, _fit_kpool_indices_reference(token_indices, topk_tokens)
)
def test_fit_kpool_indices_exact_width_is_noop():
token_indices = torch.tensor([[3, 2, 1, -1]], dtype=torch.int32)
@@ -0,0 +1,162 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""The ROCm MXFP4 indexer reads the paged cache in place, so each prefill
chunk is split back into its requests' rows, which one launch finds through
the chunk's query_start_loc. A chunk is whole requests or one query slice of a
long request, and both have to come back with the right rows and the right
block-table rows.
"""
import pytest
import torch
from vllm.platforms import current_platform
if not current_platform.is_rocm():
pytest.skip("ROCm-only", allow_module_level=True)
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerPrefillChunkMetadata,
)
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
native_decode,
plan_gather_launches,
plan_prefill_chunks,
split_prefill_chunks,
)
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import rocm_mxfp4_consumer_rows
def _chunk(block_table, token_start, token_end, row_ends):
ends = torch.tensor(row_ends, dtype=torch.int32)
return DeepseekV32IndexerPrefillChunkMetadata(
block_table=block_table,
cu_seqlen_ks=torch.full_like(ends, 7),
cu_seqlen_ke=ends + 7,
cu_seq_lens=torch.zeros(1, dtype=torch.int32),
token_to_seq=torch.zeros(1, dtype=torch.int32),
total_seq_lens=1,
token_start=token_start,
token_end=token_end,
num_reqs=block_table.shape[0],
)
# A decode (1 token), then prefills of 3, 3, 5 and 6 query tokens; the last
# one is sliced into two chunks.
QUERY_START_LOC = [0, 1, 4, 7, 12, 18]
SEQ_LENS = torch.tensor([40, 10, 12, 21, 64])
BLOCK_TABLE = torch.arange(20, dtype=torch.int32).view(5, 4)
CHUNKS = [
_chunk(BLOCK_TABLE[1:4], 1, 12, list(range(11))),
_chunk(BLOCK_TABLE[4:5], 12, 15, [29, 30, 30]),
_chunk(BLOCK_TABLE[4:5], 15, 18, [31, 31, 32]),
]
def _plans(min_gather_width, block=8):
return plan_prefill_chunks(
CHUNKS,
QUERY_START_LOC,
SEQ_LENS,
SEQ_LENS.int() // 2,
2,
block,
min_gather_width,
torch.tensor(QUERY_START_LOC, dtype=torch.int32),
)
def test_chunks_split_into_requests():
plans = _plans(20.0)
assert [p.requests for p in plans] == [
[(0, 3, 0), (3, 6, 1), (6, 11, 2)],
[(0, 3, 0)],
[(0, 3, 0)],
]
# every chunk launches once, with offsets local to the chunk
assert [p.query_start_loc.tolist() for p in plans] == [
[0, 3, 6, 11],
[0, 3],
[0, 3],
]
# the logits are as wide as the longest compressed context in the chunk
assert [p.width for p in plans] == [10, 32, 32]
assert [p.context_lens.tolist() for p in plans] == [[5, 6, 10], [32], [32]]
torch.testing.assert_close(plans[2].row_ends, torch.tensor([31, 31, 32]).int())
torch.testing.assert_close(plans[2].block_ends, torch.tensor([4, 4, 4]).int())
assert [p.use_gather for p in plans] == [False, True, True]
assert [p.first_request for p in plans] == [1, 4, 4]
# no candidate blocks, as in the model-neutral builder
for plan in _plans(None, block=0):
assert plan.block_ends is None and not plan.use_gather
def test_launches_follow_the_logits_budget(monkeypatch):
"""Each launch's fp32 logits fit in VLLM_SPARSE_INDEXER_MAX_LOGITS_MB. A dense
chunk's logits are [rows, longest context in the chunk]: K is read in place,
not gathered, so requests share a launch until their rows no longer fit, and
a request that does not fit alone is split on its query rows. A consumer's
logits are [rows, pool]."""
budget = 4 * 1000 * 30
contexts, queries = torch.tensor([1000, 600, 200]), torch.tensor([10, 10, 10])
assert split_prefill_chunks(contexts, queries, budget, 2) == [
(slice(2, 5), slice(0, 30))
]
# the third request would take the chunk past the budget
queries = torch.tensor([10, 10, 11])
assert split_prefill_chunks(contexts, queries, budget) == [
(slice(0, 2), slice(0, 20)),
(slice(2, 3), slice(0, 11)),
]
assert split_prefill_chunks(torch.tensor([1000]), torch.tensor([100]), budget) == [
(slice(0, 1), slice(lo, min(lo + 30, 100))) for lo in range(0, 100, 30)
]
# the default 512 MiB holds 128 rows of a 1M context, or 8192 of a 16K pool
assert split_prefill_chunks(
torch.tensor([1 << 20]), torch.tensor([200]), 512 << 20
) == [(slice(0, 1), slice(0, 128)), (slice(0, 1), slice(128, 200))]
monkeypatch.setenv("VLLM_SPARSE_INDEXER_MAX_LOGITS_MB", "512")
assert rocm_mxfp4_consumer_rows(16384) == 8192
def test_gather_launches_rejoin_a_requests_rows():
"""The consumers' logits are [rows, pool] whatever the context, so a
request's rows go back together across the chunks that cut them, and a
launch never mixes requests."""
# the first chunk is too narrow to gather, the last request's slices rejoin
(joined,) = plan_gather_launches(CHUNKS, _plans(20.0), 100)
assert (joined.token_start, joined.token_end) == (12, 18)
# every chunk gathers: the first chunk's three requests launch apart
launches = plan_gather_launches(CHUNKS, _plans(0.0), 100)
assert [(g.token_start, g.token_end) for g in launches] == [
(1, 4),
(4, 7),
(7, 12),
(12, 18),
]
assert plan_gather_launches(CHUNKS, _plans(None), 100) == []
def test_decode_launches_native_on_uniform_steps():
"""A decode step goes to the kernel as next_n-row sequences only when its
shape says so: each request has next_n rows, and cudagraph padding (query
length 0) comes only after them. A FULL graph captured on a uniform batch
then replays the same launch on a padded one."""
rows = torch.zeros(8, dtype=torch.int32)
row_block_table = torch.arange(32, dtype=torch.int32).view(8, 4)
context_lens = torch.tensor([9, 4, 7, 0, 5], dtype=torch.int32)
native = native_decode(rows, row_block_table, [2, 2, 2, 0], 2, context_lens)
assert native is not None and native.next_n == 2
assert native.context_lens.tolist() == [9, 4, 7, 0]
# every request's first flattened row, as a view
assert native.block_table.tolist() == row_block_table[::2].tolist()
assert native.block_table.data_ptr() == row_block_table.data_ptr()
assert native_decode(rows, row_block_table, [2, 0, 2, 2], 2, context_lens) is None
# a ragged step, rows padded past the requests, and no speculation
assert native_decode(rows[:5], row_block_table, [2, 1, 2], 2, context_lens) is None
assert native_decode(rows, row_block_table, [2, 2, 2], 2, context_lens) is None
assert native_decode(rows[:4], row_block_table, [1] * 4, 1, context_lens) is None
+313 -123
View File
@@ -68,10 +68,10 @@ from vllm.utils.torch_utils import current_stream
from vllm.v1.attention.backends.mla import index_group as index_group_module
from vllm.v1.attention.backends.mla.flashattn_mla_sparse import (
FlashAttnMLASparseImpl,
FlashAttnMLASparseMetadataBuilder,
)
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseImpl,
FlashInferMLASparseMetadataBuilder,
FlashInferMLASparseTRTLLMBackend,
)
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm120 import (
@@ -1880,11 +1880,13 @@ def _make_hisparse_runtime(
block_size: int = 64,
max_swap_rows: int | None = None,
index_group: hisparse_runtime.HiSparseIndexGroup | None = None,
max_union_rows: int | None = None,
) -> HiSparseRuntime:
runtime = HiSparseRuntime(
config=ResolvedHiSparseConfig(
top_k=top_k,
device_buffer_size=device_buffer_size,
max_union_rows=max_union_rows or device_buffer_size,
),
max_num_reqs=max_num_reqs,
row_width=row_width,
@@ -1941,6 +1943,10 @@ def _make_hisparse_cache_handle(
return HiSparseCacheHandle(runtime)
def _valid_rows(num_rows: int) -> torch.Tensor:
return torch.tensor([num_rows], dtype=torch.int32, device=DEVICE_TYPE)
@requires_hisparse_ops
def test_hisparse_uses_graph_stable_request_state_mapping():
device = torch.device(DEVICE_TYPE)
@@ -1967,6 +1973,7 @@ def test_hisparse_uses_graph_stable_request_state_mapping():
block_table=torch.tensor([[1]], dtype=torch.int32, device=device),
logical_topk_indices=torch.tensor([[0]], dtype=torch.int32, device=device),
block_size=block_size,
num_valid_rows=_valid_rows(1),
)
torch.accelerator.synchronize()
@@ -2009,12 +2016,263 @@ def test_hisparse_maps_speculative_rows_through_request_state():
block_table=torch.zeros((1, 1), dtype=torch.int32, device=device),
logical_topk_indices=torch.zeros((4, 1), dtype=torch.int32, device=device),
block_size=block_size,
num_valid_rows=_valid_rows(4),
)
torch.accelerator.synchronize()
assert physical.tolist() == [[block_size]] * 4
@requires_hisparse_ops
@pytest.mark.parametrize(
"num_rows,row_stride,top_k",
[(8, 128, 128), (4, 32, 128), (8, 2048, 2048)],
ids=["disjoint", "overlap", "long_mtp"],
)
def test_hisparse_speculative_rows_resolve_host_misses_consistently(
num_rows, row_stride, top_k
):
"""Verification rows of one request must agree on its hot-buffer slots.
Each row resolved residency in its own thread block against the request's
shared slot ownership and LRU, so rows missing on different host rows could
claim the same free slot. One row's hot index then pointed at a slot holding
another row's KV. Overlapping rows must share one slot per host row, and
long_mtp's rows span several resolution passes.
"""
device = torch.device(DEVICE_TYPE)
block_size, row_width = 64, 64
num_blocks = 2 * num_rows * top_k // block_size
kv_pool = torch.randn(
(num_blocks + 1, block_size, row_width), dtype=torch.float32
).pin_memory()
flat_pool = kv_pool.reshape(-1, row_width)
runtime = _make_hisparse_runtime(
top_k=top_k,
device_buffer_size=num_rows * top_k,
max_num_reqs=1,
row_width=row_width,
block_size=block_size,
max_swap_rows=num_rows,
)
runtime.bind_source_cache(kv_pool)
cache = HiSparseCacheHandle(runtime)
cache.all_context_pages_resident = False
block_table = torch.arange(
1, num_blocks + 1, dtype=torch.int32, device=device
).view(1, num_blocks)
req_ids = torch.zeros(num_rows, dtype=torch.int32, device=device)
rows = torch.arange(num_rows, dtype=torch.int32, device=device)[:, None]
base = torch.arange(top_k, dtype=torch.int32, device=device)[None, :]
for step in range(4):
runtime.begin_forward()
# Rows start row_stride apart (disjoint at row_stride == top_k) and
# shift by half a top-k per step: all misses first, then a mix.
topk = (rows * row_stride + base + step * (top_k // 2)) % (
num_blocks * block_size
)
hot_indices = cache.swap_in(
req_id_per_token=req_ids,
block_table=block_table,
logical_topk_indices=topk.clone(),
block_size=block_size,
num_valid_rows=_valid_rows(num_rows),
)
torch.accelerator.synchronize()
global_ref = _triton_convert_reference_impl(
req_ids, block_table, topk, block_size, top_k
)
gathered = runtime.hot.attention_cache.reshape(-1, row_width)[
hot_indices.to(torch.long)
].cpu()
torch.testing.assert_close(gathered, flat_pool[global_ref.cpu().to(torch.long)])
@requires_hisparse_ops
def test_hisparse_speculative_rows_count_a_shared_load_once():
"""A host row two verification rows select loads once; the reuse is a hit."""
device = torch.device(DEVICE_TYPE)
block_size, row_width, top_k = 64, 64, 128
num_blocks = top_k // block_size
kv_pool = torch.randn(
(num_blocks + 1, block_size, row_width), dtype=torch.float32
).pin_memory()
runtime = _make_hisparse_runtime(
top_k=top_k,
device_buffer_size=2 * top_k,
max_num_reqs=1,
row_width=row_width,
block_size=block_size,
max_swap_rows=2,
)
runtime.bind_source_cache(kv_pool)
cache = HiSparseCacheHandle(runtime)
cache.all_context_pages_resident = False
block_table = torch.arange(
1, num_blocks + 1, dtype=torch.int32, device=device
).view(1, num_blocks)
topk = torch.arange(top_k, dtype=torch.int32, device=device).repeat(2, 1)
runtime.begin_forward()
cache.swap_in(
req_id_per_token=torch.zeros(2, dtype=torch.int32, device=device),
block_table=block_table,
logical_topk_indices=topk,
block_size=block_size,
num_valid_rows=_valid_rows(2),
)
torch.accelerator.synchronize()
assert runtime.index_group.swap_stats.cpu().tolist() == [top_k, top_k]
@requires_hisparse_ops
def test_hisparse_resolver_reads_current_request_ids():
"""The resolver must see this call's request ids, not the previous call's.
It runs on the copy stream after waiting only on ``logical_topk_ready``,
which the indexer records before attention writes the ids. An MTP drafter
alternates four rows per request with one, so stale ids resolve rows
against other requests' KV. Stalling the compute stream exposes the race.
"""
device = torch.device(DEVICE_TYPE)
block_size, row_width, top_k, blocks_per_req, num_reqs = 64, 16, 64, 4, 2
kv_pool = torch.randn(
(num_reqs * blocks_per_req + 1, block_size, row_width), dtype=torch.float32
).pin_memory()
runtime = _make_hisparse_runtime(
top_k=top_k,
device_buffer_size=4 * top_k,
max_num_reqs=num_reqs,
row_width=row_width,
block_size=block_size,
max_swap_rows=4 * num_reqs,
)
runtime.bind_source_cache(kv_pool)
ready = torch.Event()
runtime.index_group.logical_topk_ready = ready
cache = HiSparseCacheHandle(runtime)
cache.all_context_pages_resident = False
cache.source_block_table = torch.arange(
1, num_reqs * blocks_per_req + 1, dtype=torch.int32, device=device
).view(num_reqs, blocks_per_req)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache]
index_group.physical_topk_indices = torch.empty(
(4 * num_reqs + 1, top_k), dtype=torch.int32, device=device
)
# Four rows per request, then one per request plus a CUDA-graph padding
# row, which maps to request 0 and must be skipped.
for rows_per_req, num_padding in ((4, 0), (1, 1)):
num_rows = num_reqs * rows_per_req
req_ids = torch.arange(num_reqs, dtype=torch.int32, device=device)
req_ids = torch.cat(
[
req_ids.repeat_interleave(rows_per_req),
torch.zeros(num_padding, dtype=torch.int32, device=device),
]
)
topk = torch.stack(
[
torch.randperm(blocks_per_req * block_size, device=device)[:top_k]
for _ in range(req_ids.numel())
]
).to(torch.int32)
query_start_loc = torch.arange(
0, num_rows + 1, rows_per_req, dtype=torch.int32, device=device
)
attn_metadata = SimpleNamespace(
req_id_per_token=req_ids,
query_start_loc=torch.cat([query_start_loc, query_start_loc[-1:]]),
block_size=block_size,
)
runtime.begin_forward()
ready.record(current_stream())
torch.cuda._sleep(200_000_000)
hot_indices = index_group.convert_logical_to_physical_topk(
0, topk, attn_metadata, block_stride_rows=None, return_valid_counts=False
)
torch.accelerator.synchronize()
assert (hot_indices[num_rows:] == -1).all()
global_ref = _triton_convert_reference_impl(
req_ids[:num_rows],
cache.source_block_table,
topk[:num_rows],
block_size,
top_k,
)
gathered = runtime.hot.attention_cache.reshape(-1, row_width)[
hot_indices[:num_rows].to(torch.long)
].cpu()
torch.testing.assert_close(
gathered, kv_pool.reshape(-1, row_width)[global_ref.cpu().to(torch.long)]
)
@requires_hisparse_ops
def test_hisparse_union_table_scales_with_union_bound():
"""Shared memory follows the per-request union bound, not the hot buffer.
Sizing the table from device_buffer_size needs ~340 KB here and fails.
"""
device = torch.device(DEVICE_TYPE)
block_size, row_width, top_k = 64, 64, 128
num_blocks = top_k // block_size
kv_pool = torch.randn(
(num_blocks + 1, block_size, row_width), dtype=torch.float32
).pin_memory()
runtime = _make_hisparse_runtime(
top_k=top_k,
device_buffer_size=32768,
max_union_rows=top_k,
max_num_reqs=1,
row_width=row_width,
block_size=block_size,
max_swap_rows=1,
)
runtime.bind_source_cache(kv_pool)
cache = HiSparseCacheHandle(runtime)
cache.all_context_pages_resident = False
req_ids = torch.zeros(1, dtype=torch.int32, device=device)
block_table = torch.arange(
1, num_blocks + 1, dtype=torch.int32, device=device
).view(1, num_blocks)
topk = torch.arange(top_k, dtype=torch.int32, device=device).view(1, top_k)
runtime.begin_forward()
hot_indices = cache.swap_in(
req_id_per_token=req_ids,
block_table=block_table,
logical_topk_indices=topk,
block_size=block_size,
num_valid_rows=_valid_rows(req_ids.numel()),
)
torch.accelerator.synchronize()
global_ref = _triton_convert_reference_impl(
req_ids, block_table, topk, block_size, top_k
)
gathered = runtime.hot.attention_cache.reshape(-1, row_width)[
hot_indices.to(torch.long)
].cpu()
torch.testing.assert_close(
gathered, kv_pool.reshape(-1, row_width)[global_ref.cpu().to(torch.long)]
)
@requires_hisparse_ops
def test_hisparse_rejects_union_bound_beyond_shared_memory():
"""An oversized union bound fails at construction, not on the first forward."""
with pytest.raises(ValueError, match="shared memory"):
_make_hisparse_runtime(top_k=2048, device_buffer_size=32768)
@requires_hisparse_ops
def test_hisparse_resident_rows_bypass_hot_lru():
device = torch.device(DEVICE_TYPE)
@@ -2054,6 +2312,7 @@ def test_hisparse_resident_rows_bypass_hot_lru():
block_table=source_table,
logical_topk_indices=topk,
block_size=block_size,
num_valid_rows=_valid_rows(request_ids.numel()),
return_valid_counts=True,
)
torch.accelerator.synchronize()
@@ -2117,6 +2376,7 @@ def test_hisparse_swap_in_preserves_rows_across_eviction():
block_table=block_table,
logical_topk_indices=topk.clone(),
block_size=block_size,
num_valid_rows=_valid_rows(req_ids.numel()),
return_valid_counts=True,
)
torch.accelerator.synchronize()
@@ -2198,6 +2458,7 @@ def test_hisparse_multi_step_swaps_match_independent():
req_id_per_token=req_ids,
block_table=block_table,
block_size=block_size,
num_valid_rows=_valid_rows(req_ids.numel()),
)
producer_indices = [
producer.swap_in(logical_topk_indices=topk.clone(), **kw) for topk in topks
@@ -2272,6 +2533,7 @@ def test_hisparse_multi_step_writes_request_major_output():
block_table,
logical[:, step],
block_size=block_size,
num_valid_rows=_valid_rows(request_ids.numel()),
return_valid_counts=True,
attention_indices_out=physical[:, step],
valid_counts_out=valid_counts[:, step],
@@ -2336,6 +2598,7 @@ def test_hisparse_kv_update_writes_resident_and_staging_caches():
layer = SimpleNamespace(
hisparse_cache=cache_handle,
use_pcp=False,
pcp_shard_decode_requests=False,
impl=impl,
)
mla_attention.MLAAttention.update_kv_cache(
@@ -2455,6 +2718,7 @@ def test_hisparse_remaps_strided_hma_rows_for_attention():
[[0, 1, 2, 3]], dtype=torch.int32, device=device
),
block_size=block_size,
num_valid_rows=_valid_rows(1),
)
assert runtime.hot.attention_cache is not None
@@ -2588,6 +2852,7 @@ def test_hisparse_newest_write_and_recycled_slot_invalidation():
block_table=block_table,
logical_topk_indices=topk,
block_size=block_size,
num_valid_rows=_valid_rows(req_ids.numel()),
)
torch.accelerator.synchronize()
stale_hot_slot = hot_indices[0, 0].item()
@@ -2603,6 +2868,7 @@ def test_hisparse_newest_write_and_recycled_slot_invalidation():
block_table=block_table,
logical_topk_indices=topk,
block_size=block_size,
num_valid_rows=_valid_rows(req_ids.numel()),
)
torch.accelerator.synchronize()
idx = hot_indices.cpu().tolist()[0][0]
@@ -3001,8 +3267,8 @@ def test_hisparse_gather_prefill_cache_prefers_resident_rows():
torch.testing.assert_close(staged_flat[i], expected)
def test_hisparse_fp8_decode_resolves_steps_then_runs_batched_attention(monkeypatch):
"""FP8 decode must use active dimensions when common metadata is padded."""
def test_hisparse_fp8_decode_resolves_rows_once_then_runs_batched_attention():
"""Verification rows resolve in one swap_in; FP8 attention sees them batched."""
device = torch.device("cpu")
num_decodes = 2
query_len = 3
@@ -3013,48 +3279,29 @@ def test_hisparse_fp8_decode_resolves_steps_then_runs_batched_attention(monkeypa
.view(-1, 1)
.expand(-1, 4)
)
steps: list[int] = []
kernel_shapes: list[torch.Size] = []
def swap_in(req_ids, *, logical_topk_indices, **kwargs): # noqa: ARG001
steps.append(int(logical_topk_indices[0, 0]))
output = kwargs["attention_indices_out"]
if output is not None:
output.copy_(logical_topk_indices + 10)
return topk[:num_decodes]
return logical_topk_indices + 10
def run_kernel(self, *, q, **kwargs): # noqa: ARG001
kernel_shapes.append(q.shape)
return q[..., :1], None
runtime = SimpleNamespace(
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device))
)
leader_cache = SimpleNamespace(
runtime=runtime,
source_block_table=torch.empty(
num_decodes, 1, dtype=torch.int32, device=device
cache = SimpleNamespace(
runtime=SimpleNamespace(
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device))
),
swap_in=MagicMock(side_effect=swap_in),
)
follower_cache = SimpleNamespace(
runtime=runtime,
source_block_table=torch.empty(
num_decodes, 1, dtype=torch.int32, device=device
),
swap_in=MagicMock(side_effect=swap_in),
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [leader_cache, follower_cache]
index_group.caches = [cache]
index_group.physical_topk_indices = torch.empty(
(num_tokens + 1, 4), dtype=torch.int32, device=device
)
index_group.valid_topk_counts = torch.empty(
num_tokens + 1, dtype=torch.int32, device=device
)
index_group.request_ids = torch.arange(
num_decodes, dtype=torch.int32, device=device
)
impl = SimpleNamespace(
kv_lora_rank=1,
index_group=index_group,
@@ -3062,84 +3309,50 @@ def test_hisparse_fp8_decode_resolves_steps_then_runs_batched_attention(monkeypa
)
impl._fp8_flash_mla_kernel = MethodType(run_kernel, impl)
metadata = SimpleNamespace(
num_decodes=num_tokens,
num_decode_tokens=num_tokens,
decode_max_query_len=1,
query_start_loc=torch.arange(
0,
num_tokens + 1,
query_len,
dtype=torch.int32,
device=device,
0, num_tokens + 1, query_len, dtype=torch.int32, device=device
),
block_table=torch.empty(num_decodes, 1, dtype=torch.int32, device=device),
req_id_per_token=torch.arange(
num_decodes, dtype=torch.int32, device=device
).repeat_interleave(query_len),
block_size=64,
)
output = FlashMLASparseImpl._host_backed_fp8_decode(
impl,
q,
topk,
metadata,
SimpleNamespace(),
num_decodes,
query_len,
impl, q, topk, metadata, SimpleNamespace(), num_decodes
)
assert steps == [0, 1, 2]
cache.swap_in.assert_called_once()
torch.testing.assert_close(
cache.swap_in.call_args.args[0], metadata.req_id_per_token
)
torch.testing.assert_close(
cache.swap_in.call_args.kwargs["logical_topk_indices"], topk
)
assert kernel_shapes == [(num_decodes, query_len, 2, 4)]
assert output.shape == (num_tokens, 2, 1)
torch.testing.assert_close(
index_group.physical_topk_indices[:num_tokens], topk + 10
def test_hisparse_keeps_speculative_rows_as_decodes():
"""HiSparse limits decodes to verification requests, not short extends.
FlashAttn sparse MLA used to classify MTP verification as prefill under
HiSparse, whose residency-dependent route a FULL CUDA graph freezes at
capture.
"""
builder = object.__new__(FlashAttnMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object()),
speculative_config=SimpleNamespace(
num_speculative_tokens=3, parallel_drafting=False
),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
use_v2_model_runner=True,
)
follower_indices = index_group.convert_decode_logical_to_physical_topk(
1,
topk,
metadata,
return_valid_counts=False,
num_decodes=num_decodes,
decode_query_len=query_len,
)
assert steps == [0, 1, 2, 0, 1, 2]
torch.testing.assert_close(follower_indices, topk + 10)
builder._init_reorder_batch_threshold(256, supports_spec_as_decode=True)
def test_hisparse_varlen_decode_uses_canonical_request_rows():
"""Graph metadata's query upper bound must preserve packed token rows."""
num_decodes = 2
topk = torch.arange(18, dtype=torch.int32).view(9, 2)
def swap_in(_request_ids, *, logical_topk_indices, **_kwargs):
return logical_topk_indices + 10
cache = SimpleNamespace(
source_block_table=torch.zeros((num_decodes, 1), dtype=torch.int32),
swap_in=MagicMock(side_effect=swap_in),
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache]
index_group.physical_topk_indices = torch.empty((10, 2), dtype=torch.int32)
index_group.valid_topk_counts = torch.empty(10, dtype=torch.int32)
index_group.request_ids = torch.arange(num_decodes, dtype=torch.int32)
metadata = SimpleNamespace(
num_decodes=num_decodes,
num_decode_tokens=topk.shape[0],
decode_max_query_len=15,
query_start_loc=torch.tensor([0, 8, 9], dtype=torch.int32),
block_size=64,
)
physical_topk = index_group.convert_decode_logical_to_physical_topk(
0,
topk,
metadata,
return_valid_counts=False,
)
torch.testing.assert_close(physical_topk, topk + 10)
request_rows = cache.swap_in.call_args_list[0].args[0]
torch.testing.assert_close(request_rows, index_group.request_ids)
assert builder.reorder_batch_threshold == 4
def test_flashinfer_hisparse_decode_runs_batched_attention():
@@ -3168,7 +3381,7 @@ def test_flashinfer_hisparse_decode_runs_batched_attention():
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache_handle]
index_group.convert_decode_logical_to_physical_topk = MethodType(
index_group.convert_logical_to_physical_topk = MethodType(
convert_decode, index_group
)
impl = object.__new__(FlashInferMLASparseImpl)
@@ -3200,7 +3413,7 @@ def test_flashattn_hisparse_decode_uses_index_group():
physical = topk.clone()
counts = torch.full((num_tokens,), 4, dtype=torch.int32, device=DEVICE_TYPE)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.convert_decode_logical_to_physical_topk = MagicMock(
index_group.convert_logical_to_physical_topk = MagicMock(
return_value=(physical, counts)
)
index_group.physical_kv_cache = MagicMock(
@@ -3223,7 +3436,7 @@ def test_flashattn_hisparse_decode_uses_index_group():
assert output.shape == (num_tokens, 2, 1)
assert lse is None
index_group.convert_decode_logical_to_physical_topk.assert_called_once()
index_group.convert_logical_to_physical_topk.assert_called_once()
impl._run_mqa_kernel.assert_called_once()
@@ -3233,9 +3446,7 @@ def test_flashinfer_sm120_hisparse_decode_uses_index_group():
topk = torch.zeros(num_tokens, 4, dtype=torch.int32, device=DEVICE_TYPE)
physical = topk.clone()
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.convert_decode_logical_to_physical_topk = MagicMock(
return_value=physical
)
index_group.convert_logical_to_physical_topk = MagicMock(return_value=physical)
index_group.physical_kv_cache = MagicMock(
return_value=torch.empty(1, device=DEVICE_TYPE)
)
@@ -3259,7 +3470,7 @@ def test_flashinfer_sm120_hisparse_decode_uses_index_group():
assert output.shape == (num_tokens, 2, 1)
assert lse is None
index_group.convert_decode_logical_to_physical_topk.assert_called_once()
index_group.convert_logical_to_physical_topk.assert_called_once()
impl._run_mqa_kernel.assert_called_once()
@@ -3291,27 +3502,6 @@ def test_hisparse_resident_prefill_uses_attention_block_stride():
assert index_group._convert_once.call_args.kwargs["block_stride_rows"] == 832
def test_hisparse_shared_sparse_builder_routes_multi_token_chunks_to_prefill():
"""Default sparse backends must route multi-token chunks to prefill."""
builder = object.__new__(FlashInferMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object()),
speculative_config=SimpleNamespace(
num_speculative_tokens=4,
parallel_drafting=False,
),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
)
builder._init_reorder_batch_threshold(
1024,
supports_spec_as_decode=True,
supports_dcp_with_varlen=True,
)
assert builder.reorder_batch_threshold == 1
def test_hisparse_flashmla_reorders_full_speculative_window_as_decode():
builder = object.__new__(FlashMLASparseMetadataBuilder)
builder.vllm_config = SimpleNamespace(
@@ -3453,7 +3643,7 @@ def test_flashmla_fp8_paths_accept_decode_subset(monkeypatch, use_mixed_batch: b
if use_mixed_batch:
fp8_metadata = FlashMLASparseMetadata.FP8KernelMetadata(
scheduler_metadata=object(), # type: ignore[arg-type]
scheduler_metadata=object(),
dummy_block_table=torch.empty(1, 1, dtype=torch.int32, device=DEVICE_TYPE),
cache_lens=torch.empty(1, dtype=torch.int32, device=DEVICE_TYPE),
)
@@ -3466,7 +3656,7 @@ def test_flashmla_fp8_paths_accept_decode_subset(monkeypatch, use_mixed_batch: b
num_prefill_tokens=num_batch_tokens - num_decode_tokens,
decode=FP8Meta.Decode(
seq_lens=torch.empty(1, dtype=torch.int32, device=DEVICE_TYPE),
kernel_metadata=object(), # type: ignore[arg-type]
kernel_metadata=object(),
decode_query_len=num_decode_tokens,
),
prefill=FP8Meta.Prefill(
@@ -3652,7 +3842,7 @@ def test_fp8_mixed_batch_dcp_neutralizes_empty_rows(monkeypatch):
metadata = SimpleNamespace(
fp8_extra_metadata=FlashMLASparseMetadata.FP8KernelMetadata(
scheduler_metadata=object(), # type: ignore[arg-type]
scheduler_metadata=object(),
dummy_block_table=torch.empty(1, 1, dtype=torch.int32, device=DEVICE_TYPE),
cache_lens=torch.empty(1, dtype=torch.int32, device=DEVICE_TYPE),
),
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
from vllm.config import CUDAGraphMode
from vllm.platforms import current_platform
from vllm.v1.attention.backends.triton_attn import TritonAttentionMetadataBuilder
from vllm.v1.attention.backends.triton_attn_diffkv import (
TritonAttentionDiffKVMetadataBuilder,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec
# 64 segments only while num_seqs * num_kv_heads * 16 < 188 SMs on SM12.0 and
# the 64-segment scratch holds every query token (e.g. multi-query verify).
@pytest.mark.parametrize(
"builder_cls",
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
)
@pytest.mark.parametrize(
"capability,num_kv_heads,num_seqs,query_len,segments",
[
((12, 0), 1, 11, 1, 64),
((12, 0), 1, 12, 1, 16),
((12, 0), 8, 1, 1, 64),
((12, 0), 8, 2, 1, 16),
((9, 0), 1, 1, 1, 16),
((12, 0), 1, 2, 4, 64),
((12, 0), 1, 10, 4, 16),
],
)
def test_split_k_segments_follow_sm_occupancy(
monkeypatch, builder_cls, capability, num_kv_heads, num_seqs, query_len, segments
):
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
monkeypatch.setattr(
current_platform, "is_device_capability", lambda cap: cap == capability
)
monkeypatch.setattr(current_platform, "num_compute_units", lambda: 188)
config = SimpleNamespace(
model_config=SimpleNamespace(
get_num_attention_heads=lambda _: 8,
get_num_kv_heads=lambda _: num_kv_heads,
get_head_size=lambda: 128,
rswa_window=None,
),
parallel_config=None,
scheduler_config=SimpleNamespace(max_num_seqs=16),
speculative_config=None,
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
),
)
spec = FullAttentionSpec(
block_size=16, num_kv_heads=num_kv_heads, head_size=128, dtype=torch.bfloat16
)
builder = builder_cls(spec, ["layer.0"], config, "cpu")
batch = BatchSpec(seq_lens=[128] * num_seqs, query_lens=[query_len] * num_seqs)
metadata = builder.build(0, create_common_attn_metadata(batch, 16, "cpu"))
assert metadata.num_par_softmax_segments == segments
assert metadata.softmax_segm_output.shape[2] == segments
assert metadata.softmax_segm_max.shape[0] >= num_seqs * query_len
# DiffKV re-allocates the output; it must stay sized like the base buffers.
assert builder.softmax_segm_output.shape[0] == builder.softmax_segm_max.shape[0]
assert (
metadata.softmax_segm_output.data_ptr()
== builder.softmax_segm_output.data_ptr()
)
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Integration tests for TRTLLM gen-full attention through FlashInfer."""
import dataclasses
import unittest.mock
from functools import partial
@@ -513,3 +514,50 @@ def test_trtllm_gen_nvfp4_kv_integration(batch_spec_name: str):
kv_cache_dtype="nvfp4",
model_name=MODEL_NVFP4,
)
@torch.inference_mode()
def test_trtllm_gen_draft_decode_metadata_tracks_in_place_seq_lens(
monkeypatch: pytest.MonkeyPatch,
):
"""Fused draft steps reuse the step-1 build after advancing seq_lens in
place, so its decode metadata must match the split path's step-2 rebuild."""
monkeypatch.setattr(
"vllm.utils.flashinfer.supports_trtllm_attention",
unittest.mock.Mock(return_value=True),
)
monkeypatch.setattr(
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
_mock_get_per_layer_parameters,
)
vllm_config = create_vllm_config(
model_name=MODEL, block_size=BLOCK_SIZE, num_gpu_blocks=NUM_GPU_BLOCKS
)
model_config = vllm_config.model_config
kv_cache_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=model_config.get_num_kv_heads(vllm_config.parallel_config),
head_size=model_config.get_head_size(),
dtype=model_config.dtype,
)
device = torch.device(f"{DEVICE_TYPE}:0")
with set_current_vllm_config(vllm_config):
builder = FlashInferMetadataBuilder(
kv_cache_spec, ["test_layer_0"], vllm_config, device
)
assert builder.supports_draft_decode_metadata_update
step1 = create_common_attn_metadata(BATCH_SPECS["decode_only"], BLOCK_SIZE, device)
reused = builder.build(common_prefix_len=0, common_attn_metadata=step1)
step1.seq_lens.add_(1)
step2 = dataclasses.replace(step1, seq_lens_cpu_upper_bound=step1.seq_lens.cpu())
rebuilt = builder.build(common_prefix_len=0, common_attn_metadata=step2)
assert isinstance(reused.decode, FlashInferTrtllmAPIDecode)
for field in dataclasses.fields(reused.decode):
value = getattr(reused.decode, field.name)
expected = getattr(rebuilt.decode, field.name)
if isinstance(value, torch.Tensor):
assert torch.equal(value, expected), field.name
else:
assert value == expected, field.name
@@ -0,0 +1,87 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import sys
from types import ModuleType, SimpleNamespace
import pytest
import torch
from torch._subclasses.fake_tensor import FakeTensorMode
from vllm.platforms import current_platform
from vllm.v1.attention.ops import vit_attn_wrappers
def _noncontiguous_bshd(device: torch.device | None = None) -> torch.Tensor:
return (
torch.arange(120, dtype=torch.float32, device=device)
.reshape(1, 3, 5, 8)
.transpose(1, 2)
)
def test_registered_attention_wrapper_fake_layouts():
with FakeTensorMode():
q = _noncontiguous_bshd()
cu_seqlens = torch.tensor([0, 5], dtype=torch.int32)
max_seqlen = torch.tensor(5, dtype=torch.int32)
flashinfer_cu_seqlens = torch.tensor([0, 5, 0, 5], dtype=torch.int32)
sequence_lengths = torch.tensor([5], dtype=torch.int32)
outputs = (
torch.ops.vllm.flash_attn_maxseqlen_wrapper(
q, q, q, 1, False, None, None, cu_seqlens, max_seqlen
),
torch.ops.vllm.triton_attn_wrapper(
q, q, q, 1, None, cu_seqlens, max_seqlen
),
torch.ops.vllm.torch_sdpa_wrapper(q, q, q, None, None, False),
torch.ops.vllm.flashinfer_wrapper(
q,
q,
q,
1.0,
torch.empty(1, dtype=torch.uint8),
flashinfer_cu_seqlens,
max_seqlen,
sequence_lengths,
None,
None,
None,
None,
),
)
assert all(output.is_contiguous() for output in outputs)
def test_aiter_flash_attn_omits_out_and_returns_contiguous_output(
monkeypatch: pytest.MonkeyPatch,
):
aiter = ModuleType("aiter")
def flash_attn_varlen_func(q, k, v, **kwargs):
assert "out" not in kwargs
return q
aiter.__dict__["flash_attn_varlen_func"] = flash_attn_varlen_func
monkeypatch.setitem(sys.modules, "aiter", aiter)
monkeypatch.setattr(
vit_attn_wrappers, "current_platform", SimpleNamespace(is_rocm=lambda: True)
)
q = _noncontiguous_bshd()
assert not q.is_contiguous()
output = vit_attn_wrappers.flash_attn_maxseqlen_wrapper(q, q, q, 1, True, None)
assert torch.equal(output, q)
assert output.is_contiguous()
@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="Requires GPU")
def test_sdpa_output_layout_without_cu_seqlens():
q = _noncontiguous_bshd(torch.device("cuda"))
output = vit_attn_wrappers.vit_torch_sdpa_wrapper(q, q, q)
assert output.is_contiguous()
@@ -13,6 +13,9 @@ import torch
from tests.v1.core.test_prefix_caching import make_kv_cache_manager, make_request
from vllm.distributed.kv_transfer.kv_connector.v1.base import SupportsHMA
from vllm.model_executor.layers.mamba.checkpoint import (
compute_mamba_prefill_checkpoints,
)
from vllm.utils.hashing import sha256
from vllm.v1.core.kv_cache_utils import (
KVCacheBlockCopy,
@@ -28,6 +31,7 @@ from vllm.v1.kv_cache_interface import (
KVCacheGroupSpec,
MambaSpec,
SlidingWindowSpec,
get_mamba_prefill_checkpoint_position,
)
@@ -686,6 +690,81 @@ def test_transient_checkpoint_evicts_retained_boundary_hash():
assert manager.block_pool.get_cached_block(checkpoint_hash, [1]) is None
@pytest.mark.parametrize("prompt_len", [120, 104, 96])
def test_prompt_end_checkpoint_survives_block_aligned_cache_count(prompt_len):
"""At the default match unit the hybrid coordinator hands ``cache_blocks``
a block-aligned token count, which is below the prompt length whenever the
prompt is not block-aligned. The prompt-end checkpoint is the replay
boundary and must stay published under retention_interval=0; only a
mid-prompt checkpoint is transient.
"""
hash_block_size = mamba_block_size = 32
manager = make_full_mamba_manager(
dcp_world_size=1,
hash_block_size=hash_block_size,
full_block_size=hash_block_size,
mamba_block_size=mamba_block_size,
num_prefill_checkpoint_blocks=1,
)
manager.coordinator.retention_interval = 0
assert not manager.coordinator.enable_partial_hash_hits
request = make_request("producer", list(range(prompt_len)), hash_block_size, sha256)
assert manager.allocate_slots(request, request.num_tokens) is not None
checkpoint_position = get_mamba_prefill_checkpoint_position(
prompt_len, hash_block_size, drop_eagle_block=False
)
checkpoint_hash = request.block_hashes[checkpoint_position // hash_block_size - 1]
hit = manager.block_pool.get_cached_block(checkpoint_hash, [1])
assert hit is not None
assert hit[0].block_hash_num_tokens == checkpoint_position
manager.free(request)
replay = make_request("replay", list(range(prompt_len)), hash_block_size, sha256)
_, num_computed, _ = manager.get_computed_blocks(replay)
assert num_computed == checkpoint_position
@pytest.mark.parametrize("retention_interval,reserved", [(None, True), (0, False)])
def test_intermediate_chunk_checkpoint_reserved_only_under_dense_retention(
retention_interval, reserved
):
"""A checkpoint inside a chunk that does not finish the prefill is only
publishable under dense retention. With retention_interval=0 it would be
evicted as transient, so the block is not reserved in the first place;
the prefill-end checkpoint is reserved either way.
"""
hash_block_size = 16
manager = make_full_mamba_manager(
dcp_world_size=1,
hash_block_size=hash_block_size,
full_block_size=hash_block_size,
mamba_block_size=32,
num_prefill_checkpoint_blocks=1,
)
manager.coordinator.retention_interval = retention_interval
mamba_manager = manager.coordinator.single_type_managers[1]
request = make_request("producer", list(range(240)), hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(request)
free_before = manager.block_pool.get_num_free_blocks()
# Mid-prompt chunk: the chunk-keyed position (112) is inside it. Blocks:
# the attention blocks, the running mamba block, plus the checkpoint.
assert manager.allocate_slots(request, 128, num_computed, computed_blocks)
assert (request.request_id in mamba_manager._checkpoints) == reserved
allocated = free_before - manager.block_pool.get_num_free_blocks()
assert allocated == 128 // hash_block_size + 1 + int(reserved)
request.num_computed_tokens = 128
manager.new_step_starts()
# Final chunk: the prefill-end checkpoint at 224 is reserved either way.
assert manager.allocate_slots(request, 112) is not None
assert mamba_manager._checkpoints[request.request_id][0] == 224
end_hash = request.block_hashes[224 // hash_block_size - 1]
assert manager.block_pool.get_cached_block(end_hash, [1]) is not None
def test_eagle_block_aligned_checkpoint_replaces_newer_hash():
hash_block_size = mamba_block_size = 32
manager = make_full_mamba_manager(
@@ -2531,3 +2610,105 @@ def test_boundary_states_offered_past_prompt_for_resumed_prefill():
offered = [b for _, _, b in drain_boundary_state_offloads(manager).get("0", [])]
assert 2 * block_size in offered
assert req0.num_prompt_tokens < 2 * block_size
def test_prompt_end_checkpoint_survives_sparse_retention_with_coarse_hash():
"""With hash_block_size == mamba block size (no fine-grained matching), the
hybrid coordinator caches the final chunk only up to its last full block,
so the managers see ``num_tokens < num_prompt_tokens`` there too. The
prompt-end checkpoint must still be published under retention_interval=0,
otherwise the next request that extends this prompt misses the prefix.
"""
block_size = 32
manager = make_full_mamba_manager(
dcp_world_size=1,
hash_block_size=block_size,
full_block_size=block_size,
mamba_block_size=block_size,
num_prefill_checkpoint_blocks=1,
)
manager.coordinator.retention_interval = 0
# 240 tokens: not block aligned, prompt-end checkpoint at 224.
request = make_request("producer", list(range(240)), block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(request)
assert manager.allocate_slots(request, 128, num_computed, computed_blocks)
request.num_computed_tokens = 128
manager.new_step_starts()
assert manager.allocate_slots(request, 112) is not None
end_hash = request.block_hashes[224 // block_size - 1]
assert manager.block_pool.get_cached_block(end_hash, [1]) is not None
# A request extending the prompt resumes from that checkpoint.
follower = make_request("follower", list(range(240)) + [7] * 40, block_size, sha256)
_, num_hit, _ = manager.get_computed_blocks(follower)
assert num_hit == 224
@pytest.mark.parametrize(
"hash_block_size,mamba_block_size,use_eagle",
[(32, 32, False), (16, 32, False), (32, 32, True)],
)
@pytest.mark.parametrize("retention_interval", [0, None])
@pytest.mark.parametrize(
"num_prompt_tokens,num_output_tokens",
[(104, 0), (200, 0), (40, 24), (40, 25), (150, 43)],
)
@pytest.mark.parametrize("chunk_blocks", [2, 100])
def test_checkpoint_reservation_matches_worker(
hash_block_size,
mamba_block_size,
use_eagle,
retention_interval,
num_prompt_tokens,
num_output_tokens,
chunk_blocks,
):
"""The worker exports a checkpoint wherever `compute_mamba_prefill_checkpoints`
says, into whatever block sits at its column. Each chunk, the manager must
either reserve exactly that position and column, or leave the column null so
the export is masked; anything else publishes a hash over the wrong state.
Under sparse retention, only the prefill-end chunk may reserve one.
"""
manager = make_full_mamba_manager(
dcp_world_size=1,
hash_block_size=hash_block_size,
full_block_size=hash_block_size,
mamba_block_size=mamba_block_size,
num_blocks=64,
use_eagle=use_eagle,
num_speculative_blocks=3 if use_eagle else 0,
num_prefill_checkpoint_blocks=1,
)
manager.coordinator.retention_interval = retention_interval
mamba_manager = manager.coordinator.single_type_managers[1]
request = make_request(
"req", list(range(num_prompt_tokens)), hash_block_size, sha256
)
request.append_output_token_ids(list(range(1000, 1000 + num_output_tokens)))
num_tokens = request.num_tokens
prefill_end = max(num_prompt_tokens, num_tokens - 1)
start = 0
while start < num_tokens:
end = min(start + chunk_blocks * mamba_block_size, num_tokens)
assert manager.allocate_slots(request, end - start) is not None
offsets, cols = compute_mamba_prefill_checkpoints(
[end],
[end - start],
hash_block_size=hash_block_size,
mamba_block_size=mamba_block_size,
checkpoint_alignment=16,
drop_eagle_block=use_eagle,
)
reserved = mamba_manager._checkpoints.get(request.request_id)
if reserved is not None:
assert reserved == (start + offsets[0], cols[0])
assert retention_interval is None or end >= prefill_end
elif offsets[0]:
assert mamba_manager.req_to_blocks[request.request_id][cols[0]].is_null
request.num_computed_tokens = end
manager.new_step_starts()
start = end
+337 -34
View File
@@ -52,12 +52,14 @@ from vllm.v1.core.kv_cache_utils import (
hash_block_tokens,
init_none_hash,
is_kv_cache_spec_uniform,
kv_cache_groups_tp_replicas,
make_block_hash_with_group_id,
tensor_data,
to_event_extra_keys,
)
from vllm.v1.hisparse.layout import (
create_hisparse_layout,
get_hisparse_gpu_memory_usage,
get_hisparse_kv_cache_groups,
)
from vllm.v1.kv_cache_interface import (
ChunkedLocalAttentionSpec,
@@ -116,9 +118,6 @@ def test_hisparse_hma_uses_resolved_gpu_block_size(
cache_role=SparseCacheRole.INDEXER,
),
}
group_spec = UniformTypeKVCacheSpecs.from_specs(specs)
assert group_spec is not None
group = KVCacheGroupSpec(list(specs), group_spec)
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=HiSparseConfig()),
model_config=SimpleNamespace(
@@ -140,14 +139,9 @@ def test_hisparse_hma_uses_resolved_gpu_block_size(
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC,
),
)
indexer_spec = specs["model.layers.0.self_attn.indexer"]
assert get_hisparse_gpu_memory_usage(config, [group]) == (
indexer_spec.max_memory_usage_bytes(config)
)
monkeypatch.setattr(kv_cache_utils, "get_hisparse_host_pool_bytes", lambda _: 2**30)
cache_config = kv_cache_utils.get_kv_cache_config_from_groups(
config, [group], available_memory=2**30
config, get_hisparse_kv_cache_groups(config, specs), available_memory=2**30
)
assert cache_config.num_blocks == 7
assert cache_config.hisparse_host_num_blocks is not None
@@ -204,6 +198,157 @@ def test_hisparse_hma_uses_resolved_gpu_block_size(
assert scheduler_block_size == hash_block_size == gpu_block_size
@pytest.mark.parametrize("extra_blocks,ok", [(1, False), (2, True)])
def test_hisparse_host_pool_must_fit_max_model_len(monkeypatch, extra_blocks, ok):
"""Every page needs a host block, so one max_model_len request must fit."""
monkeypatch.setattr(
hisparse_runtime_module.current_platform, "is_cuda_alike", lambda: True
)
specs = {
"model.layers.0.self_attn": MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=576,
dtype=torch.bfloat16,
is_index_group_leader=True,
),
"model.layers.0.self_attn.indexer": MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
cache_role=SparseCacheRole.INDEXER,
),
}
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=HiSparseConfig()),
model_config=SimpleNamespace(
hf_config=SimpleNamespace(index_topk=128), max_model_len=64 * 4
),
parallel_config=SimpleNamespace(tensor_parallel_size=1, world_size=1),
cache_config=SimpleNamespace(num_gpu_blocks_override=7),
)
host_page = specs["model.layers.0.self_attn"].page_size_bytes
host_budget = (4 + extra_blocks) * host_page
groups = get_hisparse_kv_cache_groups(config, specs)
if ok:
layout = create_hisparse_layout(config, groups, host_budget=host_budget)
assert layout.host_num_blocks == 4 + extra_blocks
else:
with pytest.raises(ValueError, match="increase host_pool_gib"):
create_hisparse_layout(config, groups, host_budget=host_budget)
@pytest.mark.parametrize(
"max_model_len,num_gpu_blocks,ok",
[
(8192, 160, False),
(8192, 1000, True),
(32768, 656, False),
(32768, 657, True),
(-1, 657, True),
],
)
def test_hisparse_pool_must_fit_max_model_len(
monkeypatch, max_model_len, num_gpu_blocks, ok
):
"""Each resident group takes its own blocks from HiSparse's shared GPU pool,
so a pool that fits only the indexer pages must be rejected at startup.
Resident pages are capped at the in-flight window: at 32768 tokens with 2048
in flight, one request needs 512 indexer + 4 x 32 resident + 16 hot blocks,
plus the null block. Auto-fit (-1) must pick a length that passes the same
check."""
monkeypatch.setattr(
hisparse_runtime_module.current_platform, "is_cuda_alike", lambda: True
)
monkeypatch.setattr(kv_cache_utils, "get_hisparse_host_pool_bytes", lambda _: 2**30)
specs: dict[str, KVCacheSpec] = {}
for i in range(4):
specs[f"model.layers.{i}.self_attn"] = MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=576,
dtype=torch.bfloat16,
is_index_group_leader=True,
)
specs[f"model.layers.{i}.self_attn.indexer"] = MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
cache_role=SparseCacheRole.INDEXER,
)
config = VllmConfig(model_config=ModelConfig(max_model_len=max_model_len))
config.scheduler_config.max_num_batched_tokens = 2048
# Async scheduling doubles the in-flight window, and with it the bound.
config.scheduler_config.async_scheduling = False
config.attention_config.hisparse_config = HiSparseConfig()
config.model_config.hf_config.index_topk = 128
config.cache_config.num_gpu_blocks_override = num_gpu_blocks
config.cache_config.kv_cache_layout = "BLHNC"
# Workers report the resident/hot caches HiSparse derives.
specs |= {
name: group.kv_cache_spec
for group in get_hisparse_kv_cache_groups(config, specs) or []
if isinstance(group.kv_cache_spec, (HiSparseResidentSpec, HiSparseHotSpec))
for name in group.layer_names
}
if ok:
kv_cache_utils.get_kv_cache_configs(config, [specs], [2**34])
else:
with pytest.raises(ValueError, match="max seq len"):
kv_cache_utils.get_kv_cache_configs(config, [specs], [2**34])
def test_hisparse_derived_specs_do_not_affect_kv_cache_layout(monkeypatch):
"""Workers report HiSparse's resident/hot caches, which lay out their own raw
backing; KV cache layout resolution must skip them."""
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
monkeypatch.setattr(
hisparse_runtime_module.current_platform, "is_cuda_alike", lambda: True
)
monkeypatch.delenv("VLLM_KV_CACHE_LAYOUT", raising=False)
specs: dict[str, KVCacheSpec] = {
"model.layers.0.self_attn": MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=576,
dtype=torch.bfloat16,
is_index_group_leader=True,
),
"model.layers.0.self_attn.indexer": MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
cache_role=SparseCacheRole.INDEXER,
),
}
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
config.attention_config.hisparse_config = HiSparseConfig()
config.model_config.hf_config.index_topk = 128
reported = specs | {
name: group.kv_cache_spec
for group in get_hisparse_kv_cache_groups(config, specs) or []
if isinstance(group.kv_cache_spec, (HiSparseResidentSpec, HiSparseHotSpec))
for name in group.layer_names
}
assert len(reported) > len(specs)
layouts = []
for worker_specs in (specs, reported):
config.cache_config.kv_cache_layout = None
layouts.append(
resolve_kv_cache_layout(
config, [["BLHNC", "LBNHC"]], list(worker_specs.values())
)
)
assert layouts[0] == layouts[1]
def test_hisparse_rejects_deepseek_v4():
full_specs = {
"model.layers.0.attn": MLAAttentionSpec(
@@ -214,9 +359,6 @@ def test_hisparse_rejects_deepseek_v4():
model_version="deepseek_v4",
)
}
full_uniform = UniformTypeKVCacheSpecs.from_specs(full_specs)
assert full_uniform is not None
group = KVCacheGroupSpec(list(full_specs), full_uniform)
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=HiSparseConfig()),
model_config=SimpleNamespace(hf_config=SimpleNamespace(index_topk=512)),
@@ -224,11 +366,7 @@ def test_hisparse_rejects_deepseek_v4():
)
with pytest.raises(ValueError, match="does not support DeepSeek V4"):
create_hisparse_layout(
config,
[group],
host_budget=2**30,
)
get_hisparse_kv_cache_groups(config, full_specs)
@pytest.fixture(autouse=True)
@@ -822,12 +960,12 @@ def test_generate_block_hash_extra_keys():
# Test with no extra keys
extra_keys, next_mm_idx = generate_block_hash_extra_keys(request, 0, 5, 0)
assert extra_keys == (("hash1", 0),)
assert extra_keys == (("mm", "hash1", 0),)
assert next_mm_idx == 1
# Test with partial overlap
extra_keys, next_mm_idx = generate_block_hash_extra_keys(request, 3, 8, 0)
assert extra_keys == (("hash1", -3),)
assert extra_keys == (("mm", "hash1", -3),)
assert next_mm_idx == 1
# Test with no overlap
@@ -837,7 +975,7 @@ def test_generate_block_hash_extra_keys():
# Test with multiple extra keys
extra_keys, next_mm_idx = generate_block_hash_extra_keys(request, 0, 15, 0)
assert extra_keys == (("hash1", 0), ("hash2", 10))
assert extra_keys == (("mm", "hash1", 0), ("mm", "hash2", 10))
assert next_mm_idx == 2
@@ -865,9 +1003,9 @@ def test_generate_block_hash_extra_keys_cache_salt():
# salt is added for the first token
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 1, 0)
assert extra_keys == ("salt",)
assert extra_keys == (("cache_salt", "salt"),)
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 10, 0)
assert extra_keys == ("salt",)
assert extra_keys == (("cache_salt", "salt"),)
# no salt added for other tokens
extra_keys, _ = generate_block_hash_extra_keys(request, 1, 2, 0)
@@ -888,7 +1026,7 @@ def test_generate_block_hash_extra_keys_cache_salt():
# Test with no extra keys
extra_keys, next_mm_idx = generate_block_hash_extra_keys(request_mm, 0, 5, 0)
assert extra_keys == (("hash1", 0), "salt")
assert extra_keys == (("mm", "hash1", 0), ("cache_salt", "salt"))
assert next_mm_idx == 1
@@ -906,13 +1044,13 @@ def test_generate_block_hash_extra_keys_prompt_embeds():
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 5, 0)
expected_embeds = prompt_embeds[0:5]
expected_hash = hashlib.sha256(kv_cache_utils.tensor_data(expected_embeds)).digest()
assert extra_keys == (expected_hash,)
assert extra_keys == (("prompt_embeds", expected_hash),)
# Test with prompt embeds for the second block
extra_keys, _ = generate_block_hash_extra_keys(request, 5, 10, 0)
expected_embeds = prompt_embeds[5:10]
expected_hash = hashlib.sha256(kv_cache_utils.tensor_data(expected_embeds)).digest()
assert extra_keys == (expected_hash,)
assert extra_keys == (("prompt_embeds", expected_hash),)
def test_generate_block_hash_extra_keys_prompt_embeds_cached(monkeypatch):
@@ -976,13 +1114,80 @@ def test_generate_block_hash_extra_keys_lora():
)
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 3, 0)
assert extra_keys == ("test_lora_adapter",)
assert extra_keys == (("lora", "test_lora_adapter", "/path/to/lora"),)
request.lora_request = None
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 3, 0)
assert extra_keys is None
@pytest.mark.parametrize("hash_fn", [sha256, sha256_cbor])
def test_lora_name_and_cache_salt_block_hashes_do_not_collide(hash_fn):
"""A cache_salt equal to a LoRA name must not share that LoRA's blocks."""
lora_request = LoRARequest(
lora_name="foo", lora_int_id=1, lora_path="/path/to/lora"
)
lora_req = Request(
request_id="lora",
prompt_token_ids=[0, 1, 2],
sampling_params=SamplingParams(max_tokens=1),
pooling_params=None,
lora_request=lora_request,
block_hasher=get_request_block_hasher(3, hash_fn),
)
salted_req = make_request("salted", [0, 1, 2], hash_fn=hash_fn, cache_salt="foo")
assert lora_req.block_hashes[0] != salted_req.block_hashes[0]
@pytest.mark.parametrize("hash_fn", [sha256, sha256_cbor])
def test_lora_path_change_changes_block_hashes(hash_fn):
"""Re-pointing a LoRA name at another adapter must not reuse its blocks."""
def make_lora_request(lora_path: str) -> Request:
return Request(
request_id=lora_path,
prompt_token_ids=[0, 1, 2],
sampling_params=SamplingParams(max_tokens=1),
pooling_params=None,
lora_request=LoRARequest(
lora_name="foo", lora_int_id=1, lora_path=lora_path
),
block_hasher=get_request_block_hasher(3, hash_fn),
)
first = make_lora_request("/path/to/lora_a")
second = make_lora_request("/path/to/lora_b")
assert first.block_hashes[0] != second.block_hashes[0]
def test_to_event_extra_keys_keeps_untagged_event_format():
"""KV events keep publishing the extra-key shapes consumers already parse."""
request = make_request(
"0",
list(range(10)),
mm_positions=[PlaceholderRange(offset=2, length=3)],
mm_hashes=["hash1"],
cache_salt="salt",
)
request.lora_request = LoRARequest(
lora_name="adapter", lora_int_id=1, lora_path="/path/to/lora"
)
extra_keys, _ = generate_block_hash_extra_keys(request, 0, 5, 0)
assert extra_keys == (
("lora", "adapter", "/path/to/lora"),
("mm", "hash1", 2),
("cache_salt", "salt"),
)
event_keys = ("adapter", ("hash1", 2), "salt")
assert to_event_extra_keys([extra_keys, None]) == [event_keys, None]
assert to_event_extra_keys([]) is None
assert to_event_extra_keys(None) is None
@pytest.mark.parametrize("hash_fn", [sha256, sha256_cbor])
def test_hash_block_tokens(hash_fn):
parent_block_hash = BlockHash(b"123")
@@ -1013,9 +1218,11 @@ def test_request_block_hasher(hash_fn):
block_hashes = request.block_hashes
assert len(block_hashes) == 2
assert block_hashes[0] == hash_fn(
(kv_cache_utils.NONE_HASH, (0, 1, 2), (("hash1", 0),))
(kv_cache_utils.NONE_HASH, (0, 1, 2), (("mm", "hash1", 0),))
)
assert block_hashes[1] == hash_fn(
(block_hashes[0], (3, 4, 5), (("mm", "hash2", 0),))
)
assert block_hashes[1] == hash_fn((block_hashes[0], (3, 4, 5), (("hash2", 0),)))
@pytest.mark.parametrize("hash_fn", [sha256, sha256_cbor])
@@ -1043,7 +1250,7 @@ def test_request_block_hasher_incremental_append_with_multiple_mm_features(hash_
)
expected_second_hash = hash_fn(
(incremental.block_hashes[0], (4, 5, 6, 7), (("A", 0), ("B", 2)))
(incremental.block_hashes[0], (4, 5, 6, 7), (("mm", "A", 0), ("mm", "B", 2)))
)
assert incremental.block_hashes[1] == expected_second_hash
assert incremental.block_hashes == fresh.block_hashes
@@ -3182,6 +3389,7 @@ def new_mla_spec(cache_dtype_str=None, block_size: int = 16):
return MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=576,
dtype=torch.float32,
cache_dtype_str=cache_dtype_str,
@@ -3192,6 +3400,7 @@ def new_swa_mla_spec(head_size=576, sliding_window=128, model_version=None):
return SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
max_tp_shards=1,
head_size=head_size,
dtype=torch.float32,
sliding_window=sliding_window,
@@ -3657,7 +3866,7 @@ def test_request_block_hasher_with_prompt_embeds(hash_fn: Callable[[Any], bytes]
(
kv_cache_utils.NONE_HASH,
tuple(prompt_token_ids[:block_size]),
(block1_embeds_hash,),
(("prompt_embeds", block1_embeds_hash),),
)
)
assert block_hashes[0] == expected_hash1
@@ -3669,7 +3878,7 @@ def test_request_block_hasher_with_prompt_embeds(hash_fn: Callable[[Any], bytes]
(
block_hashes[0],
tuple(prompt_token_ids[block_size:num_tokens]),
(block2_embeds_hash,),
(("prompt_embeds", block2_embeds_hash),),
)
)
assert block_hashes[1] == expected_hash2
@@ -3706,7 +3915,7 @@ def test_request_with_prompt_embeds_and_mm_inputs(hash_fn: Callable[[Any], bytes
(
kv_cache_utils.NONE_HASH,
tuple(prompt_token_ids[:block_size]),
(("hash1", 0), block1_embeds_hash),
(("mm", "hash1", 0), ("prompt_embeds", block1_embeds_hash)),
)
)
assert block_hashes[0] == expected_hash1
@@ -3718,7 +3927,7 @@ def test_request_with_prompt_embeds_and_mm_inputs(hash_fn: Callable[[Any], bytes
(
block_hashes[0],
tuple(prompt_token_ids[block_size:num_tokens]),
(("hash2", 0), block2_embeds_hash),
(("mm", "hash2", 0), ("prompt_embeds", block2_embeds_hash)),
)
)
assert block_hashes[1] == expected_hash2
@@ -4545,3 +4754,97 @@ def test_trailing_layer_fallback_requires_exact_partition():
_annotate_eagle_groups(config, specs, trimmed, use_trailing_layer_fallback=True)
assert not any(g.is_eagle_group for g in trimmed)
_GQA_SPEC = FullAttentionSpec(
block_size=16, num_kv_heads=8, head_size=64, dtype=torch.float32
)
_GQA_SWA_SPEC = SlidingWindowSpec(
block_size=16, num_kv_heads=8, head_size=64, dtype=torch.float32, sliding_window=128
)
@pytest.mark.parametrize(
"specs,expected",
[
pytest.param({"l.0": new_mla_spec(), "l.1": new_mla_spec()}, 4, id="mla"),
pytest.param(
{
"l.0": new_mla_spec(),
"l.1": new_mla_spec(),
"s.0": new_swa_mla_spec(),
"s.1": new_swa_mla_spec(),
},
4,
id="mla-and-swa-mla",
),
pytest.param({"l.0": _GQA_SPEC, "l.1": _GQA_SPEC}, 1, id="gqa"),
pytest.param(
{"l.0": new_mla_spec(), "l.1": _GQA_SPEC},
1,
id="mla-and-gqa-uniform-group",
),
pytest.param(
{
"l.0": new_mla_spec(),
"l.1": new_mla_spec(),
"s.0": _GQA_SWA_SPEC,
"s.1": _GQA_SWA_SPEC,
},
1,
id="mla-and-gqa-swa",
),
],
)
def test_kv_tp_replicas(monkeypatch, specs, expected):
"""Resolved per layer before scheduler flattening hides mixed groups."""
from vllm.config import ParallelConfig
from vllm.platforms import current_platform
monkeypatch.setattr(current_platform, "device_count", lambda: 4)
parallel_config = ParallelConfig(tensor_parallel_size=4)
vllm_config = VllmConfig(
model_config=ModelConfig(max_model_len=16), parallel_config=parallel_config
)
vllm_config.cache_config.kv_cache_layout = "LBNHC"
mem = sum(s.page_size_bytes for s in specs.values()) * 10
configs = get_kv_cache_configs(vllm_config, [specs], [mem])
assert configs[0].kv_tp_replicas == expected
scheduler = generate_scheduler_kv_cache_config(configs)
assert scheduler.kv_tp_replicas == expected
@pytest.mark.parametrize(
"specs,tp_size,dcp_size,expected",
[
pytest.param([new_mla_spec()], 8, 1, 8, id="mla"),
pytest.param([new_mla_spec()], 8, 2, 1, id="mla-dcp"),
pytest.param(
[replace(new_mla_spec(), max_tp_shards=None)], 8, 1, 1, id="mla-unset"
),
pytest.param([replace(_GQA_SPEC, max_tp_shards=2)], 8, 1, 4, id="gqa-partial"),
pytest.param([replace(_GQA_SPEC, max_tp_shards=8)], 4, 1, 1, id="gqa-sharded"),
pytest.param(
[new_mla_spec(), replace(_GQA_SWA_SPEC, max_tp_shards=4)],
8,
1,
2,
id="mla-and-gqa-partial",
),
pytest.param(
[
HiddenStateCacheSpec(
block_size=16, num_kv_heads=1, head_size=64, dtype=torch.float32
)
],
8,
1,
1,
id="hidden-state",
),
],
)
def test_kv_cache_groups_tp_replicas(specs, tp_size, dcp_size, expected):
"""Replicas are the gcd of each layer's tp_size // max_tp_shards."""
groups = [KVCacheGroupSpec([f"l.{i}"], spec) for i, spec in enumerate(specs)]
assert kv_cache_groups_tp_replicas(groups, tp_size, dcp_size) == expected
+398 -86
View File
@@ -168,6 +168,7 @@ def make_hisparse_kv_cache_config(
host_num_blocks: int,
*,
transfer_device_cache: bool = False,
num_resident_groups: int = 1,
) -> KVCacheConfig:
source_spec = FullAttentionSpec(
block_size=HISPARSE_BLOCK_SIZE,
@@ -210,6 +211,13 @@ def make_hisparse_kv_cache_config(
enable_kv_transfer=False,
)
)
for group_idx in range(1, num_resident_groups):
groups.extend(
replace(
group, layer_names=[f"{name}_{group_idx}" for name in group.layer_names]
)
for group in groups[2:4]
)
return KVCacheConfig(
num_blocks=num_blocks,
hisparse_host_num_blocks=host_num_blocks,
@@ -225,6 +233,7 @@ def make_hisparse_kv_cache_manager(
max_model_len: int = 128,
max_in_flight_tokens: int | None = None,
enable_caching: bool = False,
num_prefill_lookahead: int = 0,
**config_kwargs,
) -> KVCacheManager:
config = make_hisparse_kv_cache_config(num_blocks, host_num_blocks, **config_kwargs)
@@ -234,9 +243,53 @@ def make_hisparse_kv_cache_manager(
max_in_flight_tokens=max_in_flight_tokens,
enable_caching=enable_caching,
hash_block_size=HISPARSE_BLOCK_SIZE,
num_prefill_lookahead=num_prefill_lookahead,
)
def _allocate_scheduled(
manager: KVCacheManager,
request: Request,
num_new_tokens: int,
*,
num_new_computed_tokens: int = 0,
num_external_computed_tokens: int = 0,
**kwargs,
) -> KVCacheBlocks | None:
"""``allocate_slots`` plus the per-step residency work the connector runs."""
blocks = manager.allocate_slots(
request,
num_new_tokens,
num_new_computed_tokens=num_new_computed_tokens,
num_external_computed_tokens=num_external_computed_tokens,
**kwargs,
)
if blocks is None or kwargs.get("delay_cache_blocks"):
return blocks
num_computed_tokens = min(
request.num_computed_tokens
+ num_new_computed_tokens
+ num_external_computed_tokens,
manager.max_model_len,
)
num_tokens = min(num_computed_tokens + num_new_tokens, request.num_tokens)
get_hisparse_coordinator(manager).advance_scheduled(
[(request.request_id, num_tokens)]
)
return blocks
def test_hisparse_does_not_write_back_reprefillable_tokens():
"""Multi-module MTP re-prefills the last tokens, so they are not final."""
manager = make_hisparse_kv_cache_manager(32, 16, num_prefill_lookahead=3)
request = make_request(
"request", list(range(2 * HISPARSE_BLOCK_SIZE)), HISPARSE_BLOCK_SIZE, sha256
)
assert _allocate_scheduled(manager, request, 2 * HISPARSE_BLOCK_SIZE)
transfers = get_hisparse_coordinator(manager).build_offload_command().page_transfers
assert len(transfers) == 1
def test_hisparse_builds_dma_row_mirrors_across_pages():
manager = make_hisparse_kv_cache_manager(32, 16)
request = make_request(
@@ -245,7 +298,7 @@ def test_hisparse_builds_dma_row_mirrors_across_pages():
HISPARSE_BLOCK_SIZE,
sha256,
)
assert manager.allocate_slots(request, num_new_tokens=32) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=32) is not None
coordinator = get_hisparse_coordinator(manager)
resident_blocks = coordinator.resident_managers[0].req_to_blocks[request.request_id]
host_blocks = coordinator.host_manager.req_to_blocks[request.request_id]
@@ -308,14 +361,14 @@ def test_hisparse_reports_when_context_is_fully_resident():
manager = make_hisparse_kv_cache_manager(32, 16)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
request = make_request("request", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, num_new_tokens=len(tokens)) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=len(tokens)) is not None
coordinator = get_hisparse_coordinator(manager)
scheduled = ((request.request_id, len(tokens) - 1, 1),)
assert coordinator.all_context_pages_resident(scheduled)
for hot_manager in coordinator.hot_managers:
hot_manager.require_hot(request.request_id)
assert manager.allocate_slots(request, num_new_tokens=len(tokens)) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=len(tokens)) is not None
_publish_hisparse_pages(manager)
pool = manager.block_pool
pool.get_new_blocks(pool.get_num_free_blocks())
@@ -333,7 +386,9 @@ def test_hisparse_host_prefix_can_be_completed_by_indexer_offload():
)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
spills = get_hisparse_coordinator(manager).build_offload_command().page_transfers
spill_counts = {spill.transfer_id: 1 for spill in spills}
get_hisparse_coordinator(manager).update_spills(spill_counts, spill_counts)
@@ -348,7 +403,8 @@ def test_hisparse_host_prefix_can_be_completed_by_indexer_offload():
assert num_local == 2 * HISPARSE_BLOCK_SIZE
assert [len(group_blocks) for group_blocks in blocks.blocks] == [3, 2, 0, 0]
allocated = manager.allocate_slots(
allocated = _allocate_scheduled(
manager,
resumed,
num_new_tokens=1,
num_new_computed_tokens=num_local,
@@ -379,7 +435,9 @@ def test_hisparse_indexer_offload_is_capped_by_missing_host_prefix():
)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
spills = get_hisparse_coordinator(manager).build_offload_command().page_transfers
spill_counts = {spill.transfer_id: 1 for spill in spills}
get_hisparse_coordinator(manager).update_spills(spill_counts, spill_counts)
@@ -410,7 +468,7 @@ def test_connector_completes_partial_prefix_without_importing_missing_host_kv(
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(64))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=64) is not None
assert _allocate_scheduled(manager, original, num_new_tokens=64) is not None
_publish_hisparse_pages(manager)
host, indexer, _, _ = manager.get_blocks(original.request_id).blocks
missing_indexer = indexer[1].block_id
@@ -457,7 +515,8 @@ def test_connector_completes_partial_prefix_without_importing_missing_host_kv(
assert asynchronous == (external > 0)
assert [len(group) for group in blocks.blocks] == [3, 1, 0, 0]
assert (
manager.allocate_slots(
_allocate_scheduled(
manager,
resumed,
int(external == 0),
delay_cache_blocks=True,
@@ -486,7 +545,8 @@ def test_connector_completes_partial_prefix_without_importing_missing_host_kv(
def allocate_external_prefix(
manager: KVCacheManager, request: Request, num_tokens: int
) -> KVCacheBlocks | None:
return manager.allocate_slots(
return _allocate_scheduled(
manager,
request,
num_new_tokens=0,
num_external_computed_tokens=num_tokens,
@@ -538,7 +598,7 @@ def test_nixl_hisparse_full_block_import_keeps_a_writable_tail(num_tokens):
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
assert _allocate_scheduled(manager, request, num_new_tokens=1) is not None
assert coordinator.build_row_mirrors([(request.request_id, num_tokens - 1, 1)])
# A pending restore must not expose uninitialized GPU copies to prefix hits.
assert all(resident[-1] not in copies for copies in coordinator.copies.values())
@@ -583,15 +643,15 @@ def test_hisparse_keeps_resident_pages_until_hot_buffer_is_allocated(enable_cach
32, 32, max_model_len=256, enable_caching=enable_caching
)
first = make_request("first", list(range(160)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(first, num_new_tokens=128) is not None
assert _allocate_scheduled(manager, first, num_new_tokens=128) is not None
_publish_hisparse_pages(manager)
first.num_computed_tokens = 128
pool = manager.block_pool
held = pool.get_new_blocks(pool.get_num_free_blocks() - 3)
assert manager.allocate_slots(first, num_new_tokens=1) is not None
assert _allocate_scheduled(manager, first, num_new_tokens=1) is not None
second = make_request("second", [1000] * 16, HISPARSE_BLOCK_SIZE, sha256)
manager.allocate_slots(second, num_new_tokens=16)
_allocate_scheduled(manager, second, num_new_tokens=16)
coordinator = get_hisparse_coordinator(manager)
scheduled = (("first", 128, 1),)
assert coordinator.all_context_pages_resident(scheduled)
@@ -600,7 +660,7 @@ def test_hisparse_keeps_resident_pages_until_hot_buffer_is_allocated(enable_cach
# Once another allocation finishes, A can acquire its hot buffer and
# safely release its clean pages for other requests to reuse.
pool.free_blocks(held)
assert manager.allocate_slots(first, num_new_tokens=1) is not None
assert _allocate_scheduled(manager, first, num_new_tokens=1) is not None
assert all(m.has_hot("first") for m in coordinator.hot_managers)
pool.get_new_blocks(pool.get_num_free_blocks())
assert not coordinator.all_context_pages_resident(scheduled)
@@ -611,21 +671,24 @@ def test_hisparse_full_pool_keeps_pages_pinned_until_preemption():
"""Without room for a hot buffer, admission must defer instead of losing KV."""
manager = make_hisparse_kv_cache_manager(18, 18, max_model_len=160)
first = make_request("first", list(range(128)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(first, num_new_tokens=128) is not None
assert _allocate_scheduled(manager, first, num_new_tokens=128) is not None
_publish_hisparse_pages(manager)
assert manager.block_pool.get_num_free_blocks() == 1
first.num_computed_tokens = 128
assert manager.allocate_slots(first, num_new_tokens=1) is None
assert _allocate_scheduled(manager, first, num_new_tokens=1) is None
assert get_hisparse_coordinator(manager).all_context_pages_resident(
(("first", 127, 1),)
)
manager.free(first)
second = make_request("second", [1000] * 16, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(second, num_new_tokens=16) is not None
assert _allocate_scheduled(manager, second, num_new_tokens=16) is not None
def test_hisparse_materializes_prefix_without_allocating_hot_blocks():
@pytest.mark.parametrize("num_resident_groups", [1, 3])
def test_hisparse_materializes_prefix_without_allocating_hot_blocks(
num_resident_groups,
):
"""A host prefix becomes visible only when every page is durable.
Completing a later page first must not expose a prefix with a hole.
@@ -634,10 +697,11 @@ def test_hisparse_materializes_prefix_without_allocating_hot_blocks():
32,
16,
enable_caching=True,
num_resident_groups=num_resident_groups,
)
tokens = list(range(2 * HISPARSE_BLOCK_SIZE))
request = make_request("resident", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, num_new_tokens=len(tokens)) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=len(tokens)) is not None
blocks = manager.get_block_ids(request.request_id)
assert len(blocks[2]) == 2
assert blocks[3] == []
@@ -675,19 +739,21 @@ def test_hisparse_materializes_prefix_without_allocating_hot_blocks():
assert blocks[3] == []
def test_hisparse_materialization_respects_per_step_spill_budget():
@pytest.mark.parametrize("num_resident_groups", [1, 3])
def test_hisparse_materialization_respects_per_step_spill_budget(num_resident_groups):
"""Prefix publication must not bypass the configured spill batch limit."""
manager = make_hisparse_kv_cache_manager(
32,
16,
enable_caching=True,
num_resident_groups=num_resident_groups,
)
coordinator = get_hisparse_coordinator(manager)
coordinator.max_spill_pages = 1
tokens = list(range(2 * HISPARSE_BLOCK_SIZE))
request = make_request("bounded", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, num_new_tokens=len(tokens)) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=len(tokens)) is not None
first = coordinator.build_offload_command().page_transfers
assert len(first) == 1
@@ -705,7 +771,9 @@ def test_hisparse_deferred_free_retains_host_blocks_until_fence():
host_free = host_pool.get_num_free_blocks()
device_free = manager.block_pool.get_num_free_blocks()
request = make_request("free", list(range(16)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, 16, delay_cache_blocks=True) is not None
assert (
_allocate_scheduled(manager, request, 16, delay_cache_blocks=True) is not None
)
blocks = manager.pop_blocks_for_free(request)
assert host_pool.get_num_free_blocks() < host_free
assert blocks and any(host_pool.blocks[b.block_id] is b for b in blocks)
@@ -782,14 +850,15 @@ def test_hisparse_inflight_host_import_reserves_remaining_gpu_pages():
assert required == 4
@pytest.mark.parametrize(
"full_sequence_must_fit,host_num_blocks,admitted",
[(True, 2, False), (True, 3, True), (False, 2, False), (False, 3, True)],
)
def test_hisparse_async_admission_requires_only_import_destinations(
full_sequence_must_fit, host_num_blocks, admitted, tmp_path
@pytest.mark.parametrize("host_num_blocks,admitted", [(5, False), (6, True)])
def test_hisparse_async_admission_requires_full_prompt_host_pages(
host_num_blocks, admitted, tmp_path
):
"""Imports need host destinations, but do not reserve future prefill pages."""
"""An async load is admitted only if its whole prompt's host pages fit.
The in-flight prefill's host page is not free, so the waiting request's
four prompt pages need six host blocks including the null block.
"""
from .utils import create_scheduler, mock_kv
(tmp_path / "config.json").write_text(
@@ -804,7 +873,7 @@ def test_hisparse_async_admission_requires_only_import_destinations(
manager = make_hisparse_kv_cache_manager(32, host_num_blocks)
scheduler.kv_cache_manager = manager
scheduler.kv_cache_config = manager.kv_cache_config
scheduler.scheduler_reserve_full_isl = full_sequence_must_fit
assert scheduler.scheduler_reserve_full_isl
inflight = make_request(
"inflight", list(range(3 * HISPARSE_BLOCK_SIZE)), HISPARSE_BLOCK_SIZE, sha256
)
@@ -822,6 +891,52 @@ def test_hisparse_async_admission_requires_only_import_destinations(
assert bool(manager.get_blocks(request.request_id).blocks[0]) == admitted
def test_hisparse_admitted_async_loads_can_finish_with_nothing_running(tmp_path):
"""Admitted async loads must not strand each other on host capacity.
Waiting requests keep their blocks and are never preempted, so two imports
that each hold a host page while together needing more than the pool has
left would never be scheduled again. HiSparse relies on full-ISL admission:
a load is admitted only if its whole prompt's host pages fit, so the newest
admitted load can always finish and free host blocks for the others.
"""
from .utils import create_scheduler, mock_kv
(tmp_path / "config.json").write_text(
'{"architectures": ["OPTForCausalLM"], "model_type": "opt"}'
)
scheduler = create_scheduler(
model=str(tmp_path),
skip_tokenizer_init=True,
max_model_len=128,
use_kv_connector=mock_kv(matched_tokens=HISPARSE_BLOCK_SIZE, is_async=True),
)
# One null block plus three usable host blocks.
manager = make_hisparse_kv_cache_manager(32, 4)
scheduler.kv_cache_manager = manager
scheduler.kv_cache_config = manager.kv_cache_config
assert scheduler.scheduler_reserve_full_isl
first = make_request(
"first", list(range(3 * HISPARSE_BLOCK_SIZE)), HISPARSE_BLOCK_SIZE, sha256
)
second = make_request(
"second",
list(range(1000, 1000 + 3 * HISPARSE_BLOCK_SIZE)),
HISPARSE_BLOCK_SIZE,
sha256,
)
for request in (first, second):
scheduler.add_request(request)
scheduler.schedule()
admitted = {r.request_id for r in scheduler._inflight_prefills}
scheduler.finished_recving_kv_req_ids.update(admitted)
num_scheduled_tokens = 0
for _ in range(4):
num_scheduled_tokens += scheduler.schedule().total_num_scheduled_tokens
assert num_scheduled_tokens > 0
@pytest.mark.parametrize(
"evictable,local_tokens,free_blocks,admitted",
[
@@ -845,58 +960,47 @@ def test_hisparse_import_capacity_includes_hits_and_cow(
assert host_pool.get_num_free_blocks() == free_blocks
assert (
coordinator.host_manager.get_num_blocks_to_allocate(
"waiting", 64, [hit], 32, local_tokens, 64
"waiting", 32, [hit], 32, local_tokens, 32
)
<= host_pool.get_num_free_blocks()
) == admitted
@pytest.mark.parametrize("enable_caching", [False, True])
def test_hisparse_host_exhaustion_keeps_gpu_pages_readable(enable_caching):
"""Pages without a host destination must survive GPU cache reclamation."""
manager = make_hisparse_kv_cache_manager(32, 2, enable_caching=enable_caching)
def test_hisparse_host_exhaustion_defers_allocation(enable_caching):
"""Pages are only allocated with host backing, so every one can be reclaimed."""
manager = make_hisparse_kv_cache_manager(32, 5, enable_caching=enable_caching)
donor = make_request("donor", [99] * 16, HISPARSE_BLOCK_SIZE, sha256)
assert _allocate_scheduled(manager, donor, 16) is not None
request = make_request("resident", list(range(64)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, 64) is not None
free_gpu = manager.block_pool.get_num_free_blocks()
assert manager.allocate_slots(request, 64) is None
assert manager.block_pool.get_num_free_blocks() == free_gpu
# The donor's in-flight write-back holds its host block until acked.
manager.free(donor)
coordinator = get_hisparse_coordinator(manager)
assert coordinator.has_pending_reclamation()
assert manager.allocate_slots(request, 64) is None
_publish_hisparse_pages(manager)
assert not coordinator.has_pending_reclamation()
assert _allocate_scheduled(manager, request, 64) is not None
host = coordinator.host_manager
assert host is not None
assert [b.is_null for b in host.req_to_blocks[request.request_id]] == [
False,
True,
True,
True,
]
assert not any(b.is_null for b in host.req_to_blocks[request.request_id])
_publish_hisparse_pages(manager)
for hot in coordinator.hot_managers:
hot.require_hot(request.request_id)
hot.allocate_new_blocks(request.request_id, 64, 64)
coordinator.update_residency(request.request_id)
assert coordinator.request_states[request.request_id].unpinned_pages == {0, 1}
for resident in coordinator.resident_managers:
for block in resident.req_to_blocks[request.request_id][1:]:
assert not block.is_null and block.ref_cnt > 0
assert coordinator.request_states[request.request_id].valid_pages == {0}
pool = coordinator.get_host_block_pool()
assert pool is not None
manager.free(request)
assert pool.get_num_free_blocks() == 1
def test_hisparse_host_cow_takes_priority_over_new_pages():
"""The last host block must hold the private tail, not a fresh page."""
manager = make_hisparse_kv_cache_manager(32, 3)
coordinator = get_hisparse_coordinator(manager)
host = coordinator.host_manager
assert host is not None
source = host.block_pool.get_new_blocks(1)[0]
host.req_to_blocks["cow"] = [source]
host._partial_hit_reqs["cow"] = (0, source)
host.allocate_new_blocks("cow", 32, 32)
private, missing = host.req_to_blocks["cow"]
assert not private.is_null and private is not source
assert missing.is_null
assert host.take_host_cow_copies() == [(source, private)]
assert [b.ref_cnt for b in resident.req_to_blocks[request.request_id]] == [
0,
0,
1,
1,
]
@pytest.mark.parametrize("failed", [False, True])
@@ -938,7 +1042,7 @@ def test_hisparse_recomputation_does_not_complete_failed_host_import():
# allocation reaches the original import boundary before the worker runs.
request.num_computed_tokens = 16
manager.cache_blocks(request, 16)
assert manager.allocate_slots(request, 16) is not None
assert _allocate_scheduled(manager, request, 16) is not None
state = get_hisparse_coordinator(manager).request_states.get(request.request_id)
assert state is None or 1 not in state.valid_pages
@@ -959,12 +1063,12 @@ def test_hisparse_resident_request_can_grow_without_hot_capacity():
"""Running resident history must not be mistaken for a new host-prefix hit."""
manager = make_hisparse_kv_cache_manager(8, 16)
request = make_request("resident", list(range(48)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, num_new_tokens=32) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=32) is not None
request.num_computed_tokens = 32
# Three free blocks fit the next indexer/resident pages, but not a hot region.
assert manager.block_pool.get_num_free_blocks() == 3
assert manager.allocate_slots(request, num_new_tokens=1) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=1) is not None
assert manager.get_block_ids(request.request_id)[3] == []
@@ -1014,7 +1118,7 @@ def test_hisparse_events_report_host_and_device_placement():
enable_kv_cache_events=True,
)
request = make_request("request", list(range(64)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, 64) is not None
assert _allocate_scheduled(manager, request, 64) is not None
_publish_hisparse_pages(manager)
stored = [
@@ -1077,7 +1181,9 @@ def test_hisparse_prefix_hit_adopts_gpu_shadow_pages():
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
_publish_hisparse_pages(manager)
original_resident_ids = [
block.block_id for block in manager.get_blocks("original").blocks[2]
@@ -1087,7 +1193,8 @@ def test_hisparse_prefix_hit_adopts_gpu_shadow_pages():
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
computed, num_computed, _ = manager.get_computed_blocks(resumed)
assert num_computed == 3 * HISPARSE_BLOCK_SIZE
assert manager.allocate_slots(
assert _allocate_scheduled(
manager,
resumed,
num_new_tokens=len(tokens) - num_computed,
num_new_computed_tokens=num_computed,
@@ -1103,19 +1210,71 @@ def test_hisparse_prefix_hit_adopts_gpu_shadow_pages():
)
@pytest.mark.parametrize("free_blocks,adopted_pages", [(7, []), (10, [0, 1])])
def test_hisparse_prefix_hit_under_pressure_adopts_surviving_copies(
free_blocks, adopted_pages
):
"""A host prefix hit must not starve its own allocation of free blocks.
Admission counts free GPU copies as free, but adopting a copy pins it. When
adoption ran before the hit's allocation, it took blocks the allocation was
promised and the pool ran dry (``Cannot get N free blocks``). The allocation
now goes first, evicting a prefix's copies tail first; the copies it leaves
are adopted.
"""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
_publish_hisparse_pages(manager)
copy_ids = [block.block_id for block in manager.get_blocks("original").blocks[2]]
manager.free(original)
pool = manager.block_pool
pool.get_new_blocks(pool.get_num_free_blocks() - free_blocks)
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
computed, num_computed, _ = manager.get_computed_blocks(resumed)
assert num_computed == 3 * HISPARSE_BLOCK_SIZE
assert _allocate_scheduled(
manager,
resumed,
num_new_tokens=len(tokens) - num_computed,
num_new_computed_tokens=num_computed,
new_computed_blocks=computed,
)
resumed_blocks = manager.get_blocks("resumed").blocks
assert [block.block_id for block in resumed_blocks[2][:3]] == [
copy_ids[page] if page in adopted_pages else pool.null_block.block_id
for page in range(3)
]
gpu_ids = [
block.block_id
for group in resumed_blocks[1:]
for block in group
if not block.is_null
]
assert len(gpu_ids) == len(set(gpu_ids))
def test_hisparse_host_backed_request_accepts_local_prefix_hit():
"""Local group-completion hits need no external host import allocation."""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
_publish_hisparse_pages(manager)
manager.free(original)
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
computed, num_computed, _ = manager.get_computed_blocks(resumed)
assert num_computed == 3 * HISPARSE_BLOCK_SIZE
assert manager.allocate_slots(
assert _allocate_scheduled(
manager,
resumed,
num_new_tokens=len(tokens) - num_computed,
num_new_computed_tokens=num_computed,
@@ -1129,7 +1288,9 @@ def test_hisparse_finished_request_leaves_free_copies():
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
_publish_hisparse_pages(manager)
manager.free(original)
@@ -1142,12 +1303,151 @@ def test_hisparse_finished_request_leaves_free_copies():
assert not coordinator.spills_to_send
@pytest.mark.parametrize(
"status,expected_cached_pages",
[
(RequestStatus.FINISHED_STOPPED, 2),
(RequestStatus.FINISHED_ABORTED, 2),
(RequestStatus.RUNNING, 0),
],
ids=["stopped", "aborted", "running"],
)
def test_hisparse_cleanup_publishes_only_finalized_terminal_pages(
status, expected_cached_pages
):
"""Only terminal cleanup may publish completed, finalized pages."""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
coordinator = get_hisparse_coordinator(manager)
request = make_request("terminal", list(range(33)), HISPARSE_BLOCK_SIZE, sha256)
request.spec_token_ids = list(range(33, 49))
assert (
_allocate_scheduled(manager, request, 49, num_lookahead_tokens=16) is not None
)
host_blocks = list(manager.get_blocks(request.request_id).blocks[0])
command = coordinator.build_offload_command()
counts = {transfer.transfer_id: 1 for transfer in command.page_transfers}
assert len(counts) == 2
request.status = status
manager.free(request)
coordinator.update_spills(counts, counts)
assert all(
block.block_hash is not None for block in host_blocks[:expected_cached_pages]
)
assert all(
block.block_hash is None for block in host_blocks[expected_cached_pages:]
)
assert all(block.ref_cnt == 0 for block in host_blocks)
assert not coordinator.has_pending_work()
@pytest.mark.parametrize("num_pages,reads_host", [(4, True), (3, False)])
def test_hisparse_prefill_reads_host_once_it_fills_admission_window(
num_pages, reads_host
):
"""A prefill switches to host reads once it fills its admission window.
Admission caps each request's resident pages at the in-flight window,
assuming older pages move to host, but pinned pages were released only
once free blocks fell below a fixed watermark. A chunked prefill larger
than the watermark outgrew the pool first and was preempted.
"""
window_pages = 4
manager = make_hisparse_kv_cache_manager(
32,
16,
enable_caching=True,
max_in_flight_tokens=window_pages * HISPARSE_BLOCK_SIZE,
)
coordinator = get_hisparse_coordinator(manager)
tokens = list(range(2 * window_pages * HISPARSE_BLOCK_SIZE))
request = make_request("prefill", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert (
_allocate_scheduled(manager, request, num_pages * HISPARSE_BLOCK_SIZE)
is not None
)
pool = coordinator.gpu_pool
assert pool is not None
assert pool.get_num_free_blocks() >= coordinator.transition_watermark
hot_manager = coordinator.hot_managers[0]
assert (request.request_id in hot_manager.hot_required) == reads_host
def test_hisparse_preempted_prefill_resumes_from_durable_prefix():
"""A prefill preempted mid-way must resume from the pages already on host.
Host writes trail a chunked prefill by a chunk, and host pages were only
published once the whole computed prefix was durable. Each chunk moved
that target past the finished writes, so nothing was published before the
prefill ended: a prefill preempted each time it outgrew the GPU pool
recomputed from the start forever.
"""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
coordinator = get_hisparse_coordinator(manager)
chunk = 2 * HISPARSE_BLOCK_SIZE
tokens = list(range(3 * chunk))
request = make_request("long", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert _allocate_scheduled(manager, request, chunk) is not None
request.num_computed_tokens = chunk
first_chunk_writes = coordinator.build_offload_command().page_transfers
assert _allocate_scheduled(manager, request, chunk) is not None
request.num_computed_tokens = 2 * chunk
acks = {transfer.transfer_id: 1 for transfer in first_chunk_writes}
coordinator.update_spills(acks, acks)
manager.free(request)
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.get_computed_blocks(resumed)[1] == chunk
def test_hisparse_terminal_prefix_waits_for_all_workers_and_preserves_identity():
"""Old completions retain their pages through pressure and request-ID reuse."""
manager = make_hisparse_kv_cache_manager(32, 8, enable_caching=True)
coordinator = get_hisparse_coordinator(manager)
host_pool = coordinator.get_host_block_pool()
tokens = list(range(2 * HISPARSE_BLOCK_SIZE + 1))
request = make_request("reused", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert _allocate_scheduled(manager, request, len(tokens)) is not None
old_blocks = list(manager.get_blocks(request.request_id).blocks[0])
command = coordinator.build_offload_command()
counts = {transfer.transfer_id: 2 for transfer in command.page_transfers}
partial = dict.fromkeys(counts, 1)
first_completions = partial.copy()
first_completions[next(iter(counts))] = 2
coordinator.update_spills(counts, first_completions)
request.status = RequestStatus.FINISHED_LENGTH_CAPPED
manager.free(request)
replacement = make_request(
"reused", list(range(100, 117)), HISPARSE_BLOCK_SIZE, sha256
)
assert _allocate_scheduled(manager, replacement, 17) is not None
new_blocks = list(manager.get_blocks(replacement.request_id).blocks[0])
pressure = host_pool.get_new_blocks(host_pool.get_num_free_blocks())
assert not {block.block_id for block in old_blocks[:2]} & {
block.block_id for block in pressure + new_blocks
}
# Only the page every worker finished writing is published.
assert old_blocks[0].block_hash is not None
assert all(block.block_hash is None for block in old_blocks[1:])
coordinator.update_spills({}, partial)
repeated = make_request("probe", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.get_computed_blocks(repeated)[1] == 2 * HISPARSE_BLOCK_SIZE
assert all(block.block_hash is None for block in new_blocks)
assert all(block.ref_cnt == 0 for block in old_blocks[:2])
coordinator.update_spills({}, partial)
assert all(block.ref_cnt == 0 for block in old_blocks[:2])
host_pool.free_blocks(pressure)
manager.free(replacement)
_publish_hisparse_pages(manager)
assert not coordinator.has_pending_work()
def test_hisparse_reset_prefix_cache_drops_copies():
"""Reset must forget GPU copies along with the host hashes they mirror."""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
request = make_request("request", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, num_new_tokens=len(tokens)) is not None
assert _allocate_scheduled(manager, request, num_new_tokens=len(tokens)) is not None
_publish_hisparse_pages(manager)
manager.free(request)
@@ -1162,7 +1462,9 @@ def test_hisparse_reused_copy_is_not_adopted():
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(original, num_new_tokens=len(tokens)) is not None
assert (
_allocate_scheduled(manager, original, num_new_tokens=len(tokens)) is not None
)
_publish_hisparse_pages(manager)
indexer_blocks = list(manager.get_blocks("original").blocks[1])
manager.free(original)
@@ -1175,7 +1477,8 @@ def test_hisparse_reused_copy_is_not_adopted():
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
computed, num_computed, _ = manager.get_computed_blocks(resumed)
assert num_computed == 3 * HISPARSE_BLOCK_SIZE
assert manager.allocate_slots(
assert _allocate_scheduled(
manager,
resumed,
num_new_tokens=len(tokens) - num_computed,
num_new_computed_tokens=num_computed,
@@ -2901,21 +3204,21 @@ def test_mm_prefix_caching():
(
kv_cache_utils.NONE_HASH,
tuple(all_token_ids[:block_size]),
(("aaa", 11),),
(("mm", "aaa", 11),),
)
)
assert block_hashes[1] == sha256(
(
block_hashes[0],
tuple(all_token_ids[block_size : block_size * 2]),
(("aaa", -5), ("bbb", 14)),
(("mm", "aaa", -5), ("mm", "bbb", 14)),
)
)
assert block_hashes[2] == sha256(
(
block_hashes[1],
tuple(all_token_ids[block_size * 2 : block_size * 3]),
(("bbb", -2),),
(("mm", "bbb", -2),),
)
)
@@ -2938,7 +3241,7 @@ def test_mm_prefix_caching():
(
block_hashes[2],
tuple(all_token_ids[3 * block_size :] + [8] * 5),
(("ccc", 0),),
(("mm", "ccc", 0),),
)
)
@@ -2984,7 +3287,11 @@ def test_cache_key_salting():
block_hashes = req0.block_hashes
assert len(block_hashes) == 3
assert block_hashes[0] == sha256(
(kv_cache_utils.NONE_HASH, tuple(token_ids[:block_size]), ("salt1",))
(
kv_cache_utils.NONE_HASH,
tuple(token_ids[:block_size]),
(("cache_salt", "salt1"),),
)
)
assert block_hashes[1] == sha256(
(block_hashes[0], tuple(token_ids[block_size : block_size * 2]), None)
@@ -3029,7 +3336,11 @@ def test_cache_key_salting():
block_hashes = req2.block_hashes
assert len(block_hashes) == 3
assert block_hashes[0] == sha256(
(kv_cache_utils.NONE_HASH, tuple(token_ids[:block_size]), ("salt2",))
(
kv_cache_utils.NONE_HASH,
tuple(token_ids[:block_size]),
(("cache_salt", "salt2"),),
)
)
assert block_hashes[1] == sha256(
(block_hashes[0], tuple(token_ids[block_size : block_size * 2]), None)
@@ -5067,7 +5378,8 @@ def test_can_fit_full_sequence_hisparse_caps_resident_pages():
)
assert (
manager.allocate_slots(
_allocate_scheduled(
manager,
request,
num_new_tokens=HISPARSE_BLOCK_SIZE,
full_sequence_must_fit=True,
@@ -5927,7 +6239,7 @@ def test_device_eviction_keeps_host_prefix():
"""Device eviction must not target a same-numbered host block."""
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
request = make_request("producer", list(range(64)), HISPARSE_BLOCK_SIZE, sha256)
assert manager.allocate_slots(request, 64) is not None
assert _allocate_scheduled(manager, request, 64) is not None
_publish_hisparse_pages(manager)
host, indexer, _, _ = manager.get_blocks(request.request_id).blocks
device_block = indexer[0]
+176 -54
View File
@@ -39,9 +39,11 @@ from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.utils.hashing import sha256
from vllm.v1.core.encoder_cache_manager import EncoderCacheManager
from vllm.v1.core.kv_cache_coordinator import HybridKVCacheCoordinator
from vllm.v1.core.kv_cache_manager import KVCacheManager
from vllm.v1.core.kv_cache_utils import get_request_block_hasher, init_none_hash
from vllm.v1.core.sched.diffusion_scheduler import (
DiffusionAsyncScheduler,
DiffusionScheduler,
diffusion_canvas_width,
)
from vllm.v1.core.sched.interface import PauseState
@@ -436,6 +438,52 @@ def test_schedule_partial_requests():
assert requests[2].request_id not in output.num_scheduled_tokens
def test_encoder_only_prompt_longer_than_budget_is_chunked():
"""The engine switches chunked prefill off for an encoder-only instance,
but the token budget must still split its prompt across steps instead of
leaving the request waiting forever."""
scheduler = create_scheduler(
model="llava-hf/llava-1.5-7b-hf",
max_num_batched_tokens=1024,
max_model_len=4096,
mm_encoder_only=True,
)
# EngineCore turns this off after config validation whenever the instance
# holds no KV cache, which is every encoder-only instance.
scheduler.scheduler_config.enable_chunked_prefill = False
(request,) = create_requests(
num_requests=1,
num_tokens=2500,
mm_positions=[[PlaceholderRange(offset=100, length=600)]],
)
scheduler.add_request(request)
def advance(output):
scheduler.update_from_output(
output,
ModelRunnerOutput(
req_ids=[request.request_id],
req_id_to_index={request.request_id: 0},
sampled_token_ids=[[]],
logprobs=None,
prompt_logprobs_dict={},
pooler_output=[],
),
)
first = scheduler.schedule()
assert first.num_scheduled_tokens[request.request_id] == 1024
assert request.request_id in first.scheduled_encoder_inputs
advance(first)
second = scheduler.schedule()
assert second.num_scheduled_tokens[request.request_id] == 1024
advance(second)
third = scheduler.schedule()
assert third.num_scheduled_tokens[request.request_id] == 452
@pytest.mark.parametrize("has_running", [True, False])
def test_schedule_prefills_gating(has_running: bool):
"""DP prefill-balancing gate: when `throttle_prefills` is True, a new
@@ -861,6 +909,49 @@ def test_update_from_output_routes_sampling_masks_by_request():
assert all(out.new_sampling_mask.offsets is None for out in outputs)
def test_update_from_output_routes_multi_position_sampling_masks():
scheduler = create_scheduler()
scheduler.return_sampling_mask = True
requests = create_requests(num_requests=2, max_tokens=10)
for req in requests:
req.num_computed_tokens = req.num_tokens
scheduler.requests[req.request_id] = req
scheduler.running.append(req)
req.status = RequestStatus.RUNNING
scheduler_output = SchedulerOutput(
scheduled_new_reqs=[],
scheduled_cached_reqs=CachedRequestData.make_empty(),
num_scheduled_tokens={req.request_id: 1 for req in requests},
total_num_scheduled_tokens=2,
scheduled_encoder_inputs={},
scheduled_spec_decode_tokens={},
num_common_prefix_blocks=[],
finished_req_ids=set(),
free_encoder_mm_hashes=[],
)
model_output = ModelRunnerOutput(
req_ids=[req.request_id for req in requests],
req_id_to_index={req.request_id: i for i, req in enumerate(requests)},
sampled_token_ids=[[1, 2], [3, 4, 5]],
logprobs=None,
prompt_logprobs_dict={},
pooler_output=[],
sampling_masks=SamplingMaskLists(
token_ids=np.array([1, 6, 2, 3, 7, 8, 4, 5, 9], dtype=np.int32),
offsets=np.array([0, 2, 3, 6, 7, 9]),
cu_num_generated_tokens=[0, 2, 5],
),
)
outputs = scheduler.update_from_output(scheduler_output, model_output)[0].outputs
assert [out.new_sampling_mask.to_nested_list() for out in outputs] == [
[[1, 6], [2]],
[[3, 7, 8], [4], [5, 9]],
]
def test_stop_via_update_from_output():
"""Test stopping behavior through update_from_output."""
scheduler = create_scheduler(num_speculative_tokens=1)
@@ -1562,13 +1653,7 @@ def test_scheduler_reset_prefix_cache():
assert not scheduler.reset_prefix_cache()
scheduler.aux_output_connector.reset.assert_not_called()
with pytest.raises(RuntimeError, match=r"pause\(mode='keep'\)"):
scheduler.reset_prefix_cache(reset_running_requests=True)
# pause(mode="keep") also waits for scheduled model outputs to drain.
scheduler.set_pause_state(PauseState.PAUSED_ALL)
with pytest.raises(RuntimeError, match="model output is in flight"):
scheduler.reset_prefix_cache(reset_running_requests=True)
# Pause completes pending model outputs before the caller resets the scheduler.
for request in requests:
request.num_in_flight_tokens = 0
@@ -6667,7 +6752,7 @@ def _create_hybrid_mamba_connector_scheduler(
num_blocks: int = 100,
supports_divergent_hits: bool = True,
) -> Scheduler:
"""FA + Mamba ("all" cache mode) scheduler with a MockKVConnector."""
"""FA + Mamba ("align" cache mode) scheduler with a MockKVConnector."""
model_config = ModelConfig(
model="facebook/opt-125m",
trust_remote_code=True,
@@ -6688,7 +6773,7 @@ def _create_hybrid_mamba_connector_scheduler(
cache_config=CacheConfig(
block_size=block_size,
enable_prefix_caching=True,
mamba_cache_mode="all",
mamba_cache_mode="align",
),
kv_transfer_config=KVTransferConfig(
kv_connector="MockKVConnector",
@@ -6720,7 +6805,7 @@ def _create_hybrid_mamba_connector_scheduler(
block_size=block_size,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="all",
mamba_cache_mode="align",
),
),
],
@@ -6736,6 +6821,33 @@ def _create_hybrid_mamba_connector_scheduler(
)
def _seed_hybrid_prefix(
manager: KVCacheManager, num_blocks: int, block_size: int
) -> tuple[list[int], list[int]]:
"""Prefill a prefix one block per step so that align-mode Mamba caches
the state at every block boundary. Returns the FA and Mamba block ids."""
[fill] = create_requests(
num_requests=1,
num_tokens=num_blocks * block_size,
max_tokens=1,
same_prompt=True,
block_size=block_size,
req_ids=["fill"],
)
computed_blocks, num_computed, _ = manager.get_computed_blocks(fill)
assert num_computed == 0
mamba_ids = []
for i in range(num_blocks):
manager.allocate_slots(
fill, block_size, new_computed_blocks=computed_blocks if i == 0 else None
)
fill.num_computed_tokens += block_size
fa_ids, group_mamba_ids = manager.get_block_ids(fill.request_id)
mamba_ids.append(group_mamba_ids[i])
manager.free(fill)
return fa_ids, mamba_ids
@pytest.mark.parametrize(
"matched_tokens,expected_num_computed",
[
@@ -6761,23 +6873,8 @@ def test_hybrid_per_group_hit_divergence_with_connector(
manager = scheduler.kv_cache_manager
assert isinstance(manager.coordinator, HybridKVCacheCoordinator)
# Seed a 4-block prefix so both groups cache all four boundaries
# (mamba cache mode "all" caches every block's state densely).
[fill] = create_requests(
num_requests=1,
num_tokens=4 * block_size,
max_tokens=1,
same_prompt=True,
block_size=block_size,
req_ids=["fill"],
)
computed_blocks, num_computed, _ = manager.get_computed_blocks(fill)
blocks = manager.allocate_slots(
fill, fill.num_tokens, num_computed, computed_blocks
)
fa_ids = [b.block_id for b in blocks.blocks[0]]
mamba_ids = [b.block_id for b in blocks.blocks[1]]
manager.free(fill)
# Seed a 4-block prefix so both groups cache all four boundaries.
fa_ids, mamba_ids = _seed_hybrid_prefix(manager, 4, block_size)
# Evict the FA tail and the middle mamba states; block 0 (both groups)
# and the deep mamba state at block 3 survive.
@@ -6801,8 +6898,8 @@ def test_hybrid_per_group_hit_divergence_with_connector(
scheduler.add_request(replay)
output = scheduler.schedule()
num_scheduled = output.num_scheduled_tokens[replay.request_id]
assert replay.num_tokens - num_scheduled == expected_num_computed
[new_req] = output.scheduled_new_reqs
assert new_req.num_computed_tokens == expected_num_computed
@pytest.mark.parametrize(
@@ -6837,20 +6934,7 @@ def test_hybrid_fa_deeper_hit_respects_connector_lookup_policy(
assert isinstance(manager.coordinator, HybridKVCacheCoordinator)
# Seed a 4-block prefix in both groups.
[fill] = create_requests(
num_requests=1,
num_tokens=4 * block_size,
max_tokens=1,
same_prompt=True,
block_size=block_size,
req_ids=["fill"],
)
computed_blocks, num_computed, _ = manager.get_computed_blocks(fill)
blocks = manager.allocate_slots(
fill, fill.num_tokens, num_computed, computed_blocks
)
mamba_ids = [b.block_id for b in blocks.blocks[1]]
manager.free(fill)
_, mamba_ids = _seed_hybrid_prefix(manager, 4, block_size)
# Keep all FA blocks; evict every mamba state but block 0. FA reaches 4
# blocks, the mamba hit only reaches 1 -> diverged (FA > Mamba).
@@ -6871,8 +6955,8 @@ def test_hybrid_fa_deeper_hit_respects_connector_lookup_policy(
scheduler.add_request(replay)
output = scheduler.schedule()
num_scheduled = output.num_scheduled_tokens[replay.request_id]
assert replay.num_tokens - num_scheduled == expected_num_computed
[new_req] = output.scheduled_new_reqs
assert new_req.num_computed_tokens == expected_num_computed
def _make_encoder_instance_request(scheduler, text_prefix=8, image_tokens=16):
@@ -7115,14 +7199,15 @@ def diffusion_model_runner(monkeypatch):
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
def _diffusion_scheduler(**kwargs) -> DiffusionAsyncScheduler:
def _diffusion_scheduler(async_scheduling: bool = True, **kwargs) -> DiffusionScheduler:
scheduler_cls = DiffusionAsyncScheduler if async_scheduling else DiffusionScheduler
scheduler = create_scheduler(
async_scheduling=True,
async_scheduling=async_scheduling,
diffusion_canvas_length=8,
scheduler_cls=DiffusionAsyncScheduler,
scheduler_cls=scheduler_cls,
**kwargs,
)
assert isinstance(scheduler, DiffusionAsyncScheduler)
assert isinstance(scheduler, scheduler_cls)
return scheduler
@@ -7133,7 +7218,7 @@ def test_diffusion_scheduler_is_selected_by_default(async_scheduling):
async_scheduling=async_scheduling, diffusion_canvas_length=8
).vllm_config.scheduler_config
assert config.get_scheduler_cls() is (
DiffusionAsyncScheduler if config.async_scheduling else Scheduler
DiffusionAsyncScheduler if config.async_scheduling else DiffusionScheduler
)
@@ -7155,10 +7240,13 @@ def test_diffusion_scheduler_narrows_the_canvas_per_request():
@pytest.mark.parametrize("structured", [False, True])
@pytest.mark.parametrize("async_scheduling", [False, True])
@pytest.mark.usefixtures("diffusion_model_runner")
def test_diffusion_scheduler_trims_full_width_worker_drafts(structured):
def test_diffusion_scheduler_trims_full_width_worker_drafts(
structured, async_scheduling
):
"""Padded worker drafts must be narrowed before scheduling or grammar validation."""
scheduler = _diffusion_scheduler()
scheduler = _diffusion_scheduler(async_scheduling=async_scheduling)
wide = _diffusion_request("wide", {})
narrow = _diffusion_request("narrow", {"diffusion_canvas_length": 4})
for request in (wide, narrow):
@@ -7173,8 +7261,12 @@ def test_diffusion_scheduler_trims_full_width_worker_drafts(structured):
)
tokens = list(range(8)) if structured else [-1] * 8
drafts = DraftTokenIds(["wide", "narrow"], [tokens.copy(), tokens.copy()])
output = scheduler.schedule()
scheduler.update_draft_token_ids_in_output(drafts, output)
if async_scheduling:
output = scheduler.schedule()
scheduler.update_draft_token_ids_in_output(drafts, output)
else:
scheduler.update_draft_token_ids(drafts)
output = scheduler.schedule()
assert output.scheduled_spec_decode_tokens == {
"wide": tokens,
@@ -7186,6 +7278,36 @@ def test_diffusion_scheduler_trims_full_width_worker_drafts(structured):
assert narrow.structured_output_request.grammar.seen == [tokens[:4]]
@pytest.mark.parametrize(
"sampled, expected_status",
[
pytest.param([], RequestStatus.RUNNING, id="denoising"),
pytest.param([1] * 4, RequestStatus.FINISHED_LENGTH_CAPPED, id="final"),
],
)
@pytest.mark.usefixtures("diffusion_model_runner")
def test_sync_diffusion_step_commits_only_emitted_tokens(sampled, expected_status):
"""An empty denoising step reuses the canvas; a completed read emits it."""
scheduler = _diffusion_scheduler(async_scheduling=False)
request = _diffusion_request(
"read", {"diffusion_canvas_length": 4, "diffusion_read_only": True}
)
request.max_tokens = request.sampling_params.max_tokens = 4
scheduler.add_request(request)
_model_output(scheduler, scheduler.schedule(), [[]])
scheduler.update_draft_token_ids(
DraftTokenIds([request.request_id], [list(range(8))])
)
output = scheduler.schedule()
assert output.num_scheduled_tokens == {request.request_id: 4}
_model_output(scheduler, output, [sampled])
assert request.num_computed_tokens == request.num_prompt_tokens + len(sampled)
assert list(request.output_token_ids) == sampled
assert request.status == expected_status
@pytest.mark.usefixtures("diffusion_model_runner")
def test_diffusion_scheduler_defers_a_read_with_every_step_in_flight():
scheduler = _diffusion_scheduler()
+3
View File
@@ -60,6 +60,7 @@ def create_scheduler(
long_prefill_token_threshold: int = 0,
long_prefill_token_threshold_adaptive: bool = False,
disable_chunked_mm_input: bool = False,
mm_encoder_only: bool = False,
use_kv_connector: None | bool | str | MockKVConfig = None,
kv_role: str = "kv_both",
num_blocks: int = 10000,
@@ -109,6 +110,8 @@ def create_scheduler(
# SchedulerConfig one, so both must agree.
max_model_len=max_model_len,
)
if mm_encoder_only:
model_config.multimodal_config.mm_encoder_only = True
if use_ec_connector and ec_role == "ec_producer":
model_config.multimodal_config = MultiModalConfig()
if max_model_len is None:
@@ -257,7 +257,7 @@ class TestCudagraphDispatcher:
def test_get_capture_descs_empty_when_not_initialized(self):
"""Test that get_capture_descs returns empty list when keys not initialized."""
comp_config = CompilationConfig(
cudagraph_mode="FULL",
cudagraph_mode=CUDAGraphMode.FULL,
mode=CompilationMode.NONE,
cudagraph_capture_sizes=[1, 8],
)
@@ -419,7 +419,7 @@ def _run_and_monitor_call(
def test_capture_replay_bypass_logic():
comp_config = CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
cudagraph_mode="FULL",
cudagraph_mode=CUDAGraphMode.FULL,
cudagraph_capture_sizes=[1, 2],
)
vllm_config = _create_vllm_config(comp_config)
@@ -489,7 +489,7 @@ def test_nested_wrappers():
"""Tests a scenario with a PIECEWISE wrapper inside a FULL one."""
comp_config = CompilationConfig(
mode=CompilationMode.VLLM_COMPILE,
cudagraph_mode="FULL",
cudagraph_mode=CUDAGraphMode.FULL,
cudagraph_capture_sizes=[1],
)
vllm_config = _create_vllm_config(comp_config)
+4 -2
View File
@@ -38,7 +38,7 @@ def _reset_graph_pool_id():
def _create_vllm_config() -> MagicMock:
compilation_config = CompilationConfig(
cudagraph_mode="FULL",
cudagraph_mode=CUDAGraphMode.FULL,
cudagraph_capture_sizes=[4],
)
compilation_config.max_cudagraph_capture_size = 4
@@ -132,6 +132,7 @@ def test_piecewise_capture_uses_pcp_dummy_slot_mappings():
pcp_world_size=pcp_world_size,
pcp_rank=0,
device=torch.device("cpu"),
shard_decode_requests=False,
max_num_reqs=num_reqs,
max_num_tokens=num_tokens,
block_tables=pcp_block_tables,
@@ -264,7 +265,7 @@ def _create_decode_vllm_config(
use_recoverssm: bool = False,
) -> MagicMock:
compilation_config = CompilationConfig(
cudagraph_mode="FULL_AND_PIECEWISE",
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE,
cudagraph_capture_sizes=capture_sizes,
)
compilation_config.max_cudagraph_capture_size = capture_sizes[-1]
@@ -473,6 +474,7 @@ def test_dynamic_spec_decode_shared_token_count_stays_reachable(monkeypatch):
assert any(len(descs) > 1 for descs in by_num_tokens.values())
for desc in full_descs:
assert desc.num_reqs is not None
assert desc in manager._candidates[(desc.num_tokens, 0)], desc
assert (
manager.dispatch(
+53 -3
View File
@@ -14,7 +14,7 @@ Test organization:
from collections.abc import Hashable
from types import SimpleNamespace
from typing import Any
from typing import Any, cast
from unittest.mock import MagicMock, patch
import pytest
@@ -100,6 +100,50 @@ class _MockModel(SupportsEncoderCudaGraph):
def get_encoder_cudagraph_budget_range(self, vllm_config):
return (self._min_budget, self._max_budget)
def get_max_frames_per_video(self) -> int:
return 0
def get_encoder_cudagraph_item_specs(
self, mm_kwargs: dict[str, Any]
) -> list[EncoderItemSpec]:
return []
def prepare_encoder_cudagraph_capture_inputs(
self,
token_budget: int,
max_batch_size: int,
max_frames_per_batch: int,
device: torch.device,
dtype: torch.dtype,
path: str = "default",
axis_keys: tuple[Hashable, ...] | None = None,
) -> EncoderCudaGraphCaptureInputs:
return EncoderCudaGraphCaptureInputs(values={})
def prepare_encoder_cudagraph_replay_buffers(
self,
mm_kwargs: dict[str, Any],
max_batch_size: int,
max_frames_per_batch: int,
path: str = "default",
) -> EncoderCudaGraphReplayBuffers:
return EncoderCudaGraphReplayBuffers(values={})
def encoder_cudagraph_forward(
self, inputs: dict[str, torch.Tensor], path: str = "default"
) -> torch.Tensor:
return torch.zeros(0)
def encoder_eager_forward(
self, mm_kwargs: dict[str, Any], path: str = "default"
) -> torch.Tensor:
return torch.zeros(0)
def select_encoder_cudagraph_items(
self, mm_kwargs: dict[str, Any], indices: list[int]
) -> dict[str, Any]:
return {}
def _make_manager_with_budgets(budgets: list[int]) -> EncoderCudaGraphManager:
"""Create a minimal EncoderCudaGraphManager with only token_budgets set.
@@ -594,6 +638,7 @@ def test_eonly_capture_preserves_outputs_across_replay_and_fallback(profile_only
ECConnectorBase,
ECConnectorMetadata,
)
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.worker.gpu.ec_connector import ActiveECConnector
from vllm.v1.worker.gpu.mm.encoder_runner import EncoderRunner
from vllm.v1.worker.mm_encoder_model_runner import MMEncoderModelRunner
@@ -629,8 +674,11 @@ def test_eonly_capture_preserves_outputs_across_replay_and_fallback(profile_only
"vllm.v1.worker.gpu.ec_connector.get_ec_transfer", return_value=connector
):
ec = ActiveECConnector(SimpleNamespace(), cache)
scheduled = SimpleNamespace(
ec_connector_metadata=ECConnectorMetadata(), finished_req_ids=frozenset()
scheduled = cast(
SchedulerOutput,
SimpleNamespace(
ec_connector_metadata=ECConnectorMetadata(), finished_req_ids=frozenset()
),
)
saved_outputs: list[tuple[torch.Tensor, torch.Tensor]] = []
# Mixed sizes exercise packing order; 64 is the boundary, 81 falls back.
@@ -643,6 +691,7 @@ def test_eonly_capture_preserves_outputs_across_replay_and_fallback(profile_only
outputs = manager.execute(inputs)
assert outputs is not None
cache[str(len(cache))] = outputs[0]
assert ec_output is not None
assert ec_output.finished_sending is None
assert outputs is not None
for actual, eager in zip(outputs, expected):
@@ -656,6 +705,7 @@ def test_eonly_capture_preserves_outputs_across_replay_and_fallback(profile_only
connector.get_finished.return_value = (set(cache), None)
with ec.maybe_get_output(scheduled) as ec_output:
pass
assert ec_output is not None
assert ec_output.finished_sending == set(cache)
+5 -32
View File
@@ -155,7 +155,7 @@ def test_v1_generation_is_deterministic_across_batch_sizes_with_needle(
# Ensure engines are shutdown to free GPU/VRAM across test sessions
if llm is not None:
with contextlib.suppress(Exception):
llm.shutdown()
llm.llm_engine.engine_core.shutdown()
@skip_unsupported
@@ -176,17 +176,6 @@ def test_logprobs_bitwise_batch_invariance_bs1_vs_bsN(
random.seed(seed)
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
# For batch invariance, disable custom all-reduce to ensure deterministic
# all-reduce operations (custom all-reduce may not be deterministic)
import vllm.envs as envs
disable_custom_ar = envs.VLLM_BATCH_INVARIANT
if disable_custom_ar:
print(f"\n{'=' * 80}")
print(f"BATCH INVARIANCE MODE: Disabling custom all-reduce (TP={tp_size})")
print(f"{'=' * 80}\n")
llm = LLM(
model=TEST_MODEL,
tensor_parallel_size=tp_size,
@@ -456,7 +445,7 @@ def test_logprobs_bitwise_batch_invariance_ragged_chunked_prefill(backend):
)
finally:
with contextlib.suppress(Exception):
llm.shutdown()
llm.llm_engine.engine_core.shutdown()
@skip_unsupported
@@ -505,7 +494,7 @@ def test_simple_generation(backend):
finally:
with contextlib.suppress(Exception):
llm.shutdown()
llm.llm_engine.engine_core.shutdown()
@skip_unsupported
@@ -744,15 +733,6 @@ def test_decode_logprobs_match_prefill_logprobs(
random.seed(seed)
tp_size = int(os.getenv("VLLM_TEST_TP_SIZE", "1"))
import vllm.envs as envs
disable_custom_ar = envs.VLLM_BATCH_INVARIANT
if disable_custom_ar:
print(f"\n{'=' * 80}")
print(f"BATCH INVARIANCE MODE: Disabling custom all-reduce (TP={tp_size})")
print(f"{'=' * 80}\n")
llm = LLM(
model=TEST_MODEL,
tensor_parallel_size=tp_size,
@@ -815,15 +795,8 @@ def test_decode_logprobs_match_prefill_logprobs(
if token_idx == 0:
prefix_prompt = prompt
else:
# Use the partial output text up to this token
# We'll need to construct this from the full output
prefix_output = decode_output.outputs[0]
# Get the text for tokens 0 to token_idx-1
# Unfortunately, we don't have per-token text, so we'll use
# a different approach: run prefill with prompt + tokens[0:token_idx]
# Actually, we need to get the actual text. Let's use a workaround:
# Run a generation with max_tokens = token_idx to get that prefix
# No per-token text, so regenerate with max_tokens = token_idx
# to get the prefix text
prefix_sp = SamplingParams(
temperature=0.0,
max_tokens=token_idx,
@@ -12,6 +12,7 @@ from PIL import Image
from utils import _extract_step_logprobs, skip_if_not_cuda
from vllm import LLM, SamplingParams
from vllm.inputs import TextPrompt
VLM_TEST_MODEL = os.getenv("VLLM_VLM_TEST_MODEL", "Qwen/Qwen3-VL-2B-Instruct")
@@ -30,8 +31,8 @@ def _make_image(seed: int, size: int) -> Image.Image:
return Image.fromarray(rng.integers(0, 255, (size, size, 3), dtype=np.uint8))
def _make_inputs(input_type: str, num_reqs: int) -> list[dict]:
inputs = []
def _make_inputs(input_type: str, num_reqs: int) -> list[TextPrompt]:
inputs: list[TextPrompt] = []
for i in range(num_reqs):
if input_type == "image":
prompt = IMAGE_PROMPT
@@ -54,7 +55,7 @@ def _make_inputs(input_type: str, num_reqs: int) -> list[dict]:
return inputs
def _assert_batch_invariant(llm: LLM, inputs: list[dict], sampling) -> None:
def _assert_batch_invariant(llm: LLM, inputs: list[TextPrompt], sampling) -> None:
bs1 = [
_extract_step_logprobs(llm.generate([inp], sampling, use_tqdm=False)[0])
for inp in inputs
@@ -134,4 +135,4 @@ def _run_vlm_batch_invariance(
_assert_batch_invariant(llm, inputs, sampling)
finally:
with contextlib.suppress(Exception):
llm.shutdown()
llm.llm_engine.engine_core.shutdown()
@@ -221,13 +221,15 @@ def _make_cutlass_fp4_moe_batch_invariant_case(
in_dtype=dtype,
activation=activation,
)
prepare_finalize = maybe_make_prepare_finalize(
moe=moe_config,
quant_config=quant_config,
allow_new_interface=True,
use_monolithic=False,
)
assert prepare_finalize is not None
kernel = mk.FusedMoEKernel(
maybe_make_prepare_finalize(
moe=moe_config,
quant_config=quant_config,
allow_new_interface=True,
use_monolithic=False,
),
prepare_finalize,
CutlassExpertsFp4(
moe_config=moe_config,
quant_config=quant_config,
@@ -97,4 +97,4 @@ def test_dense_nvfp4_generation_is_deterministic_across_batch_sizes_e2e(backend)
finally:
if llm is not None:
with contextlib.suppress(Exception):
llm.shutdown()
llm.llm_engine.engine_core.shutdown()
@@ -524,6 +524,7 @@ def test_rms_norm_batch_invariance(dtype):
batch[4] = row[0]
out_batch = rms_norm_batch_invariant(batch, weight, eps=eps)
assert isinstance(out_single, torch.Tensor) and isinstance(out_batch, torch.Tensor)
assert torch.equal(out_single[0], out_batch[4]), (
"rms_norm output for a row differs when batch context changes"
)
@@ -547,6 +548,7 @@ if __name__ == "__main__":
# Batch-invariant implementation
triton_output = rms_norm_batch_invariant(input_tensor, weight, eps=eps)
assert isinstance(triton_output, torch.Tensor)
# Compare
max_diff = (triton_output - reference_output).abs().max().item()
+5 -1
View File
@@ -11,6 +11,7 @@ import pytest
import torch
from tests.utils import RemoteOpenAIServer
from vllm.platforms import current_platform
from vllm.utils.import_utils import has_deep_ep
# Detect Blackwell / B200 (compute capability 10.x)
@@ -30,7 +31,10 @@ DP_SIZE = 2
# GSM8K eval configuration
NUM_QUESTIONS = 256 # Fast eval for CI; but must be large enough to hit dbo thresholds
NUM_SHOTS = 5 # Few-shot examples
MIN_ACCURACY = 0.62 # Expected 0.64 with 2% buffer (based on vLLM test data)
# Expected 0.64 with 2% buffer (based on vLLM test data)
# On ROCm, widened to 0.61 after observing 0.617 amd-ci nightly flake twice.
MIN_ACCURACY = 0.61 if current_platform.is_rocm() else 0.62
# Increase max_num_seqs to trigger DBO for decode batches
# With 64 seqs, decode batches should exceed the 32 token threshold
+1 -1
View File
@@ -61,7 +61,7 @@ async def test_run_eagle_dp(monkeypatch: pytest.MonkeyPatch, attn_backend: str):
data_parallel_backend="mp", # ray takes more time
trust_remote_code=True,
max_model_len=16384,
attention_config={"backend": attn_backend}, # type: ignore[arg-type]
attention_config={"backend": attn_backend},
)
eagle_engine_args = replace(
+491
View File
@@ -0,0 +1,491 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Numerical checks against an independent, teacher-forced target model."""
import json
import math
from collections import Counter
from dataclasses import dataclass
from functools import lru_cache
import torch
import xgrammar as xgr
from tokenizers.decoders import DecodeStream
from tests.conftest import HfRunner
from vllm import SamplingParams
from vllm.logprobs import Logprob
from vllm.outputs import RequestOutput
from vllm.tokenizers.detokenizer_utils import convert_ids_list_to_tokens
from vllm.v1.engine.logprobs import LogprobsProcessor
@dataclass(frozen=True)
class AccuracyTolerance:
logprob_atol: float
greedy_atol: float
logprob_mean_atol: float = 0.1
greedy_total_atol: float = 0.5
def logprob_error(self, reference: torch.Tensor) -> torch.Tensor:
return torch.full_like(reference, self.logprob_atol)
def check_first_divergence(
baseline: RequestOutput,
actual: RequestOutput,
params: SamplingParams,
tolerance: AccuracyTolerance,
context: str,
) -> None:
"""Require the two engines' scores to justify their first different choice."""
assert baseline.finished and actual.finished, context
assert len(baseline.outputs) == len(actual.outputs) == 1, context
assert baseline.prompt_token_ids is not None, context
assert baseline.prompt_token_ids == actual.prompt_token_ids, context
base, other = baseline.outputs[0], actual.outputs[0]
position = next(
(i for i, (a, b) in enumerate(zip(base.token_ids, other.token_ids)) if a != b),
None,
)
if position is None:
assert len(base.token_ids) == len(other.token_ids), (
f"{context}: one completion is a strict prefix of the other"
)
assert (base.finish_reason, base.stop_reason) == (
other.finish_reason,
other.stop_reason,
), f"{context}: identical tokens have different stopping reasons"
return
assert params.logprobs is not None and params.logprobs > 0, context
assert params.temperature == 0.0, context
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
assert not params.logit_bias, context
a, b = base.token_ids[position], other.token_ids[position]
counts = Counter(base.token_ids[:position])
context = (
f"{context}, first divergence position={position}, "
f"baseline token={a}, actual token={b}"
)
for side, completion, selected, alternative in (
("baseline", base, a, b),
("actual", other, b, a),
):
assert completion.logprobs is not None, context
assert len(completion.logprobs) == len(completion.token_ids), context
scores = completion.logprobs[position]
assert selected in scores, f"{context}, {side}: missing selected token score"
chosen = scores[selected].logprob
assert math.isfinite(chosen), f"{context}, {side}: non-finite selected score"
known = alternative in scores
if known:
competing = scores[alternative].logprob
assert math.isfinite(competing), (
f"{context}, {side}: divergent token has a non-finite score"
)
else:
# The sampled token may be returned in addition to the requested
# top-k. An omitted token's raw score is bounded by the kth score.
top_scores = [
score.logprob
for token, score in scores.items()
if len(scores) == params.logprobs or token != selected
]
assert len(top_scores) == params.logprobs, context
assert not any(math.isnan(score) for score in top_scores), context
competing = min(top_scores)
# Both candidates were emitted with the same history and constraints;
# frequency penalties are the only supported transform changing their
# finite score difference. Prompt tokens do not contribute to counts.
chosen -= params.frequency_penalty * counts[selected]
competing -= params.frequency_penalty * counts[alternative]
gap = chosen - competing
detail = (
f"{context}, {side}: selected={selected}, alternative={alternative}, "
f"{'gap' if known else 'gap lower bound'}={gap}"
)
if known:
# Log-softmax and reconstructing penalties may round in FP32, but
# a near tie cannot excuse selecting the engine's own worse token.
assert gap >= -1e-5, f"{detail}: selected token is below its alternative"
assert gap <= tolerance.greedy_atol, (
f"{detail}: divergence exceeds near-tie bound={tolerance.greedy_atol}"
)
def check_logprobs(
scores: dict[int, Logprob],
reference: torch.Tensor,
token: int,
requested: int,
tolerance: AccuracyTolerance,
context: str,
) -> torch.Tensor:
"""Check every score, reported rank, and the complete requested top-k."""
assert all(0 <= token_id < reference.numel() for token_id in scores), context
assert token in scores, f"{context}: missing score for token {token}"
assert max(1, requested) <= len(scores) <= requested + 1, context
assert not torch.isnan(reference).any(), context
assert all(s.rank is not None and s.rank >= 1 for s in scores.values()), context
ids = torch.tensor(list(scores), device=reference.device)
actual = torch.tensor(
[score.logprob for score in scores.values()], device=reference.device
)
expected = reference[ids]
finite = torch.isfinite(expected)
assert torch.equal(torch.isfinite(actual), finite), (
f"{context}: finite/masked logprobs differ: {scores}"
)
assert torch.equal(actual[~finite], expected[~finite]), context
assert (actual[finite] <= 0).all(), f"{context}: positive log probability"
errors = (actual[finite] - expected[finite]).abs()
bounds = tolerance.logprob_error(expected[finite])
assert (errors <= bounds).all(), (
f"{context}: token IDs={ids[finite].tolist()}, "
f"actual={actual[finite].tolist()}, reference={expected[finite].tolist()}, "
f"error={errors.tolist()}, bound={bounds.tolist()}"
)
for token_id, score in scores.items():
value = reference[token_id]
if not torch.isfinite(value):
continue
delta = tolerance.logprob_error(value)
lower = 1 + int((reference > value + 2 * delta).sum())
upper = max(1, int((reference >= value - 2 * delta).sum()))
assert score.rank is not None and lower <= score.rank <= upper, (
f"{context}: token={token_id}, rank={score.rank}, "
f"reference rank interval=[{lower}, {upper}]"
)
if requested:
# The sampled token can be outside top-k even when it ties the kth
# score. Its strict-greater rank can therefore duplicate a top-k rank.
top_ids = (
list(scores)
if len(scores) == requested
else [t for t in scores if t != token]
)
assert len(top_ids) == requested, f"{context}: incomplete top-k"
assert {scores[t].rank for t in top_ids} == set(range(1, requested + 1)), (
context
)
ordered = sorted(top_ids, key=lambda t: scores[t].rank)
assert all(
scores[a].logprob >= scores[b].logprob for a, b in zip(ordered, ordered[1:])
), f"{context}: top-k scores disagree with their reported ranks"
boundary = reference.topk(requested).values[-1]
if torch.isfinite(boundary):
delta = tolerance.logprob_error(boundary)
required = (reference > boundary + 2 * delta).nonzero().flatten()
assert set(required.tolist()) <= scores.keys(), (
f"{context}: missing an unambiguously top-{requested} token"
)
assert (reference[top_ids] >= boundary - 2 * delta).all(), (
f"{context}: returned token below the top-{requested} boundary"
)
return errors
def check_greedy_token(
logits: torch.Tensor,
token: int,
tolerance: AccuracyTolerance,
context: str,
) -> float:
assert not torch.isnan(logits).any(), context
assert torch.isfinite(logits[token]), (
f"{context}: selected token {token} is forbidden by the sampling parameters"
)
best = int(logits.argmax())
gap = float(logits[best] - logits[token])
assert gap <= tolerance.greedy_atol, (
f"{context}: selected token={token}, reference best={best}, "
f"logit gap={gap}, bound={tolerance.greedy_atol}"
)
return gap
def check_accuracy_budget(errors, gaps, tolerance, context):
"""Reject systematic sub-bound errors within each request and score stream."""
if errors:
finite_errors = torch.cat(errors)
if finite_errors.numel():
mean_error = float(finite_errors.mean())
assert mean_error <= tolerance.logprob_mean_atol, (
f"{context}: mean logprob error={mean_error}, "
f"bound={tolerance.logprob_mean_atol}"
)
assert sum(gaps) <= tolerance.greedy_total_atol, (
f"{context}: total greedy logit gap={sum(gaps)}, "
f"bound={tolerance.greedy_total_atol}"
)
def _check_decoded_tokens(processor, scores, history, context):
ids = list(scores)
decoded = convert_ids_list_to_tokens(processor.tokenizer, ids)
decoded = processor._verify_tokens(decoded, ids, context_token_ids=history[-4:])
for token, text in zip(ids, decoded, strict=True):
assert scores[token].decoded_token == text, (
f"{context}: incorrect decoded text for token {token}"
)
@torch.inference_mode()
def check_request_accuracy(
hf: HfRunner,
request: RequestOutput,
params: SamplingParams,
tolerance: AccuracyTolerance,
context: str,
) -> None:
"""Score the actual continuation, including positions after any divergence."""
assert request.finished and len(request.outputs) == 1, context
(completion,) = request.outputs
prompt = request.prompt_token_ids
assert prompt is not None and len(prompt) > 0, context
tokens = list(completion.token_ids)
assert params.max_tokens is not None and 0 < len(tokens) <= params.max_tokens, (
context
)
# Incremental decoding buffers incomplete UTF-8; decoding the final token
# list in one call can incorrectly append a replacement character.
stream = DecodeStream(skip_special_tokens=params.skip_special_tokens)
tokenizer = hf.tokenizer.backend_tokenizer
for token in prompt:
stream.step(tokenizer, token)
visible = tokens
if completion.finish_reason == "stop" and not params.include_stop_str_in_output:
visible = tokens[:-1]
expected_text = "".join(stream.step(tokenizer, token) or "" for token in visible)
assert completion.text == expected_text, (
f"{context}: decoded text does not match generated token IDs"
)
inputs = torch.tensor([prompt + tokens], device=hf.device)
logits = hf.model(input_ids=inputs, use_cache=False).logits[0].float()
# Use the existing byte-fallback handling with an independent request
# history; numerical scores always come from the HF model above.
decoder = LogprobsProcessor(
tokenizer=hf.tokenizer,
logprobs=None,
prompt_logprobs=None,
cumulative_logprob=None,
num_logprobs=None,
num_prompt_logprobs=None,
)
# Prompt token i is predicted by the causal logits at position i - 1.
if params.prompt_logprobs is None:
assert request.prompt_logprobs is None, context
else:
assert request.prompt_logprobs is not None, context
assert len(request.prompt_logprobs) == len(prompt), context
assert request.prompt_logprobs[0] is None, context
errors = []
for i, scores in enumerate(request.prompt_logprobs[1:], 1):
assert scores is not None, context
_check_decoded_tokens(decoder, scores, prompt[1:i], context)
errors.append(
check_logprobs(
scores,
logits[i - 1].log_softmax(-1),
prompt[i],
params.prompt_logprobs,
tolerance,
f"{context}, prompt position={i}",
)
)
check_accuracy_budget(errors, [], tolerance, f"{context}, prompt logprobs")
if params.logprobs is None:
assert completion.logprobs is None, context
else:
assert completion.logprobs is not None, context
assert len(completion.logprobs) == len(tokens), context
reference = SamplingReference(
hf.tokenizer,
logits.shape[-1],
hf.model.generation_config.to_dict(),
params,
)
errors = []
gaps = []
for i, token in enumerate(tokens):
raw, processed = reference.distributions(
logits[len(prompt) + i - 1], tokens[:i]
)
position = f"{context}, generated position={i}"
gaps.append(check_greedy_token(processed, token, tolerance, position))
if completion.logprobs is not None:
_check_decoded_tokens(decoder, completion.logprobs[i], tokens[:i], position)
errors.append(
check_logprobs(
completion.logprobs[i],
raw.log_softmax(-1),
token,
params.logprobs,
tolerance,
position,
)
)
check_accuracy_budget(errors, gaps, tolerance, f"{context}, completion")
# Advance the grammar through the last token too; an incomplete JSON prefix
# is allowed at max_tokens, but every emitted token must remain valid.
reference.accept_history(tokens)
check_stopping(
tokens,
completion.finish_reason,
reference.stop_ids,
params,
context,
eos_token_id=hf.tokenizer.eos_token_id,
stop_reason=completion.stop_reason,
)
def check_stopping(
tokens,
finish_reason,
stop_ids,
params,
context,
*,
eos_token_id: int | None,
stop_reason: int | str | None,
):
assert not params.ignore_eos and not params.stop, context
assert not stop_ids.intersection(tokens[:-1]), (
f"{context}: generation continued after a stop token"
)
if tokens[-1] in stop_ids:
assert finish_reason == "stop", (
f"{context}: stop token did not terminate output"
)
expected_stop_reason = None if tokens[-1] == eos_token_id else tokens[-1]
assert stop_reason == expected_stop_reason, (
f"{context}: stop reason={stop_reason}, expected={expected_stop_reason}"
)
else:
assert finish_reason == "length" and len(tokens) == params.max_tokens, context
assert stop_reason is None, f"{context}: length cap has a stop reason"
@lru_cache(maxsize=4)
def _compiler(tokenizer, vocab_size: int):
info = xgr.TokenizerInfo.from_huggingface(tokenizer, vocab_size=vocab_size)
return xgr.GrammarCompiler(info, max_threads=1, cache_enabled=True)
class SamplingReference:
"""One request's reference; histories must grow without changing their prefix."""
def __init__(
self,
tokenizer,
vocab_size: int,
generation_config: dict,
params: "SamplingParams",
):
assert params.temperature == 0.0, "Only the original greedy matrix is supported"
assert params.presence_penalty == 0.0 and params.repetition_penalty == 1.0
assert params.allowed_token_ids is None and not params.logit_bias
self.vocab_size = vocab_size
self.min_tokens = params.min_tokens
self.frequency_penalty = params.frequency_penalty
self.stop_ids = set(params.stop_token_ids or [])
for eos in (tokenizer.eos_token_id, generation_config.get("eos_token_id")):
if eos is not None:
self.stop_ids.update([eos] if isinstance(eos, int) else eos)
assert all(0 <= token < vocab_size for token in self.stop_ids)
# Match public bad-word tokenization semantics without using sampler code.
self.bad_words: list[list[int]] = []
for word in params.bad_words or []:
plain = tokenizer.encode(word.lstrip(), add_special_tokens=False)
spaced = tokenizer.encode(" " + word.lstrip(), add_special_tokens=False)
assert plain, f"Empty bad-word tokenization: {word!r}"
self.bad_words.append(plain)
if spaced and len(spaced) == len(plain) and spaced[0] != plain[0]:
self.bad_words.append(spaced)
self.history: list[int] = []
self.matcher = None
self.bitmask = None
if params.structured_outputs is not None:
schema = params.structured_outputs.json
assert schema is not None, "Only the original JSON schema is supported"
# Preserve dictionary order: xgrammar's default grammar orders fields.
schema = schema if isinstance(schema, str) else json.dumps(schema)
compiled = _compiler(tokenizer, vocab_size).compile_json_schema(
schema, any_whitespace=True
)
self.matcher = xgr.GrammarMatcher(
compiled, override_stop_tokens=sorted(self.stop_ids) or None
)
self.bitmask = xgr.allocate_token_bitmask(1, vocab_size)
def accept_history(self, generated_ids: list[int]) -> bool:
"""Validate newly generated grammar tokens, including the final EOS.
Return whether the grammar has terminated. Use this after the final
output token; no next-token distribution exists after termination.
"""
assert generated_ids[: len(self.history)] == self.history, (
"Each reference belongs to one monotonically growing request history"
)
if self.matcher is not None:
for token in generated_ids[len(self.history) :]:
assert self.matcher.accept_token(token), (
f"Grammar rejected token {token} at position {len(self.history)}"
)
self.history.append(token)
return self.matcher.is_terminated()
else:
self.history = generated_ids.copy()
return False
def distributions(
self, raw_logits: torch.Tensor, generated_ids: list[int]
) -> tuple[torch.Tensor, torch.Tensor]:
"""Return FP32 logits before and after non-grammar sampling transforms.
``raw_logits`` scores the next token after the prompt and
``generated_ids``. Returned tensors do not alias the model's tensor.
Normalize the first result to check reported completion logprobs;
the second supplies the greedy decision reference.
"""
assert raw_logits.shape == (self.vocab_size,)
assert not self.accept_history(generated_ids), (
"Cannot generate a distribution after grammar EOS"
)
grammar_logits = raw_logits.float().clone()
if self.matcher is not None:
assert self.bitmask is not None
self.matcher.fill_next_token_bitmask(self.bitmask)
words = self.bitmask[0, :, None]
allowed = ((words >> torch.arange(32)) & 1).flatten()
allowed = allowed[: self.vocab_size].bool().to(raw_logits.device)
grammar_logits.masked_fill_(~allowed, -torch.inf)
processed = grammar_logits.clone()
for bad_word in self.bad_words:
prefix = bad_word[:-1]
if not prefix or generated_ids[-len(prefix) :] == prefix:
processed[bad_word[-1]] = -torch.inf
if len(generated_ids) < self.min_tokens and self.stop_ids:
stop_ids = sorted(self.stop_ids)
stop_scores = processed[stop_ids].clone()
processed[stop_ids] = -torch.inf
# A completed grammar may have no continuation except a stop token.
if self.matcher is not None and torch.isneginf(processed).all():
processed[stop_ids] = stop_scores
if self.frequency_penalty:
for token, count in Counter(generated_ids).items():
processed[token] -= self.frequency_penalty * count
return grammar_logits, processed
@@ -0,0 +1,624 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Accuracy with automatic attention selection and the model's normal dtype.
Complements the strict Flex/FP32 invariance checks in test_async_scheduling.py.
"""
import os
from dataclasses import replace
from typing import Any
import pytest
import torch
from tests.conftest import HfRunner, VllmRunner
from tests.utils import (
large_gpu_mark,
single_gpu_only,
)
from tests.v1.e2e.general.accuracy_utils import (
AccuracyTolerance,
check_accuracy_budget,
check_first_divergence,
check_greedy_token,
check_logprobs,
check_request_accuracy,
check_stopping,
)
from vllm import SamplingParams
from vllm.logprobs import Logprob
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.platforms import current_platform
from vllm.sampling_params import StructuredOutputsParams
from vllm.utils.torch_utils import set_default_torch_num_threads
from vllm.v1.metrics.reader import Metric
MODEL = "Qwen/Qwen3-0.6B"
EAGLE3_TARGET_MODEL = "meta-llama/Llama-3.2-1B-Instruct"
# Need to enforce eager for MRV2 while we sort out cudagraph issues.
ENFORCE_EAGER = os.getenv("ENFORCE_EAGER", "0") == "1"
first_prompt = (
"The following numbers of the sequence "
+ ", ".join(str(i) for i in range(10))
+ " are:"
)
example_prompts = [first_prompt, "In one word, the capital of France is "] + [
f"Tell me about the number {i}: " for i in range(32)
]
default_params = dict(
temperature=0.0, # greedy
max_tokens=30,
min_tokens=28,
)
@single_gpu_only
def test_without_spec_decoding(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
sample_json_schema,
):
"""Check target-model accuracy across scheduling and executor configurations."""
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params: list[dict[str, Any]] = [
dict(),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(bad_words=["the", " the"], logprobs=2),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
),
dict(
structured_outputs=struct_outputs,
frequency_penalty=-1.0,
),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(True, "mp", False, None, True),
(False, "mp", True, None, False),
(False, "uni", True, None, False),
(True, "mp", True, None, False),
(True, "uni", True, None, False),
(False, "mp", True, None, True),
(True, "mp", True, None, True),
(True, "uni", True, None, True),
]
run_tests(vllm_runner, hf_runner, MODEL, test_configs, test_sampling_params)
@single_gpu_only
@large_gpu_mark(min_gb=16)
def test_with_eagle3_spec_decoding(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
sample_json_schema,
):
"""Check accuracy and acceptance, including drafts that exceed model length."""
spec_config = {
"method": "eagle3",
"num_speculative_tokens": 2,
"model": "nm-testing/Llama3_2_1B_speculator.eagle3",
}
# Set small draft model len to force doesn't-fit-in-drafter case.
spec_config_short = spec_config | {"max_model_len": 50}
struct_outputs = StructuredOutputsParams(json=sample_json_schema)
test_sampling_params: list[dict[str, Any]] = [
dict(),
dict(frequency_penalty=-1.0),
dict(bad_words=["the", " the"]),
dict(bad_words=["the", " the"], logprobs=2),
dict(logprobs=2),
dict(logprobs=2, frequency_penalty=-1.0),
dict(prompt_logprobs=2),
dict(prompt_logprobs=2, logprobs=2),
dict(structured_outputs=struct_outputs),
dict(
structured_outputs=struct_outputs,
logprobs=2,
frequency_penalty=-1.0,
),
]
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, spec_config, False),
(True, "mp", False, spec_config, True),
(True, "uni", False, spec_config_short, True),
(False, "mp", True, spec_config, False),
(True, "mp", True, spec_config, False),
(False, "mp", True, spec_config_short, True),
(True, "uni", True, spec_config, False),
(True, "uni", True, spec_config_short, False),
(True, "mp", True, spec_config, True),
(True, "uni", True, spec_config_short, True),
]
run_tests(
vllm_runner, hf_runner, EAGLE3_TARGET_MODEL, test_configs, test_sampling_params
)
@single_gpu_only
@pytest.mark.skipif(
current_platform.is_xpu(),
reason=("XPU matmul/attention kernels are not batch-invariant"),
)
def test_with_ngram_gpu_spec_decoding(
vllm_runner: type[VllmRunner], hf_runner: type[HfRunner]
):
"""Check ngram accuracy and acceptance across scheduling configurations."""
ngram_gpu_config = {
"method": "ngram_gpu",
"num_speculative_tokens": 3,
"prompt_lookup_max": 3,
"prompt_lookup_min": 2,
}
# test_preemption, executor, async_scheduling,
# spec_config, test_prefill_chunking
test_configs = [
(False, "mp", False, None, False),
(False, "mp", False, ngram_gpu_config, False),
(True, "mp", False, ngram_gpu_config, True),
(False, "mp", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, False),
(True, "uni", True, ngram_gpu_config, False),
(True, "mp", True, ngram_gpu_config, True),
]
run_tests(vllm_runner, hf_runner, MODEL, test_configs, [{}, dict(logprobs=2)])
def run_tests(
vllm_runner: type[VllmRunner],
hf_runner: type[HfRunner],
model: str,
test_configs: list[tuple],
test_sampling_params: list[dict[str, Any]],
):
"""Compare the shared prefix and independently validate every continuation."""
assert test_configs[0] == (False, "mp", False, None, False), (
"The baseline must use synchronous target-only decoding"
)
outputs = []
for n, config in enumerate(test_configs, 1):
outputs.append(
run_test(
vllm_runner,
model,
f"{n}/{len(test_configs)}",
test_sampling_params,
*config,
)
)
baseline_config, baseline_batches, _ = outputs[0]
# Compare vLLM's own decisions at the first divergence, where histories
# still match. HF then scores each continuation, including after divergence.
# Neither engine forces an attention backend, dtype, or matmul precision.
# Qwen/Llama BF16 controls and Qwen holdouts measured max score error <0.38,
# per-stream request mean <0.073, max greedy gap 0.125, and request sum 0.25.
# Per-request budgets also reject systematic errors below the scalar bounds.
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
# These short CPU reductions cost more to distribute across a thread pool.
with set_default_torch_num_threads(1), hf_runner(model) as hf:
hf.model.eval()
for config, batches, _ in outputs:
assert len(batches) == len(test_sampling_params)
for baseline_batch, batch, overrides in zip(
baseline_batches, batches, test_sampling_params, strict=True
):
assert len(batch) == len(example_prompts), config
params = SamplingParams(**default_params, **overrides)
for i, (baseline, request, prompt) in enumerate(
zip(baseline_batch, batch, example_prompts, strict=True)
):
assert request.prompt_token_ids == hf.tokenizer.encode(prompt)
context = f"config=[{config}], params={overrides}, request={i}"
if params.logprobs is not None:
check_first_divergence(
baseline,
request,
params,
tolerance,
f"baseline=[{baseline_config}], {context}",
)
check_request_accuracy(
hf,
request,
params,
tolerance,
context,
)
print(f"ACCURACY PASSED: config=[{config}], params={overrides}")
baseline_acceptances = next((o[2] for o in outputs if o[2] is not None), None)
if baseline_acceptances is not None:
for settings, (config, _, acceptances) in zip(
test_configs, outputs, strict=True
):
if acceptances is None:
continue
test_preemption, _, _, spec_config, _ = settings
assert spec_config is not None
for baseline, actual, params in zip(
baseline_acceptances, acceptances, test_sampling_params, strict=True
):
context = f"config=[{config}], params={params}"
if spec_config.get("max_model_len") is None:
# Keep the original acceptance-quality floor per batch.
relative_drop = (
0.10 if current_platform.is_rocm() and test_preemption else 0.05
)
assert actual >= baseline * (1 - relative_drop), (
f"{context}: acceptance={actual}, baseline={baseline}"
)
else:
assert actual > 0.1, f"{context}: acceptance={actual}"
def run_test(
vllm_runner: type[VllmRunner],
model: str,
test_str: str,
sampling_param_tests: list[dict[str, Any]],
test_preemption: bool,
executor: str,
async_scheduling: bool,
spec_config: dict[str, Any] | None,
test_prefill_chunking: bool,
):
spec_decoding = spec_config is not None
spec_method = (spec_config or {}).get("method", "none")
# Chunked ngram decoding admits fewer concurrent requests under the
# 48-token budget. Its original 33-block cache did not preempt on ROCm.
# A 17-block cache forces contention while every original request fits
# comfortably within 256 tokens (the longest prompt plus output is 67).
cache_blocks = 17 if test_prefill_chunking and spec_method == "ngram_gpu" else 33
cache_arg: dict[str, Any] = (
dict(
num_gpu_blocks_override=cache_blocks,
max_model_len=(cache_blocks - 1) * 16,
)
if test_preemption
else dict(gpu_memory_utilization=0.9, max_model_len=4096)
)
spec_mml = (spec_config or {}).get("max_model_len")
test_config = (
f"executor={executor}, preemption={test_preemption}, "
f"async_sched={async_scheduling}, "
f"chunk_prefill={test_prefill_chunking}, "
f"spec_decoding={spec_decoding}, spec_method={spec_method}, spec_mml={spec_mml}"
)
print("-" * 80)
print(f"---- TESTING {test_str}: {test_config}")
print("-" * 80)
with vllm_runner(
model,
enable_chunked_prefill=test_prefill_chunking,
# Force prefill chunking
max_num_batched_tokens=48 if test_prefill_chunking else None,
enforce_eager=ENFORCE_EAGER,
async_scheduling=async_scheduling,
distributed_executor_backend=executor,
speculative_config=spec_config,
disable_log_stats=False,
enable_prefix_caching=False if current_platform.is_rocm() else None,
**cache_arg,
) as vllm_model:
results = []
acceptance_rates: list[float] | None = [] if spec_decoding else None
for override_params in sampling_param_tests:
metrics_before = vllm_model.llm.get_metrics()
print(f"----------- RUNNING PARAMS: {override_params}")
results.append(
vllm_model.llm.generate(
vllm_model.get_inputs(example_prompts),
sampling_params=SamplingParams(**default_params, **override_params),
)
)
metrics_after = vllm_model.llm.get_metrics()
if acceptance_rates is not None:
acceptance_rate = _get_acceptance_rate(metrics_before, metrics_after)
acceptance_rates.append(acceptance_rate)
print(f"ACCEPTANCE RATE {acceptance_rate}")
if test_preemption:
preemptions = _get_count(
metrics_before, metrics_after, "vllm:num_preemptions"
)
assert preemptions > 0, "preemption test had no preemptions"
# Preserve the original parameter-effect checks across repeated batches.
if len(results) > 1:
baseline = _result_signature(results[0])
for outputs, params in zip(results[1:], sampling_param_tests[1:], strict=True):
assert _result_signature(outputs) != baseline, (
f"{test_config}: sampling parameters had no observable effect: {params}"
)
# The old ROCm filter used schema-only as its first parameter set.
# Retain those comparisons after restoring the ordinary cases too.
schema_batches = [
batch
for batch, params in zip(results, sampling_param_tests, strict=True)
if params.get("structured_outputs") is not None
]
for batch in schema_batches[1:]:
assert _result_signature(batch) != _result_signature(schema_batches[0]), (
f"{test_config}: structured sampling parameters had no effect"
)
return test_config, results, acceptance_rates
def _result_signature(requests):
return [
(
list(request.outputs[0].token_ids),
request.outputs[0].text,
request.prompt_logprobs,
request.outputs[0].logprobs,
)
for request in requests
]
def _get_acceptance_rate(before: list[Metric], after: list[Metric]) -> float:
draft = _get_count(before, after, "vllm:spec_decode_num_draft_tokens")
accept = _get_count(before, after, "vllm:spec_decode_num_accepted_tokens")
assert draft > 0, "speculative test did not draft any tokens"
assert 0 <= accept <= draft, f"invalid acceptance counters: {accept=}, {draft=}"
return accept / draft
def _get_count(before: list[Metric], after: list[Metric], name: str) -> int:
before_val = next(m.value for m in before if m.name == name)
after_val = next(m.value for m in after if m.name == name)
return after_val - before_val
@pytest.mark.parametrize(
"corruption", ["score", "rank", "top_k", "missing", "nan", "positive", "order"]
)
def test_accuracy_checks_reject_incorrect_logprobs(corruption):
second = 2.875 if corruption == "order" else 1.0
reference = torch.tensor([3.0, second, -2.0, -5.0]).log_softmax(-1)
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
scores = {
0: Logprob(logprob=float(reference[0]), rank=1, decoded_token="a"),
1: Logprob(logprob=float(reference[1]), rank=2, decoded_token="b"),
}
check_logprobs(scores, reference, 0, 2, tolerance, "control")
if corruption == "score":
scores[0] = replace(scores[0], logprob=scores[0].logprob - 1.0)
elif corruption == "rank":
scores[1] = replace(scores[1], rank=1)
elif corruption == "top_k":
del scores[1]
scores[3] = Logprob(logprob=float(reference[3]), rank=2, decoded_token="d")
elif corruption == "missing":
del scores[0]
elif corruption == "positive":
scores[0] = replace(scores[0], logprob=0.1)
elif corruption == "order":
scores[0] = replace(scores[0], rank=2)
scores[1] = replace(scores[1], rank=1)
else:
scores[0] = replace(scores[0], logprob=float("nan"))
with pytest.raises(AssertionError):
check_logprobs(scores, reference, 0, 2, tolerance, corruption)
def test_accuracy_checks_distinguish_ties_from_wrong_tokens():
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
logits = torch.tensor([3.0, 2.875, -2.0, -torch.inf])
check_greedy_token(logits, 0, tolerance, "best")
check_greedy_token(logits, 1, tolerance, "near tie")
for token in (2, 3):
with pytest.raises(AssertionError):
check_greedy_token(logits, token, tolerance, "incorrect token")
# top-k may omit a sampled token tied at its boundary. The sampled rank
# can duplicate a sequential top-k rank without corrupting the result.
reference = torch.zeros(4).log_softmax(-1)
scores = {
token: Logprob(logprob=float(reference[token]), rank=rank)
for token, rank in [(3, 1), (0, 1), (1, 2)]
}
check_logprobs(scores, reference, 3, 2, tolerance, "tied top-k")
# A grammar with one allowed token still returns the requested top-k,
# including masked entries whose score is exactly negative infinity.
reference = torch.tensor([0.0, -torch.inf, -torch.inf])
scores = {0: Logprob(0.0, 1), 1: Logprob(-float("inf"), 2)}
check_logprobs(scores, reference, 0, 2, tolerance, "masked top-k")
def test_accuracy_checks_reject_incorrect_stopping():
params = SamplingParams(max_tokens=3)
stop_ids = {2, 3}
for tokens, reason, stop_reason in [
([0, 1, 2], "stop", None),
([0, 1, 3], "stop", 3),
([0, 1, 0], "length", None),
]:
check_stopping(
tokens,
reason,
stop_ids,
params,
"valid stopping at length cap",
eos_token_id=2,
stop_reason=stop_reason,
)
for tokens, reason, stop_reason in [
([0, 2, 1], "length", None),
([0, 1, 2], "length", None),
([0, 1, 2], "stop", 2),
([0, 1, 3], "stop", None),
([0, 1, 3], "stop", 2),
([0, 1, 0], "length", 3),
]:
with pytest.raises(AssertionError):
check_stopping(
tokens,
reason,
stop_ids,
params,
"incorrect stopping",
eos_token_id=2,
stop_reason=stop_reason,
)
def test_accuracy_checks_reject_systematic_sub_bound_errors():
tolerance = AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25)
reference = torch.tensor([3.0, 2.75, -2.0]).log_softmax(-1)
scores = {i: Logprob(float(reference[i]) - 0.4, i + 1) for i in (0, 1)}
# Each corrupted score fits the scalar bound, but the bias must not pass.
errors = check_logprobs(scores, reference, 0, 2, tolerance, "biased scores")
with pytest.raises(AssertionError, match="mean logprob error"):
check_accuracy_budget([errors], [], tolerance, "biased scores")
gap = check_greedy_token(reference, 1, tolerance, "one ambiguous choice")
with pytest.raises(AssertionError, match="total greedy logit gap"):
check_accuracy_budget([], [gap] * 30, tolerance, "systematically worse choices")
check_accuracy_budget(
[torch.tensor([0.03, 0.07])], [0.125, 0.125], tolerance, "control variation"
)
def _divergence_request(
tokens: list[int], scores: dict[int, float], position: int = 0
) -> RequestOutput:
logprobs: list[dict[int, Logprob]] = [{} for _ in tokens]
logprobs[position] = {
token: Logprob(score, rank)
for rank, (token, score) in enumerate(
sorted(scores.items(), key=lambda item: item[1], reverse=True), 1
)
}
return RequestOutput(
request_id="test",
prompt=None,
prompt_token_ids=[0, 0, 0],
prompt_logprobs=None,
outputs=[
CompletionOutput(
index=0,
text="",
token_ids=tokens,
cumulative_logprob=None,
logprobs=logprobs,
finish_reason="length",
)
],
finished=True,
)
@pytest.mark.parametrize(
"base_scores,actual_scores,error",
[
({0: -0.8, 1: -0.9}, {0: -0.9, 1: -0.8}, None),
({0: -0.8, 1: -0.8}, {0: -0.8, 1: -0.8}, None),
({0: -0.8, 1: -0.9}, {0: -0.8, 1: -0.9}, "actual.*below"),
({0: -0.9, 1: -0.8}, {0: -0.9, 1: -0.8}, "baseline.*below"),
({0: -0.8, 1: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*near-tie"),
({0: -0.8, 1: -0.9}, {0: -1.1, 1: -0.8}, "actual.*near-tie"),
({0: -0.8, 2: -0.9}, {0: -0.9, 1: -0.8}, None),
({0: -0.8, 2: -1.1}, {0: -0.9, 1: -0.8}, "baseline.*lower bound"),
({0: -0.8, 1: -0.9}, {1: -0.8, 2: -1.1}, "actual.*lower bound"),
],
ids=[
"near-tie-rank-reversal",
"exact-tie",
"wrong-near-tie-actual-choice",
"wrong-near-tie-baseline-choice",
"decisive-baseline",
"decisive-actual",
"missing-candidate-inconclusive",
"missing-candidate-decisive-baseline",
"missing-candidate-decisive-actual",
],
)
def test_first_divergence_checks_engine_preferences(base_scores, actual_scores, error):
baseline = _divergence_request([0], base_scores)
actual = _divergence_request([1], actual_scores)
args = (
baseline,
actual,
SamplingParams(temperature=0, logprobs=2),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
"paired engines",
)
if error is None:
check_first_divergence(*args)
else:
with pytest.raises(AssertionError, match=error):
check_first_divergence(*args)
@pytest.mark.parametrize("missing_alternative", [False, True])
def test_first_divergence_uses_generated_penalty_history(missing_alternative):
# Raw ordering favors token 1; one generated 0 reverses the penalized order.
# The prompt contains three more 0s which must not contribute to penalties.
base_scores = {0: -1.5, 1: -0.6}
if missing_alternative:
# The selected 0 is outside top-2. Use the top-k boundary (-0.6),
# excluding the additional sampled token (-1.5), for the missing 1.
base_scores = {0: -1.5, 2: -0.5, 3: -0.6}
baseline = _divergence_request([0, 0, 2], base_scores, position=1)
actual = _divergence_request([0, 1, 3, 4], {0: -1.6, 1: -0.5}, position=1)
check_first_divergence(
baseline,
actual,
SamplingParams(temperature=0, logprobs=2, frequency_penalty=-1),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
"different later histories are validated separately",
)
@pytest.mark.parametrize("mismatch", ["length", "finish_reason", "prompt"])
def test_first_divergence_rejects_mismatches_without_a_token_change(mismatch):
baseline = _divergence_request([0, 1], {})
actual = _divergence_request([0, 1], {})
if mismatch == "length":
actual.outputs[0].token_ids = [0]
elif mismatch == "finish_reason":
actual.outputs[0].finish_reason = "stop"
else:
actual.prompt_token_ids = [1]
with pytest.raises(AssertionError):
check_first_divergence(
baseline,
actual,
SamplingParams(temperature=0, logprobs=2),
AccuracyTolerance(logprob_atol=0.5, greedy_atol=0.25),
mismatch,
)
+227 -27
View File
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import time
import prometheus_client
import pytest
import torch
@@ -18,6 +20,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import (
MultiConnector,
)
from vllm.platforms import current_platform
from vllm.sampling_params import SamplingParams
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
@@ -92,6 +95,8 @@ def test_hisparse_spill_and_prefix_restore(
A regression omitted attention metadata before FULL graph replay, so decode
completed normally while its newly written KV rows were never copied to host.
MTP layers write after the target forward; their rows used to be mirrored
before the drafter wrote them, so the drafter later read stale host rows.
"""
capability = current_platform.get_device_capability()
if capability is None or capability.major < 9:
@@ -168,49 +173,70 @@ def test_hisparse_spill_and_prefix_restore(
model_runner.cudagraph_manager, "run_fullgraph", record_fullgraph
)
# The MTP layer writes its rows after the target forward, so it is
# mirrored at the start of the next step instead of in finish_forward.
draft_layers = set(worker._draft_layers)
assert draft_layers
original_finish_forward = worker.finish_forward
verified_full_replay_rows = 0
original_finish_previous_step = worker._finish_previous_step
verified_rows = {"target": 0, "draft": 0}
copied_nonzero_kv = False
draft_check_pending = False
def check_host_rows(layer_indices: set[int], kind: str) -> None:
nonlocal copied_nonzero_kv
# Synchronize only the test's inspection, not the worker itself.
with gpu_sync_allowed():
torch.accelerator.synchronize()
assert worker._row_mirrors
for layer_index in layer_indices:
cache = worker.cache_handles[layer_index]
source_index = cache.runtime.resident_source_index
for mirror in worker._row_mirrors:
source_row = mirror.source_starts[source_index]
destination_row = mirror.destination_start
num_rows = mirror.num_rows
source_block, source_offset = divmod(
source_row, worker.kernel_block_size
)
with gpu_sync_allowed():
gpu_rows = worker.resident_caches[layer_index][
source_block, source_offset : source_offset + num_rows
].cpu()
host_rows = worker.host_caches[layer_index][
destination_row : destination_row + num_rows
]
assert torch.equal(host_rows, gpu_rows)
copied_nonzero_kv |= bool(torch.count_nonzero(gpu_rows).item())
verified_rows[kind] += num_rows
def finish_forward():
nonlocal full_replay_pending, verified_full_replay_rows
nonlocal copied_nonzero_kv
nonlocal full_replay_pending, draft_check_pending
try:
original_finish_forward()
if not full_replay_pending:
return
# Synchronize only the test's inspection, not finish_forward itself.
with gpu_sync_allowed():
torch.accelerator.synchronize()
assert worker._row_mirrors
for layer_index, cache in enumerate(worker.cache_handles):
source_index = cache.runtime.resident_source_index
for mirror in worker._row_mirrors:
source_row = mirror.source_starts[source_index]
destination_row = mirror.destination_start
num_rows = mirror.num_rows
source_block, source_offset = divmod(
source_row, worker.kernel_block_size
)
with gpu_sync_allowed():
gpu_rows = worker.resident_caches[layer_index][
source_block, source_offset : source_offset + num_rows
].cpu()
host_rows = worker.host_caches[layer_index][
destination_row : destination_row + num_rows
]
assert torch.equal(host_rows, gpu_rows)
copied_nonzero_kv |= bool(torch.count_nonzero(gpu_rows).item())
verified_full_replay_rows += num_rows
target_layers = set(range(len(worker.cache_handles))) - draft_layers
check_host_rows(target_layers, "target")
draft_check_pending = True
finally:
full_replay_pending = False
def finish_previous_step():
nonlocal draft_check_pending
original_finish_previous_step()
if draft_check_pending:
draft_check_pending = False
check_host_rows(draft_layers, "draft")
monkeypatch.setattr(worker, "finish_forward", finish_forward)
monkeypatch.setattr(worker, "_finish_previous_step", finish_previous_step)
expected = runner.generate_greedy([target], max_tokens=8)
assert full_graph_calls > 0
assert verified_full_replay_rows > 0
assert verified_rows["target"] > 0
assert verified_rows["draft"] > 0
assert copied_nonzero_kv
runner.generate_greedy(pressure, max_tokens=8)
@@ -223,3 +249,177 @@ def test_hisparse_spill_and_prefix_restore(
assert actual == expected
if with_offloading:
assert _offload_load_bytes() > load_bytes
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="HiSparse requires NVIDIA CUDA"
)
@fork_new_process_for_each_test
def test_hisparse_host_exhaustion_defers_requests(
monkeypatch: pytest.MonkeyPatch,
vllm_runner: type[VllmRunner],
):
"""A full host pool defers requests instead of leaving pages GPU-only."""
capability = current_platform.get_device_capability()
if capability is None or capability.major < 9:
pytest.skip("Sparse MLA requires Hopper or newer")
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
prompts = [
[1000 + request_idx * 64 + i % 64 for i in range(257)]
for request_idx in range(3)
]
with vllm_runner(
MODEL,
load_format="dummy",
hf_overrides=_shrink_config,
attention_config=AttentionConfig(
hisparse_config=HiSparseConfig(device_buffer_size=512)
),
kv_transfer_config=KVTransferConfig(
kv_connector="HiSparseConnector",
kv_role="kv_both",
kv_connector_extra_config={"host_pool_gib": 1},
),
block_size=64,
max_model_len=320,
max_num_batched_tokens=512,
max_num_seqs=3,
num_gpu_blocks_override=128,
enable_prefix_caching=False,
enable_chunked_prefill=True,
enforce_eager=True,
) as runner:
expected = [runner.generate_greedy([p], max_tokens=16)[0] for p in prompts]
engine = runner.llm.llm_engine.engine_core.engine_core
coordinator = get_hisparse_coordinator(engine.scheduler.kv_cache_manager)
host = coordinator.host_manager
assert host is not None
# Leave room for one full request plus part of another.
spare_blocks = 8
num_pressure = host.block_pool.get_num_free_blocks() - spare_blocks
host.allocate_new_blocks(
"host-pressure",
num_pressure * host.block_size,
num_pressure * host.block_size,
)
original_plan = coordinator.plan_prefix_materialization
original_count = host.get_num_blocks_to_allocate
checked_steps = 0
refusals = 0
def plan(request_id, num_computed_tokens):
nonlocal checked_steps
assert not any(b.is_null for b in host.req_to_blocks[request_id])
checked_steps += 1
original_plan(request_id, num_computed_tokens)
def count(*args, **kwargs):
nonlocal refusals
required = original_count(*args, **kwargs)
refusals += int(required > 0)
return required
monkeypatch.setattr(coordinator, "plan_prefix_materialization", plan)
monkeypatch.setattr(host, "get_num_blocks_to_allocate", count)
actual = runner.generate_greedy(prompts, max_tokens=16)
assert checked_steps > 0
assert refusals > 0
assert actual == expected
@pytest.mark.skipif(
not current_platform.is_cuda(), reason="HiSparse requires NVIDIA CUDA"
)
@fork_new_process_for_each_test
def test_hisparse_terminal_prefix_reuse(
monkeypatch: pytest.MonkeyPatch,
vllm_runner: type[VllmRunner],
):
"""Finished requests publish mirrored host KV after a late acknowledgement."""
capability = current_platform.get_device_capability()
if capability is None or capability.major < 9:
pytest.skip("Sparse MLA requires Hopper or newer")
monkeypatch.setenv("VLLM_ENABLE_V1_MULTIPROCESSING", "0")
monkeypatch.setenv("VLLM_DEEP_GEMM_WARMUP", "skip")
target = [1000 + i % 64 for i in range(257)]
sampling = SamplingParams(temperature=0, max_tokens=1, ignore_eos=True)
with vllm_runner(
MODEL,
load_format="dummy",
hf_overrides=_shrink_config,
attention_config=AttentionConfig(
hisparse_config=HiSparseConfig(
device_buffer_size=512, eager_host_mirror=True
)
),
kv_transfer_config=KVTransferConfig(
kv_connector="HiSparseConnector",
kv_role="kv_both",
kv_connector_extra_config={"host_pool_gib": 0.01},
),
block_size=64,
max_model_len=320,
max_num_batched_tokens=512,
max_num_seqs=2,
num_gpu_blocks_override=128,
enable_prefix_caching=True,
enable_chunked_prefill=True,
enforce_eager=True,
) as runner:
engine = runner.llm.llm_engine.engine_core.engine_core
coordinator = get_hisparse_coordinator(engine.scheduler.kv_cache_manager)
worker = _get_hisparse_worker(runner)
original_updates = worker.take_transfer_updates
original_free = coordinator.free
held_completions: list[int] = []
update_calls = 0
terminal_pending_pages = 0
def take_updates():
nonlocal update_calls
with gpu_sync_allowed():
torch.accelerator.synchronize()
enqueued, completed = original_updates()
held_completions.extend(completed)
update_calls += 1
if update_calls <= 2:
return enqueued, []
completed = held_completions.copy()
held_completions.clear()
return enqueued, completed
def free(request_id):
nonlocal terminal_pending_pages
state = coordinator.request_states.get(request_id)
if state is not None:
terminal_pending_pages += len(state.pending_pages)
original_free(request_id)
def drain_pending_work():
deadline = time.monotonic() + 10
while coordinator.has_pending_work():
assert time.monotonic() < deadline, "HiSparse transfers did not drain"
runner.llm.llm_engine.step()
monkeypatch.setattr(worker, "take_transfer_updates", take_updates)
monkeypatch.setattr(coordinator, "free", free)
[first] = runner.llm.generate(
[{"prompt_token_ids": target}], sampling, use_tqdm=False
)
assert terminal_pending_pages == 4
assert first.num_cached_tokens == 0
assert coordinator.has_pending_work()
drain_pending_work()
assert not coordinator.has_pending_work()
assert not held_completions
assert update_calls > 2
[repeated] = runner.llm.generate(
[{"prompt_token_ids": target}], sampling, use_tqdm=False
)
assert repeated.num_cached_tokens == 256
assert repeated.outputs[0].token_ids == first.outputs[0].token_ids
drain_pending_work()
assert not coordinator.has_pending_work()
+120 -26
View File
@@ -10,11 +10,16 @@ from vllm.v1.metrics.reader import Counter
from ...models.utils import check_logprobs_close
from ...utils import large_gpu_mark, multi_gpu_test
# Mamba2 (Nemotron-3) hybrid.
# Mamba2 (Nemotron-3) hybrids.
MAMBA2_MODEL = "nvidia/NVIDIA-Nemotron-3-Nano-4B-BF16"
# FlashInfer 0.7.0's standard SSU cannot compile Nano's DIM=80 configuration.
MAMBA2_FLASHINFER_MODEL = "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4"
MODELS = [
pytest.param(MAMBA2_MODEL, marks=large_gpu_mark(min_gb=40)),
]
FLASHINFER_MODELS = [
pytest.param(MAMBA2_FLASHINFER_MODEL, marks=large_gpu_mark(min_gb=40)),
]
PROMPTS = [
"The capital of France is",
@@ -22,6 +27,16 @@ PROMPTS = [
]
@pytest.fixture(autouse=True)
def _use_v1_model_runner_by_default(monkeypatch):
# Triton ReplaySSM is V1-only. FlashInfer V2 tests override this locally.
with monkeypatch.context() as patch:
patch.setenv("VLLM_USE_V2_MODEL_RUNNER", "0")
envs.disable_envs_cache()
yield
envs.disable_envs_cache()
def _check_replayssm_parity(
vllm_runner,
model_name,
@@ -29,17 +44,11 @@ def _check_replayssm_parity(
tensor_parallel_size=1,
mamba_backend: str = "triton",
name_1: str = "replayssm",
require_v2: bool = False,
monkeypatch: pytest.MonkeyPatch | None = None,
expected_v2: bool | None = None,
):
# Compare logprobs, not greedy ids: ReplaySSM's fp arithmetic can flip a
# near-tie. Baseline and ReplaySSM run at the same TP, so TP numerics are
# common-mode and only ReplaySSM varies.
if require_v2:
assert monkeypatch is not None
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
envs.disable_envs_cache()
# near-tie. Baseline and ReplaySSM use the same backend so only ReplaySSM
# behavior varies.
common = dict(
max_model_len=1024,
trust_remote_code=True,
@@ -49,14 +58,17 @@ def _check_replayssm_parity(
mamba_backend=mamba_backend,
)
with vllm_runner(model_name, **common) as llm:
if require_v2:
assert llm.llm.llm_engine.vllm_config.use_v2_model_runner
if expected_v2 is not None:
assert llm.llm.llm_engine.vllm_config.use_v2_model_runner is expected_v2
baseline = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
with vllm_runner(
model_name, use_replayssm=True, replayssm_buffer_len=16, **common
model_name,
use_replayssm=True,
replayssm_buffer_len=16,
**common,
) as llm:
if require_v2:
assert llm.llm.llm_engine.vllm_config.use_v2_model_runner
if expected_v2 is not None:
assert llm.llm.llm_engine.vllm_config.use_v2_model_runner is expected_v2
replay = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
check_logprobs_close(
@@ -80,19 +92,101 @@ def test_replayssm_decode_matches_baseline_tp2(vllm_runner, model_name):
_check_replayssm_parity(vllm_runner, model_name, tensor_parallel_size=2)
@pytest.mark.parametrize("model_name", MODELS)
def test_replayssm_flashinfer_decode_matches_baseline_v2(
vllm_runner, model_name, monkeypatch
@pytest.mark.parametrize("model_name", FLASHINFER_MODELS)
@pytest.mark.parametrize("use_v2_model_runner", [False, True], ids=["v1", "v2"])
def test_replayssm_flashinfer_decode_matches_baseline(
vllm_runner, model_name, monkeypatch, use_v2_model_runner
):
pytest.importorskip("flashinfer.mamba.checkpointing_ssu")
_check_replayssm_parity(
vllm_runner,
model_name,
mamba_backend="flashinfer",
name_1="replayssm_flashinfer_v2",
require_v2=True,
monkeypatch=monkeypatch,
try:
with monkeypatch.context() as patch:
patch.setenv("VLLM_USE_V2_MODEL_RUNNER", str(int(use_v2_model_runner)))
envs.disable_envs_cache()
_check_replayssm_parity(
vllm_runner,
model_name,
mamba_backend="flashinfer",
name_1="replayssm_flashinfer",
expected_v2=use_v2_model_runner,
)
finally:
# The context restores the environment before the final cache reset.
envs.disable_envs_cache()
@pytest.mark.parametrize("model_name", FLASHINFER_MODELS)
def test_replayssm_flashinfer_spec_decode_matches_baseline(vllm_runner, model_name):
common = dict(
max_model_len=1024,
trust_remote_code=True,
enable_prefix_caching=False,
mamba_cache_mode="none",
speculative_config={
"method": "ngram",
"num_speculative_tokens": 3,
"prompt_lookup_max": 3,
},
)
with vllm_runner(model_name, mamba_backend="flashinfer", **common) as llm:
baseline = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
with vllm_runner(
model_name,
use_replayssm=True,
replayssm_buffer_len=16,
mamba_backend="flashinfer",
**common,
) as llm:
replay = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
check_logprobs_close(
outputs_0_lst=baseline,
outputs_1_lst=replay,
name_0="baseline_spec",
name_1="replayssm_flashinfer_spec",
)
@multi_gpu_test(num_gpus=2)
@large_gpu_mark(min_gb=40)
@pytest.mark.parametrize("use_v2_model_runner", [False, True], ids=["v1", "v2"])
def test_replayssm_flashinfer_mtp(vllm_runner, monkeypatch, use_v2_model_runner):
common = dict(
max_model_len=1024,
trust_remote_code=True,
enable_prefix_caching=False,
mamba_cache_mode="none",
mamba_backend="flashinfer",
tensor_parallel_size=2,
disable_log_stats=False,
speculative_config={"method": "mtp", "num_speculative_tokens": 3},
)
try:
with monkeypatch.context() as patch:
patch.setenv("VLLM_USE_V2_MODEL_RUNNER", str(int(use_v2_model_runner)))
envs.disable_envs_cache()
with vllm_runner(
MAMBA2_FLASHINFER_MODEL,
use_replayssm=True,
replayssm_buffer_len=16,
**common,
) as llm:
assert (
llm.llm.llm_engine.vllm_config.use_v2_model_runner
is use_v2_model_runner
)
outputs = llm.generate_greedy(PROMPTS, max_tokens=32)
draft_count = sum(
metric.value
for metric in llm.llm.get_metrics()
if isinstance(metric, Counter)
and metric.name == "vllm:spec_decode_num_drafts"
)
finally:
envs.disable_envs_cache()
# At least one request must run past the 16-token replay window; another
# may legitimately stop early on EOS.
assert any(len(token_ids) > 16 for token_ids, _ in outputs)
assert draft_count > 0
# Prefix spans several mamba blocks; prefix caching only reuses full blocks.
-4
View File
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from transformers import AutoTokenizer
from tests.v1.engine.utils import (
@@ -19,9 +18,6 @@ from vllm.engine.arg_utils import EngineArgs
from ...distributed.conftest import publisher_config, random_port # noqa: F401
EngineCoreSampleLogprobsType = list[tuple[torch.Tensor, torch.Tensor]]
EngineCorePromptLogprobsType = tuple[torch.Tensor, torch.Tensor]
def _build_test_vectors_no_logprobs() -> DummyOutputProcessorTestVectors:
"""Generate output processor dummy test vectors, without logprobs.
@@ -20,6 +20,8 @@ from vllm.v1.engine.core_client import BackgroundResources
from vllm.v1.engine.utils import (
CoreEngineActorManager,
EngineZmqAddresses,
_dp_nodes_master_first,
_node_ip_from_resources,
get_engine_zmq_addresses,
launch_core_engines,
)
@@ -363,3 +365,110 @@ def test_ray_dp_addresses_resolved_before_actor_creation(
"time they DEALER-connect. See PR #42585 / Ray-DP "
"multi-API-server regression."
)
def test_dp_nodes_master_first_orders_and_validates():
master = {"GPU": 2.0, "node:10.0.0.1": 1.0, "node:__internal_head__": 1.0}
worker = {"GPU": 2.0, "node:10.0.0.2": 1.0}
nodes = _dp_nodes_master_first({"w": worker, "m": master}, "10.0.0.1")
assert [node_id for node_id, _ in nodes] == ["m", "w"]
with pytest.raises(AssertionError, match="DP master node"):
_dp_nodes_master_first({"w": worker}, "10.0.0.1")
with pytest.raises(AssertionError, match="one head node"):
_dp_nodes_master_first({"a": master, "b": dict(master)}, "10.0.0.1")
@pytest.fixture
def ray_2gpu_node(monkeypatch: pytest.MonkeyPatch):
"""Real single-node Ray with 2 virtual GPUs and no dashboard.
Resource maps and placement groups are real. Without the dashboard any
``ray.util.state.list_nodes()`` call fails, the production condition this
path must survive. Only the platform device key is patched ("" on CPU).
"""
from ray._private.state import available_resources_per_node
if ray.is_initialized():
ray.shutdown()
ray.init(num_cpus=4, num_gpus=2, include_dashboard=False, log_to_driver=False)
monkeypatch.setattr("vllm.v1.engine.utils.current_platform.ray_device_key", "GPU")
(node_resources,) = available_resources_per_node().values()
master_ip = _node_ip_from_resources(node_resources)
assert master_ip is not None
created = []
def hold_gpus(num_gpus: int):
"""Occupy GPUs so the node looks like it already runs engines."""
pg = ray.util.placement_group([{"GPU": 1.0}] * num_gpus)
ray.get(pg.ready(), timeout=60)
created.append(pg)
yield SimpleNamespace(master_ip=master_ip, hold_gpus=hold_gpus, created=created)
for pg in created:
ray.util.remove_placement_group(pg)
ray.shutdown()
def _elastic_ep_config(dp_size: int, world_size: int, master_ip: str):
return SimpleNamespace(
parallel_config=SimpleNamespace(
data_parallel_size=dp_size,
data_parallel_master_ip=master_ip,
world_size=world_size,
)
)
@pytest.mark.timeout(120)
def test_add_dp_placement_groups_does_not_require_ray_default(ray_2gpu_node):
"""DP 1 -> 2 on an idle node: one schedulable group pinned to the master,
found without the dashboard (``list_nodes`` would fail here)."""
ip = ray_2gpu_node.master_ip
pgs, local_ranks = CoreEngineActorManager.add_dp_placement_groups(
_elastic_ep_config(dp_size=1, world_size=1, master_ip=ip), 2
)
ray_2gpu_node.created.extend(pgs)
assert [pg.bundle_specs for pg in pgs] == [
[{"GPU": 1.0, f"node:{ip}": 0.001}, {"CPU": 1.0}]
]
assert local_ranks == [0]
ray.get(pgs[0].ready(), timeout=60)
@pytest.mark.timeout(120)
def test_add_dp_placement_groups_counts_engines_already_on_node(ray_2gpu_node):
"""One GPU already held -> the new engine gets local rank 1."""
ray_2gpu_node.hold_gpus(1)
pgs, local_ranks = CoreEngineActorManager.add_dp_placement_groups(
_elastic_ep_config(dp_size=1, world_size=1, master_ip=ray_2gpu_node.master_ip),
2,
)
ray_2gpu_node.created.extend(pgs)
assert len(pgs) == 1
assert local_ranks == [1]
ray.get(pgs[0].ready(), timeout=60)
@pytest.mark.timeout(120)
def test_add_dp_placement_groups_respects_world_size(ray_2gpu_node):
"""With TP=2 a node with one idle GPU cannot host a new engine."""
ray_2gpu_node.hold_gpus(1)
assert CoreEngineActorManager.add_dp_placement_groups(
_elastic_ep_config(dp_size=1, world_size=2, master_ip=ray_2gpu_node.master_ip),
2,
) == ([], [])
def test_add_dp_placement_groups_noop_without_growth():
assert CoreEngineActorManager.add_dp_placement_groups(
_elastic_ep_config(dp_size=2, world_size=1, master_ip="10.0.0.1"), 2
) == ([], [])
+31
View File
@@ -108,6 +108,37 @@ def test_mm_prefix_lm_raises_batched_tokens_floor():
assert vllm_config.scheduler_config.max_num_batched_tokens >= 2496
def test_custom_histogram_buckets_from_cli():
parser = EngineArgs.add_cli_args(FlexibleArgumentParser())
# Unset: byte-identical default behavior.
args = parser.parse_args([])
vllm_config = EngineArgs.from_cli_args(args=args).create_engine_config()
assert vllm_config.observability_config.custom_histogram_buckets is None
# A JSON mapping round-trips into the config verbatim.
args = parser.parse_args(
[
"--custom-histogram-buckets",
'{"request_latency": [0.01, 0.05, 0.1, 0.5]}',
]
)
vllm_config = EngineArgs.from_cli_args(args=args).create_engine_config()
assert vllm_config.observability_config.custom_histogram_buckets == {
"request_latency": [0.01, 0.05, 0.1, 0.5]
}
# Malformed JSON is rejected at argument-parsing time.
parser.exit_on_error = False
with pytest.raises(ArgumentError):
parser.parse_args(["--custom-histogram-buckets", "{not json"])
# An unknown family key parses as JSON but fails config validation.
args = parser.parse_args(["--custom-histogram-buckets", '{"bogus": [1.0, 2.0]}'])
with pytest.raises(ValueError, match="unknown bucket family"):
EngineArgs.from_cli_args(args=args).create_engine_config()
def test_data_parallel_start_rank_zero_infers_hybrid_lb():
"""An explicit --data-parallel-start-rank 0 must be treated the same as
any other explicit start rank when inferring hybrid LB mode, not as
@@ -222,6 +222,24 @@ def _make_dplb_client(num_engines: int = 3, client_count: int = 1) -> DPLBAsyncM
return client
def test_dplb_weight_checksums_gather_every_engine():
"""call_utility_async on a DPLB client would keep only the first engine."""
client = _make_dplb_client(num_engines=2)
async def call_utility(method, *args, engine):
assert (method, args) == ("compute_weight_checksums", ())
return [{f"dp{engine[0]}:tp{tp}:w": "x"} for tp in (0, 1)]
client._call_utility_async = call_utility
workers = asyncio.run(client.compute_weight_checksums_async())
assert [key for worker in workers for key in worker] == [
"dp0:tp0:w",
"dp0:tp1:w",
"dp1:tp0:w",
"dp1:tp1:w",
]
def test_dplb_late_interaction_sticky_routing():
client = _make_dplb_client()
-7
View File
@@ -49,13 +49,6 @@ def vllm_model(vllm_runner, request):
yield vllm_model
@pytest.fixture(scope="function")
def vllm_model_apc(vllm_runner):
"""VllmRunner test fixture with APC."""
with _vllm_model(True, vllm_runner) as vllm_model:
yield vllm_model
@pytest.fixture(
# Function scope decouples tests & allows
# env var adjustment via monkeypatch
+82 -1
View File
@@ -18,7 +18,7 @@ from tests.v1.engine.utils import (
from vllm import PoolingParams
from vllm.logprobs import FlatLogprobs, Logprob, PromptLogprobs, SampleLogprobs
from vllm.lora.request import LoRARequest
from vllm.outputs import CompletionOutput, RequestOutput
from vllm.outputs import CompletionOutput, RequestOutput, SamplingMask
from vllm.sampling_params import RequestOutputKind, SamplingParams
from vllm.tokenizers import TokenizerLike
from vllm.v1.engine import (
@@ -35,6 +35,7 @@ from vllm.v1.engine.output_processor import (
RequestState,
)
from vllm.v1.metrics.stats import IterationStats, PrefillStats, SchedulerStats
from vllm.v1.outputs import SamplingMaskLists
@pytest.mark.parametrize("flat_logprobs", [False, True])
@@ -62,6 +63,31 @@ def test_delta_output_without_new_tokens_returns_empty_logprobs(
assert len(output.logprobs) == 0
def test_completion_output_preserves_each_sampling_mask_position() -> None:
state = RequestState.__new__(RequestState)
state.detokenizer = MagicMock()
state.detokenizer.get_next_output_text.return_value = ""
state.logprobs_processor = MagicMock()
state.logprobs_processor.logprobs = None
state.logprobs_processor.cumulative_logprob = None
state.output_kind = RequestOutputKind.DELTA
state.request_index = 0
state.sampling_mask_chunks = [
SamplingMaskLists(
token_ids=np.array([10, 11, 20]),
offsets=np.array([0, 2, 3]),
),
SamplingMaskLists(token_ids=np.array([30, 31, 32])),
]
state.routed_experts_chunks = []
state.spec_decode_metrics = None
output = state._new_completion_output([1, 2, 3], FinishReason.LENGTH, None)
assert output.sampling_mask is not None
assert output.sampling_mask.token_ids == [[10, 11], [20], [30, 31, 32]]
def _ref_convert_id_to_token(
tokenizer: TokenizerLike,
token_id: int,
@@ -1549,3 +1575,58 @@ def test_abort_requests(runner: str, abort_by: str, dummy_test_vectors):
output_processor.abort_requests([request.request_id], internal=True)
else:
output_processor.abort_requests([request.external_req_id], internal=False)
@pytest.mark.parametrize("output_kind", list(RequestOutputKind))
def test_sampling_masks_follow_output_kind(output_kind):
state = RequestState.__new__(RequestState)
state.detokenizer = MagicMock()
state.detokenizer.get_next_output_text.return_value = ""
state.logprobs_processor = MagicMock()
state.logprobs_processor.logprobs = None
state.logprobs_processor.cumulative_logprob = None
state.output_kind = output_kind
state.request_index = 0
state.sampling_mask_chunks = []
state.routed_experts_chunks = []
state.spec_decode_metrics = None
supports = [[10, 11], [20], [30, 31]]
masks = []
for position, support in enumerate(supports):
state.sampling_mask_chunks.append(SamplingMaskLists(np.asarray(support)))
finish = FinishReason.LENGTH if position == len(supports) - 1 else None
mask = state._new_completion_output([support[0]], finish, None).sampling_mask
masks.append(mask.token_ids if mask is not None else None)
if output_kind == RequestOutputKind.DELTA:
assert masks == [[support] for support in supports]
else:
assert masks == [None, None, supports]
def test_request_output_add_merges_delta_sampling_masks():
def delta(token_ids, sampling_mask):
completion = CompletionOutput(
index=0,
text="",
token_ids=token_ids,
cumulative_logprob=None,
logprobs=None,
sampling_mask=sampling_mask,
)
return RequestOutput(
request_id="request",
prompt=None,
prompt_token_ids=[1],
prompt_logprobs=None,
outputs=[completion],
finished=False,
)
merged = delta([], None)
merged.add(delta([10], SamplingMask([[10, 11]])), aggregate=True)
merged.add(delta([20], SamplingMask([[20]])), aggregate=True)
assert merged.outputs[0].token_ids == [10, 20]
assert merged.outputs[0].sampling_mask.token_ids == [[10, 11], [20]]
+125 -2
View File
@@ -1,14 +1,18 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import os
from contextlib import nullcontext
from multiprocessing import connection
from threading import Event
from types import SimpleNamespace
import pytest
import torch
import zmq
import vllm.platforms as platforms
from vllm.utils import torch_utils
from vllm.v1.engine import core as core_module
from vllm.v1.engine import utils as engine_utils
from vllm.v1.engine.core import EngineCoreProc, EngineShutdownState
@@ -19,10 +23,129 @@ from vllm.v1.engine.utils import (
EngineZmqAddresses,
wait_for_engine_startup,
)
from vllm.v1.executor import UniProcExecutor, multiproc_executor
pytestmark = pytest.mark.skip_global_cleanup
@pytest.mark.parametrize(
(
"executor_class",
"local_engine_count",
"initial_threads",
"user_threads",
"fail_start",
"expected",
),
[
(UniProcExecutor, 1, 192, None, False, (12, "12", "1")),
(UniProcExecutor, 2, 192, None, False, (6, "6", "1")),
(UniProcExecutor, 2, 192, None, True, (6, "6", "1")),
(UniProcExecutor, 2, 5, None, False, (5, "5", "1")),
(UniProcExecutor, 2, 1, None, False, (1, "1", "1")),
(UniProcExecutor, 2, 5, "5", False, (5, "5", None)),
(
multiproc_executor.MultiprocExecutor,
2,
192,
None,
False,
(192, None, None),
),
],
)
def test_engine_core_startup_threads_are_scoped_to_launch(
monkeypatch: pytest.MonkeyPatch,
executor_class,
local_engine_count: int,
initial_threads: int,
user_threads: str | None,
fail_start: bool,
expected: tuple[int, str | None, str | None],
):
"""UniProc workers inherit their CPU share and restore the parent."""
marker = torch_utils.OMP_NUM_THREADS_SET_BY_VLLM
monkeypatch.delenv(marker, raising=False)
monkeypatch.delenv("OMP_NUM_THREADS", raising=False)
if user_threads is not None:
monkeypatch.setenv("OMP_NUM_THREADS", user_threads)
monkeypatch.setattr(torch_utils, "available_cpu_count", lambda: 12)
platform = SimpleNamespace(
is_cpu=lambda: False, is_cuda_alike=lambda: True, is_xpu=lambda: False
)
monkeypatch.setattr(engine_utils, "current_platform", platform)
threads = SimpleNamespace(count=initial_threads)
setter_calls = []
def set_threads(count):
setter_calls.append(count)
threads.count = count
monkeypatch.setattr(torch, "get_num_threads", lambda: threads.count)
monkeypatch.setattr(torch, "set_num_threads", set_threads)
start_states = []
def thread_state():
return (
threads.count,
os.environ.get("OMP_NUM_THREADS"),
os.environ.get(marker),
)
def start_process():
start_states.append(thread_state())
if fail_start:
raise RuntimeError("start failed")
def get_context():
assert thread_state() == (initial_threads, user_threads, None)
return SimpleNamespace(
Process=lambda **kwargs: SimpleNamespace(
name=kwargs["name"],
exitcode=1 if fail_start else None,
start=start_process,
)
)
monkeypatch.setattr(engine_utils, "get_mp_context", get_context)
monkeypatch.setattr(engine_utils, "shutdown", lambda *_args, **_kwargs: None)
monkeypatch.setattr(
engine_utils.numa_utils,
"configure_subprocess",
lambda *args, **kwargs: nullcontext(),
)
with (
pytest.raises(RuntimeError, match="start failed")
if fail_start
else nullcontext()
):
manager = CoreEngineProcManager(
local_engine_count=local_engine_count,
start_index=0,
local_start_index=0,
vllm_config=SimpleNamespace(
shutdown_timeout=0,
parallel_config=SimpleNamespace(
data_parallel_size=local_engine_count,
assigned_physical_gpu_ids=None,
use_ray=False,
),
),
local_client=True,
handshake_address="unused",
executor_class=executor_class,
log_stats=False,
)
manager._finalizer.detach()
assert start_states == [expected] * (1 if fail_start else local_engine_count)
assert thread_state() == (initial_threads, user_threads, None)
assert setter_calls == (
[expected[0], initial_threads]
if executor_class is UniProcExecutor and expected[0] < initial_threads
else []
)
@pytest.mark.parametrize(
("is_rocm", "request_timeout", "manager_timeout", "process_timeout"),
[
@@ -181,9 +304,9 @@ def test_wait_for_engine_startup_reports_watched_process_exit():
wait_for_engine_startup(
handshake_socket,
[CoreEngine()],
parallel_config, # type: ignore[arg-type]
parallel_config,
coordinated_dp=False,
cache_config=None, # type: ignore[arg-type]
cache_config=None,
launch=launch,
)
finally:
+32
View File
@@ -0,0 +1,32 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from unittest.mock import AsyncMock, call
import pytest
from vllm.v1.engine.core_client import DPLBAsyncMPClient
pytestmark = pytest.mark.cpu_test
@pytest.mark.asyncio
@pytest.mark.parametrize(
"results, expected",
[
([True, True], True),
([True, False], False),
([False, True], False),
([False, False], False),
],
)
async def test_dp_wake_up_requires_all_engines_awake(results, expected):
client = object.__new__(DPLBAsyncMPClient)
client.core_engines = [b"engine-0", b"engine-1"]
client._call_utility_async = AsyncMock(side_effect=results)
assert await client.wake_up_async(["weights"]) is expected
assert client._call_utility_async.await_args_list == [
call("wake_up", ["weights"], engine=b"engine-0"),
call("wake_up", ["weights"], engine=b"engine-1"),
]
+3 -3
View File
@@ -85,12 +85,12 @@ def test_multiproc_executor_worker_termination_timeout(
monkeypatch.setattr(multiproc_executor_module.time, "sleep", clock.sleep)
executor = MultiprocExecutor.__new__(MultiprocExecutor)
proc = _FakeProcess(clock, exits_at=exits_at)
executor._ensure_worker_termination([proc])
executor._ensure_worker_termination([proc]) # type: ignore[list-item]
assert proc.terminate_called is expected_terminate
class CustomMultiprocExecutor(MultiprocExecutor):
def collective_rpc(
def collective_rpc( # type: ignore[override]
self,
method: str | Callable,
timeout: float | None = None,
@@ -98,7 +98,7 @@ class CustomMultiprocExecutor(MultiprocExecutor):
kwargs: dict | None = None,
non_block: bool = False,
unique_reply_rank: int | None = None,
kv_output_aggregator: KVOutputAggregator = None,
kv_output_aggregator: KVOutputAggregator | None = None,
ec_output_aggregator: ECOutputAggregator | None = None,
) -> Any | list[Any] | Future[Any | list[Any]]:
# Drop marker to show that this was run
@@ -78,6 +78,20 @@ wait_for_server() {
done" && return 0 || return 1
}
# b200-k8s pods use host networking, so a fixed port can already be taken by
# another job on the node. Bind all the ports at once so they are distinct.
free_ports() {
python3 - "$1" <<'EOF'
import socket
import sys
socks = [socket.socket() for _ in range(int(sys.argv[1]))]
for s in socks:
s.bind(("", 0))
print(" ".join(str(s.getsockname()[1]) for s in socks))
EOF
}
# Function to clean up previous instances
cleanup_instances() {
echo "Cleaning up any running vLLM instances..."
@@ -107,6 +121,9 @@ run_tests_for_model() {
# Proxy args: repeated --prefill URL BOOTSTRAP_PORT and --decode URL.
PROXY_ARGS=()
# Per prefiller: server and bootstrap. Per decoder: server. Then the proxy.
read -r -a PORTS <<< "$(free_ports $((2 * NUM_PREFILL_INSTANCES + NUM_DECODE_INSTANCES + 1)))"
PROXY_PORT=${PORTS[${#PORTS[@]} - 1]}
# Start prefill instances
for i in $(seq 0 $((NUM_PREFILL_INSTANCES-1))); do
@@ -119,10 +136,8 @@ run_tests_for_model() {
GPU_ID="${GPU_ID},${NEXT_GPU}"
done
# Calculate port number (base port + instance number)
PORT=$((8100 + i))
# Bootstrap server port for this prefiller. Avoid clash across instances.
BOOTSTRAP_PORT=$((8998 + i))
PORT=${PORTS[$((2 * i))]}
BOOTSTRAP_PORT=${PORTS[$((2 * i + 1))]}
echo "Starting prefill instance $i on GPU $GPU_ID, port $PORT, bootstrap $BOOTSTRAP_PORT"
@@ -162,8 +177,7 @@ run_tests_for_model() {
NEXT_GPU=$(((GPU_ID + j) % $(get_num_gpus)))
GPU_ID="${GPU_ID},${NEXT_GPU}"
done
# Calculate port number (base port + instance number)
PORT=$((8200 + i))
PORT=${PORTS[$((2 * NUM_PREFILL_INSTANCES + i))]}
echo "Starting decode instance $i on GPU $GPU_ID, port $PORT"
@@ -205,16 +219,16 @@ run_tests_for_model() {
done
# Start the proxy server
echo "Starting proxy server on port 8192"
echo "Starting proxy server on port $PROXY_PORT"
python3 "${GIT_ROOT}/examples/disaggregated/mooncake_connector/mooncake_connector_proxy.py" \
--port 8192 "${PROXY_ARGS[@]}" &
--port "$PROXY_PORT" "${PROXY_ARGS[@]}" &
# Wait for the proxy to start
sleep 5
# Run lm eval for this model
echo "Running tests for $model_name"
TEST_MODEL=$model_name python3 -m pytest -s -x \
TEST_MODEL=$model_name PROXY_PORT=$PROXY_PORT python3 -m pytest -s -x \
"${GIT_ROOT}/tests/v1/kv_connector/mooncake_integration/test_accuracy.py"
# Clean up before running next model
@@ -5,7 +5,7 @@ import os
import lm_eval
import openai
BASE_URL = "http://localhost:8192/v1"
BASE_URL = f"http://localhost:{os.environ.get('PROXY_PORT', 8192)}/v1"
NUM_CONCURRENT = 100
TASK = "gsm8k"
FILTER = "exact_match,strict-match"
@@ -60,7 +60,7 @@ vllm serve "$MODEL" \
--block-size 128 \
--trust-remote-code \
--enable-prefix-caching \
--mamba-cache-mode all \
--mamba-cache-mode align \
--kv-transfer-config "$KV_CONFIG" \
"${EXTRA_ARGS[@]}" &
@@ -78,7 +78,7 @@ vllm serve "$MODEL" \
--block-size 128 \
--trust-remote-code \
--enable-prefix-caching \
--mamba-cache-mode all \
--mamba-cache-mode align \
--kv-transfer-config "$KV_CONFIG" \
"${EXTRA_ARGS[@]}" &
@@ -158,8 +158,18 @@ def run_rocm_pd_accuracy(connector, model, prefill_tp, decode_tp, monkeypatch):
"VLLM_ROCM_USE_AITER": "1",
"VLLM_KV_CACHE_LAYOUT": "HND",
}
bootstrap_port = get_open_port()
with contextlib.ExitStack() as stack:
bootstrap_port = 0
if connector == "mooncake":
from vllm.distributed.kv_transfer.kv_connector.v1.mooncake.mooncake_utils import ( # noqa: E501
MooncakeBootstrapServer,
)
bootstrap = MooncakeBootstrapServer("127.0.0.1", 0)
stack.callback(bootstrap.shutdown)
bootstrap.start()
bootstrap_port = bootstrap.port
extra["bootstrap_server_address"] = f"127.0.0.1:{bootstrap_port}"
servers: list[RemoteOpenAIServer] = []
stack.callback(RemoteOpenAIServer.shutdown_many, servers)
for role, tp, assigned in (
@@ -176,7 +186,6 @@ def run_rocm_pd_accuracy(connector, model, prefill_tp, decode_tp, monkeypatch):
selector: ",".join(assigned),
"VLLM_PORT": str(get_open_port()),
"VLLM_NIXL_SIDE_CHANNEL_PORT": str(get_open_port()),
"VLLM_MOONCAKE_BOOTSTRAP_PORT": str(bootstrap_port),
}
servers.append(
RemoteOpenAIServer(
@@ -17,7 +17,10 @@ from vllm.distributed.kv_transfer.kv_connector.v1.offloading.scheduler import (
SchedulerOffloadConfig,
)
from vllm.platforms import current_platform
from vllm.v1.core.kv_cache_utils import generate_scheduler_kv_cache_config
from vllm.v1.core.kv_cache_utils import (
generate_scheduler_kv_cache_config,
kv_cache_groups_tp_replicas,
)
from vllm.v1.kv_cache_interface import (
CircularBufferSpec,
FullAttentionSpec,
@@ -164,6 +167,7 @@ def _mla_spec(
return MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=head_size,
dtype=dtype,
tokens_per_state=tokens_per_state,
@@ -321,7 +325,184 @@ def _replicated_layout(
config.parallel_config.nnodes = nnodes
if world_size is not None:
config.parallel_config.world_size = world_size
return build_offloading_config(config, kv_cache_config).replicated_layout
kv_cache_config.kv_tp_replicas = kv_cache_groups_tp_replicas(
kv_cache_config.kv_cache_groups,
config.parallel_config.tensor_parallel_size,
config.parallel_config.decode_context_parallel_size,
)
# Scheduler and Worker offload config
worker_offload_config = build_offloading_config(config, kv_cache_config)
scheduler_offload_config = build_offloading_config(
config, generate_scheduler_kv_cache_config([kv_cache_config])
)
# Verify that the Worker and Scheduler agree on replication.
# and worker-bytes-per-block
assert (
worker_offload_config.replicated_layout
== scheduler_offload_config.replicated_layout
)
assert (
worker_offload_config.worker_kv_bytes_per_block
== scheduler_offload_config.worker_kv_bytes_per_block
)
return worker_offload_config.replicated_layout
_SWA_MLA_PAGE = SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
max_tp_shards=1,
head_size=512,
dtype=torch.float32,
sliding_window=128,
).page_size_bytes
def _make_swa_mla_kv_cache_config(
num_blocks: int = 4,
) -> KVCacheConfig:
"""Single SlidingWindowMLASpec group — DSV4 sliding-window layers."""
spec = SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
max_tp_shards=1,
head_size=512,
dtype=torch.float32,
sliding_window=128,
)
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=_SWA_MLA_PAGE * num_blocks,
layers=["layer"],
layer_stride=_SWA_MLA_PAGE * num_blocks,
block_stride=_SWA_MLA_PAGE,
)
],
kv_cache_groups=[KVCacheGroupSpec(["layer"], spec)],
)
def _make_dsv4_flash_kv_cache_config(num_blocks: int = 4) -> KVCacheConfig:
"""Minimal fake of DeepSeek-V4-Flash's five UniformTypeKVCacheSpecs groups.
The real model has the following groups (layer counts from runtime logs);
2 per group is enough to exercise the structural properties that govern
replicated_layout:
group[0]: 22 SlidingWindowMLASpec layers, sliding_window=128
group[1]: 21 SlidingWindowMLASpec layers, sliding_window=128
group[2]: 62 MLAAttentionSpec layers (MLA + indexer.k_cache)
group[3]: 42 SlidingWindowMLASpec layers, sliding_window=8
group[4]: 20 SlidingWindowMLASpec layers, sliding_window=128
All inner specs have num_kv_heads=1 → every group is TP-replicated.
"""
block_size = 16
dtype = torch.float32
head_size = 512
def _swa_group(tag: str, sw: int) -> KVCacheGroupSpec:
names = [f"{tag}_0", f"{tag}_1"]
spec = SlidingWindowMLASpec(
block_size=block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=head_size,
dtype=dtype,
sliding_window=sw,
)
return KVCacheGroupSpec(
names,
UniformTypeKVCacheSpecs(
block_size=block_size,
kv_cache_specs={name: spec for name in names},
),
)
def _mla_group(tag: str) -> KVCacheGroupSpec:
names = [f"{tag}_0", f"{tag}_1"]
spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=head_size,
dtype=dtype,
)
return KVCacheGroupSpec(
names,
UniformTypeKVCacheSpecs(
block_size=block_size,
kv_cache_specs={name: spec for name in names},
),
)
groups = [
_swa_group("swa_128a", 128), # group[0]: SWA-MLA, sw=128
_swa_group("swa_128b", 128), # group[1]: SWA-MLA, sw=128
_mla_group("mla"), # group[2]: MLA + indexer layers
_swa_group("swa_8", 8), # group[3]: SWA-MLA, sw=8
_swa_group("swa_128c", 128), # group[4]: SWA-MLA, sw=128
]
# All specs share the same page size (num_kv_heads=1, head_size=512, fp32).
page = MLAAttentionSpec(
block_size=block_size, num_kv_heads=1, head_size=head_size, dtype=dtype
).page_size_bytes
all_layers = [name for g in groups for name in g.layer_names]
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=page * len(all_layers) * num_blocks,
layers=all_layers,
layer_stride=page * num_blocks,
block_stride=page,
)
],
kv_cache_groups=groups,
)
def _make_dsv3_2_kv_cache_config(num_blocks: int = 4) -> KVCacheConfig:
"""Minimal fake of DeepSeek-V3.2-Exp's single UniformTypeKVCacheSpecs group.
The real model has 1 group (layer counts from runtime logs):
group[0]: 122 MLAAttentionSpec layers (self_attn.attn + indexer.k_cache)
All inner specs have num_kv_heads=1 → the group is TP-replicated.
GLM-5.3 has the same topology (one UniformType group of MLAAttentionSpec
layers, num_kv_heads=1) with 99 layers instead of 122, so this config
covers both models.
"""
block_size = 16
names = [f"mla_{i}" for i in range(4)] # 4 layers; real model has 122
spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
max_tp_shards=1,
head_size=512,
dtype=torch.float32,
)
group = KVCacheGroupSpec(
names,
UniformTypeKVCacheSpecs(
block_size=block_size,
kv_cache_specs={name: spec for name in names},
),
)
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=spec.page_size_bytes * len(names) * num_blocks,
layers=names,
layer_stride=spec.page_size_bytes * num_blocks,
block_stride=spec.page_size_bytes,
)
],
kv_cache_groups=[group],
)
@pytest.mark.parametrize("packed", [False, True])
@@ -588,35 +769,64 @@ def test_replicated_layout_enabled_for_pure_mla_tp_mp_single_node(
)
@pytest.mark.parametrize("world_size", [2, 4])
def test_replicated_layout_enabled_for_swa_mla(world_size: int):
"""SlidingWindowMLASpec groups are also replicated and qualify."""
assert _replicated_layout(
_make_swa_mla_kv_cache_config(),
tensor_parallel_size=world_size,
)
@pytest.mark.parametrize("world_size", [2, 4, 8])
def test_replicated_layout_dsv4_flash(world_size: int):
"""DeepSeek-V4-Flash: all 5 UniformType groups are MLA/SWA-MLA with
num_kv_heads=1, so replicated_layout must be True under TP/mp single-node."""
assert _replicated_layout(
_make_dsv4_flash_kv_cache_config(),
tensor_parallel_size=world_size,
)
@pytest.mark.parametrize("world_size", [2, 4, 8])
def test_replicated_layout_dsv3_2(world_size: int):
"""DeepSeek-V3.2 / GLM-5.3: single UniformType group of MLAAttentionSpec
layers (122 and 99 respectively), num_kv_heads=1 → replicated_layout must
be True under TP/mp single-node."""
assert _replicated_layout(
_make_dsv3_2_kv_cache_config(),
tensor_parallel_size=world_size,
)
def test_replicated_layout_enabled_for_uniform_wrapper_mla():
"""UniformTypeKVCacheSpecs wrapping MLA layers of different sizes qualifies:
each layer is replicated and the page accounting sums correctly."""
mla_layers = ["layer0", "layer1"]
spec = UniformTypeKVCacheSpecs(
block_size=16,
kv_cache_specs={"layer0": _mla_spec(), "layer1": _mla_spec(head_size=256)},
)
total_page = spec.page_size_bytes
num_blocks = 4
kv_cache_config = KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=total_page * num_blocks,
layers=mla_layers,
layer_stride=total_page * num_blocks,
block_stride=total_page,
)
],
kv_cache_groups=[KVCacheGroupSpec(mla_layers, spec)],
)
assert _replicated_layout(kv_cache_config)
@pytest.mark.parametrize(
("kv_cache_config", "case"),
[
(
KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[
KVCacheTensor(
size=_MLA_PAGE * 4,
layers=["layer"],
layer_stride=_MLA_PAGE * 4,
block_stride=_MLA_PAGE,
)
],
kv_cache_groups=[
KVCacheGroupSpec(
["layer"],
SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
head_size=512,
dtype=torch.float32,
sliding_window=128,
),
)
],
),
"sliding-window-mla",
),
(
KVCacheConfig(
num_blocks=4,
@@ -642,40 +852,6 @@ def test_replicated_layout_enabled_for_pure_mla_tp_mp_single_node(
),
"hidden-state",
),
(
# One group, two page sizes: layer1's run starts past layer0's region.
KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[
KVCacheTensor(
size=(_MLA_PAGE + _HALF_MLA_PAGE) * 4,
layers=["layer0"],
layer_stride=_MLA_PAGE * 4,
block_stride=_MLA_PAGE,
),
KVCacheTensor(
size=(_MLA_PAGE + _HALF_MLA_PAGE) * 4,
layers=["layer1"],
layer_stride=_HALF_MLA_PAGE * 4,
block_stride=_HALF_MLA_PAGE,
offset=_MLA_PAGE * 4,
),
],
kv_cache_groups=[
KVCacheGroupSpec(
["layer0", "layer1"],
UniformTypeKVCacheSpecs(
block_size=16,
kv_cache_specs={
"layer0": _mla_spec(),
"layer1": _mla_spec(head_size=256),
},
),
)
],
),
"uniform-wrapper",
),
(
# Overlaid groups with different page sizes: a block is a window of
# the largest group's packing.
@@ -726,6 +902,84 @@ def test_replicated_layout_enabled_for_pure_mla_tp_mp_single_node(
),
"mla-mamba-hybrid",
),
],
ids=[
"hidden-state",
"mla-full-hybrid",
"mla-mamba-hybrid",
],
)
def test_replicated_layout_excludes_unproven_cache_shapes(
kv_cache_config: KVCacheConfig,
case: str,
):
assert not _replicated_layout(kv_cache_config), case
@pytest.mark.parametrize(
("kv_cache_config", "case"),
[
(
KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[
KVCacheTensor(
size=_MLA_PAGE * 4,
layers=["layer"],
layer_stride=_MLA_PAGE * 4,
block_stride=_MLA_PAGE,
)
],
kv_cache_groups=[
KVCacheGroupSpec(
["layer"],
SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
max_tp_shards=1,
head_size=512,
dtype=torch.float32,
sliding_window=128,
),
)
],
),
"sliding-window-mla",
),
(
# One group, two page sizes: layer1's run starts past layer0's region.
KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[
KVCacheTensor(
size=(_MLA_PAGE + _HALF_MLA_PAGE) * 4,
layers=["layer0"],
layer_stride=_MLA_PAGE * 4,
block_stride=_MLA_PAGE,
),
KVCacheTensor(
size=(_MLA_PAGE + _HALF_MLA_PAGE) * 4,
layers=["layer1"],
layer_stride=_HALF_MLA_PAGE * 4,
block_stride=_HALF_MLA_PAGE,
offset=_MLA_PAGE * 4,
),
],
kv_cache_groups=[
KVCacheGroupSpec(
["layer0", "layer1"],
UniformTypeKVCacheSpecs(
block_size=16,
kv_cache_specs={
"layer0": _mla_spec(),
"layer1": _mla_spec(head_size=256),
},
),
)
],
),
"uniform-wrapper",
),
(
KVCacheConfig(
num_blocks=4,
@@ -748,31 +1002,54 @@ def test_replicated_layout_enabled_for_pure_mla_tp_mp_single_node(
],
ids=[
"sliding-window-mla",
"hidden-state",
"uniform-wrapper",
"mla-full-hybrid",
"mla-mamba-hybrid",
"multi-group-mla",
],
)
def test_replicated_layout_excludes_unproven_cache_shapes(
def test_replicated_layout_supported_cache_shapes(
kv_cache_config: KVCacheConfig,
case: str,
):
assert not _replicated_layout(kv_cache_config), case
assert _replicated_layout(kv_cache_config), case
def test_replicated_layout_rejects_bare_mla_with_mixed_page_accounting():
@pytest.mark.parametrize(
("main_spec", "add_spec", "expected"),
[
(
_mla_spec(head_size=512),
_mla_spec(head_size=128, dtype=torch.uint8), # indexer.k_cache spec
True,
),
(
_mla_spec(head_size=512),
_full_attention_spec(),
False,
),
],
ids=["uniform-mla-indexer", "uniform-mla-fa"],
)
def test_replicated_layout_for_dsa_style_groups(
main_spec: KVCacheSpec, add_spec: KVCacheSpec, expected: bool
):
"""KV Cache groups with packed-specs inside a UniformTypeKVCacheSpec."""
num_blocks = 4
main_spec = _mla_spec(head_size=512)
indexer_spec = _mla_spec(head_size=128, dtype=torch.uint8)
main_layers = [f"main_{i}" for i in range(61)]
indexer_layers = [f"indexer_{i}" for i in range(61)]
# A DSA-style group: the main pages and the smaller indexer pages are packed one
# after the other, so a block holds more than 61 MLA pages.
add_layers = [f"add_{i}" for i in range(61)]
main_bytes = main_spec.page_size_bytes * len(main_layers)
indexer_bytes = indexer_spec.page_size_bytes * len(indexer_layers)
size = (main_bytes + indexer_bytes) * num_blocks
add_bytes = add_spec.page_size_bytes * len(add_layers)
size = (main_bytes + add_bytes) * num_blocks
kv_cache_specs = {
**{layer: main_spec for layer in main_layers},
**{layer: add_spec for layer in add_layers},
}
layer_names = main_layers + add_layers
group_spec: KVCacheSpec = UniformTypeKVCacheSpecs(
block_size=16, kv_cache_specs=kv_cache_specs
)
kv_cache_config = KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
@@ -784,16 +1061,16 @@ def test_replicated_layout_rejects_bare_mla_with_mixed_page_accounting():
),
KVCacheTensor(
size=size,
layers=indexer_layers,
layer_stride=indexer_spec.page_size_bytes * num_blocks,
block_stride=indexer_spec.page_size_bytes,
layers=add_layers,
layer_stride=add_spec.page_size_bytes * num_blocks,
block_stride=add_spec.page_size_bytes,
offset=main_bytes * num_blocks,
),
],
kv_cache_groups=[KVCacheGroupSpec(main_layers + indexer_layers, main_spec)],
kv_cache_groups=[KVCacheGroupSpec(layer_names, group_spec)],
)
assert not _replicated_layout(kv_cache_config)
assert _replicated_layout(kv_cache_config) == expected
@pytest.mark.parametrize(
@@ -841,6 +1118,7 @@ _SWA_SPEC = SlidingWindowSpec(
_SWA_MLA_SPEC = SlidingWindowMLASpec(
block_size=16,
num_kv_heads=1,
max_tp_shards=1,
head_size=576,
dtype=torch.float32,
sliding_window=128,
@@ -904,6 +1182,52 @@ def test_canonical_layout_gate(kv_cache_groups, certified):
assert _parallelism_agnostic(kv_cache_groups, canonical=True) is certified
@pytest.mark.parametrize(
("spec"),
[_SWA_MLA_SPEC, _mla_spec(tokens_per_state=2)],
ids=["swa", "compressed-mla"],
)
def test_uncertifiable_canonical_layout_resets_replication(spec: KVCacheSpec):
def _get_offloading_config(canonical: bool):
config = _make_vllm_config(
tensor_parallel_size=2,
extra_config={"canonical_layout": True} if canonical else None,
)
config.model_config.use_mla = True
PAGE = spec.page_size_bytes
kv_config = KVCacheConfig(
num_blocks=4,
kv_cache_tensors=[
KVCacheTensor(
size=PAGE * 4,
layers=["layer"],
layer_stride=PAGE * 4,
block_stride=PAGE,
)
],
kv_cache_groups=[
KVCacheGroupSpec(["layer"], spec),
],
)
kv_config.kv_tp_replicas = kv_cache_groups_tp_replicas(
kv_config.kv_cache_groups,
config.parallel_config.tensor_parallel_size,
config.parallel_config.decode_context_parallel_size,
)
return build_offloading_config(config, kv_config)
offload_config = _get_offloading_config(canonical=False)
assert offload_config.replicated_layout
assert not offload_config.parallel.is_parallelism_agnostic
canon_offload_config = _get_offloading_config(canonical=True)
assert not canon_offload_config.replicated_layout
assert not canon_offload_config.parallel.is_parallelism_agnostic
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
@@ -480,7 +480,7 @@ def test_reset():
def test_prom_metrics_observes_manager_counter():
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -506,7 +506,7 @@ def test_prom_metrics_observes_manager_counter():
def test_prom_metrics_observes_flat_transfer_metrics_and_legacy_metrics():
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -568,7 +568,7 @@ def test_prom_metrics_observes_manager_gauge_and_histogram():
return_value=_spec_cls_with_metric_definitions(metric_definitions),
):
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(store_threshold=0), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(store_threshold=0),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -612,7 +612,7 @@ def test_prom_metrics_lazily_observes_labeled_metric():
return_value=_spec_cls_with_metric_definitions(metric_definitions),
):
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(store_threshold=0), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(store_threshold=0),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -651,7 +651,7 @@ def test_prom_metrics_rejects_wrong_label_count():
return_value=_spec_cls_with_metric_definitions(metric_definitions),
):
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(store_threshold=0), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(store_threshold=0),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -672,7 +672,7 @@ def test_prom_metrics_rejects_wrong_label_count():
def test_prom_metrics_uses_configured_manager_metrics():
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(store_threshold=0), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(store_threshold=0),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -693,7 +693,7 @@ def test_prom_metrics_registers_tiering_metrics_from_spec():
"spec_name": "TieringOffloadingSpec",
"secondary_tiers": [],
},
), # type: ignore[arg-type]
),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -741,7 +741,7 @@ def test_aggregate_into_empty_stats():
def test_prom_metrics_multi_engine_routing():
"""Metrics are routed to the correct engine index."""
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -767,7 +767,7 @@ def test_prom_metrics_multi_engine_routing():
def test_prom_metrics_rejects_undeclared_metric():
"""observe() asserts if a metric was never declared in metadata."""
prom_metrics = OffloadPromMetrics(
vllm_config=_FakeVllmConfig(store_threshold=0), # type: ignore[arg-type]
vllm_config=_FakeVllmConfig(store_threshold=0),
metric_types={
Gauge: _FakeMetric,
Counter: _FakeMetric,
@@ -1,15 +1,21 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import contextlib
import ctypes
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
import torch
from vllm.config.compilation import CUDAGraphMode
from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorRole
from vllm.distributed.kv_transfer.kv_connector.v1.example_connector import (
ExampleConnector,
)
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse import (
worker as worker_module,
)
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.connector import (
HiSparseConnector,
HiSparseConnectorMetadata,
@@ -19,8 +25,14 @@ from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.worker import (
HiSparseConnectorWorker,
)
from vllm.distributed.kv_transfer.kv_connector.v1.multi_connector import MultiConnector
from vllm.v1.hisparse import runtime as runtime_module
from vllm.v1.hisparse.coordinator import get_hisparse_coordinator
from vllm.v1.hisparse.runtime import HiSparseCacheHandle
from vllm.v1.hisparse.types import (
SparseKVOffloadCommand,
SparseKVPageTransfer,
SparseKVRowMirror,
)
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
@@ -83,6 +95,7 @@ def test_full_graph_step_prepares_host_mirror_outside_model():
worker._group_leaders = (("layer", handle),)
worker._per_layer_mirrored = set()
worker._submitted_mirror_layers = set()
worker._draft_layers = ()
worker.is_host_writer = True
worker._enqueue_row_dma = MagicMock()
worker.start_step = MagicMock(
@@ -114,3 +127,245 @@ def test_full_graph_step_prepares_host_mirror_outside_model():
worker._enqueue_row_dma.assert_called_once_with((0,), ready_event=None)
runtime.invalidate_written_slots.assert_called_once()
class _FakeEvent:
log: list[tuple[str, object]] = []
def __init__(self, *args, **kwargs) -> None:
pass
def record(self, stream=None) -> None:
self.log.append(("event", self))
def query(self) -> bool:
return True
def synchronize(self) -> None:
pass
@pytest.mark.parametrize("cg_mode", [CUDAGraphMode.FULL, CUDAGraphMode.NONE])
def test_draft_layer_rows_mirrored_after_drafter(monkeypatch, cg_mode):
"""Draft-layer host rows must hold the drafter's writes before page release.
The drafter writes its layers' rows after the target forward. Mirroring
them at the end of the target forward (the only mirror a FULL graph gets)
leaves pre-draft rows on the host, and the page is still reported clean.
"""
block_size, width = 4, 8
resident_block, host_block, transfer_id = 2, 1, 7
log: list[tuple[str, object]] = []
_FakeEvent.log = log
def swap_blocks_batch(src, dst, sizes):
for src_ptr, dst_ptr, size in zip(src.tolist(), dst.tolist(), sizes.tolist()):
ctypes.memmove(dst_ptr, src_ptr, size)
log.append(("dma", dst_ptr))
monkeypatch.setattr(torch, "Event", _FakeEvent)
monkeypatch.setattr(torch, "Stream", lambda *args, **kwargs: MagicMock())
monkeypatch.setattr(torch.cuda, "Stream", lambda *args, **kwargs: MagicMock())
monkeypatch.setattr(torch.cuda, "stream", lambda _: contextlib.nullcontext())
compute_stream = MagicMock()
monkeypatch.setattr(worker_module, "current_stream", lambda: compute_stream)
monkeypatch.setattr(worker_module.ops, "swap_blocks_batch", swap_blocks_batch)
monkeypatch.setattr(
runtime_module,
"get_forward_context",
lambda: SimpleNamespace(cudagraph_runtime_mode=cg_mode),
)
slots = torch.arange(block_size) + resident_block * block_size
request_state_indices = torch.full((1,), -1, dtype=torch.int32)
handles = []
for draft_layer in (False, True):
runtime = SimpleNamespace(
is_group_leader=True,
eager_host_mirror=True,
resident_source_index=0,
host_cache=torch.zeros(4 * block_size, width),
request_state_indices=request_state_indices,
begin_forward=MagicMock(),
invalidate_written_slots=MagicMock(),
)
handle = HiSparseCacheHandle(runtime)
handle.view = SimpleNamespace(
block_size=block_size, cache=torch.zeros(4, block_size, width)
)
handle.slot_mapping = slots
handle.mirror_slot_mapping = slots
handle.draft_layer = draft_layer
handles.append(handle)
target, draft = handles
# Rows the draft layer held before this step's drafter ran.
draft.view.cache[resident_block] = -1.0
worker = HiSparseConnectorWorker(
SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_batched_tokens=16),
num_lookahead_tokens=3,
),
MagicMock(),
)
worker.initialize(
handles,
["target", "draft"],
MagicMock(),
max_num_reqs=1,
host_num_blocks=4,
device=torch.device("cpu"),
pinned_host_pools=[],
)
connector = object.__new__(HiSparseConnector)
connector.connector_worker = worker
connector._get_connector_metadata = MagicMock(
return_value=HiSparseConnectorMetadata(
SparseKVOffloadCommand(
[
SparseKVPageTransfer(
transfer_id=transfer_id,
host_block_id=host_block,
resident_block_ids=(resident_block,),
after_forward=True,
)
]
),
(),
(),
{
"req": (
SparseKVRowMirror(
source_starts=(resident_block * block_size,),
destination_start=host_block * block_size,
num_rows=block_size,
),
)
},
True,
)
)
# A verification step: four query tokens of one request fill the page.
attn_metadata = SimpleNamespace(
num_actual_tokens=block_size,
num_decode_tokens=0,
num_reqs=1,
max_query_len=block_size,
req_id_per_token=torch.zeros(block_size, dtype=torch.int32),
)
connector.start_load_kv(
SimpleNamespace(),
request_state_indices=None,
request_ids=["req"],
num_tokens=block_size,
attn_metadata={"target": attn_metadata, "draft": attn_metadata},
)
target.view.cache[resident_block] = 1.0
if cg_mode != CUDAGraphMode.FULL:
target.finish_kv_update()
connector.finish_forward()
enqueued_before_draft = list(worker._enqueued_transfer_ids)
# The drafter writes the draft layer's rows for the same positions.
if cg_mode != CUDAGraphMode.FULL:
draft.prepare_group_for_batch(attn_metadata)
draft.view.cache[resident_block] = 2.0
if cg_mode != CUDAGraphMode.FULL:
draft.finish_kv_update()
# The next step's start mirrors the drafter's rows, then hands the page over.
compute_stream.wait_event.reset_mock()
connector._get_connector_metadata.return_value = HiSparseConnectorMetadata(
None, (), (), {}, True
)
connector.start_load_kv(
SimpleNamespace(),
request_state_indices=None,
request_ids=[],
num_tokens=0,
attn_metadata={},
)
((completion_event, _),) = worker._pending_transfer_events
worker_meta = connector.build_connector_worker_meta()
host_rows = slice(host_block * block_size, (host_block + 1) * block_size)
torch.testing.assert_close(target.runtime.host_cache[host_rows], torch.ones(4, 8))
torch.testing.assert_close(
draft.runtime.host_cache[host_rows], torch.full((4, 8), 2.0)
)
draft_host = draft.runtime.host_cache
draft_host_range = range(
draft_host.data_ptr(),
draft_host.data_ptr() + draft_host.numel() * draft_host.element_size(),
)
draft_copies = [
index
for index, (kind, ptr) in enumerate(log)
if kind == "dma" and ptr in draft_host_range
]
# One draft-layer copy, and the page is not handed back before it.
assert len(draft_copies) == 1
assert enqueued_before_draft == []
assert log.index(("event", completion_event)) > draft_copies[0]
# The next forward waits for the draft copy: the scheduler may already
# have handed the blocks it reads and writes to another request.
draft_copy_event = next(
entry[1] for entry in log[draft_copies[0] :] if entry[0] == "event"
)
assert compute_stream.wait_event.call_args_list[0].args == (draft_copy_event,)
assert worker_meta is not None
assert worker_meta.enqueued_transfer_counts == {transfer_id: 1}
assert worker_meta.completed_transfer_counts == {transfer_id: 1}
def test_scheduled_prefix_hit_publishes_adopted_copies():
"""Copies adopted after scheduling must reach the worker's block table."""
from tests.v1.core.test_prefix_caching import (
HISPARSE_BLOCK_SIZE,
_allocate_scheduled,
_publish_hisparse_pages,
make_hisparse_kv_cache_manager,
make_request,
sha256,
)
from vllm.v1.core.kv_cache_utils import init_none_hash
init_none_hash(sha256)
manager = make_hisparse_kv_cache_manager(32, 16, enable_caching=True)
tokens = list(range(4 * HISPARSE_BLOCK_SIZE))
original = make_request("original", tokens, HISPARSE_BLOCK_SIZE, sha256)
assert _allocate_scheduled(manager, original, num_new_tokens=len(tokens))
_publish_hisparse_pages(manager)
copy_ids = [block.block_id for block in manager.get_blocks("original").blocks[2]]
manager.free(original)
resumed = make_request("resumed", tokens, HISPARSE_BLOCK_SIZE, sha256)
computed, num_computed, _ = manager.get_computed_blocks(resumed)
num_new_tokens = len(tokens) - num_computed
assert manager.allocate_slots(
resumed,
num_new_tokens=num_new_tokens,
num_new_computed_tokens=num_computed,
new_computed_blocks=computed,
)
scheduler = HiSparseConnectorScheduler(async_speculative=False)
scheduler.bind_coordinator(get_hisparse_coordinator(manager))
scheduler.requests[resumed.request_id] = resumed
scheduler_output = SimpleNamespace(
scheduled_new_reqs=[
SimpleNamespace(
req_id=resumed.request_id,
num_computed_tokens=num_computed,
block_ids=manager.get_block_ids(resumed.request_id),
)
],
scheduled_cached_reqs=SimpleNamespace(
req_ids=[], num_computed_tokens=[], new_block_ids=[]
),
num_scheduled_tokens={resumed.request_id: num_new_tokens},
)
scheduler.build_connector_meta(scheduler_output)
resident_ids = scheduler_output.block_table_updates[resumed.request_id][2]
assert resident_ids[:3] == copy_ids[:3]
File diff suppressed because it is too large Load Diff
@@ -242,6 +242,8 @@ async def test_build_transfer_params_uses_non_overlapping_physical_pages():
kv_cache_config = make_hybrid_gdn_kv_cache_config(block_size=16)
worker = object.__new__(MooncakeConnectorWorker)
worker.shutdown = noop_shutdown
# __new__ skips __init__, where this cache is created. register_kv_caches clears it.
worker._prepared_transfer_regions = {}
worker.use_mla = False
worker.engine = SimpleNamespace(batch_register_memory=lambda *_: 0)
worker.is_kv_consumer = True
@@ -310,7 +310,9 @@ def _make_vllm_config(
kv_cache_layout: KVCacheLayout = KVCacheLayout.LBHNC,
disable_hybrid_kv_cache_manager: bool = True,
) -> SimpleNamespace:
cache_config = SimpleNamespace(block_size=16, num_gpu_blocks=10)
cache_config = SimpleNamespace(
block_size=16, num_gpu_blocks=10, prefix_match_unit=None
)
cache_config.get_resolved_kv_cache_layout = lambda: kv_cache_layout
return SimpleNamespace(
model_config=_FakeModelConfig(),
@@ -1541,7 +1543,7 @@ def test_store_sending_thread_reports_job_when_the_preamble_raises():
# every dequeue leaves through the same exit.
thread = _make_store_sending_thread(MagicMock())
req = _make_store_req("req-a", [b"a0", b"a1"])
req.token_len_chunk = None # type: ignore[assignment]
req.token_len_chunk = None
with contextlib.suppress(TypeError):
_run_store_req(thread, req)
@@ -21,6 +21,9 @@ import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.single_type_kv_cache_manager import FullAttentionManager
from vllm.v1.kv_cache_interface import FullAttentionSpec, UniformTypeKVCacheSpecs
mori_available = importlib.util.find_spec("mori") is not None
@@ -44,6 +47,16 @@ MoRIIOMode = moriio_connector.MoRIIOMode
moriio_common = importlib.import_module(
"vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common"
)
get_role = moriio_common.get_role
set_role = moriio_common.set_role
@pytest.fixture
def restore_moriio_role():
"""Undo the process-global role a full scheduler construction leaves behind."""
role = get_role()
yield
set_role(role)
class _FakeScheduler(moriio_connector.MoRIIOConnectorScheduler): # type: ignore[name-defined]
@@ -53,7 +66,7 @@ class _FakeScheduler(moriio_connector.MoRIIOConnectorScheduler): # type: ignore
def __init__(self, **attrs):
self._mamba_group_ids: list[int] = []
self._attn_group_ids: list[int] = [0]
self._ssm_state_slots_are_positional = False
self._num_ssm_scratch_blocks = 0
self._is_hma_required = False
self.kv_cache_config = SimpleNamespace(
kv_cache_groups=[None, None],
@@ -110,22 +123,56 @@ def _gdn_split_info(conv_rows=3, key_dim=4, value_dim=8, dtype_size=2):
)
def _mamba_spec(num_states: int = 2):
def _mamba_spec(num_states: int = 2, *, num_speculative_blocks: int = 0):
shapes = tuple((1, 1) for _ in range(num_states))
return moriio_connector.MambaSpec(
block_size=16,
shapes=shapes,
dtypes=(torch.float32,) * num_states,
mamba_cache_mode="all",
mamba_cache_mode="align",
num_speculative_blocks=num_speculative_blocks,
)
def _gate_vllm_config(*, read_mode: bool = True, speculative_config=None):
def _spec_config(method: str):
return SimpleNamespace(method=method, use_dspark=lambda: method == "dspark")
def _gate_vllm_config(
*,
read_mode: bool = True,
speculative_config=None,
block_size: int = 16,
num_lookahead_tokens: int = 0,
num_speculative_tokens: int = 0,
mamba_cache_mode: str = "align",
dcp_size: int = 1,
):
return SimpleNamespace(
kv_transfer_config=SimpleNamespace(
kv_connector_extra_config={"read_mode": read_mode}
kv_connector_extra_config={
"read_mode": read_mode,
"host_ip": "127.0.0.1",
"handshake_port": 6001,
"notify_port": 6002,
},
kv_role="kv_consumer",
),
speculative_config=speculative_config,
cache_config=SimpleNamespace(
block_size=block_size,
mamba_cache_mode=mamba_cache_mode,
),
scheduler_config=SimpleNamespace(disable_hybrid_kv_cache_manager=False),
num_lookahead_tokens=num_lookahead_tokens,
num_speculative_tokens=num_speculative_tokens,
parallel_config=SimpleNamespace(
tensor_parallel_size=1,
decode_context_parallel_size=dcp_size,
data_parallel_rank=0,
data_parallel_size_local=1,
data_parallel_size=1,
),
)
@@ -145,7 +192,7 @@ def test_split_block_groups_ignores_transfer_disabled_group():
block_size=16,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="all",
mamba_cache_mode="align",
)
config = SimpleNamespace(
kv_cache_groups=[
@@ -196,6 +243,7 @@ def test_exchange_blocks_ignore_transfer_disabled_group():
def test_scheduler_rejects_multiple_attention_groups_with_mamba():
"""A drafter owning its own transfer group is refused, with a hint."""
config = SimpleNamespace(
kv_cache_groups=[
SimpleNamespace(enable_kv_transfer=True, kv_cache_spec=object()),
@@ -205,7 +253,7 @@ def test_scheduler_rejects_multiple_attention_groups_with_mamba():
)
config.transfer_groups = tuple(config.kv_cache_groups)
with pytest.raises(moriio_common.MoRIIOError, match="exactly one transferable"):
with pytest.raises(moriio_common.MoRIIOError, match="separate attention group"):
moriio_connector.MoRIIOConnectorScheduler(_gate_vllm_config(), "engine", config)
@@ -251,7 +299,7 @@ def test_scheduler_rejects_mamba_group_without_two_states():
moriio_connector.MoRIIOConnectorScheduler(_gate_vllm_config(), "engine", config)
def test_scheduler_rejects_speculative_hybrid_read():
def test_scheduler_rejects_non_dspark_speculative_hybrid_read():
config = SimpleNamespace(
kv_cache_groups=[
SimpleNamespace(enable_kv_transfer=True, kv_cache_spec=object()),
@@ -262,7 +310,89 @@ def test_scheduler_rejects_speculative_hybrid_read():
with pytest.raises(moriio_common.MoRIIOError, match="speculative decoding"):
moriio_connector.MoRIIOConnectorScheduler(
_gate_vllm_config(speculative_config=object()), "engine", config
_gate_vllm_config(speculative_config=_spec_config("ngram")),
"engine",
config,
)
def _dspark_wrapped_attention_config(*, dcp_sharded: bool = True):
"""Mamba first, so a wrapped full-attention group at index 1 has to be found.
A bare ``isinstance(FullAttentionSpec)`` misses the wrapper and leaves
``_full_attn_group_idx`` at its initial 0, which is the Mamba group.
"""
full = FullAttentionSpec(
block_size=4,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
dcp_sharded=dcp_sharded,
)
config = SimpleNamespace(
kv_cache_groups=[
SimpleNamespace(
enable_kv_transfer=True,
kv_cache_spec=_mamba_spec(num_speculative_blocks=2),
),
SimpleNamespace(
enable_kv_transfer=True,
kv_cache_spec=UniformTypeKVCacheSpecs(
block_size=4, kv_cache_specs={"target": full, "draft": full}
),
),
],
)
config.transfer_groups = tuple(config.kv_cache_groups)
return config
@pytest.mark.usefixtures("restore_moriio_role")
@pytest.mark.parametrize(
"dcp_size,dcp_sharded,expected_tail", [(1, True, 4), (4, True, 1), (4, False, 4)]
)
def test_scheduler_accepts_dspark_with_wrapped_full_attention(
dcp_size, dcp_sharded, expected_tail
):
config = _dspark_wrapped_attention_config(dcp_sharded=dcp_sharded)
vllm_config = _gate_vllm_config(
speculative_config=_spec_config("dspark"),
block_size=4,
num_lookahead_tokens=7,
num_speculative_tokens=7,
dcp_size=dcp_size,
)
scheduler = moriio_connector.MoRIIOConnectorScheduler(vllm_config, "engine", config)
assert scheduler._full_attn_group_idx == 1
assert scheduler._num_ssm_scratch_blocks == 2
assert scheduler._max_decode_tail_blocks == expected_tail
# A first decode step reserves padded target rows AND drafter lookahead.
spec = config.transfer_groups[1].kv_cache_spec
manager = FullAttentionManager(
spec,
block_pool=BlockPool(32, enable_caching=False, hash_block_size=4),
enable_caching=False,
kv_cache_group_id=1,
scheduler_block_size=16,
dcp_world_size=dcp_size,
)
imported_tokens = manager.block_size
target_tokens = 1 + vllm_config.num_speculative_tokens
manager.allocate_new_blocks(
"decode",
num_tokens=imported_tokens + target_tokens + vllm_config.num_lookahead_tokens,
num_tokens_main_model=imported_tokens + target_tokens,
)
local = [b.block_id for b in manager.req_to_blocks["decode"]]
remote = [100]
assert scheduler._align_read_blocks(
local, remote, scheduler._max_decode_tail_blocks
) == (local[:1], remote)
with pytest.raises(ValueError, match="tail"):
scheduler._align_read_blocks(
local + [99], remote, scheduler._max_decode_tail_blocks
)
@@ -294,20 +424,7 @@ def test_split_block_groups_accepts_empty_abort_payload():
assert sched.split_block_groups(()) == ([], [])
def test_split_block_groups_keeps_positional_slots_in_all_mode():
# mamba_cache_mode="all" keeps a state per block position.
sched = _FakeScheduler(
_has_mamba=True,
_attn_group_ids=[0],
_mamba_group_ids=[1],
_ssm_state_slots_are_positional=True,
)
attn, mamba = sched.split_block_groups(([1], [40, 41, 42]))
assert attn == [1]
assert mamba == [[40, 41, 42]]
def test_split_block_groups_keeps_only_running_state_outside_all_mode():
def test_split_block_groups_keeps_only_running_state():
sched = _FakeScheduler(
_has_mamba=True,
_attn_group_ids=[0],
@@ -316,6 +433,27 @@ def test_split_block_groups_keeps_only_running_state_outside_all_mode():
assert sched.split_block_groups(([1], [40, 41])) == ([1], [[41]])
@pytest.mark.parametrize(
"blocks,expected",
[
# The running state is picked only after the scratch slots are gone.
([40, 41, 42, 43], [41]),
# Never empty: a list shorter than the scratch count keeps one state.
([40], [40]),
([], []),
],
)
def test_split_block_groups_strips_dspark_scratch_slots(blocks, expected):
sched = _FakeScheduler(
_has_mamba=True,
_attn_group_ids=[0],
_mamba_group_ids=[1],
_num_ssm_scratch_blocks=2,
)
assert sched.split_block_groups(([1], blocks)) == ([1], [expected])
# --------------------------------------------------------------------------
# request_finished_all_groups
# --------------------------------------------------------------------------
@@ -384,7 +522,6 @@ def _make_read_scheduler():
_has_mamba=True,
_attn_group_ids=[0],
_mamba_group_ids=[1],
_ssm_state_slots_are_positional=True,
request_id_to_transfer_id={},
transfer_id_to_request_id={},
_reqs_need_recv={},
@@ -407,17 +544,17 @@ def _make_read_request(remote_block_ids):
def test_update_state_drops_decode_recompute_tail_block():
sched = _make_read_scheduler()
request = _make_read_request([[10, 11], [90, 91]])
request = _make_read_request([[10, 11], [91]])
blocks = _FakeBlocks(
all_groups=([100, 101, 102], [200, 201, 202]),
)
sched.update_state_after_alloc(request, blocks, num_external_tokens=256)
assert sched._reqs_need_recv["req"][1] == [[100, 101], [200, 201]]
assert sched._reqs_need_recv["req"][1] == [[100, 101], [202]]
assert sched._req_kv_params["req"]["remote_block_ids"] == [
[10, 11],
[90, 91],
[91],
]
@@ -434,6 +571,22 @@ def test_update_state_pairs_shorter_local_blocks_with_remote_suffix():
assert sched._req_kv_params["req"]["remote_block_ids"] == [[12], [92]]
def test_update_state_pairs_trimmed_mamba_state_with_remote_state():
"""The DSpark shape end to end: scratch slots are stripped, the running
state is then selected, and the attention list loses its lookahead tail."""
sched = _make_read_scheduler()
sched._num_ssm_scratch_blocks = 2
sched._max_decode_tail_blocks = 2
request = _make_read_request([[10, 11], [90]])
# Mamba group: [null, running state, scratch, scratch].
blocks = _FakeBlocks(all_groups=([100, 101, 102, 103], [200, 201, 202, 203]))
sched.update_state_after_alloc(request, blocks, num_external_tokens=256)
assert sched._reqs_need_recv["req"][1] == [[100, 101], [201]]
assert sched._req_kv_params["req"]["remote_block_ids"] == [[10, 11], [90]]
def test_update_state_full_attention_hit_still_carries_mamba_state():
sched = _make_read_scheduler()
request = _make_read_request([[10], [90]])
@@ -601,6 +601,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
}
@@ -626,6 +627,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
},
"MockConnector": {"mock_field": [1, 2, 3]},
}
@@ -657,6 +659,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
},
}
@@ -678,6 +681,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
mock_stats = MockConnectorStats(data={"mock_field": [1, 2, 3]})
@@ -709,6 +713,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
@@ -742,6 +747,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
},
"ExampleConnector": {"some_field": [1, 2, 3]},
}
@@ -781,6 +787,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -798,6 +805,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -831,6 +839,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -859,6 +868,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -887,6 +897,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -918,6 +929,7 @@ class TestMultiConnectorStats:
"num_failed_notifications": [],
"num_failed_handshakes": [],
"num_kv_expired_reqs": [],
"num_notifications_after_expiry": [],
}
)
}
@@ -114,7 +114,7 @@ def get_default_xfer_telemetry(
class AttributeDict(dict):
__slots__ = ()
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__ # type: ignore[assignment]
__setattr__ = dict.__setitem__
# We can't instantiate nixlXferTelemetry because it's read only and
# ray env does not have NIXL, so we must fake it
@@ -1698,6 +1698,7 @@ def test_kv_connector_stats_failure_grouping():
stats.record_failed_handshake()
stats.record_failed_notification()
stats.record_kv_expired_req()
stats.record_notification_after_expiry()
assert not stats.is_empty()
# No successful transfers: latency stats are zero but the failure
@@ -1706,6 +1707,7 @@ def test_kv_connector_stats_failure_grouping():
assert reduced["Num successful transfers"] == 0
assert reduced["Num failed transfers"] == 3
assert reduced["Num KV expired reqs"] == 1
assert reduced["Num notifs after expiry"] == 1
def test_nixl_prom_metrics_group_handshake_with_transfer_failures():
@@ -1750,6 +1752,7 @@ def test_nixl_prom_metrics_group_handshake_with_transfer_failures():
stats.record_failed_handshake()
stats.record_failed_notification()
stats.record_kv_expired_req()
stats.record_notification_after_expiry()
prom.observe(stats.data, engine_idx=0)
def counter_value(name: str) -> float:
@@ -1761,6 +1764,33 @@ def test_nixl_prom_metrics_group_handshake_with_transfer_failures():
assert counter_value("vllm:nixl_num_failed_transfers_total") == 3.0
assert counter_value("vllm:nixl_num_kv_expired_reqs_total") == 1.0
assert counter_value("vllm:nixl_num_notifications_after_expiry_total") == 1.0
@patch(
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
FakeNixlWrapper,
)
def test_notification_after_expiry_is_counted(default_vllm_config, dist_init):
vllm_config = create_vllm_config()
connector = NixlConnector(
vllm_config, KVConnectorRole.WORKER, make_kv_cache_config(block_size=16)
)
connector.connector_worker = FakeNixlConnectorWorker(
vllm_config, connector.engine_id, hand_shake_latency=0
)
worker = connector.connector_worker
worker._reqs_to_process.add("known")
worker._reqs_to_send["known"] = time.perf_counter() + 10
worker.nixl_wrapper.get_new_notifs = MagicMock(
return_value={"decode-agent": [b"known:1", b"unknown:1"]}
)
assert worker._get_new_notifs() == {"known"}
stats = connector.get_kv_connector_stats()
assert isinstance(stats, NixlKVConnectorStats)
assert stats.data["num_notifications_after_expiry"] == [1]
def test_multi_kv_connector_stats_aggregation():
@@ -856,28 +856,6 @@ def test_apply_prefix_caching_mamba_hybrid(
[[6, 7, 8, 9], [99]],
id="fa_prefix_hit_and_ssm_trim",
),
# Multi-slot SSM ("all" mode): a local prefix hit leaves fewer local
# slots; the earlier remote slots are covered locally → remote tail.
pytest.param(
10,
10,
[list(range(10)), [5, 6]],
[list(range(10)), [1, 2, 3]],
[list(range(10)), [5, 6]],
[list(range(10)), [2, 3]],
id="ssm_multi_block_local_hit_tail",
),
# Multi-slot SSM ("all" mode): the one trailing local position holds
# the token D recomputes itself → local head-clip.
pytest.param(
10,
10,
[list(range(10)), [4, 5, 6]],
[list(range(10)), [8, 9]],
[list(range(10)), [4, 5]],
[list(range(10)), [8, 9]],
id="ssm_multi_block_local_extra_head_clip",
),
],
)
def test_apply_prefix_caching_ssm_prefix_cache_hit(
@@ -2034,13 +2012,12 @@ def test_logical_to_kernel_block_ids_with_remote_ratio(
@pytest.mark.cpu_test
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."""
"""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."""
sched = make_nixl_scheduler(has_mamba=True, is_hma_required=True)
sched.blocks_per_sw = [0, 0]
sched._ssm_spec_blocks = [None, 2]
sched._ssm_state_slots_are_positional = False
# Align-mode list: null placeholders, state block, 2 speculative slots.
clipped = sched.get_exchange_clipped_blocks(([1, 2, 3], [0, 0, 7, 8, 9]))
@@ -2055,24 +2032,20 @@ def test_exchange_clipped_blocks_ssm_single_state():
# Scratch slots not allocated: the state slot still survives.
assert sched.get_exchange_clipped_blocks(([1], [5]))[1] == [5]
assert sched.get_exchange_clipped_blocks(([1], [])) == ([1], [])
# Per-step partial lists must not be interpreted as state + scratch slots.
assert sched.get_exchange_clipped_blocks(([1], [7, 8]), clip_ssm=False) == (
[1],
[7, 8],
)
sched.blocks_per_sw = [2, 0]
assert sched.get_exchange_clipped_blocks(([1, 2, 3], [7, 8, 9])) == ([2, 3], [7])
# Non-mamba models pass through unchanged.
fa_sched = make_nixl_scheduler(has_mamba=False)
assert fa_sched.get_exchange_clipped_blocks(([1, 2],)) == ([1, 2],)
@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."""
sched = make_nixl_scheduler(has_mamba=True, is_hma_required=True)
sched.blocks_per_sw = [0, 0]
sched._ssm_spec_blocks = [None, 2]
sched._ssm_state_slots_are_positional = True
clipped = sched.get_exchange_clipped_blocks(([1, 2, 3], [0, 5, 6, 7, 8, 9]))
assert clipped == ([1, 2, 3], [0, 5, 6, 7])
# ── Hybrid MLA+SSM (KimiLinear-shaped KDA+MLA) tests ─────────────────────
@@ -2387,3 +2360,50 @@ def test_push_write_hybrid_mla_replicates_attention():
assert spec.remote_block_ids == [[7, 8], [3]]
assert call.kwargs["local_xfer_side_handle"] == local_handle
assert call.kwargs["remote_xfer_side_handle"] == remote_handle
def _make_host_buffer_worker(copy_op):
"""A worker stripped down to what the host-buffer copy paths touch."""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
NixlConnectorWorker,
)
worker = object.__new__(NixlConnectorWorker)
worker.use_host_buffer = True
worker.copy_blocks = copy_op
return worker
@pytest.mark.cpu_test
@pytest.mark.parametrize(
"group_block_ids,expected_ids",
[
# Single group (non-hybrid model): one copy, as before.
([[1, 2, 3]], [1, 2, 3]),
# Hybrid model: three groups collapse into a single copy.
([[1, 2], [3, 4], [5]], [1, 2, 3, 4, 5]),
# An empty group contributes no ids.
([[1, 2], []], [1, 2]),
],
)
def test_sync_recved_kv_issues_one_copy_per_request(group_block_ids, expected_ids):
"""h2d copies are issued once per request, not once per KV cache group."""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import ReqMeta
calls = []
worker = _make_host_buffer_worker(
lambda src, dst, src_ids, dst_ids, direction: calls.append(
(src_ids, dst_ids, direction)
)
)
worker.host_xfer_buffers = {"layer": None}
worker.device_kv_caches = {"layer": None}
meta = ReqMeta(
local_block_ids=group_block_ids,
local_physical_block_ids=group_block_ids,
tp_size=1,
)
worker.sync_recved_kv_to_device("req", meta)
assert calls == [(expected_ids, expected_ids, "h2d")]
@@ -1256,7 +1256,7 @@ class TestPushWriterNegative:
w = _StubWriterWorker.fresh()
for bogus_rid in (123, None, 4.5, b"bytes-not-str"):
payload = _registration_data("placeholder")
payload["request_id"] = bogus_rid # type: ignore[assignment]
payload["request_id"] = bogus_rid
notif = PUSH_REG_NOTIF_PREFIX + msgspec.msgpack.encode(payload)
w._handle_push_reg_notif(notif)
assert w._pending_d_registrations == {}
@@ -1357,6 +1357,7 @@ class TestPushWriterNegative:
assert notified == set()
# Did not register anywhere.
assert "never-heard-of-you" not in w._recving_transfers
assert w.xfer_stats.data["num_notifications_after_expiry"] == [1]
def test_start_load_kv_with_empty_metadata_is_noop(self):
"""Empty metadata must not wake the writer or enqueue anything."""
@@ -566,10 +566,7 @@ def test_fs_tiering_offloading(tmp_path) -> None:
("state-spaces/mamba-1.4b-hf", 16, 1),
],
)
@pytest.mark.parametrize("mamba_cache_mode", ["align", "all"])
def test_mamba_cpu_offload_boundary(
model: str, block_size: int, tp_size: int, mamba_cache_mode: str
):
def test_mamba_cpu_offload_boundary(model: str, block_size: int, tp_size: int):
kv_transfer_config = KVTransferConfig(
kv_connector="OffloadingConnector",
kv_role="kv_both",
@@ -586,7 +583,7 @@ def test_mamba_cpu_offload_boundary(
kv_transfer_config=kv_transfer_config,
language_model_only=True,
enable_prefix_caching=True,
mamba_cache_mode=mamba_cache_mode,
mamba_cache_mode="align",
# Use lossless state storage so this exact-equality regression isolates
# offload boundary selection from low-precision Mamba checkpointing.
mamba_cache_dtype="float32",
@@ -5,6 +5,7 @@ from unittest.mock import patch
import pytest
from vllm.v1.metrics.stats import KV_FETCH_STAGES
from vllm.v1.outputs import (
EMPTY_MODEL_RUNNER_OUTPUT,
KVConnectorOutput,
@@ -28,6 +29,11 @@ def _num_waiting_requests(scheduler) -> int:
return len(scheduler.waiting) + len(scheduler.kv_holding_waiting)
def _kv_fetch_stages(scheduler) -> tuple[int, ...]:
"""(waiting_to_start, in_progress, completed_waiting) request counts."""
return tuple(scheduler._kv_fetch_counts[s] for s in KV_FETCH_STAGES)
def test_basic_lifecycle():
"""Test lifecycle of a remote prefill."""
vllm_config = create_vllm_config()
@@ -50,10 +56,12 @@ def test_basic_lifecycle():
scheduler.add_request(request)
request_id = request.request_id
assert _kv_fetch_stages(scheduler) == (1, 0, 0)
# STEP (1):
# (1a): schedule()
scheduler_output = scheduler.schedule()
assert _kv_fetch_stages(scheduler) == (0, 1, 0)
# Nothing running and empty scheduler output.
assert len(scheduler.running) == 0
@@ -105,11 +113,13 @@ def test_basic_lifecycle():
)
assert _num_waiting_requests(scheduler) == 1
assert request_id in scheduler.finished_recving_kv_req_ids
assert _kv_fetch_stages(scheduler) == (0, 0, 1)
# STEP (3):
# (3a): schedule(): this should actually schedule.
scheduler_output = scheduler.schedule()
assert len(scheduler.running) == 1
assert _kv_fetch_stages(scheduler) == (0, 0, 0)
# Confirm the block are actually allocated.
num_hashed_blocks = 0
@@ -582,6 +592,24 @@ def test_cannot_recv():
assert_scheduler_empty(scheduler)
def test_kv_fetch_stages_cleared_on_abort():
vllm_config = create_vllm_config()
scheduler = create_scheduler(vllm_config)
BLOCK_SIZE = vllm_config.cache_config.block_size
request = create_request(
request_id=1,
block_size=BLOCK_SIZE,
num_tokens=int(BLOCK_SIZE * 2.5),
do_remote_prefill=True,
)
scheduler.add_request(request)
scheduler.schedule()
assert _kv_fetch_stages(scheduler) == (0, 1, 0)
scheduler.finish_requests(request.request_id, RequestStatus.FINISHED_ABORTED)
assert _kv_fetch_stages(scheduler) == (0, 0, 0)
@patch(
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_scheduler.current_platform"
)
+3 -1
View File
@@ -60,6 +60,8 @@ def assert_scheduler_empty(scheduler: Scheduler):
assert len(scheduler.finished_req_ids) == 0
assert len(scheduler.finished_recving_kv_req_ids) == 0
assert len(scheduler._inflight_prefills) == 0
assert not scheduler._kv_fetch_stages
assert not any(scheduler._kv_fetch_counts.values())
# EncoderCacheManager.
assert len(scheduler.encoder_cache_manager.freed) == 0
@@ -474,7 +476,7 @@ def make_kv_cache_config(
mamba_enabled: bool = False,
sw_size: int = 128,
num_blocks: int = 100,
mamba_cache_mode: Literal["all", "align", "none"] = "none",
mamba_cache_mode: Literal["align", "none"] = "none",
) -> KVCacheConfig:
kv_cache_groups = [
KVCacheGroupSpec(
+41 -41
View File
@@ -349,10 +349,10 @@ class TestServeExternalRequests:
mgr._failed_serve_ctxs = [ctx]
sess_a = _RecordingSession()
sess_b = _RecordingSession()
mgr._sessions = {"a": sess_a, "b": sess_b} # type: ignore[assignment]
mgr._sessions = {"a": sess_a, "b": sess_b}
parent = _RecordingParent()
mgr.serve_external_requests(parent) # type: ignore[arg-type]
mgr.serve_external_requests(parent)
# Failed serve released and queue cleared.
assert parent.finished == ["p2p:peer:req-1:lu1"]
@@ -364,10 +364,10 @@ class TestServeExternalRequests:
def test_no_failed_serves_still_serves_sessions(self):
mgr = _make_manager()
sess = _RecordingSession()
mgr._sessions = {"a": sess} # type: ignore[assignment]
mgr._sessions = {"a": sess}
parent = _RecordingParent()
mgr.serve_external_requests(parent) # type: ignore[arg-type]
mgr.serve_external_requests(parent)
assert parent.finished == []
assert sess.served_with == [parent]
@@ -427,7 +427,7 @@ class TestSubmitStore:
forwards directly to that session rather than re-buffering."""
mgr = _make_manager()
bound = _FakeSession(peer_id="10.0.0.1:8000", connected=True)
mgr._kv_to_session["req-1"] = bound # type: ignore[assignment]
mgr._kv_to_session["req-1"] = bound
# Note: _sessions is intentionally untouched — this test isolates
# the kv_request_id → session fast path.
job = _job_metadata(
@@ -495,7 +495,7 @@ class TestSubmitLoad:
mgr = _make_manager()
peer_id = "10.0.0.1:8000"
existing = _FakeSession(peer_id=peer_id, connected=True)
mgr._sessions[peer_id] = existing # type: ignore[assignment]
mgr._sessions[peer_id] = existing
job = _job_metadata(
job_id=42,
keys=[b"k1", b"k2"],
@@ -581,7 +581,7 @@ class TestOnRequestFinished:
(FetchMsg received) routes via _kv_to_session and pops the entry."""
mgr = _make_manager()
bound = _FakeSession(peer_id="some-peer:1", connected=True)
mgr._kv_to_session["req-1"] = bound # type: ignore[assignment]
mgr._kv_to_session["req-1"] = bound
ctx = _req_context(kv_params=_remote_decoder_kv_params(kv_request_id="req-1"))
mgr.on_request_finished(ctx)
assert bound.finishes == ["req-1"]
@@ -718,8 +718,8 @@ class TestGetFinished:
def poll(self):
return []
mgr._control = FakeControl() # type: ignore[assignment]
mgr._data = None # type: ignore[assignment]
mgr._control = FakeControl()
mgr._data = None
return mgr
def test_drains_finished_jobs(self):
@@ -740,7 +740,7 @@ class TestGetFinished:
pass
mgr = self._make()
mgr._data = FakeData() # type: ignore[assignment]
mgr._data = FakeData()
dead = _FakeSession(
peer_id="dead:1234",
alive=False,
@@ -749,7 +749,7 @@ class TestGetFinished:
close_req_ids=["req-load"],
close_stores=[10, 11],
)
mgr._sessions["dead:1234"] = dead # type: ignore[assignment]
mgr._sessions["dead:1234"] = dead
results = list(mgr.get_finished_jobs())
# 2 baseline + 1 failed load + 2 failed stores
@@ -769,14 +769,14 @@ class TestGetFinished:
pass
mgr = self._make()
mgr._data = FakeData() # type: ignore[assignment]
mgr._data = FakeData()
dead = _FakeSession(
peer_id="dead:1234",
alive=False,
connected=True,
close_req_ids=["req-probe-1", "req-probe-2"],
)
mgr._sessions["dead:1234"] = dead # type: ignore[assignment]
mgr._sessions["dead:1234"] = dead
list(mgr.get_finished_jobs())
assert "dead:1234" not in mgr._sessions
@@ -854,7 +854,7 @@ class TestHasPendingWork:
"""The result is the same regardless of session state — there is
no 'idle' branch."""
mgr = _make_manager()
mgr._sessions["peer:1"] = _FakeSession(peer_id="peer:1") # type: ignore[assignment]
mgr._sessions["peer:1"] = _FakeSession(peer_id="peer:1")
assert mgr.has_pending_work() is True
@@ -919,12 +919,12 @@ class TestShutdownDrain:
mgr = _make_manager()
data = _ShutdownFakeData(still_queue=still_queue)
control = _ShutdownFakeControl()
mgr._data = data # type: ignore[assignment]
mgr._control = control # type: ignore[assignment]
mgr._data = data
mgr._control = control
if inflight_ids:
session = _FakeSession(peer_id="peer:1", connected=True)
session._server._inflight = {tid: object() for tid in inflight_ids}
mgr._sessions["peer:1"] = session # type: ignore[assignment]
mgr._sessions["peer:1"] = session
return mgr, data, control
def test_shutdown_drains_inflight_via_wait_cancel(self):
@@ -1148,10 +1148,10 @@ def _build_paired_managers() -> tuple[P2PSecondaryTierManager, P2PSecondaryTierM
ctrl_b = _LoopbackControl(mgr_b._local_id)
ctrl_a.pair(ctrl_b)
mgr_a._control = ctrl_a # type: ignore[assignment]
mgr_b._control = ctrl_b # type: ignore[assignment]
mgr_a._data = _FakeData(mgr_a._local_id) # type: ignore[assignment]
mgr_b._data = _FakeData(mgr_b._local_id) # type: ignore[assignment]
mgr_a._control = ctrl_a
mgr_b._control = ctrl_b
mgr_a._data = _FakeData(mgr_a._local_id)
mgr_b._data = _FakeData(mgr_b._local_id)
return mgr_a, mgr_b
@@ -1334,7 +1334,7 @@ class TestAcceptNewPeers:
mgr = _make_manager()
peer_id = "10.0.0.1:8000"
existing = _FakeSession(peer_id=peer_id, connected=True)
mgr._sessions[peer_id] = existing # type: ignore[assignment]
mgr._sessions[peer_id] = existing
new_conn = _RecordingConn(peer_id)
mgr._accept_new_peers([new_conn])
@@ -1365,7 +1365,7 @@ class TestAcceptNewPeers:
pass
mgr = _make_manager()
mgr._data = FakeData() # type: ignore[assignment]
mgr._data = FakeData()
peer_id = "10.0.0.1:8000"
# Real ControlConnection-shaped fake: send/close/peer_id only.
@@ -1382,7 +1382,7 @@ class TestAcceptNewPeers:
def close(self) -> None:
self.alive = False
mgr._accept_new_peers([_Conn(peer_id)]) # type: ignore[arg-type]
mgr._accept_new_peers([_Conn(peer_id)])
assert peer_id in mgr._sessions
assert mgr._sessions[peer_id].connected is True
@@ -1411,7 +1411,7 @@ class TestPollOnce:
loads=[LoadResult(job_id=11, kv_request_id="req-11", success=True)],
stores=[StoreResult(job_id=22, success=True)],
)
mgr._sessions[peer_alive] = alive # type: ignore[assignment]
mgr._sessions[peer_alive] = alive
# Dead session whose pending close() jobs surface as failures.
peer_dead = "10.0.0.3:9999"
@@ -1423,7 +1423,7 @@ class TestPollOnce:
close_req_ids=["req-33"],
close_stores=[44],
)
mgr._sessions[peer_dead] = dead # type: ignore[assignment]
mgr._sessions[peer_dead] = dead
class _Ctrl:
def poll(self_inner):
@@ -1433,8 +1433,8 @@ class TestPollOnce:
def remove_remote_peer(self_inner, pid):
pass
mgr._control = _Ctrl() # type: ignore[assignment]
mgr._data = _Data() # type: ignore[assignment]
mgr._control = _Ctrl()
mgr._data = _Data()
mgr._poll_once()
@@ -1464,7 +1464,7 @@ class TestPollOnce:
connected=True,
new_fetch_ids=["req-1"],
)
mgr._sessions[peer] = sess # type: ignore[assignment]
mgr._sessions[peer] = sess
mgr._unbound_stores["req-1"] = [
_UnboundStoreBatch(job_id=5, keys=[b"k1"], block_ids=[0]),
_UnboundStoreBatch(job_id=6, keys=[b"k2"], block_ids=[1]),
@@ -1474,7 +1474,7 @@ class TestPollOnce:
def poll(self_inner):
return []
mgr._control = _Ctrl() # type: ignore[assignment]
mgr._control = _Ctrl()
mgr._poll_once()
assert mgr._kv_to_session["req-1"] is sess
@@ -1496,13 +1496,13 @@ class TestPollOnce:
connected=True,
new_fetch_ids=["req-fast"],
)
mgr._sessions[peer] = sess # type: ignore[assignment]
mgr._sessions[peer] = sess
class _Ctrl:
def poll(self_inner):
return []
mgr._control = _Ctrl() # type: ignore[assignment]
mgr._control = _Ctrl()
mgr._poll_once()
assert mgr._kv_to_session["req-fast"] is sess
@@ -1519,13 +1519,13 @@ class TestPollOnce:
connected=True,
loads=[LoadResult(job_id=5, kv_request_id="req-5", success=False)],
)
mgr._sessions[peer] = sess # type: ignore[assignment]
mgr._sessions[peer] = sess
class _Ctrl:
def poll(self_inner):
return []
mgr._control = _Ctrl() # type: ignore[assignment]
mgr._control = _Ctrl()
mgr._poll_once()
@@ -1549,26 +1549,26 @@ class TestDrainJobs:
def test_returns_immediately_when_quiescent(self):
"""No sessions and no inflight: drain_jobs returns without sleeping."""
mgr = _make_manager()
mgr._control = _DrainCtrl() # type: ignore[assignment]
mgr._control = _DrainCtrl()
sleeps: list[float] = []
# If drain_jobs sleeps when nothing is pending, that's a regression.
import vllm.v1.kv_offload.tiering.p2p.manager as m
original_sleep = m.time.sleep
m.time.sleep = lambda s: sleeps.append(s) # type: ignore[assignment]
m.time.sleep = lambda s: sleeps.append(s)
try:
mgr.drain_jobs()
finally:
m.time.sleep = original_sleep # type: ignore[assignment]
m.time.sleep = original_sleep
assert sleeps == []
def test_returns_when_session_has_no_inflight_or_inbound(self):
"""A session with empty _inbound and _inflight does not block drain."""
mgr = _make_manager()
mgr._control = _DrainCtrl() # type: ignore[assignment]
mgr._sessions["peer:1"] = _FakeSession(peer_id="peer:1") # type: ignore[assignment]
mgr._control = _DrainCtrl()
mgr._sessions["peer:1"] = _FakeSession(peer_id="peer:1")
# Should return on the first iteration.
mgr.drain_jobs()
@@ -1576,10 +1576,10 @@ class TestDrainJobs:
"""A session that stays inflight past 5s triggers the warning, and
once it clears the loop returns."""
mgr = _make_manager()
mgr._control = _DrainCtrl() # type: ignore[assignment]
mgr._control = _DrainCtrl()
sess = _FakeSession(peer_id="peer:1")
sess._server._inflight = {1: object()} # non-empty
mgr._sessions["peer:1"] = sess # type: ignore[assignment]
mgr._sessions["peer:1"] = sess
# Synthetic monotonic clock: 100.0 for the start stamp, then 106.0
# for the first elapsed-check (past the 5s warning threshold), then
@@ -288,17 +288,17 @@ def _make_session(
session = P2PSession(
peer_id=peer_id,
local_id=local_id,
transport=transport, # type: ignore[arg-type]
transport=transport,
local_block_len=transport.block_len,
local_hash_seed=local_hash_seed,
conn=conn, # type: ignore[arg-type]
conn=conn,
)
return session, conn, transport
def _serve(session: P2PSession, parent: FakeParent) -> None:
"""Resolve enqueued inbound lookups, as the manager does each step."""
session.serve_external_requests(parent) # type: ignore[arg-type]
session.serve_external_requests(parent)
def _activate(
@@ -1951,7 +1951,7 @@ class TestFinishRequestServerSide:
)
session.poll()
# Force write_blocks to fail on the next call.
transport.write_blocks = lambda *a, **kw: None # type: ignore[assignment]
transport.write_blocks = lambda *a, **kw: None # type: ignore[method-assign]
session.add_stored_blocks("req-1", [b"k1"], [0], job_id=42)
@@ -2057,7 +2057,7 @@ class TestFinishRequestServerSide:
assert outbound.finishing is False
# Round 2: write_blocks fails for k2 while transfer_1 is still inflight.
transport.write_blocks = lambda *a, **kw: None # type: ignore[assignment]
transport.write_blocks = lambda *a, **kw: None # type: ignore[method-assign]
session.add_stored_blocks("req-1", [b"k2"], [1], job_id=200)
# No new transfer was registered.
assert list(session._server._inflight.keys()) == [tid_1]
@@ -2163,7 +2163,7 @@ class TestPendingSession:
session = P2PSession(
peer_id="peer:8000",
local_id="local:9000",
transport=transport, # type: ignore[arg-type]
transport=transport,
local_block_len=4096,
local_hash_seed=_DEFAULT_HASH_SEED,
conn=None,
@@ -2183,13 +2183,13 @@ class TestPendingSession:
session = P2PSession(
peer_id="peer:8000",
local_id="local:9000",
transport=transport, # type: ignore[arg-type]
transport=transport,
local_block_len=4096,
local_hash_seed=_DEFAULT_HASH_SEED,
conn=None,
)
conn = FakeConnection(peer_id="peer:8000")
session.attach_connection(conn) # type: ignore[arg-type]
session.attach_connection(conn)
assert conn._sent
assert conn._sent[0][TYPE_KEY] == ConnectMsg.TYPE
@@ -2197,7 +2197,7 @@ class TestPendingSession:
"""attach_connection on an already-connected session raises."""
session, conn, _ = _make_session()
with pytest.raises(ValueError, match="already connected"):
session.attach_connection(FakeConnection()) # type: ignore[arg-type]
session.attach_connection(FakeConnection())
def test_pending_close_returns_pending_stores(self):
"""Closing a pending session reports buffered stores as failed."""
@@ -2205,7 +2205,7 @@ class TestPendingSession:
session = P2PSession(
peer_id="peer:8000",
local_id="local:9000",
transport=transport, # type: ignore[arg-type]
transport=transport,
local_block_len=4096,
local_hash_seed=_DEFAULT_HASH_SEED,
conn=None,
@@ -2313,7 +2313,7 @@ class TestAdversarial:
def test_non_dict_message(self):
session, conn, _ = _make_session()
_activate(session, conn)
conn._inbox.append(42) # type: ignore[arg-type]
conn._inbox.append(42)
result_ = session.poll()
loads = result_.loads
stores = result_.stores
@@ -2402,7 +2402,7 @@ class TestDispatchErrorHandling:
def _boom(*args, **kwargs):
raise RuntimeError("simulated internal bug")
session._server.on_fetch = _boom # type: ignore[assignment]
session._server.on_fetch = _boom
conn.enqueue(
{
TYPE_KEY: FetchMsg.TYPE,
@@ -2425,7 +2425,7 @@ class TestDispatchErrorHandling:
def _boom(*args, **kwargs):
raise RuntimeError("simulated internal bug")
session._server.on_fetch = _boom # type: ignore[assignment]
session._server.on_fetch = _boom
for _ in range(_MAX_CONSECUTIVE_DISPATCH_ERRORS):
conn.enqueue(
{
@@ -2454,7 +2454,7 @@ class TestDispatchErrorHandling:
# Alternate (boom, success) (_MAX-1) times: counter rises to 1
# then resets to 0 each cycle, never reaching the threshold.
for _ in range(_MAX_CONSECUTIVE_DISPATCH_ERRORS - 1):
session._server.on_fetch = _boom # type: ignore[assignment]
session._server.on_fetch = _boom
conn.enqueue(
{
TYPE_KEY: FetchMsg.TYPE,
@@ -2465,7 +2465,7 @@ class TestDispatchErrorHandling:
}
)
session.poll()
session._server.on_fetch = original_on_fetch # type: ignore[assignment]
session._server.on_fetch = original_on_fetch
# A benign no-op message (unknown type) dispatches cleanly
# and resets the consecutive-error counter.
conn.enqueue({TYPE_KEY: "unknown_for_test"})
+54 -71
View File
@@ -3,7 +3,7 @@
import random
from collections.abc import Callable
from typing import NamedTuple, TypeAlias
from typing import NamedTuple, NoReturn, TypeAlias
import numpy as np
import pytest
@@ -13,6 +13,7 @@ from tests.utils import create_new_process_for_each_test
from tests.v1.sample.utils import (
LogitsprocsTestFakes,
create_fake_logits,
create_mock_reasoning_config,
create_penalty_tensor,
create_prompt_tokens_tensor,
fake_apply_logitsprocs,
@@ -103,14 +104,6 @@ class LogitsProcsRequestParams:
return f"MyClass({summ})"
class MockReasoningConfig:
"""Minimal reasoning config for ``ThinkingBudgetStateHolder`` tests."""
reasoning_start_token_ids = [THINK_START_TOKEN_ID]
reasoning_end_token_ids = [THINK_END_TOKEN_ID]
enabled = True
def _generate_fake_sampling_metadata(
num_output_tokens: int,
batch_size: int,
@@ -131,7 +124,9 @@ def _generate_fake_sampling_metadata(
)
vllm_config = VllmConfig()
vllm_config.reasoning_config = MockReasoningConfig()
vllm_config.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
logitsprocs = build_logitsprocs(
vllm_config=vllm_config,
@@ -242,7 +237,7 @@ def _raise_error_invalid(
request_params: LogitsProcsRequestParams,
step_idx: int,
err_cls: type[Exception] = ValueError,
) -> None:
) -> NoReturn:
raise err_cls(
f"Validation failed for step={step_idx}, "
f"batch_index={batch_index}, "
@@ -268,6 +263,7 @@ def _logit_bias_validate(
) -> None:
"""Validate logit bias logitproc applied correctly."""
logit_bias = request_params.params.logit_bias
assert logit_bias is not None
logits_old = test_fakes.logits[persistent_batch[batch_index].workload_index].cpu()
logits_new = logits_new[batch_index].cpu()
for token_id in range(VOCAB_SIZE):
@@ -368,9 +364,7 @@ def _min_tokens_validate(
ref_num_out_tokens = len(request_params.out_tokens)
min_reached = ref_num_out_tokens >= MIN_TOKENS_LEN_THRESHOLD
ref_all_stop_token_ids = request_params.params.all_stop_token_ids
mt_lp: MinTokensLogitsProcessor = next(
test_fakes.get_logitsprocs_by_cls(MinTokensLogitsProcessor)
)
mt_lp = next(test_fakes.get_logitsprocs_by_cls(MinTokensLogitsProcessor))
assert isinstance(mt_lp, MinTokensLogitsProcessor)
min_tok = mt_lp.min_toks.get(batch_index, None)
@@ -689,7 +683,7 @@ class LogitsprocTestHelpers(NamedTuple):
gen_request_fxn: Callable | None = None
logitsprocs_test_mapping = {
logitsprocs_test_mapping: dict[LogitprocType, LogitsprocTestHelpers] = {
STR_NO_LOGITPROC: LogitsprocTestHelpers(eval_fxn=_none_validate),
LogitBiasLogitsProcessor: LogitsprocTestHelpers(
gen_request_fxn=_logit_bias_params, eval_fxn=_logit_bias_validate
@@ -706,22 +700,22 @@ logitsprocs_test_mapping = {
}
def _get_test_cases() -> list[list[str]]:
def _get_test_cases() -> list[list[LogitprocType]]:
"""Each test case is a set of logitsprocs."""
logitsprocs_types = list(logitsprocs_test_mapping.keys())
logitsprocs_types: list[LogitprocType] = list(logitsprocs_test_mapping.keys())
# Isolate thinking-budget handling from other processors to avoid cross-talk.
thinking_id: LogitprocType = STR_THINKING_BUDGET
other_processors = [
other_processors: list[LogitprocType] = [
p for p in logitsprocs_types if p != STR_NO_LOGITPROC and p != thinking_id
]
return (
[[STR_NO_LOGITPROC]]
+ [[logitproc_type, STR_NO_LOGITPROC] for logitproc_type in other_processors]
+ [other_processors]
+ [[thinking_id]]
test_cases: list[list[LogitprocType]] = [[STR_NO_LOGITPROC]]
test_cases.extend(
[logitproc_type, STR_NO_LOGITPROC] for logitproc_type in other_processors
)
test_cases.extend([other_processors, [thinking_id]])
return test_cases
def _generate_fake_step_update(
@@ -774,6 +768,7 @@ def _generate_fake_step_update(
for add_req_params in workload_params[wdx : (wdx + num_step_add_replace)]:
# Replace as many removed requests as possible with added requests
add_remove_idx = batch_update_builder.pop_removed()
assert add_remove_idx is not None
batch_update_builder.added.append(
(
add_remove_idx,
@@ -976,13 +971,6 @@ def test_logitsprocs(
step_idx += 1
class MockReasoningNoEndTokens:
"""Reasoning config with no end token ids (disables enforcement in holder)."""
reasoning_start_token_ids = [THINK_START_TOKEN_ID]
reasoning_end_token_ids: list[int] = []
def test_maybe_create_thinking_budget_holder_without_reasoning():
cfg = VllmConfig()
assert cfg.reasoning_config is None
@@ -1000,7 +988,9 @@ def test_maybe_create_thinking_budget_holder_without_reasoning():
def test_thinking_budget_holder_has_tracked_after_sync_add():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1030,7 +1020,9 @@ def test_thinking_budget_holder_has_tracked_after_sync_add():
def test_thinking_budget_holder_sync_remove_clears_state():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1060,7 +1052,9 @@ def test_thinking_budget_holder_sync_remove_clears_state():
def test_thinking_budget_holder_sync_add_without_budget_drops_row():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1081,7 +1075,9 @@ def test_thinking_budget_holder_sync_add_without_budget_drops_row():
def test_thinking_budget_holder_swap_exchanges_state():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1125,7 +1121,9 @@ def test_thinking_budget_holder_swap_exchanges_state():
def test_thinking_budget_holder_unidirectional_move():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1163,7 +1161,9 @@ def test_thinking_budget_holder_unidirectional_move():
def test_thinking_budget_holder_update_state_repeat_indices_last_row_wins():
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1197,7 +1197,7 @@ def test_thinking_budget_holder_update_state_repeat_indices_last_row_wins():
def test_thinking_budget_holder_spec_mode_tensor_layout():
h = ThinkingBudgetStateHolder(
MockReasoningConfig(),
create_mock_reasoning_config([THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]),
8,
2,
torch.device("cpu"),
@@ -1209,7 +1209,7 @@ def test_thinking_budget_holder_spec_mode_tensor_layout():
def test_thinking_budget_holder_empty_end_tokens_disables_row():
vc = VllmConfig()
vc.reasoning_config = MockReasoningNoEndTokens()
vc.reasoning_config = create_mock_reasoning_config([THINK_START_TOKEN_ID], [])
h = ThinkingBudgetStateHolder(
vc.reasoning_config,
vc.scheduler_config.max_num_seqs,
@@ -1253,7 +1253,9 @@ def test_thinking_budget_enforced_without_penalties():
passing an empty list (the pre-fix behavior) prevents budget enforcement.
"""
vc = VllmConfig()
vc.reasoning_config = MockReasoningConfig()
vc.reasoning_config = create_mock_reasoning_config(
[THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]
)
budget = 3 # allow 3 thinking tokens
h = ThinkingBudgetStateHolder(
@@ -1346,7 +1348,11 @@ def test_thinking_budget_long_thinking_section_end_marker_found_at_correct_index
"""Test thinking budget enforced for a long thinking run,
then a natural end marker."""
h = ThinkingBudgetStateHolder(
MockReasoningConfig(), 8, 0, torch.device("cpu"), False
create_mock_reasoning_config([THINK_START_TOKEN_ID], [THINK_END_TOKEN_ID]),
8,
0,
torch.device("cpu"),
False,
)
h.sync_batch(
BatchUpdate(
@@ -1356,8 +1362,8 @@ def test_thinking_budget_long_thinking_section_end_marker_found_at_correct_index
moved=(),
)
)
start = MockReasoningConfig.reasoning_start_token_ids
end = MockReasoningConfig.reasoning_end_token_ids
start = [THINK_START_TOKEN_ID]
end = [THINK_END_TOKEN_ID]
out: list[int] = list(start)
h.update_state([out], None, None)
@@ -1396,13 +1402,9 @@ class TestThinkingBudgetReentry:
@staticmethod
def _make_holder(end_token_ids: list[int]) -> ThinkingBudgetStateHolder:
class FakeReasoningConfig:
reasoning_start_token_ids = [TestThinkingBudgetReentry.THINK_START]
reasoning_end_token_ids: list[int] = []
enabled = True
cfg = FakeReasoningConfig()
cfg.reasoning_end_token_ids = end_token_ids
cfg = create_mock_reasoning_config(
[TestThinkingBudgetReentry.THINK_START], end_token_ids
)
return ThinkingBudgetStateHolder(
reasoning_config=cfg,
max_num_seqs=8,
@@ -1526,21 +1528,12 @@ class TestThinkingBudgetNaturalEndReentry:
@staticmethod
def _make_holder(end_token_ids):
from dataclasses import dataclass
from vllm.v1.sample.thinking_budget_state import (
ThinkingBudgetStateHolder,
)
@dataclass
class FakeReasoningConfig:
reasoning_start_token_ids: list[int]
reasoning_end_token_ids: list[int]
enabled: bool = True
cfg = FakeReasoningConfig(
reasoning_start_token_ids=[TestThinkingBudgetNaturalEndReentry.THINK_START],
reasoning_end_token_ids=end_token_ids,
cfg = create_mock_reasoning_config(
[TestThinkingBudgetNaturalEndReentry.THINK_START], end_token_ids
)
return ThinkingBudgetStateHolder(
reasoning_config=cfg,
@@ -1830,21 +1823,11 @@ class TestThinkingBudgetNaturalEndReentry:
natural </think> exit, continue_thinking is cleared and Block 2
enforcement works correctly.
"""
from dataclasses import dataclass
from unittest.mock import MagicMock
from vllm.v1.sample.thinking_budget_state import ThinkingBudgetStateHolder
@dataclass
class FakeReasoningConfig:
reasoning_start_token_ids: list[int]
reasoning_end_token_ids: list[int]
enabled: bool = True
cfg = FakeReasoningConfig(
reasoning_start_token_ids=[self.THINK_START],
reasoning_end_token_ids=self.THINK_END_SINGLE,
)
cfg = create_mock_reasoning_config([self.THINK_START], self.THINK_END_SINGLE)
holder = ThinkingBudgetStateHolder(
reasoning_config=cfg,
max_num_seqs=8,
+10 -6
View File
@@ -57,15 +57,20 @@ prompts = [
class DummyLogitsProcessor(LogitsProcessor):
"""Fake logit processor to support unit testing and examples."""
@classmethod
def validate_params(cls, params: SamplingParams):
target_token: int | None = params.extra_args and params.extra_args.get(
"target_token"
@staticmethod
def _get_target_token(params: SamplingParams) -> int | None:
target_token = (
params.extra_args.get(DUMMY_LOGITPROC_ARG) if params.extra_args else None
)
if target_token is not None and not isinstance(target_token, int):
raise VLLMValidationError(
f"target_token value {target_token} {type(target_token)} is not int"
)
return target_token
@classmethod
def validate_params(cls, params: SamplingParams):
cls._get_target_token(params)
def __init__(
self, vllm_config: "VllmConfig", device: torch.device, is_pin_memory: bool
@@ -78,8 +83,7 @@ class DummyLogitsProcessor(LogitsProcessor):
def update_state(self, batch_update: BatchUpdate | None):
def extract_extra_arg(params: SamplingParams) -> int | None:
self.validate_params(params)
return params.extra_args and params.extra_args.get("target_token")
return self._get_target_token(params)
process_dict_updates(
self.req_info,
@@ -271,3 +271,49 @@ def test_prometheus_logger_default_buckets():
assert found[metric_name] == [float(b) for b in expected], metric_name
finally:
unregister_vllm_metrics()
def test_histogram_buckets_override_precedence():
"""A present family key wins verbatim; absent keys keep defaults."""
overrides = {
"request_latency": [0.5, 1.0],
"request_tokens": [16.0, 4096.0],
}
got = histogram_buckets("request_latency", overrides=overrides)
assert got == [0.5, 1.0]
assert got is not overrides["request_latency"]
# An override replaces the max_model_len-derived series entirely.
assert histogram_buckets("request_tokens", overrides=overrides) == [
16.0,
4096.0,
]
assert (
histogram_buckets("time_to_first_token", overrides=overrides)
== DEFAULT_BUCKET_SNAPSHOTS["time_to_first_token"]
)
def test_prometheus_logger_applies_overrides():
"""Every family must honour an override, with a distinct list each.
Overriding all of them at once is what catches a histogram wired to the
defaults instead of the override, and a family wired to the wrong list.
"""
overridden: dict[str, list[float]] = {
family: [index + 1.0, index + 2.0]
for index, family in enumerate(sorted(BUCKET_FAMILY_KEYS))
}
config = build_logger_config(
ObservabilityConfig(
kv_cache_metrics=True,
custom_histogram_buckets=overridden,
)
)
try:
PrometheusStatLogger(config)
found = collect_histogram_buckets()
assert set(found) == set(METRIC_FAMILIES)
for metric_name, family in METRIC_FAMILIES.items():
assert found[metric_name] == overridden[family], metric_name
finally:
unregister_vllm_metrics()
@@ -341,6 +341,7 @@ def test_batch_allowed_needs_one_shared_set():
assert states.batch_allowed([]) is None
shared = states.batch_allowed([0])
assert shared is not None
assert shared.tolist() == [1, 2, 3]
assert shared.dtype == torch.int64
assert states.batch_allowed([0, 0]) is shared
@@ -34,6 +34,8 @@ def test_stats_match_reference(vocab: int, dtype: torch.dtype):
)
assert torch.equal(argmax, ref_argmax)
torch.testing.assert_close(entropy, ref_entropy, atol=2e-3, rtol=1e-3)
assert probs is not None
assert ref_probs is not None
torch.testing.assert_close(probs.float(), ref_probs.float(), atol=5e-3, rtol=2e-2)
assert probs.dtype == torch.bfloat16
assert probs.shape == logits.shape
@@ -100,6 +102,7 @@ def test_masked_logits_keep_a_finite_entropy():
assert entropy[0].item() < 1e-6 and entropy[1].item() < 1e-6
assert abs(entropy[2].item() - math.log(2.0)) < 1e-4
assert torch.equal(argmax[[0, 1, 3]], torch.tensor([3, 3, 3], device="cuda"))
assert probs is not None
assert probs[0, 3].item() == 1.0 and probs[0].sum().item() == 1.0
_, _, ref_entropy, _ = sample_row_stats_reference(logits, temps, 1, None)
assert torch.isfinite(ref_entropy).all()
File diff suppressed because it is too large Load Diff
+21 -7
View File
@@ -16,6 +16,7 @@ from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.vocab_parallel_embedding import (
ParallelLMHead,
UnquantizedEmbeddingMethod,
VocabParallelEmbedding,
)
@@ -32,10 +33,17 @@ class _FakeLmHead:
self.tp_size = 1
def _fake_lm_head(
weight: torch.Tensor, quantized: bool = False, shard_indices: object | None = None
) -> VocabParallelEmbedding:
# The dtype tests only need the projection fields, not distributed setup.
return _FakeLmHead(weight, quantized, shard_indices) # type: ignore[return-value]
def _build_processor(vocab_size: int) -> LogitsProcessor:
lp = LogitsProcessor(vocab_size)
# The TP gather is orthogonal to the dtype behavior under test.
lp._gather_logits = lambda logits: logits
lp._gather_logits = lambda logits: logits # type: ignore[method-assign]
return lp
@@ -47,8 +55,9 @@ def test_fp32_head_runs_projection_in_fp32(default_vllm_config):
hidden_states = torch.randn(num_tokens, hidden_size, dtype=torch.bfloat16)
weight = torch.randn(vocab_size, hidden_size, dtype=torch.bfloat16)
logits = lp._get_logits(hidden_states, _FakeLmHead(weight), None)
logits = lp._get_logits(hidden_states, _fake_lm_head(weight), None)
assert logits is not None
assert logits.dtype == torch.float32
assert torch.isfinite(logits).all()
expected = torch.nn.functional.linear(hidden_states.float(), weight.float())
@@ -66,8 +75,9 @@ def test_non_fp32_head_dtype_uses_cast_path(default_vllm_config):
hidden_states = torch.randn(4, hidden_size, dtype=torch.bfloat16)
weight = torch.randn(vocab_size, hidden_size, dtype=torch.bfloat16)
logits = lp._get_logits(hidden_states, _FakeLmHead(weight), None)
logits = lp._get_logits(hidden_states, _fake_lm_head(weight), None)
assert logits is not None
assert logits.dtype == torch.float16
expected = torch.nn.functional.linear(hidden_states.half(), weight.half())
torch.testing.assert_close(logits, expected)
@@ -82,7 +92,7 @@ def test_head_dtype_equal_to_model_dtype_uses_quant_method(default_vllm_config):
hidden_states = torch.randn(4, hidden_size, dtype=torch.bfloat16)
weight = torch.randn(vocab_size, hidden_size, dtype=torch.bfloat16)
lm_head = _FakeLmHead(weight)
lm_head = _fake_lm_head(weight)
with mock.patch.object(
lm_head.quant_method,
@@ -94,6 +104,7 @@ def test_head_dtype_equal_to_model_dtype_uses_quant_method(default_vllm_config):
logits = lp._get_logits(hidden_states, lm_head, None)
apply_mock.assert_called_once()
assert logits is not None
assert logits.dtype == torch.bfloat16
@@ -120,9 +131,10 @@ def test_fp32_head_uses_mm_fast_path_on_device(default_vllm_config):
with mock.patch(
"vllm.model_executor.layers.logits_processor.F.linear"
) as linear_mock:
logits = lp._get_logits(hidden_states, _FakeLmHead(weight), None)
logits = lp._get_logits(hidden_states, _fake_lm_head(weight), None)
linear_mock.assert_not_called()
assert logits is not None
assert logits.dtype == torch.float32
expected = torch.nn.functional.linear(hidden_states.float(), weight.float())
torch.testing.assert_close(logits, expected)
@@ -131,7 +143,7 @@ def test_fp32_head_uses_mm_fast_path_on_device(default_vllm_config):
def test_fp32_head_rejects_quantized_lm_head(default_vllm_config):
lp = _build_processor(64)
lp.head_dtype = torch.float32
lm_head = _FakeLmHead(torch.randn(64, 16, dtype=torch.bfloat16), quantized=True)
lm_head = _fake_lm_head(torch.randn(64, 16, dtype=torch.bfloat16), quantized=True)
with pytest.raises(ValueError, match="unquantized"):
lp._get_logits(torch.randn(4, 16, dtype=torch.bfloat16), lm_head, None)
@@ -197,7 +209,7 @@ def test_get_top_tokens_honors_head_dtype(default_vllm_config):
hidden_states = torch.randn(4, hidden_size, dtype=torch.bfloat16)
weight = torch.randn(vocab_size, hidden_size, dtype=torch.bfloat16)
lm_head = _FakeLmHead(
lm_head = _fake_lm_head(
weight,
shard_indices=types.SimpleNamespace(
num_org_vocab_padding=0, org_vocab_start_index=0
@@ -236,7 +248,9 @@ def test_fp32_head_e2e_no_nan():
for output in outputs:
for completion in output.outputs:
assert completion.logprobs is not None
for token_id, position in zip(completion.token_ids, completion.logprobs):
assert position is not None
# The sampled token survived filtering, so its logprob is finite.
assert math.isfinite(position[token_id].logprob)
# No returned logprob is NaN.
+30 -14
View File
@@ -24,6 +24,7 @@ from vllm import SamplingParams
from vllm.config.model import LogprobsMode
from vllm.distributed import cleanup_dist_env_and_memory
from vllm.exceptions import VLLMValidationError
from vllm.logprobs import Logprob
from vllm.platforms import current_platform
from vllm.v1.engine.input_processor import InputProcessor
@@ -145,7 +146,7 @@ def _repeat_logprob_config(
def _run_and_validate(
vllm_model: VllmRunner,
test_prompts: list[str],
vllm_sampling_params: SamplingParams,
vllm_sampling_params: SamplingParams | list[SamplingParams],
hf_logprobs: list[list[torch.Tensor]],
hf_outputs: list[tuple[list[int], str]],
logprob_prompt_logprob_list: BatchLogprobsSpecType,
@@ -163,11 +164,12 @@ def _run_and_validate(
# Extract request-level (prompt)logprobs config
num_top_logprobs, num_top_prompt_logprobs = logprob_prompt_logprob
assert vllm_result.prompt_token_ids is not None
# Test whether sampled token output is consistent between vLLM and HF
# vLLM prompt+completion should match HF output
if temperature == 0.0:
assert (
vllm_result.prompt_token_ids + vllm_result.outputs[0].token_ids
vllm_result.prompt_token_ids + list(vllm_result.outputs[0].token_ids)
== hf_output[0]
)
else:
@@ -191,7 +193,9 @@ def _run_and_validate(
# Confirm that the output token appears among the logprobs
assert token_id in logprobs
token_in_topk = logprobs[token_id].rank <= num_top_logprobs
rank = logprobs[token_id].rank
assert rank is not None
token_in_topk = rank <= num_top_logprobs
# If the output token is not included in the top K
# logprob, it can return 1 more data
@@ -207,8 +211,10 @@ def _run_and_validate(
output_text = vllm_result.outputs[0].text
output_string_from_most_likely_tokens_lst: list[str] = []
for top_logprobs in vllm_result.outputs[0].logprobs:
top_logprob = next(iter(top_logprobs.values()))
for output_logprobs in vllm_result.outputs[0].logprobs:
assert output_logprobs is not None
top_logprob = next(iter(output_logprobs.values()))
assert top_logprob.decoded_token is not None
output_string_from_most_likely_tokens_lst.append(
top_logprob.decoded_token
)
@@ -226,8 +232,9 @@ def _run_and_validate(
# Compare vLLM sample logprobs to HF
vllm_sample_logprobs = vllm_result.outputs[0].logprobs
for i, top_logprobs in enumerate(vllm_sample_logprobs):
for token_id, sample_logprob in top_logprobs.items():
for i, sample_logprobs in enumerate(vllm_sample_logprobs):
assert sample_logprobs is not None
for token_id, sample_logprob in sample_logprobs.items():
if temperature == 0.0 or i == 0:
logprob = sample_logprob.logprob
torch.testing.assert_close(
@@ -271,9 +278,9 @@ def _run_and_validate(
# Confirm that the prompt token appears among the logprobs
assert prompt_token_id in prompt_logprobs
token_in_topk = (
prompt_logprobs[prompt_token_id].rank <= num_top_prompt_logprobs
)
prompt_rank = prompt_logprobs[prompt_token_id].rank
assert prompt_rank is not None
token_in_topk = prompt_rank <= num_top_prompt_logprobs
# If the prompt token is not included in the top K
# logprob, it can return 1 more data
@@ -294,9 +301,10 @@ def _run_and_validate(
# 1:.
vllm_prompt_logprobs = vllm_result.prompt_logprobs[1:]
for i, vllm_prompt_logprob_dict in enumerate(vllm_prompt_logprobs):
for token_id, logprob in vllm_prompt_logprob_dict.items():
assert vllm_prompt_logprob_dict is not None
for token_id, prompt_lp in vllm_prompt_logprob_dict.items():
torch.testing.assert_close(
logprob.logprob,
prompt_lp.logprob,
hf_logprob[0][i][token_id].item(),
atol=2e-2,
rtol=2e-2,
@@ -607,7 +615,9 @@ def test_logprobs_mode(logprobs_mode: LogprobsMode):
total_token_with_logprobs = 0
positive_values = 0
for output in results[0].outputs:
assert output.logprobs is not None
for logprobs in output.logprobs:
assert logprobs is not None
for token_id in logprobs:
logprob = logprobs[token_id]
if logprobs_mode in ("raw_logprobs", "processed_logprobs"):
@@ -648,6 +658,7 @@ def test_prompt_logprobs_mode():
)
assert results[0].prompt_logprobs is not None
assert results[0].prompt_logprobs[1] is not None
assert results[0].prompt_token_ids is not None
tok_id = results[0].prompt_token_ids[1]
values[mode] = results[0].prompt_logprobs[1][tok_id].logprob
finally:
@@ -1228,10 +1239,12 @@ def test_spec_decode_logprobs(
[prompt, prompt], [sampling_params, penalty_sampling_params]
)
# Collect logprobs outputs from reference LLM.
ref_logprobs = []
ref_logprobs: list[Logprob] = []
for results in ref_results:
for output in results.outputs:
assert output.logprobs is not None
for logprobs in output.logprobs:
assert logprobs is not None
ref_logprobs.extend(logprobs.values())
del ref_llm
torch.accelerator.empty_cache()
@@ -1249,10 +1262,12 @@ def test_spec_decode_logprobs(
[prompt, prompt], [sampling_params, penalty_sampling_params]
)
# Collect logprobs outputs from spec decode LLM.
spec_logprobs = []
spec_logprobs: list[Logprob] = []
for results in spec_results:
for output in results.outputs:
assert output.logprobs is not None
for logprobs in output.logprobs:
assert logprobs is not None
spec_logprobs.extend(logprobs.values())
del spec_llm
torch.accelerator.empty_cache()
@@ -1326,6 +1341,7 @@ def test_prompt_logprobs_with_chunking_and_preemption():
"Unexpected number of prompt logprob positions"
)
assert sampling_params.prompt_logprobs is not None
# Each position should have the requested number of logprobs
for pos, logprobs_dict in enumerate(prompt_logprobs):
if logprobs_dict is not None: # First token may be None
+1
View File
@@ -333,6 +333,7 @@ def test_sampler_repetition_penalty(
for batch_idx in range(batch_size):
non_penalized_token_id = logits[batch_idx].argmax().item()
penalized_token_id = logits[batch_idx].argmin().item()
assert sampling_metadata.prompt_token_ids is not None
prompt_tokens = sampling_metadata.prompt_token_ids[batch_idx][:].tolist()
output_tokens = sampling_metadata.output_token_ids[batch_idx]
if repetition_penalty > 1.0:
@@ -4,6 +4,7 @@
import torch
from tests.v1.sample.utils import create_mock_reasoning_config
from vllm.sampling_params import SamplingParams
from vllm.v1.sample.logits_processor.interface import (
BatchUpdate,
@@ -12,14 +13,9 @@ from vllm.v1.sample.logits_processor.interface import (
from vllm.v1.sample.thinking_budget_state import ThinkingBudgetStateHolder
class _MockReasoningConfig:
reasoning_start_token_ids = [151667]
reasoning_end_token_ids = [151668]
def _make_holder() -> ThinkingBudgetStateHolder:
return ThinkingBudgetStateHolder(
_MockReasoningConfig(),
create_mock_reasoning_config([151667], [151668]),
8,
0,
torch.device("cpu"),
+2 -1
View File
@@ -104,7 +104,8 @@ def test_trace_decode_token_ids_rejects_speculative_decoding():
params = SamplingParams(trace_decode_token_ids=[1])
with pytest.raises(ValueError, match="not supported with speculative decoding"):
params._validate_trace_replay(
_make_model_config(vocab_size=100), speculative_config=object()
_make_model_config(vocab_size=100),
speculative_config=object(),
)
+17 -1
View File
@@ -4,16 +4,28 @@
from collections.abc import Iterator
from enum import Enum
from typing import NamedTuple
from unittest.mock import MagicMock
import regex as re
import torch
from vllm import CompletionOutput
from vllm.config import ReasoningConfig
from vllm.utils.torch_utils import make_tensor_with_pad
from vllm.v1.sample.logits_processor import BatchUpdate, LogitsProcessor
from vllm.v1.sample.metadata import SamplingMetadata
def create_mock_reasoning_config(
start_token_ids: list[int], end_token_ids: list[int]
) -> ReasoningConfig:
return MagicMock(
spec=ReasoningConfig,
reasoning_start_token_ids=start_token_ids,
reasoning_end_token_ids=end_token_ids,
)
class BatchLogprobsComposition(Enum):
"""Types of logprobs configs to include in test batch."""
@@ -141,7 +153,11 @@ def compute_correct_cumulative_logprob(completion_output: CompletionOutput) -> f
token_ids = completion_output.token_ids
logprobs = completion_output.logprobs
assert logprobs is not None
return sum([lp[tok_id].logprob for tok_id, lp in zip(token_ids, logprobs)])
values: list[float] = []
for tok_id, lp in zip(token_ids, logprobs):
assert lp is not None
values.append(lp[tok_id].logprob)
return sum(values)
def create_fake_logits(batch_size: int, vocab_size: int) -> torch.Tensor:
@@ -55,6 +55,7 @@ def _flush_gpu_cache(llm: LLM, sampling_params: SamplingParams, seed: int = 0):
block_size = cache_config.block_size
# Use 1.2x GPU capacity to give the lazy cursor enough scheduling steps
# to walk past all target blocks near the tail of the free queue.
assert num_gpu_blocks is not None
total_tokens_needed = int(num_gpu_blocks * block_size * 1.5)
# Use token-id prompts so each filler is unique (no prefix sharing).
+5 -1
View File
@@ -260,6 +260,7 @@ def test_block_stored_per_group_metadata_full_attention() -> None:
)
assert ev.block_hashes == [expected_hash_0]
assert ev.parent_block_hash is None
assert req.prompt_token_ids is not None
assert ev.token_ids == req.prompt_token_ids[0:BLOCK_SIZE]
# Second block's parent_block_hash equals the first block's hash.
@@ -296,7 +297,7 @@ def test_eager_store_lora_metadata() -> None:
f"expected lora_name='test-lora', got {ev.lora_name!r}"
)
assert ev.extra_keys is not None, "expected extra_keys for lora request"
assert any("test-lora" in keys for keys in ev.extra_keys), (
assert any(keys is not None and "test-lora" in keys for keys in ev.extra_keys), (
f"expected 'test-lora' in extra_keys, got {ev.extra_keys}"
)
assert len(ev.token_ids) == BLOCK_SIZE
@@ -372,6 +373,7 @@ def test_finished_eager_store_emits_all_storage_events() -> None:
secondary_event_hash = maybe_convert_block_hash(get_block_hash(secondary_hash))
by_hash = {event.block_hashes[0]: event for event in stored}
assert set(by_hash) == {*primary_event_hashes, secondary_event_hash}
assert req.prompt_token_ids is not None
assert (
by_hash[primary_event_hashes[0]].token_ids == req.prompt_token_ids[:BLOCK_SIZE]
)
@@ -451,6 +453,7 @@ def test_secondary_hash_block_stored_metadata() -> None:
by_hash = {event.block_hashes[0]: event for event in stored}
assert set(by_hash) == {primary_event_hash, secondary_event_hash}
assert by_hash[primary_event_hash].block_size == BLOCK_SIZE
assert req.prompt_token_ids is not None
assert by_hash[primary_event_hash].token_ids == req.prompt_token_ids[:BLOCK_SIZE]
assert by_hash[secondary_event_hash].block_size == BLOCK_SIZE // 2
assert (
@@ -752,6 +755,7 @@ def test_mamba_align_skips_positional_event_metadata() -> None:
stored = [e for e in events if isinstance(e, BlockStored)]
assert len(stored) == 2
assert {ev.group_idx for ev in stored} == {0}
assert req.prompt_token_ids is not None
for idx, ev in enumerate(stored):
assert ev.block_size == vbs
assert ev.token_ids == req.prompt_token_ids[idx * vbs : (idx + 1) * vbs]
+6 -54
View File
@@ -19,6 +19,7 @@ from vllm.config import (
SchedulerConfig,
VllmConfig,
)
from vllm.config.cache import MambaCacheMode
from vllm.config.kv_events import KVEventsConfig
from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
SimpleCPUOffloadConnector,
@@ -1243,7 +1244,7 @@ def test_preemption_no_cpu_block_leak() -> None:
block_hasher=req._block_hasher,
)
hit_tokens, is_async = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens > 0
assert hit_tokens is not None and hit_tokens > 0
gpu_blocks2 = fix.gpu_block_pool.get_new_blocks(num_blocks)
kv_blocks2 = KVCacheBlocks(blocks=(gpu_blocks2,))
@@ -1338,7 +1339,7 @@ def test_inflight_finish_deferred_cleanup() -> None:
block_hasher=req._block_hasher,
)
hit_tokens, _ = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens > 0
assert hit_tokens is not None and hit_tokens > 0
gpu_blocks2 = fix.gpu_block_pool.get_new_blocks(num_blocks)
kv_blocks2 = KVCacheBlocks(blocks=(gpu_blocks2,))
@@ -1896,7 +1897,7 @@ def test_reset_pending_loads() -> None:
block_hasher=req._block_hasher,
)
hit_tokens, is_async = sched.get_num_new_matched_tokens(req2, num_computed_tokens=0)
assert hit_tokens > 0
assert hit_tokens is not None and hit_tokens > 0
gpu_blocks2 = gpu_pool.get_new_blocks(num_blocks)
kv_blocks2 = KVCacheBlocks(blocks=(gpu_blocks2,))
@@ -2246,7 +2247,7 @@ def _make_hybrid_attention_mamba_scheduler(
hash_block_size: int | None = None,
dcp_world_size: int = 4,
lazy: bool = False,
mamba_cache_mode: str = "align",
mamba_cache_mode: MambaCacheMode = "align",
enable_kv_cache_events: bool = False,
) -> SchedulerFixture:
"""Build a scheduler for one attention group plus one Mamba group."""
@@ -2334,7 +2335,7 @@ def test_hybrid_store_uses_resolved_group_block_sizes() -> None:
# of the hash block, so it cannot exceed the smallest of them.
hash_block_size=BLOCK_SIZE,
dcp_world_size=dcp_world_size,
mamba_cache_mode="all",
mamba_cache_mode="none",
)
sched = fix.scheduler
gpu_pool = fix.gpu_block_pool
@@ -2746,55 +2747,6 @@ def test_eager_store_does_not_scan_mamba_blocks_positionally() -> None:
assert sched._reqs_to_store[req.request_id].num_stored_blocks == [2, 0]
def test_eager_store_scans_mamba_all_blocks_positionally() -> None:
"""Mamba all-mode retains positional identity and needs no handoff."""
block_size = 4 * BLOCK_SIZE
fix = _make_hybrid_attention_mamba_scheduler(
num_cpu_blocks=16,
num_gpu_blocks=24,
block_size=block_size,
mamba_cache_mode="all",
)
sched = fix.scheduler
gpu_pool = fix.gpu_block_pool
attention_manager, mamba_manager = sched.cpu_coordinator.single_type_managers
assert attention_manager.has_positionally_stable_blocks
assert mamba_manager.has_positionally_stable_blocks
req = _make_cp_request(num_blocks=2, virtual_block_size=block_size)
attention_blocks = _allocate_cp_gpu_blocks(
gpu_pool, req, 2, virtual_block_size=block_size, group_id=0
)
mamba_blocks = _allocate_cp_gpu_blocks(
gpu_pool, req, 2, virtual_block_size=block_size, group_id=1
)
kv_blocks = KVCacheBlocks(blocks=(attention_blocks, mamba_blocks))
sched.update_state_after_alloc(req, kv_blocks, num_external_tokens=0)
# build_connector_meta runs before the scheduler commits this step's
# tokens, so the positional scan picks the blocks up on the next step.
first = sched.build_connector_meta(
make_scheduler_output(
{req.request_id: 2 * block_size},
new_reqs={req.request_id: kv_blocks.get_block_ids()},
)
)
assert first.store_gpu_blocks == []
req.num_computed_tokens = 2 * block_size
meta = sched.build_connector_meta(
make_scheduler_output(
{req.request_id: 1},
cached_req_new_blocks={req.request_id: None},
)
)
assert set(meta.store_gpu_blocks) == {
*(block.block_id for block in attention_blocks),
*(block.block_id for block in mamba_blocks),
}
assert sched._reqs_to_store[req.request_id].num_stored_blocks == [2, 2]
@pytest.mark.parametrize("gone_via", ["preempted", "finished", "unregistered"])
def test_boundary_handoff_dropped_for_departing_request(gone_via: str) -> None:
"""Handoffs for a request leaving this step must not be read.
+23 -16
View File
@@ -36,6 +36,7 @@ from vllm.v1.core.kv_cache_utils import (
)
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheLayout,
KVCacheSpec,
@@ -50,7 +51,10 @@ from vllm.v1.simple_kv_offload.cuda_mem_ops import (
build_params,
)
from vllm.v1.simple_kv_offload.disk_backend import DiskBackend
from vllm.v1.simple_kv_offload.metadata import SimpleCPUOffloadMetadata
from vllm.v1.simple_kv_offload.metadata import (
SimpleCPUOffloadMetadata,
SimpleCPUOffloadWorkerMetadata,
)
from vllm.v1.simple_kv_offload.worker import SimpleCPUOffloadWorker
from vllm.v1.worker.gpu.kv_connector import ActiveKVConnector
from vllm.v1.worker.kv_connector_model_runner_mixin import KVConnectorModelRunnerMixin
@@ -64,6 +68,12 @@ ITERS = 30
SLEEP_CYCLES = 50_000_000
def _make_worker(
kv_cache_config: KVCacheConfig | None, cpu_capacity_bytes: int
) -> SimpleCPUOffloadWorker:
return SimpleCPUOffloadWorker(None, kv_cache_config, cpu_capacity_bytes)
def _make_backend() -> tuple[DmaCopyBackend, torch.Tensor, torch.Tensor]:
gpu = {"k": torch.zeros((NUM_BLOCKS, BLOCK_BYTES), dtype=torch.int8, device="cuda")}
cpu = {
@@ -87,7 +97,7 @@ def _make_backend() -> tuple[DmaCopyBackend, torch.Tensor, torch.Tensor]:
def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
"""A finished request's final store must drain without another model step."""
backend, gpu, cpu = _make_backend()
worker = SimpleCPUOffloadWorker(None, None, cpu_capacity_bytes=0)
worker = _make_worker(None, 0)
worker._backend = backend
connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
connector.worker_handler = worker
@@ -105,7 +115,7 @@ def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
active = ActiveKVConnector.__new__(ActiveKVConnector)
active.kv_connector = connector
active._disabled = False
active._pending_load_start = False
active._pending_load_kwargs = None
module = "vllm.v1.worker.gpu.kv_connector"
monkeypatch.setattr(f"{module}.is_forward_context_available", lambda: True)
monkeypatch.setattr(f"{module}.get_forward_context", lambda: None)
@@ -123,6 +133,7 @@ def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
completion = connector.build_connector_worker_meta()
time.sleep(0.001)
assert completion is not None, "CPU store never completed on the empty step"
assert isinstance(completion, SimpleCPUOffloadWorkerMetadata)
assert completion.completed_store_events == {0: 1}
assert torch.equal(cpu[0], gpu[0].cpu())
finally:
@@ -132,7 +143,7 @@ def test_no_forward_step_completes_cpu_store(monkeypatch, use_v2):
def test_deferred_store_waits_for_draft_forward(monkeypatch):
"""Target completion must not submit the store before draft finalization."""
backend, gpu, cpu = _make_backend()
worker = SimpleCPUOffloadWorker(None, None, cpu_capacity_bytes=0)
worker = _make_worker(None, 0)
worker._backend = backend
connector = SimpleCPUOffloadConnector.__new__(SimpleCPUOffloadConnector)
connector.worker_handler = worker
@@ -267,8 +278,9 @@ class _RecordingBackend:
def test_transfer_hooks_pass_wait_event_for_store_only():
"""wait_for_save gates stores on a compute-done event; start_load_kv does not."""
worker = SimpleCPUOffloadWorker(
vllm_config=None, kv_cache_config=None, cpu_capacity_bytes=0
worker = _make_worker(
kv_cache_config=None,
cpu_capacity_bytes=0,
)
recording = _RecordingBackend()
worker._backend = recording
@@ -332,8 +344,7 @@ def test_register_shared_kv_cache_storage(monkeypatch, layout: KVCacheLayout):
)
],
)
worker = SimpleCPUOffloadWorker(
vllm_config=None,
worker = _make_worker(
kv_cache_config=cache_config,
cpu_capacity_bytes=raw.nbytes,
)
@@ -366,8 +377,7 @@ def test_register_kv_cache_storage_with_trailing_padding(monkeypatch):
cache_bytes = num_blocks * block_bytes
raw = torch.zeros(4096, dtype=torch.int8, device="cuda")
cache = raw[:cache_bytes].view(num_blocks, block_bytes)
worker = SimpleCPUOffloadWorker(
vllm_config=None,
worker = _make_worker(
kv_cache_config=MagicMock(
num_blocks=num_blocks,
kv_cache_tensors=[
@@ -412,8 +422,7 @@ def test_register_separate_kv_head_groups(monkeypatch):
)
caches = dense_kv_cache_views(raw, spec, num_blocks, num_layers, layout)
layer_names = [f"layer.{i}" for i in range(num_layers)]
worker = SimpleCPUOffloadWorker(
vllm_config=None,
worker = _make_worker(
kv_cache_config=MagicMock(
num_blocks=num_blocks,
kv_cache_tensors=[
@@ -509,8 +518,7 @@ def test_register_mixed_page_sizes_in_one_cache_group(monkeypatch):
assert len(set(pages)) > 1, "the mixed page sizes are what this test covers"
kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
worker = SimpleCPUOffloadWorker(
vllm_config=None,
worker = _make_worker(
kv_cache_config=kv_cache_config,
cpu_capacity_bytes=sum(pages) * num_blocks,
)
@@ -567,8 +575,7 @@ def test_register_mixed_page_sizes_odd_block_counts(monkeypatch, rank_blocks):
assert kv_cache_config.num_blocks == rank_blocks
kv_caches = allocate_kv_cache(kv_cache_config, torch.device("cuda"), layout)
worker = SimpleCPUOffloadWorker(
vllm_config=None,
worker = _make_worker(
kv_cache_config=kv_cache_config,
cpu_capacity_bytes=sum(pages) * rank_blocks,
)
@@ -25,7 +25,7 @@ def make_manager(
num_reqs, num_steps = confidences.shape
manager = AdaptiveVerificationManager.__new__(AdaptiveVerificationManager)
manager.num_speculative_steps = num_steps
manager._stale_confidences = [SimpleNamespace(np=confidences)]
manager._stale_confidences = [SimpleNamespace(np=confidences)] # type: ignore[list-item] # CPU-only confidence buffer.
manager._stale_idx = 0
manager.req_states = SimpleNamespace(
req_id_to_index={"low": 0, "high": 1},
@@ -176,6 +176,7 @@ def test_budget_stops_where_marginal_drafts_stop_paying_for_themselves():
{"low": 3, "high": 3},
{"low": [1, 2], "high": [3, 4]},
)
assert manager._batch_budget is not None
valid_drafts, num_non_draft_tokens, draft_budget = manager._batch_budget
assert draft_budget == 1
@@ -183,14 +184,16 @@ def test_budget_stops_where_marginal_drafts_stop_paying_for_themselves():
assert num_non_draft_tokens == {"low": 1, "high": 1}
def test_profiled_batches_seed_cost_curves_via_consumer():
def test_profiled_batches_seed_cost_curves_via_consumer(monkeypatch):
manager = AdaptiveVerificationManager.__new__(AdaptiveVerificationManager)
manager.req_states = SimpleNamespace(max_num_batched_tokens=4096, max_num_reqs=64)
manager.num_speculative_steps = 7
manager.num_bonus_tokens = 1
curves: dict[str, list[tuple[int, float]]] = {}
manager.set_cost_curves = lambda draft, verify: curves.update(
draft=draft, verify=verify
monkeypatch.setattr(
manager,
"set_cost_curves",
lambda draft, verify: curves.update(draft=draft, verify=verify),
)
timings = [
@@ -258,6 +261,7 @@ def test_budget_caps_at_one_rejection_sampler_chunk():
{"low": 3, "high": 3},
{"low": [1, 2], "high": [3, 4]},
)
assert manager._batch_budget is not None
_, _, draft_budget = manager._batch_budget
assert draft_budget <= 1
@@ -285,6 +289,7 @@ def test_zero_budget_rebuilds_cpu_cu_num_logits():
{"low": 3, "high": 3, "prefill": 40},
{"low": [1, 2], "high": [3, 4]},
)
assert manager._batch_budget is not None
_, _, draft_budget = manager._batch_budget
assert draft_budget == 0
@@ -323,6 +328,7 @@ def test_zero_budget_keeps_one_grammar_row_per_scheduled_draft():
manager.get_num_tokens(
{"low": 3, "high": 3, "prefill": 40}, scheduled_spec_decode_tokens
)
assert manager._batch_budget is not None
assert manager._batch_budget[2] == 0
req_ids = ["low", "high", "prefill"]
+3 -1
View File
@@ -434,7 +434,9 @@ def test_context_kv_uses_quantized_projection_fallback(monkeypatch):
for projection in projections
]
qwen3_dflash.DFlashQwen3Model._build_context_kv_buffers(
model, layers_attn, has_bias=False
model,
layers_attn,
has_bias=False,
)
assert model._fused_kv_weight is None
assert all(not hasattr(projection, "weight") for projection in projections)
@@ -143,7 +143,7 @@ def test_dflash_drafter_window_reserves_bonus_token():
# window = 4, so 96 fits (96 + 4 == 100) but 97 does not (97 + 4 == 101)
assert input_fits_in_drafter(dflash_runner, SimpleNamespace(max_seq_len=96))
assert not input_fits_in_drafter(dflash_runner, SimpleNamespace(max_seq_len=97))
assert not input_fits_in_drafter(dflash_runner, None) # no metadata
assert not input_fits_in_drafter(dflash_runner, None)
# Other drafters don't reserve the bonus token, so 97 fits (97 + 3 == 100).
plain_runner = SimpleNamespace(
@@ -56,6 +56,7 @@ def _make_predictor(vocab_size: int) -> DeepSeekV4MultiTokenPredictor:
):
shared_head = SharedHead(config=config, prefix="shared_head")
assert shared_head.head is not None
generator = torch.Generator().manual_seed(7)
with torch.no_grad():
shared_head.head.weight.normal_(0.0, 0.02, generator=generator)
+4 -4
View File
@@ -25,7 +25,7 @@ def _create_vllm_config_for_dsd(
max_num_seqs: int,
max_spec_tokens: int,
*,
cudagraph_mode: str = "FULL_AND_PIECEWISE",
cudagraph_mode: CUDAGraphMode = CUDAGraphMode.FULL_AND_PIECEWISE,
use_dynamic_sd: bool = True,
num_spec_per_batch_size: list[tuple[int, int, int]] | None = None,
) -> MagicMock:
@@ -199,7 +199,7 @@ def test_dynamic_sd_non_uniform_batch_falls_back_to_piecewise(monkeypatch):
vllm_config = _create_vllm_config_for_dsd(
max_num_seqs=512,
max_spec_tokens=max_spec_tokens,
cudagraph_mode="FULL_AND_PIECEWISE",
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE,
use_dynamic_sd=True,
)
manager = gpu_cudagraph_utils.CudaGraphManager(
@@ -316,7 +316,7 @@ def test_basic_sd_does_not_capture_shorter_full_decode_shapes(monkeypatch):
vllm_config = _create_vllm_config_for_dsd(
max_num_seqs=max_num_seqs,
max_spec_tokens=max_spec_tokens,
cudagraph_mode="FULL_AND_PIECEWISE",
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE,
use_dynamic_sd=False,
)
manager = gpu_cudagraph_utils.CudaGraphManager(
@@ -382,7 +382,7 @@ def test_dynamic_sd_only_captures_scheduled_query_lengths(monkeypatch):
vllm_config = _create_vllm_config_for_dsd(
max_num_seqs=max_num_seqs,
max_spec_tokens=max_spec_tokens,
cudagraph_mode="FULL_AND_PIECEWISE",
cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE,
use_dynamic_sd=True,
num_spec_per_batch_size=num_spec_per_batch_size,
)
+17 -11
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import Literal
from unittest import mock
import numpy as np
@@ -31,6 +32,7 @@ from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.spec_decode.dflash import DFlashProposer
from vllm.v1.spec_decode.draft_model import DraftModelProposer
from vllm.v1.spec_decode.eagle import EagleProposer
from vllm.v1.spec_decode.llm_base_proposer import SpecDecodeBaseProposer
from vllm.v1.spec_decode.metadata import SpecDecodeMetadata
from vllm.v1.worker.gpu_input_batch import CachedRequestState, InputBatch
@@ -46,13 +48,13 @@ DEVICE_TYPE = current_platform.device_type
def _create_proposer(
method: str,
method: Literal["eagle", "eagle3", "draft_model", "dflash"],
num_speculative_tokens: int,
attention_backend: str | None = None,
parallel_drafting: bool = False,
rejection_sample_method: str = "standard",
draft_sample_method: str = "greedy",
) -> EagleProposer:
rejection_sample_method: Literal["standard", "synthetic", "block"] = "standard",
draft_sample_method: Literal["greedy", "probabilistic"] = "greedy",
) -> SpecDecodeBaseProposer:
# Method-dependent setup
if method == "eagle":
target_model_dir = model_dir
@@ -102,9 +104,14 @@ def _create_proposer(
max_model_len=model_config.max_model_len,
is_encoder_decoder=model_config.is_encoder_decoder,
),
attention_config=AttentionConfig(backend=attention_backend),
attention_config=AttentionConfig(
backend=AttentionBackendEnum[attention_backend]
if attention_backend
else None
),
)
proposer: SpecDecodeBaseProposer
if method == "dflash":
proposer = DFlashProposer(vllm_config=vllm_config, device=device)
elif "eagle" in method:
@@ -135,7 +142,7 @@ def test_prepare_next_token_ids():
)
mock_num_scheduled_tokens = {req_id: 0 for req_id in req_ids}
mock_requests = {}
mock_requests: dict[str, CachedRequestState] = {}
for req_id in req_ids:
mock_request = mock.MagicMock(spec=CachedRequestState)
# Each request will have a backup next token id of 10, 20, 30, 40
@@ -948,13 +955,12 @@ def test_propose(method, attn_backend, num_speculative_tokens, monkeypatch):
attn_metadata_builder = attn_metadata_builder_cls(
kv_cache_spec=create_standard_kv_cache_spec(proposer.vllm_config),
layer_names=proposer._draft_attn_layer_names,
layer_names=sorted(proposer._draft_attn_layer_names),
vllm_config=proposer.vllm_config,
device=device,
)
# Mock runner and draft_attn_groups for attention metadata building
proposer.runner = mock.MagicMock()
# Mock draft_attn_groups for attention metadata building.
mock_attn_group = mock.MagicMock()
mock_attn_group.get_metadata_builder.return_value = attn_metadata_builder
mock_attn_group.layer_names = list(proposer._draft_attn_layer_names)
@@ -1054,11 +1060,10 @@ def test_propose_stores_probabilistic_draft_probs(attn_backend, monkeypatch):
)
attn_metadata_builder = attn_metadata_builder_cls(
kv_cache_spec=create_standard_kv_cache_spec(proposer.vllm_config),
layer_names=proposer._draft_attn_layer_names,
layer_names=sorted(proposer._draft_attn_layer_names),
vllm_config=proposer.vllm_config,
device=device,
)
proposer.runner = mock.MagicMock()
mock_attn_group = mock.MagicMock()
mock_attn_group.get_metadata_builder.return_value = attn_metadata_builder
mock_attn_group.layer_names = list(proposer._draft_attn_layer_names)
@@ -1133,6 +1138,7 @@ def test_set_inputs_first_pass_dflash():
num_speculative_tokens = 3
proposer = _create_proposer("dflash", num_speculative_tokens)
assert isinstance(proposer, DFlashProposer)
mask_token_id = proposer.parallel_drafting_token_id
# Setup batch with 3 requests
@@ -93,7 +93,7 @@ def _run_build(
with patch.object(base_speculator, "build_attn_metadata", fake_build_attn_metadata):
EagleSpeculator._build_uniform_attn_metadata(
fake, # type: ignore[arg-type]
fake,
batch_desc=batch_desc,
num_reqs=num_reqs,
num_query_per_req=num_query_per_req,
@@ -146,7 +146,7 @@ def test_prepare_next_token_ids_padded():
mock_input_batch.vocab_size = 100
mock_input_batch.num_tokens_no_spec = np.array([5] * num_requests)
mock_requests = {}
mock_requests: dict[str, CachedRequestState] = {}
for req_id in req_ids:
mock_request = mock.MagicMock(spec=CachedRequestState)
# Each request will have a backup next token id of 10, 20, 30, 40
+29 -11
View File
@@ -11,6 +11,7 @@ from torch import nn
from vllm.config import (
CompilationConfig,
CompilationMode,
DeviceConfig,
LoadConfig,
VllmConfig,
@@ -122,7 +123,7 @@ def test_lilicorr_matches_exported_head(head_width, slots, dtype):
set_current_vllm_config(
VllmConfig(
device_config=DeviceConfig("cuda"),
compilation_config=CompilationConfig(mode=0),
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
)
),
):
@@ -183,7 +184,7 @@ def test_runtime_length_keeps_trained_checkpoint_geometry(monkeypatch):
with set_current_vllm_config(
VllmConfig(
device_config=DeviceConfig("cpu"),
compilation_config=CompilationConfig(mode=0),
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
)
):
for slots in (1, 3):
@@ -268,7 +269,11 @@ def test_candidates_use_global_partition_and_exclude_padding(monkeypatch, tp_siz
)
monkeypatch.setattr(logits_processor, "_topk", lambda x, k: x.topk(k, dim=-1))
ids, values = logits_processor.LogitsProcessor.get_top_k_tokens(
fake, lm_head, torch.empty(2, 1), 2, return_log_probs=True
fake,
lm_head,
torch.empty(2, 1),
2,
return_log_probs=True,
)
expected = torch.cat(valid_shards, -1).log_softmax(-1).topk(2)
torch.testing.assert_close(ids, expected.indices)
@@ -349,22 +354,35 @@ def test_candidate_generation_routes_scores_and_adaptive_inputs(monkeypatch, lil
compute_candidates=lambda h: (candidates, log_probs),
model=SimpleNamespace(lilicorr=score, candidate_selector=score),
)
spec.target_embeddings = lambda ids: ids.float().unsqueeze(-1).expand(*ids.shape, 4)
if lilicorr:
assert isinstance(spec, LiLiCorrSpeculator)
monkeypatch.setattr(
spec,
"target_embeddings",
lambda ids: ids.float().unsqueeze(-1).expand(*ids.shape, 4),
raising=False,
)
spec.anchor_hidden.copy_(torch.arange(12).view(3, 4))
spec.anchor_valid[:2] = True
spec.candidate_sampler.sample = sample
spec._maybe_predict_acceptance = lambda *args: adaptive_inputs.extend(args)
monkeypatch.setattr(spec.candidate_sampler, "sample", sample)
monkeypatch.setattr(
spec, "_maybe_predict_acceptance", lambda *args: adaptive_inputs.extend(args)
)
spec._generate_draft(3, 9, None, None, None)
expected_ids = candidates.view(3, 2, 4)
expected_first = spec.target_embeddings(expected_ids) if lilicorr else expected_ids
expected_first = (
spec.target_embeddings(expected_ids)
if isinstance(spec, LiLiCorrSpeculator)
else expected_ids
)
torch.testing.assert_close(scoring_inputs[0], expected_first)
torch.testing.assert_close(scoring_inputs[1], log_probs.view(3, 2, 4))
torch.testing.assert_close(
scoring_inputs[2], hidden[spec.sample_indices].view(3, 2, 4)
)
if lilicorr:
assert isinstance(spec, LiLiCorrSpeculator)
torch.testing.assert_close(scoring_inputs[3], spec.anchor_hidden)
torch.testing.assert_close(scoring_inputs[4], spec.anchor_valid)
else:
@@ -472,7 +490,7 @@ def test_checkpoint_coverage_rejects_incomplete_or_wrong_heads(
):
from vllm.model_executor.models.lilicorr import LiLiCorr, LiLiCorrForCausalLM
wrapper = LiLiCorrForCausalLM.__new__(LiLiCorrForCausalLM)
wrapper = LiLiCorrForCausalLM.__new__(LiLiCorrForCausalLM) # type: ignore[type-abstract]
nn.Module.__init__(wrapper)
wrapper.model = LiLiCorr.__new__(LiLiCorr)
nn.Module.__init__(wrapper.model)
@@ -480,7 +498,7 @@ def test_checkpoint_coverage_rejects_incomplete_or_wrong_heads(
with set_current_vllm_config(
VllmConfig(
device_config=DeviceConfig("cpu"),
compilation_config=CompilationConfig(mode=0),
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
)
):
wrapper.model.lilicorr = LiLiCorrHead(
@@ -615,7 +633,7 @@ def owned_head_model(monkeypatch):
with set_current_vllm_config(
VllmConfig(
device_config=DeviceConfig("cpu"),
compilation_config=CompilationConfig(mode=0),
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
)
):
model = LiLiCorrForCausalLM(vllm_config=vllm_config)
@@ -720,7 +738,7 @@ def test_quantized_head_calls_methods_without_reading_packed_weights(monkeypatch
with set_current_vllm_config(
VllmConfig(
device_config=DeviceConfig("cpu"),
compilation_config=CompilationConfig(mode=0),
compilation_config=CompilationConfig(mode=CompilationMode.NONE),
)
):
head = LiLiCorrHead(
@@ -16,6 +16,7 @@ from types import SimpleNamespace
import pytest
import vllm.v1.spec_decode.llm_base_proposer as llm_base_proposer
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.spec_decode.eagle import EagleProposer
SCHEDULER_BLOCK_SIZE = 256
@@ -61,10 +62,10 @@ def _make_proposer(
return proposer
def _make_kv_cache_config(layer_names: set[str]) -> SimpleNamespace:
def _make_kv_cache_config(layer_names: set[str]) -> KVCacheConfig:
spec = SimpleNamespace(block_size=SCHEDULER_BLOCK_SIZE)
group = SimpleNamespace(layer_names=list(layer_names), kv_cache_spec=spec)
return SimpleNamespace(kv_cache_groups=[group])
return SimpleNamespace(kv_cache_groups=[group]) # type: ignore[return-value]
def test_block_size_uses_kernel_block_size(monkeypatch: pytest.MonkeyPatch):
@@ -81,7 +82,9 @@ def test_block_size_uses_kernel_block_size(monkeypatch: pytest.MonkeyPatch):
assert proposer.block_size == KERNEL_BLOCK_SIZE
assert proposer.block_size != SCHEDULER_BLOCK_SIZE
# The metadata builder keeps receiving the kernel block size as well.
assert proposer.draft_attn_groups[0].kernel_block_size == KERNEL_BLOCK_SIZE
group = proposer.draft_attn_groups[0]
assert isinstance(group, _FakeAttentionGroup)
assert group.kernel_block_size == KERNEL_BLOCK_SIZE
def test_block_size_falls_back_to_kv_cache_spec(monkeypatch: pytest.MonkeyPatch):
+1 -2
View File
@@ -43,7 +43,7 @@ def test_glm_mtp_defers_lm_head(default_vllm_config):
index_kpool=4,
)
vllm_config = mock.MagicMock()
vllm_config.speculative_config.draft_model_config.hf_config = config
vllm_config.speculative_config.draft_model_config.hf_text_config = config
vllm_config.scheduler_config.max_num_batched_tokens = 4
with (
@@ -220,7 +220,6 @@ def test_mtp_propose(num_speculative_tokens, monkeypatch):
device=device,
)
proposer.runner = mock.MagicMock()
mock_attn_group = mock.MagicMock()
mock_attn_group.get_metadata_builder.return_value = attn_metadata_builder
mock_attn_group.layer_names = list(proposer._draft_attn_layer_names)
@@ -2,6 +2,8 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Backend and engine-reasoner checks that are not manager-flow tests."""
from typing import Literal
import pytest
from transformers import AutoTokenizer
@@ -17,7 +19,9 @@ TOKENIZER = "gpt2"
NUM_SPEC_TOKENS = 4
def _make_manager_and_request(backend: str, prompt_str: str = '{"a": "b"}'):
def _make_manager_and_request(
backend: Literal["xgrammar", "guidance"], prompt_str: str = '{"a": "b"}'
):
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
prompt = tokenizer.encode(prompt_str)
@@ -33,6 +37,7 @@ def _make_manager_and_request(backend: str, prompt_str: str = '{"a": "b"}'):
sampling_params = SamplingParams(
structured_outputs=StructuredOutputsParams(json='{"type": "object"}'),
)
assert sampling_params.structured_outputs is not None
sampling_params.structured_outputs._backend = backend
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
@@ -43,6 +48,7 @@ def _make_manager_and_request(backend: str, prompt_str: str = '{"a": "b"}'):
pooling_params=None,
)
manager.grammar_init(request)
assert request.structured_output_request is not None
while not request.structured_output_request._check_grammar_completion():
continue
@@ -168,7 +168,7 @@ def test_watermarked_bonus_uses_target_key():
watermarker=GumbelWatermarker(key=42, context_width=2),
)
expected = GumbelWatermarker(key=42, context_width=2).sample(
target_logits.unsqueeze(0), contexts[1:], lambda _: None
target_logits.unsqueeze(0), contexts[1:]
)
assert num_sampled.item() == 2
@@ -196,13 +196,189 @@ def test_watermarked_recovery_uses_target_key():
watermarker=GumbelWatermarker(key=42, context_width=2),
)
expected = GumbelWatermarker(key=42, context_width=2).sample(
target_logits.unsqueeze(0), contexts[:1], lambda _: None
target_logits.unsqueeze(0), contexts[:1]
)
assert num_sampled.item() == 1
assert sampled[0, 0] == expected.token_ids[0]
def test_repeated_draft_context_does_not_change_acceptance():
torch.manual_seed(0)
num_trials = 8
# A draft distribution of its own, so the drafts are not accepted outright.
target_logits = torch.randn(64, device="cuda")
draft_logits = torch.randn(64, device="cuda")
inputs = _build_rejection_sample_inputs(
target_logits,
draft_logits,
num_speculative_steps=1,
temperature=1.0,
num_trials=num_trials,
)
expected, expected_num_sampled = rejection_sample(**inputs, num_speculative_steps=1)
sampled, num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=1,
contexts=torch.tensor([[10, 11], [11, 12]], device="cuda").repeat(
num_trials, 1
),
watermarking=torch.ones(num_trials, dtype=torch.bool, device="cuda"),
watermarking_skip_mask=torch.tensor([True, False], device="cuda").repeat(
num_trials
),
watermarker=GumbelWatermarker(key=42, context_width=2),
)
# Some drafts must actually be rejected, or the ordinary-residual branch
# the skip mask selects is never reached.
assert (expected_num_sampled == 1).any()
torch.testing.assert_close(num_sampled, expected_num_sampled, rtol=0, atol=0)
torch.testing.assert_close(sampled[:, :1], expected[:, :1], rtol=0, atol=0)
def test_repeated_context_skip_mask_is_read_per_row_in_a_block():
"""A block of three drafts, accepted at row 0 and rejected at row 1.
The skip mask selects the sampler per row, so the row the target recovers
at decides which key draws the recovery token.
"""
num_speculative_steps = 3
target_logits = torch.tensor([float("-inf"), 0.0, 1.0, 2.0], device="cuda")
draft_logits = torch.tensor([30.0, -30.0, -30.0, -30.0], device="cuda")
inputs = _build_rejection_sample_inputs(
target_logits,
draft_logits,
num_speculative_steps=num_speculative_steps,
temperature=1.0,
num_trials=1,
)
# Row 0 drafts a token the target gives 0.67 and the draft e**-60, so it is
# accepted; row 1 drafts a token the target gives no mass, so it is not.
inputs["draft_sampled"][1] = 3
inputs["draft_sampled"][2] = 0
contexts = torch.tensor(
[[10, 11], [11, 3], [3, 0], [0, 1]], dtype=torch.int64, device="cuda"
)
expected, expected_num_sampled = rejection_sample(
**inputs, num_speculative_steps=num_speculative_steps
)
assert expected_num_sampled.item() == 2
assert expected[0, 0].item() == 3
watermarker = GumbelWatermarker(key=42, context_width=2)
skipped, skipped_num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=num_speculative_steps,
contexts=contexts,
watermarking=torch.tensor([True], device="cuda"),
watermarking_skip_mask=torch.tensor([False, True, False, False], device="cuda"),
watermarker=watermarker,
)
assert skipped_num_sampled.item() == 2
torch.testing.assert_close(skipped[:, :2], expected[:, :2], rtol=0, atol=0)
watermarked, watermarked_num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=num_speculative_steps,
contexts=contexts,
watermarking=torch.tensor([True], device="cuda"),
watermarking_skip_mask=torch.zeros(
num_speculative_steps + 1, dtype=torch.bool, device="cuda"
),
watermarker=watermarker,
)
# The residual equals the target to within e**-60, so the recovery token is
# the target key's draw on the rejected row's context.
recovery = GumbelWatermarker(key=42, context_width=2).sample(
target_logits.unsqueeze(0), contexts[1:2], lambda _: None
)
assert watermarked_num_sampled.item() == 2
assert watermarked[0, 0].item() == 3
assert watermarked[0, 1] == recovery.token_ids[0]
def test_repeated_recovery_context_uses_ordinary_residual_sample():
target_logits = torch.tensor([float("-inf"), 0.0, 1.0, 2.0], device="cuda")
draft_logits = torch.tensor([100.0, -100.0, -100.0, -100.0], device="cuda")
inputs = _build_rejection_sample_inputs(
target_logits,
draft_logits,
num_speculative_steps=1,
temperature=1.0,
num_trials=1,
)
inputs["draft_sampled"][1] = 0
expected, expected_num_sampled = rejection_sample(**inputs, num_speculative_steps=1)
sampled, num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=1,
contexts=torch.tensor([[10, 11], [11, 0]], device="cuda"),
watermarking=torch.tensor([True], device="cuda"),
watermarking_skip_mask=torch.tensor([True, False], device="cuda"),
watermarker=GumbelWatermarker(key=42, context_width=2),
)
torch.testing.assert_close(num_sampled, expected_num_sampled, rtol=0, atol=0)
torch.testing.assert_close(sampled[:, :1], expected[:, :1], rtol=0, atol=0)
def test_repeated_bonus_context_uses_ordinary_target_sample():
target_logits = torch.randn(64, device="cuda")
inputs = _build_rejection_sample_inputs(
target_logits,
target_logits,
num_speculative_steps=1,
temperature=1.0,
num_trials=1,
)
expected, expected_num_sampled = rejection_sample(**inputs, num_speculative_steps=1)
sampled, num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=1,
contexts=torch.tensor([[10, 11], [11, 12]], device="cuda"),
watermarking=torch.tensor([True], device="cuda"),
watermarking_skip_mask=torch.tensor([False, True], device="cuda"),
watermarker=GumbelWatermarker(key=42, context_width=2),
)
torch.testing.assert_close(num_sampled, expected_num_sampled, rtol=0, atol=0)
torch.testing.assert_close(sampled[:, :2], expected[:, :2], rtol=0, atol=0)
def test_repeated_context_does_not_change_unwatermarked_or_greedy_rows():
target_logits = torch.randn(64, device="cuda")
inputs = _build_rejection_sample_inputs(
target_logits,
target_logits,
num_speculative_steps=1,
temperature=1.0,
num_trials=2,
)
inputs["temperature"][1] = 0
expected, expected_num_sampled = rejection_sample(**inputs, num_speculative_steps=1)
sampled, num_sampled = watermarked_rejection_sample(
**inputs,
num_speculative_steps=1,
contexts=torch.tensor([[10, 11], [11, 12], [20, 21], [21, 22]], device="cuda"),
watermarking=torch.tensor([False, True], device="cuda"),
watermarking_skip_mask=torch.ones(4, dtype=torch.bool, device="cuda"),
watermarker=GumbelWatermarker(key=42, context_width=2),
)
torch.testing.assert_close(num_sampled, expected_num_sampled, rtol=0, atol=0)
for row, length in enumerate(num_sampled):
torch.testing.assert_close(
sampled[row, : int(length)], expected[row, : int(length)], rtol=0, atol=0
)
def test_watermarked_recovery_supports_smaller_draft_vocabulary():
target_logits = torch.tensor([float("-inf"), 0.0, 1.0, 2.0, 100.0], device="cuda")
draft_logits = torch.tensor([100.0, -100.0, -100.0, -100.0], device="cuda")
@@ -225,9 +401,7 @@ def test_watermarked_recovery_supports_smaller_draft_vocabulary():
watermarking=torch.tensor([True], device="cuda"),
watermarker=watermarker,
)
expected = watermarker.sample(
target_logits[:4].unsqueeze(0), contexts[:1], lambda _: None
)
expected = watermarker.sample(target_logits[:4].unsqueeze(0), contexts[:1])
assert num_sampled.item() == 1
assert sampled[0, 0] == expected.token_ids[0]
@@ -735,6 +909,7 @@ def test_verify_rejects_unproposed_drafts():
inputs["expanded_idx_mapping"],
inputs["expanded_local_pos"],
None,
draft_sampled,
)
return sampled, num_sampled
@@ -91,7 +91,7 @@ def test_grammar_bitmask_with_specdec():
json='{"type": "object"}',
),
)
sampling_params.structured_outputs._backend = "guidance"
sampling_params.structured_outputs._backend = "guidance" # type: ignore[union-attr]
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
my_req_id = f"my_req_id_{i}"
@@ -107,19 +107,23 @@ def test_grammar_bitmask_with_specdec():
def grammar_bitmask(req: Request, tokens: list[int]) -> None:
structured_output_manager.grammar_bitmask(
requests={req.request_id: req},
structured_output_request_ids={req.request_id: 0},
structured_output_request_ids=[req.request_id],
scheduled_spec_decode_tokens={req.request_id: tokens},
)
# At this point, we rolled-back, so should not be terminated
assert not req.structured_output_request.grammar.is_terminated()
assert req.structured_output_request is not None
grammar = req.structured_output_request.grammar
assert grammar is not None and not isinstance(grammar, Exception)
assert not grammar.is_terminated()
# The grammar might not yet be compiled, so we wait for it
assert request.structured_output_request is not None
while not request.structured_output_request._check_grammar_completion():
continue
assert request.structured_output_request.grammar.accept_tokens(
request.request_id, prompt[:i]
)
grammar = request.structured_output_request.grammar
assert grammar is not None and not isinstance(grammar, Exception)
assert grammar.accept_tokens(request.request_id, prompt[:i])
grammar_bitmask(request, prompt[i:] + [tokenizer.eos_token_id])
grammar_bitmask(
@@ -155,7 +159,7 @@ def test_grammar_init_async_and_sync(async_grammar):
json='{"type": "object"}',
),
)
sampling_params.structured_outputs._backend = "guidance"
sampling_params.structured_outputs._backend = "guidance" # type: ignore[union-attr]
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
request = Request(
@@ -169,6 +173,7 @@ def test_grammar_init_async_and_sync(async_grammar):
# Check the internal _grammar type immediately after init
# Before _check_grammar_completion is called, async mode should have a Future
assert request.structured_output_request is not None
raw_grammar = request.structured_output_request._grammar
if async_grammar:
assert isinstance(raw_grammar, Future), (
@@ -191,7 +196,7 @@ def test_grammar_init_async_and_sync(async_grammar):
# Verify grammar is properly initialized and functional
grammar = request.structured_output_request.grammar
assert grammar is not None
assert grammar is not None and not isinstance(grammar, Exception)
assert not grammar.is_terminated()
# Verify the grammar can accept valid tokens
@@ -13,6 +13,7 @@ from mistral_common.protocol.instruct.tool_calls import Tool, ToolChoiceEnum
from transformers import AutoTokenizer
from vllm.config import StructuredOutputsConfig, VllmConfig
from vllm.config.structured_outputs import StructuredOutputsBackend
from vllm.exceptions import VLLMValidationError
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.tokenizers.mistral import MistralTokenizer
@@ -41,7 +42,9 @@ EBNF_GRAMMAR = 'root ::= "id=" [0-9]+'
def _validate(
grammar: str, backend: str = "xgrammar", tokenizer: object | None = None
grammar: str,
backend: StructuredOutputsBackend = "xgrammar",
tokenizer: object | None = None,
) -> StructuredOutputsParams:
params = SamplingParams(structured_outputs=StructuredOutputsParams(grammar=grammar))
params._validate_structured_outputs(
@@ -10,9 +10,11 @@ from transformers import AutoTokenizer
from vllm.config import DeviceConfig, StructuredOutputsConfig, VllmConfig
from vllm.config.model import ModelConfig
from vllm.config.speculative import SpeculativeConfig
from vllm.config.structured_outputs import StructuredOutputsBackend
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
from vllm.v1.structured_output.backend_outlines import OutlinesGrammar
TOKENIZER = "gpt2"
THINK_END = "\n" # reasoning-end marker (single GPT-2 token)
@@ -84,7 +86,7 @@ def _wait_for_grammar(request: Request) -> None:
def _build_harness(
tokenizer,
backend: str,
backend: StructuredOutputsBackend,
prefix: str = "",
use_reasoner: bool = True,
reasoning_ended: bool | None = None,
@@ -112,7 +114,7 @@ def _build_harness(
structured_outputs=structured_outputs
or StructuredOutputsParams(json=JSON_SCHEMA)
)
sampling_params.structured_outputs._backend = backend
sampling_params.structured_outputs._backend = backend # type: ignore[union-attr]
sampling_params.update_from_generation_config({}, tokenizer.eos_token_id)
prompt_ids = tokenizer.encode(prefix) if prefix else []
@@ -130,9 +132,10 @@ def _build_harness(
structured_req = request.structured_output_request
assert request.prompt_token_ids is not None
assert structured_req is not None
assert structured_req.grammar is not None
grammar = structured_req.grammar
assert grammar is not None and not isinstance(grammar, Exception)
if prompt_ids:
assert structured_req.grammar.accept_tokens(
assert grammar.accept_tokens(
request.request_id,
prompt_ids,
)
@@ -173,7 +176,7 @@ def _run_real_flow(
structured_req = request.structured_output_request
assert structured_req is not None
grammar = structured_req.grammar
assert grammar is not None
assert grammar is not None and not isinstance(grammar, Exception)
assert not grammar.is_terminated()
# `bitmask[i]` is the grammar state after the first `i` scheduled tokens.
# These tests commit the validated prefix, so the matching post-accept
@@ -335,7 +338,7 @@ FLOW_CASES = [
@pytest.mark.parametrize("case", FLOW_CASES)
def test_real_flow(
tokenizer,
backend: str,
backend: StructuredOutputsBackend,
case: FlowCase,
):
if backend == "guidance" and case.xfail_guidance:
@@ -379,7 +382,7 @@ def test_real_flow(
)
def test_initial_constraint_activation(
tokenizer,
backend: str,
backend: StructuredOutputsBackend,
use_reasoner: bool,
reasoning_ended: bool | None,
enable_in_reasoning: bool,
@@ -431,7 +434,7 @@ def test_initial_constraint_activation(
)
def test_regex_flow(
tokenizer,
backend: str,
backend: StructuredOutputsBackend,
raw_drafts: tuple[str, ...],
expected_validated: tuple[str, ...] | None,
expected_row_pattern: str,
@@ -459,7 +462,9 @@ def test_regex_flow(
@pytest.mark.parametrize("backend", REGEX_BACKENDS)
def test_rejected_draft_keeps_later_rows_constrained(tokenizer, backend: str):
def test_rejected_draft_keeps_later_rows_constrained(
tokenizer, backend: StructuredOutputsBackend
):
"""A draft the grammar rejects during bitmask fill must not unconstrain
the remaining rows or the bonus row."""
manager, request = _build_harness(
@@ -492,7 +497,7 @@ def test_outlines_termination(tokenizer):
structured_req = request.structured_output_request
assert structured_req is not None
grammar = structured_req.grammar
assert grammar is not None
assert isinstance(grammar, OutlinesGrammar)
one, eos = _to_token_ids(tokenizer, ("1", EOS))
assert not grammar.accept_tokens(request.request_id, [eos])
@@ -184,4 +184,5 @@ def test_auto_backend_falls_back_on_unsupported_schema(schema, expected_backend)
StructuredOutputsConfig(backend="auto"),
tokenizer=object(),
)
assert params.structured_outputs is not None
assert params.structured_outputs._backend == expected_backend
+67 -3
View File
@@ -13,6 +13,7 @@ from vllm.v1.outputs import (
LogprobsLists,
LogprobsTensors,
ModelRunnerOutput,
SamplingMaskLists,
)
from vllm.v1.sample.ops.topk_topp_sampler import apply_top_k_top_p
from vllm.v1.worker.gpu.sample.output import SamplingMaskTensors
@@ -63,8 +64,6 @@ def test_logprobs_tensors_tolists_with_tensor_boundaries():
def test_sampling_mask_lists_to_nested_list():
from vllm.v1.outputs import SamplingMaskLists
mask = SamplingMaskLists(
token_ids=np.array([10, 11, 12, 20, 21]),
offsets=np.array([0, 3, 5]),
@@ -76,6 +75,22 @@ def test_sampling_mask_lists_to_nested_list():
assert SamplingMaskLists(np.array([7, 9])).to_nested_list() == [[7, 9]]
def test_sampling_mask_lists_slices_multiple_positions_by_request():
masks = SamplingMaskLists(
token_ids=np.array([10, 11, 20, 30, 31, 32, 40]),
offsets=np.array([0, 2, 3, 6, 7]),
cu_num_generated_tokens=[0, 1, 3, 4],
)
single = masks.slice_request(0, 1)
multi = masks.slice_request(1, 2)
assert single.to_nested_list() == [[10, 11]]
assert single.offsets is None
assert multi.to_nested_list() == [[20], [30, 31, 32]]
assert multi.cu_num_generated_tokens is None
@pytest.mark.parametrize("max_num_kept", [512, 20_001])
@pytest.mark.skipif(
current_platform.is_xpu(),
@@ -102,7 +117,10 @@ def test_sampling_mask_tensors_match_finite_support(max_num_kept):
expected[1] = expected[7] = []
tensors = SamplingMaskTensors.from_logits(
logits.to(DEVICE_TYPE), num_sampled_tokens.to(DEVICE_TYPE), max_num_kept
logits.to(DEVICE_TYPE),
torch.arange(len(sizes) + 1, device=DEVICE_TYPE, dtype=torch.int32),
num_sampled_tokens.to(DEVICE_TYPE),
max_num_kept,
)
assert tensors.token_ids.shape[1] == min(max_num_kept, MAX_COMPACT_SUPPORT)
@@ -127,6 +145,7 @@ def test_sampling_mask_matches_processed_top_k_top_p_support():
tensors = SamplingMaskTensors.from_logits(
processed_logits,
cu_num_logits=torch.tensor([0, 1], dtype=torch.int32, device=DEVICE_TYPE),
num_sampled_tokens=torch.tensor([1], device=DEVICE_TYPE),
max_num_kept=3,
)
@@ -135,6 +154,50 @@ def test_sampling_mask_matches_processed_top_k_top_p_support():
assert result.to_nested_list() == [expected_token_ids]
def test_sampling_mask_tensors_uses_request_boundaries():
logits = torch.full((6, 8), -float("inf"), device=DEVICE_TYPE)
logits[0, [1, 3]] = 0
logits[2, [2, 4, 6]] = 0
logits[5, [0, 7]] = 0
counts = torch.tensor([1, 0, 1], device=DEVICE_TYPE, dtype=torch.int32)
tensors = SamplingMaskTensors.from_logits(
logits,
torch.tensor([0, 2, 5, 6], device=DEVICE_TYPE, dtype=torch.int32),
counts,
max_num_kept=3,
)
assert tensors.tolists().to_nested_list() == [[1, 3], [], [0, 7]]
def test_sampling_mask_tensors_multirow_request_layout():
rows_per_request = 4
counts = np.array([1, 2, 4, 0], dtype=np.int32)
logits = torch.full((16, 16), -float("inf"), device=DEVICE_TYPE)
expected = []
for row in [0, 4, 5, 8, 9, 10, 11]:
kept = torch.tensor(
[row % 16, (row + 3) % 16, (row + 7) % 16], device=DEVICE_TYPE
).unique(sorted=True)
logits[row, kept] = 0
expected.append(kept.tolist())
tensors = SamplingMaskTensors.from_logits(
logits,
torch.arange(0, 17, 4, device=DEVICE_TYPE, dtype=torch.int32),
torch.from_numpy(counts).to(DEVICE_TYPE),
max_num_kept=2,
rows_per_request=rows_per_request,
)
result = tensors.to_cpu_nonblocking().tolists(counts)
assert tensors.token_ids.shape == (16, 2)
assert tensors.rows_per_request == rows_per_request
assert result.to_nested_list() == expected
assert result.cu_num_generated_tokens == [0, 1, 3, 7, 7]
def test_sampling_mask_preserves_top_k_boundary_ties():
"""When the kept support is wider than `max_num_kept` (e.g. a top-k
boundary tie keeps more than k logits), the mask must fall back to the
@@ -147,6 +210,7 @@ def test_sampling_mask_preserves_top_k_boundary_ties():
tensors = SamplingMaskTensors.from_logits(
processed_logits,
cu_num_logits=torch.tensor([0, 1], dtype=torch.int32, device=DEVICE_TYPE),
num_sampled_tokens=torch.tensor([1], device=DEVICE_TYPE),
max_num_kept=3,
)
+8 -5
View File
@@ -86,6 +86,9 @@ def test_get_kv_cache_spec_resolves_hisparse_block_size(
get_attn_backend=lambda backend=backend: backend,
)
monkeypatch.setattr(attn_utils, "get_layers_from_vllm_config", lambda *_: layers)
monkeypatch.setattr(
attn_utils_module, "get_hisparse_kv_cache_groups", lambda *_: []
)
config = SimpleNamespace(
attention_config=SimpleNamespace(hisparse_config=object() if enabled else None)
)
@@ -135,7 +138,7 @@ def test_attention_checks_preserve_global_and_target_scoped_support():
_TargetBackend,
["target"],
spec,
0, # type: ignore[arg-type]
0,
)
target_group.metadata_builders = [
_FakeMetadataBuilder(AttentionCGSupport.ALWAYS) # type: ignore[list-item]
@@ -144,7 +147,7 @@ def test_attention_checks_preserve_global_and_target_scoped_support():
_DraftBackend,
["draft"],
spec,
0, # type: ignore[arg-type]
0,
)
draft_group.metadata_builders = [
_FakeMetadataBuilder(AttentionCGSupport.UNIFORM_BATCH) # type: ignore[list-item]
@@ -152,14 +155,14 @@ def test_attention_checks_preserve_global_and_target_scoped_support():
groups = [[target_group, draft_group]]
# The runner-wide execution mode must still honor the drafter's limit.
unfiltered = get_attn_cg_support(groups, None) # type: ignore[arg-type]
unfiltered = get_attn_cg_support(groups, None)
assert unfiltered.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
assert unfiltered.min_cg_attn_backend == "_DraftBackend"
# Adaptive verification validates only the target's varlen graphs.
target_only = get_attn_cg_support(
groups,
None, # type: ignore[arg-type]
None,
checked_layer_names={"target"},
)
assert target_only.min_cg_support == AttentionCGSupport.ALWAYS
@@ -176,7 +179,7 @@ def test_attention_checks_preserve_global_and_target_scoped_support():
draft_group.layer_names.append("target")
target_with_shared_group = get_attn_cg_support(
groups,
None, # type: ignore[arg-type]
None,
checked_layer_names={"target"},
)
assert target_with_shared_group.min_cg_support == AttentionCGSupport.UNIFORM_BATCH
@@ -3,10 +3,15 @@
from types import SimpleNamespace
import pytest
import torch
from vllm.distributed import parallel_state
from vllm.model_executor.models.interfaces import EagleModelMixin
from vllm.model_executor.models.mimo import MiMoModel
from vllm.models.minimax_m3.nvidia import model as minimax_m3
from vllm.sequence import IntermediateTensors
from vllm.v1.worker.gpu.spec_decode.eagle.eagle3_utils import (
reserve_aux_intermediate_tensor_slots,
verify_supports_aux_hidden_states_over_pp,
)
@@ -24,3 +29,153 @@ def test_mimo_does_not_inherit_aux_hidden_state_pp_support():
assert not inner.supports_aux_hidden_states_over_pp
with pytest.raises(ValueError, match="does not support eagle3"):
verify_supports_aux_hidden_states_over_pp(target, "eagle3")
class _PPAuxLayer(torch.nn.Module):
"""Aliases and mutates residual in place like MiniMaxM3DecoderLayer."""
ffn_all_reduce_deferred = False
def __init__(self, index):
super().__init__()
self.index = index
def forward(self, positions, hidden_states, residual):
total = hidden_states if residual is None else hidden_states + residual
residual = hidden_states if residual is None else residual
residual.copy_(total + self.index + 1)
return torch.full_like(hidden_states, 10 * (self.index + 1)), residual
class _PPAuxNorm(torch.nn.Module):
"""Clobbers its inputs so aux taps that alias them would fail."""
def forward(self, hidden_states, residual):
output = hidden_states + residual
hidden_states.fill_(-101)
residual.fill_(-103)
return output, residual
@pytest.fixture
def minimax_pp_stage(monkeypatch):
"""Use the real MiniMax constructor/forward and aux helpers on CPU tensors."""
group = SimpleNamespace(world_size=2, is_first_rank=True, is_last_rank=False)
bounds = [0, 3]
monkeypatch.setattr(minimax_m3, "get_pp_group", lambda: group)
monkeypatch.setattr(parallel_state, "get_pp_group", lambda: group)
monkeypatch.setattr(parallel_state, "model_parallel_is_initialized", lambda: True)
monkeypatch.setattr(
minimax_m3,
"VocabParallelEmbedding",
lambda *args, **kwargs: torch.nn.Identity(),
)
monkeypatch.setattr(
minimax_m3, "MiniMAXGemmaRMSNorm", lambda *args, **kwargs: _PPAuxNorm()
)
monkeypatch.setattr(
minimax_m3,
"MiniMaxM3DecoderLayer",
lambda **kwargs: _PPAuxLayer(int(kwargs["prefix"].rsplit(".", 1)[1])),
)
def make_layers(num_layers, build, prefix):
return (
*bounds,
torch.nn.ModuleList(
build(f"{prefix}.{index}")
if bounds[0] <= index < bounds[1]
else torch.nn.Identity()
for index in range(num_layers)
),
)
monkeypatch.setattr(minimax_m3, "make_layers", make_layers)
def make_stage(start, end, taps, world_size=2):
bounds[:] = [start, end]
group.world_size = world_size
group.is_first_rank = start == 0
group.is_last_rank = end == 6
config = SimpleNamespace(
vocab_size=16, hidden_size=6144, num_hidden_layers=6, rms_norm_eps=1e-6
)
model = minimax_m3.MiniMaxM3Model(
vllm_config=SimpleNamespace(
model_config=SimpleNamespace(hf_text_config=config),
quant_config=None,
speculative_config=None,
use_v2_model_runner=False,
)
)
model._set_aux_hidden_state_layers(taps)
target = SimpleNamespace(
model=model,
make_empty_intermediate_tensors=model.make_empty_intermediate_tensors,
)
reserve_aux_intermediate_tensor_slots(target)
return model, target
return make_stage
# Input 7; _PPAuxLayer i adds 11 * (i + 1) to hidden + residual.
def _expected_aux_value(tap):
return 7 + 11 * tap * (tap + 1) // 2
def _pp_aux_state(value):
return torch.full((2, 6144), float(value), device="cpu")
@pytest.mark.parametrize("taps", [(0, 3, 6), (0, 1, 3), (4, 5, 6)])
def test_minimax_pp2_preserves_ordered_global_aux_taps(minimax_pp_stage, taps):
first, _ = minimax_pp_stage(0, 3, taps)
sent = first(None, None, None, _pp_aux_state(7))
last, target = minimax_pp_stage(3, 6, taps)
reserved = target.make_empty_intermediate_tensors(2, torch.float32, "cpu")
assert set(sent.tensors) == set(reserved.tensors)
result = last(None, None, sent)
assert isinstance(result, tuple)
output, aux = result
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
for hidden, tap in zip(aux, taps, strict=True):
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
def test_minimax_missing_upstream_aux_slot_is_not_silently_dropped(minimax_pp_stage):
model, _ = minimax_pp_stage(3, 6, (0, 3, 6))
incoming = IntermediateTensors(
{
"hidden_states": _pp_aux_state(30),
"residual": _pp_aux_state(43),
"aux_hidden_states_0": _pp_aux_state(7),
}
)
with pytest.raises(RuntimeError, match="Missing aux_hidden_states_1"):
model(None, None, incoming)
@pytest.mark.parametrize("taps", [(), (0, 3, 6)])
def test_minimax_pp1_output_and_aux_taps(minimax_pp_stage, taps):
model, _ = minimax_pp_stage(0, 6, taps, world_size=1)
output = model(None, None, None, _pp_aux_state(7))
if taps:
output, aux = output
for hidden, tap in zip(aux, taps, strict=True):
torch.testing.assert_close(hidden, _pp_aux_state(_expected_aux_value(tap)))
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))
def test_minimax_pp2_without_aux_keeps_hidden_and_residual_transport(minimax_pp_stage):
first, _ = minimax_pp_stage(0, 3, ())
sent = first(None, None, None, _pp_aux_state(7))
assert set(sent.tensors) == {"hidden_states", "residual"}
torch.testing.assert_close(sent["hidden_states"], _pp_aux_state(30))
torch.testing.assert_close(sent["residual"], _pp_aux_state(43))
last, target = minimax_pp_stage(3, 6, ())
assert set(
target.make_empty_intermediate_tensors(12, torch.bfloat16, "cpu").tensors
) == {"hidden_states", "residual"}
output = last(None, None, sent)
torch.testing.assert_close(output, _pp_aux_state(_expected_aux_value(6)))

Some files were not shown because too many files have changed in this diff Show More