[Mini-vLLM] Cut dead subsystems: models, entrypoints, backends, utils, tests

- Drop dead model modules, keeping files live imports require
- Remove anthropic, cohere, codegen entrypoints and batch STT modes
- Delete unused attention backends, MoE experts, and NPU/XPU util leaves
- Strip dead third_party trees and ROCm leaves with no CUDA path
- Remove mooncake EC connectors: dependency missing since branch base
- Re-audit verified by full import sweep and Qwen3.5 smoke test

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 00:20:48 +07:00
co-authored by Hinata
parent 6a95f62e2f
commit 81074e94a3
940 changed files with 11 additions and 380533 deletions
@@ -1,205 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from dataclasses import dataclass
import numpy as np
import pytest
import torch
from tests.v1.attention.utils import BatchSpec, create_common_attn_metadata
from vllm.platforms import current_platform
from vllm.v1.attention.backends.utils import make_local_attention_virtual_batches
@dataclass
class LocalAttentionTestData:
# Input parameters
batch_spec: BatchSpec
attn_chunk_size: int
block_size: int
# Expected return values
expected_q_seqlens: list[int]
expected_k_seqlens: list[int]
expected_local_block_table: list[list[int]]
DEVICE_TYPE = current_platform.device_type
test_data_list = [
# Same as example in docstring of make_local_attention_virtual_batches
# except block table has 9 columns instead of 10
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[4, 10, 5],
seq_lens=[6, 17, 9],
),
attn_chunk_size=4,
block_size=2,
expected_q_seqlens=[2, 2, 1, 4, 4, 1, 4, 1],
expected_k_seqlens=[4, 2, 4, 4, 4, 1, 4, 1],
# 2 pages per local branch
# (chunk size 4 // block size 2)
expected_local_block_table=[
[0, 1], # local-batch 0, (batch 0, starting from k[0])
[2, 3], # local-batch 1, (batch 0, starting from k[4])
[11, 12], # local-batch 2, (batch 1, starting from k[4])
[13, 14], # local-batch 3, (batch 1, starting from k[8])
[15, 16], # local-batch 4, (batch 1, starting from k[12])
[17, 17], # local-batch 5, (batch 1, starting from k[16])
[20, 21], # local-batch 6, (batch 2, starting from k[4])
[22, 23], # local-batch 7, (batch 2, starting from k[8])
],
),
# Case where block indices are not clipped to block table ncols-1
# because tokens_in_last_block == attn_chunk_size
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[8],
seq_lens=[12],
),
attn_chunk_size=4,
block_size=2,
expected_q_seqlens=[4, 4],
expected_k_seqlens=[4, 4],
expected_local_block_table=[
[2, 3],
[4, 5],
],
),
# Case where all kv_seq positions are involved in attn
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[7],
# 10 - 7 = 3 previously computed tokens
seq_lens=[10],
),
attn_chunk_size=4,
block_size=2,
expected_q_seqlens=[1, 4, 2],
expected_k_seqlens=[4, 4, 2],
expected_local_block_table=[
[0, 1],
[2, 3],
[4, 4],
],
),
# Case where attn_chunk_size > kv_seq_len
# so no extra mini virtual batches are created
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[4],
seq_lens=[6],
),
# Larger than kv_seq_len
attn_chunk_size=10,
block_size=2,
# No change to q_seqlens and k_seqlens
expected_q_seqlens=[4],
expected_k_seqlens=[6],
# In this case, we only need a block-table like:
# block_table = [ [0, 1, 2] ] # 1 batch, 3 pages
# But we need to pad it to 5 pages per local batch
# because currently the pages_per_local_batch
# is calculated as (attn_chunk_size // block_size)
expected_local_block_table=[
[0, 1, 2, 2, 2],
],
),
# Block size equal to chunk size
# Expect single page per batch in local batch table
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[6, 6],
seq_lens=[8, 8],
),
attn_chunk_size=4,
block_size=4,
expected_q_seqlens=[2, 4, 2, 4],
expected_k_seqlens=[4, 4, 4, 4],
# Initial block table = [
# [0, 1], < batch 0
# [2, 3], < batch 1
# ]
expected_local_block_table=[
[0], # local-batch 0, (batch 0, starting from k[0])
[1], # local-batch 1, (batch 0, starting from k[4])
[2], # local-batch 1, (batch 0, starting from k[0])
[3], # local-batch 1, (batch 0, starting from k[4])
],
),
# Case where query falls in the second attention chunk
# k_toks > 0 1 2 3 4
# q_toks v _____________
# 0 | 1
# 1 | 1 1
# 2 | 1 1 1
# 3 | 1 1 1 1
# 4 | 1
# where tokens 0,1,2,3 have been pre-computed
LocalAttentionTestData(
batch_spec=BatchSpec(
query_lens=[1],
seq_lens=[5],
),
attn_chunk_size=4,
block_size=2,
expected_q_seqlens=[1],
expected_k_seqlens=[1],
expected_local_block_table=[
[2, 2],
],
),
]
@pytest.mark.parametrize("test_data", test_data_list)
def test_local_attention_virtual_batches(test_data: LocalAttentionTestData):
device = torch.device(f"{DEVICE_TYPE}:0")
batch_spec = test_data.batch_spec
attn_chunk_size = test_data.attn_chunk_size
block_size = test_data.block_size
expected_q_seqlens = test_data.expected_q_seqlens
expected_k_seqlens = test_data.expected_k_seqlens
expected_local_block_table = test_data.expected_local_block_table
# Create common attention metadata
common_attn_metadata = create_common_attn_metadata(
batch_spec,
block_size,
device,
# Use torch.arange instead of torch.randint so we can assert on
# block table tensor values. The block table will have shape
# (num_batches, cdiv(max_seq_len, block_size)) and the values will be
# arranged from 0 to cdiv(max_seq_len, block_size)-1
arange_block_indices=True,
)
# Call the function
result, _ = make_local_attention_virtual_batches(
attn_chunk_size, common_attn_metadata, block_size
)
# Convert to numpy for easier comparison
actual_q_seqlens = np.diff(result.query_start_loc_cpu.numpy())
assert result.seq_lens_cpu_upper_bound is not None
actual_k_seqlens = result.seq_lens_cpu_upper_bound.numpy()
# Check that all query lengths are less than or equal to attn_chunk_size
assert all(q_len <= attn_chunk_size for q_len in actual_q_seqlens)
# Check that all key lengths are less than or equal to attn_chunk_size
assert all(k_len <= attn_chunk_size for k_len in actual_k_seqlens)
# Check that the total number of query tokens is preserved
assert sum(actual_q_seqlens) == sum(batch_spec.query_lens)
# Verify results
np.testing.assert_array_equal(actual_q_seqlens, expected_q_seqlens)
np.testing.assert_array_equal(actual_k_seqlens, expected_k_seqlens)
expected_block_table_tensor = torch.tensor(
expected_local_block_table, dtype=torch.int32, device=device
)
print(f"Expected block table:\n{expected_block_table_tensor}")
print(f"Actual block table:\n{result.block_table_tensor}")
torch.testing.assert_close(result.block_table_tensor, expected_block_table_tensor)
@@ -1,146 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Tests for CUDA attention backend selection and probe error handling.
Environment-shaped probe failures (missing packages, unreadable caches,
broken driver installs) must mark the backend unavailable rather than
terminating engine init; programming errors must still propagate.
See https://github.com/vllm-project/vllm/issues/51658.
"""
from unittest.mock import MagicMock, patch
import pytest
import torch
from vllm.platforms import current_platform
from vllm.platforms.cuda import CudaPlatform
from vllm.platforms.interface import DeviceCapability
from vllm.v1.attention.backends.registry import AttentionBackendEnum
from vllm.v1.attention.selector import AttentionSelectorConfig
pytestmark = pytest.mark.skipif(
not current_platform.is_cuda(), reason="CUDA-specific tests"
)
SELECTOR_CONFIG = AttentionSelectorConfig(
head_size=64,
dtype=torch.float16,
kv_cache_dtype=None,
block_size=16,
)
SM90 = DeviceCapability(major=9, minor=0)
@pytest.mark.parametrize(
"exc",
[
ImportError("flashinfer is not installed"),
PermissionError(13, "Permission denied", "/root/.cache/flashinfer"),
OSError("libcuda.so.1: cannot open shared object file"),
],
)
def test_get_valid_backends_records_environment_failure(exc):
with patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc):
valid, invalid_reasons = CudaPlatform.get_valid_backends(
device_capability=SM90,
attn_selector_config=SELECTOR_CONFIG,
num_heads=32,
)
assert valid == []
assert invalid_reasons
for _priority, reasons in invalid_reasons.values():
assert reasons == [f"{type(exc).__name__}: {exc}"]
@pytest.mark.parametrize(
"exc",
[
RuntimeError("CUDA error: no kernel image is available"),
AttributeError("module has no attribute 'get_builder_cls'"),
KeyboardInterrupt(),
],
)
def test_get_valid_backends_propagates_unexpected_errors(exc):
with (
patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc),
pytest.raises(type(exc)),
):
CudaPlatform.get_valid_backends(
device_capability=SM90,
attn_selector_config=SELECTOR_CONFIG,
num_heads=32,
)
def test_get_valid_backends_keeps_probing_after_failure():
healthy = MagicMock()
healthy.validate_configuration.return_value = []
side_effects = [OSError("probe failed")] + [healthy] * 32
with patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=side_effects):
valid, invalid_reasons = CudaPlatform.get_valid_backends(
device_capability=SM90,
attn_selector_config=SELECTOR_CONFIG,
num_heads=32,
)
assert len(invalid_reasons) == 1
assert valid
def test_sm90_nope_mla_prefers_flashinfer_without_changing_rope_order():
backend_cls = MagicMock()
backend_cls.validate_configuration.return_value = []
sparse_backends = {
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
AttentionBackendEnum.FLASHMLA_SPARSE,
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
}
def sparse_order(head_size: int) -> list[AttentionBackendEnum]:
config = SELECTOR_CONFIG._replace(
head_size=head_size,
use_mla=True,
use_sparse=True,
)
with patch(
"vllm.platforms.cuda._get_attn_backend_class",
return_value=backend_cls,
):
valid, _ = CudaPlatform.get_valid_backends(
device_capability=SM90,
attn_selector_config=config,
num_heads=32,
)
return [
candidate.backend
for candidate in valid
if candidate.backend in sparse_backends
]
assert sparse_order(512) == [
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
AttentionBackendEnum.FLASHMLA_SPARSE,
]
assert sparse_order(576) == [
AttentionBackendEnum.FLASH_ATTN_MLA_SPARSE,
AttentionBackendEnum.FLASHMLA_SPARSE,
AttentionBackendEnum.FLASHINFER_MLA_SPARSE_SM90,
]
def test_selected_backend_probe_failure_raises_value_error_with_cause():
exc = OSError("libcuda.so.1: cannot open shared object file")
with (
patch("vllm.platforms.cuda._get_attn_backend_class", side_effect=exc),
patch.object(CudaPlatform, "get_device_capability", return_value=SM90),
pytest.raises(ValueError, match="OSError") as excinfo,
):
CudaPlatform.get_attn_backend_cls(
selected_backend=AttentionBackendEnum.FLASH_ATTN,
attn_selector_config=SELECTOR_CONFIG,
num_heads=32,
)
assert excinfo.value.__cause__ is exc
@@ -1,165 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""The empty-shard mask fused into the DCP A2A pack kernel must be bit-exact
with the eager ``mask_dcp_empty_shards_`` pass it replaces."""
import pytest
import torch
from vllm.platforms import current_platform
from vllm.v1.attention.ops.dcp import (
_dcp_a2a_lse_pack_dim,
_dcp_a2a_pack_send,
mask_dcp_empty_shards_,
)
requires_accelerator = pytest.mark.skipif(
not current_platform.is_cuda_alike(),
reason="needs a CUDA or ROCm device for the Triton pack kernel",
)
def _pack(out, lse, world_size, h_per_rank, head_dim, seq_lens, query_start_loc):
lse_pack_dim = _dcp_a2a_lse_pack_dim(out.dtype)
send = torch.zeros(
(world_size, out.shape[0], h_per_rank, head_dim + lse_pack_dim),
device=out.device,
dtype=out.dtype,
)
_dcp_a2a_pack_send(
out,
lse,
send,
world_size,
h_per_rank,
head_dim,
lse_pack_dim,
seq_lens=seq_lens,
query_start_loc=query_start_loc,
)
return send
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
@pytest.mark.parametrize("world_size,h_per_rank", [(8, 2), (8, 16), (4, 4), (2, 1)])
@pytest.mark.parametrize("tokens_per_req", [1, 2, 3])
@pytest.mark.parametrize("num_pad_rows", [0, 2])
@requires_accelerator
@pytest.mark.parametrize(
"seq_lens_list",
[
[16, 16, 16, 16], # no empty shards (the long-context decode case)
[16, 0, 16, 0], # interior empty shards
[0, 0, 0, 0], # every shard empty
[16, 16, 0, 0], # trailing empty shards, i.e. cudagraph padding
[0, 16, 16, 16], # leading empty shard
[16] * 52, # the profiled conc-52 decode batch
[7], # single request
],
)
def test_fused_mask_matches_eager(
dtype, world_size, h_per_rank, tokens_per_req, num_pad_rows, seq_lens_list
):
torch.manual_seed(0)
device = "cuda"
head_dim = 512
num_seqs = len(seq_lens_list)
# tokens_per_req > 1 is the MTP / multi-token-verify shape.
num_rows = num_seqs * tokens_per_req + num_pad_rows
num_heads = world_size * h_per_rank
out = torch.randn(num_rows, num_heads, head_dim, device=device, dtype=dtype)
lse = torch.randn(num_rows, num_heads, device=device, dtype=torch.float32)
seq_lens = torch.tensor(seq_lens_list, device=device, dtype=torch.int32)
query_start_loc = torch.arange(
0,
(num_seqs + 1) * tokens_per_req,
tokens_per_req,
device=device,
dtype=torch.int32,
) # rows past query_start_loc[-1] are cudagraph padding
# Reference: mask eagerly, then pack with masking disabled.
ref_lse = lse.clone()
mask_dcp_empty_shards_(ref_lse, seq_lens, query_start_loc)
expected = _pack(out, ref_lse, world_size, h_per_rank, head_dim, None, None)
# Under test: pack with the mask fused in.
actual = _pack(
out, lse.clone(), world_size, h_per_rank, head_dim, seq_lens, query_start_loc
)
# The packed LSE slots hold halves of an fp32, not meaningful floats, so
# compare the send buffers bitwise: -inf's high half is a NaN in fp16.
assert torch.equal(actual.view(torch.int16), expected.view(torch.int16)), (
"fused mask is not bit-exact with the eager mask"
)
@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
@pytest.mark.parametrize("seed", range(8))
@requires_accelerator
def test_fused_mask_matches_eager_ragged(dtype, seed):
"""Non-uniform per-request query lengths.
The uniform-stride cases above never exercise an unequal gap between
consecutive ``query_start_loc`` entries, which is what the in-kernel
boundary search has to get right. MTP with partial acceptance produces
exactly this: some requests contribute one row, others several, in the
same batch.
"""
torch.manual_seed(seed)
device = "cuda"
world_size, h_per_rank, head_dim = 8, 2, 512
num_seqs = 17
query_lens = torch.randint(1, 5, (num_seqs,), dtype=torch.int32)
query_start_loc = torch.zeros(num_seqs + 1, dtype=torch.int32)
query_start_loc[1:] = torch.cumsum(query_lens, 0)
# Mix real, empty, and (via padding rows) out-of-range shards.
seq_lens = torch.randint(0, 2, (num_seqs,), dtype=torch.int32) * 16
num_rows = int(query_start_loc[-1]) + 3
query_start_loc = query_start_loc.to(device)
seq_lens = seq_lens.to(device)
num_heads = world_size * h_per_rank
out = torch.randn(num_rows, num_heads, head_dim, device=device, dtype=dtype)
lse = torch.randn(num_rows, num_heads, device=device, dtype=torch.float32)
ref_lse = lse.clone()
mask_dcp_empty_shards_(ref_lse, seq_lens, query_start_loc)
expected = _pack(out, ref_lse, world_size, h_per_rank, head_dim, None, None)
actual = _pack(
out, lse.clone(), world_size, h_per_rank, head_dim, seq_lens, query_start_loc
)
assert torch.equal(actual.view(torch.int16), expected.view(torch.int16)), (
f"ragged query_start_loc mismatch: query_lens={query_lens.tolist()}, "
f"seq_lens={seq_lens.tolist()}"
)
@requires_accelerator
def test_mask_disabled_is_unmasked():
"""Passing no seq_lens/query_start_loc must leave the LSE untouched."""
torch.manual_seed(0)
device = "cuda"
world_size, h_per_rank, head_dim = 8, 2, 512
out = torch.randn(
4, world_size * h_per_rank, head_dim, device=device, dtype=torch.bfloat16
)
lse = torch.randn(4, world_size * h_per_rank, device=device, dtype=torch.float32)
packed = _pack(out, lse, world_size, h_per_rank, head_dim, None, None)
assert torch.isfinite(packed.float()).all()
def test_eager_mask_handles_rank_with_no_local_sequences():
"""Padded graph rows are all empty when a DCP rank has no sequences."""
lse = torch.randn(8, 4, dtype=torch.float32)
seq_lens = torch.empty(0, dtype=torch.int32)
query_start_loc = torch.tensor([0], dtype=torch.int32)
mask_dcp_empty_shards_(lse, seq_lens, query_start_loc)
assert torch.isneginf(lse).all()
-223
View File
@@ -1,223 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from types import SimpleNamespace
from unittest.mock import patch
import pytest
import torch
from vllm._aiter_ops import rocm_aiter_ops
from vllm.model_executor.layers.mamba.gdn import qwen_gdn_linear_attn
from vllm.model_executor.layers.mamba.gdn.qwen_gdn_linear_attn import (
ChunkGatedDeltaRule,
_resolve_gdn_prefill_backend,
)
from vllm.platforms import current_platform
def _make_config(
*,
backend: str = "aiter_flydsl",
head_k_dim: int | None = 128,
head_v_dim: int | None = 128,
dtype: torch.dtype = torch.bfloat16,
):
return SimpleNamespace(
additional_config={"gdn_prefill_backend": backend},
model_config=SimpleNamespace(
dtype=dtype,
hf_text_config=SimpleNamespace(
linear_key_head_dim=head_k_dim,
linear_value_head_dim=head_v_dim,
),
),
)
def _resolve_on_rocm(config, *, kernels_available: bool = True, mi3xx: bool = True):
with (
patch.object(
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=True
),
patch.object(
qwen_gdn_linear_attn.rocm_aiter_ops,
"is_gdn_flydsl_prefill_available",
return_value=kernels_available,
),
patch("vllm.platforms.rocm.on_mi3xx", return_value=mi3xx),
):
return _resolve_gdn_prefill_backend(config)
@pytest.mark.parametrize(
"head_k_dim,head_v_dim,dtype,expected",
[
(128, 128, torch.bfloat16, "aiter_flydsl"),
(64, 128, torch.bfloat16, "triton"),
(128, 64, torch.bfloat16, "triton"),
(128, 128, torch.float16, "triton"),
],
)
def test_resolve_aiter_flydsl_gdn_prefill_backend(
head_k_dim: int,
head_v_dim: int,
dtype: torch.dtype,
expected: str,
):
config = _make_config(head_k_dim=head_k_dim, head_v_dim=head_v_dim, dtype=dtype)
requested, active = _resolve_on_rocm(config)
assert requested == "aiter_flydsl"
assert active == expected
@pytest.mark.parametrize(
"mi3xx,kernels_available,head_k_dim,expected",
[
(True, True, 128, "aiter_flydsl"),
(False, True, 128, "triton"),
(True, False, 128, "triton"),
(True, True, 64, "triton"),
],
)
def test_auto_defaults_to_aiter_flydsl(
mi3xx: bool, kernels_available: bool, head_k_dim: int, expected: str
):
"""Under auto, FlyDSL is the default only where it was validated and the
model and build can serve it; everything else stays on Triton."""
config = _make_config(backend="auto", head_k_dim=head_k_dim)
assert _resolve_on_rocm(
config, kernels_available=kernels_available, mi3xx=mi3xx
) == ("auto", expected)
@pytest.mark.parametrize("backend", ["aiter_flydsl", "auto"])
def test_kda_style_model_cannot_select_flydsl(backend: str):
"""Kimi K3 KDA reports head dims through linear_attn_config, not these.
Its builder overrides _build_chunk_metadata, which the AITER path skips,
so this pins the reason the two never meet: the resolver turns the model
down before the builder is ever constructed.
"""
config = _make_config(backend=backend, head_k_dim=None, head_v_dim=None)
assert _resolve_on_rocm(config) == (backend, "triton")
@pytest.mark.parametrize("on_rocm", [True, False], ids=["kernels_missing", "not_rocm"])
def test_explicit_aiter_flydsl_fails_closed(on_rocm: bool):
"""An explicit request that cannot be honoured is a configuration error.
Falling back silently would report the run as healthy while the requested
kernels were never used.
"""
config = _make_config()
if on_rocm:
with pytest.raises(RuntimeError, match="not importable"):
_resolve_on_rocm(config, kernels_available=False)
return
with (
patch.object(
qwen_gdn_linear_attn.current_platform, "is_rocm", return_value=False
),
patch.object(
qwen_gdn_linear_attn.current_platform, "is_cuda", return_value=True
),
pytest.raises(RuntimeError, match="aiter_flydsl"),
):
_resolve_gdn_prefill_backend(config)
def _flydsl_prefill_unavailable() -> bool:
if not current_platform.is_rocm():
return True
from vllm.platforms.rocm import on_mi3xx
return not on_mi3xx() or not rocm_aiter_ops.is_gdn_flydsl_prefill_available()
@pytest.mark.skipif(
_flydsl_prefill_unavailable(),
reason="needs gfx942/gfx950 with the AITER FlyDSL GDN prefill kernels installed",
)
@pytest.mark.parametrize(
"state_dtype", [torch.float32, torch.bfloat16], ids=["fp32_state", "bf16_state"]
)
def test_aiter_flydsl_prefill_matches_triton_reference(state_dtype: torch.dtype):
"""Run both prefill paths on device and compare.
The reference is the same AITER entry point with the FlyDSL prepare and K5
kernels switched off, so the only thing that differs between the two calls
is the kernels this backend exists to select. The state dtype follows
--mamba-ssm-cache-dtype, which may be float32 or bfloat16.
"""
from aiter.ops.triton.gated_delta_net import chunk_gated_delta_rule_opt_vk
torch.manual_seed(0)
device = torch.device("cuda")
seq_lens = [70, 130]
total_tokens = sum(seq_lens)
num_k_heads, num_v_heads, head_dim = 2, 4, 128
# use_qk_l2norm_in_kernel=False matches the prefill path, where the model
# has already normalised q and k. Feeding raw normals instead lets the
# delta rule run away to NaN, which says nothing about either kernel.
q = torch.nn.functional.normalize(
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
).to(torch.bfloat16)
k = torch.nn.functional.normalize(
torch.randn(1, total_tokens, num_k_heads, head_dim, device=device), dim=-1
).to(torch.bfloat16)
v = torch.randn(
1, total_tokens, num_v_heads, head_dim, dtype=torch.bfloat16, device=device
)
# g is a log-domain decay, so keep it negative or the recurrence diverges
# and the comparison stops saying anything about the kernels.
g = -torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
beta = torch.rand(1, total_tokens, num_v_heads, dtype=torch.float32, device=device)
cu_seqlens = torch.tensor([0, 70, 200], dtype=torch.int32, device=device)
initial_state = torch.randn(
len(seq_lens),
num_v_heads,
head_dim,
head_dim,
device=device,
).to(state_dtype)
shared = {
"q": q,
"k": k,
"v": v,
"g": g,
"beta": beta,
"output_final_state": True,
"cu_seqlens": cu_seqlens,
"use_qk_l2norm_in_kernel": False,
}
reference_out, reference_state = chunk_gated_delta_rule_opt_vk(
initial_state=initial_state.clone(),
state_dtype=state_dtype,
use_chunk_flydsl=False,
use_prepare_flydsl=False,
**shared,
)
flydsl_out, flydsl_state = ChunkGatedDeltaRule.forward_aiter_flydsl(
None,
initial_state=initial_state.clone(),
aiter_prefill_metadata=rocm_aiter_ops.build_gdn_flydsl_prefill_metadata(
seq_lens, cu_seqlens=cu_seqlens
),
**shared,
)
assert flydsl_state.dtype == state_dtype
torch.testing.assert_close(
flydsl_out.float(), reference_out.float(), rtol=2e-2, atol=2e-2
)
torch.testing.assert_close(
flydsl_state.float(), reference_state.float(), rtol=2e-2, atol=2e-2
)
@@ -1,154 +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 BatchSpec, create_common_attn_metadata
from vllm.config import CUDAGraphMode
from vllm.platforms import current_platform
from vllm.v1.attention.backends.triton_attn import TritonAttentionMetadataBuilder
from vllm.v1.attention.backends.triton_attn_diffkv import (
TritonAttentionDiffKVMetadataBuilder,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec
# 64 segments only while num_seqs * num_kv_heads * 16 < 188 SMs on SM12.0 and
# the 64-segment scratch holds every query token (e.g. multi-query verify).
@pytest.mark.parametrize(
"builder_cls",
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
)
@pytest.mark.parametrize(
"capability,num_kv_heads,num_seqs,query_len,segments",
[
((12, 0), 1, 11, 1, 64),
((12, 0), 1, 12, 1, 16),
((12, 0), 8, 1, 1, 64),
((12, 0), 8, 2, 1, 16),
((9, 0), 1, 1, 1, 16),
((12, 0), 1, 2, 4, 64),
((12, 0), 1, 10, 4, 16),
],
)
def test_split_k_segments_follow_sm_occupancy(
monkeypatch, builder_cls, capability, num_kv_heads, num_seqs, query_len, segments
):
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
monkeypatch.setattr(
current_platform, "is_device_capability", lambda cap: cap == capability
)
monkeypatch.setattr(current_platform, "num_compute_units", lambda: 188)
config = SimpleNamespace(
model_config=SimpleNamespace(
get_num_attention_heads=lambda _: 8,
get_num_kv_heads=lambda _: num_kv_heads,
get_head_size=lambda: 128,
rswa_window=None,
),
parallel_config=None,
scheduler_config=SimpleNamespace(max_num_seqs=16),
speculative_config=None,
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
),
)
spec = FullAttentionSpec(
block_size=16, num_kv_heads=num_kv_heads, head_size=128, dtype=torch.bfloat16
)
builder = builder_cls(spec, ["layer.0"], config, "cpu")
batch = BatchSpec(seq_lens=[128] * num_seqs, query_lens=[query_len] * num_seqs)
metadata = builder.build(0, create_common_attn_metadata(batch, 16, "cpu"))
assert metadata.num_par_softmax_segments == segments
assert metadata.softmax_segm_output.shape[2] == segments
assert metadata.softmax_segm_max.shape[0] >= num_seqs * query_len
# DiffKV re-allocates the output; it must stay sized like the base buffers.
assert builder.softmax_segm_output.shape[0] == builder.softmax_segm_max.shape[0]
assert (
metadata.softmax_segm_output.data_ptr()
== builder.softmax_segm_output.data_ptr()
)
def _draft_builder(builder_cls, rswa_window: int | None):
config = SimpleNamespace(
model_config=SimpleNamespace(
get_num_attention_heads=lambda _: 8,
get_num_kv_heads=lambda _: 1,
get_head_size=lambda: 128,
rswa_window=rswa_window,
),
parallel_config=None,
scheduler_config=SimpleNamespace(max_num_seqs=16),
speculative_config=None,
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
),
)
spec = FullAttentionSpec(
block_size=16, num_kv_heads=1, head_size=128, dtype=torch.bfloat16
)
return builder_cls(spec, ["layer.0"], config, "cpu")
def _draft_decode_batch(seq_lens: list[int]):
batch = BatchSpec(seq_lens=seq_lens, query_lens=[1] * len(seq_lens))
return create_common_attn_metadata(batch, 16, "cpu")
@pytest.mark.parametrize(
"builder_cls",
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
)
@pytest.mark.parametrize("rswa_window", [None, 64])
def test_draft_decode_update_flag_matches_build_writes(builder_cls, rswa_window):
"""The update is a no-op, so the builder may claim support only when
build() writes no builder-owned tensor that a captured graph reads."""
builder = _draft_builder(builder_cls, rswa_window)
common_metadata = _draft_decode_batch([5, 9])
common_metadata.rswa_prefix_lens = torch.tensor([3, 7], dtype=torch.int32)
def owned_bytes():
# Bytes, not values: uninitialized scratch may hold NaNs.
return {
name: value.view(torch.uint8).clone()
for name, value in vars(builder).items()
if isinstance(value, torch.Tensor)
}
before = owned_bytes()
builder.build(0, common_metadata)
after = owned_bytes()
written = [name for name in before if not torch.equal(before[name], after[name])]
assert builder.supports_draft_decode_metadata_update is (not written)
assert builder.supports_draft_decode_metadata_update is (rswa_window is None)
@pytest.mark.parametrize(
"builder_cls",
[TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder],
)
def test_draft_decode_update_matches_fresh_build(builder_cls):
"""A replayed graph reads metadata built at capture; after an in-place
update it must match a fresh build of the replayed batch."""
torch.manual_seed(0)
builder = _draft_builder(builder_cls, rswa_window=None)
captured = _draft_decode_batch([100, 120])
metadata = builder.build(0, captured)
replayed = _draft_decode_batch([128, 30])
# The replayed batch arrives through the same persistent input buffers.
captured.seq_lens.copy_(replayed.seq_lens)
captured.block_table_tensor.copy_(replayed.block_table_tensor)
captured.slot_mapping.copy_(replayed.slot_mapping)
builder.update_draft_decode_metadata(metadata)
expected = _draft_builder(builder_cls, rswa_window=None).build(0, replayed)
assert torch.equal(metadata.seq_lens, expected.seq_lens)
assert torch.equal(metadata.block_table, expected.block_table)
assert torch.equal(metadata.slot_mapping, expected.slot_mapping)
assert torch.equal(metadata.query_start_loc, expected.query_start_loc)
@@ -1,158 +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 BatchSpec, create_common_attn_metadata
from vllm.config import CUDAGraphMode
from vllm.platforms import current_platform
from vllm.v1.attention.backends.triton_attn import TritonAttentionMetadataBuilder
from vllm.v1.attention.backends.triton_attn_diffkv import (
TritonAttentionDiffKVMetadataBuilder,
)
from vllm.v1.kv_cache_interface import FullAttentionSpec, KVQuantMode
def _build(
monkeypatch,
builder_cls,
capability,
num_kv_heads,
query_lens,
max_num_seqs=16,
num_speculative_tokens=None,
parallel_drafting=False,
kv_quant_mode=KVQuantMode.NONE,
):
monkeypatch.setattr(current_platform, "is_cuda", lambda: True)
monkeypatch.setattr(
current_platform, "is_device_capability", lambda cap: cap == capability
)
monkeypatch.setattr(current_platform, "num_compute_units", lambda: 188)
config = SimpleNamespace(
model_config=SimpleNamespace(
get_num_attention_heads=lambda _: 8,
get_num_kv_heads=lambda _: num_kv_heads,
get_head_size=lambda: 128,
rswa_window=None,
),
parallel_config=None,
scheduler_config=SimpleNamespace(max_num_seqs=max_num_seqs),
speculative_config=(
None
if num_speculative_tokens is None
else SimpleNamespace(
num_speculative_tokens=num_speculative_tokens,
parallel_drafting=parallel_drafting,
)
),
compilation_config=SimpleNamespace(
cudagraph_mode=CUDAGraphMode.NONE, static_forward_context={}
),
)
spec = FullAttentionSpec(
block_size=16,
num_kv_heads=num_kv_heads,
head_size=128,
dtype=torch.bfloat16,
kv_quant_mode=kv_quant_mode,
)
builder = builder_cls(spec, ["layer.0"], config, "cpu")
batch = BatchSpec(seq_lens=[128] * len(query_lens), query_lens=query_lens)
metadata = builder.build(0, create_common_attn_metadata(batch, 16, "cpu"))
assert metadata.softmax_segm_output.shape[2] == metadata.num_par_softmax_segments
assert metadata.softmax_segm_max.shape[0] >= sum(query_lens)
# DiffKV re-allocates the output; it must stay sized like the base buffers.
assert builder.softmax_segm_output.shape[0] == builder.softmax_segm_max.shape[0]
assert (
metadata.softmax_segm_output.data_ptr()
== builder.softmax_segm_output.data_ptr()
)
return builder, metadata
BUILDERS = [TritonAttentionMetadataBuilder, TritonAttentionDiffKVMetadataBuilder]
# Verify batches: the 64-segment scratch holds min(11, max_num_seqs) * (1 + K)
# rows, and its 16-segment view covers every 3D-eligible sequence. 64 segments
# follow the request count, not Q blocks: on SM12.0 they stay faster for verify
# batches up to 11 requests (22 Q blocks at K=3).
@pytest.mark.parametrize("builder_cls", BUILDERS)
@pytest.mark.parametrize(
"max_num_seqs,num_speculative_tokens,num_seqs,rows,segments",
[
(16, 3, 10, 44, 64),
(16, 3, 11, 44, 64),
(16, 3, 12, 44, 16),
(16, 3, 16, 44, 16),
(1, 5, 1, 6, 64),
],
)
def test_split_k_segment_rows_cover_verify_queries(
monkeypatch,
builder_cls,
max_num_seqs,
num_speculative_tokens,
num_seqs,
rows,
segments,
):
builder, metadata = _build(
monkeypatch,
builder_cls,
(12, 0),
1,
[1 + num_speculative_tokens] * num_seqs,
max_num_seqs,
num_speculative_tokens,
)
assert builder.softmax_segm_max.shape[:2] == (rows, 8)
assert metadata.num_par_softmax_segments == segments
# Without SM12.0 64-segment reuse, the scratch holds exactly
# min(seq_threshold_3D, max_num_seqs) * query_len rows for split-K query_lens.
@pytest.mark.parametrize(
"num_speculative_tokens,parallel_drafting,max_num_seqs,rows",
[
(None, False, 8, 8),
(4, False, 8, 40),
(7, False, 8, 64),
(8, False, 8, 64),
(3, True, 8, 56),
(4, True, 8, 64),
(5, False, 1, 6),
],
)
@pytest.mark.parametrize(
"kv_quant_mode", [KVQuantMode.NONE, KVQuantMode.INT4_PER_TOKEN_HEAD]
)
def test_split_k_scratch_rows_follow_speculative_config(
monkeypatch,
num_speculative_tokens,
parallel_drafting,
max_num_seqs,
rows,
kv_quant_mode,
):
# The INT4 launcher never runs multi-query split-K.
if kv_quant_mode == KVQuantMode.INT4_PER_TOKEN_HEAD:
rows = max_num_seqs
builder, _ = _build(
monkeypatch,
TritonAttentionMetadataBuilder,
(9, 0),
1,
[1],
max_num_seqs,
num_speculative_tokens,
parallel_drafting,
kv_quant_mode,
)
assert builder.softmax_segm_output.shape == (rows, 8, 16, 128)
assert builder.softmax_segm_max.shape == (rows, 8, 16)
assert builder.softmax_segm_expsum.shape == (rows, 8, 16)
@@ -1,87 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import sys
from types import ModuleType, SimpleNamespace
import pytest
import torch
from torch._subclasses.fake_tensor import FakeTensorMode
from vllm.platforms import current_platform
from vllm.v1.attention.ops import vit_attn_wrappers
def _noncontiguous_bshd(device: torch.device | None = None) -> torch.Tensor:
return (
torch.arange(120, dtype=torch.float32, device=device)
.reshape(1, 3, 5, 8)
.transpose(1, 2)
)
def test_registered_attention_wrapper_fake_layouts():
with FakeTensorMode():
q = _noncontiguous_bshd()
cu_seqlens = torch.tensor([0, 5], dtype=torch.int32)
max_seqlen = torch.tensor(5, dtype=torch.int32)
flashinfer_cu_seqlens = torch.tensor([0, 5, 0, 5], dtype=torch.int32)
sequence_lengths = torch.tensor([5], dtype=torch.int32)
outputs = (
torch.ops.vllm.flash_attn_maxseqlen_wrapper(
q, q, q, 1, False, None, None, cu_seqlens, max_seqlen
),
torch.ops.vllm.triton_attn_wrapper(
q, q, q, 1, None, cu_seqlens, max_seqlen
),
torch.ops.vllm.torch_sdpa_wrapper(q, q, q, None, None, False),
torch.ops.vllm.flashinfer_wrapper(
q,
q,
q,
1.0,
torch.empty(1, dtype=torch.uint8),
flashinfer_cu_seqlens,
max_seqlen,
sequence_lengths,
None,
None,
None,
None,
),
)
assert all(output.is_contiguous() for output in outputs)
def test_aiter_flash_attn_omits_out_and_returns_contiguous_output(
monkeypatch: pytest.MonkeyPatch,
):
aiter = ModuleType("aiter")
def flash_attn_varlen_func(q, k, v, **kwargs):
assert "out" not in kwargs
return q
aiter.__dict__["flash_attn_varlen_func"] = flash_attn_varlen_func
monkeypatch.setitem(sys.modules, "aiter", aiter)
monkeypatch.setattr(
vit_attn_wrappers, "current_platform", SimpleNamespace(is_rocm=lambda: True)
)
q = _noncontiguous_bshd()
assert not q.is_contiguous()
output = vit_attn_wrappers.flash_attn_maxseqlen_wrapper(q, q, q, 1, True, None)
assert torch.equal(output, q)
assert output.is_contiguous()
@pytest.mark.skipif(not current_platform.is_cuda_alike(), reason="Requires GPU")
def test_sdpa_output_layout_without_cu_seqlens():
q = _noncontiguous_bshd(torch.device("cuda"))
output = vit_attn_wrappers.vit_torch_sdpa_wrapper(q, q, q)
assert output.is_contiguous()