[Mini-vLLM] SM86-only cut: models, backends, Rust, tests

- Keep only Qwen3.5, Qwen3.5-MTP and Qwen4Exp model paths; trim the model registry to 41 entries
- Delete idle attention backends (MLA, FlashInfer, ROCm-only, quant backends) and dead GDN CuTeDSL kernels
- Remove inc/quark quant loaders; keep compressed-tensors and Marlin
- Drop the Rust frontend, pooling entrypoints, and idle test suites
- Rebuild kernels for sm_80;sm_86 and strip the extensions
- Verified: full import sweep clean (optional deps only) and a dummy-load Qwen3.5 engine run on RTX 3090 via the Triton GDN path

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-18 19:19:56 +07:00
co-authored by Hinata
parent c5ab42bc0f
commit e61dcb9143
2728 changed files with 159 additions and 950401 deletions
@@ -1,104 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Differential test for the AITER MLA uniform-MTP padding decision.
`_uniform_padded_mtp_qo_len` decides whether a full-CUDA-graph decode batch may
synthesize dummy query rows. It used to reach that decision through eight tensor
dispatches -- sum/item, boolean-mask index, all, eq, nonzero, item, any -- on a
CPU tensor holding one entry per request. It now reads the tensor out once and
decides on Python ints.
That rewrite also **reordered** the checks: the `num_decode_tokens <= sum(...)`
early-out moved below the divisibility and `uniform_qo_len <= 1` guards. Every
one of those paths returns 0, so the result should be unchanged -- but "should
be" is exactly the sort of claim worth checking exhaustively, so both
implementations are carried here and compared over the whole small input space.
Pure host arithmetic; no GPU required.
"""
import itertools
import pytest
import torch
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
def _reference(qo_len: torch.Tensor, max_qo_len: int, num_decode_tokens: int) -> int:
"""The pre-#58381 implementation, verbatim."""
num_reqs = qo_len.numel()
if num_reqs == 0 or num_decode_tokens <= 0:
return 0
if num_decode_tokens <= int(qo_len.sum().item()):
return 0
if num_decode_tokens % num_reqs != 0:
return 0
uniform_qo_len = num_decode_tokens // num_reqs
if uniform_qo_len <= 1:
return 0
positive_qo_len = qo_len[qo_len > 0]
if positive_qo_len.numel() == qo_len.numel():
return 0
if positive_qo_len.numel() > 0:
if max_qo_len != uniform_qo_len:
return 0
if not torch.all(positive_qo_len == uniform_qo_len):
return 0
zero_positions = torch.nonzero(qo_len == 0, as_tuple=False).flatten()
if zero_positions.numel() > 0:
first_zero = int(zero_positions[0].item())
if torch.any(qo_len[first_zero:] > 0):
return 0
return uniform_qo_len
_ACTUAL = AiterMLAMetadataBuilder._uniform_padded_mtp_qo_len
@pytest.mark.parametrize("num_reqs", [1, 2, 3, 4])
def test_matches_reference_exhaustively(num_reqs):
"""Every qo_len vector x decode-token count x max_qo_len in a small space."""
checked = 0
for lens in itertools.product(range(0, 4), repeat=num_reqs):
qo = torch.tensor(lens, dtype=torch.int32)
for num_decode_tokens in range(0, 13):
for max_qo_len in range(0, 5):
got = _ACTUAL(qo, max_qo_len, num_decode_tokens)
want = _reference(qo, max_qo_len, num_decode_tokens)
assert got == want, (
f"lens={lens} num_decode_tokens={num_decode_tokens} "
f"max_qo_len={max_qo_len}: got {got}, reference {want}"
)
checked += 1
assert checked > 0
def test_empty_batch():
assert _ACTUAL(torch.zeros(0, dtype=torch.int32), 4, 8) == 0
assert _reference(torch.zeros(0, dtype=torch.int32), 4, 8) == 0
def test_the_padded_mtp_case_that_should_succeed():
"""A live prefix at the uniform width, then zero-padded dummies."""
qo = torch.tensor([4, 4, 0, 0], dtype=torch.int32)
# 4 requests x 4 tokens = 16 captured, 8 live -> dummies are synthesizable.
assert _ACTUAL(qo, 4, 16) == 4
assert _reference(qo, 4, 16) == 4
def test_positive_after_zero_is_rejected():
"""A live request after a padding hole breaks the contiguous-prefix layout."""
qo = torch.tensor([4, 0, 4, 0], dtype=torch.int32)
assert _ACTUAL(qo, 4, 16) == 0
assert _reference(qo, 4, 16) == 0
def test_ragged_live_lengths_are_rejected():
qo = torch.tensor([4, 2, 0, 0], dtype=torch.int32)
assert _ACTUAL(qo, 4, 16) == 0
assert _reference(qo, 4, 16) == 0
File diff suppressed because it is too large Load Diff
@@ -1,195 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for mamba attention backend selectors."""
from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.layers.mamba.abstract import MambaBase
from vllm.model_executor.layers.mamba.linear.minimax_linear_attn import (
MiniMaxText01LinearAttention,
)
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
from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
from vllm.v1.attention.backends.short_conv_attn import ShortConvAttentionBackend
@pytest.mark.parametrize(("use_replayssm", "expected_blocks"), [(False, 3), (True, 0)])
def test_replayssm_does_not_reserve_speculative_state_blocks(
use_replayssm, expected_blocks
):
layer = SimpleNamespace(
get_state_shape=lambda: ((2,),),
get_state_dtype=lambda: (torch.float32,),
mamba_type=MambaAttentionBackendEnum.MAMBA2,
is_kv_cache_tp_replicated=False,
)
vllm_config = SimpleNamespace(
cache_config=SimpleNamespace(
mamba_block_size=1,
mamba_page_size_padded=None,
mamba_cache_mode="none",
use_replayssm=use_replayssm,
),
num_speculative_tokens=3,
)
spec = MambaBase.get_kv_cache_spec(layer, vllm_config)
assert spec is not None
assert spec.num_speculative_blocks == expected_blocks
@pytest.mark.parametrize(
"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",
[
(
MambaMixer,
dict(
hidden_size=128,
ssm_state_size=16,
conv_kernel_size=4,
intermediate_size=256,
time_step_rank=8,
use_conv_bias=True,
use_bias=False,
use_rms_norm=True,
),
Mamba1AttentionBackend,
MambaAttentionBackendEnum.MAMBA1,
),
(
MambaMixer2,
dict(
hidden_size=128,
ssm_state_size=16,
conv_kernel_size=4,
intermediate_size=256,
use_conv_bias=True,
use_bias=False,
n_groups=1,
num_heads=8,
head_dim=32,
),
Mamba2AttentionBackend,
MambaAttentionBackendEnum.MAMBA2,
),
(
MiniMaxText01LinearAttention,
dict(
config=SimpleNamespace(
hidden_size=256,
num_attention_heads=8,
head_dim=32,
num_hidden_layers=12,
block=64,
),
prefix="layers.0.self_attn",
),
LinearAttentionBackend,
MambaAttentionBackendEnum.LINEAR,
),
(
ShortConv,
dict(
config=SimpleNamespace(conv_L_cache=32, conv_bias=True),
dim=128,
layer_idx=0,
),
ShortConvAttentionBackend,
MambaAttentionBackendEnum.SHORT_CONV,
),
],
)
def test_mamba_layers_get_attn_backend(
default_vllm_config,
dist_init,
layer_class,
init_kwargs,
expected_backend,
expected_mamba_type,
):
"""Test that Mamba-like layers return the correct attention backend."""
if layer_class is MiniMaxText01LinearAttention:
init_kwargs["vllm_config"] = default_vllm_config
layer = layer_class(**init_kwargs)
backend_class = layer.get_attn_backend()
assert backend_class is expected_backend
assert layer.mamba_type == expected_mamba_type
@pytest.mark.parametrize(
"layer_class,expected_backend,expected_mamba_type",
[
(MambaMixer, Mamba1AttentionBackend, MambaAttentionBackendEnum.MAMBA1),
(MambaMixer2, Mamba2AttentionBackend, MambaAttentionBackendEnum.MAMBA2),
(
MiniMaxText01LinearAttention,
LinearAttentionBackend,
MambaAttentionBackendEnum.LINEAR,
),
(ShortConv, ShortConvAttentionBackend, MambaAttentionBackendEnum.SHORT_CONV),
],
)
def test_mamba_layers_have_unified_interface(
layer_class, expected_backend, expected_mamba_type
):
"""Test that all Mamba layers have the unified get_attn_backend
interface."""
assert hasattr(layer_class, "get_attn_backend"), (
f"{layer_class.__name__} should have get_attn_backend method"
)
assert hasattr(layer_class, "mamba_type"), (
f"{layer_class.__name__} should have mamba_type property"
)
-360
View File
@@ -1,360 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from functools import partial
from types import SimpleNamespace
import pytest
import torch
from tests.v1.attention.test_attention_backends import (
BATCH_SPECS,
_test_backend_correctness,
)
from tests.v1.attention.utils import BatchSpec
from vllm.config import ModelConfig
from vllm.platforms import current_platform
from vllm.platforms.interface import DeviceCapability
from vllm.utils.b12x import get_b12x_paged_attention
from vllm.v1.attention.backends import b12x
from vllm.v1.attention.backends.b12x import (
B12xPagedAttentionBackend,
B12xPagedAttentionImpl,
_kv_page_size,
_max_page_table_width,
)
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheLayout
def _require_b12x_paged_attention() -> None:
capability = current_platform.get_device_capability()
if (
not current_platform.is_cuda()
or capability is None
or not B12xPagedAttentionBackend.supports_compute_capability(capability)
):
pytest.skip("b12x paged attention requires SM120 or SM121.")
paged_attention = get_b12x_paged_attention()
if paged_attention is None or not paged_attention.is_supported():
pytest.skip("b12x paged attention is not available.")
def _causal_mask(
b: torch.Tensor,
h: torch.Tensor,
q_idx: torch.Tensor,
kv_idx: torch.Tensor,
*,
context_len: int,
):
return q_idx + context_len >= kv_idx
def _causal_sliding_window_mask(
b: torch.Tensor,
h: torch.Tensor,
q_idx: torch.Tensor,
kv_idx: torch.Tensor,
*,
context_len: int,
sliding_window: int,
):
causal_mask = q_idx + context_len >= kv_idx
window_mask = q_idx + context_len - kv_idx < sliding_window
return causal_mask & window_mask
@pytest.mark.parametrize(
("dtype", "kv_cache_dtype", "paged_attention", "expected_reason"),
[
pytest.param(
torch.float16,
"fp8_e4m3",
None,
"b12x currently requires bfloat16 queries",
id="query-dtype",
),
pytest.param(
torch.bfloat16,
"float16",
None,
"b12x does not support float16 KV cache",
id="kv-cache-dtype",
),
pytest.param(
torch.bfloat16,
"auto",
None,
"Install the b12x backend with `pip install vllm[b12x]`",
id="package-not-installed",
),
pytest.param(
torch.bfloat16,
"auto",
SimpleNamespace(is_supported=lambda: False),
"b12x paged attention is not supported on the current device",
id="device-api",
),
pytest.param(
torch.bfloat16,
"auto",
SimpleNamespace(is_supported=lambda: True),
None,
id="supported",
),
],
)
def test_b12x_attention_config_support(
monkeypatch: pytest.MonkeyPatch,
dtype: torch.dtype,
kv_cache_dtype: str,
paged_attention,
expected_reason: str | None,
) -> None:
monkeypatch.setattr(
b12x,
"get_b12x_paged_attention",
lambda: paged_attention,
)
reason = B12xPagedAttentionBackend.supports_combination(
head_size=128,
dtype=dtype,
kv_cache_dtype=kv_cache_dtype,
block_size=128,
use_mla=False,
has_sink=False,
use_sparse=False,
use_mm_prefix=False,
device_capability=DeviceCapability(12, 0),
)
assert reason == expected_reason
def test_b12x_attention_uses_two_plane_nhd_cache() -> None:
spec = B12xPagedAttentionBackend.customize_spec(
FullAttentionSpec(
block_size=128,
num_kv_heads=4,
head_size=128,
dtype=torch.bfloat16,
)
)
assert spec.num_head_slots == 2
assert spec.state_content_bytes == 4 * 128 * 2
assert B12xPagedAttentionBackend.supported_kv_cache_layouts() == (
KVCacheLayout.LBHNC,
KVCacheLayout.BLHNC,
)
assert B12xPagedAttentionBackend.supports_block_size(128)
assert not B12xPagedAttentionBackend.supports_block_size(32)
def test_b12x_attention_hybrid_cache_capacity_includes_expansion() -> None:
assert _max_page_table_width(4096, 128, 4096, False) == 32
assert _max_page_table_width(4096, 128, 4096, True) == 64
def test_b12x_attention_runtime_page_size_comes_from_cache() -> None:
key_cache = torch.empty((3, 64, 4, 128), device="meta")
value_cache = torch.empty_like(key_cache)
assert _kv_page_size(key_cache, value_cache) == 64
with pytest.raises(ValueError, match="matching K/V page sizes"):
_kv_page_size(key_cache, torch.empty((3, 128, 4, 128), device="meta"))
def test_b12x_attention_lazily_prepares_decode_bucket(monkeypatch) -> None:
impl = object.__new__(B12xPagedAttentionImpl)
plan = SimpleNamespace(layout=SimpleNamespace(nbytes=96))
created: list[tuple[int, int]] = []
def create_plan(page_size: int, batch_size: int) -> SimpleNamespace:
created.append((page_size, batch_size))
return plan
impl._decode_plans = {}
impl._create_decode_plan = create_plan
impl._scratch_nbytes = 128
impl._extend_plans = {}
impl._verify_q_per_req = 0
metadata = SimpleNamespace(max_query_len=1)
monkeypatch.setattr(b12x, "_capture_alloc_forbidden", lambda: False)
assert impl._select_plan(metadata, 7, 7, 7, 64) is plan
assert impl._select_plan(metadata, 7, 7, 7, 64) is plan
assert created == [(64, 7)]
def test_b12x_attention_fp8_descales_follow_request_batch() -> None:
impl = object.__new__(B12xPagedAttentionImpl)
impl.kv_cache_dtype = "fp8_e4m3"
layer = SimpleNamespace(
_k_scale=torch.tensor(2.0),
_v_scale=torch.tensor([3.0, 4.0, 5.0]),
)
k_descale, v_descale = impl._prepare_fp8_descales(
layer, num_reqs=2, device=torch.device("cpu")
)
torch.testing.assert_close(k_descale, torch.tensor([2.0, 2.0]))
torch.testing.assert_close(v_descale, torch.tensor([3.0, 4.0]))
assert k_descale.stride() == (0,)
assert v_descale.stride() == (1,)
def test_b12x_attention_sinks_refresh_in_place_after_reload() -> None:
impl = object.__new__(B12xPagedAttentionImpl)
source = torch.tensor([1.0, 2.0], dtype=torch.bfloat16)
impl._sinks_source = source
impl.sinks = None
impl.process_weights_after_loading(torch.bfloat16)
assert impl.sinks is not None
sinks_ptr = impl.sinks.data_ptr()
source.copy_(torch.tensor([3.0, 4.0], dtype=torch.bfloat16))
impl.process_weights_after_loading(torch.bfloat16)
assert impl.sinks.data_ptr() == sinks_ptr
torch.testing.assert_close(impl.sinks, source.float())
@pytest.mark.parametrize(
"batch_spec_name",
["small_decode", "small_prefill", "mixed_small", "medium_decode"],
)
@pytest.mark.parametrize(
("kv_cache_dtype", "model_dtype"),
[
("auto", None),
("bfloat16", torch.bfloat16),
("fp8_e4m3", torch.bfloat16),
],
)
@pytest.mark.parametrize("block_size", [64, 128])
def test_b12x_causal_backend_correctness(
default_vllm_config,
workspace_init,
batch_spec_name: str,
kv_cache_dtype: str,
model_dtype: torch.dtype | None,
block_size: int,
) -> None:
"""b12x causal paged attention matches the shared SDPA reference."""
_require_b12x_paged_attention()
batch_spec = BATCH_SPECS[batch_spec_name]
_test_backend_correctness(
batch_spec,
"Qwen/Qwen3-0.6B",
[AttentionBackendEnum.B12X],
_causal_mask,
block_size=block_size,
kv_cache_dtype=kv_cache_dtype,
model_dtype=model_dtype,
max_num_seqs=batch_spec.batch_size,
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
)
@pytest.mark.parametrize(
"batch_spec",
[
pytest.param(BatchSpec(seq_lens=[2080, 2200], query_lens=[1, 1]), id="decode"),
pytest.param(BatchSpec(seq_lens=[2080, 2200], query_lens=[8, 8]), id="prefill"),
],
)
def test_b12x_causal_sliding_window(
default_vllm_config,
workspace_init,
batch_spec: BatchSpec,
) -> None:
"""b12x causal sliding-window attention matches the shared reference."""
_require_b12x_paged_attention()
model = "microsoft/Phi-tiny-MoE-instruct"
sliding_window = ModelConfig(
model=model, max_model_len=max(batch_spec.seq_lens)
).get_sliding_window()
assert sliding_window is not None
mask = partial(_causal_sliding_window_mask, sliding_window=sliding_window)
_test_backend_correctness(
batch_spec,
model,
[AttentionBackendEnum.B12X],
mask,
block_size=64,
atol=3e-2,
rtol=3e-2,
max_num_seqs=batch_spec.batch_size,
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
)
def test_b12x_attention_sinks(
default_vllm_config,
workspace_init,
) -> None:
"""b12x attention sinks match the explicit sink reference."""
_require_b12x_paged_attention()
batch_spec = BATCH_SPECS["small_prefill"]
_test_backend_correctness(
batch_spec,
"Qwen/Qwen3-0.6B",
[AttentionBackendEnum.B12X],
_causal_mask,
block_size=64,
atol=3e-2,
rtol=3e-2,
use_sinks=True,
max_num_seqs=batch_spec.batch_size,
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
)
def test_b12x_decode_cuda_graph_replay(
default_vllm_config,
workspace_init,
) -> None:
"""b12x decode output remains correct after CUDA graph replay."""
_require_b12x_paged_attention()
batch_spec = BATCH_SPECS["small_decode"]
_test_backend_correctness(
batch_spec,
"Qwen/Qwen3-0.6B",
[AttentionBackendEnum.B12X],
_causal_mask,
block_size=64,
use_cuda_graph=True,
max_num_seqs=batch_spec.batch_size,
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
)
def test_b12x_speculative_verification_uses_cuda_graph_plan(
default_vllm_config,
workspace_init,
) -> None:
"""Exercise the verifier plan rather than the general extend plan."""
_require_b12x_paged_attention()
batch_spec = BatchSpec(seq_lens=[32, 40], query_lens=[4, 4])
_test_backend_correctness(
batch_spec,
"Qwen/Qwen3-0.6B",
[AttentionBackendEnum.B12X],
_causal_mask,
block_size=128,
num_speculative_tokens=3,
use_cuda_graph=True,
max_num_seqs=batch_spec.batch_size,
max_num_batched_tokens=max(sum(batch_spec.query_lens), 64),
)
-140
View File
@@ -1,140 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for attention configuration and per-KV-group backend selection."""
from types import SimpleNamespace
import pytest
from vllm.config.attention import AttentionConfig, HiSparseConfig
from vllm.model_executor.layers.attention.attention import (
_largest_kernel_block_within,
)
from vllm.v1.attention.backend import AttentionType, MultipleOf
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.attention.selector import get_attn_spec_kind
from vllm.v1.hisparse.runtime import ResolvedHiSparseConfig
from vllm.v1.kv_cache_interface import KVCacheSpecKind
@pytest.mark.parametrize(
"supported_sizes,expected",
[
([MultipleOf(16)], 1536),
([16, 32], 32),
([2048], 2048),
([MultipleOf(2048)], 2048),
],
)
def test_largest_kernel_block_within(supported_sizes, expected):
class Backend:
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None):
return supported_sizes
assert _largest_kernel_block_within(Backend, 1024, 1024 * 1536, 2048) == expected
@pytest.mark.parametrize(
"signals,expected",
[
(dict(use_mla=False, has_sliding_window=False), "full"),
(dict(use_mla=True, has_sliding_window=False), "mla"),
(dict(use_mla=True, has_sliding_window=True), "sw_mla"),
(dict(use_mla=False, has_sliding_window=True), "sw"),
],
)
def test_get_attn_spec_kind_decoder(signals, expected):
kind_by_name = {
"full": KVCacheSpecKind.FULL_ATTENTION,
"mla": KVCacheSpecKind.MLA_ATTENTION,
"sw_mla": KVCacheSpecKind.SLIDING_WINDOW_MLA,
"sw": KVCacheSpecKind.SLIDING_WINDOW,
}
kind = get_attn_spec_kind(attn_type=AttentionType.DECODER, **signals)
assert kind is kind_by_name[expected]
@pytest.mark.parametrize(
"attn_type,expected",
[
(AttentionType.ENCODER_ONLY, KVCacheSpecKind.ENCODER_ONLY_ATTENTION),
(AttentionType.ENCODER_DECODER, KVCacheSpecKind.CROSS_ATTENTION),
],
)
def test_get_attn_spec_kind_attn_type(attn_type, expected):
kind = get_attn_spec_kind(
use_mla=False,
has_sliding_window=False,
attn_type=attn_type,
)
assert kind is expected
def test_backend_per_kind_parses_strings():
cfg = AttentionConfig(
backend_per_kind={
"mla_attention": "FLASHINFER_MLA",
"sliding_window_mla": "triton_mla", # case-insensitive
}
)
assert cfg.backend_per_kind["mla_attention"] is AttentionBackendEnum.FLASHINFER_MLA
assert cfg.backend_per_kind["sliding_window_mla"] is AttentionBackendEnum.TRITON_MLA
def test_backend_per_kind_rejects_unknown_kind():
with pytest.raises(ValueError, match="Unknown KV cache group kind"):
AttentionConfig(backend_per_kind={"not_a_kind": "TRITON_MLA"})
def test_backend_per_kind_defaults_empty():
assert AttentionConfig().backend_per_kind == {}
def test_hisparse_device_buffer_size_boundaries():
vllm_config = SimpleNamespace(
attention_config=AttentionConfig(hisparse_config=HiSparseConfig()),
speculative_config=None,
)
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
assert resolved is not None
assert resolved.device_buffer_size == 256
vllm_config.attention_config.hisparse_config = HiSparseConfig(
device_buffer_size=127
)
with pytest.raises(ValueError, match="expected at least 128"):
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
vllm_config.attention_config.hisparse_config = HiSparseConfig(
device_buffer_size=32768
)
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
assert resolved is not None
assert resolved.device_buffer_size == 32768
vllm_config.attention_config.hisparse_config = HiSparseConfig(
device_buffer_size=32769
)
with pytest.raises(ValueError, match="int16 slot-index limit"):
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
def test_hisparse_device_buffer_covers_speculative_window():
vllm_config = SimpleNamespace(
attention_config=AttentionConfig(hisparse_config=HiSparseConfig()),
speculative_config=SimpleNamespace(
num_speculative_tokens=3,
parallel_drafting=False,
),
)
resolved = ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
assert resolved is not None
assert resolved.device_buffer_size == 5 * 128
vllm_config.attention_config.hisparse_config = HiSparseConfig(
device_buffer_size=4 * 128 - 1
)
with pytest.raises(ValueError, match="expected at least 512"):
ResolvedHiSparseConfig.from_vllm_config(vllm_config, model_top_k=128)
-316
View File
@@ -1,316 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Smoke tests for the CPU MLA backend.
Two levels of coverage are provided:
* :func:`test_kv_cache_cpu_write` checks that the kv-cache write logic
inlined in the CPU MLA backend writes the latent KV cache in the same
layout the CPU decode kernel expects. This runs without downloading
any model weights and is safe for CI.
* :func:`test_cpu_mla_backend_smoke` exercises the full end-to-end path
(LLM engine, model construction, prefill + decode) against a shrunk
DeepSeek-V2-Lite with `hf_overrides`. It uses `dummy` weights so the
outputs are not meaningful, only shape / plumbing correctness is
asserted. Marked `cpu_model` so it is skipped on non-CPU CI.
"""
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.attention.backends.mla.prefill.cpu_sdpa import (
CPUSDPAMLAPrefillBackend,
)
from vllm.v1.attention.backends.mla.prefill.selector import (
get_mla_prefill_backend,
)
from vllm.v1.attention.backends.mla.prefill.zen_cpu_sdpa import (
ZenCPUSDPAMLAPrefillBackend,
)
def _reference_ragged_attention(
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
q_cu_seq_lens: torch.Tensor,
kv_cu_seq_lens: torch.Tensor,
*,
scale: float,
causal: bool,
) -> tuple[torch.Tensor, torch.Tensor]:
outputs: list[torch.Tensor] = []
lses: list[torch.Tensor] = []
num_reqs = q_cu_seq_lens.numel() - 1
for req_idx in range(num_reqs):
q_start = int(q_cu_seq_lens[req_idx])
q_end = int(q_cu_seq_lens[req_idx + 1])
kv_start = int(kv_cu_seq_lens[req_idx])
kv_end = int(kv_cu_seq_lens[req_idx + 1])
q_r = q[q_start:q_end].transpose(0, 1).float()
k_r = k[kv_start:kv_end].transpose(0, 1).float()
v_r = v[kv_start:kv_end].transpose(0, 1).float()
scores = torch.matmul(q_r, k_r.transpose(-2, -1)) * scale
if causal:
causal_mask = torch.ones(
(q_end - q_start, kv_end - kv_start),
dtype=torch.bool,
device=scores.device,
).triu(1)
scores.masked_fill_(causal_mask.unsqueeze(0), float("-inf"))
probs = torch.softmax(scores, dim=-1)
outputs.append(torch.matmul(probs, v_r).transpose(0, 1).to(v.dtype))
lses.append(torch.logsumexp(scores, dim=-1))
return torch.cat(outputs, dim=0), torch.cat(lses, dim=1)
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
def test_kv_cache_cpu_write() -> None:
kv_lora_rank = 512
pe_dim = 64
block_size = 16
num_blocks = 4
num_tokens = 8
dtype = torch.float32
kv_c = torch.randn(num_tokens, kv_lora_rank, dtype=dtype)
k_pe = torch.randn(num_tokens, pe_dim, dtype=dtype)
kv_cache = torch.zeros(num_blocks, block_size, kv_lora_rank + pe_dim, dtype=dtype)
slot_mapping = torch.arange(num_tokens, dtype=torch.long)
# Mark the last slot as padding to make sure we honour negative slots.
slot_mapping[-1] = -1
flat = kv_cache.view(-1, kv_lora_rank + pe_dim)
slots = slot_mapping.to(torch.long)
valid_mask = slots >= 0
if not valid_mask.all().item():
slots = slots[valid_mask]
kv_c = kv_c[valid_mask]
k_pe = k_pe[valid_mask]
target_dtype = flat.dtype
flat[slots, :kv_lora_rank] = kv_c.to(target_dtype)
flat[slots, kv_lora_rank:] = k_pe.to(target_dtype)
flat = kv_cache.view(-1, kv_lora_rank + pe_dim)
for i in range(num_tokens - 1):
assert torch.equal(flat[i, :kv_lora_rank], kv_c[i])
assert torch.equal(flat[i, kv_lora_rank:], k_pe[i])
# The padding slot must remain untouched.
assert torch.all(flat[num_tokens - 1] == 0)
@pytest.mark.cpu_model
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
def test_cpu_mla_backend_smoke(tmp_path) -> None:
# Shrink the architecture aggressively so the test is CI-friendly.
from vllm import LLM, SamplingParams
hf_overrides = {
"num_hidden_layers": 2,
"n_routed_experts": 4,
"first_k_dense_replace": 0,
"num_experts_per_tok": 2,
}
llm = LLM(
model="deepseek-ai/DeepSeek-V2-Lite",
skip_tokenizer_init=True,
trust_remote_code=True,
load_format="dummy",
enforce_eager=True,
max_model_len=128,
max_num_seqs=2,
block_size=16,
gpu_memory_utilization=0.25,
hf_overrides=hf_overrides,
kv_transfer_config={
"kv_connector": "ExampleConnector",
"kv_role": "kv_both",
"kv_connector_extra_config": {
"shared_storage_path": str(tmp_path),
},
},
)
sampling_params = SamplingParams(max_tokens=4, temperature=0.0)
outputs = llm.generate([[1, 2, 3, 4], [5, 6, 7]], sampling_params, use_tqdm=False)
assert len(outputs) == 2
for output in outputs:
# `dummy` weights do not produce meaningful text, but the number
# of generated tokens must match what we asked for.
assert len(output.outputs[0].token_ids) == 4
prefix_hit_prompt = [1] * 20
outputs = llm.generate([prefix_hit_prompt], sampling_params, use_tqdm=False)
assert len(outputs[0].outputs[0].token_ids) == 4
assert llm.reset_prefix_cache(reset_connector=False)
# ExampleConnector persists KV externally at block granularity. With a
# 20-token prompt and block_size=16, the second run reloads 16 cached
# tokens and forces the 4-token suffix through MLA prefill with context.
outputs = llm.generate([prefix_hit_prompt], sampling_params, use_tqdm=False)
assert len(outputs[0].outputs[0].token_ids) == 4
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
def test_cpu_mla_prefill_backend_selected() -> None:
# On CPU (no device capability) the MLA prefill backend must be the
# SDPA-based CPU backend, not flash-attn which is unavailable on CPU.
# Accelerator-specific subclasses (e.g. the zentorch-backed Zen CPU
# backend) are also valid selections.
backend_cls = get_mla_prefill_backend(None)
assert issubclass(backend_cls, CPUSDPAMLAPrefillBackend)
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
def test_cpu_mla_prefill_new_tokens() -> None:
# The SDPA prefill must exactly match a reference causal attention over
# the ragged (varlen) q/k/v layout, with per-request padding handled.
backend = CPUSDPAMLAPrefillBackend(
num_heads=4,
scale=0.25,
kv_lora_rank=16,
qk_nope_head_dim=16,
qk_rope_head_dim=0,
v_head_dim=16,
vllm_config=None,
)
class _PrefillMeta:
query_start_loc = torch.tensor([0, 3, 6], dtype=torch.int32)
backend.prepare_metadata(_PrefillMeta())
q = torch.randn(6, 4, 16, dtype=torch.bfloat16)
k = torch.randn(6, 4, 16, dtype=torch.bfloat16)
v = torch.randn(6, 4, 16, dtype=torch.bfloat16)
out = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=False)
ref, _ = _reference_ragged_attention(
q,
k,
v,
_PrefillMeta.query_start_loc,
_PrefillMeta.query_start_loc,
scale=0.25,
causal=True,
)
assert out.float().allclose(ref.float(), atol=2e-2)
assert out.shape == (6, 4, 16)
out_lse, lse = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
ref_out, ref_lse = _reference_ragged_attention(
q,
k,
v,
_PrefillMeta.query_start_loc,
_PrefillMeta.query_start_loc,
scale=0.25,
causal=True,
)
assert out_lse.float().allclose(ref_out.float(), atol=2e-2)
assert lse.float().allclose(ref_lse.float(), atol=2e-2)
assert lse.shape == (4, 6)
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
def test_cpu_mla_prefill_context_chunk() -> None:
backend = CPUSDPAMLAPrefillBackend(
num_heads=4,
scale=0.25,
kv_lora_rank=16,
qk_nope_head_dim=16,
qk_rope_head_dim=0,
v_head_dim=16,
vllm_config=None,
)
class _PrefillMeta:
query_start_loc = torch.tensor([0, 5], dtype=torch.int32)
class _Chunk:
query_start_loc = torch.tensor([0, 2, 5], dtype=torch.int32)
cu_seq_lens = torch.tensor([0, 3, 7], dtype=torch.int32)
backend.prepare_metadata(_PrefillMeta())
q = torch.randn(5, 4, 16, dtype=torch.bfloat16)
k = torch.randn(7, 4, 16, dtype=torch.bfloat16)
v = torch.randn(7, 4, 16, dtype=torch.bfloat16)
out, lse = backend.run_prefill_context_chunk(_Chunk(), q, k, v)
ref_out, ref_lse = _reference_ragged_attention(
q,
k,
v,
_Chunk.query_start_loc,
_Chunk.cu_seq_lens,
scale=0.25,
causal=False,
)
assert out.float().allclose(ref_out.float(), atol=2e-2)
assert lse.float().allclose(ref_lse.float(), atol=2e-2)
assert out.shape == (5, 4, 16)
assert lse.shape == (4, 5)
@pytest.mark.skipif(not current_platform.is_cpu(), reason="CPU only")
@pytest.mark.skipif(
not ZenCPUSDPAMLAPrefillBackend.is_available(),
reason="requires a Zen CPU with the zentorch_sdpa op registered",
)
def test_zen_cpu_mla_prefill_new_tokens() -> None:
# Runs the zentorch kernel itself. The head dims are deliberately
# asymmetric (v_head_dim < qk_head_dim, as in real MLA) so that the V
# padding and output slicing are exercised; the generic-CPU cases above
# use equal dims and never reach that code.
qk_head_dim = 24
v_head_dim = 16
backend = ZenCPUSDPAMLAPrefillBackend(
num_heads=4,
scale=0.25,
kv_lora_rank=16,
qk_nope_head_dim=16,
qk_rope_head_dim=8,
v_head_dim=v_head_dim,
vllm_config=None,
)
class _PrefillMeta:
query_start_loc = torch.tensor([0, 3, 6], dtype=torch.int32)
backend.prepare_metadata(_PrefillMeta())
q = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
k = torch.randn(6, 4, qk_head_dim, dtype=torch.bfloat16)
v = torch.randn(6, 4, v_head_dim, dtype=torch.bfloat16)
out = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=False)
ref, _ = _reference_ragged_attention(
q,
k,
v,
_PrefillMeta.query_start_loc,
_PrefillMeta.query_start_loc,
scale=0.25,
causal=True,
)
assert out.shape == (6, 4, v_head_dim)
assert out.float().allclose(ref.float(), atol=2e-2)
# zentorch_sdpa does not return a usable LSE, so that path must fall back
# to the fp32 reference and match the generic backend exactly.
generic = CPUSDPAMLAPrefillBackend(
num_heads=4,
scale=0.25,
kv_lora_rank=16,
qk_nope_head_dim=16,
qk_rope_head_dim=8,
v_head_dim=v_head_dim,
vllm_config=None,
)
generic.prepare_metadata(_PrefillMeta())
zen_out, zen_lse = backend.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
gen_out, gen_lse = generic.run_prefill_new_tokens(q, k, v, return_softmax_lse=True)
assert torch.equal(zen_out, gen_out)
assert torch.equal(zen_lse, gen_lse)
@@ -1,284 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.models.deepseek_v4.amd.rocm import (
DeepseekV4ROCMAiterMLASparseMetadataBuilder,
DeepseekV4ROCMAiterSparseSWAMetadataBuilder,
)
from vllm.models.deepseek_v41.amd import rocm as v41_rocm
from vllm.models.deepseek_v41.amd.rocm import (
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
)
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.attention.backends.mla import indexer
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV4IndexerBackend,
DeepseekV32IndexerMetadataBuilder,
DeepseekV41IndexerBackend,
)
def _make_indexer_config(*, architecture: str, adaptive: bool):
return SimpleNamespace(
model_config=SimpleNamespace(architectures=[architecture]),
num_speculative_tokens=1,
speculative_config=SimpleNamespace(enable_adaptive_verification=adaptive),
)
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.
monkeypatch.setattr(indexer.current_platform, "is_cuda", lambda: False)
monkeypatch.setattr(indexer.current_platform, "is_rocm", lambda: True)
def _make_indexer_builder(*, adaptive: bool, capacity: int = 12):
builder = DeepseekV32IndexerMetadataBuilder.__new__(
DeepseekV32IndexerMetadataBuilder
)
builder.vllm_config = SimpleNamespace(
speculative_config=SimpleNamespace(enable_adaptive_verification=adaptive)
)
builder.supports_varlen = False
builder.decode_seq_lens_buffer = torch.zeros(capacity, dtype=torch.int32)
builder.expanded_block_table_buffer = torch.zeros((capacity, 2), dtype=torch.int32)
builder.decode_lens_buffer = torch.zeros(capacity, dtype=torch.int32)
builder.arange_buffer = torch.arange(capacity, dtype=torch.int32)
return builder
@pytest.mark.cpu_test
def test_deepseek_rocm_adaptive_builders_support_varlen_full_graphs():
adaptive_config = SimpleNamespace(
speculative_config=SimpleNamespace(enable_adaptive_verification=True)
)
fixed_config = SimpleNamespace(
speculative_config=SimpleNamespace(enable_adaptive_verification=False)
)
for builder_cls in (
DeepseekV4ROCMAiterMLASparseMetadataBuilder,
DeepseekV4ROCMAiterSparseSWAMetadataBuilder,
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
v41_rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder,
):
assert (
builder_cls.get_cudagraph_support(adaptive_config, SimpleNamespace())
== AttentionCGSupport.ALWAYS
)
assert (
builder_cls.get_cudagraph_support(fixed_config, SimpleNamespace())
== AttentionCGSupport.UNIFORM_BATCH
)
@pytest.mark.cpu_test
@pytest.mark.parametrize(
("architecture", "backend_cls"),
[
("DeepseekV4ForCausalLM", DeepseekV4IndexerBackend),
("DeepseekV41ForCausalLM", DeepseekV41IndexerBackend),
],
)
def test_deepseek_rocm_adaptive_indexer_support(
monkeypatch: pytest.MonkeyPatch,
architecture: str,
backend_cls: type[DeepseekV4IndexerBackend],
):
_mock_rocm_platform(monkeypatch)
adaptive_config = _make_indexer_config(architecture=architecture, adaptive=True)
fixed_config = _make_indexer_config(architecture=architecture, adaptive=False)
assert backend_cls.supports_device_cpu_query_lens_mismatch()
assert indexer._rocm_supports_flattened_device_query_lens(adaptive_config)
assert backend_cls.get_builder_cls() is DeepseekV32IndexerMetadataBuilder
assert indexer._use_flattening(adaptive_config)
assert (
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
adaptive_config, SimpleNamespace()
)
== AttentionCGSupport.ALWAYS
)
assert not indexer._use_flattening(fixed_config)
assert (
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
fixed_config, SimpleNamespace()
)
== AttentionCGSupport.UNIFORM_BATCH
)
@pytest.mark.cpu_test
def test_deepseek_v41_rocm_fixed_k_path_is_unchanged(
monkeypatch: pytest.MonkeyPatch,
):
_mock_rocm_platform(monkeypatch)
fixed_config = _make_indexer_config(
architecture="DeepseekV41ForCausalLM", adaptive=False
)
for builder_cls in (
DeepseekV41ROCMAiterMLASparseMetadataBuilder,
v41_rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder,
):
assert (
builder_cls.get_cudagraph_support(fixed_config, SimpleNamespace())
== AttentionCGSupport.UNIFORM_BATCH
)
assert not indexer._use_flattening(fixed_config)
assert (
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
fixed_config, SimpleNamespace()
)
== AttentionCGSupport.UNIFORM_BATCH
)
@pytest.mark.cpu_test
@pytest.mark.parametrize(
"architecture",
["DeepseekV32ForCausalLM", "GlmMoeDsaForCausalLM"],
)
def test_rocm_adaptive_indexer_flattening_rejects_other_architectures(
monkeypatch: pytest.MonkeyPatch,
architecture: str,
):
_mock_rocm_platform(monkeypatch)
adaptive_config = _make_indexer_config(architecture=architecture, adaptive=True)
assert not indexer._rocm_supports_flattened_device_query_lens(adaptive_config)
assert not indexer._use_flattening(adaptive_config)
assert (
DeepseekV32IndexerMetadataBuilder.get_cudagraph_support(
adaptive_config, SimpleNamespace()
)
== AttentionCGSupport.UNIFORM_BATCH
)
@pytest.mark.cpu_test
def test_rocm_adaptive_indexer_preserves_single_request_uniform_path(
monkeypatch: pytest.MonkeyPatch,
):
builder = _make_indexer_builder(adaptive=True, capacity=8)
class FakeUniformKernel:
called = False
def __call__(
self,
seq_lens,
decode_seq_lens,
block_table,
expanded_block_table,
decode_lens,
num_decode_tokens,
max_decode_len,
):
self.called = True
assert num_decode_tokens == 4
assert block_table.stride(0) == expanded_block_table.stride(0) == 2
decode_seq_lens[:max_decode_len] = torch.arange(
seq_lens[0] - max_decode_len + 1,
seq_lens[0] + 1,
dtype=torch.int32,
)
expanded_block_table[:max_decode_len] = block_table[0]
decode_lens[:max_decode_len] = 1
fake_kernel = FakeUniformKernel()
monkeypatch.setattr(indexer, "_PREPARE_UNIFORM_DECODE_KERNEL", fake_kernel)
seq_lens, block_table, decode_lens, batch_size, requires_padding = (
builder._prepare_decode_tensors(
seq_lens=torch.tensor([10], dtype=torch.int32),
block_table=torch.tensor([[1, 2]], dtype=torch.int32),
decode_lens=torch.tensor([4], dtype=torch.int32),
decode_lens_cpu=torch.tensor([4], dtype=torch.int32),
query_start_loc=torch.tensor([0], dtype=torch.int32),
num_decodes=1,
num_decode_tokens=4,
use_native=False,
next_n=8,
max_decode_len=4,
)
)
assert fake_kernel.called
torch.testing.assert_close(seq_lens, torch.tensor([7, 8, 9, 10], dtype=torch.int32))
torch.testing.assert_close(
block_table,
torch.tensor([[1, 2], [1, 2], [1, 2], [1, 2]], dtype=torch.int32),
)
torch.testing.assert_close(decode_lens, torch.ones(4, dtype=torch.int32))
assert batch_size == 4
assert not requires_padding
@pytest.mark.cpu_test
def test_rocm_adaptive_indexer_replays_changed_allocations_with_stable_buffers():
builder = _make_indexer_builder(adaptive=True)
buffer_ptrs = (
builder.decode_seq_lens_buffer.data_ptr(),
builder.expanded_block_table_buffer.data_ptr(),
builder.decode_lens_buffer.data_ptr(),
)
block_table = torch.tensor([[1, 2], [3, 4], [5, 6]], dtype=torch.int32)
decode_lens_cpu = torch.tensor([4, 4, 0], dtype=torch.int32)
first = builder._prepare_decode_tensors(
seq_lens=torch.tensor([20, 20, 0], dtype=torch.int32),
block_table=block_table,
decode_lens=torch.tensor([7, 1, 0], dtype=torch.int32),
decode_lens_cpu=decode_lens_cpu,
query_start_loc=torch.tensor([0, 7, 8], dtype=torch.int32),
num_decodes=3,
num_decode_tokens=10,
use_native=False,
next_n=8,
max_decode_len=4,
)
torch.testing.assert_close(
first[0],
torch.tensor([14, 15, 16, 17, 18, 19, 20, 20, 0, 0], dtype=torch.int32),
)
torch.testing.assert_close(
first[1][:, 0],
torch.tensor([1, 1, 1, 1, 1, 1, 1, 3, 0, 0], dtype=torch.int32),
)
second = builder._prepare_decode_tensors(
seq_lens=torch.tensor([20, 20, 0], dtype=torch.int32),
block_table=block_table,
decode_lens=torch.tensor([1, 7, 0], dtype=torch.int32),
decode_lens_cpu=decode_lens_cpu,
query_start_loc=torch.tensor([0, 1, 8], dtype=torch.int32),
num_decodes=3,
num_decode_tokens=10,
use_native=False,
next_n=8,
max_decode_len=4,
)
torch.testing.assert_close(
second[0],
torch.tensor([20, 14, 15, 16, 17, 18, 19, 20, 0, 0], dtype=torch.int32),
)
torch.testing.assert_close(
second[1][:, 0],
torch.tensor([1, 3, 3, 3, 3, 3, 3, 3, 0, 0], dtype=torch.int32),
)
torch.testing.assert_close(second[2], torch.ones(10, dtype=torch.int32))
assert second[3:] == (10, False)
assert buffer_ptrs == (
builder.decode_seq_lens_buffer.data_ptr(),
builder.expanded_block_table_buffer.data_ptr(),
builder.decode_lens_buffer.data_ptr(),
)
@@ -1,885 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for DeepSeek-V4 in-image bidirectional SWA visibility (vision variant).
The reference semantics are a torch port of the official
``get_image_visible`` / ``get_window_topk_idxs_visible``: inside an image span
[span_start, span_end] (inclusive), a token at ``pos`` sees
``min(pos - span_start, max_image_tokens - 1)`` extra tokens to the left and
``min(span_end - pos, max_image_tokens)`` to the right; the window then starts
at ``max(pos - (window - 1) - max(left - (window - 1), 0), 0)`` and ends at
``pos + right`` (inclusive).
"""
import inspect
import pytest
import torch
from transformers import DeepseekV4Config
from typing_extensions import TypedDict
from tests.v1.attention.utils import create_vllm_config
from vllm.models.deepseek_v4.common.ops.cache_utils import (
build_flashinfer_mixed_sparse_indices,
combine_topk_swa_indices,
)
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.sparse_swa import (
DeepseekSparseSWAMetadataBuilder,
_compute_image_visibility_kernel,
_compute_swa_indices_and_lens_kernel,
)
from vllm.v1.kv_cache_interface import SlidingWindowMLASpec
WINDOW = 8
MAX_IMG = 6
WIDTH = WINDOW + MAX_IMG
BLOCK_SIZE = 64
def ref_left_right(
seq_lens: list[int],
query_lens: list[int],
spans_per_req: list[list[tuple[int, int]]],
max_image_tokens: int,
) -> tuple[list[int], list[int]]:
"""Per-token (left, right) for the flattened decode-first token stream."""
lefts: list[int] = []
rights: list[int] = []
for seq_len, query_len, spans in zip(seq_lens, query_lens, spans_per_req):
prefix_len = seq_len - query_len
for i in range(query_len):
pos = prefix_len + i
left = right = 0
for span_start, span_end in spans:
if span_start <= pos <= span_end:
left = min(pos - span_start, max_image_tokens - 1)
right = min(span_end - pos, max_image_tokens)
lefts.append(left)
rights.append(right)
return lefts, rights
def ref_swa_bounds(
pos: int, window: int, left: int, right: int, replay_start: int = 0
) -> tuple[int, int]:
"""Reference [start, end) window bounds for one query token. Under SWA
bounded replay no window KV exists below ``replay_start``."""
left_add = max(left - (window - 1), 0)
start = max(pos - (window - 1) - left_add, 0, replay_start)
return start, pos + right + 1
def make_batch(
seq_lens: list[int],
query_lens: list[int],
device: torch.device,
):
"""Build the kernel inputs for a decode-first batch."""
num_reqs = len(seq_lens)
query_start_loc = torch.zeros(num_reqs + 1, dtype=torch.int32, device=device)
query_start_loc[1:] = torch.tensor(
query_lens, dtype=torch.int32, device=device
).cumsum(0)
num_tokens = int(query_start_loc[-1])
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
token_to_req = torch.repeat_interleave(
torch.arange(num_reqs, dtype=torch.int32, device=device),
torch.tensor(query_lens, dtype=torch.int32, device=device),
)
max_blocks = (max(seq_lens) + BLOCK_SIZE - 1) // BLOCK_SIZE
block_table = torch.arange(
num_reqs * max_blocks, dtype=torch.int32, device=device
).view(num_reqs, max_blocks)
slot_mapping = torch.arange(num_tokens, dtype=torch.int64, device=device)
return query_start_loc, seq_lens_t, token_to_req, slot_mapping, block_table
def ref_swa_slot_rows(
seq_lens: list[int],
query_lens: list[int],
spans_per_req: list[list[tuple[int, int]]],
block_table: torch.Tensor,
window: int,
max_image_tokens: int,
width: int,
replay_starts: list[int] | None = None,
) -> tuple[list[list[int]], list[int]]:
"""Reference paged slot-id rows and lens for every token in the batch."""
block_table_cpu = block_table.cpu()
lefts, rights = ref_left_right(
seq_lens, query_lens, spans_per_req, max_image_tokens
)
replay_starts = replay_starts or [0] * len(seq_lens)
rows: list[list[int]] = []
lens: list[int] = []
token = 0
for req, (seq_len, query_len) in enumerate(zip(seq_lens, query_lens)):
prefix_len = seq_len - query_len
for i in range(query_len):
pos = prefix_len + i
start, end = ref_swa_bounds(
pos, window, lefts[token], rights[token], replay_starts[req]
)
row = []
for p in range(start, end):
blk = int(block_table_cpu[req, p // BLOCK_SIZE])
row.append(blk * BLOCK_SIZE + p % BLOCK_SIZE)
lens.append(len(row))
row.extend([-1] * (width - len(row)))
rows.append(row)
token += 1
return rows, lens
def run_swa_kernel(
seq_lens: list[int],
query_lens: list[int],
spans_per_req: list[list[tuple[int, int]]],
window: int = WINDOW,
max_image_tokens: int = MAX_IMG,
with_image: bool = True,
) -> tuple[torch.Tensor, torch.Tensor]:
device = torch.device("cuda")
query_start_loc, seq_lens_t, token_to_req, slot_mapping, block_table = make_batch(
seq_lens, query_lens, device
)
num_tokens = int(query_start_loc[-1])
width = window + (max_image_tokens if with_image else 0)
swa_indices = torch.zeros(num_tokens, 1, width, dtype=torch.int32, device=device)
swa_lens = torch.zeros(num_tokens, dtype=torch.int32, device=device)
is_valid = slot_mapping >= 0
replay_start_t = torch.zeros(len(seq_lens), dtype=torch.int32, device=device)
if with_image:
lefts, rights = ref_left_right(
seq_lens, query_lens, spans_per_req, max_image_tokens
)
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
else:
left_t = right_t = swa_lens # unused dummies
_compute_swa_indices_and_lens_kernel[(num_tokens,)](
swa_indices,
swa_indices.stride(0),
swa_lens,
window,
width,
left_t,
right_t,
query_start_loc,
seq_lens_t,
token_to_req,
is_valid,
block_table,
block_table.stride(0),
BLOCK_SIZE,
replay_start_t,
token_offset=0,
HAS_IMAGE=with_image,
TRITON_BLOCK_SIZE=1024,
)
return swa_indices[:, 0], swa_lens
# seq_lens, query_lens, spans per request (positions are prompt-absolute,
# inclusive on both ends, matching the reference's sentinel-bracketed spans).
class _Case(TypedDict):
seq_lens: list[int]
query_lens: list[int]
spans: list[list[tuple[int, int]]]
CASES: list[_Case] = [
# two image spans in one request, one pure-text request
{
"seq_lens": [30, 12],
"query_lens": [30, 12],
"spans": [[(4, 12), (20, 24)], []],
},
# span larger than max_image_tokens, straddling the window boundary
{
"seq_lens": [26],
"query_lens": [26],
"spans": [[(2, 17)]],
},
# chunked prefill: span fully inside the second chunk's query
{
"seq_lens": [40, 9],
"query_lens": [16, 9],
"spans": [[(30, 38)], []],
},
# span ending exactly at the prompt end; tiny request
{
"seq_lens": [7, 15],
"query_lens": [7, 15],
"spans": [[(0, 6)], [(10, 14)]],
},
]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("case", CASES)
def test_swa_indices_kernel_with_image_spans(case):
rows, lens = ref_swa_slot_rows(
case["seq_lens"],
case["query_lens"],
case["spans"],
make_batch(case["seq_lens"], case["query_lens"], torch.device("cuda"))[4],
WINDOW,
MAX_IMG,
WIDTH,
)
indices, actual_lens = run_swa_kernel(
case["seq_lens"], case["query_lens"], case["spans"], with_image=True
)
assert actual_lens.cpu().tolist() == lens
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("case", CASES)
def test_swa_indices_kernel_without_image_unchanged(case):
"""HAS_IMAGE=False must reproduce the plain causal sliding window."""
rows, lens = ref_swa_slot_rows(
case["seq_lens"],
case["query_lens"],
[[] for _ in case["seq_lens"]],
make_batch(case["seq_lens"], case["query_lens"], torch.device("cuda"))[4],
WINDOW,
MAX_IMG,
WINDOW,
)
indices, actual_lens = run_swa_kernel(
case["seq_lens"], case["query_lens"], case["spans"], with_image=False
)
assert indices.shape[-1] == WINDOW
assert actual_lens.cpu().tolist() == lens
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_image_visibility_kernel():
"""The builder's visibility kernel must match get_image_visible."""
device = torch.device("cuda")
seq_lens = [30, 12]
query_lens = [30, 12]
spans = [[(4, 12), (20, 24)], []]
query_start_loc, seq_lens_t, token_to_req, _, _ = make_batch(
seq_lens, query_lens, device
)
num_tokens = int(query_start_loc[-1])
# CSR span layout: request -> contiguous [start, end) span list.
indptr = [0, 2, 2]
starts = [4, 20]
ends = [12, 24]
left = torch.zeros(num_tokens, dtype=torch.int32, device=device)
right = torch.zeros(num_tokens, dtype=torch.int32, device=device)
_compute_image_visibility_kernel[(num_tokens,)](
left,
right,
torch.tensor(indptr, dtype=torch.int32, device=device),
torch.tensor(starts, dtype=torch.int32, device=device),
torch.tensor(ends, dtype=torch.int32, device=device),
query_start_loc,
seq_lens_t,
token_to_req,
MAX_IMG,
token_offset=0,
)
ref_left, ref_right = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
assert left.cpu().tolist() == ref_left
assert right.cpu().tolist() == ref_right
def combine_case(
compress_ratio: int,
topk: int,
seq_lens: list[int],
query_lens: list[int],
spans: list[list[tuple[int, int]]],
with_image: bool,
replay_starts: list[int] | None = None,
combine_fn=combine_topk_swa_indices,
in_range_topk: bool = False,
):
"""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
query_start_loc = torch.zeros(num_reqs + 1, dtype=torch.int32, device=device)
query_start_loc[1:] = torch.tensor(
query_lens, dtype=torch.int32, device=device
).cumsum(0)
num_tokens = int(query_start_loc[-1])
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
# The builder's gather covers only the context above the replay start.
gather_lens = torch.tensor(
[
q + min(max(s - q - r, 0), WINDOW - 1)
for s, q, r in zip(seq_lens, query_lens, replay_starts)
],
dtype=torch.int32,
device=device,
)
N = (max(seq_lens) + compress_ratio - 1) // compress_ratio
M = N + int(gather_lens.max()) + 8
gen = torch.Generator(device="cpu").manual_seed(0)
topk_indices = torch.randint(
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)]
if with_image:
lefts, rights = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
else:
left_t = right_t = None
# V4.1's combine has no image windows (causal SWA only).
has_image = "left_visible" in inspect.signature(combine_fn).parameters
image_kwargs = (
dict(left_visible=left_t, right_visible=right_t, max_image_tokens=MAX_IMG)
if has_image
else {}
)
combined_indices, combined_lens = combine_fn(
topk_indices,
query_start_loc,
seq_lens_t,
gather_lens,
WINDOW,
compress_ratio,
topk,
M,
N,
**image_kwargs,
)
# Reference rows.
lefts, rights = ref_left_right(
seq_lens,
query_lens,
spans if with_image else [[] for _ in seq_lens],
MAX_IMG,
)
topk_cpu = topk_indices.cpu()
width = WINDOW + (MAX_IMG if has_image else 0)
combined_topk = (topk + width + 127) // 128 * 128
rows = []
lens = []
token = 0
for b, (seq_len, query_len) in enumerate(zip(seq_lens, query_lens)):
prefix_len = seq_len - query_len
gather_start = seq_len - int(gather_lens[b])
for i in range(query_len):
pos = prefix_len + i
topk_len = min((pos + 1) // compress_ratio, topk)
start, end = ref_swa_bounds(pos, WINDOW, lefts[token], rights[token])
# The window never reaches below the gathered buffer.
start = max(start, gather_start)
swa_len = end - start
row = [-1] * combined_topk
for j in range(topk_len):
row[j] = int(topk_cpu[token, j]) + M * b
for j in range(swa_len):
row[topk_len + j] = M * b + N + start + j - gather_start
rows.append(row)
lens.append(topk_len + swa_len)
token += 1
return combined_indices, combined_lens, rows, lens
COMBINE_CASES = [
dict(compress_ratio=1, topk=0), # SWA-only layer
dict(compress_ratio=4, topk=16), # C4A layer
]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
def test_combine_topk_swa_with_image_spans(cfg):
case = CASES[0]
indices, lens, rows, exp_lens = combine_case(
cfg["compress_ratio"],
cfg["topk"],
case["seq_lens"],
case["query_lens"],
case["spans"],
with_image=True,
)
assert lens.cpu().tolist() == exp_lens
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
@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 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=[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
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("cfg", COMBINE_CASES)
def test_combine_topk_swa_without_image_unchanged(cfg):
"""left_visible=None must reproduce the plain causal combined indices."""
case = CASES[0]
indices, lens, rows, exp_lens = combine_case(
cfg["compress_ratio"],
cfg["topk"],
case["seq_lens"],
case["query_lens"],
case["spans"],
with_image=False,
)
assert lens.cpu().tolist() == exp_lens
assert indices.cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_flashinfer_mixed_sparse_indices_with_image_spans():
device = torch.device("cuda")
# 1 decode token (req 0) + two prefill requests (reqs 1, 2).
seq_lens = [20, 30, 9]
query_lens = [1, 30, 9]
spans = [[], [(4, 12)], [(0, 6)]]
query_start_loc = torch.tensor([0, 1, 31, 40], dtype=torch.int32, device=device)
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
token_to_req = torch.tensor(
[0] + [1] * 30 + [2] * 9, dtype=torch.int32, device=device
)
block_table = torch.arange(3, dtype=torch.int32, device=device).view(3, 1)
decode_swa = torch.tensor(
[[100, 101, 102, 103, 104, 105, 106, 107]], dtype=torch.int32, device=device
)
prefill_topk = torch.zeros(39, 0, dtype=torch.int32, device=device)
lefts, rights = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
left_t = torch.tensor(lefts, dtype=torch.int32, device=device)
right_t = torch.tensor(rights, dtype=torch.int32, device=device)
sparse_indices, sparse_lens = build_flashinfer_mixed_sparse_indices(
decode_swa_indices=decode_swa,
decode_compressed_indices=None,
decode_compressed_topk_lens=None,
prefill_topk_indices=prefill_topk,
query_start_loc=query_start_loc,
seq_lens=seq_lens_t,
token_to_req_indices=token_to_req,
swa_block_table=block_table,
swa_block_size=BLOCK_SIZE,
compressed_block_table=None,
compressed_block_size=BLOCK_SIZE,
window_size=WINDOW,
compress_ratio=1,
topk=0,
prefill_left_visible=left_t,
prefill_right_visible=right_t,
max_image_tokens=MAX_IMG,
)
swa_total = WINDOW + MAX_IMG
assert sparse_indices.shape == (40, swa_total)
assert sparse_lens.cpu().tolist() == [swa_total] * 40
# Decode row: slots copied, image-extension columns padded with -1.
decode_row = sparse_indices[0].cpu().tolist()
assert decode_row[:WINDOW] == list(range(100, 108))
assert decode_row[WINDOW:] == [-1] * MAX_IMG
# Prefill rows: paged slot ids over the widened window.
exp_rows, _ = ref_swa_slot_rows(
seq_lens, query_lens, spans, block_table, WINDOW, MAX_IMG, swa_total
)
actual = sparse_indices[1:].cpu().tolist()
assert actual == exp_rows[1:]
def make_builder(
vision: bool,
window: int = WINDOW,
max_image_tokens: int = MAX_IMG,
max_num_batched_tokens: int = 64,
model_name: str = "Qwen/Qwen3-0.6B",
builder_cls: type[
DeepseekSparseSWAMetadataBuilder
] = DeepseekSparseSWAMetadataBuilder,
deepseek_v4_config: bool = True,
bounded_replay: bool = False,
) -> DeepseekSparseSWAMetadataBuilder:
vision_fields = dict(vision_n_layers=2, vision_max_n_token=max_image_tokens)
vllm_config = create_vllm_config(
model_name=model_name,
max_model_len=4096,
max_num_batched_tokens=max_num_batched_tokens,
max_num_seqs=8,
hf_config_override={"sliding_window": window}
| (vision_fields if vision and not deepseek_v4_config else {}),
)
if vision and deepseek_v4_config:
# Only V4 configs widen the SWA window in-kernel over image spans
vllm_config.model_config.hf_config = DeepseekV4Config(
num_hidden_layers=1,
layer_types=["sliding_attention"],
sliding_window=window,
**vision_fields,
)
spec = SlidingWindowMLASpec(
block_size=BLOCK_SIZE,
num_kv_heads=1,
head_size=512,
dtype=torch.bfloat16,
sliding_window=window,
cache_dtype_str="auto",
model_version="deepseek_v4",
bounded_replay=bounded_replay,
)
return builder_cls(
kv_cache_spec=spec,
layer_names=["layer0"],
vllm_config=vllm_config,
device=torch.device("cuda"),
)
def build_metadata(
builder: DeepseekSparseSWAMetadataBuilder,
seq_lens: list[int],
query_lens: list[int],
mm_req_doc_ranges: dict[int, list[tuple[int, int]]] | None,
replay_starts: list[int] | None = None,
):
device = torch.device("cuda")
query_start_loc, seq_lens_t, _, slot_mapping, block_table = make_batch(
seq_lens, query_lens, device
)
replay_start = (
None
if replay_starts is None
else torch.tensor(replay_starts, dtype=torch.int32, device=device)
)
return builder.build(
0,
CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc.cpu(),
seq_lens=seq_lens_t,
seq_lens_cpu_upper_bound=seq_lens_t.cpu(),
num_reqs=len(seq_lens),
num_actual_tokens=int(query_start_loc[-1]),
max_query_len=max(query_lens),
max_seq_len=max(seq_lens),
block_table_tensor=block_table,
slot_mapping=slot_mapping,
causal=True,
mm_req_doc_ranges=mm_req_doc_ranges,
),
replay_start=replay_start,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_in_image_visibility():
seq_lens = [30, 12]
query_lens = [30, 12]
spans = [[(4, 12), (20, 24)], []]
builder = make_builder(vision=True)
md = build_metadata(builder, seq_lens, query_lens, {0: spans[0], 1: spans[1]})
assert md.num_prefills == 2
assert md.num_decode_tokens == 0
assert md.prefill_swa_indices.shape[-1] == WIDTH
assert md.prefill_left_visible is not None
assert md.prefill_right_visible is not None
ref_left, ref_right = ref_left_right(seq_lens, query_lens, spans, MAX_IMG)
assert md.prefill_left_visible.cpu().tolist() == ref_left
assert md.prefill_right_visible.cpu().tolist() == ref_right
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
rows, lens = ref_swa_slot_rows(
seq_lens, query_lens, spans, block_table, WINDOW, MAX_IMG, WIDTH
)
assert md.prefill_swa_lens.cpu().tolist() == lens
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_no_image_spans_fast_path():
"""Vision model, image-free batch: no visibility tensors, plain window."""
seq_lens = [30, 12]
query_lens = [30, 12]
builder = make_builder(vision=True)
md = build_metadata(builder, seq_lens, query_lens, {0: [], 1: []})
assert md.prefill_left_visible is None
assert md.prefill_right_visible is None
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
rows, lens = ref_swa_slot_rows(
seq_lens, query_lens, [[], []], block_table, WINDOW, MAX_IMG, WIDTH
)
assert md.prefill_swa_lens.cpu().tolist() == lens
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_text_model_unchanged():
"""Text-only model: buffers stay window-sized and spans are ignored."""
seq_lens = [30, 12]
query_lens = [30, 12]
builder = make_builder(vision=False)
assert builder.max_image_tokens == 0
md = build_metadata(builder, seq_lens, query_lens, None)
assert md.prefill_swa_indices.shape[-1] == WINDOW
assert md.prefill_left_visible is None
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
rows, lens = ref_swa_slot_rows(
seq_lens, query_lens, [[], []], block_table, WINDOW, MAX_IMG, WINDOW
)
assert md.prefill_swa_lens.cpu().tolist() == lens
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("compress_ratio", [0, 1, 2])
@pytest.mark.parametrize("query_len", [100, 4000])
def test_v41_image_prefill_uses_causal_swa(compress_ratio, query_len):
"""V4.1 image tokens use the same causal SWA as text, including in chunks."""
from vllm.models.deepseek_v41.common.ops.cache_utils import (
combine_topk_swa_indices as combine_v41,
)
from vllm.models.deepseek_v41.sparse_mla import DeepseekV41SparseSWAMetadataBuilder
seq_len, window, max_image_tokens = 4000, 128, 2048
spans = [(1900, 3947)]
builder = make_builder(
True,
window,
max_image_tokens,
query_len,
builder_cls=DeepseekV41SparseSWAMetadataBuilder,
deepseek_v4_config=False,
)
assert builder.max_image_tokens == 0
md = build_metadata(builder, [seq_len], [query_len], {0: spans})
assert md.prefill_left_visible is None
assert md.prefill_right_visible is None
assert md.prefill_swa_indices.shape[-1] == window
plan = md.get_prefill_chunk_plan(
compress_ratio, prefill_chunk_size=4, has_compressed=compress_ratio > 0
)
[(start, end, n, m)] = plan
gather_len = int(md.prefill_gather_lens[0])
assert (start, end, m - n) == (0, 1, gather_len)
assert gather_len == query_len + min(seq_len - query_len, window - 1)
indices, lens = combine_v41(
torch.empty(query_len, 0, dtype=torch.int32, device="cuda"),
md.query_start_loc,
md.prefill_seq_lens,
md.prefill_gather_lens,
window,
compress_ratio,
0,
m,
n,
)
indices, lens = indices.cpu(), lens.cpu().tolist()
paged_indices = md.prefill_swa_indices.cpu()
paged_lens = md.prefill_swa_lens.cpu().tolist()
for token, pos in enumerate(range(seq_len - query_len, seq_len)):
lo, hi = max(0, pos - window + 1), pos + 1
row = indices[token, : lens[token]]
assert lens[token] == hi - lo
assert torch.all((row >= n) & (row < m))
absolute_keys = row - n + seq_len - gather_len
assert absolute_keys.tolist() == list(range(lo, hi))
assert paged_lens[token] == hi - lo
assert paged_indices[token, 0, : hi - lo].tolist() == list(range(lo, hi))
# SWA bounded replay: every prefill index path clamps the window at replay_start.
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_replay_start_bounds_prefill_window_and_gather():
"""Paged-direct prefill indices stop at replay_start and the FlashMLA
gather only covers the context the request may see."""
seq_lens = [40, 12, 30]
query_lens = [24, 12, 10]
replay_starts = [12, 0, 0]
builder = make_builder(vision=False)
md = build_metadata(builder, seq_lens, query_lens, None, replay_starts)
assert md.replay_start is not None
assert md.replay_start.cpu().tolist() == replay_starts
_, _, _, _, block_table = make_batch(seq_lens, query_lens, torch.device("cuda"))
rows, lens = ref_swa_slot_rows(
seq_lens,
query_lens,
[[], [], []],
block_table,
WINDOW,
MAX_IMG,
WINDOW,
replay_starts=replay_starts,
)
assert md.prefill_swa_lens.cpu().tolist() == lens
assert md.prefill_swa_indices[:, 0].cpu().tolist() == rows
# Request 0: the first replayed row (pos 16) sees [12, 16]; its last row
# (pos 39) is a full window above the replay start and sees all of it.
assert md.prefill_swa_lens[0].item() == 16 - 12 + 1
assert md.prefill_swa_lens[23].item() == WINDOW
# gather_len = query_len + min(prefix_len - replay_start, WINDOW - 1).
assert md.prefill_gather_lens.cpu().tolist() == [
24 + min(16 - 12, WINDOW - 1),
12,
10 + min(20, WINDOW - 1),
]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_builder_replaying_group_builds_without_replay_start():
"""Graph captures build without model-specific kwargs: a replaying group's
metadata then bounds nothing."""
builder = make_builder(vision=False, bounded_replay=True)
md = build_metadata(builder, [40, 12], [24, 12], None)
assert not md.replay_start.any()
assert md.prefill_swa_lens[0].item() == WINDOW
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_v41_flashinfer_mixed_sparse_indices_respect_replay_start():
from vllm.models.deepseek_v41.common.ops.cache_utils import (
build_flashinfer_mixed_sparse_indices as build_v41,
)
device = torch.device("cuda")
# 1 decode token (req 0) + two prefill requests; req 1 resumes at 16.
seq_lens = [20, 40, 9]
query_lens = [1, 24, 9]
replay_starts = [0, 16, 0]
query_start_loc = torch.tensor([0, 1, 25, 34], dtype=torch.int32, device=device)
seq_lens_t = torch.tensor(seq_lens, dtype=torch.int32, device=device)
token_to_req = torch.tensor(
[0] + [1] * 24 + [2] * 9, dtype=torch.int32, device=device
)
block_table = torch.arange(3, dtype=torch.int32, device=device).view(3, 1)
kwargs = dict(
decode_swa_indices=torch.zeros((1, WINDOW), dtype=torch.int32, device=device),
decode_compressed_indices=None,
decode_compressed_topk_lens=None,
prefill_topk_indices=torch.empty((33, 0), dtype=torch.int32, device=device),
query_start_loc=query_start_loc,
seq_lens=seq_lens_t,
token_to_req_indices=token_to_req,
swa_block_table=block_table,
swa_block_size=BLOCK_SIZE,
compressed_block_table=None,
compressed_block_size=BLOCK_SIZE,
window_size=WINDOW,
compress_ratio=1,
topk=0,
)
plain, _ = build_v41(
replay_start=torch.zeros(3, dtype=torch.int32, device=device), **kwargs
)
bounded, _ = build_v41(
replay_start=torch.tensor(replay_starts, dtype=torch.int32, device=device),
**kwargs,
)
rows, _ = ref_swa_slot_rows(
seq_lens,
query_lens,
[[], [], []],
block_table,
WINDOW,
MAX_IMG,
WINDOW,
replay_starts=replay_starts,
)
# Decode row is copied through; prefill rows follow the bounded window.
assert bounded[0].cpu().tolist() == plain[0].cpu().tolist()
assert bounded[1:].cpu().tolist() == rows[1:]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_dspark_noncausal_draft_decode_update_matches_build():
"""A DSpark draft graph refreshes its non-causal SWA metadata in place
instead of rebuilding it, so the refresh must match a fresh build."""
from vllm.v1.attention.backends.mla.compressor_utils import (
get_dspark_swa_index_width,
)
num_spec = 4
query_lens = [num_spec] * 3
def make_dspark_builder():
builder = make_builder(vision=False)
builder.is_dspark = True
builder.noncausal_index_width = get_dspark_swa_index_width(WINDOW, num_spec)
builder.decode_threshold = num_spec
return builder
def common_metadata(seq_lens):
query_start_loc, seq_lens_t, _, slot_mapping, block_table = make_batch(
seq_lens, query_lens, torch.device("cuda")
)
return CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc.cpu(),
seq_lens=seq_lens_t,
seq_lens_cpu_upper_bound=seq_lens_t.cpu(),
num_reqs=len(seq_lens),
num_actual_tokens=int(query_start_loc[-1]),
max_query_len=num_spec,
max_seq_len=max(seq_lens),
block_table_tensor=block_table,
slot_mapping=slot_mapping,
causal=False,
)
captured_seq_lens = [6, 40, 130]
replay_seq_lens = [130, 9, 90]
builder = make_dspark_builder()
captured = common_metadata(captured_seq_lens)
md = builder.build(0, captured)
replay = common_metadata(replay_seq_lens)
expected = make_dspark_builder().build(0, replay)
# A replay sees new inputs through the same device buffers.
captured.seq_lens.copy_(replay.seq_lens)
captured.block_table_tensor.copy_(replay.block_table_tensor)
builder.update_draft_decode_metadata(md)
assert md.decode_swa_width == builder.noncausal_index_width
torch.testing.assert_close(md.decode_swa_lens, expected.decode_swa_lens)
torch.testing.assert_close(md.decode_swa_indices, expected.decode_swa_indices)
@@ -1,771 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Correctness tests for DSpark non-causal sliding-window MLA via sparse indices.
DSpark drafts a block of N tokens whose attention is NON-CAUSAL within the block:
every block token attends to the sliding window of context AND to all block
tokens (including ones at later positions than itself).
We can implement this using the existing sparse-MLA pathway by expanding the window size
to include the rest of the block tokens: instead of setting topk indices to the 127
previous tokens, we expand it to the next power of 2 (256) and include up to
swa_size + block_size - 1 topk indices, so that each query attends to the rest. The
remaining slots are filled with padding.
The sparse-MLA decode kernels (FlashMLA on SM90/SM100, FlashInfer TRTLLM on
SM100/SM120) are index-driven: each query attends over exactly the slots in its
index list, with no causal mask (see ``flash_mla_with_kvcache(..., indices=...)``
and ``_forward_decode``'s "attend only by generated indices"). The existing
``test_sparse_mla_backends`` suite already validates arbitrary index lists, but
only ones whose entries are <= the query's own position. This test suite specifically
ensures correctness of the non-causal attention case.
This reuses the harness/helpers of ``test_sparse_mla_backends.py`` (same model
shapes, fp8_ds_mla round-trip, mock indexer, MockSparseMLAAttentionLayer); only
the index construction differs.
"""
import math
from types import MethodType, SimpleNamespace
import pytest
import torch
from tests.v1.attention.test_mla_backends import (
BatchSpec,
MockSparseMLAAttentionLayer,
create_and_prepopulate_kv_cache,
)
from tests.v1.attention.test_sparse_mla_backends import (
_quantize_dequantize_fp8_ds_mla,
)
from tests.v1.attention.utils import (
create_common_attn_metadata,
create_standard_kv_cache_spec,
create_vllm_config,
)
from vllm.config import set_current_vllm_config
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.platforms import current_platform
if not current_platform.is_cuda():
pytest.skip(
"DSpark non-causal sparse MLA tests currently only support CUDA.",
allow_module_level=True,
)
from vllm.utils.math_utils import cdiv
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseTRTLLMBackend,
)
from vllm.v1.attention.backends.mla.flashmla_sparse import FlashMLASparseBackend
from vllm.v1.attention.ops import flashmla
DEVICE_TYPE = current_platform.device_type
# (window, block_size, topk_width). topk_width must be a multiple of the kernel's
# B_TOPK (= padded query-head count, 64 or 128); we use 128-multiples to cover
# both. The "wide" case needs window + block > 128 -> width must grow past 128.
_DSPARK_CONFIGS = {
"small_block": (8, 4, 128),
"full_window_block": (128, 5, 256),
}
def _build_dspark_noncausal_indices(
seq_lens: list[int],
query_lens: list[int],
window: int,
topk_width: int,
device: torch.device,
) -> torch.Tensor:
"""Per-token sparse indices for the DSpark non-causal block.
For a request with context length ``ctx`` and a query block of ``q_len``
tokens (block positions ``ctx .. ctx+q_len-1``), EVERY block query attends to
the same set: the trailing ``window`` context positions plus all block
positions, i.e. the contiguous range ``[max(ctx-window,0) .. ctx+q_len-1]``.
This is non-causal: an early block query's list contains later block tokens
(future-pointing). The list is padded to ``topk_width`` with ``-1``.
"""
total_query_tokens = sum(query_lens)
sparse_indices = torch.full(
(total_query_tokens, topk_width), -1, dtype=torch.int32, device=device
)
gt = 0
for s_len, q_len in zip(seq_lens, query_lens):
ctx_len = s_len - q_len
lo = max(ctx_len - window, 0)
hi = ctx_len + q_len # exclusive: window context + the full block
idx_list = torch.arange(lo, hi, dtype=torch.int32, device=device)
n = idx_list.numel()
assert n <= topk_width, (
f"index list ({n}) exceeds aligned topk width ({topk_width})"
)
for _ in range(q_len):
sparse_indices[gt, :n] = idx_list
gt += 1
return sparse_indices
def _run_sparse_backend_vs_sdpa(
backend_cls,
seq_lens: list[int],
query_lens: list[int],
sparse_indices: torch.Tensor,
kv_cache_dtype: str,
block_size: int,
num_heads: int,
device: torch.device,
force_future_dominance: bool = False,
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.
Mirrors ``test_sparse_mla_backends.test_sparse_backend_decode_correctness``
but with externally-supplied (non-causal) ``sparse_indices``.
``num_heads`` selects the kernel's B_TOPK (= padded q-head count): 128 -> 128,
64 -> 64. The aligned widths (128/256) are multiples of both, so num_heads=64
exercises the head64 decode path that the SM100 alignment assert guards.
``force_future_dominance`` scales the LAST block token's latent KV so it
dominates the softmax for every query that attends to it. With random data the
few future block tokens carry negligible attention mass (especially with a wide
window), so causal and non-causal outputs coincide; this knob makes the
future-token contribution provably large for the differentiation test. It is
OFF for the correctness test (which needs sensitivity to all tokens).
Returns (backend_output, noncausal_reference, causal_reference). The causal
reference restricts each query to indices <= its own absolute position.
"""
batch_spec = BatchSpec(seq_lens=seq_lens, query_lens=query_lens)
topk_tokens = sparse_indices.shape[1]
dtype = torch.bfloat16
use_fp8_ds_mla_quantization = kv_cache_dtype == "fp8_ds_mla"
kv_lora_rank = 512
qk_rope_head_dim = 64
head_size = kv_lora_rank + qk_rope_head_dim
max_seqlen = max(seq_lens)
total_cache_tokens = sum(seq_lens)
vllm_config = create_vllm_config(
model_name="deepseek-ai/DeepSeek-V2-Lite-Chat",
tensor_parallel_size=1,
max_model_len=max_seqlen,
num_gpu_blocks=max(2048, cdiv(total_cache_tokens, block_size) + 1),
block_size=block_size,
hf_config_override={
"index_topk": topk_tokens,
"attn_module_list_cfg": [{"topk_tokens": topk_tokens}],
},
)
model_config = vllm_config.model_config
model_config.hf_text_config = SimpleNamespace(
index_topk=topk_tokens,
q_lora_rank=None,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
model_type="deepseek_v2",
)
del model_config.hf_config.index_topk # Composite configs only nest this field.
model_config.dtype = dtype
model_config.get_num_attention_heads = MethodType(
lambda self, parallel_config: num_heads, model_config
)
model_config.get_num_kv_heads = MethodType(
lambda self, parallel_config: 1, model_config
)
model_config.get_head_size = MethodType(lambda self: head_size, model_config)
model_config.get_sliding_window = MethodType(lambda self: None, model_config)
kv_cache_spec = create_standard_kv_cache_spec(vllm_config)
torch.manual_seed(0)
scale = 1.0 / math.sqrt(head_size)
# Shared MLA projection weights, used by both reference and backend.
W_UK = torch.rand(
kv_lora_rank, num_heads, qk_nope_head_dim, dtype=dtype, device=device
)
W_UV = torch.rand(kv_lora_rank, num_heads, v_head_dim, dtype=dtype, device=device)
all_q_vllm, all_kv_c_vllm, all_k_pe_vllm = [], [], []
kv_c_contexts, k_pe_contexts = [], []
reference_outputs = []
# Causal counterpart of the reference: same index lists, but each query is
# restricted to indices <= its own absolute position (drops future-pointing
# block tokens). Used to prove the non-causal result is genuinely different.
causal_reference_outputs = []
kv_cache_scale = torch.tensor(1.0, dtype=torch.float32, device=device)
global_token_idx = 0
for s_len, q_len in zip(seq_lens, query_lens):
ctx_len = s_len - q_len
q_c = torch.rand(
q_len,
num_heads,
qk_nope_head_dim + qk_rope_head_dim,
dtype=dtype,
device=device,
)
kv_c_full = torch.rand(s_len, kv_lora_rank, dtype=dtype, device=device)
k_pe_full = torch.rand(s_len, 1, qk_rope_head_dim, dtype=dtype, device=device)
if force_future_dominance:
# Scale the last block token's latent KV so its key/value dominate the
# softmax for any query attending to it. 4x in the latent dot makes its
# pre-softmax score exceed the others by a wide margin, so non-causal
# queries (which include it) diverge sharply from causal ones (which,
# for all but the last query, exclude it). Applied before quantization
# so cache and reference stay consistent.
kv_c_full[s_len - 1] = kv_c_full[s_len - 1] * 4.0 + 2.0
if use_fp8_ds_mla_quantization:
is_sm100 = torch.cuda.get_device_capability()[0] >= 10
kv_c_full, k_pe_squeezed = _quantize_dequantize_fp8_ds_mla(
kv_c_full,
k_pe_full.squeeze(1),
block_size=block_size,
scale=kv_cache_scale,
simulate_sm100_e8m0_scales=is_sm100,
)
k_pe_full = k_pe_squeezed.unsqueeze(1)
q_nope, q_pe = q_c.split([qk_nope_head_dim, qk_rope_head_dim], dim=-1)
ql_nope = torch.einsum("qnh,lnh->qnl", q_nope, W_UK)
q_mqa = torch.cat([ql_nope, q_pe], dim=-1)
k_mqa = torch.cat([kv_c_full, k_pe_full.squeeze(1)], dim=-1)
v_mqa = kv_c_full
# Per-token sparse SDPA reference over the supplied (non-causal) indices.
def _sparse_sdpa(idx_tensor, q_tok, k_mqa=k_mqa, v_mqa=v_mqa):
k_sparse = k_mqa[idx_tensor].unsqueeze(1).expand(-1, num_heads, -1)
v_sparse = v_mqa[idx_tensor].unsqueeze(1).expand(-1, num_heads, -1)
out = torch.nn.functional.scaled_dot_product_attention(
q_tok.unsqueeze(0).transpose(1, 2),
k_sparse.unsqueeze(0).transpose(1, 2),
v_sparse.unsqueeze(0).transpose(1, 2),
scale=scale,
)
out = out.transpose(1, 2).squeeze(0)
out = torch.einsum("qnl,lnv->qnv", out, W_UV)
return out.flatten(start_dim=-2)
for q_idx in range(q_len):
tok_sparse_idx = sparse_indices[global_token_idx]
valid_indices = tok_sparse_idx[tok_sparse_idx >= 0].long()
q_tok = q_mqa[q_idx : q_idx + 1]
reference_outputs.append(_sparse_sdpa(valid_indices, q_tok))
# Causal: drop indices pointing past this query's own position.
abs_pos = ctx_len + q_idx
causal_indices = valid_indices[valid_indices <= abs_pos]
causal_reference_outputs.append(_sparse_sdpa(causal_indices, q_tok))
global_token_idx += 1
all_q_vllm.append(q_c)
all_kv_c_vllm.append(kv_c_full[ctx_len:])
all_k_pe_vllm.append(k_pe_full[ctx_len:])
kv_c_contexts.append(kv_c_full[: ctx_len + 1])
k_pe_contexts.append(k_pe_full[: ctx_len + 1])
query_vllm = torch.cat(all_q_vllm, dim=0)
kv_c_vllm = torch.cat(all_kv_c_vllm, dim=0)
k_pe_vllm = torch.cat(all_k_pe_vllm, dim=0)
sdpa_reference = torch.cat(reference_outputs, dim=0)
causal_reference = torch.cat(causal_reference_outputs, dim=0)
vllm_config.cache_config.cache_dtype = kv_cache_dtype
vllm_config.model_config.hf_text_config.index_topk = topk_tokens
common_attn_metadata = create_common_attn_metadata(
batch_spec, block_size, device, arange_block_indices=True
)
if stale_cpu_query_lens is not None:
# Adaptive verification updates only device boundaries; the stale CPU
# copy proves token_to_req_indices consumes the device layout.
assert len(stale_cpu_query_lens) == len(query_lens)
cpu_query_start_loc = [0]
for query_len in stale_cpu_query_lens:
cpu_query_start_loc.append(cpu_query_start_loc[-1] + query_len)
common_attn_metadata.query_start_loc_cpu = torch.tensor(
cpu_query_start_loc, dtype=torch.int32
)
kv_cache = create_and_prepopulate_kv_cache(
kv_c_contexts=kv_c_contexts,
k_pe_contexts=k_pe_contexts,
block_size=block_size,
head_size=head_size,
dtype=dtype,
device=device,
num_blocks=vllm_config.cache_config.num_gpu_blocks,
common_attn_metadata=common_attn_metadata,
randomize_blocks=False,
kv_cache_dtype=kv_cache_dtype,
scale=kv_cache_scale,
)
# The sparse builder clones the layer's dense-MHA prefill backend from
# static_forward_context; register a mock layer carrying one.
from vllm.v1.attention.backends.mla.prefill import get_mla_prefill_backend
prefill_backend = get_mla_prefill_backend(vllm_config)(
num_heads=num_heads,
scale=scale,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
vllm_config=vllm_config,
)
vllm_config.compilation_config.static_forward_context["placeholder"] = (
SimpleNamespace(prefill_backend=prefill_backend)
)
builder = backend_cls.get_builder_cls()(
kv_cache_spec, ["placeholder"], vllm_config, device
)
metadata = builder.build(
common_prefix_len=0, common_attn_metadata=common_attn_metadata
)
mock_indexer = SimpleNamespace(topk_indices_buffer=sparse_indices)
kv_b_proj_weight = torch.cat([W_UK, W_UV], dim=-1).view(
kv_lora_rank, num_heads * (qk_nope_head_dim + v_head_dim)
)
mock_kv_b_proj = ColumnParallelLinear(
input_size=kv_lora_rank,
output_size=num_heads * (qk_nope_head_dim + v_head_dim),
bias=False,
).to(device=device, dtype=dtype)
mock_kv_b_proj.weight = torch.nn.Parameter(kv_b_proj_weight.T.contiguous())
with set_current_vllm_config(vllm_config):
impl = backend_cls.get_impl_cls()(
num_heads=num_heads,
head_size=head_size,
scale=scale,
num_kv_heads=1,
alibi_slopes=None,
sliding_window=None,
kv_cache_dtype=vllm_config.cache_config.cache_dtype,
logits_soft_cap=None,
attn_type="decoder",
kv_sharing_target_layer_name=None,
q_lora_rank=None,
kv_lora_rank=kv_lora_rank,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
qk_head_dim=qk_nope_head_dim + qk_rope_head_dim,
v_head_dim=v_head_dim,
kv_b_proj=mock_kv_b_proj,
indexer=mock_indexer,
)
impl.process_weights_after_loading(dtype)
mock_layer = MockSparseMLAAttentionLayer(
impl=impl,
num_heads=num_heads,
qk_nope_head_dim=qk_nope_head_dim,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=v_head_dim,
kv_lora_rank=kv_lora_rank,
device=device,
W_UK=W_UK,
W_UV=W_UV,
q_scale=1.0,
k_scale=1.0,
)
out_buffer = torch.empty(
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
def _skip_if_backend_unavailable(backend_cls, kv_cache_dtype: str, block_size: int):
if kv_cache_dtype not in backend_cls.supported_kv_cache_dtypes:
pytest.skip(f"{backend_cls.get_name()} does not support {kv_cache_dtype}")
if (
backend_cls is FlashMLASparseBackend
and kv_cache_dtype.startswith("fp8")
and kv_cache_dtype != "fp8_ds_mla"
):
pytest.skip("FlashMLA Sparse fp8 only supports fp8_ds_mla kv-cache dtype")
if not backend_cls.supports_block_size(block_size):
pytest.skip(
f"{backend_cls.get_name()} does not support block_size={block_size}"
)
if backend_cls is FlashMLASparseBackend:
ok, reason = flashmla.is_flashmla_sparse_supported()
if not ok:
pytest.skip(reason)
elif backend_cls is FlashInferMLASparseTRTLLMBackend:
cap = current_platform.get_device_capability()
if cap is None or not backend_cls.supports_compute_capability(cap):
pytest.skip("FlashInferMLASparseTRTLLMBackend requires SM 10.x capability")
@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,
):
"""Replay uses device boundaries, including empty padding, despite stale CPU."""
backend_cls = FlashInferMLASparseTRTLLMBackend
_skip_if_backend_unavailable(backend_cls, "fp8", 64)
device = torch.device(DEVICE_TYPE)
seq_lens = [257, 270, 265, 276]
sparse_indices = _build_dspark_noncausal_indices(
seq_lens,
query_lens,
window=128,
topk_width=256,
device=device,
)
backend_output, sdpa_reference, _ = _run_sparse_backend_vs_sdpa(
backend_cls,
seq_lens,
query_lens,
sparse_indices,
"fp8",
64,
16,
device,
qk_nope_head_dim=192,
v_head_dim=256,
stale_cpu_query_lens=[4, 4, 4, 4],
capture_graph=True,
)
torch.testing.assert_close(
backend_output,
sdpa_reference,
rtol=0.065,
atol=0.05,
)
@pytest.mark.parametrize(
"backend_cls",
[FlashMLASparseBackend, FlashInferMLASparseTRTLLMBackend],
ids=["FlashMLA", "FlashInferTRTLLM"],
)
@pytest.mark.parametrize("config_name", list(_DSPARK_CONFIGS.keys()))
# Per backend, the skip logic routes fp8 to the supported flavor: FlashMLA tests
# auto + fp8_ds_mla (and skips per-tensor "fp8", which it aliases to ds_mla);
# FlashInfer TRTLLM tests auto + per-tensor "fp8" (and skips fp8_ds_mla, which it
# does not implement). So both backends get a bf16 case and an fp8 case.
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8_ds_mla", "fp8"])
@pytest.mark.parametrize("block_size", [64])
# h_q=128 -> B_TOPK=128; h_q=64 -> B_TOPK=64 (covers the head64 decode path the
# SM100 alignment assert specifically guards). Aligned widths (128/256) satisfy both.
@pytest.mark.parametrize("num_heads", [128, 64], ids=["h128", "h64"])
def test_dspark_noncausal_sparse_mla_matches_sdpa(
default_vllm_config,
dist_init,
workspace_init,
backend_cls,
config_name,
kv_cache_dtype,
block_size,
num_heads,
):
"""Non-causal (window ∪ block, future-pointing) per-token indices must match
a dense SDPA reference over the same indices, for both sparse-MLA backends."""
_skip_if_backend_unavailable(backend_cls, kv_cache_dtype, block_size)
window, block, topk_width = _DSPARK_CONFIGS[config_name]
device = torch.device(DEVICE_TYPE)
# Decode-style batch: each request has `block` query tokens and enough
# context for a full sliding window.
seq_lens = [window + block + 123, window + block + 50]
query_lens = [block, block]
sparse_indices = _build_dspark_noncausal_indices(
seq_lens, query_lens, window, topk_width, device
)
# Sanity: the construction must actually be non-causal (an early block query
# must reference a later block position than itself).
ctx0 = seq_lens[0] - query_lens[0]
first_query_valid = sparse_indices[0][sparse_indices[0] >= 0]
assert int(first_query_valid.max()) >= ctx0 + query_lens[0] - 1, (
"expected the first block query to attend to a future block token"
)
backend_output, sdpa_reference, _ = _run_sparse_backend_vs_sdpa(
backend_cls,
seq_lens,
query_lens,
sparse_indices,
kv_cache_dtype,
block_size,
num_heads,
device,
)
assert backend_output.shape == sdpa_reference.shape
assert backend_output.dtype == sdpa_reference.dtype
assert torch.isfinite(backend_output).all()
if kv_cache_dtype.startswith("fp8"):
rtol, atol = 0.065, 0.05
else:
rtol, atol = 0.01, 0.01
torch.testing.assert_close(backend_output, sdpa_reference, rtol=rtol, atol=atol)
@pytest.mark.parametrize(
"backend_cls",
[FlashMLASparseBackend, FlashInferMLASparseTRTLLMBackend],
ids=["FlashMLA", "FlashInferTRTLLM"],
)
@pytest.mark.parametrize("config_name", list(_DSPARK_CONFIGS.keys()))
@pytest.mark.parametrize("block_size", [64])
def test_dspark_noncausal_differs_from_causal(
default_vllm_config,
dist_init,
workspace_init,
backend_cls,
config_name,
block_size,
):
"""Differentiation guard: prove the backend genuinely attends to the
future-pointing indices (not silently applying a causal mask, and not merely
coinciding with a causal result because future tokens carry little weight).
With random data the few future block tokens are a negligible fraction of the
attended set (especially with a wide window), so causal and non-causal outputs
are numerically indistinguishable -- that is correct physics, not a backend
bug. To make the check meaningful we use ``force_future_dominance`` so the last
block token dominates the softmax: the backend must then match the non-causal
reference and diverge sharply from the causal one. bf16 (``auto``) suffices;
the property is dtype-independent and fp8 correctness is covered above.
"""
_skip_if_backend_unavailable(backend_cls, "auto", block_size)
window, block, topk_width = _DSPARK_CONFIGS[config_name]
device = torch.device(DEVICE_TYPE)
seq_lens = [window + block + 123, window + block + 50]
query_lens = [block, block]
sparse_indices = _build_dspark_noncausal_indices(
seq_lens, query_lens, window, topk_width, device
)
backend_output, sdpa_reference, causal_reference = _run_sparse_backend_vs_sdpa(
backend_cls,
seq_lens,
query_lens,
sparse_indices,
"auto",
block_size,
128,
device,
force_future_dominance=True,
)
# The two references must be clearly distinguishable for the check to mean
# anything (dominance guarantees this).
ref_gap = (sdpa_reference - causal_reference).abs().max().item()
assert ref_gap > 0.1, (
f"non-causal and causal references are too close (gap={ref_gap}); "
"force_future_dominance did not create a separable scenario"
)
# Backend must track the NON-causal reference, not the causal one.
torch.testing.assert_close(backend_output, sdpa_reference, rtol=0.01, atol=0.01)
causal_err = (backend_output - causal_reference).abs().max().item()
assert causal_err > 0.1, (
f"non-causal backend output matches the causal reference "
f"(max abs diff={causal_err}); future-pointing indices are not attended to"
)
@pytest.mark.parametrize("context_len", [20, 128, 900])
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float8_e4m3fn])
@pytest.mark.parametrize("num_heads", [16, 64])
def test_dsv41_flashinfer_dspark_window_matches_reference(
context_len, dtype, num_heads, monkeypatch
):
"""Draft queries see the full block without treating padded slots as keys."""
if not current_platform.is_device_capability_family(100):
pytest.skip("DSV4 TRTLLM sparse attention requires SM100")
from vllm.models.deepseek_v41.nvidia.flashinfer_sparse import (
DeepseekSparseSWAFlashInferMetadataBuilder,
DeepseekV4FlashInferMLAAttention,
)
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV41SparseSWAMetadataBuilder,
)
torch.manual_seed(123)
device = "cuda"
query_lens = [5, 3]
context_lens = [context_len, context_len + 137]
num_real_tokens, num_tokens, head_dim = 8, 9, 512
cache = torch.randn(32, 128, head_dim, device=device, dtype=torch.bfloat16).to(
dtype
)
query = torch.randn(
num_tokens, num_heads, head_dim, device=device, dtype=torch.bfloat16
).to(dtype)
indices = torch.full((num_tokens, 256), -1, device=device, dtype=torch.int32)
visible_indices = []
visible_lens = []
for req, (context, query_len) in enumerate(zip(context_lens, query_lens)):
visible = (
torch.arange(max(context - 128, 0), context + query_len, device=device)
+ req * 16 * 128
)
visible_indices.extend([visible] * query_len)
visible_lens.extend([visible.numel()] * query_len)
for token, visible in enumerate(visible_indices):
indices[token, : visible.numel()] = visible.to(torch.int32)
query_start_loc = torch.tensor([0, 5, 8, 9], dtype=torch.int32)
metadata = SimpleNamespace(
num_decodes=3,
num_prefills=0,
num_decode_tokens=num_tokens,
num_prefill_tokens=0,
seq_lens=torch.tensor(
[context_lens[0] + 5, context_lens[1] + 3, 1],
device=device,
dtype=torch.int32,
),
query_start_loc=query_start_loc.to(device),
query_start_loc_cpu=query_start_loc,
token_to_req_indices=torch.tensor(
[0] * 5 + [1] * 3 + [2], device=device, dtype=torch.int32
),
decode_swa_indices=indices,
decode_swa_width=256,
decode_swa_lens=torch.tensor(
visible_lens + [0], device=device, dtype=torch.int32
),
block_table=torch.arange(48, device=device, dtype=torch.int32).view(3, -1),
block_size=128,
replay_start=torch.zeros(3, device=device, dtype=torch.int32),
flashinfer_sparse_index_cache={},
max_decode_query_len=5,
)
# Exercise FlashInfer preparation without constructing a model/config.
def init_parent(builder):
builder._max_tokens = num_tokens
builder.device = device
builder.window_size = 128
monkeypatch.setattr(DeepseekV41SparseSWAMetadataBuilder, "__init__", init_parent)
monkeypatch.setattr(
DeepseekV41SparseSWAMetadataBuilder,
"build",
lambda *args: metadata,
)
builder = DeepseekSparseSWAFlashInferMetadataBuilder()
common_metadata = SimpleNamespace(causal=False)
builder.build(0, common_metadata)
prepared = (
metadata.flashinfer_decode_topk_lens,
metadata.flashinfer_decode_seq_lens,
)
attention = SimpleNamespace(
kv_cache_torch_dtype=dtype,
window_size=128,
compress_ratio=0,
topk_indices_buffer=torch.empty(
num_tokens, 0, device=device, dtype=torch.int32
),
scale=1 / math.sqrt(head_dim),
_flashinfer_fp8_bmm1_scale=1 / math.sqrt(head_dim),
_flashinfer_fp8_bmm2_scale=1.0,
attn_sink=None,
)
attention._build_sparse_index_metadata = MethodType(
DeepseekV4FlashInferMLAAttention._build_sparse_index_metadata, attention
)
output = torch.empty_like(query, dtype=torch.bfloat16)
def forward():
metadata.flashinfer_sparse_index_cache.clear()
DeepseekV4FlashInferMLAAttention._forward(
attention, query, None, cache, metadata, None, True, output
)
def check_output():
references = []
for token, visible in enumerate(visible_indices):
keys = cache.flatten(0, 1)[visible].float()
weights = torch.softmax(
query[token].float() @ keys.T / math.sqrt(head_dim), -1
)
references.append(weights @ keys)
atol = 0.01 if dtype == torch.bfloat16 else 0.05
torch.testing.assert_close(
output[:num_real_tokens].float(),
torch.stack(references),
atol=atol,
rtol=0.05,
)
forward()
check_output()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
forward()
# Replay must consume the current inputs, including KV written since capture.
query.copy_(torch.randn_like(query, dtype=torch.bfloat16).to(dtype))
cache.copy_(torch.randn_like(cache, dtype=torch.bfloat16).to(dtype))
# A new step changes visibility as well as Q/KV, without recapturing.
metadata.seq_lens.sub_(1)
metadata.decode_swa_lens[:num_real_tokens].sub_(1)
for token, visible in enumerate(visible_indices):
indices[token, visible.numel() - 1] = -1
visible_indices[token] = visible[:-1]
builder.build(0, common_metadata)
assert metadata.flashinfer_decode_topk_lens.data_ptr() == prepared[0].data_ptr()
assert metadata.flashinfer_decode_seq_lens.data_ptr() == prepared[1].data_ptr()
torch.testing.assert_close(prepared[0], metadata.decode_swa_lens.clamp_min(128))
torch.testing.assert_close(
prepared[1], metadata.seq_lens[metadata.token_to_req_indices.long()]
)
graph.replay()
check_output()
@@ -1,162 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Equivalence tests for the AITER MLA page-index expansion kernel.
`_expand_page_indices_kernel` turns a block table into the per-token flat page
indices the AITER MLA decode kernel consumes (it always runs with page_size=1
internally, so `kv_buffer` is flattened and each token needs its own index).
The kernel was parallelised over token chunks as well as requests; at
concurrency 1 the previous `(num_reqs,)` grid put a single workgroup in a serial
loop over the whole sequence. These tests pin the result to a straightforward
PyTorch expansion so the parallelisation cannot change what is produced.
Both block-table strides are passed by the caller, so a non-contiguous view is
covered explicitly rather than assumed away.
"""
import pytest
import torch
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
_expand_page_indices_kernel,
)
def _reference(block_table, cu_num_tokens, kernel_block_size, out_len, device):
"""Per-token flat index, written the obvious way."""
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
num_reqs = cu_num_tokens.numel() - 1
for r in range(num_reqs):
start = int(cu_num_tokens[r])
end = int(cu_num_tokens[r + 1])
n = end - start
if n <= 0:
continue
tok = torch.arange(n, device=device)
blk = tok // kernel_block_size
off = tok % kernel_block_size
out[start:end] = block_table[r, blk].to(torch.int64) * kernel_block_size + off
return out
def _run(block_table, cu_num_tokens, kernel_block_size, out_len, device):
out = torch.full((out_len,), -1, dtype=torch.int64, device=device)
num_reqs = cu_num_tokens.numel() - 1
max_tokens_per_req = block_table.shape[1] * kernel_block_size
num_chunks = max(1, -(-max_tokens_per_req // 1024))
_expand_page_indices_kernel[(num_reqs, num_chunks)](
out,
block_table,
block_table.stride(0),
block_table.stride(1),
cu_num_tokens,
cu_num_tokens[1:] - cu_num_tokens[:-1],
KERNEL_BLOCK_SIZE=kernel_block_size,
BLOCK_SIZE=1024,
)
return out
def _make(seq_lens, kernel_block_size, device, noncontig=False):
num_reqs = len(seq_lens)
max_blocks = (
max(1, max((s + kernel_block_size - 1) // kernel_block_size for s in seq_lens))
+ 2
)
width = max_blocks * 2 if noncontig else max_blocks
torch.manual_seed(0)
bt = torch.randint(0, 10_000, (num_reqs, width), dtype=torch.int64, device=device)
if noncontig:
bt = bt[:, ::2]
assert not bt.is_contiguous()
cu = torch.zeros(num_reqs + 1, dtype=torch.int64, device=device)
cu[1:] = torch.tensor(seq_lens, dtype=torch.int64, device=device).cumsum(0)
return bt, cu, int(cu[-1])
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
@pytest.mark.parametrize(
"seq_lens", [[1], [128], [4096], [1, 1], [4096, 7], [37, 4096, 1], [1024] * 8]
)
@pytest.mark.parametrize("kernel_block_size", [1, 16, 64])
def test_matches_reference(seq_lens, kernel_block_size):
bt, cu, total = _make(seq_lens, kernel_block_size, "cuda")
got = _run(bt, cu, kernel_block_size, total, "cuda")
want = _reference(bt, cu, kernel_block_size, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
@pytest.mark.parametrize("kernel_block_size", [1, 16])
def test_non_contiguous_block_table(kernel_block_size):
"""Column stride != 1 must be honoured, not assumed away."""
bt, cu, total = _make([4096, 37], kernel_block_size, "cuda", noncontig=True)
got = _run(bt, cu, kernel_block_size, total, "cuda")
want = _reference(bt, cu, kernel_block_size, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_ragged_batch_leaves_other_rows_untouched():
"""A short request must not have its tail written by a longer one's chunks."""
kbs = 16
bt, cu, total = _make([4096, 1, 512], kbs, "cuda")
out = torch.full((total + 8,), -999, dtype=torch.int64, device="cuda")
num_chunks = max(1, -(-(bt.shape[1] * kbs) // 1024))
_expand_page_indices_kernel[(3, num_chunks)](
out,
bt,
bt.stride(0),
bt.stride(1),
cu,
cu[1:] - cu[:-1],
KERNEL_BLOCK_SIZE=kbs,
BLOCK_SIZE=1024,
)
want = _reference(bt, cu, kbs, total, "cuda")
torch.testing.assert_close(out[:total], want, atol=0, rtol=0)
# The slack past the last request must be untouched.
assert torch.all(out[total:] == -999)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_zero_length_request_writes_nothing():
"""A zero-token request in a padded batch must produce no stores."""
kbs = 16
bt, cu, total = _make([256, 0, 128], kbs, "cuda")
got = _run(bt, cu, kbs, total, "cuda")
want = _reference(bt, cu, kbs, total, "cuda")
torch.testing.assert_close(got, want, atol=0, rtol=0)
assert int(cu[2] - cu[1]) == 0
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a GPU")
def test_over_provisioned_chunks_do_not_change_result():
"""Extra chunks must be inert.
Each program covers `chunk_idx * BLOCK_SIZE + [0, BLOCK_SIZE)`, so the grid
has to span the request: 8192 tokens need at least ceil(8192/1024) == 8
chunks, and fewer would simply leave the tail unwritten. The caller sizes
the grid from `block_table.shape[1] * kernel_block_size`, an upper bound
over the batch, so in a ragged batch most requests get more chunks than
they need. That over-provisioning is the case worth pinning: the surplus
programs must return early and change nothing.
"""
kbs = 1
bt, cu, total = _make([8192], kbs, "cuda")
ref = _reference(bt, cu, kbs, total, "cuda")
required = -(-total // 1024)
for num_chunks in (required, required * 2, required * 8):
out = torch.full((total,), -1, dtype=torch.int64, device="cuda")
_expand_page_indices_kernel[(1, num_chunks)](
out,
bt,
bt.stride(0),
bt.stride(1),
cu,
cu[1:] - cu[:-1],
KERNEL_BLOCK_SIZE=kbs,
BLOCK_SIZE=1024,
)
torch.testing.assert_close(out, ref, atol=0, rtol=0)
@@ -1,80 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""FlashInfer GQA builder: reorder threshold under DCP with spec decode."""
import pytest
from vllm.platforms import current_platform
if not current_platform.is_cuda():
pytest.skip("FlashInfer backend requires a CUDA platform.", allow_module_level=True)
import torch
from tests.v1.attention.utils import create_vllm_config
from vllm.config import SpeculativeConfig, set_current_vllm_config
from vllm.v1.attention.backend import AttentionCGSupport
from vllm.v1.attention.backends import flashinfer as flashinfer_backend
from vllm.v1.attention.backends.flashinfer import (
FlashInferDecodeKernel,
FlashInferMetadataBuilder,
)
from vllm.v1.attention.backends.utils import PerLayerParameters
from vllm.v1.kv_cache_interface import FullAttentionSpec
def test_flashinfer_gqa_dcp_spec_decode_clamps_reorder_threshold(monkeypatch):
"""trtllm-gen decode receives no cp_rank/global-seq-len information, so its
end-aligned causal mask is wrong for q_len > 1 over the DCP-interleaved
local KV shard. The builder must keep reorder_batch_threshold at 1 under
DCP so spec queries take the (DCP-aware) prefill path instead.
"""
vllm_config = create_vllm_config(max_model_len=1024)
vllm_config.parallel_config.decode_context_parallel_size = 2
vllm_config.speculative_config = SpeculativeConfig(
method="ngram", num_speculative_tokens=3
)
monkeypatch.setattr(
flashinfer_backend, "can_use_trtllm_attention", lambda *args, **kwargs: True
)
monkeypatch.setattr(
FlashInferMetadataBuilder,
"_get_flashinfer_trtllm_api_decode_kernel",
staticmethod(lambda: FlashInferDecodeKernel.TRTLLM_GEN),
)
monkeypatch.setattr(
flashinfer_backend,
"get_per_layer_parameters",
lambda *args, **kwargs: {
"layer.0": PerLayerParameters(
window_left=-1, logits_soft_cap=None, sm_scale=0.1, has_sinks=False
)
},
)
kv_cache_spec = FullAttentionSpec(
block_size=16,
num_kv_heads=vllm_config.model_config.get_num_kv_heads(
vllm_config.parallel_config
),
head_size=vllm_config.model_config.get_head_size(),
dtype=vllm_config.model_config.dtype,
)
with set_current_vllm_config(vllm_config):
builder = FlashInferMetadataBuilder(
kv_cache_spec,
["layer.0"],
vllm_config,
torch.device("cpu"),
)
# Guard against passing vacuously with the kernel disabled.
assert (
builder.flashinfer_trtllm_api_decode_kernel == FlashInferDecodeKernel.TRTLLM_GEN
)
assert builder.reorder_batch_threshold == 1
assert (
FlashInferMetadataBuilder.get_cudagraph_support(vllm_config, kv_cache_spec)
== AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
)
@@ -1,179 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import MethodType
from unittest.mock import MagicMock
import pytest
import torch
from vllm.platforms import current_platform
requires_flashinfer_mla = pytest.mark.skipif(
not current_platform.has_device_capability(100),
reason="FlashInfer MLA requires compute capability 10 or above.",
)
def test_mla_dcp_gathered_query_reserves_backend_head_storage():
from vllm.v1.attention.ops.dcp import reserve_query_head_storage
query = torch.randn(3, 24, 576, dtype=torch.bfloat16)
padded = reserve_query_head_storage(query, 128)
assert padded.shape == query.shape
assert padded.stride() == query.stride()
assert padded.untyped_storage().nbytes() >= 3 * 128 * 576 * 2
assert torch.equal(padded, query)
@requires_flashinfer_mla
def test_flashinfer_mla_selects_backend_for_gathered_heads():
from vllm.v1.attention.backends.mla.flashinfer_mla import (
_select_mla_decode_backend,
)
assert _select_mla_decode_backend(6) is None
assert _select_mla_decode_backend(24) == "cute-dsl"
@requires_flashinfer_mla
def test_flashinfer_mla_forward_uses_gathered_head_count(monkeypatch):
import vllm.v1.attention.backends.mla.flashinfer_mla as flashinfer_mla
impl = MagicMock()
impl.bmm1_scale = 1.0
impl.bmm2_scale = 1.0
impl.need_to_return_lse_for_decode = True
impl.dcp_world_size = 1
impl.dcp_rank = 0
impl.cp_kv_cache_interleave_size = 1
impl.num_heads = 6
impl.qk_nope_head_dim = 128
impl.kv_lora_rank = 512
impl.qk_rope_head_dim = 64
impl.kv_cache_dtype = "auto"
attn_metadata = MagicMock()
attn_metadata.causal = True
attn_metadata.num_decode_tokens = 2
attn_metadata.num_decodes = 2
attn_metadata.max_seq_len = 1
attn_metadata.decode.block_table = torch.zeros(2, 1, dtype=torch.int32)
attn_metadata.decode.seq_lens = torch.ones(2, dtype=torch.int32)
attn_metadata.decode.max_query_len = 1
query = torch.ones(2, 24, 576, dtype=torch.bfloat16)
kv_cache = torch.ones(1, 128, 576, dtype=torch.bfloat16)
kernel = MagicMock(
return_value=(
torch.ones(2, 1, 24, 512, dtype=torch.bfloat16),
torch.ones(2, 24, dtype=torch.float32),
)
)
monkeypatch.setattr(flashinfer_mla, "_get_workspace_buffer", MagicMock())
monkeypatch.setattr(flashinfer_mla, "trtllm_batch_decode_with_kv_cache_mla", kernel)
layer = MagicMock()
output, lse = flashinfer_mla.FlashInferMLAImpl.forward_mqa(
impl, query, kv_cache, attn_metadata, layer
)
assert kernel.call_args.kwargs["backend"] == "cute-dsl"
assert output.shape == (2, 24, 512)
assert lse is not None and lse.shape == (2, 24)
@requires_flashinfer_mla
@pytest.mark.parametrize("causal", [True, False], ids=["causal", "noncausal"])
def test_flashinfer_mla_forward_uses_native_dcp_api(monkeypatch, causal):
import vllm.v1.attention.backends.mla.flashinfer_mla as flashinfer_mla
impl = MagicMock()
impl.bmm1_scale = 1.0
impl.bmm2_scale = 1.0
impl.need_to_return_lse_for_decode = True
impl.num_heads = 6
impl.qk_nope_head_dim = 128
impl.kv_lora_rank = 512
impl.qk_rope_head_dim = 64
impl.kv_cache_dtype = "auto"
impl.dcp_world_size = 8
impl.dcp_rank = 3
impl.cp_kv_cache_interleave_size = 1
impl._flattened_decode_metadata = MethodType(
flashinfer_mla.FlashInferMLAImpl._flattened_decode_metadata, impl
)
num_reqs, query_len = 2, 3
num_tokens = num_reqs * query_len
block_table = torch.tensor([[10], [20]], dtype=torch.int32)
seq_lens = torch.tensor([4, 5], dtype=torch.int32)
global_causal_seq_lens = torch.tensor([31, 35], dtype=torch.int32)
attn_metadata = MagicMock()
attn_metadata.causal = causal
attn_metadata.num_decode_tokens = num_tokens
attn_metadata.num_decodes = num_reqs
attn_metadata.max_seq_len = 9
attn_metadata.decode.block_table = block_table
attn_metadata.decode.seq_lens = seq_lens
attn_metadata.decode.dcp_tot_seq_lens = global_causal_seq_lens
attn_metadata.decode.max_query_len = query_len
attn_metadata.decode.query_start_loc = torch.arange(
0, num_tokens + 1, query_len, dtype=torch.int32
)
attn_metadata.decode.query_len = 0
query = torch.ones(num_tokens, 24, 576, dtype=torch.bfloat16)
kv_cache = torch.ones(2, 128, 576, dtype=torch.bfloat16)
kernel_batch = num_reqs if causal else num_tokens
kernel_query_len = query_len if causal else 1
kernel = MagicMock(
return_value=(
torch.ones(
kernel_batch,
kernel_query_len,
24,
512,
dtype=torch.bfloat16,
),
torch.ones(
kernel_batch,
kernel_query_len,
24,
dtype=torch.float32,
),
)
)
monkeypatch.setattr(flashinfer_mla, "_get_workspace_buffer", MagicMock())
monkeypatch.setattr(flashinfer_mla, "trtllm_batch_decode_with_kv_cache_mla", kernel)
output, lse = flashinfer_mla.FlashInferMLAImpl.forward_mqa(
impl, query, kv_cache, attn_metadata, MagicMock()
)
call = kernel.call_args.kwargs
assert call["query"].shape == (kernel_batch, kernel_query_len, 24, 576)
expected_block_table = (
block_table if causal else block_table.repeat_interleave(query_len, dim=0)
)
expected_seq_lens = seq_lens if causal else seq_lens.repeat_interleave(query_len)
expected_global_seq_lens = (
global_causal_seq_lens
if causal
else global_causal_seq_lens.repeat_interleave(query_len)
)
torch.testing.assert_close(call["block_tables"], expected_block_table)
torch.testing.assert_close(call["seq_lens"], expected_seq_lens)
assert call["backend"] == "cute-dsl"
assert call["enable_dcp"] is True
assert call["cp_world"] == 8
assert call["cp_rank"] == 3
torch.testing.assert_close(
call["causal_seqlens_kv_global"], expected_global_seq_lens
)
assert "multi_ctas_kv_counter_buffer" not in call
assert flashinfer_mla.FlashInferMLAImpl.lse_base_on_e
assert output.shape == (num_tokens, 24, 512)
assert lse is not None and lse.shape == (num_tokens, 24)
@@ -1,563 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for the FlashInfer SM90 sparse MLA backend wiring and index packing.
The FlashInfer wrapper and top-k conversion are replaced by CPU recorders;
the tests pin the contract between the impl and the kernel API: page_size=1
varlen rows, reserved-buffer refresh, plan parameters (dims, NoPE/rope scale,
causality), ckv/kpe cache splitting, and the backend's model-shape gates.
"""
from types import SimpleNamespace
from typing import Any
import pytest
import torch
# isort: off
import vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90 as sm90_mod
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse_sm90 import (
FlashInferMLASparseSM90Backend,
FlashInferMLASparseSM90Builder,
FlashInferMLASparseSM90Impl,
)
from vllm.v1.kv_cache_interface import MLAAttentionSpec
# isort: on
BLOCK_SIZE = 64
HEAD = 512
TOPK = 128 # triton convert requires width % 128 == 0
def ref_convert(req_id, block_table, token_indices, BLOCK_SIZE=64, **kw):
out = torch.full_like(token_indices, -1)
counts = torch.zeros(token_indices.shape[0], dtype=torch.int32)
for t in range(token_indices.shape[0]):
vals = []
for j in range(token_indices.shape[1]):
pos = int(token_indices[t, j])
if pos == -1:
continue
blk = int(block_table[int(req_id[t]), pos // BLOCK_SIZE])
if blk < 0:
continue
vals.append(blk * kw["BLOCK_STRIDE_ROWS"] + pos % BLOCK_SIZE)
out[t, : len(vals)] = torch.tensor(vals, dtype=out.dtype)
counts[t] = len(vals)
return out, counts
class FakeWrapper:
def __init__(self):
self.plan_args = None
self.run_args = None
self._plan_info: Any = None
self._planned_backend: Any = None
def plan(self, *args, **kwargs):
self.plan_args = (args, kwargs)
def run(self, *args, **kwargs):
q_nope, q_pe, ckv, kpe = args
self.run_args = (q_nope, q_pe, ckv, kpe, kwargs)
return torch.zeros(
q_nope.shape[0], q_nope.shape[1], ckv.shape[-1], dtype=torch.bfloat16
)
class FakeState:
def __init__(self, width, max_tokens=64):
self.kv_indices = torch.zeros(max_tokens * width, dtype=torch.int32)
self.kv_len_arr = torch.zeros(max_tokens, dtype=torch.int32)
self.kv_indptr = torch.zeros(max_tokens + 1, dtype=torch.int32)
self.wrapper = FakeWrapper()
self.plan_calls = []
self.index_topk = 2048
self.index_kpool = 4
self.max_valid = 2051
def plan(self, num_tokens, kv_lens, cam, req_id_per_token):
self.plan_calls.append((num_tokens, kv_lens))
def pack_indices(self, slots):
for row in range(slots.shape[0]):
start, end = self.kv_indptr[row : row + 2].tolist()
self.kv_indices[start:end] = slots[row, : end - start].clamp(min=0)
def make_impl(qk_rope, kv_dtype="fp8_e4m3", num_heads=2, topk_width=TOPK):
impl = object.__new__(FlashInferMLASparseSM90Impl)
impl.num_heads = num_heads
impl.head_size = HEAD + qk_rope
impl.scale = (HEAD + qk_rope) ** -0.5
impl.kv_lora_rank = HEAD
impl.qk_rope_head_dim = qk_rope
impl.kv_cache_dtype = kv_dtype
impl.use_fp8_kv_cache = kv_dtype in ("fp8", "fp8_e4m3")
rows = 4
impl.topk_indices_buffer = torch.full((rows, topk_width), -1, dtype=torch.int32)
return impl, rows
def make_batch(rows, topk_rows, own_blocks):
req_id = torch.tensor([0] * rows, dtype=torch.int32)
block_table = torch.zeros(1, 16, dtype=torch.int32)
block_table[:, 0] = own_blocks[0]
topk = torch.full((rows, TOPK), -1, dtype=torch.int32)
for t, row in enumerate(topk_rows):
topk[t, : len(row)] = torch.tensor(row, dtype=torch.int32)
return SimpleNamespace(
req_id_per_token=req_id, block_table=block_table, block_size=BLOCK_SIZE
)
@pytest.mark.parametrize("qk_rope,kv_dtype", [(0, "fp8_e4m3"), (64, "auto")])
def test_forward_wiring(monkeypatch, qk_rope, kv_dtype):
impl, rows = make_impl(qk_rope, kv_dtype)
state = FakeState(TOPK)
monkeypatch.setattr(
sm90_mod, "triton_convert_req_index_to_global_index", ref_convert
)
# req with context 10 < topk: 8 valid + -1 padding.
topk_rows = [
[7, 3, 1, 9, 0, 2, 5, 8] + [-1] * (TOPK - 8),
[4, 0, 2, 3, 1] + [-1] * (TOPK - 5),
[6, 5, 4] + [-1] * (TOPK - 3),
[2] + [-1] * (TOPK - 1),
]
impl.topk_indices_buffer.copy_(torch.tensor(topk_rows, dtype=torch.int32))
state.kv_indptr[1:5] = torch.tensor([8, 13, 16, 17], dtype=torch.int32)
state.kv_indptr[5:] = 17
meta = make_batch(rows, topk_rows, [3])
meta.state = state
q_nope = torch.randn(rows, impl.num_heads, HEAD)
q_rope = torch.randn(rows, impl.num_heads, qk_rope)
dtype = torch.uint8 if impl.use_fp8_kv_cache else torch.bfloat16
cache = torch.zeros(8, 2, BLOCK_SIZE, impl.head_size, dtype=dtype)[:, 0]
out, lse = impl.forward_mqa(
(q_nope, q_rope), cache, meta, SimpleNamespace(_k_scale_float=0.5)
)
assert lse is None and out.shape == (rows, impl.num_heads, HEAD)
# Reserved buffers carry this step's slots; lengths are NOT refreshed
# here (the builder plans them host-side before capture/replay).
ref_slots, ref_counts = ref_convert(
meta.req_id_per_token,
meta.block_table,
impl.topk_indices_buffer,
BLOCK_STRIDE_ROWS=2 * BLOCK_SIZE,
)
offset = 0
for t in range(rows):
k = int(ref_counts[t])
assert (
state.kv_indices[offset : offset + k].tolist() == ref_slots[t, :k].tolist()
)
offset += k
assert state.plan_calls == []
assert state.wrapper.run_args is not None
q_pe, ckv, kpe, kwargs = state.wrapper.run_args[1:]
assert q_pe.shape == (rows, impl.num_heads, qk_rope)
assert ckv.shape == ((8 - 1) * 2 * BLOCK_SIZE + BLOCK_SIZE, 1, HEAD)
assert kpe.shape[-1] == qk_rope
if impl.use_fp8_kv_cache:
assert kwargs["ckv_scale"] == 0.5 and kwargs["kpe_scale"] == 1.0
else:
assert kwargs == {}
@pytest.mark.parametrize("use_mha", [False, True])
@pytest.mark.parametrize("num_decodes", [0, 1])
def test_builder_plans_only_rows_dispatched_to_mqa(monkeypatch, use_mha, num_decodes):
"""MHA prefill rows must not make the MQA kernel read beyond its query."""
builder = object.__new__(FlashInferMLASparseSM90Builder)
builder._adaptive_verification = False
builder.state = FakeState(TOPK)
builder._attention_layer = SimpleNamespace(_use_sparse_mha=lambda _: use_mha)
metadata = object.__new__(sm90_mod.FlashInferMLASparseSM90Metadata)
metadata.state = None
metadata.req_id_per_token = None
metadata.num_prefills = 1
metadata.num_decode_tokens = num_decodes
monkeypatch.setattr(
sm90_mod.FlashInferMLASparseMetadataBuilder,
"build",
lambda *_args, **_kwargs: metadata,
)
cam = SimpleNamespace(
num_reqs=num_decodes + 1,
query_start_loc_cpu=torch.tensor(
[0, 1, 6] if num_decodes else [0, 5], dtype=torch.int32
),
seq_lens_cpu_upper_bound=torch.tensor(
[1402, 5] if num_decodes else [5], dtype=torch.int32
),
positions=None,
)
result = builder.build(0, cam)
assert result.state is builder.state
expected_lens = [1402] if num_decodes else []
if not use_mha:
expected_lens += [1, 2, 3, 4, 5]
assert builder.state.plan_calls[0][0] == len(expected_lens)
assert builder.state.plan_calls[0][1].tolist() == expected_lens
@pytest.mark.parametrize("kv_dtype", [torch.bfloat16, torch.float8_e4m3fn])
def test_plan_uses_state_params(monkeypatch, kv_dtype):
"""The NoPE/rope dims and scale live on the builder state, not the layer.
Without a device batch layout plan() takes exact per-row KV lengths and
rebuilds the schedule on every call; the indptrs are always full-size
with zero-query padding rows past num_tokens. An fp8 cache plans as
float8_e4m3fn.
"""
wrapper = FakeWrapper()
plan_info = [0] * sm90_mod._PLAN_INFO_LEN
plan_info[sm90_mod._PI_KV_INDPTR] = 64 * 4
wrapper._plan_info = torch.tensor(plan_info)
wrapper._planned_backend = SimpleNamespace(
_int_workspace_buffer=torch.zeros(64, dtype=torch.int32)
)
state = sm90_mod._SM90State.__new__(sm90_mod._SM90State)
state.device = torch.device("cpu")
state.wrapper = wrapper
state.num_heads = 4
state.kv_dtype = kv_dtype
state.kv_lora_rank = HEAD
state.qk_rope_head_dim = 64
state.sm_scale = 576**-0.5
state.max_tokens = 4
state.topk_width = TOPK
state.kv_indices = torch.zeros(4 * TOPK)
state._arange_cpu = torch.arange(5, dtype=torch.int32)
state._qo_cpu = torch.empty(5, dtype=torch.int32)
state._kv_cpu = torch.empty(5, dtype=torch.int32)
state._lens_cpu = torch.full((4,), TOPK, dtype=torch.int32)
state._saved_kv_end = torch.empty(0, dtype=torch.int32)
state.plan(3, torch.tensor([2, 5, 7], dtype=torch.int32), None, None)
assert wrapper.plan_args is not None
args, kwargs = wrapper.plan_args
(qo, kv, indices, kv_len, heads, ckv, kpe, page, causal, scale) = args
assert qo.tolist() == [0, 1, 2, 3, 3] # clamp: rows past 3 have no queries
assert kv.tolist() == [0, 2, 7, 14, 14]
assert kv_len.tolist() == [2, 5, 7, 0]
assert (heads, ckv, kpe, page, causal) == (4, HEAD, 64, 1, False)
assert scale == 576**-0.5
assert kwargs["q_data_type"] == torch.bfloat16
assert kwargs["kv_data_type"] == kv_dtype
# Replanning a smaller batch must clear the previous rows' lengths.
state.plan(1, torch.tensor([TOPK], dtype=torch.int32), None, None)
assert state._kv_cpu.tolist() == [0, TOPK, TOPK, TOPK, TOPK]
assert state._lens_cpu.tolist() == [TOPK, 0, 0, 0]
state.plan(0, torch.empty(0, dtype=torch.int32), None, None)
assert state._kv_cpu.tolist() == [0, 0, 0, 0, 0]
assert state._lens_cpu.tolist() == [0, 0, 0, 0]
@pytest.mark.skipif(not torch.cuda.is_available(), reason="Requires CUDA")
@pytest.mark.parametrize("width", [128, 2048, 2176])
def test_pack_indices_replays_with_updated_offsets(width):
"""Graph replay packs exact prefixes after row lengths and slots change."""
state = sm90_mod._SM90State.__new__(sm90_mod._SM90State)
state.kv_indptr = torch.zeros(5, dtype=torch.int32, device="cuda")
state.kv_indices = torch.full((4 * width,), -99, dtype=torch.int32, device="cuda")
# Exercise a contiguous view with an unaligned starting address.
slots = torch.arange(4 * width + 1, dtype=torch.int32, device="cuda")[1:]
slots = slots.view(4, width)
state.kv_indptr.copy_(torch.tensor([0, 1, 4, 4, 4]))
state.pack_indices(slots)
torch.accelerator.synchronize()
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
state.pack_indices(slots)
for lengths in ([1, 3, 0, 0], [width, 0, 17, width - 1], [0, 0, 0, 0]):
offsets = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()])
state.kv_indptr.copy_(offsets)
state.kv_indices.fill_(-99)
slots.add_(1)
graph.replay()
expected = torch.cat(
[slots[row, :length] for row, length in enumerate(lengths)]
)
torch.testing.assert_close(state.kv_indices[: expected.numel()], expected)
assert (state.kv_indices[expected.numel() :] == -99).all()
@pytest.mark.parametrize("adaptive", [False, True])
def test_kv_lens_host_formula(adaptive):
"""Per-row host lengths: context == position + 1; capped at
index_topk + trailing-pool remainder past the sparse threshold.
Exact (synced) without a host upper bound; with one, a sync-free bound
capped at the largest valid count, which the plan clamps on device.
"""
builder = object.__new__(FlashInferMLASparseSM90Builder)
builder.state = FakeState(TOPK)
builder._adaptive_verification = adaptive
seq_lens = torch.tensor([100, 9, 3000], dtype=torch.int32)
cam = SimpleNamespace(
num_reqs=3,
query_start_loc_cpu=torch.tensor([0, 5, 7, 10], dtype=torch.int32),
seq_lens=seq_lens,
seq_lens_cpu_upper_bound=None,
)
num_rows, lens, exact = builder._kv_lens_host(cam)
assert num_rows == 10 and exact
# req0: positions 95..99 -> ctx 96..100 (all <= 2048: full context)
# req1: positions 7,8 -> ctx 8,9
# req2: positions 2997..2999 -> ctx 2998..3000 (> 2048: topk + ctx%4)
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2050, 2051, 2048]
cam.seq_lens_cpu_upper_bound = seq_lens
num_rows, lens, exact = builder._kv_lens_host(cam)
assert num_rows == 10 and not exact
if adaptive:
# Host query split may differ from the device one: batch-wide bound.
assert lens.tolist() == [2051] * 10
else:
assert lens.tolist() == [96, 97, 98, 99, 100, 8, 9, 2051, 2051, 2051]
def test_kv_lens_host_empty():
builder = object.__new__(FlashInferMLASparseSM90Builder)
cam = SimpleNamespace(
num_reqs=0,
query_start_loc_cpu=torch.tensor([0], dtype=torch.int32),
seq_lens=torch.zeros(0, dtype=torch.int32),
)
num_rows, lens, _ = builder._kv_lens_host(cam)
assert num_rows == 0 and lens.numel() == 0
_NO_KPOOL = object()
@pytest.mark.parametrize(
"spec_dtype,expected_kv_dtype",
[
(torch.bfloat16, torch.bfloat16),
(torch.uint8, torch.float8_e4m3fn),
],
ids=["bf16", "fp8"],
)
@pytest.mark.parametrize(
"index_kpool,prefill_lens",
[
(4, [2048, 2049, 2050, 2051]),
(None, [2048] * 4),
(_NO_KPOOL, [2048] * 4),
],
ids=["kpool4", "kpool_none", "no_kpool_attr"],
)
def test_builder_kpool_from_model_config(
monkeypatch, index_kpool, prefill_lens, spec_dtype, expected_kv_dtype
):
"""The builder took kpool from the KV cache spec, whose tokens_per_state is
1, so the tail pool was never read. The state plans the cache's logical
dtype: uint8 fp8 storage becomes float8_e4m3fn."""
monkeypatch.setattr(
sm90_mod.FlashInferMLASparseMetadataBuilder,
"__init__",
lambda *_args, **_kwargs: None,
)
class _RecordingState:
def __init__(self, *args, **kwargs):
self.kv_dtype = args[2]
self.index_topk = kwargs["index_topk"]
self.index_kpool = kwargs["index_kpool"]
monkeypatch.setattr(sm90_mod, "_SM90State", _RecordingState)
impl, _ = make_impl(64)
spec = MLAAttentionSpec(
block_size=BLOCK_SIZE, num_kv_heads=1, head_size=576, dtype=spec_dtype
)
assert spec.tokens_per_state == 1
hf_config = SimpleNamespace(index_topk=2048)
if index_kpool is not _NO_KPOOL:
hf_config.index_kpool = index_kpool
vllm_config = SimpleNamespace(
compilation_config=SimpleNamespace(
static_forward_context={"attn": SimpleNamespace(impl=impl)}
),
scheduler_config=SimpleNamespace(
max_num_batched_tokens=64, async_scheduling=False
),
model_config=SimpleNamespace(hf_text_config=hf_config),
speculative_config=None,
)
builder = FlashInferMLASparseSM90Builder(
spec, ["attn"], vllm_config, torch.device("cpu")
)
assert builder.state.kv_dtype == expected_kv_dtype
# req0: prefill chunk ending at context 42295; req1: context <= topk.
cam = SimpleNamespace(
num_reqs=2,
query_start_loc_cpu=torch.tensor([0, 4, 6], dtype=torch.int32),
seq_lens=torch.tensor([42295, 100], dtype=torch.int32),
seq_lens_cpu_upper_bound=None,
)
num_rows, lens, exact = builder._kv_lens_host(cam)
assert num_rows == 6 and exact
assert lens.tolist() == prefill_lens + [99, 100]
def _sm90_flashinfer_available():
return (
torch.cuda.is_available()
and torch.cuda.get_device_capability()[0] == 9
and sm90_mod.has_flashinfer_sm90_nope_mla()
)
SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH = 16, 2048, 4, 2176
def _real_state(rows):
return sm90_mod._SM90State(
torch.device("cuda"),
SM90_HEADS,
torch.bfloat16,
rows,
SM90_WIDTH,
HEAD,
0,
HEAD**-0.5,
SM90_TOPK,
SM90_KPOOL,
)
def _clamp_batch(num_reqs, q_per_req, lo, hi, topk, kpool, width):
"""Random batch: per-row contexts, device layout, and top-k slots."""
last = torch.randint(lo + q_per_req, hi, (num_reqs,))
ctx = (last[:, None] + torch.arange(1 - q_per_req, 1)).reshape(-1)
valid = torch.where(ctx <= topk, ctx, topk + ctx % kpool)
cam = SimpleNamespace(
seq_lens=last.to(torch.int32).cuda(),
query_start_loc=(torch.arange(num_reqs + 1) * q_per_req).to(torch.int32).cuda(),
)
req_id = torch.arange(num_reqs, dtype=torch.int32).repeat_interleave(q_per_req)
slots = torch.randint(0, 1 << 16, (ctx.numel(), width), dtype=torch.int32)
slots[torch.arange(width) >= valid[:, None]] = -1
return ctx, valid.to(torch.int32), cam, req_id.cuda(), slots.cuda()
@pytest.mark.skipif(
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
)
@pytest.mark.parametrize(
"num_reqs,q_per_req,lo,hi",
[
(64, 1, 1, 3000),
(16, 6, 2030, 2070), # MTP-style rows straddling index_topk
(4096, 1, 1, 3000), # clamp spans several program blocks
],
)
def test_upper_bound_plan_matches_exact(num_reqs, q_per_req, lo, hi):
"""Sync-free planning from optimistic host bounds (async spec decode)
must match exact planning: the device clamp trims every work item back
to its row's valid count, so no -1 slot is read."""
torch.manual_seed(0)
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
ctx, valid, cam, req_id, slots = _clamp_batch(
num_reqs, q_per_req, lo, hi, topk, kpool, width
)
rows = ctx.numel()
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
q_pe = q.new_empty(rows, heads, 0)
def run(state):
state.pack_indices(slots)
return state.wrapper.run(q, q_pe, kv, kv[..., :0])
exact = _real_state(rows)
exact.plan(rows, valid, None, None)
ub = _real_state(rows)
host_bound = torch.clamp(ctx + torch.randint(0, 7, (rows,)), max=ub.max_valid)
ub.plan(rows, host_bound, cam, req_id)
out = run(ub)
assert not out.isnan().any()
torch.testing.assert_close(out, run(exact), atol=1e-2, rtol=1e-2)
@pytest.mark.skipif(
not _sm90_flashinfer_available(), reason="Requires SM90 FlashInfer MLA"
)
def test_upper_bound_plan_reused_across_steps(monkeypatch):
"""Growing contexts (draft/decode steps) reuse the padded plan and only
re-clamp on device, matching an exact replan every step."""
torch.manual_seed(0)
heads, topk, kpool, width = SM90_HEADS, SM90_TOPK, SM90_KPOOL, SM90_WIDTH
rows = 48
ctx, _, _, req_id, _ = _clamp_batch(rows, 1, 1, 3000, topk, kpool, width)
exact, ub = _real_state(rows), _real_state(rows)
replans: list[int] = []
plan_fn = ub._plan
def counting_plan(num_tokens, kv_lens):
replans.append(num_tokens)
plan_fn(num_tokens, kv_lens)
monkeypatch.setattr(ub, "_plan", counting_plan)
kv = torch.randn(1 << 16, 1, HEAD, device="cuda", dtype=torch.bfloat16)
for step in range(5):
step_ctx = ctx + step
valid = torch.where(step_ctx <= topk, step_ctx, topk + step_ctx % kpool)
slots = torch.randint(0, 1 << 16, (rows, width), dtype=torch.int32)
slots[torch.arange(width) >= valid[:, None]] = -1
slots = slots.cuda()
cam = SimpleNamespace(
seq_lens=step_ctx.to(torch.int32).cuda(),
query_start_loc=torch.arange(rows + 1, dtype=torch.int32).cuda(),
)
num_plans = len(replans)
ub.plan(rows, torch.clamp(step_ctx + 5, max=ub.max_valid), cam, req_id)
assert len(replans) - num_plans == (1 if step == 0 else 0)
exact.plan(rows, valid.to(torch.int32), None, None)
q = torch.randn(rows, heads, HEAD, device="cuda", dtype=torch.bfloat16)
outs = []
for state in (ub, exact):
state.pack_indices(slots)
outs.append(state.wrapper.run(q, q[..., :0], kv, kv[..., :0]))
torch.testing.assert_close(outs[0], outs[1], atol=1e-2, rtol=1e-2)
def test_supports_combination_gates(monkeypatch, default_vllm_config):
monkeypatch.setattr(sm90_mod, "has_flashinfer_sm90_nope_mla", lambda: True)
call = lambda **kw: FlashInferMLASparseSM90Backend.supports_combination(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="fp8_e4m3",
block_size=64,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
device_capability=SimpleNamespace(major=9),
**kw,
)
assert call() is None # no model config: only the feature gate applies
import vllm.config as cfg
monkeypatch.setattr(
cfg,
"get_current_vllm_config",
lambda: SimpleNamespace(model_config=None),
)
assert call() is None
monkeypatch.setattr(sm90_mod, "has_flashinfer_sm90_nope_mla", lambda: False)
assert "requires FlashInfer" in (call() or "")
@@ -1,94 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Behavior checks for FlashInfer SM120 sparse MLA backend selection."""
from types import SimpleNamespace
import torch
from vllm.config import set_current_vllm_config
from vllm.models.deepseek_v4.nvidia.flashinfer_sparse import (
_required_sm120_sparse_topk,
)
from vllm.platforms.interface import DeviceCapability
from vllm.utils import flashinfer as fi_utils
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
FlashInferMLASparseSM120Backend,
)
from vllm.v1.attention.backends.registry import AttentionBackendEnum
def _fake_vllm_config(model_type: str) -> SimpleNamespace:
return SimpleNamespace(
model_config=SimpleNamespace(
hf_text_config=SimpleNamespace(model_type=model_type, index_topk=2048),
),
)
def test_sm120_backend_uses_dedicated_backend_name() -> None:
assert FlashInferMLASparseSM120Backend.get_name() == "FLASHINFER_MLA_SPARSE_SM120"
assert (
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM120.get_class()
is FlashInferMLASparseSM120Backend
)
def test_sm120_backend_uses_sparse_mqa_for_prefill() -> None:
impl_cls = FlashInferMLASparseSM120Backend.get_impl_cls()
assert impl_cls.is_sparse
assert not impl_cls.supports_dense_mha_prefill
def test_v32_glm_sm120_backend_accepts_glm_block_size(
monkeypatch,
) -> None:
monkeypatch.setattr(fi_utils, "has_flashinfer_sparse_mla_sm120", lambda: True)
with set_current_vllm_config(_fake_vllm_config("glm4_moe")):
invalid_reasons = FlashInferMLASparseSM120Backend.validate_configuration(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
block_size=256,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
use_per_head_quant_scales=False,
device_capability=DeviceCapability(12, 0),
attn_type="decoder",
)
assert invalid_reasons == []
def test_sm120_dsv4_capability_checks_exact_dispatch_shape(monkeypatch) -> None:
fake_module = SimpleNamespace(
_DECODE_DSV4_DISPATCH=frozenset({(32, 128), (32, 192)})
)
monkeypatch.setattr(fi_utils, "has_flashinfer_sparse_mla_sm120", lambda: True)
monkeypatch.setattr(fi_utils, "_get_submodule", lambda _name: fake_module)
fi_utils.has_flashinfer_sparse_mla_sm120_config.cache_clear()
assert fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 128)
assert fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 192)
assert not fi_utils.has_flashinfer_sparse_mla_sm120_config(32, 256)
assert not fi_utils.has_flashinfer_sparse_mla_sm120_config(16, 192)
fi_utils.has_flashinfer_sparse_mla_sm120_config.cache_clear()
def test_sm120_dsv4_required_topk_tracks_dspark_width() -> None:
causal = SimpleNamespace(
attention_config=SimpleNamespace(use_non_causal=False),
speculative_config=SimpleNamespace(num_speculative_tokens=5),
)
dspark = SimpleNamespace(
attention_config=SimpleNamespace(use_non_causal=True),
speculative_config=SimpleNamespace(num_speculative_tokens=5),
)
assert _required_sm120_sparse_topk(causal, 128) == 128
assert _required_sm120_sparse_topk(dspark, 128) == 192
@@ -1,166 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU-only tests for FlashInfer sparse MLA backend constraints."""
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from vllm.v1.attention.backends.mla.flashinfer_mla_sparse import (
_DEFAULT_WORKSPACE_BUFFER_SIZE,
FlashInferMLASparseTRTLLMBackend,
_required_workspace_bytes,
compute_trtllm_sparse_mla_workspace_bytes,
)
# Reporter config from vllm#50781: GLM-5.2 (64 q heads), TP=8, DCP=8,
# max_num_batched_tokens=16384, FlashInfer 0.6.14.
_REPORTER_HEADS_PER_RANK = 64 // 8
_REPORTER_DCP = 8
_REPORTER_MAX_TOKENS = 16384
# From the reported crash: trtllm-gen requested exactly this many bytes for
# trtllm_gen_softmax_workspace after an 8 MiB counter carve had left
# 404,750,336 of the 413,138,944-byte default buffer.
_REPORTER_OBSERVED_SOFTMAX_BYTES = 1_611_661_312
_REPORTER_OBSERVED_PRECARVE_BYTES = 8_388_608
def test_reporter_softmax_carve_is_reproduced_byte_exactly():
# The crashing step scheduled 12288 tokens (a single 12K-token request);
# the softmax slab formula must reproduce the kernel's request exactly:
# 8 * (8 heads/rank * 8 dcp) * 12288 tokens * 256 + 1 MiB guard.
softmax_bytes = compute_trtllm_sparse_mla_workspace_bytes(
base_workspace_bytes=0,
dcp_world_size=_REPORTER_DCP,
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
max_num_batched_tokens=12288,
)
assert softmax_bytes == _REPORTER_OBSERVED_SOFTMAX_BYTES
def test_reporter_config_covers_observed_overflow():
computed = compute_trtllm_sparse_mla_workspace_bytes(
base_workspace_bytes=_DEFAULT_WORKSPACE_BUFFER_SIZE,
dcp_world_size=_REPORTER_DCP,
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
)
assert computed >= (
_REPORTER_OBSERVED_SOFTMAX_BYTES + _REPORTER_OBSERVED_PRECARVE_BYTES
)
def test_non_dcp_size_is_unchanged():
computed = compute_trtllm_sparse_mla_workspace_bytes(
base_workspace_bytes=_DEFAULT_WORKSPACE_BUFFER_SIZE,
dcp_world_size=1,
num_heads_per_rank=128,
max_num_batched_tokens=65536,
)
assert computed == _DEFAULT_WORKSPACE_BUFFER_SIZE
def test_combined_pcp_dcp_rejects_flashinfer_sparse():
config = SimpleNamespace(
parallel_config=SimpleNamespace(
prefill_context_parallel_size=4,
decode_context_parallel_size=4,
),
model_config=None,
)
with patch("vllm.config.get_current_vllm_config", return_value=config):
reason = FlashInferMLASparseTRTLLMBackend.supports_combination(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
block_size=64,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
device_capability=SimpleNamespace(major=10),
)
assert reason is not None
assert "use FLASHMLA_SPARSE" in reason
@pytest.mark.parametrize("pcp_size,dcp_size", [(4, 1), (1, 4)])
def test_single_context_parallel_mode_allows_flashinfer_sparse(
pcp_size: int, dcp_size: int
):
config = SimpleNamespace(
parallel_config=SimpleNamespace(
prefill_context_parallel_size=pcp_size,
decode_context_parallel_size=dcp_size,
),
model_config=None,
)
with patch("vllm.config.get_current_vllm_config", return_value=config):
reason = FlashInferMLASparseTRTLLMBackend.supports_combination(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="fp8",
block_size=64,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
device_capability=SimpleNamespace(major=10),
)
assert reason is None
def test_default_constant_matches_envs_default(monkeypatch):
from vllm import envs
monkeypatch.delenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", raising=False)
assert _DEFAULT_WORKSPACE_BUFFER_SIZE == envs.VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE
def test_env_unset_returns_computed(monkeypatch):
monkeypatch.delenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", raising=False)
required = _required_workspace_bytes(
dcp_world_size=_REPORTER_DCP,
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
)
assert required == compute_trtllm_sparse_mla_workspace_bytes(
_DEFAULT_WORKSPACE_BUFFER_SIZE,
_REPORTER_DCP,
_REPORTER_HEADS_PER_RANK,
_REPORTER_MAX_TOKENS,
)
def test_env_override_below_computed_is_respected_with_warning(monkeypatch):
override = 100 * 1024 * 1024
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", str(override))
with patch(
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse.logger"
) as mock_logger:
required = _required_workspace_bytes(
dcp_world_size=_REPORTER_DCP,
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
)
assert required == override
mock_logger.warning_once.assert_called_once()
def test_env_override_above_computed_is_respected_without_warning(monkeypatch):
override = 8 * 1024 * 1024 * 1024
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", str(override))
with patch(
"vllm.v1.attention.backends.mla.flashinfer_mla_sparse.logger"
) as mock_logger:
required = _required_workspace_bytes(
dcp_world_size=_REPORTER_DCP,
num_heads_per_rank=_REPORTER_HEADS_PER_RANK,
max_num_batched_tokens=_REPORTER_MAX_TOKENS,
)
assert required == override
mock_logger.warning_once.assert_not_called()
@@ -1,312 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU tests for the FlashMLA sparse backend NoPE-512 (GLM5Next) gates.
GLM5Next is rope-free MLA: qk_nope_head_dim=256, qk_rope_head_dim=0,
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 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.
"""
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,
FlashMLASparseBackend,
_fp8_kv_pages,
)
from vllm.v1.kv_cache_interface import (
KVCacheConfig,
KVCacheGroupSpec,
KVCacheLayout,
KVCacheTensor,
KVQuantMode,
MLAAttentionSpec,
)
from vllm.v1.worker.utils import (
AttentionGroup,
allocate_kv_cache,
prepare_kernel_block_sizes,
select_common_block_size,
)
SM90 = DeviceCapability(major=9, minor=0)
SM100 = DeviceCapability(major=10, minor=0)
BF16_CACHE_DTYPES = (None, "auto", "bfloat16", "float16")
NOPE_SM90_CACHE_DTYPES = (*BF16_CACHE_DTYPES, "fp8_ds_mla")
def _supports_combination(head_size, kv_cache_dtype, capability):
return FlashMLASparseBackend.supports_combination(
head_size,
torch.bfloat16,
kv_cache_dtype,
64,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
device_capability=capability,
)
@pytest.fixture
def rope_free_model(monkeypatch):
"""Patch get_current_vllm_config so the model looks like GLM5Next NoPE."""
import vllm.config as cfg
monkeypatch.setattr(
cfg,
"get_current_vllm_config",
lambda: SimpleNamespace(
model_config=SimpleNamespace(
hf_text_config=SimpleNamespace(qk_rope_head_dim=0)
)
),
)
@pytest.fixture
def rope_carrying_model(monkeypatch):
"""Patch get_current_vllm_config with a rope-carrying (576-style) model."""
import vllm.config as cfg
monkeypatch.setattr(
cfg,
"get_current_vllm_config",
lambda: SimpleNamespace(
model_config=SimpleNamespace(
hf_text_config=SimpleNamespace(qk_rope_head_dim=64)
)
),
)
def test_supported_head_sizes_include_512():
assert FlashMLASparseBackend.get_supported_head_sizes() == [576, 512]
def test_flashmla_bf16_nope_accepts_packed_manager_blocks():
spec = MLAAttentionSpec(
block_size=1152,
num_kv_heads=1,
head_size=512,
dtype=torch.bfloat16,
cache_dtype_str="bfloat16",
block_stride_alignment=1024,
)
num_blocks = 2
layers = ["layer.0", "layer.1"]
page_size = spec.page_size_bytes
config = KVCacheConfig(
num_blocks=num_blocks,
kv_cache_tensors=[
KVCacheTensor(
size=num_blocks * len(layers) * page_size,
layers=layers,
layer_stride=page_size,
block_stride=len(layers) * page_size,
)
],
kv_cache_groups=[KVCacheGroupSpec(layers, spec)],
)
groups = [[AttentionGroup(FlashMLASparseBackend, layers, spec, 0)]]
kernel_block_sizes = prepare_kernel_block_sizes(config, groups)
caches = allocate_kv_cache(
config,
torch.device("cpu"),
KVCacheLayout.BLHNC,
kernel_block_sizes,
)
assert kernel_block_sizes == [1152]
assert caches["layer.0"].shape == (num_blocks, 1, 1152, 512)
@pytest.mark.parametrize("sm100", [False, True])
def test_flashmla_quantized_cache_kernel_pages(monkeypatch, sm100):
"""Quantized blocks are read as 64-token pages; SM100 only row-aligns them
(TMA) and keeps 64-token blocks."""
monkeypatch.setattr(
current_platform,
"is_device_capability_family",
lambda family, device_id=0: sm100 and family == 100,
)
spec = MLAAttentionSpec(
block_size=1152,
num_kv_heads=1,
head_size=576,
dtype=torch.float8_e4m3fn,
cache_dtype_str="fp8_ds_mla",
kv_quant_mode=KVQuantMode.FP8_PER_TENSOR,
state_content_bytes=656,
)
kernel_block_size = 64 if sm100 else 1152
assert (
select_common_block_size(1152, [FlashMLASparseBackend], [spec])
== kernel_block_size
)
def test_fp8_kv_pages_address_packed_blocks():
"""Token t of block b is row b * block_stride_rows + t of the 64-row pages;
64-token blocks are passed through."""
row, block_size, stride_rows = 656, 128, 192
backing = torch.arange(3 * stride_rows).repeat_interleave(row)
cache = backing.view(3, stride_rows, row)[:, :block_size]
pages, block_stride_rows = _fp8_kv_pages(cache, block_size)
assert block_stride_rows == stride_rows
assert pages.shape[1:] == (64, row)
slot = 2 * block_stride_rows + 100
assert torch.equal(pages[slot // 64, slot % 64], cache[2, 100])
pages, block_stride_rows = _fp8_kv_pages(cache[:, :64], 64)
assert block_stride_rows is None
assert torch.equal(pages, cache[:, :64])
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", 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", 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", 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", "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
@pytest.mark.parametrize("capability", [SM90, SM100], ids=["sm90", "sm100"])
@pytest.mark.parametrize(
"kv_cache_dtype",
("auto", "bfloat16", "fp8", "fp8_ds_mla", "nvfp4_ds_mla"),
)
def test_576_unchanged_for_all_dtypes(kv_cache_dtype, capability):
# DeepSeek 576 must be untouched by the NoPE-512 gates, except for the
# pre-existing SM100-only nvfp4 rule.
reason = _supports_combination(576, kv_cache_dtype, capability)
if kv_cache_dtype == "nvfp4_ds_mla" and capability.major != 10:
assert reason is not None and "SM100" in reason
else:
assert reason is None, reason
def _sparse_order(kv_cache_dtype, head_size, num_heads=32, capability=SM100):
try:
from vllm.platforms.cuda import _get_backend_priorities
except ImportError as e: # pragma: no cover - depends on host
pytest.skip(f"CUDA platform unavailable on this host: {e}")
priorities = _get_backend_priorities(
use_mla=True,
device_capability=capability,
num_heads=num_heads,
kv_cache_dtype=kv_cache_dtype,
head_size=head_size,
)
sparse = {
"FLASH_ATTN_MLA_SPARSE",
"FLASH_ATTN_MLA_SPARSE_FA4",
"FLASHMLA_SPARSE",
"FLASHINFER_MLA_SPARSE",
"FLASHINFER_MLA_SPARSE_SM90",
}
return [b.name for b in priorities if b.name in sparse]
@pytest.mark.parametrize("num_heads", [32, 64], ids=["tp2", "tp1"])
def test_sm100_bf16_512_priority_unchanged(num_heads):
"""Adding head_size 512 must not reorder the SM100 bf16 sparse list.
On SM100 with >16 heads the hardcoded bf16 order is
[FLASHMLA_SPARSE, FLASHINFER_MLA_SPARSE] (FlashMLA first). head_size 512
must leave this untouched (identical to the 576 order); the guard that
keeps bf16-512 from *serving* through FlashMLA on SM100 lives in
supports_combination (gated to SM90), tested separately.
"""
order512 = _sparse_order("auto", 512, num_heads=num_heads)
order576 = _sparse_order("auto", 576, num_heads=num_heads)
assert order512 == order576, order512
assert order512[0] == "FLASHMLA_SPARSE", order512
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
@pytest.mark.skipif(not current_platform.is_cuda(), reason="Requires CUDA backends")
def test_sm100_576_bf16_low_heads_falls_back_from_fa4(monkeypatch):
"""With FA4 unusable, low-head bf16 selection lands on FlashInfer."""
import vllm.v1.attention.backends.mla.flashattn_mla_sparse as fa4_sparse
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.v1.attention.backends.registry import AttentionBackendEnum
monkeypatch.setattr(fa4_sparse, "_fa4_cute_mla_available", lambda: "no FA4")
def reasons(name):
backend_cls = AttentionBackendEnum[name].get_class()
return backend_cls.validate_configuration(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
block_size=64,
use_mla=True,
has_sink=False,
use_sparse=True,
use_mm_prefix=False,
use_per_head_quant_scales=False,
device_capability=SM100,
attn_type="decoder",
)
order = _sparse_order("auto", 576, num_heads=16)
with set_current_vllm_config(VllmConfig()):
# The selector takes the first candidate with no rejection reasons.
selected = next(name for name in order if not reasons(name))
assert order[0] == "FLASH_ATTN_MLA_SPARSE_FA4", order
assert selected == "FLASHINFER_MLA_SPARSE"
@@ -1,40 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GLM-5.3-Flash indexer kernel block sizes are DeepGEMM pool pages."""
from types import SimpleNamespace
import pytest
from vllm.platforms import current_platform
from vllm.v1.attention.backends.mla import indexer
from vllm.v1.attention.backends.mla.indexer import Glm5NextIndexerBackend
KPOOL = 4
@pytest.mark.parametrize(
"rocm,sm120,expected",
[
(False, False, [KPOOL * 32, KPOOL * 64]),
# SM120 DeepGEMM takes only 64-entry pages for the fp8 cache.
(False, True, [KPOOL * 64]),
# ROCm's AITER paged-MQA logits take the same pool pages.
(True, False, [KPOOL * 32, KPOOL * 64]),
],
)
def test_glm5next_indexer_kernel_block_sizes(monkeypatch, rocm, sm120, expected):
monkeypatch.setattr(current_platform, "is_rocm", lambda: rocm)
monkeypatch.setattr(
current_platform,
"is_device_capability_family",
lambda family: sm120 and family == 120,
)
model_config = SimpleNamespace(hf_text_config=SimpleNamespace(index_kpool=KPOOL))
config = SimpleNamespace(model_config=model_config)
monkeypatch.setattr(indexer, "get_current_vllm_config", lambda: config)
spec = SimpleNamespace(tokens_per_state=KPOOL)
assert Glm5NextIndexerBackend.get_supported_kernel_block_sizes(spec) == expected
# Platform block-size selection queries without a spec.
assert Glm5NextIndexerBackend.get_supported_kernel_block_sizes() == expected
@@ -1,131 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Attention metadata geometry must come from the builder's own group."""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.attention.backends.cpu_attn import (
CPUAttentionBackendImpl,
CPUAttentionMetadataBuilder,
)
from vllm.v1.attention.backends.flash_attn import FlashAttentionMetadataBuilder
requires_cpu = pytest.mark.skipif(
not current_platform.is_cpu(), reason="CPU attention backend"
)
# Laguna's shape: 48 query heads model-wide, 64 on its sliding layers, both
# against 8 KV heads.
MODEL_WIDE_NUM_HEADS = 48
NUM_KV_HEADS = 8
def _layers(layer_num_heads: list[int]):
"""Stand-in attention layers, one per head count, as one attention group."""
return {
f"layer_{i}": SimpleNamespace(
impl=MagicMock(
spec=CPUAttentionBackendImpl,
num_heads=num_heads,
sliding_window=None,
)
)
for i, num_heads in enumerate(layer_num_heads)
}
def _build(layer_num_heads: list[int]) -> CPUAttentionMetadataBuilder:
layers = _layers(layer_num_heads)
vllm_config = MagicMock()
vllm_config.model_config.dtype = torch.bfloat16
vllm_config.model_config.get_num_attention_heads.return_value = MODEL_WIDE_NUM_HEADS
vllm_config.cache_config.cache_dtype = "auto"
kv_cache_spec = SimpleNamespace(
num_kv_heads=NUM_KV_HEADS, head_size=64, block_size=16
)
with (
patch(
"vllm.v1.attention.backends.utils.get_layers_from_vllm_config",
return_value=layers,
),
patch(
"vllm.v1.attention.backends.cpu_attn.get_layers_from_vllm_config",
return_value=layers,
),
):
return CPUAttentionMetadataBuilder(
kv_cache_spec=kv_cache_spec,
layer_names=list(layers),
vllm_config=vllm_config,
device=torch.device("cpu"),
)
@requires_cpu
@pytest.mark.parametrize("group_num_heads", [MODEL_WIDE_NUM_HEADS, 64, 16])
def test_num_heads_comes_from_the_group(group_num_heads):
"""The group's own count wins, even when it is not the model-wide one."""
builder = _build([group_num_heads, group_num_heads])
assert builder.num_heads == group_num_heads
@requires_cpu
def test_mixed_head_counts_in_one_group_are_rejected():
"""Grouping guarantees uniformity; a mixed group means that broke."""
with pytest.raises(AssertionError, match="share num_heads"):
_build([MODEL_WIDE_NUM_HEADS, 64])
def test_flash_attention_geometry_comes_from_the_group():
"""FA3 must use group geometry for layers without an ``impl`` wrapper."""
layers = {f"layer_{i}": SimpleNamespace(num_heads=16) for i in range(2)}
vllm_config = MagicMock()
vllm_config.model_config.get_num_attention_heads.return_value = MODEL_WIDE_NUM_HEADS
vllm_config.model_config.get_num_kv_heads.return_value = NUM_KV_HEADS
vllm_config.model_config.get_head_size.return_value = 128
vllm_config.model_config.rswa_window = None
vllm_config.model_config.is_mm_prefix_lm = False
vllm_config.parallel_config.cp_kv_cache_interleave_size = 1
vllm_config.compilation_config.cudagraph_mode.has_full_cudagraphs.return_value = (
False
)
vllm_config.compilation_config.max_cudagraph_capture_size = None
kv_cache_spec = SimpleNamespace(
block_size=16,
num_kv_heads=2,
head_size=64,
dtype=torch.bfloat16,
dcp_sharded=True,
)
with (
patch(
"vllm.v1.attention.backends.utils.get_layers_from_vllm_config",
return_value=layers,
),
patch(
"vllm.distributed.parallel_state.get_dcp_group",
side_effect=AssertionError,
),
patch(
"vllm.v1.attention.backends.flash_attn.get_flash_attn_version",
return_value=3,
),
):
builder = FlashAttentionMetadataBuilder(
kv_cache_spec=kv_cache_spec,
layer_names=list(layers),
vllm_config=vllm_config,
device=torch.device("cpu"),
)
assert builder.aot_schedule
assert builder.num_heads_q == 16
assert builder.num_heads_kv == 2
assert builder.headdim == 64
@@ -1,48 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""A KV cache group may hold both windowed and global layers — e.g. Gemma-3 with
the hybrid KV cache manager disabled, where the sliding-window layers are
promoted to full-attention *storage* and merged into one group whose spec still
records the window. Backends must take the window from the layers, never from
that group spec, or the global layers get windowed too and silently lose access
to everything older than the window.
"""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from vllm.v1.attention.backends.cpu_attn import (
CPUAttentionBackendImpl,
CPUAttentionMetadataBuilder,
)
def _layers(layer_windows: list[int]):
"""Stand-in attention layers, one per window, as one KV cache group."""
return {
f"layer_{i}": SimpleNamespace(
impl=MagicMock(spec=CPUAttentionBackendImpl, sliding_window=window)
)
for i, window in enumerate(layer_windows)
}
@pytest.mark.parametrize(
"layer_windows,expected",
[
([512, 512], 512), # uniform sliding window -> shared by the group
([-1, -1], -1), # all global -> no window
([512, -1], -1), # mixed -> the group cannot assume either window
],
)
def test_cpu_group_sliding_window(layer_windows, expected):
layers = _layers(layer_windows)
builder = SimpleNamespace(vllm_config=None, layer_names=list(layers))
with patch(
"vllm.v1.attention.backends.cpu_attn.get_layers_from_vllm_config",
return_value=layers,
):
window = CPUAttentionMetadataBuilder._group_sliding_window(builder)
assert window == expected
File diff suppressed because it is too large Load Diff
@@ -1,665 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from tests.v1.attention.utils import create_vllm_config
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonMetadataBuilder,
)
from vllm.models.deepseek_v4.sparse_mla import DeepseekV4SparseMLABackend
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4SparseMLABackend as DeepseekV41SparseMLABackend,
)
from vllm.utils.deep_gemm import mqa_logits_use_mx_scales
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla import indexer as indexer_module
from vllm.v1.attention.backends.mla.compressor_utils import (
CompressedSlotMappingKernel,
get_compressed_slot_mapping,
)
from vllm.v1.attention.backends.mla.indexer import (
BuildPrefillChunkMetadataKernel,
DeepseekV4IndexerBackend,
DeepSeekV32IndexerDecodeMetadata,
DeepseekV32IndexerMetadata,
DeepseekV32IndexerMetadataBuilder,
DeepseekV41IndexerBackend,
get_max_prefill_buffer_size,
)
from vllm.v1.attention.backends.mla.sparse_utils import (
ConvertReqIndexToGlobalIndexKernel,
)
from vllm.v1.kv_cache_interface import (
MLAAttentionSpec,
compute_layer_kv_cache_shape_bytes,
)
from vllm.v1.worker.block_table import get_block_table_width
from vllm.v1.worker.utils import select_common_block_size
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("query_lens", [[1], [6] * 16, [0, 2, 6, 0, 4], [0, 0, 0]])
@pytest.mark.parametrize("padding", [0, 17])
def test_fused_indexer_decode_metadata(query_lens, padding):
"""Flatten device query boundaries and clear graph padding on every replay."""
from vllm.v1.attention.ops.metadata import _indexer_decode_metadata_kernel
device = "cuda"
lengths = torch.tensor(query_lens, device=device, dtype=torch.int32)
qsl = torch.cat(
[torch.zeros(1, device=device, dtype=torch.int32), lengths.cumsum(0).int()]
)
reqs = len(query_lens)
n = sum(query_lens)
tokens = n + padding
capacity = max(tokens, reqs) + 31
seq = lengths + 4096
# Exercise block-table row padding and masked columns.
bt = torch.arange(reqs * 74, device=device, dtype=torch.int32).view(reqs, 74)[
:, :65
]
out_bt = torch.full((capacity, 69), -99, device=device, dtype=torch.int32)
outputs = [
torch.full((capacity,), -99, device=device, dtype=torch.int32) for _ in range(4)
]
out_seq, out_lens, indices, per_req = outputs
grid = max(reqs, tokens + (capacity - tokens + 255) // 256)
_indexer_decode_metadata_kernel[(grid,)](
qsl,
seq,
bt,
out_seq,
out_bt,
out_lens,
indices,
per_req,
reqs,
tokens,
capacity,
bt.stride(0),
out_bt.stride(0),
BLOCK_COLS=bt.shape[1],
num_warps=4,
)
expected_req = torch.repeat_interleave(torch.arange(reqs, device=device), lengths)
expected_seq = torch.cat(
[torch.arange(4097, 4097 + q, device=device) for q in query_lens]
)
torch.testing.assert_close(out_seq[:n], expected_seq.int(), rtol=0, atol=0)
assert torch.count_nonzero(out_seq[n:]) == 0
torch.testing.assert_close(out_bt[:n, :65], bt[expected_req], rtol=0, atol=0)
assert torch.count_nonzero(out_bt[n:tokens, :65]) == 0
torch.testing.assert_close(indices[:n], expected_req.int(), rtol=0, atol=0)
torch.testing.assert_close(
indices[n:tokens],
torch.arange(reqs, reqs + padding, device=device, dtype=torch.int32),
)
assert torch.all(out_lens[:tokens] == 1)
torch.testing.assert_close(per_req[:reqs], lengths)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_indexer_draft_decode_metadata_update_is_capture_safe():
if not indexer_module.has_deep_gemm():
pytest.skip("requires DeepGEMM")
device = torch.device("cuda")
num_reqs = 3
seq_lens = torch.tensor([17, 33, 65], dtype=torch.int32, device=device)
decode_seq_lens = torch.zeros((num_reqs, 1), dtype=torch.int32, device=device)
block_table = torch.arange(num_reqs * 4, dtype=torch.int32, device=device).view(
num_reqs, 4
)
num_sms = torch.cuda.get_device_properties(device).multi_processor_count
# SM100's paged MQA logits only take varlen rows.
indices = (
torch.arange(num_reqs, dtype=torch.int32, device=device)
if mqa_logits_use_mx_scales()
else None
)
schedule_metadata = indexer_module.get_paged_mqa_logits_metadata(
torch.div(seq_lens, 16, rounding_mode="floor").unsqueeze(1),
64,
num_sms,
indices=indices,
).clone()
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.dcp_world_size = 1
builder.compress_ratio = 16
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)
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=DeepSeekV32IndexerDecodeMetadata(
block_table=block_table,
seq_lens=decode_seq_lens,
decode_lens=torch.zeros(num_reqs, dtype=torch.int32, device=device),
requires_padding=False,
schedule_metadata=schedule_metadata,
indices=indices,
),
block_table=block_table,
)
builder.update_draft_decode_metadata(metadata)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
builder.update_draft_decode_metadata(metadata)
seq_lens.copy_(torch.tensor([32, 48, 80], dtype=torch.int32, device=device))
graph.replay()
torch.accelerator.synchronize()
expected_decode_seq_lens = torch.div(seq_lens, 16, rounding_mode="floor")
torch.testing.assert_close(decode_seq_lens.flatten(), expected_decode_seq_lens)
torch.testing.assert_close(
schedule_metadata,
indexer_module.get_paged_mqa_logits_metadata(
expected_decode_seq_lens.unsqueeze(1), 64, num_sms, indices=indices
),
)
assert metadata.decode is not None
assert torch.all(metadata.decode.decode_lens == 1)
expected_slot_mapping = block_table[:, 0].to(torch.int64) * 64 + torch.tensor(
[1, 2, 4], dtype=torch.int64, device=device
)
torch.testing.assert_close(metadata.slot_mapping, expected_slot_mapping)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
@pytest.mark.parametrize("compress_ratio", [1, 4])
def test_indexer_draft_decode_refresh_follows_new_batch(monkeypatch, 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
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.dcp_world_size = 1
builder.compress_ratio = compress_ratio
builder.arange_buffer = torch.arange(num_reqs + 1, dtype=torch.int32, device=device)
builder.kv_cache_spec = SimpleNamespace(block_size=64, 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),
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)
torch.testing.assert_close(decode.block_table, request_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]]
)
@pytest.mark.parametrize("use_sparse_mla_builder", [False, True])
def test_device_token_request_mapping(query_lens, use_sparse_mla_builder):
"""Graph replay follows device boundaries even when CPU lengths are stale."""
lengths = torch.tensor(query_lens, device="cuda", dtype=torch.int32)
qsl = torch.cat(
[torch.zeros(1, device="cuda", dtype=torch.int32), lengths.cumsum(0).int()]
)
n = sum(query_lens)
output = torch.full((n + 7,), -99, device="cuda", dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=qsl,
query_start_loc_cpu=qsl.cpu(),
seq_lens=lengths,
num_reqs=len(query_lens),
num_actual_tokens=output.numel(),
max_query_len=max(query_lens),
max_seq_len=max(query_lens),
block_table_tensor=torch.empty(
(len(query_lens), 1), device="cuda", dtype=torch.int32
),
slot_mapping=torch.full((n + 7,), -1, device="cuda", dtype=torch.int64),
)
def build_mapping():
if use_sparse_mla_builder:
builder = SimpleNamespace(req_id_per_token_buffer=output)
return SparseMLACommonMetadataBuilder._build_req_id_per_token(
builder, common
)
return common.token_to_req_indices(output)
result = build_mapping()
assert result.data_ptr() == output.data_ptr()
expected = torch.repeat_interleave(
torch.arange(len(query_lens), device="cuda", dtype=torch.int32), lengths
)
torch.testing.assert_close(output[:n], expected)
assert torch.count_nonzero(output[n:]) == 0
graph = torch.cuda.CUDAGraph()
common._token_to_req_indices_cache = None
with torch.cuda.graph(graph):
build_mapping()
reversed_lens = lengths.flip(0)
qsl[1:].copy_(reversed_lens.cumsum(0))
graph.replay()
expected = torch.repeat_interleave(
torch.arange(len(query_lens), device="cuda", dtype=torch.int32), reversed_lens
)
torch.testing.assert_close(output[:n], expected)
assert torch.count_nonzero(output[n:]) == 0
def test_indexer_shares_uncompressed_block_size_with_deepseek_v4_mla():
"""Packed MLA/indexer groups must retain 64 compressed rows per page."""
kernel_block_size = select_common_block_size(
256, [DeepseekV4SparseMLABackend, DeepseekV4IndexerBackend]
)
spec = MLAAttentionSpec(
block_size=256,
num_kv_heads=1,
head_size=132,
dtype=torch.uint8,
tokens_per_state=4,
)
assert compute_layer_kv_cache_shape_bytes(spec, 2, kernel_block_size) == (
2,
1,
64,
132,
)
def test_indexer_preserves_deepseek_v41_mla_block_size():
"""V4.1 retains its smaller pages independently of V4's C4 indexer."""
block_size = DeepseekV41SparseMLABackend.get_supported_kernel_block_sizes()[0]
assert isinstance(block_size, int)
assert (
select_common_block_size(
block_size, [DeepseekV41SparseMLABackend, DeepseekV41IndexerBackend]
)
== block_size
)
def test_indexer_warmup_normalizes_zero_compress_ratios():
config = SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_batched_tokens=8),
model_config=SimpleNamespace(
hf_text_config=SimpleNamespace(
compress_ratios=[0, 0, 4, 128, 0], index_kpool=32
)
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=1,
prefill_context_parallel_size=1,
cp_kv_cache_interleave_size=1,
),
)
keys = BuildPrefillChunkMetadataKernel().get_warmup_keys(config)
assert {key.compress_ratio for key in keys} == {1, 4, 32, 128}
assert {(key.query_slice_start, key.query_slice_stop) for key in keys} == {
(query_slice_start, query_slice_stop)
for query_slice_start in (1, 2, 16)
for query_slice_stop in (1, 2, 16)
}
def test_indexer_warmup_includes_pcp_normalized_dcp_key(monkeypatch):
monkeypatch.setattr(
"vllm.v1.attention.backends.mla.indexer.get_dcp_group",
lambda: SimpleNamespace(rank_in_group=2),
)
config = SimpleNamespace(
scheduler_config=SimpleNamespace(max_num_batched_tokens=8),
model_config=SimpleNamespace(
hf_text_config=SimpleNamespace(compress_ratios=[32], index_kpool=32)
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=4,
prefill_context_parallel_size=4,
cp_kv_cache_interleave_size=1,
),
)
keys = BuildPrefillChunkMetadataKernel().get_warmup_keys(config)
# Triton's compile key normalizes generic i32 values to 2 and divisible
# i32 values (including zero) to 16.
assert {(key.dcp_rank, key.dcp_world) for key in keys} == {(2, 2), (16, 1)}
assert {
(
key.input_variant.is_aligned("uncompressed_seq_lens"),
key.input_variant.is_aligned("cu_compressed_seq_lens"),
)
for key in keys
} == {(False, False), (False, True), (True, False), (True, True)}
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)
assert {(key.compress_ratio, key.block_size) for key in keys} == {(32, 2)}
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_compressed_slot_mapping_inherits_padded_token_slots():
"""A token whose own slot is padded (SWA bounded replay) closes no
compressed state either."""
device = torch.device("cuda")
query_start_loc = torch.tensor([0, 8], dtype=torch.int32, device=device)
seq_lens = torch.tensor([8], dtype=torch.int32, device=device)
block_table = torch.tensor([[3]], dtype=torch.int32, device=device)
slot_mapping = torch.arange(8, dtype=torch.int64, device=device)
slot_mapping[:4] = -1
compressed = get_compressed_slot_mapping(
8,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size=4,
compress_ratio=2,
)
assert compressed.tolist() == [-1, -1, -1, -1, -1, 3 * 4 + 2, -1, 3 * 4 + 3]
@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),
model_config=SimpleNamespace(
max_model_len=1024,
hf_text_config=SimpleNamespace(index_topk=2048),
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=1,
prefill_context_parallel_size=1,
cp_kv_cache_interleave_size=1,
),
)
keys = ConvertReqIndexToGlobalIndexKernel().get_warmup_keys(
config,
block_stride_rows=4096,
)
assert {key.block_stride_rows for key in keys} == {4096}
def test_zero_token_pcp_rank_participates_in_compressed_mapping_gather(monkeypatch):
builder = object.__new__(DeepseekV32IndexerMetadataBuilder)
builder.compress_ratio = 4
builder.use_pcp = True
builder.pcp_world_size = 4
builder.pcp_rank = 0
builder.dcp_world_size = 1
builder.cp_kv_cache_interleave_size = 1
builder.kv_cache_spec = SimpleNamespace(block_size=64, num_states=64)
builder.compressed_slot_mapping_buffer = torch.zeros(8, dtype=torch.int64)
def fake_get_compressed_slot_mapping(
num_tokens,
slot_mapping,
query_start_loc,
seq_lens,
block_table,
block_size,
compress_ratio,
out,
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)
return out[:num_tokens]
gathered_slot_mapping = torch.tensor([123, -1, -1, -1], dtype=torch.int64)
class FakePCPGroup:
def __init__(self):
self.calls = 0
def all_gather(self, tensor, dim=0):
self.calls += 1
assert dim == 0
torch.testing.assert_close(tensor, torch.tensor([-1]))
return gathered_slot_mapping
fake_pcp_group = FakePCPGroup()
monkeypatch.setattr(
indexer_module,
"get_compressed_slot_mapping",
fake_get_compressed_slot_mapping,
)
monkeypatch.setattr(indexer_module, "get_pcp_group", lambda: fake_pcp_group)
query_start_loc = torch.tensor([0, 0], dtype=torch.int32)
seq_lens = torch.tensor([16], dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc,
seq_lens=seq_lens,
seq_lens_cpu_upper_bound=seq_lens,
num_reqs=1,
num_actual_tokens=0,
max_query_len=0,
max_seq_len=16,
block_table_tensor=torch.tensor([[0]], dtype=torch.int32),
slot_mapping=torch.tensor([11, 22, 33, 44], dtype=torch.int64),
causal=True,
)
metadata = builder.build(common_prefix_len=0, common_attn_metadata=common)
assert fake_pcp_group.calls == 1
assert metadata.num_decodes == 0
assert metadata.num_decode_tokens == 0
assert metadata.num_prefills == 0
assert metadata.num_prefill_tokens == 0
torch.testing.assert_close(metadata.slot_mapping, gathered_slot_mapping)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_indexer_builder_deepseek_v4_compressed_slot_mapping_uses_num_states():
"""Regression test: DeepseekV4 compression path must compute slot_mapping from
compressed positions, not reuse the uncompressed common metadata mapping.
"""
device = torch.device("cuda")
# num_states = block_size // tokens_per_state = 256 // 4 = 64
kv_cache_spec = MLAAttentionSpec(
block_size=256,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
tokens_per_state=4,
)
vllm_config = create_vllm_config(max_model_len=1024)
max_num_blocks = kv_cache_spec.max_num_blocks_per_req(vllm_config, 1024)
block_table_width = get_block_table_width(max_num_blocks, kv_cache_spec.block_size)
builder = DeepseekV32IndexerMetadataBuilder(
kv_cache_spec=kv_cache_spec,
layer_names=["dummy"],
vllm_config=vllm_config,
device=device,
block_table_width=block_table_width,
)
# Construct a single request where:
# - num_computed = 240 (=> compressed_pos_start = 60)
# - query_len = 40 (=> num_groups = 10)
# => compressed positions are 60..69 which cross the storage block boundary at 64.
query_start_loc = torch.tensor([0, 40], dtype=torch.int32, device=device)
query_start_loc_cpu = query_start_loc.cpu()
seq_lens = torch.tensor([280], dtype=torch.int32, device=device) # 240 + 40
# Two blocks: compressed positions 0..63 map to block 5, 64..127 map to block 7.
block_table_tensor = torch.tensor([[5, 7]], dtype=torch.int32, device=device)
# Dummy uncompressed slot mapping (length == uncompressed num_actual_tokens).
slot_mapping = torch.full((40,), -123, dtype=torch.int64, device=device)
common = CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc_cpu,
seq_lens=seq_lens,
seq_lens_cpu_upper_bound=seq_lens.cpu(),
num_reqs=1,
num_actual_tokens=40,
max_query_len=40,
max_seq_len=280,
block_table_tensor=block_table_tensor,
slot_mapping=slot_mapping,
causal=True,
)
md = builder.build(common_prefix_len=0, common_attn_metadata=common)
# The compressed slot_mapping retains the original uncompressed size (40).
# Only every compress_ratio-th position gets a valid slot; the rest are -1.
assert md.slot_mapping.numel() == 40
valid_slots = md.slot_mapping[md.slot_mapping >= 0]
assert valid_slots.numel() == 10 # 40 tokens / compress_ratio 4
storage_bs = kv_cache_spec.num_states # 64
# Compressed positions 60..63 land in block 5, positions 64..69 in block 7.
expected = torch.tensor(
[
5 * storage_bs + 60,
5 * storage_bs + 61,
5 * storage_bs + 62,
5 * storage_bs + 63,
]
+ [
7 * storage_bs + 0,
7 * storage_bs + 1,
7 * storage_bs + 2,
7 * storage_bs + 3,
7 * storage_bs + 4,
7 * storage_bs + 5,
],
dtype=torch.int64,
device=device,
)
torch.testing.assert_close(valid_slots, expected)
@pytest.mark.parametrize("compress_ratio", [1, 4])
def test_indexer_prefill_budget_matches_compressed_workspace(compress_ratio):
"""The chunker budget is in compressed rows, like the K-gather workspace."""
max_model_len = 1024
kv_cache_spec = MLAAttentionSpec(
block_size=256,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
tokens_per_state=compress_ratio,
)
vllm_config = create_vllm_config(max_model_len=max_model_len)
max_num_blocks = kv_cache_spec.max_num_blocks_per_req(vllm_config, max_model_len)
block_table_width = get_block_table_width(max_num_blocks, kv_cache_spec.block_size)
builder = DeepseekV32IndexerMetadataBuilder(
kv_cache_spec=kv_cache_spec,
layer_names=["dummy"],
vllm_config=vllm_config,
device=torch.device("cpu"),
block_table_width=block_table_width,
)
workspace_rows = get_max_prefill_buffer_size(vllm_config) // compress_ratio
assert builder.max_prefill_buffer_size == workspace_rows
# Overflows the workspace unless the chunker splits.
num_reqs = 3 * (workspace_rows // (max_model_len // compress_ratio)) + 1
compressed_seq_lens = torch.full((num_reqs,), max_model_len // compress_ratio)
query_lens = torch.ones(num_reqs, dtype=torch.int64)
chunks = builder._split_indexer_prefill_chunks(
compressed_seq_lens,
query_lens,
builder.max_prefill_buffer_size,
max_logits_bytes=10**15,
)
assert len(chunks) > 1
for req_slice, _ in chunks:
assert int(compressed_seq_lens[req_slice].sum()) <= workspace_rows
@@ -1,75 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Which next_n the DSA indexer decode path may hand to DeepGEMM unflattened.
Getting this wrong is not a slow path but a crash: `fp8_fp4_paged_mqa_logits`
asserts both that the architecture implements the requested `next_n` and that
the schedule metadata was sized for the matching slot count.
"""
import pytest
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import _paged_mqa_logits_schedule_slots
from vllm.v1.attention.backends.mla import indexer
NUM_SMS = 114 # H100 PCIe
def _set_arch(monkeypatch, family: int, *, cuda: bool = True, deep_gemm: bool = True):
monkeypatch.setattr(current_platform, "is_cuda", lambda: cuda)
monkeypatch.setattr(
current_platform,
"is_device_capability_family",
lambda capability, device_id=0: capability // 10 == family,
)
monkeypatch.setattr(indexer, "has_deep_gemm", lambda: deep_gemm)
@pytest.mark.parametrize(
"family,expected_native",
[
# SM90 gained next_n=4 (MTP=3) via 2-CTA multicast, but never 3.
(9, {1, 2, 4}),
# SM100 schedules any next_n with multi-atom tiles.
(10, {1, 2, 3, 4, 5, 8}),
# SM120 advertises multi-atom too but is unvalidated on hardware, so
# it stays on the conservative gate. Loosen it only with measurements.
(12, {1, 2}),
],
)
def test_native_decode_gate_per_architecture(monkeypatch, family, expected_native):
_set_arch(monkeypatch, family)
for next_n in (1, 2, 3, 4, 5, 8):
assert indexer._supports_native_decode(next_n) == (next_n in expected_native), (
f"family={family} next_n={next_n}"
)
@pytest.mark.parametrize(
"cuda,deep_gemm", [(False, True), (True, False), (False, False)]
)
def test_native_decode_gate_without_deepgemm(monkeypatch, cuda, deep_gemm):
"""Without the DeepGEMM kernels only the shapes every backend handles."""
_set_arch(monkeypatch, 9, cuda=cuda, deep_gemm=deep_gemm)
assert [indexer._supports_native_decode(n) for n in (1, 2, 3, 4)] == [
True,
True,
False,
False,
]
def test_sm90_next_n_4_halves_the_schedule_slots(monkeypatch):
"""SM90 next_n=4 runs one scheduler task per 2-CTA cluster, not per SM."""
_set_arch(monkeypatch, 9)
assert _paged_mqa_logits_schedule_slots(NUM_SMS, 4) == NUM_SMS // 2
for next_n in (1, 2, 3):
assert _paged_mqa_logits_schedule_slots(NUM_SMS, next_n) == NUM_SMS
@pytest.mark.parametrize("family", [10, 12])
def test_multicast_is_sm90_only(monkeypatch, family):
_set_arch(monkeypatch, family)
for next_n in (1, 2, 3, 4):
assert _paged_mqa_logits_schedule_slots(NUM_SMS, next_n) == NUM_SMS
@@ -1,241 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""TP query-row sharding of the DSA indexer prefill (see PrefillRowShard):
each rank scores a contiguous slice; the group exchanges int32s per row."""
from types import SimpleNamespace
import pytest
import torch
import vllm.model_executor.layers.sparse_attn_indexer as sparse_indexer
import vllm.v1.attention.backends.mla.indexer as indexer
from vllm.config import AttentionConfig, CUDAGraphMode
from vllm.model_executor.layers.sparse_attn_indexer import PrefillRowShard
MIN_ROWS = AttentionConfig().indexer_tp_shard_min_rows
def _chunk(start: int, end: int) -> SimpleNamespace:
"""Chunk over rows [start, end); bounds derive from the global row."""
n = end - start
return SimpleNamespace(
token_start=start,
token_end=end,
cu_seqlen_ks=torch.zeros(n, dtype=torch.int32),
cu_seqlen_ke=((torch.arange(n) * 7 + start) % 65).int(),
)
@pytest.mark.parametrize("world", [2, 3, 8])
def test_shard_narrowing_covers_every_row_once(world: int) -> None:
"""Narrowed windows tile the prefill rows exactly once, carry the causal
bounds of those global rows, and skip chunks foreign to this rank."""
decode, rows = 5, 997
edges = [decode, decode + 330, decode + 337, decode + rows]
chunks = [_chunk(lo, hi) for lo, hi in zip(edges, edges[1:])]
sizes = [rows // world + int(r < rows % world) for r in range(world)]
covered = []
for rank in range(world):
shard = PrefillRowShard(decode, sizes, rank)
for chunk in chunks:
window = shard.narrow(chunk)
if window is None:
continue
start, end, ks, ke = window
lo, hi = start - chunk.token_start, end - chunk.token_start
torch.testing.assert_close(ks, chunk.cu_seqlen_ks[lo:hi])
torch.testing.assert_close(ke, chunk.cu_seqlen_ke[lo:hi])
covered.append((start, end))
covered.sort()
# Windows must be disjoint, contiguous and exactly cover the prefill rows.
assert [s for s, _ in covered] == [decode, *[e for _, e in covered][:-1]]
assert covered[-1][1] == decode + rows
def test_shard_exchange_reassembles_rows_only(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Gathered indices land only on real prefill rows: leading decode rows
and trailing CUDA-graph padding stay untouched, and the full k-pool
width (tail columns included) is exchanged."""
decode, pad, topk, kpool = 5, 3, 8, 4
width = topk + kpool - 1
sizes = [17, 9, 21]
buffer = torch.full((decode + sum(sizes) + pad, width), -7, dtype=torch.int32)
gathered = torch.arange(sum(sizes) * width, dtype=torch.int32).reshape(-1, width)
calls = []
def fake_group():
def all_gatherv(local, dim, sizes):
calls.append((local, sizes))
return gathered
return SimpleNamespace(all_gatherv=all_gatherv)
monkeypatch.setattr(sparse_indexer, "get_tp_group", fake_group)
for rank in range(len(sizes)):
PrefillRowShard(decode, sizes, rank).exchange_topk(buffer, width)
assert calls[0][1] == sizes and calls[0][0].is_contiguous()
torch.testing.assert_close(buffer[decode : decode + sum(sizes)], gathered)
assert torch.all(buffer[:decode] == -7), "decode rows stay outside"
assert torch.all(buffer[decode + sum(sizes) :] == -7), "padding untouched"
@pytest.mark.parametrize("tp_size", [2, 4, 8])
def test_balanced_row_shard_partitions_and_declines(tp_size: int) -> None:
"""The split covers every row once with >= 1 row per rank and declines
below the activation floor (or on a single rank)."""
n = MIN_ROWS
shapes = [
([4 * n], [4 * n]), # fresh prompt: the full causal cost ramp
# uneven requests at different context depths
([2 * n, 7, 4 * n, n // 3 + 5], [2 * n, 9007, 4 * n + 500, n // 3 + 60005]),
]
ratio = 4
for query_lens, seq_lens in shapes:
sizes = indexer.balanced_prefill_row_shard(
torch.tensor(seq_lens, dtype=torch.int32),
torch.tensor(query_lens, dtype=torch.int32),
ratio,
tp_size,
n,
)
assert sizes is not None and len(sizes) == tp_size
assert sum(sizes) == sum(query_lens) and min(sizes) >= 1
lens = torch.tensor([n - 1], dtype=torch.int32)
assert indexer.balanced_prefill_row_shard(lens, lens, ratio, tp_size, n) is None
assert indexer.balanced_prefill_row_shard(lens, lens, ratio, 1, n) is None
def test_row_shard_threshold_is_total_not_per_rank() -> None:
"""The activation floor counts TOTAL rows regardless of tp_size: a
per-rank floor would need 128K rows at TP8, i.e. an unschedulable
--max-num-batched-tokens of 128K on 80 GB Hopper nodes."""
lens = torch.tensor([MIN_ROWS], dtype=torch.int32)
for tp_size in (2, 4, 8):
sizes = indexer.balanced_prefill_row_shard(lens, lens, 4, tp_size, MIN_ROWS)
assert sizes is not None
def test_tp2_old_per_rank_window_stays_replicated() -> None:
"""32K-64K total rows engaged on TP2 under the old per-rank floor
(16K rows/rank); the total floor now keeps them replicated — the
all_gatherv latency term is largest at small tp."""
window = torch.tensor([3 * MIN_ROWS // 4], dtype=torch.int32)
assert indexer.balanced_prefill_row_shard(window, window, 4, 2, MIN_ROWS) is None
def test_row_shard_floor_is_at_least_tp_size() -> None:
"""A floor below tp_size still leaves every rank at least one row."""
lens = torch.tensor([8], dtype=torch.int32)
assert indexer.balanced_prefill_row_shard(lens, lens, 4, 8, 1) is not None
assert indexer.balanced_prefill_row_shard(lens - 1, lens - 1, 4, 8, 1) is None
def test_row_sharding_gate_rejects_unsupported_configurations(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The gate is the whole safety envelope; nothing else guards the exchange."""
monkeypatch.setattr(indexer.current_platform, "is_cuda", lambda: True)
def supported(**kwargs):
mode = kwargs.pop("cudagraph_mode", CUDAGraphMode.PIECEWISE)
cfg = SimpleNamespace(compilation_config=SimpleNamespace(cudagraph_mode=mode))
args = {"dcp_world_size": 1, "use_pcp": False, "tp_size": 4, **kwargs}
return indexer.tp_prefill_row_sharding_supported(cfg, **args)
assert supported()
for bad in ({"tp_size": 1}, {"dcp_world_size": 2}, {"use_pcp": True}):
assert not supported(**bad)
for name in (
"VLLM_DISABLE_PYNCCL",
"VLLM_USE_NCCL_SYMM_MEM",
"VLLM_BATCH_INVARIANT",
):
with monkeypatch.context() as m:
m.setattr(indexer.envs, name, True)
assert not supported()
# FULL captures mixed batches whole, so the exchange must stay out.
assert not supported(cudagraph_mode=CUDAGraphMode.FULL)
assert supported(cudagraph_mode=CUDAGraphMode.FULL_AND_PIECEWISE)
def test_profiling_run_reserves_exchange_transient(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""The dummy run returns before the exchange executes, so its all_gatherv
output plus staging copy must be reserved up front when row sharding is
active -- and only then."""
rows, topk = 128, 8
buffer = torch.empty((rows, topk), dtype=torch.int32)
peak = 2 * rows * topk * buffer.element_size()
specs = (((1,), torch.uint8), ((1,), torch.uint8))
numels: list[int] = []
real_empty = torch.empty
def recording_empty(*args, **kwargs):
out = real_empty(*args, **kwargs)
numels.append(out.numel())
return out
def run_dummy(tp_world: int) -> None:
numels.clear()
with monkeypatch.context() as m:
m.setattr(torch, "empty", recording_empty)
m.setattr(
sparse_indexer,
"get_forward_context",
lambda: SimpleNamespace(attn_metadata=None),
)
m.setattr(sparse_indexer, "_gather_workspace_shapes", lambda *a: specs)
m.setattr(
sparse_indexer,
"current_workspace_manager",
lambda: SimpleNamespace(get_simultaneous=lambda *s: None),
)
m.setattr(
sparse_indexer,
"get_tp_group",
lambda: SimpleNamespace(world_size=tp_world),
)
m.setattr(
sparse_indexer,
"get_current_vllm_config_or_none",
lambda: SimpleNamespace(
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.PIECEWISE
),
parallel_config=SimpleNamespace(
decode_context_parallel_size=1,
prefill_context_parallel_size=1,
),
),
)
m.setattr(sparse_indexer.envs, "VLLM_SPARSE_INDEXER_MAX_LOGITS_MB", 1)
m.setattr(indexer.current_platform, "is_cuda", lambda: True)
sparse_indexer.sparse_attn_indexer(
hidden_states=torch.empty(4, 4),
k_cache_prefix="k",
kv_cache=torch.empty(4, 4),
q_quant=torch.empty(4, 4),
q_scale=None,
k=None,
weights=torch.empty(4),
quant_block_size=128,
scale_fmt=None,
topk_tokens=topk,
head_dim=64,
max_model_len=1024,
total_seq_lens=512,
topk_indices_buffer=buffer,
skip_k_cache_insert=True,
use_pcp=False,
pcp_shard_decode_requests=False,
dense_mha_metadata_layer_name="",
)
run_dummy(tp_world=2)
assert peak in numels
run_dummy(tp_world=1)
assert peak not in numels
@@ -1,121 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU tests for the kpool indexer's kernel block selection."""
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 Glm5NextIndexerBackend
from vllm.v1.kv_cache_interface import MLAAttentionSpec
from vllm.v1.worker.utils import prepare_kernel_block_sizes, select_common_block_size
pytestmark = pytest.mark.cpu_test
# ``index_kpool`` of zai-org/GLM-5.3-Flash: one indexer state pools 4
# compressed states (hence a kernel block is page * 4 tokens).
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, layer_names=[])],
kv_cache_tensors=[],
)
attn_groups = [
[SimpleNamespace(backend=backend, kv_cache_spec=spec) 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_kpool_group_maps_pool_pages(
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 = 256 if manager_block % 256 == 0 else 128
# The kpool group's AttentionGroup selects its kernel block this way.
selected = [
select_common_block_size(manager_block, [Glm5NextIndexerBackend], [spec])
]
assert selected == [expected]
assert selected != [manager_block]
# The hybrid block-table split stays integral.
assert manager_block % selected[0] == 0
def test_prepare_uses_the_backend_vote():
"""Unpacked groups take `select_common_block_size`'s answer."""
class Fixed64Backend:
@staticmethod
def get_supported_kernel_block_sizes(kv_cache_spec=None):
return [64]
@staticmethod
def get_name() -> str:
return "FIXED64"
plain_spec = MLAAttentionSpec(
block_size=640,
num_kv_heads=1,
head_size=128,
dtype=torch.bfloat16,
)
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(kv_cache_spec=None):
return [MultipleOf(1)]
@staticmethod
def get_name() -> str:
return "ACCEPTALL"
assert _prepare(plain_spec, [AcceptAllBackend]) == [640]
@@ -1,510 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU tests for the kpool tail slot mapping (no GPU required).
The kpool tail cache is a 1-block-per-request circular ring addressed by
``pos % kpool`` (``CircularBufferSpec`` / ``CircularBufferManager``: exactly one block
allocated per request, never grown, so only column 0 of its block table is
ever written; the rest stays zero-initialized).
The generic per-group slot kernel cannot express that layout: it maps
``pos -> bt[req][pos // bs] * bs + pos % bs`` (``_compute_slot_mappings_kernel``
in vllm/v1/worker/gpu/block_table.py), so every token at ``pos >= kpool``
reads a zero column and collapses onto physical tail block 0. All concurrent
requests then share one ``kpool``-slot ring and corrupt each other's pool
compression.
These tests pin that defect's arithmetic, verify the circular replacement
(``compute_kpool_tail_slot_mapping``), and mirror the tail kernels' index
math to show cross-request pollution before the fix and isolation after.
"""
from types import SimpleNamespace
import pytest
import torch
from vllm.config import VllmConfig, set_current_vllm_config
from vllm.models.glm5next.common.attention import Glm5NextTailCache
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.indexer import (
KpoolTailBackend,
KpoolTailMetadataBuilder,
compute_kpool_tail_slot_mapping,
)
from vllm.v1.kv_cache_interface import CircularBufferSpec, compute_layout_strides
from vllm.v1.kv_cache_layout import KVCacheLayout
KPOOL = 4
def test_tail_backend_layout_matches_kernel_pointer_arithmetic():
(layout,) = KpoolTailBackend.supported_kv_cache_layouts()
spec = CircularBufferSpec(
block_size=KPOOL,
num_kv_heads=2,
head_size=128,
head_size_v=0,
dtype=torch.bfloat16,
)
strides = compute_layout_strides(spec, num_blocks=8, num_layers=3, layout=layout)
_, _, head_stride, state_stride, content_stride = strides
assert layout is KVCacheLayout.BLHNC
assert head_stride == KPOOL * 128 * torch.bfloat16.itemsize
assert state_stride == 128 * torch.bfloat16.itemsize
assert content_stride == 1
@pytest.mark.parametrize(
"num_speculative_tokens, ring", [(0, 4), (1, 8), (4, 8), (7, 16), (13, 32)]
)
def test_tail_ring_divides_the_attention_block(num_speculative_tokens, ring):
"""With 7 draft tokens the ring was 12 slots. 12 does not divide the
640-token KDA attention block, so the scheduler block grew to their lcm
and prefix-cache hits were cut down to multiples of 1920."""
with set_current_vllm_config(VllmConfig()):
cache = Glm5NextTailCache(
head_dim=128,
dtype=torch.bfloat16,
prefix="tail",
cache_config=SimpleNamespace(block_size=640),
index_kpool=KPOOL,
)
spec = cache.get_kv_cache_spec(
SimpleNamespace(num_speculative_tokens=num_speculative_tokens)
)
assert isinstance(spec, CircularBufferSpec) and spec.block_size == ring
assert ring >= KPOOL + num_speculative_tokens
assert 640 % ring == 0
def make_tail_block_table(own_blocks, width=64):
"""Tail-group block table as BlockTables produces it: column 0 holds the
request's single CircularBufferManager block, the remaining columns are never
written and stay zero."""
bt = torch.zeros(len(own_blocks), width, dtype=torch.int32)
bt[:, 0] = torch.tensor(own_blocks, dtype=torch.int32)
return bt
def legacy_generic_tail_slots(block_table, query_start_loc, positions):
"""Reference of the generic ``_compute_slot_mappings_kernel`` arithmetic
(block_table.py:305-313) applied to the tail group's table."""
slots = []
for req in range(block_table.shape[0]):
for i in range(query_start_loc[req], query_start_loc[req + 1]):
pos = int(positions[i])
block_number = int(block_table[req, pos // KPOOL])
slots.append(block_number * KPOOL + pos % KPOOL)
return torch.tensor(slots, dtype=torch.int64)
def circular_tail_slots(
slot_mapping, block_table, query_start_loc, positions, num_actual, num_reqs
):
return compute_kpool_tail_slot_mapping(
slot_mapping,
block_table,
query_start_loc,
positions,
num_actual,
num_reqs,
KPOOL,
)
def make_batch(per_req_positions, padded_len=None):
positions = torch.cat(
[torch.tensor(p, dtype=torch.int64) for p in per_req_positions]
)
num_actual = positions.numel()
num_reqs = len(per_req_positions)
lens = [len(p) for p in per_req_positions]
qsl = torch.zeros(num_reqs + 1, dtype=torch.int64)
torch.cumsum(torch.tensor(lens, dtype=torch.int64), 0, out=qsl[1:])
if padded_len is None:
padded_len = num_actual
slot_mapping = torch.full((padded_len,), -1, dtype=torch.int64)
return positions, qsl, slot_mapping, num_actual, num_reqs
def test_legacy_generic_mapping_collapses_onto_block_zero():
"""The bug: with the manager's 1-column block table, the generic kernel
maps every pos >= kpool onto tail block 0, and distinct requests collide."""
own_blocks = [5, 9]
per_req = [list(range(10)), list(range(12))] # prompts of len 10 and 12
positions, qsl, _, num_actual, num_reqs = make_batch(per_req)
bt = make_tail_block_table(own_blocks)
legacy = legacy_generic_tail_slots(bt, qsl, positions)
# Every token at pos >= kpool resolves to block 0, not the request's own.
off = 0
for req, prompt in enumerate(per_req):
req_slots = legacy[off : off + len(prompt)]
for pos in range(len(prompt)):
slot = int(req_slots[pos])
if pos >= KPOOL:
assert slot // KPOOL == 0, (
f"expected collapse onto block 0 at pos {pos}"
)
assert slot // KPOOL != own_blocks[req]
off += len(prompt)
# The two requests share ring slots -> cross-request pollution.
a_slots = set(legacy[: len(per_req[0])].tolist())
b_slots = set(legacy[len(per_req[0]) :].tolist())
assert a_slots & b_slots, "legacy mapping must collide across requests"
def test_circular_mapping_isolates_requests():
"""The fix: every token lands in its own request's block at pos % kpool,
and no slot is ever shared by two different requests (slots do recur
within a request every kpool positions -- that is the circular design)."""
own_blocks = [5, 9]
per_req = [list(range(10)), list(range(12))]
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
bt = make_tail_block_table(own_blocks)
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
off = 0
per_req_slots = []
for req, prompt in enumerate(per_req):
req_slots = set()
for pos in range(len(prompt)):
slot = int(out[off + pos])
assert slot // KPOOL == own_blocks[req], (
f"req {req} pos {pos} left its tail block"
)
assert slot % KPOOL == pos % KPOOL
req_slots.add(slot)
per_req_slots.append(req_slots)
off += len(prompt)
assert not per_req_slots[0] & per_req_slots[1]
@pytest.mark.parametrize("prompt_len", [1, 2, 3, 4])
def test_circular_mapping_matches_generic_for_short_requests(prompt_len):
"""For pos < kpool the generic kernel already picks the own block, so the
two mappings agree while every position fits the request's first block
(single-request behavior is unchanged)."""
own_blocks = [7]
per_req = [list(range(prompt_len))]
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
bt = make_tail_block_table(own_blocks)
legacy = legacy_generic_tail_slots(bt, qsl, positions)
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
assert torch.equal(out, legacy)
def test_circular_mapping_preserves_padding_and_empty_batch():
# 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
)
bt = make_tail_block_table(own_blocks)
out = circular_tail_slots(slot_mapping, bt, qsl, positions, num_actual, num_reqs)
assert out.shape == slot_mapping.shape
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)
def make_common_metadata(per_req_positions, own_blocks, with_positions=True):
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(
per_req_positions, padded_len=sum(len(p) for p in per_req_positions) + 4
)
bt = make_tail_block_table(own_blocks)
seq_lens = torch.tensor(
[max(p) + 1 if p else 1 for p in per_req_positions], dtype=torch.int64
)
return CommonAttentionMetadata(
query_start_loc=qsl,
query_start_loc_cpu=qsl.clone(),
seq_lens=seq_lens,
num_reqs=num_reqs,
num_actual_tokens=num_actual,
max_query_len=max((len(p) for p in per_req_positions), default=1),
max_seq_len=int(seq_lens.max()) if num_reqs else 1,
block_table_tensor=bt,
slot_mapping=slot_mapping,
positions=positions if with_positions else None,
)
def make_tail_builder(block_size=KPOOL, max_num_batched_tokens=128):
builder = object.__new__(KpoolTailMetadataBuilder)
builder.kv_cache_spec = SimpleNamespace(block_size=block_size)
builder.slot_mapping_buffer = torch.empty(max_num_batched_tokens, dtype=torch.int64)
return builder
def test_builder_build_uses_circular_mapping():
per_req = [list(range(10)), list(range(12))]
own_blocks = [5, 9]
cam = make_common_metadata(per_req, own_blocks)
meta = KpoolTailMetadataBuilder.build(make_tail_builder(), 0, cam)
out = meta.slot_mapping
off = 0
for req, prompt in enumerate(per_req):
for pos in range(len(prompt)):
slot = int(out[off + pos])
assert slot // KPOOL == own_blocks[req]
assert slot % KPOOL == pos % KPOOL
off += len(prompt)
# Padding tail of the buffer keeps the -1 sentinel.
assert torch.equal(
out[cam.num_actual_tokens :], torch.full_like(out[cam.num_actual_tokens :], -1)
)
def test_builder_build_falls_back_without_positions():
"""Capture / dummy builds without positions keep the generic mapping."""
per_req = [list(range(10))]
cam = make_common_metadata(per_req, [5], with_positions=False)
meta = KpoolTailMetadataBuilder.build(make_tail_builder(), 0, cam)
assert meta.slot_mapping is cam.slot_mapping
def test_builder_updates_draft_mapping():
builder = make_tail_builder()
cam = make_common_metadata([[15], [16]], [5, 9])
meta = KpoolTailMetadataBuilder.build(builder, 0, cam)
assert cam.positions is not None
cam.positions.add_(1)
builder.update_draft_decode_metadata(meta)
assert meta.slot_mapping[:2].tolist() == [5 * KPOOL, 9 * KPOOL + 1]
def test_builder_reuses_slot_mapping_storage():
builder = make_tail_builder()
first = make_common_metadata([list(range(10))], [5])
first_meta = KpoolTailMetadataBuilder.build(builder, 0, first)
data_ptr = first_meta.slot_mapping.data_ptr()
second = make_common_metadata([list(range(12))], [9])
second_meta = KpoolTailMetadataBuilder.build(builder, 0, second)
assert second_meta.slot_mapping.data_ptr() == data_ptr
assert second_meta.slot_mapping[:12].tolist() == [
9 * KPOOL + pos % KPOOL for pos in range(12)
]
# ---------------------------------------------------------------------------
# Index-level mirror of the tail kernels: seed / stash / pool completion
# (addressing replicated from kpool_compress.py's Triton kernels).
# ---------------------------------------------------------------------------
class TailRingMirror:
"""Mirror of the tail-ring addressing in _kpool_tail_seed_kernel and
_kpool_decode_update_batched_kernel."""
def __init__(self, num_blocks, kpool=KPOOL, ring=None):
self.kpool = kpool
self.ring = ring or kpool
self.k = torch.full((num_blocks, self.ring, 3), float("nan"))
self.s = torch.full((num_blocks, self.ring, 3), float("nan"))
def stash(self, tail_slot, pos, k, s):
blk, off = tail_slot // self.ring, pos % self.ring
self.k[blk, off] = k
self.s[blk, off] = s
seed = stash # the seed kernel writes with the same addressing
def complete(self, tail_slot, pos, k, s):
blk = tail_slot // self.ring
start = pos - (self.kpool - 1)
kk = torch.stack(
[self.k[blk, (start + i) % self.ring] for i in range(self.kpool)]
)
ss = torch.stack(
[self.s[blk, (start + i) % self.ring] for i in range(self.kpool)]
)
kk[-1], ss[-1] = k, s # is_current for the completing token
w = torch.softmax(ss, dim=0)
return (kk * w).sum(0)
def token_kv(req, pos):
k = torch.tensor([pos + 100.0 * req, pos + 0.5, 2.0 * pos + 0.25])
s = torch.tensor([0.1 * (pos + 1) + req, 0.2 * pos, 0.05 * pos])
return k, s
def tail_slot_for(mapping, req, pos, own_block):
if mapping == "legacy":
bt_val = own_block if pos < KPOOL else 0
return bt_val * KPOOL + pos % KPOOL
return own_block * KPOOL + pos % KPOOL
def run_scenario(mapping, interleave):
"""Requests A (block 5, prompt len 9) and B (block 9, prompt len 11)
decode concurrently; returns A's boundary pool [8, 9, 10, 11]."""
ring = TailRingMirror(num_blocks=16)
blocks = {"A": 5, "B": 9}
prompts = {"A": 9, "B": 11}
def slot(req, pos):
return tail_slot_for(mapping, 0 if req == "A" else 1, pos, blocks[req])
# Prefill: seed each request's trailing incomplete pool.
for req, L in prompts.items():
for pos in range(L - (L % KPOOL or KPOOL), L):
if pos < 0:
continue
ring.stash(slot(req, pos), pos, *token_kv(0 if req == "A" else 1, pos))
# Decode: A emits pos 9, 10, 11; B emits 11, 12, 13. `interleave`
# processes B before A within a step, which is exactly what concurrent
# Triton programs do when they share tail block 0.
order = ["B", "A"] if interleave else ["A", "B"]
decode = {"A": [9, 10, 11], "B": [11, 12, 13]}
result = None
for step in range(3):
for req in order:
pos = decode[req][step]
k, s = token_kv(0 if req == "A" else 1, pos)
if pos % KPOOL == KPOOL - 1:
pool = ring.complete(slot(req, pos), pos, k, s)
if req == "A":
result = pool
ring.stash(slot(req, pos), pos, k, s)
return result
def test_interleaved_decode_pollution_legacy_vs_circular():
"""Ground truth: request A decoding alone (its ring used exclusively)."""
torch.manual_seed(0)
ground_truth = run_scenario("circular", interleave=False)
legacy = run_scenario("legacy", interleave=True)
circular = run_scenario("circular", interleave=True)
# The old mapping lets request B's tokens into A's ring: A's boundary
# pool is compressed from 2 of B's tokens -> wrong.
assert not torch.allclose(legacy, ground_truth), (
f"legacy mapping unexpectedly clean: {legacy} vs {ground_truth}"
)
# The circular mapping keeps the rings isolated under interleaving.
torch.testing.assert_close(circular, ground_truth)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device")
@pytest.mark.parametrize(
"per_req,own_blocks,num_actual,padded_len",
[
([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, 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), untouched padding beyond num_actual, and PAD for
requests on the null block."""
ring_size = 2 * KPOOL
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(own_blocks)
ref = compute_kpool_tail_slot_mapping(
slot_mapping, bt, qsl, positions, num_actual, num_reqs, ring_size
)
got = compute_kpool_tail_slot_mapping(
slot_mapping.cuda(),
bt.cuda(),
qsl.cuda().to(torch.int32),
positions.cuda(),
num_actual,
num_reqs,
ring_size,
)
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")
def test_triton_mapping_reads_strided_block_table():
"""The kernel must address the block table through its real stride(0),
not a dense assumption (the #57477 class of bug): a tail block table that
is a column view of a wider allocation must still read column 0."""
per_req = [list(range(10)), list(range(12))]
positions, qsl, slot_mapping, num_actual, num_reqs = make_batch(per_req)
own_blocks = [11, 22]
wide = torch.zeros(num_reqs, 8, dtype=torch.int32)
bt = wide[:, 1:4] # non-contiguous view, stride(0) == 8
bt[:, 0] = torch.tensor(own_blocks, dtype=torch.int32)
ref = circular_tail_slots(
slot_mapping, bt.contiguous(), qsl, positions, num_actual, num_reqs
)
got = circular_tail_slots(
slot_mapping.cuda(),
bt.cuda(),
qsl.cuda().to(torch.int32),
positions.cuda(),
num_actual,
num_reqs,
)
torch.testing.assert_close(got.cpu(), ref)
for req, blk in enumerate(own_blocks):
start, end = int(qsl[req]), int(qsl[req + 1])
assert (got[start:end] // KPOOL == blk).all()
@pytest.mark.parametrize("ring_pools", [1, 2])
def test_rejected_completing_draft_needs_ring_slots(ring_pools):
"""With a one-pool ring, the drafts behind a rejected pool-completing draft
overwrote the pool's earlier keys, so its redo compressed wrong keys."""
ring_size = ring_pools * KPOOL
truth = TailRingMirror(num_blocks=2, ring=ring_size)
ring = TailRingMirror(num_blocks=2, ring=ring_size)
block = 1
def slot(pos):
return block * ring_size + pos % ring_size
for pos in range(4, 7):
truth.stash(slot(pos), pos, *token_kv(0, pos))
ring.stash(slot(pos), pos, *token_kv(0, pos))
expected = truth.complete(slot(7), 7, *token_kv(0, 7))
# Draft 7 completes the pool and is rejected. With a one-pool ring, drafts
# 8..10 overwrite the slots of positions 4..6, which are read by the redo
# of 7.
for pos in range(7, 11):
k, s = token_kv(9, pos) # draft values
if pos % KPOOL == KPOOL - 1:
ring.complete(slot(pos), pos, k, s)
ring.stash(slot(pos), pos, k, s)
redo = ring.complete(slot(7), 7, *token_kv(0, 7))
if ring_pools == 1:
assert not torch.allclose(redo, expected)
else:
torch.testing.assert_close(redo, expected)
File diff suppressed because it is too large Load Diff
@@ -1,355 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Per-request scheduling of MLA chunked-context prefill.
These cover the metadata contract `_compute_prefill_context` relies on: every
context row is gathered exactly once, no chunk exceeds the workspace, and a
chunk never covers a prefill without context (which is why the partial no
longer needs an empty-span masking pass).
"""
from types import SimpleNamespace
import pytest
import torch
import vllm.utils.gpu_sync_debug as gsd
from vllm.model_executor.layers.attention.mla_attention import (
build_mla_chunked_context_metadata,
init_mla_context_partial,
reorg_kvcache,
)
from vllm.model_executor.layers.attention.sparse_mla_attention import (
SparseMLACommonMetadataBuilder,
)
BLOCK_SIZE = 16
def build_chunked_context(
context_lens: list[int],
query_lens: list[int],
workspace_size: int,
block_size: int = BLOCK_SIZE,
dcp_world_size: int = 1,
dcp_local_block_size: int = 1,
):
query_start_loc = torch.zeros(len(query_lens) + 1, dtype=torch.int32)
query_start_loc[1:] = torch.tensor(query_lens, dtype=torch.int32).cumsum(0)
workspace_rows = workspace_size + workspace_size // dcp_world_size
return build_mla_chunked_context_metadata(
context_lens_cpu=torch.tensor(context_lens, dtype=torch.int32),
prefill_query_start_loc_cpu=query_start_loc,
chunked_prefill_workspace=torch.empty((workspace_rows, 1)),
chunked_prefill_workspace_size=workspace_size,
block_size=block_size,
align_chunk_to_block=True,
device=torch.device("cpu"),
dcp_world_size=dcp_world_size,
dcp_local_block_size=dcp_local_block_size,
dcp_virtual_block_size=dcp_local_block_size * dcp_world_size,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_sparse_context_lengths_do_not_force_gpu_sync(monkeypatch):
"""Sparse MLA must pin computed context lengths before the H2D copy."""
builder = SimpleNamespace(
_context_lens_cpu=torch.empty(2, dtype=torch.int32, pin_memory=True),
chunked_prefill_workspace=torch.empty((2048, 1)),
chunked_prefill_workspace_size=1024,
kv_cache_spec=SimpleNamespace(block_size=BLOCK_SIZE),
device=torch.device("cuda"),
dcp_world_size=1,
dcp_local_block_size=1,
dcp_virtual_block_size=1,
dcp_manager=None,
)
common_metadata = SimpleNamespace(
seq_lens_cpu_upper_bound=torch.tensor([17, 2052, 324], dtype=torch.int32),
query_start_loc_cpu=torch.tensor([0, 1, 5, 9], dtype=torch.int32),
)
monkeypatch.setattr(gsd, "_SYNC_CHECK_MODE", "error")
monkeypatch.setattr(gsd, "_sync_check_enabled", True)
gsd._install_copy_checkers()
metadata = gsd.with_gpu_sync_check(
SparseMLACommonMetadataBuilder._build_chunked_context_fields
)(
builder,
common_metadata,
num_decodes=1,
num_prefills=2,
prefill_query_lens_cpu=torch.tensor([4, 4], dtype=torch.int32),
)
assert metadata is not None
assert metadata.context_lens.device.type == "cuda"
assert metadata.context_lens.tolist() == [2048, 320]
@pytest.mark.parametrize(
"context_lens,workspace_size",
[
# Heterogeneous batch: the long request must not shrink the chunk the
# short ones share.
([960, 16, 16, 16, 16, 16, 16, 16], 1024),
# A single request that does not fit is split on its own.
([2048, 320], 1024),
# Every request needs its own chunk.
([1024, 1024, 1024], 1024),
# Unaligned tails.
([37, 1000, 5], 1024),
# A zero-context request between active requests must not become an
# empty TRTLLM ragged-attention row.
([4, 0, 2], 1024),
([1], 1024),
],
)
def test_chunks_gather_every_context_row_exactly_once(context_lens, workspace_size):
"""Chunks tile the batch's context without gaps, overlap, or overflow.
This is the invariant the whole schedule rests on: attention over a chunk
only sees the rows that chunk gathered, so a row counted twice or dropped
silently corrupts the context partial.
"""
query_lens = [4] * len(context_lens)
metadata = build_chunked_context(context_lens, query_lens, workspace_size)
assert metadata is not None
assert metadata.context_lens.tolist() == context_lens
gathered: dict[int, list[tuple[int, int]]] = {}
previous_request_start = -1
for chunk in metadata.chunks:
assert chunk.all_rows_active
assert chunk.num_context_tokens <= workspace_size
assert chunk.num_context_tokens == int(chunk.cu_seq_lens[-1])
assert chunk.token_to_seq.shape[0] == chunk.num_context_tokens
# Chunks are emitted in request order, which is what lets the partial
# treat only a chunk's first request as a continuation.
assert chunk.request_slice.start >= previous_request_start
previous_request_start = chunk.request_slice.start
starts = chunk.starts.tolist()
seq_lens = chunk.seq_lens.tolist()
assert len(starts) == len(seq_lens) == chunk.num_requests
for offset, (start, length) in enumerate(zip(starts, seq_lens)):
assert length > 0, "a chunk must not cover an empty context span"
gathered.setdefault(chunk.request_slice.start + offset, []).append(
(start, length)
)
expected = {i: length for i, length in enumerate(context_lens) if length > 0}
assert gathered.keys() == expected.keys()
for request, spans in gathered.items():
cursor = 0
for start, length in spans:
assert start == cursor
cursor += length
assert cursor == expected[request]
def test_continuation_is_confined_to_a_chunks_first_request():
"""Only a chunk's first request may continue an earlier chunk.
`accumulate_mla_context_chunk` merges the continuation token slice and
writes the rest, so a chunk that continues a request other than its first,
or reports the wrong boundary, folds the partial into the wrong tokens.
"""
context_lens = [2048, 32, 32]
query_lens = [3, 5, 7]
metadata = build_chunked_context(context_lens, query_lens, 1024)
assert metadata is not None
query_start_loc = [0, 3, 8, 15]
assert [chunk.is_continuation for chunk in metadata.chunks] == [
False,
True,
False,
]
for chunk in metadata.chunks:
starts = chunk.starts.tolist()
assert chunk.is_continuation == (starts[0] > 0)
# Requests after the first always start at the beginning of their
# context, so they can only ever be initialized, never merged.
assert all(start == 0 for start in starts[1:])
request_start = chunk.request_slice.start
request_end = chunk.request_slice.stop
assert chunk.continuation_token_end == query_start_loc[request_start + 1]
assert chunk.token_slice == slice(
query_start_loc[request_start], query_start_loc[request_end]
)
assert chunk.query_start_loc.tolist() == [
offset - chunk.token_slice.start
for offset in query_start_loc[request_start : request_end + 1]
]
def test_tail_splitting_minimizes_chunks():
"""A tail request may fill one chunk and continue at the next chunk's head.
Without tail splitting these contexts need three chunks. Splitting on the
block boundary reduces that to the workspace lower bound of two.
"""
metadata = build_chunked_context([768, 512, 512], [3, 5, 7], 1024)
assert metadata is not None
assert len(metadata.chunks) == 2
first, second = metadata.chunks
assert first.starts.tolist() == [0, 0]
assert first.seq_lens.tolist() == [768, 256]
assert not first.is_continuation
assert second.starts.tolist() == [256, 0]
assert second.seq_lens.tolist() == [256, 512]
assert second.is_continuation
def test_prefills_without_context_are_skipped_and_neutralized():
"""Context-free prefills get neutral partials instead of chunk work.
If the full-query partial leaves either an internal or trailing gap
uninitialized, the final merge combines the suffix with undefined scratch.
"""
metadata = build_chunked_context([64, 0, 64, 0], [4, 4, 4, 4], 1024)
assert metadata is not None
covered = {
request
for chunk in metadata.chunks
for request in range(chunk.request_slice.start, chunk.request_slice.stop)
}
assert covered == {0, 2}
assert metadata.empty_token_slices == [slice(4, 8), slice(12, 16)]
output, output_lse = init_mla_context_partial(
metadata,
attn_output=torch.empty(4, 2, 3),
attn_softmax_lse=torch.empty(2, 4),
num_tokens=16,
)
assert output.shape == (16, 2, 3)
assert output_lse.shape == (2, 16)
for token_slice in metadata.empty_token_slices:
assert not torch.count_nonzero(output[token_slice])
assert torch.isneginf(output_lse[:, token_slice]).all()
def test_no_context_needs_no_chunks():
assert build_chunked_context([0, 0], [4, 4], 1024) is None
def test_dcp_chunks_fit_the_per_rank_row_budget():
"""Under DCP each rank gathers its own shard, so the budget is 1/world.
The local starts and lengths must tile the rank's padded context the same
way the global ones tile the real context, since `reorg_kvcache` unpads
using them.
"""
dcp_world_size, interleave, workspace_size = 2, 64, 1024
context_lens = [3000, 200, 200]
metadata = build_chunked_context(
context_lens,
[4] * len(context_lens),
workspace_size,
block_size=128,
dcp_world_size=dcp_world_size,
dcp_local_block_size=interleave,
)
assert metadata is not None
assert metadata.context_lens.tolist() == context_lens
virtual_block_size = interleave * dcp_world_size
local_cursor: dict[int, int] = {}
for chunk in metadata.chunks:
assert chunk.num_local_context_tokens <= workspace_size // dcp_world_size
assert chunk.local_starts == chunk.starts.tolist()
assert chunk.padded_local_cu_seq_lens.tolist() == [0] + list(
torch.tensor(chunk.padded_local_seq_lens).cumsum(0)
)
assert (
chunk.padded_local_token_to_seq.shape[0] == chunk.num_local_context_tokens
)
for offset, (start, length) in enumerate(
zip(chunk.local_starts, chunk.padded_local_seq_lens)
):
request = chunk.request_slice.start + offset
assert start == local_cursor.get(request, 0)
local_cursor[request] = start + length
for request, length in enumerate(context_lens):
padded_local = -(-length // virtual_block_size) * interleave
assert local_cursor[request] == padded_local
def test_dcp_reorg_uses_each_chunks_local_starts():
"""Reorganization drops DCP padding at each request's own chunk offset."""
dcp_world_size, interleave, workspace_size = 2, 64, 1024
metadata = build_chunked_context(
[3000, 200, 200],
[4, 4, 4],
workspace_size,
block_size=128,
dcp_world_size=dcp_world_size,
dcp_local_block_size=interleave,
)
assert metadata is not None
for chunk in metadata.chunks:
assert chunk.padded_local_seq_lens is not None
assert chunk.local_context_lens_allranks is not None
assert chunk.local_starts is not None
toks = chunk.num_local_context_tokens
rank_buffers = [torch.full((toks, 1, 1), -1) for _ in range(dcp_world_size)]
expected = []
src_token_idx = 0
for request, (padded_len, local_lens, local_start) in enumerate(
zip(
chunk.padded_local_seq_lens,
chunk.local_context_lens_allranks,
chunk.local_starts,
)
):
for rank, local_len in enumerate(local_lens):
actual_len = min(max(0, local_len - local_start), padded_len)
values = (
request * 100_000
+ rank * 10_000
+ torch.arange(local_start, local_start + actual_len)
).view(-1, 1, 1)
rank_buffers[rank][src_token_idx : src_token_idx + actual_len] = values
expected.append(values)
src_token_idx += padded_len
allgathered = torch.cat(rank_buffers)
reorganized, _ = reorg_kvcache(
allgathered,
allgathered,
padded_local_chunk_seq_lens_lst=chunk.padded_local_seq_lens,
local_context_lens_allranks=chunk.local_context_lens_allranks,
local_starts=chunk.local_starts,
sum_seq_len=chunk.num_context_tokens,
max_seq_len=chunk.max_seq_len,
toks=toks,
)
torch.testing.assert_close(reorganized, torch.cat(expected))
def test_chunked_context_metadata_owns_context_lengths():
"""Reusing CPU scratch must not overwrite an earlier batch's context lengths."""
context_lens = torch.tensor([16, 32], dtype=torch.int32)
metadata = build_mla_chunked_context_metadata(
context_lens_cpu=context_lens,
prefill_query_start_loc_cpu=torch.tensor([0, 4, 8], dtype=torch.int32),
chunked_prefill_workspace=torch.empty((64, 1)),
chunked_prefill_workspace_size=64,
block_size=BLOCK_SIZE,
align_chunk_to_block=True,
device=torch.device("cpu"),
dcp_world_size=1,
dcp_local_block_size=1,
dcp_virtual_block_size=1,
)
context_lens.zero_()
assert metadata is not None
assert metadata.context_lens.tolist() == [16, 32]
-260
View File
@@ -1,260 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.model_executor.layers.attention.mla_attention import (
MLACommonMetadata,
MLACommonMetadataBuilder,
QueryLenSupport,
)
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.kv_cache_interface import MLAAttentionSpec
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,
causal: bool = False,
) -> CommonAttentionMetadata:
num_reqs = len(query_start_loc) - 1
num_tokens = query_start_loc[-1] if num_tokens is None else num_tokens
return CommonAttentionMetadata(
query_start_loc=torch.tensor(query_start_loc, dtype=torch.int32),
query_start_loc_cpu=torch.tensor(query_start_loc, dtype=torch.int32),
seq_lens=torch.arange(1, num_reqs + 1, dtype=torch.int32) * 100 + 8,
num_reqs=num_reqs,
num_actual_tokens=num_tokens,
max_query_len=max(
end - start for start, end in zip(query_start_loc, query_start_loc[1:])
),
max_seq_len=num_reqs * 100 + 8,
block_table_tensor=torch.arange(num_reqs * 3, dtype=torch.int32).view(
num_reqs, 3
),
slot_mapping=torch.arange(num_tokens),
causal=causal,
seq_lens_cpu_upper_bound=None,
)
def _builder(marked: bool = True) -> _NonCausalMLAMetadataBuilder:
builder = object.__new__(_NonCausalMLAMetadataBuilder)
builder.device = torch.device("cpu")
builder.reorder_batch_threshold = 1
builder.query_len_support = QueryLenSupport.SINGLE_ONLY
builder.non_causal_multi_token_decode = marked
builder.dcp_world_size = 1
builder.use_pcp = False
builder.metadata_cls = MLACommonMetadata
builder.model_config = SimpleNamespace(
dtype=torch.bfloat16, get_head_size=lambda: 576
)
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()
target_metadata = builder.build(0, _metadata([0, 1, 2], causal=True))
assert (
target_metadata.num_decodes,
target_metadata.num_decode_tokens,
target_metadata.num_prefills,
target_metadata.causal,
) == (2, 2, 0, True)
common_metadata = _metadata([0, 8, 16])
metadata = builder.build(0, common_metadata)
assert metadata.num_decodes == 2
assert metadata.num_decode_tokens == 16
assert metadata.num_prefills == 0
assert metadata.prefill is None
assert metadata.decode is not None
assert metadata.decode.block_table.shape == (2, 3)
assert metadata.decode.seq_lens.shape == (2,)
assert torch.equal(metadata.decode.block_table, common_metadata.block_table_tensor)
assert torch.equal(metadata.decode.seq_lens, common_metadata.seq_lens)
assert not metadata.causal
def test_noncausal_support_is_explicit_and_uniform():
with pytest.raises(ValueError, match="explicitly supported"):
_builder(marked=False).build(0, _metadata([0, 8, 16]))
with pytest.raises(ValueError, match="uniform query block"):
_builder().build(0, _metadata([0, 3, 8]))
def test_noncausal_block_allows_trailing_cudagraph_padding():
common_metadata = _metadata([0, 8, 16, 16], num_tokens=24)
common_metadata.seq_lens[-1] = 0
metadata = _builder().build(0, common_metadata)
assert metadata.num_decodes == 3
assert metadata.num_decode_tokens == 24
assert metadata.decode is not None
assert metadata.decode.seq_lens.tolist() == [108, 208, 0]
def test_noncausal_block_rejects_non_trailing_padding():
with pytest.raises(ValueError, match="uniform query block"):
_builder().build(0, _metadata([0, 8, 8, 16], num_tokens=24))
def test_noncausal_decode_metadata_keeps_live_request_buffers():
common_metadata = _metadata([0, 8, 16])
metadata = _builder().build(0, common_metadata)
assert metadata.decode is not None
assert metadata.decode.seq_lens.data_ptr() == common_metadata.seq_lens.data_ptr()
assert (
metadata.decode.block_table.data_ptr()
== common_metadata.block_table_tensor.data_ptr()
)
def test_mla_cache_marker_is_promoted_to_group_capability():
kwargs = {
"block_size": 64,
"num_kv_heads": 1,
"head_size": 576,
"dtype": torch.bfloat16,
}
marked = MLAAttentionSpec(**kwargs, non_causal_multi_token_decode=True)
unmarked = MLAAttentionSpec(**kwargs)
assert MLAAttentionSpec.merge([marked, marked]).non_causal_multi_token_decode
assert not MLAAttentionSpec.merge(
[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,
)
@@ -1,240 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for MLA prefill backend fused-quant-output support.
Covers two things:
* `MLAPrefillBackend.supports_quant_output`, the capability gate that decides
whether the prefill kernel writes quantized output directly (FA4 native
fused FP8, see flash-attention#135) instead of the post-quant path.
* The numerical equivalence of that fused FP8 write versus the bf16-attention
+ standalone static-FP8-quant path it replaces (GPU-only, SM100/SM110).
"""
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from vllm.model_executor.layers.quantization.utils.quant_utils import (
kFp8Dynamic128Sym,
kFp8StaticTensorSym,
kNvfp4Dynamic,
)
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
from vllm.v1.attention.backends.mla.prefill.flash_attn import (
FlashAttnPrefillBackend,
)
_FA_MODULE = "vllm.v1.attention.backends.mla.prefill.flash_attn"
class _DummyPrefillBackend(MLAPrefillBackend):
"""Concrete backend that does NOT override supports_quant_output."""
@staticmethod
def get_name() -> str:
return "DUMMY"
def run_prefill_new_tokens(self, *args, **kwargs): # pragma: no cover
raise NotImplementedError
def run_prefill_context_chunk(self, *args, **kwargs): # pragma: no cover
raise NotImplementedError
@pytest.mark.parametrize(
"quant_key", [kFp8StaticTensorSym, kFp8Dynamic128Sym, kNvfp4Dynamic, None]
)
def test_base_backend_never_supports_quant_output(quant_key):
"""The base default opts every backend out unless it overrides."""
backend = object.__new__(_DummyPrefillBackend)
assert backend.supports_quant_output(quant_key) is False
def _make_fa_backend(version: int | None, is_vllm_fa: bool):
"""Build a FlashAttnPrefillBackend without running its heavy __init__."""
backend = object.__new__(FlashAttnPrefillBackend)
backend.vllm_flash_attn_version = version
backend._is_vllm_fa = is_vllm_fa
return backend
@pytest.mark.parametrize(
("version", "is_vllm_fa", "dc_major", "quant_key", "expected"),
[
# FA4 + vLLM-FA + Blackwell SM100/SM110 + static FP8 -> fused.
(4, True, 10, kFp8StaticTensorSym, True),
(4, True, 11, kFp8StaticTensorSym, True),
# Wrong compute capability (SM90 / SM120) -> not supported (#135).
(4, True, 9, kFp8StaticTensorSym, False),
(4, True, 12, kFp8StaticTensorSym, False),
# Not FA4.
(3, True, 10, kFp8StaticTensorSym, False),
(2, True, 10, kFp8StaticTensorSym, False),
(None, True, 10, kFp8StaticTensorSym, False),
# Upstream (ROCm) flash-attn, not vLLM-FA.
(4, False, 10, kFp8StaticTensorSym, False),
# Quant keys not wired through FA4 yet.
(4, True, 10, kFp8Dynamic128Sym, False),
(4, True, 10, kNvfp4Dynamic, False),
],
)
def test_flash_attn_supports_quant_output(
version, is_vllm_fa, dc_major, quant_key, expected
):
backend = _make_fa_backend(version, is_vllm_fa)
with patch(f"{_FA_MODULE}.current_platform") as plat:
plat.get_device_capability.return_value = DeviceCapability(
major=dc_major, minor=0
)
assert backend.supports_quant_output(quant_key) is expected
def test_flash_attn_supports_quant_output_unknown_device():
"""A None device capability (e.g. capability probe failed) is safe."""
backend = _make_fa_backend(version=4, is_vllm_fa=True)
with patch(f"{_FA_MODULE}.current_platform") as plat:
plat.get_device_capability.return_value = None
assert backend.supports_quant_output(kFp8StaticTensorSym) is False
@pytest.mark.parametrize(
("version", "enable_jit_warmup", "expected_calls"),
[(4, True, 1), (4, False, 0), (3, True, 0)],
)
def test_flash_attn_registers_warmup_only_for_fa4(
version: int,
enable_jit_warmup: bool,
expected_calls: int,
):
vllm_config = SimpleNamespace(
kernel_config=SimpleNamespace(enable_jit_warmup=enable_jit_warmup)
)
with (
patch(f"{_FA_MODULE}.flash_attn_varlen_func"),
patch(f"{_FA_MODULE}.get_flash_attn_version", return_value=version),
patch(f"{_FA_MODULE}._FA4_MLA_PREFILL_KERNEL.register_warmup") as register,
patch(f"{_FA_MODULE}.current_platform") as platform,
):
platform.get_device_capability.return_value = DeviceCapability(10, 0)
FlashAttnPrefillBackend(
num_heads=16,
scale=1.0,
kv_lora_rank=512,
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
vllm_config=vllm_config,
)
assert register.call_count == expected_calls
def test_flash_attn_prefill_backend_signature_accepts_fused_kwargs():
"""run_prefill_new_tokens must accept out/output_scale so the direct
(non-**kwargs) call in forward_mha type- and runtime-checks."""
import inspect
params = inspect.signature(
FlashAttnPrefillBackend.run_prefill_new_tokens
).parameters
assert "out" in params
assert "output_scale" in params
# The base contract must expose them too (Liskov / direct call site).
base_params = inspect.signature(MLAPrefillBackend.run_prefill_new_tokens).parameters
assert "out" in base_params
assert "output_scale" in base_params
def test_mla_impl_forward_mha_accepts_output_scale():
"""The abstract MLA impl forward_mha must carry output_scale so every
override (and the unconditional forward_impl call) stays compatible."""
import inspect
from vllm.v1.attention.backend import MLAAttentionImpl
params = inspect.signature(MLAAttentionImpl.forward_mha).parameters
assert "output_scale" in params
assert params["output_scale"].default is None
def _fused_fp8_skip_reason() -> str | None:
"""FA4 fused FP8 output needs a real Blackwell SM100/SM110 GPU."""
if not torch.cuda.is_available():
return "requires CUDA"
major = torch.cuda.get_device_capability()[0]
if major not in (10, 11):
return f"FA4 fused FP8 output requires SM100/SM110, got SM{major}x"
return None
_FUSED_FP8_SKIP = _fused_fp8_skip_reason()
@pytest.mark.skipif(_FUSED_FP8_SKIP is not None, reason=_FUSED_FP8_SKIP or "")
def test_fa4_fused_fp8_output_matches_post_quant(default_vllm_config):
"""FA4's fused FP8 write (output_scale, flash-attention#135) must match the
bf16-attention + standalone static-FP8-quant path it replaces, since
production uses the same output_scale for both."""
from vllm.model_executor.layers.quantization.input_quant_fp8 import QuantFP8
from vllm.model_executor.layers.quantization.utils.quant_utils import GroupShape
from vllm.platforms import current_platform
from vllm.vllm_flash_attn import flash_attn_varlen_func
torch.manual_seed(0)
device = torch.device("cuda")
fp8_dtype = current_platform.fp8_dtype()
# MLA prefill head dims (post kv_b_proj): q/k = qk_nope(128)+qk_rope(64),
# v = v_head_dim(128); DeepSeek-V2-Lite has 16 query heads.
num_heads, qk_head_dim, v_head_dim, seqlen = 16, 192, 128, 512
cu_seqlens = torch.tensor([0, seqlen], dtype=torch.int32, device=device)
q = torch.randn(seqlen, num_heads, qk_head_dim, dtype=torch.bfloat16, device=device)
k = torch.randn(seqlen, num_heads, qk_head_dim, dtype=torch.bfloat16, device=device)
v = torch.randn(seqlen, num_heads, v_head_dim, dtype=torch.bfloat16, device=device)
fa_kwargs = dict(
cu_seqlens_q=cu_seqlens,
cu_seqlens_k=cu_seqlens,
max_seqlen_q=seqlen,
max_seqlen_k=seqlen,
causal=True,
fa_version=4,
)
# Reference: bf16 attention, then standalone static per-tensor FP8 quant.
out_bf16 = flash_attn_varlen_func(q=q, k=k, v=v, **fa_kwargs)
out_2d = out_bf16.reshape(seqlen, num_heads * v_head_dim)
# Scale the amax near e4m3 max so the check uses the representable range.
finfo = torch.finfo(fp8_dtype)
scale = (out_2d.abs().max() / finfo.max).to(torch.float32).reshape(1)
quant_op = QuantFP8(static=True, group_shape=GroupShape.PER_TENSOR)
ref_fp8, _ = quant_op(out_2d, scale)
# Feature: FA4 writes e4m3 into the (tokens, heads*dim) buffer directly.
fused_fp8 = torch.empty(
seqlen, num_heads * v_head_dim, dtype=fp8_dtype, device=device
)
flash_attn_varlen_func(
q=q,
k=k,
v=v,
out=fused_fp8.view(seqlen, num_heads, v_head_dim),
output_scale=scale,
**fa_kwargs,
)
# Non-degenerate (catches a no-op / all-zero write).
assert torch.isfinite(fused_fp8.float()).all()
assert fused_fp8.float().abs().any()
# e4m3 has 3 mantissa bits, so allow ~1 mantissa step of rounding slack.
ref = ref_fp8.float() * scale
got = fused_fp8.float() * scale
torch.testing.assert_close(got, ref, rtol=0.125, atol=float(scale) * 2)
# ...and most elements land in the exact same fp8 bucket.
exact = (fused_fp8.view(torch.uint8) == ref_fp8.view(torch.uint8)).float().mean()
assert exact > 0.9, f"only {exact:.1%} of fused FP8 outputs matched the baseline"
@@ -1,274 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for MLA prefill backend registry."""
import gc
from unittest.mock import MagicMock
import pytest
import torch
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
from vllm.v1.attention.backends.mla.prefill.flashinfer import FlashInferPrefillBackend
from vllm.v1.attention.backends.mla.prefill.registry import (
MLAPrefillBackendEnum,
register_mla_prefill_backend,
)
from vllm.v1.attention.backends.mla.prefill.trtllm_ragged import (
TrtllmRaggedPrefillBackend,
)
from vllm.v1.worker.workspace import (
current_workspace_manager,
init_workspace_manager,
reset_workspace_manager,
)
class CustomMLAPrefillBackend(MLAPrefillBackend):
"""Mock custom MLA prefill backend for testing."""
supported_dtypes = [torch.bfloat16, torch.float16]
@staticmethod
def get_name() -> str:
return "CUSTOM"
def run_prefill_new_tokens(self, q, k, v, return_softmax_lse):
raise NotImplementedError
def run_prefill_context_chunk(self, chunk, q, k, v, out=None):
raise NotImplementedError
def test_prefill_backend_clone_has_isolated_metadata():
backend = CustomMLAPrefillBackend(
num_heads=4,
scale=0.5,
kv_lora_rank=8,
qk_nope_head_dim=16,
qk_rope_head_dim=8,
v_head_dim=32,
vllm_config=object(),
)
clone = backend.clone()
assert isinstance(clone, CustomMLAPrefillBackend)
assert clone is not backend
assert clone.num_heads == backend.num_heads
assert clone.scale == backend.scale
backend._prefill_metadata = object()
clone._prefill_metadata = object()
assert clone._prefill_metadata is not backend._prefill_metadata
@pytest.mark.parametrize(
"backend_cls", [TrtllmRaggedPrefillBackend, FlashInferPrefillBackend]
)
def test_prefill_backend_does_not_pin_grown_workspace(monkeypatch, backend_cls):
"""Reserving workspace at init must not keep a view of it: when another user
grows the shared workspace, the old buffer must be freed."""
monkeypatch.setenv("VLLM_FLASHINFER_WORKSPACE_BUFFER_SIZE", "4096")
init_workspace_manager(torch.device("cpu"))
try:
manager = current_workspace_manager()
backend = backend_cls(
num_heads=4,
scale=0.5,
kv_lora_rank=8,
qk_nope_head_dim=16,
qk_rope_head_dim=8,
v_head_dim=32,
vllm_config=MagicMock(),
)
(view,) = manager.get_simultaneous(((1,), torch.uint8))
old_storage = view.untyped_storage()._weak_ref()
del view
manager.get_simultaneous(((1 << 20,), torch.uint8))
gc.collect()
assert torch.UntypedStorage._expired(old_storage)
del backend
finally:
reset_workspace_manager()
@pytest.fixture(autouse=True)
def cleanup_overrides():
"""Clear any overrides after each test."""
yield
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)
aliases = []
for backend in all_backends:
if backend.name != "CUSTOM" and backend is MLAPrefillBackendEnum.CUSTOM:
aliases.append(backend.name)
assert len(aliases) == 0, (
f"BUG! CUSTOM is an alias of: {', '.join(aliases)}!\n"
f"CUSTOM.value = {repr(MLAPrefillBackendEnum.CUSTOM.value)}\n"
f"All MLA prefill backend values:\n"
+ "\n".join(f" {b.name}: {repr(b.value)}" for b in all_backends)
)
assert MLAPrefillBackendEnum.CUSTOM.name == "CUSTOM"
def test_custom_unregistered_raises():
with pytest.raises(ValueError, match="must be registered before use"):
MLAPrefillBackendEnum.CUSTOM.get_path()
def test_register_custom_backend_with_class_path():
register_mla_prefill_backend(
MLAPrefillBackendEnum.CUSTOM,
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
assert MLAPrefillBackendEnum.CUSTOM.is_overridden()
assert MLAPrefillBackendEnum.CUSTOM.get_class().get_name() == "CUSTOM"
def test_register_custom_backend_as_decorator():
@register_mla_prefill_backend(MLAPrefillBackendEnum.CUSTOM)
class DecoratedPrefillBackend(MLAPrefillBackend):
supported_dtypes = [torch.bfloat16]
@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, q, k, v, out=None):
raise NotImplementedError
assert MLAPrefillBackendEnum.CUSTOM.is_overridden()
assert "DecoratedPrefillBackend" in MLAPrefillBackendEnum.CUSTOM.get_path()
def test_override_existing_backend():
register_mla_prefill_backend(
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()
def test_clear_override():
original_path = MLAPrefillBackendEnum.FLASH_ATTN.get_path()
register_mla_prefill_backend(
MLAPrefillBackendEnum.FLASH_ATTN,
"tests.v1.attention.test_mla_prefill_registry.CustomMLAPrefillBackend",
)
MLAPrefillBackendEnum.FLASH_ATTN.clear_override()
assert not MLAPrefillBackendEnum.FLASH_ATTN.is_overridden()
assert MLAPrefillBackendEnum.FLASH_ATTN.get_path() == original_path
def test_unknown_backend_name_raises():
with pytest.raises(ValueError, match="Unknown MLA prefill backend"):
MLAPrefillBackendEnum["NONEXISTENT"]
def test_rocm_aiter_fa_registered():
"""ROCM_AITER_FA is a known backend pointing at the AITER FA class."""
assert "ROCM_AITER_FA" in MLAPrefillBackendEnum.__members__
path = MLAPrefillBackendEnum.ROCM_AITER_FA.get_path()
assert path == (
"vllm.v1.attention.backends.mla.prefill.aiter_flash_attn."
"AiterFlashAttnPrefillBackend"
)
backend_cls = MLAPrefillBackendEnum.ROCM_AITER_FA.get_class()
assert backend_cls.get_name() == "ROCM_AITER_FA"
# 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)
@@ -1,631 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# 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
import torch
from vllm.config import AttentionConfig, ModelConfig, VllmConfig
from vllm.platforms import current_platform
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,
)
@pytest.fixture(autouse=True)
def clear_cache():
"""Clear lru cache to ensure each test case runs without caching."""
_auto_select_mla_prefill_backend.cache_clear()
def _make_mock_model_config(
qk_nope_head_dim: int = 128,
qk_rope_head_dim: int = 64,
v_head_dim: int = 128,
dtype: torch.dtype = torch.bfloat16,
) -> ModelConfig:
mock_config = MagicMock(spec=ModelConfig)
mock_config.dtype = dtype
mock_config.hf_text_config = MagicMock()
mock_config.hf_text_config.qk_nope_head_dim = qk_nope_head_dim
mock_config.hf_text_config.qk_rope_head_dim = qk_rope_head_dim
mock_config.hf_text_config.v_head_dim = v_head_dim
return mock_config
def _make_vllm_config(
model_config: ModelConfig | None = None,
mla_prefill_backend: MLAPrefillBackendEnum | None = None,
) -> VllmConfig:
if model_config is None:
model_config = _make_mock_model_config()
attention_config = AttentionConfig(mla_prefill_backend=mla_prefill_backend)
mock_vllm_config = MagicMock(spec=VllmConfig)
mock_vllm_config.model_config = model_config
mock_vllm_config.attention_config = attention_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()
with patch("vllm.platforms.current_platform") as mock_platform:
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()
class FlashAttnBackend:
@staticmethod
def get_name():
return "FLASH_ATTN"
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"
def test_explicit_flash_attn_selection(self):
try:
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
except ImportError:
pytest.skip("FLASH_ATTN backend not available")
return
vllm_config = _make_vllm_config(
mla_prefill_backend=MLAPrefillBackendEnum.FLASH_ATTN,
)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.is_cpu.return_value = False
mock_platform.get_device_capability.return_value = DeviceCapability(
major=9, minor=0
)
with patch.object(
flash_attn_cls,
"validate_configuration",
return_value=[],
):
backend = get_mla_prefill_backend(vllm_config)
assert backend.get_name() == "FLASH_ATTN"
def test_explicit_backend_invalid_raises_error(self):
vllm_config = _make_vllm_config(
mla_prefill_backend=MLAPrefillBackendEnum.FLASHINFER,
)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.is_cpu.return_value = False
mock_platform.get_device_capability.return_value = DeviceCapability(
major=9, minor=0
)
with pytest.raises(ValueError, match="is not valid"):
get_mla_prefill_backend(vllm_config)
def test_explicit_backend_import_error_raises(self):
vllm_config = _make_vllm_config(
mla_prefill_backend=MLAPrefillBackendEnum.TRTLLM_RAGGED,
)
with patch("vllm.platforms.current_platform") as mock_platform:
mock_platform.is_cpu.return_value = False
mock_platform.get_device_capability.return_value = DeviceCapability(
major=10, minor=0
)
with (
patch.object(
MLAPrefillBackendEnum.TRTLLM_RAGGED,
"get_class",
side_effect=ImportError("trtllm not installed"),
),
pytest.raises(ValueError, match="is not valid"),
):
get_mla_prefill_backend(vllm_config)
@pytest.mark.parametrize(
("qk_nope_head_dim", "v_head_dim"),
[(128, 128), (192, 256), (64, 128)],
ids=["deepseek", "glm", "mistral_s4"],
)
def test_auto_selection_on_hopper(self, qk_nope_head_dim: int, v_head_dim: int):
try:
flash_attn_cls = MLAPrefillBackendEnum.FLASH_ATTN.get_class()
except ImportError:
pytest.skip("FLASH_ATTN backend not available")
return
vllm_config = _make_vllm_config(
_make_mock_model_config(
qk_nope_head_dim=qk_nope_head_dim,
v_head_dim=v_head_dim,
)
)
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(flash_attn_cls, "is_available", return_value=True),
patch(
"vllm.v1.attention.backends.mla.prefill.flash_attn."
"get_flash_attn_version",
return_value=3,
),
):
mock_platform.is_cpu.return_value = False
mock_platform.get_device_capability.return_value = DeviceCapability(
major=9, minor=0
)
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"
class TestAutoSelectMLAPrefillBackend:
"""Tests for fallback and error paths in auto-selection."""
def test_blackwell_glm_dimensions_use_trtllm(self):
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=192,
qk_rope_head_dim=64,
v_head_dim=256,
),
)
try:
trtllm_cls = MLAPrefillBackendEnum.TRTLLM_RAGGED.get_class()
except ImportError:
pytest.skip("MLA prefill backend not available")
return
with (
patch("vllm.platforms.current_platform") as mock_platform,
patch.object(trtllm_cls, "validate_configuration", return_value=[]),
):
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_platform_hook_raises_propagates(self):
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
)
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:
"""Tests for backend validation logic."""
def test_backend_supported_dimension_validation(self):
try:
from vllm.v1.attention.backends.mla.prefill.flashinfer import (
FlashInferPrefillBackend,
)
from vllm.v1.attention.backends.mla.prefill.trtllm_ragged import (
TrtllmRaggedPrefillBackend,
)
except ImportError:
pytest.skip("MLA prefill backend not available")
return
capability = DeviceCapability(major=10, minor=0)
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
),
)
with patch.object(FlashInferPrefillBackend, "is_available", return_value=True):
invalid_reasons = FlashInferPrefillBackend.validate_configuration(
capability,
selector_config,
)
assert len(invalid_reasons) == 0
selector_config_invalid = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=64,
qk_rope_head_dim=64,
v_head_dim=128,
),
)
with patch.object(FlashInferPrefillBackend, "is_available", return_value=True):
invalid_reasons = FlashInferPrefillBackend.validate_configuration(
capability,
selector_config_invalid,
)
assert len(invalid_reasons) == 1
assert "supported MLA dimensions" in invalid_reasons[0]
selector_config_glm5 = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=192,
qk_rope_head_dim=64,
v_head_dim=256,
),
)
with patch.object(
TrtllmRaggedPrefillBackend, "is_available", return_value=True
):
invalid_reasons = TrtllmRaggedPrefillBackend.validate_configuration(
capability,
selector_config_glm5,
)
assert invalid_reasons == []
def test_flash_attn_accepts_glm53_flash_nope_dimensions(self):
"""(256, 0, 256) runs the same FA kernels as GLM-5's (192, 64, 256); a
RoPE-carrying 320-wide query does not."""
try:
from vllm.v1.attention.backends.mla.prefill.flash_attn import (
FlashAttnPrefillBackend,
)
except ImportError:
pytest.skip("MLA prefill backend not available")
return
capability = DeviceCapability(major=10, minor=0)
def validate(qk_rope_head_dim: int) -> list[str]:
selector_config = MLAPrefillSelectorConfig(
dtype=torch.bfloat16,
mla_dimensions=MLADimensions(
qk_nope_head_dim=256,
qk_rope_head_dim=qk_rope_head_dim,
v_head_dim=256,
),
)
with patch.object(
FlashAttnPrefillBackend, "is_available", return_value=True
):
return FlashAttnPrefillBackend.validate_configuration(
capability, selector_config
)
assert validate(qk_rope_head_dim=0) == []
invalid_reasons = validate(qk_rope_head_dim=64)
assert len(invalid_reasons) == 1
assert "supported MLA dimensions" in invalid_reasons[0]
@pytest.mark.skipif(
not current_platform.is_cuda_alike(),
reason="Imports vllm.platforms.rocm, whose module init requires a CUDA or "
"ROCm torch build; not importable on XPU/CPU/TPU.",
)
class TestROCmAiterFAPrefillSelection:
"""Tests for the ROCm AITER FlashAttention MLA prefill backend."""
def test_rocm_priorities_prefer_aiter_fa(self):
"""On ROCm, ROCM_AITER_FA is tried first, FLASH_ATTN as fallback."""
from vllm.platforms.rocm import RocmPlatform
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,
]
def test_supported_dtypes_are_fp16_bf16_only(self):
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
AiterFlashAttnPrefillBackend,
)
assert AiterFlashAttnPrefillBackend.supports_dtype(torch.bfloat16)
assert AiterFlashAttnPrefillBackend.supports_dtype(torch.float16)
# FP8 is served by the separate AITER ASM backend, not this one.
assert not AiterFlashAttnPrefillBackend.supports_dtype(torch.float8_e4m3fn)
def test_supports_compute_capability_on_rocm(self):
from vllm.v1.attention.backends.mla.prefill import aiter_flash_attn as mod
# Gating is decided by on_mi3xx(), not by capability
capability = MagicMock()
with patch.object(mod.current_platform, "is_rocm", return_value=False):
assert not mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
capability
)
with (
patch.object(mod.current_platform, "is_rocm", return_value=True),
patch("vllm.platforms.rocm.on_mi3xx", return_value=False),
):
assert not mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
capability
)
with (
patch.object(mod.current_platform, "is_rocm", return_value=True),
patch("vllm.platforms.rocm.on_mi3xx", return_value=True),
):
assert mod.AiterFlashAttnPrefillBackend.supports_compute_capability(
capability
)
def test_is_available_delegates_to_rocm_aiter_ops(self):
from vllm._aiter_ops import rocm_aiter_ops
from vllm.v1.attention.backends.mla.prefill import aiter_flash_attn as mod
with patch.object(rocm_aiter_ops, "is_enabled", return_value=False):
assert not mod.AiterFlashAttnPrefillBackend.is_available()
with patch.object(rocm_aiter_ops, "is_enabled", return_value=True):
assert mod.AiterFlashAttnPrefillBackend.is_available()
def test_auto_select_prefers_aiter_fa_on_rocm(self):
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
AiterFlashAttnPrefillBackend,
)
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
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):
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 get_mla_prefill_backend_cls,
# not the capability.
selector_config = MLAPrefillSelectorConfig(dtype=torch.bfloat16)
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"
class TestMLAPrefillBackendParsing:
"""Tests for string-based mla_prefill_backend parsing from CLI args."""
def test_valid_string_parses_to_enum(self):
config = AttentionConfig(
mla_prefill_backend="FLASH_ATTN",
)
assert config.mla_prefill_backend == MLAPrefillBackendEnum.FLASH_ATTN
def test_invalid_string_raises_error(self):
with pytest.raises(ValueError, match="Unknown MLA prefill backend"):
AttentionConfig(
mla_prefill_backend="NONEXISTENT",
)
class TestMLAPrefillBackendConfig:
"""Tests for mla_prefill_backend configuration in AttentionConfig."""
def test_default_backend_is_none(self):
config = AttentionConfig()
assert config.mla_prefill_backend is None
def test_explicit_flash_attn_backend(self):
config = AttentionConfig(
mla_prefill_backend=MLAPrefillBackendEnum.FLASH_ATTN,
)
assert config.mla_prefill_backend == MLAPrefillBackendEnum.FLASH_ATTN
def test_explicit_trtllm_ragged_backend(self):
config = AttentionConfig(
mla_prefill_backend=MLAPrefillBackendEnum.TRTLLM_RAGGED,
)
assert config.mla_prefill_backend == MLAPrefillBackendEnum.TRTLLM_RAGGED
-885
View File
@@ -1,885 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""mm_prefix query-range metadata and the FA4 mask_mod that consumes it.
The metadata tests run anywhere. The FA4 tests need SM100 and run the real
kernel against a dense float32 reference, which is the only way to check what
cannot be reasoned about from the Python side:
* ``q_ranges[token_idx, 0]`` indexing an aux tensor with a runtime ``Int32``.
* ``cu_seqlens_q[b] + q_local`` matching FA4's own packing of a varlen batch.
The mask_mod is the *entire* mask (``(causal ∧ window) ∨ mm_prefix``), so
callers must pass ``causal=False`` and no FA-layer window. FA #155 stopped
auto-clearing those when ``mask_mod`` is set; leaving ``causal=True`` would
short out the mask_mod on SM90 and clip bidirectional ranges on SM100.
"""
import numpy as np
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.attention.backends.utils import (
fill_mm_prefix_query_ranges,
)
from vllm.v1.kv_cache_interface import KVCacheLayout
def _fa4_available() -> bool:
if not current_platform.is_cuda():
return False
from vllm.v1.attention.backends.fa_utils import is_fa_version_supported
return is_fa_version_supported(4)
requires_fa4 = pytest.mark.skipif(
not _fa4_available(), reason="FA4 mm_prefix mask_mod requires FA4"
)
# Imported conditionally because these pull in CuTe / FA4 build artifacts that
# are absent wherever requires_fa4 skips.
if _fa4_available():
from types import MethodType
from tests.v1.attention.test_attention_backends import (
MockAttentionLayer,
create_and_prepopulate_kv_cache,
)
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
create_standard_kv_cache_spec,
create_vllm_config,
)
from vllm.config import set_current_vllm_config
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
from vllm.v1.attention.backends.flash_attn import (
FlashAttentionImpl,
FlashAttentionMetadataBuilder,
_make_mm_prefix_mask_mod,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec, get_kv_quant_mode
from vllm.vllm_flash_attn.flash_attn_interface import flash_attn_varlen_func
DEVICE = torch.device("cuda:0")
DTYPE = torch.bfloat16
HEAD_SIZE = 128
NUM_HEADS = 8
NUM_KV_HEADS = 8
SLIDING_WINDOW_LEFT = 129
# --------------------------------------------------------------------------- #
# Metadata construction
# --------------------------------------------------------------------------- #
# Stands in for the builder's persistent (max_num_batched_tokens, 2) buffer.
STAGING_CAPACITY = 64
def _query_ranges(mm_ranges, query_lens, seq_lens):
"""Fill a staging buffer and return the written rows, or None if empty."""
query_start_loc = torch.tensor(
[0, *torch.tensor(query_lens).cumsum(0).tolist()], dtype=torch.int32
)
# Poison the buffer so a stale row surviving the fill is visible.
out = np.full((STAGING_CAPACITY, 2), 12345, dtype=np.int32)
num_tokens = fill_mm_prefix_query_ranges(
out,
mm_ranges,
query_start_loc,
torch.tensor(seq_lens, dtype=torch.int32),
)
if num_tokens == 0:
return None
return torch.from_numpy(out[:num_tokens])
def test_matches_range_scan_semantics_with_context_offset():
"""Pin the equivalence the O(1) lookup rests on.
The kernel checks ``r_start <= kv_idx <= r_end`` for the range containing
the query token, which is only equal to the old scan's
``any(q in r and kv in r)`` because ranges never overlap. Request 1 carries
a context offset so the local-to-absolute query mapping is exercised too.
"""
mm_ranges = {0: [(1, 3), (5, 7)], 1: [(2, 4), (9, 12)]}
query_lens = [8, 6]
seq_lens = [8, 13]
query_ranges = _query_ranges(mm_ranges, query_lens, seq_lens)
assert query_ranges is not None
token_start = 0
for req_idx, query_len in enumerate(query_lens):
context_len = seq_lens[req_idx] - query_len
for q_local in range(query_len):
q_abs = context_len + q_local
r_start, r_end = query_ranges[token_start + q_local].tolist()
for kv_idx in range(seq_lens[req_idx]):
old_scan_keep = any(
start < end and start <= q_abs <= end and start <= kv_idx <= end
for start, end in mm_ranges[req_idx]
)
new_keep = r_start <= kv_idx <= r_end
assert new_keep == old_scan_keep, (req_idx, q_abs, kv_idx)
token_start += query_len
def test_ranges_beyond_scheduled_chunk_are_clipped():
"""Chunked prefill must not error or produce a wrong mask.
``disable_chunked_mm_input`` keeps a single mm item intact but still splits
a prompt across steps, so a request's ranges routinely sit entirely past the
tokens scheduled so far. Sizing by query token makes the out-of-chunk part
a no-op rather than an out-of-bounds condition.
"""
# Step 1 of "TTTT IIIIII": only the 4 text tokens are scheduled, so the
# range is entirely ahead of the chunk. The old bounds check raised here.
assert _query_ranges({0: [(4, 9)]}, query_lens=[4], seq_lens=[4]) is None
# A range starting mid-chunk and running past its end keeps its absolute
# bounds, so the bidirectional block still reaches the range's later keys
# once they are cached. Query tokens here are absolute positions 2..5.
query_ranges = _query_ranges({0: [(4, 9)]}, query_lens=[4], seq_lens=[6])
assert query_ranges is not None
expected = torch.tensor([[-1, -1], [-1, -1], [4, 9], [4, 9]], dtype=torch.int32)
torch.testing.assert_close(query_ranges, expected)
def test_buffer_reuse_does_not_leak_previous_rows():
"""The staging buffer persists across steps, so every reported row must be
rewritten. Guards against dropping the ``-1`` fill as an optimization: a
step whose ranges shrink would otherwise expose the prior step's bounds and
silently widen the bidirectional mask.
"""
out = np.zeros((STAGING_CAPACITY, 2), dtype=np.int32)
query_start_loc = torch.tensor([0, 8], dtype=torch.int32)
seq_lens = torch.tensor([8], dtype=torch.int32)
num_tokens = fill_mm_prefix_query_ranges(
out, {0: [(0, 7)]}, query_start_loc, seq_lens
)
assert num_tokens == 8
np.testing.assert_array_equal(out[:8], np.tile([0, 7], (8, 1)))
# Same rows scheduled, but now only tokens 2..3 sit inside a range.
num_tokens = fill_mm_prefix_query_ranges(
out, {0: [(2, 3)]}, query_start_loc, seq_lens
)
assert num_tokens == 8
expected = np.full((8, 2), -1, dtype=np.int32)
expected[2:4] = (2, 3)
np.testing.assert_array_equal(out[:8], expected)
def test_returns_none_when_no_range_covers_a_query_token():
"""No aux tensor means forward() skips the mask_mod entirely.
Returning None rather than an all-``-1`` tensor is what keeps text-only and
decode-only batches off the fill path.
"""
# Text-only batch on an mm_prefix model: every request present, no ranges.
assert _query_ranges({0: [], 1: []}, query_lens=[2, 2], seq_lens=[2, 2]) is None
# Degenerate single-token ranges are skipped, matching the Triton path's
# `start < end` validity check.
assert _query_ranges({0: [(1, 1)]}, query_lens=[4], seq_lens=[4]) is None
# Decode rows: the query token is generated, so it is in no range.
assert _query_ranges({0: [(1, 3)]}, query_lens=[1], seq_lens=[9]) is None
# --------------------------------------------------------------------------- #
# FA4 kernel
# --------------------------------------------------------------------------- #
def _cu_seqlens(lens: list[int]) -> torch.Tensor:
out = torch.zeros(len(lens) + 1, dtype=torch.int32)
out[1:] = torch.tensor(lens, dtype=torch.int32).cumsum(0)
return out
def _dense_reference(
q,
k_per_req,
v_per_req,
query_lens,
seq_lens,
mm_ranges,
sliding_window_left,
scale,
mm_clamp_sw=0,
):
"""Dense float32 ``(causal AND window) OR mm_prefix`` per request.
``mm_clamp_sw`` confines the bidirectional block to the window, reproducing
Gemma4's ``mm_prefix_clamp_sliding_window``. Only the past bound applies, so
future keys inside a range still pass.
"""
out = torch.empty_like(q, dtype=torch.float32)
repeats = q.shape[1] // k_per_req[0].shape[1]
q_off = 0
for req_idx, (q_len, k_len) in enumerate(zip(query_lens, seq_lens)):
ctx = k_len - q_len
q_pos = torch.arange(q_len, device=q.device) + ctx
k_pos = torch.arange(k_len, device=q.device)
delta = q_pos[:, None] - k_pos[None, :]
keep = delta >= 0
if sliding_window_left is not None:
keep &= delta < sliding_window_left
for start, end in mm_ranges.get(req_idx, []):
if start >= end:
continue
q_in = (q_pos >= start) & (q_pos <= end)
k_in = (k_pos >= start) & (k_pos <= end)
mm = q_in[:, None] & k_in[None, :]
if mm_clamp_sw > 0:
mm &= delta < mm_clamp_sw
keep |= mm
q_i = q[q_off : q_off + q_len].float().transpose(0, 1)
k_i = k_per_req[req_idx].float().transpose(0, 1)
v_i = v_per_req[req_idx].float().transpose(0, 1)
if repeats > 1:
k_i = k_i.repeat_interleave(repeats, dim=0)
v_i = v_i.repeat_interleave(repeats, dim=0)
scores = (q_i @ k_i.transpose(-1, -2)) * scale
scores = scores.masked_fill(~keep[None], float("-inf"))
out[q_off : q_off + q_len] = (scores.softmax(-1) @ v_i).transpose(0, 1)
q_off += q_len
return out
def _split(packed: torch.Tensor, lens: list[int]) -> list[torch.Tensor]:
return list(packed.split(lens))
def _reference(q, k, v, query_lens, seq_lens, mm_ranges, sw_left, scale, **kwargs):
return _dense_reference(
q,
_split(k, seq_lens),
_split(v, seq_lens),
query_lens,
seq_lens,
mm_ranges,
sw_left,
scale,
**kwargs,
)
def _run_kernel(
q, k, v, query_lens, seq_lens, mm_ranges, sliding_window_left, scale, mm_clamp_sw=0
):
cu_q = _cu_seqlens(query_lens)
cu_k = _cu_seqlens(seq_lens)
staging = torch.full((int(cu_q[-1]), 2), 12345, dtype=torch.int32).numpy()
num_rows = fill_mm_prefix_query_ranges(
staging, mm_ranges, cu_q, torch.tensor(seq_lens, dtype=torch.int32)
)
assert num_rows > 0, "test case must have at least one in-range query token"
q_ranges = torch.from_numpy(staging[:num_rows]).to(DEVICE)
cu_q_gpu = cu_q.to(DEVICE)
out = torch.empty_like(q)
flash_attn_varlen_func(
q=q,
k=k,
v=v,
out=out,
cu_seqlens_q=cu_q_gpu,
cu_seqlens_k=cu_k.to(DEVICE),
max_seqlen_q=max(query_lens),
max_seqlen_k=max(seq_lens),
softmax_scale=scale,
causal=False,
fa_version=4,
mask_mod=_make_mm_prefix_mask_mod(
sliding_window=mm_clamp_sw, sliding_window_left=sliding_window_left
),
aux_tensors=[q_ranges, cu_q_gpu],
)
return out
def _randn_qkv(query_lens, seq_lens):
torch.manual_seed(0)
q = torch.randn(sum(query_lens), NUM_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
k = torch.randn(sum(seq_lens), NUM_KV_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
v = torch.randn(sum(seq_lens), NUM_KV_HEADS, HEAD_SIZE, dtype=DTYPE, device=DEVICE)
return q, k, v, HEAD_SIZE**-0.5
# (name, query_lens, seq_lens, mm_ranges). One shape per index computation the
# mask_mod performs; shapes that differ only in request count are omitted.
CASES = [
# cu_seqlens_q[b] + q_local: unequal query lens across the batch, the
# packing the pooling workload never produced.
(
"varlen_batch",
[128, 64, 200],
[128, 64, 200],
{0: [(8, 71)], 1: [(0, 31), (40, 55)], 2: [(64, 191)]},
),
# q_abs = q_idx + (seqlen_k - seqlen_q): ranges are absolute prompt
# positions, so part of each range sits in the context.
(
"context_offset",
[64],
[320],
{0: [(32, 95), (200, 287)]},
),
# Decode rows: the query token is generated, so it is in no range and must
# get the (-1, -1) sentinel. One prefill row keeps the batch mixed.
(
"mixed_prefill_decode",
[160, 1, 1, 1],
[160, 512, 300, 97],
{0: [(32, 127)], 1: [(4, 259)], 2: [(8, 71)], 3: [(1, 64)]},
),
]
# A 320-token range, wider than the window. Every CASES range is narrower than
# the window and therefore clamp-insensitive, so the window modes are exercised
# on this shape instead: images larger than the window are exactly why
# mm_prefix_clamp_sliding_window exists.
WIDE_RANGE_CASE = ([384], [384], {0: [(32, 351)]})
# (sliding_window_left, mm_clamp_sw). sliding_window_left selects between the
# two mask_mod variants; mm_clamp_sw gates the Gemma4 clamp inside the sliding
# one. Gemma4 sets mm_clamp_sw == sw_val, and the unclamped variant ignores
# mm_clamp_sw, so a clamp without a window is not a reachable configuration.
WINDOW_MODES = [
(None, 0),
(SLIDING_WINDOW_LEFT, 0),
(SLIDING_WINDOW_LEFT, SLIDING_WINDOW_LEFT),
]
WINDOW_IDS = ["full_causal", "window", "window_clamped"]
@requires_fa4
@pytest.mark.parametrize("case", CASES, ids=[c[0] for c in CASES])
def test_mm_prefix_mask_mod_matches_dense_reference(case):
_, query_lens, seq_lens, mm_ranges = case
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
args = (q, k, v, query_lens, seq_lens, mm_ranges, SLIDING_WINDOW_LEFT, scale)
torch.testing.assert_close(
_run_kernel(*args).float(), _reference(*args), atol=2e-2, rtol=2e-2
)
@requires_fa4
@pytest.mark.parametrize("window_mode", WINDOW_MODES, ids=WINDOW_IDS)
def test_window_modes_on_a_range_wider_than_the_window(window_mode):
"""Cover the three reachable window configurations.
The clamped mode additionally asserts the clamp changes the mask at all,
without which a range narrower than the window would leave the clamp branch
unexercised while the test still passed.
"""
sliding_window_left, mm_clamp_sw = window_mode
query_lens, seq_lens, mm_ranges = WIDE_RANGE_CASE
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
args = (q, k, v, query_lens, seq_lens, mm_ranges, sliding_window_left, scale)
expected = _reference(*args, mm_clamp_sw=mm_clamp_sw)
if mm_clamp_sw:
assert not torch.allclose(
expected, _reference(*args, mm_clamp_sw=0), atol=2e-2, rtol=2e-2
), "range is not wide enough to exercise the clamp branch"
actual = _run_kernel(*args, mm_clamp_sw=mm_clamp_sw)
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
@requires_fa4
def test_ranges_outside_chunk_degrade_to_causal():
"""A range fully behind the scheduled chunk must not widen the mask.
Under chunked prefill a request's ranges routinely sit entirely in the
already-computed context. Indexing by query token makes those a no-op; the
result must be identical to running with no ranges at all.
"""
query_lens, seq_lens = [64], [512]
q, k, v, scale = _randn_qkv(query_lens, seq_lens)
# Range (16, 79) is entirely below the chunk start (448), plus one live
# range so the fill still reports rows.
args = (q, k, v, query_lens, seq_lens)
actual = _run_kernel(*args, {0: [(16, 79), (448, 511)]}, None, scale)
expected = _reference(*args, {0: [(448, 511)]}, None, scale)
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
# --------------------------------------------------------------------------- #
# FA4 through the metadata builder and the paged KV cache
# --------------------------------------------------------------------------- #
# Stock google/gemma-4-E2B-it ships text_config.use_bidirectional_attention as
# null, so is_mm_prefix_lm is False out of the box. Tests that exercise the
# builder must flip it via `_enable_mm_prefix`. Only config.json / tokenizer
# are read; weights are never loaded.
MODEL = "google/gemma-4-E2B-it"
BLOCK_SIZE = 16
SLIDING_WINDOW = 256
# Request 0 is a prefill chunk whose range starts mid-context; requests 1-3 are
# decodes whose generated token sits outside every range.
PAGED_SEQ_LENS = [352, 513, 200, 97]
PAGED_QUERY_LENS = [96, 1, 1, 1]
PAGED_MM_RANGES = {
0: [(224, 287), (300, 351)],
1: [(4, 259)],
2: [(0, 63), (80, 143)],
3: [(1, 64)],
}
def _enable_mm_prefix(vllm_config):
"""Flip stock Gemma4's null use_bidirectional_attention to "vision".
``ModelConfig.__init__`` derives ``model_arch_config`` once from
``hf_text_config``, and ``is_mm_prefix_lm`` is a ``cached_property`` that
may already hold False from that first derivation, so re-derive and drop
the cache.
"""
model_config = vllm_config.model_config
model_config.hf_text_config.use_bidirectional_attention = "vision"
model_config.model_arch_config = model_config.get_model_arch_config()
model_config.__dict__.pop("is_mm_prefix_lm", None)
return vllm_config
@requires_fa4
def test_decode_only_batch_reports_no_ranges():
"""Decode-only steps must carry no mm_prefix metadata at all.
This is what makes FULL CUDA graph capture consistent for this feature.
Capture runs through ``_dummy_run`` with no multimodal requests, so no
mask_mod is attached to the captured graph; a decode-only replay must
therefore also want no mask_mod, or the captured graph would silently drop
it. Indexing by query token gives that for free, because a generated token
is always past every prompt range.
The range-id scheme keyed off the request having ranges at all, so it
attached a mask_mod to decode steps and did not have this property.
"""
vllm_config = _enable_mm_prefix(
create_vllm_config(
model_name=MODEL,
max_model_len=1024,
block_size=BLOCK_SIZE,
num_gpu_blocks=256,
)
)
decode_batch = BatchSpec(
seq_lens=[513, 200, 97], query_lens=[1, 1, 1], name="decode_only"
)
common = create_common_attn_metadata(decode_batch, BLOCK_SIZE, DEVICE)
common.mm_req_doc_ranges = {0: [(4, 259)], 1: [(0, 63)], 2: [(1, 64)]}
builder = FlashAttentionMetadataBuilder(
create_standard_kv_cache_spec(vllm_config),
["model.layers.0.self_attn.attn"],
vllm_config,
DEVICE,
)
md = builder.build(common_prefix_len=0, common_attn_metadata=common)
assert md.mm_prefix_query_range_tensor is None
@requires_fa4
@pytest.mark.parametrize(
"head_size",
[
# 128: FA4's default SM100 path (not the dedicated hd256 kernel), so
# paged KV + seqused_k works on B200 and H100. Non-paged mm_prefix
# cases in this file already use HEAD_SIZE=128.
pytest.param(128, id="hd128"),
# 512: Gemma4 global head dim; FA4 resolves on H100, skips on
# Blackwell (TMEM).
pytest.param(512, id="global_512"),
],
)
def test_mm_prefix_kv_cache_path(head_size: int):
"""FA4 + mask_mod + block_table matches a dense reference.
Use head_size=128 on B200/H100 (FA4 + paged/`seqused_k` supported) and
512 on H100 only (Blackwell FA4 rejects 512 via TMEM). Avoid 256: SM100's
dedicated hd256 2CTA kernel asserts away ``seqused_k``, which paged KV
requires.
Tensors, kv_cache_spec, and FlashAttentionImpl must all use the same
``head_size`` — ``run_attention_backend`` / ``create_standard_kv_cache_spec``
read ``get_head_size()`` (=512 for Gemma4), so this test builds them
explicitly. The sliding window is set on the impl; mm_prefix encodes it in
mask_mod and clears FA's built-in window at forward time.
"""
torch.manual_seed(0)
vllm_config = _enable_mm_prefix(
create_vllm_config(
model_name=MODEL,
max_model_len=max(PAGED_SEQ_LENS),
block_size=BLOCK_SIZE,
num_gpu_blocks=2048,
)
)
assert vllm_config.model_config.is_mm_prefix_lm
mc = vllm_config.model_config
# Keep every get_head_size() reader (builder helpers, etc.) on the same dim.
mc.get_head_size = MethodType(lambda self: head_size, mc)
# Skip under the same config Gemma4 forces (flash_attn_version=4), so the
# check matches FlashAttentionImpl's get_flash_attn_version call.
with set_current_vllm_config(vllm_config):
if get_flash_attn_version(head_size=head_size) != 4:
pytest.skip(f"FA4 does not support head_size={head_size} on this device")
num_heads = mc.get_num_attention_heads(vllm_config.parallel_config)
num_kv_heads = mc.get_num_kv_heads(vllm_config.parallel_config)
scale = head_size**-0.5
batch = BatchSpec(
seq_lens=PAGED_SEQ_LENS, query_lens=PAGED_QUERY_LENS, name="mm_prefix_mixed"
)
kv_cache_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=num_kv_heads,
head_size=head_size,
dtype=mc.dtype,
sliding_window=SLIDING_WINDOW,
kv_quant_mode=get_kv_quant_mode(vllm_config.cache_config.cache_dtype),
)
common = create_common_attn_metadata(batch, BLOCK_SIZE, DEVICE)
common.mm_req_doc_ranges = PAGED_MM_RANGES
qs, new_ks, new_vs, k_fulls, v_fulls, k_ctxs, v_ctxs = [], [], [], [], [], [], []
for q_len, s_len in zip(PAGED_QUERY_LENS, PAGED_SEQ_LENS):
ctx = s_len - q_len
shape = (num_kv_heads, head_size)
qs.append(torch.randn(q_len, num_heads, head_size, dtype=DTYPE, device=DEVICE))
k_full = torch.randn(s_len, *shape, dtype=DTYPE, device=DEVICE)
v_full = torch.randn(s_len, *shape, dtype=DTYPE, device=DEVICE)
k_fulls.append(k_full)
v_fulls.append(v_full)
k_ctxs.append(k_full[:ctx])
v_ctxs.append(v_full[:ctx])
new_ks.append(k_full[ctx:])
new_vs.append(v_full[ctx:])
query = torch.cat(qs)
key = torch.cat(new_ks)
value = torch.cat(new_vs)
kv_cache = create_and_prepopulate_kv_cache(
k_contexts=k_ctxs,
v_contexts=v_ctxs,
block_size=BLOCK_SIZE,
num_kv_heads=num_kv_heads,
head_size=head_size,
dtype=DTYPE,
device=DEVICE,
num_blocks=2048,
common_attn_metadata=common,
layout=KVCacheLayout.LBNHC,
randomize_blocks=True,
)
# Packed KV layout is [..., 2 * head_size]; impl.split(head_size) needs match.
assert kv_cache.shape[-1] == 2 * head_size
layer_names = ["model.layers.0.self_attn.attn"]
with set_current_vllm_config(vllm_config):
builder = FlashAttentionMetadataBuilder(
kv_cache_spec, layer_names, vllm_config, DEVICE
)
attn_metadata = builder.build(common_prefix_len=0, common_attn_metadata=common)
# head_size=128 keeps FA4 under local attention on Blackwell (the
# FA4→FA2 demotion is only for local+256). Window is still encoded in
# mask_mod at forward; FA's built-in window is cleared there.
impl = FlashAttentionImpl(
num_heads=num_heads,
head_size=head_size,
scale=scale,
num_kv_heads=num_kv_heads,
alibi_slopes=None,
sliding_window=SLIDING_WINDOW,
kv_cache_dtype="auto",
)
assert impl.vllm_flash_attn_version == 4, (
f"expected FA4, got FA{impl.vllm_flash_attn_version} for "
f"head_size={head_size}"
)
assert impl.head_size == head_size == kv_cache_spec.head_size
mock_layer = MockAttentionLayer(DEVICE)
output = torch.empty_like(query)
impl.do_kv_cache_update(
mock_layer, key, value, kv_cache, attn_metadata.slot_mapping
)
actual = impl.forward(
mock_layer, query, key, value, kv_cache, attn_metadata, output=output
)
ref_args = (query, k_fulls, v_fulls, PAGED_QUERY_LENS, PAGED_SEQ_LENS)
expected = _dense_reference(*ref_args, PAGED_MM_RANGES, SLIDING_WINDOW, scale)
torch.testing.assert_close(actual.float(), expected, atol=2e-2, rtol=2e-2)
# Without this the assertion above would also pass if the mask_mod were
# silently dropped, since the batch would then be plain causal + window.
causal_only = _dense_reference(*ref_args, {}, SLIDING_WINDOW, scale)
assert not torch.allclose(expected, causal_only, atol=2e-2, rtol=2e-2), (
"test batch does not actually exercise the mm_prefix branch"
)
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA backend imports")
@pytest.mark.parametrize(
"query_len,seq_len,spans,expected,unclamped_expected",
[
(16, 32, [(20, 28)], True, True),
(16, 32, [(0, 16)], False, True),
(16, 32, [(0, 17)], True, True),
(16, 32, [(32, 40)], False, False),
(16, 32, [(31, 40)], False, True),
(1, 24, [(20, 28)], False, True),
(0, 24, [(20, 28)], False, False),
(16, 32, [(20, 20)], False, False),
(16, 64, [(20, 28)], False, False),
],
)
def test_composite_routes_queries_that_need_image_masking(
query_len, seq_len, spans, expected, unclamped_expected
):
"""Historical images and single-query steps must use the causal graph path."""
from types import SimpleNamespace
from vllm.v1.attention.backends.composite import requires_mm_prefix
common = SimpleNamespace(
max_query_len=query_len,
mm_req_doc_ranges={0: spans},
query_start_loc_cpu=torch.tensor([0, query_len]),
seq_lens_cpu_upper_bound=torch.tensor([seq_len]),
)
assert requires_mm_prefix(common) is expected
assert requires_mm_prefix(common, unclamped_window=True) is unclamped_expected
@pytest.mark.skipif(not current_platform.is_cuda(), reason="CUDA attention kernels")
@pytest.mark.parametrize("head_size", [256, 512])
@pytest.mark.parametrize(
"reverse_children,cache_dtype",
[(False, "auto"), (True, "auto"), (False, "fp8_e4m3")],
)
@pytest.mark.parametrize("causal_backend_name", ["FLASHINFER", "FLASH_ATTN"])
def test_composite_shared_cache_across_image_and_causal_steps(
head_size, reverse_children, cache_dtype, causal_backend_name
):
"""Changing routes must preserve KV writes, image masking and graph replay."""
if causal_backend_name == "FLASHINFER":
if not current_platform.is_device_capability_family(100):
pytest.skip("The Triton/FlashInfer composite supports Blackwell")
else:
if not current_platform.is_device_capability(90):
pytest.skip("The Triton/FlashAttention composite supports Hopper")
if reverse_children or cache_dtype != "auto":
pytest.skip("Reverse-child and FP8 coverage is backend-independent")
from vllm.config import set_current_vllm_config
from vllm.engine.arg_utils import EngineArgs
from vllm.model_executor.layers.attention import Attention
from vllm.utils.torch_utils import set_default_torch_dtype
from vllm.v1.attention.backend import AttentionCGSupport, CommonAttentionMetadata
from vllm.v1.attention.backends.composite import (
MMPrefixAttentionRouting,
create_composite_attention_backend,
)
from vllm.v1.attention.backends.flash_attn import (
FlashAttentionMetadata,
)
from vllm.v1.attention.backends.flashinfer import (
FlashInferBackend,
FlashInferMetadata,
FlashInferTrtllmAPIDecode,
TRTLLMPrefill,
)
from vllm.v1.attention.backends.triton_attn import (
TritonAttentionBackend,
TritonAttentionMetadata,
)
from vllm.v1.attention.backends.triton_flash_attn import (
TritonFlashAttentionBackend,
)
from vllm.v1.attention.backends.triton_flashinfer import (
TritonFlashInferBackend,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec, SlidingWindowSpec
if causal_backend_name == "FLASHINFER":
backend = TritonFlashInferBackend
causal_metadata_type = FlashInferMetadata
block_size = backend.get_supported_kernel_block_sizes()[0]
else:
backend = TritonFlashAttentionBackend
causal_metadata_type = FlashAttentionMetadata
block_size = backend.get_preferred_block_size(16)
num_blocks = (209 + block_size - 1) // block_size
torch.manual_seed(42)
attention_config = {"backend": backend.get_name()}
if causal_backend_name == "FLASH_ATTN":
attention_config["flash_attn_version"] = 4
cfg = EngineArgs(
model="google/gemma-4-31B-it",
dtype="bfloat16",
max_model_len=512,
max_num_seqs=4,
max_num_batched_tokens=512,
block_size=block_size,
kv_cache_dtype=cache_dtype,
enforce_eager=True,
attention_config=attention_config,
).create_engine_config()
cfg.cache_config.kv_cache_layout = "LBHNC"
window = 128 if head_size == 256 else None
storage_dtype = torch.uint8 if cache_dtype == "fp8_e4m3" else DTYPE
spec_kwargs = dict(
block_size=block_size,
num_kv_heads=16,
head_size=head_size,
dtype=storage_dtype,
kv_quant_mode=get_kv_quant_mode(cache_dtype),
)
spec = (
SlidingWindowSpec(**spec_kwargs, sliding_window=window)
if window
else FullAttentionSpec(**spec_kwargs)
)
if reverse_children:
# Swapping the children and policy must preserve outputs and KV writes;
# dispatch cannot depend on a particular child's class or position.
class ReversedRouting(MMPrefixAttentionRouting):
capture_variant = 0
def select(self, metadata):
return 1 - super().select(metadata)
@staticmethod
def variant_uses_mm_prefix(variant):
return variant == 1
backend = create_composite_attention_backend(
FlashInferBackend,
TritonAttentionBackend,
name="ReversedCompositeBackend",
backend_name="CUSTOM",
module=__name__,
routing_policy=ReversedRouting,
)
with set_current_vllm_config(cfg), set_default_torch_dtype(DTYPE):
layer = Attention(
32,
head_size,
head_size**-0.5,
num_kv_heads=16,
cache_config=cfg.cache_config,
prefix="composite_test",
per_layer_sliding_window=window,
attn_backend=backend,
).to(DEVICE)
layer.mm_prefix_clamp_sliding_window = window is not None
assert backend.get_builder_cls().get_cudagraph_support(cfg, spec) == (
AttentionCGSupport.UNIFORM_SINGLE_TOKEN_DECODE
)
if window:
layer.mm_prefix_clamp_sliding_window = False
assert backend.get_builder_cls().get_cudagraph_support(cfg, spec) == (
AttentionCGSupport.NEVER
)
layer.mm_prefix_clamp_sliding_window = True
builder = backend.get_builder_cls()(spec, ["composite_test"], cfg, DEVICE)
# Match production, where unwritten page tails are zero-initialized.
cache = torch.zeros(
num_blocks,
16,
block_size,
2 * head_size,
dtype=storage_dtype,
device=DEVICE,
)
keys = torch.randn(209, 16, head_size, dtype=DTYPE, device=DEVICE)
values = torch.randn_like(keys)
if cache_dtype == "fp8_e4m3":
keys = keys.to(torch.float8_e4m3fn).to(DTYPE)
values = values.to(torch.float8_e4m3fn).to(DTYPE)
table = torch.arange(num_blocks, dtype=torch.int32, device=DEVICE).unsqueeze(0)
previous = 0
for end, spans, metadata_type in [
(128, [(32, 111)], TritonAttentionMetadata),
(129, [(32, 111)], causal_metadata_type),
(145, [(32, 111)], causal_metadata_type),
(209, [(32, 111), (160, 207)], TritonAttentionMetadata),
]:
qlen = end - previous
starts = torch.tensor([0, qlen], dtype=torch.int32)
lengths = torch.tensor([end], dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=starts.to(DEVICE),
query_start_loc_cpu=starts,
seq_lens=lengths.to(DEVICE),
seq_lens_cpu_upper_bound=lengths,
num_reqs=1,
num_actual_tokens=qlen,
max_query_len=qlen,
max_seq_len=end,
block_table_tensor=table,
slot_mapping=torch.arange(previous, end, device=DEVICE),
mm_req_doc_ranges={0: spans},
)
metadata = builder.build(0, common)
assert isinstance(metadata, metadata_type)
if isinstance(metadata, FlashInferMetadata):
if qlen == 1:
assert isinstance(metadata.decode, FlashInferTrtllmAPIDecode)
else:
assert isinstance(metadata.prefill, TRTLLMPrefill)
query = torch.randn(qlen, 32, head_size, dtype=DTYPE, device=DEVICE)
if cache_dtype == "fp8_e4m3":
query = query.to(torch.float8_e4m3fn).to(DTYPE)
key, value = keys[previous:end], values[previous:end]
output = torch.empty_like(query)
layer.impl.do_kv_cache_update(layer, key, value, cache, common.slot_mapping)
layer.impl.forward(layer, query, key, value, cache, metadata, output)
expected = _dense_reference(
query,
[keys[:end]],
[values[:end]],
[qlen],
[end],
{0: spans},
window,
head_size**-0.5,
mm_clamp_sw=window or 0,
)
torch.testing.assert_close(output.float(), expected, atol=2e-2, rtol=2e-2)
if qlen == 1:
metadata = builder.build_for_cudagraph_capture(common)
assert isinstance(metadata, metadata_type)
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
layer.impl.forward(
layer, query, key, value, cache, metadata, output
)
output.zero_()
graph.replay()
torch.testing.assert_close(
output.float(), expected, atol=2e-2, rtol=2e-2
)
previous = end
@@ -1,315 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Routing/selection tests for the AITER ASM cprr DCP-verify route.
Companion to the upstream segmented-verify tests. Everything here is pure CPU:
it pins the *decisions* (which route a KV group takes, which head count the
kernel runs at, which configurations are refused) rather than kernel numerics.
The numerics parity test against the segmented route needs a GPU and both
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",
reason="ROCm AITER MLA backend not available",
)
_heads = rocm_aiter_mla._asm_dcp_verify_heads
_configured = rocm_aiter_mla._asm_dcp_verify_configured
_select_route = rocm_aiter_mla._select_dcp_decode_route
Route = rocm_aiter_mla._DCPDecodeRoute
NATIVE = rocm_aiter_mla._NATIVE_CPRR_HEADS
MIN_QLEN = rocm_aiter_mla._MIN_CPRR_QLEN
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 == "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):
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "unknown")
with pytest.raises(ValueError, match="Invalid value"):
_ = rocm_aiter_mla.envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY
# --------------------------------------------------------------------------
# _asm_dcp_verify_heads -- which head count the cprr kernel runs at
# --------------------------------------------------------------------------
@pytest.mark.parametrize("n", NATIVE)
def test_native_head_counts_are_used_as_is(n):
assert _heads(n) == n
def test_non_native_head_count_pads_up_to_the_next_native():
"""K3 at TP8/DCP8 gathers 96 heads for the target; the kernel has no 96
variant, so it must run at 128, not silently fall out of the asm path."""
assert _heads(96) == 128
assert _heads(1) == 16
assert _heads(17) == 32
assert _heads(65) == 128
def test_head_count_above_the_largest_native_is_unservable():
"""0 means 'cannot serve'; anything else would route a shape the kernel
has no build for."""
assert _heads(max(NATIVE) + 1) == 0
assert _heads(256) == 0
# --------------------------------------------------------------------------
# _asm_dcp_verify_configured -- reachability
# --------------------------------------------------------------------------
@pytest.fixture
def on_gfx950(monkeypatch):
"""The cprr kernels are built only for gfx950, so the gate checks the arch.
Patched rather than detected, so both branches run on any runner."""
import vllm.platforms.rocm as rocm
monkeypatch.setattr(rocm, "on_gfx950", lambda: True)
def test_route_needs_dcp(on_gfx950):
assert _configured(dcp_world_size=1, cp_interleave=1, multi_token_decode=True) is (
False
)
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
True
)
def test_round_robin_interleave_other_than_one_is_excluded(on_gfx950):
"""The kernel's global-position causal window assumes interleave 1, the
same restriction the segmented gate carries."""
assert _configured(dcp_world_size=8, cp_interleave=2, multi_token_decode=True) is (
False
)
assert _configured(dcp_world_size=8, cp_interleave=16, multi_token_decode=True) is (
False
)
def test_route_needs_multi_token_decode(on_gfx950):
"""Single-token decode is already served. Enabling the route for it would
pad the head count on every step and buy nothing."""
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=False) is (
False
)
def test_route_needs_gfx950(monkeypatch):
"""hsa/gfx942/mla and hsa/gfx1250/mla carry no cprr rows, so off gfx950 the
kernel lookup fails at the first verify step rather than falling back."""
import vllm.platforms.rocm as rocm
monkeypatch.setattr(rocm, "on_gfx950", lambda: False)
assert _configured(dcp_world_size=8, cp_interleave=1, multi_token_decode=True) is (
False
)
# --------------------------------------------------------------------------
# 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.q_data_type = torch.bfloat16
self.mla_dims = SimpleNamespace(
kv_lora_rank=512,
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
)
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)
# These cases pick between cprr and segmented. On a gfx942 runner the real
# arch would add the Triton verify route, which this stub cannot build.
import vllm.platforms.rocm as rocm
monkeypatch.setattr(rocm, "on_gfx942", 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
# --------------------------------------------------------------------------
def test_min_cprr_qlen_is_above_two():
"""Qlen 2 is below CPRR's floor and must use segmented verification."""
assert MIN_QLEN > 2
@pytest.mark.parametrize(
"segmented,triton,causal,qlen,asm,expected",
[
(True, False, True, 1, True, Route.PLAIN),
(True, False, True, 2, True, Route.SEGMENTED),
(True, False, True, 3, True, Route.CPRR),
(True, False, True, 4, True, Route.CPRR),
(True, False, True, 4, False, Route.SEGMENTED),
(True, False, False, 2, True, Route.PLAIN),
(True, False, False, 4, False, Route.PLAIN),
(False, False, True, 3, True, Route.CPRR),
# gfx942: no cprr and no segmented, so causal verify goes to Triton.
(False, True, True, 1, False, Route.PLAIN),
(False, True, True, 2, False, Route.TRITON),
(False, True, True, 4, False, Route.TRITON),
(False, True, False, 4, False, Route.PLAIN),
# cprr still wins at or above its qlen floor.
(False, True, True, 4, True, Route.CPRR),
(False, True, True, 2, True, Route.TRITON),
],
)
def test_dcp_decode_route(segmented, triton, causal, qlen, asm, expected):
route = _select_route(
supports_segmented=segmented,
supports_triton=triton,
causal=causal,
max_qo_len=qlen,
asm_selected=asm,
)
assert route is expected
def test_causal_multi_token_batch_without_a_valid_route_fails():
with pytest.raises(RuntimeError, match="requires either segmented MLA"):
_select_route(
supports_segmented=False,
supports_triton=False,
causal=True,
max_qo_len=2,
asm_selected=True,
)
# Kernel numerics live in test_rocm_aiter_mla_dcp_cprr_numerics.py, which runs
# the real builder and the real asm kernel on a gfx950 GPU.
@@ -1,547 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""GPU numerics for the AITER ASM cprr DCP-verify route.
Runs the REAL metadata builder (``AiterMLAMetadataBuilder.build``, so
``get_mla_metadata_v1`` is exercised with the cprr kwargs and the persistent
schedule buffers are produced) and the REAL asm kernel, on ONE GPU with the DCP
ranks simulated one after another.
That is legitimate because the aiter MLA backend contains no collective on this
path: the query all-gather happens in the *layer*, strictly before
``forward_mqa``, so the head fold, the round-robin kernel call and the un-fold
are pure per-rank local arithmetic in which ``cp_world_size``/``cp_rank`` are
just numbers feeding the causal-mask maths. Restricting a shard to a residue
class of global positions is exactly what DCP rank r sees.
Three properties are checked:
* each shard matches an exact torch reference over the positions it holds,
with causality applied on the GLOBAL position (the thing cprr reconstructs
in-kernel and the segmented route instead carries in per-row lengths);
* the LSE merge of all shards reproduces full-context attention;
* a shard told the wrong ``cp_rank`` fails both -- without this positive
control a passing run proves nothing, since a kernel that ignored global
positions still produces plausible-looking output.
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
if not current_platform.is_rocm():
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
from vllm._aiter_ops import is_aiter_found # noqa: E402
from vllm.v1.attention.backends.mla import rocm_aiter_mla # noqa: E402
KV_LORA_RANK = 512
QK_ROPE_HEAD_DIM = 64
QK_NOPE_HEAD_DIM = 128
HEAD_SIZE = KV_LORA_RANK + QK_ROPE_HEAD_DIM
SCALE = (QK_NOPE_HEAD_DIM + QK_ROPE_HEAD_DIM) ** -0.5
DCP = 8
NUM_REQS = 8
CTX = 256
QLEN = 5 # 1 + num_speculative_tokens; must clear _MIN_CPRR_QLEN
# fp8-e4m3 keeps 3 mantissa bits, so the relative error floor is ~6.2e-2. Gates
# are relative for the same reason: an absolute bound would just be a bound on
# the output magnitude.
SHARD_RTOL = 1.0e-1
MERGE_RTOL = 5.0e-2
MODEL = "deepseek-ai/DeepSeek-R1"
def _gpu_available() -> bool:
return is_aiter_found() and torch.accelerator.is_available()
def _on_gfx950() -> bool:
if not is_aiter_found():
return False
from vllm.platforms.rocm import on_gfx950
return on_gfx950()
requires_cprr = pytest.mark.skipif(
not (_gpu_available() and _on_gfx950()),
reason="cprr DCP verify needs ROCm + AITER on gfx950",
)
@pytest.fixture(autouse=True)
def select_asm_route(monkeypatch):
monkeypatch.setenv("VLLM_ROCM_AITER_MLA_DCP_VERIFY", "asm")
# --------------------------------------------------------------------------
# reference maths
# --------------------------------------------------------------------------
def _torch_reference(q_f32, kv_f32, ctx, qlen, scale, positions):
"""Exact absorbed-MLA decode over an explicit set of GLOBAL KV positions.
A shard sees only ``positions``, but causality still uses the global
position: query token i (global position ctx + i) may attend to any p in
positions with p <= ctx + i. Restricting ``positions`` to a round-robin
residue class is precisely DCP rank r's view.
"""
nr, _, heads, _ = q_f32.shape
dev = q_f32.device
o = torch.zeros(nr, qlen, heads, KV_LORA_RANK, dtype=torch.float32, device=dev)
lse = torch.full((nr, qlen, heads), float("-inf"), dtype=torch.float32, device=dev)
for r in range(nr):
kv_sel = kv_f32[r].index_select(0, positions)
for i in range(qlen):
valid = positions <= (ctx + i)
if not bool(valid.any()):
continue
k = kv_sel[valid]
s = (q_f32[r, i] @ k.T) * scale
m = s.max(dim=-1, keepdim=True).values
p = torch.exp(s - m)
denom = p.sum(dim=-1, keepdim=True)
o[r, i] = (p / denom) @ k[:, :KV_LORA_RANK]
lse[r, i] = m.squeeze(-1) + torch.log(denom.squeeze(-1))
return o, lse
def _merge_partials(os_, lses):
"""Cross-shard softmax merge (natural-log LSE)."""
stack_lse = torch.stack(lses)
m = stack_lse.max(dim=0).values
w = torch.exp(stack_lse - m)
num = (w.unsqueeze(-1) * torch.stack(os_)).sum(dim=0)
den = w.sum(dim=0).unsqueeze(-1)
return num / den, m + torch.log(w.sum(dim=0))
# --------------------------------------------------------------------------
# single-process rank simulation
# --------------------------------------------------------------------------
class _FakeGroup:
def __init__(self, world_size: int, rank: int):
self.world_size = world_size
self.rank_in_group = rank
self.rank = rank
self.local_rank = rank
def all_gather(self, tensor, dim=0):
raise RuntimeError(
"collective called in a single-process test -- the path under test "
"is supposed to be collective-free; this indicates a real change"
)
def _install_fake_groups(dcp_size: int, cp_rank: int, tp_size: int = 1) -> None:
"""Point vLLM's parallel_state at rank-simulating stubs (no NCCL)."""
import vllm.distributed.parallel_state as ps
import vllm.model_executor.layers.attention.mla_attention as mla_attention
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
dcp = _FakeGroup(dcp_size, cp_rank)
tp = _FakeGroup(tp_size, cp_rank)
ps.get_dcp_group = lambda: dcp
ps.get_tp_group = lambda: tp
# Both of these imported the symbol directly at module import time, so
# patching parallel_state alone leaves them resolving the real group (and
# the builder then reports dcp_world_size 1, silently skipping the route).
backend.get_dcp_group = lambda: dcp
mla_attention.get_dcp_group = lambda: dcp
@pytest.fixture(autouse=True)
def _restore_parallel_groups():
"""Undo _install_fake_groups after every test.
It patches module globals in three modules, so without this the fake DCP
group leaks into the rest of the pytest session and silently breaks
unrelated tests that expect a real (or absent) group.
"""
import vllm.distributed.parallel_state as ps
import vllm.model_executor.layers.attention.mla_attention as mla_attention
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
saved = [
(mod, name, getattr(mod, name))
for mod, name in (
(ps, "get_dcp_group"),
(ps, "get_tp_group"),
(backend, "get_dcp_group"),
(mla_attention, "get_dcp_group"),
)
]
yield
for mod, name, value in saved:
setattr(mod, name, value)
class _PrefillBackendStub:
"""The base builder does ``attention_layer.prefill_backend.clone()``.
prefill_backend is consulted only from the chunked-context prefill path,
which a decode-only test never enters.
"""
def clone(self):
return self
def _make_ctx_layer(vllm_config):
"""Stand-in for the registered attention layer in static_forward_context.
``MLACommonMetadataBuilder.__init__`` reads the MLA dims, ``dcp_manager``
and ``prefill_backend`` off this object. ``dcp_manager`` is the Direct-DCP
symmetric-memory workspace, used ONLY by the chunked-prefill KV all-gather;
it is constructed without running __init__ so no peer pointers are exchanged
and no collective is issued. That is what keeps this test single-process.
"""
from vllm.v1.attention.ops.dcp import MLADCPManager
mgr = object.__new__(MLADCPManager)
mgr.init_kv_gather = lambda *a, **k: None
return SimpleNamespace(
non_causal_multi_token_decode=False,
q_lora_rank=None,
kv_lora_rank=KV_LORA_RANK,
qk_nope_head_dim=QK_NOPE_HEAD_DIM,
qk_rope_head_dim=QK_ROPE_HEAD_DIM,
v_head_dim=QK_NOPE_HEAD_DIM,
dcp_manager=mgr,
prefill_backend=_PrefillBackendStub(),
)
def _ensure_workspace_manager(device: torch.device) -> None:
"""Init the global workspace manager, which GPUModelRunner does in production.
``AiterMLAMetadataBuilder.__init__`` reserves the fp8 prefill
persistent-scheduling scratch through ``current_workspace_manager()``, so
merely constructing a builder outside a serve trips its assert. Idempotent:
one builder is constructed per DCP shard. Deliberately does NOT lock the
workspace -- production locks only after warmup, and this keeps allocating
across shards.
"""
from vllm.v1.worker.workspace import (
init_workspace_manager,
is_workspace_manager_initialized,
)
if not is_workspace_manager_initialized():
init_workspace_manager(device)
class _Layer:
def __init__(self, device):
self._q_scale = torch.tensor(1.0, device=device)
self._k_scale = torch.tensor(1.0, device=device)
self._v_scale = torch.tensor(1.0, device=device)
def _build_impl(num_heads: int, dcp: int, cp_rank: int):
"""Real AiterMLAImpl.forward_mqa bound to a minimally-populated instance.
Constructing the full impl would drag in kv_b_proj and the rest of the
weight-dependent MLA setup -- i.e. model loading, which this test exists to
avoid. forward_mqa's fold path reads only the attributes set below.
"""
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAImpl
impl = object.__new__(AiterMLAImpl)
impl.kv_lora_rank = KV_LORA_RANK
impl.qk_rope_head_dim = QK_ROPE_HEAD_DIM
impl.num_heads = num_heads
impl.dcp_world_size = dcp
impl.dcp_rank = cp_rank
impl.pcp_world_size = 1
impl.kv_cache_dtype = "fp8"
impl.scale = SCALE
# `_decode_num_heads` is a read-only property deriving num_heads *
# dcp_world_size, both set above; assert rather than assign.
assert impl._decode_num_heads == num_heads * dcp
return impl
def _make_vllm_config(heads_per_rank: int):
"""A DCP8 MLA config with no weights and no distributed init.
DeepSeek-R1's config supplies the MLA dims (kv_lora_rank 512, rope 64,
nope 128) that the aiter asm kernel is built for; only the head count is
overridden, to place the GATHERED count (heads_per_rank * DCP) on the
kernel variant under test. ``get_num_attention_heads`` reads
model_arch_config, a snapshot taken at config-creation time, so patching
hf_config alone would be inert.
"""
from tests.v1.attention.utils import create_vllm_config
vllm_config = create_vllm_config(
model_name=MODEL,
tensor_parallel_size=1,
max_model_len=2048,
max_num_seqs=NUM_REQS * 2,
max_num_batched_tokens=4096,
)
vllm_config.model_config.model_arch_config.total_num_attention_heads = (
heads_per_rank
)
# Without a speculative config the batch reorder threshold stays at 1 and a
# qlen-QLEN row is classified as a PREFILL, so the decode path under test is
# never reached. _init_reorder_batch_threshold reads exactly these two
# fields, so a stand-in is enough and avoids pulling in a draft model.
vllm_config.speculative_config = SimpleNamespace(
num_speculative_tokens=QLEN - 1, parallel_drafting=False
)
vllm_config.cache_config.cache_dtype = "fp8"
vllm_config.parallel_config.decode_context_parallel_size = DCP
vllm_config.parallel_config.cp_kv_cache_interleave_size = 1
return vllm_config
def _run_shard(
vllm_config,
spec,
layer_name,
device,
cp_rank,
kern_rank,
q_flat,
kv_flat,
nr,
qlen,
ctx,
dcp,
pos,
):
"""Build real metadata for one DCP rank and run the real asm kernel.
``kern_rank`` is separate from ``cp_rank`` so the positive control can hand
rank r's pages to the kernel while telling it that it is rank r+1.
"""
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
L = ctx + qlen
local_len = int(pos.numel())
# One GLOBAL kv cache: page (req*L + p) holds request req position p. Shards
# select pages by residue class, so every shard reads the same underlying
# bytes and no re-quantisation noise is introduced between arms.
block_table = (
torch.arange(nr, device=device).view(nr, 1) * L + pos.view(1, -1)
).to(torch.int32)
# seq_lens is the GLOBAL context; dcp_local_seq_lens is what this rank
# actually holds. Passing the global length as the local one walks the
# kernel off the end of the page table.
seq_lens_cpu = torch.full((nr,), L, dtype=torch.int32)
local_cpu = torch.full((nr,), local_len, dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=torch.arange(
0, nr * qlen + 1, qlen, dtype=torch.int32, device=device
),
query_start_loc_cpu=torch.arange(0, nr * qlen + 1, qlen, dtype=torch.int32),
seq_lens=seq_lens_cpu.to(device),
num_reqs=nr,
num_actual_tokens=nr * qlen,
max_query_len=qlen,
max_seq_len=L,
block_table_tensor=block_table,
slot_mapping=torch.arange(nr * qlen, dtype=torch.int64, device=device),
causal=True,
dcp_local_seq_lens=local_cpu.to(device),
dcp_local_seq_lens_cpu_upper_bound=local_cpu,
)
_install_fake_groups(dcp, kern_rank)
builder = AiterMLAMetadataBuilder(spec, [layer_name], vllm_config, device)
md = builder.build(0, common)
impl = _build_impl(builder.num_heads, dcp, kern_rank)
o, lse = impl.forward_mqa(q_flat, kv_flat, md, _Layer(device))
torch.accelerator.synchronize()
return md, o, lse, local_len
def _numerics(heads_per_rank: int, sabotage: bool = False):
"""Run every DCP shard and return (per-shard max rel err, merged rel err)."""
import aiter
from vllm.config import set_current_vllm_config
device = torch.device("cuda", 0)
torch.accelerator.set_device_index(device.index)
torch.manual_seed(0)
_ensure_workspace_manager(device)
_install_fake_groups(DCP, 0)
vllm_config = _make_vllm_config(heads_per_rank)
with set_current_vllm_config(vllm_config):
from vllm.v1.kv_cache_interface import MLAAttentionSpec
layer_name = "model.layers.0.self_attn.attn"
vllm_config.compilation_config.static_forward_context[layer_name] = (
_make_ctx_layer(vllm_config)
)
# block_size 1: one page per token, so page ids are positions and the
# residue-class page table is expressible directly.
spec = MLAAttentionSpec(
block_size=1,
num_kv_heads=1,
head_size=HEAD_SIZE,
dtype=vllm_config.model_config.dtype,
non_causal_multi_token_decode=False,
)
nr, ctx, qlen = NUM_REQS, CTX, QLEN
L = ctx + qlen
gathered_heads = heads_per_rank * DCP
kv_dtype = aiter.dtypes.fp8
kv_flat = torch.randn(
nr * L, 1, HEAD_SIZE, dtype=torch.float32, device=device
).to(kv_dtype)
q_flat = (
torch.randn(
nr * qlen,
gathered_heads,
HEAD_SIZE,
dtype=torch.float32,
device=device,
)
.mul_(0.5)
.to(kv_dtype)
)
# Dequantise for the reference so the comparison measures the kernel,
# not the fp8 cast that both sides share.
kv_f32 = kv_flat.float().view(nr, L, HEAD_SIZE)
q_f32 = q_flat.float().view(nr, qlen, gathered_heads, HEAD_SIZE)
ref_o, _ = _torch_reference(
q_f32, kv_f32, ctx, qlen, SCALE, torch.arange(L, device=device)
)
shard_o, shard_lse = [], []
max_shard_rel = 0.0
for r in range(DCP):
pos = torch.arange(r, L, DCP, device=device) # residue class r
kern_rank = (r + 1) % DCP if sabotage else r
md, o, lse, _ = _run_shard(
vllm_config,
spec,
layer_name,
device,
r,
kern_rank,
q_flat,
kv_flat,
nr,
qlen,
ctx,
DCP,
pos,
)
# The route actually under test must have been taken; a silent
# fall-out to Triton/segmented would otherwise pass quietly.
assert md.decode.dcp_route is rocm_aiter_mla._DCPDecodeRoute.CPRR
assert md.decode.asm_decode_num_heads, "cprr asm route was not taken"
o = o.float().view(nr, qlen, gathered_heads, KV_LORA_RANK)
shard_lse.append(lse.float().view(nr, qlen, gathered_heads))
shard_o.append(o)
po, _ = _torch_reference(q_f32, kv_f32, ctx, qlen, SCALE, pos)
rel = (o - po).abs().max().item() / max(po.abs().max().item(), 1e-6)
max_shard_rel = max(max_shard_rel, rel)
merged, _ = _merge_partials(shard_o, shard_lse)
merge_rel = (merged - ref_o).abs().max().item() / max(
ref_o.abs().max().item(), 1e-6
)
return max_shard_rel, merge_rel
# --------------------------------------------------------------------------
# tests
# --------------------------------------------------------------------------
@requires_cprr
@pytest.mark.parametrize(
"heads_per_rank",
[
16, # 128 gathered heads -- a NATIVE cprr kernel, no padding
12, # 96 gathered heads -- K3's DSpark target, must pad up to 128
],
ids=["native-128", "padded-96-to-128"],
)
@torch.inference_mode()
def test_cprr_shards_match_reference_and_merge_to_full_context(heads_per_rank):
"""Every DCP shard must be right, and their LSE merge must reproduce
full-context attention.
A shard that ignored global positions (applying a local causal tail
instead) still produces plausible-looking output; it only diverges from the
reference on the tokens whose causal window is truncated. Checking the merge
alone would hide that, so both are asserted.
"""
shard_rel, merge_rel = _numerics(heads_per_rank)
assert shard_rel < SHARD_RTOL, f"per-shard rel err {shard_rel:.3e}"
assert merge_rel < MERGE_RTOL, f"merged rel err {merge_rel:.3e}"
@requires_cprr
@torch.inference_mode()
def test_wrong_cp_rank_breaks_the_result():
"""Positive control: without it, a passing run above proves nothing.
Feeding shard r's pages to the kernel while telling it that it is rank r+1
shifts every reconstructed global position by one, so both the causal mask
and the round-robin reconstruction are wrong. If the error does NOT blow up,
the kernel is not using cp_rank and the test above has no power.
"""
shard_rel, merge_rel = _numerics(16, sabotage=True)
assert shard_rel > SHARD_RTOL or merge_rel > MERGE_RTOL, (
f"sabotaged run still passed (shard {shard_rel:.3e}, merge "
f"{merge_rel:.3e}) -- cp_rank is not reaching the kernel"
)
@requires_cprr
def test_cprr_kernel_is_selected_for_the_k3_shape():
"""The K3 DSpark target shape must actually reach the cprr route.
Guards against a silent fall-out to segmented/Triton, which is what the
stock configuration does and what this route exists to avoid.
"""
from vllm.v1.attention.backends.mla import rocm_aiter_mla as m
assert (
m._asm_dcp_verify_configured(
dcp_world_size=DCP, cp_interleave=1, multi_token_decode=True
)
is True
)
assert QLEN >= m._MIN_CPRR_QLEN
route = m._select_dcp_decode_route(
supports_segmented=True,
supports_triton=False,
causal=True,
max_qo_len=QLEN,
asm_selected=True,
)
assert route is m._DCPDecodeRoute.CPRR
assert m._asm_dcp_verify_heads(96) in m._NATIVE_CPRR_HEADS
@@ -1,331 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Causal target verify under DCP on gfx942 (MI300/MI325).
Reproduces the attention shape of
vllm serve moonshotai/Kimi-K3 --tensor-parallel-size 8 \
--decode-context-parallel-size 8 \
--speculative-config '{"method": "dspark", "num_speculative_tokens": 5}'
96 gathered heads, bf16 KV, qlen 6 and the 768-token blocks the hybrid KDA
layers impose. Segmented MLA tiles those blocks at 128 tokens and needs 128 KiB
of LDS (gfx942 has 64 KiB), so the builder must route this shape to the generic
Triton split-KV kernel. DeepSeek-V3 with MTP and an fp8 KV cache at DCP 8 hits
the same limit through its 128 gathered heads. Shapes segmented MLA fits stay
on it.
The real metadata builder and ``forward_mqa`` run on one GPU with the DCP ranks
simulated one after another. That is sound because this path has no
collective: the query all-gather happens in the layer, before ``forward_mqa``.
"""
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
from vllm.utils.math_utils import cdiv
if not current_platform.is_rocm():
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
from vllm._aiter_ops import is_aiter_found # noqa: E402
# DeepSeek-R1 supplies the MLA dims, which Kimi-K3 and DeepSeek-V3 share; only
# the head count is overridden.
MODEL = "deepseek-ai/DeepSeek-R1"
KV_LORA_RANK, ROPE_DIM, NOPE_DIM = 512, 64, 128
HEAD_SIZE = KV_LORA_RANK + ROPE_DIM
SCALE = (NOPE_DIM + ROPE_DIM) ** -0.5
DCP = 8
# Each rank holds ~800 tokens per request, so its shard spans several blocks.
NUM_REQS, CTX = 4, 6400
FP8_KV_SCALE = 0.05
def _on_gfx942() -> bool:
if not (is_aiter_found() and torch.accelerator.is_available()):
return False
from vllm.platforms.rocm import on_gfx942
return on_gfx942()
pytestmark = pytest.mark.skipif(not _on_gfx942(), reason="needs ROCm + AITER on gfx942")
class _FakeGroup:
def __init__(self, world_size: int, rank: int):
self.world_size = world_size
self.rank_in_group = self.rank = self.local_rank = rank
def all_gather(self, tensor, dim=0):
raise RuntimeError("DCP verify must not issue a collective")
@pytest.fixture
def fake_dcp_groups(monkeypatch):
"""Point every importer of get_dcp_group at a settable rank stub."""
import vllm.distributed.parallel_state as ps
import vllm.model_executor.layers.attention.mla_attention as mla_attention
import vllm.v1.attention.backends.mla.rocm_aiter_mla as backend
group = _FakeGroup(DCP, 0)
for module in (ps, mla_attention, backend):
monkeypatch.setattr(module, "get_dcp_group", lambda: group)
monkeypatch.setattr(ps, "get_tp_group", lambda: _FakeGroup(1, 0))
return group
def _vllm_config(heads_per_rank: int, qlen: int, fp8_kv: bool):
from tests.v1.attention.utils import create_vllm_config
config = create_vllm_config(
model_name=MODEL,
max_model_len=CTX + qlen,
max_num_seqs=NUM_REQS,
max_num_batched_tokens=4096,
)
config.model_config.model_arch_config.total_num_attention_heads = heads_per_rank
# The reorder threshold reads only these two fields; without them a
# multi-token row is classified as prefill and never reaches decode.
config.speculative_config = SimpleNamespace(
num_speculative_tokens=qlen - 1, parallel_drafting=False
)
config.parallel_config.decode_context_parallel_size = DCP
config.parallel_config.cp_kv_cache_interleave_size = 1
if fp8_kv:
config.cache_config.cache_dtype = "fp8"
return config
def _ctx_layer():
"""The registered-layer fields MLACommonMetadataBuilder.__init__ reads."""
from vllm.v1.attention.ops.dcp import MLADCPManager
dcp_manager = object.__new__(MLADCPManager)
dcp_manager.init_kv_gather = lambda *args, **kwargs: None
# Only chunked-context prefill uses the cloned backend.
prefill_backend = SimpleNamespace()
prefill_backend.clone = lambda: prefill_backend
return SimpleNamespace(
non_causal_multi_token_decode=False,
q_lora_rank=None,
kv_lora_rank=KV_LORA_RANK,
qk_nope_head_dim=NOPE_DIM,
qk_rope_head_dim=ROPE_DIM,
v_head_dim=NOPE_DIM,
dcp_manager=dcp_manager,
prefill_backend=prefill_backend,
)
def _impl(dcp_rank: int, heads_per_rank: int, fp8_kv: bool):
"""forward_mqa needs these attributes, not the weight-loading __init__."""
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAImpl
impl = object.__new__(AiterMLAImpl)
impl.num_heads = heads_per_rank
impl.kv_lora_rank = KV_LORA_RANK
impl.qk_rope_head_dim = ROPE_DIM
impl.dcp_world_size = DCP
impl.dcp_rank = dcp_rank
impl.pcp_world_size = 1
impl.kv_cache_dtype = "fp8" if fp8_kv else "auto"
impl.scale = SCALE
impl._sm_count = current_platform.num_compute_units()
return impl
def _run_rank(config, spec, layer_name, group, rank, q, kv_cache_src, k_scale):
"""Shard the KV round-robin onto ``rank`` and run its verify step."""
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAMetadataBuilder
device = q.device
qlen, heads = q.shape[1], q.shape[2] // DCP
seq_len = CTX + qlen
positions = torch.arange(rank, seq_len, DCP, device=device)
local_len = positions.numel()
# Production block tables span max_model_len, so every rank's table is at
# least as wide as the largest shard needs.
blocks_per_req = cdiv(cdiv(seq_len, DCP), spec.block_size)
kv_cache = torch.zeros(
NUM_REQS * blocks_per_req,
spec.block_size,
HEAD_SIZE,
dtype=kv_cache_src.dtype,
device=device,
)
kv_cache.view(NUM_REQS, -1, HEAD_SIZE)[:, :local_len] = kv_cache_src[:, positions]
block_table = torch.arange(
NUM_REQS * blocks_per_req, dtype=torch.int32, device=device
).view(NUM_REQS, blocks_per_req)
query_start_loc = torch.arange(
0, NUM_REQS * qlen + 1, qlen, dtype=torch.int32, device=device
)
local_lens = torch.full((NUM_REQS,), local_len, dtype=torch.int32)
common = CommonAttentionMetadata(
query_start_loc=query_start_loc,
query_start_loc_cpu=query_start_loc.cpu(),
seq_lens=torch.full((NUM_REQS,), seq_len, dtype=torch.int32, device=device),
num_reqs=NUM_REQS,
num_actual_tokens=NUM_REQS * qlen,
max_query_len=qlen,
max_seq_len=seq_len,
block_table_tensor=block_table,
slot_mapping=torch.arange(NUM_REQS * qlen, dtype=torch.int64, device=device),
causal=True,
dcp_local_seq_lens=local_lens.to(device),
dcp_local_seq_lens_cpu_upper_bound=local_lens,
)
group.rank_in_group = group.rank = group.local_rank = rank
builder = AiterMLAMetadataBuilder(spec, [layer_name], config, device)
metadata = builder.build(0, common)
layer = SimpleNamespace(
_q_scale=torch.tensor(1.0, device=device),
_k_scale=torch.tensor(k_scale, device=device),
)
impl = _impl(rank, heads, kv_cache_src.dtype != torch.bfloat16)
output, lse = impl.forward_mqa(q.flatten(0, 1), kv_cache, metadata, layer)
return metadata.decode.dcp_route.name, output, lse
@pytest.mark.parametrize(
"heads_per_rank, qlen, block_size, fp8_kv, route",
[
(12, 6, 768, False, "TRITON"),
(12, 6, 64, False, "SEGMENTED"),
(16, 2, 16, True, "TRITON"),
],
ids=["kimi-k3-hybrid-kda-blocks", "segmented-fits", "deepseek-v3-mtp-fp8-kv"],
)
@torch.inference_mode()
def test_dcp_verify_matches_attention(
fake_dcp_groups, heads_per_rank, qlen, block_size, fp8_kv, route
):
from vllm.config import set_current_vllm_config
from vllm.v1.kv_cache_interface import MLAAttentionSpec
from vllm.v1.worker.workspace import (
init_workspace_manager,
is_workspace_manager_initialized,
)
device = torch.device("cuda", torch.accelerator.current_device_index())
if not is_workspace_manager_initialized():
init_workspace_manager(device)
torch.manual_seed(0)
seq_len = CTX + qlen
q = torch.randn(
NUM_REQS,
qlen,
heads_per_rank * DCP,
HEAD_SIZE,
dtype=torch.bfloat16,
device=device,
)
kv = torch.randn(NUM_REQS, seq_len, HEAD_SIZE, device=device).clamp_(-4, 4)
if fp8_kv:
k_scale = FP8_KV_SCALE
kv_cache_src = (kv / k_scale).to(current_platform.fp8_dtype())
else:
k_scale = 1.0
kv_cache_src = kv.to(torch.bfloat16)
kv_ref = kv_cache_src.float() * k_scale
config = _vllm_config(heads_per_rank, qlen, fp8_kv)
layer_name = "model.layers.0.self_attn.attn"
with set_current_vllm_config(config):
config.compilation_config.static_forward_context[layer_name] = _ctx_layer()
spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=HEAD_SIZE,
dtype=kv_cache_src.dtype,
cache_dtype_str="fp8" if fp8_kv else None,
non_causal_multi_token_decode=False,
)
shards = [
_run_rank(
config,
spec,
layer_name,
fake_dcp_groups,
rank,
q,
kv_cache_src,
k_scale,
)
for rank in range(DCP)
]
assert {shard_route for shard_route, _, _ in shards} == {route}
lses = torch.stack([lse.float() for _, _, lse in shards])
weights = torch.exp(lses - lses.max(dim=0).values)
merged = (
weights.unsqueeze(-1) * torch.stack([out.float() for _, out, _ in shards])
).sum(dim=0) / weights.sum(dim=0).unsqueeze(-1)
# Query token t of a request sees the context plus verify tokens 0..t.
scores = torch.einsum("rthd,rld->rthl", q.float(), kv_ref) * SCALE
visible = torch.arange(seq_len, device=device) <= CTX + torch.arange(
qlen, device=device
).view(-1, 1)
scores.masked_fill_(~visible[None, :, None, :], float("-inf"))
reference = torch.einsum(
"rthl,rld->rthd", scores.softmax(dim=-1), kv_ref[..., :KV_LORA_RANK]
)
torch.testing.assert_close(
merged.view_as(reference), reference, rtol=2e-2, atol=2e-2
)
@pytest.mark.parametrize(
"fp8_kv, num_heads, block_size",
[
(False, 96, 768),
(False, 128, 64),
(True, 64, 128),
(True, 128, 16),
],
)
def test_segmented_lds_gate_matches_the_kernel(fp8_kv, num_heads, block_size):
"""The gate must flag exactly the shapes AITER segmented MLA cannot compile."""
from triton.runtime.errors import OutOfResources
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
_get_segmented_mla_decode,
_segmented_mla_fits_lds,
_segmented_mla_page_size,
)
page = _segmented_mla_page_size(block_size)
kv_dtype = current_platform.fp8_dtype() if fp8_kv else torch.bfloat16
q = torch.zeros(1, num_heads, HEAD_SIZE, dtype=torch.bfloat16, device="cuda")
kv = torch.zeros(1, page, 1, HEAD_SIZE, dtype=kv_dtype, device="cuda")
one_row = torch.tensor([0, 1], dtype=torch.int32, device="cuda")
try:
_get_segmented_mla_decode()(
q,
kv,
None,
one_row,
torch.tensor([page], dtype=torch.int32, device="cuda"),
page,
torch.zeros(1, 1, dtype=torch.int32, device="cuda"),
SCALE,
KV_LORA_RANK,
ROPE_DIM,
causal=True,
q_descale=None,
kv_descale=torch.tensor(1.0, device="cuda"),
skip_reduce=True,
)
compiles = True
except OutOfResources:
compiles = False
assert _segmented_mla_fits_lds(num_heads, block_size, fp8_kv) == compiles
@@ -1,202 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Decode-kernel routing for the ROCm AITER MLA backend.
Gluon exposes a single fp8-KV regime, bh16bn128. It is a bf16-query kernel that
upcasts the cache in registers with a hardcoded scale of 1.0, and it asserts
batch_size == 1, so it cannot serve a decode batch. Every fp8 shape therefore
has to land on the asm kernels, which ship real fp8 variants for gqa=16. These
tests pin that down at the predicates, since the failure it prevents is either a
batch assertion or -- worse -- a silently wrong result.
Gluon is still the route for supported non-DCP decode shapes. DCP multi-token
verification uses segmented MLA instead, so it depends on neither Gluon's
query-head nor its long-context pipeline limits.
"""
import pytest
import torch
from vllm.platforms import current_platform
if not current_platform.is_rocm():
pytest.skip("ROCm AITER MLA tests", allow_module_level=True)
from vllm.v1.attention.backends.mla import rocm_aiter_mla # noqa: E402
from vllm.v1.attention.backends.mla.rocm_aiter_mla import AiterMLAHelper # noqa: E402
FP8_DTYPES = ["fp8", "fp8_e4m3", "fp8_e5m2"]
UNQUANTIZED_DTYPES = ["auto", "bfloat16"]
@pytest.fixture
def gluon_available(monkeypatch):
"""Pin the arch gate and the mode knob so only the dtype rules are in play.
Gluon ships a gfx950 build only, and VLLM_ROCM_AITER_MLA_ASM_PADDING can
force the asm path on any arch. Without pinning both, the expectations that
bf16 *keeps* Gluon would pass on a gfx950 host and fail on gfx942 for
reasons that have nothing to do with what these tests cover.
"""
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: True)
monkeypatch.setattr(rocm_aiter_mla, "_aiter_mla_small_head_mode", lambda: "auto")
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES)
@pytest.mark.parametrize("num_heads", [1, 2, 4, 5, 6, 8, 12, 16, 32, 128])
@pytest.mark.parametrize("max_qo_len", [1, 2, 4, 5, 8, 15])
def test_non_dcp_fp8_never_routes_to_gluon(kv_cache_dtype, num_heads, max_qo_len):
"""No non-DCP fp8 shape reaches either Gluon entry point.
The head count is deliberately swept across divisors of 16 as well as
non-divisors: the divisor case (e.g. 8 heads at TP8) is the one that stays
on Gluon for bf16 and so is the one an fp8 guard has to override.
"""
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
assert not AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES)
@pytest.mark.parametrize("num_heads", [1, 2, 4, 8, 12])
@pytest.mark.parametrize("mode", ["auto", "gluon", "asm"])
def test_fp8_never_routes_to_gluon_under_any_mode(
monkeypatch, kv_cache_dtype, num_heads, mode
):
"""VLLM_ROCM_AITER_MLA_ASM_PADDING cannot force a non-DCP fp8 cache onto Gluon.
The dtype guard deliberately precedes the mode knob: honouring an explicit
"gluon" request under fp8 would hand Gluon the batch it asserts against, so
it is overridden rather than obeyed. Pinned here because the override is a
correctness decision, not a preference.
"""
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: True)
monkeypatch.setattr(rocm_aiter_mla, "_aiter_mla_small_head_mode", lambda: mode)
assert not AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
assert not AiterMLAHelper.use_gluon_verify(num_heads, 8, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [16, 17, 32, 64, 128])
@pytest.mark.parametrize("max_qo_len", [1, 4, 8])
def test_large_head_counts_never_use_gluon(kv_cache_dtype, num_heads, max_qo_len):
""">= 16 heads has always been asm-only; the dtype guard must not change it."""
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
assert not AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [8, 16, 32, 96])
@pytest.mark.parametrize("max_qo_len", [2, 3, 8])
def test_dcp_multitoken_verify_never_uses_gluon(
gluon_available, kv_cache_dtype, num_heads, max_qo_len
):
assert not AiterMLAHelper.use_gluon_verify(
num_heads, max_qo_len, kv_cache_dtype, dcp_world_size=8
)
def test_segmented_dcp_verify_does_not_depend_on_gluon(monkeypatch):
monkeypatch.setattr(rocm_aiter_mla, "_gluon_mla_decode_supported", lambda: False)
monkeypatch.setattr(rocm_aiter_mla, "_segmented_mla_decode_supported", lambda: True)
assert rocm_aiter_mla._segmented_dcp_verify_supported(8, 1)
# Round-robin interleaving other than 1 is not served by this route.
assert not rocm_aiter_mla._segmented_dcp_verify_supported(8, 4)
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [1, 2, 4, 8])
def test_unquantized_divisor_heads_keep_gluon_decode(
gluon_available, kv_cache_dtype, num_heads
):
"""Divisor head counts keep the Gluon single-token decode for bf16.
Gluon does not scale with KV length the way the asm persistent decode does,
so this is the faster path where it is usable.
"""
assert AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [3, 5, 6, 7, 9, 12, 15])
def test_unquantized_non_divisor_heads_use_asm_decode(kv_cache_dtype, num_heads):
"""Non-divisor head counts are padded to 16 and take the asm decode."""
assert not AiterMLAHelper.use_gluon_decode(num_heads, 1, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [5, 8, 12])
@pytest.mark.parametrize("max_qo_len", [2, 4, 8, 15])
def test_unquantized_small_head_verify_keeps_gluon(
gluon_available, kv_cache_dtype, num_heads, max_qo_len
):
"""bf16 has no gqa<16, qseqlen>1 asm kernel, so verify still flattens onto Gluon.
Unlike the decode predicate, this one does not care whether the head count
divides 16 -- the flatten reshapes to qseqlen=1 either way.
"""
assert AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
# The verify flatten is a separate entry point from the single-token decode.
assert not AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
@pytest.mark.parametrize("kv_cache_dtype", FP8_DTYPES + UNQUANTIZED_DTYPES)
@pytest.mark.parametrize("num_heads", [5, 8, 12, 16, 32])
def test_decode_and_verify_are_disjoint(kv_cache_dtype, num_heads):
"""The two Gluon entry points partition on qlen and never both fire."""
for max_qo_len in (1, 2, 8):
assert not (
AiterMLAHelper.use_gluon_decode(num_heads, max_qo_len, kv_cache_dtype)
and AiterMLAHelper.use_gluon_verify(num_heads, max_qo_len, kv_cache_dtype)
)
@pytest.mark.parametrize("kv_cache_dtype", UNQUANTIZED_DTYPES)
def test_oversized_kv_cache_refuses_gluon(gluon_available, kv_cache_dtype):
"""Past 2 GiB per layer Gluon drops its KV bounds mask and reads out of range.
``None`` is the profiling case, before the cache is sized: nothing to
refuse yet, so the usual route stands.
"""
bound = rocm_aiter_mla._GLUON_MAX_KV_CACHE_BYTES
for kv_cache_bytes in (None, bound):
assert AiterMLAHelper.use_gluon_decode(8, 1, kv_cache_dtype, kv_cache_bytes)
assert AiterMLAHelper.use_gluon_verify(
8, 8, kv_cache_dtype, kv_cache_bytes=kv_cache_bytes
)
assert not AiterMLAHelper.use_gluon_decode(8, 1, kv_cache_dtype, bound + 1)
assert not AiterMLAHelper.use_gluon_verify(
8, 8, kv_cache_dtype, kv_cache_bytes=bound + 1
)
@pytest.mark.parametrize("num_heads", [1, 2, 3, 5, 6, 7, 8, 9, 12, 15])
def test_padded_query_is_contiguous(num_heads):
"""asm_mla.cu:805 requires Q.is_contiguous().
Padding a non-divisor head count to 16 tiles the query and slices it back
down, which yields a non-contiguous view whenever more than one tile is
needed (12 heads -> repeat to 24 -> slice to 16). The asm kernel rejects
that outright, so the padding has to materialize the result.
"""
q = torch.randn(4, num_heads, 576)
padded = AiterMLAHelper.get_mla_padded_q(num_heads, q)
assert padded.shape[1] == max(16, num_heads)
assert padded.is_contiguous()
@pytest.mark.parametrize("num_heads", [1, 2, 3, 5, 6, 7, 8, 9, 12, 15, 16, 32])
def test_pad_unpad_round_trip_preserves_head_order(num_heads):
"""Unpadding recovers each original head from the padded output, in order."""
q = torch.arange(num_heads, dtype=torch.float32).view(1, num_heads, 1)
padded = AiterMLAHelper.get_mla_padded_q(num_heads, q)
unpadded = AiterMLAHelper.get_mla_unpadded_o(num_heads, padded)
assert unpadded.shape == q.shape
torch.testing.assert_close(unpadded, q)
def test_a_non_causal_block_never_routes_to_gluon(gluon_available):
"""A small-head block that normally uses Gluon must use ASM when non-causal."""
assert not AiterMLAHelper.use_gluon_verify(12, 8, "auto", causal=False)
File diff suppressed because it is too large Load Diff
@@ -1,54 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
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(
"ROCm AITER sparse indexer test requires ROCm with AITER.",
allow_module_level=True,
)
from vllm._aiter_ops import rocm_aiter_ops
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as sparse_mod
def test_rocm_fp8_mqa_logits_disables_clean_logits(monkeypatch):
captured = {}
expected = torch.empty((1, 1))
def fake_fp8_mqa_logits(*args, clean_logits):
captured["clean_logits"] = clean_logits
return expected
monkeypatch.setattr(sparse_mod, "_ON_GFX942", False)
monkeypatch.setattr(rocm_aiter_ops, "is_enabled", lambda: True)
monkeypatch.setattr(
sparse_mod,
"mqa_logits_module",
lambda: SimpleNamespace(fp8_mqa_logits=fake_fp8_mqa_logits),
)
q = torch.empty((1, 1, 1))
k_fp8 = torch.empty((1, 1))
scale = torch.empty((1,))
weights = torch.empty((1, 1))
cu_seqlen_ks = torch.zeros((1,), dtype=torch.int32)
cu_seqlen_ke = torch.ones((1,), dtype=torch.int32)
result = sparse_mod.rocm_fp8_mqa_logits(
q,
(k_fp8, scale),
weights,
cu_seqlen_ks,
cu_seqlen_ke,
)
assert result is expected
assert captured["clean_logits"] is False
@@ -1,331 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
pytestmark = pytest.mark.skipif(
not current_platform.is_rocm(), reason="ROCm-only aiter path"
)
def _rows_from_ragged(indices: torch.Tensor, indptr: torch.Tensor) -> list[list[int]]:
ends = indptr.tolist()
return [indices[s:e].tolist() for s, e in zip(ends, ends[1:])]
def test_triton_sparse_mla_gate(monkeypatch) -> None:
import vllm._aiter_ops as aiter_ops
from vllm._aiter_ops import rocm_aiter_ops
from vllm.platforms.rocm import on_gfx950
warnings: list[str] = []
monkeypatch.setattr(
aiter_ops.logger,
"warning_once",
lambda msg, *args, **kwargs: warnings.append(msg % args),
)
def enabled(aiter: bool, flag: bool) -> bool:
monkeypatch.setenv("VLLM_ROCM_USE_AITER", str(int(aiter)))
monkeypatch.setenv("VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA", str(int(flag)))
rocm_aiter_ops.refresh_env_variables()
return bool(rocm_aiter_ops.is_triton_sparse_mla_enabled())
try:
assert not enabled(aiter=True, flag=False) and not warnings
assert not enabled(aiter=False, flag=True)
assert "VLLM_ROCM_USE_AITER is off" in warnings.pop()
# On gfx950 the flag takes effect; elsewhere it warns and falls back.
assert enabled(aiter=True, flag=True) == on_gfx950()
if not on_gfx950():
assert "gfx950" in warnings.pop()
finally:
monkeypatch.undo()
rocm_aiter_ops.refresh_env_variables()
@pytest.mark.parametrize(
"rope_dim",
[0, 64],
ids=["rope_free", "appended_rope"], # GLM-5.3-Flash; GLM-5.1/5.2, V3.2
)
@pytest.mark.parametrize("kv_cache_dtype", ["auto", "fp8"])
@torch.inference_mode()
def test_forward_mqa_prepares_triton_sparse_mla_inputs(
monkeypatch, rope_dim: int, kv_cache_dtype: str
) -> None:
"""What forward_mqa hands aiter: global slots built from the request-local
top-k rows, q quantized with the layer's scale, and the cache as stored."""
from vllm._aiter_ops import rocm_aiter_ops
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
ROCMAiterMLASparseImpl,
)
device = torch.device("cuda")
gen = torch.Generator().manual_seed(0)
kv_lora_rank, num_heads, topk, block_size = 512, 16, 128, 16
head_size = kv_lora_rank + rope_dim
fp8 = kv_cache_dtype == "fp8"
# A decode row, then a short prefill.
query_lens, seq_lens = [1, 5], [40, 20]
num_tokens = sum(query_lens)
block_table = torch.randperm(8, generator=gen).view(2, 4).to(device, torch.int32)
topk_indices = torch.full((num_tokens, topk), -1, dtype=torch.int32)
req_id_per_token: list[int] = []
rows: list[list[int]] = []
for req, (query_len, seq_len) in enumerate(zip(query_lens, seq_lens)):
for pos in range(seq_len - query_len, seq_len):
local = torch.randperm(pos + 1, generator=gen)
topk_indices[len(rows), : pos + 1] = local.int()
slots = block_table[req, local // block_size].cpu() * block_size
rows.append((slots + local % block_size).tolist())
req_id_per_token.append(req)
indptr = torch.tensor([0] + [len(row) for row in rows]).cumsum(0)
impl = ROCMAiterMLASparseImpl.__new__(ROCMAiterMLASparseImpl)
impl.num_heads = num_heads
impl.kv_lora_rank = kv_lora_rank
impl.qk_rope_head_dim = rope_dim
impl.scale = head_size**-0.5
impl.sinks = torch.randn(num_heads, generator=gen).to(device)
impl.kv_cache_dtype = kv_cache_dtype
impl.topk_indices_buffer = topk_indices.to(device)
impl.owns_indexer = True
impl.index_epoch = 0
impl.use_aiter_sparse_mla = True
layer = SimpleNamespace(
_q_scale=torch.tensor([0.02], device=device),
_k_scale=torch.tensor([0.01], device=device),
)
metadata = SimpleNamespace(
num_actual_tokens=num_tokens,
topk_tokens=topk,
req_id_per_token=torch.tensor(req_id_per_token, dtype=torch.int32).to(device),
block_table=block_table,
block_size=block_size,
paged_kv_indptr=indptr.to(device, torch.int32),
paged_kv_indices=torch.zeros(num_tokens * topk, dtype=torch.int32).to(device),
attn_out_dtype=torch.bfloat16,
)
cache_dtype = current_platform.fp8_dtype() if fp8 else torch.bfloat16
kv_cache = torch.zeros(8, block_size, head_size, device=device).to(cache_dtype)
# Two rows of cudagraph padding past the real tokens.
q = torch.randn(num_tokens + 2, num_heads, head_size, generator=gen).to(
device, torch.bfloat16
)
calls = []
monkeypatch.setattr(
rocm_aiter_ops, "triton_sparse_mla_fwd", lambda *a, **k: calls.append((a, k))
)
out, lse = impl.forward_mqa(q, kv_cache, metadata, layer)
assert len(calls) == 1
(q_in, kv_in, o, sm_scale, kv_indptr, kv_indices), kwargs = calls[0]
assert _rows_from_ragged(kv_indices, kv_indptr) == rows
assert q_in.shape[0] == num_tokens
if fp8:
assert q_in.dtype == cache_dtype
torch.testing.assert_close(
q_in.float() * layer._q_scale, q[:num_tokens].float(), atol=1e-3, rtol=0.07
)
else:
assert q_in.data_ptr() == q.data_ptr()
assert kv_in.shape == (8 * block_size, 1, 1, head_size)
assert kv_in.data_ptr() == kv_cache.data_ptr()
assert o.data_ptr() == out.data_ptr() and o.shape[0] == num_tokens
assert sm_scale == impl.scale
assert kwargs["kv_lora_rank"] == kv_lora_rank
assert kwargs["qk_rope_head_dim"] == rope_dim
assert kwargs["q_scale"] is layer._q_scale
assert kwargs["kv_scale"] is layer._k_scale
assert kwargs["attn_sink"] is impl.sinks
assert lse is None
@pytest.mark.parametrize(
("model", "compress_ratio"),
[("deepseek_v41", 1), ("deepseek_v41", 2), ("deepseek_v4", 4)],
)
@torch.inference_mode()
def test_paged_prefill_indices_match_gathered_prefill(
monkeypatch, model: str, compress_ratio: int
) -> None:
"""The aiter prefill reads the paged caches through the SWA builder's rows
and build_prefill_topk_ragged_indices, and must attend exactly the keys the
dequantize-and-gather prefill does."""
import importlib
from tests.v1.attention.utils import create_vllm_config
from vllm._aiter_ops import rocm_aiter_ops
from vllm.v1.attention.backend import CommonAttentionMetadata
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
build_prefill_topk_ragged_indices,
)
from vllm.v1.kv_cache_interface import SlidingWindowMLASpec
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
builder_cls = (
rocm.DeepseekV41ROCMAiterSparseSWAMetadataBuilder
if model == "deepseek_v41"
else rocm.DeepseekV4ROCMAiterSparseSWAMetadataBuilder
)
device = torch.device("cuda")
gen = torch.Generator().manual_seed(compress_ratio)
window, width, block_size, max_model_len = 16, 32, 16, 128
comp_block = block_size // compress_ratio
num_compressed = max_model_len // compress_ratio
# A decode row, then prefills with and without a prefix.
prefix_lens, query_lens = [20, 0, 13, 40], [1, 7, 20, 9]
seq_lens = [p + q for p, q in zip(prefix_lens, query_lens)]
num_decodes = num_decode_tokens = 1
num_tokens = sum(query_lens)
qsl = torch.tensor([0] + query_lens).cumsum(0).to(torch.int32)
positions = torch.cat([torch.arange(p, s) for p, s in zip(prefix_lens, seq_lens)])
token_to_req = torch.repeat_interleave(
torch.arange(len(query_lens)), torch.tensor(query_lens)
)
swa_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
comp_bt = torch.randperm(32, generator=gen)[:16].view(4, 4).to(device, torch.int32)
vllm_config = create_vllm_config(
model_name="facebook/opt-125m",
max_model_len=max_model_len,
block_size=block_size,
max_num_seqs=4,
max_num_batched_tokens=64,
hf_config_override={
"compress_ratios": [compress_ratio],
"index_topk": width,
"sliding_window": window,
},
)
swa_spec = SlidingWindowMLASpec(
block_size=block_size,
num_kv_heads=1,
head_size=512,
dtype=torch.bfloat16,
sliding_window=window,
cache_dtype_str="fp8_ds_mla",
model_version="deepseek_v4",
)
slots = swa_bt.cpu()[token_to_req, positions // block_size] * block_size + (
positions % block_size
)
common = CommonAttentionMetadata(
query_start_loc=qsl.to(device),
query_start_loc_cpu=qsl,
seq_lens=torch.tensor(seq_lens, dtype=torch.int32).to(device),
seq_lens_cpu_upper_bound=torch.tensor(seq_lens, dtype=torch.int32),
num_reqs=len(query_lens),
num_actual_tokens=num_tokens,
max_query_len=max(query_lens),
max_seq_len=max(seq_lens),
block_table_tensor=swa_bt,
slot_mapping=slots.to(device, torch.int64),
positions=positions.to(device),
causal=True,
)
def build(enabled: bool):
monkeypatch.setattr(
rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: enabled
)
return builder_cls(swa_spec, ["swa"], vllm_config, device).build(0, common)
assert build(enabled=False).prefill_swa_ragged_indices is None
md = build(enabled=True)
assert md.num_decode_tokens == num_decode_tokens
# Local top-k rows. Under each row's causal cap sit a failed candidate and
# one past the pool; past the cap, stale values neither path may read.
num_prefill_tokens = num_tokens - num_decode_tokens
topk = torch.full((num_prefill_tokens, width), -1, dtype=torch.int32)
for row in range(num_prefill_tokens):
visible = (int(positions[row + num_decode_tokens]) + 1) // compress_ratio
cap = min(visible, width)
topk[row, :cap] = torch.randperm(visible, generator=gen)[:cap].int()
if cap >= 2:
topk[row, :2] = torch.tensor([-1, num_compressed + 3])
topk[row, cap:] = torch.randint(
0, num_compressed, (width - cap,), generator=gen
).int()
topk = topk.to(device)
topk_indices, topk_indptr = build_prefill_topk_ragged_indices(
topk,
md.token_to_req_indices,
md.query_start_loc,
md.seq_lens,
md.is_valid_token,
comp_bt,
block_size=comp_block,
compress_ratio=compress_ratio,
num_compressed=num_compressed,
token_offset=num_decode_tokens,
)
paged_keys = [
sorted([("s", x) for x in swa if x >= 0] + [("c", x) for x in top if x >= 0])
for swa, top in zip(
_rows_from_ragged(
md.prefill_swa_ragged_indices, md.prefill_swa_ragged_indptr
),
_rows_from_ragged(topk_indices, topk_indptr),
)
]
# The gathered path's combine, mapped from workspace offsets to cache slots.
M = num_compressed + window + num_tokens
combined, combined_lens = rocm.combine_topk_swa_indices(
topk,
md.query_start_loc[num_decodes:],
md.prefill_seq_lens,
md.prefill_gather_lens,
window,
compress_ratio,
width,
M,
num_compressed,
)
gather_start = (md.prefill_seq_lens - md.prefill_gather_lens).tolist()
swa_bt_cpu, comp_bt_cpu = swa_bt.cpu(), comp_bt.cpu()
def slot(block_table, req, pos, size):
return int(block_table[req, pos // size]) * size + pos % size
gathered_keys = []
for row, (values, n) in enumerate(zip(combined.tolist(), combined_lens.tolist())):
req = int(token_to_req[row + num_decode_tokens])
chunk_req = req - num_decodes
keys = []
for value in values[:n]:
if value < 0:
continue
offset = value - chunk_req * M
if offset < num_compressed:
keys.append(("c", slot(comp_bt_cpu, req, offset, comp_block)))
else:
pos = gather_start[chunk_req] + offset - num_compressed
keys.append(("s", slot(swa_bt_cpu, req, pos, block_size)))
gathered_keys.append(sorted(keys))
assert paged_keys == gathered_keys
@pytest.mark.parametrize("model", ["deepseek_v4", "deepseek_v41"])
def test_aiter_sparse_mla_stays_off_with_kv_connector(monkeypatch, model) -> None:
import importlib
from vllm._aiter_ops import rocm_aiter_ops
rocm = importlib.import_module(f"vllm.models.{model}.amd.rocm")
monkeypatch.setattr(rocm_aiter_ops, "is_triton_sparse_mla_enabled", lambda: True)
assert rocm._aiter_sparse_mla_enabled(has_kv_transfer=False)
assert not rocm._aiter_sparse_mla_enabled(has_kv_transfer=True)
@@ -1,992 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for attention backend selectors."""
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
import torch
from vllm.config.attention import AttentionConfig
from vllm.config.parallel import ParallelConfig
from vllm.platforms import current_platform
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.attention.selector import AttentionSelectorConfig
# ROCm-specific attention backend selection tests
pytestmark = pytest.mark.skipif(
not current_platform.is_rocm(), reason="ROCm-specific tests"
)
@pytest.fixture
def mock_vllm_config():
"""Create a mock VllmConfig for testing."""
config = MagicMock()
config.model_config.dtype = torch.float16
config.model_config.hf_config.architectures = ["LlamaForCausalLM"]
config.cache_config.block_size = 16
return config
@pytest.fixture
def mock_get_cdna_version():
"""Mock cdna version arch detection to return True."""
with patch("vllm.platforms.rocm.get_cdna_version", return_value=3):
yield
@pytest.fixture
def cleared_attention_selector_cache():
from vllm.v1.attention.selector import _cached_get_attn_backend
_cached_get_attn_backend.cache_clear()
yield
_cached_get_attn_backend.cache_clear()
def test_deepseek_rocm_backend_registry_paths_are_model_specific():
assert AttentionBackendEnum.ROCM_FLASHMLA_SPARSE_DSV4.get_path() == (
"vllm.models.deepseek_v4.amd.rocm.DeepseekV4ROCMAiterMLASparseBackend"
)
assert AttentionBackendEnum.ROCM_FLASHMLA_SPARSE_DSV41.get_path() == (
"vllm.models.deepseek_v41.amd.rocm.DeepseekV41ROCMAiterMLASparseBackend"
)
@pytest.mark.parametrize(
"backend_name, expect_warning",
[
("ROCM_FLASHMLA_SPARSE_DSV4", True),
("ROCM_FLASHMLA_SPARSE_DSV41", False),
],
ids=["legacy", "canonical"],
)
def test_deepseek_v41_rocm_accepts_legacy_backend_alias(backend_name, expect_warning):
from vllm.models.deepseek_v41.amd import model as dsv41_model
from vllm.models.deepseek_v41.amd.rocm import (
DeepseekV41ROCMAiterMLAAttention,
DeepseekV41ROCMAiterMLASparseBackend,
)
config = SimpleNamespace(
attention_config=AttentionConfig(backend=backend_name),
parallel_config=ParallelConfig(),
)
with patch.object(dsv41_model.logger, "warning_once") as warning_once:
selected = dsv41_model._select_dsv4_attn_cls(config)
assert selected is DeepseekV41ROCMAiterMLAAttention
if expect_warning:
warning_once.assert_called_once()
else:
warning_once.assert_not_called()
assert (
DeepseekV41ROCMAiterMLASparseBackend.get_name() == "ROCM_FLASHMLA_SPARSE_DSV41"
)
def test_aiter_unified_attention_uses_dedicated_metadata_builder():
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionBackend,
RocmAiterUnifiedAttentionMetadataBuilder,
)
from vllm.v1.attention.backends.rocm_attn import (
RocmAttentionBackend,
RocmAttentionMetadataBuilder,
)
assert RocmAttentionBackend.get_builder_cls() is RocmAttentionMetadataBuilder
assert (
RocmAiterUnifiedAttentionBackend.get_builder_cls()
is RocmAiterUnifiedAttentionMetadataBuilder
)
def test_rocm_backends_do_not_support_mm_prefix():
"""Regression test: ROCm backends must not claim mm_prefix support.
If they do, prefix-LM multimodal models that attend vision tokens
bidirectionally (e.g. Gemma3 4B) will use bidirectional attention
via the ROCm backend instead of falling back to Triton, producing
incorrect results. Remove this test only if support is properly added.
"""
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionBackend,
)
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
assert not RocmAttentionBackend.supports_mm_prefix(), (
"RocmAttentionBackend does not support mm_prefix — "
"defer to Triton unified attention instead for now"
"See https://github.com/vllm-project/vllm/issues/48172"
)
assert not RocmAiterUnifiedAttentionBackend.supports_mm_prefix(), (
"RocmAiterUnifiedAttentionBackend does not support mm_prefix — "
"defer to Triton unified attention instead for now"
"See https://github.com/ROCm/aiter/issues/4168"
)
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(
use_aot_compile=True, save_format="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(
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,
)
builder = object.__new__(RocmAiterUnifiedAttentionMetadataBuilder)
metadata = MagicMock()
metadata.seq_lens = torch.tensor([1048576, 524288], dtype=torch.int32)
builder.build = MagicMock(return_value=metadata)
common = MagicMock()
expected_query_start_loc = torch.tensor([0, 2, 5], dtype=torch.int32)
common.query_start_loc = expected_query_start_loc.clone()
metadata.query_start_loc = common.query_start_loc
actual = builder.build_for_cudagraph_capture(common)
builder.build.assert_called_once_with(0, common)
assert actual is metadata
assert torch.equal(actual.seq_lens, torch.ones_like(actual.seq_lens))
assert actual.query_start_loc is common.query_start_loc
assert torch.equal(actual.query_start_loc, expected_query_start_loc)
@pytest.mark.parametrize("use_dcp", [False, True])
@pytest.mark.parametrize(
"env_vars, selected_backend, expected_backend_path",
[
# Test Case: Explicit FLEX_ATTENTION backend
(
{},
"FLEX_ATTENTION",
AttentionBackendEnum.FLEX_ATTENTION.get_path(),
),
# Test Case 1: Default (no env vars, no explicit backend)
(
{},
None,
AttentionBackendEnum.ROCM_ATTN.get_path(),
),
# Test Case 2: Explicit TRITON_ATTN backend
(
{},
"TRITON_ATTN",
AttentionBackendEnum.TRITON_ATTN.get_path(),
),
# Test Case 3: Explicit ROCM_ATTN backend
(
{},
"ROCM_ATTN",
AttentionBackendEnum.ROCM_ATTN.get_path(),
),
# Test Case 4: Explicit ROCM_AITER_FA backend
(
{},
"ROCM_AITER_FA",
AttentionBackendEnum.ROCM_AITER_FA.get_path(),
),
# Test Case 5: Explicit ROCM_AITER_UNIFIED_ATTN backend
(
{},
"ROCM_AITER_UNIFIED_ATTN",
AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN.get_path(),
),
# Test Case 6: VLLM_ROCM_USE_AITER=1
(
{"VLLM_ROCM_USE_AITER": "1"},
None,
AttentionBackendEnum.ROCM_ATTN.get_path(),
),
# Test Case 7: VLLM_ROCM_USE_AITER=1 + explicit TRITON_ATTN
(
{"VLLM_ROCM_USE_AITER": "1"},
"TRITON_ATTN",
AttentionBackendEnum.TRITON_ATTN.get_path(),
),
# Test Case 8: VLLM_ROCM_USE_AITER=1 + VLLM_ROCM_USE_AITER_MHA=0
(
{"VLLM_ROCM_USE_AITER": "1", "VLLM_ROCM_USE_AITER_MHA": "0"},
None,
AttentionBackendEnum.ROCM_ATTN.get_path(),
),
# Test Case 9: VLLM_ROCM_USE_AITER=1 + explicit ROCM_ATTN
(
{"VLLM_ROCM_USE_AITER": "1"},
"ROCM_ATTN",
AttentionBackendEnum.ROCM_ATTN.get_path(),
),
],
)
def test_standard_attention_backend_selection(
env_vars,
selected_backend,
expected_backend_path,
use_dcp,
mock_vllm_config,
mock_get_cdna_version,
monkeypatch,
):
"""Standard ROCm backends remain selectable without DCP and reject DCP."""
# Set environment variables
for key, value in env_vars.items():
monkeypatch.setenv(key, value)
# Import after setting env vars to ensure they're picked up
# Reload envs to pick up new environment variables
import importlib
import vllm.envs as envs
importlib.reload(envs)
# Convert string backend to enum if provided
backend_enum = None
if selected_backend:
backend_enum = getattr(AttentionBackendEnum, selected_backend)
# Get the backend class path
from vllm.platforms.rocm import RocmPlatform
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=16,
use_mla=False,
has_sink=False,
use_sparse=False,
use_dcp=use_dcp,
)
if use_dcp:
with pytest.raises(ValueError, match="DCP not supported"):
RocmPlatform.get_attn_backend_cls(backend_enum, attn_selector_config)
return
backend_path = RocmPlatform.get_attn_backend_cls(
selected_backend=backend_enum, attn_selector_config=attn_selector_config
)
assert backend_path == expected_backend_path
@pytest.mark.parametrize("use_dcp", [False, True])
@pytest.mark.parametrize(
"env_vars, selected_backend, block_size, expected_backend_path, should_raise",
[
# Test Case 1: TRITON_MLA with block_size != 1
(
{},
"TRITON_MLA",
16,
AttentionBackendEnum.TRITON_MLA.get_path(),
False,
),
# Test Case 2: TRITON_MLA with block_size == 1 (should raise)
(
{},
"TRITON_MLA",
1,
None,
True,
),
# Test Case 3: ROCM_AITER_MLA with block_size == 1
(
{},
"ROCM_AITER_MLA",
1,
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
False,
),
# Test Case 4: ROCM_AITER_MLA with block_size != 1 (should raise)
(
{},
"ROCM_AITER_MLA",
16,
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
False,
),
# Test Case 5: VLLM_ROCM_USE_AITER=1 with block_size == 1
(
{"VLLM_ROCM_USE_AITER": "1"},
None,
1,
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
False,
),
# Test Case 6: VLLM_ROCM_USE_AITER=1 with block_size == 16
# (should use ROCM_AITER_MLA now, as it supports block_size 16)
(
{"VLLM_ROCM_USE_AITER": "1"},
None,
16,
AttentionBackendEnum.ROCM_AITER_MLA.get_path(),
False,
),
# Test Case 7: VLLM_ROCM_USE_AITER=1 + explicit TRITON_MLA
(
{"VLLM_ROCM_USE_AITER": "1"},
"TRITON_MLA",
16,
AttentionBackendEnum.TRITON_MLA.get_path(),
False,
),
# Test Case 8: Explicit ROCM_AITER_TRITON_MLA
(
{},
"ROCM_AITER_TRITON_MLA",
16,
AttentionBackendEnum.ROCM_AITER_TRITON_MLA.get_path(),
False,
),
],
)
def test_mla_backend_selection(
env_vars,
selected_backend,
block_size,
expected_backend_path,
should_raise,
use_dcp,
mock_vllm_config,
monkeypatch,
):
"""Dense MLA remains selectable with DCP for valid block sizes."""
# Set environment variables
for key, value in env_vars.items():
monkeypatch.setenv(key, value)
# Import after setting env vars
# Reload envs
import importlib
import vllm.envs as envs
importlib.reload(envs)
# Mock is_aiter_mla_enabled based on env vars and block_size
aiter_enabled = env_vars.get("VLLM_ROCM_USE_AITER") == "1"
mock_rocm_ops = MagicMock()
mock_rocm_ops.is_mla_enabled.return_value = aiter_enabled
mock_aiter_module = MagicMock()
mock_aiter_module.rocm_aiter_ops = mock_rocm_ops
with patch.dict("sys.modules", {"vllm._aiter_ops": mock_aiter_module}):
# Convert string backend to enum if provided
backend_enum = None
if selected_backend:
backend_enum = getattr(AttentionBackendEnum, selected_backend)
from vllm.platforms.rocm import RocmPlatform
if should_raise:
with pytest.raises(ValueError):
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=block_size,
use_mla=True,
has_sink=False,
use_sparse=False,
use_dcp=use_dcp,
)
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=block_size,
use_mla=True,
has_sink=False,
use_sparse=False,
use_dcp=use_dcp,
)
backend_path = RocmPlatform.get_attn_backend_cls(
selected_backend=backend_enum,
attn_selector_config=attn_selector_config,
)
else:
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=block_size,
use_mla=True,
has_sink=False,
use_sparse=False,
use_dcp=use_dcp,
)
backend_path = RocmPlatform.get_attn_backend_cls(
selected_backend=backend_enum, attn_selector_config=attn_selector_config
)
assert backend_path == expected_backend_path
@pytest.mark.parametrize("use_dcp", [False, True])
@pytest.mark.parametrize(
"selected_backend", [None, AttentionBackendEnum.ROCM_AITER_MLA_SPARSE]
)
def test_sparse_mla_backend_rejects_dcp(selected_backend, use_dcp):
"""Sparse MLA remains selectable without DCP and fails early with DCP."""
from vllm.platforms.rocm import RocmPlatform
selector_config = AttentionSelectorConfig(
head_size=576,
dtype=torch.bfloat16,
kv_cache_dtype="auto",
block_size=16,
use_mla=True,
use_sparse=True,
use_dcp=use_dcp,
)
if use_dcp:
with pytest.raises(ValueError, match="DCP not supported"):
RocmPlatform.get_attn_backend_cls(selected_backend, selector_config)
else:
assert RocmPlatform.get_attn_backend_cls(selected_backend, selector_config) == (
AttentionBackendEnum.ROCM_AITER_MLA_SPARSE.get_path()
)
@pytest.mark.parametrize("use_dcp", [False, True])
@pytest.mark.parametrize(
"selected_backend, head_size, kv_cache_dtype",
[
(AttentionBackendEnum.TRITON_ATTN_DIFFKV, 192, "bfloat16"),
# A 128-dimensional head uses 118 packed bytes, or 59 fp16 elements.
(AttentionBackendEnum.TURBOQUANT, 59, "turboquant_k3v4_nc"),
],
)
def test_specialized_attention_backends_reject_dcp(
selected_backend, head_size, kv_cache_dtype, use_dcp
):
"""Valid DiffKV and compressed-cache configurations must reject DCP."""
from vllm.platforms.rocm import RocmPlatform
selector_config = AttentionSelectorConfig(
head_size=head_size,
dtype=torch.bfloat16,
kv_cache_dtype=kv_cache_dtype,
block_size=16,
use_dcp=use_dcp,
)
if use_dcp:
with pytest.raises(ValueError, match="DCP not supported"):
RocmPlatform.get_attn_backend_cls(selected_backend, selector_config)
else:
assert RocmPlatform.get_attn_backend_cls(selected_backend, selector_config) == (
selected_backend.get_path()
)
def test_aiter_fa_requires_mi3xx(mock_vllm_config):
"""Test that ROCM_AITER_FA requires CDNA3+ architecture."""
from vllm.platforms.rocm import RocmPlatform
# Mock cdna version to return 1 (used by supports_compute_capability)
with (
patch("vllm.platforms.rocm.get_cdna_version", return_value=1),
pytest.raises(
ValueError,
match="compute capability not supported",
),
):
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=16,
use_mla=False,
has_sink=False,
use_sparse=False,
)
RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_AITER_FA,
attn_selector_config=attn_selector_config,
)
@pytest.fixture
def turboquant_run_config():
"""Current config of a run whose KV cache dtype is a turboquant_* preset."""
config = SimpleNamespace(
cache_config=SimpleNamespace(cache_dtype="turboquant_k8v4")
)
with patch(
"vllm.config.get_current_vllm_config_or_none",
return_value=config,
):
yield config
def test_turboquant_boundary_selection_is_not_cached_from_ordinary_run(
cleared_attention_selector_cache,
):
from vllm.config import CacheConfig, VllmConfig, set_current_vllm_config
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
from vllm.v1.attention.selector import get_attn_backend
from vllm.v1.kv_cache_layout import KVCacheLayout
ordinary_config = VllmConfig(cache_config=CacheConfig(cache_dtype="auto"))
turboquant_config = VllmConfig(
cache_config=CacheConfig(cache_dtype="turboquant_k8v4")
)
backend_priorities = [
AttentionBackendEnum.ROCM_ATTN,
AttentionBackendEnum.TRITON_ATTN,
AttentionBackendEnum.TURBOQUANT,
]
with patch(
"vllm.platforms.rocm._get_backend_priorities",
return_value=backend_priorities,
):
with set_current_vllm_config(ordinary_config):
ordinary_backend = get_attn_backend(128, torch.float16, "auto")
with set_current_vllm_config(turboquant_config):
boundary_backend = get_attn_backend(128, torch.float16, "auto")
quantized_backend = get_attn_backend(128, torch.float16, "turboquant_k8v4")
assert ordinary_backend is AttentionBackendEnum.ROCM_ATTN.get_class()
assert quantized_backend is AttentionBackendEnum.TURBOQUANT.get_class()
assert get_supported_kv_cache_layouts([boundary_backend, quantized_backend]) == [
KVCacheLayout.LBNHC
]
def test_turboquant_run_does_not_mask_unsupported_selected_backend(
turboquant_run_config,
):
from vllm.platforms.rocm import RocmPlatform
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=16,
)
with (
patch("vllm.platforms.rocm.get_cdna_version", return_value=1),
pytest.raises(ValueError, match="compute capability not supported"),
):
RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_AITER_FA,
attn_selector_config=attn_selector_config,
)
def test_turboquant_layout_check_respects_backend_override():
from vllm.platforms.rocm import _shares_layout_with_turboquant
from vllm.v1.kv_cache_layout import KVCacheLayout
boundary_backend = MagicMock()
boundary_backend.supported_kv_cache_layouts.return_value = (KVCacheLayout.LBHNC,)
turboquant_override = MagicMock()
turboquant_override.supported_kv_cache_layouts.return_value = (KVCacheLayout.LBHNC,)
with patch.object(
AttentionBackendEnum.TURBOQUANT,
"get_class",
return_value=turboquant_override,
) as get_turboquant_class:
assert _shares_layout_with_turboquant(boundary_backend)
get_turboquant_class.assert_called_once_with()
@pytest.mark.parametrize(
"selected_backend",
[None, "ROCM_ATTN", "ROCM_AITER_FA", "TURBOQUANT"],
)
def test_turboquant_boundary_layers_share_a_layout(
selected_backend,
turboquant_run_config,
mock_get_cdna_version,
):
"""A turboquant_* run must resolve to backends with a common KV layout.
The boundary layers keep the native dtype and pick their own backend while
every other layer picks TURBOQUANT. Engine startup hard-errors when the two
share no layout, so the boundary layers must not land on a native ROCm or
AITER backend, whichever backend the run asked for.
"""
from vllm.platforms.rocm import RocmPlatform
from vllm.utils.import_utils import resolve_obj_by_qualname
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
backend_enum = (
getattr(AttentionBackendEnum, selected_backend) if selected_backend else None
)
def resolve(kv_cache_dtype):
path = RocmPlatform.get_attn_backend_cls(
selected_backend=backend_enum,
attn_selector_config=AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype=kv_cache_dtype,
block_size=16,
),
)
return resolve_obj_by_qualname(path)
boundary_backend = resolve("auto")
quantized_backend = resolve("turboquant_k8v4")
assert quantized_backend is AttentionBackendEnum.TURBOQUANT.get_class()
# Raises when the intersection is empty, which is the startup failure.
assert get_supported_kv_cache_layouts([boundary_backend, quantized_backend])
def test_sparse_not_supported(mock_vllm_config):
"""Test that sparse MLA without use_mla flag raises an error."""
from vllm.platforms.rocm import RocmPlatform
with pytest.raises(
ValueError,
match="No valid attention backend found",
):
attn_selector_config = AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=16,
use_mla=False,
has_sink=False,
use_sparse=True,
)
RocmPlatform.get_attn_backend_cls(
selected_backend=None, attn_selector_config=attn_selector_config
)
def _kv_connector_selector_config() -> AttentionSelectorConfig:
return AttentionSelectorConfig(
head_size=128,
dtype=torch.float16,
kv_cache_dtype="auto",
block_size=16,
use_mla=False,
has_sink=False,
use_sparse=False,
use_kv_connector=True,
)
def test_unified_attn_declares_kv_connector_support():
"""ROCM_AITER_UNIFIED_ATTN opts into KV connectors and ROCM_ATTN does not."""
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionBackend,
)
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
assert RocmAiterUnifiedAttentionBackend.supports_kv_connector() is True
assert RocmAttentionBackend.supports_kv_connector() is False
def test_unified_attn_supports_kv_connector(mock_vllm_config, mock_get_cdna_version):
"""ROCM_AITER_UNIFIED_ATTN can be selected with KV connectors."""
from vllm.platforms.rocm import RocmPlatform
backend_path = RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN,
attn_selector_config=_kv_connector_selector_config(),
)
assert backend_path == AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN.get_path()
def test_rocm_attn_rejects_kv_connector(mock_vllm_config, mock_get_cdna_version):
"""Selecting ROCM_ATTN with a KV connector is illegal."""
from vllm.platforms.rocm import RocmPlatform
attn_selector_config = _kv_connector_selector_config()
with pytest.raises(ValueError, match="KV connector not supported"):
RocmPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.ROCM_ATTN,
attn_selector_config=attn_selector_config,
)
@pytest.mark.parametrize(
"aiter_found, expected_backend",
[
(True, AttentionBackendEnum.ROCM_AITER_UNIFIED_ATTN),
(False, AttentionBackendEnum.TRITON_ATTN),
],
)
def test_auto_selection_for_kv_connector(
aiter_found, expected_backend, mock_vllm_config, mock_get_cdna_version
):
"""Auto-selection with a KV connector and AITER enabled resolves to unified attn,
and to triton attn if AITER not enabled."""
from vllm.platforms.rocm import RocmPlatform
with patch(
"vllm._aiter_ops.is_aiter_found_and_supported", return_value=aiter_found
):
backend_path = RocmPlatform.get_attn_backend_cls(
selected_backend=None,
attn_selector_config=_kv_connector_selector_config(),
)
assert backend_path == expected_backend.get_path()
def test_unified_attn_prefers_block_contiguous_layout():
"""Unified attn prefers a block-first KV layout, hence ok with kv connectors."""
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionBackend,
)
from vllm.v1.attention.backends.rocm_attn import RocmAttentionBackend
unified_preferred = RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()[0]
rocm_attn_preferred = RocmAttentionBackend.supported_kv_cache_layouts()[0]
assert unified_preferred.is_block_contiguous is True
assert rocm_attn_preferred.is_block_contiguous is False
def test_unified_attn_drops_lhbnc_with_kv_connector():
"""Connectors move a block as one contiguous byte range, which LHBNC breaks."""
from vllm.config import KVTransferConfig, VllmConfig, set_current_vllm_config
from vllm.v1.attention.backends.rocm_aiter_unified_attn import (
RocmAiterUnifiedAttentionBackend,
)
from vllm.v1.kv_cache_interface import KVCacheLayout
assert KVCacheLayout.LHBNC in (
RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()
)
config = VllmConfig(
kv_transfer_config=KVTransferConfig(
kv_connector="ExampleConnector", kv_role="kv_both"
)
)
with set_current_vllm_config(config):
layouts = RocmAiterUnifiedAttentionBackend.supported_kv_cache_layouts()
assert layouts
assert all(layout.is_block_compact for layout in layouts)
@@ -1,310 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import set_random_seed
from vllm.v1.attention.backends.mla import rocm_aiter_mla_sparse as sparse_mod
from vllm.v1.attention.backends.mla.rocm_aiter_mla_sparse import (
ROCMAiterMLASparseBackend,
_use_rocm_sparse_triton,
fit_kpool_indices_to_aiter,
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_sparse_kv_row_offset,
_validate_dsv4_sparse_dims,
_validate_sparse_dims,
)
from vllm.v1.kv_cache_interface import KVCacheLayout
@triton.jit
def _store_sparse_kv_row_offset_kernel(slot_ptr, output_ptr, stride: tl.constexpr):
slot = tl.load(slot_ptr)
tl.store(output_ptr, _sparse_kv_row_offset(slot, stride))
def _fit_kpool_indices_reference(
token_indices: torch.Tensor, topk_tokens: int
) -> torch.Tensor:
history = token_indices[:, :topk_tokens]
tail = token_indices[:, topk_tokens:]
valid_history = (history >= 0).sum(dim=1)
valid_tail = (tail >= 0).sum(dim=1)
keep_history = torch.minimum(valid_history, topk_tokens - valid_tail)
columns = torch.arange(topk_tokens, device=token_indices.device).unsqueeze(0)
tail_offsets = columns - keep_history.unsqueeze(1)
tail_values = torch.gather(
tail, 1, tail_offsets.clamp(min=0, max=tail.shape[1] - 1)
)
output = torch.where(columns < keep_history.unsqueeze(1), history, tail_values)
valid_output = columns < (keep_history + valid_tail).unsqueeze(1)
return torch.where(valid_output, output, -1)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
def test_fit_kpool_indices_preserves_tail_and_best_history():
token_indices = torch.tensor(
[
[10, 9, 8, 7, 6, 5, 100, 101],
[10, 9, 8, -1, -1, -1, 100, -1],
[-1, -1, -1, -1, -1, -1, -1, -1],
],
dtype=torch.int32,
device="cuda",
)
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=6)
assert fitted.tolist() == [
[10, 9, 8, 7, 100, 101],
[10, 9, 8, 100, -1, -1],
[-1, -1, -1, -1, -1, -1],
]
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
@pytest.mark.parametrize(
("num_tokens", "topk_tokens", "tail_width"),
[(1, 4, 1), (7, 6, 2), (13, 128, 128), (3, 2048, 128)],
)
def test_fit_kpool_indices_matches_eager_reference(num_tokens, topk_tokens, tail_width):
"""The Triton fit must reproduce the eager packing rule exactly."""
set_random_seed(topk_tokens + num_tokens)
width = topk_tokens + tail_width
token_indices = torch.randint(0, 4096, (num_tokens, width), dtype=torch.int32)
valid = torch.rand((num_tokens, width)) < 0.5
valid[0] = False
valid[-1] = True
token_indices = torch.where(valid, token_indices, -1).cuda()
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=topk_tokens)
torch.testing.assert_close(
fitted, _fit_kpool_indices_reference(token_indices, topk_tokens)
)
def test_fit_kpool_indices_exact_width_is_noop():
token_indices = torch.tensor([[3, 2, 1, -1]], dtype=torch.int32)
fitted = fit_kpool_indices_to_aiter(token_indices, topk_tokens=4)
assert fitted.data_ptr() == token_indices.data_ptr()
def test_fit_kpool_indices_rejects_narrow_input():
with pytest.raises(ValueError, match="at least topk_tokens"):
fit_kpool_indices_to_aiter(
torch.zeros((1, 3), dtype=torch.int32), topk_tokens=4
)
def test_rocm_sparse_mla_supports_glm_packed_layout():
assert KVCacheLayout.BLHNC in ROCMAiterMLASparseBackend.supported_kv_cache_layouts()
@pytest.mark.parametrize(
(
"kv_cache_dtype",
"head_size",
"num_prefills",
"num_decodes",
"num_decode_tokens",
"max_query_len",
"expected",
),
[
("auto", 512, 1, 0, 0, 32, True),
("auto", 512, 1, 2, 2, 32, True),
("auto", 512, 0, 2, 2, 1, True),
("fp8", 512, 1, 0, 0, 32, False),
("auto", 576, 1, 0, 0, 32, False),
("auto", 512, 0, 2, 4, 2, True),
("auto", 512, 0, 2, 12, 6, True),
("auto", 512, 0, 0, 0, 0, False),
],
)
def test_rocm_sparse_triton_route(
kv_cache_dtype,
head_size,
num_prefills,
num_decodes,
num_decode_tokens,
max_query_len,
expected,
):
"""Validate Triton routing for prefill, decode, and MTP verification."""
assert (
_use_rocm_sparse_triton(
kv_cache_dtype=kv_cache_dtype,
head_size=head_size,
kv_lora_rank=512,
num_prefills=num_prefills,
num_decodes=num_decodes,
num_decode_tokens=num_decode_tokens,
max_query_len=max_query_len,
)
is expected
)
@pytest.mark.parametrize(
("gfx942", "fp8", "num_prefills", "num_decodes", "prefill_max_seq_len", "route"),
[
pytest.param(True, False, 1, 0, 129, "triton", id="above-topk"),
pytest.param(False, False, 1, 0, 129, "aiter", id="gfx950"),
pytest.param(True, True, 1, 0, 129, "aiter", id="fp8"),
pytest.param(True, False, 0, 2, 129, "aiter", id="decode-only"),
pytest.param(True, False, 1, 1, 129, "aiter", id="mixed"),
pytest.param(True, False, 1, 0, 128, "aiter", id="equal-topk"),
pytest.param(True, False, 1, 0, 127, "aiter", id="below-topk"),
pytest.param(True, False, 0, 0, 129, "aiter", id="empty"),
pytest.param(
True, False, 1, 0, None, "missing", id="required-prefill-metadata"
),
],
)
def test_rocm_long_bf16_prefill_dispatch(
monkeypatch, gfx942, fp8, num_prefills, num_decodes, prefill_max_seq_len, route
):
"""Check the new dispatch gate using CPU tensors and intercepted kernels."""
monkeypatch.setattr("vllm.platforms.rocm.on_gfx942", lambda: gfx942)
class KernelSelected(Exception):
pass
def triton_kernel(**kwargs):
raise KernelSelected("triton")
def aiter_kernel(*args, **kwargs):
raise KernelSelected("aiter")
monkeypatch.setattr(sparse_mod, "rocm_sparse_attn_prefill", triton_kernel)
monkeypatch.setattr(sparse_mod.rocm_aiter_ops, "mla_decode_fwd", aiter_kernel)
impl = object.__new__(sparse_mod.ROCMAiterMLASparseImpl)
impl.num_heads = 64
impl.kv_lora_rank = 512
impl.kv_cache_dtype = "fp8" if fp8 else "auto"
impl.scale = 576**-0.5
impl.sinks = None
dtype = torch.float8_e4m3fn if fp8 else torch.bfloat16
q = torch.empty(2, 64, 576, dtype=dtype)
kv = torch.empty(4, 1, 576, dtype=dtype)
metadata = SimpleNamespace(
attn_out_dtype=torch.bfloat16,
num_prefills=num_prefills,
num_decodes=num_decodes,
num_decode_tokens=num_decodes,
max_query_len=2,
prefill_max_seq_len=prefill_max_seq_len,
topk_tokens=128,
work_meta_data=None,
qo_indptr=torch.arange(3, dtype=torch.int32),
paged_kv_indices=torch.empty(0, dtype=torch.int32),
paged_kv_indptr=torch.zeros(3, dtype=torch.int32),
paged_kv_last_page_len=torch.ones(2, dtype=torch.int32),
)
# Irrelevant routes must not inspect prefill-only metadata.
if (
not gfx942
or fp8
or num_decodes
or not num_prefills
or prefill_max_seq_len is None
):
del metadata.prefill_max_seq_len
del metadata.topk_tokens
layer = SimpleNamespace(_q_scale=1.0, _k_scale=1.0)
error = AttributeError if route == "missing" else KernelSelected
match = "prefill_max_seq_len" if route == "missing" else f"^{route}$"
with pytest.raises(error, match=match):
impl._forward_mla(layer, q, kv, metadata)
@pytest.mark.parametrize("gfx942", [False, True])
@pytest.mark.parametrize("num_heads", [8, 12])
def test_rocm_sparse_triton_route_preserves_padded_sinks(
monkeypatch, num_heads, gfx942
):
monkeypatch.setattr("vllm.platforms.rocm.on_gfx942", lambda: gfx942)
captured = {}
def fake_rocm_sparse_attn_prefill(**kwargs):
output = kwargs["output"]
captured["attn_sink"] = kwargs["attn_sink"]
output.copy_(
captured["attn_sink"].to(output.dtype).view(1, -1, 1).expand_as(output)
)
monkeypatch.setattr(
sparse_mod, "rocm_sparse_attn_prefill", fake_rocm_sparse_attn_prefill
)
impl = object.__new__(sparse_mod.ROCMAiterMLASparseImpl)
impl.num_heads = num_heads
impl.kv_lora_rank = 512
impl.kv_cache_dtype = "auto"
impl.scale = 512**-0.5
impl.sinks = torch.arange(num_heads, dtype=torch.float32)
q = torch.zeros(2, 16, 512, dtype=torch.bfloat16)
kv = torch.zeros(4, 1, 512, dtype=torch.bfloat16)
metadata = SimpleNamespace(
attn_out_dtype=torch.bfloat16,
num_prefills=1,
num_decodes=0,
num_decode_tokens=0,
max_query_len=2,
paged_kv_indices=torch.empty(0, dtype=torch.int32),
paged_kv_indptr=torch.zeros(3, dtype=torch.int32),
)
output, lse = impl._forward_mla(SimpleNamespace(), q, kv, metadata)
if num_heads == 8:
expected_sinks = impl.sinks.repeat_interleave(2)
else:
expected_sinks = torch.cat((impl.sinks, impl.sinks[:4]))
torch.testing.assert_close(captured["attn_sink"], expected_sinks)
assert output.shape == (2, num_heads, 512)
torch.testing.assert_close(
output[:, :, 0].float(),
impl.sinks.expand(2, -1),
)
assert lse is None
def test_rocm_sparse_attention_accepts_glm_nope_dimensions():
_validate_sparse_dims(512, 512, 0, "test")
def test_rocm_sparse_attention_rejects_inconsistent_dimensions():
with pytest.raises(AssertionError, match="expected head_dim"):
_validate_sparse_dims(511, 512, 0, "test")
def test_dsv4_sparse_attention_keeps_layout_constraint():
_validate_dsv4_sparse_dims(512, 448, 64, "test")
with pytest.raises(AssertionError, match="expects 448 NoPE dims"):
_validate_dsv4_sparse_dims(512, 512, 0, "test")
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm required")
def test_sparse_prefill_kv_row_offset_does_not_overflow_int32():
# GLM's 640-token pages cross the signed-int32 address boundary at block
# 6554 for a 512-element KV row. The production kernel must promote the
# slot before multiplying by the row stride.
slot = torch.tensor([6554 * 640], dtype=torch.int32, device="cuda")
output = torch.empty(1, dtype=torch.int64, device="cuda")
_store_sparse_kv_row_offset_kernel[(1,)](slot, output, stride=512)
assert output.item() == 6554 * 640 * 512
@@ -1,445 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
import pytest
import torch
from tests.utils import multi_gpu_only
from vllm.platforms import current_platform
from vllm.v1.attention.ops.rocm_aiter_mla_prefill import context_row_indices
@pytest.mark.parametrize(
"padded,lengths,starts,total,expected",
[
([3, 2], [[7, 6], [2, 1]], [5, 0], 6, [0, 1, 5, 3, 4, 8]),
([3], [[2, 9]], [4], 3, [3, 4, 5]),
([3], [[1, 1]], [0], 3, None),
],
ids=["padding_and_chunk_starts", "empty_rank", "inconsistent_total"],
)
def test_dcp_context_indices(padded, lengths, starts, total, expected):
chunk = SimpleNamespace(
padded_local_seq_lens=padded,
local_context_lens_allranks=lengths,
local_starts=starts,
num_local_context_tokens=sum(padded),
num_context_tokens=total,
)
if expected is None:
with pytest.raises(AssertionError):
context_row_indices(chunk, torch.device("cpu"))
else:
rows = context_row_indices(chunk, torch.device("cpu"))
assert rows.tolist() == expected
assert rows.dtype == torch.int32
def test_compressed_gather_preserves_bytes_and_workspace_partition(monkeypatch):
from vllm.v1.attention.ops import rocm_aiter_mla_prefill as prefill
workspace = torch.full((12, 4), -1, dtype=torch.bfloat16)
cache = torch.arange(8, dtype=torch.uint8).reshape(2, 4)
chunk = SimpleNamespace(
num_local_context_tokens=2,
local_context_lens_allranks=[[2, 2]],
padded_local_cu_seq_lens=torch.tensor([0, 2]),
num_requests=1,
starts=torch.tensor([0]),
)
def local_gather(src, dst, *args):
assert src.dtype == dst.dtype == torch.uint8
dst.copy_(src)
def allgather(dst, src):
assert dst.dtype == src.dtype == torch.uint8
assert dst.shape == (4, 4)
assert src.shape == (2, 4)
dst[:2].copy_(src)
dst[2:].copy_(src + 16)
monkeypatch.setattr(prefill.ops, "cp_gather_cache", local_gather)
gathered = prefill.gather_compressed_context(
cache, workspace, torch.empty(1, 1), chunk, allgather, torch.float8_e4m3fn
)
torch.testing.assert_close(
gathered.view(torch.uint8), torch.cat((cache, cache + 16))
)
# Retain the original logical capacity even though the byte view is larger.
assert gathered.data_ptr() - workspace.data_ptr() == 4 * 4
torch.testing.assert_close(workspace.view(torch.uint8).reshape(-1, 4)[:2], cache)
@pytest.mark.parametrize(
"unsupported",
[
"packed_cache",
"e5m2",
"bf16_cache",
"quantized_weight",
"bias",
"no_indices",
"query_dtype",
"prefill_dtype",
"weight_dtype",
"weight_layout",
"cache_layout",
"dimensions",
"no_aiter",
],
)
def test_dcp_prefill_unsupported_formats_use_original_path(monkeypatch, unsupported):
from vllm.platforms import current_platform
if not current_platform.is_rocm():
pytest.skip("ROCm MLA backend")
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
AiterMLAImpl,
MLACommonImpl,
)
if unsupported == "no_aiter":
monkeypatch.setattr(
"vllm.v1.attention.backends.mla.rocm_aiter_mla."
"is_aiter_found_and_supported",
lambda: False,
)
impl = object.__new__(AiterMLAImpl)
impl.kv_cache_dtype = {
"packed_cache": "fp8_ds_mla",
"e5m2": "fp8_e5m2",
"bf16_cache": "auto",
}.get(unsupported, "fp8")
impl.kv_lora_rank = 512
if unsupported == "dimensions":
impl.kv_lora_rank = 256
impl.qk_nope_head_dim = impl.v_head_dim = 128
impl.qk_rope_head_dim = 64
impl.num_heads = 1
impl.kv_b_proj = SimpleNamespace(
weight=torch.empty(256, 512, dtype=torch.bfloat16),
weight_scale=torch.ones(1) if unsupported == "quantized_weight" else None,
bias=torch.ones(256) if unsupported == "bias" else None,
)
if unsupported == "weight_dtype":
impl.kv_b_proj.weight = impl.kv_b_proj.weight.half()
elif unsupported == "weight_layout":
impl.kv_b_proj.weight = torch.empty(512, 256, dtype=torch.bfloat16).T
metadata = SimpleNamespace(
prefill=SimpleNamespace(
q_data_type=torch.float16
if unsupported == "prefill_dtype"
else torch.bfloat16
),
dcp_context_row_indices=None if unsupported == "no_indices" else [],
)
expected = (torch.ones(1), torch.zeros(1))
def fused_mla_kv_concat(kv_nope, k_pe, use_fp8_prefill):
raise AssertionError("The fallback should receive the callback")
def original_path(*args):
assert args[-1] is fused_mla_kv_concat
return expected
monkeypatch.setattr(
MLACommonImpl,
"_context_parallel_compute_prefill_context",
original_path,
)
q = torch.empty(1, 1, 192, dtype=torch.bfloat16)
cache = torch.empty(1, 1536, 576, dtype=torch.uint8)
if unsupported == "query_dtype":
q = q.half()
elif unsupported == "cache_layout":
cache = torch.empty(1, 1536, 1152, dtype=torch.uint8)[..., ::2]
assert (
impl._context_parallel_compute_prefill_context(
q,
cache,
metadata,
torch.ones(1),
8,
fused_mla_kv_concat_fn=fused_mla_kv_concat,
)
is expected
)
@pytest.mark.skipif(not current_platform.is_rocm(), reason="ROCm MLA backend")
@multi_gpu_only(num_gpus=2)
@pytest.mark.parametrize("interleave", [1, 64])
@pytest.mark.parametrize(
"context_lens,workspace_size",
[([145, 37], 1024), ([545, 0, 3, 0], 256)],
ids=["single_chunk", "continuations_and_empty_context"],
)
def test_dcp_prefill_matches_full_attention(
interleave, context_lens, workspace_size, tmp_path
):
"""Real DCP gather, fused expansion and suffix/chunk merges match dense SDPA."""
import torch.multiprocessing as mp
from vllm._aiter_ops import is_aiter_found_and_supported
if not is_aiter_found_and_supported():
pytest.skip("AITER on CDNA 3 or newer is required")
mp.spawn(
_dcp_prefill_worker,
args=(
f"file://{tmp_path / 'dist_init'}",
interleave,
context_lens,
workspace_size,
),
nprocs=2,
)
@torch.inference_mode()
def _dcp_prefill_worker(rank, init_method, interleave, context_lens, workspace_size):
import torch.nn.functional as F
from tests.v1.attention.test_mla_backends import MockMLAAttentionLayer
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
create_vllm_config,
)
from vllm.config import set_current_vllm_config
from vllm.distributed import (
cleanup_dist_env_and_memory,
init_distributed_environment,
initialize_model_parallel,
)
from vllm.model_executor.layers.linear import ColumnParallelLinear
from vllm.v1.attention.backends.mla.prefill.aiter_flash_attn import (
AiterFlashAttnPrefillBackend,
)
from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
AiterMLAImpl,
AiterMLAMetadataBuilder,
)
from vllm.v1.attention.ops.dcp import MLADCPManager
from vllm.v1.kv_cache_interface import MLAAttentionSpec
from vllm.v1.worker.workspace import init_workspace_manager
torch.accelerator.set_device_index(rank)
torch.set_num_threads(1)
device = torch.device(f"cuda:{rank}")
init_workspace_manager(device)
world_size, num_heads, block_size = 2, 12, 64
config = create_vllm_config(
model_name="deepseek-ai/DeepSeek-V2-Lite",
dtype=torch.bfloat16,
tensor_parallel_size=world_size,
max_model_len=2048,
block_size=block_size,
max_num_seqs=8,
max_num_batched_tokens=2048,
)
config.cache_config.cache_dtype = "fp8"
config.parallel_config.decode_context_parallel_size = world_size
config.parallel_config.cp_kv_cache_interleave_size = interleave
config.attention_config.use_prefill_query_quantization = False
config.kernel_config.enable_jit_warmup = False
with set_current_vllm_config(config):
init_distributed_environment(
world_size=world_size,
rank=rank,
local_rank=rank,
distributed_init_method=init_method,
)
initialize_model_parallel(
tensor_model_parallel_size=world_size,
decode_context_model_parallel_size=world_size,
)
try:
projection = ColumnParallelLinear(
512,
num_heads * world_size * 256,
bias=False,
params_dtype=torch.bfloat16,
).to(device)
torch.manual_seed(101 + rank)
projection.weight.copy_(torch.randn_like(projection.weight) * 0.02)
dims = dict(
kv_lora_rank=512,
qk_nope_head_dim=128,
qk_rope_head_dim=64,
v_head_dim=128,
)
impl = AiterMLAImpl(
num_heads=num_heads,
head_size=576,
scale=192**-0.5,
num_kv_heads=1,
alibi_slopes=None,
sliding_window=None,
kv_cache_dtype="fp8",
logits_soft_cap=None,
attn_type="decoder",
kv_sharing_target_layer_name=None,
q_lora_rank=None,
qk_head_dim=192,
kv_b_proj=projection,
**dims,
)
layer = MockMLAAttentionLayer(
impl=impl,
num_heads=num_heads,
device=device,
kv_b_proj=projection,
q_scale=1.0,
k_scale=0.07,
**dims,
)
layer.prefill_backend = AiterFlashAttnPrefillBackend(
num_heads=num_heads,
scale=impl.scale,
vllm_config=config,
**dims,
)
layer.dcp_manager = MLADCPManager(
config,
device,
num_heads,
576,
512,
torch.bfloat16,
torch.bfloat16,
None,
True,
False,
)
config.compilation_config.static_forward_context["mla"] = layer
spec = MLAAttentionSpec(
block_size=block_size,
num_kv_heads=1,
head_size=576,
dtype=current_platform.fp8_dtype(),
cache_dtype_str="fp8",
)
builder = AiterMLAMetadataBuilder(spec, ["mla"], config, device)
builder.chunked_prefill_workspace_size = workspace_size
builder.chunked_prefill_workspace = torch.empty(
(workspace_size + workspace_size // world_size, 576),
dtype=torch.bfloat16,
device=device,
)
layer.dcp_manager.init_kv_gather(
builder.chunked_prefill_workspace, workspace_size
)
query_lens = [i + 2 for i in range(len(context_lens))]
batch = BatchSpec(
seq_lens=[c + q for c, q in zip(context_lens, query_lens)],
query_lens=query_lens,
)
common = create_common_attn_metadata(
batch, block_size, device, arange_block_indices=True
)
metadata = builder.build(0, common)
assert metadata.prefill is not None
chunked = metadata.prefill.chunked_context
assert chunked is not None and metadata.dcp_context_row_indices is not None
if 0 in context_lens:
assert chunked.empty_token_slices
assert any(c.is_continuation for c in chunked.chunks)
else:
assert len(chunked.chunks) == 1
blocks_per_req = common.block_table_tensor.shape[1]
cache = torch.zeros(
(len(context_lens) * blocks_per_req, block_size, 576),
dtype=torch.bfloat16,
device=device,
).to(current_platform.fp8_dtype())
queries, suffixes, references = [], [], []
# All ranks reconstruct the same global cache before sharding it.
torch.manual_seed(42)
for request, (context_len, query_len) in enumerate(
zip(context_lens, query_lens)
):
latent = torch.randn(
context_len, 576, device=device, dtype=torch.bfloat16
)
quantized = (latent.float() / layer._k_scale).to(cache.dtype)
positions = torch.arange(context_len, device=device)
shard = quantized.view(torch.uint8)[
(positions // interleave) % world_size == rank
]
cache.view(len(context_lens), -1, 576).view(torch.uint8)[
request, : len(shard)
].copy_(shard)
suffix = torch.randn(
query_len, 576, device=device, dtype=torch.bfloat16
)
q = (
torch.randn(
query_len, num_heads, 192, device=device, dtype=torch.bfloat16
)
* 0.5
)
full_latent = torch.cat(
(
(quantized.float() * layer._k_scale).to(torch.bfloat16),
suffix,
)
)
kv = F.linear(full_latent[:, :512], projection.weight).view(
-1, num_heads, 256
)
k_nope, v = kv.split(128, dim=-1)
k = torch.cat(
(k_nope, full_latent[:, None, 512:].expand(-1, num_heads, -1)),
dim=-1,
)
mask = torch.arange(context_len + query_len, device=device)[
None, :
] <= (context_len + torch.arange(query_len, device=device)[:, None])
references.append(
F.scaled_dot_product_attention(
q.transpose(0, 1).float(),
k.transpose(0, 1).float(),
v.transpose(0, 1).float(),
attn_mask=mask,
scale=impl.scale,
).transpose(0, 1)
)
queries.append(q)
suffixes.append(suffix)
q, suffix = torch.cat(queries), torch.cat(suffixes)
output = torch.empty(
q.shape[0], num_heads * 128, device=device, dtype=torch.bfloat16
)
# Ensure this test cannot silently succeed through the fallback.
with pytest.MonkeyPatch.context() as patch:
def unexpected_fallback(*args, **kwargs):
raise AssertionError("Expected the compressed DCP path")
patch.setattr(
"vllm.model_executor.layers.attention.mla_attention."
"MLACommonImpl._context_parallel_compute_prefill_context",
unexpected_fallback,
)
impl.forward_mha(
q,
suffix[:, :512],
suffix[:, None, 512:],
cache,
metadata,
layer._k_scale,
output,
)
torch.testing.assert_close(
output.view(-1, num_heads, 128).float(),
torch.cat(references),
rtol=0.03,
atol=0.003,
)
finally:
cleanup_dist_env_and_memory()
@@ -1,32 +0,0 @@
# 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
@@ -1,163 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""The ROCm MXFP4 indexer reads the paged cache in place, so each prefill
chunk is split back into its requests' rows, which one launch finds through
the chunk's query_start_loc. A chunk is whole requests or one query slice of a
long request, and both have to come back with the right rows and the right
block-table rows.
"""
import pytest
import torch
from vllm.platforms import current_platform
if not current_platform.is_rocm():
pytest.skip("ROCm-only", allow_module_level=True)
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerPrefillChunkMetadata,
)
from vllm.v1.attention.backends.mla.rocm_paged_mxfp4_indexer import (
native_decode,
plan_gather_launches,
plan_prefill_chunks,
split_prefill_chunks,
)
from vllm.v1.attention.ops.rocm_paged_mxfp4_indexer import rocm_mxfp4_consumer_rows
def _chunk(block_table, token_start, token_end, row_ends):
ends = torch.tensor(row_ends, dtype=torch.int32)
return DeepseekV32IndexerPrefillChunkMetadata(
block_table=block_table,
cu_seqlen_ks=torch.full_like(ends, 7),
cu_seqlen_ke=ends + 7,
cu_seq_lens=torch.zeros(1, dtype=torch.int32),
token_to_seq=torch.zeros(1, dtype=torch.int32),
total_seq_lens=1,
max_seqlen_k=int(ends.max()),
token_start=token_start,
token_end=token_end,
num_reqs=block_table.shape[0],
)
# A decode (1 token), then prefills of 3, 3, 5 and 6 query tokens; the last
# one is sliced into two chunks.
QUERY_START_LOC = [0, 1, 4, 7, 12, 18]
SEQ_LENS = torch.tensor([40, 10, 12, 21, 64])
BLOCK_TABLE = torch.arange(20, dtype=torch.int32).view(5, 4)
CHUNKS = [
_chunk(BLOCK_TABLE[1:4], 1, 12, list(range(11))),
_chunk(BLOCK_TABLE[4:5], 12, 15, [29, 30, 30]),
_chunk(BLOCK_TABLE[4:5], 15, 18, [31, 31, 32]),
]
def _plans(min_gather_width, block=8):
return plan_prefill_chunks(
CHUNKS,
QUERY_START_LOC,
SEQ_LENS,
SEQ_LENS.int() // 2,
2,
block,
min_gather_width,
torch.tensor(QUERY_START_LOC, dtype=torch.int32),
)
def test_chunks_split_into_requests():
plans = _plans(20.0)
assert [p.requests for p in plans] == [
[(0, 3, 0), (3, 6, 1), (6, 11, 2)],
[(0, 3, 0)],
[(0, 3, 0)],
]
# every chunk launches once, with offsets local to the chunk
assert [p.query_start_loc.tolist() for p in plans] == [
[0, 3, 6, 11],
[0, 3],
[0, 3],
]
# the logits are as wide as the longest compressed context in the chunk
assert [p.width for p in plans] == [10, 32, 32]
assert [p.context_lens.tolist() for p in plans] == [[5, 6, 10], [32], [32]]
torch.testing.assert_close(plans[2].row_ends, torch.tensor([31, 31, 32]).int())
torch.testing.assert_close(plans[2].block_ends, torch.tensor([4, 4, 4]).int())
assert [p.use_gather for p in plans] == [False, True, True]
assert [p.first_request for p in plans] == [1, 4, 4]
# no candidate blocks, as in the model-neutral builder
for plan in _plans(None, block=0):
assert plan.block_ends is None and not plan.use_gather
def test_launches_follow_the_logits_budget(monkeypatch):
"""Each launch's fp32 logits fit in VLLM_SPARSE_INDEXER_MAX_LOGITS_MB. A dense
chunk's logits are [rows, longest context in the chunk]: K is read in place,
not gathered, so requests share a launch until their rows no longer fit, and
a request that does not fit alone is split on its query rows. A consumer's
logits are [rows, pool]."""
budget = 4 * 1000 * 30
contexts, queries = torch.tensor([1000, 600, 200]), torch.tensor([10, 10, 10])
assert split_prefill_chunks(contexts, queries, budget, 2) == [
(slice(2, 5), slice(0, 30))
]
# the third request would take the chunk past the budget
queries = torch.tensor([10, 10, 11])
assert split_prefill_chunks(contexts, queries, budget) == [
(slice(0, 2), slice(0, 20)),
(slice(2, 3), slice(0, 11)),
]
assert split_prefill_chunks(torch.tensor([1000]), torch.tensor([100]), budget) == [
(slice(0, 1), slice(lo, min(lo + 30, 100))) for lo in range(0, 100, 30)
]
# the default 512 MiB holds 128 rows of a 1M context, or 8192 of a 16K pool
assert split_prefill_chunks(
torch.tensor([1 << 20]), torch.tensor([200]), 512 << 20
) == [(slice(0, 1), slice(0, 128)), (slice(0, 1), slice(128, 200))]
monkeypatch.setenv("VLLM_SPARSE_INDEXER_MAX_LOGITS_MB", "512")
assert rocm_mxfp4_consumer_rows(16384) == 8192
def test_gather_launches_rejoin_a_requests_rows():
"""The consumers' logits are [rows, pool] whatever the context, so a
request's rows go back together across the chunks that cut them, and a
launch never mixes requests."""
# the first chunk is too narrow to gather, the last request's slices rejoin
(joined,) = plan_gather_launches(CHUNKS, _plans(20.0), 100)
assert (joined.token_start, joined.token_end) == (12, 18)
# every chunk gathers: the first chunk's three requests launch apart
launches = plan_gather_launches(CHUNKS, _plans(0.0), 100)
assert [(g.token_start, g.token_end) for g in launches] == [
(1, 4),
(4, 7),
(7, 12),
(12, 18),
]
assert plan_gather_launches(CHUNKS, _plans(None), 100) == []
def test_decode_launches_native_on_uniform_steps():
"""A decode step goes to the kernel as next_n-row sequences only when its
shape says so: each request has next_n rows, and cudagraph padding (query
length 0) comes only after them. A FULL graph captured on a uniform batch
then replays the same launch on a padded one."""
rows = torch.zeros(8, dtype=torch.int32)
row_block_table = torch.arange(32, dtype=torch.int32).view(8, 4)
context_lens = torch.tensor([9, 4, 7, 0, 5], dtype=torch.int32)
native = native_decode(rows, row_block_table, [2, 2, 2, 0], 2, context_lens)
assert native is not None and native.next_n == 2
assert native.context_lens.tolist() == [9, 4, 7, 0]
# every request's first flattened row, as a view
assert native.block_table.tolist() == row_block_table[::2].tolist()
assert native.block_table.data_ptr() == row_block_table.data_ptr()
assert native_decode(rows, row_block_table, [2, 0, 2, 2], 2, context_lens) is None
# a ragged step, rows padded past the requests, and no speculation
assert native_decode(rows[:5], row_block_table, [2, 1, 2], 2, context_lens) is None
assert native_decode(rows, row_block_table, [2, 2, 2], 2, context_lens) is None
assert native_decode(rows[:4], row_block_table, [1] * 4, 1, context_lens) is None
@@ -1,188 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""CPU tests for the decode top-k row->token mapping (no GPU required).
On non-uniform decode batches (``requires_padding`` -- mixed plain-decode and
spec-verify requests, or variable MTP verify lens; taken on Hopper where the
varlen/flatten logits path is unavailable), the pool-topk rows follow the
PADDED ``[batch_size, next_n]`` grid: row ``(b, t)`` is flat decode token
``offset_b + t``. The former inline ``dec_seq = positions[:n] + 1``
(``n = batch_size * next_n``) indexes the flat per-token layout with padded
coordinates, so rows after the first non-uniform request read another
request's positions and rows past the decode region read prefill tokens --
``expand_pools_and_append_tail`` then anchors the tail at a foreign length.
These tests pin the defect with the exact production arithmetic and verify
the layout-aware replacement (``_decode_topk_seq_lens``), including the tail
expansion consequences via the pure-torch expand/append pair that the fused
kernel is documented to replicate.
"""
import torch
# Bootstrap the glm5next package before importing kpool_compress directly: its
# import runs glm5next/__init__, which pulls model -> attention -> the indexer
# dispatcher (sparse_indexer) -> back into the nvidia/amd sparse_indexer
# modules. Production always enters via attention.py first.
# isort: off
import vllm.models.glm5next # noqa: F401
from vllm.models.glm5next.nvidia.ops.kpool_compress import ( # noqa: E402
append_tail_to_topk,
expand_pools_to_tokens,
)
# isort: on
from vllm.models.glm5next.common.sparse_indexer import (
_decode_topk_seq_lens,
_fill_short_decode_causal_indices,
)
from vllm.platforms import current_platform
if current_platform.is_rocm():
from vllm.models.glm5next.amd import sparse_indexer as indexer_mod
else:
from vllm.models.glm5next.nvidia import sparse_indexer as indexer_mod
KPOOL = 4
TOPK_TOKENS = 16
SELECT_K = TOPK_TOKENS // KPOOL
def test_kpool_ops_dispatch_matches_platform():
expected_backend = ".amd." if current_platform.is_rocm() else ".nvidia."
assert expected_backend in indexer_mod.kpool_ops.__name__
def test_short_decode_fills_exact_causal_rows():
topk = torch.full((3, 8), 99, dtype=torch.int32)
positions = torch.tensor([0, 3, 7], dtype=torch.int64)
assert _fill_short_decode_causal_indices(topk, positions, 3, 8, 8)
assert topk.tolist() == [
[0, -1, -1, -1, -1, -1, -1, -1],
[0, 1, 2, 3, -1, -1, -1, -1],
[0, 1, 2, 3, 4, 5, 6, 7],
]
def test_short_decode_leaves_buffer_unchanged_for_sparse_context():
topk = torch.full((2, 8), 99, dtype=torch.int32)
before = topk.clone()
assert not _fill_short_decode_causal_indices(topk, torch.tensor([7, 8]), 2, 9, 8)
assert torch.equal(topk, before)
def make_non_uniform_batch():
"""3 requests: plain decode (1 token), MTP verify (4), adaptive verify (3).
Flat decode positions (production layout: decode tokens first, then any
prefill tokens of the same batch):
req0: [30] (context len 30)
req1: [100..103] (verify at context len 100)
req2: [7, 8, 9] (verify at context len 7)
Followed by 4 prefill tokens at positions 555..558 so the flat tensor is
at least ``n = 3 * 4`` long, as it is in a real mixed batch.
"""
decode_lens = torch.tensor([1, 4, 3], dtype=torch.int64)
per_req_positions = [[30], [100, 101, 102, 103], [7, 8, 9]]
flat_decode = [p for req in per_req_positions for p in req]
positions = torch.tensor(flat_decode + [555, 556, 557, 558], dtype=torch.int64)
return decode_lens, per_req_positions, positions
def expected_row_seq_lens(per_req_positions, batch_size, next_n):
"""Ground truth: row (b, t) -> pos + 1 for real rows, 0 for pad rows."""
out = torch.zeros(batch_size * next_n, dtype=torch.int32)
for b, req in enumerate(per_req_positions):
for t, pos in enumerate(req):
out[b * next_n + t] = pos + 1
return out
def test_legacy_flat_layout_misaligns_and_bleeds():
"""The bug: ``positions[:n] + 1`` with padded-row coordinates reads other
requests' positions and prefill positions."""
decode_lens, per_req, positions = make_non_uniform_batch()
batch_size = decode_lens.shape[0]
next_n = int(decode_lens.max())
n = batch_size * next_n
assert n == 12
legacy = positions[:n].to(torch.int32) + 1
expected = expected_row_seq_lens(per_req, batch_size, next_n)
# Row (1, 0): req1's first verify token (pos 100, seq 101) reads flat
# index 4 -> req1's LAST verify token (pos 103). Its true tail token is
# dropped and the tail anchors 3 tokens late.
assert int(legacy[4]) == 104 and int(expected[4]) == 101
# Rows (2, *): req2 starts at flat offset 5, but padded coordinates point
# at flat indices 8..11 -- the batch's PREFILL positions.
for t in range(3):
assert int(legacy[2 * next_n + t]) >= 556, (
"legacy row (2, t) should read prefill positions"
)
assert not torch.equal(legacy, expected)
def test_helper_uniform_layout_matches_flat_slice():
"""Uniform batches keep the flat shortcut (zero behavior/perf change)."""
per_req = [[200, 201, 202, 203], [50, 51, 52, 53]]
positions = torch.tensor([p for r in per_req for p in r], dtype=torch.int64)
decode_lens = torch.tensor([4, 4], dtype=torch.int64)
out = _decode_topk_seq_lens(positions, decode_lens, 8, 2, 4, requires_padding=False)
assert torch.equal(out, positions[:8].to(torch.int32) + 1)
def test_helper_padded_layout_per_row():
"""Non-uniform batches map every padded row to its own token's position;
pad rows get 0 (empty tail)."""
decode_lens, per_req, positions = make_non_uniform_batch()
out = _decode_topk_seq_lens(positions, decode_lens, 8, 3, 4, requires_padding=True)
expected = expected_row_seq_lens(per_req, 3, 4)
assert torch.equal(out, expected)
# Pad rows (0, 1..3) and (2, 3) collapse to 0 -> no tail appended.
assert out[1] == 0 and out[2] == 0 and out[3] == 0 and out[11] == 0
def expand_tail_region(dec_seq):
"""Run the production pure-torch expand + append pair (the fused kernel
replicates it exactly on the identity path) and return the tail columns
[TOPK_TOKENS, TOPK_TOKENS + KPOOL - 1)."""
rows = dec_seq.shape[0]
pool_ids = torch.arange(SELECT_K, dtype=torch.int64).expand(rows, SELECT_K)
valid = torch.ones_like(pool_ids, dtype=torch.bool)
expanded = expand_pools_to_tokens(pool_ids, valid, TOPK_TOKENS, KPOOL)
seq_lens = dec_seq.to(torch.int32)
pool_lens = (seq_lens // KPOOL).to(torch.int32)
out = append_tail_to_topk(expanded, seq_lens, pool_lens, KPOOL)
return out[:, TOPK_TOKENS:]
def test_tail_expansion_legacy_vs_fixed():
"""End-to-end tail consequence: the fixed mapping appends exactly the
request's trailing incomplete pool; the legacy flat slice drops real tail
tokens and emits indices far past the request's own sequence."""
decode_lens, per_req, positions = make_non_uniform_batch()
n = 12
fixed = _decode_topk_seq_lens(
positions, decode_lens, 8, 3, 4, requires_padding=True
)
legacy = positions[:n].to(torch.int32) + 1
fixed_tail = expand_tail_region(fixed)
legacy_tail = expand_tail_region(legacy)
# Fixed: row (1, 0) (seq 101) keeps its single tail token 100; row (2, 2)
# (seq 10) keeps its full trailing pool [8, 9].
assert fixed_tail[4, 0].item() == 100
assert fixed_tail[10, :2].tolist() == [8, 9]
# Legacy: row (1, 0) loses its tail token (anchored at 104, count 0)...
assert legacy_tail[4, 0].item() == -1
# ...and row (2, 2) reads prefill position 557 -> tail indices 556/557,
# way past req2's 10-token sequence -> out-of-bounds block-table reads.
assert legacy_tail[10, :2].tolist() == [556, 557]
assert not torch.equal(legacy_tail, fixed_tail)
File diff suppressed because it is too large Load Diff
@@ -1,127 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Sparse MLA allocation and warmup must agree on physical addressing."""
from types import MethodType, SimpleNamespace
from unittest.mock import MagicMock
import pytest
import torch
from vllm.config import CacheConfig
from vllm.model_executor.layers.attention.mla_attention import MLAAttention
from vllm.model_executor.models.deepseek_v2 import DeepseekV32IndexerCache
from vllm.platforms import current_platform
from vllm.v1.attention.backend import MultipleOf
from vllm.v1.attention.backends.mla.indexer import DeepseekV32IndexerBackend
from vllm.v1.attention.backends.mla.sparse_utils import (
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL,
flat_kv_row_view,
)
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.attention.backends.utils import get_supported_kv_cache_layouts
from vllm.v1.core.kv_cache_planning import get_kv_cache_config_from_groups
from vllm.v1.kv_cache_interface import KVCacheGroupSpec, UniformTypeKVCacheSpecs
from vllm.v1.kv_cache_layout import KVCacheLayout
from vllm.v1.worker.utils import allocate_kv_cache, customize_attention_spec
pytestmark = pytest.mark.skip_global_cleanup
@pytest.mark.parametrize(
"device",
[
"cpu",
pytest.param(
"cuda",
marks=pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUDA only"
),
),
],
)
@pytest.mark.parametrize(
"layout", [KVCacheLayout.BLHNC, KVCacheLayout.BLNHC, KVCacheLayout.LBNHC]
)
@pytest.mark.parametrize(
"backend,cache_dtype,sm100,stride_alignment",
[
(AttentionBackendEnum.FLASHINFER_MLA_SPARSE, "auto", True, 32 * 1152),
(AttentionBackendEnum.FLASHINFER_MLA_SPARSE, "fp8", True, 32 * 576),
pytest.param(
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE_FA4,
"auto",
True,
64 * 1152,
marks=pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUDA only"
),
),
(AttentionBackendEnum.FLASHMLA_SPARSE, "auto", True, 1152),
(AttentionBackendEnum.FLASHMLA_SPARSE, "fp8_ds_mla", False, MultipleOf(64)),
(AttentionBackendEnum.FLASHMLA_SPARSE, "fp8_ds_mla", True, 656),
(AttentionBackendEnum.FLASHMLA_SPARSE, "nvfp4_ds_mla", True, 352),
],
)
def test_allocation_and_warmup_follow_addressing_mode(
monkeypatch, layout, backend, cache_dtype, sm100, stride_alignment, device
):
backend = backend.get_class()
monkeypatch.setattr(
current_platform, "is_device_capability_family", lambda family: sm100
)
config = SimpleNamespace(
cache_config=CacheConfig(block_size=64),
model_config=SimpleNamespace(dtype=torch.bfloat16),
attention_config=SimpleNamespace(hisparse_config=None),
kernel_config=SimpleNamespace(enable_jit_warmup=True),
)
config.cache_config.kv_cache_layout = layout.name
layer = SimpleNamespace(
_vllm_config=config,
attn_backend=backend,
kv_cache_dtype=cache_dtype,
head_size=576,
sliding_window=None,
indexer=None,
non_causal_multi_token_decode=False,
)
layer._uses_flat_kv_cache = MethodType(MLAAttention._uses_flat_kv_cache, layer)
spec = customize_attention_spec(
backend, MLAAttention.get_kv_cache_spec(layer, config)
)
indexer = SimpleNamespace(
cache_config=config.cache_config, head_dim=132, dtype=torch.uint8
)
index_spec = DeepseekV32IndexerCache.get_kv_cache_spec(indexer, config)
assert spec.block_stride_alignment == stride_alignment
assert index_spec.block_stride_alignment is None
assert layout in get_supported_kv_cache_layouts(
[backend, DeepseekV32IndexerBackend]
)
specs = {"mla": spec, "indexer": index_spec}
group = KVCacheGroupSpec(
list(specs), UniformTypeKVCacheSpecs(block_size=64, kv_cache_specs=specs)
)
cache = get_kv_cache_config_from_groups(config, [group], 2**20)
views = allocate_kv_cache(cache, torch.device(device), layout)
register = MagicMock()
monkeypatch.setattr(
_CONVERT_REQ_INDEX_TO_GLOBAL_INDEX_KERNEL, "register_warmup", register
)
MLAAttention.bind_kv_cache(layer, views["mla"])
DeepseekV32IndexerCache.bind_kv_cache(indexer, views["indexer"])
assert indexer.kv_cache.stride(0) == views["indexer"].stride(0)
alignment = spec.get_block_stride_alignment()
assert views["mla"].stride(0) * views["mla"].element_size() % alignment == 0
if not layer._uses_flat_kv_cache():
register.assert_not_called()
else:
rows, stride = flat_kv_row_view(layer.kv_cache, 64)
register.assert_called_once_with(config, block_stride_rows=stride)
layer.kv_cache[1, 0].fill_(3)
torch.testing.assert_close(rows[stride], layer.kv_cache[1, 0])
if alignment == 1:
assert cache.kv_cache_tensors[0].size == cache.num_blocks * sum(
item.page_size_bytes for item in specs.values()
)
@@ -1,51 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import pytest
import torch
pytest.importorskip("cutlass")
from vllm.model_executor.layers.attention.sparse_mla_attention import (
_build_topk_mask,
_topk_mask_shape,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_build_topk_mask_single_request_matches_generic_path() -> None:
topk = torch.tensor(
[[0, 31, 32, 63, -1], [1, 64, 127, -1, -1]],
dtype=torch.int32,
device="cuda",
)
num_words = (128 + 31) // 32
single_out = torch.zeros(1, 2, num_words, dtype=torch.int32, device="cuda")
generic_out = torch.zeros(2, 1, num_words, dtype=torch.int32, device="cuda")
single_req = _build_topk_mask([topk], [2], 2, 128, single_out)
generic = _build_topk_mask([topk[:1], topk[1:]], [1, 1], 1, 128, generic_out)
torch.testing.assert_close(single_req[0, 0], generic[0, 0])
torch.testing.assert_close(single_req[0, 1], generic[1, 0])
def test_topk_mask_rows_are_aligned_for_vectorized_loads() -> None:
assert _topk_mask_shape(2, 129, 129) == (2, 256, 8)
assert _topk_mask_shape(2, 129, 129, reserve_key_starts_word=True) == (
2,
256,
8,
)
@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA")
def test_build_topk_mask_preserves_aligned_row_storage() -> None:
shape = _topk_mask_shape(1, 1, 129)
out = torch.zeros(shape, dtype=torch.int32, device="cuda")
topk = torch.tensor([[0, 128]], dtype=torch.int32, device="cuda")
mask = _build_topk_mask([topk], [1], 1, 129, out)
assert mask.shape == (1, 1, 8)
assert mask[0, 0].tolist() == [1, 0, 0, 0, 1, 0, 0, 0]
@@ -1,563 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Integration tests for TRTLLM gen-full attention through FlashInfer."""
import dataclasses
import unittest.mock
from functools import partial
import pytest
import torch
from torch.nn.attention.flex_attention import create_block_mask, flex_attention
from tests.kernels.attention.test_trtllm_kvfp8_dequant import make_random_kv_cache
from tests.v1.attention.test_attention_backends import create_and_prepopulate_kv_cache
from tests.v1.attention.utils import (
BatchSpec,
create_common_attn_metadata,
create_vllm_config,
)
from vllm.config import set_current_vllm_config
from vllm.platforms import current_platform
from vllm.utils.torch_utils import (
is_strictly_contiguous,
nvfp4_kv_cache_full_dim,
set_random_seed,
)
from vllm.v1.attention.backends.utils import PerLayerParameters
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVCacheLayout, KVQuantMode
if not current_platform.is_device_capability_family(100):
pytest.skip(
"TRTLLM integration tests require NVIDIA Blackwell (SM100).",
allow_module_level=True,
)
from vllm.v1.attention.backends.flashinfer import ( # noqa: E402
FlashInferDecodeKernel,
FlashInferImpl,
FlashInferMetadataBuilder,
FlashInferTrtllmAPIDecode,
TRTLLMPrefill,
trtllm_prefill_attn_kvfp8_dequant,
)
class MockAttentionLayer:
"""Minimal mock of an attention layer for testing."""
def __init__(self, device: torch.device):
self._q_scale = torch.tensor(2.0, device=device)
self._k_scale = torch.tensor(3.0, device=device)
self._v_scale = torch.tensor(4.0, device=device)
self._q_scale_float = 2.0
self._k_scale_float = 3.0
self._v_scale_float = 4.0
self._o_scale_float = None
MODEL = "Qwen/Qwen2.5-0.5B"
MODEL_NVFP4 = "Qwen/Qwen3-4B" # nvfp4 needs head_dim >= 128 (or 80)
BLOCK_SIZE = 16
NUM_GPU_BLOCKS = 8192
DEVICE_TYPE = current_platform.device_type
BATCH_SPECS = {
"decode_only": BatchSpec(
seq_lens=[128, 256, 512],
query_lens=[1, 1, 1],
),
"prefill_only": BatchSpec(
seq_lens=[64, 128, 256],
query_lens=[16, 32, 16],
),
"mixed": BatchSpec(
seq_lens=[128, 256, 512, 128],
query_lens=[1, 1, 8, 16],
),
}
def _mock_get_per_layer_parameters(vllm_config, layer_names, impl_cls):
head_size = vllm_config.model_config.get_head_size()
return {
name: PerLayerParameters(
window_left=-1,
logits_soft_cap=0.0,
sm_scale=1.0 / (head_size**0.5),
)
for name in layer_names
}
@pytest.mark.parametrize(
"block_size,num_prefills,has_host_lengths,quantize_query",
[
(16, 1, True, False),
(64, 2, True, False),
(128, 2, True, False),
(16, 2, False, False),
(16, 2, True, True),
],
)
@torch.inference_mode()
def test_prefill_dequant_scratch_ignores_unused_capacity(
block_size, num_prefills, has_host_lengths, quantize_query, monkeypatch
):
"""Bound scratch by attended prefill KV, including cached prefixes."""
device = torch.device("cuda")
config = create_vllm_config(model_name=MODEL, max_model_len=32768)
config.cache_config.cache_dtype = "fp8"
config.cache_config.kv_cache_layout = "LBHNC"
config.attention_config.use_trtllm_attention = True
config.attention_config.disable_flashinfer_q_quantization = not quantize_query
monkeypatch.setattr(
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
_mock_get_per_layer_parameters,
)
spec = FullAttentionSpec(
block_size=block_size,
num_kv_heads=2,
head_size=64,
dtype=torch.uint8,
kv_quant_mode=KVQuantMode.FP8_PER_TENSOR,
)
kv_cache, scale = make_random_kv_cache(32, 2, block_size, 64)
batch = BatchSpec(
seq_lens=[1024] + [17, 65][-num_prefills:],
query_lens=[1] + [2, 8][-num_prefills:],
)
common = create_common_attn_metadata(batch, block_size, device)
if not has_host_lengths:
common.seq_lens_cpu_upper_bound = None
live_pages = ((65 if has_host_lengths else 1024) + block_size - 1) // block_size
with set_current_vllm_config(config):
builder = FlashInferMetadataBuilder(spec, ["layer.0"], config, device)
for capacity in (64, 256):
# Unused columns can contain nonzero page IDs.
common.block_table_tensor = torch.randint(
1, 32, (batch.batch_size, capacity), dtype=torch.int32, device=device
)
metadata = builder.build(0, common)
assert isinstance(metadata.prefill, TRTLLMPrefill)
table = metadata.prefill.block_tables
assert is_strictly_contiguous(table)
assert (metadata.q_data_type_prefill == current_platform.fp8_dtype()) == (
quantize_query
)
if not quantize_query:
converted, _ = trtllm_prefill_attn_kvfp8_dequant(
kv_cache, table, scale, scale, metadata.q_data_type_prefill
)
assert converted.shape[0] == num_prefills * live_pages + 1
width = capacity if quantize_query else live_pages
torch.testing.assert_close(table, common.block_table_tensor[1:, :width])
def _create_nvfp4_hnd_kv_cache(
k_contexts,
v_contexts,
block_size,
num_kv_heads,
head_size,
dtype,
device,
num_blocks,
common_attn_metadata,
kv_scale_val,
):
"""Create an nvfp4 KV cache by quantizing bf16 context via
reshape_and_cache_flash, using the same block-table layout as
create_and_prepopulate_kv_cache.
The returned tensor is dtype ``uint8`` with head-group layout
``(num_blocks, 2 * num_kv_heads, block_size, full_dim)``
where K heads occupy the first ``num_kv_heads`` heads and V heads the second.
Each ``full_dim = head_size // 2 + head_size // 16`` block packs two regions:
- **FP4 data** (``head_size // 2`` bytes): pairs of E2M1 values,
two per byte.
- **FP8 block scales** (``head_size // 16`` bytes): one E4M3
scale per 16-element block.
Args:
k_contexts: List of key context tensors, one per sequence.
v_contexts: List of value context tensors, one per sequence.
block_size: Number of tokens per cache block.
num_kv_heads: Number of key/value heads.
head_size: Head dimension (must be divisible by 16).
dtype: Source data type for the bf16 intermediate cache.
device: Target device.
num_blocks: Total number of blocks to allocate.
common_attn_metadata: Metadata containing block tables and
sequence lengths.
kv_scale_val: Scalar float used as both k_scale and v_scale
during quantization.
Returns:
``torch.Tensor``: The nvfp4 kv_cache tensor (uint8, LBHNC-strided).
"""
# First create a bf16 cache so block tables are populated.
bf16_cache = create_and_prepopulate_kv_cache(
k_contexts,
v_contexts,
block_size,
num_kv_heads,
head_size,
dtype,
device,
num_blocks,
common_attn_metadata,
layout=KVCacheLayout.LBHNC,
)
# (num_blocks, 2 * num_kv_heads, block_size, full_dim) — K heads first, then V heads
full_dim = nvfp4_kv_cache_full_dim(head_size)
nvfp4_cache = torch.zeros(
(num_blocks, 2 * num_kv_heads, block_size, full_dim),
dtype=torch.uint8,
device=device,
)
k_cache, v_cache = nvfp4_cache.split(num_kv_heads, dim=1)
# Flatten bf16 context into tokens and quantize via reshape_and_cache_flash.
# bf16_cache is (B, H, N, 2*hs); split K/V on the content dim.
block_table = common_attn_metadata.block_table_tensor
seq_lens = common_attn_metadata.seq_lens.cpu()
query_lens = (
common_attn_metadata.query_start_loc_cpu[1:]
- common_attn_metadata.query_start_loc_cpu[:-1]
)
kv_scale_t = torch.tensor(kv_scale_val, dtype=torch.float32, device=device)
for i in range(len(k_contexts)):
ctx_len = int(seq_lens[i]) - int(query_lens[i])
if ctx_len == 0:
continue
# Gather context tokens from the bf16 cache using block table.
n_ctx_blocks = (ctx_len + block_size - 1) // block_size
blocks = block_table[i, :n_ctx_blocks]
k_ctx = (
bf16_cache[blocks, :, :, :head_size]
.transpose(1, 2)
.reshape(-1, num_kv_heads, head_size)[:ctx_len]
)
v_ctx = (
bf16_cache[blocks, :, :, head_size:]
.transpose(1, 2)
.reshape(-1, num_kv_heads, head_size)[:ctx_len]
)
# Build slot mapping for these context tokens.
token_offsets = torch.arange(ctx_len, device=device)
block_indices = token_offsets // block_size
intra_offsets = token_offsets % block_size
slots = block_table[i, block_indices] * block_size + intra_offsets
# reshape_and_cache_flash expects (B, N, H, D) cache views.
torch.ops._C_cache_ops.reshape_and_cache_flash(
k_ctx,
v_ctx,
k_cache.transpose(1, 2),
v_cache.transpose(1, 2),
slots,
"nvfp4",
kv_scale_t,
kv_scale_t,
)
return nvfp4_cache
def _run_trtllm_integration(batch_spec, kv_cache_dtype="auto", model_name=MODEL):
"""Run TRTLLM attention through the full FlashInfer pipeline
and compare against an SDPA reference."""
set_random_seed(42)
device = torch.device(f"{DEVICE_TYPE}:0")
vllm_config = create_vllm_config(
model_name=model_name,
max_model_len=max(batch_spec.seq_lens),
block_size=BLOCK_SIZE,
num_gpu_blocks=NUM_GPU_BLOCKS,
)
vllm_config.attention_config.use_trtllm_attention = True
vllm_config.cache_config.cache_dtype = kv_cache_dtype
num_q_heads = vllm_config.model_config.get_num_attention_heads(
vllm_config.parallel_config
)
num_kv_heads = vllm_config.model_config.get_num_kv_heads(
vllm_config.parallel_config
)
head_size = vllm_config.model_config.get_head_size()
dtype = vllm_config.model_config.dtype
scale = 1.0 / (head_size**0.5)
# 1. Generate data and compute SDPA reference
all_q, all_k, all_v = [], [], []
all_sdpa_out = []
k_contexts, v_contexts = [], []
for i in range(batch_spec.batch_size):
s_len = batch_spec.seq_lens[i]
q_len = batch_spec.query_lens[i]
ctx_len = s_len - q_len
q = torch.randn(q_len, num_q_heads, head_size, dtype=dtype, device=device)
k_full = torch.randn(s_len, num_kv_heads, head_size, dtype=dtype, device=device)
v_full = torch.randn(s_len, num_kv_heads, head_size, dtype=dtype, device=device)
# SDPA reference (N=1, H, L, D)
q_sdpa = q.unsqueeze(0).transpose(1, 2)
k_sdpa = k_full.unsqueeze(0).transpose(1, 2)
v_sdpa = v_full.unsqueeze(0).transpose(1, 2)
if num_q_heads != num_kv_heads:
repeats = num_q_heads // num_kv_heads
k_sdpa = k_sdpa.repeat_interleave(repeats, dim=1)
v_sdpa = v_sdpa.repeat_interleave(repeats, dim=1)
def causal_mask_mod(b, h, q_idx, kv_idx, *, context_len):
return (q_idx + context_len) >= kv_idx
mask_fn = partial(causal_mask_mod, context_len=ctx_len)
block_mask = create_block_mask(
mask_fn, B=None, H=None, Q_LEN=q_len, KV_LEN=s_len, device=device
)
sdpa_out = flex_attention(
q_sdpa,
k_sdpa,
v_sdpa,
block_mask=block_mask,
scale=scale,
enable_gqa=True,
)
all_sdpa_out.append(sdpa_out.transpose(1, 2).squeeze(0))
all_q.append(q)
all_k.append(k_full[ctx_len:])
all_v.append(v_full[ctx_len:])
k_contexts.append(k_full[:ctx_len])
v_contexts.append(v_full[:ctx_len])
query_vllm = torch.cat(all_q, dim=0)
key_vllm = torch.cat(all_k, dim=0)
value_vllm = torch.cat(all_v, dim=0)
sdpa_output = torch.cat(all_sdpa_out, dim=0)
common_attn_metadata = create_common_attn_metadata(batch_spec, BLOCK_SIZE, device)
# 2. Create HND KV cache
is_nvfp4 = kv_cache_dtype == "nvfp4"
if is_nvfp4:
# Compute a global scale from the context data.
all_ctx = torch.cat(k_contexts + v_contexts, dim=0)
kv_scale_val = (all_ctx.abs().amax() / 448.0).item()
kv_cache = _create_nvfp4_hnd_kv_cache(
k_contexts,
v_contexts,
BLOCK_SIZE,
num_kv_heads,
head_size,
dtype,
device,
NUM_GPU_BLOCKS,
common_attn_metadata,
kv_scale_val,
)
else:
kv_scale_val = 1.0
kv_cache = create_and_prepopulate_kv_cache(
k_contexts,
v_contexts,
BLOCK_SIZE,
num_kv_heads,
head_size,
dtype,
device,
NUM_GPU_BLOCKS,
common_attn_metadata,
layout=KVCacheLayout.LBHNC,
)
# 3. Run through FlashInfer with TRTLLM enabled
vllm_config.cache_config.kv_cache_layout = "LBHNC"
is_nvfp4 = kv_cache_dtype == "nvfp4"
kv_quant_mode = KVQuantMode.NVFP4 if is_nvfp4 else KVQuantMode.NONE
spec_dtype = torch.uint8 if is_nvfp4 else dtype
kv_cache_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=num_kv_heads,
head_size=head_size,
dtype=spec_dtype,
kv_quant_mode=kv_quant_mode,
)
layer_names = ["test_layer_0"]
with (
set_current_vllm_config(vllm_config),
unittest.mock.patch(
"vllm.utils.flashinfer.supports_trtllm_attention",
return_value=True,
),
unittest.mock.patch(
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
_mock_get_per_layer_parameters,
),
):
builder = FlashInferMetadataBuilder(
kv_cache_spec, layer_names, vllm_config, device
)
attn_metadata = builder.build(
common_prefix_len=0,
common_attn_metadata=common_attn_metadata,
)
# Verify the correct TRTLLM metadata types were produced.
has_prefills = any(ql > 1 for ql in batch_spec.query_lens)
has_decodes = any(ql == 1 for ql in batch_spec.query_lens)
if has_prefills:
assert isinstance(attn_metadata.prefill, TRTLLMPrefill), (
f"Expected TRTLLMPrefill, got {type(attn_metadata.prefill)}"
)
if has_decodes:
assert isinstance(attn_metadata.decode, FlashInferTrtllmAPIDecode), (
f"Expected FlashInferTrtllmAPIDecode, got {type(attn_metadata.decode)}"
)
assert attn_metadata.decode.kernel == FlashInferDecodeKernel.TRTLLM_GEN
impl = FlashInferImpl(
num_heads=num_q_heads,
head_size=head_size,
scale=scale,
num_kv_heads=num_kv_heads,
alibi_slopes=None,
sliding_window=None,
kv_cache_dtype=kv_cache_dtype,
)
mock_layer = MockAttentionLayer(device)
if is_nvfp4:
# For nvfp4, k_scale/v_scale are the global quantization
# scales (amax/448) used by reshape_and_cache_flash.
kv_scale_t = torch.tensor(kv_scale_val, dtype=torch.float32, device=device)
mock_layer._k_scale = kv_scale_t
mock_layer._v_scale = kv_scale_t
mock_layer._k_scale_float = kv_scale_val
mock_layer._v_scale_float = kv_scale_val
output = torch.empty_like(query_vllm)
impl.do_kv_cache_update(
mock_layer,
key_vllm,
value_vllm,
kv_cache,
attn_metadata.slot_mapping,
)
# nvfp4 trtllm kernel requires FP8 queries. In the real
# pipeline the attention layer handles this; here we
# quantize manually.
if is_nvfp4:
finfo = torch.finfo(torch.float8_e4m3fn)
q_amax = query_vllm.abs().amax().clamp(min=1e-12)
q_s = (finfo.max / q_amax * 0.1).item()
query_vllm = (
(query_vllm * q_s).clamp(finfo.min, finfo.max).to(torch.float8_e4m3fn)
)
mock_layer._q_scale = torch.tensor(
1.0 / q_s, dtype=torch.float32, device=device
)
mock_layer._q_scale_float = 1.0 / q_s
output = impl.forward(
mock_layer,
query_vllm,
key_vllm,
value_vllm,
kv_cache,
attn_metadata,
output=output,
)
# 4. Compare against SDPA reference
if is_nvfp4:
atol, rtol = 1.0, 1.0 # nvfp4 has higher quantization error
else:
atol, rtol = 1e-2, 1e-2
torch.testing.assert_close(output, sdpa_output, atol=atol, rtol=rtol)
@pytest.mark.parametrize(
"batch_spec_name",
list(BATCH_SPECS.keys()),
)
@torch.inference_mode()
def test_trtllm_gen_full_attention_integration(batch_spec_name: str):
"""Test TRTLLM gen-full attention through the full FlashInfer
MetadataBuilder.build() -> FlashInferImpl.forward() pipeline,
with real TRTLLM kernels on Blackwell."""
_run_trtllm_integration(BATCH_SPECS[batch_spec_name])
@pytest.mark.parametrize(
"batch_spec_name",
list(BATCH_SPECS.keys()),
)
@torch.inference_mode()
def test_trtllm_gen_nvfp4_kv_integration(batch_spec_name: str):
"""Test TRTLLM attention with nvfp4 KV cache through the full
FlashInfer MetadataBuilder.build() -> FlashInferImpl.forward() pipeline."""
_run_trtllm_integration(
BATCH_SPECS[batch_spec_name],
kv_cache_dtype="nvfp4",
model_name=MODEL_NVFP4,
)
@torch.inference_mode()
def test_trtllm_gen_draft_decode_metadata_tracks_in_place_seq_lens(
monkeypatch: pytest.MonkeyPatch,
):
"""Fused draft steps reuse the step-1 build after advancing seq_lens in
place, so its decode metadata must match the split path's step-2 rebuild."""
monkeypatch.setattr(
"vllm.utils.flashinfer.supports_trtllm_attention",
unittest.mock.Mock(return_value=True),
)
monkeypatch.setattr(
"vllm.v1.attention.backends.flashinfer.get_per_layer_parameters",
_mock_get_per_layer_parameters,
)
vllm_config = create_vllm_config(
model_name=MODEL, block_size=BLOCK_SIZE, num_gpu_blocks=NUM_GPU_BLOCKS
)
model_config = vllm_config.model_config
kv_cache_spec = FullAttentionSpec(
block_size=BLOCK_SIZE,
num_kv_heads=model_config.get_num_kv_heads(vllm_config.parallel_config),
head_size=model_config.get_head_size(),
dtype=model_config.dtype,
)
device = torch.device(f"{DEVICE_TYPE}:0")
with set_current_vllm_config(vllm_config):
builder = FlashInferMetadataBuilder(
kv_cache_spec, ["test_layer_0"], vllm_config, device
)
assert builder.supports_draft_decode_metadata_update
step1 = create_common_attn_metadata(BATCH_SPECS["decode_only"], BLOCK_SIZE, device)
reused = builder.build(common_prefix_len=0, common_attn_metadata=step1)
step1.seq_lens.add_(1)
step2 = dataclasses.replace(step1, seq_lens_cpu_upper_bound=step1.seq_lens.cpu())
rebuilt = builder.build(common_prefix_len=0, common_attn_metadata=step2)
assert isinstance(reused.decode, FlashInferTrtllmAPIDecode)
for field in dataclasses.fields(reused.decode):
value = getattr(reused.decode, field.name)
expected = getattr(rebuilt.decode, field.name)
if isinstance(value, torch.Tensor):
assert torch.equal(value, expected), field.name
else:
assert value == expected, field.name