Skip to content

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

Merged
azaidy merged 2 commits into
ROCm:mainfrom
mengfei-jiang:qsa-paged-sparse-attention
Oct 15, 2026
Merged

azaidy merged 2 commits into
ROCm:mainfrom
mengfei-jiang:qsa-paged-sparse-attention

Conversation

@mengfei-jiang

@mengfei-jiang mengfei-jiang commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Add QSA triton kernels for compressed-key scoring, block index expansion, and sparse paged GQA.

Source: ROCm/ATOM atom/model_ops/qwen4_exp/ops/qsa.py

Kernels:

  • _qsa_paged_mqa_logits_kernel
  • _qsa_paged_mqa_logits_mfma_kernel
  • _expand_selected_groups
  • _qsa_sparse_paged_gqa_kernel

Also includes:

  • Functional test
  • Performance benchmark

Motivation

Technical Details

Test Plan

Test Result

Submission Checklist

@mengfei-jiang
mengfei-jiang requested a review from a team October 13, 2026 06:31
@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 (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
ci:windows Windows JIT op smoke test on the gfx1201 ROCm runner
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 6469 --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 changed the title [Triton] [QSA] Add paged sparse attention kernels [Triton/Gluon] [FlyDSL] [QSA] Add paged sparse attention kernels Oct 13, 2026
@mengfei-jiang
mengfei-jiang force-pushed the qsa-paged-sparse-attention branch from df0973c to 4f02fb1 Compare October 13, 2026 06:34
@mengfei-jiang
mengfei-jiang force-pushed the qsa-paged-sparse-attention branch 2 times, most recently from 8df5dfb to 3bd2f43 Compare October 13, 2026 07:07
@Boss2002n
Boss2002n requested a balanced review from Copilot October 13, 2026 09:33

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.

🟡 Changes recommended

Architecture dispatch, page-table bounds, subgroup masking, backend scope, and test coverage have unresolved correctness issues.

3 open findings
What changed in this PR

Adds QSA paged sparse attention support, including compressed-key scoring, token selection, and sparse paged GQA.

Changes:

  • Adds Triton scoring, expansion, and sparse-attention kernels.
  • Adds an optional FlyDSL prefill scorer.
  • Adds functional tests and performance benchmarks.
File Description
aiter/​ops/​triton/​attention/​qsa.py Provides public wrappers and dispatch logic.
aiter/​ops/​triton/​_triton_kernels/​attention/​qsa.py Implements the Triton QSA kernels.
aiter/​ops/​flydsl/​kernels/​mqa_logits/​qsa_flydsl_layout.py Implements the FlyDSL MFMA scorer.
op_tests/​triton_tests/​attention/​test_qsa.py Tests causal selection and batched consistency.
op_tests/​op_benchmarks/​triton/​bench_qsa.py Benchmarks selection and sparse GQA.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread aiter/ops/triton/attention/qsa.py Resolved
@mengfei-jiang
mengfei-jiang force-pushed the qsa-paged-sparse-attention branch 3 times, most recently from c7677cb to 468d2c3 Compare October 13, 2026 12:42

@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.

Please create separate PRs for different kernel providers. Flydsl and Triton should each get their own PR. Triton tests/benches should only work on the triton kernel. For all encompassing benches/tests please place them in op_tests.

@azaidy azaidy self-assigned this Oct 13, 2026
@zufayu
zufayu requested review from azaidy and yadaish October 14, 2026 01:28
@zufayu

zufayu commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

This PR spans both backends, so it has two reviewers:

  • aiter/ops/flydsl/kernels/mqa_logits/qsa_flydsl_layout.py — FlyDSL side, @yadaish
  • aiter/ops/triton/_triton_kernels/attention/qsa.py, aiter/ops/triton/attention/qsa.py — Triton side, @azaidy

@yadaish is the primary reviewer; @azaidy please take a look at the Triton kernels. The two layouts need to stay consistent, so it's worth one of you confirming the interface matches before merge.

mengfei-jiang added a commit to mengfei-jiang/ATOM that referenced this pull request Oct 14, 2026
Replace vendored QSA scoring, selection and sparse paged GQA kernels
with imports from aiter (ROCm/aiter#6469). Delete qsa_flydsl_layout.py
(now in aiter). Utility kernels (draft metadata, compressed slots,
mRoPE, store rows, compress groups) remain local.

Co-Authored-By: Claude <[email protected]>
Add QSA triton kernels for compressed-key scoring, block index
expansion, and sparse paged GQA.

Source: ROCm/ATOM atom/model_ops/qwen4_exp/ops/qsa.py

Kernels:
- _qsa_paged_mqa_logits_kernel
- _qsa_paged_mqa_logits_mfma_kernel
- _expand_selected_groups
- _qsa_sparse_paged_gqa_kernel

Also includes:
- Functional test
- Performance benchmark

Co-Authored-By: Claude <[email protected]>
@mengfei-jiang
mengfei-jiang force-pushed the qsa-paged-sparse-attention branch from 468d2c3 to 96b9348 Compare October 14, 2026 03:06
@github-actions github-actions Bot changed the title [Triton/Gluon] [FlyDSL] [QSA] Add paged sparse attention kernels [Triton/Gluon] [QSA] Add paged sparse attention kernels Oct 14, 2026
@github-actions github-actions Bot removed the FlyDSL label Oct 14, 2026
valarLip
valarLip previously approved these changes Oct 14, 2026

@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.

LGTM

@mengfei-jiang

mengfei-jiang commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Please create separate PRs for different kernel providers. Flydsl and Triton should each get their own PR. Triton tests/benches should only work on the triton kernel. For all encompassing benches/tests please place them in op_tests.

@azaidy Done, please take another look.

Comment thread aiter/ops/triton/attention/qsa.py Resolved
Move FlyDSL dispatch and qsa_select_paged_tokens out of the triton
wrapper into aiter/ops/qsa.py, so the triton wrapper stays triton-only.

- aiter/ops/qsa.py: top-level dispatch (FlyDSL + triton fallback)
- aiter/ops/triton/attention/qsa.py: triton-only wrappers
- Remove qsa_select_paged_tokens and FlyDSL references from triton wrapper
- Update test and bench imports

Co-Authored-By: Claude <[email protected]>
@mengfei-jiang
mengfei-jiang force-pushed the qsa-paged-sparse-attention branch from 34811bb to 4dde2ce Compare October 15, 2026 08:35

@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! Thanks for making the change @mengfei-jiang

@azaidy
azaidy merged commit a96b202 into ROCm:main Oct 15, 2026
mengfei-jiang added a commit to mengfei-jiang/ATOM that referenced this pull request Oct 22, 2026
Replace vendored QSA scoring, selection and sparse paged GQA kernels
with imports from aiter (ROCm/aiter#6469). Delete qsa_flydsl_layout.py
(now in aiter). Utility kernels (draft metadata, compressed slots,
mRoPE, store rows, compress groups) remain local.

Co-Authored-By: Claude <[email protected]>
mengfei-jiang added a commit to mengfei-jiang/ATOM that referenced this pull request Oct 29, 2026
Replace vendored QSA scoring, selection and sparse paged GQA kernels
with imports from aiter (ROCm/aiter#6469). Delete qsa_flydsl_layout.py
(now in aiter). Utility kernels (draft metadata, compressed slots,
mRoPE, store rows, compress groups) remain local.

Co-Authored-By: Claude <[email protected]>
valarLip pushed a commit that referenced this pull request Nov 9, 2026
…decode scorer (#7008)

* [Triton/Gluon] [QSA] FP8 KV and FP8 / FP4 index caches, stacked-head decode scorer

Bring the QSA operator changes of ROCm/ATOM#2652 into the Triton QSA
kernels that #6469 / #6515 ported from ATOM before that PR landed.

- qsa_store_quantized_rows: FP8 rows with one FP32 scale per (token,
  head) = row amax / FP8 max (K and V in one launch), and MXFP4 rows
  (packed E2M1 pairs, one E8M0 exponent per 32 dims, rounded up so a
  group never clips). qsa_cache_row_layout describes the stored row.
- qsa_sparse_paged_gqa(k_scale=, v_scale=): reads E4M3 K/V tiles,
  multiplies the key scale into its score column and folds the value
  scale into the probability before PV; FP8 has its own tile config.
- qsa_paged_mqa_logits / qsa_select_paged_tokens(compressed_k_scale=):
  FP8 (row scale) and MXFP4 compressed index keys in the CUDA-core,
  prefill MFMA and stacked scorers. FlyDSL stays BF16-only.
- stacked_decode=True: decode-sized calls (<= 256 rows) score with an
  MFMA kernel that stacks 4 rows x 4 index heads into M = 16, so a
  request's keys are read once per verify instead of once per row.
  Off by default, so existing BF16 callers keep their kernels.

The BF16 path and the existing signatures are unchanged; new arguments
are trailing keywords with defaults.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Address review: page-table bound, CPU import, writer checks

- Scorers: the MFMA and stacked kernels mask page-table loads with
  columns < num_columns as well as the rounded table width, so a narrow
  table (for example [1, 3] at page size 4) is not read past its end.
- Without a visible GPU, aiter.dtypes.fp8 is a uint8 placeholder. FP8_MAX
  is None there instead of a module-level torch.finfo error, so both QSA
  modules import on CPU; FP8 layouts raise until a GPU FP8 dtype exists.
- qsa_store_quantized_rows rejects non-contiguous, non-integer or
  multi-dim slots (the writers read slots[row] without a stride), a scale
  plane whose shape does not match the cache, and a second K/V plane whose
  cache or scale shape or dtype differs from the first.
- Tests for each case: a [1, 3] page table through the CUDA-core, MFMA and
  stacked scorers in BF16 / FP8 / FP4, bad slots and planes for both
  writers, and an import in a subprocess with no visible GPU.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Quantize FP4 index rows with _mxfp4_quant_op

Address review: drop the QSA writer's own E2M1 encoder and inline E8M0
math, and extend aiter's MXFP4 quantizer to cover what QSA needs.

- _mxfp4_quant_op / _mxfp4_pack_op / _mxfp4_pack_bits gain
  ROUNDING_MODE (0 = ties to nearest even, the existing behavior and
  default; 1 = ties away from zero). Both the normal and the denormal
  branch of the bit path implement mode 1; USE_ASM with mode 1 is a
  static_assert, since v_cvt_scalef32_pk_fp4_f32 only rounds to even.
- _mxfp4_ceil_scale_from_amax / _mxfp4_quant_op gain MAX_SCALE_E8M0
  (default 254 = uncapped, so inf / NaN amax keeps its NaN scale);
  only SCALING_MODE=1 accepts a cap.
- _qsa_store_rows_fp4_kernel loads the row as a [1, HEAD_DIM] tile and
  calls _mxfp4_quant_op(SCALING_MODE=1, ROUNDING_MODE=1,
  MAX_SCALE_E8M0=240): the cache bytes of ATOM's QSA writer, with E8M0
  kept within the readers' FP16 decode.
- Tests: E2M1 ties at 0.25 ... 5.0 times the scale, and the E8M0 cap.

Default arguments compile to the same instructions as before.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Reject partial second planes and mismatched scale planes

- qsa_store_quantized_rows: second_cache, second_scale and second_values go
  together or not at all; a partial set used to be ignored without an error.
- qsa_paged_mqa_logits: compressed_k_scale must have the full shape and dtype
  of the cache's scale plane (qsa_cache_row_layout), not only its first three
  dims. A short FP4 group axis used to pass and the kernel read past each
  scale row.
- qsa_sparse_paged_gqa: v_scale must have the shape of k_scale, and a v_scale
  without an FP8 cache and k_scale is rejected.
- The CUDA-core scorer is one kernel with KEY_FMT (0 BF16, 1 FP8, 2 MXFP4),
  like the MFMA kernels, instead of a separate FP4 kernel with a copied body.
  Every variant compiles to the same instructions as before.
- test_qsa.py: tests for the rejected inputs; randn gets an explicit dtype.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Move QSA tiles to JSON, reuse _mxfp4_e8m0_to_fp32

- The stacked decode scorer's tiles and the FP8 GQA tiles move from Python
  dicts to configs/<arch>/triton/attention/qsa/DEFAULT.json, read with
  resolve_config_dir() and load_config_json(). gfx942 and gfx950 get the
  previous Python values; gfx1250 is seeded byte-identical from gfx950.
  Only the stacked and FP8 GQA paths read the file, so BF16 calls do not
  depend on it on any arch.
- The MXFP4 readers decode the group scale with
  _mxfp4_e8m0_to_fp32(e + 14) instead of a local copy. The bits are the
  same for all 256 exponents.
- The FP8 writer's kernel name includes FP8_MAX_C, which differs per arch.
- Move the CUDA-core comment from the MFMA branch to the CUDA-core launch.
- test_qsa.py: the cap test builds its values on the GPU with an explicit
  dtype, and the other float factories get a dtype too. The narrow
  page-table test uses a real [1, 3] table and no longer claims to catch a
  read of entry 3: such a read has no visible effect, and the test passes on
  the kernels without the fix as well.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Accept FP16 / FP32 caches again, check writer and GQA inputs

Review follow-up (valar-cop):
- Unquantized FP16 and FP32 caches work again in the index scorers and
  sparse GQA, as on main; 4811ba3 accepted only BF16. A scale plane passed
  with an unquantized cache is rejected.
- qsa_store_quantized_rows checks the scale plane's dtype, and raises a
  ValueError instead of view's RuntimeError when the cache or scale plane is
  a slice of a larger page pool.
- qsa_cache_row_layout("fp4", d) needs a power-of-two d >= 32, so the FP4
  scorers raise a ValueError for d = 96 instead of failing to compile.
- qsa_sparse_paged_gqa needs float32 k_scale / v_scale.
- Comments: why page_ok keeps columns < num_columns, the CUDA-core fallback,
  a one-line _tuned_tile docstring. torch.logspace in the test takes a dtype.

The compiled kernels are unchanged.

Co-authored-by: Cursor <[email protected]>

* Read the QSA tile table optionally; test more head_dims

configs/<arch>/triton/attention/qsa exists only for gfx942, gfx950 and
gfx1250, and _tuned_tile read it with required=True, so stacked_decode
and FP8 sparse GQA raised FileNotFoundError on any other arch. Load it with
required=False: without the table stacked_decode scores with the other
kernels and FP8 K/V keep the _kernel_config tiles, as BF16 does.

Tests: run the FP8 GQA case and a stacked_decode call as on gfx1100 (no
QSA config), and parametrize the quantized scoring test over head_dim
(32, 64, 128, 256) and heads (1, 2, 4), which covers FP4 at head_dim 32.

Co-authored-by: Cursor <[email protected]>

* Reuse _fp8_quant_op in the FP8 writer; fp4_utils in the test

The FP8 QSA writer computed the row amax, scale and clamp itself, which is
what _fp8_quant_op in fused_fp8_quant.py does with one group per row; K and
V repeated that code. Call _fp8_quant_op from one _store_fp8_row helper.
Scales are unchanged; at rounding ties a few bytes move one E4M3 code,
because _fp8_quant_op multiplies by 1 / scale instead of FP8_MAX / amax.

The test's MXFP4 dequant reimplemented mxfp4_to_f32 and e8m0_to_f32 from
aiter.utility.fp4_utils, which test_quant_mxfp4.py uses; use them.

Co-authored-by: Cursor <[email protected]>

* Clean up the QSA diff: one test case builder and reference, shared FP4 key-tile decode, one matrix-core launch

- test_qsa: _index_case / _stacked_case and their references become one
  _case and one _reference; the writer reject tests share _planes; the
  narrow page-table test uses them instead of its own reference.
- kernels: the MFMA and stacked scorers share _fp4_key_tile; the CUDA-core
  scorer loads unquantized Q rows with _load_q_row; duplicate comments go.
- wrapper: the stacked and MFMA scorers share one launch; the FP8 and FP4
  writers share their common arguments.

Outputs are bitwise identical to the previous commit.

Co-authored-by: Cursor <[email protected]>

* Fold the stacked QSA scorer into the MFMA kernel and share the scale-plane check

- _qsa_paged_mqa_logits_mfma_kernel takes STACK_HEADS; the stacked kernel and
  its repr are gone.
- _load_fp4_keys is the one MXFP4 key decode of the CUDA-core and MFMA scorers.
- _check_scale_plane validates the writer, scorer and GQA scale planes.
- The FP8 writer takes None for the second plane instead of HAS_SECOND.
- bench_qsa: _quantize returns one (cache, scale) pair; _scenario is gone.

Co-authored-by: Cursor <[email protected]>

* Leave existing QSA code as on main where the change does not need it

- The stacked scorer is its own kernel again, so the prefill MFMA kernel only
  gains the KEY_FMT branches; both decode MXFP4 keys with _load_fp4_keys.
- The CUDA-core scorer keeps main's Q and key loads in its unquantized branch.
- FlyDSL dispatch only adds the compressed_k_scale check; main's docstrings,
  launch arguments, bench imports, labels and help text are restored.

Co-authored-by: Cursor <[email protected]>

* Say why _tuned_tile is cached and what "bf16" covers in the QSA docstrings

Co-authored-by: Cursor <[email protected]>

* Keep main's QSA exports and quant comments, and note the stacked page_ok bound

Co-authored-by: Cursor <[email protected]>

* Scope the exactness note of _load_fp4_keys to BF16 / FP32

Co-authored-by: Cursor <[email protected]>

* Share one scoring path across key formats in the QSA kernels

MXFP4 keys are now decoded into a full-width key tile (_load_fp4_keys
interleaves the low and high nibbles), so the CUDA-core, MFMA and stacked
scorers differ by key format only in how the key tile is loaded. main's Q
loads and per-head scoring in the CUDA-core and MFMA kernels are back to
their original text, and _load_q_row is gone.

Also:
- sparse GQA: one QK dot and one PV dot for both cache formats; FP8 only
  adds the key-scale and value-scale multiplies.
- the writers drop `row < num_rows`, always true for the (rows, heads) grid,
  and the num_rows argument.
- qsa_cache_row_layout returns a QSARowLayout NamedTuple.
- bench_qsa.py: bench_select picks logits / select from args.op instead of
  a scoring_only flag.
- test_qsa.py: _store builds its planes with _planes.

PR diff against main: +1793 -93 before, +1701 -61 after; the kernel file
changes 24 of main's lines instead of 56.

The FP4 scores now sum in a different order, so they are not bitwise equal
to the previous head; the other outputs are expected to be.

Co-authored-by: Cursor <[email protected]>

* Read QSARowLayout fields by name in bench_qsa

Use the layout's field names in the benchmark, as the wrapper and the
test do, and keep the reviewed comment on the CUDA-core fallback.
Benchmark output and kernels are unchanged.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
ruanjm pushed a commit that referenced this pull request Nov 10, 2026
…decode scorer (#7008)

* [Triton/Gluon] [QSA] FP8 KV and FP8 / FP4 index caches, stacked-head decode scorer

Bring the QSA operator changes of ROCm/ATOM#2652 into the Triton QSA
kernels that #6469 / #6515 ported from ATOM before that PR landed.

- qsa_store_quantized_rows: FP8 rows with one FP32 scale per (token,
  head) = row amax / FP8 max (K and V in one launch), and MXFP4 rows
  (packed E2M1 pairs, one E8M0 exponent per 32 dims, rounded up so a
  group never clips). qsa_cache_row_layout describes the stored row.
- qsa_sparse_paged_gqa(k_scale=, v_scale=): reads E4M3 K/V tiles,
  multiplies the key scale into its score column and folds the value
  scale into the probability before PV; FP8 has its own tile config.
- qsa_paged_mqa_logits / qsa_select_paged_tokens(compressed_k_scale=):
  FP8 (row scale) and MXFP4 compressed index keys in the CUDA-core,
  prefill MFMA and stacked scorers. FlyDSL stays BF16-only.
- stacked_decode=True: decode-sized calls (<= 256 rows) score with an
  MFMA kernel that stacks 4 rows x 4 index heads into M = 16, so a
  request's keys are read once per verify instead of once per row.
  Off by default, so existing BF16 callers keep their kernels.

The BF16 path and the existing signatures are unchanged; new arguments
are trailing keywords with defaults.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Address review: page-table bound, CPU import, writer checks

- Scorers: the MFMA and stacked kernels mask page-table loads with
  columns < num_columns as well as the rounded table width, so a narrow
  table (for example [1, 3] at page size 4) is not read past its end.
- Without a visible GPU, aiter.dtypes.fp8 is a uint8 placeholder. FP8_MAX
  is None there instead of a module-level torch.finfo error, so both QSA
  modules import on CPU; FP8 layouts raise until a GPU FP8 dtype exists.
- qsa_store_quantized_rows rejects non-contiguous, non-integer or
  multi-dim slots (the writers read slots[row] without a stride), a scale
  plane whose shape does not match the cache, and a second K/V plane whose
  cache or scale shape or dtype differs from the first.
- Tests for each case: a [1, 3] page table through the CUDA-core, MFMA and
  stacked scorers in BF16 / FP8 / FP4, bad slots and planes for both
  writers, and an import in a subprocess with no visible GPU.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Quantize FP4 index rows with _mxfp4_quant_op

Address review: drop the QSA writer's own E2M1 encoder and inline E8M0
math, and extend aiter's MXFP4 quantizer to cover what QSA needs.

- _mxfp4_quant_op / _mxfp4_pack_op / _mxfp4_pack_bits gain
  ROUNDING_MODE (0 = ties to nearest even, the existing behavior and
  default; 1 = ties away from zero). Both the normal and the denormal
  branch of the bit path implement mode 1; USE_ASM with mode 1 is a
  static_assert, since v_cvt_scalef32_pk_fp4_f32 only rounds to even.
- _mxfp4_ceil_scale_from_amax / _mxfp4_quant_op gain MAX_SCALE_E8M0
  (default 254 = uncapped, so inf / NaN amax keeps its NaN scale);
  only SCALING_MODE=1 accepts a cap.
- _qsa_store_rows_fp4_kernel loads the row as a [1, HEAD_DIM] tile and
  calls _mxfp4_quant_op(SCALING_MODE=1, ROUNDING_MODE=1,
  MAX_SCALE_E8M0=240): the cache bytes of ATOM's QSA writer, with E8M0
  kept within the readers' FP16 decode.
- Tests: E2M1 ties at 0.25 ... 5.0 times the scale, and the E8M0 cap.

Default arguments compile to the same instructions as before.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Reject partial second planes and mismatched scale planes

- qsa_store_quantized_rows: second_cache, second_scale and second_values go
  together or not at all; a partial set used to be ignored without an error.
- qsa_paged_mqa_logits: compressed_k_scale must have the full shape and dtype
  of the cache's scale plane (qsa_cache_row_layout), not only its first three
  dims. A short FP4 group axis used to pass and the kernel read past each
  scale row.
- qsa_sparse_paged_gqa: v_scale must have the shape of k_scale, and a v_scale
  without an FP8 cache and k_scale is rejected.
- The CUDA-core scorer is one kernel with KEY_FMT (0 BF16, 1 FP8, 2 MXFP4),
  like the MFMA kernels, instead of a separate FP4 kernel with a copied body.
  Every variant compiles to the same instructions as before.
- test_qsa.py: tests for the rejected inputs; randn gets an explicit dtype.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Move QSA tiles to JSON, reuse _mxfp4_e8m0_to_fp32

- The stacked decode scorer's tiles and the FP8 GQA tiles move from Python
  dicts to configs/<arch>/triton/attention/qsa/DEFAULT.json, read with
  resolve_config_dir() and load_config_json(). gfx942 and gfx950 get the
  previous Python values; gfx1250 is seeded byte-identical from gfx950.
  Only the stacked and FP8 GQA paths read the file, so BF16 calls do not
  depend on it on any arch.
- The MXFP4 readers decode the group scale with
  _mxfp4_e8m0_to_fp32(e + 14) instead of a local copy. The bits are the
  same for all 256 exponents.
- The FP8 writer's kernel name includes FP8_MAX_C, which differs per arch.
- Move the CUDA-core comment from the MFMA branch to the CUDA-core launch.
- test_qsa.py: the cap test builds its values on the GPU with an explicit
  dtype, and the other float factories get a dtype too. The narrow
  page-table test uses a real [1, 3] table and no longer claims to catch a
  read of entry 3: such a read has no visible effect, and the test passes on
  the kernels without the fix as well.

Co-authored-by: Cursor <[email protected]>

* [Triton/Gluon] [QSA] Accept FP16 / FP32 caches again, check writer and GQA inputs

Review follow-up (valar-cop):
- Unquantized FP16 and FP32 caches work again in the index scorers and
  sparse GQA, as on main; 4811ba3 accepted only BF16. A scale plane passed
  with an unquantized cache is rejected.
- qsa_store_quantized_rows checks the scale plane's dtype, and raises a
  ValueError instead of view's RuntimeError when the cache or scale plane is
  a slice of a larger page pool.
- qsa_cache_row_layout("fp4", d) needs a power-of-two d >= 32, so the FP4
  scorers raise a ValueError for d = 96 instead of failing to compile.
- qsa_sparse_paged_gqa needs float32 k_scale / v_scale.
- Comments: why page_ok keeps columns < num_columns, the CUDA-core fallback,
  a one-line _tuned_tile docstring. torch.logspace in the test takes a dtype.

The compiled kernels are unchanged.

Co-authored-by: Cursor <[email protected]>

* Read the QSA tile table optionally; test more head_dims

configs/<arch>/triton/attention/qsa exists only for gfx942, gfx950 and
gfx1250, and _tuned_tile read it with required=True, so stacked_decode
and FP8 sparse GQA raised FileNotFoundError on any other arch. Load it with
required=False: without the table stacked_decode scores with the other
kernels and FP8 K/V keep the _kernel_config tiles, as BF16 does.

Tests: run the FP8 GQA case and a stacked_decode call as on gfx1100 (no
QSA config), and parametrize the quantized scoring test over head_dim
(32, 64, 128, 256) and heads (1, 2, 4), which covers FP4 at head_dim 32.

Co-authored-by: Cursor <[email protected]>

* Reuse _fp8_quant_op in the FP8 writer; fp4_utils in the test

The FP8 QSA writer computed the row amax, scale and clamp itself, which is
what _fp8_quant_op in fused_fp8_quant.py does with one group per row; K and
V repeated that code. Call _fp8_quant_op from one _store_fp8_row helper.
Scales are unchanged; at rounding ties a few bytes move one E4M3 code,
because _fp8_quant_op multiplies by 1 / scale instead of FP8_MAX / amax.

The test's MXFP4 dequant reimplemented mxfp4_to_f32 and e8m0_to_f32 from
aiter.utility.fp4_utils, which test_quant_mxfp4.py uses; use them.

Co-authored-by: Cursor <[email protected]>

* Clean up the QSA diff: one test case builder and reference, shared FP4 key-tile decode, one matrix-core launch

- test_qsa: _index_case / _stacked_case and their references become one
  _case and one _reference; the writer reject tests share _planes; the
  narrow page-table test uses them instead of its own reference.
- kernels: the MFMA and stacked scorers share _fp4_key_tile; the CUDA-core
  scorer loads unquantized Q rows with _load_q_row; duplicate comments go.
- wrapper: the stacked and MFMA scorers share one launch; the FP8 and FP4
  writers share their common arguments.

Outputs are bitwise identical to the previous commit.

Co-authored-by: Cursor <[email protected]>

* Fold the stacked QSA scorer into the MFMA kernel and share the scale-plane check

- _qsa_paged_mqa_logits_mfma_kernel takes STACK_HEADS; the stacked kernel and
  its repr are gone.
- _load_fp4_keys is the one MXFP4 key decode of the CUDA-core and MFMA scorers.
- _check_scale_plane validates the writer, scorer and GQA scale planes.
- The FP8 writer takes None for the second plane instead of HAS_SECOND.
- bench_qsa: _quantize returns one (cache, scale) pair; _scenario is gone.

Co-authored-by: Cursor <[email protected]>

* Leave existing QSA code as on main where the change does not need it

- The stacked scorer is its own kernel again, so the prefill MFMA kernel only
  gains the KEY_FMT branches; both decode MXFP4 keys with _load_fp4_keys.
- The CUDA-core scorer keeps main's Q and key loads in its unquantized branch.
- FlyDSL dispatch only adds the compressed_k_scale check; main's docstrings,
  launch arguments, bench imports, labels and help text are restored.

Co-authored-by: Cursor <[email protected]>

* Say why _tuned_tile is cached and what "bf16" covers in the QSA docstrings

Co-authored-by: Cursor <[email protected]>

* Keep main's QSA exports and quant comments, and note the stacked page_ok bound

Co-authored-by: Cursor <[email protected]>

* Scope the exactness note of _load_fp4_keys to BF16 / FP32

Co-authored-by: Cursor <[email protected]>

* Share one scoring path across key formats in the QSA kernels

MXFP4 keys are now decoded into a full-width key tile (_load_fp4_keys
interleaves the low and high nibbles), so the CUDA-core, MFMA and stacked
scorers differ by key format only in how the key tile is loaded. main's Q
loads and per-head scoring in the CUDA-core and MFMA kernels are back to
their original text, and _load_q_row is gone.

Also:
- sparse GQA: one QK dot and one PV dot for both cache formats; FP8 only
  adds the key-scale and value-scale multiplies.
- the writers drop `row < num_rows`, always true for the (rows, heads) grid,
  and the num_rows argument.
- qsa_cache_row_layout returns a QSARowLayout NamedTuple.
- bench_qsa.py: bench_select picks logits / select from args.op instead of
  a scoring_only flag.
- test_qsa.py: _store builds its planes with _planes.

PR diff against main: +1793 -93 before, +1701 -61 after; the kernel file
changes 24 of main's lines instead of 56.

The FP4 scores now sum in a different order, so they are not bitwise equal
to the previous head; the other outputs are expected to be.

Co-authored-by: Cursor <[email protected]>

* Read QSARowLayout fields by name in bench_qsa

Use the layout's field names in the benchmark, as the wrapper and the
test do, and keep the reviewed comment on the CUDA-core fallback.
Benchmark output and kernels are unchanged.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
zovonoir pushed a commit to mengfei-jiang/ATOM that referenced this pull request Nov 11, 2026
Replace vendored QSA scoring, selection and sparse paged GQA kernels
with imports from aiter (ROCm/aiter#6469). Delete qsa_flydsl_layout.py
(now in aiter). Utility kernels (draft metadata, compressed slots,
mRoPE, store rows, compress groups) remain local.

Co-Authored-By: Claude <[email protected]>
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