Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
e6969ab
feat: initial implementation
simondanielsson Sep 24, 2026
50a3ade
feat: add benchmark script
simondanielsson Sep 25, 2026
86e1a03
fix: update the heuristic for when to use the kernel
simondanielsson Sep 25, 2026
42675ca
chore: cleanup comments
simondanielsson Sep 25, 2026
133e5ae
fix: only run splitk during pure decodes
simondanielsson Sep 25, 2026
c6212db
chore: rename kernel
simondanielsson Sep 25, 2026
33cf434
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Sep 25, 2026
185882e
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Sep 30, 2026
d9cce6b
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Sep 30, 2026
80f1c1e
fix: check num_splits in callsite t oavoid calling prefill kernel in …
simondanielsson Oct 1, 2026
ed8e7dd
fix: set manual seed using set_random_seed util
simondanielsson Oct 1, 2026
2085dec
Merge remote-tracking branch 'upstream/main' into feat/glm53flash-spa…
simondanielsson Oct 2, 2026
b43a03f
test: tighten tests
simondanielsson Oct 2, 2026
12105b5
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Oct 5, 2026
9ae9cea
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Oct 6, 2026
c882afc
Merge branch 'main' into feat/glm53flash-sparse-decode
dllehr-amd Oct 7, 2026
9a444cf
fix: remove trivial test
simondanielsson Oct 7, 2026
a175d19
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Oct 7, 2026
aa3ee5b
fix: add new mocked attributes to fix failing tests
simondanielsson Oct 7, 2026
d5de4fe
Merge branch 'main' into feat/glm53flash-sparse-decode
simondanielsson Oct 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions benchmarks/kernels/benchmark_sparse_mla_decode_bf16.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Benchmark the ROCm bf16 sparse-MLA decode split-K kernel in isolation.

Example usage:
python3 benchmarks/kernels/benchmark_sparse_mla_decode_bf16.py \
--rows 1 4 16 64 --lens 2048 --splits auto 4 16 32
"""

import argparse
import itertools
import json

import torch

from vllm.triton_utils import triton
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_rocm_sparse_attn_decode_ragged_bf16_triton,
_rocm_sparse_attn_prefill_ragged_triton,
_sparse_decode_bf16_num_splits,
)

BLOCK_H = 16
BLOCK_K = 32


def make_inputs(rows: int, live: int, args):
torch.manual_seed(args.seed)
kv = (
torch.randn(args.capacity, args.head_dim, device="cuda", dtype=torch.bfloat16)
* 0.125
)
q = (
torch.randn(
rows, args.heads, args.head_dim, device="cuda", dtype=torch.bfloat16
)
* 0.125
)
slots = torch.stack(
[torch.randperm(args.capacity, device="cuda")[:live] for _ in range(rows)]
)
indices = slots.reshape(-1).to(torch.int32)
indptr = torch.arange(rows + 1, device="cuda", dtype=torch.int32) * live
sink = (
torch.randn(args.heads, device="cuda", dtype=torch.float32)
if args.sink
else None
)
return q, kv, indices, indptr, sink


def resolve_splits(spec: str, rows: int, live: int, args) -> int:
if spec != "auto":
return int(spec)
return _sparse_decode_bf16_num_splits(
rows, triton.cdiv(args.heads, BLOCK_H), live, BLOCK_K
)


def benchmark(backend: str, rows: int, live: int, spec: str, args) -> dict:
q, kv, indices, indptr, sink = make_inputs(rows, live, args)
nope, rope = args.head_dim, 0
splits = resolve_splits(spec, rows, live, args)

def ragged():
return _rocm_sparse_attn_prefill_ragged_triton(
q, kv, indices, indptr, args.scale, sink, nope, rope
)

def splitk():
return _rocm_sparse_attn_decode_ragged_bf16_triton(
q, kv, indices, indptr, args.scale, sink, nope, rope, splits
)

run = ragged if backend == "ragged" else splitk
torch.testing.assert_close(run(), ragged(), atol=2e-2, rtol=2e-2)
ms = triton.testing.do_bench(run, warmup=args.warmup, rep=args.rep)
return dict(
backend=backend,
rows=rows,
live=live,
heads=args.heads,
head_dim=args.head_dim,
splits=splits if backend == "splitk" else 1,
workgroups=rows * triton.cdiv(args.heads, BLOCK_H) * splits,
us=ms * 1000,
kv_gbps=rows * live * args.head_dim * 2 / (ms * 1e6),
)


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--rows", type=int, nargs="+", default=[1, 2, 4, 8, 16, 64])
parser.add_argument(
"--lens",
type=int,
nargs="+",
default=[2048],
help="Selected KV slots per row; GLM-5.3-Flash uses index_topk=2048",
)
parser.add_argument(
"--splits",
nargs="+",
default=["auto"],
help="Split counts to sweep, or auto for the runtime heuristic",
)
parser.add_argument(
"--backends",
nargs="+",
choices=["ragged", "splitk"],
default=["ragged", "splitk"],
)
parser.add_argument(
"--heads", type=int, default=8, help="Heads per rank; 64 at TP8 gives 8"
)
parser.add_argument("--head-dim", type=int, default=512)
parser.add_argument("--capacity", type=int, default=65536)
parser.add_argument("--scale", type=float, default=0.044194173824159216)
parser.add_argument("--sink", action="store_true")
parser.add_argument("--warmup", type=int, default=25)
parser.add_argument("--rep", type=int, default=200)
parser.add_argument("--seed", type=int, default=123)
args = parser.parse_args()

print(json.dumps(dict(gpu=torch.cuda.get_device_name(0), args=vars(args))))
for backend, rows, live in itertools.product(args.backends, args.rows, args.lens):
specs = ["1"] if backend == "ragged" else args.splits
for spec in specs:
print(json.dumps(benchmark(backend, rows, live, spec, args)), flush=True)


if __name__ == "__main__":
main()
146 changes: 146 additions & 0 deletions tests/kernels/attention/test_rocm_triton_attn_dsv4.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,137 @@ def test_sparse_attn_prefill_ragged_kernel() -> None:
torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2)


NOPE_ONLY_HEAD_DIM = 512


def _nope_only_ragged_inputs(
kv_lens: list[int], num_heads: int, device: torch.device
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
"""Build a GLM-like 512+0 NoPE decode batch with ragged KV segments."""
num_kv = 4096
kv = (
torch.randn(num_kv, NOPE_ONLY_HEAD_DIM, dtype=torch.bfloat16, device=device)
* 0.125
)
q = (
torch.randn(
len(kv_lens),
num_heads,
NOPE_ONLY_HEAD_DIM,
dtype=torch.bfloat16,
device=device,
)
* 0.125
)
rows = [torch.randperm(num_kv)[:length].tolist() for length in kv_lens]
indices, indptr = _ragged_from_rows(rows, device)
return q, kv, indices, indptr


# Lengths below the split count leave splits empty; non-multiples force a tail.
_NOPE_ONLY_KV_LENS = [0, 1, 3, 37, 129, 2048]


@requires_split_decode_arch
@pytest.mark.parametrize("num_splits", [2, 4, 8, 32])
@pytest.mark.parametrize("with_sink", [True, False])
@torch.inference_mode()
def test_sparse_attn_decode_bf16_split_k_matches_ragged(
num_splits: int, with_sink: bool
) -> None:
"""Split-K decode must reproduce the single-workgroup ragged kernel."""
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_rocm_sparse_attn_decode_ragged_bf16_triton,
_rocm_sparse_attn_prefill_ragged_triton,
)

device = torch.device("cuda")
torch.manual_seed(0)
Comment thread
simondanielsson marked this conversation as resolved.
Resolved
num_heads = 16
q, kv, indices, indptr = _nope_only_ragged_inputs(
_NOPE_ONLY_KV_LENS, num_heads, device
)
attn_sink = (
torch.randn(num_heads, dtype=torch.float32, device=device)
if with_sink
else None
)
scale = NOPE_ONLY_HEAD_DIM**-0.5

expected = _rocm_sparse_attn_prefill_ragged_triton(
q=q,
kv=kv,
indices=indices,
indptr=indptr,
scale=scale,
attn_sink=attn_sink,
nope_head_dim=NOPE_ONLY_HEAD_DIM,
rope_head_dim=0,
)
actual = _rocm_sparse_attn_decode_ragged_bf16_triton(
q=q,
kv=kv,
indices=indices,
indptr=indptr,
scale=scale,
attn_sink=attn_sink,
nope_head_dim=NOPE_ONLY_HEAD_DIM,
rope_head_dim=0,
num_splits=num_splits,
)
torch.testing.assert_close(actual, expected, atol=2e-2, rtol=2e-2)


@requires_split_decode_arch
@pytest.mark.parametrize("sparse_len", [0, 2048], ids=["fallback", "splitk"])
@torch.inference_mode()
def test_sparse_attn_decode_bf16_writes_caller_output(sparse_len: int) -> None:
"""The decode entry point writes the ragged result into the caller's out.

Both dispatch branches are covered: ``sparse_len`` below the split floor
falls through to the single-pass kernel, above it takes split-K.
"""
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
_rocm_sparse_attn_prefill_ragged_triton,
rocm_sparse_attn_decode_bf16,
)

device = torch.device("cuda")
torch.manual_seed(0)
num_heads = 16
q, kv, indices, indptr = _nope_only_ragged_inputs(
_NOPE_ONLY_KV_LENS, num_heads, device
)
attn_sink = torch.randn(num_heads, dtype=torch.float32, device=device)
scale = NOPE_ONLY_HEAD_DIM**-0.5

expected = _rocm_sparse_attn_prefill_ragged_triton(
q=q,
kv=kv,
indices=indices,
indptr=indptr,
scale=scale,
attn_sink=attn_sink,
nope_head_dim=NOPE_ONLY_HEAD_DIM,
rope_head_dim=0,
)
output = torch.empty_like(expected)
rocm_sparse_attn_decode_bf16(
q=q,
kv=kv.unsqueeze(1),
scale=scale,
head_dim=NOPE_ONLY_HEAD_DIM,
nope_head_dim=NOPE_ONLY_HEAD_DIM,
rope_head_dim=0,
attn_sink=attn_sink,
output=output,
ragged_indices=indices,
ragged_indptr=indptr,
sparse_len=sparse_len,
)
torch.testing.assert_close(output, expected, atol=2e-2, rtol=2e-2)


@pytest.mark.parametrize(
("num_queries", "on_gfx950", "expected"),
[(1023, True, False), (1024, True, True), (1024, False, False)],
Expand Down Expand Up @@ -905,6 +1036,21 @@ def test_decode_num_splits_gfx950(monkeypatch) -> None:
assert mod._decode_gfx950_num_splits(1, 1, 128, 8192) == 32
assert mod._decode_gfx950_num_splits(17, 1, 128, 32) == 4
assert mod._decode_gfx950_num_splits(512, 1, 128, 7812) == 1
assert mod._decode_gfx950_num_splits(4, 1, 2048.0, 0.0, 32) == 32


@torch.inference_mode()
def test_sparse_decode_bf16_num_splits_floor_and_tile_clamp(monkeypatch) -> None:
"""Short rows skip splitting, and splits never exceed the tiles they walk."""
from vllm.v1.attention.ops import rocm_aiter_mla_sparse as mod

monkeypatch.setattr(mod, "_decode_num_splits", lambda *args: 32)
monkeypatch.setattr(mod, "_decode_gfx950_num_splits", lambda *args: 32)

floor = mod._SPARSE_DECODE_BF16_MIN_SPLIT_LEN
assert mod._sparse_decode_bf16_num_splits(1, 1, floor - 1, 32) == 1
assert mod._sparse_decode_bf16_num_splits(1, 1, floor, 32) == floor // 32
assert mod._sparse_decode_bf16_num_splits(1, 1, 2048, 32) == 32


@requires_split_decode_arch
Expand Down
47 changes: 33 additions & 14 deletions vllm/v1/attention/backends/mla/rocm_aiter_mla_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
)
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_sparse_attn_decode_bf16,
rocm_sparse_attn_prefill,
)
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
Expand Down Expand Up @@ -822,20 +823,38 @@ def _forward_mla(
self.sinks.reshape(1, self.num_heads, 1),
q.shape[1],
).reshape(-1)
rocm_sparse_attn_prefill(
q=q,
kv=kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1]),
indices=None,
topk_length=None,
scale=self.scale,
head_dim=q.shape[-1],
nope_head_dim=self.kv_lora_rank,
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
attn_sink=triton_sinks,
output=output,
ragged_indices=attn_metadata.paged_kv_indices,
ragged_indptr=attn_metadata.paged_kv_indptr,
)
kv = kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1])
if attn_metadata.num_decode_tokens == num_tokens:
rocm_sparse_attn_decode_bf16(
q=q,
kv=kv,
scale=self.scale,
head_dim=q.shape[-1],
nope_head_dim=self.kv_lora_rank,
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
attn_sink=triton_sinks,
output=output,
ragged_indices=attn_metadata.paged_kv_indices,
ragged_indptr=attn_metadata.paged_kv_indptr,
sparse_len=min(
attn_metadata.max_seq_len, attn_metadata.topk_tokens
),
)
else:
rocm_sparse_attn_prefill(
q=q,
kv=kv,
indices=None,
topk_length=None,
scale=self.scale,
head_dim=q.shape[-1],
nope_head_dim=self.kv_lora_rank,
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
attn_sink=triton_sinks,
output=output,
ragged_indices=attn_metadata.paged_kv_indices,
ragged_indptr=attn_metadata.paged_kv_indptr,
)
output = AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
return output, None

Expand Down
Loading
Loading