Skip to content

[TRITON][GLUON] Add DSv4 sparse MLA prefill Triton and unified with MLA Gluon kernel on GFX950 - #3833

Merged
Dewei-Wang-sh merged 12 commits into
ROCm:mainfrom
leonling-ll:liyang/dsv4_sparse_attn_prefill
Jul 5, 2026
Merged

Dewei-Wang-sh merged 12 commits into
ROCm:mainfrom
leonling-ll:liyang/dsv4_sparse_attn_prefill

Conversation

@leonling-ll

@leonling-ll leonling-ll commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

This PR aims to add sparse attention prefill kernel (triton + gluon gfx950).

The triton kernels are adapted from vLLM mla_sparse_dsv4 with enabling triton autotune.

It reuses mla_decode_gluon and unifies as mla_gluon kernel for both mla decode and sparse prefill.

The prefill performance status:

Q H Kv topk triton ms triton TFLOPS gluon ms gluon TFLOPS speedup
4096 128 4096 512 1.788 192.035 0.8562 400.964 2.09x
4096 128 4096 1024 3.260 209.629 1.313 520.291 2.48x
8192 128 8192 512 3.572 191.414 1.663 411.194 2.15x
8192 128 8192 1024 6.490 212.226 2.669 516.077 2.43x

This table can be reproduce with:

python bench_sparse_attention_dsv4.py --shapes prefill

This PR is split from #3456 as the first part.

@leonling-ll
leonling-ll requested review from a team, Dewei-Wang-sh and Copilot June 22, 2026 02:55
@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: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 3833 --add-label <label>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Adds DeepSeek V4 sparse MLA prefill support to AITer, including a Triton implementation (with autotune) and an optimized Gluon (CDNA4/gfx950) kernel, plus wrappers/tests/benchmarks to validate and measure performance.

Changes:

  • Introduces Triton sparse-attention prefill kernel + ragged-index preparation kernels and autotune configs.
  • Adds a gfx950 Gluon sparse-attention prefill kernel and a wrapper that selects Gluon when available.
  • Adds an accuracy/perf test and a benchmark driver, and documents the new Gluon kernel.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
op_tests/test_sparse_attention_dsv4.py Adds a torch reference + correctness/perf test harness for sparse prefill.
op_tests/op_benchmarks/triton/bench_sparse_attention_dsv4.py Adds a Triton vs Gluon benchmark runner and reporting.
aiter/ops/triton/gluon/sparse_attention_dsv4.py Implements the gfx950 Gluon sparse MLA prefill kernel + host launcher.
aiter/ops/triton/gluon/README.md Documents the new Gluon sparse-attention kernel and how to run tests/benchmarks.
aiter/ops/triton/attention/sparse_attention_dsv4.py Adds the public wrapper API, dense→CSR packing helpers, and Gluon gating logic.
aiter/ops/triton/_triton_kernels/attention/sparse_attention_dsv4.py Adds Triton kernels for index packing and sparse prefill (autotuned).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread aiter/ops/triton/gluon/README.md Resolved
Comment thread aiter/ops/triton/gluon/README.md Resolved
Comment thread aiter/ops/triton/gluon/README.md Resolved
Comment thread aiter/ops/triton/gluon/README.md Resolved
@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch from d605eb9 to 3e79696 Compare June 22, 2026 05:31

@Dewei-Wang-sh Dewei-Wang-sh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

reuse the mla_decode_gluon to relieve maintain burden.

@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch 3 times, most recently from 356fd58 to 7813e7a Compare June 24, 2026 05:58
Prefill-only slice of the DSV4 compressed sparse attention work: bf16 KV
flat-buffer prefill kernel (Triton + persistent Gluon), the ragged-index
builders + host launcher, and the prefill test/benchmark. Decode (fp8_ds_mla
paged cache) is intentionally excluded from this branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

Resolve the code style check failure

Address Comments
Fix format

Unify dsv4 sparse attn and mla_decode
@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch from 7813e7a to e31de73 Compare June 24, 2026 07:48
@leonling-ll leonling-ll changed the title [TRITON][GLUON] Add DSv4 sparse MLA prefill kernel Triton + Gluon for gfx950 [TRITON][GLUON] Add DSv4 sparse MLA prefill Triton and unify MLA Gluon kernel for decode on GFX950 Jun 24, 2026
@leonling-ll leonling-ll changed the title [TRITON][GLUON] Add DSv4 sparse MLA prefill Triton and unify MLA Gluon kernel for decode on GFX950 [TRITON][GLUON] Add DSv4 sparse MLA prefill Triton and unified with MLA Gluon kernel on GFX950 Jun 24, 2026
@zufayu
zufayu requested review from yzhou103 and removed request for yzhou103 June 26, 2026 06:14
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
@Dewei-Wang-sh

Copy link
Copy Markdown
Contributor

overall, we should keep it additive and add comments about env/change, keep it concise and clear.

Address review comments

Minimize changes

The dev branch selected DeepSeek V4 sparse prefill via a `mode="decode" |
"dsv4-prefill"` string that drove a separate wrapper branch duplicating the
whole bh64 decode setup. Replace it with a `has_pe=True` flag (HAS_PE=False =>
prefill) and collapse the duplicated branch back onto main's single-path
decode wrapper, adding prefill support as minimal inline guards:

- q_pe may be None (fixed head_dim_kpe=64), small `if not has_pe` block aliases
  the unused q_pe/k_pe placeholders and forces kv_pe_offset=0 / use_2d_view=False
- bh64 regime: has_pe keeps the split auto-pick + asserts; else NUM_KV_SPLITS=1
  with a batch % 64 guard
- unified bh64 grid (cdiv(batch, NUM_XCDS) * NUM_KV_SPLITS) covers both paths

Callers (sparse_attention_dsv4, bench_sparse_attention_dsv4) pass has_pe=False.

Verified on gfx950: test_mla decode (bh64/bh16bn64/bh16bn128, +lse/varlen) and
test_sparse_attention_dsv4 prefill (+sink) all pass; benchmark shows prefill is
performance-neutral vs the pre-refactor version (within +-1%).
@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch from 708895d to 0f4d2e2 Compare July 2, 2026 09:00
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
@leonling-ll
leonling-ll requested a review from Dewei-Wang-sh July 2, 2026 09:05
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
Comment thread aiter/ops/triton/gluon/mla_gluon.py Resolved
@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch 2 times, most recently from cd2912a to bdbd317 Compare July 3, 2026 04:32
@leonling-ll
leonling-ll force-pushed the liyang/dsv4_sparse_attn_prefill branch from bdbd317 to 87e062c Compare July 3, 2026 04:55

@Dewei-Wang-sh Dewei-Wang-sh left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

@Dewei-Wang-sh
Dewei-Wang-sh merged commit b50066a into ROCm:main Jul 5, 2026
56 checks passed
@leonling-ll
leonling-ll deleted the liyang/dsv4_sparse_attn_prefill branch July 6, 2026 02:26
wangye805 added a commit that referenced this pull request Aug 18, 2026
Adds the training backward for the DeepSeek-V4 sparse MLA attention on gfx950
(CDNA4). This is the counterpart to the DSv4 sparse prefill forward added in
#3833; aiter had no sparse-MLA backward before this.

Same op contract as the forward's has_pe=False path: shared-KV GQA with
K == V == kv as one dense 512-wide tensor, RoPE applied in place caller-side,
scale 1/sqrt(512), attn_sink folded into the softmax denominator only, and
topk_indices == -1 masked out.

    from aiter.ops.triton.gluon.mla_gluon import mla_gluon
    from aiter.ops.triton.attention.sparse_attention_dsv4_bwd import (
        sparse_mla_bwd_dsv4,
    )

    o, lse = mla_gluon(..., has_pe=False, attn_sink=sink, return_lse=True)
    dq, dkv, d_sink = sparse_mla_bwd_dsv4(q, kv, do, o, lse, topk, attn_sink=sink)

mla_gluon's lse is already sink-inclusive (the sink is folded into e_max/e_sum
before lse = e_max + log(e_sum)), which is the convention this backward expects,
so the two compose directly with no adaptation.

Five kernels plus one torch reduction:

  delta        triton   rowsum(O*dO), streams bf16 and accumulates fp32
  dQ           gluon    one LDS read of the gathered KV feeds both the S and dP
                        MFMAs; also emits this chunk's dS / P
  dKV-interm   gluon    contracts over all heads inside one MFMA pair, Q/dO
                        transposed once into registers, D split across grid.y
  CSR build    torch    sort + searchsorted on int16-narrowed keys
  dKV gather   triton   atomic-free -- the scatter is inverted so each KV row
                        gathers its own contributors
  d_sink       torch    26 us

num_kv >= T is supported, so a compressed pool (kv rows T..num_kv-1) works.
R_CHUNK splits the rank dimension and defaults to unchunked; it exists only to
bound the interm intermediate (T*topk*512 bf16, 2.0 GiB at T=4096 topk=512) and
costs a dQ read-modify-write between chunks plus one CSR build per chunk.

Performance (MI355X, T=4096 H=128 topk=512, realistic SWA(128)+pool top-k),
against the Primus-Turbo FlyDSL backward on identical tensors in one process:

                        ours      flydsl
  per-kernel sum      3.380 ms   3.223 ms     407 vs 426 TFLOPS
  end-to-end          3.238 ms   3.471 ms     424 vs 396 TFLOPS

Read that as parity: the two differ mainly in how much each allocates per call.

Correctness: cos > 0.999 on dq / dkv / d_sink against torch autograd through an
independent fp32 reference forward, across H in {64,128}, pool and no-pool,
chunked and unchunked, with and without attn_sink.

Note the test skips on non-gfx950, so it will not exercise anything unless CI
has a CDNA4 runner. It has been run on MI355X.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
yanxuer-999 added a commit to yanxuer-999/aiter that referenced this pull request Aug 19, 2026
…on->mla_gluon rename

aiter commit b50066a (2026-07-05, PR ROCm#3833 "Add DSv4 sparse MLA prefill
Triton and unified MLA Gluon kernel") merged
aiter/ops/triton/gluon/mla_decode_gluon.py into a new unified
aiter/ops/triton/gluon/mla_gluon.py and renamed the entry point
mla_decode_gluon -> mla_gluon. This benchmark script kept importing the old
module/function, so it has crashed with ModuleNotFoundError on every daily
CI run since build ROCm#24 (2026-07-07) and produced zero data for ~6 weeks
(confirmed via central benchmark.db: last successful row was build ROCm#22,
2026-07-05).

mla_gluon's decode-path signature is unchanged from mla_decode_gluon
(q_nope, q_pe, kv_c, o, page_table, seq_info, sm_scale, use_2d_view,
min_kv_seq_len, ...), so this is a drop-in rename with no other logic
changes needed.

Co-authored-by: Cursor <[email protected]>
wangye805 added a commit that referenced this pull request Aug 21, 2026
Adds the training backward for the DeepSeek-V4 sparse MLA attention on gfx950
(CDNA4). This is the counterpart to the DSv4 sparse prefill forward added in
#3833; aiter had no sparse-MLA backward before this.

Same op contract as the forward's has_pe=False path: shared-KV GQA with
K == V == kv as one dense 512-wide tensor, RoPE applied in place caller-side,
scale 1/sqrt(512), attn_sink folded into the softmax denominator only, and
topk_indices == -1 masked out.

    from aiter.ops.triton.gluon.mla_gluon import mla_gluon
    from aiter.ops.triton.attention.sparse_attention_dsv4_bwd import (
        sparse_mla_bwd_dsv4,
    )

    o, lse = mla_gluon(..., has_pe=False, attn_sink=sink, return_lse=True)
    dq, dkv, d_sink = sparse_mla_bwd_dsv4(q, kv, do, o, lse, topk, attn_sink=sink)

mla_gluon's lse is already sink-inclusive (the sink is folded into e_max/e_sum
before lse = e_max + log(e_sum)), which is the convention this backward expects,
so the two compose directly with no adaptation.

Five kernels plus one torch reduction:

  delta        triton   rowsum(O*dO), streams bf16 and accumulates fp32
  dQ           gluon    one LDS read of the gathered KV feeds both the S and dP
                        MFMAs; also emits this chunk's dS / P
  dKV-interm   gluon    contracts over all heads inside one MFMA pair, Q/dO
                        transposed once into registers, D split across grid.y
  CSR build    torch    sort + searchsorted on int16-narrowed keys
  dKV gather   triton   atomic-free -- the scatter is inverted so each KV row
                        gathers its own contributors
  d_sink       torch    26 us

num_kv >= T is supported, so a compressed pool (kv rows T..num_kv-1) works.
R_CHUNK splits the rank dimension and defaults to unchunked; it exists only to
bound the interm intermediate (T*topk*512 bf16, 2.0 GiB at T=4096 topk=512) and
costs a dQ read-modify-write between chunks plus one CSR build per chunk.

Performance (MI355X, T=4096 H=128 topk=512, realistic SWA(128)+pool top-k),
against the Primus-Turbo FlyDSL backward on identical tensors in one process:

                        ours      flydsl
  per-kernel sum      3.380 ms   3.223 ms     407 vs 426 TFLOPS
  end-to-end          3.238 ms   3.471 ms     424 vs 396 TFLOPS

Read that as parity: the two differ mainly in how much each allocates per call.

Correctness: cos > 0.999 on dq / dkv / d_sink against torch autograd through an
independent fp32 reference forward, across H in {64,128}, pool and no-pool,
chunked and unchunked, with and without attn_sink.

Note the test skips on non-gfx950, so it will not exercise anything unless CI
has a CDNA4 runner. It has been run on MI355X.
wangye805 added a commit that referenced this pull request Aug 21, 2026
Adds the training backward for the DeepSeek-V4 sparse MLA attention on gfx950
(CDNA4). This is the counterpart to the DSv4 sparse prefill forward added in
#3833; aiter had no sparse-MLA backward before this.

Same op contract as the forward's has_pe=False path: shared-KV GQA with
K == V == kv as one dense 512-wide tensor, RoPE applied in place caller-side,
scale 1/sqrt(512), attn_sink folded into the softmax denominator only, and
topk_indices == -1 masked out.

    from aiter.ops.triton.gluon.mla_gluon import mla_gluon
    from aiter.ops.triton.attention.sparse_attention_dsv4_bwd import (
        sparse_mla_bwd_dsv4,
    )

    o, lse = mla_gluon(..., has_pe=False, attn_sink=sink, return_lse=True)
    dq, dkv, d_sink = sparse_mla_bwd_dsv4(q, kv, do, o, lse, topk, attn_sink=sink)

mla_gluon's lse is already sink-inclusive (the sink is folded into e_max/e_sum
before lse = e_max + log(e_sum)), which is the convention this backward expects,
so the two compose directly with no adaptation.

Five kernels plus one torch reduction:

  delta        triton   rowsum(O*dO), streams bf16 and accumulates fp32
  dQ           gluon    one LDS read of the gathered KV feeds both the S and dP
                        MFMAs; also emits this chunk's dS / P
  dKV-interm   gluon    contracts over all heads inside one MFMA pair, Q/dO
                        transposed once into registers, D split across grid.y
  CSR build    torch    sort + searchsorted on int16-narrowed keys
  dKV gather   triton   atomic-free -- the scatter is inverted so each KV row
                        gathers its own contributors
  d_sink       torch    26 us

num_kv >= T is supported, so a compressed pool (kv rows T..num_kv-1) works.
R_CHUNK splits the rank dimension and defaults to unchunked; it exists only to
bound the interm intermediate (T*topk*512 bf16, 2.0 GiB at T=4096 topk=512) and
costs a dQ read-modify-write between chunks plus one CSR build per chunk.

Performance (MI355X, T=4096 H=128 topk=512, realistic SWA(128)+pool top-k),
against the Primus-Turbo FlyDSL backward on identical tensors in one process:

                        ours      flydsl
  per-kernel sum      3.380 ms   3.223 ms     407 vs 426 TFLOPS
  end-to-end          3.238 ms   3.471 ms     424 vs 396 TFLOPS

Read that as parity: the two differ mainly in how much each allocates per call.

Correctness: cos > 0.999 on dq / dkv / d_sink against torch autograd through an
independent fp32 reference forward, across H in {64,128}, pool and no-pool,
chunked and unchunked, with and without attn_sink.

Note the test skips on non-gfx950, so it will not exercise anything unless CI
has a CDNA4 runner. It has been run on MI355X.
wangye805 added a commit that referenced this pull request Aug 25, 2026
* [TRITON][GLUON][GFX950][DSV4] Sparse MLA training backward

Adds the training backward for the DeepSeek-V4 sparse MLA attention on gfx950
(CDNA4). This is the counterpart to the DSv4 sparse prefill forward added in
#3833; aiter had no sparse-MLA backward before this.

Same op contract as the forward's has_pe=False path: shared-KV GQA with
K == V == kv as one dense 512-wide tensor, RoPE applied in place caller-side,
scale 1/sqrt(512), attn_sink folded into the softmax denominator only, and
topk_indices == -1 masked out.

    from aiter.ops.triton.gluon.mla_gluon import mla_gluon
    from aiter.ops.triton.attention.sparse_attention_dsv4_bwd import (
        sparse_mla_bwd_dsv4,
    )

    o, lse = mla_gluon(..., has_pe=False, attn_sink=sink, return_lse=True)
    dq, dkv, d_sink = sparse_mla_bwd_dsv4(q, kv, do, o, lse, topk, attn_sink=sink)

mla_gluon's lse is already sink-inclusive (the sink is folded into e_max/e_sum
before lse = e_max + log(e_sum)), which is the convention this backward expects,
so the two compose directly with no adaptation.

Five kernels plus one torch reduction:

  delta        triton   rowsum(O*dO), streams bf16 and accumulates fp32
  dQ           gluon    one LDS read of the gathered KV feeds both the S and dP
                        MFMAs; also emits this chunk's dS / P
  dKV-interm   gluon    contracts over all heads inside one MFMA pair, Q/dO
                        transposed once into registers, D split across grid.y
  CSR build    torch    sort + searchsorted on int16-narrowed keys
  dKV gather   triton   atomic-free -- the scatter is inverted so each KV row
                        gathers its own contributors
  d_sink       torch    26 us

num_kv >= T is supported, so a compressed pool (kv rows T..num_kv-1) works.
R_CHUNK splits the rank dimension and defaults to unchunked; it exists only to
bound the interm intermediate (T*topk*512 bf16, 2.0 GiB at T=4096 topk=512) and
costs a dQ read-modify-write between chunks plus one CSR build per chunk.

Performance (MI355X, T=4096 H=128 topk=512, realistic SWA(128)+pool top-k),
against the Primus-Turbo FlyDSL backward on identical tensors in one process:

                        ours      flydsl
  per-kernel sum      3.380 ms   3.223 ms     407 vs 426 TFLOPS
  end-to-end          3.238 ms   3.471 ms     424 vs 396 TFLOPS

Read that as parity: the two differ mainly in how much each allocates per call.

Correctness: cos > 0.999 on dq / dkv / d_sink against torch autograd through an
independent fp32 reference forward, across H in {64,128}, pool and no-pool,
chunked and unchunked, with and without attn_sink.

Note the test skips on non-gfx950, so it will not exercise anything unless CI
has a CDNA4 runner. It has been run on MI355X.

* Drop the _be suffix from the dKV gather

The suffix distinguished this kernel from an earlier one-entry-at-a-time gather that is not in
this tree, so in-tree it only reads as an unexplained abbreviation.
`_bwd_dkv_gather_acc_v4_be` -> `_bwd_dkv_gather_acc_v4`, `dkv_gather_acc_be` -> `dkv_gather_acc`.

The kernel docstring compared itself against that absent kernel, which after the rename would
have been self-referential; it now states the same reasoning as a design note -- carrying
BLOCK_E entries per iteration widens the load to dwordx4 and cuts the trip count on the long
runs a realistic top-k produces, and the gather needs both.

No functional change. 6/6 tests pass on gfx950 (MI355X).

* Name things after what they are, not what they were

Three symbols carried a suffix that only made sense against an earlier variant that was never
part of this tree, so in-tree they read as unexplained abbreviations:

  build_inverted_topk_fast          -> build_inverted_topk
  _dkv_interm_v4_bd_kernel          -> _dkv_interm_v4_kernel
  sparse_mla_bwd_dkv_interm_v4_bd   -> sparse_mla_bwd_dkv_interm_v4

Two of their docstrings pointed at those absent variants ("bit-identical to the reference
below", "vs 1.631 for dkv_interm_v4", "did NOT matter in the old kernel"). Nothing below or
elsewhere in the tree matched, so the comparisons are restated as standalone reasoning: why
int16 keys plus searchsorted are the right formulation, and why MFMA_K only pays once the D
split takes the kernel off the bandwidth ceiling.

Also `ar` -> `row_ids` in the CSR build, with a note that its dtype must match the sort key --
that is why it is constructed inside each branch rather than once above them.

No functional change. 6/6 tests pass on gfx950 (MI355X).

* Fold the Triton kernels into the Gluon module; drop the _gluon suffix

`_triton_kernels/` holds the Triton *implementation* of an op, which a public wrapper can
select or fall back to -- `attention/pa_mqa_logits.py` picks between the Gluon kernel and the
`_triton_kernels/` one at import time. Our delta and CSR-gather kernels are not that: there is
no Triton backward to fall back to, they are the memory-bound phases of this one kernel.

Filing them under `_triton_kernels/attention/sparse_attention_dsv4_bwd.py` put them directly
next to `_triton_kernels/attention/sparse_attention_dsv4.py`, which IS the forward's Triton
path, so the pair read as a Triton fwd/bwd that does not exist. They now live beside the Gluon
kernels they serve, which is what every other Gluon module here does -- mla_gluon, pa_decode_gluon
and pa_mqa_logits all keep their plain @triton.jit helpers inline and none import from
`_triton_kernels/`.

The `_gluon` suffix goes with it: the file is already in `gluon/`, four of the seven modules
there carry no suffix, and `pa_mqa_logits` is the same basename in all three trees without one.
Same for `sparse_mla_bwd_dq_gluon` -> `sparse_mla_bwd_dq`, which its sibling never had.

No functional change. 6/6 tests pass on gfx950 (MI355X).

* Reject an R_CHUNK that does not divide TOPK

R_CHUNK was only checked for being a multiple of 32, so a value like 192 against TOPK=512 was
accepted and left a 128-wide tail chunk. That is wrong in three places at once, and none of
them raise:

  * both Gluon kernels take the chunk width as a constexpr and mask the top-k load against
    R_CHUNK rather than against TOPK, so the tail iteration reads past the end of each row --
    into the next token's indices for tokens 0..T-2, and past the tensor entirely for the last
    one, which faults the GPU (measured at T=128 H=64 topk=128 R_CHUNK=96);
  * the CSR build is handed `topk_indices[:, r:r+R_CHUNK]`, which torch clamps to the narrower
    tail, so its entries are encoded against that width;
  * the gather consumes those entries against interm, which is still R_CHUNK wide, so every
    entry past the first token addresses the wrong row.

The default path (R_CHUNK=None -> TOPK) and the previously tested chunked case both divide, so
this never surfaced. Handling a narrower tail instead would cost a second kernel compile per
shape for a knob whose only job is bounding the interm buffer, so the divisor is required.

Adds a test for the case that clears the tile-width check but not this one (96 against TOPK=128).
7/7 tests pass on gfx950 (MI355X).

* Add kernel reprs and fill in the input validation

Both from review feedback on the PR.

Kernel reprs follow `_gluon_kernels/gfx950/attention/pa_decode_sparse.py`: a `make_kernel_repr`
object per kernel naming its constexprs, passed as `repr=` to the jit decorator. Note the DSv4
forward does not do this -- neither the Triton path nor `mla_gluon` -- but the same-arch Gluon
decode does and so do ~20 other kernel modules, so this reads as an omission there rather than
a deliberate choice. It earns its keep on a kernel whose PR is about performance: a trace now
says which tile configuration ran instead of leaving it to be inferred.

    _dq_v4_kernel_R_CHUNK_512_BLOCK_H_64_TILE_K_32_D_512_IS_FIRST_CHUNK_1
    _delta_v4_kernel_D_512_BLOCK_R_8

Validation follows `attention/pa_prefill_sparse.py`, which is the forward's public entry:
RuntimeError with the offending value for dtype problems, assert for shape and contiguity. The
compound asserts are split so a failure says which tensor was wrong, and `lse`, `attn_sink` and
the `topk_indices` dtype are now checked at all -- previously nothing looked at them.

7/7 tests pass on gfx950 (MI355X).

* Fix the style regressions from the previous commit

Ruff and Black both went red on fb3b7ed, entirely on changes I made rather than on anything in
the kernels:

  * I001 -- the public wrapper's three `from ... import` statements were collapsed into one
    while rewriting the imports for the module merge. Ruff's own fix splits them back apart,
    so the original shape was correct; restored.
  * I001 -- placement of the new `make_kernel_repr` import.
  * C408 -- `dict()` call in the test helper added with the R_CHUNK test; now a literal.
  * Black wanted one fewer blank line after the same import.

Also brings the module docstring in line with the rest of the file and with the forward, which
writes `gfx950 (MI355X)` rather than the bare product name -- the architecture is what
constrains the kernel, the SKU is what the wall-clock was measured on, so both belong.

Verified against the CI's own versions (ruff 0.16.0, black stable) before pushing this time.
7/7 tests pass on gfx950 (MI355X).

* Address review: add an op benchmark, drop dead knobs, trim the docstrings

**Benchmark.** Review asked for a way to reproduce the performance in the PR description; the
unit tests only establish correctness. `op_tests/op_benchmarks/triton/bench_sparse_attention_dsv4_bwd.py`
is modelled on the forward's bench_sparse_attention_dsv4.py.

The top-k builder is the part worth attention. It is a sliding window plus a causally-visible
compressed pool, not uniform random, because the two are not interchangeable for this op: a
uniform top-k spreads contributors evenly over the KV rows, while the real distribution gives
the pool rows runs of a few thousand, and the dKV gather is sized for exactly those runs.
Benchmarking on uniform indices reports a gather roughly twice as fast as the real one.

`--breakdown` times each phase separately, which is what produces the per-kernel table. A
small-shape autograd check runs first so a broken kernel fails before it is timed. There is no
FlyDSL comparison column: that backward has no single entry point -- it is driven phase by
phase through compile() calls -- so wiring it in would mean carrying third-party launch code
that aiter reviewers cannot run anyway. The comparison in the PR description was measured out
of tree.

**PREFETCH.** Never anything but 0: the launcher defaulted it off and the public wrapper never
passed it, in any commit on this branch. It is a gl.constexpr, so the branch was folded at
compile time and the prefetch path never reached the ISA -- removing it changes no generated
code, and interm measures 1.136 ms against 1.138 before. The review suggested it would save a
branch in the loop; that part does not hold, the value here is that the file no longer offers a
knob that does nothing. What it would have done is software-pipeline the dS/P loads one rank
tile ahead; that was slower at BD=256, which is the configuration we ship, because the extra
live blocks cost occupancy.

**ACCUMULATE.** Likewise always True from the caller. Rather than delete it, the wrapper now
passes `accumulate=(r > 0)`: the accumulator is freshly zeroed, so the first chunk can write
instead of reading it back. This is not a speedup -- the accumulator is 10.5 MB, about 1.7 us
against a 3.2 ms pipeline, and end-to-end does not move outside noise. It makes the flag
reachable and its docstring true.

**Docstrings.** They lose the tuning history. What we measured on the way to a configuration is
not something a reader of the shipped code needs; only the configuration itself is. Same rule
applied to the CSR build, where a rejected bincount+cumsum formulation was being documented
alongside the one actually used.

7/7 tests pass on gfx950 (MI355X). Benchmark reports 3.231 ms end-to-end and 3.217 ms as the
per-kernel sum, 425 / 427 TFLOPS.

* Check that topk_indices has one row per query token

From review. Only `topk_indices.shape[1]` was read, so nothing rejected an index tensor with a
different number of rows than `q`. The dQ grid is sized from `q`, and the kernel addresses each
row as `token_idx * stride_topk_t`, so a shorter tensor is read past its end -- the same failure
mode as the R_CHUNK case: plausible-looking indices for most tokens, then off the end.

The other tensors that feed the same grid were already covered (`do` and `o` against `q.shape`,
`lse` against `(T, H)`, `attn_sink` against `(H,)`); this was the remaining gap.

8/8 tests pass on gfx950 (MI355X).

* Move the Gluon kernels to _gluon_kernels/gfx950/attention

Requested in review: `gluon/` is the older location and new Gluon kernels belong under
`_gluon_kernels/`. The arch-namespaced path also fits this kernel better than the flat one did,
since it is gfx950-only and asserts as much -- it now sits beside
`_gluon_kernels/gfx950/attention/pa_decode_sparse.py`, which has the same shape: private kernels
here, public entry under `attention/`.

Imports in the public wrapper and the benchmark follow. No `__init__.py` is added; that tree
uses namespace packages, as pa_decode_sparse already does.

The `gluon/README.md` entry goes away with it. That file scopes itself to "all kernels in this
directory", and the ops already living in `_gluon_kernels/` (pa_decode_sparse, fp8_mqa_logits)
are not listed there either, so keeping the row would have been the odd one out. There is no
README under `_gluon_kernels/` to move it to, and none is wanted; what it documented now lives
in the PR description, which gained the full signature and the shapes the wrapper enforces:

    sparse_mla_bwd_dsv4(q, kv, do, o, lse, topk_indices,
                        attn_sink=None, scale=None, R_CHUNK=None) -> (dq, dkv, d_sink)

    q, do, o      [T, H, 512]    bf16, contiguous
    kv            [num_kv, 512]  bf16, K == V, num_kv >= T (rows T.. are the compressed pool)
    lse           [T, H]         fp32, sink-inclusive, from the forward
    topk_indices  [T, TOPK]      int32, -1 marks an invalid slot
    attn_sink     [H]            fp32, optional
    R_CHUNK                      multiple of 32 and a divisor of TOPK; None = unchunked

head_dim is fixed at 512 and the op is gfx950-only; the public wrapper asserts both.

Kernels are byte-identical apart from one docstring line that referred to the old location.
8/8 tests pass and the benchmark reports 3.226 ms / 426 TFLOPS on gfx950 (MI355X), unchanged.

* Separate the kernel layers, and stop duplicating the pipeline and the reference

All from Bruno's review.

**Layering.** Kernel-layer modules in this repo import no torch -- both neighbours in
`_gluon_kernels/gfx950/attention/` have zero torch references, and so does everything under
`_triton_kernels/attention/`. Ours was the exception. The two `@gluon.jit` kernels stay in
`_gluon_kernels/gfx950/attention/`, the two `@triton.jit` kernels move to
`_triton_kernels/attention/`, and the five launchers plus the CSR build and the sink gradient
move up to `attention/sparse_attention_dsv4_bwd.py`. Both kernel modules are now torch-free with
no public functions, matching their neighbours, so the kernels can be reached without pulling in
torch.

The Triton path is `_triton_kernels/attention/`, not `_triton_kernels/gfx950/attention/` as the
comment suggested: that tree has no arch level. `pa_decode_sparse`, `fp8_mqa_logits` and `mla`
all sit arch-namespaced under `_gluon_kernels/` and flat under `_triton_kernels/`.

**Pipeline duplication.** The benchmark was restating the production orchestration -- phase
order, tile widths, workspace, and a copy of the sink-gradient expression. It now shares the
real thing: `plan_bwd()` validates and allocates, `bwd_phases()` yields `(name, thunk)` in
execution order, `sparse_mla_bwd_dsv4` runs them, and the benchmark times them one at a time.
The measurement is of the phases the op actually runs, and there is nothing left to drift. The
sink gradient lives once, on the plan object.

**Reference duplication.** The fp32 reference forward existed in both the test and the
benchmark. It moves to `aiter.test_mha_common.sparse_mla_dsv4_ref`, beside the other reference
implementations, and returns `(o, lse)` from one differentiable pass so backward values come
from autograd through it. Both callers use it; the test file loses 46 lines.

**Benchmark harness.** `triton.testing.do_bench` replaces the hand-rolled event loop -- 55 of
the 67 benchmarks here already use it. Help text added to `--cfgs` and `--skip-correctness`.

do_bench flushes L2 between repetitions, so the reported numbers move: 3.271 ms / 420 TFLOPS
end-to-end at T=4096 H=128 topk=512, against 3.229 / 426 with the previous cache-warm loop. The
per-phase figures move further for the same reason and now sum slightly above the end-to-end
number. The PR description carries the new tables.

8/8 tests pass on gfx950 (MI355X).

* Widen the int16 CSR cutoff and drop an unused benchmark parameter

Both from review.

`build_inverted_topk` gated the int16 sort key on `num_kv < 32767`. The largest value that has
to fit is `num_kv` itself (`row_ids` runs to `num_kv` inclusive), and that is exactly
`torch.iinfo(torch.int16).max`, so the boundary case was falling back to an int32 key -- an
8-pass radix sort instead of 2 -- for no reason. Now `<= torch.iinfo(torch.int16).max`, written
against the type rather than a literal.

`_print_table` took a `title` it never used, carried over from the forward's benchmark. Dropped;
the section header is already printed by the caller.

8/8 tests pass on gfx950 (MI355X).

* Reject host tensors, and give a fully-masked row a defined output

Both from review.

`plan_bwd` checked the arch but never that the tensors were on device, so a host tensor got as
far as the kernel launch and failed there. It now raises the same way the forward's entry does,
naming the offending argument and its device.

`sparse_mla_dsv4_ref` produced NaN for a row whose top-k is entirely -1 with no sink: every
contributor is masked, the denominator is 0, and the output was 0/0. Such a row now yields 0,
with the lse left at -inf, which is the honest value for a row with nothing in it. The V4 top-k
always keeps at least the token itself so the in-tree callers never reach this, but the
reference is shared from `test_mha_common` now and should not hand a caller NaN for a case it
can legitimately construct.

8/8 tests pass on gfx950 (MI355X); benchmark unchanged at 3.229 ms / 426 TFLOPS on an idle GPU.

* Reject a benchmark topk narrower than the sliding window

From review. `_build_topk_swa_pool` documents a `[T, topk]` result but returned the full
`[T, SWA]` window whenever `topk <= SWA`, so `--cfgs 4096,128,64` would have reported topk=64
in the results table while timing 128 -- and computed its TFLOPS from the number it printed.

The window is the floor of a V4 top-k, so a narrower request has no meaning; it is now an error
rather than a silently different shape. The `--cfgs` help text already stated the constraint,
which is exactly the sort of thing that should be enforced rather than documented. The
`n_pool <= 0` branch becomes `n_pool == 0`, the only case it can still see.

The default configurations are unaffected: all three have topk >= 128.

* Validate attn_sink, and mark the plan helpers private

Two suppressed review comments on the last round, both fair.

`attn_sink` is optional, so it sat outside the device sweep added for the required tensors and
was only shape-checked -- yet `compute_d_sink` does GPU math with it, so a host or non-fp32 sink
failed late and unhelpfully. It is now checked the same way as the rest.

`plan_bwd` / `bwd_phases` exist so the benchmark can time the phases the op actually runs, not
as API. They read as public in a public wrapper module, so they are `_plan_bwd` / `_bwd_phases`
now, leaving `sparse_mla_bwd_dsv4` as the only supported entry -- which is what `__all__`
already said. The benchmark importing the private names matches what the other benchmarks here
do with kernel-layer symbols.

8/8 tests pass on gfx950 (MI355X); benchmark 3.231 ms / 425 TFLOPS on an idle GPU.
yanxuer-999 added a commit to yanxuer-999/aiter that referenced this pull request Sep 15, 2026
…on->mla_gluon rename

aiter commit b50066a (2026-07-05, PR ROCm#3833 "Add DSv4 sparse MLA prefill
Triton and unified MLA Gluon kernel") merged
aiter/ops/triton/gluon/mla_decode_gluon.py into a new unified
aiter/ops/triton/gluon/mla_gluon.py and renamed the entry point
mla_decode_gluon -> mla_gluon. This benchmark script kept importing the old
module/function, so it has crashed with ModuleNotFoundError on every daily
CI run since build ROCm#24 (2026-07-07) and produced zero data for ~6 weeks
(confirmed via central benchmark.db: last successful row was build ROCm#22,
2026-07-05).

mla_gluon's decode-path signature is unchanged from mla_decode_gluon
(q_nope, q_pe, kv_c, o, page_table, seq_info, sm_scale, use_2d_view,
min_kv_seq_len, ...), so this is a drop-in rename with no other logic
changes needed.

Co-authored-by: Cursor <[email protected]>
yanxuer-999 added a commit to yanxuer-999/aiter that referenced this pull request Oct 15, 2026
…on->mla_gluon rename

aiter commit b50066a (2026-07-05, PR ROCm#3833 "Add DSv4 sparse MLA prefill
Triton and unified MLA Gluon kernel") merged
aiter/ops/triton/gluon/mla_decode_gluon.py into a new unified
aiter/ops/triton/gluon/mla_gluon.py and renamed the entry point
mla_decode_gluon -> mla_gluon. This benchmark script kept importing the old
module/function, so it has crashed with ModuleNotFoundError on every daily
CI run since build ROCm#24 (2026-07-07) and produced zero data for ~6 weeks
(confirmed via central benchmark.db: last successful row was build ROCm#22,
2026-07-05).

mla_gluon's decode-path signature is unchanged from mla_decode_gluon
(q_nope, q_pe, kv_c, o, page_table, seq_info, sm_scale, use_2d_view,
min_kv_seq_len, ...), so this is a drop-in rename with no other logic
changes needed.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 7ad610b)
yanxuer-999 added a commit to yanxuer-999/aiter that referenced this pull request Oct 22, 2026
…on->mla_gluon rename

aiter commit b50066a (2026-07-05, PR ROCm#3833 "Add DSv4 sparse MLA prefill
Triton and unified MLA Gluon kernel") merged
aiter/ops/triton/gluon/mla_decode_gluon.py into a new unified
aiter/ops/triton/gluon/mla_gluon.py and renamed the entry point
mla_decode_gluon -> mla_gluon. This benchmark script kept importing the old
module/function, so it has crashed with ModuleNotFoundError on every daily
CI run since build ROCm#24 (2026-07-07) and produced zero data for ~6 weeks
(confirmed via central benchmark.db: last successful row was build ROCm#22,
2026-07-05).

mla_gluon's decode-path signature is unchanged from mla_decode_gluon
(q_nope, q_pe, kv_c, o, page_table, seq_info, sm_scale, use_2d_view,
min_kv_seq_len, ...), so this is a drop-in rename with no other logic
changes needed.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 7ad610b)
yanxuer-999 added a commit to yanxuer-999/aiter that referenced this pull request Nov 13, 2026
…on->mla_gluon rename

aiter commit b50066a (2026-07-05, PR ROCm#3833 "Add DSv4 sparse MLA prefill
Triton and unified MLA Gluon kernel") merged
aiter/ops/triton/gluon/mla_decode_gluon.py into a new unified
aiter/ops/triton/gluon/mla_gluon.py and renamed the entry point
mla_decode_gluon -> mla_gluon. This benchmark script kept importing the old
module/function, so it has crashed with ModuleNotFoundError on every daily
CI run since build ROCm#24 (2026-07-07) and produced zero data for ~6 weeks
(confirmed via central benchmark.db: last successful row was build ROCm#22,
2026-07-05).

mla_gluon's decode-path signature is unchanged from mla_decode_gluon
(q_nope, q_pe, kv_c, o, page_table, seq_info, sm_scale, use_2d_view,
min_kv_seq_len, ...), so this is a drop-in rename with no other logic
changes needed.

Co-authored-by: Cursor <[email protected]>
(cherry picked from commit 7ad610b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants