Skip to content

[Triton/Gluon] [GFX12] Gluon a8w8 Sparse MLA - #6116

Merged
azaidy merged 37 commits into
mainfrom
shaoclee/pa_decode_sparse_fp8
Oct 22, 2026
Merged

azaidy merged 37 commits into
mainfrom
shaoclee/pa_decode_sparse_fp8

Conversation

@k50112113

@k50112113 k50112113 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds a8w8 sparse MLA for gfx1250 with vLLM-compatible kv_cache related kernels with the ATOM-style kv_cache format support [448B + 72B + 50B padding + 642B]

Notice on the API change:

removed use_exp2
removed kv_scales

…ng nothing

Renames so every DeepSeek-V4 op in the mxfp8 quant module carries the same
prefix, with each kernel beside its launcher:

  fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert_aligned
      -> fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert
  quantize_and_insert_k_cache
      -> fused_deepseek_v4_quantize_and_insert_k_cache
  compress_norm_rope_store_triton
      -> fused_deepseek_v4_compress_norm_rope_store
  compress_norm_rope_store_two_stage_triton
      -> fused_deepseek_v4_compress_norm_rope_store_two_stage

The paged-K reader moves in from the module it arrived in, which retires:

  dsv4_dequant_gather_k_cache.dequantize_and_gather_k_cache
      -> fused_mxfp8_quant.fused_deepseek_v4_dequantize_and_gather_k_cache
  _dsv4_dequant_gather_k_cache_kernel
      -> _fused_deepseek_v4_dequant_gather_k_cache_kernel

It brought a second copy of _rec_geometry with it. The two differed only in
testing len(shape) rather than .dim(); the surviving copy keeps len(shape),
because vLLM's warmup hands it a TritonWarmupTensor, which carries a shape
and is not a torch.Tensor.

Tests
-----
The writer/reader pair had none, and the 640-byte aligned record -- the only
one production uses -- had no coverage below the end-to-end level:

  - round-trip on both layouts against a torch decode of the stored bytes,
    with the writer's quantization error bounded separately, so a layout bug
    cannot hide inside the tolerance that the quantization needs
  - the two layouts must decode bit-identically, at zero tolerance
  - the single-pass and two-stage compressors must write the same cache

The last one matters because aiter's two compressor kernels each carry ~33
lines of full-width GPT-J RoPE with no counterpart in vLLM, so nothing
compared them against anything.

bench_fused_kv_compress_sparse_attn measured nothing
----------------------------------------------------
It built positions=0, and a token only emits when
(position + 1) % compress_ratio == 0, so every program took the early exit
and not one byte of the KV cache was written. Confirmed directly before the
fix: zero bytes changed by a launch. Every figure it has printed was launch
overhead.

Three things were wrong, all of which only mattered once tokens ran:

  positions      now cycle the emitting values, bounded so the gather stays
                 inside the block table
  block_table    was all zeros, so every token re-read row 0 and the whole
                 gather came from cache; now spread over the state cache
  counted_bytes  counted one state row per token, but an emitting token
                 reads (1 + overlap) * compress_ratio rows twice, once for
                 scores and once for values -- understating the read side by
                 ~256x at cr128

With that fixed the split's gate is measured rather than assumed:

  cr128  tokens=1024   single 218.1us   two-stage 43.6us   5.00x
  cr4    tokens=256    single   3.8us   two-stage  5.5us   0.70x

which is why the caller restricts the two-stage path to cr >= 128.

New benchmarks
--------------
bench_fused_deepseek_v4_k_cache
    writer and reader, both record layouts. Aligned writes ~43% faster than
    packed (1022 vs 716 GB/s at seq 1024).

bench_fused_deepseek_v4_qnorm_rope_kv_insert
    the producer with and without the fused Q pack, against the standalone
    pack as a second kernel. Fusing is 1.23-1.88x, which is the question the
    caller's pack-fusion switch exists to answer.

Noted, not fixed: the writer's use_fnuz guard reads `if not True:`, a port
slip from vLLM's current_platform.is_fp8_fnuz(), so it never fires.
@k50112113
k50112113 requested a review from a team October 3, 2026 02:01
@github-actions

github-actions Bot commented Oct 3, 2026

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 (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
multigpu Aiter multi-GPU tests on the 8-GPU runner
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 6116 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

@github-actions github-actions Bot 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.

Remaining comments which cannot be posted as a review comment to avoid GitHub Rate Limit

ruff

⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"cr128": dict(state_width=512, compress_ratio=128, overlap=False,
block_size=8, state_mid=8, kv_page=2,
block_table_width=4096),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

"cr4": dict(state_width=1024, compress_ratio=4, overlap=True,
block_size=4, state_mid=4, kv_page=64,
block_table_width=8192),


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

return dict(
state_cache=state_cache,
num_actual=a.tokens,
token_to_req_indices=torch.zeros(a.tokens, dtype=torch.int32,
device=device),
positions=emitting_positions(a, device),
slot_mapping=slot_mapping,
# Spread over the state cache rather than pointing every gather at
# row 0: an emitting token reads (1 + overlap) * compress_ratio rows,
# and with one shared row they all come from cache, which flatters
# the bandwidth. Entries stay below state_cache.shape[0], which is
# what bounds the index.
block_table=torch.randint(0, a.tokens, (a.tokens, a.block_table_width),
dtype=torch.int32, device=device),
block_size=a.block_size,
state_width=a.state_width,
cos_sin_cache=cos_sin_cache,
kv_cache=kv_cache,
k_cache_metadata=SimpleNamespace(slot_mapping=slot_mapping),
pdl_kwargs={},
head_dim=a.head_dim,
rope_head_dim=a.rope_dim,
compress_ratio=a.compress_ratio,
overlap=a.overlap,
use_fp4_cache=False,
rms_norm_weight=torch.ones(a.head_dim, dtype=torch.bfloat16,
device=device),
rms_norm_eps=a.rms_eps,
quant_block=a.quant_block,
token_stride=a.token_stride,
scale_dim=a.scale_dim,
)


⚠️ [ruff] <UP031> reported by reviewdog 🐶
Use format specifiers instead of percent format

print("compressor variant=%s head_dim=%d rope_dim=%d token_stride=%d "
"state_width=%d compress_ratio=%d overlap=%s"


⚠️ [ruff] <UP031> reported by reviewdog 🐶
Use format specifiers instead of percent format

print("%-10s %-12s %-12s %-12s %-10s %s"


⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable kwargs

fused_deepseek_v4_compress_norm_rope_store(**kwargs)


⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable kwargs

**kwargs, num_decode_tokens=0, compress_scratch=scratch


⚠️ [ruff] <B023> reported by reviewdog 🐶
Function definition does not bind loop variable scratch

**kwargs, num_decode_tokens=0, compress_scratch=scratch


⚠️ [ruff] <UP031> reported by reviewdog 🐶
Use format specifiers instead of percent format

print("%-10d %-12.2f %-12.2f %-12.1f %-10.4f %.2fx"


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

_ULP = dict(rtol=2**-7, atol=1e-5)


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

_EXACT = dict(rtol=0, atol=0)


⚠️ [ruff] <C408> reported by reviewdog 🐶
Unnecessary dict() call (rewrite as a literal)

_CR128 = dict(
head_dim=512, rope_dim=64, quant_block=64, token_stride=_REC, scale_dim=8,
state_width=512, compress_ratio=128, overlap=False,
block_size=8, state_mid=8, kv_page=2, rows_per_block=64,
block_table_width=64, cos_sin_rows=4096, rms_eps=1e-6,
)

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.

Copilot review overview

🟡 Changes recommended

API compatibility, concurrency safety, unsupported compressor modes, and benchmark correctness issues remain unresolved.

Review effort: Balanced
Findings: 9 High severity · 16 Medium severity · 7 Low severity

Open (32)

And 12 more that still need to be addressed.

What changed in this PR

Adds gfx1250 DeepSeek-V4 a8w8 sparse MLA with ATOM-compatible and aligned vLLM KV-cache formats.

Changes:

  • Adds Q/KV quantization, compression, cache insertion, and gathering kernels.
  • Extends sparse paged decode for packed FP8 Q/KV and dual cache streams.
  • Adds correctness tests and performance benchmarks.
File Description
aiter/​ops/​triton/​attention/​pa_decode_sparse.py Adds gfx1250 packed-FP8 decode dispatch.
aiter/​ops/​triton/​quant/​fused_mxfp8_quant.py Adds public DSv4 producer and cache APIs.
aiter/​ops/​triton/​_triton_kernels/​attention/​pa_decode_sparse.py Extends split-K reduction metadata.
aiter/​ops/​triton/​_triton_kernels/​quant/​fused_mxfp8_quant.py Implements DSv4 quantization and compression kernels.
op_tests/​triton_tests/​attention/​test_pa_decode_sparse.py Tests packed, aligned, and dual-cache decode.
op_tests/​triton_tests/​quant/​test_quant_mxfp8.py Tests producer and cache formats.
op_tests/​op_benchmarks/​triton/​bench_pa_decode_sparse.py Benchmarks sparse decode providers.
op_tests/​op_benchmarks/​triton/​bench_fused_kv_compress_sparse_attn.py Benchmarks KV compression paths.
op_tests/​op_benchmarks/​triton/​bench_fused_deepseek_v4_qnorm_rope_kv_insert.py Benchmarks fused Q/KV production.
op_tests/​op_benchmarks/​triton/​bench_fused_deepseek_v4_k_cache.py Benchmarks K-cache read/write.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@cagrikymk

Copy link
Copy Markdown
Contributor

@k50112113

Clude generated review:

My take:
I think we dont ecven have to support non exp2 path as I dont expect that to be faster for any arch.

Private wrapper name (_pa_decode_sparse_v4_2buff can be modified to be consistent with the other private wrappers. Naming it _pa_decode_sparse_gfx1250 would be more consistent.

Correctness

1. NaN when a tile has no valid keys (Gluon v4 kernel, ~L2135–2148)
Only alpha is guarded against m_new == -inf. p = gl.exp2(scores - m_new[:, None]) isn't. When KV_SPLITS > 1, m_i starts at -inf. So if a split's first tile is all -1 or out-of-range slots (for example a short SWA window), p becomes -inf - (-inf) = NaN. That poisons l_i and acc. The next valid tile makes m finite, so the reduce treats the split as live and the NaN reaches the output. The comment calls such a tile "a no-op", but the code doesn't make it one. Suggest:

m_safe = gl.where(m_new == float("-inf"), 0.0, m_new)
p = gl.exp2(scores - m_safe[:, None])

The non-exp2 epilogue (~L2275) has the same gap. It can't trigger today because USE_EXP2 is always True.

2. BLOCK_H=16 workaround doesn't cover every H (wrapper ~L1337–1359)
The pin to 32 only applies to 32 <= H < 64. For H < 32 (e.g. H=16 at TP8) we still get max(next_pow2(H), 16) = 16. For H=16, T≥1024, the split heuristic gives kv_splits = 1. That is exactly the combination the comment says Triton 3.8.0 miscompiles (~1e38 garbage). H in [64,128) with T < 32 also gives 16. The existing tests only run H=16 up to T=512, which always uses ≥2 splits, so they can't catch this. Please either apply the pin for every H < 64 or reject BLOCK_H=16 && KV_SPLITS==1.

3. Gather kernel uses block_table.shape[-1] as the row stride (fused_mxfp8_quant.py wrapper L543, kernel L792)
block_table_ptr + batch_idx * max_blocks_per_seq is wrong for a column-sliced table such as block_table[:, :n], which CUDA-graph padding commonly produces. Every request after row 0 would read another request's block ids. Please pass block_table.stride(0).

4. int32 overflow in Q addressing (fused producer kernel ~L511–563, q-pack kernel L314)
(tok * padded_heads + h) * HEAD is computed in int32 and wraps at T * padded_heads >= 4M. That's T=32768 with padded_heads=128, which is reachable since the docstring routes prefill here. Please cast tok / row to int64 first.

Should fix

5. Empty token with KV_SPLITS == 1 never writes out (kernel ~L1751)
With kv_len == 0 and no extra stream, every CTA returns early, so out keeps whatever torch.empty left. With splits > 1 the reduce writes zeros. Padded CUDA-graph tokens at large T hit this. The two paths should agree, e.g. zero-fill on early exit when KV_SPLITS == 1.

6. Silently ignored arguments on gfx1250 (wrapper ~L286–311, L1282)
The v4 branch returns before the assert that rejects inv_rope_positions, inv_rope_cos_sin_cache and out_mxfp8. A caller who passes out_mxfp8 gets un-rotated bf16 output and an untouched buffer. extra_indices/extra_indptr without extra_cache are dropped the same way. Please add a guard.

7. Extra stream is read with the main stream's row strides (kernel ~L1291–1341, wrapper L1531–1532)
kv_stride_n/kvr_stride_n come from unified_kv but are also used for the extra-stream descriptors. _v4_2buff_geometry never checks extra.stride(-2) == main.stride(-2) or stride(-1) == 1. This isn't reachable through today's 640-B path, but an assert would close it.

8. fused_deepseek_v4_quantize_and_insert_k_cache assumes K rows are contiguous (kernel L636)
k_ptr + pid * input_dim together with a wrapper that only checks shape and dtype means a view like kv[:, :512] gets mis-read. Please call .contiguous() or pass the stride.

9. FNUZ fp8_max differs between the two KV writers
The fused producer uses 224.0 (wrapper L374) and the standalone insert uses 240.0 (L472). The same KV gets different scales depending on which writer ran. Neither FNUZ path is tested.

10. ctas_h > 1 multicast (kernel ~L2015, L2047–2051), off by default
The multicast for tile i+1 into buffer (i+1)%2 is issued before this iteration's cluster.arrive(). A peer CTA may still be reading tile i−1 from that buffer. Also, arrive comes before tdm.async_wait. Worth fixing before anyone enables ctas_h.

Tests

  • test_pa_decode_sparse_with_extra went from T∈{1,32,128,2437} × H=16 to T∈{128,2437} × H=128 on all arches. gfx950 loses its H=16 and small-T/high-split coverage.
  • The unified-cache test packs with .contiguous(), so blk_rows == block_size and _v4_2buff_row reduces to the identity. The paged row mapping isn't really exercised. The main (SWA) stream is never tested with a pooled per-layer stride.
  • The compressor test only compares single-pass against two-stage, and both share the same norm/quant/rope code, so there's no independent reference. It also doesn't cover the 584-B layout, overlap=True, or slot=-1.
  • There's no slot=-1 test for the standalone insert, no FNUZ coverage, and no non-contiguous K or sliced block_table. The last two would have caught update script #3 and fix err #8.

Nits

  • The MAIN_IS_WINDOW branch in the reduce is unreachable: no caller sets it and no main kernel implements it.
  • Stale comments: "3-deep gather ring" (the code has NUM_BUFFERS=2), and "eight accumulators" / "four accumulators" (there are two).
  • The commented-out mask=h_mask_out in the reduce is only safe because BLOCK_H is hard-coded to 1. Please restore the mask or assert it.

@azaidy azaidy 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!

@azaidy
azaidy merged commit 997c6ba into main Oct 22, 2026
@azaidy
azaidy deleted the shaoclee/pa_decode_sparse_fp8 branch October 22, 2026 15:18
omuhamma added a commit that referenced this pull request Nov 17, 2026
…la-640

Conflicts (both sides added code at the same place):
- fused_mxfp8_quant.py (kernel + wrapper), sparse_mla.py: keep main's
  DeepSeek-V4 / gfx950 fp8 additions and the fp8_k3_mla_640 helpers side by side.
- pa_decode_sparse.py segment count: take main's (extra-stream aware); with no
  extra stream it equals the old cdiv(kv_len, KV_SPLITS * BLOCK_K).

Follow-ups for main's pa_decode_sparse changes (#6116 and later):
- The reduce kernel is base-2 only (USE_EXP2 removed): the HAS_LSE epilogue
  now always converts m with LN2, and _forward_k3_640 no longer passes USE_EXP2.
- The reduce takes extra_indptr and HAS_EXTRA: _forward_k3_640 passes
  kv_indptr as a placeholder with HAS_EXTRA=False (no extra key stream).
- ruff/black: sorted imports in sparse_mla.py, dict literals in the K3.1 test.
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.

5 participants