Skip to content

[Triton/Gluon] [QSA] Add paged sparse attention kernels - #4882

Closed
haic0 wants to merge 16 commits into
ROCm:mainfrom
haic0:qsa-paged-sparse-attention
Closed

haic0 wants to merge 16 commits into
ROCm:mainfrom
haic0:qsa-paged-sparse-attention

Conversation

@haic0

@haic0 haic0 commented Aug 20, 2026 •

Copy link
Copy Markdown

Summary

Add portable Qwen3.8-Flash-Next QSA scoring, radix selection, index expansion, and sparse GQA operators with gfx950 parity coverage.

  • Add portable Triton paged MQA scoring and sparse paged GQA kernels.
  • Add gfx950 Gluon implementations with guarded dispatch and portable Triton fallback.
  • Keep radix top-k and index expansion on their existing paths.
  • Enable automatic Gluon dispatch only for validated gfx950 Qwen3.8 geometries; explicit Triton and Gluon overrides remain available.
  • Reject non-contiguous 1D metadata consumed as contiguous by kernels, and validate positive integer selection parameters before arithmetic.

Released Qwen3.8 geometry

The released BF16 and FP8 Qwen3.8-Flash-Next checkpoints use:

indexer_n_heads=4
indexer_kv_heads=1
indexer_head_dim=128
indexer_budget=2048
indexer_compress_ratio=4

The gfx950 Gluon scorer supports both this four-head production shape and the earlier eight-head development shape. On AMD Instinct MI350X (gfx950:sramecc+:xnack-), ROCm 7.2, PyTorch 2.9.1, and Triton 3.7.0, seven alternating-backend runs for rows=32, heads=4, head_dim=128, page_size=8, and pages=512 measured:

  • Triton mean p50: 0.018383 ms, p50 CV 1.736%.
  • Gluon mean p50: 0.017566 ms, p50 CV 0.080%.
  • Speedup: 1.047x.

The complete QSA test file passed on the same MI350X environment: 17 passed.

gfx950 sparse GQA performance

Shape: num_tokens=16, num_query_heads=10, head_dim=128, selection_width=2051.

The following exact-head results were measured from runtime commit 2462d5b64 on AMD Instinct MI350X (gfx950:sramecc+:xnack-), ROCm 7.2, PyTorch 2.9.1, and Triton 3.7.0. Current PR head 150c7bc12 adds only the corresponding documentation refresh. Each result is the mean p50 from seven alternating-backend runs with 100 warmup iterations and 500 measured iterations per backend.

  • Ordered indices: Triton 0.115509 ms, Gluon 0.092252 ms — 20.1% lower latency (1.252x); p50 CV 2.353% / 0.124%.
  • Randomized indices: Triton 0.118881 ms, Gluon 0.094143 ms — 20.8% lower latency (1.263x); p50 CV 1.690% / 0.549%.

The benchmark reports every run's p20/p50/p80, aggregate p20/p50/p80, p50 standard deviation/CV, backend order, and full environment/config metadata. Unsupported shapes and failures retain the Triton fallback.

Reproduction

python -m pytest -q op_tests/triton_tests/attention/test_qsa_validation.py
python -m pytest -q op_tests/triton_tests/attention/test_qsa.py
python op_tests/op_benchmarks/triton/bench_qsa_sparse_gqa.py --order ordered --runs 7 --warmup 100 --rep 500
python op_tests/op_benchmarks/triton/bench_qsa_sparse_gqa.py --order random --runs 7 --warmup 100 --rep 500

Add portable Qwen-Air QSA scoring, radix selection, index expansion, and sparse GQA operators with gfx950 parity coverage.

Signed-off-by: haic0 <[email protected]>
Co-authored-by: Cursor <[email protected]>
@haic0
haic0 requested a review from a team August 20, 2026 09:43
@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs; main branch always runs both MI35X and MI300X
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 4882 --add-label <label>

PR title tags:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf] and op tags like [MLA] are left untouched. Add the no-auto-title label to opt this PR out of title tagging.

@github-actions github-actions Bot changed the title [QSA] Add paged sparse attention kernels [Triton/Gluon] [QSA] Add paged sparse attention kernels Aug 20, 2026
@haic0
haic0 marked this pull request as draft August 20, 2026 09:46
@haic0 haic0 changed the title [Triton/Gluon] [QSA] Add paged sparse attention kernels [Rocm/Gluon] [QSA] Add paged sparse attention kernels Aug 20, 2026
haic0 and others added 9 commits August 20, 2026 23:03
Add validated gfx950 Gluon kernels while retaining portable Triton fallback and limiting automatic dispatch to the faster scoring path.

Signed-off-by: haic0 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Specialize the validated Qwen-Air geometry so wider tiles, cache-all loads, and a separate tail avoid overhead while retaining guarded Triton fallback.

Signed-off-by: haic0 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Apply Black formatting and remove Ruff-reported no-op exception placeholders so the pre-check workflow can pass.

Signed-off-by: haic0 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Reject unsupported strided metadata and invalid integer options before kernel launch, with focused regression coverage. Make gfx950 performance claims directly reproducible through alternating repeated measurements and environment reporting.

Signed-off-by: haic0 <[email protected]>
Co-authored-by: Cursor <[email protected]>
@haic0
haic0 marked this pull request as ready for review August 21, 2026 14:19
@github-actions github-actions Bot changed the title [Rocm/Gluon] [QSA] Add paged sparse attention kernels [Triton/Gluon] [QSA] Add paged sparse attention kernels Aug 21, 2026
@zufayu
zufayu requested a review from vgokhale August 24, 2026 01:44
@andyluo7

andyluo7 commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Downstream SGLang Qwen3.8-Flash-Next validation on AMD Instinct MI350X
(gfx950:sramecc+:xnack-) is complete for the current code.

Environment:

  • Image: lmsysorg/sglang@sha256:6d68cd19206716cb3f1e31e2ad89cd0852d7ae614a792773c30a4277f8955c72
  • ROCm 7.2, PyTorch 2.9.1, Triton 3.7.0
  • SGLang candidate head/tree: f12fef52f / ea5aed44af3173be874f283cd053d5f5c6e8bac5
  • Runtime-tested parent head/tree: 519881df5 / 86fca326cf8064c158eb44068a66511827df95e4
    (the final candidate adds documentation only)
  • AITER runtime code: 2462d5b64
  • Current AITER PR head: 150c7bc12 (documentation-only delta from the tested runtime code)

Downstream results:

  • Patch-identical predecessor, BF16 TP2 EAGLE graph mode: GSM8K 96.8037%, 1,314/1,314
    responses, 388.737 s, 510.322 output tok/s, mean speculative accept length
    3.5710, 183 decode graph replay entries, zero missing-weight warnings, and
    zero tracebacks.
  • Exact runtime parent, FP8 TP1 EAGLE graph mode: GSM8K 96.7275%, 1,314/1,314 responses,
    613.948 s, 327.827 output tok/s, mean speculative accept length 3.5648,
    496 decode graph replay entries, zero missing-weight warnings, and zero
    tracebacks. This exact-runtime-head run exercised the nightly's canonical
    served-model, graph-replay, and complete-checkpoint-loading assertions.

The BF16 TP2 run required NCCL_P2P_DISABLE=1 and
--disable-custom-all-reduce because newly created communicators on this node
failed with hipIpcGetMemHandle failed: invalid argument. Treat that result as
model-correctness evidence, not as a normal TP2 performance result.

SGLang's direct AITER paged-QSA integration is intentionally opt-in and
eager-only. A direct-AITER FP8 TP1 eager smoke exercised both sparse-attention
and token-selection dispatch, returned the expected arithmetic answer, and
completed a forced 512-token decode without a server traceback.

Graph-mode serving does not depend on this PR: a released-AITER fallback smoke
used image-provided AITER d9e5ef7ce, mounted no #4882 files, returned the
expected answer, completed a forced 512-token decode, and replayed the decode
graph. PR #4882 therefore provides the optional direct paged-QSA acceleration,
not a graph-mode runtime dependency.

@valarLip valarLip left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed this with one question in mind: which of the four operators already exist in aiter. Answer: two overlap substantially with code already in the tree, one correctly reuses the existing path, and one is genuinely new.

1. qsa_paged_mqa_logits — aiter already has four paged MQA scorers

Existing Form MFMA sites
aiter/ops/triton/attention/pa_mqa_logits.py fp8 paged, split-KV, preshuffle, varctx schedule, gfx1250 tuning —
aiter/ops/triton/gluon/pa_mqa_logits.py Gluon, three kernel variants 251
aiter/ops/triton/attention/fp8_mqa_logits.py non-paged ragged —
aiter/ops/flydsl/kernels/mqa_logits/ FlyDSL fp8 + fp4 + fp4-prefill —

This path is under active development — dbd8bf5bd6 reworked fp8_mqa_logits buffer offsets last week. This PR adds a fifth.

The differences I can find are: bf16 instead of fp8; no per-head weights (existing computes sum_h w_h * relu(q_h·k), this computes sum_h relu(q_h·k) / sqrt(d)); and the compressed cache layout [pages, page_size, 1, head_dim]. The dtype is a real difference. The weights are an optional argument's worth of difference — deepgemm_fp8_paged_mqa_logits already takes weights as a parameter.

What makes this more than a structural concern is the kernel itself. _qsa_paged_mqa_logits_kernel scores with

score += tl.maximum(tl.sum(keys * query[None, :], axis=1), 0.0)

inside a tl.static_range over heads — an elementwise multiply and a reduction, with no tl.dot anywhere in the file. The Gluon variant has 9 MFMA sites against the existing Gluon scorer's 251. That is consistent with the reported 1.047x Gluon-over-Triton speedup: if both arms were reaching the matrix cores, the gap between a Triton and a hand-written Gluon scorer would not be 4.7%.

My suggestion would be to make this a bf16 branch of pa_mqa_logits with weights optional, rather than a parallel implementation. That inherits split-KV, preshuffle, the varctx schedule and the existing MFMA work instead of restarting from a non-MFMA baseline.

2. The scoring math already exists a second time in the tree

aiter/ops/triton/attention/dsv4_indexer.py::indexer_fwd is the same function — (relu(einsum) * w).sum(head) under a compress_ratio causal mask, followed by top-k. It is a torch/einsum reference rather than a kernel, and it is not paged, but it is the same definition.

The visibility rule is now written twice, independently:

# this PR, _qsa_paged_mqa_logits_kernel
visible_groups = min((query_position + 1) // COMPRESS_RATIO, context_len // COMPRESS_RATIO)

# dsv4_indexer._causal_mask
(p_idx + 1) * compress_ratio - 1 <= s_idx

Neither references the other, and no test compares them. If the compression semantics ever change, both have to change, and nothing in CI notices if only one does. Validating the new kernel against indexer_fwd in test_qsa.py would tie them together at essentially no cost.

3. Radix top-k — correctly reused

qsa.py:14 imports top_k_per_row_prefill from aiter.ops.topk. No duplication here.

4. qsa_expand_block_indices — genuinely new, but the description says otherwise

I couldn't find an existing "compressed group index → token index, plus the causal tail" operator anywhere in the tree (msa_block_select.py:621's pages_per_block is block→page, a different mapping). This one stands on its own.

But the summary says "Keep radix top-k and index expansion on their existing paths", while the PR adds _triton_kernels/attention/qsa_expand_indices.py (88 lines). There is no existing path for index expansion — the description and the diff disagree.

5. qsa_sparse_paged_gqa — overlapping neighbourhood, but the layout is new

Existing sparse attention entries: pa_decode_sparse.py, pa_prefill_sparse.py, unified_attention_sparse_mla.py, sparse_mla_dsv4_train.py, sparse_attention_dsv4_bwd.py, plus csrc/kernels/sparse_attn/msa/, mla_sparse_prefill.py and pa_sparse_prefill_opus.py.

The closest, pa_decode_sparse, takes unified_kv [total_pages, D] at page_size=1 with K and V shared — the MLA shape. This PR takes separate k_cache/v_cache at [pages, page_size, kv_heads, dim] with GQA grouping. That combination is not in the tree, so I think this operator is justified.

Two things I'd still raise:

The index representation is a third convention. Every existing sparse path uses kv_indices + kv_indptr (ragged CSR with -1 as the unused-tail sentinel). This one uses a fixed-width 2D [tokens, selection_width]. Callers wiring several of these together now have to convert between them.

The Gluon dispatch is pinned to one checkpoint's configuration:

group_size == _GLUON_GQA_GROUP_SIZE      # 5
logical_indices.shape[1] == _GLUON_SPARSE_WIDTH   # 2051
q.shape[2] == _GLUON_HEAD_DIM            # 128

2051 is token_topk + compress_ratio - 1 = 2048 + 4 − 1. A model shipped with a different indexer budget silently falls back to Triton with no diagnostic. pa_decode_sparse's gfx950 Gluon driver dispatches on cache.ndim and dtype and doesn't bind the selection width; matching that shape would make this survive a checkpoint change. The same applies to _GLUON_MQA_HEAD_COUNTS on the scoring side.

Summary

Of the 2410 lines, the scoring portion — qsa.py's scoring section plus the two qsa_paged_mqa_logits kernel files, roughly 800 lines — is the part I don't think should exist separately, both because pa_mqa_logits already covers it and because the new implementation doesn't use the matrix cores that the existing one does. The sparse GQA operator and the index expansion look like real additions.

Happy to be corrected on any of this if there's a constraint on the QSA cache layout that rules out extending pa_mqa_logits — that's the main thing I might be missing.

@haic0 haic0 closed this Sep 21, 2026
SamiAario-AMD added a commit that referenced this pull request Sep 28, 2026
This line already names the #4882 Triton bench from its fixup, so it cannot fold into the Gluon pin commit.

Co-authored-by: Cursor <[email protected]>
SamiAario-AMD added a commit that referenced this pull request Sep 28, 2026
SamiAario-AMD added a commit that referenced this pull request Sep 28, 2026
SamiAario-AMD added a commit that referenced this pull request Sep 28, 2026
SamiAario-AMD added a commit that referenced this pull request Sep 29, 2026
This line already names the #4882 Triton bench from its fixup, so it cannot fold into the Gluon pin commit.

Co-authored-by: Cursor <[email protected]>
SamiAario-AMD added a commit that referenced this pull request Sep 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants