Merge branch 'main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-09 17:41:13 +00:00
1122 changed files with 60114 additions and 20956 deletions
@@ -13,7 +13,11 @@ from vllm.model_executor.layers.mamba.linear.minimax_linear_attn import (
)
from vllm.model_executor.layers.mamba.mamba_mixer import MambaMixer
from vllm.model_executor.layers.mamba.mamba_mixer2 import MambaMixer2
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateShapeCalculator
from vllm.model_executor.layers.mamba.short_conv import ShortConv
from vllm.model_executor.models.falcon_h1 import FalconH1ForCausalLM
from vllm.model_executor.models.granitemoehybrid import GraniteMoeHybridForCausalLM
from vllm.model_executor.models.zamba2 import Zamba2ForCausalLM
from vllm.v1.attention.backends.linear_attn import LinearAttentionBackend
from vllm.v1.attention.backends.mamba1_attn import Mamba1AttentionBackend
from vllm.v1.attention.backends.mamba2_attn import Mamba2AttentionBackend
@@ -47,6 +51,45 @@ def test_replayssm_does_not_reserve_speculative_state_blocks(
assert spec.num_speculative_blocks == expected_blocks
@pytest.mark.parametrize(
"model_cls", [FalconH1ForCausalLM, GraniteMoeHybridForCausalLM, Zamba2ForCausalLM]
)
def test_mamba2_config_state_shape_includes_speculative_tokens(model_cls):
"""The config-time shape sizes the padded Mamba page, so it must match
MambaMixer2.get_state_shape, whose conv state grows with spec tokens."""
hf_config = SimpleNamespace(
hidden_size=128,
mamba_expand=2,
mamba_d_ssm=None,
mamba_n_groups=1,
mamba_ngroups=1,
mamba_n_heads=8,
n_mamba_heads=8,
mamba_d_head=32,
mamba_headdim=32,
mamba_d_state=16,
mamba_d_conv=4,
)
vllm_config = SimpleNamespace(
model_config=SimpleNamespace(hf_config=hf_config),
parallel_config=SimpleNamespace(tensor_parallel_size=1),
num_speculative_tokens=2,
)
assert model_cls.get_mamba_state_shape_from_config(
vllm_config
) == MambaStateShapeCalculator.mamba2_state_shape(
tp_world_size=1,
intermediate_size=256,
n_groups=1,
num_heads=8,
head_dim=32,
state_size=16,
conv_kernel=4,
num_spec=2,
)
@pytest.mark.parametrize(
"layer_class, init_kwargs, expected_backend, expected_mamba_type",
[
@@ -302,8 +302,13 @@ def combine_case(
with_image: bool,
replay_starts: list[int] | None = None,
combine_fn=combine_topk_swa_indices,
in_range_topk: bool = False,
):
"""Run combine_topk_swa_indices and return (indices, lens, expected)."""
"""Run combine_topk_swa_indices and return (indices, lens, expected).
``in_range_topk`` draws top-k indices below N, for combiners that drop
out-of-range ones.
"""
device = torch.device("cuda")
num_reqs = len(seq_lens)
replay_starts = replay_starts or [0] * num_reqs
@@ -326,7 +331,11 @@ def combine_case(
M = N + int(gather_lens.max()) + 8
gen = torch.Generator(device="cpu").manual_seed(0)
topk_indices = torch.randint(
0, 4096, (num_tokens, max(topk, 1)), generator=gen, dtype=torch.int32
0,
N if in_range_topk else 4096,
(num_tokens, max(topk, 1)),
generator=gen,
dtype=torch.int32,
).to(device)
topk_indices = topk_indices[:, : max(topk, 1)]
@@ -415,24 +424,26 @@ def test_combine_topk_swa_with_image_spans(cfg):
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
def test_v41_combine_topk_swa_stops_at_replay_start(cfg):
@pytest.mark.parametrize("query_len", [24, 20])
def test_v41_combine_topk_swa_stops_at_replay_start(cfg, query_len):
"""SWA bounded replay: the gathered buffer starts at replay_start, so the
window never indexes below it."""
from vllm.models.deepseek_v41.common.ops.cache_utils import (
combine_topk_swa_indices as combine_v41,
)
# Request 0 replays [16, 40): the windows of its first rows would
# otherwise reach below 16.
# Request 0 replays from 16: a 24-token chunk starts there, a 20-token
# chunk leaves only 4 context tokens above it (fewer than the window).
indices, lens, rows, exp_lens = combine_case(
cfg["compress_ratio"],
cfg["topk"],
seq_lens=[40, 12],
query_lens=[24, 12],
query_lens=[query_len, 12],
spans=[[], []],
with_image=False,
replay_starts=[16, 0],
combine_fn=combine_v41,
in_range_topk=True,
)
assert lens.cpu().tolist() == exp_lens
assert indices.cpu().tolist() == rows
@@ -55,7 +55,6 @@ if not current_platform.is_cuda():
)
from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseTRTLLMBackend,
)
@@ -122,6 +121,7 @@ def _run_sparse_backend_vs_sdpa(
qk_nope_head_dim: int = 128,
v_head_dim: int = 128,
stale_cpu_query_lens: list[int] | None = None,
capture_graph: bool = False,
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Run a sparse-MLA backend with the given per-token indices and compute a
dense per-token SDPA reference over the SAME indices.
@@ -394,9 +394,25 @@ def _run_sparse_backend_vs_sdpa(
metadata.num_actual_tokens, num_heads * v_head_dim, dtype=dtype, device=device
)
with torch.inference_mode():
impl.record_logical_topk_ready()
backend_output = mock_layer.forward_impl(
query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer
)
if capture_graph:
device_boundaries = common_attn_metadata.query_start_loc.clone()
common_attn_metadata.query_start_loc.copy_(
common_attn_metadata.query_start_loc_cpu
)
metadata = builder.build(0, common_attn_metadata)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
impl.record_logical_topk_ready()
backend_output = mock_layer.forward_impl(
query_vllm, kv_c_vllm, k_pe_vllm, kv_cache, metadata, out_buffer
)
common_attn_metadata.query_start_loc.copy_(device_boundaries)
builder.build(0, common_attn_metadata)
graph.replay()
return backend_output, sdpa_reference, causal_reference
@@ -423,22 +439,19 @@ def _skip_if_backend_unavailable(backend_cls, kv_cache_dtype: str, block_size: i
pytest.skip("FlashInferMLASparseTRTLLMBackend requires SM 10.x capability")
def test_flashinfer_sparse_mla_adaptive_varlen_matches_sdpa(
@pytest.mark.parametrize("query_lens", [[1, 7, 3, 5], [1, 7, 8, 0]])
def test_flashinfer_sparse_mla_adaptive_varlen_graph_matches_sdpa(
default_vllm_config,
dist_init,
workspace_init,
query_lens,
):
"""Adaptive request boundaries must drive SM100 sparse index conversion."""
"""Replay uses device boundaries, including empty padding, despite stale CPU."""
backend_cls = FlashInferMLASparseTRTLLMBackend
_skip_if_backend_unavailable(backend_cls, "fp8", 64)
assert (
backend_cls.get_builder_cls().get_cudagraph_support(None, None)
== AttentionCGSupport.ALWAYS
)
device = torch.device(DEVICE_TYPE)
seq_lens = [257, 270, 265, 276]
query_lens = [1, 7, 3, 5]
sparse_indices = _build_dspark_noncausal_indices(
seq_lens,
query_lens,
@@ -459,6 +472,7 @@ def test_flashinfer_sparse_mla_adaptive_varlen_matches_sdpa(
qk_nope_head_dim=192,
v_head_dim=256,
stale_cpu_query_lens=[4, 4, 4, 4],
capture_graph=True,
)
torch.testing.assert_close(
@@ -7,9 +7,9 @@ v_head_dim=256, kv_lora_rank=512 -> head_size 512. These tests pin the
selection contract only (no GPU required):
* ``get_supported_head_sizes`` advertises 512 so the backend is a candidate;
* ``supports_combination`` admits exactly two shapes for 512 -- a quantized
DS-MLA cache format (zero-padded 576/656B envelope) and a rope-free bf16
cache on SM90 -- and rejects everything else;
* ``supports_combination`` admits 512 only for rope-free models on SM90, with
a bf16 cache or an fp8_ds_mla cache (zero RoPE slot), and rejects
everything else;
* adding 512 must NOT reorder the SM100 priority list for bf16, which is why
the bf16 arm is restricted to SM90.
"""
@@ -19,6 +19,7 @@ from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backends.mla.flashmla_sparse import (
QUANTIZED_DS_MLA_CACHE_FORMATS,
@@ -29,7 +30,7 @@ SM90 = DeviceCapability(major=9, minor=0)
SM100 = DeviceCapability(major=10, minor=0)
BF16_CACHE_DTYPES = (None, "auto", "bfloat16", "float16")
QUANTIZED_CACHE_DTYPES = ("fp8_ds_mla", "nvfp4_ds_mla")
NOPE_SM90_CACHE_DTYPES = (*BF16_CACHE_DTYPES, "fp8_ds_mla")
def _supports_combination(head_size, kv_cache_dtype, capability):
@@ -86,34 +87,26 @@ def test_quantized_ds_mla_formats_are_the_envelope_set():
assert frozenset({"fp8_ds_mla", "nvfp4_ds_mla"}) == QUANTIZED_DS_MLA_CACHE_FORMATS
@pytest.mark.parametrize("kv_cache_dtype", QUANTIZED_CACHE_DTYPES)
def test_nope_512_quantized_rejected_here(kv_cache_dtype):
# Quantized DS-MLA NoPE-512 is served by the zero-padded 576/656B
# envelope, wired up in a separate change; this backend must reject it.
reason = _supports_combination(512, kv_cache_dtype, SM90)
assert reason is not None
@pytest.mark.parametrize("kv_cache_dtype", BF16_CACHE_DTYPES)
def test_nope_512_bf16_sm90_rope_free_accepted(kv_cache_dtype, rope_free_model):
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
def test_nope_512_sm90_rope_free_accepted(kv_cache_dtype, rope_free_model):
assert _supports_combination(512, kv_cache_dtype, SM90) is None
@pytest.mark.parametrize("kv_cache_dtype", BF16_CACHE_DTYPES)
def test_nope_512_bf16_sm90_rope_carrying_rejected(kv_cache_dtype, rope_carrying_model):
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
def test_nope_512_sm90_rope_carrying_rejected(kv_cache_dtype, rope_carrying_model):
reason = _supports_combination(512, kv_cache_dtype, SM90)
assert reason is not None and "rope-free" in reason
@pytest.mark.parametrize("kv_cache_dtype", BF16_CACHE_DTYPES)
def test_nope_512_bf16_sm100_rejected(kv_cache_dtype, rope_free_model):
@pytest.mark.parametrize("kv_cache_dtype", NOPE_SM90_CACHE_DTYPES)
def test_nope_512_sm100_rejected(kv_cache_dtype, rope_free_model):
# The SM90 restriction is what keeps the SM100 priority order unchanged.
reason = _supports_combination(512, kv_cache_dtype, SM100)
assert reason is not None
@pytest.mark.parametrize("kv_cache_dtype", ("fp8", "fp8_e4m3"))
def test_nope_512_plain_fp8_rejected(kv_cache_dtype, rope_free_model):
@pytest.mark.parametrize("kv_cache_dtype", ("fp8", "fp8_e4m3", "nvfp4_ds_mla"))
def test_nope_512_other_quantized_rejected(kv_cache_dtype, rope_free_model):
reason = _supports_combination(512, kv_cache_dtype, SM90)
assert reason is not None
@@ -174,3 +167,15 @@ def test_sm100_bf16_512_priority_unchanged(num_heads):
def test_sm100_576_priority_unchanged():
order = _sparse_order("auto", 576, num_heads=32)
assert order[0] == "FLASHMLA_SPARSE", order
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA backends")
def test_sm90_nope_fp8_ds_mla_resolves_to_flashmla():
"""The sparse backends ranked ahead of FLASHMLA_SPARSE for SM90 NoPE-512
reject fp8_ds_mla, so the auto-selector lands on FlashMLA."""
from vllm.v1.attention.backends.registry import AttentionBackendEnum
order = _sparse_order("fp8_ds_mla", 512, num_heads=64, capability=SM90)
for name in order[: order.index("FLASHMLA_SPARSE")]:
backend_cls = AttentionBackendEnum[name].get_class()
assert not backend_cls.supports_kv_cache_dtype("fp8_ds_mla"), name
+199
View File
@@ -0,0 +1,199 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.mamba.gdn import qwen_gdn_linear_attn
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
ChunkGatedDeltaRule,
_resolve_gdn_prefill_backend,
)
from vllm.platforms import current_platform
def _make_config(
*,
backend: str = "aiter_flydsl",
head_k_dim: int | None = 128,
head_v_dim: int | None = 128,
dtype: torch.dtype = torch.bfloat16,
):
return SimpleNamespace(
additional_config={"gdn_prefill_backend": backend},
model_config=SimpleNamespace(
dtype=dtype,
hf_text_config=SimpleNamespace(
linear_key_head_dim=head_k_dim,
linear_value_head_dim=head_v_dim,
),
),
)
def _resolve_on_rocm(config, *, kernels_available: bool = True):
with (
patch.object(
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=True
),
patch.object(
qwen_gdn_linear_attn.rocm_aiter_ops,
"is_gdn_flydsl_prefill_available",
return_value=kernels_available,
),
):
return _resolve_gdn_prefill_backend(config)
@pytest.mark.parametrize(
"head_k_dim,head_v_dim,dtype,expected",
[
(128, 128, torch.bfloat16, "aiter_flydsl"),
(64, 128, torch.bfloat16, "triton"),
(128, 64, torch.bfloat16, "triton"),
(128, 128, torch.float16, "triton"),
],
)
def test_resolve_aiter_flydsl_gdn_prefill_backend(
head_k_dim: int,
head_v_dim: int,
dtype: torch.dtype,
expected: str,
):
config = _make_config(head_k_dim=head_k_dim, head_v_dim=head_v_dim, dtype=dtype)
requested, active = _resolve_on_rocm(config)
assert requested == "aiter_flydsl"
assert active == expected
def test_kda_style_model_cannot_select_flydsl():
"""Kimi K3 KDA reports head dims through linear_attn_config, not these.
Its builder overrides _build_chunk_metadata, which the AITER path skips,
so this pins the reason the two never meet: the resolver turns the model
down before the builder is ever constructed.
"""
config = _make_config(head_k_dim=None, head_v_dim=None)
assert _resolve_on_rocm(config) == ("aiter_flydsl", "triton")
@pytest.mark.parametrize("on_rocm", [True, False], ids=["kernels_missing", "not_rocm"])
def test_explicit_aiter_flydsl_fails_closed(on_rocm: bool):
"""An explicit request that cannot be honoured is a configuration error.
Falling back silently would report the run as healthy while the requested
kernels were never used.
"""
config = _make_config()
if on_rocm:
with pytest.raises(RuntimeError, match="not importable"):
_resolve_on_rocm(config, kernels_available=False)
return
with (
patch.object(
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=False
),
patch.object(
qwen_gdn_linear_attn.current_platform, "is_cuda", return_value=True
),
pytest.raises(RuntimeError, match="aiter_flydsl"),
):
_resolve_gdn_prefill_backend(config)
def _flydsl_prefill_unavailable() -> bool:
return (
not current_platform.is_rocm()
or not rocm_aiter_ops.is_gdn_flydsl_prefill_available()
)
@pytest.mark.skipif(
_flydsl_prefill_unavailable(),
reason="needs ROCm with the AITER FlyDSL GDN prefill kernels installed",
)
@pytest.mark.parametrize(
"state_dtype", [torch.float32, torch.bfloat16], ids=["fp32_state", "bf16_state"]
)
def test_aiter_flydsl_prefill_matches_triton_reference(state_dtype: torch.dtype):
"""Run both prefill paths on device and compare.
The reference is the same AITER entry point with the FlyDSL prepare and K5
kernels switched off, so the only thing that differs between the two calls
is the kernels this backend exists to select. The state dtype follows
--mamba-ssm-cache-dtype, which may be float32 or bfloat16.
"""
from aiter.ops.triton.gated_delta_net import chunk_gated_delta_rule_opt_vk
torch.manual_seed(0)
device = torch.device("cuda")
seq_lens = [70, 130]
total_tokens = sum(seq_lens)
num_k_heads, num_v_heads, head_dim = 2, 4, 128
# use_qk_l2norm_in_kernel=False matches the prefill path, where the model
# has already normalised q and k. Feeding raw normals instead lets the
# delta rule run away to NaN, which says nothing about either kernel.
q = torch.nn.functional.normalize(
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
).to(torch.bfloat16)
k = torch.nn.functional.normalize(
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
).to(torch.bfloat16)
v = torch.randn(
1, total_tokens, num_v_heads, head_dim, dtype=torch.bfloat16, device=device
)
# g is a log-domain decay, so keep it negative or the recurrence diverges
# and the comparison stops saying anything about the kernels.
g = -torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
beta = torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
cu_seqlens = torch.tensor([0, 70, 200], dtype=torch.int32, device=device)
initial_state = torch.randn(
len(seq_lens),
num_v_heads,
head_dim,
head_dim,
device=device,
).to(state_dtype)
shared = {
"q": q,
"k": k,
"v": v,
"g": g,
"beta": beta,
"output_final_state": True,
"cu_seqlens": cu_seqlens,
"use_qk_l2norm_in_kernel": False,
}
reference_out, reference_state = chunk_gated_delta_rule_opt_vk(
initial_state=initial_state.clone(),
state_dtype=state_dtype,
use_chunk_flydsl=False,
use_prepare_flydsl=False,
**shared,
)
flydsl_out, flydsl_state = ChunkGatedDeltaRule.forward_aiter_flydsl(
None,
initial_state=initial_state.clone(),
aiter_prefill_metadata=rocm_aiter_ops.build_gdn_flydsl_prefill_metadata(
seq_lens, cu_seqlens=cu_seqlens
),
**shared,
)
assert flydsl_state.dtype == state_dtype
torch.testing.assert_close(
flydsl_out.float(), reference_out.float(), rtol=2e-2, atol=2e-2
)
torch.testing.assert_close(
flydsl_state.float(), reference_state.float(), rtol=2e-2, atol=2e-2
)
@@ -385,7 +385,7 @@ def test_cudagraph_capture_batch_stays_decode_only():
def _create_checkpoint_builder_and_batch(
num_spec: int, prefix_match_unit: int = 16
num_spec: int, prefix_match_unit: int | None = 16
) -> tuple[GDNAttentionMetadataBuilder, CommonAttentionMetadata, dict]:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B",
@@ -413,6 +413,8 @@ def _create_checkpoint_builder_and_batch(
vllm_config=vllm_config,
device=DEVICE,
)
vllm_config.cache_config.hash_block_size = prefix_match_unit or 64
vllm_config.cache_config.cache_hit_alignment_tokens = prefix_match_unit or 64
batch = BatchSpec(
seq_lens=[65, 100, 100], query_lens=[3 if num_spec else 1, 100, 99]
)
@@ -431,7 +433,9 @@ def _create_checkpoint_builder_and_batch(
@pytest.mark.parametrize("num_spec", [0, 3])
@pytest.mark.parametrize("prefix_match_unit, expected_offset", [(16, 96), (8, 96)])
@pytest.mark.parametrize(
"prefix_match_unit, expected_offset", [(None, 64), (16, 96), (8, 96)]
)
def test_checkpoint_metadata_preserves_non_spec_order(
num_spec, prefix_match_unit, expected_offset
):
@@ -0,0 +1,211 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Which path GDN metadata takes when a decode row carries no draft tokens.
`build_for_cudagraph_capture` derives the draft count from the query length
(`num_decode_draft_tokens = query_len - 1`), so a capture shape of one token
per request describes rows with zero drafts. `GDNAttentionMetadataBuilder`
routes every row with `num_decode_draft_tokens_cpu >= 0` through the
speculative path, zero drafts included: that path is the only one that
applies each row's accepted-token offset to the recurrent state, so a
zero-draft decode row must not fall back to the plain decode path.
"""
import pytest
import torch
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
create_vllm_config,
)
from vllm.config import SpeculativeConfig
from vllm.config.compilation import CUDAGraphMode
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateShapeCalculator
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadataBuilder
from vllm.v1.kv_cache_interface import MambaSpec
BLOCK_SIZE = 16
DEVICE = torch.device("cpu")
NUM_SPEC = 3
def _builder(
use_spec_decode: bool,
mamba_cache_mode: str = "none",
shapes: tuple[tuple[int, ...], ...] = ((16, 64),),
dtypes: tuple[torch.dtype, ...] = (torch.float16,),
) -> GDNAttentionMetadataBuilder:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B",
block_size=BLOCK_SIZE,
)
vllm_config.compilation_config.cudagraph_mode = CUDAGraphMode.FULL_AND_PIECEWISE
vllm_config.speculative_config = (
SpeculativeConfig(method="ngram", num_speculative_tokens=NUM_SPEC)
if use_spec_decode
else None
)
# "none" keeps the block table as-is; the align gather needs columns for
# the speculative blocks, which `_decode_metadata` appends on request.
vllm_config.cache_config.mamba_cache_mode = mamba_cache_mode
mamba_spec = MambaSpec(
block_size=BLOCK_SIZE,
shapes=shapes,
dtypes=dtypes,
num_speculative_blocks=NUM_SPEC,
)
return GDNAttentionMetadataBuilder(
kv_cache_spec=mamba_spec,
layer_names=["layer.0"],
vllm_config=vllm_config,
device=DEVICE,
)
def _capture_metadata(builder, query_len: int, batch_size: int = 2):
"""Metadata as produced during CUDA-graph capture of a decode shape."""
batch = BatchSpec(
seq_lens=[64] * batch_size,
query_lens=[query_len] * batch_size,
)
common = create_common_attn_metadata(batch, BLOCK_SIZE, DEVICE)
return builder.build_for_cudagraph_capture(common)
def _decode_metadata(builder, num_accepted: list[int], seq_len: int = 64):
"""Metadata for a live decode batch where no row was given drafts.
Every row schedules a single token, so `num_decode_draft_tokens_cpu` is all
zeros -- the shape the runner produces once `zero_draft_decode_mask` has
promoted zero-draft decode rows out of the `-1` placeholder.
`num_accepted` is what the previous step accepted (bonus token included,
so one is the minimum), which is what decides the state slot.
"""
batch = BatchSpec(
seq_lens=[seq_len] * len(num_accepted), query_lens=[1] * len(num_accepted)
)
common = create_common_attn_metadata(
batch, BLOCK_SIZE, DEVICE, arange_block_indices=True
)
if builder.vllm_config.cache_config.mamba_cache_mode == "align":
# Align gathers the last 1 + num_speculative_blocks columns starting at
# the request's current block, so the table has to reach past the end of
# the sequence -- at runtime it is sized by max_model_len, while the
# test helper sizes it by seq_len.
rows, cols = common.block_table_tensor.shape
extra = (
torch.arange(
rows * NUM_SPEC, dtype=common.block_table_tensor.dtype, device=DEVICE
).view(rows, NUM_SPEC)
+ rows * cols
)
common.block_table_tensor = torch.cat([common.block_table_tensor, extra], dim=1)
accepted = torch.tensor(num_accepted, dtype=torch.int32, device=DEVICE)
num_decode_draft_tokens_cpu = torch.zeros(len(num_accepted), dtype=torch.int32)
return builder.build(0, common, accepted, num_decode_draft_tokens_cpu)
def test_zero_draft_capture_shape_routes_through_the_speculative_path():
"""The one-token capture shape is what breaks backends whose decode kernels
assume a full num_spec + 1 query window: `num_decode_draft_tokens_cpu =
query_len - 1 = 0` for every row, which is `>= 0` and must still take the
speculative path (not the plain decode path that drops the state offset),
with a state tensor sized for the full window even though every row only
supplies a single query token.
Only `query_len=1` (zero drafts) discriminates this from the plain-decode
path before the fix: for any `query_len > 1`, `num_decode_draft_tokens_cpu`
is already `> 0` and both the pre-fix and post-fix code agree, so this
does not need parametrizing over larger draft counts.
"""
meta = _capture_metadata(_builder(use_spec_decode=True), query_len=1)
assert meta.num_spec_decodes == 2
assert meta.num_decodes == 0
slots = meta.spec_state_indices_tensor
assert slots is not None
# The kernels index columns 0..num_spec of this tensor.
assert slots.shape[1] == NUM_SPEC + 1
assert int(slots.min()) >= 0
query_lens = torch.diff(meta.spec_query_start_loc)
assert torch.all(query_lens == 1)
def test_plain_decode_without_spec_decode_skips_the_speculative_path():
"""Without a speculative config the builder never builds spec metadata,
so a one-token-per-row decode capture takes the plain decode path.
Not a regression check for this patch (this branch is untouched by it),
but it is what keeps the test above from passing vacuously: it would also
pass if the builder routed every row through the speculative path
unconditionally, regardless of whether speculative decoding is even
configured.
"""
meta = _capture_metadata(_builder(use_spec_decode=False), query_len=1)
assert meta.num_spec_decodes == 0
assert meta.num_decodes == 2
@pytest.mark.parametrize(
"mamba_cache_mode, shapes, dtypes",
[
("none", ((16, 64),), (torch.float16,)),
# Kimi-Linear's KDA layers subclass GatedDeltaNetAttention and consume
# this same metadata, and prefix caching (which Kimi enables by
# default) puts the cache in align mode -- so the guarantee has to hold
# for that state shape and mode too.
(
"align",
MambaStateShapeCalculator.kda_state_shape(
tp_world_size=1, num_heads=4, head_dim=32, num_spec=NUM_SPEC
),
(torch.bfloat16, torch.bfloat16),
),
],
ids=["gdn_none", "kimi_kda_align"],
)
def test_zero_draft_batch_still_applies_the_accepted_token_offset(
mamba_cache_mode, shapes, dtypes
):
"""The numeric difference the fix makes, on the batch shape that triggers it.
The recurrent kernels read their state at column `num_accepted_tokens - 1`
of `spec_state_indices_tensor`. Before the fix, a batch in which *every*
speculative row drafted nothing was pushed onto the non-speculative path,
which passes `non_spec_state_indices_tensor` -- always column 0 -- and
drops `num_accepted_tokens` entirely. A row that accepted drafts on the
previous step wrote its fresh state further along, so column 0 is stale.
"""
accepted = [NUM_SPEC, 1]
meta = _decode_metadata(
_builder(
use_spec_decode=True,
mamba_cache_mode=mamba_cache_mode,
shapes=shapes,
dtypes=dtypes,
),
accepted,
)
assert meta.num_spec_decodes == len(accepted)
assert meta.num_decodes == 0
# Dropping these is what silently sent the kernels to the wrong slot.
assert meta.num_accepted_tokens is not None
assert meta.num_accepted_tokens.tolist()[: len(accepted)] == accepted
assert meta.non_spec_state_indices_tensor is None
slots = meta.spec_state_indices_tensor
assert slots is not None
for row, num_accepted in enumerate(accepted):
read = int(slots[row, num_accepted - 1])
fallback = int(slots[row, 0])
# Only the row that accepted a draft moved off column 0; the row that
# accepted nothing but its bonus token legitimately stays there. This
# also confirms the columns are genuinely distinct blocks (via
# `arange_block_indices=True` in `_decode_metadata`), not just
# distinct labels for the same one -- otherwise `read != fallback`
# here would mean nothing.
assert (read != fallback) == (num_accepted > 1)
@@ -122,6 +122,7 @@ def test_indexer_draft_decode_metadata_update_is_capture_safe():
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.dcp_world_size = 1
builder.compress_ratio = 16
builder.kernel_block_size = None
builder.num_sms = num_sms
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
builder.kv_cache_spec = SimpleNamespace(num_states=64)
@@ -140,6 +141,7 @@ def test_indexer_draft_decode_metadata_update_is_capture_safe():
requires_padding=False,
schedule_metadata=schedule_metadata,
),
block_table=block_table,
)
builder.update_draft_decode_metadata(metadata)
@@ -167,6 +169,65 @@ def test_indexer_draft_decode_metadata_update_is_capture_safe():
torch.testing.assert_close(metadata.slot_mapping, expected_slot_mapping)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize(
"block_size,kernel_block_size,compress_ratio", [(64, 64, 1), (256, 64, 4)]
)
def test_indexer_draft_decode_refresh_follows_new_batch(
monkeypatch, block_size, kernel_block_size, compress_ratio
):
"""Without a prior build(), the refresh must not keep the last batch's state."""
monkeypatch.setattr(indexer_module, "has_deep_gemm", lambda: False)
device = torch.device("cuda")
num_reqs, width = 3, 8
factor = block_size // kernel_block_size
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.dcp_world_size = 1
builder.compress_ratio = compress_ratio
builder.kernel_block_size = kernel_block_size
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
builder.kv_cache_spec = SimpleNamespace(block_size=block_size, num_states=64)
def stale(*shape: int) -> torch.Tensor:
return torch.full(shape, -7, dtype=torch.int32, device=device)
decode = DeepSeekV32IndexerDecodeMetadata(
block_table=stale(num_reqs, width // factor),
seq_lens=stale(num_reqs, 1),
decode_lens=stale(num_reqs),
requires_padding=False,
schedule_metadata=stale(1),
indices=stale(num_reqs),
per_req_decode_lens=stale(num_reqs),
)
request_block_table = torch.randint(
0, 1000, (num_reqs, width), dtype=torch.int32, device=device
)
seq_lens = torch.tensor([17, 33, 65], dtype=torch.int32, device=device)
metadata = DeepseekV32IndexerMetadata(
seq_lens=seq_lens,
max_seq_len=128,
slot_mapping=torch.zeros(num_reqs, dtype=torch.int64, device=device),
num_decodes=num_reqs,
num_decode_tokens=num_reqs,
num_prefills=0,
num_prefill_tokens=0,
decode=decode,
block_table=request_block_table,
)
builder.update_draft_decode_metadata(metadata)
expected_block_table = request_block_table[:, ::factor] // factor
torch.testing.assert_close(decode.block_table, expected_block_table)
torch.testing.assert_close(decode.indices, builder.arange_buffer[:num_reqs])
assert torch.all(decode.per_req_decode_lens == 1)
assert torch.all(decode.decode_lens == 1)
expected_seq_lens = torch.div(seq_lens, compress_ratio, rounding_mode="floor")
torch.testing.assert_close(decode.seq_lens.flatten(), expected_seq_lens)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize(
"query_lens", [[1], [0, 257, 1, 0, 3], [6] * 64, [2, 6, 4, 0], [0, 0, 0]]
@@ -315,6 +376,9 @@ def test_compressed_slot_mapping_warmup_includes_index_kpool():
config = SimpleNamespace(
cache_config=SimpleNamespace(block_size=256),
model_config=SimpleNamespace(hf_text_config=SimpleNamespace(index_kpool=32)),
parallel_config=SimpleNamespace(
decode_context_parallel_size=1, cp_kv_cache_interleave_size=1
),
)
keys = CompressedSlotMappingKernel().get_warmup_keys(config)
@@ -343,6 +407,41 @@ def test_compressed_slot_mapping_inherits_padded_token_slots():
assert compressed.tolist() == [-1, -1, -1, -1, -1, 3 * 4 + 2, -1, 3 * 4 + 3]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_compressed_slot_mapping_dcp_uses_rank_local_state_positions():
"""Under DCP each rank writes only the states it owns, at the state's
rank-local position."""
device = torch.device("cuda")
dcp, interleave, ratio, block_size = 2, 4, 2, 4
num_tokens = 32
query_start_loc = torch.tensor([0, num_tokens], dtype=torch.int32, device=device)
seq_lens = torch.tensor([num_tokens], dtype=torch.int32, device=device)
block_table = torch.tensor([[5, 7]], dtype=torch.int32, device=device)
pos = torch.arange(num_tokens)
for rank in range(dcp):
owned = (pos // interleave) % dcp == rank
slot_mapping = torch.where(owned, 0, -1).to(torch.int64).to(device)
compressed = get_compressed_slot_mapping(
num_tokens,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size=block_size,
compress_ratio=ratio,
dcp_world_size=dcp,
cp_interleave=interleave,
)
local_pos = pos // (interleave * dcp) * interleave + pos % interleave
state = local_pos // ratio
expected = torch.where(
owned & ((pos + 1) % ratio == 0),
block_table[0].cpu()[state // block_size] * block_size + state % block_size,
-1,
)
assert compressed.tolist() == expected.tolist()
def test_index_conversion_warmup_uses_physical_block_stride():
config = SimpleNamespace(
cache_config=SimpleNamespace(block_size=64),
@@ -370,6 +469,8 @@ def test_zero_token_pcp_rank_participates_in_compressed_mapping_gather(monkeypat
builder.use_pcp = True
builder.pcp_world_size = 4
builder.pcp_rank = 0
builder.dcp_world_size = 1
builder.cp_kv_cache_interleave_size = 1
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)
@@ -383,8 +484,11 @@ def test_zero_token_pcp_rank_participates_in_compressed_mapping_gather(monkeypat
block_size,
compress_ratio,
out,
dcp_world_size,
cp_interleave,
):
assert num_tokens == 0
assert dcp_world_size == 1
assert block_size == 64
assert compress_ratio == 4
out.fill_(-1)
@@ -0,0 +1,135 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU tests for storage-block kernel-block selection in prepare_kernel_block_sizes."""
from types import SimpleNamespace
import pytest
import torch
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.models.glm5next.common.attention import Glm5NextIndexerCache
from vllm.v1.attention.backend import AttentionBackend, MultipleOf
from vllm.v1.attention.backends.mla import indexer as indexer_mod
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerBackend,
KpoolTailBackend,
)
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
ROCMAiterMLASparseBackend,
)
from vllm.v1.kv_cache_interface import MLAAttentionSpec
from vllm.v1.worker.utils import prepare_kernel_block_sizes
pytestmark = pytest.mark.cpu_test
# ``index_kpool`` of zai-org/GLM-5.3-Flash: one indexer state pools 4
# compressed states (hence storage_block_size = page * 4).
INDEX_KPOOL = 4
# The hybrid KDA/mamba manager floors at TP8..TP1; 640 is the geometry of the
# original report ("the 640-token block table").
TP_FLOOR_MANAGER_BLOCKS = [640, 1152, 2176, 4352]
def _mock_rocm_platform(monkeypatch: pytest.MonkeyPatch) -> None:
# Platform predicates are mutually exclusive in production. Override both
# so these ROCm policy tests do not inherit CUDA capabilities from the CI
# host running them (same approach as test_deepseek_v4_rocm_adaptive).
monkeypatch.setattr(indexer_mod.current_platform, "is_cuda", lambda: False)
monkeypatch.setattr(indexer_mod.current_platform, "is_rocm", lambda: True)
def _kpool_storage_spec(manager_block: int) -> MLAAttentionSpec:
"""Real Glm5NextIndexerCache spec for the given cache block size."""
with set_current_vllm_config(VllmConfig()):
cache = Glm5NextIndexerCache(
head_dim=128,
dtype=torch.bfloat16,
prefix="model.layers.0.indexer.k_cache_probe",
cache_config=SimpleNamespace(block_size=manager_block),
index_kpool=INDEX_KPOOL,
)
spec = cache.get_kv_cache_spec(VllmConfig())
assert isinstance(spec, MLAAttentionSpec)
return spec
def _prepare(
spec: MLAAttentionSpec, backends: list[type[AttentionBackend]]
) -> list[int]:
kv_cache_config = SimpleNamespace(
kv_cache_groups=[SimpleNamespace(kv_cache_spec=spec)]
)
attn_groups = [[SimpleNamespace(backend=backend) for backend in backends]]
return prepare_kernel_block_sizes(kv_cache_config, attn_groups)
@pytest.mark.parametrize("manager_block", TP_FLOOR_MANAGER_BLOCKS)
def test_prepare_uses_storage_block_for_the_kpool_group(
monkeypatch: pytest.MonkeyPatch, manager_block: int
):
"""The bug: on ROCm, kpool groups must get 128/256 - not the 640-4352
manager block - as their kernel block size.
Manager-granular selection is what made the block table address manager
blocks while the kpool writer and the index-cache gather read pool pages,
aliasing every cache column past the request's row.
"""
_mock_rocm_platform(monkeypatch)
spec = _kpool_storage_spec(manager_block)
expected_storage = 256 if manager_block % 256 == 0 else 128
assert spec.storage_block_size == expected_storage
selected = _prepare(
spec,
[ROCMAiterMLASparseBackend, DeepseekV32IndexerBackend, KpoolTailBackend],
)
assert selected == [expected_storage]
assert selected != [manager_block]
# The hybrid block-table split stays integral.
assert manager_block % selected[0] == 0
def test_prepare_falls_back_when_storage_block_is_not_supported():
"""No storage block, or a storage block the backends reject (e.g. the
CUDA indexer's exact ``[64]`` vs a 128-token storage block): selection is
`select_common_block_size`'s answer, unchanged from no-fix behavior.
"""
class Fixed64Backend:
@staticmethod
def get_supported_kernel_block_sizes():
return [64]
@staticmethod
def get_name() -> str:
return "FIXED64"
# Storage block the group's backend does not accept -> backend vote (64).
spec = _kpool_storage_spec(640)
assert spec.storage_block_size == 128
assert _prepare(spec, [Fixed64Backend]) == [64]
# No storage block at all (any non-kpool MLA model) -> backend vote.
plain_spec = MLAAttentionSpec(
block_size=640,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
)
assert plain_spec.storage_block_size is None
assert _prepare(plain_spec, [Fixed64Backend]) == [64]
# ...and with backends that accept the manager block, the manager wins,
# exactly as on main.
class AcceptAllBackend:
@staticmethod
def get_supported_kernel_block_sizes():
return [MultipleOf(1)]
@staticmethod
def get_name() -> str:
return "ACCEPTALL"
assert _prepare(plain_spec, [AcceptAllBackend]) == [640]
@@ -227,8 +227,10 @@ def test_circular_mapping_matches_generic_for_short_requests(prompt_len):
def test_circular_mapping_preserves_padding_and_empty_batch():
own_blocks = [5, 9]
per_req = [list(range(10)), list(range(12))]
# The last request is a padding request on the null block, which owns no
# tail block and must never be written.
own_blocks = [5, 9, 0]
per_req = [list(range(10)), list(range(12)), [0, 1]]
padded_len = sum(len(p) for p in per_req) + 8
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(
per_req, padded_len=padded_len
@@ -237,7 +239,8 @@ def test_circular_mapping_preserves_padding_and_empty_batch():
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
assert out.shape == slot_mapping.shape
assert torch.equal(out[num_actual:], torch.full_like(out[num_actual:], -1))
pad_start = int(qsl[-2])
assert torch.equal(out[pad_start:], torch.full_like(out[pad_start:], -1))
empty = circular_tail_slots(slot_mapping, bt, qsl, positions[:0], 0, num_reqs)
assert torch.equal(empty, slot_mapping)
@@ -430,25 +433,27 @@ def test_interleaved_decode_pollution_legacy_vs_circular():
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
@pytest.mark.parametrize(
"per_req,num_actual,padded_len",
"per_req,own_blocks,num_actual,padded_len",
[
([list(range(10)), list(range(12))], 22, 22),
([list(range(10)), list(range(12))], 22, 30),
([[3, 4], [0], [7, 8, 9]], 6, 8),
([[5]], 1, 1),
([list(range(10)), list(range(12))], [5, 6], 22, 22),
([list(range(10)), list(range(12))], [5, 6], 22, 30),
([[3, 4], [0], [7, 8, 9]], [5, 0, 7], 6, 8),
([[5]], [5], 1, 1),
([[0], [0]], [0, 0], 2, 4), # dummy run: every row on the null block
],
)
def test_triton_mapping_matches_cpu(per_req, num_actual, padded_len):
def test_triton_mapping_matches_cpu(per_req, own_blocks, num_actual, padded_len):
"""The CUDA (Triton) path must match the CPU torch reference, including
tokens between the last request boundary and num_actual_tokens (mapped to
the last request) and untouched padding beyond num_actual."""
the last request), untouched padding beyond num_actual, and PAD for
requests on the null block."""
positions, qsl, slot_mapping, _, num_reqs = make_batch(
per_req, padded_len=padded_len
)
# Replace the all--1 placeholder slots with sentinel values to check the
# padding range is copied through untouched.
slot_mapping = torch.arange(padded_len, dtype=torch.int64) + 1000
bt = make_tail_block_table(list(range(5, 5 + num_reqs)))
bt = make_tail_block_table(own_blocks)
ref = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
got = circular_tail_slots(
@@ -460,6 +465,9 @@ def test_triton_mapping_matches_cpu(per_req, num_actual, padded_len):
num_reqs,
)
torch.testing.assert_close(got.cpu(), ref)
for req, blk in enumerate(own_blocks):
if blk == 0:
assert (got[int(qsl[req]) : int(qsl[req + 1])] == -1).all()
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
@@ -0,0 +1,168 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Internal prefill checkpoints for Mamba2 align-mode prefix caching."""
import torch
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
create_vllm_config,
)
from vllm.v1.attention.backends.mamba2_attn import (
Mamba2AttentionMetadataBuilder,
)
from vllm.v1.attention.backends.mamba_attn import BaseMambaAttentionMetadataBuilder
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.kv_cache_interface import MambaSpec
compute_chunk_metadata = BaseMambaAttentionMetadataBuilder._compute_chunk_metadata
def test_no_checkpoint_offsets_preserves_legacy_chunking():
"""Passing no offsets must reproduce the pre-feature chunk layout."""
num_computed = torch.tensor([0, 300])
qsl = torch.tensor([0, 700, 1000])
cu, seq_idx, last, ckpt = compute_chunk_metadata(256, 2, num_computed, qsl)
# Row 0: 700 fresh tokens from sequence position 0 -> 256, 256, 188.
# Row 1: 300 new tokens resuming at 300. 300 % 256 == 44, so it finishes
# its partial chunk with 256 - 44 == 212 tokens, then 88.
assert cu == [0, 256, 512, 700, 912, 1000]
assert seq_idx == [0, 0, 0, 1, 1]
assert last == [2, 4]
assert ckpt == [-1, -1]
def test_chunking_realigns_to_the_grid_after_a_checkpoint():
"""After the forced break, chunks resume breaking on chunk_size.
100 -> then 156 to reach the 256 grid, then full chunks. Without the
realignment the second chunk would span 100..356 and cross a boundary.
"""
num_computed = torch.tensor([0])
qsl = torch.tensor([0, 700])
cu, _, _, _ = compute_chunk_metadata(
256, 1, num_computed, qsl, checkpoint_offsets_p=[100]
)
assert cu == [0, 100, 256, 512, 700]
def test_checkpoint_on_a_resumed_request_is_relative_to_the_query():
"""Offsets count from the query start, not the sequence start."""
num_computed = torch.tensor([300])
qsl = torch.tensor([0, 500])
cu, _, _, ckpt = compute_chunk_metadata(
256, 1, num_computed, qsl, checkpoint_offsets_p=[212]
)
# Row resumes at sequence position 300. 300 % 256 == 44, so the partial
# chunk is 212 tokens and already ends exactly at the checkpoint (query
# offset 212 == sequence position 512) — no extra split needed.
assert cu == [0, 212, 468, 500]
assert ckpt == [0]
MAMBA_BLOCK_SIZE = 256
CHUNK_SIZE = 256
DEVICE = torch.device("cpu")
def _create_mamba2_builder(
mamba_cache_mode: str = "align",
num_prefill_checkpoint_blocks: int = 1,
prefill_checkpoint_alignment: int | None = 1,
) -> Mamba2AttentionMetadataBuilder:
vllm_config = create_vllm_config(
model_name="Qwen/Qwen3.5-0.8B", block_size=MAMBA_BLOCK_SIZE
)
vllm_config.cache_config.mamba_cache_mode = mamba_cache_mode
# get_mamba_chunk_size() reads `mamba_chunk_size` then `chunk_size`.
vllm_config.model_config.hf_text_config.mamba_chunk_size = CHUNK_SIZE
spec = MambaSpec(
block_size=MAMBA_BLOCK_SIZE,
shapes=((16, 64),),
dtypes=(torch.float16,),
mamba_cache_mode=mamba_cache_mode,
num_prefill_checkpoint_blocks=num_prefill_checkpoint_blocks,
prefill_checkpoint_alignment=prefill_checkpoint_alignment,
)
builder = Mamba2AttentionMetadataBuilder(
kv_cache_spec=spec,
layer_names=["layer.0"],
vllm_config=vllm_config,
device=DEVICE,
)
vllm_config.cache_config.hash_block_size = MAMBA_BLOCK_SIZE
vllm_config.cache_config.cache_hit_alignment_tokens = MAMBA_BLOCK_SIZE
return builder
def _build(builder, seq_lens, query_lens):
common = create_common_attn_metadata(
BatchSpec(seq_lens=seq_lens, query_lens=query_lens),
MAMBA_BLOCK_SIZE,
DEVICE,
arange_block_indices=True,
)
# create_common_attn_metadata leaves is_prefilling unset; the builder
# asserts on it. Every row here is a full prefill.
common = common.replace(is_prefilling=torch.ones(len(seq_lens), dtype=torch.bool))
return builder.build(common_prefix_len=0, common_attn_metadata=common)
def test_builder_emits_one_checkpoint_entry_per_prefill_row():
"""Declined rows stay in place, masked, and a chunk ends on the checkpoint."""
builder = _create_mamba2_builder()
# Row 0 (seq_len 900) checkpoints at 768; row 1 (seq_len 100) is too short
# for a checkpoint at all.
meta = _build(builder, seq_lens=[900, 100], query_lens=[900, 100])
assert meta.checkpoint_chunk_idx is not None
assert meta.checkpoint_meta is not None
assert meta.checkpoint_chunk_idx.numel() == 2
# The exporter masks row 1 off by its zero offset and null block, but
# still loads its chunk index first, so the placeholder must be in range.
assert meta.checkpoint_meta.checkpoint_offsets.tolist() == [768, 0]
assert meta.checkpoint_meta.state_indices[1].item() == NULL_BLOCK_ID
assert meta.checkpoint_chunk_idx[1].item() == 0
# The checkpoint's token offset is the end of its chunk. Asserting it here
# also proves the chunk split actually landed on the checkpoint.
ckpt_chunk = meta.checkpoint_chunk_idx[0]
assert meta.cu_chunk_seqlen_p[ckpt_chunk + 1].item() == 768
def test_update_block_table_regathers_checkpoint_blocks():
"""Groups sharing a spec reuse one group's metadata via update_block_table.
Checkpoint destinations are block-table entries, so each group needs its
own: layers of different groups share physical tensors, and reusing the
first group's indices writes every group's checkpoint into its blocks.
"""
builder = _create_mamba2_builder()
meta = _build(builder, seq_lens=[900, 100], query_lens=[900, 100])
assert meta.checkpoint_meta is not None
# A second group's table: same shape as the first, disjoint block ids.
other_table = torch.arange(1000, 1016, dtype=torch.int32).reshape(2, 8)
updated = builder.update_block_table(
meta, other_table, torch.zeros(1000, dtype=torch.int64)
)
# Row 0 checkpoints in column cdiv(900, 256) - 2 == 2; row 1 declined.
assert updated.checkpoint_meta is not None
assert updated.checkpoint_meta.state_indices.tolist() == [
other_table[0, 2].item(),
NULL_BLOCK_ID,
]
def test_builder_emits_nothing_outside_align_mode():
builder = _create_mamba2_builder(mamba_cache_mode="none")
meta = _build(builder, seq_lens=[900], query_lens=[900])
assert meta.checkpoint_chunk_idx is None
+2 -3
View File
@@ -538,10 +538,9 @@ def create_and_prepopulate_kv_cache(
if fp8_attention:
if use_fp8_ds_mla:
kv_lora_rank = kv_c_contexts[0].shape[-1]
rope_dim = k_pe_contexts[0].shape[-1]
# 4 * 4: 4 float32 scale values for 128-element tiles
# 2 * rope_dim: 16-bit RoPE values
kv_entry_size = kv_lora_rank + 4 * 4 + 2 * rope_dim
# 2 * 64: 16-bit RoPE values (zero-filled for NoPE models)
kv_entry_size = kv_lora_rank + 4 * 4 + 2 * 64
elif use_nvfp4_ds_mla:
kv_lora_rank = kv_c_contexts[0].shape[-1]
rope_dim = k_pe_contexts[0].shape[-1]
+121
View File
@@ -19,6 +19,21 @@ class _NonCausalMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
supports_non_causal_multi_token_decode = True
class _CausalOnlyMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
pass
class _DraftMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
"""Triton-like: non-causal decode is supported, DCP draft decode is not."""
supports_non_causal_multi_token_decode = True
class _DcpCapableMLAMetadataBuilder(MLACommonMetadataBuilder[MLACommonMetadata]):
supports_non_causal_multi_token_decode = True
supports_non_causal_multi_token_dcp = True
def _metadata(
query_start_loc: list[int],
num_tokens: int | None = None,
@@ -60,6 +75,54 @@ def _builder(marked: bool = True) -> _NonCausalMLAMetadataBuilder:
return builder
def _mla_layer(*, non_causal: bool = False) -> SimpleNamespace:
return SimpleNamespace(
non_causal_multi_token_decode=non_causal,
q_lora_rank=None,
kv_lora_rank=512,
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
prefill_backend=SimpleNamespace(clone=lambda: None),
)
def _merged_mla_spec() -> MLAAttentionSpec:
return MLAAttentionSpec(
block_size=64,
num_kv_heads=1,
head_size=576,
dtype=torch.bfloat16,
non_causal_multi_token_decode=True,
)
def _dspark_dcp_vllm_config(
static_forward_context: dict[str, SimpleNamespace],
) -> SimpleNamespace:
return SimpleNamespace(
speculative_config=SimpleNamespace(
method="dspark", num_speculative_tokens=None
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=2,
prefill_context_parallel_size=1,
cp_kv_cache_interleave_size=1,
),
compilation_config=SimpleNamespace(
static_forward_context=static_forward_context
),
model_config=SimpleNamespace(
dtype=torch.bfloat16,
max_model_len=128,
get_num_attention_heads=lambda _parallel_config: 16,
),
cache_config=SimpleNamespace(cache_dtype="auto", block_size=64),
scheduler_config=SimpleNamespace(max_num_seqs=1),
attention_config=SimpleNamespace(use_prefill_query_quantization=False),
)
def test_group_capability_keeps_runtime_causality_per_step():
builder = _builder()
@@ -137,3 +200,61 @@ def test_mla_cache_marker_is_promoted_to_group_capability():
[unmarked, unmarked]
).non_causal_multi_token_decode
assert MLAAttentionSpec.merge([unmarked, marked]).non_causal_multi_token_decode
def test_builder_scopes_noncausal_capability_to_its_layers():
merged_spec = _merged_mla_spec()
static_forward_context = {
"target": _mla_layer(non_causal=False),
"draft": _mla_layer(non_causal=True),
# Indexer and compressor caches share an MLA group but predate the flag.
"indexer": SimpleNamespace(),
}
vllm_config = _dspark_dcp_vllm_config(static_forward_context)
device = torch.device("cpu")
def _flag(layer_names: list[str]) -> bool:
return _DcpCapableMLAMetadataBuilder(
merged_spec,
layer_names,
vllm_config,
device,
supports_dcp_with_varlen=True,
).non_causal_multi_token_decode
assert not _flag(["target"])
assert _flag(["draft"])
assert _flag(["target", "draft"])
assert not _flag(["target", "indexer"])
def test_merged_group_spec_does_not_mark_a_target_only_builder():
# Both builders receive the same merged spec; only the draft layer is
# non-causal. Constructing through __init__ would still fail DCP
# validation if the builder read the group flag.
merged_spec = _merged_mla_spec()
static_forward_context = {
"target": _mla_layer(non_causal=False),
"draft": _mla_layer(non_causal=True),
}
vllm_config = _dspark_dcp_vllm_config(static_forward_context)
device = torch.device("cpu")
assert merged_spec.non_causal_multi_token_decode
target = _CausalOnlyMLAMetadataBuilder(
merged_spec,
["target"],
vllm_config,
device,
supports_dcp_with_varlen=True,
)
assert not target.non_causal_multi_token_decode
with pytest.raises(ValueError, match="non-causal draft"):
_DraftMLAMetadataBuilder(
merged_spec,
["draft"],
vllm_config,
device,
supports_dcp_with_varlen=True,
)
+88 -32
View File
@@ -54,10 +54,20 @@ def test_prefill_backend_clone_has_isolated_metadata():
def cleanup_overrides():
"""Clear any overrides after each test."""
yield
for member in MLAPrefillBackendEnum:
for member in list(MLAPrefillBackendEnum):
member.clear_override()
def _remove_dynamic_member(enum_cls, member):
value = member.value
name = member.name
enum_cls._member_map_.pop(name, None)
enum_cls._member_names_.remove(name)
delattr(enum_cls, name)
if enum_cls._value2member_map_.get(value) is member:
del enum_cls._value2member_map_[value]
def test_custom_is_not_alias_of_any_backend():
all_backends = list(MLAPrefillBackendEnum)
@@ -83,21 +93,11 @@ def test_custom_unregistered_raises():
def test_register_custom_backend_with_class_path():
register_mla_prefill_backend(
backend=MLAPrefillBackendEnum.CUSTOM,
class_path=(
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
),
MLAPrefillBackendEnum.CUSTOM,
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
assert MLAPrefillBackendEnum.CUSTOM.is_overridden()
class_path = MLAPrefillBackendEnum.CUSTOM.get_path()
assert class_path == (
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
)
backend_cls = MLAPrefillBackendEnum.CUSTOM.get_class()
assert backend_cls.get_name() == "CUSTOM"
assert MLAPrefillBackendEnum.CUSTOM.get_class().get_name() == "CUSTOM"
def test_register_custom_backend_as_decorator():
@@ -120,33 +120,20 @@ def test_register_custom_backend_as_decorator():
def test_override_existing_backend():
original_path = MLAPrefillBackendEnum.FLASH_ATTN.get_path()
register_mla_prefill_backend(
backend=MLAPrefillBackendEnum.FLASH_ATTN,
class_path=(
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
),
MLAPrefillBackendEnum.FLASH_ATTN,
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
assert MLAPrefillBackendEnum.FLASH_ATTN.get_class().get_name() == "CUSTOM"
assert MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
assert MLAPrefillBackendEnum.FLASH_ATTN.get_path() != original_path
backend_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
assert backend_cls.get_name() == "CUSTOM"
def test_clear_override():
original_path = MLAPrefillBackendEnum.FLASH_ATTN.get_path()
register_mla_prefill_backend(
backend=MLAPrefillBackendEnum.FLASH_ATTN,
class_path=(
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
),
MLAPrefillBackendEnum.FLASH_ATTN,
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
assert MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
MLAPrefillBackendEnum.FLASH_ATTN.clear_override()
assert not MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
assert MLAPrefillBackendEnum.FLASH_ATTN.get_path() == original_path
@@ -172,3 +159,72 @@ def test_rocm_aiter_fa_registered():
# The AITER FA path is the fp16/bf16 generic-varlen prefill path.
assert backend_cls.supports_dtype(torch.bfloat16)
assert backend_cls.supports_dtype(torch.float16)
def test_register_dynamic_member():
p = "tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend"
member = MLAPrefillBackendEnum.register("DYNAMIC_TEST", p)
assert member.name == "DYNAMIC_TEST"
assert member is MLAPrefillBackendEnum["DYNAMIC_TEST"]
_remove_dynamic_member(MLAPrefillBackendEnum, member)
def test_register_dynamic_member_duplicate_raises():
path = "some.module.Class"
MLAPrefillBackendEnum.register("DUP_TEST", path)
with pytest.raises(ValueError, match="already exists"):
MLAPrefillBackendEnum.register("DUP_TEST", "other.module.OtherClass")
_remove_dynamic_member(MLAPrefillBackendEnum, MLAPrefillBackendEnum.DUP_TEST)
class StringDecoratorMLAPrefillBackend(MLAPrefillBackend):
"""Mock backend defined at module level so get_class() can resolve
the auto-generated class path (local classes are not importable)."""
supported_dtypes = [torch.bfloat16]
requires_r1_mla_dimensions = False
@staticmethod
def get_name() -> str:
return "DECORATED"
def run_prefill_new_tokens(self, q, k, v, return_softmax_lse):
raise NotImplementedError
def run_prefill_context_chunk(self, chunk_idx, q, k, v):
raise NotImplementedError
def test_register_mla_prefill_backend_with_string_name_direct():
register_mla_prefill_backend(
"STRING_DIRECT",
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
member = MLAPrefillBackendEnum.STRING_DIRECT
assert member.is_overridden()
assert member.get_class().get_name() == "CUSTOM"
member.clear_override()
_remove_dynamic_member(MLAPrefillBackendEnum, member)
def test_register_mla_prefill_backend_with_string_name_decorator():
# The decorated class must be module-level: the decorator derives a
# class path from it, and get_class() re-imports that path. A class
# defined inside this test would have a non-importable <locals> path.
decorated_cls = StringDecoratorMLAPrefillBackend
result = register_mla_prefill_backend("STRING_DECORATOR")(decorated_cls)
assert result is decorated_cls
member = MLAPrefillBackendEnum.STRING_DECORATOR
assert member.is_overridden()
assert member.get_path() == (
f"{decorated_cls.__module__}.{decorated_cls.__qualname__}"
)
assert member.get_class() is decorated_cls
assert member.get_class().get_name() == "DECORATED"
member.clear_override()
_remove_dynamic_member(MLAPrefillBackendEnum, member)
+200 -111
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for MLA prefill backend selector."""
from contextlib import suppress
from unittest.mock import MagicMock, patch
import pytest
@@ -9,13 +10,12 @@ import torch
from vllm.config import AttentionConfig, ModelConfig, VllmConfig
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.platforms.interface import DeviceCapability, Platform
from vllm.v1.attention.backends.mla.prefill.base import MLADimensions
from vllm.v1.attention.backends.mla.prefill.registry import MLAPrefillBackendEnum
from vllm.v1.attention.backends.mla.prefill.selector import (
MLAPrefillSelectorConfig,
_auto_select_mla_prefill_backend,
_get_mla_prefill_backend_priorities,
get_mla_prefill_backend,
)
@@ -55,51 +55,170 @@ def _make_vllm_config(
return mock_vllm_config
class TestPlatformMLAPrefillHooks:
"""Tests for the Platform.get_mla_prefill_backend_cls hook itself."""
def _get_tried_backends(self, capability, mla_dimensions):
"""Run the default hook, returning the backend order tried."""
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=mla_dimensions,
)
tried: list[MLAPrefillBackendEnum] = []
def mock_get_class(backend_enum):
tried.append(backend_enum)
cls = MagicMock()
cls.validate_configuration.return_value = ["not available"]
return cls
with (
patch.object(Platform, "get_device_capability", return_value=capability),
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
suppress(ValueError),
):
Platform.get_mla_prefill_backend_cls(selector_config)
return tried
def test_priorities_no_capability(self):
tried = self._get_tried_backends(
None,
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
)
assert tried == [MLAPrefillBackendEnum.FLASH_ATTN]
def test_priorities_blackwell_glm_dimensions(self):
tried = self._get_tried_backends(
DeviceCapability(major=10, minor=0),
MLADimensions(qk_nope_head_dim=192, qk_rope_head_dim=64, v_head_dim=256),
)
assert tried == [
MLAPrefillBackendEnum.TRTLLM_RAGGED,
MLAPrefillBackendEnum.FLASH_ATTN,
MLAPrefillBackendEnum.FLASHINFER,
MLAPrefillBackendEnum.TOKENSPEED_MLA,
]
def test_priorities_blackwell_deepseek_dimensions(self):
tried = self._get_tried_backends(
DeviceCapability(major=10, minor=0),
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
)
assert tried == [
MLAPrefillBackendEnum.FLASH_ATTN,
MLAPrefillBackendEnum.TRTLLM_RAGGED,
MLAPrefillBackendEnum.FLASHINFER,
MLAPrefillBackendEnum.TOKENSPEED_MLA,
]
def test_priorities_hopper(self):
tried = self._get_tried_backends(
DeviceCapability(major=9, minor=0),
MLADimensions(qk_nope_head_dim=128, qk_rope_head_dim=64, v_head_dim=128),
)
assert tried == [MLAPrefillBackendEnum.FLASH_ATTN]
def test_skips_import_error_backends(self):
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=192,
qk_rope_head_dim=64,
v_head_dim=256,
),
)
valid = MagicMock()
valid.validate_configuration.return_value = []
def mock_get_class(backend_enum):
if backend_enum is MLAPrefillBackendEnum.FLASH_ATTN:
return valid
raise ImportError("not installed")
with (
patch.object(
Platform,
"get_device_capability",
return_value=DeviceCapability(major=10, minor=0),
),
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
):
selected = Platform.get_mla_prefill_backend_cls(selector_config)
assert selected is valid
def test_all_invalid_raises_error(self):
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
invalid = MagicMock()
invalid.validate_configuration.return_value = ["not available"]
with (
patch.object(
Platform,
"get_device_capability",
return_value=DeviceCapability(major=10, minor=0),
),
patch.object(MLAPrefillBackendEnum, "get_class", return_value=invalid),
pytest.raises(ValueError, match="No valid MLA"),
):
Platform.get_mla_prefill_backend_cls(selector_config)
def test_cpu_platform_returns_fixed_backend(self):
"""CPU backends are returned via the fixed-backend hook."""
try:
cpu_cls = MLAPrefillBackendEnum.CPU.get_class()
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
except ImportError:
pytest.skip("CPU MLA prefill backend not available")
return
from vllm.platforms.cpu import CpuPlatform
expected = zen_cls if zen_cls.is_available() else cpu_cls
assert (
CpuPlatform.get_mla_prefill_backend_cls(
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
)
is expected
)
class TestGetMLAPrefillBackend:
"""Tests for get_mla_prefill_backend (public API)."""
def test_cpu_uses_sdpa_prefill(self):
vllm_config = _make_vllm_config()
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
# A Zen CPU with zentorch selects the Zen backend, so expect whichever
# one this host offers.
expected = (
zen_cls if zen_cls.is_available() else MLAPrefillBackendEnum.CPU.get_class()
)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.is_cpu.return_value = True
backend = get_mla_prefill_backend(vllm_config)
assert backend is expected
def test_zen_cpu_prefers_zentorch_prefill(self):
vllm_config = _make_vllm_config()
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(zen_cls, "is_available", return_value=True),
):
mock_platform.is_cpu.return_value = True
backend = get_mla_prefill_backend(vllm_config)
assert backend is zen_cls
def test_zen_cpu_falls_back_when_zentorch_unavailable(self):
vllm_config = _make_vllm_config()
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(zen_cls, "is_available", return_value=False),
):
mock_platform.is_cpu.return_value = True
mock_platform.get_mla_prefill_backend_cls.return_value = (
MLAPrefillBackendEnum.CPU.get_class()
)
backend = get_mla_prefill_backend(vllm_config)
assert backend is MLAPrefillBackendEnum.CPU.get_class()
def test_zen_cpu_prefers_zentorch_prefill(self):
from vllm.platforms.cpu import CpuPlatform
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
with patch.object(zen_cls, "is_available", return_value=True):
backend = CpuPlatform.get_mla_prefill_backend_cls(
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
)
assert backend is zen_cls
def test_zen_cpu_falls_back_when_zentorch_unavailable(self):
from vllm.platforms.cpu import CpuPlatform
zen_cls = MLAPrefillBackendEnum.ZEN_CPU.get_class()
with patch.object(zen_cls, "is_available", return_value=False):
backend = CpuPlatform.get_mla_prefill_backend_cls(
MLAPrefillSelectorConfig(dtype=torch.bfloat16)
)
assert backend is MLAPrefillBackendEnum.CPU.get_class()
def test_no_device_capability_returns_flash_attn(self):
vllm_config = _make_vllm_config()
@@ -108,16 +227,8 @@ class TestGetMLAPrefillBackend:
def get_name():
return "FLASH_ATTN"
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(
MLAPrefillBackendEnum.FLASH_ATTN,
"get_class",
return_value=FlashAttnBackend,
),
):
mock_platform.get_device_capability.return_value = None
mock_platform.is_cpu.return_value = False
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.get_mla_prefill_backend_cls.return_value = FlashAttnBackend
backend = get_mla_prefill_backend(vllm_config)
assert backend.get_name() == "FLASH_ATTN"
@@ -214,7 +325,7 @@ class TestGetMLAPrefillBackend:
mock_platform.get_device_capability.return_value = DeviceCapability(
major=9, minor=0
)
mock_platform.is_rocm.return_value = False
mock_platform.get_mla_prefill_backend_cls.return_value = flash_attn_cls
backend = get_mla_prefill_backend(vllm_config)
assert backend.get_name() == "FLASH_ATTN"
@@ -224,7 +335,6 @@ class TestAutoSelectMLAPrefillBackend:
"""Tests for fallback and error paths in auto-selection."""
def test_blackwell_glm_dimensions_use_trtllm(self):
capability = DeviceCapability(major=10, minor=0)
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
@@ -235,7 +345,6 @@ class TestAutoSelectMLAPrefillBackend:
)
try:
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
trtllm_cls = MLAPrefillBackendEnum.TRTLLM_RAGGED.get_class()
except ImportError:
pytest.skip("MLA prefill backend not available")
@@ -243,19 +352,13 @@ class TestAutoSelectMLAPrefillBackend:
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(flash_attn_cls, "is_available", return_value=True),
patch.object(trtllm_cls, "validate_configuration", return_value=[]),
):
# Force the non-ROCm priority on the Blackwell.
mock_platform.is_rocm.return_value = False
backend = _auto_select_mla_prefill_backend(
capability,
selector_config,
)
mock_platform.get_mla_prefill_backend_cls.return_value = trtllm_cls
backend = _auto_select_mla_prefill_backend(selector_config)
assert backend.get_name() == "TRTLLM_RAGGED"
def test_all_fail_raises_error(self):
capability = DeviceCapability(major=10, minor=0)
def test_platform_hook_raises_propagates(self):
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
@@ -265,18 +368,14 @@ class TestAutoSelectMLAPrefillBackend:
),
)
def mock_get_class(backend_enum): # noqa: ARG001
cls = MagicMock()
cls.validate_configuration.return_value = ["not available"]
return cls
with patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class):
_auto_select_mla_prefill_backend.cache_clear()
with pytest.raises(ValueError, match="No valid MLA"):
_auto_select_mla_prefill_backend(
capability,
selector_config,
)
with (
patch("vllm.platforms.current_platform") as mock_platform,
pytest.raises(ValueError, match="No valid MLA"),
):
mock_platform.get_mla_prefill_backend_cls.side_effect = ValueError(
"No valid MLA prefill backend found"
)
_auto_select_mla_prefill_backend(selector_config)
class TestBackendValidation:
@@ -391,18 +490,29 @@ class TestROCmAiterFAPrefillSelection:
def test_rocm_priorities_prefer_aiter_fa(self):
"""On ROCm, ROCM_AITER_FA is tried first, FLASH_ATTN as fallback."""
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.is_rocm.return_value = True
priorities = _get_mla_prefill_backend_priorities(
DeviceCapability(major=9, minor=5),
MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
)
from vllm.platforms.rocm import RocmPlatform
assert priorities == [
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
tried: list[MLAPrefillBackendEnum] = []
def mock_get_class(backend_enum):
tried.append(backend_enum)
cls = MagicMock()
cls.validate_configuration.return_value = ["not available"]
return cls
with (
patch.object(
RocmPlatform,
"get_device_capability",
return_value=MagicMock(),
),
patch.object(MLAPrefillBackendEnum, "get_class", mock_get_class),
suppress(ValueError),
):
RocmPlatform.get_mla_prefill_backend_cls(selector_config)
assert tried == [
MLAPrefillBackendEnum.ROCM_AITER_FA,
MLAPrefillBackendEnum.FLASH_ATTN,
]
@@ -459,50 +569,29 @@ class TestROCmAiterFAPrefillSelection:
AiterFlashAttnPrefillBackend,
)
# gfx gating is simulated via the mocked validate_configuration,
# not the capability.
capability = MagicMock()
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(
AiterFlashAttnPrefillBackend,
"validate_configuration",
return_value=[],
),
):
mock_platform.is_rocm.return_value = True
backend = _auto_select_mla_prefill_backend(capability, selector_config)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.get_mla_prefill_backend_cls.return_value = (
AiterFlashAttnPrefillBackend
)
backend = _auto_select_mla_prefill_backend(selector_config)
assert backend.get_name() == "ROCM_AITER_FA"
def test_auto_select_falls_back_to_flash_attn_when_aiter_invalid(self):
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
AiterFlashAttnPrefillBackend,
)
try:
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
except ImportError:
pytest.skip("FLASH_ATTN backend not available")
return
# the fallback is forced by the mocked validate_configuration,
# the fallback is forced by the mocked get_mla_prefill_backend_cls,
# not the capability.
capability = MagicMock()
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(
AiterFlashAttnPrefillBackend,
"validate_configuration",
return_value=["compute capability not supported"],
),
patch.object(flash_attn_cls, "validate_configuration", return_value=[]),
):
mock_platform.is_rocm.return_value = True
backend = _auto_select_mla_prefill_backend(capability, selector_config)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.get_mla_prefill_backend_cls.return_value = flash_attn_cls
backend = _auto_select_mla_prefill_backend(selector_config)
assert backend.get_name() == "FLASH_ATTN"
@@ -11,7 +11,11 @@ routes built; it is marked and skipped when unavailable.
from __future__ import annotations
import sys
from types import SimpleNamespace
import pytest
import torch
rocm_aiter_mla = pytest.importorskip(
"vllm.v1.attention.backends.mla.rocm_aiter_mla",
@@ -26,9 +30,15 @@ NATIVE = rocm_aiter_mla._NATIVE_CPRR_HEADS
MIN_QLEN = rocm_aiter_mla._MIN_CPRR_QLEN
def test_dcp_verify_env_defaults_to_segmented(monkeypatch):
def test_dcp_verify_env_defaults_to_auto(monkeypatch):
monkeypatch.delenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", raising=False)
assert rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "segmented"
assert rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "auto"
@pytest.mark.parametrize("route", ["auto", "asm", "segmented"])
def test_dcp_verify_env_accepts_routes(monkeypatch, route):
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", route)
assert route == rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY
def test_dcp_verify_env_rejects_unknown_route(monkeypatch):
@@ -116,6 +126,126 @@ def test_route_needs_gfx950(monkeypatch):
)
# --------------------------------------------------------------------------
# AiterMLAMetadataBuilder -- the route the env value resolves to
# --------------------------------------------------------------------------
DCP = 8
def _build(monkeypatch, route, gathered_heads, segmented_supported=True):
"""Run the real builder __init__ on CPU at TP8/DCP8 with speculative decoding.
Stubs only what needs a GPU, AITER, or a DCP group, so the route decision
under test is the one the builder actually makes.
"""
def init_common_builder(self, *args, **kwargs):
self.num_heads = gathered_heads // DCP
self.dcp_world_size = DCP
self.reorder_batch_threshold = 5
monkeypatch.setattr(
rocm_aiter_mla.MLACommonMetadataBuilder, "__init__", init_common_builder
)
monkeypatch.setattr(
rocm_aiter_mla,
"_segmented_dcp_verify_supported",
lambda *args: segmented_supported,
)
monkeypatch.setattr(rocm_aiter_mla, "_fp8_mla_prefill_supported", lambda: False)
monkeypatch.setattr(
rocm_aiter_mla, "get_dcp_group", lambda: SimpleNamespace(rank_in_group=0)
)
monkeypatch.setattr(
torch.cuda,
"get_device_properties",
lambda device: SimpleNamespace(multi_processor_count=256),
)
monkeypatch.setitem(
sys.modules,
"aiter",
SimpleNamespace(
dtypes=SimpleNamespace(fp8="fp8", fp16="fp16", bf16="bf16"),
get_mla_metadata_info_v1=lambda *args, **kwargs: tuple(
(1, torch.int32) for _ in range(6)
),
),
)
if route is None:
monkeypatch.delenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", raising=False)
else:
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", route)
config = SimpleNamespace(
speculative_config=SimpleNamespace(num_speculative_tokens=4),
parallel_config=SimpleNamespace(
decode_context_parallel_size=DCP, cp_kv_cache_interleave_size=1
),
model_config=SimpleNamespace(max_model_len=16, dtype=torch.bfloat16),
scheduler_config=SimpleNamespace(max_num_seqs=2),
cache_config=SimpleNamespace(cache_dtype="fp8_e4m3", num_gpu_blocks=None),
compilation_config=SimpleNamespace(
cudagraph_mode=SimpleNamespace(has_full_cudagraphs=lambda: False)
),
)
return rocm_aiter_mla.AiterMLAMetadataBuilder(
kv_cache_spec=SimpleNamespace(block_size=1, dtype=torch.bfloat16),
layer_names=["layer.0"],
vllm_config=config,
device=torch.device("cpu"),
)
@pytest.mark.parametrize("route", [None, "auto", "AUTO"])
def test_auto_selects_cprr_for_k3_gathered_heads(on_gfx950, monkeypatch, route):
"""K3 at TP8/DCP8 gathers 96 heads; auto must take cprr padded to 128."""
builder = _build(monkeypatch, route, gathered_heads=96)
assert builder._asm_dcp_verify
assert builder._asm_dcp_verify_heads == 128
assert builder._num_attention_heads == 128
def test_auto_falls_back_to_segmented_above_largest_native(on_gfx950, monkeypatch):
builder = _build(monkeypatch, "auto", gathered_heads=256)
assert not builder._asm_dcp_verify
assert builder._supports_segmented_dcp_verify
def test_auto_without_any_route_names_the_missing_segmented_build(
on_gfx950, monkeypatch
):
with pytest.raises(ValueError) as exc:
_build(monkeypatch, "auto", gathered_heads=256, segmented_supported=False)
assert "VLLM_ROCM_AITER_MLA_DCP_VERIFY=auto" in str(exc.value)
assert "lacks segmented MLA decode" in str(exc.value)
@pytest.mark.parametrize("route", ["asm", "ASM"])
def test_explicit_asm_is_case_insensitive(on_gfx950, monkeypatch, route):
"""env_with_choices returns the raw string; ASM used to mean segmented."""
assert _build(monkeypatch, route, gathered_heads=96)._asm_dcp_verify
def test_explicit_asm_refuses_unservable_heads(on_gfx950, monkeypatch):
with pytest.raises(ValueError) as exc:
_build(monkeypatch, "ASM", gathered_heads=256)
assert "VLLM_ROCM_AITER_MLA_DCP_VERIFY=asm" in str(exc.value)
assert "Set VLLM_ROCM_AITER_MLA_DCP_VERIFY=segmented" in str(exc.value)
@pytest.mark.parametrize("route", ["segmented", "SEGMENTED"])
def test_explicit_segmented_never_selects_cprr(on_gfx950, monkeypatch, route):
assert not _build(monkeypatch, route, gathered_heads=96)._asm_dcp_verify
def test_auto_off_gfx950_stays_segmented(monkeypatch):
import vllm.platforms.rocm as rocm
monkeypatch.setattr(rocm, "on_gfx950", lambda: False)
assert not _build(monkeypatch, "auto", gathered_heads=96)._asm_dcp_verify
# --------------------------------------------------------------------------
# qlen floor
# --------------------------------------------------------------------------
@@ -61,6 +61,216 @@ def test_aiter_unified_attention_uses_dedicated_metadata_builder():
)
def test_segmented_attention_uses_dedicated_backend_components():
from vllm.v1.attention.backends.rocm_segmented_attn import (
RocmSegmentedAttentionBackend,
RocmSegmentedAttentionImpl,
RocmSegmentedAttentionMetadataBuilder,
)
assert (
RocmSegmentedAttentionBackend.get_builder_cls()
is RocmSegmentedAttentionMetadataBuilder
)
assert RocmSegmentedAttentionBackend.get_impl_cls() is RocmSegmentedAttentionImpl
assert RocmSegmentedAttentionBackend.get_name() == "ROCM_SEGMENTED_ATTN"
assert RocmSegmentedAttentionBackend.supports_non_causal()
assert RocmSegmentedAttentionBackend.supports_sliding_window()
assert RocmSegmentedAttentionBackend.supports_sink()
assert not RocmSegmentedAttentionBackend.supports_mm_prefix()
@pytest.mark.parametrize(
"sliding_window,logits_soft_cap,has_sinks",
[(4096, None, False), (None, 50.0, False), (None, None, True)],
)
def test_segmented_attention_admits_unified_fallback_features(
monkeypatch, sliding_window, logits_soft_cap, has_sinks
):
from vllm.platforms import rocm
from vllm.v1.attention.backend import AttentionType
from vllm.v1.attention.backends.rocm_segmented_attn import (
RocmSegmentedAttentionImpl,
)
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
monkeypatch.setattr(rocm, "on_gfx12x", lambda: True)
sinks = torch.zeros(8) if has_sinks else None
impl = RocmSegmentedAttentionImpl(
num_heads=8,
head_size=128,
scale=128**-0.5,
num_kv_heads=2,
alibi_slopes=None,
sliding_window=sliding_window,
kv_cache_dtype="auto",
logits_soft_cap=logits_soft_cap,
attn_type=AttentionType.DECODER,
sinks=sinks,
)
assert isinstance(impl, RocmSegmentedAttentionImpl)
@pytest.mark.parametrize(
"platform,rdna",
[("cuda", False), ("cpu", False), ("xpu", False), ("rocm", False), ("rocm", True)],
)
def test_segmented_attention_requires_rocm_rdna(monkeypatch, platform, rdna):
"""Reject unsupported platforms before probing ROCm or constructing kernels."""
from vllm.platforms import rocm
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backends import rocm_segmented_attn as segmented
monkeypatch.setattr(
segmented,
"current_platform",
SimpleNamespace(is_rocm=lambda: platform == "rocm"),
)
def on_rdna():
assert platform == "rocm", "Must not probe ROCm on another platform"
return rdna
monkeypatch.setattr(rocm, "on_gfx1x", on_rdna)
reason = segmented.RocmSegmentedAttentionBackend.supports_combination(
128,
torch.bfloat16,
"auto",
32,
False,
False,
False,
False,
DeviceCapability(12, 0),
)
if rdna:
assert reason is None
segmented.RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
else:
assert reason == "ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm"
with pytest.raises(ValueError, match="requires AMD RDNA GPUs on ROCm"):
segmented.RocmSegmentedAttentionImpl(
8, 128, 128**-0.5, 2, None, None, "auto"
)
@pytest.mark.parametrize("explicit_cache", [False, True])
def test_segmented_triton_cache_survives_standalone_compilation(
monkeypatch, tmp_path, explicit_cache
):
"""Backend initialization preserves one cache across model compilations."""
import os
from vllm.compilation.compiler_interface import InductorStandaloneAdaptor
from vllm.platforms import rocm
from vllm.v1.attention.backends.rocm_segmented_attn import (
RocmSegmentedAttentionImpl,
)
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
monkeypatch.setenv("VLLM_CACHE_ROOT", str(tmp_path))
monkeypatch.delenv("TRITON_CACHE_DIR", raising=False)
monkeypatch.delenv("TORCHINDUCTOR_CACHE_DIR", raising=False)
expected = tmp_path / "rocm_segmented_attention" / "triton"
if explicit_cache:
expected = tmp_path / "custom"
monkeypatch.setenv("TRITON_CACHE_DIR", str(expected))
for model in ("target", "draft", "restart_target"):
RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
assert os.environ["TRITON_CACHE_DIR"] == str(expected)
assert expected.is_dir()
InductorStandaloneAdaptor("binary").initialize_cache(str(tmp_path / model))
assert os.environ["TRITON_CACHE_DIR"] == str(expected)
def test_segmented_attention_is_opt_in(monkeypatch):
from vllm.platforms import rocm
from vllm.platforms.rocm import RocmPlatform, _get_backend_priorities
assert AttentionBackendEnum.ROCM_SEGMENTED_ATTN not in _get_backend_priorities(
use_mla=False, use_sparse=False
)
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
monkeypatch.setattr(rocm, "on_gfx12x", lambda: True)
config = AttentionSelectorConfig(
head_size=128,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
block_size=32,
)
path = RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_SEGMENTED_ATTN,
attn_selector_config=config,
)
assert path == AttentionBackendEnum.ROCM_SEGMENTED_ATTN.get_path()
def test_segmented_attention_rejects_mm_prefix_at_selection(monkeypatch):
from vllm.platforms import rocm
from vllm.platforms.rocm import RocmPlatform
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
config = AttentionSelectorConfig(
head_size=128,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
block_size=32,
use_mm_prefix=True,
)
with pytest.raises(ValueError, match="multimodal token full attention"):
RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_SEGMENTED_ATTN,
attn_selector_config=config,
)
def test_segmented_attention_forward_uses_dedicated_dispatch(monkeypatch):
from vllm.config import KernelConfig
from vllm.platforms import rocm
from vllm.v1.attention.backends.rocm_segmented_attn import (
RocmSegmentedAttentionImpl,
)
monkeypatch.setattr(rocm, "on_gfx1x", lambda: True)
impl = RocmSegmentedAttentionImpl(8, 128, 128**-0.5, 2, None, None, "auto")
impl._segmented_attention_config = SimpleNamespace(
kernel_config=KernelConfig(),
scheduler_config=SimpleNamespace(max_num_seqs=1, max_num_batched_tokens=3),
model_config=SimpleNamespace(max_model_len=16),
)
query = torch.empty(3, 8, 128, dtype=torch.bfloat16)
key = torch.empty(3, 2, 128, dtype=torch.bfloat16)
value = torch.empty_like(key)
output = torch.empty_like(query)
kv_cache = torch.empty(2, 2, 16, 256, dtype=torch.bfloat16)
metadata = SimpleNamespace(
use_cascade=False,
num_actual_tokens=3,
block_table=torch.zeros(1, 1, dtype=torch.int32),
query_start_loc=torch.tensor([0, 3], dtype=torch.int32),
seq_lens=torch.tensor([3], dtype=torch.int32),
max_seq_len=3,
max_query_len=3,
causal=True,
)
layer = SimpleNamespace(_k_scale=torch.ones(()), _v_scale=torch.ones(()))
with patch(
"vllm.v1.attention.backends.rocm_segmented_attn.segmented_attention"
) as dispatch:
result = impl.forward(layer, query, key, value, kv_cache, metadata, output)
assert result is output
dispatch.assert_called_once()
assert dispatch.call_args.kwargs["key_cache"].shape == (2, 16, 2, 128)
def test_aiter_unified_attention_capture_preserves_query_start_locations():
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionMetadataBuilder,
@@ -0,0 +1,32 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
from vllm._aiter_ops import is_aiter_found_and_supported
from vllm.platforms import current_platform
if not current_platform.is_rocm() or not is_aiter_found_and_supported():
pytest.skip("Requires ROCm with AITER.", allow_module_level=True)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import _per_sequence_context_lens
def test_per_row_table_uses_last_column():
seq_lens = torch.tensor([8192, 1500, 3000, 700], dtype=torch.int32)
next_n = 3
offsets = torch.arange(next_n, dtype=torch.int32) - next_n + 1
per_row = seq_lens.unsqueeze(1) + offsets
out = _per_sequence_context_lens(per_row)
assert out.shape == (4,)
assert out.is_contiguous()
assert torch.equal(out, seq_lens)
@pytest.mark.parametrize("shape", [(4,), (4, 1)])
def test_per_sequence_input_is_unchanged(shape):
context_lens = torch.arange(1, 5, dtype=torch.int32).reshape(shape)
assert _per_sequence_context_lens(context_lens) is context_lens
+31 -19
View File
@@ -295,7 +295,8 @@ def _quantize_dequantize_fp8_ds_mla(
rope_dim = k_pe.shape[-1]
num_tokens = kv_c.shape[0]
num_blocks = max(1, math.ceil(num_tokens / block_size))
entry_size = kv_lora_rank + 4 * 4 + 2 * rope_dim
# The 64-dim RoPE slot is always there; NoPE rows zero-fill it.
entry_size = kv_lora_rank + 4 * 4 + 2 * 64
tmp_cache = torch.zeros(
num_blocks, block_size, entry_size, dtype=torch.uint8, device=kv_c.device
@@ -413,6 +414,13 @@ def _quantize_dequantize_nvfp4_ds_mla(
@pytest.mark.parametrize("tensor_parallel_size", [1, 2, 4])
@pytest.mark.parametrize("block_size", [32, 64])
@pytest.mark.parametrize(("q_scale", "k_scale"), [(1.0, 1.0), (2.0, 3.0)])
@pytest.mark.parametrize(
("total_num_heads", "qk_nope_head_dim", "qk_rope_head_dim", "v_head_dim"),
[
pytest.param(128, 128, 64, 128, id="deepseek"),
pytest.param(64, 256, 0, 256, id="glm53_flash_nope"),
],
)
def test_sparse_backend_decode_correctness(
default_vllm_config,
dist_init,
@@ -424,8 +432,18 @@ def test_sparse_backend_decode_correctness(
workspace_init,
q_scale: float,
k_scale: float,
total_num_heads: int,
qk_nope_head_dim: int,
qk_rope_head_dim: int,
v_head_dim: int,
monkeypatch,
):
if qk_rope_head_dim == 0 and (
backend_cls != FlashMLASparseBackend
or kv_cache_dtype not in ("auto", "fp8_ds_mla")
or torch.cuda.get_device_capability()[0] != 9
):
pytest.skip("NoPE sparse MLA is served by FlashMLA on SM90 only")
if (
batch_name == "large_q_pure_prefill"
and backend_cls == FlashMLASparseBackend
@@ -484,15 +502,10 @@ def test_sparse_backend_decode_correctness(
device = torch.device(DEVICE_TYPE)
dtype = torch.bfloat16
# Model hyper-parameters (kept intentionally small for the unit test)
total_num_heads = 128
# Compute per-rank heads for simulated TP
num_heads = max(1, total_num_heads // tensor_parallel_size)
kv_lora_rank = 512
qk_nope_head_dim = 128
qk_rope_head_dim = 64
v_head_dim = 128
head_size = kv_lora_rank + qk_rope_head_dim
topk_tokens = 128
@@ -2565,7 +2578,7 @@ def test_hisparse_multi_step_writes_request_major_output():
@requires_hisparse_ops
def test_hisparse_kv_update_writes_resident_and_staging_caches():
def test_hisparse_kv_update_writes_resident_cache():
device = torch.device(DEVICE_TYPE)
block_size = 4
row_width = 8
@@ -2584,18 +2597,11 @@ def test_hisparse_kv_update_writes_resident_and_staging_caches():
block_table=torch.tensor([[1]], dtype=torch.int32, device=device),
slot_mapping=resident_slots,
)
cache_handle.mirror_staging_cache = torch.empty(
(1, block_size, row_width), dtype=torch.float32, device=device
)
cache_handle.mirror_staging_slots = torch.arange(
block_size, dtype=torch.int64, device=device
)
slots = torch.tensor([3, 7, -1], dtype=torch.int64, device=device)
kv_c = torch.randn(8, row_width - 2, device=device)
k_pe = torch.randn(8, 1, 2, device=device)
cache_handle.num_actual_tokens = slots.numel()
cache_handle.decode_batch = False
cache_handle.host_mirror_required = True
source_cache = torch.zeros_like(cache_handle.view.cache)
impl = object.__new__(FlashMLASparseImpl)
layer = SimpleNamespace(
@@ -2622,9 +2628,6 @@ def test_hisparse_kv_update_writes_resident_and_staging_caches():
expected.to(device),
)
torch.testing.assert_close(source_cache, torch.zeros_like(source_cache))
staged = cache_handle.mirror_staging_cache.view(-1, row_width)
staged_expected = torch.cat([kv_c[:3], k_pe[:3, 0]], dim=-1)
torch.testing.assert_close(staged[:3], staged_expected)
@requires_hisparse_ops
@@ -3293,7 +3296,8 @@ def test_hisparse_fp8_decode_resolves_rows_once_then_runs_batched_attention():
cache = SimpleNamespace(
runtime=SimpleNamespace(
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device))
hot=SimpleNamespace(attention_cache=torch.empty(1, device=device)),
max_swap_rows=num_tokens,
),
source_block_table=torch.empty(
num_decodes, 1, dtype=torch.int32, device=device
@@ -3601,15 +3605,22 @@ def test_flashinfer_sm120_hisparse_decode_uses_index_group():
def test_hisparse_resident_prefill_uses_attention_block_stride():
"""A batch beyond the swap-row capacity must bypass swap_in.
The index-group workspace has one more row than the HiSparse swap rows, so
routing on its size sent a 2-token batch with max_num_seqs=1 (a piecewise
CUDA-graph capture) into swap_in, which overflowed its capacity of 1.
"""
expected = torch.tensor([[19]], dtype=torch.int32)
cache_handle = SimpleNamespace(
all_context_pages_resident=True,
view=SimpleNamespace(block_size=64, attention_block_stride=832),
block_table=torch.tensor([[3]], dtype=torch.int32),
runtime=SimpleNamespace(max_swap_rows=1),
)
index_group = object.__new__(HiSparseMLAIndexGroup)
index_group.caches = [cache_handle]
index_group.physical_topk_indices = torch.empty((1, 1), dtype=torch.int32)
index_group.physical_topk_indices = torch.empty((2, 1), dtype=torch.int32)
index_group._convert_once = MagicMock(return_value=expected)
topk = torch.zeros((2, 1), dtype=torch.int32)
metadata = SimpleNamespace(
@@ -3809,6 +3820,7 @@ def test_flashmla_fp8_paths_accept_decode_subset(monkeypatch, use_mixed_batch: b
topk_indices_buffer=topk_indices,
num_heads=2,
kv_lora_rank=1,
q_head_size=3,
index_group=None,
index_group_index=0,
dcp_world_size=1,
@@ -22,6 +22,7 @@ from vllm.v1.core.kv_cache_utils import (
get_block_hash,
get_group_id,
init_none_hash,
resolve_cache_hit_alignment_tokens,
)
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.kv_cache_interface import (
@@ -148,29 +149,84 @@ def make_full_mamba_manager(
)
def test_dcp_fine_hit_retention_uses_hash_alignment_without_eagle():
"""DCP must not discard a reusable Mamba state at hash alignment."""
hash_block_size = 2
@pytest.mark.parametrize(
"dcp_world_size,hash_block_size,block_size,prompt_tokens,checkpoint_blocks",
[
(4, 2, 2, 7, 0),
(8, 16, 16, 512, 1),
(8, 16, 16, 513, 1),
*[(8, 128, 896, p, 1) for p in (127, 128, 129, 7040, 7168, 7296, 7449)],
],
)
@pytest.mark.parametrize("use_eagle", [False, True])
@pytest.mark.parametrize("extension_tokens", [0, 32])
def test_dcp_fine_hit_retention_uses_hash_alignment(
dcp_world_size,
hash_block_size,
block_size,
prompt_tokens,
checkpoint_blocks,
use_eagle,
extension_tokens,
):
"""Resends and extensions reuse the retained hash-aligned checkpoint."""
manager = make_full_mamba_manager(
dcp_world_size=4,
dcp_world_size=dcp_world_size,
hash_block_size=hash_block_size,
full_block_size=hash_block_size,
mamba_block_size=hash_block_size,
num_blocks=64,
full_block_size=block_size,
mamba_block_size=block_size,
num_blocks=128,
use_eagle=use_eagle,
num_speculative_blocks=4 if use_eagle else 0,
num_prefill_checkpoint_blocks=checkpoint_blocks,
)
manager.coordinator.retention_interval = 0
token_ids = list(range(7))
producer = make_request("producer", token_ids, hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(producer)
assert num_computed == 0
assert manager.allocate_slots(producer, 6, 0, computed_blocks) is not None
assert manager.coordinator.enable_partial_hash_hits
scheduler = SimpleNamespace(
block_size=block_size * dcp_world_size,
cache_config=SimpleNamespace(block_size=block_size),
hash_block_size=hash_block_size,
max_num_scheduled_tokens=8192,
scheduler_config=SimpleNamespace(long_prefill_token_threshold=0),
use_eagle_block_drop=use_eagle,
mamba_partial_cache_hit=True,
mamba_shared_prefix_checkpoint=False,
mamba_has_prefill_checkpoint_blocks=bool(checkpoint_blocks),
mamba_prefill_checkpoint_alignment=16,
)
producer = make_request(
"producer", list(range(prompt_tokens)), hash_block_size, sha256
)
while producer.num_computed_tokens < prompt_tokens:
scheduled = Scheduler._mamba_block_aligned_split(
scheduler, producer, prompt_tokens - producer.num_computed_tokens
)
assert scheduled > 0
manager.new_step_starts()
assert manager.allocate_slots(producer, scheduled) is not None
producer.num_computed_tokens += scheduled
manager.free(producer)
manager.new_step_starts()
consumer = make_request("consumer", token_ids, hash_block_size, sha256)
_, num_computed, _ = manager.get_computed_blocks(consumer)
assert num_computed == 6
replay = make_request(
"replay", list(range(prompt_tokens + extension_tokens)), hash_block_size, sha256
)
_, hit, _ = manager.get_computed_blocks(replay)
expected = (
max((prompt_tokens // hash_block_size - 1) * hash_block_size, 0)
if use_eagle
else ((prompt_tokens - 1) // hash_block_size * hash_block_size)
)
assert hit == expected
cached_states = {
end
for end in range(hash_block_size, prompt_tokens + 1, hash_block_size)
if manager.block_pool.get_cached_block(
producer.block_hashes[end // hash_block_size - 1], [1]
)
is not None
}
assert cached_states == ({expected} if expected else set())
@pytest.mark.parametrize("dcp_world_size", [1, 4])
@@ -339,7 +395,7 @@ def test_hybrid_mamba_align_partial_hash_hit():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
blocks = manager.allocate_slots(req0, 6, num_computed, computed_blocks)
@@ -488,7 +544,7 @@ def test_hybrid_mamba_partial_tail_owner_uses_cow_on_continue():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -538,7 +594,7 @@ def test_partial_hit_then_internal_checkpoint_uses_distinct_mamba_blocks():
num_prefill_checkpoint_blocks=1,
)
owner = make_request("owner", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
owner = make_request("owner", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(owner)
assert manager.allocate_slots(owner, 6, num_computed, computed_blocks) is not None
manager.free(owner)
@@ -619,44 +675,70 @@ def test_internal_checkpoint_uses_partial_hash_lifecycle():
assert num_computed == 112
@pytest.mark.parametrize(
"retention_interval,transient_published",
[(None, True), (0, False)],
)
@pytest.mark.parametrize("retention_interval", [None, 0, 32, 64, 256])
@pytest.mark.parametrize("hash_block_size", [16, 32])
@pytest.mark.parametrize("use_eagle", [False, True])
def test_internal_checkpoint_publication_respects_retention(
retention_interval, transient_published
retention_interval, hash_block_size, use_eagle
):
"""With retention_interval=0, a mid-prompt internal checkpoint is
request-local and must not enter the prefix cache; the prompt-end
checkpoint keeps the existing publication behavior. Dense retention
(None) is unchanged.
"""
hash_block_size = 16
"""Publish only retained block boundaries and the final prompt checkpoint."""
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,
use_eagle=use_eagle,
)
manager.coordinator.retention_interval = retention_interval
request = make_request("producer", list(range(240)), hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(request)
# Mid-prompt chunk: exports a transient checkpoint at 112.
# The EAGLE adjustment can make a chunk checkpoint block-aligned or partial.
assert manager.allocate_slots(request, 128, num_computed, computed_blocks)
transient_hash = request.block_hashes[112 // hash_block_size - 1]
checkpoint = (128 if use_eagle else 127) // hash_block_size * hash_block_size - (
hash_block_size if use_eagle else 0
)
retained_checkpoint = checkpoint % 32 == 0 and (
retention_interval is None
or (retention_interval > 0 and checkpoint % retention_interval == 0)
)
transient_hash = request.block_hashes[checkpoint // hash_block_size - 1]
transient_hit = manager.block_pool.get_cached_block(transient_hash, [1])
assert (transient_hit is not None) == transient_published
assert (transient_hit is not None) == retained_checkpoint
offloads = drain_boundary_state_offloads(manager).get(request.request_id, [])
assert any(position == checkpoint for _, _, position in offloads) == (
retained_checkpoint
)
assert all(
position % 32 == 0
and (
retention_interval is None
or (retention_interval > 0 and position % retention_interval == 0)
)
for _, _, position in offloads
)
if retention_interval in (None, 32, 64):
retained_hash = request.block_hashes[128 // hash_block_size - 1]
assert manager.block_pool.get_cached_block(retained_hash, [1]) is not None
request.num_computed_tokens = 128
manager.new_step_starts()
# Final chunk: the prompt-end checkpoint at 224 stays published.
# The final checkpoint is reusable regardless of the retention interval.
assert manager.allocate_slots(request, 112) is not None
end_hash = request.block_hashes[224 // hash_block_size - 1]
prompt_checkpoint = (
240 if use_eagle else 239
) // hash_block_size * hash_block_size - (hash_block_size if use_eagle else 0)
end_hash = request.block_hashes[prompt_checkpoint // hash_block_size - 1]
assert manager.block_pool.get_cached_block(end_hash, [1]) is not None
assert any(
position == prompt_checkpoint
for _, _, position in drain_boundary_state_offloads(manager).get(
request.request_id, []
)
)
def test_transient_checkpoint_evicts_retained_boundary_hash():
@@ -802,9 +884,9 @@ def test_hash_aligned_query_end_uses_regular_partial_tail():
mamba_block_size=mamba_block_size,
num_prefill_checkpoint_blocks=1,
)
request = make_request("producer", list(range(14)), hash_block_size, sha256)
request = make_request("producer", list(range(15)), hash_block_size, sha256)
new_blocks = manager.allocate_slots(request, request.num_tokens)
new_blocks = manager.allocate_slots(request, 14)
assert new_blocks is not None
mamba_manager = manager.coordinator.single_type_managers[1]
@@ -928,7 +1010,7 @@ def test_boundary_state_offloads_returns_cow_target():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -1004,7 +1086,7 @@ def test_finished_partial_tail_uses_table_source_once():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
source_block_id = manager.get_blocks("0").get_block_ids()[1][1]
@@ -1024,7 +1106,7 @@ def test_finished_partial_tail_uses_table_source_once():
enable_caching=True,
hash_block_size=hash_block_size,
)
req1 = make_request("1", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req1 = make_request("1", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = advanced_manager.get_computed_blocks(req1)
assert (
advanced_manager.allocate_slots(req1, 6, num_computed, computed_blocks)
@@ -1212,7 +1294,7 @@ def test_truncate_computed_blocks_preserves_sparse_prefix_positions():
enable_caching=True,
hash_block_size=hash_block_size,
)
producer = make_request("producer", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
producer = make_request("producer", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
blocks, num_computed, _ = manager.get_computed_blocks(producer)
assert manager.allocate_slots(producer, 6, num_computed, blocks) is not None
manager.free(producer)
@@ -1267,7 +1349,7 @@ def test_truncate_computed_blocks_allows_short_mamba_group_only():
enable_caching=True,
hash_block_size=hash_block_size,
)
producer = make_request("producer", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
producer = make_request("producer", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
blocks, num_computed, _ = manager.get_computed_blocks(producer)
assert manager.allocate_slots(producer, 6, num_computed, blocks) is not None
manager.free(producer)
@@ -1331,7 +1413,7 @@ def test_hybrid_mamba_partial_tail_owner_continue_preserves_later_hit():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -1411,7 +1493,7 @@ def test_hybrid_mamba_moved_partial_entry_defers_same_step_hit():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -1470,7 +1552,7 @@ def test_hybrid_full_attention_partial_hash_hit_uses_cow():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -1544,7 +1626,7 @@ def test_hybrid_partial_hit_cow_target_starts_uncached():
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert num_computed == 0
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -1700,7 +1782,7 @@ def test_cow_retained_blocks_returned_for_release():
enable_caching=True,
hash_block_size=hash_block_size,
)
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
@@ -2133,6 +2215,72 @@ def test_hybrid_sliding_window_group_disables_partial_hash_hits():
assert len(computed_blocks.blocks[0]) * hash_block_size == num_computed
@pytest.mark.parametrize("with_sliding_window", [False, True])
def test_resolved_cache_hit_alignment_matches_coordinator(with_sliding_window):
"""Workers place Mamba checkpoints on the engine-resolved alignment, so it
must be where the coordinator lands hits, including when a group without
fine-grained lookups disables partial hits."""
hash_block_size = 2
mamba_block_size = 4 * hash_block_size
kv_cache_groups = [
KVCacheGroupSpec(
["full"],
FullAttentionSpec(
block_size=hash_block_size,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
),
),
KVCacheGroupSpec(
["mamba"],
MambaSpec(
block_size=mamba_block_size,
shapes=(1, 1),
dtypes=(torch.float32,),
mamba_cache_mode="align",
),
),
]
if with_sliding_window:
kv_cache_groups.append(
KVCacheGroupSpec(
["swa"],
SlidingWindowSpec(
block_size=2 * hash_block_size,
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
sliding_window=2 * hash_block_size,
),
)
)
kv_cache_config = KVCacheConfig(
num_blocks=64, kv_cache_tensors=[], kv_cache_groups=kv_cache_groups
)
coordinator = make_kv_cache_manager(
kv_cache_config=kv_cache_config,
max_model_len=8192,
enable_caching=True,
hash_block_size=hash_block_size,
).coordinator
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(enable_prefix_caching=True),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
)
assert coordinator.enable_partial_hash_hits != with_sliding_window
assert (
resolve_cache_hit_alignment_tokens(
kv_cache_config,
vllm_config,
coordinator.scheduler_block_size,
hash_block_size,
)
== coordinator._cache_hit_alignment_tokens
)
def test_opted_out_scratch_group_keeps_partial_hash_hits():
hash_block_size = 2
mamba_block_size = 2 * hash_block_size
@@ -2179,7 +2327,7 @@ def test_opted_out_scratch_group_keeps_partial_hash_hits():
assert manager.coordinator.enable_partial_hash_hits
req0 = make_request("0", [0, 0, 1, 1, 2, 2], hash_block_size, sha256)
req0 = make_request("0", [0, 0, 1, 1, 2, 2, 3], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
manager.free(req0)
@@ -2240,7 +2388,7 @@ def test_kpool_tail_supports_128_token_partial_hash_hits():
assert manager.coordinator.enable_partial_hash_hits
shared_prefix = [10] * (12 * hash_block_size)
req0 = make_request("0", shared_prefix, hash_block_size, sha256)
req0 = make_request("0", shared_prefix + [11], hash_block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert (
manager.allocate_slots(req0, len(shared_prefix), num_computed, computed_blocks)
@@ -2266,7 +2414,7 @@ def test_hybrid_partial_hash_hit_uses_cow_under_dcp(dcp_world_size: int):
)
assert manager.coordinator.enable_partial_hash_hits
req0 = make_request("dcp-owner", [0, 0, 1, 1, 2, 2], 2, sha256)
req0 = make_request("dcp-owner", [0, 0, 1, 1, 2, 2, 3], 2, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 6, num_computed, computed_blocks) is not None
manager.free(req0)
@@ -2318,7 +2466,7 @@ def test_dcp_partial_hit_resumes_on_replicated_mamba_snapshot(
assert manager.coordinator.single_type_managers[1].block_size == block_size
prefix = list(range(12))
req0 = make_request("snapshot-owner", prefix, block_size, sha256)
req0 = make_request("snapshot-owner", prefix + [12], block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 12, num_computed, computed_blocks) is not None
manager.free(req0)
@@ -2355,7 +2503,7 @@ def test_dcp_joint_hit_is_bounded_by_replicated_mamba_snapshots():
mamba_block_size=block_size,
)
prefix = list(range(12))
req0 = make_request("joint-owner", prefix, block_size, sha256)
req0 = make_request("joint-owner", prefix + [12], block_size, sha256)
computed_blocks, num_computed, _ = manager.get_computed_blocks(req0)
assert manager.allocate_slots(req0, 8, num_computed, computed_blocks) is not None
manager.new_step_starts()
@@ -2702,6 +2850,7 @@ def test_checkpoint_reservation_matches_worker(
mamba_block_size=mamba_block_size,
checkpoint_alignment=16,
drop_eagle_block=use_eagle,
cache_hit_alignment_tokens=mamba_manager.cache_hit_alignment_tokens,
)
reserved = mamba_manager._checkpoints.get(request.request_id)
if reserved is not None:
+82
View File
@@ -60,6 +60,7 @@ from vllm.v1.core.kv_cache_utils import (
from vllm.v1.hisparse.layout import (
create_hisparse_layout,
get_hisparse_kv_cache_groups,
get_hisparse_steady_state_concurrency,
)
from vllm.v1.kv_cache_interface import (
ChunkedLocalAttentionSpec,
@@ -198,6 +199,48 @@ def test_hisparse_hma_uses_resolved_gpu_block_size(
assert scheduler_block_size == hash_block_size == gpu_block_size
def test_hisparse_steady_state_concurrency_excludes_spilled_resident_pages():
"""Running requests pin only their resident tail; the newest still needs its
full in-flight window to be admitted."""
block_size = 16
config = SimpleNamespace(
model_config=SimpleNamespace(max_model_len=10 * block_size),
parallel_config=SimpleNamespace(decode_context_parallel_size=1),
max_in_flight_tokens=10 * block_size,
)
attn_spec = FullAttentionSpec(
block_size=block_size, num_kv_heads=1, head_size=64, dtype=torch.float16
)
page_size = attn_spec.page_size_bytes
kv_cache_config = KVCacheConfig(
num_blocks=64,
kv_cache_tensors=[],
kv_cache_groups=[
KVCacheGroupSpec(["source"], attn_spec, host_resident=True),
KVCacheGroupSpec(["indexer"], attn_spec),
KVCacheGroupSpec(
["resident"],
HiSparseResidentSpec(block_size=block_size, page_size=page_size),
),
KVCacheGroupSpec(
["hot"],
HiSparseHotSpec(
block_size=block_size, page_size=page_size, blocks_per_request=4
),
),
],
hisparse_host_num_blocks=100,
)
# Admission takes indexer 10 + resident 10 + hot 4 = 24 blocks and steady
# state 16, so 3 fit (2 x 16 + 24 <= 64) but not 4 (3 x 16 + 24 > 64).
assert get_hisparse_steady_state_concurrency(config, kv_cache_config) == 3.5
# The worst-case bound charges all 10 resident pages.
assert get_max_concurrency_for_kv_cache_config(
config, kv_cache_config
) == pytest.approx(64 / 24)
@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."""
@@ -923,6 +966,24 @@ def test_free_kv_cache_block_queue_popleft_n():
assert block.next_free_block is None
@pytest.mark.parametrize("num_blocks", [1, 2, 16])
def test_free_kv_cache_block_queue_popleft_n_drain_and_refill(num_blocks):
"""Draining a batch must leave the sentinels ready for reuse."""
blocks = [KVCacheBlock(block_id=i) for i in range(num_blocks)]
queue = FreeKVCacheBlockQueue(blocks)
assert queue.popleft_n(num_blocks) == blocks
assert queue.num_free_blocks == 0
assert queue.fake_free_list_head.next_free_block is queue.fake_free_list_tail
assert queue.fake_free_list_tail.prev_free_block is queue.fake_free_list_head
assert all(b.prev_free_block is None and b.next_free_block is None for b in blocks)
assert queue.popleft_n(0) == []
queue.append_n(blocks)
assert queue.popleft_n(num_blocks) == blocks
assert queue.num_free_blocks == 0
def test_free_kv_cache_block_queue_get_all_free_blocks():
# Create a list of KVCacheBlock objects
blocks = [KVCacheBlock(block_id=i) for i in range(5)]
@@ -1873,6 +1934,27 @@ def test_dcp_target_allocates_replicated_draft_independently(
assert [len(group) for group in cached_blocks.blocks] == [1, 4]
def test_dcp_replicated_kpool_tail_keeps_block_interior_layout(monkeypatch):
"""A replicated kpool tail ring is per-request state, not a draft group."""
from vllm.v1.attention.backends.utils import resolve_kv_cache_layout
monkeypatch.delenv("VLLM_KV_CACHE_LAYOUT", raising=False)
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
config.parallel_config.decode_context_parallel_size = 4
config.cache_config.kv_cache_layout = None
tail = KpoolTailSpec(
block_size=4,
num_kv_heads=2,
head_size=128,
head_size_v=0,
dtype=torch.bfloat16,
sliding_window=4,
dcp_sharded=False,
)
layout = resolve_kv_cache_layout(config, [["LBHNC"]], [new_mla_spec(), tail])
assert layout == KVCacheLayout.LBHNC
@pytest.mark.parametrize("use_mla", [False, True])
def test_full_attention_merge_preserves_replicated_cache_geometry(use_mla):
config = VllmConfig(model_config=ModelConfig(max_model_len=1024))
+14 -26
View File
@@ -594,8 +594,12 @@ def test_nixl_hisparse_full_block_import_keeps_a_writable_tail(num_tokens):
failed_recving_kv_req_ids=set(),
finished_recving_kv_req_ids={request.request_id},
prefix_replay_tokens=0,
prefix_replay_group_ids=(),
)
scheduler._mark_prefix_replay = MethodType(Scheduler._mark_prefix_replay, scheduler)
scheduler._load_restores_replay_window = MethodType(
Scheduler._load_restores_replay_window, scheduler
)
Scheduler._update_waiting_for_remote_kv(scheduler, request)
assert request.num_tokens - request.num_computed_tokens == 1
assert _allocate_scheduled(manager, request, num_new_tokens=1) is not None
@@ -5043,19 +5047,10 @@ def test_hybrid_local_kv_retention_mtp_reuses_latest_boundary():
def test_hybrid_mamba_retention_mtp_resend_of_aligned_prompt():
"""An identical resend and a longer sibling resume at DIFFERENT positions.
"""EAGLE resend and extension reuse the same retained checkpoint.
How far a lookup matches depends on who is asking. A resend of the same
prompt caps its lookup at ``num_tokens - 1`` (the last token is recomputed
for logits), while a sibling whose prompt merely starts with this one caps
above the prompt. The two coincide unless the prompt length is an exact
multiple of the alignment -- there they differ by one alignment unit, and
under the EAGLE drop BOTH are reachable.
Retaining only the higher one leaves the resend with every retained state
above every candidate its lookup can produce, and the reconciled hit
collapses to 0 -- the same zero-hit failure sparse retention already fixes
at unaligned prompt lengths.
Attention may inspect the prompt's final block before dropping it, so an
aligned resend must not lose another block to the P - 1 lookup limit.
"""
block_size = 32
num_spec = 3
@@ -5093,16 +5088,12 @@ def test_hybrid_mamba_retention_mtp_resend_of_aligned_prompt():
use_eagle=True,
)
# 128 tokens, an exact multiple of the 32-token alignment. A longer sibling
# matches 128 and drops to 96; this prompt's own resend caps at 127, matches
# 96 and drops to 64. Both states must survive retention.
# Both requests prove 128 attention tokens, drop one block, and reuse 96.
token_ids = [i for i in range(4) for _ in range(block_size)]
req0 = make_request("0", token_ids, block_size, sha256)
computed_blocks, num_computed_tokens, _ = manager.get_computed_blocks(req0)
assert num_computed_tokens == 0
# Prefill in block-aligned chunks the way the align-mode scheduler does: a
# state only materializes as a chunk's running-state block, so a
# single-shot prefill could not retain the lower one.
# Materialize the checkpoint through normal block-aligned prefill chunks.
for chunk_end in (32, 64, 96, 128):
blocks = manager.allocate_slots(
req0,
@@ -5114,8 +5105,7 @@ def test_hybrid_mamba_retention_mtp_resend_of_aligned_prompt():
assert blocks is not None
req0.num_computed_tokens = chunk_end
# Block ``i`` ends at token ``(i + 1) * 32``, so positions 64 and 96 are
# mamba blocks 1 and 2.
# Both materialized replay checkpoints survive; resend and extension use 96.
pool = manager.block_pool
expected_mamba_cached = {1, 2}
for i in range(4):
@@ -5126,15 +5116,13 @@ def test_hybrid_mamba_retention_mtp_resend_of_aligned_prompt():
assert cached is None, f"mamba hash {i} should not be cached"
manager.free(req0)
# The identical resend: full attention matches blocks 0-2 (96 tokens, capped
# by num_tokens - 1) and the EAGLE drop caps the candidate at 64. Without
# the lower state retained the reconciled hit would be 0.
# The identical resend must reuse the retained checkpoint, not miss to zero.
req1 = make_request("1", token_ids, block_size, sha256)
computed_blocks, num_computed_tokens, _ = manager.get_computed_blocks(req1)
assert num_computed_tokens == 2 * block_size
assert [len(blocks) for blocks in computed_blocks.blocks] == [2, 2]
assert num_computed_tokens == 3 * block_size
assert [len(blocks) for blocks in computed_blocks.blocks] == [3, 3]
# The longer sibling resumes one alignment unit higher, off the same prompt.
# The longer sibling reuses that same checkpoint.
longer = make_request("2", token_ids + [9] * block_size, block_size, sha256)
computed_blocks, num_computed_tokens, _ = manager.get_computed_blocks(longer)
assert num_computed_tokens == 3 * block_size
+27
View File
@@ -247,6 +247,33 @@ def test_remote_kv_hit_is_taken_in_whole_blocks():
assert swa_blocks[new_req.replay_start // BLOCK_SIZE] is not swa_manager._null_block
@pytest.mark.parametrize("is_async", [False, True])
@pytest.mark.parametrize("matched", [WINDOW, 4 * BLOCK_SIZE - 1])
def test_kv_load_carrying_window_does_not_replay(is_async, matched):
"""A load of the request's own blocks (P/D) restores every transfer group,
window included, so the hit is taken as is: no replay, no cut to whole
blocks, and a hit no longer than the window is kept."""
scheduler = _replay_scheduler(
use_kv_connector=MockKVConfig(matched_tokens=matched, is_async=is_async)
)
request = create_requests(
num_requests=1, num_tokens=NUM_PROMPT_TOKENS, block_size=BLOCK_SIZE
)[0]
scheduler.connector.get_loaded_kv_cache_group_ids = lambda request: (FULL, SWA)
scheduler.add_request(request)
out = scheduler.schedule()
if is_async:
assert request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
scheduler.update_from_output(
out, create_model_runner_output([], finished_recving={request.request_id})
)
out = scheduler.schedule()
new_req = _new_req_data(out, request)
assert new_req.num_computed_tokens == matched
assert new_req.replay_start == 0
assert out.num_scheduled_tokens[request.request_id] == NUM_PROMPT_TOKENS - matched
@pytest.mark.parametrize("via_connector", [False, True])
def test_hit_no_longer_than_window_is_ignored(via_connector):
"""Such a hit would be recomputed in full anyway. It is not adopted (an
+197 -1
View File
@@ -3,7 +3,7 @@
import dataclasses
from concurrent.futures import Future
from types import SimpleNamespace
from unittest.mock import Mock
from unittest.mock import Mock, patch
import numpy as np
import pytest
@@ -35,6 +35,7 @@ from vllm.multimodal.inputs import (
MultiModalKwargsItem,
PlaceholderRange,
)
from vllm.pooling_params import PoolingParams
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.utils.hashing import sha256
from vllm.v1.core.encoder_cache_manager import EncoderCacheManager
@@ -60,6 +61,7 @@ from vllm.v1.kv_cache_interface import (
KVCacheGroupSpec,
MambaSpec,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import (
DraftTokenIds,
ECConnectorOutput,
@@ -278,6 +280,24 @@ def test_schedule(enable_prefix_caching: bool, prompt_logprobs: int | None):
assert scheduler.running[i] == request
def test_pooling_chunked_prefill_can_finish_at_max_model_len():
scheduler = create_scheduler(
max_num_seqs=1, max_model_len=8, max_num_batched_tokens=4, runner="pooling"
)
assert scheduler.max_model_len == 8
request = Request(
request_id="pool",
prompt_token_ids=[1] * 8,
sampling_params=None,
pooling_params=PoolingParams(task="embed"),
)
scheduler.add_request(request)
scheduler.schedule()
# The final chunk must reach max_model_len, not stop one token short.
assert scheduler.schedule().num_scheduled_tokens == {"pool": 4}
def test_scheduler_stats_route_to_existing_output_client():
scheduler = create_scheduler()
request = create_requests(num_requests=1)[0]
@@ -688,6 +708,33 @@ def test_throttle_capacity_bound_guard_admits():
assert "b" in output.num_scheduled_tokens
def test_same_step_duplicate_encoder_input_stays_cached():
scheduler = create_scheduler(
model="llava-hf/llava-1.5-7b-hf",
max_num_batched_tokens=1024,
max_model_len=2048,
)
request = create_requests(
1,
num_tokens=2000,
req_ids=["repeated"],
mm_hashes_list=[["image", "image", "image"]],
mm_positions=[
[PlaceholderRange(offset=offset, length=576) for offset in (0, 600, 1300)]
],
)[0]
scheduler.add_request(request)
output = scheduler.schedule()
assert output.scheduled_encoder_inputs == {request.request_id: [0]}
_model_output(scheduler, output, [[]])
# The second occurrence is partially consumed; the third is not scheduled.
cache = scheduler.encoder_cache_manager
assert cache.get_cached_input_ids(request) == {1}
assert "image" not in cache.freeable
def test_no_mm_input_chunking():
# Disable multimodal input chunking.
scheduler = create_scheduler(
@@ -2526,6 +2573,96 @@ def _step_until_kv_transfer_finished(scheduler: Scheduler, req_ids: list[str]):
return initial_ecos
def _runner_output(
req_ids: list[str], finished_recving: set[str] | None = None
) -> ModelRunnerOutput:
return ModelRunnerOutput(
req_ids=req_ids,
req_id_to_index={req_id: i for i, req_id in enumerate(req_ids)},
sampled_token_ids=[[1] for _ in req_ids],
kv_connector_output=KVConnectorOutput(finished_recving=finished_recving),
)
@pytest.mark.parametrize(
"load_done_before_pause", [False, True], ids=["load-in-flight", "load-done"]
)
def test_pause_new_drains_async_kv_loads(load_done_before_pause: bool):
"""A PAUSED_NEW (pause mode="wait") drain must finish requests that hold KV
blocks for an async load, keep blockless queued requests queued, and leave
no blocks behind, so the post-drain cache reset succeeds."""
block_size = 16
scheduler = create_scheduler(
enable_prefix_caching=True,
use_kv_connector=mock_kv(matched_tokens=2 * block_size, is_async=True),
block_size=block_size,
)
loading, queued = create_requests(
num_requests=2,
num_tokens=3 * block_size,
max_tokens=2,
block_size=block_size,
req_ids=["loading", "queued"],
)
scheduler.add_request(loading)
output = scheduler.schedule()
assert loading.status == RequestStatus.WAITING_FOR_REMOTE_KVS
pending_recv = {"loading"}
if load_done_before_pause:
scheduler.update_from_output(output, _runner_output([], pending_recv))
pending_recv = None
else:
scheduler.update_from_output(output, _runner_output([]))
scheduler.set_pause_state(PauseState.PAUSED_NEW)
scheduler.add_request(queued)
num_steps = 0
while scheduler.has_requests():
num_steps += 1
assert num_steps <= 4, "pause drain did not finish"
output = scheduler.schedule()
assert set(output.num_scheduled_tokens) <= {"loading"}
scheduler.update_from_output(
output, _runner_output(list(output.num_scheduled_tokens), pending_recv)
)
pending_recv = None
# What pause runs once drained; it raises if the load still holds blocks.
assert scheduler.reset_prefix_cache(reset_running_requests=True)
assert loading.status == RequestStatus.FINISHED_LENGTH_CAPPED
assert loading.request_id not in scheduler.requests
assert list(scheduler.waiting) == [queued]
assert queued.status == RequestStatus.WAITING
scheduler.set_pause_state(PauseState.UNPAUSED)
scheduler.schedule()
assert queued.status == RequestStatus.WAITING_FOR_REMOTE_KVS
def test_pause_new_ignores_streaming_session_waiting_for_input():
"""A session idle in WAITING_FOR_STREAMING_REQ cannot progress, so it must
not keep a PAUSED_NEW drain from completing."""
stop_token = 7
scheduler = create_scheduler()
(session,) = create_requests(
num_requests=1, num_tokens=4, stop_token_ids=[stop_token], req_ids=["s"]
)
session.resumable = True
scheduler.add_request(session)
output = scheduler.schedule()
scheduler.update_from_output(
output,
ModelRunnerOutput(
req_ids=["s"], req_id_to_index={"s": 0}, sampled_token_ids=[[stop_token]]
),
)
assert session in scheduler.kv_holding_waiting
scheduler.set_pause_state(PauseState.PAUSED_NEW)
assert scheduler.get_num_unfinished_requests() == 0
@pytest.mark.parametrize(
("load_modes", "expected_has_sync_loads"),
[
@@ -2586,6 +2723,65 @@ def test_kv_connector_honors_skip_reading_prefix_cache():
assert output.num_scheduled_tokens[scoring.request_id] == BLOCK_SIZE * 4
@pytest.mark.parametrize("is_async", [False, True])
def test_kv_connector_records_external_cache_hit_sources(monkeypatch, is_async):
block_size = 16
num_matched_tokens = 2 * block_size
scheduler = create_scheduler(
enable_prefix_caching=True,
use_kv_connector=mock_kv(
matched_tokens=num_matched_tokens,
is_async=is_async,
),
block_size=block_size,
)
request = create_requests(
num_requests=1,
num_tokens=2 * num_matched_tokens,
block_size=block_size,
)[0]
assert scheduler.connector is not None
get_sources = Mock(
return_value={CacheHitSource.P2P: block_size, CacheHitSource.HOST: block_size}
)
update_state = Mock(wraps=scheduler.connector.update_state_after_alloc)
calls = Mock()
calls.attach_mock(update_state, "allocated")
calls.attach_mock(get_sources, "sources")
monkeypatch.setattr(scheduler.connector, "update_state_after_alloc", update_state)
monkeypatch.setattr(
scheduler.connector, "get_external_cache_hit_sources", get_sources
)
scheduler.add_request(request)
# A failed allocation is not an admission: nothing is attributed.
with patch.object(scheduler.kv_cache_manager, "allocate_slots", return_value=None):
scheduler.schedule()
get_sources.assert_not_called()
update_state.assert_not_called()
scheduler.schedule()
# Attribution runs once, after the connector has built its load plan.
get_sources.assert_called_once_with(request, num_matched_tokens)
assert [c[0] for c in calls.mock_calls] == ["allocated", "sources"]
connector_stats = scheduler.connector_prefix_cache_stats
assert connector_stats is not None
assert connector_stats.hits == num_matched_tokens
assert connector_stats.hits_by_source == {
CacheHitSource.P2P: block_size,
CacheHitSource.HOST: block_size,
}
if is_async:
# Re-admission after the async load completes is not a new hit.
scheduler.make_stats()
_step_until_kv_transfer_finished(scheduler, [request.request_id])
get_sources.assert_called_once()
connector_stats = scheduler.connector_prefix_cache_stats
assert connector_stats is not None
assert connector_stats.hits_by_source == {}
@pytest.mark.parametrize("is_async", [False, True])
def test_kv_connector_basic(is_async: bool):
"""Test whether Scheduler with KVConnector schedules tokens, allocates
@@ -6,10 +6,14 @@ import random
import pytest
import torch
from vllm.sampling_params import SamplingParams
from vllm.utils.hashing import sha256
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.kv_cache_utils import (
BlockHash,
KVCacheBlock,
get_request_block_hasher,
init_none_hash,
make_block_hash_with_group_id,
)
from vllm.v1.core.single_type_kv_cache_manager import (
@@ -30,6 +34,7 @@ from vllm.v1.kv_cache_interface import (
RSWASpec,
SlidingWindowSpec,
)
from vllm.v1.request import Request
pytestmark = pytest.mark.cpu_test
@@ -238,6 +243,71 @@ def test_mamba_checkpoint_admission_matches_allocation(
assert admission_estimate == allocation_estimate == allocated
@pytest.mark.parametrize("num_speculative_blocks", [1, 2, 3])
@pytest.mark.parametrize("first_chunk_blocks", [2, 4])
@pytest.mark.parametrize("retention_interval", [0, None])
def test_mamba_checkpoint_hash_maps_only_to_checkpoint_block(
num_speculative_blocks, first_chunk_blocks, retention_interval
):
"""A checkpoint step must not leave a never-written speculative block
cached."""
block_size = 128
spec = MambaSpec(
block_size=block_size,
shapes=((1, 1),),
dtypes=(torch.float32,),
mamba_cache_mode="align",
num_speculative_blocks=num_speculative_blocks,
num_prefill_checkpoint_blocks=1,
prefill_checkpoint_alignment=16,
)
pool = BlockPool(num_gpu_blocks=64, enable_caching=True, hash_block_size=128)
manager = MambaManager(
spec,
block_pool=pool,
enable_caching=True,
kv_cache_group_id=0,
scheduler_block_size=block_size,
)
# MTP/EAGLE moves the checkpoint one block below the last full block.
manager.drop_eagle_checkpoint_block = True
init_none_hash(sha256)
prompt_tokens = 6 * block_size + 50
request = Request(
request_id="r",
prompt_token_ids=list(range(prompt_tokens)),
sampling_params=SamplingParams(max_tokens=1),
pooling_params=None,
block_hasher=get_request_block_hasher(block_size, sha256),
)
def step(start, end):
estimate = manager.get_num_blocks_to_allocate("r", end, [], start, start, end)
free_before = pool.get_num_free_blocks()
manager.allocate_new_blocks("r", end, end)
assert free_before - pool.get_num_free_blocks() == estimate
manager.cache_blocks(
request,
end,
retention_interval=retention_interval,
replay_boundaries=[5 * block_size],
)
request.num_computed_tokens = end
step(0, first_chunk_blocks * block_size)
speculative_blocks = manager.req_to_blocks["r"][-num_speculative_blocks:]
manager.new_step_starts()
step(first_chunk_blocks * block_size, prompt_tokens)
checkpoint_position, checkpoint_idx = manager._checkpoints["r"]
checkpoint_block = manager.req_to_blocks["r"][checkpoint_idx]
assert all(
b.block_hash is None or b is checkpoint_block for b in speculative_blocks
)
block_hash = request.block_hashes[checkpoint_position // block_size - 1]
assert pool.get_cached_block(block_hash, [0]) == [checkpoint_block]
def get_sliding_window_manager(
sliding_window_spec,
block_pool,
+3
View File
@@ -18,6 +18,7 @@ from vllm.config import (
SpeculativeConfig,
VllmConfig,
)
from vllm.config.model import RunnerOption
from vllm.config.scheduler import SchedulerPolicy
from vllm.multimodal.inputs import (
MultiModalFeatureSpec,
@@ -78,6 +79,7 @@ def create_scheduler(
ec_role: str | None = None,
use_v2_model_runner: bool | None = None,
kv_cache_spec: KVCacheSpec | None = None,
runner: RunnerOption = "auto",
per_request_spec_decode_metrics: str = "none",
scheduling_policy: SchedulerPolicy = "fcfs",
diffusion_canvas_length: int | None = None,
@@ -109,6 +111,7 @@ def create_scheduler(
# The scheduler reads model_config.max_model_len, not the
# SchedulerConfig one, so both must agree.
max_model_len=max_model_len,
runner=runner,
)
if mm_encoder_only:
model_config.multimodal_config.mm_encoder_only = True
+80 -2
View File
@@ -20,9 +20,13 @@ from vllm.distributed.device_communicators import pynccl_allocator
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.worker.gpu import cudagraph_utils as gpu_cudagraph_utils
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.dp_utils import dispatch_cg_and_sync_dp
from vllm.v1.worker.gpu.input_batch import InputBuffers
from vllm.v1.worker.gpu.pcp_manager import PCPManager
from vllm.v1.worker.gpu.spec_decode.autoregressive.cudagraph_utils import (
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar import (
cudagraph_utils as spec_cudagraph_utils,
)
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.cudagraph_utils import (
SpeculatorCudaGraphManager,
)
@@ -226,8 +230,10 @@ def test_speculator_capture_preserves_decode_query_bounds(
)
manager = SpeculatorCudaGraphManager.__new__(SpeculatorCudaGraphManager)
manager.max_num_reqs = num_reqs
manager.decode_query_len = uniform_token_count or max_query_len or num_tokens
manager.vllm_config = SimpleNamespace(
parallel_config=SimpleNamespace(data_parallel_size=1)
parallel_config=SimpleNamespace(data_parallel_size=1),
num_speculative_tokens=3,
)
buffers = InputBuffers(num_reqs, num_tokens, torch.device("cpu"))
block_tables = MagicMock()
@@ -488,6 +494,78 @@ def test_dynamic_spec_decode_shared_token_count_stays_reachable(monkeypatch):
), desc
@pytest.mark.parametrize("specialize", [False, True])
def test_speculator_replays_graph_for_runtime_width(monkeypatch, specialize):
"""Equal batch shapes must replay the graph captured for the selected K."""
monkeypatch.setattr(
gpu_cudagraph_utils,
"get_pp_group",
lambda: SimpleNamespace(is_first_rank=True, is_last_rank=True),
)
monkeypatch.setattr(
gpu_cudagraph_utils.current_platform, "get_global_graph_pool", lambda: object()
)
monkeypatch.setattr(gpu_cudagraph_utils, "get_offloader", MagicMock)
monkeypatch.setattr(
spec_cudagraph_utils, "prepare_inputs_to_capture", lambda *a, **kw: ({}, {})
)
forward = MagicMock()
replayed_widths: list[int] = []
def capture(manager, create_forward_fn, progress_bar_desc):
for desc in manager._capture_descs[CUDAGraphMode.FULL]:
create_forward_fn(desc, warmup=False)(CUDAGraphMode.NONE)
k = forward.call_args.kwargs["num_speculative_steps"]
graph = MagicMock()
graph.replay.side_effect = lambda k=k: replayed_widths.append(k)
manager.graphs[desc] = graph
manager._graphs_captured = True
monkeypatch.setattr(gpu_cudagraph_utils.CudaGraphManager, "capture", capture)
manager = spec_cudagraph_utils.SpeculatorCudaGraphManager(
_create_decode_vllm_config(
capture_sizes=[4],
num_speculative_tokens=4,
dynamic_spec_schedule=[(1, 2, 4), (3, 4, 2), (5, 6, 1), (7, 8, 0)],
),
device=torch.device("cpu"),
cudagraph_mode=CUDAGraphMode.FULL_DECODE_ONLY,
decode_query_len=1,
)
manager.capture(
forward,
MagicMock(),
MagicMock(),
MagicMock(),
[],
MagicMock(),
specialize_spec_tokens=specialize,
)
captured_widths = [4, 2] if specialize else [4]
assert [c.kwargs["num_speculative_steps"] for c in forward.call_args_list] == (
captured_widths
)
for k in (2, 4, 2, 3):
desc, _ = dispatch_cg_and_sync_dp(
manager,
num_reqs=3,
num_tokens=3,
uniform_token_count=1,
dp_size=1,
dp_rank=0,
)
desc = manager.specialize_spec_tokens(desc, k)
captured_k = k if specialize else 4
if captured_k in captured_widths:
assert desc.cg_mode == CUDAGraphMode.FULL
assert desc.num_tokens == 4
manager.run_fullgraph(desc)
assert replayed_widths[-1] == captured_k
else:
assert desc.cg_mode == CUDAGraphMode.NONE
@pytest.mark.parametrize(
"decode_query_len,capture_sizes",
[(1, [1, 2, 4, 8]), (2, [2, 4, 8, 16]), (8, [8, 16, 32, 64])],
@@ -245,6 +245,138 @@ class TestFindBudgetGraph:
assert mgr.get_num_graphs_to_capture() == 3
# ---------------------------------------------------------------------------
# _execute_local greedy packing with budget-cliff deferral (no GPU required)
# ---------------------------------------------------------------------------
def _run_packing(
mgr: EncoderCudaGraphManager, specs: list[EncoderItemSpec]
) -> list[tuple[list[int], str, int]]:
"""Run _execute_local with graph replay and postprocess mocked out.
Returns:
(batch_indices, path, token_budget) for every graph replay.
"""
mgr.model = MagicMock()
runs: list[tuple[list[int], str, int]] = []
def fake_run(mm_kwargs, token_budget, path="default", axis_keys=()):
runs.append((list(mm_kwargs["indices"]), path, token_budget))
n_tokens = sum(
specs[i].get_path_output_tokens(path) for i in mm_kwargs["indices"]
)
return torch.zeros(n_tokens, 32)
def fake_postprocess(
graph_outputs,
batch_indices,
per_item_out_tokens,
outputs_by_orig_idx,
clone,
batch_mm_kwargs,
):
for i in batch_indices:
outputs_by_orig_idx[i] = torch.zeros(per_item_out_tokens[i], 32)
mgr.model.postprocess_encoder_output = fake_postprocess
with (
patch.object(mgr, "_get_item_specs", lambda mm_kwargs: specs),
patch.object(
mgr,
"_select_items",
lambda mm_kwargs, indices: ({"indices": indices}, ()),
),
patch.object(mgr, "_run_budget_graph", fake_run),
):
result = mgr._execute_local({})
assert len(result) == len(specs)
return runs
class TestExecuteLocalPacking:
"""Greedy packing defers items that cross a budget cliff."""
@staticmethod
def _spec(tokens: int) -> EncoderItemSpec:
return EncoderItemSpec(input_size=tokens, output_tokens=tokens)
def test_cliff_deferral_splits_batch(self):
# Merging would force 4200 tokens into the 8192 budget; deferring
# the 4000-token item costs 256 + 4096 instead.
mgr = _make_manager_with_budgets([256, 4096, 8192])
runs = _run_packing(mgr, [self._spec(4000), self._spec(200)])
assert runs == [([1], "default", 256), ([0], "default", 4096)]
def test_tie_does_not_defer(self):
# 4096 + 4096 ties the merged 8192 budget; merging wins because it
# saves one replay.
mgr = _make_manager_with_budgets([256, 4096, 8192])
runs = _run_packing(mgr, [self._spec(4000), self._spec(4000)])
assert runs == [([0, 1], "default", 8192)]
def test_deferral_requires_item_outweighing_batch(self):
# The third 1366-token item would save budget if deferred (4096+2048
# < 8192) but is smaller than the current batch (4096), so it merges:
# deferring mid-size items fragments flood packing into extra replays.
mgr = _make_manager_with_budgets([256, 2048, 4096, 8192])
runs = _run_packing(mgr, [self._spec(1366)] * 3)
assert runs == [([0, 1, 2], "default", 8192)]
def test_packing_without_cliff_unchanged(self):
mgr = _make_manager_with_budgets([256, 4096])
runs = _run_packing(mgr, [self._spec(100), self._spec(100)])
assert runs == [([0, 1], "default", 256)]
def test_small_items_split_to_avoid_cliff(self):
# Merging 3+ items of 100 tokens crosses 256 -> 4096; splitting
# into pairs costs 256 + 256 < 4096.
mgr = _make_manager_with_budgets([256, 4096])
runs = _run_packing(mgr, [self._spec(100)] * 4)
assert runs == [([0, 1], "default", 256), ([2, 3], "default", 256)]
def test_max_batch_size_split_unchanged(self):
mgr = _make_manager_with_budgets([1024, 4096])
mgr.max_batch_size = 3
runs = _run_packing(mgr, [self._spec(100)] * 4)
assert runs == [([0, 1, 2], "default", 1024), ([3], "default", 1024)]
def test_oversized_item_still_falls_back_to_eager(self):
mgr = _make_manager_with_budgets([256, 4096])
runs = _run_packing(mgr, [self._spec(100), self._spec(9000)])
assert runs == [([0], "default", 256)]
assert mgr.graph_misses == 1
def test_multi_path_deferral_skips_zero_token_paths(self):
mgr = _make_manager_with_budgets([256, 4096, 8192])
mgr.path_token_budgets = {
"a": [0, 256, 4096, 8192],
"b": [256, 4096, 8192],
}
specs = [
EncoderItemSpec(
input_size=300,
output_tokens=300,
path_output_tokens={"a": 200, "b": 100},
),
EncoderItemSpec(
input_size=4000,
output_tokens=4000,
path_output_tokens={"a": 0, "b": 4000},
),
]
runs = _run_packing(mgr, specs)
# Path b alone triggers deferral (256 + 4096 < 8192); the deferred
# item has zero tokens on path a, so that path is skipped.
assert runs == [
([0], "a", 256),
([0], "b", 256),
([1], "b", 4096),
]
# ---------------------------------------------------------------------------
# get_cumulative_stats
# ---------------------------------------------------------------------------
+25 -4
View File
@@ -132,6 +132,26 @@ async def test_load(
)
after.callback(engine.shutdown)
# The first request an engine serves pays a few hundred milliseconds of
# one-off setup, and while it does the engine holds the requests already
# routed to it while reporting itself idle, which is enough to skew the
# split asserted on below. Pay it on every engine first, then measure.
await asyncio.gather(
*(
generate(
engine,
f"warmup-{rank}",
prompt,
output_kind,
max_tokens=1,
data_parallel_rank=rank,
)
for rank in range(DP_SIZE)
)
)
for sl in stats_loggers.values():
sl.finished_req_count = 0
NUM_REQUESTS = 100
NUM_EXPECTED_TOKENS = 10
@@ -699,7 +719,7 @@ async def test_dp_pause_barrier_request_deadlock():
# Drive the staggered barrier. Old code deadlocks here.
try:
await asyncio.wait_for(client.call_utility_async("barrier"), timeout=30)
except asyncio.TimeoutError:
except TimeoutError:
for t in mid_barrier_tasks:
t.cancel()
pytest.fail(
@@ -727,12 +747,13 @@ async def test_dp_pause_wait_mode_drains_in_flight():
prompt=DP_PAUSE_PROMPT,
params=SamplingParams(max_tokens=64),
)
# Wait for the first output, so drain has something to observe: a
# request still queued holds no blocks and is not waited on.
out = await asyncio.wait_for(collector.get(), timeout=30)
await engine.pause_generation(mode="wait")
assert await engine.is_paused()
while True:
while not out.finished:
out = await asyncio.wait_for(collector.get(), timeout=30)
if out.finished:
break
await engine.resume_generation()
async for out in engine.generate(
+7 -4
View File
@@ -110,8 +110,10 @@ def check_first_divergence(
# 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}"
# Same FP32 rounding slack as above, applied to the upper bound.
assert gap <= tolerance.greedy_atol + 1e-5, (
f"{detail}: divergence exceeds near-tie bound="
f"{tolerance.greedy_atol} (+1e-5 slack)"
)
@@ -201,9 +203,10 @@ def check_greedy_token(
)
best = int(logits.argmax())
gap = float(logits[best] - logits[token])
assert gap <= tolerance.greedy_atol, (
# FP32 rounding can push a true near-tie fractionally past the bound.
assert gap <= tolerance.greedy_atol + 1e-5, (
f"{context}: selected token={token}, reference best={best}, "
f"logit gap={gap}, bound={tolerance.greedy_atol}"
f"logit gap={gap}, bound={tolerance.greedy_atol} (+1e-5 slack)"
)
return gap
@@ -271,9 +271,9 @@ def run_tests(
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
)
# Preemption recomputes requests and loses n-gram drafts,
# so allow a larger drop there.
relative_drop = 0.10 if test_preemption else 0.05
assert actual >= baseline * (1 - relative_drop), (
f"{context}: acceptance={actual}, baseline={baseline}"
)
+16 -4
View File
@@ -25,6 +25,12 @@ PROMPTS = [
"The capital of France is",
"Once upon a time, in a small village,",
]
# The NVFP4 model is not reproducible across engine instances; these prompts
# avoid near-ties and decode confidently past the replay window.
FLASHINFER_PROMPTS = [
"The capital of France is",
"It was the best of times, it was the worst of times,",
]
@pytest.fixture(autouse=True)
@@ -43,6 +49,7 @@ def _check_replayssm_parity(
*,
tensor_parallel_size=1,
mamba_backend: str = "triton",
prompts: list[str] = PROMPTS,
name_1: str = "replayssm",
expected_v2: bool | None = None,
):
@@ -60,7 +67,7 @@ def _check_replayssm_parity(
with vllm_runner(model_name, **common) as llm:
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)
baseline = llm.generate_greedy_logprobs(prompts, max_tokens=32, num_logprobs=5)
with vllm_runner(
model_name,
use_replayssm=True,
@@ -69,7 +76,7 @@ def _check_replayssm_parity(
) as llm:
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)
replay = llm.generate_greedy_logprobs(prompts, max_tokens=32, num_logprobs=5)
check_logprobs_close(
outputs_0_lst=baseline,
@@ -105,6 +112,7 @@ def test_replayssm_flashinfer_decode_matches_baseline(
vllm_runner,
model_name,
mamba_backend="flashinfer",
prompts=FLASHINFER_PROMPTS,
name_1="replayssm_flashinfer",
expected_v2=use_v2_model_runner,
)
@@ -127,7 +135,9 @@ def test_replayssm_flashinfer_spec_decode_matches_baseline(vllm_runner, model_na
},
)
with vllm_runner(model_name, mamba_backend="flashinfer", **common) as llm:
baseline = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
baseline = llm.generate_greedy_logprobs(
FLASHINFER_PROMPTS, max_tokens=32, num_logprobs=5
)
with vllm_runner(
model_name,
use_replayssm=True,
@@ -135,7 +145,9 @@ def test_replayssm_flashinfer_spec_decode_matches_baseline(vllm_runner, model_na
mamba_backend="flashinfer",
**common,
) as llm:
replay = llm.generate_greedy_logprobs(PROMPTS, max_tokens=32, num_logprobs=5)
replay = llm.generate_greedy_logprobs(
FLASHINFER_PROMPTS, max_tokens=32, num_logprobs=5
)
check_logprobs_close(
outputs_0_lst=baseline,
@@ -1,10 +1,12 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import uuid
from pathlib import Path
import pytest
import vllm.distributed.ec_transfer.ec_connector.cpu.scheduler as sched_mod
import vllm.distributed.nixl_utils as nixl_utils
from tests.v1.ec_connector.unit.utils import create_ec_vllm_config
from vllm.config.ec_transfer import ECTransferConfig
from vllm.distributed.ec_transfer.ec_connector.cpu.ec_shared_region import (
@@ -57,6 +59,72 @@ def test_string_false_in_extra_config_leaves_nixl_off(monkeypatch):
s.shutdown()
@pytest.mark.cpu_test
def test_missing_nixl_releases_shared_region(monkeypatch):
"""A failed constructor leaves no scheduler for the caller to shut down."""
# Import before patching to avoid caching the missing-NIXL values.
from vllm.distributed.ec_transfer.ec_connector.cpu.data import nixl # noqa: F401
region = _region()
monkeypatch.setattr(sched_mod, "create_ec_shared_region", lambda cfg: region)
monkeypatch.setattr(nixl_utils, "NixlWrapper", None)
monkeypatch.setattr(nixl_utils, "nixl_agent_config", None)
cfg = create_ec_vllm_config(ec_role="ec_both")
cfg.ec_transfer_config.ec_connector_extra_config["ec_enable_nixl"] = True
try:
with pytest.raises(RuntimeError, match="ec_enable_nixl requires NIXL"):
ECCPUScheduler(cfg)
assert not Path(region._mmap_path).exists()
assert region._fd is None
assert region._mmap_obj is None
finally:
region.cleanup()
@pytest.mark.cpu_test
def test_control_transport_failure_releases_nixl_and_shared_region(monkeypatch):
import vllm.distributed.ec_transfer.ec_connector.cpu.control.zmq as zmq_mod
import vllm.distributed.ec_transfer.ec_connector.cpu.data.nixl as data_mod
class RegisteredData:
registered = True
def deregister(self):
self.registered = False
data = RegisteredData()
error = RuntimeError("control transport failed")
def fail_control_transport():
raise error
region = _region()
monkeypatch.setattr(sched_mod, "create_ec_shared_region", lambda cfg: region)
monkeypatch.setattr(nixl_utils, "NixlWrapper", object())
monkeypatch.setattr(nixl_utils, "nixl_agent_config", object())
monkeypatch.setattr(data_mod, "NixlDataTransport", lambda **kwargs: data)
monkeypatch.setattr(zmq_mod, "ZmqClientTransport", fail_control_transport)
cfg = create_ec_vllm_config(ec_role="ec_consumer")
cfg.model_config.hf_config = None
cfg.model_config.get_inputs_embeds_size.return_value = 8
cfg.model_config.model = "test-model"
cfg.ec_transfer_config.ec_connector_extra_config["ec_enable_nixl"] = True
try:
with pytest.raises(RuntimeError, match="control transport failed") as exc:
ECCPUScheduler(cfg)
assert exc.value is error
assert not data.registered
assert not Path(region._mmap_path).exists()
assert region._fd is None
assert region._mmap_obj is None
finally:
region.cleanup()
@pytest.mark.skipif(NixlWrapper is None, reason="Requires NIXL package")
def test_gate_on_wires_data_transport_and_producer_session(monkeypatch):
# Port 0 lets the OS pick an ephemeral port so the real ZMQ ROUTER bind
+283 -9
View File
@@ -2,8 +2,10 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import asyncio
import threading
import time
from contextlib import ExitStack
from http import HTTPStatus
from unittest.mock import AsyncMock, MagicMock, call
import pytest
@@ -11,7 +13,7 @@ import pytest
import vllm.v1.engine.async_llm as async_llm_module
from vllm import SamplingParams
from vllm.assets.image import ImageAsset
from vllm.config import LoggingConfig, VllmConfig
from vllm.config import LoggingConfig, ProfilerConfig, VllmConfig
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.entrypoints.openai.chat_completion.protocol import (
ChatCompletionRequest,
@@ -20,10 +22,11 @@ from vllm.entrypoints.openai.chat_completion.protocol import (
from vllm.entrypoints.openai.chat_completion.serving import OpenAIServingChat
from vllm.entrypoints.openai.models.protocol import BaseModelPath
from vllm.entrypoints.openai.models.serving import OpenAIServingModels
from vllm.exceptions import VLLMValidationError
from vllm.exceptions import ProfilerAlreadyActiveError, VLLMValidationError
from vllm.inputs import PromptType
from vllm.outputs import RequestOutput
from vllm.platforms import current_platform
from vllm.profiler.wrapper import WorkerProfiler
from vllm.sampling_params import RequestOutputKind
from vllm.utils.torch_utils import set_default_torch_num_threads
from vllm.v1.engine.async_llm import AsyncLLM
@@ -87,13 +90,19 @@ def _mock_async_llm_dependencies(monkeypatch: pytest.MonkeyPatch):
return engine_core
def test_cuda_profiler_requests_reach_engine_core(monkeypatch: pytest.MonkeyPatch):
def _mock_vllm_config() -> MagicMock:
vllm_config = MagicMock()
vllm_config.logging_config = LoggingConfig()
vllm_config.observability_config.otlp_traces_endpoint = None
vllm_config.scheduler_config.stream_interval = 1
return vllm_config
def test_cuda_profiler_requests_reach_engine_core(monkeypatch: pytest.MonkeyPatch):
vllm_config = _mock_vllm_config()
vllm_config.profiler_config.profiler = "cuda"
vllm_config.profiler_config.ignore_frontend = False
vllm_config.profiler_config.should_profile_frontend = False
engine_core = _mock_async_llm_dependencies(monkeypatch)
engine = AsyncLLM(vllm_config, MagicMock(), log_stats=False)
@@ -105,22 +114,22 @@ def test_cuda_profiler_requests_reach_engine_core(monkeypatch: pytest.MonkeyPatc
asyncio.run(profile())
assert engine.profiler is None
engine_core.profile_async.assert_has_awaits([call(True, None), call(False)])
engine_core.profile_async.assert_has_awaits(
[call(True, None, None, None), call(False)]
)
def test_cuda_only_torch_profiler_skips_frontend_cpu_trace(
monkeypatch: pytest.MonkeyPatch,
):
vllm_config = MagicMock()
vllm_config.logging_config = LoggingConfig()
vllm_config.observability_config.otlp_traces_endpoint = None
vllm_config.scheduler_config.stream_interval = 1
vllm_config = _mock_vllm_config()
vllm_config.profiler_config.profiler = "torch"
vllm_config.profiler_config.ignore_frontend = False
vllm_config.profiler_config.torch_profiler_activities = ["CUDA"]
vllm_config.profiler_config.should_profile_frontend = False
_mock_async_llm_dependencies(monkeypatch)
profiler = MagicMock()
monkeypatch.setattr(async_llm_module, "TorchProfilerWrapper", profiler)
monkeypatch.setattr(async_llm_module, "create_frontend_profiler", profiler)
engine = AsyncLLM(vllm_config, MagicMock(), log_stats=False)
@@ -128,6 +137,271 @@ def test_cuda_only_torch_profiler_skips_frontend_cpu_trace(
profiler.assert_not_called()
def test_profile_forwards_overrides_rejects_duplicate_and_allows_restart(
monkeypatch: pytest.MonkeyPatch,
):
vllm_config = _mock_vllm_config()
vllm_config.profiler_config.should_profile_frontend = False
engine_core = _mock_async_llm_dependencies(monkeypatch)
engine = AsyncLLM(vllm_config, MagicMock(), log_stats=False)
async def profile():
for kwargs in (
{"profile_prefix": "../trace"},
{"delay_iterations": -1},
{"max_iterations": -1},
):
with pytest.raises(ValueError):
await engine.start_profile(**kwargs)
await engine.start_profile(
"session",
delay_iterations=5,
max_iterations=2,
)
with pytest.raises(ProfilerAlreadyActiveError) as exc_info:
await engine.start_profile("duplicate")
assert exc_info.value.http_status == HTTPStatus.CONFLICT
await engine.stop_profile()
await engine.start_profile("next-session")
await engine.stop_profile()
asyncio.run(profile())
engine_core.profile_async.assert_has_awaits(
[
call(True, "session", 5, 2),
call(False),
call(True, "next-session", None, None),
call(False),
]
)
def test_stop_profile_waits_for_inflight_start(monkeypatch: pytest.MonkeyPatch):
vllm_config = _mock_vllm_config()
engine_core = _mock_async_llm_dependencies(monkeypatch)
events: list[str] = []
frontend_profiler = MagicMock()
frontend_profiler.start.side_effect = lambda: events.append("frontend_start")
frontend_profiler.stop.side_effect = lambda: events.append("frontend_stop")
engine = AsyncLLM(
vllm_config,
MagicMock(),
log_stats=False,
profiler=frontend_profiler,
)
async def profile():
start_rpc_entered = asyncio.Event()
release_start_rpc = asyncio.Event()
async def profile_async(is_start, *args):
if is_start:
start_rpc_entered.set()
await release_start_rpc.wait()
events.append("engine_start_done")
else:
events.append("engine_stop")
engine_core.profile_async.side_effect = profile_async
start_task = asyncio.create_task(engine.start_profile())
await start_rpc_entered.wait()
stop_task = asyncio.create_task(engine.stop_profile())
await asyncio.sleep(0)
release_start_rpc.set()
await asyncio.wait_for(asyncio.gather(start_task, stop_task), timeout=5)
asyncio.run(profile())
assert events[:2] == ["engine_start_done", "frontend_start"]
assert sorted(events[2:]) == ["engine_stop", "frontend_stop"]
assert engine._profile_session_active is False
@pytest.mark.parametrize("failure", ["error", "cancel"])
def test_interrupted_engine_profile_start_skips_frontend_profiler(
monkeypatch: pytest.MonkeyPatch, failure: str
):
"""The frontend trace starts only after the engine start succeeds. A
cancelled start may still reach the engine, so it keeps the session active
until /stop_profile."""
vllm_config = _mock_vllm_config()
engine_core = _mock_async_llm_dependencies(monkeypatch)
frontend_profiler = MagicMock()
engine = AsyncLLM(
vllm_config,
MagicMock(),
log_stats=False,
profiler=frontend_profiler,
)
async def profile():
start_rpc_entered = asyncio.Event()
async def profile_async(is_start, *args):
if not is_start:
return
start_rpc_entered.set()
if failure == "error":
raise RuntimeError("engine profiler failed to start")
await asyncio.Event().wait()
engine_core.profile_async.side_effect = profile_async
start_task = asyncio.create_task(engine.start_profile())
await start_rpc_entered.wait()
if failure == "cancel":
start_task.cancel()
expected = RuntimeError if failure == "error" else asyncio.CancelledError
with pytest.raises(expected):
await start_task
assert engine._profile_session_active is (failure == "cancel")
await engine.stop_profile()
assert engine._profile_session_active is False
asyncio.run(profile())
frontend_profiler.start.assert_not_called()
class _BlockingStartProfiler(WorkerProfiler):
def __init__(self) -> None:
self.in_start = threading.Event()
self.release_start = threading.Event()
self.stop_call_count = 0
super().__init__(
ProfilerConfig(profiler="torch", torch_profiler_dir="/tmp/mock")
)
def _start(self) -> None:
self.in_start.set()
if not self.release_start.wait(timeout=5):
raise TimeoutError("start was never released")
def _stop(self) -> None:
self.stop_call_count += 1
def test_stop_after_cancelled_frontend_start_stops_frontend_profiler(
monkeypatch: pytest.MonkeyPatch,
):
"""Cancelling start_profile while the frontend profiler is starting keeps
the session active, and the next stop_profile still stops the backend."""
vllm_config = _mock_vllm_config()
engine_core = _mock_async_llm_dependencies(monkeypatch)
frontend_profiler = _BlockingStartProfiler()
engine = AsyncLLM(
vllm_config,
MagicMock(),
log_stats=False,
profiler=frontend_profiler,
)
async def profile():
try:
start_task = asyncio.create_task(engine.start_profile())
assert await asyncio.to_thread(frontend_profiler.in_start.wait, 5)
start_task.cancel()
with pytest.raises(asyncio.CancelledError):
await start_task
assert engine._profile_session_active is True
stop_task = asyncio.create_task(engine.stop_profile())
done, _ = await asyncio.wait({stop_task}, timeout=0.1)
assert not done, "stop_profile did not wait for the in-flight start"
frontend_profiler.release_start.set()
await asyncio.wait_for(stop_task, timeout=5)
finally:
frontend_profiler.release_start.set()
asyncio.run(profile())
assert frontend_profiler.stop_call_count == 1
assert frontend_profiler._active is False
assert frontend_profiler._running is False
assert engine._profile_session_active is False
assert engine_core.profile_async.await_args_list == [
call(True, None, None, None),
call(False),
]
def test_multi_client_profile_uses_idempotent_engine_requests(
monkeypatch: pytest.MonkeyPatch, tmp_path
):
vllm_config = _mock_vllm_config()
vllm_config.profiler_config = ProfilerConfig(
profiler="torch",
torch_profiler_dir=str(tmp_path),
torch_profiler_activities=["CPU"],
)
engine_core = _mock_async_llm_dependencies(monkeypatch)
profiler = MagicMock()
monkeypatch.setattr(async_llm_module, "create_frontend_profiler", profiler)
engines = [
AsyncLLM(
vllm_config,
MagicMock(),
log_stats=False,
client_count=2,
client_index=client_index,
)
for client_index in range(2)
]
assert all(engine.profiler is None for engine in engines)
profiler.assert_not_called()
async def profile():
await engines[0].start_profile()
await engines[1].start_profile()
await engines[1].stop_profile()
await engines[0].start_profile()
asyncio.run(profile())
engine_core.profile_async.assert_has_awaits(
[
call(True, None, None, None),
call(True, None, None, None),
call(False),
call(True, None, None, None),
]
)
def test_frontend_profiler_ignores_worker_iteration_bounds(
monkeypatch: pytest.MonkeyPatch, tmp_path
):
vllm_config = _mock_vllm_config()
vllm_config.profiler_config = ProfilerConfig(
profiler="torch",
torch_profiler_dir=str(tmp_path),
torch_profiler_activities=["CPU", "CUDA"],
delay_iterations=5,
max_iterations=2,
wait_iterations=3,
warmup_iterations=1,
)
_mock_async_llm_dependencies(monkeypatch)
profiler = MagicMock()
monkeypatch.setattr("vllm.profiler.wrapper.TorchProfilerWrapper", profiler)
engine = AsyncLLM(vllm_config, MagicMock(), log_stats=False)
frontend_config = profiler.call_args.args[0]
assert frontend_config.delay_iterations == 0
assert frontend_config.max_iterations == 0
assert frontend_config.wait_iterations == 0
assert frontend_config.warmup_iterations == 0
assert engine.profiler is profiler.return_value
async def generate(
engine: AsyncLLM,
request_id: str,
@@ -13,8 +13,9 @@ from unittest.mock import Mock
import pytest
import ray
import zmq
from torch.distributed import TCPStore
from vllm.utils.network_utils import make_zmq_socket, split_zmq_path
from vllm.utils.network_utils import get_open_port, make_zmq_socket, split_zmq_path
from vllm.v1.engine.core import EngineCoreActorMixin
from vllm.v1.engine.core_client import BackgroundResources
from vllm.v1.engine.utils import (
@@ -22,7 +23,7 @@ from vllm.v1.engine.utils import (
EngineZmqAddresses,
_dp_nodes_master_first,
_node_ip_from_resources,
get_engine_zmq_addresses,
bind_engine_zmq_listeners,
launch_core_engines,
)
from vllm.v1.utils import APIServerProcessManager
@@ -66,35 +67,27 @@ class _StubEngineCoreActor(EngineCoreActorMixin):
# Module-level stub worker for the Ray-DP regression test. Must be importable
# by ``multiprocessing.spawn`` (no closures, no nesting). Mirrors the worker
# in ``tests/entrypoints/test_api_server_process_manager.py``.
def _bind_and_report_worker(listen_address, sock, args, client_config):
"""Bind ROUTER/PULL with a kernel-assigned port, report the actual
endpoints back via ``actual_address_pipe``, then exit."""
# by ``multiprocessing.spawn`` (no closures, no nesting).
def _adopt_listener_worker(listen_address, sock, args, client_config):
"""Adopt the supervisor-bound ROUTER/PULL listeners, then exit."""
ctx = zmq.Context()
try:
in_sock = make_zmq_socket(
ctx, client_config["input_address"], zmq.ROUTER, bind=True
ctx,
client_config["input_address"],
zmq.ROUTER,
bind=True,
listener=client_config["input_listener"],
)
out_sock = make_zmq_socket(
ctx, client_config["output_address"], zmq.PULL, bind=True
ctx,
client_config["output_address"],
zmq.PULL,
bind=True,
listener=client_config["output_listener"],
)
try:
pipe = client_config["actual_address_pipe"]
try:
pipe.send(
{
"input_address": in_sock.getsockopt(zmq.LAST_ENDPOINT).decode(),
"output_address": out_sock.getsockopt(
zmq.LAST_ENDPOINT
).decode(),
}
)
finally:
pipe.close()
finally:
in_sock.close(linger=0)
out_sock.close(linger=0)
in_sock.close(linger=0)
out_sock.close(linger=0)
finally:
ctx.term()
@@ -134,6 +127,72 @@ def _make_addresses() -> EngineZmqAddresses:
)
@pytest.mark.parametrize(
("overrides", "expect_store"),
[
({"data_parallel_backend": "mp"}, True),
({}, True),
(
{
"data_parallel_backend": "mp",
"data_parallel_rank": 1,
"local_engines_only": True,
},
False,
),
({"data_parallel_backend": "mp", "data_parallel_rank_local": 0}, False),
({"data_parallel_backend": "mp", "enable_elastic_ep": True}, False),
({"data_parallel_backend": "mp", "data_parallel_size": 1}, False),
],
ids=["mp", "ray", "non-master-node", "offline", "elastic-ep", "single-engine"],
)
def test_coordination_store_held_only_by_the_online_dp_master(
monkeypatch: pytest.MonkeyPatch, overrides: dict[str, Any], expect_store: bool
) -> None:
"""The DP master node holds a coordination store for both engine backends,
so engines there pick world-group ports at bind time. Every other
deployment keeps the pre-allocated ports and must not hold one."""
class FakeManager:
def __init__(self, **kwargs) -> None:
self.kwargs = kwargs
vllm_config = _make_vllm_config_ray_dp_multinode()
parallel_config = vllm_config.parallel_config
for name, value in overrides.items():
setattr(parallel_config, name, value)
# A fresh port per case so a lingering handshake socket cannot fail the next.
parallel_config.data_parallel_rpc_port = get_open_port()
parallel_config._coord_store_port = 0
monkeypatch.setattr("vllm.v1.engine.utils.CoreEngineProcManager", FakeManager)
monkeypatch.setattr("vllm.v1.engine.utils.CoreEngineActorManager", FakeManager)
monkeypatch.setattr(
"vllm.v1.engine.utils.wait_for_engine_startup", lambda *args, **kwargs: None
)
with launch_core_engines(
vllm_config,
executor_class=_DummyExecutor,
log_stats=False,
addresses=_make_addresses(),
) as engine_launch:
assert engine_launch.engine_manager is not None
if not expect_store:
assert not parallel_config._coord_store_port
return
assert parallel_config._coord_store_port
# Engines look the store up while they start, so it must be reachable
# for as long as this frame is alive.
client = TCPStore(
parallel_config.data_parallel_master_ip,
parallel_config._coord_store_port,
is_master=False,
wait_for_workers=False,
)
client.set("probe", b"1")
assert client.get("probe") == b"1"
def _make_cpu_placement_group():
pg = ray.util.placement_group(
[{"CPU": 0.001}, {"CPU": 1.0}],
@@ -260,17 +319,9 @@ def test_ray_dp_addresses_resolved_before_actor_creation(
``launch_core_engines`` Ray branch pickles ``addresses`` into each engine
actor at ``.remote()`` time, and ``EngineCoreActorMixin._perform_handshakes``
is a no-op, so the actor uses that pickled snapshot for the rest of its
life. If ``run_multi_api_server`` allocates ``addresses`` as
``tcp://host:0`` placeholders (its default), the actors hold placeholders
forever and DEALER-connect to port 0 — ZMQ ``connect`` is async and does
not raise, so the failure mode is a deterministic hang.
The Ray-DP carve-out in ``run_multi_api_server`` forces
``defer_api_server_ports=False`` when ``data_parallel_backend == "ray"``
so addresses are pre-allocated in the driver and Ray pickles real ports
into each actor. This test mirrors that call-site logic and asserts the
actors hold real (non-placeholder) endpoints. If the carve-out is
removed without an alternative fix, the test fails.
life. The supervisor therefore binds the frontend listeners before actor
construction and Ray pickles their resolved endpoints. This test asserts
that each actor holds real (non-placeholder) endpoints.
"""
created_placement_groups: list[Any] = []
@@ -289,15 +340,10 @@ def test_ray_dp_addresses_resolved_before_actor_creation(
vllm_config = _make_vllm_config_ray_dp_multinode()
# Mirror run_multi_api_server's address-allocation logic. The Ray DP
# carve-out forces pre-allocation so the addresses pickled into engine
# actors at .remote() time are real, not ``tcp://host:0``.
is_ray_dp = vllm_config.parallel_config.data_parallel_backend == "ray"
addresses = get_engine_zmq_addresses(
vllm_config,
num_api_servers=2,
defer_api_server_ports=not is_ray_dp,
)
# Mirror run_multi_api_server: bind listeners in the supervisor so the
# addresses pickled into Ray actors contain kernel-assigned ports.
listeners = bind_engine_zmq_listeners(vllm_config, num_api_servers=2)
addresses = listeners.addresses
sock = socket.socket()
engine_manager: CoreEngineActorManager | None = None
@@ -314,26 +360,17 @@ def test_ray_dp_addresses_resolved_before_actor_creation(
engine_manager = engine_launch.engine_manager
assert isinstance(engine_manager, CoreEngineActorManager)
# API-server children bind to the pre-allocated ports.
# API-server children adopt the already-bound listener FDs.
api_server_manager = APIServerProcessManager(
listen_address="tcp://127.0.0.1:0",
sock=sock,
args="test_args",
num_servers=2,
input_addresses=addresses.inputs,
output_addresses=addresses.outputs,
target_server_fn=_bind_and_report_worker,
input_listeners=listeners.inputs,
output_listeners=listeners.outputs,
target_server_fn=_adopt_listener_worker,
)
# run_multi_api_server skips ``gather_actual_addresses`` for
# Ray DP (addresses are already real). Mirror that.
if not is_ray_dp:
actual_inputs, actual_outputs = (
api_server_manager.gather_actual_addresses(timeout=15.0)
)
addresses.inputs = actual_inputs
addresses.outputs = actual_outputs
# Snapshot what each Ray actor actually holds.
actors = (
engine_manager.local_engine_actors + engine_manager.remote_engine_actors
@@ -360,9 +397,9 @@ def test_ray_dp_addresses_resolved_before_actor_creation(
assert scheme == "tcp", url
assert port and int(port) > 0, (
f"Ray actor was pickled with placeholder address {url!r}; "
"``run_multi_api_server`` must pre-allocate ports for the "
"Ray DP backend so the actors hold real endpoints by the "
"time they DEALER-connect. See PR #42585 / Ray-DP "
"``run_multi_api_server`` must bind frontend listeners before "
"constructing Ray DP actors so they hold real endpoints when "
"they DEALER-connect. See PR #42585 / Ray-DP "
"multi-API-server regression."
)
+109
View File
@@ -0,0 +1,109 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""The DP world group picks its port when it binds, not ahead of time."""
import multiprocessing as mp
import socket
import traceback
from multiprocessing.queues import Queue
import pytest
import torch
from vllm.distributed.utils import create_tcp_store
from vllm.utils.network_utils import get_open_port
RESULT_TIMEOUT_S = 240
def _join_dp_world_group(
dp_rank: int, coord_store_port: int, dp_master_port: int, result: Queue
) -> None:
"""Bring up one DP rank of the world group and report what it saw."""
try:
import torch.distributed as dist
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.config.parallel import ParallelConfig
from vllm.distributed.parallel_state import init_distributed_environment
parallel_config = ParallelConfig(
data_parallel_size=2, data_parallel_rank=dp_rank
)
parallel_config.data_parallel_master_ip = "127.0.0.1"
parallel_config._data_parallel_master_port_list = [dp_master_port]
parallel_config._coord_store_port = coord_store_port
with set_current_vllm_config(VllmConfig(parallel_config=parallel_config)):
init_distributed_environment(
world_size=1, rank=0, local_rank=0, backend="gloo"
)
reduced = torch.tensor([dp_rank + 1])
dist.all_reduce(reduced)
result.put((dp_rank, int(reduced.item()), None))
except Exception:
result.put((dp_rank, None, traceback.format_exc()))
@pytest.mark.skipif(
not torch.distributed.is_gloo_available(), reason="gloo backend required"
)
@pytest.mark.parametrize("with_coord_store", [True, False])
def test_dp_world_group_survives_a_taken_preallocated_port(with_coord_store: bool):
"""With a coordination store, the two ranks agree on a port the group binds
itself, so a pre-allocated port taken in the meantime cannot stop startup.
Without one, the pre-allocated port is still used as before.
"""
squatter = None
coord_store = None
try:
if with_coord_store:
# Something else grabbed the pre-allocated port after it was picked.
squatter = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
squatter.bind(("127.0.0.1", 0))
squatter.listen(1)
dp_master_port = squatter.getsockname()[1]
coord_store = create_tcp_store(
"127.0.0.1", 0, is_master=True, world_size=-1, wait_for_workers=False
)
coord_store_port = coord_store.port
else:
dp_master_port = get_open_port()
coord_store_port = 0
ctx = mp.get_context("spawn")
result: Queue = ctx.Queue()
procs = [
ctx.Process(
target=_join_dp_world_group,
args=(dp_rank, coord_store_port, dp_master_port, result),
)
for dp_rank in range(2)
]
for proc in procs:
proc.start()
reports: list[tuple[int, int | None, str | None]] = []
try:
while len(reports) < len(procs):
reports.append(result.get(timeout=RESULT_TIMEOUT_S))
if reports[-1][2] is not None:
break # the peer would wait on this rank; do not wait for it
finally:
for proc in procs:
proc.join(timeout=30)
if proc.is_alive():
proc.kill()
for dp_rank, reduced, error in sorted(reports):
assert error is None, f"DP rank {dp_rank} failed:\n{error}"
# Both ranks joined the same group: 1 + 2 over the two ranks.
assert reduced == 3, f"DP rank {dp_rank} all-reduced to {reduced}"
if with_coord_store:
assert coord_store is not None
bound_port = int(coord_store.get("world_pg_port").decode())
assert bound_port != dp_master_port
finally:
if squatter is not None:
squatter.close()
@@ -0,0 +1,224 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
#
# Regression tests for termination signals that arrive while EngineCoreProc is
# still being constructed.
#
# When this fix matters
# ---------------------
# Engine shutdown is driven from the frontend. If a frontend process dies while
# EngineCore is still starting up, the process manager sends SIGTERM to its
# children and force kills whatever is still alive after a short timeout (see
# shutdown in vllm/v1/utils.py). Construction is slow - it spawns the executor
# processes, loads weights, profiles and captures CUDA graphs - so that
# shutdown often lands inside the construction window. Bigger models and more
# ranks widen the window. This is the case PR 52299 (follow up to 43417) has to
# survive: 43417 stops EngineCore from exiting silently, but the request itself
# still has to outlive the construction window.
#
# run_engine_core installs the signal handler before engine_core exists, so in
# that window the handler runs with engine_core == None. Losing the request
# there is permanent, not a delay: shutdown_state stays RUNNING, and
# wakeup_engine returns early while consuming the one-shot SignalCallback. The
# busy loop then starts RUNNING and blocks on input_queue forever, so no later
# signal can wake it. Graceful shutdown is gone for good and the process only
# stops when something force kills it, which skips executor shutdown and GPU
# release. In a log this shows up as the signal being received, followed by a
# force kill of EngineCore after the process manager timeout.
#
# What these tests pin
# --------------------
# A request arriving in the window must be remembered somewhere other than
# engine_core, applied before run_busy_loop starts, and must not consume the
# one-shot wakeup callback, so a later signal can still wake an idle loop.
import queue
import signal as signal_module
from typing import Any
from vllm.v1.engine import EngineCoreRequestType
from vllm.v1.engine import core as core_module
from vllm.v1.engine.core import EngineCoreProc, EngineShutdownState
WAKEUP_ITEM = (EngineCoreRequestType.WAKEUP, None)
CONSTRUCTION_SIGNAL = signal_module.SIGTERM
class _FakeSignal:
# Minimal stand-in for the signal module. It records the installed handler
# so the test can fire it by hand, and avoids touching the real process
# signal disposition. Signals is reused from the real module so the handler
# can still resolve signal.Signals(signum).name.
SIGTERM = signal_module.SIGTERM
SIGINT = signal_module.SIGINT
SIG_DFL = signal_module.SIG_DFL
Signals = signal_module.Signals
def __init__(self):
self.handlers = {}
def signal(self, signum, handler):
self.handlers[signum] = handler
def fire(self):
self.handlers[CONSTRUCTION_SIGNAL](CONSTRUCTION_SIGNAL, None)
class _FakeSignalCallback:
# One-shot stand-in for SignalCallback. The real class runs the callback on
# a dedicated thread and exits after a single trigger, so every later
# trigger is a no-op. Running the callback inline keeps the test
# deterministic instead of depending on thread scheduling.
instances: list["_FakeSignalCallback"] = []
def __init__(self, callback):
self.callback = callback
self.trigger_count = 0
self.consumed = False
self.stopped = False
_FakeSignalCallback.instances.append(self)
def trigger(self):
self.trigger_count += 1
if self.stopped or self.consumed:
return
self.consumed = True
callback, self.callback = self.callback, None
callback()
def stop(self):
self.stopped = True
class _StubParallelConfig:
def __init__(self):
self.data_parallel_size = 1
self.data_parallel_rank_local = 0
self.data_parallel_index = 0
self.data_parallel_rank = 0
self.numa_bind = False
def reconfigure_for_independent_dp_rank(self):
pass
class _StubModelConfig:
is_moe = False
class _StubVllmConfig:
def __init__(self):
self.parallel_config = _StubParallelConfig()
self.model_config = _StubModelConfig()
self.logging_config = None
self.kv_transfer_config = None
self.shutdown_timeout = 0
def _run_engine_core(
monkeypatch,
*,
signal_during_construction=False,
signal_while_idle=False,
):
_FakeSignalCallback.instances.clear()
fake_signal = _FakeSignal()
trace = {}
class StubEngineCoreProc:
def __init__(self, *args, **kwargs):
self.shutdown_state = EngineShutdownState.RUNNING
# Same queue type as EngineCore, so the wakeup path under test is
# the real one.
self.input_queue = queue.Queue[tuple[EngineCoreRequestType, Any]]()
self.vllm_config = kwargs.get("vllm_config")
if signal_during_construction:
# The termination signal lands mid construction, while the
# caller still sees engine_core == None.
fake_signal.fire()
trace["constructed"] = True
def run_busy_loop(self):
# What the real loop sees on its first _handle_shutdown() check.
trace["loop_entered"] = True
trace["state_at_loop_entry"] = self.shutdown_state
if signal_while_idle:
fake_signal.fire()
try:
trace["wakeup"] = self.input_queue.get_nowait()
except queue.Empty:
trace["wakeup"] = None
def shutdown(self):
pass
def _send_engine_dead(self):
pass
def has_work(self):
return False
monkeypatch.setattr(core_module, "signal", fake_signal)
monkeypatch.setattr(core_module, "SignalCallback", _FakeSignalCallback)
monkeypatch.setattr(core_module, "EngineCoreProc", StubEngineCoreProc)
monkeypatch.setattr(core_module, "DPEngineCoreProc", StubEngineCoreProc)
monkeypatch.setattr(core_module, "configure_logging", lambda *a, **k: None)
monkeypatch.setattr(
core_module, "maybe_register_config_serialize_by_value", lambda *a, **k: None
)
monkeypatch.setattr(core_module, "set_process_title", lambda *a, **k: None)
monkeypatch.setattr(core_module, "maybe_init_worker_tracer", lambda *a, **k: None)
monkeypatch.setattr(core_module, "decorate_logs", lambda *a, **k: None)
EngineCoreProc.run_engine_core(vllm_config=_StubVllmConfig())
return trace
def test_signal_during_construction_is_applied_before_loop(monkeypatch):
trace = _run_engine_core(monkeypatch, signal_during_construction=True)
assert trace["constructed"] is True
assert trace["loop_entered"] is True
# The request arrived while engine_core was None, so it could not be stored
# there. It must still be applied before run_busy_loop starts, otherwise the
# loop comes up as RUNNING, the shutdown is silently dropped, and force kill
# becomes the only way out.
assert trace["state_at_loop_entry"] == EngineShutdownState.REQUESTED, (
"a signal received during construction must be applied before the loop "
f"starts, got {trace['state_at_loop_entry']!r}"
)
def test_signal_during_construction_keeps_later_wakeup_working(monkeypatch):
trace = _run_engine_core(
monkeypatch,
signal_during_construction=True,
signal_while_idle=True,
)
assert trace["state_at_loop_entry"] == EngineShutdownState.REQUESTED, (
"the construction time signal must be applied before the loop starts, "
f"got {trace['state_at_loop_entry']!r}"
)
# SignalCallback is one-shot. If the construction time signal consumed it,
# no wakeup could be delivered afterwards and the idle busy loop would block
# on input_queue forever instead of shutting down, so the process would sit
# there holding GPU memory until something force kills it.
assert trace["wakeup"] == WAKEUP_ITEM, (
"a signal after construction must still wake the idle loop, "
f"got {trace['wakeup']!r}"
)
def test_signal_while_idle_still_wakes_the_loop(monkeypatch):
trace = _run_engine_core(monkeypatch, signal_while_idle=True)
assert trace["state_at_loop_entry"] == EngineShutdownState.RUNNING
assert trace["wakeup"] == WAKEUP_ITEM
def test_no_signal_leaves_the_loop_running(monkeypatch):
trace = _run_engine_core(monkeypatch)
assert trace["state_at_loop_entry"] == EngineShutdownState.RUNNING
assert trace["wakeup"] is None
@@ -82,7 +82,12 @@ def _validate(enable_trace_replay: bool) -> None:
enable_trace_replay=enable_trace_replay,
is_diffusion=False,
),
vllm_config=SimpleNamespace(reasoning_config=None),
vllm_config=SimpleNamespace(
reasoning_config=None,
# Engine has no watermark configuration.
_check_supports_watermarking=lambda params: False,
),
resolve_watermarking=lambda params: False,
speculative_config=None,
structured_outputs_config=None,
diffusion_config=None,
@@ -0,0 +1,27 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from unittest.mock import AsyncMock
import pytest
from vllm.v1.engine.async_llm import AsyncLLM
@pytest.mark.asyncio
async def test_kv_transfer_rejection_stub_disables_watermarking():
engine = object.__new__(AsyncLLM)
add_request = AsyncMock()
engine.engine_core = SimpleNamespace(
add_request_async=add_request,
shutdown=lambda **kwargs: None,
)
await engine.notify_kv_transfer_request_rejected(
"request",
{"do_remote_prefill": True},
)
request = add_request.call_args.args[0]
assert request.sampling_params.watermarking is False
+33
View File
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock, call
import pytest
from vllm import LLM
from vllm.exceptions import ProfilerAlreadyActiveError
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.engine.llm_engine import LLMEngine
from vllm.v1.metrics.reader import Counter, Gauge, Histogram, Metric, Vector
@@ -52,6 +53,38 @@ def test_step_invalidates_mm_processor_cache_misses():
]
def test_duplicate_profile_start_rejected_before_engine_core_dispatch():
engine = object.__new__(LLMEngine)
engine.engine_core = MagicMock()
engine._profile_session_active = False
engine.start_profile("first")
with pytest.raises(ProfilerAlreadyActiveError):
engine.start_profile("duplicate")
engine.engine_core.profile.assert_called_once_with(True, "first", None, None)
@pytest.mark.parametrize(
"kwargs",
[
{"profile_prefix": "../trace"},
{"delay_iterations": -1},
{"max_iterations": -1},
],
)
def test_invalid_profile_controls_rejected_before_engine_core_dispatch(kwargs):
engine = object.__new__(LLMEngine)
engine.engine_core = MagicMock()
engine._profile_session_active = False
with pytest.raises(ValueError):
engine.start_profile(**kwargs)
engine.engine_core.profile.assert_not_called()
def _vllm_model(
apc: bool,
vllm_runner: type[VllmRunner],
+15 -7
View File
@@ -70,16 +70,24 @@ def test_execute_worker_rpc_returns_worker_exception():
@pytest.mark.parametrize("stalled", [False, True])
def test_take_draft_token_ids_uses_execute_model_timeout(monkeypatch, stalled):
"""A wedged draft-token readback must not block EngineCore forever."""
@pytest.mark.parametrize(
"method,result",
[
("take_draft_token_ids", DraftTokenIds(["req"], [[1, 2, 3]])),
("execute_dummy_batch", None),
],
)
def test_model_rpc_uses_execute_model_timeout(monkeypatch, method, result, stalled):
"""A wedged model RPC must not block EngineCore forever. For
execute_dummy_batch this is an idle DP rank stuck in a collective with a
hung peer."""
monkeypatch.setenv("VLLM_EXECUTE_MODEL_TIMEOUT_SECONDS", "7")
draft = DraftTokenIds(["req"], [[1, 2, 3]])
def dequeue(*, timeout=None):
assert timeout is not None and 0 < timeout <= 7
if stalled:
raise TimeoutError
return WorkerProc.ResponseStatus.SUCCESS, draft
return WorkerProc.ResponseStatus.SUCCESS, result
executor: Any = MultiprocExecutor.__new__(MultiprocExecutor)
executor.is_failed = False
@@ -89,7 +97,7 @@ def test_take_draft_token_ids_uses_execute_model_timeout(monkeypatch, stalled):
executor.response_mqs = [None, SimpleNamespace(dequeue=dequeue)]
if stalled:
with pytest.raises(TimeoutError, match="take_draft_token_ids timed out"):
executor.take_draft_token_ids()
with pytest.raises(TimeoutError, match=f"{method} timed out"):
getattr(executor, method)()
else:
assert executor.take_draft_token_ids() is draft
assert getattr(executor, method)() is result
@@ -1,157 +0,0 @@
#!/bin/bash
set -xe
# Hosts / ports
PREFILL_HOST=${PREFILL_HOST:-"localhost"}
PREFILL_PORT=${PREFILL_PORT:-8100}
PREFILL_NIXL_SIDE_PORT=${PREFILL_NIXL_SIDE_PORT:-5577}
DECODE_HOST=${DECODE_HOST:-"localhost"}
DECODE_PORT=${DECODE_PORT:-8200}
PROXY_HOST=${PROXY_HOST:-"localhost"}
PROXY_PORT=${PROXY_PORT:-8192}
BASELINE_HOST=${BASELINE_HOST:-"localhost"}
BASELINE_PORT=${BASELINE_PORT:-9290}
# Model to run.
MODEL_NAME=${MODEL_NAME:-"meta-llama/Llama-3.2-3B-Instruct"}
MAX_MODEL_LEN=${MAX_MODEL_LEN:-1024}
BLOCK_SIZE=${BLOCK_SIZE:-32}
# execution env
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
GIT_ROOT="${GIT_ROOT:-$(cd -- "${SCRIPT_DIR}/../../../.." && pwd -P)}"
EXP_ROOT="${GIT_ROOT}/tests/v1/kv_connector/nixl_integration"
CONDA_PATH=${CONDA_PATH:-"/home/${USER}/anaconda3"}
CONDA_ENV_NAME=${CONDA_ENV_NAME:-"nixl"}
OUTPUT_FILE=${OUTPUT_FILE:-"${EXP_ROOT}/.tpu_accuracy_test_outputs.txt"}
# Trap the SIGINT signal (triggered by Ctrl+C)
trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
# Waits for vLLM server to start.
wait_for_server() {
local host=$1
local port=$2
timeout 1200 bash -c "
until curl -s ${host}:${port}/v1/completions > /dev/null; do
sleep 1
done" && return 0 || return 1
}
# Cleanup function
cleanup() {
echo "Caught Ctrl+C, cleaning up..."
# Cleanup commands
pgrep python | xargs kill -9 || true
# pkill -f python || true
echo "Cleanup complete. Exiting."
}
launch_baseline() {
BASELINE_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
VLLM_LOGGING_LEVEL=DEBUG \
PJRT_DEVICE=TPU \
VLLM_WORKER_MULTIPROC_METHOD=spawn \
VLLM_ENABLE_V1_MULTIPROCESSING=0 vllm serve $MODEL_NAME \
--host ${BASELINE_HOST} \
--port ${BASELINE_PORT} \
--max-model-len ${MAX_MODEL_LEN}\
--seed 42 \
--block-size ${BLOCK_SIZE} \
--gpu-memory-utilization 0.5 \
--enforce-eager"
echo "${BASELINE_BASE_CMD}"
ssh -tt "${BASELINE_HOST}" "${BASELINE_BASE_CMD}" &
}
launch_pd() {
PREFILL_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
UCX_TLS=tcp \
VLLM_MULTIPROC_EXECUTE_MODEL_TIMEOUT_S=200 \
VLLM_LOGGING_LEVEL=DEBUG \
VLLM_NIXL_SIDE_CHANNEL_HOST=${PREFILL_HOST} \
VLLM_NIXL_SIDE_CHANNEL_PORT=${PREFILL_NIXL_SIDE_PORT} \
PJRT_DEVICE=TPU \
VLLM_WORKER_MULTIPROC_METHOD=spawn \
VLLM_ENABLE_V1_MULTIPROCESSING=0 vllm serve $MODEL_NAME \
--host ${PREFILL_HOST} \
--port ${PREFILL_PORT} \
--max-model-len ${MAX_MODEL_LEN}\
--seed 42 \
--block-size ${BLOCK_SIZE} \
--enforce-eager \
--gpu-memory-utilization 0.5 \
--kv-transfer-config '{\"kv_connector\":\"NixlConnector\",\"kv_role\":\"kv_both\",\"kv_buffer_device\":\"cpu\"}'"
DECODE_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
UCX_TLS=tcp \
VLLM_MULTIPROC_EXECUTE_MODEL_TIMEOUT_S=200 \
VLLM_LOGGING_LEVEL=DEBUG \
PJRT_DEVICE=TPU \
VLLM_WORKER_MULTIPROC_METHOD=spawn \
VLLM_ENABLE_V1_MULTIPROCESSING=0 vllm serve $MODEL_NAME \
--host ${DECODE_HOST} \
--port ${DECODE_PORT} \
--max-model-len ${MAX_MODEL_LEN}\
--seed 42 \
--block-size ${BLOCK_SIZE} \
--enforce-eager \
--gpu-memory-utilization 0.5 \
--kv-transfer-config '{\"kv_connector\":\"NixlConnector\",\"kv_role\":\"kv_both\",\"kv_buffer_device\":\"cpu\"}'"
echo "${PREFILL_BASE_CMD}"
echo "${DECODE_BASE_CMD}"
sleep 2
# execute on hosts
ssh -tt "${PREFILL_HOST}" "${PREFILL_BASE_CMD}" &
ssh -tt "${DECODE_HOST}" "${DECODE_BASE_CMD}" &
sleep 1
wait_for_server "${PREFILL_HOST}" "${PREFILL_PORT}"
sleep 1
wait_for_server "${DECODE_HOST}" "${DECODE_PORT}"
sleep 1
}
launch_pd_proxy(){
PROXY_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
python3 ${EXP_ROOT}/toy_proxy_server.py \
--prefiller-host ${PREFILL_HOST} --prefiller-port ${PREFILL_PORT} \
--decoder-host ${DECODE_HOST} --decoder-port ${DECODE_PORT} \
--host=${PROXY_HOST} --port ${PROXY_PORT}"
echo "${PROXY_BASE_CMD}"
ssh -tt "${PROXY_HOST}" "${PROXY_BASE_CMD}" &
}
run_tests(){
local service_url=$1
local mode=$2
python3 "${EXP_ROOT}"/test_disagg_accuracy.py --service_url="${service_url}" --model_name="${MODEL_NAME}" --mode="${mode}" --file_name="${OUTPUT_FILE}"
}
# run non-disagg. baseline & save outputs
launch_baseline
sleep 2
wait_for_server "${BASELINE_HOST}" "${BASELINE_PORT}"
run_tests "http://${BASELINE_HOST}:${BASELINE_PORT}" "baseline"
cleanup
sleep 10
# run disagg. & do exact-match with the outputs from baseline
launch_pd
launch_pd_proxy
sleep 10
run_tests "http://${PROXY_HOST}:${PROXY_PORT}" "disagg"
echo "-----P/D success----"
rm "${OUTPUT_FILE}"
cleanup
exit 0
@@ -1,125 +0,0 @@
#!/bin/bash
set -xe
# Hosts / ports
PREFILL_HOST=${PREFILL_HOST:-"localhost"}
PREFILL_PORT=${PREFILL_PORT:-8100}
PREFILL_NIXL_SIDE_PORT=${PREFILL_NIXL_SIDE_PORT:-5577}
DECODE_HOST=${DECODE_HOST:-"localhost"}
DECODE_PORT=${DECODE_PORT:-8200}
PROXY_HOST=${PROXY_HOST:-"localhost"}
PROXY_PORT=${PROXY_PORT:-8192}
BASELINE_HOST=${BASELINE_HOST:-"localhost"}
BASELINE_PORT=${BASELINE_PORT:-9290}
# Model to run.
MODEL_NAME=${MODEL_NAME:-"meta-llama/Llama-3.2-3B-Instruct"}
MAX_MODEL_LEN=${MAX_MODEL_LEN:-1024}
BLOCK_SIZE=${BLOCK_SIZE:-32}
# execution env
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
GIT_ROOT="${GIT_ROOT:-$(cd -- "${SCRIPT_DIR}/../../../.." && pwd -P)}"
EXP_ROOT="${GIT_ROOT}/tests/v1/kv_connector/nixl_integration"
CONDA_PATH=${CONDA_PATH:-"/home/${USER}/anaconda3"}
CONDA_ENV_NAME=${CONDA_ENV_NAME:-"nixl"}
OUTPUT_FILE=${OUTPUT_FILE:-"${EXP_ROOT}/.tpu_accuracy_test_outputs.txt"}
# Trap the SIGINT signal (triggered by Ctrl+C)
trap 'kill $(jobs -pr)' SIGINT SIGTERM EXIT
# Waits for vLLM server to start.
wait_for_server() {
local host=$1
local port=$2
timeout 1200 bash -c "
until curl -s ${host}:${port}/v1/completions > /dev/null; do
sleep 1
done" && return 0 || return 1
}
# Cleanup function
cleanup() {
echo "Caught Ctrl+C, cleaning up..."
# Cleanup commands
pgrep python | xargs kill -9 || true
# pkill -f python || true
echo "Cleanup complete. Exiting."
}
launch_pd() {
PREFILL_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
UCX_TLS=tcp \
VLLM_MULTIPROC_EXECUTE_MODEL_TIMEOUT_S=200 \
VLLM_LOGGING_LEVEL=DEBUG \
VLLM_NIXL_SIDE_CHANNEL_HOST=${PREFILL_HOST} \
VLLM_NIXL_SIDE_CHANNEL_PORT=${PREFILL_NIXL_SIDE_PORT} \
PJRT_DEVICE=TPU \
VLLM_WORKER_MULTIPROC_METHOD=spawn \
VLLM_ENABLE_V1_MULTIPROCESSING=0 vllm serve $MODEL_NAME \
--host ${PREFILL_HOST} \
--port ${PREFILL_PORT} \
--max-model-len ${MAX_MODEL_LEN}\
--seed 42 \
--block-size ${BLOCK_SIZE} \
--enforce-eager \
--gpu-memory-utilization 0.5 \
--kv-transfer-config '{\"kv_connector\":\"NixlConnector\",\"kv_role\":\"kv_both\",\"kv_buffer_device\":\"cpu\"}'"
DECODE_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
UCX_TLS=tcp \
VLLM_MULTIPROC_EXECUTE_MODEL_TIMEOUT_S=200 \
VLLM_LOGGING_LEVEL=DEBUG \
PJRT_DEVICE=TPU \
VLLM_WORKER_MULTIPROC_METHOD=spawn \
VLLM_ENABLE_V1_MULTIPROCESSING=0 vllm serve $MODEL_NAME \
--host ${DECODE_HOST} \
--port ${DECODE_PORT} \
--max-model-len ${MAX_MODEL_LEN}\
--seed 42 \
--block-size ${BLOCK_SIZE} \
--enforce-eager \
--gpu-memory-utilization 0.5 \
--kv-transfer-config '{\"kv_connector\":\"NixlConnector\",\"kv_role\":\"kv_both\",\"kv_buffer_device\":\"cpu\"}'"
echo "${PREFILL_BASE_CMD}"
echo "${DECODE_BASE_CMD}"
sleep 2
# execute on hosts
ssh -tt "${PREFILL_HOST}" "${PREFILL_BASE_CMD}" &
ssh -tt "${DECODE_HOST}" "${DECODE_BASE_CMD}" &
sleep 1
wait_for_server "${PREFILL_HOST}" "${PREFILL_PORT}"
sleep 1
wait_for_server "${DECODE_HOST}" "${DECODE_PORT}"
sleep 1
}
launch_pd_proxy(){
PROXY_BASE_CMD="source ${CONDA_PATH}/bin/activate ${CONDA_ENV_NAME};
python3 ${EXP_ROOT}/toy_proxy_server.py \
--prefiller-host ${PREFILL_HOST} --prefiller-port ${PREFILL_PORT} \
--decoder-host ${DECODE_HOST} --decoder-port ${DECODE_PORT} \
--host=${PROXY_HOST} --port ${PROXY_PORT}"
echo "${PROXY_BASE_CMD}"
ssh -tt "${PROXY_HOST}" "${PROXY_BASE_CMD}" &
}
# run disagg. & do exact-match with the outputs from baseline
launch_pd
launch_pd_proxy
sleep 10
PREFILL_HOST=${PREFILL_HOST} \
PREFILL_PORT=${PREFILL_PORT} \
DECODE_HOST=${DECODE_HOST} \
DECODE_PORT=${DECODE_PORT} \
PROXY_HOST=${PROXY_HOST} \
PROXY_PORT=${PROXY_PORT} python -m pytest -s -v "${GIT_ROOT}"/tests/v1/kv_connector/nixl_integration/test_edge_cases.py
@@ -77,6 +77,7 @@ from vllm.v1.kv_offload.base import (
make_offload_key,
)
from vllm.v1.kv_offload.cpu.manager import CPUOffloadingManager
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput
from vllm.v1.request import RequestStatus
@@ -197,14 +198,18 @@ def test_swa_offload_window_covers_unaligned_hit(
manager.complete_load(job.keys, state.req_context)
def _make_partial_tail_scheduler() -> OffloadingConnectorScheduler:
def _make_partial_tail_scheduler(
recurrent_only: bool = False,
) -> OffloadingConnectorScheduler:
vllm_config = _make_vllm_config(extra_config={"self_describing_kv_events": True})
vllm_config.cache_config.prefix_match_unit = 4
vllm_config.cache_config.prefix_match_unit = None if recurrent_only else 4
vllm_config.speculative_config = None
vllm_config.kv_events_config = KVEventsConfig(
enable_kv_cache_events=True, publisher="null"
)
kv_cache_config = _make_mamba_hybrid_kv_cache_config()
if recurrent_only:
kv_cache_config.kv_cache_groups = kv_cache_config.kv_cache_groups[1:]
spec = MockOffloadingSpec(build_offloading_config(vllm_config, kv_cache_config))
return OffloadingConnectorScheduler(spec, vllm_config, kv_cache_config)
@@ -576,6 +581,284 @@ def test_recurrent_group_unhashed_block_does_not_truncate_load_boundary():
assert 42 in loaded
@pytest.mark.parametrize(
("recurrent_source", "expected"),
[
("host", {CacheHitSource.P2P: 16, CacheHitSource.HOST: 12}),
("p2p", {CacheHitSource.P2P: 28}),
(None, {CacheHitSource.P2P: 16, CacheHitSource.HOST: 12}),
],
)
def test_external_cache_hit_sources_preserve_partial_tail_origin(
recurrent_source, expected
):
"""Recurrent state covers the whole prefix; the outermost tier wins."""
scheduler = _make_partial_tail_scheduler()
request = _make_partial_tail_request(scheduler)
req_status = scheduler._req_status["req"]
req_status.update_offload_keys()
scheduler.manager.lookup.return_value = LookupResult.HIT
assert scheduler._lookup(req_status) == 28
def get_load_source(key, req_context):
if get_offload_group_idx(key) == 1:
assert recurrent_source is not None
return recurrent_source
block_hash = get_offload_block_hash(key)
return "p2p" if block_hash == b"h3" else "host"
scheduler.manager.get_load_source.side_effect = get_load_source
recurrent_block = KVCacheBlock(41)
if recurrent_source is None:
recurrent_block.set_block_hash(
make_block_hash_with_group_id(BlockHash(b"cached"), 1), 12
)
scheduler.update_state_after_alloc(
request,
KVCacheBlocks(
(
[KVCacheBlock(31), KVCacheBlock(32)],
[KVCacheBlock(0, is_null=True), recurrent_block],
)
),
num_external_tokens=28,
)
assert req_status.partial_tail_boundary is None
assert scheduler.get_external_cache_hit_sources(request, 28) == expected
@pytest.mark.parametrize(
("second_source", "expected"),
[
("host", {CacheHitSource.HOST: 4, CacheHitSource.DISK: 4}),
("p2p", {CacheHitSource.P2P: 4, CacheHitSource.DISK: 4}),
],
)
def test_external_cache_hit_sources_reconcile_different_group_chunk_sizes(
request_runner,
second_source,
expected,
):
"""Groups with different chunk sizes overlap; the outermost tier wins."""
block_size = 4
groups = [
KVCacheGroupSpec(
[f"layer{group_idx}"],
FullAttentionSpec(
block_size=block_size * (group_idx + 1),
num_kv_heads=1,
head_size=1,
dtype=torch.float32,
),
)
for group_idx in range(2)
]
runner = request_runner(
block_size=block_size,
num_gpu_blocks=100,
async_scheduling=False,
kv_cache_groups=groups,
)
scheduler = runner.connector_scheduler
request = MagicMock(request_id="mixed")
req_status = RequestOffloadState(
config=scheduler.config,
req=request,
req_context=ReqContext(req_id=request.request_id),
offloading_context=RequestOffloadingContext(policy=OffloadPolicy.CHUNK_LEVEL),
)
for group_idx, group_state in enumerate(req_status.group_states):
group_state.offload_keys = [
make_offload_key(f"h{chunk_idx}".encode(), group_idx)
for chunk_idx in range(2 // (group_idx + 1))
]
scheduler._req_status[request.request_id] = req_status
runner.manager.get_load_source.side_effect = lambda key, req_context: (
("host" if get_offload_block_hash(key) == b"h0" else "disk")
if get_offload_group_idx(key) == 0
else second_source
)
scheduler.update_state_after_alloc(
request,
KVCacheBlocks(([KVCacheBlock(1), KVCacheBlock(2)], [KVCacheBlock(3)])),
2 * block_size,
)
assert scheduler.get_external_cache_hit_sources(request, 2 * block_size) == expected
@pytest.mark.parametrize(
("ranges", "expected"),
[
pytest.param(
[(8, 12, "host"), (0, 8, "host"), (4, 10, "host")],
{CacheHitSource.HOST: 8, CacheHitSource.EXTERNAL_UNSPECIFIED: 4},
id="overlapping-same-source-and-adjacent-endpoints",
),
pytest.param(
[(10, 20, "p2p"), (6, 10, "disk"), (0, 8, "host"), (4, 12, "host")],
{CacheHitSource.HOST: 2, CacheHitSource.DISK: 4, CacheHitSource.P2P: 6},
id="nested-tiers-and-clipped-ranges",
),
pytest.param(
[(0, 4, "disk"), (16, 20, "disk"), (8, 8, "disk")],
{CacheHitSource.EXTERNAL_UNSPECIFIED: 12},
id="no-covering-ranges",
),
],
)
def test_external_cache_hit_sources_range_boundaries(ranges, expected):
scheduler = _make_partial_tail_scheduler()
request = _make_partial_tail_request(scheduler)
state = scheduler._req_status[request.request_id]
state.num_locally_computed_tokens = 4
for idx, (lo, hi, source) in enumerate(ranges):
key = make_offload_key(str(idx).encode(), 0)
state.load_key_ranges.append((lo, hi, key))
scheduler.manager.get_load_source.side_effect = lambda key, ctx: ranges[
int(get_offload_block_hash(key))
][2]
result = scheduler.get_external_cache_hit_sources(request, 12)
assert result == expected
assert sum(result.values()) == 12
@pytest.mark.parametrize("source", ["host", "disk", "p2p", "external_unspecified"])
def test_external_cache_hit_sources_recurrent_only_state(source):
scheduler = _make_partial_tail_scheduler(recurrent_only=True)
request = _make_partial_tail_request(scheduler)
request.num_prompt_tokens = request.num_tokens = 64
request.block_hashes = [BlockHash(f"h{i}".encode()) for i in range(4)]
request.all_token_ids = list(range(64))
state = scheduler._req_status[request.request_id]
state.update_offload_keys()
scheduler.manager.lookup.return_value = LookupResult.HIT
assert scheduler._lookup(state) == 48
scheduler.manager.get_load_source.return_value = source
scheduler.update_state_after_alloc(
request,
KVCacheBlocks(
(
[
KVCacheBlock(0, is_null=True),
KVCacheBlock(0, is_null=True),
KVCacheBlock(41),
],
)
),
48,
)
assert scheduler.get_external_cache_hit_sources(request, 48) == {
CacheHitSource(source): 48
}
scheduler.manager.get_load_source.assert_called_once()
@pytest.mark.parametrize("sparse_kind", ["sliding", "chunked_local"])
@pytest.mark.parametrize("blocks_per_chunk", [1, 2])
@pytest.mark.parametrize("local_tokens", [0, 4])
@pytest.mark.parametrize("full_attention", [False, True])
@pytest.mark.parametrize(
"sparse_source", ["host", "disk", "p2p", "external_unspecified", "mixed"]
)
def test_external_cache_hit_sources_use_loaded_attention_ranges(
sparse_kind,
blocks_per_chunk,
local_tokens,
full_attention,
sparse_source,
):
"""SWA/local attention affects only loaded positions, not omitted history."""
block_size = 4
chunk_size = block_size * blocks_per_chunk
spec_kwargs = dict(
block_size=block_size, num_kv_heads=1, head_size=1, dtype=torch.float32
)
sparse_spec = (
SlidingWindowSpec(**spec_kwargs, sliding_window=2 * chunk_size)
if sparse_kind == "sliding"
else ChunkedLocalAttentionSpec(
**spec_kwargs, attention_chunk_size=2 * chunk_size
)
)
groups = [KVCacheGroupSpec(["sparse"], sparse_spec)]
if full_attention:
groups.insert(0, KVCacheGroupSpec(["full"], FullAttentionSpec(**spec_kwargs)))
vllm_config = _make_vllm_config(extra_config={"block_size": chunk_size})
vllm_config.cache_config.block_size = block_size
vllm_config.speculative_config = None
kv_cache_config = KVCacheConfig(
num_blocks=100,
kv_cache_tensors=[],
kv_cache_groups=groups,
)
spec = MockOffloadingSpec(build_offloading_config(vllm_config, kv_cache_config))
scheduler = OffloadingConnectorScheduler(spec, vllm_config, kv_cache_config)
request = MagicMock(request_id="sparse")
req_status = RequestOffloadState(
config=scheduler.config,
req=request,
req_context=ReqContext(req_id=request.request_id),
offloading_context=RequestOffloadingContext(policy=OffloadPolicy.CHUNK_LEVEL),
num_locally_computed_tokens=local_tokens,
)
scheduler._req_status[request.request_id] = req_status
block_groups = []
for group_idx, state in enumerate(req_status.group_states):
state.offload_keys = [
make_offload_key(str(i).encode(), group_idx) for i in range(4)
]
block_groups.append(
[
KVCacheBlock(
0
if group_idx == len(groups) - 1 and i < 2 * blocks_per_chunk
else 1 + group_idx * 100 + i,
is_null=group_idx == len(groups) - 1 and i < 2 * blocks_per_chunk,
)
for i in range(4 * blocks_per_chunk)
]
)
def get_load_source(key, req_context):
chunk_idx = int(get_offload_block_hash(key))
if get_offload_group_idx(key) == len(groups) - 1:
assert chunk_idx >= 2 # Earlier sparse keys were not loaded.
if sparse_source == "mixed":
return "host" if chunk_idx == 2 else "disk"
return sparse_source
return "host"
scheduler.manager.get_load_source.side_effect = get_load_source
count = 4 * chunk_size - local_tokens
scheduler.update_state_after_alloc(
request, KVCacheBlocks(tuple(block_groups)), count
)
expected: dict[CacheHitSource, int] = {}
def expect(source: CacheHitSource, num_tokens: int) -> None:
expected[source] = expected.get(source, 0) + num_tokens
expect(
CacheHitSource.HOST if full_attention else CacheHitSource.EXTERNAL_UNSPECIFIED,
2 * chunk_size - local_tokens,
)
for chunk_idx in range(2, 4):
source = (
("host" if chunk_idx == 2 else "disk")
if sparse_source == "mixed"
else sparse_source
)
expect(CacheHitSource(source), chunk_size)
result = scheduler.get_external_cache_hit_sources(request, count)
assert result == expected
assert sum(result.values()) == count
assert scheduler.get_external_cache_hit_sources(request, 0) == {}
def test_partial_lookup_requires_every_cache_group():
scheduler = _make_partial_tail_scheduler()
_make_partial_tail_request(scheduler)
@@ -1400,7 +1683,6 @@ def test_two_groups_full_and_sliding_window(request_runner, async_scheduling: bo
# are within the window → loads blocks 1,2
expected_loaded=((0, 0), (0, 1), (0, 2), (1, 1), (1, 2)),
)
runner.manager.touch.assert_not_called()
# 3 blocks are hit on GPU [0, 1, 2]
@@ -57,6 +57,7 @@ from vllm.v1.kv_offload.base import (
make_offload_key,
)
from vllm.v1.kv_offload.config import OffloadingConfig
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
@@ -129,6 +130,7 @@ class MockOffloadingSpec(OffloadingSpec):
self.manager = MagicMock(spec=OffloadingManager)
self.manager.prepare_load = lambda keys, req_context: MockLoadStoreSpec(keys)
self.manager.lookup.return_value = LookupResult.MISS
self.manager.get_load_source.return_value = CacheHitSource.EXTERNAL_UNSPECIFIED
self.manager.get_stats.return_value = None
self.manager.on_new_request.return_value = RequestOffloadingContext()
self.handler = MockOffloadingWorker()
@@ -8,7 +8,6 @@ prefix cache hash table so future requests cannot match and reuse corrupted data
"""
from collections.abc import Callable
from unittest.mock import Mock
import pytest
@@ -16,6 +15,7 @@ from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import Request, RequestStatus
from .utils import (
create_mock_connector,
create_model_runner_output,
create_request,
create_scheduler,
@@ -73,7 +73,7 @@ def test_invalid_blocks_evicted_prevents_cache_pollution(
}
# mock connector indicating sync load
fail_scheduler.connector = Mock()
fail_scheduler.connector = create_mock_connector()
fail_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, False)
)
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from unittest.mock import Mock
import pytest
@@ -10,6 +9,7 @@ from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import FinishReason, Request, RequestStatus
from .utils import (
create_mock_connector,
create_model_runner_output,
create_request,
create_scheduler,
@@ -56,7 +56,7 @@ def test_error_propagation_sync_load(fail_scheduler: Scheduler):
request.request_id: num_external_computed_tokens,
}
fail_scheduler.connector = Mock()
fail_scheduler.connector = create_mock_connector()
fail_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, False)
)
@@ -110,7 +110,7 @@ def test_error_propagation_async_load(fail_scheduler: Scheduler):
request.request_id: num_external_computed_tokens,
}
fail_scheduler.connector = Mock()
fail_scheduler.connector = create_mock_connector()
fail_scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
fail_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, True)
@@ -64,6 +64,42 @@ def test_hisparse_requires_block_outermost_device_layout():
assert HiSparseConnector.get_required_kvcache_layout(MagicMock()) == "BLHNC"
def test_scheduler_stats_report_host_pool_usage():
"""The scheduler-side stats sample the coordinator's host pool level."""
from tests.v1.core.test_prefix_caching import (
HISPARSE_BLOCK_SIZE,
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, host_num_blocks=8)
scheduler = HiSparseConnectorScheduler(async_speculative=False)
scheduler.bind_coordinator(get_hisparse_coordinator(manager))
coordinator = scheduler.coordinator
stats = scheduler.get_kv_connector_stats()
assert stats.data["host_cache_usage_perc"] == [0.0]
assert stats.data["pending_page_transfers"] == [0]
request = make_request(
"request", list(range(4 * HISPARSE_BLOCK_SIZE)), HISPARSE_BLOCK_SIZE, sha256
)
assert manager.allocate_slots(request, num_new_tokens=64) is not None
host_blocks = coordinator.host_manager.req_to_blocks[request.request_id]
num_used = sum(not block.is_null for block in host_blocks)
# The pool reserves the null block, so 8 configured blocks yield 7 usable.
expected = pytest.approx(num_used / 7)
assert 0 < num_used <= 7
for _ in range(2):
stats = scheduler.get_kv_connector_stats()
assert stats.data["host_cache_usage_perc"] == [expected]
def test_no_forward_enqueues_deferred_hisparse_transfers():
"""A zero-token step must still enqueue deferred post-forward transfers."""
connector = object.__new__(ActiveKVConnector)
@@ -26,6 +26,28 @@ def test_record_snapshot_and_reduce():
assert reduced["HiSparse host-to-device bytes"] == 64
def test_record_host_usage_reports_latest_level():
stats = HiSparseKVConnectorStats()
stats.record_host_usage(usage=0.4, pending_page_transfers=2)
stats.record_host_usage(usage=0.8, pending_page_transfers=0)
reduced = stats.reduce()
assert reduced["HiSparse host KV cache usage %"] == 80.0
def test_aggregate_keeps_latest_host_usage_level():
first = HiSparseKVConnectorStats()
first.record_host_usage(usage=0.4, pending_page_transfers=2)
second = HiSparseKVConnectorStats()
second.record_host_usage(usage=0.8, pending_page_transfers=0)
second.record_host_usage(usage=0.6, pending_page_transfers=1)
first.aggregate(second)
assert first.data["host_cache_usage_perc"] == [0.4, 0.6]
assert first.data["pending_page_transfers"] == [2, 1]
def test_aggregate_extends_snapshot_deltas():
first = HiSparseKVConnectorStats()
first.record_snapshot(hits=7, misses=3, host_to_device_bytes=48)
@@ -34,11 +56,9 @@ def test_aggregate_extends_snapshot_deltas():
first.aggregate(second)
assert first.data == {
"cache_hits": [7, 5],
"cache_misses": [3, 1],
"host_to_device_bytes": [48, 16],
}
assert first.data["cache_hits"] == [7, 5]
assert first.data["cache_misses"] == [3, 1]
assert first.data["host_to_device_bytes"] == [48, 16]
def test_aggregate_skips_empty_stats():
@@ -60,3 +80,54 @@ def test_build_kv_connector_stats_round_trip():
assert rebuilt is not None
assert isinstance(rebuilt, HiSparseKVConnectorStats)
assert rebuilt.reduce() == stats.reduce()
def test_prom_metrics_observe_host_usage_gauges():
from types import SimpleNamespace
from typing import Any
from prometheus_client import Counter, Gauge, Histogram
from vllm.distributed.kv_transfer.kv_connector.v1.hisparse.stats import (
HiSparsePromMetrics,
)
class _FakeMetric:
def __init__(self, **kwargs: Any):
self.kwargs = kwargs
self.increments: list[int | float] = []
self.set_values: list[int | float] = []
def labels(self, *labelvalues: object) -> "_FakeMetric":
return self
def inc(self, value: int | float) -> None:
self.increments.append(value)
def set(self, value: int | float) -> None:
self.set_values.append(value)
created: dict[str, _FakeMetric] = {}
class _NamedFake(_FakeMetric):
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
created[kwargs["name"]] = self
prom = HiSparsePromMetrics(
vllm_config=SimpleNamespace(kv_transfer_config=None),
metric_types={Gauge: _NamedFake, Counter: _NamedFake, Histogram: _NamedFake},
labelnames=["model_name"],
per_engine_labelvalues={0: ["model"]},
)
stats = HiSparseKVConnectorStats()
stats.record_snapshot(hits=3, misses=2, host_to_device_bytes=32)
stats.record_host_usage(usage=0.5, pending_page_transfers=1)
stats.record_host_usage(usage=0.75, pending_page_transfers=3)
prom.observe(stats.to_dict())
assert created["vllm:hisparse_cache_hits"].increments == [3]
assert created["vllm:hisparse_host_to_device_bytes"].increments == [32]
assert created["vllm:hisparse_host_cache_usage_perc"].set_values == [0.75]
assert created["vllm:hisparse_pending_page_transfers"].set_values == [3]
@@ -11,7 +11,6 @@ These tests verify correct behavior in three scenarios:
"""
from collections.abc import Callable
from unittest.mock import Mock
import pytest
@@ -19,6 +18,7 @@ from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import FinishReason, Request, RequestStatus
from .utils import (
create_mock_connector,
create_model_runner_output,
create_request,
create_scheduler,
@@ -83,7 +83,7 @@ def test_sync_recompute_blocks_not_freed_for_running_requests(
}
# mock connector indicating sync load
recompute_scheduler.connector = Mock()
recompute_scheduler.connector = create_mock_connector()
recompute_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, False)
)
@@ -206,7 +206,7 @@ def test_sync_fail_invalid_blocks_evicted(fail_scheduler: Scheduler):
}
# mock connector indicating sync load
fail_scheduler.connector = Mock()
fail_scheduler.connector = create_mock_connector()
fail_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, False)
)
@@ -323,7 +323,7 @@ def test_async_recompute_blocks_not_cached_when_invalid(
}
# mock connector indicating async load
recompute_scheduler.connector = Mock()
recompute_scheduler.connector = create_mock_connector()
recompute_scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, True)
)
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from unittest.mock import Mock
import pytest
@@ -10,6 +9,7 @@ from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.request import Request, RequestStatus
from .utils import (
create_mock_connector,
create_model_runner_output,
create_request,
create_scheduler,
@@ -41,7 +41,7 @@ def test_failed_receive_completion_honors_failure_policy(policy):
scheduler = create_scheduler(create_vllm_config(kv_load_failure_policy=policy))
request = create_request(num_tokens=3 * scheduler.block_size)
scheduler.add_request(request)
scheduler.connector = Mock()
scheduler.connector = create_mock_connector()
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
scheduler.connector.get_num_new_matched_tokens.side_effect = [
(2 * scheduler.block_size, True),
@@ -103,7 +103,7 @@ def test_async_load_failure(
request3.request_id: num_external_computed_tokens,
}
scheduler.connector = Mock()
scheduler.connector = create_mock_connector()
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True)
@@ -181,7 +181,7 @@ def test_sync_load_failure(
request3.request_id: num_external_computed_tokens,
}
scheduler.connector = Mock()
scheduler.connector = create_mock_connector()
scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=False)
)
@@ -262,7 +262,7 @@ def test_sync_load_failure_with_shared_blocks(
request1.request_id: num_external_computed_tokens,
}
scheduler.connector = Mock()
scheduler.connector = create_mock_connector()
scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=False)
)
@@ -333,7 +333,7 @@ def test_async_progressive_load_failure(
request.request_id: num_external_computed_tokens,
}
scheduler.connector = Mock()
scheduler.connector = create_mock_connector()
scheduler.connector.get_loaded_kv_cache_group_ids.return_value = (0,)
scheduler.connector.get_num_new_matched_tokens.side_effect = (
_make_get_num_new_matched_tokens(req_num_new_matched_tokens, async_load=True)
@@ -38,6 +38,7 @@ from vllm.v1.kv_cache_interface import (
KVCacheTensor,
MambaSpec,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput
from .utils import create_vllm_config
@@ -208,6 +209,29 @@ def test_scheduler_role_initializes_store_scheduler_only():
mock_scheduler.return_value.bind_gpu_block_pool.assert_called_once_with(block_pool)
def test_scheduler_reports_mooncake_cache_source():
vllm_config = _make_vllm_config()
kv_cache_config = _make_kv_cache_config()
with (
set_current_vllm_config(vllm_config),
patch(
"vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store."
"connector.MooncakeStoreScheduler"
),
):
connector = mooncake_store_connector.MooncakeStoreConnector(
vllm_config, KVConnectorRole.SCHEDULER, kv_cache_config
)
# Mooncake Store is an external cache service. Its internal memory and
# local-storage policy is intentionally hidden behind that stable label.
assert connector.get_external_cache_hit_sources(
None, # type: ignore[arg-type]
32,
) == {CacheHitSource.EXTERNAL_UNSPECIFIED: 32}
def test_worker_methods_delegate_to_store_worker():
vllm_config = _make_vllm_config()
kv_cache_config = _make_kv_cache_config()
@@ -3,6 +3,8 @@
import importlib.util
import socket
import uuid
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock, patch
import msgspec
@@ -20,11 +22,13 @@ from vllm.config import (
set_current_vllm_config,
)
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_common import (
ROLE,
MoRIIOAgentMetadata,
MoRIIOConnectorMetadata,
MoRIIOConstants,
MoRIIOMode,
resolve_host_ip,
set_role,
zmq_ctx,
)
from vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector import (
@@ -147,6 +151,61 @@ def _write_consumer_scheduler_for_finished_request(tp_size: int = 2):
return scheduler
def _write_producer_scheduler(block_size: int = 1) -> Any:
"""Bare WRITE-mode PRODUCER scheduler exercising the save path without a
real engine/RDMA stack. Uses a single full-attention KV group (index 0)."""
scheduler = MoRIIOConnectorScheduler.__new__(MoRIIOConnectorScheduler)
scheduler.mode = MoRIIOMode.WRITE
scheduler.is_producer = True
scheduler.block_size = block_size
scheduler.blocks_per_sw = [0]
scheduler._group_block_sizes = [block_size]
scheduler.transfer_id_to_request_id = {}
scheduler._reqs_need_recv = {}
scheduler._reqs_need_save = {}
scheduler._reqs_need_pending_save = {}
scheduler._req_kv_params = {}
scheduler._reqs_need_send = {}
return scheduler
def _spec_kv_params(transfer_id: str = "xfer-spec") -> dict[str, Any]:
# request_id embeds no zmq address, so add_new_req resolves the peer here.
return {
"transfer_id": transfer_id,
"remote_engine_id": "remote-engine",
"remote_block_ids": [],
"remote_host": "127.0.0.1",
"remote_handshake_port": 5000,
"remote_notify_port": 5001,
}
def _build_meta(
scheduler: Any, req_ids=None, new_block_ids=None, num_scheduled_tokens=None
) -> Any:
# Final-chunk detection reads num_scheduled_tokens, so expose it.
scheduler_output = SimpleNamespace(
scheduled_cached_reqs=SimpleNamespace(
req_ids=req_ids or [],
new_block_ids=new_block_ids or [],
),
num_scheduled_tokens=num_scheduled_tokens or {},
)
return scheduler.build_connector_meta(scheduler_output)
def test_write_mode_does_not_reload_remote_kv_after_preemption():
scheduler = _write_consumer_scheduler_for_finished_request()
request = create_request(request_id=1, num_tokens=32, do_remote_prefill=True)
assert scheduler.get_num_new_matched_tokens(request, 0) == (32, True)
assert request.kv_transfer_params is not None
request.kv_transfer_params["do_remote_prefill"] = False
assert scheduler.get_num_new_matched_tokens(request, 0) == (0, False)
class FakeMoRIIOWrapper:
# A fake MoRIIOWrapper for testing purposes
def __init__(self, *args, **kwargs):
@@ -700,6 +759,203 @@ def test_resolve_host_ip_prefers_extra_config():
assert resolve_host_ip({"host_ip": ""}) == fallback
def test_write_mode_excludes_spec_lookahead_blocks():
# The save path must record only the prompt blocks, clamping off the
# trailing lookahead blocks decode never allocates.
set_role(ROLE.PRODUCER)
scheduler = _write_producer_scheduler(block_size=1)
req_id = "req-spec"
prompt_blocks = [10, 11, 12, 13, 14, 15, 16, 17]
lookahead_blocks = [18, 19, 20]
local_block_ids = [prompt_blocks + lookahead_blocks]
# block_size=1 => num_prompt_tokens == prompt block count, all scheduled in
# this single chunk, so final-chunk detection fires.
num_prompt_tokens = len(prompt_blocks)
req = SimpleNamespace(
request_id=req_id,
num_prompt_tokens=num_prompt_tokens,
num_computed_tokens=0,
kv_transfer_params=_spec_kv_params(),
)
scheduler._reqs_need_save[req_id] = (req, local_block_ids)
scheduler._req_kv_params[req_id] = _spec_kv_params()
meta = _build_meta(scheduler, num_scheduled_tokens={req_id: num_prompt_tokens})
assert isinstance(meta, MoRIIOConnectorMetadata)
assert req_id in meta.reqs_to_save
saved = meta.reqs_to_save[req_id]
assert saved.local_block_ids == [prompt_blocks]
def test_write_mode_chunked_prefill_clamps_spec_lookahead_blocks():
# Non-final chunks are buffered untouched; lookahead blocks are only clamped
# on the final-chunk save.
set_role(ROLE.PRODUCER)
scheduler = _write_producer_scheduler(block_size=1)
req_id = "req-spec-chunked"
num_prompt_tokens = 8
first_chunk = [10, 11, 12, 13]
final_chunk = [14, 15, 16, 17, 18, 19, 20] # 4 prompt + 3 lookahead
prompt_blocks = [10, 11, 12, 13, 14, 15, 16, 17]
req = SimpleNamespace(
request_id=req_id,
num_prompt_tokens=num_prompt_tokens,
num_computed_tokens=0,
kv_transfer_params=_spec_kv_params(),
)
# Step 1: first chunk (4 of 8 tokens) is buffered, not saved.
scheduler._reqs_need_save[req_id] = (req, [first_chunk])
scheduler._req_kv_params[req_id] = _spec_kv_params()
meta_step1 = _build_meta(scheduler, num_scheduled_tokens={req_id: 4})
assert req_id not in meta_step1.reqs_to_save
assert req_id in scheduler._reqs_need_pending_save
assert scheduler._reqs_need_pending_save[req_id][1] == [first_chunk]
# Step 2: final chunk (computed 4 + scheduled 4 >= 8) assembles the full
# local set, clamps the lookahead, and records only the prompt blocks.
req.num_computed_tokens = 4
meta_step2 = _build_meta(
scheduler,
req_ids=[req_id],
new_block_ids=[[final_chunk]],
num_scheduled_tokens={req_id: 4},
)
assert req_id in meta_step2.reqs_to_save
assert meta_step2.reqs_to_save[req_id].local_block_ids == [prompt_blocks]
assert req_id not in scheduler._reqs_need_pending_save
@pytest.mark.parametrize(
("block_size", "num_prompt_tokens", "num_prompt_blocks"),
[
# block_size=4: exact multiple (2 full blocks) and non-multiple (3 blocks,
# last one partial).
pytest.param(4, 8, 2, id="bs4-exact-multiple"),
pytest.param(4, 9, 3, id="bs4-non-multiple"),
# block_size=16: exact multiple (2 full blocks) and non-multiple (3
# blocks, last one partial).
pytest.param(16, 32, 2, id="bs16-exact-multiple"),
pytest.param(16, 40, 3, id="bs16-non-multiple"),
],
)
def test_write_mode_clamps_prompt_blocks_with_block_size_gt_1(
block_size, num_prompt_tokens, num_prompt_blocks
):
# With block_size > 1 the clamp must keep exactly
# ceil(num_prompt_tokens / block_size) prompt blocks and drop the tail.
set_role(ROLE.PRODUCER)
scheduler = _write_producer_scheduler(block_size=block_size)
req_id = f"req-bs{block_size}-{num_prompt_tokens}"
prompt_blocks = list(range(10, 10 + num_prompt_blocks))
lookahead_blocks = [10 + num_prompt_blocks]
local_block_ids = [prompt_blocks + lookahead_blocks]
req = SimpleNamespace(
request_id=req_id,
num_prompt_tokens=num_prompt_tokens,
num_computed_tokens=0,
kv_transfer_params=_spec_kv_params(),
)
scheduler._reqs_need_save[req_id] = (req, local_block_ids)
scheduler._req_kv_params[req_id] = _spec_kv_params()
meta = _build_meta(scheduler, num_scheduled_tokens={req_id: num_prompt_tokens})
assert isinstance(meta, MoRIIOConnectorMetadata)
assert req_id in meta.reqs_to_save
assert len(prompt_blocks) == num_prompt_blocks
assert meta.reqs_to_save[req_id].local_block_ids == [prompt_blocks]
def test_write_mode_defers_save_until_prompt_complete_with_lookahead():
# Under speculative decoding the producer reserves lookahead blocks beyond
# the last-scheduled prompt token, inflating the accumulated block count on
# a non-final chunk. Token-progress detection must keep deferring until the
# prompt is complete, where the lookahead is clamped off.
#
# block_size=1, num_prompt_tokens=10, chunk=4, num_lookahead=3: after 8
# prompt tokens the producer holds 8 + 3 = 11 blocks, but token progress
# 8 < 10 must keep waiting until the final chunk completes tokens 9-10.
set_role(ROLE.PRODUCER)
scheduler = _write_producer_scheduler(block_size=1)
req_id = "req-lookahead-final-chunk"
num_prompt_tokens = 10
chunk1_blocks = [100, 101, 102, 103] # prompt tokens 1-4
chunk2_blocks = [104, 105, 106, 107, 108, 109, 110] # 4 prompt + 3 lookahead
prompt_blocks = [100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
req = SimpleNamespace(
request_id=req_id,
num_prompt_tokens=num_prompt_tokens,
num_computed_tokens=0,
kv_transfer_params=_spec_kv_params(),
)
scheduler._req_kv_params[req_id] = _spec_kv_params()
# Chunk 1 (tokens 1-4): computed 0 + scheduled 4 < 10 -> buffered.
scheduler._reqs_need_save[req_id] = (req, [chunk1_blocks])
meta1 = _build_meta(scheduler, num_scheduled_tokens={req_id: 4})
assert req_id not in meta1.reqs_to_save, "chunk 1 must not be saved"
assert req_id in scheduler._reqs_need_pending_save
assert scheduler._reqs_need_pending_save[req_id][1] == [chunk1_blocks]
# Chunk 2 (tokens 5-8) inflates the buffered count to 11 via lookahead, but
# token progress 4 + 4 = 8 < 10 keeps the request deferred.
req.num_computed_tokens = 4
meta2 = _build_meta(
scheduler,
req_ids=[req_id],
new_block_ids=[[chunk2_blocks]],
num_scheduled_tokens={req_id: 4},
)
assert req_id not in meta2.reqs_to_save, (
"second-to-last chunk saved prematurely despite incomplete prompt"
)
assert req_id in scheduler._reqs_need_pending_save
assert scheduler._reqs_need_pending_save[req_id][1] == [
chunk1_blocks + chunk2_blocks
]
# Final chunk (tokens 9-10, no new blocks): computed 8 + scheduled 2 >= 10
# emits the save with the trailing lookahead block clamped off.
req.num_computed_tokens = 8
meta3 = _build_meta(
scheduler,
req_ids=[req_id],
new_block_ids=[None],
num_scheduled_tokens={req_id: 2},
)
assert req_id in meta3.reqs_to_save, "final chunk must emit the WRITE save"
assert meta3.reqs_to_save[req_id].local_block_ids == [prompt_blocks]
assert req_id not in scheduler._reqs_need_pending_save
def test_clamp_to_prompt_blocks_clamps_each_group_by_its_own_block_size():
# Two full-attention groups with different block sizes are each clamped to
# their own prompt-block count; a sliding-window group is left untouched.
scheduler = MoRIIOConnectorScheduler.__new__(MoRIIOConnectorScheduler)
scheduler.blocks_per_sw = [0, 0, 3]
scheduler._group_block_sizes = [16, 32, 16]
req = SimpleNamespace(num_prompt_tokens=40)
block_ids = [
[0, 1, 2, 3, 4], # ceil(40/16)=3 -> clamp to 3
[10, 11, 12], # ceil(40/32)=2 -> clamp to 2
[20, 21, 22, 23, 24], # sliding-window -> untouched
]
clamped = scheduler._clamp_to_prompt_blocks(req, block_ids)
assert clamped == [[0, 1, 2], [10, 11], [20, 21, 22, 23, 24]]
def _make_hybrid_kv_cache_config() -> KVCacheConfig:
"""One full-attention group + one sliding-window group (Gemma-like)."""
full_spec = FullAttentionSpec(
@@ -731,6 +987,35 @@ def _make_hybrid_kv_cache_config() -> KVCacheConfig:
)
def _make_sliding_window_only_kv_cache_config() -> KVCacheConfig:
"""A uniform sliding-window model (e.g. Mistral-7B): the single group is a
SlidingWindowSpec, so HMA is not required once hybrid management is
disabled, yet the spec guard still applies."""
sw_spec = SlidingWindowSpec(
block_size=16,
num_kv_heads=4,
head_size=64,
dtype=torch.float16,
sliding_window=32,
)
num_blocks = 2
page = sw_spec.page_size_bytes
return KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=num_blocks * page,
layers=["sw0"],
layer_stride=num_blocks * page,
block_stride=page,
)
],
kv_cache_groups=[
KVCacheGroupSpec(layer_names=["sw0"], kv_cache_spec=sw_spec),
],
)
def _read_scheduler(
kv_cache_config: KVCacheConfig, disable_hma: bool = False
) -> MoRIIOConnectorScheduler:
@@ -820,15 +1105,6 @@ def test_non_sliding_window_hybrid_is_rejected():
_read_scheduler(config)
def test_token_count_basis_uses_full_attention_group():
"""Chunked-prefill token counting must use an unclipped full-attention
group (blocks_per_sw == 0), not a clipped sliding-window group."""
scheduler = _read_scheduler(_make_hybrid_kv_cache_config())
# Group 0 is the full-attention group
assert scheduler._full_attn_group_idx == 0
assert scheduler._full_attn_block_size == 16
def test_get_exchange_clipped_blocks_clips_only_sw_group():
"""get_exchange_clipped_blocks keeps the full attn group intact and clips the
sliding-window group to its window tail."""
@@ -897,6 +1173,71 @@ def test_single_group_path_unchanged():
assert scheduler.get_exchange_clipped_blocks(blocks) == blocks
class _FakeSpecConfig(SimpleNamespace):
"""Minimal speculative_config stand-in. Any drafter-capability probe
(use_dflash/use_eagle/use_dspark/uses_draft_model/...) defaults to False so
VllmConfig.num_lookahead_tokens resolves cleanly as upstream adds methods."""
def __getattr__(self, name: str):
if name.startswith(("use_", "uses_")):
return lambda *a, **k: False
raise AttributeError(name)
def _fake_speculative_config(num_speculative_tokens: int = 1) -> SimpleNamespace:
return _FakeSpecConfig(num_speculative_tokens=num_speculative_tokens)
def _spec_vllm_config() -> VllmConfig:
vllm_config = create_vllm_config(role="kv_producer", read_mode=False)
vllm_config.speculative_config = _fake_speculative_config()
# HMA off => the WRITE+hybrid guard is skipped, so construction reaches the
# spec-decode guard (the only path that hits it).
vllm_config.scheduler_config.disable_hybrid_kv_cache_manager = True
return vllm_config
def test_spec_decode_rejected_with_sliding_window_groups():
"""MoRIIO + speculative decoding fails closed on sliding-window models,
since the prompt-block clamp only covers full-attention groups. The only
reachable path is a uniform SWA model with HMA disabled."""
vllm_config = _spec_vllm_config()
with (
set_current_vllm_config(vllm_config),
pytest.raises(NotImplementedError, match="speculative decoding"),
):
MoRIIOConnector(
vllm_config,
KVConnectorRole.SCHEDULER,
_make_sliding_window_only_kv_cache_config(),
)
def test_spec_decode_allowed_with_full_attention_only():
"""Full-attention-only models (e.g. GLM) do not trip the spec guard."""
vllm_config = _spec_vllm_config()
with set_current_vllm_config(vllm_config):
connector = MoRIIOConnector(
vllm_config,
KVConnectorRole.SCHEDULER,
_make_test_kv_cache_config(),
)
assert connector.connector_scheduler is not None
def test_spec_decode_allowed_with_sliding_window_in_read_mode():
"""The spec guard is WRITE-mode only; READ mode is unaffected."""
vllm_config = create_vllm_config(role="kv_consumer", read_mode=True)
vllm_config.speculative_config = _fake_speculative_config()
with set_current_vllm_config(vllm_config):
connector = MoRIIOConnector(
vllm_config,
KVConnectorRole.SCHEDULER,
_make_hybrid_kv_cache_config(),
)
assert connector.connector_scheduler is not None
def test_hybrid_write_mode_rejected():
"""Hybrid KV cache groups are unsupported in WRITE mode and fail closed."""
vllm_config = create_vllm_config(role="kv_producer", read_mode=False)
@@ -7,32 +7,20 @@ These exercise the highest-risk, otherwise-untested scheduler logic without a
GPU or the ``mori`` runtime: per-group block-id splitting, the READ/WRITE
``N-1`` token accounting, P-side prompt truncation, and offset-template cache
wiring.
Like ``test_moriio_kv_layout.py`` the whole module is skipped unless it is
running on ROCm with ``mori`` installed (importing the connector pulls in
``mori``). The authoritative run happens on the MIA recipe image.
"""
import importlib
import importlib.util
from dataclasses import asdict
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.sched.output import SchedulerOutput
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
if not (current_platform.is_rocm() and mori_available):
pytest.skip(
"MoRIIOs are only available on ROCm with mori package installed",
allow_module_level=True,
)
moriio_connector = importlib.import_module(
"vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector"
)
@@ -525,6 +513,8 @@ def _make_read_scheduler():
request_id_to_transfer_id={},
transfer_id_to_request_id={},
_reqs_need_recv={},
_reqs_need_save={},
_reqs_need_send={},
_req_kv_params={},
_max_decode_tail_blocks=1,
)
@@ -538,24 +528,52 @@ def _make_read_request(remote_block_ids):
"transfer_id": "tx",
"remote_engine_id": "prefill",
"remote_block_ids": remote_block_ids,
"remote_host": "127.0.0.1",
"remote_handshake_port": 6000,
"remote_notify_port": 6001,
},
)
def test_update_state_drops_decode_recompute_tail_block():
@pytest.mark.parametrize("external_tokens", [0, 256])
@pytest.mark.parametrize("has_mamba", [False, True])
@pytest.mark.parametrize("zero_ids", [None, [], [101], [101, 102, 202, 999]])
def test_update_state_drops_decode_recompute_tail_block(
external_tokens, has_mamba, zero_ids
):
"""Only full hybrid READ destinations skip zeroing; local tails still zero."""
sched = _make_read_scheduler()
request = _make_read_request([[10, 11], [91]])
sched._has_mamba = has_mamba
remote_blocks = [[10, 11], [91]] if has_mamba else [[10, 11]]
request = _make_read_request(remote_blocks)
blocks = _FakeBlocks(
all_groups=([100, 101, 102], [200, 201, 202]),
all_groups=([100, 101, 102], [200, 201, 202])
if has_mamba
else ([100, 101, 102],),
)
sched.update_state_after_alloc(request, blocks, num_external_tokens=256)
sched.update_state_after_alloc(request, blocks, num_external_tokens=external_tokens)
assert sched._reqs_need_recv["req"][1] == [[100, 101], [202]]
assert sched._req_kv_params["req"]["remote_block_ids"] == [
[10, 11],
[91],
]
expected_blocks = [[100, 101] if external_tokens else []]
if has_mamba:
expected_blocks.append([202])
assert sched._reqs_need_recv["req"][1] == expected_blocks
assert sched._req_kv_params["req"]["remote_block_ids"] == remote_blocks
output = SchedulerOutput.make_empty()
output.new_block_ids_to_zero = None if zero_ids is None else list(zero_ids)
before = asdict(output)
meta = sched.build_connector_meta(output)
assert meta.reqs_to_recv["req"].local_block_ids == expected_blocks
if zero_ids and has_mamba and external_tokens:
before["new_block_ids_to_zero"] = zero_ids[1:]
assert asdict(output) == before
# A later local allocation of the same pages must still be zeroed.
output.new_block_ids_to_zero = [100, 101, 102]
meta = sched.build_connector_meta(output)
assert not meta.reqs_to_recv
assert output.new_block_ids_to_zero == [100, 101, 102]
def test_update_state_pairs_shorter_local_blocks_with_remote_suffix():
@@ -806,7 +824,7 @@ def test_get_num_new_matched_tokens_write_plain_keeps_all_tokens():
req = SimpleNamespace(
num_prompt_tokens=10,
prompt_token_ids=list(range(10)),
kv_transfer_params=None,
kv_transfer_params={"do_remote_prefill": True},
)
n, is_async = sched.get_num_new_matched_tokens(req, num_computed_tokens=2)
# Pure-attention WRITE: no N-1 drop; full length minus already-computed.
@@ -830,7 +848,7 @@ def test_get_num_new_matched_tokens_supports_embeds_only_prompts(
num_prompt_tokens=10,
prompt_token_ids=None,
prompt_embeds=object(),
kv_transfer_params=None,
kv_transfer_params={"do_remote_prefill": True},
)
assert sched.get_num_new_matched_tokens(req, num_computed_tokens) == (
@@ -661,16 +661,34 @@ def test_moriio_wrapper_rejects_invalid_messages(role, payload, match):
wrapper._handle_message(payload)
def test_local_block_ids_longer_than_remote_raises_value_error():
cache = torch.empty((8, 2, 4, 2, 3), dtype=torch.bfloat16)
def test_local_block_ids_longer_than_remote_raises():
# A longer local list is a genuine bug here and must fail loudly; the WRITE
# producer save path trims lookahead blocks before they reach this layer.
cache = torch.empty((8, 2, 4, 2, 3), dtype=torch.bfloat16) # interleaved
worker = _worker({"layer": cache}, {"layer": _full_spec()})
with pytest.raises(ValueError, match="longer than remote_block_ids"):
moriio_layout.compute_block_transfer_offsets(
"layer", cache, worker.layer_to_spec, [1, 3], [4], _remote_meta().num_blocks
"layer",
cache,
worker.layer_to_spec,
[1, 3, 6, 7],
[4, 5],
_remote_meta().num_blocks,
)
def test_shorter_local_block_ids_still_transfers_only_what_decode_allocated():
# READ-mode partial transfer keeps its shorter-local behavior.
cache = torch.empty((8, 2, 4, 2, 3), dtype=torch.bfloat16)
worker = _worker({"layer": cache}, {"layer": _full_spec()})
short = moriio_layout.compute_block_transfer_offsets(
"layer", cache, worker.layer_to_spec, [1], [4, 5], _remote_meta().num_blocks
)
assert len(short[0]) == 1
@pytest.mark.parametrize(
("local_block_ids", "remote_block_ids", "match"),
[
@@ -34,6 +34,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.nixl import (
NixlKVConnectorStats,
)
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput, KVConnectorWorkerMetadata
MODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct"
@@ -246,6 +247,18 @@ def test_multi_connector_rejects_multiple_mem_pool_contexts(mc: MultiConnector):
mc.get_mem_pool_context()
def test_cache_hit_sources_delegate_to_selected_connector(mc: MultiConnector):
request = MagicMock(request_id="request")
mc._requests_to_connector[request.request_id] = 1
sources = {CacheHitSource.DISK: 32}
mc._connectors[1].get_external_cache_hit_sources.return_value = sources
assert mc.get_external_cache_hit_sources(request, 32) is sources
mc._connectors[1].get_external_cache_hit_sources.assert_called_once_with(
request, 32
)
# Helper function to compare directories recursively
def _compare_directories(dir1: Path, dir2: Path) -> bool:
"""Compares two directories recursively for identical content."""
+347 -16
View File
@@ -14,7 +14,7 @@ from collections import defaultdict
from concurrent.futures import Future
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import MagicMock, patch
from unittest.mock import MagicMock, call, patch
import msgspec
import numpy as np
@@ -50,6 +50,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.nixl import (
NixlKVConnectorStats,
)
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.metadata import (
HeartbeatInfo,
RemoteMeta,
ReqMeta,
compute_nixl_compatibility_hash,
@@ -143,6 +144,7 @@ class FakeNixlWrapper:
def __init__(self, agent_name: str, *args, **kwargs):
self._cycles_before_xfer_done = 0
self._check_xfer_state_cycles: defaultdict[int, int] = defaultdict(lambda: 0)
self.invalid_remote_agents: set[str] = set()
def get_reg_descs(self, caches_data, memory_type: str) -> list:
return [str(uuid.uuid4()) for _ in caches_data]
@@ -163,6 +165,7 @@ class FakeNixlWrapper:
return self.AGENT_METADATA
def add_remote_agent(self, agent_metadata: bytes) -> str:
self.invalid_remote_agents.discard(self.REMOTE_AGENT_NAME)
return self.REMOTE_AGENT_NAME
def get_new_notifs(self) -> dict[str, list[bytes]]:
@@ -184,6 +187,9 @@ class FakeNixlWrapper:
def remove_remote_agent(self, agent: str) -> None:
pass
def check_remote_metadata(self, agent: str) -> bool:
return agent not in self.invalid_remote_agents
def send_notif(self, agent_name: str, notif_msg: bytes) -> None:
pass
@@ -895,11 +901,16 @@ class TestNixlHandshake:
vllm_config = create_vllm_config()
connector = NixlConnector(
vllm_config, KVConnectorRole.WORKER, make_kv_cache_config(block_size=16)
)
# num_blocks=1 keeps the fake handshake's region_num_blocks consistent
# with the minimal single-block registration below (num_descs == 1);
# _fa_desc_replicated cross-checks the two.
kv_cache_config = make_kv_cache_config(block_size=16, num_blocks=1)
connector = NixlConnector(vllm_config, KVConnectorRole.WORKER, kv_cache_config)
connector.connector_worker = FakeNixlConnectorWorker(
vllm_config, connector.engine_id, hand_shake_latency=0
vllm_config,
connector.engine_id,
hand_shake_latency=0,
kv_cache_config=kv_cache_config,
)
worker = connector.connector_worker
@@ -1117,17 +1128,24 @@ class TestNixlHandshake:
return
raise TimeoutError("Took too long to complete async handshake.")
@pytest.mark.parametrize(
("kv_cache_layout", "enable_permute_local_kv"),
# enable_permute_local_kv only covers a local LBNHC cache.
[("LBHNC", False), ("BLHNC", True)],
)
@patch(
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
FakeNixlWrapper,
)
def test_handshake_fails_on_kv_cache_layout_mismatch(
self, default_vllm_config, dist_init
self, default_vllm_config, dist_init, kv_cache_layout, enable_permute_local_kv
):
"""Verify that adding a remote agent fails if kv_cache_layout differs.
This test is only relevant for heterogeneous TP.
"""
vllm_config = create_vllm_config()
vllm_config = create_vllm_config(
enable_permute_local_kv=enable_permute_local_kv
)
# Mock TP world size to 2 to force heterogeneous TP when
# remote_tp_size=1
@@ -1140,7 +1158,10 @@ class TestNixlHandshake:
vllm_config, KVConnectorRole.WORKER, make_kv_cache_config(block_size=16)
)
connector.connector_worker = FakeNixlConnectorWorker(
vllm_config, connector.engine_id, hand_shake_latency=0
vllm_config,
connector.engine_id,
hand_shake_latency=0,
kv_cache_layout=kv_cache_layout,
)
worker = connector.connector_worker
@@ -2072,6 +2093,7 @@ def test_mixed_memory_local_descriptors_split_by_memory_type():
worker.kv_caches_base_addr = {"local": {0: [100, 200]}}
worker._has_mamba = False
worker._mixed_mem_types = True
worker._skip_dram_xfer = False
worker.region_mem_types = ["DRAM", "VRAM"]
worker.region_num_blocks = [2, 2]
worker._desc_is_dram_by_block_size = {}
@@ -2099,7 +2121,9 @@ def test_mixed_memory_local_descriptors_split_by_memory_type():
assert handle == 22
assert worker._dram_src_handles_by_block_size[worker.block_size] == 11
assert [block[2] for block in blocks] == [0, 0, 3, 3]
# Must stay an array: P_TP > D_TP splits call .tolist() on it.
assert isinstance(blocks, np.ndarray)
assert blocks[:, 2].tolist() == [0, 0, 3, 3]
memory_types = [
call.args[1] for call in worker.nixl_wrapper.get_xfer_descs.call_args_list
]
@@ -2124,6 +2148,8 @@ def recv_worker():
worker._handshake_futures = {}
worker._remote_agents = {}
worker._engine_by_address = {}
worker._failed_remote_engines = set()
worker._invalid_remote_engines = set()
worker._replicated_pcp_done_sending = set()
worker._invalid_block_ids = queue.Queue()
worker._pending_recv_notifs = {}
@@ -2135,6 +2161,7 @@ def recv_worker():
worker.enable_permute_local_kv = False
worker.enable_heterogeneous_attn_post_process = False
worker.tp_rank = 0
worker._skip_dram_xfer = False
worker._log_failure = MagicMock() # type: ignore[method-assign]
worker.xfer_stats = NixlKVConnectorStats()
worker.nixl_wrapper = MagicMock()
@@ -2192,6 +2219,66 @@ def test_mixed_memory_read_failure_does_not_notify_producer(recv_worker):
worker.nixl_wrapper.send_notif.assert_not_called()
def test_hisparse_dram_rank0_only_read_keeps_device_part(recv_worker):
worker = recv_worker
worker.tp_rank = 1
worker._skip_dram_xfer = True
worker._desc_is_dram_by_block_size = {16: np.array([True, True, False, False])}
worker._desc_pos_by_block_size = {16: np.array([0, 1, 0, 1])}
worker._dram_src_handles_by_block_size = {16: None}
worker.nixl_wrapper.make_prepped_xfer.side_effect = [102]
worker.nixl_wrapper.check_xfer_state.return_value = "DONE"
worker._read_blocks_mixed(
request_id="request",
local_block_size_key=16,
local_device_handle=20,
local_dram_handle=None,
remote_xfer_side_handle=30,
local_block_descs_ids=np.array([0, 2]),
remote_block_descs_ids=np.array([5, 7]),
notif_agent="prefill",
notif_id=b"request:1",
)
(device_read,) = worker.nixl_wrapper.make_prepped_xfer.call_args_list
assert device_read.args[:2] == ("READ", 20)
np.testing.assert_array_equal(device_read.args[2], [0])
np.testing.assert_array_equal(device_read.args[4], [7])
assert worker.get_finished() == (set(), {"request"})
worker.nixl_wrapper.send_notif.assert_called_once_with(
"prefill", notif_msg=b"request:1"
)
def test_hisparse_dram_rank0_only_dram_only_read_completes(recv_worker):
"""With nothing left to read, the request still completes and notifies."""
worker = recv_worker
worker.tp_rank = 1
worker._skip_dram_xfer = True
worker._desc_is_dram_by_block_size = {16: np.array([True, True, False, False])}
worker._desc_pos_by_block_size = {16: np.array([0, 1, 0, 1])}
worker._read_blocks_mixed(
request_id="request",
local_block_size_key=16,
local_device_handle=20,
local_dram_handle=None,
remote_xfer_side_handle=30,
local_block_descs_ids=np.array([0, 1]),
remote_block_descs_ids=np.array([5, 6]),
notif_agent="prefill",
notif_id=b"request:1",
)
worker.nixl_wrapper.make_prepped_xfer.assert_not_called()
assert worker.get_finished() == (set(), {"request"})
worker.nixl_wrapper.send_notif.assert_called_once_with(
"prefill", notif_msg=b"request:1"
)
def element_byte_addrs(view: torch.Tensor) -> list[int]:
"""Absolute byte addresses of every element of a (possibly strided) view."""
offsets = torch.zeros(view.shape, dtype=torch.int64)
@@ -2700,6 +2787,51 @@ def test_engine_with_inflight_transfer_is_not_evicted(default_vllm_config, dist_
assert mock_rem.call_count == 2
@patch(
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
FakeNixlWrapper,
)
def test_heartbeated_engine_is_not_evicted(default_vllm_config, dist_init, monkeypatch):
"""Heartbeats keep a remote engine's NIXL state alive.
Requests waiting in the D scheduler issue no reads, but their engine is
heartbeated through its remote agents. If the TTL expires anyway, the
next heartbeat evicts the engine and starts a new handshake, which loads
every remote agent again.
"""
from vllm.distributed.kv_transfer.kv_connector.v1.nixl import base_worker
worker, engine_id = _setup_worker_with_remote_engine(engine_ttl=10.0)
nixl_wrapper = worker.nixl_wrapper
now = {"t": 1000.0}
monkeypatch.setattr(base_worker.time, "perf_counter", lambda: now["t"])
worker._engine_last_active[engine_id] = now["t"]
metadata = NixlConnectorMetadata()
metadata.heartbeat_by_engine = {
engine_id: HeartbeatInfo(
req_ids={"remote-req"}, host="localhost", port=1234, tp_size=2
)
}
with (
patch.object(nixl_wrapper, "send_notif") as mock_send,
patch.object(nixl_wrapper, "remove_remote_agent") as mock_rem,
patch.object(worker, "_handshake_initiation_executor") as mock_executor,
):
# One heartbeat every 5 s for twice the TTL, and no reads.
for _ in range(4):
now["t"] += 5.0
worker._send_heartbeats(metadata)
assert engine_id in worker._remote_agents
mock_rem.assert_not_called()
mock_executor.submit.assert_not_called()
# Every heartbeat reached both remote agents.
assert mock_send.call_count == 8
@patch(
"vllm.distributed.kv_transfer.kv_connector.v1.nixl.base_worker.NixlWrapper",
FakeNixlWrapper,
@@ -2761,9 +2893,9 @@ class TestPeerReplacement:
self.nixl.REMOTE_AGENT_NAME = engine_id
future.set_result(self.worker._nixl_handshake(host, port, 1, engine_id))
def _request(self, engine_id="new", blocks=(1,), awaiting_kvs=True):
def _request(self, engine_id="new", blocks=(1,), awaiting_kvs=True, req_id=None):
metadata = NixlConnectorMetadata()
metadata.reqs_to_recv[f"{engine_id}-req"] = ReqMeta(
metadata.reqs_to_recv[req_id or f"{engine_id}-req"] = ReqMeta(
local_block_ids=(blocks,),
local_physical_block_ids=(blocks,),
tp_size=1,
@@ -2774,6 +2906,11 @@ class TestPeerReplacement:
)
return metadata
def _fail_old_peer(self):
self.worker.start_load_kv(self._request("old"))
self.nixl.invalid_remote_agents.add("old")
self.transport.check_xfer_state.return_value = "ERR"
def test_cleans_old_peer_after_confirmed_handshake(self):
self._connect("healthy", host="other-host")
old_handle = self.worker.dst_xfer_side_handles["old"][0]
@@ -2823,7 +2960,12 @@ class TestPeerReplacement:
],
ids=["healthy", "failed-sibling-completes", "failed-sibling-fails"],
)
def test_waits_for_reads_before_cleanup_and_failure_reporting(self, states, failed):
@pytest.mark.parametrize("invalidated", [False, True])
def test_waits_for_reads_before_cleanup_and_failure_reporting(
self, states, failed, invalidated
):
if invalidated:
self.nixl.invalid_remote_agents.add("old")
self.worker._recving_metadata.update(self._request("old").reqs_to_recv)
self.worker._recving_transfers["old-req"] = [1, 2] if failed else [1]
self.transport.check_xfer_state.side_effect = states
@@ -2842,6 +2984,7 @@ class TestPeerReplacement:
)
assert self.transport.release_xfer_handle.call_count == (2 if failed else 1)
self.transport.remove_remote_agent.assert_called_once_with("old")
assert not self.worker._invalid_remote_engines
def test_waits_for_queued_notification(self):
metadata = self._request("old", blocks=())
@@ -2862,22 +3005,31 @@ class TestPeerReplacement:
assert result.failed_recving == set()
self.transport.remove_remote_agent.assert_called_once_with("old")
def test_waits_for_other_handshakes(self):
@pytest.mark.parametrize("invalidated", [False, True])
def test_waits_for_other_handshakes(self, invalidated):
if invalidated:
self._fail_old_peer()
else:
self._connect()
self.worker._ensure_handshake("other", "other-host", 1234, 1)
self._connect()
self.worker.get_transfer_results()
self.transport.remove_remote_agent.assert_not_called()
self.transport.check_remote_metadata.assert_not_called()
self._connect("other", host="other-host")
self.worker.get_transfer_results()
self.transport.remove_remote_agent.assert_called_once_with("old")
def test_rehandshakes_queued_request_for_released_engine(self):
@pytest.mark.parametrize("invalidated", [False, True])
def test_rehandshakes_queued_request_for_released_engine(self, invalidated):
# A request queued after its engine's handshake, but drained only after
# that engine was replaced and released, must not read from it.
if invalidated:
self._fail_old_peer()
metadata = self._request("old", blocks=(), awaiting_kvs=False)
self.worker._ready_requests.put(("old-req", metadata.reqs_to_recv["old-req"]))
self._connect()
if not invalidated:
self._connect()
self.worker.get_transfer_results()
self.transport.remove_remote_agent.assert_called_once_with("old")
@@ -2885,6 +3037,185 @@ class TestPeerReplacement:
assert "old" in self.worker._handshake_futures
self.transport.send_notif.assert_not_called()
@pytest.mark.parametrize("missing", [False, True, RuntimeError("probe failed")])
def test_recovery_requires_confirmed_missing_metadata(self, missing):
self._fail_old_peer()
# A missing rank suffices even if another rank still has metadata.
self.worker._remote_agents["old"][(0, 1)] = "old-other-rank"
self.nixl.invalid_remote_agents.clear()
if missing is True:
self.nixl.invalid_remote_agents.add("old-other-rank")
elif isinstance(missing, Exception):
self.transport.check_remote_metadata.side_effect = missing
result = self.worker.get_transfer_results()
assert result.finished_recving == result.failed_recving == {"old-req"}
assert self.worker.get_block_ids_with_load_errors() == {1}
assert ("old" not in self.worker._remote_agents) is (missing is True)
assert self.transport.release_dlist_handle.call_count == (missing is True)
@pytest.mark.parametrize("handshake_fails", [False, True])
def test_recovery_rehandshakes_same_id_with_fresh_descriptors(
self, handshake_fails
):
old_handle = self.worker.dst_xfer_side_handles["old"][0]
self._fail_old_peer()
self.worker.get_transfer_results()
self.transport.release_dlist_handle.assert_called_once_with(old_handle)
assert not self.worker._engine_by_address
with pytest.raises(KeyError):
self.worker.transfer_topo.get_engine_info("old")
self.transport.make_prepped_xfer.reset_mock()
self.worker.start_load_kv(self._request("old", req_id="next"))
self.transport.make_prepped_xfer.assert_not_called()
if handshake_fails:
self.worker._handshake_futures["old"].set_exception(
RuntimeError("handshake failed")
)
result = self.worker.get_transfer_results()
assert result.failed_recving == result.finished_recving == {"next"}
assert "old" not in self.worker._remote_agents
assert self.worker._ready_requests.empty()
return
self._connect("old")
fresh_handle = self.worker.dst_xfer_side_handles["old"][0]
assert fresh_handle != old_handle
assert self.worker._engine_by_address == {("localhost", 1234): "old"}
self.transport.check_xfer_state.return_value = "DONE"
self.worker.start_load_kv(NixlConnectorMetadata())
assert self.transport.make_prepped_xfer.call_args.args[3] == fresh_handle
result = self.worker.get_transfer_results()
assert result.finished_recving == {"next"} and not result.failed_recving
self.transport.release_dlist_handle.assert_called_once_with(old_handle)
def test_recovery_drains_reads_and_rejects_new_ones_without_harming_other_peers(
self,
):
self._connect("healthy", host="other-host")
self.worker._recving_metadata.update(self._request("old").reqs_to_recv)
self.worker._recving_metadata.update(self._request("healthy").reqs_to_recv)
self.worker._recving_transfers.update(
{"old-req": [10, 11], "healthy-req": [12]}
)
self.nixl.invalid_remote_agents.add("old")
self.transport.check_xfer_state.side_effect = (
lambda h: "ERR" if h == 10 else "PROC"
)
old_handle = self.worker.dst_xfer_side_handles["old"][0]
result = self.worker.get_transfer_results()
assert not result.finished_recving and not result.failed_recving
self.transport.release_dlist_handle.assert_not_called()
self.worker.start_load_kv(self._request("old", req_id="blocked"))
self.transport.make_prepped_xfer.assert_not_called()
self.transport.check_xfer_state.side_effect = (
lambda h: "DONE" if h == 11 else "PROC"
)
result = self.worker.get_transfer_results()
assert (
result.finished_recving == result.failed_recving == {"old-req", "blocked"}
)
assert set(self.worker._remote_agents) == {"healthy"}
assert self.worker._recving_transfers == {"healthy-req": [12]}
self.transport.remove_remote_agent.assert_called_once_with("old")
calls = self.transport.mock_calls
assert calls.index(call.release_xfer_handle(11)) < calls.index(
call.release_dlist_handle(old_handle)
)
def test_repeated_invalidation_backs_off_before_rehandshake(self):
# A peer that is invalidated again soon after recovery (eg a persistent
# RDMA fault) must not re-handshake on every request.
self._fail_old_peer()
self.worker.get_transfer_results()
self.transport.remove_remote_agent.assert_called_once_with("old")
self._connect("old")
self._fail_old_peer()
assert self.worker.get_transfer_results().failed_recving == {"old-req"}
assert "old" in self.worker._remote_agents
self.transport.make_prepped_xfer.reset_mock()
self.worker.start_load_kv(self._request("old", req_id="next"))
assert self.worker.get_transfer_results().failed_recving == {"next"}
self.transport.make_prepped_xfer.assert_not_called()
assert "old" not in self.worker._handshake_futures
self.transport.remove_remote_agent.assert_called_once()
backoff, release_at = self.worker._invalid_engine_backoff["old"]
assert backoff == 1.0
self.worker._invalid_engine_backoff["old"] = (backoff, release_at - backoff)
self.worker.get_transfer_results()
assert self.transport.remove_remote_agent.call_count == 2
assert "old" not in self.worker._remote_agents
def test_recovery_waits_until_failed_handle_can_be_released(self):
self._fail_old_peer()
with patch.object(
self.transport, "release_xfer_handle", side_effect=RuntimeError("in use")
):
result = self.worker.get_transfer_results()
assert not result.finished_recving and not result.failed_recving
assert self.worker._recving_transfers["old-req"]
self.transport.release_dlist_handle.assert_not_called()
result = self.worker.get_transfer_results()
assert result.finished_recving == result.failed_recving == {"old-req"}
self.transport.remove_remote_agent.assert_called_once_with("old")
@pytest.mark.parametrize("expired", [False, True])
def test_success_and_expiry_do_not_probe_metadata(self, expired):
metadata = self._request("old")
if expired:
metadata.reqs_to_recv["old-req"].remote.blocks_expiry_time = 0.0
self.worker._bidirectional_kv_xfer_enabled = True
with (
patch.object(self.worker.xfer_stats, "record_failed_transfer") as failure,
patch.object(self.worker.xfer_stats, "record_kv_expired_req") as expiry,
):
self.worker.start_load_kv(metadata)
result = self.worker.get_transfer_results()
assert result.finished_recving == {"old-req"}
assert result.failed_recving == ({"old-req"} if expired else set())
assert expiry.call_count == int(expired)
failure.assert_not_called()
self.transport.check_remote_metadata.assert_not_called()
self.transport.remove_remote_agent.assert_not_called()
@pytest.mark.parametrize("awaiting_kvs", [False, True])
def test_invalid_peer_empty_recv_is_reported_only_when_awaited(self, awaiting_kvs):
self._fail_old_peer()
self.worker._recving_transfers["old-req"].append(11)
self.transport.check_xfer_state.side_effect = (
lambda h: "PROC" if h == 11 else "ERR"
)
self.worker.get_transfer_results()
self.transport.make_prepped_xfer.reset_mock()
self.worker.start_load_kv(
self._request("old", blocks=(), awaiting_kvs=awaiting_kvs, req_id="empty")
)
result = self.worker.get_transfer_results()
expected = {"empty"} if awaiting_kvs else set()
assert result.finished_recving == result.failed_recving == expected
self.transport.make_prepped_xfer.assert_not_called()
self.transport.send_notif.assert_not_called()
self.transport.remove_remote_agent.assert_not_called()
def test_eviction_clears_pending_recovery(self):
self.worker._failed_remote_engines.add("old")
self.worker._invalid_remote_engines.add("old")
self.worker._engine_ttl = 1
self.worker._engine_last_active["old"] = time.perf_counter() - 10
self.worker._evict_stale_engines()
self.worker.get_transfer_results()
self.transport.remove_remote_agent.assert_called_once_with("old")
assert not self.worker._failed_remote_engines
assert not self.worker._invalid_remote_engines
def test_transfer_topology_unregister():
"""TransferTopology.unregister_remote_engine removes the engine."""
@@ -60,6 +60,8 @@ def region_pull_worker():
worker._transfer_layer_group_ids = ()
worker._bidirectional_kv_xfer_enabled = False
worker._recving_transfers = {}
worker._failed_remote_engines = set()
worker._invalid_remote_engines = set()
worker.use_mla, worker._has_mamba = True, False
worker.dcp_size = 1
worker.dcp_rank = 0
@@ -265,6 +267,7 @@ def test_region_pull_completion_zeros_only_own_padding(region_pull_worker):
worker.region_num_blocks = [4, 4]
worker.block_len_per_layer = [8, 8]
worker.block_stride_per_layer = [24, 24]
worker._skip_dram_xfer = False
worker._recving_metadata = {
"request": ReqMeta(
local_block_ids=[[1, 2], [0, 1]],
@@ -690,6 +693,8 @@ def test_read_blocks_for_req_expands_remote_ids(
worker = object.__new__(NixlConnectorWorker)
worker._physical_blocks_per_logical_kv_block = local_physical_per_logical
worker._invalid_remote_engines = set()
worker._remote_agents = {"remote-engine": {}}
worker._engine_last_active = {}
worker._recving_transfers = {}
worker._bidirectional_kv_xfer_enabled = False
@@ -1399,46 +1404,66 @@ def test_map_block_ids_for_block_size_ratio_hybrid():
@pytest.mark.cpu_test
def test_post_process_zeroes_untransferred_tail():
"""The untransferred sub-blocks of the last local block are zeroed on
receive; mamba state caches are untouched by the attention permute."""
@pytest.mark.parametrize(
("kv_cache_layout", "enable_permute_local_kv"),
[("LBHNC", False), ("LBNHC", False), ("LBNHC", True)],
)
def test_post_process_zeroes_untransferred_tail(
kv_cache_layout, enable_permute_local_kv
):
"""Received remote sub-blocks are regrouped per head and the untransferred
sub-blocks of the last local block are zeroed on receive, once per block
although two attention groups alias the tensor."""
from unittest.mock import MagicMock
from vllm.distributed.kv_transfer.kv_connector.v1.nixl.worker import (
NixlConnectorWorker,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec, MambaSpec
ratio = 4
block_tokens = 8 # 2 tokens per remote sub-block
num_kv_heads = 2 # fewer than ratio
worker = MagicMock(spec=NixlConnectorWorker)
worker._group_spec_types = (FullAttentionSpec, MambaSpec)
worker.transfer_topo = MagicMock()
worker.device_type = "cpu"
worker.enable_permute_local_kv = False
attn_cache = torch.ones(6, block_tokens, 2, 4)
mamba_cache = torch.ones(6, 16)
worker.device_kv_caches = {"attn.0": attn_cache, "mamba.0": mamba_cache}
worker.enable_permute_local_kv = enable_permute_local_kv
worker.kv_cache_layout = kv_cache_layout
# Attention caches are [B, H, N, C]; distinct values per head and token.
expected = torch.arange(6 * num_kv_heads * block_tokens * 4).view(
6, num_kv_heads, block_tokens, 4
)
# Blocks [2, 3] as received: `ratio` head-major remote sub-blocks each.
received = (
expected[2:4]
.unflatten(2, (ratio, -1))
.transpose(1, 2)
.reshape(2, num_kv_heads, block_tokens, 4)
)
if kv_cache_layout == "LBNHC":
attn_cache = expected.transpose(1, 2).contiguous().transpose(1, 2)
if enable_permute_local_kv:
# The remote is LBHNC: its bytes land in token-major memory.
attn_cache.transpose(1, 2)[2:4] = received.view(2, block_tokens, -1, 4)
# Otherwise token-major blocks receive the sub-blocks in token order.
else:
attn_cache = expected.clone()
attn_cache[2:4] = received
worker.device_kv_caches = {"attn.0": attn_cache, "swa.0": attn_cache}
fa_group = MagicMock(layer_names=["attn.0"])
ssm_group = MagicMock(layer_names=["mamba.0"])
worker.kv_cache_config = MagicMock(transfer_groups=[fa_group, ssm_group])
# The cached property filters mamba layers out of the permuted caches.
attn_caches = NixlConnectorWorker._attention_kv_caches.func(worker)
assert len(attn_caches) == 1 and attn_caches[0] is attn_cache
worker._attention_kv_caches = attn_caches
swa_group = MagicMock(layer_names=["swa.0"])
worker.kv_cache_config = MagicMock(transfer_groups=[fa_group, swa_group])
_bind_worker_method(worker, "post_process_device_kv_on_receive")
# Request occupies blocks [2, 3]; only 6 of 8 sub-blocks were received.
worker.post_process_device_kv_on_receive(ratio, [([2, 3], 6)])
# Group 0 request in blocks [2, 3]; only 6 of 8 sub-blocks were received.
worker.post_process_device_kv_on_receive(ratio, [(0, [2, 3], 6)])
# Block 2 fully covered; block 3 covered for 2 sub-blocks (4 tokens).
assert torch.all(attn_cache[2] == 1)
assert torch.all(attn_cache[3, :4] == 1)
assert torch.all(attn_cache[3, 4:] == 0)
# Untouched blocks and the mamba cache keep their content.
assert torch.all(attn_cache[4] == 1)
assert torch.all(mamba_cache == 1)
assert torch.equal(attn_cache[2], expected[2])
assert torch.equal(attn_cache[3, :, :4], expected[3, :, :4])
assert torch.all(attn_cache[3, :, 4:] == 0)
# Untouched blocks keep their content.
assert torch.equal(attn_cache[4], expected[4])
@pytest.mark.cpu_test
@@ -1555,17 +1580,22 @@ def test_failed_load_rezeroes_unwritten_skipped_blocks():
@pytest.mark.cpu_test
@pytest.mark.parametrize(
"has_mamba,is_hma_required,expected_count",
"has_mamba,is_hma_required,bounded_replay,expected_count",
[
(True, True, 9),
(False, False, 10),
(False, True, 10),
(True, True, False, 9),
(False, False, False, 10),
(False, True, False, 10),
(False, True, True, 9),
],
ids=["mamba", "fa_only", "swa_only"],
ids=["mamba", "fa_only", "swa_only", "swa_bounded_replay"],
)
def test_mamba_n1_d_side(has_mamba, is_hma_required, expected_count):
"""D-side: Mamba gets N-1 matched tokens, non-Mamba gets N."""
sched = make_nixl_scheduler(has_mamba=has_mamba, is_hma_required=is_hma_required)
def test_mamba_n1_d_side(has_mamba, is_hma_required, bounded_replay, expected_count):
"""D-side: Mamba and SWA bounded replay get N-1 matched tokens, others N."""
sched = make_nixl_scheduler(
has_mamba=has_mamba,
is_hma_required=is_hma_required,
bounded_replay=bounded_replay,
)
req = create_request(num_tokens=10, do_remote_prefill=True)
count, is_async = sched.get_num_new_matched_tokens(req, num_computed_tokens=0)
@@ -1634,6 +1664,20 @@ def test_mamba_n1_p_side_truncation():
fa_sched.on_new_request(fa_req)
assert len(fa_req.prompt_token_ids) == fa_original
# SWA bounded replay: the window is not replayed after the load, so the
# prefiller stops short of the last token too.
swa_sched = make_nixl_scheduler(is_hma_required=True, bounded_replay=True)
swa_req = create_request(num_tokens=10, do_remote_decode=True)
swa_sched.on_new_request(swa_req)
assert len(swa_req.prompt_token_ids) == 9
# A request that skips reading the prefix cache (prompt logprobs) is not
# cut: the decoder loads nothing and recomputes its whole prompt.
logprobs_req = create_request(num_tokens=10, do_remote_decode=True)
logprobs_req.sampling_params.skip_reading_prefix_cache = True
swa_sched.on_new_request(logprobs_req)
assert len(logprobs_req.prompt_token_ids) == 10
@pytest.mark.cpu_test
@pytest.mark.parametrize(
@@ -1245,8 +1245,12 @@ def test_mismatched_mla_kernel_page_rejected_for_mla_hybrid():
worker.add_remote_agent(meta_r, remote_tp_rank=0, remote_tp_size=2)
def _make_csa_linear_ple_worker(scratch_aliases: str = "compressed"):
"""``scratch_aliases`` selects which pages the compressor ring overlays."""
def _make_csa_linear_ple_worker(
scratch_aliases: str = "compressed", ple_page_size: int = 256
):
"""``scratch_aliases`` selects which pages the compressor ring overlays;
``ple_page_size`` widens the PLE page beyond the page it shares a region
with (block-outer layout: both start at byte 0 of the block)."""
from unittest.mock import MagicMock
from vllm.config import set_current_vllm_config
@@ -1305,7 +1309,7 @@ def _make_csa_linear_ple_worker(scratch_aliases: str = "compressed"):
block_size=1,
shapes=((6, 3),),
dtypes=(torch.float16,),
page_size_padded=256,
page_size_padded=ple_page_size,
mamba_type=MambaAttentionBackendEnum.SHORT_CONV,
tp_replicated=True,
)
@@ -1339,17 +1343,22 @@ def _make_csa_linear_ple_worker(scratch_aliases: str = "compressed"):
("compressed.0",),
("compressed.1",),
)
region_size = 512
page_size = 256
# Region 0 hosts the PLE page: its blocks are as wide as the widest page.
block_strides = [max(page_size, ple_page_size)] + [page_size] * (
len(tensor_regions) - 1
)
region_sizes = [2 * stride for stride in block_strides]
region_offsets = [sum(region_sizes[:index]) for index in range(len(region_sizes))]
kv_cache_config = KVCacheConfig(
num_blocks=2,
kv_cache_tensors=[
KVCacheTensor(
size=len(tensor_regions) * region_size,
size=sum(region_sizes),
layers=[layer_name],
layer_stride=region_size,
block_stride=page_size,
offset=region_index * region_size,
layer_stride=region_sizes[region_index],
block_stride=block_strides[region_index],
offset=region_offsets[region_index],
)
for region_index, layer_names in enumerate(tensor_regions)
for layer_name in layer_names
@@ -1386,10 +1395,14 @@ def _make_csa_linear_ple_worker(scratch_aliases: str = "compressed"):
set_current_vllm_config(vllm_config),
):
worker = NixlConnectorWorker(vllm_config, "local-engine", kv_cache_config)
tensors = [torch.zeros((2, 256), dtype=torch.uint8) for _ in range(4)]
tensors = [
torch.zeros((2, stride), dtype=torch.uint8) for stride in block_strides
]
worker.register_kv_caches(
{
layer_name: tensors[region_index]
layer_name: tensors[region_index][
:, : (ple_page_size if layer_name == "mamba.ple" else page_size)
]
for region_index, layer_names in enumerate(tensor_regions)
for layer_name in layer_names
}
@@ -1523,6 +1536,7 @@ def test_csa_linear_remote_ple_is_copied_whole():
kv_cache_layout="HND",
block_size=4,
ssm_sizes=(24, 32),
ple_block_len=256,
attn_backend_name="test",
physical_blocks_per_logical_kv_block=1,
)
@@ -1535,7 +1549,7 @@ def test_csa_linear_remote_ple_is_copied_whole():
assert descriptors[-2:, 0].tolist() == [0x10000, 0x10100]
assert descriptors[-2:, 1].tolist() == [256, 256]
metadata.block_lens[0] = 128
metadata.ple_block_len = 128
with pytest.raises(ValueError, match="PLE pages require identical"):
worker._build_mamba_remote(
metadata,
@@ -1544,6 +1558,30 @@ def test_csa_linear_remote_ple_is_copied_whole():
)
@pytest.mark.cpu_test
def test_csa_linear_ple_page_wider_than_the_shared_region_page():
"""The PLE page is discovered in the region of the main KV page registered
first (both start at byte 0 of the block); its descriptors must still cover
the whole PLE page, not the region's block_len."""
worker = _make_csa_linear_ple_worker(ple_page_size=384)
assert worker._ple_region_index == 0
assert worker.block_len_per_layer[0] == 256
assert worker.block_stride_per_layer[0] == 384
assert worker._ple_block_len == 384
bases = [0x10000, 0x20000, 0x30000, 0x40000]
mamba = worker._build_mamba_local(bases)
assert mamba[-2:, 0].tolist() == [0x10000, 0x10000 + 384]
assert mamba[-2:, 1].tolist() == [384, 384]
metadata = msgspec.msgpack.decode(
worker.xfer_handshake_metadata.agent_metadata_bytes, type=NixlAgentMetadata
)
assert metadata.ple_block_len == 384
assert metadata.block_lens[0] == 256
def _make_ring_worker():
"""Paged MLA group plus a per-layer ring group, no Mamba: the shape of a
model whose sliding-window KV lives in per-request rings."""
@@ -379,6 +379,8 @@ class _StubWriterWorker(NixlPushConnectorWorker):
w.pp_size = 1
w.engine_id = "test-decode-engine"
w._remote_agents = {}
w._failed_remote_engines = set()
w._invalid_remote_engines = set()
w._handshake_lock = threading.RLock()
w._physical_blocks_per_logical_kv_block = 1
w._uses_region_group_mapping = False
@@ -36,6 +36,7 @@ from vllm.v1.kv_cache_interface import (
KVCacheTensor,
SlidingWindowSpec,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput
from vllm.v1.request import Request
from vllm.v1.simple_kv_offload.metadata import (
@@ -232,6 +233,9 @@ def test_nixl_wins_load_over_cpu_offload():
assert not sched_out.has_sync_kv_loads
assert mc._requests_to_connector[request.request_id] == 0
assert mc.get_external_cache_hit_sources(request, 2 * BLOCK_SIZE) == {
CacheHitSource.P2P: 2 * BLOCK_SIZE
}
meta = sched_out.kv_connector_metadata
assert isinstance(meta, MultiKVConnectorMetadata)
@@ -302,6 +306,9 @@ def test_cpu_offload_wins_when_nixl_has_no_match():
assert hit_tokens is not None and hit_tokens > 0
assert mc._requests_to_connector[req2.request_id] == 1
assert is_async is True
assert mc.get_external_cache_hit_sources(req2, hit_tokens) == {
CacheHitSource.HOST: hit_tokens
}
@pytest.mark.parametrize("swa_enabled", [False, True], ids=["fa_only", "fa_sw"])
+13
View File
@@ -6,6 +6,7 @@ from collections.abc import Callable
from dataclasses import dataclass
from itertools import chain, count
from typing import Any, Literal
from unittest.mock import Mock
import torch
@@ -42,6 +43,7 @@ from vllm.v1.kv_cache_interface import (
MambaSpec,
SlidingWindowSpec,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
@@ -49,6 +51,14 @@ from vllm.v1.structured_output import StructuredOutputManager
EOS_TOKEN_ID = 50256
def create_mock_connector() -> Mock:
connector = Mock()
connector.get_external_cache_hit_sources.side_effect = lambda request, num_tokens: (
{CacheHitSource.EXTERNAL_UNSPECIFIED: num_tokens} if num_tokens else {}
)
return connector
def assert_scheduler_empty(scheduler: Scheduler):
"""Confirm the scheduler is "empty" - i.e. no leaks."""
# Scheduler Metadata.
@@ -522,6 +532,7 @@ def make_kv_cache_config(
def make_nixl_scheduler(
has_mamba: bool = False,
is_hma_required: bool = False,
bounded_replay: bool = False,
heartbeat: bool = False,
kv_lease_duration: int = 30,
):
@@ -538,6 +549,7 @@ def make_nixl_scheduler(
sched = object.__new__(NixlConnectorScheduler)
sched._has_mamba = has_mamba
sched._bounded_replay = bounded_replay
sched._is_hma_required = is_hma_required
sched.kv_cache_config = make_kv_cache_config(
block_size=16,
@@ -605,6 +617,7 @@ def make_nixl_push_scheduler(
sched.side_channel_port = 5600
sched.is_bidirectional_kv_xfer_enabled = is_bidirectional_kv_xfer_enabled
sched._has_mamba = has_mamba
sched._bounded_replay = False
sched.kv_cache_config = make_kv_cache_config(
block_size=16,
mamba_enabled=has_mamba,
@@ -772,17 +772,14 @@ def test_cleanup_idempotent(iid):
def test_cleanup_unregisters_every_pinned_chunk(iid, monkeypatch):
"""cleanup() must release every chunk from a split host registration."""
r = _make_region(iid)
cudart = MagicMock()
cudart.cudaHostUnregister.return_value = MagicMock(value=0)
monkeypatch.setattr(region_module, "current_platform", MagicMock())
region_module.current_platform.is_cuda_alike.return_value = True
monkeypatch.setattr(region_module.torch.cuda, "cudart", lambda: cudart)
unregister = MagicMock()
monkeypatch.setattr(region_module, "host_unregister", unregister)
r.pinned_addresses = [0x100000, 0x200000, 0x300000]
r.is_pinned = True
r.cleanup()
assert cudart.cudaHostUnregister.call_args_list == [
assert unregister.call_args_list == [
call(0x300000),
call(0x200000),
call(0x100000),
@@ -791,40 +788,35 @@ def test_cleanup_unregisters_every_pinned_chunk(iid, monkeypatch):
@pytest.fixture
def host_register(monkeypatch):
"""Pretend to run on CUDA with host registrations capped at seven pages.
Registration goes to a mock CudaRTLibrary and the region's cleanup to a
separate mock torch runtime. Both stay installed through the cleanup that
``_region`` runs on exit.
"""Mock the cross-platform host_register/host_unregister helpers with
registrations capped at seven pages. The same unregister mock backs both
pin_mmap_region's rollback path and the region's cleanup() on exit from
``_region``.
"""
cudart = MagicMock()
cudart.cudaHostRegister.return_value = 0
cudart.cudaHostUnregister.return_value = 0
cudart.cudaGetLastError.return_value = 2
torch_cudart = MagicMock()
torch_cudart.cudaHostUnregister.return_value = MagicMock(value=0)
monkeypatch.setattr(gpu_worker.current_platform, "is_cuda_alike", lambda: True)
register = MagicMock(return_value=True)
unregister = MagicMock()
monkeypatch.setattr(gpu_worker, "MAX_HOST_REGISTER_CHUNK_BYTES", 7 * PAGE_SIZE)
monkeypatch.setattr(gpu_worker, "CudaRTLibrary", lambda: cudart)
monkeypatch.setattr(region_module.torch.cuda, "cudart", lambda: torch_cudart)
return cudart, torch_cudart
monkeypatch.setattr(gpu_worker, "host_register", register)
monkeypatch.setattr(gpu_worker, "host_unregister", unregister)
monkeypatch.setattr(region_module, "host_unregister", unregister)
return register, unregister
def test_pin_mmap_region_registers_row_aligned_chunks(iid, host_register):
"""Chunks end on row boundaries: 3-page rows under a 7-page cap register
as 6 + 6 + 3 pages, where a raw byte cap would give 7 + 7 + 1."""
cudart, torch_cudart = host_register
register, unregister = host_register
with _region(iid, num_chunks=5, cpu_page_size=3 * PAGE_SIZE) as region:
gpu_worker.pin_mmap_region(region)
base = region._base.data_ptr()
assert cudart.mock_calls == [
call.cudaHostRegister(base, 6 * PAGE_SIZE),
call.cudaHostRegister(base + 6 * PAGE_SIZE, 6 * PAGE_SIZE),
call.cudaHostRegister(base + 12 * PAGE_SIZE, 3 * PAGE_SIZE),
assert register.call_args_list == [
call(base, 6 * PAGE_SIZE),
call(base + 6 * PAGE_SIZE, 6 * PAGE_SIZE),
call(base + 12 * PAGE_SIZE, 3 * PAGE_SIZE),
]
assert region.is_pinned
assert torch_cudart.cudaHostUnregister.call_args_list == [
assert unregister.call_args_list == [
call(base + 12 * PAGE_SIZE),
call(base + 6 * PAGE_SIZE),
call(base),
@@ -833,10 +825,10 @@ def test_pin_mmap_region_registers_row_aligned_chunks(iid, host_register):
@pytest.mark.parametrize("fail_at", [0, 1, 2])
def test_pin_mmap_region_failure_leaves_region_pageable(iid, host_register, fail_at):
"""A failed chunk drains its pending error and unregisters the chunks
before it on the same handle, so the region is pinned whole or not at all."""
cudart, torch_cudart = host_register
cudart.cudaHostRegister.side_effect = [0] * fail_at + [2]
"""A failed chunk unregisters the chunks before it on the same range, so
the region is pinned whole or not at all."""
register, unregister = host_register
register.side_effect = [True] * fail_at + [False]
with _region(iid, num_chunks=5, cpu_page_size=3 * PAGE_SIZE) as region:
gpu_worker.pin_mmap_region(region)
base = region._base.data_ptr()
@@ -845,25 +837,22 @@ def test_pin_mmap_region_failure_leaves_region_pageable(iid, host_register, fail
registered = [base + i * 6 * PAGE_SIZE for i in range(fail_at)]
failed_size = min(6, 15 - 6 * fail_at) * PAGE_SIZE
assert cudart.mock_calls == [
*(call.cudaHostRegister(address, 6 * PAGE_SIZE) for address in registered),
call.cudaHostRegister(base + fail_at * 6 * PAGE_SIZE, failed_size),
call.cudaGetLastError(),
*(call.cudaHostUnregister(address) for address in reversed(registered)),
assert register.call_args_list == [
*(call(address, 6 * PAGE_SIZE) for address in registered),
call(base + fail_at * 6 * PAGE_SIZE, failed_size),
]
assert unregister.call_args_list == [
call(address) for address in reversed(registered)
]
torch_cudart.cudaHostUnregister.assert_not_called()
def test_pin_mmap_region_without_cuda_runtime_stays_pageable(
iid, host_register, monkeypatch
def test_pin_mmap_region_when_host_register_unsupported_stays_pageable(
iid, monkeypatch
):
"""A CUDA runtime that cannot be loaded leaves the region pageable instead
of failing worker startup."""
def missing_runtime():
raise AssertionError("libcudart is not loaded in the current process")
monkeypatch.setattr(gpu_worker, "CudaRTLibrary", missing_runtime)
"""A platform without host registration support (host_register()
returning False) leaves the region pageable instead of failing worker
startup."""
monkeypatch.setattr(gpu_worker, "host_register", lambda ptr, num_bytes: False)
with _region(iid) as region:
gpu_worker.pin_mmap_region(region)
assert not region.is_pinned
+3
View File
@@ -307,6 +307,7 @@ def test_cpu_spec_replicated_disabled_without_shared_region(
# those private buffers empty and corrupting subsequent loads.
import vllm.v1.kv_offload.cpu.spec as cpu_spec_module
monkeypatch.setattr(cpu_spec_module.current_platform, "is_xpu", lambda: False)
monkeypatch.setattr(cpu_spec_module.current_platform, "is_cuda_alike", lambda: rocm)
monkeypatch.setattr(cpu_spec_module.current_platform, "is_rocm", lambda: rocm)
worker_kv_bytes_per_block = SharedOffloadRegion.BLOCK_SIZE_ALIGNMENT
@@ -341,6 +342,7 @@ def test_cpu_spec_replicated_layout_truth_matrix(
# actually allocates on the shared region.
import vllm.v1.kv_offload.cpu.spec as cpu_spec_module
monkeypatch.setattr(cpu_spec_module.current_platform, "is_xpu", lambda: False)
monkeypatch.setattr(
cpu_spec_module.current_platform, "is_cuda_alike", lambda: cuda_alike
)
@@ -417,6 +419,7 @@ def test_cpu_spec_create_worker_uses_tensor_path_without_shared_region(
worker_calls.append(kwargs)
return MagicMock()
monkeypatch.setattr(cpu_spec_module.current_platform, "is_xpu", lambda: False)
monkeypatch.setattr(cpu_spec_module.current_platform, "is_cuda_alike", lambda: rocm)
monkeypatch.setattr(cpu_spec_module.current_platform, "is_rocm", lambda: rocm)
monkeypatch.setattr(cpu_spec_module, "SharedOffloadRegion", fake_region_ctor)
+18 -4
View File
@@ -17,6 +17,7 @@ import pytest
from vllm.v1.kv_offload.tiering.base import SecondaryTierManager
from vllm.v1.kv_offload.tiering.example.manager import ExampleSecondaryTierManager
from vllm.v1.kv_offload.tiering.factory import SecondaryTierFactory
from vllm.v1.metrics.cache_hit_source import CacheHitSource
# ---------------------------------------------------------------------------
# Fixtures
@@ -43,12 +44,22 @@ def _make_mock_args():
def test_pre_registered_tiers_can_be_imported():
"""CI sentinel: registered tiers import and yield SecondaryTierManager."""
# Derived from each tier's ``medium``; P2P has none and sets its own.
expected_sources = {
"example": CacheHitSource.HOST,
"fs": CacheHitSource.DISK,
"obj": CacheHitSource.DISK,
"p2p": CacheHitSource.P2P,
}
for tier_type in SecondaryTierFactory._registry:
# KVCR is an optional external dependency and may not be installed.
if tier_type == "kvcr" and find_spec("kvcr") is None:
continue
cls = SecondaryTierFactory._registry[tier_type]()
assert issubclass(cls, SecondaryTierManager)
assert cls.cache_hit_source == expected_sources.get(
tier_type, CacheHitSource.EXTERNAL_UNSPECIFIED
)
def test_example_tier_registered():
@@ -95,7 +106,8 @@ def test_create_multiple_tiers():
assert all(isinstance(tier, ExampleSecondaryTierManager) for tier in tiers)
def test_register_new_tier_type():
@pytest.mark.parametrize("tier_type", ["custom_tier", "cpu", "nvme"])
def test_register_new_tier_type(tier_type):
"""Verify that new tier types can be registered and created.
This is how external projects add custom secondary tiers
@@ -103,20 +115,22 @@ def test_register_new_tier_type():
"""
# Register a new tier type (reuse example manager for simplicity)
SecondaryTierFactory.register_tier(
"custom_tier",
tier_type,
"vllm.v1.kv_offload.tiering.example.manager",
"ExampleSecondaryTierManager",
)
primary_kv_view, offloading_spec = _make_mock_args()
tier = SecondaryTierFactory.create_secondary_tier(
{"type": "custom_tier", "custom_param": 99},
{"type": tier_type, "custom_param": 99},
primary_kv_view,
offloading_spec,
)
assert tier.tier_type == "custom_tier"
assert tier.tier_type == tier_type
assert isinstance(tier, ExampleSecondaryTierManager)
# Attribution follows the tier's medium, never its registration name.
assert tier.cache_hit_source is CacheHitSource.HOST
# ---------------------------------------------------------------------------
+53 -32
View File
@@ -18,7 +18,7 @@ from kvcr.types import (
BlockKey,
CacheTier,
InventoryEvent,
MemDescriptor,
MemoryRef,
OpEntryResult,
OpEntryStatus,
OpHandle,
@@ -36,7 +36,9 @@ from vllm.v1.kv_offload.base import (
ReqContext,
make_offload_key,
)
from vllm.v1.kv_offload.tiering.backpressure import EMABackpressureDetector
from vllm.v1.kv_offload.tiering.base import JobResult, TransferJob
from vllm.v1.kv_offload.tiering.factory import SecondaryTierFactory
from vllm.v1.kv_offload.tiering.kvcr import manager as kvcr_manager
from vllm.v1.kv_offload.tiering.kvcr.manager import KVCRSecondaryTierManager
@@ -78,11 +80,9 @@ class RecordingKVCR:
self.submit_hint_calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
self.discard_hint_calls: list[str] = []
self.deliver_calls: list[
tuple[OpHandle, dict[BlockKey, list[MemDescriptor]], str | None]
] = []
self.deposit_calls: list[
tuple[OpHandle, dict[BlockKey, list[MemDescriptor]]]
tuple[OpHandle, dict[BlockKey, list[MemoryRef]], str | None]
] = []
self.deposit_calls: list[tuple[OpHandle, dict[BlockKey, list[MemoryRef]]]] = []
self.completed: list[tuple[OpHandle, dict[BlockKey, OpEntryResult]]] = []
self._next_op_handle = 1
@@ -107,7 +107,7 @@ class RecordingKVCR:
def deliver(
self,
blocks: Mapping[BlockKey, list[MemDescriptor]],
blocks: Mapping[BlockKey, list[MemoryRef]],
request_id: str | None = None,
) -> OpHandle:
op_handle = self._next_op_handle
@@ -118,7 +118,7 @@ class RecordingKVCR:
def deposit(
self,
blocks: Mapping[BlockKey, list[MemDescriptor]],
blocks: Mapping[BlockKey, list[MemoryRef]],
) -> OpHandle:
op_handle = self._next_op_handle
self._next_op_handle += 1
@@ -182,6 +182,7 @@ def _make_tier(
g3: dict[str, object] | None = None,
control_ports: list[int] | None = None,
data_parallel_rank_local: int | None = None,
backpressure: dict[str, Any] | None = None,
) -> KVCRSecondaryTierManager:
def make_control(_bind_host, bind_port, advertise_host):
return _StubControlChannel(f"tcp://{advertise_host}:{int(bind_port)}")
@@ -198,7 +199,25 @@ def _make_tier(
monkeypatch.setattr(kvcr_manager, "KVCR", make_kvcr)
monkeypatch.setattr(kvcr_manager, "ZmqPeerControlChannel", make_control)
return KVCRSecondaryTierManager(
tier_config = {
"type": "kvcr",
"router_capabilities": ["router_hint"],
"control_host": "127.0.0.1",
"control_ports": control_ports if control_ports is not None else [7777],
"control_advertise_host": "127.0.0.1",
"enable_telemetry": enable_telemetry,
"secondary_g2_slots": secondary_g2_slots,
"kvcr_service_socket_path": kvcr_service_socket_path,
"compatibility_digest": compatibility_digest,
"policy": policy,
"g3": g3,
"local_dram_backend": "UCX",
"remote_fw_dram_backend": "UCX",
}
if backpressure is not None:
tier_config["backpressure"] = backpressure
tier = SecondaryTierFactory.create_secondary_tier(
tier_config=tier_config,
offloading_spec=SimpleNamespace(
config=SimpleNamespace(
parallel=SimpleNamespace(
@@ -211,20 +230,9 @@ def _make_tier(
),
),
primary_kv_view=memoryview(np.zeros((4, 16), dtype=np.int8)),
tier_type="kvcr",
router_capabilities=["router_hint"],
control_host="127.0.0.1",
control_ports=control_ports if control_ports is not None else [7777],
control_advertise_host="127.0.0.1",
enable_telemetry=enable_telemetry,
secondary_g2_slots=secondary_g2_slots,
kvcr_service_socket_path=kvcr_service_socket_path,
compatibility_digest=compatibility_digest,
policy=policy,
g3=g3,
local_dram_backend="UCX",
remote_fw_dram_backend="UCX",
)
assert isinstance(tier, KVCRSecondaryTierManager)
return tier
def test_kvcr_tier_configures_service_for_local_dp_rank(monkeypatch):
@@ -248,7 +256,11 @@ def test_kvcr_tier_configures_service_for_local_dp_rank(monkeypatch):
compatibility_digest="Opaque-Digest",
)
assert kvcr.config is not None
assert kvcr.config.pool_layouts == [("", tier._primary_row_stride)]
assert kvcr.config.pool_layouts == [("", tier.block_size_bytes)]
(region,) = kvcr.backend_configs.framework_regions
assert region.addr == np.asarray(tier._primary_kv_view).ctypes.data
assert (region.size, region.stride or region.size, region.count) == (16, 16, 4)
assert (region.label, region.mem_type, region.device_Id) == ("", "DRAM", 0)
assert kvcr.backend_configs.local_dram is None
@@ -269,10 +281,19 @@ def test_kvcr_tier_converts_g3_paths(monkeypatch, tmp_path):
)
def test_kvcr_tier_adapts_request_and_load(monkeypatch):
"""Check hint forwarding, key conversion, load descriptors, and cleanup."""
@pytest.mark.parametrize(
"backpressure",
[None, {"backpressure_cls": "EMABackpressureDetector"}],
ids=["default", "backpressure"],
)
def test_kvcr_tier_adapts_request_and_load(monkeypatch, backpressure):
"""Factory-created tiers preserve configuration and complete hinted loads."""
kvcr = RecordingKVCR()
tier = _make_tier(monkeypatch, kvcr)
tier = _make_tier(monkeypatch, kvcr, backpressure=backpressure)
if backpressure is None:
assert tier.bp_detector is None
else:
assert isinstance(tier.bp_detector, EMABackpressureDetector)
kv_hint = KvHintsEnvelope(protocol_version="0.1", message_id="msg", actions=[])
ctx = ReqContext(
req_id="req",
@@ -306,9 +327,7 @@ def test_kvcr_tier_adapts_request_and_load(monkeypatch):
assert request_id == "req"
assert list(blocks) == [key]
(descriptor,) = blocks[key]
assert descriptor.end_point_name == kvcr.nixl_agent_name
assert descriptor.addr == tier._primary_base_addr + 2 * 16
assert descriptor.size == 16
assert descriptor == MemoryRef(end_point_name=kvcr.nixl_agent_name, element_index=2)
assert list(tier.get_finished_jobs()) == [JobResult(7, True)]
# Here we verify that request cleanup discards the request-scoped hint in
@@ -351,7 +370,7 @@ def test_kvcr_tier_serves_primary_pin_request(monkeypatch):
tier = _make_tier(monkeypatch, kvcr)
keys = (BlockKey(b"k0"), BlockKey(b"k1"), BlockKey(b"k2"))
hit_keys = (keys[0], keys[2])
chunk_ids = {keys[0]: 1, keys[2]: 5}
chunk_ids = {keys[0]: 1, keys[2]: 3}
lifecycle: list[str] = []
class Parent:
@@ -388,7 +407,7 @@ def test_kvcr_tier_serves_primary_pin_request(monkeypatch):
block_descriptors = descriptors[keys[2]]
assert block_descriptors is not None
(descriptor,) = block_descriptors
assert descriptor.addr == (tier._primary_base_addr + 5 * tier._primary_row_stride)
assert descriptor == MemoryRef(end_point_name=kvcr.nixl_agent_name, element_index=3)
assert lifecycle == ["new", "finished"]
polls = 0
@@ -482,14 +501,16 @@ def test_kvcr_tier_stores_and_emits_inventory(monkeypatch):
local_dram = kvcr.backend_configs.local_dram
assert local_dram is not None
assert [(name, size) for name, _, size in local_dram.pools] == [
("", 2 * tier._primary_row_stride)
("", 2 * tier.block_size_bytes)
]
key = OffloadKey(b"k0")
tier.submit_store(_job(11, ReqContext(req_id="req"), key=key, chunk_id=2))
_, blocks = kvcr.deposit_calls[0]
assert blocks[key][0].addr == tier._primary_base_addr + 2 * 16
assert blocks[key] == [
MemoryRef(end_point_name=kvcr.nixl_agent_name, element_index=2)
]
assert list(tier.get_finished_jobs()) == [JobResult(11, True)]
assert kvcr.inventory_sink is not None
@@ -53,6 +53,7 @@ from vllm.v1.kv_offload.tiering.manager import (
TieringOffloadingManager,
)
from vllm.v1.kv_offload.tiering.spec import TieringOffloadingSpec
from vllm.v1.metrics.cache_hit_source import CacheHitSource
_CTX = ReqContext(req_id="test")
_MOCK_OFFLOADING_SPEC = MagicMock()
@@ -500,8 +501,13 @@ class TestTieringOffloadingManager:
# Lookup should find all chunks in primary
assert count_hits(self.manager, chunks) == 3
def test_promotion_from_secondary(self, manager_setup):
@pytest.mark.parametrize(
"source",
[CacheHitSource.EXTERNAL_UNSPECIFIED, CacheHitSource.DISK, CacheHitSource.P2P],
)
def test_promotion_from_secondary(self, manager_setup, monkeypatch, source):
"""Test promotion of chunks from secondary to primary tier."""
monkeypatch.setattr(ExampleSecondaryTierManager, "cache_hit_source", source)
chunks = to_keys(range(3))
# Manually add chunks to secondary tier (simulate previous cascade)
@@ -525,6 +531,27 @@ class TestTieringOffloadingManager:
# Next lookup should succeed
assert count_hits(self.manager, chunks) == 3
# The request that caused the promotion retains the secondary origin.
assert all(
self.manager.get_load_source(chunk, _CTX) == source for chunk in chunks
)
# A later request sees the chunks as ordinary host-memory primary hits.
later_context = ReqContext(req_id="later")
self.manager.on_new_request(later_context)
assert all(
self.manager.lookup(chunk, later_context) is LookupResult.HIT
for chunk in chunks
)
assert all(
self.manager.get_load_source(chunk, later_context) == "host"
for chunk in chunks
)
@pytest.mark.parametrize(
"source",
[CacheHitSource.EXTERNAL_UNSPECIFIED, CacheHitSource.DISK, CacheHitSource.P2P],
)
@pytest.mark.parametrize(
("successful_indices", "expected_results"),
[
@@ -540,8 +567,9 @@ class TestTieringOffloadingManager:
ids=["partial", "legacy-full-failure"],
)
def test_failed_promotion_keeps_only_successful_chunks(
self, manager_setup, successful_indices, expected_results
self, manager_setup, monkeypatch, source, successful_indices, expected_results
):
monkeypatch.setattr(ExampleSecondaryTierManager, "cache_hit_source", source)
chunks = to_keys(range(3))
for chunk in chunks:
self.secondary_tier1.chunks[chunk] = True
@@ -571,6 +599,14 @@ class TestTieringOffloadingManager:
assert [
self.primary_tier.lookup(chunk, _CTX) for chunk in chunks
] == expected_results
expected_source_keys = (
set()
if successful_indices is None
else {chunks[i] for i in successful_indices}
)
assert set(self.manager._request_load_sources[_CTX.req_id]) == (
expected_source_keys
)
def test_lookup_reports_sync_delay_for_resolved_lookups(self, manager_setup):
"""Resolved lookups report one sync delay sample per tier and chunk."""
@@ -1315,6 +1351,7 @@ class TestTieringOffloadingManager:
# Orchestrator state cleared.
assert self.manager._jobs == {}
assert self.manager._pending_load_submissions == {}
assert self.manager._request_load_sources == {}
assert set(self.manager._req_state) == {_CTX.req_id, rl_ctx.req_id}
assert self.manager._processed_jobs_this_step is False
+93
View File
@@ -1,10 +1,13 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from vllm.v1.core.sched.output import ScheduledEncoderInputStats, SchedulerOutput
from vllm.v1.engine import EngineCoreOutputs, FinishReason
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.metrics.stats import (
IterationStats,
PrefillStats,
PrefixCacheStats,
PromptTokenStats,
RequestStateStats,
SchedulerIterationDetails,
@@ -45,6 +48,96 @@ def test_scheduler_iteration_details_serialization():
assert decoded.scheduler_stats.iteration_details == iteration_details
def test_prefix_cache_stats_hits_by_source_accumulate():
stats = PrefixCacheStats()
stats.record(
num_tokens=8,
num_hits=5,
preempted=False,
hits_by_source={CacheHitSource.HOST: 3, CacheHitSource.DISK: 2},
)
stats.record(
num_tokens=8,
num_hits=6,
preempted=False,
hits_by_source={CacheHitSource.P2P: 5, CacheHitSource.HOST: 1},
)
# Zero counts never create an entry.
stats.record(
num_tokens=8,
num_hits=4,
preempted=False,
hits_by_source={CacheHitSource.DISK: 4, CacheHitSource.P2P: 0},
)
assert stats.hits_by_source == {
CacheHitSource.HOST: 4,
CacheHitSource.DISK: 6,
CacheHitSource.P2P: 5,
}
assert sum(stats.hits_by_source.values()) == stats.hits == 15
def test_prefix_cache_stats_record_hits_by_source():
stats = PrefixCacheStats()
stats.record(num_tokens=32, num_hits=16, preempted=False)
stats.record(
num_tokens=32,
num_hits=24,
preempted=False,
hits_by_source={CacheHitSource.HOST: 16, CacheHitSource.DISK: 8},
)
# Preempted re-admissions never contribute to hits or the split.
stats.record(
num_tokens=32,
num_hits=32,
preempted=True,
hits_by_source={CacheHitSource.P2P: 32},
)
# A connector miscount is reported as unspecified, not dropped or raised.
stats.record(
num_tokens=8,
num_hits=8,
preempted=False,
hits_by_source={CacheHitSource.HOST: 4},
)
assert stats.requests == 3
assert stats.hits == 48
assert stats.preempted_hits == 32
assert stats.hits_by_source == {
CacheHitSource.HOST: 16,
CacheHitSource.DISK: 8,
CacheHitSource.EXTERNAL_UNSPECIFIED: 8,
}
assert sum(stats.hits_by_source.values()) == 48 - 16
def test_prefix_cache_stats_hits_by_source_serialization():
connector_stats = PrefixCacheStats()
connector_stats.record(
num_tokens=16,
num_hits=8,
preempted=False,
hits_by_source={CacheHitSource.P2P: 4, CacheHitSource.HOST: 4},
)
outputs = EngineCoreOutputs(
scheduler_stats=SchedulerStats(
connector_prefix_cache_stats=connector_stats,
)
)
encoded = MsgpackEncoder().encode(outputs)
decoded = MsgpackDecoder(EngineCoreOutputs).decode(encoded)
assert decoded.scheduler_stats is not None
assert decoded.scheduler_stats.connector_prefix_cache_stats is not None
assert decoded.scheduler_stats.connector_prefix_cache_stats.hits_by_source == {
CacheHitSource.P2P: 4,
CacheHitSource.HOST: 4,
}
def test_compute_iteration_details_includes_encoder_stats():
scheduler_output = SchedulerOutput.make_empty()
scheduler_output.scheduled_encoder_input_stats = ScheduledEncoderInputStats(
@@ -227,6 +227,10 @@ def test_single_step_tile_skips_self_conditioning():
assert not states.self_conditioning_embeds[0].any()
def test_sample_step_is_compiled():
assert hasattr(_compiled_sample_step, "_torchdynamo_orig_callable")
@pytest.mark.parametrize("stance", ["default", "force_eager"])
def test_self_conditioning_stores_a_bf16_model_in_the_fp32_buffer(stance):
# The model's embeddings are bf16 while the buffer is fp32. Compiled code
+6 -2
View File
@@ -518,6 +518,7 @@ def test_prompt_logprob_token_ids_require_v2_model_runner():
structured_outputs_config=None,
tokenizer=None,
validate_logits_processors_params=lambda params: None,
resolve_watermarking=lambda params: False,
)
params = SamplingParams(prompt_logprob_token_ids=[[1, 2]])
with patch.object(SamplingParams, "verify"):
@@ -1469,7 +1470,10 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
assert float(scores.max()) <= 1e-3, "logprobs must be <= 0"
# Ragged rows: each row keeps a prefix of the candidates and must
# reproduce that prefix of the full scores, with -inf padding.
# reproduce that prefix of the full scores, with -inf padding. On ROCm
# the second generate call picks its own kernels, which moves bf16
# tails by up to 0.19; a misaligned row is off by nats either way.
ragged_atol = 0.2 if current_platform.is_rocm() else 1e-2
ragged_params = make_params(lambda j: candidate_ids(j)[: 1 + j % 4])
ragged_outputs = vllm_model.llm.generate(token_prompts, ragged_params)
for output, ragged_output in zip(outputs, ragged_outputs):
@@ -1478,7 +1482,7 @@ def test_prompt_logprob_token_ids_with_chunking_and_preemption(monkeypatch):
n = 1 + j % 4
expected[j, :n] = output.prompt_token_id_logprobs[j, :n]
np.testing.assert_allclose(
ragged_output.prompt_token_id_logprobs, expected, atol=1e-2
ragged_output.prompt_token_id_logprobs, expected, atol=ragged_atol
)
# The row count is checked against the prompt at admission.
+217 -1
View File
@@ -6,6 +6,7 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
from unittest.mock import Mock
import pytest
import torch
@@ -17,16 +18,18 @@ from vllm.config import (
KVTransferConfig,
ModelConfig,
SchedulerConfig,
SpeculativeConfig,
VllmConfig,
)
from vllm.config.cache import MambaCacheMode
from vllm.config.kv_events import KVEventsConfig
from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorRole
from vllm.distributed.kv_transfer.kv_connector.v1.simple_cpu_offload_connector import (
SimpleCPUOffloadConnector,
)
from vllm.utils.hashing import sha256
from vllm.v1.core.block_pool import BlockPool
from vllm.v1.core.kv_cache_manager import KVCacheBlocks
from vllm.v1.core.kv_cache_manager import KVCacheBlocks, KVCacheManager
from vllm.v1.core.kv_cache_utils import (
get_request_block_hasher,
init_none_hash,
@@ -51,6 +54,7 @@ from vllm.v1.kv_cache_interface import (
MambaSpec,
SlidingWindowSpec,
)
from vllm.v1.metrics.cache_hit_source import CacheHitSource
from vllm.v1.outputs import KVConnectorOutput
from vllm.v1.request import Request
from vllm.v1.simple_kv_offload.manager import SimpleCPUOffloadScheduler
@@ -211,6 +215,37 @@ class SchedulerFixture:
num_groups: int = 1
@pytest.mark.parametrize(
("backend", "source"),
[("cpu", CacheHitSource.HOST), ("disk", CacheHitSource.DISK)],
)
def test_connector_reports_configured_cache_source(
tmp_path, backend: str, source: CacheHitSource
):
kv_cache_config = _make_kv_cache_config(num_blocks=4)
vllm_config = _make_vllm_config()
extra_config = {
"cpu_bytes_to_use_per_rank": _BYTES_PER_BLOCK * 4,
"kv_offload_backend": backend,
}
if backend == "disk":
extra_config.update(
disk_path=str(tmp_path / "kv-offload.bin"),
disk_capacity_bytes=_BYTES_PER_BLOCK * 4,
)
assert vllm_config.kv_transfer_config is not None
vllm_config.kv_transfer_config.kv_connector_extra_config = extra_config
connector = SimpleCPUOffloadConnector(
vllm_config,
KVConnectorRole.SCHEDULER,
kv_cache_config,
)
assert connector.get_external_cache_hit_sources(None, 32) == {source: 32} # type: ignore[arg-type]
assert connector.get_external_cache_hit_sources(None, 0) == {} # type: ignore[arg-type]
def make_scheduler(
num_cpu_blocks: int = 8,
num_gpu_blocks: int = 16,
@@ -3089,3 +3124,184 @@ def test_lazy_target_blocks_ignore_non_prefix_cacheable_groups() -> None:
without_ring, max_batched
)
assert target_with == target_without
@pytest.mark.parametrize("retention_interval", [None, 0])
@pytest.mark.parametrize("chunk_size,prefill_lookahead", [(64, 1), (1024, 1), (1, 3)])
@pytest.mark.parametrize(
"draft_sliding_window,draft_sharded",
[(True, False), (False, False), (False, True)],
ids=["swa", "replicated_full", "sharded_full"],
)
def test_eager_store_matches_gpu_cacheable_prefix(
retention_interval: int | None,
chunk_size: int,
prefill_lookahead: int,
draft_sliding_window: bool,
draft_sharded: bool,
) -> None:
"""Preserve GPU hits for replicated SWA and DCP-sharded full-attention drafts."""
block_size = 64
scheduler_block_size = 8 * block_size
draft_block_size = scheduler_block_size if draft_sharded else block_size
prompt_len = 16 * scheduler_block_size + draft_block_size + prefill_lookahead
kv_cache_config = _make_kv_cache_config(256, num_groups=2)
for group_id, group in enumerate(kv_cache_config.kv_cache_groups):
group.kv_cache_spec = FullAttentionSpec(
block_size=block_size,
num_kv_heads=NUM_KV_HEADS,
head_size=HEAD_SIZE,
dtype=DTYPE,
dcp_sharded=group_id == 0 or draft_sharded,
)
for tensor in kv_cache_config.kv_cache_tensors:
tensor.size *= block_size // BLOCK_SIZE
tensor.layer_stride *= block_size // BLOCK_SIZE
tensor.block_stride *= block_size // BLOCK_SIZE
if draft_sliding_window:
kv_cache_config.kv_cache_groups[1].kv_cache_spec = SlidingWindowSpec(
block_size=block_size,
num_kv_heads=NUM_KV_HEADS,
head_size=HEAD_SIZE,
dtype=DTYPE,
sliding_window=scheduler_block_size,
extra_retained_tokens=prefill_lookahead - 1,
dcp_sharded=False,
)
kv_cache_config.kv_cache_groups[1].is_eagle_group = True
kv_cache_config.prefix_cache_retention_interval = retention_interval
vllm_config = _make_cp_vllm_config(dcp_world_size=8)
vllm_config.model_config.max_model_len = 16384
speculative_config = Mock(spec=SpeculativeConfig)
speculative_config.num_speculative_tokens = 3
speculative_config.use_eagle.return_value = True
speculative_config.use_eagle_block_drop.return_value = True
speculative_config.use_multi_module_mtp.return_value = prefill_lookahead > 1
vllm_config.speculative_config = speculative_config
scheduler = SimpleCPUOffloadScheduler(
vllm_config=vllm_config,
kv_cache_config=kv_cache_config,
cpu_capacity_bytes=kv_cache_config.kv_cache_tensors[0].size,
scheduler_block_size=scheduler_block_size,
hash_block_size=block_size,
)
gpu_manager = KVCacheManager(
kv_cache_config,
max_model_len=16384,
max_in_flight_tokens=chunk_size,
scheduler_block_size=scheduler_block_size,
hash_block_size=block_size,
dcp_world_size=8,
use_eagle=True,
num_prefill_lookahead=prefill_lookahead,
)
scheduler.bind_gpu_block_pool(gpu_manager.block_pool)
request = Request(
request_id="dcp-draft-source",
prompt_token_ids=list(range(prompt_len)),
sampling_params=SamplingParams(max_tokens=2),
pooling_params=None,
mm_features=None,
block_hasher=get_request_block_hasher(block_size, sha256),
)
# Follow allocate -> connector metadata -> compute completion, including
# one decode step so the final prefill blocks can be offloaded.
while request.num_computed_tokens <= prompt_len:
if request.num_computed_tokens == prompt_len:
request.append_output_token_ids([prompt_len])
num_new_tokens = min(
chunk_size, request.num_tokens - request.num_computed_tokens
)
new_blocks = gpu_manager.allocate_slots(
request, num_new_tokens, num_lookahead_tokens=3
)
assert new_blocks is not None
if request.num_computed_tokens == 0:
scheduler.update_state_after_alloc(
request, gpu_manager.get_blocks(request.request_id), 0
)
output = make_scheduler_output(
{request.request_id: num_new_tokens},
new_reqs={request.request_id: new_blocks.get_block_ids()},
)
else:
output = make_scheduler_output(
{request.request_id: num_new_tokens},
cached_req_new_blocks={request.request_id: new_blocks.get_block_ids()},
)
store_meta = scheduler.build_connector_meta(output)
request.num_computed_tokens += num_new_tokens
if store_meta.store_event >= 0:
simulate_store_completion(scheduler, store_meta.store_event)
matching_request = Request(
request_id="dcp-draft-load",
prompt_token_ids=request.prompt_token_ids,
sampling_params=request.sampling_params,
pooling_params=None,
mm_features=None,
block_hasher=request._block_hasher,
)
expected_hit = (
15 if draft_sliding_window and retention_interval is not None else 16
) * scheduler_block_size
assert gpu_manager.get_computed_blocks(matching_request)[1] == expected_hit
scheduler.request_finished(request, [])
gpu_manager.free(request)
assert gpu_manager.block_pool.reset_prefix_cache()
hit_tokens, is_async = scheduler.get_num_new_matched_tokens(
matching_request, num_computed_tokens=0
)
assert hit_tokens is not None
assert (hit_tokens, is_async) == (expected_hit, True)
assert (
gpu_manager.allocate_slots(
matching_request,
num_new_tokens=0,
num_external_computed_tokens=hit_tokens,
delay_cache_blocks=True,
)
is not None
)
load_blocks = gpu_manager.get_blocks(matching_request.request_id)
scheduler.update_state_after_alloc(matching_request, load_blocks, hit_tokens)
load_meta = scheduler.build_connector_meta(
make_scheduler_output(
{matching_request.request_id: 0},
new_reqs={matching_request.request_id: load_blocks.get_block_ids()},
)
)
# SWA loads only the eight-block tail after null padding; a sharded full
# draft must load every prefix block, with the same DCP geometry as the target.
num_draft_blocks = 8 if draft_sliding_window else hit_tokens // draft_block_size
assert load_meta.load_gpu_blocks == [
block.block_id
for block in (
*load_blocks.blocks[0],
*load_blocks.blocks[1][-num_draft_blocks:],
)
]
assert (
len(load_meta.load_gpu_blocks)
== hit_tokens // scheduler_block_size + num_draft_blocks
)
target_hashes = [
make_block_hash_with_group_id(matching_request.block_hashes[(i + 1) * 8 - 1], 0)
for i in range(hit_tokens // scheduler_block_size)
]
draft_hashes = [
make_block_hash_with_group_id(
matching_request.block_hashes[(i + 1) * draft_block_size // block_size - 1],
1,
)
for i in range(
hit_tokens // draft_block_size - num_draft_blocks,
hit_tokens // draft_block_size,
)
]
assert [
scheduler.cpu_block_pool.blocks[bid].block_hash
for bid in load_meta.load_cpu_blocks
] == target_hashes + draft_hashes
+33
View File
@@ -36,6 +36,39 @@ def test_ngram_max_len(num_speculative_tokens: int, vllm_runner):
runner.llm.generate(_PROMPTS, sampling_params)
@pytest.mark.parametrize("num_speculative_tokens", [1, 3, 10])
@pytest.mark.parametrize("method", ["ngram", "ngram_gpu"])
def test_ngram_gpu_max_len(
method: str,
num_speculative_tokens: int,
vllm_runner,
monkeypatch: pytest.MonkeyPatch,
):
"""V2 n-gram decoding stops at max_model_len."""
monkeypatch.setenv("VLLM_USE_V2_MODEL_RUNNER", "1")
with vllm_runner(
"facebook/opt-125m",
trust_remote_code=False,
max_model_len=100,
enable_chunked_prefill=None,
enforce_eager=True, # For faster initialization.
speculative_config={
"method": method,
"prompt_lookup_max": 5,
"prompt_lookup_min": 3,
"num_speculative_tokens": num_speculative_tokens,
},
) as runner:
assert runner.llm.llm_engine.vllm_config.use_v2_model_runner
sampling_params = SamplingParams(max_tokens=100, ignore_eos=True)
outputs = runner.llm.generate(_PROMPTS, sampling_params)
for output in outputs:
assert output.prompt_token_ids is not None
assert (
len(output.prompt_token_ids) + len(output.outputs[0].token_ids) == 100
)
@pytest.mark.parametrize("num_speculative_tokens", [1, 3, 10])
@pytest.mark.parametrize("attn_backend", get_attn_backend_list_based_on_platform())
def test_eagle_max_len(
@@ -11,6 +11,7 @@ from vllm.config import StructuredOutputsConfig, VllmConfig
from vllm.config.model import ModelConfig
from vllm.config.speculative import SpeculativeConfig
from vllm.parser.engine.adapters import ParserEngineReasoningAdapter
from vllm.parser.engine.parser_engine import ReasoningEnd
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
@@ -113,12 +114,12 @@ class _EngineReasonerStub(ParserEngineReasoningAdapter):
def reasoning_end_token_ids(self):
return self._end_token_ids
def find_reasoning_end_offset(self, token_ids):
def find_reasoning_end(self, token_ids):
self.windows.append(list(token_ids))
for offset, token in enumerate(token_ids):
if token in self._end_token_ids:
return offset
return len(token_ids)
return ReasoningEnd(offset, False)
return ReasoningEnd(len(token_ids), False)
def is_reasoning_end(self, input_ids):
return any(token in self._end_token_ids for token in input_ids)
+279
View File
@@ -0,0 +1,279 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Unit tests for the V2 GPU-accelerated n-gram speculator.
These tests target the Triton proposer in
``vllm.v1.worker.gpu.spec_decode.ngram.speculator`` and complement the CPU
``NgramProposer`` tests in ``test_ngram.py``. The GPU speculator follows a
slightly different policy than the CPU one: when multiple n-gram matches of
the same length exist, the GPU kernel picks the right-most (most recent)
match inside the active context, whereas the CPU implementation returns the
left-most. The expectations below reflect the GPU behavior.
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
import torch
from vllm.config import (
ModelConfig,
SchedulerConfig,
SpeculativeConfig,
VllmConfig,
)
from vllm.v1.worker.gpu.spec_decode.ngram.speculator import NgramGPUSpeculator
from vllm.v1.worker.gpu.states import RequestState
if not torch.cuda.is_available():
pytest.skip(
"CUDA required for NgramGPUSpeculator tests",
allow_module_level=True,
)
DEVICE = torch.device("cuda")
def _make_vllm_config(
min_n: int,
max_n: int,
k: int,
max_num_seqs: int = 8,
max_model_len: int = 64,
method: str = "ngram_gpu",
) -> VllmConfig:
model_config = ModelConfig(
model="facebook/opt-125m",
max_model_len=max_model_len,
enforce_eager=True,
)
scheduler_config = SchedulerConfig.default_factory(
max_num_seqs=max_num_seqs,
max_model_len=max_model_len,
)
speculative_config = SpeculativeConfig(
method=method,
prompt_lookup_min=min_n,
prompt_lookup_max=max_n,
num_speculative_tokens=k,
)
return VllmConfig(
model_config=model_config,
scheduler_config=scheduler_config,
speculative_config=speculative_config,
)
def _make_request_state(cfg: VllmConfig) -> RequestState:
assert cfg.speculative_config is not None
return RequestState(
max_num_reqs=cfg.scheduler_config.max_num_seqs,
max_model_len=cfg.model_config.max_model_len,
max_num_batched_tokens=cfg.scheduler_config.max_num_batched_tokens,
num_speculative_steps=cfg.speculative_config.num_speculative_tokens,
vocab_size=cfg.model_config.get_vocab_size(),
device=DEVICE,
use_dense_all_token_ids=True,
)
def _make_speculator(
min_n: int,
max_n: int,
k: int,
max_num_seqs: int = 8,
max_model_len: int = 32,
) -> NgramGPUSpeculator:
cfg = _make_vllm_config(
min_n=min_n,
max_n=max_n,
k=k,
max_num_seqs=max_num_seqs,
max_model_len=max_model_len,
)
return NgramGPUSpeculator(cfg, DEVICE, _make_request_state(cfg))
def _propose(
spec: NgramGPUSpeculator,
rows: list[list[int]],
seq_lens: list[int] | None = None,
num_sampled: list[int] | None = None,
last_sampled: list[int] | None = None,
slots: list[int] | None = None,
) -> list[list[int]]:
"""Place each batch row at a request slot and run propose().
Returns the drafts as python lists in batch order.
"""
B = len(rows)
if seq_lens is None:
seq_lens = [len(r) for r in rows]
if num_sampled is None:
num_sampled = [1] * B
if last_sampled is None:
last_sampled = [0] * B
if slots is None:
slots = list(range(B))
max_num_reqs = spec.max_num_reqs
all_token_ids = spec.req_states.all_token_ids.gpu
total_len = spec.req_states.total_len.gpu
all_token_ids.zero_()
total_len.zero_()
last_sampled_t = torch.zeros((max_num_reqs, 1), dtype=torch.int64, device=DEVICE)
for row, slot, seq_len, last in zip(rows, slots, seq_lens, last_sampled):
if row:
all_token_ids[slot, : len(row)] = torch.tensor(
row, dtype=torch.int32, device=DEVICE
)
total_len[slot] = seq_len
last_sampled_t[slot, 0] = last
idx_mapping = torch.tensor(slots, dtype=torch.int64, device=DEVICE)
input_batch = SimpleNamespace(num_reqs=B, idx_mapping=idx_mapping)
drafts = spec.propose(
input_batch=input_batch,
attn_metadata=None,
slot_mappings=None,
last_hidden_states=torch.empty(0, device=DEVICE),
aux_hidden_states=None,
num_sampled=torch.tensor(num_sampled, dtype=torch.int32, device=DEVICE),
num_rejected=torch.zeros(B, dtype=torch.int32, device=DEVICE),
last_sampled=last_sampled_t,
next_prefill_tokens=torch.zeros(B, dtype=torch.int32, device=DEVICE),
temperature=torch.zeros(B, dtype=torch.float32, device=DEVICE),
seeds=torch.zeros(B, dtype=torch.int64, device=DEVICE),
dp_sync=None,
)
return drafts.cpu().tolist()
@pytest.mark.parametrize("max_model_len", [32, 300])
def test_no_match_clears_previous_proposal(max_model_len):
spec = _make_speculator(min_n=2, max_n=2, k=2, max_model_len=max_model_len)
row = [0] * (max_model_len - 5) + [1, 2, 3, 1, 2]
assert _propose(spec, [row]) == [[3, 1]]
drafts = _propose(spec, [[1, 2, 3, 4, 5]], last_sampled=[42])
assert drafts == [[42, 42]]
def test_no_4gram_match_only():
"""No 4-gram match in [1,2,3,4,1,2,3] → 0 valid drafts."""
spec = _make_speculator(min_n=4, max_n=4, k=2)
drafts = _propose(spec, [[1, 2, 3, 4, 1, 2, 3]], last_sampled=[7])
assert drafts == [[7, 7]]
def test_falls_back_to_3gram_when_4gram_missing():
"""No 4-gram match but a 3-gram match exists → propose [4, 1]."""
spec = _make_speculator(min_n=3, max_n=4, k=2)
drafts = _propose(spec, [[1, 2, 3, 4, 1, 2, 3]])
assert drafts == [[4, 1]]
def test_prefers_longer_ngram():
"""Prefer a 4-gram match over a more recent 3-gram match."""
spec = _make_speculator(min_n=3, max_n=4, k=2)
drafts = _propose(spec, [[1, 2, 3, 4, 50, 51, 2, 3, 4, 60, 61, 1, 2, 3, 4]])
assert drafts == [[50, 51]]
def test_picks_longest_match_among_2_3_4_grams():
"""Prefer a 3-gram match over a more recent 2-gram match."""
spec = _make_speculator(min_n=2, max_n=4, k=2)
drafts = _propose(spec, [[2, 3, 4, 50, 51, 3, 4, 60, 61, 1, 2, 3, 4]])
assert drafts == [[50, 51]]
@pytest.mark.parametrize("max_model_len", [32, 128, 257, 1025])
def test_picks_rightmost_when_multiple_matches(max_model_len):
"""Pick the last valid match across blocks, ignoring trailing tokens."""
spec = _make_speculator(min_n=3, max_n=3, k=2, max_model_len=max_model_len)
padding = [0] * (spec.block_l - 5) if spec.n_blocks > 1 else []
row = [1, 2, 3, 100] + padding + [1, 2, 3, 200, 1, 2, 3, 300, 1, 2, 3]
drafts = _propose(spec, [row + [1, 2, 3, 999, 1, 2, 3]], seq_lens=[len(row)])
assert drafts == [[300, 1]]
def test_short_context_yields_zero_valid():
"""The only length-2 window overlaps the suffix itself → no match."""
spec = _make_speculator(min_n=2, max_n=2, k=2)
drafts = _propose(spec, [[5, 6]], last_sampled=[99])
assert drafts == [[99, 99]]
def test_zero_sampled_disables_proposal():
"""num_sampled==0 disables proposals for that request regardless of match."""
spec = _make_speculator(min_n=2, max_n=2, k=2)
drafts = _propose(spec, [[1, 2, 3, 1, 2]], num_sampled=[0], last_sampled=[77])
assert drafts == [[77, 77]]
def test_tail_falls_back_when_few_tokens_after_match():
"""Fewer than k tokens after the match → the tail falls back.
Tokens: [1, 2, 1, 2] (seq_len=4). Suffix (1, 2) matches at position 0
(the match at position 2 is the suffix itself and is excluded). With
k=3, only 2 slots map to tokens inside the context.
"""
spec = _make_speculator(min_n=2, max_n=2, k=3)
drafts = _propose(spec, [[1, 2, 1, 2]], last_sampled=[55])
assert drafts == [[1, 2, 55]]
def test_multibatch_mixed():
"""Mixed batch: row 0 matches, row 1 has no match."""
spec = _make_speculator(min_n=2, max_n=2, k=2)
drafts = _propose(
spec,
[[1, 2, 3, 1, 2], [4, 5, 6]],
last_sampled=[10, 20],
)
assert drafts[0] == [3, 1]
assert drafts[1] == [20, 20]
def test_multibatch_independent_choice_of_n():
"""Each row independently picks its longest matched n."""
spec = _make_speculator(min_n=2, max_n=3, k=2)
drafts = _propose(
spec,
[
[9, 1, 2, 3, 8, 1, 2, 3], # 3-gram (1,2,3) at idx 1 → [8, 1]
[7, 1, 2, 9, 1, 2], # 2-gram (1,2) at idx 1 → [9, 1]
],
)
assert drafts[0] == [8, 1]
assert drafts[1] == [9, 1]
def test_min_n_eq_1():
"""min_n=max_n=1 — single-token n-grams always match if context > 1."""
spec = _make_speculator(min_n=1, max_n=1, k=2)
drafts = _propose(spec, [[1, 2, 3, 4, 1]])
assert drafts == [[2, 3]]
def test_noncontiguous_idx_mapping():
"""propose() reads token rows in place via idx_mapping (non-contiguous)."""
spec = _make_speculator(min_n=2, max_n=2, k=2)
drafts = _propose(
spec,
[[7, 8, 9, 7, 8], [1, 2, 3, 1, 2]],
slots=[3, 0],
)
assert drafts == [[9, 7], [3, 1]]
def test_construction_validates_speculative_config():
spec = _make_speculator(min_n=2, max_n=3, k=2)
assert spec.min_n == 2
assert spec.max_n == 3
assert spec.num_speculative_steps == 2
# No-op hooks must not raise.
spec.init_cudagraph_manager(None)
spec.capture()
@@ -7,6 +7,7 @@ from unittest.mock import MagicMock
import numpy as np
import torch
import vllm.v1.core.kv_cache_utils as kv_cache_utils
from vllm.config import DeviceConfig, VllmConfig
from vllm.multimodal.inputs import (
MultiModalFeatureSpec,
@@ -14,6 +15,12 @@ from vllm.multimodal.inputs import (
PlaceholderRange,
)
from vllm.sampling_params import SamplingParams
from vllm.utils.hashing import sha256
from vllm.v1.core.kv_cache_utils import (
get_request_block_hasher,
hash_block_tokens,
init_none_hash,
)
from vllm.v1.core.sched.scheduler import Scheduler
from vllm.v1.engine import FinishReason
from vllm.v1.kv_cache_interface import (
@@ -365,6 +372,48 @@ class TestStreamingScheduler(unittest.TestCase):
num_new_tokens = session.num_tokens - session.num_computed_tokens
assert num_new_tokens == 2
def test_update_request_as_session_drops_stale_block_hashes(self):
"""A discarded sampled token must not stay fingerprinted in
block_hashes (#49377)."""
init_none_hash(sha256)
scheduler = create_scheduler()
hash_block_size = scheduler.hash_block_size
# hash_block_size - 1 prompt tokens, so the discarded sampled token
# completes hash block 0.
prompt = list(range(1, hash_block_size))
discarded_token = 999
session = Request(
request_id="session",
prompt_token_ids=list(prompt),
sampling_params=SamplingParams(max_tokens=16),
pooling_params=None,
block_hasher=get_request_block_hasher(hash_block_size, sha256),
resumable=True,
)
session.append_output_token_ids(discarded_token)
assert len(session.block_hashes) == 1
stale_hash = session.block_hashes[0]
session.num_computed_tokens = len(prompt)
next_token = 42
update = StreamingUpdate.from_request(
DummyRequest(request_id="session", prompt_token_ids=[next_token])
)
scheduler._update_request_as_session(session, update)
assert list(session.all_token_ids) == prompt + [next_token]
assert len(session.block_hashes) == 1
expected = hash_block_tokens(
sha256, kv_cache_utils.NONE_HASH, tuple(prompt + [next_token])
)
assert session.block_hashes[0] == expected, (
"block_hashes[0] does not identify the current token sequence"
)
assert session.block_hashes[0] != stale_hash, (
"block_hashes[0] still fingerprints the discarded sampled token"
)
def test_streaming_e2e_lifecycle(self):
"""Comprehensive integration test covering complete streaming request lifecycle
including scheduler state management and aliasing bug prevention.
@@ -1,5 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import time
from concurrent.futures import Future
@@ -14,7 +15,10 @@ from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.tokenizers import get_tokenizer
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
from vllm.v1.structured_output.backend_guidance import GuidanceBackend
from vllm.v1.structured_output.backend_guidance import (
GuidanceBackend,
process_for_additional_properties,
)
from vllm.v1.structured_output.backend_types import StructuredOutputOptions
TOKENIZER = "openai-community/gpt2"
@@ -236,3 +240,82 @@ def test_mistral_tokenizer_compile_grammar(
grammar = backend.compile_grammar(request_type, grammar_spec)
assert grammar is not None
assert not grammar.is_terminated()
def test_process_for_additional_properties_preserves_literals() -> None:
"""Literal values under const/enum/default/examples must not be rewritten
when they contain a 'properties' or 'patternProperties' key (#58695)."""
feature = {
"type": "Feature",
"geometry": None,
"properties": {"name": "HQ"},
"patternProperties": {"^x": "y"},
}
schema = {
"type": "object",
"properties": {
"const_field": {"const": feature},
"enum_field": {"enum": [feature]},
"default_field": {"type": "object", "default": feature},
"examples_field": {"type": "object", "examples": [feature]},
"properties": {"type": "string"},
"const": {
"type": "object",
"properties": {"id": {"type": "integer"}},
},
},
"$defs": {
"item": {
"type": "object",
"properties": {"label": {"type": "string"}},
}
},
}
processed = process_for_additional_properties(schema)
assert processed["additionalProperties"] is False
assert processed["$defs"]["item"]["additionalProperties"] is False
assert processed["properties"]["const"]["additionalProperties"] is False
assert "additionalProperties" not in processed["properties"]
assert processed["properties"]["const_field"]["const"] == feature
assert processed["properties"]["enum_field"]["enum"] == [feature]
assert processed["properties"]["default_field"]["default"] == feature
assert processed["properties"]["examples_field"]["examples"] == [feature]
@pytest.mark.parametrize("keyword", ["const", "enum"])
def test_disable_additional_properties_accepts_literal_with_properties_key(
keyword: str,
) -> None:
"""GuidanceBackend with disable_additional_properties=True must accept the
original literal value under const/enum and reject injected
additionalProperties (#58695)."""
feature = {"type": "Feature", "geometry": None, "properties": {"name": "HQ"}}
rewritten = {**feature, "additionalProperties": False}
schema = {keyword: feature if keyword == "const" else [feature]}
vllm_config = VllmConfig(
structured_outputs_config=StructuredOutputsConfig(
backend="guidance",
disable_additional_properties=True,
)
)
tokenizer = AutoTokenizer.from_pretrained(TOKENIZER)
backend = GuidanceBackend(
vllm_config,
tokenizer=tokenizer,
vocab_size=50257,
)
grammar = backend.compile_grammar(
StructuredOutputOptions.JSON,
json.dumps(schema),
)
valid_tokens = tokenizer.encode(json.dumps(feature)) + [tokenizer.eos_token_id]
rewritten_tokens = tokenizer.encode(json.dumps(rewritten)) + [
tokenizer.eos_token_id
]
assert grammar.validate_tokens(valid_tokens) == valid_tokens
assert grammar.validate_tokens(rewritten_tokens) != rewritten_tokens
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from vllm.exceptions import VLLMValidationError
from vllm.v1.structured_output.backend_outlines import validate_regex_is_buildable
pytestmark = pytest.mark.cpu_test
# ================================================
# Test validate_regex_is_buildable functionality
# ================================================
class TestValidateRegexIsBuildable:
class TestPR60359Regressions:
"""This class implements regression tests for PR #60359.
Initial bug report issue #60344.
validate_regex_is_buildable misses \b and backref inside groups
So, we check here that these features are rejected by us.
"""
@pytest.mark.parametrize(
"regex",
[
# top-level word boundary \b
r"a\b",
# \b inside capturing group
r"(a\b)",
# word boundary \b in nested group
r"((a\b))",
# top-level backref
r"(a)\1",
# backref in nested group
r"((a)\2)",
# positive lookahead
r"(a(?=b))",
# inline flag group + word boundary
r"(?i:a\b)",
# counted repeat over a group containing \b
r"(?:(a\b)){2}",
# lazy repeat + word boundary
r"(?:a\b)*?",
# possessive repeat + word boundary
r"(?:a\b)*+",
# atomic group + word boundary
r"(?>a\b)",
],
)
def test_unsupported_regex(self, regex):
with pytest.raises(VLLMValidationError):
validate_regex_is_buildable(regex)
@pytest.mark.parametrize(
"regex",
[
# [\b] is character class, not word-boundary \b
r"[\b]",
r"(a[\b]c)",
# escaped backslash + "b", not word-boundary \b
r"a\\b",
r"(a\\bc)",
# no \b or backref here, must be ok
r"(abc)",
# BRANCH and MAX_REPEAT must be ok
r"(a|b)+c",
r"(?:ab)*?c",
],
)
def test_supported_regex(self, regex):
validate_regex_is_buildable(regex)
@@ -0,0 +1,611 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from typing import ClassVar
import pytest
from transformers import AutoTokenizer, PreTrainedTokenizerBase
from xgrammar import Grammar
from xgrammar.testing import _is_grammar_accept_string
from vllm.config import StructuredOutputsConfig, VllmConfig
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.structured_output.backend_types import StructuredOutputOptions
from vllm.v1.structured_output.backend_xgrammar import (
XgrammarBackend,
has_xgrammar_unsupported_json_features,
validate_xgrammar_grammar,
)
from vllm.v1.structured_output.utils import choice_as_grammar
pytestmark = pytest.mark.cpu_test
def grammar_accepts(schema: dict, text: str) -> bool:
return _is_grammar_accept_string(Grammar.from_json_schema(schema), text)
# ================================================
# Unsupported schemas
# ================================================
@pytest.fixture
def unsupported_multipleOf_schemas():
return [
{"type": "number", "multipleOf": 120},
{"Even": {"type": "number", "multipleOf": 2}},
{"type": "integer", "multipleOf": 120},
{"Even": {"type": "integer", "multipleOf": 2}},
]
@pytest.fixture
def unsupported_array_schemas():
return [
# array + some constraints is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/968
{"type": "array", "uniqueItems": True},
{"type": "array", "contains": {"type": "string"}},
{"type": "array", "minContains": 1},
{"type": "array", "maxContains": 5},
]
@pytest.fixture
def unsupported_string_schemas():
return [
# ========================================================
# string + format is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/967
{"type": "string", "format": "non_existing_format"},
# ========================================================
#
# ========================================================
# string + format/pattern + length constraint is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/966
#
# pattern/format is compiled but length bounds are silently dropped,
# so the combination must be rejected instead of producing quietly
# wrong output
{"type": "string", "pattern": "^a+$", "maxLength": 2},
{"type": "string", "pattern": "^a+$", "minLength": 3},
{"type": "string", "format": "email", "maxLength": 10},
# ========================================================
]
@pytest.fixture
def unsupported_propertyNames_combinations():
return [
# ========================================================
# propertyNames + patternProperties is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/959
#
# xgrammar drops propertyNames whenever patternProperties is present,
# so "grade_12" matches the pattern and escapes the name constraint
{
"type": "object",
"propertyNames": {"pattern": "^grade_[0-9]$"}, # does NOT match "grade_12"
"patternProperties": {"^grade_[0-9]+$": {"type": "integer"}},
},
# ========================================================
#
# ========================================================
# propertyNames + maxLength is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/960
{
"type": "object",
"propertyNames": {"pattern": "^a+$", "maxLength": 2},
},
# ========================================================
#
# ========================================================
# propertyNames + properties is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/958
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"properties": {"Bad": {"type": "integer"}},
"required": ["Bad"],
},
{
"type": "object",
"propertyNames": {"enum": ["good"]},
"properties": {"Bad": {"type": "integer"}},
},
# ========================================================
#
# ========================================================
# propertyNames + unevaluatedProperties is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/961
#
# xgrammar's propertyNames-only branch falls back to an unconstrained
# value type, so it drops unevaluatedProperties whether it restricts
# values (a schema) or forbids them (false).
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"unevaluatedProperties": False,
},
# also keep in mind that unevaluatedProperties can be a schema
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"unevaluatedProperties": {"type": "integer"},
},
# ========================================================
]
@pytest.fixture
def unsupported_patternProperties_combinations():
return [
# ========================================================
# patternProperties + properties is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/964
#
# JSON Schema requires a property matched by both `properties` and
# `patternProperties` to satisfy both (conjunction), but xgrammar
# compiles them as alternative branches, so satisfying either one is
# enough.
{
"type": "object",
"patternProperties": {"^x$": {"type": "integer"}},
"properties": {"x": {"type": "string"}},
},
# ========================================================
#
# ========================================================
# patternProperties + patternProperties is unsupported by xgrammar
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/965
#
# The same alternative-branches problem applies to overlapping
# patternProperties patterns: a key matching both patterns only has to
# satisfy one of them.
{
"type": "object",
"patternProperties": {
"^a[a-z]*$": {"type": "string"},
"^[a-z]*z$": {"type": "integer"},
},
},
# ========================================================
]
@pytest.fixture
def unsupported_multibranch_allof():
"""Regression tests for issue #56556
[Bug]: JSON schema with multiple allOf branches is silently ignored
by the xgrammar structured-output backend #56556
Xgrammar currently does NOT support multi-branch allOf.
Bug reported to xgrammar team for tracking progress on resolving:
https://github.com/mlc-ai/xgrammar/issues/937
"""
return [
{
"allOf": [
{"type": "string"},
{"enum": ["yes", "no"]},
]
},
# Multi-branch test case with > 2 branches:
{
"allOf": [
{"type": "string"},
{"minLength": 2},
{"maxLength": 10},
]
},
{
"allOf": [
{"type": "integer"},
{"minimum": 0},
]
},
# Non root multi-branch allOf:
{
"type": "object",
"properties": {
"is_this_sparta": {
"allOf": [
{"type": "string"},
{"enum": ["yes", "no"]},
],
},
},
},
]
@pytest.fixture
def unsupported_vllm_issue_56556_schema():
"""Bug repro from vLLM issue #56556"""
return [
{
"$defs": {
"Base": {
"type": "object",
"properties": {"x": {"type": "integer", "minimum": 10}},
"required": ["x"],
}
},
"allOf": [
{"$ref": "#/$defs/Base"},
{
"type": "object",
"properties": {"y": {"type": "string"}},
"required": ["y"],
},
],
},
]
# ================================================
# Supported schemas
# ================================================
@pytest.fixture
def supported_frankenstein_schema():
# IMPORTANT(arpera):
# Do NOT add more keywords here! This schema is overcrowded enough that a new
# keyword can end up having no effect on the compiled grammar while the
# test still passes. Give a new keyword its own fixture and named test.
return {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"email": {"type": "string", "format": "email"},
"status": {"type": "string"},
"scores": {"type": "array", "items": {"type": "number"}},
"car_type": {"type": "string", "enum": ["sedan", "suv", "truck"]},
"car_brand": {"type": "string", "pattern": "^[a-zA-Z]+$"},
"short_description": {"type": "string", "maxLength": 50},
"mileage": {"type": "number", "minimum": 0, "maximum": 1000000},
"model_year": {
"type": "integer",
"exclusiveMinimum": 1900,
"exclusiveMaximum": 2100,
},
"long_description": {"type": "string", "minLength": 50, "maxLength": 2000},
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
},
},
},
"minProperties": 1,
"maxProperties": 100,
}
@pytest.fixture
def pattern_properties_schema():
return {
"type": "object",
"patternProperties": {"^grade_[0-9]+$": {"type": "integer"}},
}
@pytest.fixture
def property_names_schema():
return {"type": "object", "propertyNames": {"pattern": "^[a-z_]+$"}}
@pytest.fixture
def property_names_with_additional_properties_schema():
"""This combination propertyNames + additionalProperties
was unsupported some time ago by xgrammar.
So, this test case was in unsupported category before.
But this xgrammar's PR
https://github.com/mlc-ai/xgrammar/pull/836
added support of propertyNames + additionalProperties
This fix was released in xgrammar v0.2.7
which vLLM pins in PR #57272
"""
return {
"type": "object",
"propertyNames": {"pattern": "^[a-z_]+$"},
"additionalProperties": {"type": "integer"},
}
@pytest.fixture
def supported_allof_anyof_and_oneof():
"""Xgrammar DO support some variants of anyOf, allOf, oneOf
This test case was made during working on covering
unsupported multi-branch allOf to make sure the bug
is NOT present in other combinators.
See for more context in this file test `unsupported_multibranch_allof`
"""
return [
# single-branch allOf:
{
"allOf": [
{"type": "string"},
],
},
# Corner cases: empty allOf, this is a valid schema
{"allOf": []},
# multi-branch allOf:
# is NOT supported yet, see vLLM issue #56556
# single-branch anyOf:
{
"anyOf": [],
},
# multi-branch anyOf:
{
"anyOf": [
{"type": "string"},
{"type": "integer"},
],
},
# single-branch oneOf:
{
"oneOf": [
{"type": "integer", "minimum": 0, "maximum": 100},
],
},
# multi-branch oneOf:
{
"oneOf": [
{"type": "integer", "minimum": 0, "maximum": 100},
{"type": "string", "enum": ["auto", "none"]},
],
},
# Corner case:
# "allOf" is a property name, not allOf combinator keyword
{"type": "object", "properties": {"allOf": {"type": "string"}}},
]
# ================================================
# Test has_xgrammar_unsupported_json_features functionality
# ================================================
class TestHasXGrammarUnsupportedJsonFeatures:
@pytest.mark.parametrize(
"schema_type",
[
"unsupported_string_schemas",
"unsupported_multipleOf_schemas",
"unsupported_array_schemas",
"unsupported_propertyNames_combinations",
"unsupported_patternProperties_combinations",
# vLLM issue #56556
"unsupported_multibranch_allof",
"unsupported_vllm_issue_56556_schema",
],
)
def test_unsupported_json_features(self, schema_type, request):
schemas = request.getfixturevalue(schema_type)
for schema in schemas:
assert has_xgrammar_unsupported_json_features(schema), (
f"Schema should be unsupported: {schema}"
)
@pytest.mark.parametrize(
"schema_type",
[
"supported_frankenstein_schema",
"pattern_properties_schema",
"property_names_schema",
"property_names_with_additional_properties_schema",
# Additional test cases implemented during work on
# vLLM issue #56556
"supported_allof_anyof_and_oneof",
],
)
def test_supported_json_features(self, schema_type, request):
schemas = request.getfixturevalue(schema_type)
if not isinstance(schemas, list):
schemas = [schemas]
for schema in schemas:
assert not has_xgrammar_unsupported_json_features(schema), (
f"Schema should be supported: {schema}"
)
class TestPR48416Regressions:
@pytest.mark.parametrize(
"schema",
[
{"type": ["number"], "multipleOf": 3},
{
"type": ["string", "null"],
"pattern": "^a+$",
"maxLength": 2,
},
{
"type": ["array", "null"],
"items": {"type": "integer"},
"uniqueItems": True,
},
{
"type": ["object", "null"],
"properties": {"Bad": {"type": "integer"}},
"propertyNames": {"pattern": "^[a-z]+$"},
},
],
)
def test_list_type_does_not_bypass_unsupported_feature_check(self, schema):
assert has_xgrammar_unsupported_json_features(schema)
@pytest.mark.parametrize(
"schema",
[
{"type": ["string", "null"]},
{"type": ["integer", "string"]},
{"type": ["array", "null"], "items": {"type": "string"}},
{
"type": ["object", "null"],
"propertyNames": {"pattern": "^[a-z_]+$"},
},
{
"type": ["object", "null"],
"patternProperties": {"^S": {"type": "string"}},
},
],
)
def test_supported_list_type_json_features(self, schema):
assert not has_xgrammar_unsupported_json_features(schema)
class TestIsGrammarAcceptString:
class TestPR42904Support:
def test_property_names_constrains_keys(self, property_names_schema):
assert grammar_accepts(property_names_schema, '{"score": 5}')
assert grammar_accepts(property_names_schema, '{"score": "seven"}')
assert not grammar_accepts(property_names_schema, '{"Score": 5}')
assert not grammar_accepts(property_names_schema, '{"score_1": 5}')
def test_property_names_keeps_additional_properties_value_schema(
self, property_names_with_additional_properties_schema
):
schema = property_names_with_additional_properties_schema
assert grammar_accepts(schema, '{"score": 5}')
assert not grammar_accepts(schema, '{"Score": 5}')
assert not grammar_accepts(schema, '{"score": "seven"}')
def test_pattern_properties_constrains_keys_and_values(
self, pattern_properties_schema
):
assert grammar_accepts(pattern_properties_schema, '{"grade_1": 5}')
assert not grammar_accepts(pattern_properties_schema, '{"other": 5}')
assert not grammar_accepts(pattern_properties_schema, '{"grade_1": "five"}')
class TestPR48115Regressions:
@pytest.mark.parametrize("codepoint", [*range(0x20), 0x7F])
def test_choice_as_grammar_preserves_control_characters(self, codepoint):
choice = f"a{chr(codepoint)}f"
grammar = Grammar.from_ebnf(choice_as_grammar([choice]))
assert _is_grammar_accept_string(grammar, choice)
assert not _is_grammar_accept_string(grammar, "a")
assert not _is_grammar_accept_string(grammar, "af")
assert not _is_grammar_accept_string(grammar, f"a\\u{codepoint:04x}f")
@pytest.mark.parametrize(
("choice", "other"),
[
(r"a\nf", "a\nf"),
('a quote " and a backslash \\', 'a quote " and a backslash '),
("café", "cafe"),
("日本語", "日本"),
("😀", "😁"),
],
)
def test_choice_as_grammar_preserves_literal_choices(self, choice, other):
grammar = Grammar.from_ebnf(choice_as_grammar(["yes", choice]))
assert _is_grammar_accept_string(grammar, "yes")
assert _is_grammar_accept_string(grammar, choice)
assert not _is_grammar_accept_string(grammar, other)
assert not _is_grammar_accept_string(grammar, choice + "extra")
def test_validate_xgrammar_preserves_multiline_choice(self):
structured_outputs = StructuredOutputsParams(choice=["yes", "no\nplease"])
validate_xgrammar_grammar(
SamplingParams(structured_outputs=structured_outputs)
)
assert structured_outputs.choice is None
grammar = Grammar.from_ebnf(structured_outputs.grammar)
assert _is_grammar_accept_string(grammar, "yes")
assert _is_grammar_accept_string(grammar, "no\nplease")
assert not _is_grammar_accept_string(grammar, r"no\nplease")
# ================================================
# Test XgrammarBackend functionality
# ================================================
class TestXgrammarBackend:
class TestPR58067Regressions:
"""Here we check behavior logic of our flag
disable_any_whitespace when used with xgrammar backend.
"""
_TOKENIZER = "openai-community/gpt2"
_VOCAB_SIZE = 50257
tokenizer: ClassVar[PreTrainedTokenizerBase]
@classmethod
@pytest.fixture(scope="class", autouse=True)
def _shared_tokenizer(cls):
cls.tokenizer = AutoTokenizer.from_pretrained(cls._TOKENIZER)
@classmethod
def _backend(cls, *, disable_any_whitespace: bool) -> XgrammarBackend:
vllm_config = VllmConfig(
structured_outputs_config=StructuredOutputsConfig(
backend="xgrammar",
disable_any_whitespace=disable_any_whitespace,
)
)
return XgrammarBackend(
vllm_config, tokenizer=cls.tokenizer, vocab_size=cls._VOCAB_SIZE
)
@classmethod
def _accepts_json(cls, backend: XgrammarBackend, json_text: str) -> bool:
grammar = backend.compile_grammar(StructuredOutputOptions.JSON_OBJECT, "")
return grammar.accept_tokens("req", cls.tokenizer.encode(json_text))
def test_disable_any_whitespace_is_false(self):
"""Verify expected behavior of disable_any_whitespace=False"""
backend = self._backend(disable_any_whitespace=False)
# Check that grammar accepts json with NO space after colon
assert self._accepts_json(backend, '{"no_space_after_me":"yes_ofcourse"}')
# Check that grammar accepts json with space after colon
assert self._accepts_json(backend, '{"yes_space_after_me": true}')
# Check that grammar accepts json with NO space after comma
assert self._accepts_json(
backend,
'{"never_space_after_comma":"accepted","good_boy":":3"}',
)
# Check that grammar accepts json with space after comma
assert self._accepts_json(
backend,
'{"where_space_after_comma":42, "wow_thats_cool":4242}',
)
def test_disable_any_whitespace_is_true(self):
"""Verify expected behavior of disable_any_whitespace=True"""
backend = self._backend(disable_any_whitespace=True)
# Check that grammar accepts json with NO space after colon
assert self._accepts_json(backend, '{"no_space_after_me":"yes_ofcourse"}')
# Check that grammar rejects json with space after colon
assert not self._accepts_json(backend, '{"yes_space_after_me": true}')
# FIXME(arpera):
# Comma + separators=(",", ":") is wrong on xgrammar <=0.2.8
# Seehttps://github.com/mlc-ai/xgrammar/issues/945
# Re-enable both tests once vLLM pins xgrammar with the fix (>=0.2.9).
#
# # Check that grammar accepts json with NO space after comma
# assert self._accepts_json(
# backend,
# '{"never_space_after_comma":"accepted","good_boy":":3"}',
# )
#
# # Check that grammar rejects json with space after comma
# assert not self._accepts_json(
# backend,
# '{"where_space_after_comma":42, "wow_thats_cool":4242}',
# )
@@ -11,6 +11,8 @@ 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.parser.engine.adapters import ParserEngineReasoningAdapter
from vllm.parser.engine.parser_engine import ReasoningEnd
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.request import Request
from vllm.v1.structured_output import StructuredOutputManager
@@ -18,6 +20,7 @@ from vllm.v1.structured_output.backend_outlines import OutlinesGrammar
TOKENIZER = "gpt2"
THINK_END = "\n" # reasoning-end marker (single GPT-2 token)
IMPLICIT_THINK_END = "z" # accepted in strings, rejected at the object start
EOS = "<|eos|>" # resolved to tokenizer.eos_token_id
JSON_SCHEMA = '{"type": "object"}'
BACKENDS = ("xgrammar", "guidance")
@@ -43,6 +46,7 @@ class FlowCase:
prefix: str = ""
expected_validated: tuple[str, ...] | None = None
reasoning_ended: bool | None = False
engine_reasoner: bool = False
xfail_guidance: str | None = None
@@ -59,6 +63,23 @@ class MockReasoner:
return self.is_reasoning_end(delta_ids)
class MockEngineReasoner(ParserEngineReasoningAdapter):
"""Ends reasoning implicitly on ``marker``, which is also content."""
def __init__(self, tokenizer, marker: int):
self.marker = marker
@property
def reasoning_end_token_ids(self):
return frozenset({self.marker})
def find_reasoning_end(self, token_ids):
ids = list(token_ids)
if self.marker in ids:
return ReasoningEnd(ids.index(self.marker), True)
return ReasoningEnd(len(ids), False)
def _single_token(tokenizer, text: str) -> int:
token_ids = tokenizer.encode(text)
assert len(token_ids) == 1, (text, token_ids)
@@ -331,6 +352,28 @@ FLOW_CASES = [
),
id="becomes_active_terminates",
),
pytest.param(
FlowCase(
prefix='{"a": "',
raw_drafts=(IMPLICIT_THINK_END,),
expected_row_pattern="UC",
expected_reasoning=True,
expect_terminated=False,
engine_reasoner=True,
),
id="implicit_end_accepted",
),
pytest.param(
FlowCase(
raw_drafts=(" ", IMPLICIT_THINK_END, "{", "}"),
expected_validated=(" ",),
expected_row_pattern="UUUUU",
expected_reasoning=False,
expect_terminated=False,
engine_reasoner=True,
),
id="implicit_end_rejected",
),
]
@@ -344,7 +387,8 @@ def test_real_flow(
if backend == "guidance" and case.xfail_guidance:
pytest.xfail(case.xfail_guidance)
reasoner_kwargs = {"marker": _single_token(tokenizer, THINK_END)}
marker = IMPLICIT_THINK_END if case.engine_reasoner else THINK_END
reasoner_kwargs = {"marker": _single_token(tokenizer, marker)}
manager, request = _build_harness(
tokenizer,
backend,
@@ -352,6 +396,8 @@ def test_real_flow(
reasoning_ended=case.reasoning_ended,
reasoning_parser_kwargs=reasoner_kwargs,
)
if case.engine_reasoner:
manager.reasoner_cls = MockEngineReasoner
raw_drafts = _to_token_ids(tokenizer, case.raw_drafts)
expected_texts = (
-325
View File
@@ -1,325 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
from xgrammar import Grammar
from xgrammar.testing import _is_grammar_accept_string
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.v1.structured_output.backend_xgrammar import (
has_xgrammar_unsupported_json_features,
validate_xgrammar_grammar,
)
from vllm.v1.structured_output.utils import choice_as_grammar
pytestmark = pytest.mark.cpu_test
def grammar_accepts(schema: dict, text: str) -> bool:
return _is_grammar_accept_string(Grammar.from_json_schema(schema), text)
@pytest.fixture
def unsupported_string_schemas():
return [
{"type": "string", "format": "non_existing_format"},
# TODO(arpera):
# pattern/format is compiled but length bounds are silently dropped,
# so the combination must be rejected instead of producing quietly
# wrong output
# https://github.com/mlc-ai/xgrammar/issues/749
{"type": "string", "pattern": "^a+$", "maxLength": 2},
{"type": "string", "pattern": "^a+$", "minLength": 3},
{"type": "string", "format": "email", "maxLength": 10},
]
@pytest.fixture
def unsupported_integer_schemas():
return [
{"type": "integer", "multipleOf": 120},
]
@pytest.fixture
def unsupported_number_schemas():
return [
{"type": "number", "multipleOf": 120},
]
@pytest.fixture
def unsupported_array_schemas():
return [
{"type": "array", "uniqueItems": True},
{"type": "array", "contains": {"type": "string"}},
{"type": "array", "minContains": 1},
{"type": "array", "maxContains": 5},
]
@pytest.fixture
def unsupported_property_names_combinations():
return [
# TODO(arpera):
# this case is not covered by xgrammar, so we should report this bug to xgrammar
# xgrammar drops propertyNames whenever patternProperties is present,
# so "grade_12" matches the pattern and escapes the name constraint
{
"type": "object",
"patternProperties": {"^grade_[0-9]+$": {"type": "integer"}},
"propertyNames": {"pattern": "^grade_[0-9]$"}, # does NOT match "grade_12"
},
# propertyNames makes xgrammar discard the sibling additionalProperties
# value schema: https://github.com/mlc-ai/xgrammar/issues/826
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"additionalProperties": {"type": "integer"},
},
# propertyNames is a string schema that conventionally omits "type", so
# it escapes the string check while xgrammar drops its length bound all
# the same: https://github.com/mlc-ai/xgrammar/issues/749
{
"type": "object",
"propertyNames": {"pattern": "^a+$", "maxLength": 2},
},
# xgrammar emits named `properties` separately from `propertyNames` and
# only applies `propertyNames` in its additional-properties branch, so a
# key declared in `properties` escapes the name constraint regardless of
# what `propertyNames` contains.
{
"type": "object",
"properties": {"Bad": {"type": "integer"}},
"required": ["Bad"],
"propertyNames": {"pattern": "^[a-z]+$"},
},
{
"type": "object",
"properties": {"Bad": {"type": "integer"}},
"propertyNames": {"enum": ["good"]},
},
# xgrammar's propertyNames-only branch falls back to an unconstrained
# value type, so it drops unevaluatedProperties whether it restricts
# values (a schema) or forbids them (false).
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"unevaluatedProperties": {"type": "integer"},
},
{
"type": "object",
"propertyNames": {"pattern": "^[a-z]+$"},
"unevaluatedProperties": False,
},
]
@pytest.fixture
def unsupported_pattern_properties_combinations():
return [
# JSON Schema requires a property matched by both `properties` and
# `patternProperties` to satisfy both (conjunction), but xgrammar
# compiles them as alternative branches, so satisfying either one is
# enough.
{
"type": "object",
"properties": {"x": {"type": "string"}},
"patternProperties": {"^x$": {"type": "integer"}},
},
# The same alternative-branches problem applies to overlapping
# patternProperties patterns: a key matching both patterns only has to
# satisfy one of them.
{
"type": "object",
"patternProperties": {
"^a[a-z]*$": {"type": "string"},
"^[a-z]*z$": {"type": "integer"},
},
},
]
@pytest.fixture
def supported_frankenstein_schema():
# IMPORTANT(arpera):
# Do NOT add more keywords here! This schema is overcrowded enough that a new
# keyword can end up having no effect on the compiled grammar while the
# test still passes. Give a new keyword its own fixture and named test.
return {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"email": {"type": "string", "format": "email"},
"status": {"type": "string"},
"scores": {"type": "array", "items": {"type": "number"}},
"car_type": {"type": "string", "enum": ["sedan", "suv", "truck"]},
"car_brand": {"type": "string", "pattern": "^[a-zA-Z]+$"},
"short_description": {"type": "string", "maxLength": 50},
"mileage": {"type": "number", "minimum": 0, "maximum": 1000000},
"model_year": {
"type": "integer",
"exclusiveMinimum": 1900,
"exclusiveMaximum": 2100,
},
"long_description": {"type": "string", "minLength": 50, "maxLength": 2000},
"address": {
"type": "object",
"properties": {
"street": {"type": "string"},
"city": {"type": "string"},
},
},
},
"minProperties": 1,
"maxProperties": 100,
}
@pytest.fixture
def property_names_schema():
return {"type": "object", "propertyNames": {"pattern": "^[a-z_]+$"}}
@pytest.fixture
def pattern_properties_schema():
return {
"type": "object",
"patternProperties": {"^grade_[0-9]+$": {"type": "integer"}},
}
class TestHasXGrammarUnsupportedJsonFeatures:
@pytest.mark.parametrize(
"schema_type",
[
"unsupported_string_schemas",
"unsupported_integer_schemas",
"unsupported_number_schemas",
"unsupported_array_schemas",
"unsupported_property_names_combinations",
"unsupported_pattern_properties_combinations",
],
)
def test_unsupported_json_features_by_type(self, schema_type, request):
schemas = request.getfixturevalue(schema_type)
for schema in schemas:
assert has_xgrammar_unsupported_json_features(schema), (
f"Schema should be unsupported: {schema}"
)
@pytest.mark.parametrize(
"schema_type",
[
"supported_frankenstein_schema",
"pattern_properties_schema",
"property_names_schema",
],
)
def test_supported_json_features(self, schema_type, request):
schema = request.getfixturevalue(schema_type)
assert not has_xgrammar_unsupported_json_features(schema), (
f"Schema should be supported: {schema}"
)
class TestPR48416Regressions:
@pytest.mark.parametrize(
"schema",
[
{"type": ["number"], "multipleOf": 3},
{
"type": ["string", "null"],
"pattern": "^a+$",
"maxLength": 2,
},
{
"type": ["array", "null"],
"items": {"type": "integer"},
"uniqueItems": True,
},
{
"type": ["object", "null"],
"properties": {"Bad": {"type": "integer"}},
"propertyNames": {"pattern": "^[a-z]+$"},
},
],
)
def test_list_type_does_not_bypass_unsupported_feature_check(self, schema):
assert has_xgrammar_unsupported_json_features(schema)
@pytest.mark.parametrize(
"schema",
[
{"type": ["string", "null"]},
{"type": ["integer", "string"]},
{"type": ["array", "null"], "items": {"type": "string"}},
{
"type": ["object", "null"],
"propertyNames": {"pattern": "^[a-z_]+$"},
},
{
"type": ["object", "null"],
"patternProperties": {"^S": {"type": "string"}},
},
],
)
def test_supported_list_type_json_features(self, schema):
assert not has_xgrammar_unsupported_json_features(schema)
class TestIsGrammarAcceptString:
class TestPR42904Support:
def test_property_names_constrains_keys(self, property_names_schema):
assert grammar_accepts(property_names_schema, '{"score": 5}')
assert grammar_accepts(property_names_schema, '{"score": "seven"}')
assert not grammar_accepts(property_names_schema, '{"Score": 5}')
assert not grammar_accepts(property_names_schema, '{"score_1": 5}')
def test_pattern_properties_constrains_keys_and_values(
self, pattern_properties_schema
):
assert grammar_accepts(pattern_properties_schema, '{"grade_1": 5}')
assert not grammar_accepts(pattern_properties_schema, '{"other": 5}')
assert not grammar_accepts(pattern_properties_schema, '{"grade_1": "five"}')
class TestPR48115Regressions:
@pytest.mark.parametrize("codepoint", [*range(0x20), 0x7F])
def test_choice_as_grammar_preserves_control_characters(self, codepoint):
choice = f"a{chr(codepoint)}f"
grammar = Grammar.from_ebnf(choice_as_grammar([choice]))
assert _is_grammar_accept_string(grammar, choice)
assert not _is_grammar_accept_string(grammar, "a")
assert not _is_grammar_accept_string(grammar, "af")
assert not _is_grammar_accept_string(grammar, f"a\\u{codepoint:04x}f")
@pytest.mark.parametrize(
("choice", "other"),
[
(r"a\nf", "a\nf"),
('a quote " and a backslash \\', 'a quote " and a backslash '),
("café", "cafe"),
("日本語", "日本"),
("😀", "😁"),
],
)
def test_choice_as_grammar_preserves_literal_choices(self, choice, other):
grammar = Grammar.from_ebnf(choice_as_grammar(["yes", choice]))
assert _is_grammar_accept_string(grammar, "yes")
assert _is_grammar_accept_string(grammar, choice)
assert not _is_grammar_accept_string(grammar, other)
assert not _is_grammar_accept_string(grammar, choice + "extra")
def test_validate_xgrammar_preserves_multiline_choice(self):
structured_outputs = StructuredOutputsParams(choice=["yes", "no\nplease"])
validate_xgrammar_grammar(
SamplingParams(structured_outputs=structured_outputs)
)
assert structured_outputs.choice is None
grammar = Grammar.from_ebnf(structured_outputs.grammar)
assert _is_grammar_accept_string(grammar, "yes")
assert _is_grammar_accept_string(grammar, "no\nplease")
assert not _is_grammar_accept_string(grammar, r"no\nplease")
+100 -1
View File
@@ -2,11 +2,18 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Request-time validation of structured output requests."""
import json
import pytest
from vllm.config import StructuredOutputsConfig
from vllm.exceptions import VLLMClientError, VLLMValidationError
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.sampling_params import (
MAX_STRUCTURED_OUTPUT_JSON_NESTING,
STRUCTURAL_TAG_WRAPPER_NESTING,
SamplingParams,
StructuredOutputsParams,
)
pytestmark = pytest.mark.cpu_test
@@ -110,6 +117,98 @@ def test_regex_with_nul_byte_rejected(regex):
validate_xgrammar_grammar(params)
def _nested_array_schema(levels: int) -> str:
# Built as text: json.dumps on a deeply nested dict would itself recurse.
wrappers = levels - 1
return (
'{"type": "array", "items": ' * wrappers + '{"type": "string"}' + "}" * wrappers
)
def _structural_tag(schema: str) -> str:
return (
'{"type": "structural_tag", "format": {"type": "json_schema", '
f'"json_schema": {schema}}}}}'
)
@pytest.mark.parametrize(
"structured_outputs",
[
pytest.param(
{"json": _nested_array_schema(MAX_STRUCTURED_OUTPUT_JSON_NESTING + 1)},
id="json-str-over-limit",
),
pytest.param(
{"json": json.loads(_nested_array_schema(2_000))},
id="json-dict-past-recursion-limit",
),
pytest.param(
{"json": _nested_array_schema(200_000)},
id="json-str-past-json-loads-recursion-limit",
),
pytest.param(
{
"structural_tag": _structural_tag(
_nested_array_schema(
MAX_STRUCTURED_OUTPUT_JSON_NESTING
+ STRUCTURAL_TAG_WRAPPER_NESTING
)
)
},
id="structural-tag-over-limit",
),
],
)
@pytest.mark.parametrize(
"backend", ["auto", "xgrammar", "guidance", "outlines", "lm-format-enforcer"]
)
def test_deeply_nested_schema_rejected(structured_outputs, backend):
"""Converting a schema to a grammar gets steeply more expensive with nesting
and runs on the API server; past the recursion limit it used to escape as a
RecursionError (HTTP 500 with an empty message). Deep nesting must be a
validation error before any backend touches the schema."""
params = SamplingParams(
structured_outputs=StructuredOutputsParams(**structured_outputs)
)
with pytest.raises(VLLMValidationError, match="nested too deeply"):
params._validate_structured_outputs(
_StubModelConfig(is_diffusion=False),
StructuredOutputsConfig(backend=backend),
tokenizer=object(),
)
@pytest.mark.parametrize("field", ["json", "structural_tag"])
def test_xgrammar_validation_rejects_deeply_nested_schema(field):
"""Request parsing and tool parsers call validate_xgrammar_grammar directly,
before _validate_structured_outputs, so it must check nesting itself."""
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
schema = _nested_array_schema(2_000)
value = _structural_tag(schema) if field == "structural_tag" else schema
params = SamplingParams(
structured_outputs=StructuredOutputsParams(**{field: value})
)
with pytest.raises(VLLMValidationError, match="nested too deeply"):
validate_xgrammar_grammar(params)
@pytest.mark.parametrize("field", ["json", "structural_tag"])
def test_schema_at_nesting_limit_accepted(field):
"""A structural tag wraps its schema in a few more levels (more for the
tags tool parsers generate), which must not count against the schema."""
schema = _nested_array_schema(MAX_STRUCTURED_OUTPUT_JSON_NESTING)
value = _structural_tag(schema) if field == "structural_tag" else schema
structured_outputs = StructuredOutputsParams(**{field: value})
SamplingParams(structured_outputs=structured_outputs)._validate_structured_outputs(
_StubModelConfig(is_diffusion=False),
StructuredOutputsConfig(),
tokenizer=object(),
)
assert structured_outputs._backend == "xgrammar"
INVALID_JSON_SCHEMA = {"type": "object", "properties": {"name": {"type": "str"}}}
+43 -2
View File
@@ -16,7 +16,7 @@ import torch
import vllm.v1.hisparse.binding as attn_utils_module
from tests.v1.attention.utils import dense_kv_cache_views
from vllm.config.compilation import CUDAGraphMode
from vllm.config.compilation import CompilationConfig, CUDAGraphMode
from vllm.v1.attention.backend import AttentionBackend, AttentionCGSupport, MultipleOf
from vllm.v1.core.kv_cache_utils import KVCacheBlockCopy
from vllm.v1.hisparse.binding import allocate_hisparse_kv_caches
@@ -228,6 +228,47 @@ def test_varlen_cudagraph_unsupported_backend_checks_scoped_bounds():
assert unsupported([[target, never]], config, 1) == ("_DraftBackend", None)
@pytest.mark.parametrize("num_speculative_tokens", [0, 7])
def test_flashinfer_sparse_full_graphs_exclude_prefill_keep_varlen_decode(
num_speculative_tokens,
):
"""Prefill must fall back without disabling adaptive verification graphs."""
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseTRTLLMBackend,
)
backend = FlashInferMLASparseTRTLLMBackend
config: Any = SimpleNamespace(
speculative_config=SimpleNamespace(
num_speculative_tokens=num_speculative_tokens, parallel_drafting=False
),
use_v2_model_runner=True,
)
spec = MLAAttentionSpec(
block_size=64, num_kv_heads=1, head_size=576, dtype=torch.bfloat16
)
group = AttentionGroup(backend, ["target"], spec, 0)
group.metadata_builders = [object.__new__(backend.get_builder_cls())]
groups = [[group]]
support = get_attn_cg_support(groups, config)
compilation = CompilationConfig(cudagraph_mode=CUDAGraphMode.FULL)
mode = compilation.resolve_cudagraph_mode_and_sizes(
support.min_cg_support,
support.min_cg_attn_backend,
uniform_decode_query_len=1 + num_speculative_tokens,
use_v2_model_runner=True,
)
assert mode.mixed_mode() != CUDAGraphMode.FULL
assert mode.decode_mode() == CUDAGraphMode.FULL
assert get_query_lens_mismatch_unsupported_backend(groups) is None
unsupported = attn_utils.get_varlen_cudagraph_unsupported_backend
assert unsupported(groups, config, 1 + num_speculative_tokens) is None
assert unsupported(groups, config, 2 + num_speculative_tokens) == (
backend.__name__,
1 + num_speculative_tokens,
)
def test_get_kv_sharing_fast_prefill_eligible_layers(monkeypatch: pytest.MonkeyPatch):
"""Fast prefill applies to the contiguous suffix of KV-sharing layers.
@@ -393,7 +434,7 @@ def test_init_hisparse_rolls_back_shared_region(monkeypatch, failure_phase):
cache_config=SimpleNamespace(
get_resolved_kv_cache_layout=lambda: KVCacheLayout.BLHNC
),
scheduler_config=SimpleNamespace(max_num_seqs=1, max_num_batched_tokens=1),
scheduler_config=SimpleNamespace(max_num_seqs=1),
)
def allocate(*args):
+16 -1
View File
@@ -78,7 +78,7 @@ def test_encoder_graph_unsupported_modality_uses_eager_output():
"vllm.v1.worker.gpu.mm.encoder_runner.group_and_batch_mm_kwargs",
return_value=[("audio", 1, {"audio_values": torch.zeros(2)})],
):
result = runner.execute_mm_encoder([])
result = runner.execute_mm_encoder([("audio", MagicMock())])
assert len(result) == 1
assert result[0] is output
manager.execute.assert_not_called()
@@ -290,6 +290,21 @@ def test_execute_mm_encoder_caches_outputs_without_gathering():
state.encoder_runner.gather_mm_embeddings.assert_not_called()
def test_execute_mm_encoder_sorts_by_modality():
"""Items are encoded sorted by modality; outputs keep the input order."""
mm_kwargs = [("video", 0), ("image", 1), ("video", 2), ("image", 3)]
runner = _make_runner([], [])
runner.model = MagicMock()
runner.model.embed_multimodal.side_effect = lambda x: [torch.full((1, 1), x)]
with patch(
"vllm.v1.worker.gpu.mm.encoder_runner.group_and_batch_mm_kwargs",
side_effect=lambda items, **_: [(m, 1, {"x": x}) for m, x in items],
) as group:
outputs = runner.execute_mm_encoder(mm_kwargs)
assert group.call_args.args[0] == [mm_kwargs[i] for i in (1, 3, 0, 2)]
assert [int(o) for o in outputs] == [0, 1, 2, 3]
def test_execute_mm_encoder_is_a_noop_without_scheduled_items():
"""A step that schedules no encoder input must not touch the encoder."""
cache = EncoderCache()
@@ -45,7 +45,8 @@ def test_init_speculator_dispatches_extract_hidden_states(monkeypatch):
monkeypatch.setattr(spec_module, "ExtractHiddenStatesSpeculator", fake_speculator)
assert init_speculator(vllm_config, device) == (vllm_config, device)
speculator = init_speculator(vllm_config, device, cast(Any, None))
assert speculator == (vllm_config, device)
def test_propose_caches_hidden_states_and_returns_sampled_tokens(monkeypatch):
+94
View File
@@ -624,6 +624,70 @@ def test_set_active_mm_loras_builds_tower_and_connector_mappings():
assert connector_mapping.index_mapping == ((7,) * 14 + (7,) * 13 + (0,) * 12)
def test_set_active_mm_loras_follows_modality_sorted_encoder_order():
model = Mock()
model.get_mm_lora_token_counts.side_effect = (
lambda *, modality, mm_kwargs, num_mm_embeds: (num_mm_embeds, None)
)
lora_manager = Mock()
lora_manager.supports_tower_connector_lora.return_value = True
encoder_cache = EncoderCache()
for req_id, modality, length in [("req-a", "video", 1), ("req-b", "image", 2)]:
encoder_cache.mm_features[req_id] = [
MultiModalFeatureSpec(
data=None,
modality=modality,
identifier=f"{req_id}-0",
mm_position=PlaceholderRange(offset=0, length=length),
)
]
lora_state = LoraState(max_num_reqs=2)
lora_request = LoRARequest("vision-lora", 7, "/tmp/vision-lora")
lora_state.add_request("req-a", 0, lora_request)
lora_state.add_request("req-b", 1, None)
set_active_mm_loras(
model=model,
lora_manager=lora_manager,
encoder_cache=encoder_cache,
req_id_to_index={"req-a": 0, "req-b": 1},
lora_state=lora_state,
scheduled_encoder_inputs={"req-a": [0], "req-b": [0]},
)
# The image is encoded before the video, so its tokens come first.
_, tower_mapping = lora_manager.set_active_adapters.call_args_list[0].args
assert tower_mapping.index_mapping == (0, 0, 7)
def test_batch_mm_inputs_from_scheduler_sorts_by_modality():
features = {
f"req{i}": MultiModalFeatureSpec(
data=Mock(),
modality=m,
identifier=f"hash{i}",
mm_position=PlaceholderRange(offset=i, length=1),
)
for i, m in enumerate(["video", "image", "video"])
}
runner = SimpleNamespace(
requests={r: SimpleNamespace(mm_features=[f]) for r, f in features.items()}
)
scheduler_output = SimpleNamespace(
scheduled_encoder_inputs={r: [0] for r in features}
)
mm_hashes, mm_kwargs, mm_lora_refs = GPUModelRunner._batch_mm_inputs_from_scheduler(
runner, scheduler_output
)
order = ["req1", "req0", "req2"]
assert mm_hashes == [features[r].identifier for r in order]
assert mm_kwargs == [(features[r].modality, features[r].data) for r in order]
assert mm_lora_refs == [(r, features[r].mm_position) for r in order]
def test_update_states_new_request(model_runner, dist_init):
req_id = "req_0"
@@ -1015,6 +1079,36 @@ def test_reload_weights_before_load_model(model_runner):
model_runner.reload_weights()
def test_reload_weights_path_replaces_object_storage_source(monkeypatch):
# An engine started from an object-storage URI keeps that URI in
# model_config.model_weights, which the runai_streamer loader prefers over
# model_config.model. A new weights_path must replace it, or the loader
# silently re-streams the original checkpoint.
loader = Mock()
loader.get_all_weights.return_value = iter(())
monkeypatch.setattr(gpu_model_runner_module, "get_model_loader", lambda _: loader)
monkeypatch.setattr(gpu_model_runner_module, "initialize_layerwise_reload", Mock())
monkeypatch.setattr(gpu_model_runner_module, "finalize_layerwise_reload", Mock())
runner = Mock(lora_config=None)
runner.model_config = SimpleNamespace(
model="/tmp/pulled-config-files",
model_weights="s3://bucket/original",
revision="abc123",
quantization=None,
)
runner.get_model.return_value.named_parameters.return_value = []
runner.get_model.return_value.load_weights.return_value = None
GPUModelRunner.reload_weights(runner, weights_path="org/new-model")
loader.get_all_weights.assert_called_once_with(
runner.model_config, runner.get_model.return_value
)
cfg = runner.model_config
assert (cfg.model, cfg.model_weights, cfg.revision) == ("org/new-model", "", None)
def test_sample_passes_reordered_draft_probs_to_rejection_sampler():
runner = object.__new__(GPUModelRunner)
runner.use_async_scheduling = False
@@ -0,0 +1,262 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""`GPUModelRunner._prepare_inputs` must tell a chunked-prefill continuation
row apart from a genuine zero-draft decode row.
Both kinds of row are absent from `scheduled_spec_decode_tokens` and both
schedule exactly one token, so `num_decode_draft_tokens` starts at the
placeholder `-1` for either. The `zero_draft_decode_mask` in
`gpu_model_runner.py` is what tells them apart afterwards, using
`num_computed_tokens >= num_prompt_tokens`: a prefill continuation must keep
`-1` (it carries no drafts and no accepted-token offset to apply), while a
zero-draft decode row must become `0` (it still has to run the speculative
path so the recurrent backends apply that offset). Getting this wrong in
either direction was the root cause behind issue #40875: Kimi-Linear crashed
with an illegal memory access when prefill tails were misclassified as
zero-draft decodes.
Each batch below also includes one row with a real draft token, so
`scheduled_spec_decode_tokens` is non-empty even under the pre-fix
`use_spec_decode = len(scheduled_spec_decode_tokens) > 0` predicate. That
keeps the assertions targeted at the mask fix alone, not the unrelated
`use_spec_decode` predicate fix (`self.speculative_config is not None`) that
landed in the same patch.
"""
from types import SimpleNamespace
import numpy as np
import pytest
from vllm.config import (
CacheConfig,
ModelConfig,
ParallelConfig,
SchedulerConfig,
SpeculativeConfig,
VllmConfig,
set_current_vllm_config,
)
from vllm.model_executor.layers.attention import Attention
from vllm.platforms import current_platform
from vllm.sampling_params import SamplingParams
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.v1.core.sched.output import CachedRequestData, NewRequestData, SchedulerOutput
from vllm.v1.kv_cache_interface import (
FullAttentionSpec,
KVCacheConfig,
KVCacheGroupSpec,
KVCacheTensor,
)
from vllm.v1.worker.gpu_input_batch import InputBatch
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
BLOCK_SIZE = 16
NUM_BLOCKS = 10
def _get_vllm_config() -> VllmConfig:
model_config = ModelConfig(model="facebook/opt-125m", dtype="float16", seed=42)
scheduler_config = SchedulerConfig(
max_num_seqs=10,
max_num_batched_tokens=512,
max_model_len=512,
is_encoder_decoder=model_config.is_encoder_decoder,
)
cache_config = CacheConfig(
block_size=BLOCK_SIZE, gpu_memory_utilization=0.9, cache_dtype="auto"
)
cache_config.kv_cache_layout = "LBNHC"
return VllmConfig(
model_config=model_config,
cache_config=cache_config,
scheduler_config=scheduler_config,
parallel_config=ParallelConfig(),
# ngram needs no draft model weights, so the fixture stays as cheap as
# the speculative-decoding-free one in test_gpu_model_runner.py.
speculative_config=SpeculativeConfig(method="ngram", num_speculative_tokens=3),
)
def _make_model_runner(vllm_config: VllmConfig) -> GPUModelRunner:
"""Build the V1 runner the platform's worker would, without starting it."""
worker_cls = resolve_obj_by_qualname(vllm_config.parallel_config.worker_cls)
worker = SimpleNamespace(
vllm_config=vllm_config,
device=current_platform.device_type,
use_v2_model_runner=False,
)
return worker_cls._make_model_runner(worker)
def _initialize_kv_cache(runner: GPUModelRunner) -> None:
attn_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=runner.model_config.get_num_kv_heads(runner.parallel_config),
head_size=runner.model_config.get_head_size(),
dtype=runner.kv_cache_dtype,
)
tensor_size = attn_spec.page_size_bytes * NUM_BLOCKS
kv_cache_config = KVCacheConfig(
num_blocks=NUM_BLOCKS,
kv_cache_tensors=[
KVCacheTensor(
size=tensor_size,
layers=["layer.0"],
layer_stride=tensor_size,
block_stride=attn_spec.page_size_bytes,
),
],
kv_cache_groups=[
KVCacheGroupSpec(layer_names=["layer.0"], kv_cache_spec=attn_spec)
],
)
runner.kv_cache_config = kv_cache_config
runner.input_batch = InputBatch(
max_num_reqs=runner.max_num_reqs,
max_model_len=runner.max_model_len,
max_num_batched_tokens=runner.max_num_tokens,
device=runner.device,
vocab_size=runner.model_config.get_vocab_size(),
block_sizes=[kv_cache_config.kv_cache_groups[0].kv_cache_spec.block_size],
kernel_block_sizes=[
kv_cache_config.kv_cache_groups[0].kv_cache_spec.block_size
],
max_num_blocks_per_req=[NUM_BLOCKS],
)
runner.initialize_attn_backend(kv_cache_config)
@pytest.fixture
def spec_decode_model_runner(dist_init):
vllm_config = _get_vllm_config()
with set_current_vllm_config(vllm_config):
model_config = vllm_config.model_config
num_heads = model_config.get_num_kv_heads(vllm_config.parallel_config)
head_size = model_config.get_head_size()
vllm_config.compilation_config.static_forward_context["layer.0"] = Attention(
num_heads, head_size, 0.1
)
runner = _make_model_runner(vllm_config)
_initialize_kv_cache(runner)
yield runner
def _new_request(
req_id: str, prompt_len: int, num_computed_tokens: int
) -> tuple[NewRequestData, int]:
"""A request with `prompt_len` prompt tokens, `num_computed_tokens` of
which are already computed (e.g. a prefix-cache hit), scheduled for the
single remaining/next token this step."""
return (
NewRequestData(
req_id=req_id,
prompt_token_ids=list(range(prompt_len)),
mm_features=[],
sampling_params=SamplingParams(),
pooling_params=None,
block_ids=([0],),
num_computed_tokens=num_computed_tokens,
lora_request=None,
),
1,
)
def test_prefill_continuation_keeps_placeholder_decode_zero_draft_becomes_zero(
spec_decode_model_runner,
):
"""One request has one token left to prefill (`num_computed_tokens ==
num_prompt_tokens - 1`); another has already finished its prompt and is
now decoding with no draft tokens proposed this step; a third is decoding
with a real draft. `decode_with_draft` gives the batch a non-empty
`scheduled_spec_decode_tokens`, so this also exercises the `-1`-vs-`0`
distinction on the pre-fix definition of `use_spec_decode` (`len(sched
uled_spec_decode_tokens) > 0`), isolating the mask fix from the unrelated
`use_spec_decode` predicate fix that landed in the same patch."""
runner = spec_decode_model_runner
prefill_req, prefill_sched = _new_request(
"prefill_tail", prompt_len=11, num_computed_tokens=10
)
decode_req, decode_sched = _new_request(
"decode_zero_draft", prompt_len=3, num_computed_tokens=3
)
drafted_req, _ = _new_request(
"decode_with_draft", prompt_len=3, num_computed_tokens=3
)
num_scheduled_tokens = {
"prefill_tail": prefill_sched,
"decode_zero_draft": decode_sched,
"decode_with_draft": 2, # 1 draft token + 1 bonus token
}
scheduler_output = SchedulerOutput(
scheduled_new_reqs=[prefill_req, decode_req, drafted_req],
scheduled_cached_reqs=CachedRequestData.make_empty(),
num_scheduled_tokens=num_scheduled_tokens,
total_num_scheduled_tokens=sum(num_scheduled_tokens.values()),
scheduled_spec_decode_tokens={"decode_with_draft": [99]},
scheduled_encoder_inputs={},
num_common_prefix_blocks=[],
finished_req_ids=set(),
free_encoder_mm_hashes=[],
)
runner._update_states(scheduler_output)
runner._prepare_inputs(
scheduler_output,
np.array(
[num_scheduled_tokens[r] for r in runner.input_batch.req_ids],
dtype=np.int32,
),
)
prefill_idx = runner.input_batch.req_id_to_index["prefill_tail"]
decode_idx = runner.input_batch.req_id_to_index["decode_zero_draft"]
drafted_idx = runner.input_batch.req_id_to_index["decode_with_draft"]
assert runner.num_decode_draft_tokens.np[prefill_idx] == -1
assert runner.num_decode_draft_tokens.np[decode_idx] == 0
assert runner.num_decode_draft_tokens.np[drafted_idx] == 1
def test_prefill_tail_of_two_or_three_tokens_also_keeps_the_placeholder(
spec_decode_model_runner,
):
"""A chunked-prefill tail can be 1, 2, or 3 tokens (`long_prefill_token_
threshold` rounding); the mask only fires for `num_scheduled_tokens == 1`,
so wider tails must keep `-1` regardless of how much prompt is left. A
third, drafted decode row keeps `scheduled_spec_decode_tokens` non-empty
so the assertions hold on the pre-fix `use_spec_decode` predicate too."""
runner = spec_decode_model_runner
tail_2_req, _ = _new_request("tail_2", prompt_len=12, num_computed_tokens=10)
tail_3_req, _ = _new_request("tail_3", prompt_len=13, num_computed_tokens=10)
drafted_req, _ = _new_request(
"decode_with_draft", prompt_len=3, num_computed_tokens=3
)
num_scheduled_tokens = {"tail_2": 2, "tail_3": 3, "decode_with_draft": 2}
scheduler_output = SchedulerOutput(
scheduled_new_reqs=[tail_2_req, tail_3_req, drafted_req],
scheduled_cached_reqs=CachedRequestData.make_empty(),
num_scheduled_tokens=num_scheduled_tokens,
total_num_scheduled_tokens=sum(num_scheduled_tokens.values()),
scheduled_spec_decode_tokens={"decode_with_draft": [99]},
scheduled_encoder_inputs={},
num_common_prefix_blocks=[],
finished_req_ids=set(),
free_encoder_mm_hashes=[],
)
runner._update_states(scheduler_output)
runner._prepare_inputs(
scheduler_output,
np.array(
[num_scheduled_tokens[r] for r in runner.input_batch.req_ids],
dtype=np.int32,
),
)
tail_2_idx = runner.input_batch.req_id_to_index["tail_2"]
tail_3_idx = runner.input_batch.req_id_to_index["tail_3"]
assert runner.num_decode_draft_tokens.np[tail_2_idx] == -1
assert runner.num_decode_draft_tokens.np[tail_3_idx] == -1
+34 -1
View File
@@ -18,6 +18,7 @@ from vllm.v1.kv_cache_interface import (
MambaSpec,
UniformTypeKVCacheSpecs,
)
from vllm.v1.worker.gpu.async_utils import async_copy_to_np
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.model_runner import ExecuteModelState, GPUModelRunner
@@ -46,6 +47,7 @@ def test_non_last_pp_rank_uses_global_batch_for_sample_feedback():
finished_req_ids=set(),
ec_connector_output=None,
cudagraph_stats=None,
num_spec_tokens_to_schedule=0,
)
runner.sample_tokens(None)
@@ -258,7 +260,9 @@ def _make_capture_runner(captured: bool) -> GPUModelRunner:
"""Minimal V2 runner for capture_model: fakes everything except the
cudagraph_manager's needs_capture decision."""
runner = GPUModelRunner.__new__(GPUModelRunner)
runner.model_state = SimpleNamespace(supports_mm_inputs=False)
runner.model_state = SimpleNamespace(
supports_mm_inputs=False, capture_inner_cudagraphs=lambda *args: None
)
runner.cudagraph_manager = SimpleNamespace(
needs_capture=lambda: captured,
capture=lambda *args, **kwargs: None,
@@ -334,3 +338,32 @@ def test_capture_model_profile_only_skips_lock(monkeypatch):
runner.capture_model(profile_only=True)
assert lock_calls == []
@pytest.mark.parametrize("target_buffer", ["absent", "none", "tensor"])
def test_get_drafter_hidden_states_tolerates_missing_target_buffer(target_buffer):
"""Targets allocate the MTP hidden buffer only for hidden-state drafters."""
runner = GPUModelRunner.__new__(GPUModelRunner)
hidden_states = torch.zeros(4, 8)
buffer = torch.arange(16 * 8, dtype=torch.float32).view(16, 8)
if target_buffer == "absent":
runner.model = SimpleNamespace()
else:
returned = buffer if target_buffer == "tensor" else None
runner.model = SimpleNamespace(get_mtp_target_hidden_states=lambda: returned)
out = runner._get_drafter_hidden_states(hidden_states)
if target_buffer == "tensor":
assert torch.equal(out, buffer[:4])
else:
assert out is hidden_states
def test_async_copy_to_np_does_not_alias_reused_buffer():
buffer = torch.zeros(4, dtype=torch.int64)
snapshot = async_copy_to_np(buffer)
buffer.fill_(1)
assert snapshot.tolist() == [0, 0, 0, 0]
@@ -190,6 +190,7 @@ def test_v2_sample_tokens_runs_eplb_on_non_last_pp_rank(monkeypatch):
ec_connector_output=None,
routed_experts=None,
cudagraph_stats=None,
num_spec_tokens_to_schedule=0,
)
runner.req_states = SimpleNamespace()
+192 -17
View File
@@ -1,6 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import os
import threading
from contextlib import nullcontext
from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, call, patch
@@ -26,6 +28,7 @@ from vllm.profiler.wrapper import (
validate_worker_profiler_config,
)
from vllm.v1.core.sched.output import CachedRequestData
from vllm.v1.executor.abstract import Executor
from vllm.v1.worker.gpu_model_runner import GPUModelRunner
from vllm.v1.worker.gpu_worker import Worker
from vllm.v1.worker.xpu_worker import XPUWorker
@@ -98,17 +101,25 @@ def test_torch_profiler_rebuilds_one_shot_profiler_each_round(tmp_path):
def test_torch_profiler_records_each_profile_round(tmp_path):
traces: list[torch.profiler.profile] = []
trace_paths: list[str] = []
def export_trace(prof: torch.profiler.profile) -> None:
# Export as each round stops instead of parsing every round at the end.
path = str(tmp_path / f"round_{len(trace_paths)}.json")
prof.export_chrome_trace(path)
trace_paths.append(path)
wrapper = TorchProfilerWrapper(
ProfilerConfig(
profiler="torch",
torch_profiler_dir=str(tmp_path),
torch_profiler_dump_cuda_time_total=False,
torch_profiler_with_stack=False,
),
worker_name="worker",
local_rank=1,
activities=["CPU"],
on_trace_ready=traces.append,
on_trace_ready=export_trace,
)
for run in range(2):
@@ -117,10 +128,16 @@ def test_torch_profiler_records_each_profile_round(tmp_path):
pass
wrapper.stop()
assert len(traces) == 2
for run, trace in enumerate(traces):
assert len(trace_paths) == 2
for run, path in enumerate(trace_paths):
# The CPU profiler records every thread in the process, and an event
# name from elsewhere in a long session can hold invalid UTF-8.
with open(path, encoding="utf-8", errors="replace") as f:
events = json.load(f)["traceEvents"]
assert {
event.name for event in trace.events() if event.name.startswith("run_")
event["name"]
for event in events
if event.get("name", "").startswith("run_")
} == {f"run_{run}"}
@@ -145,13 +162,33 @@ def test_torch_profiler_device_summary(tmp_path, capsys, activities, dump_device
wrapper.start()
wrapper.stop()
summary = tmp_path / "profiler_out_0.txt"
summary = tmp_path / "worker.profiler_out.txt"
assert summary.exists() == dump_device_time
assert ("device times" in capsys.readouterr().out) == dump_device_time
if dump_device_time:
assert summary.read_text() == "device times\n"
def test_torch_profiler_summary_follows_output_name(tmp_path):
config = ProfilerConfig(
profiler="torch",
torch_profiler_dir=str(tmp_path),
)
with patch("vllm.profiler.wrapper.torch.profiler.profile") as profile:
table = profile.return_value.key_averages.return_value.table
table.side_effect = ["first run", "second run"]
wrapper = TorchProfilerWrapper(
config, worker_name="initial", local_rank=1, activities=["CUDA"]
)
for output_name in ["first_rank1", "second_rank1"]:
wrapper.set_output_name(output_name)
wrapper.start()
wrapper.stop()
assert (tmp_path / "first_rank1.profiler_out.txt").read_text() == "first run\n"
assert (tmp_path / "second_rank1.profiler_out.txt").read_text() == "second run\n"
@pytest.mark.parametrize(
"activities",
[[], ["CPU", "CPU"], ["INVALID"]],
@@ -170,6 +207,30 @@ def test_torch_profiler_activities_require_torch_profiler():
ProfilerConfig(torch_profiler_activities=["CPU"])
@pytest.mark.parametrize(
("profiler", "activities", "ignore_frontend", "expected"),
[
("torch", None, False, True),
("torch", ["CPU"], False, True),
("torch", ["CPU", "CUDA"], False, True),
("torch", ["CUDA"], False, False),
("torch", ["CPU"], True, False),
("cuda", None, False, False),
],
)
def test_should_profile_frontend(
profiler, activities, ignore_frontend, expected, tmp_path
):
config = ProfilerConfig(
profiler=profiler,
torch_profiler_dir=str(tmp_path) if profiler == "torch" else "",
torch_profiler_activities=activities,
ignore_frontend=ignore_frontend,
)
assert config.should_profile_frontend is expected
@pytest.mark.parametrize(
("device_type", "activities"),
[
@@ -256,16 +317,81 @@ def test_worker_reuses_torch_wrapper_across_profile_rounds(worker_type):
patch("vllm.distributed.utils.get_worker_rank_suffix", return_value="rank0"),
patch("vllm.profiler.wrapper.TorchProfilerWrapper") as wrapper,
):
worker.profile()
worker.profile(
profile_prefix="first",
delay_iterations=5,
max_iterations=2,
)
worker.profile(is_start=False)
worker.profile()
worker.profile(profile_prefix="second")
assert worker.profiler is wrapper.return_value
wrapper.assert_called_once()
assert wrapper.return_value.start.call_count == 2
assert wrapper.return_value.set_output_name.call_args_list == [
call("first_rank0"),
call("second_rank0"),
]
assert wrapper.return_value.start.call_args_list == [
call(delay_iterations=5, max_iterations=2),
call(delay_iterations=None, max_iterations=None),
]
wrapper.return_value.stop.assert_called_once_with()
def test_executor_profile_only_forwards_supplied_override_kwargs():
executor = MagicMock()
executor.vllm_config.parallel_config.worker_cls = "vllm.v1.worker.gpu_worker.Worker"
Executor.profile(executor, True, "default")
Executor.profile(
executor,
True,
"bounded",
delay_iterations=5,
max_iterations=2,
)
assert executor.collective_rpc.call_args_list == [
call("profile", args=(True, "default"), kwargs=None),
call(
"profile",
args=(True, "bounded"),
kwargs={"delay_iterations": 5, "max_iterations": 2},
),
]
class _LegacyProfileWorker:
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
pass
def test_executor_rejects_overrides_unsupported_by_worker():
"""Out-of-tree workers with the old ``profile`` signature are rejected
before dispatch, so a failed collective_rpc cannot leave replies queued."""
executor = MagicMock()
executor.vllm_config.parallel_config.worker_cls = f"{__name__}._LegacyProfileWorker"
with pytest.raises(ValueError, match="max_iterations"):
Executor.profile(executor, True, None, max_iterations=2)
Executor.profile(executor, True, "legacy")
executor.collective_rpc.assert_called_once_with(
"profile", args=(True, "legacy"), kwargs=None
)
def test_worker_rejects_invalid_profile_prefix():
worker = object.__new__(Worker)
worker.profiler = None
worker.profiler_config = ProfilerConfig(
profiler="torch", torch_profiler_dir="/tmp/mock"
)
with pytest.raises(ValueError, match="profile_prefix"):
worker.profile(profile_prefix="../trace")
def test_immediate_start_stop(default_profiler_config):
"""Test standard start without delay."""
profiler = ConcreteWorkerProfiler(default_profiler_config)
@@ -280,6 +406,33 @@ def test_immediate_start_stop(default_profiler_config):
assert profiler.stop_call_count == 1
def test_stop_waits_for_inflight_start(default_profiler_config):
"""A stop() from another thread during a slow start() must still stop the
backend instead of leaving it running with the session marked inactive."""
profiler = ConcreteWorkerProfiler(default_profiler_config)
in_start = threading.Event()
release_start = threading.Event()
def slow_start():
in_start.set()
release_start.wait()
with patch.object(profiler, "_start", side_effect=slow_start):
start_thread = threading.Thread(target=profiler.start)
start_thread.start()
assert in_start.wait(timeout=5)
stop_thread = threading.Thread(target=profiler.stop)
stop_thread.start()
stop_thread.join(timeout=0.1)
release_start.set()
start_thread.join(timeout=5)
stop_thread.join(timeout=5)
assert profiler._active is False
assert profiler._running is False
assert profiler.stop_call_count == 1
def test_delayed_start(default_profiler_config):
"""Test that profiler waits for N steps before actually starting."""
default_profiler_config.delay_iterations = 2
@@ -386,19 +539,37 @@ def test_delayed_start_and_max_iters(default_profiler_config):
assert profiler.stop_call_count == 1
def test_idempotency(default_profiler_config):
"""Test that calling start/stop multiple times doesn't break logic."""
def test_duplicate_start_is_ignored(default_profiler_config):
profiler = ConcreteWorkerProfiler(default_profiler_config)
# Double Start
profiler.start()
profiler.start()
assert profiler.start_call_count == 1 # Should only start once
assert profiler.start_call_count == 1
# Double Stop
profiler.stop()
profiler.stop()
assert profiler.stop_call_count == 1 # Should only stop once
assert profiler.stop_call_count == 1
def test_session_bounds_override_and_reset_to_defaults():
profiler = ConcreteWorkerProfiler(
ProfilerConfig(
profiler="torch",
torch_profiler_dir="/tmp/mock",
delay_iterations=3,
max_iterations=4,
)
)
profiler.start(delay_iterations=1, max_iterations=2)
assert profiler._delay_iters == 1
assert profiler._max_iters == 2
profiler.stop()
profiler.start()
assert profiler._delay_iters == 3
assert profiler._max_iters == 4
profiler.stop()
def test_step_inactive(default_profiler_config):
@@ -1081,7 +1252,9 @@ def test_gpu_worker_creates_proton_profiler():
Worker.profile(worker)
wrapper.assert_called_once_with(worker.profiler_config, worker_name="rank1")
worker.profiler.start.assert_called_once_with()
worker.profiler.start.assert_called_once_with(
delay_iterations=None, max_iterations=None
)
@_requires_cuda_for_proton
@@ -1127,7 +1300,9 @@ def test_gpu_worker_reuses_cuda_graph_proton_session():
Worker.profile(worker, is_start=False)
worker.profiler.set_output_name.assert_called_once_with("first_rank1")
worker.profiler.start.assert_called_once_with()
worker.profiler.start.assert_called_once_with(
delay_iterations=None, max_iterations=None
)
worker.profiler.stop.assert_called_once_with()
@@ -22,17 +22,17 @@ from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadata
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
from vllm.v1.worker.gpu.spec_decode import speculator as base_spec_module
from vllm.v1.worker.gpu.spec_decode.autoregressive import speculator as spec_module
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
AutoRegressiveSpeculator,
)
from vllm.v1.worker.gpu.spec_decode.multi_module_mtp.speculator import (
MultiModuleMTPSpeculator,
)
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar import speculator as spec_module
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
TargetDependentARSpeculator,
)
class _TestSpeculator(AutoRegressiveSpeculator):
class _TestSpeculator(TargetDependentARSpeculator):
def load_draft_model(self, target_model, target_attn_layer_names):
return self.test_draft_model
@@ -337,6 +337,30 @@ def test_draft_model_multimodal_embedding_capability(model_cls, expected):
assert supports_multimodal_embeddings(model_cls) is expected
@pytest.mark.parametrize(
"model_cls", [EagleLlama4ForCausalLM, EagleMistralLarge3ForCausalLM]
)
def test_mm_capable_drafter_merges_multimodal_embeddings(model_cls):
"""Drafters advertising multimodal embeddings must embed text ids and
scatter the multimodal embeddings themselves; they do not inherit
SupportsMultiModal's helpers."""
table = torch.arange(8, dtype=torch.float32).repeat(3, 1).T # [8, 3]
drafter = object.__new__(model_cls)
drafter.model = SimpleNamespace(embed_input_ids=lambda ids: table[ids])
input_ids = torch.tensor([1, 5, 6, 2])
text_only = model_cls.embed_input_ids(drafter, input_ids)
assert torch.equal(text_only, table[input_ids])
mm_embeds = [torch.full((2, 3), -1.0)]
is_multimodal = torch.tensor([False, True, True, False])
merged = model_cls.embed_input_ids(
drafter, input_ids, mm_embeds, is_multimodal=is_multimodal
)
assert torch.equal(merged[[0, 3]], table[[1, 2]])
assert torch.equal(merged[[1, 2]], mm_embeds[0])
def test_run_model_unpacks_tuple_return_for_mtp(monkeypatch):
logits_hidden = torch.full((4, 3), 1.0)
feedback_hidden = torch.full((4, 3), 2.0)
@@ -374,19 +398,22 @@ def test_run_model_reuses_tensor_return_for_mtp(monkeypatch):
(
"method_name",
"cg_mode",
"num_speculative_steps",
"expected_eager_calls",
"expected_graph_replays",
),
[
("_multi_step_decode", CUDAGraphMode.NONE, 3, 0),
("_multi_step_decode", CUDAGraphMode.FULL, 0, 3),
("_fused_multi_step_decode", CUDAGraphMode.NONE, 3, 0),
("_fused_multi_step_decode", CUDAGraphMode.FULL, 0, 1),
("_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
("_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 3),
("_fused_multi_step_decode", CUDAGraphMode.NONE, 4, 3, 0),
("_fused_multi_step_decode", CUDAGraphMode.FULL, 4, 0, 1),
("_multi_step_decode", CUDAGraphMode.FULL, 3, 0, 2),
],
)
def test_multi_step_decode_replays_captured_graph_as_expected(
method_name,
cg_mode,
num_speculative_steps,
expected_eager_calls,
expected_graph_replays,
):
@@ -416,6 +443,7 @@ def test_multi_step_decode_replays_captured_graph_as_expected(
batch_desc=batch_desc,
seq_lens_cpu_upper_bound=None,
num_tokens_across_dp=None,
num_speculative_steps=num_speculative_steps,
)
assert generate_draft.call_count == expected_eager_calls
+32 -15
View File
@@ -116,9 +116,14 @@ class _StepRecorder:
def __init__(self) -> None:
# (blocks held per group, num_computed_tokens, num_scheduled_tokens)
self.steps: list[tuple[list[int], int, int]] = []
self.num_spec_tokens_to_schedule: list[int] = []
self._held: dict[str, list[int]] = {}
def execute_model(self, scheduler_output) -> None:
if scheduler_output.total_num_scheduled_tokens:
self.num_spec_tokens_to_schedule.append(
scheduler_output.num_spec_tokens_to_schedule
)
for new_req in scheduler_output.scheduled_new_reqs:
self._held[new_req.req_id] = [len(ids) for ids in new_req.block_ids]
self._record(new_req.req_id, new_req.num_computed_tokens, scheduler_output)
@@ -161,7 +166,7 @@ def _assert_covers_lookahead(
# 0 covers eagle / MTP / draft models, 1 covers DFlash's extra in-fill query.
@pytest.mark.parametrize("extra_lookahead", [0, 1])
@pytest.mark.parametrize("num_spec_steps", [2, 3, 5, 7])
@pytest.mark.parametrize("num_spec_steps", [1, 2, 3, 5, 7])
def test_warmup_kernels_reserves_lookahead_blocks(num_spec_steps, extra_lookahead):
num_lookahead_tokens = num_spec_steps + extra_lookahead
recorder = _StepRecorder()
@@ -173,6 +178,7 @@ def test_warmup_kernels_reserves_lookahead_blocks(num_spec_steps, extra_lookahea
)
_assert_covers_lookahead(recorder.steps, num_lookahead_tokens)
assert set(recorder.num_spec_tokens_to_schedule) == {num_spec_steps}
def test_mixed_warmup_reserves_lookahead_blocks():
@@ -187,6 +193,7 @@ def test_mixed_warmup_reserves_lookahead_blocks():
)
_assert_covers_lookahead(recorder.steps, num_lookahead_tokens)
assert set(recorder.num_spec_tokens_to_schedule) == {NUM_SPEC_STEPS}
@pytest.mark.parametrize("mamba_cache_mode", ["none", "align"])
@@ -314,24 +321,28 @@ def test_reserved_block_count_matches_real_kv_cache_manager():
@pytest.mark.parametrize(
("method", "expected"),
("method", "draft_hf_config", "expected"),
[
("eagle", NUM_SPEC_STEPS),
("eagle3", NUM_SPEC_STEPS),
("mtp", NUM_SPEC_STEPS),
("dspark", NUM_SPEC_STEPS),
("draft_model", NUM_SPEC_STEPS),
("eagle", None, NUM_SPEC_STEPS),
("eagle3", None, NUM_SPEC_STEPS),
("mtp", None, NUM_SPEC_STEPS),
("dspark", None, NUM_SPEC_STEPS),
("dspark", {"sample_from_anchor": True}, NUM_SPEC_STEPS),
("dspark", {"sample_from_anchor": False}, NUM_SPEC_STEPS + 1),
("draft_model", None, NUM_SPEC_STEPS),
# DFlash's in-fill decoding adds a query for the last sampled token.
("dflash", NUM_SPEC_STEPS + 1),
("ngram", 0),
("ngram_gpu", 0),
("medusa", 0),
("mlp_speculator", 0),
("suffix", 0),
("extract_hidden_states", 0),
("dflash", None, NUM_SPEC_STEPS + 1),
("ngram", None, 0),
("ngram_gpu", None, 0),
("medusa", None, 0),
("mlp_speculator", None, 0),
("suffix", None, 0),
("extract_hidden_states", None, 0),
],
)
def test_num_lookahead_tokens_per_method(method: str, expected: int):
def test_num_lookahead_tokens_per_method(
method: str, draft_hf_config: dict | None, expected: int
):
"""`VllmConfig.num_lookahead_tokens` is the single source of the reservation.
Both the scheduler and the warmup read it, so a wrong answer here silently
@@ -350,6 +361,12 @@ def test_num_lookahead_tokens_per_method(method: str, expected: int):
speculative_config = object.__new__(SpeculativeConfig)
object.__setattr__(speculative_config, "method", method)
object.__setattr__(speculative_config, "num_speculative_tokens", NUM_SPEC_STEPS)
hf_config = SimpleNamespace(**(draft_hf_config or {}))
object.__setattr__(
speculative_config,
"draft_model_config",
SimpleNamespace(hf_config=hf_config),
)
config = _Config()
config.speculative_config = speculative_config
-3
View File
@@ -378,9 +378,6 @@ def test_execute_model_waits_previous_pp_send_before_forward(
worker = SimpleNamespace(
vllm_config=SimpleNamespace(
compilation_config=SimpleNamespace(
pass_config=SimpleNamespace(enable_sp=False)
),
parallel_config=SimpleNamespace(
pipeline_parallel_size=2, distributed_executor_backend="mp"
),
@@ -67,6 +67,22 @@ def test_prepare_attn_forwards_positions(monkeypatch: pytest.MonkeyPatch) -> Non
assert build_attn_metadata.call_args.kwargs["positions"] is positions
def test_add_request_seeds_state_idx_in_mamba_blocks() -> None:
"""A drafter group can lower cache_config.block_size below the mamba
block size; the seeded column must still be in mamba blocks."""
state = object.__new__(MambaHybridModelState)
state.cache_config = SimpleNamespace(block_size=16, mamba_block_size=880)
state._align_mode = True
state.rope_state = None
state.prompt_embeds_state = None
state.num_accepted_tokens_gpu = torch.ones(2, dtype=torch.int32)
state._mamba_state_idx_gpu = torch.zeros(2, dtype=torch.int32)
state.add_request(1, SimpleNamespace(num_computed_tokens=107_360))
assert state._mamba_state_idx_gpu[1] == 121
def test_padded_prompt_tail_builds_as_spec_decode(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -140,6 +156,177 @@ def test_padded_prompt_tail_builds_as_spec_decode(
assert meta.num_prefill_tokens == k + 1
def _mamba_hybrid_state(num_speculative_tokens: int) -> MambaHybridModelState:
state = object.__new__(MambaHybridModelState)
state.vllm_config = SimpleNamespace(num_speculative_tokens=num_speculative_tokens)
state.model_config = SimpleNamespace(max_model_len=8192)
state._align_mode = False
state.recoverssm = None
# A request that accepted 3 drafts (plus the bonus token) on the previous
# step; the others have never had a draft accepted.
state.num_accepted_tokens_gpu = torch.tensor([4, 1, 1], dtype=torch.int32)
return state
def _input_batch(
num_scheduled_tokens: list[int],
num_draft_tokens_per_req: list[int] | None,
is_prefilling: list[bool],
num_reqs_after_padding: int | None = None,
) -> SimpleNamespace:
"""`num_draft_tokens_per_req=None` is a batch where nobody proposed a
draft this step, e.g. because ngram found no match for anyone."""
num_reqs = len(num_scheduled_tokens)
query_start_loc = np.zeros(num_reqs + 1, dtype=np.int32)
query_start_loc[1:] = np.cumsum(num_scheduled_tokens)
num_tokens = int(query_start_loc[-1])
seq_lens = torch.full((num_reqs,), 10, dtype=torch.int32)
return SimpleNamespace(
num_reqs=num_reqs,
num_reqs_after_padding=num_reqs_after_padding or num_reqs,
num_tokens=num_tokens,
num_tokens_after_padding=num_tokens,
query_start_loc_np=query_start_loc,
num_scheduled_tokens=np.array(num_scheduled_tokens, dtype=np.int32),
max_query_len=None,
seq_lens_cpu_upper_bound=seq_lens,
is_prefilling_np=np.array(is_prefilling),
prefill_runs_as_decode_np=None,
num_draft_tokens_per_req=None
if num_draft_tokens_per_req is None
else np.array(num_draft_tokens_per_req, dtype=np.int32),
idx_mapping=torch.arange(num_reqs),
query_start_loc=torch.from_numpy(query_start_loc),
seq_lens=seq_lens,
dcp_local_seq_lens=None,
positions=torch.zeros(num_tokens, dtype=torch.int64),
prompt_lens=None,
)
def _prepare_attn_metadata(
state: MambaHybridModelState,
monkeypatch,
input_batch: SimpleNamespace | None = None,
cudagraph_mode: CUDAGraphMode = CUDAGraphMode.NONE,
) -> SimpleNamespace:
captured = {}
def fake_build_attn_metadata(**kwargs):
captured.update(kwargs)
return Mock()
monkeypatch.setattr(
"vllm.v1.worker.gpu.model_states.mamba_hybrid.build_attn_metadata",
fake_build_attn_metadata,
)
if input_batch is None:
input_batch = _input_batch([1, 1], None, [False, False])
state.prepare_attn(
input_batch=input_batch,
cudagraph_mode=cudagraph_mode,
block_tables=(),
slot_mappings={},
attn_groups=[],
kv_cache_config=Mock(),
)
return captured["model_specific_attn_metadata"]
def test_prepare_attn_keeps_the_accepted_offset_when_the_batch_drafted_nothing(
monkeypatch,
):
"""`num_accepted_tokens` must reach the attention builders whenever the
speculative config is on, even when *this* batch scheduled no draft
tokens at all. Before the fix, `use_spec_decode` was gated on this step's
scheduled drafts (`len(scheduled_spec_decode_tokens) > 0` in the V1
runner) rather than on the speculative config, so a request that accepted
drafts on a previous step would silently lose that offset the moment
ngram found no match for anyone in the batch.
"""
state = _mamba_hybrid_state(num_speculative_tokens=3)
metadata = _prepare_attn_metadata(state, monkeypatch)
assert metadata.num_accepted_tokens is not None
assert metadata.num_accepted_tokens.tolist() == [4, 1]
assert metadata.num_decode_draft_tokens_cpu is not None
def test_prepare_attn_omits_the_offset_without_a_speculative_config(monkeypatch):
"""Mirrors the check above: with speculative decoding off entirely, there
is no accepted-token offset to carry, and the metadata must say so
explicitly (`None`) rather than a stale or default value."""
state = _mamba_hybrid_state(num_speculative_tokens=0)
metadata = _prepare_attn_metadata(state, monkeypatch)
assert metadata.num_accepted_tokens is None
assert metadata.num_decode_draft_tokens_cpu is None
def test_zero_draft_decode_row_is_marked_as_a_speculative_row(monkeypatch):
"""A decode row that got no drafts still has to reach the speculative path.
The recurrent backends only apply a row's accepted-token offset on that
path, and a row that accepted drafts on the previous step keeps that offset
even when the current step proposes nothing (the scheduler drops drafts
whenever the token budget truncates the step). Marking such a row with the
-1 sentinel sends it to the plain decode path, which reads the state at
column 0 and ignores the offset.
"""
state = _mamba_hybrid_state(num_speculative_tokens=3)
input_batch = _input_batch([3, 1, 1], [2, 0, 0], [False, False, True])
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
assert metadata.num_decode_draft_tokens_cpu.tolist() == [
2, # decode row with drafts
0, # decode row with no drafts: speculative path, offset applied
-1, # one-token prefill tail: no offset to apply, stays a plain row
]
def test_batch_without_any_drafts_still_marks_its_decode_rows(monkeypatch):
"""`num_draft_tokens_per_req` is None whenever no row in the batch drafted
anything. Those rows are ordinary decode rows carrying an offset from the
previous step, so the absence of drafts in this step must not be read as
speculative decoding being off."""
state = _mamba_hybrid_state(num_speculative_tokens=3)
input_batch = _input_batch([1, 1], None, [False, True])
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
assert metadata.num_decode_draft_tokens_cpu.tolist() == [0, -1]
def test_padded_rows_keep_the_sentinel(monkeypatch):
"""Full CUDA-graph capture pads the batch; padded rows describe no request
and must not be picked up as speculative rows."""
state = _mamba_hybrid_state(num_speculative_tokens=3)
input_batch = _input_batch([1, 1], [0, 0], [False, False], num_reqs_after_padding=4)
metadata = _prepare_attn_metadata(
state, monkeypatch, input_batch, cudagraph_mode=CUDAGraphMode.FULL
)
assert metadata.num_decode_draft_tokens_cpu.tolist() == [0, 0, -1, -1]
def test_chunked_prefill_tail_of_two_or_three_tokens_keeps_the_sentinel(
monkeypatch,
):
"""A prefill continuation is excluded by `is_prefilling`, not by its token
count, so tails wider than one token are covered by the same rule."""
state = _mamba_hybrid_state(num_speculative_tokens=3)
input_batch = _input_batch([2, 3], [0, 0], [True, True])
metadata = _prepare_attn_metadata(state, monkeypatch, input_batch)
assert metadata.num_decode_draft_tokens_cpu.tolist() == [-1, -1]
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA")
@pytest.mark.parametrize(("num_sampled", "expected_value"), [(0, 1), (3, 3)])
def test_postprocess_state_scalar_with_int32_mapping(
+46
View File
@@ -22,6 +22,7 @@ from vllm.v1.kv_cache_interface import (
MambaSpec,
UniformTypeKVCacheSpecs,
)
from vllm.v1.worker.gpu.block_table import BlockTables
from vllm.v1.worker.gpu.model_states.mamba_hybrid import MambaHybridModelState
from vllm.v1.worker.mamba_utils import (
MambaCopyBuffers,
@@ -638,6 +639,51 @@ def test_mamba_groups_support_mixed_specs_in_uniform_group():
assert ctx.state_conv_widths.tolist() == [4, 0, 4, 0, 12]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA")
def test_v2_align_ctx_binds_request_slot_tables_for_state_copies():
"""V2 state copies may run steps after their batch (PP), so they must read
the per-request-slot tables; aligned state indices are computed for the
current batch and keep reading the gathered tables."""
cfg = _TestConfig(num_layers=1)
device = torch.device("cuda")
kv_cache_config = _make_kv_cache_config(cfg, ["layer_0"])
forward_context = {
"layer_0": _make_mock_attention(
torch.empty(cfg.num_blocks, cfg.conv_width, cfg.conv_inner_dim),
torch.empty(cfg.num_blocks, cfg.temporal_state_dim),
)
}
block_tables = BlockTables(
block_sizes=[cfg.block_size],
max_num_reqs=cfg.max_num_reqs,
max_num_batched_tokens=64,
max_num_blocks_per_group=[4],
device=device,
kernel_block_sizes=[cfg.block_size],
)
state = object.__new__(MambaHybridModelState)
state._align_mode = True
state._mamba_group_ids = []
state._mamba_spec = None
state._mamba_state_copy_funcs = _COPY_FUNCS
state.max_num_reqs = cfg.max_num_reqs
state.device = device
state.vllm_config = MagicMock()
state.vllm_config.compilation_config.static_forward_context = forward_context
state.initialize_kv_cache(kv_cache_config, block_tables)
ctx = state._mamba_ctx
assert ctx is not None and ctx.is_initialized
assert ctx.block_table_ptrs.tolist() == [
block_tables.block_tables[0].gpu.data_ptr()
]
assert ctx.aligned_index_block_table_ptrs.tolist() == [
block_tables.input_block_tables[0].data_ptr()
]
# -----------------------------------------------------------------------------
# stage_postprocess_inputs_to_gpu: single-pass staging into pinned views
# -----------------------------------------------------------------------------
+35
View File
@@ -6,6 +6,7 @@ from types import SimpleNamespace
import pytest
from vllm.v1.core.sched.output import SchedulerOutput
from vllm.v1.worker.gpu import warmup
from vllm.v1.worker.gpu.warmup import run_mixed_prefill_decode_warmup
@@ -31,6 +32,40 @@ def test_mixed_warmup_skipped_for_single_seq(max_num_reqs):
)
def test_mixed_warmup_disables_watermarking():
outputs: list[SchedulerOutput] = []
runner = SimpleNamespace(
is_pooling_model=False,
max_num_reqs=2,
kv_cache_config=SimpleNamespace(
kv_cache_groups=[
SimpleNamespace(kv_cache_spec=SimpleNamespace(block_size=16))
],
num_blocks=128,
),
vllm_config=SimpleNamespace(num_lookahead_tokens=0),
max_model_len=128,
num_speculative_steps=0,
model_state=SimpleNamespace(max_encoder_len=0),
kv_connector=SimpleNamespace(set_disabled=lambda disabled: None),
)
assert run_mixed_prefill_decode_warmup(
runner,
worker_execute_model=outputs.append,
worker_sample_tokens=lambda grammar_output: None,
num_tokens=32,
)
sampling_params = [
request.sampling_params
for output in outputs
for request in output.scheduled_new_reqs
]
assert len(sampling_params) == 2
assert all(params.watermarking is False for params in sampling_params)
@pytest.mark.parametrize("fail_warmup", [False, True])
def test_kernel_warmup_restores_uncalibrated_adaptive_manager(monkeypatch, fail_warmup):
"""Startup must warm fixed drafts before calibration and retain its manager."""
+2
View File
@@ -92,6 +92,8 @@ def test_hisparse_worker_get_kv_connector_stats_reads_completed_snapshot(monkeyp
"cache_hits": [12],
"cache_misses": [4],
"host_to_device_bytes": [64],
"host_cache_usage_perc": [],
"pending_page_transfers": [],
}