Repository navigation
[Triton/Gluon] Restructure Unified Attention Kernel (merging 2d/3d and modularization) - #6337
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: |
cd3c9e0 to
a9e6d62
Compare
WAITING ON AUTHORPR Self-ReviewRevision Waiting for the PR author. The readiness report will appear after the self-review answers are complete for this revision. Questions to answer in the PR description
Edit the Missing or invalid answers
Shadow mode reports what would block but keeps the status successful. Set |
cd3c9e0 to
c12be61
Compare
kernel_unified_attention replaces kernel_unified_attention_2d/_3d. GRID_3D picks the (q_block, kv_head, segment) program order of the split-KV launch; NUM_SEGMENTS_PER_SEQ > 1 writes partials for reduce_segments, otherwise the output. The body is split into AttentionConfig, KVLoader and AttentionProgram aggregates plus one attention_loop used for both the unmasked and the masked tiles, along the lines of the gfx950 gluon kernel. Configs and launch names are unchanged (attn_2d / attn_3d sections, 2d and 3d kernel reprs). The 2d kernel compiles to the same instruction stream as before on gfx942/gfx950/gfx1100/gfx1201/gfx1250; 3d loops only differ in the softmax scale, now a constexpr as in 2d. A 3d launch with a single segment used to write the padded segment layout into the output; it now stores the output like the 2d launch (fixes out-of-bounds writes for non power-of-2 value heads, adds the fp8 clamp).
The triton kernels read a shuffled tile as one contiguous page, so the wrapper pinned TILE_SIZE to block_size and the tuned tile (e.g. the gfx950 SHUF entries) was ignored. A tile inside one page now reads its slice of the page (one block id per tile), a tile over several pages reads each page as a contiguous chunk; both use the existing un-shuffle. One-page tiles keep the old load and codegen. The fp8 shuffled assert moves from block_size >= 32 to TILE_SIZE >= 32, so 16-token pages work with fp8.
The prefill batch was small enough to take the 3d grid, so the 2d shuffled paths went untested; use a batch that takes the 2d grid, lengths that end mid-page, fp8 on both tile cases, and no random descales, which flattened the softmax enough to hide a wrong K layout.
…n both grids The mask only depends on key and query positions. The old 3d kernel built it before the dot, the 2d kernel after; use one order. Outputs are bitwise unchanged; the 2d loop schedule changes on some archs.
… steps KVLoader.load_tile now looks the tile up once (block_ids) and builds the K and V offsets and masks with separate methods before load_k / load_v issue the loads, so the two loads can be reordered independently. A shuffled tile that is not one page is described as NUM_SLOTS slots of SLOT_SIZE keys, each inside one page, instead of two separate gather paths. Drops the forwarding KVLoader.initialize and folds the tensor-or-constexpr field wrapping into one helper. The plain layout and one-page shuffled tiles compile to the same instructions as before on gfx942/gfx950/gfx1100/gfx1101/gfx1150/gfx1151/gfx1200/gfx1201/ gfx1250.
…pans pages A shuffled V page is [BLOCK_SIZE // W, HEAD_SIZE, W]. Addressing a multi-page tile as [pages, BLOCK_SIZE * HEAD_SIZE] made the un-shuffle split that axis, and the layout derived back to the load spread a lane's W-run over pages: on gfx950 the direct-to-LDS copy of V fell to 4 bytes per lane. Keep the rows axis when a page has more than one row, so the un-shuffle only merges pages. Pages of a single row are one contiguous run and keep the flat form.
Build the offsets of a shuffled tile that spans pages in the one-page order and flatten them before the load: K as [HEAD_SIZE // W, pages, page * W], V as concatenated pages. The load and the un-shuffle are then the one-page ones, so K and V keep their 16-byte direct-to-LDS copies on gfx950; the 4-D K un-shuffle and the page-rows V form are gone.
…kernel The rebase onto main dropped what main changed in the old 2d/3d kernels: - with a sliding window the split carves only the window's tiles (split_window_tiles), as reduce_segments now expects; without it the split outputs were wrong or NaN - rows past BLOCK_Q tokens are masked, so two q blocks no longer both store segment stats for the same token (#7472) - the qq_bias load masks padded query rows
The window was a second select over S after the causal one. Build both from the key distance before the QK dot, with one unsigned compare for 0 <= dist < window. Bitwise identical output; on gfx950 sliding-window prefill and chunked prefill run 7-11% faster at head size 64 and 128, decode and head size 256 are unchanged.
…w_max Fixes ruff SIM102 under the CI-pinned ruff 0.16.0.
29576c1 to
31fb657
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Single-segment 3D decode can access tensors out of bounds for zero-KV padding sequences with no query rows, while int64 sliding-window metadata causes compilation failures and the shuffled loader lacks Triton regression coverage.
3 open issues
What changed in this PR
This PR merges AITER’s Triton 2D and 3D unified attention kernels to reduce duplicated logic and let shuffled KV caches use tuned tile sizes independently of page size.
Changes:
- Introduces shared configuration, KV loading, attention-loop, and output helpers while preserving 2D/3D profile names.
- Supports shuffled tiles that cover part of a page or span several pages.
- Updates wrapper launches and separates split-KV partial writes from direct output stores.
| File | Description |
|---|---|
aiter/ops/triton/attention/unified_attention.py |
Launches the merged kernel and removes page-sized tile restrictions. |
aiter/ops/triton/_triton_kernels/attention/unified_attention.py |
Consolidates attention logic and adds flexible shuffled-KV tile addressing. |
Review effort: Balanced
|
No activity for 15 days, so this is now labelled |
Signed-off-by: Mehmet Cagri Kaymak <[email protected]>
|
Heads-up so nothing collides by surprise: #8883 adds a split-KV decode producer for gfx1250, GQA 8 / head 64 (two KV heads per program, so no padding rows). It writes the same 🤖 Generated with Claude Code |
Signed-off-by: Mehmet Cagri Kaymak <[email protected]>
…t 3D grid A 3D launch with one segment read Q and wrote output for padding sequences with no KV and no query rows. Run the empty-segment return on every 3D launch, as the 3D kernel on main did. Signed-off-by: Mehmet Cagri Kaymak <[email protected]>
With int64 seqused_k or cu_seqlens_q, the sliding-window bitcast compare did not compile. Narrow the loads to int32: positions fit, and addresses already widen to int64. int64 callers now run the int32 code. Signed-off-by: Mehmet Cagri Kaymak <[email protected]>
|
The new cross-page shuffled |
…nd on gfx950 The shuffled Triton loader was only tested on gfx942, where the tile mostly equals the page. Run the 2D and 3D shuffled tests on the Triton backend on gfx950 too, which covers tiles larger and smaller than a page. Signed-off-by: Mehmet Cagri Kaymak <[email protected]>
Resolved against the kernel_unified_attention restructure (ROCm#6337): this PR's kernel changes are ported onto the merged 2d/3d kernel (GRID_3D).
Resolved against the kernel_unified_attention restructure (ROCm#6337): this PR's kernel changes are ported onto the merged 2d/3d kernel (GRID_3D). The updated parent PR branch is merged in as well.
Resolved against the kernel_unified_attention restructure (ROCm#6337): this PR's kernel changes are ported onto the merged 2d/3d kernel (GRID_3D). The updated parent PR branch is merged in as well.
…dim-256 prefill entry on the merged kernel After #6337 merged the 2D and 3D kernels, main's 64-row / tile-32 value got about 20% faster on the head_dim-256 bf16 prefill shapes and the entry picked on the old kernel (64 / 4 / tile 16 / waves_per_eu 0) fell to 0.88x-0.97x of it. Re-searched on the new kernel: main's tile with waves_per_eu 2 is 1.05x-1.08x faster than main's value on all 8 shapes. The other 13 changed or added entries keep their gain on the new kernel; whole table 1.24x (bf16 KV) and 1.23x (fp8 KV) over 7 models x 17 calls. Signed-off-by: Lin, KuanTing <[email protected]>
… lost to main on the restructured kernel With the 2D / 3D kernel merge (#6337) on main, several entries of this table fell behind main's values on gfx1151 (TheRock 10.3.0a20261202, torch 2.17.0a0, Triton 3.9.0; CUDA graph, every arm checked against ref_paged_attn): attn_2d.Q_GEQ_256.DT_any_bf16.D_LEQ_128 on mixed prefill-plus-decode batches (0.93x-0.97x), attn_2d.Q_LEQ_1 and Q_LEQ_1.DT_fp8_fp8 on single-sequence 256-token decode of every model and on 16 / 8-head head_dim-256 decode batches (0.79x-0.87x; these were already behind on the previous kernel), Q_GEQ_256.DT_any_fp8.D_LEQ_512 on head_dim-512 fp8-KV prefill (0.95x-0.97x) and kv_split.D_EQ_512 on 32-sequence 1k-token decode (0.96x). Each of those keys was re-swept on the merged kernel. Rule: one value per key that is at least 0.98x of main's value on every shape of the key, best geomean among those; where no value qualifies the key goes back to main's value. - attn_2d.Q_GEQ_256.DT_any_bf16.D_LEQ_128: 128 / 8 / 1 / 0, tile 32 -> 64 / 4 / 1 / 0, tile 32. Llama-3-8B and Qwen2.5-7B prefill 512-4096, chunked prefill and mixed batches: 1.05x-1.17x of main (was 0.93x-1.19x). - attn_2d.Q_LEQ_1.DT_any_bf16 (new): 16 / 8 / 1 / 2, tile 32-64 for head_dim 256 and 512 bf16 decode: 1.05x-2.3x of main (was 0.79x-1.47x). - attn_2d.Q_LEQ_1.DT_any_bf16.D_LEQ_128 (new), attn_2d.Q_LEQ_1 and attn_2d.Q_LEQ_1.DT_fp8_fp8: main's values. No single value serves both single-sequence and 32-sequence decode (one wants 4-8 warps and a 32-64 tile, the other 2 warps and a 16 tile) and the batch size is not a lookup axis. - attn_2d.Q_GEQ_256.DT_any_fp8.D_LEQ_512: main's value. No candidate beat it on the chunked-prefill shape. - kv_split.D_EQ_512.DT_any_bf16: SEGMENTS_PER_CU 16 -> 4. Gemma-4 bf16 decode 1.01x-4.55x of main (was 0.96x-4.55x). Whole table on the merged kernel, 6 models x 17 shapes, bf16: geomean 1.35x of main, no shape under 0.99x; 1.06x of this PR's previous table. fp8 KV and fp8 / fp8 variants: every entry still changed by this PR is at or above main's value on its shapes. Signed-off-by: Lin, KuanTing <[email protected]>
… lost to main on the restructured kernel With the 2D / 3D kernel merge (#6337) on main, several entries of this table fell behind main's values on gfx1150 (12 CU; TheRock 10.3.0a20261202, torch 2.17.0a0, Triton 3.9.0; CUDA graph, every arm checked against ref_paged_attn): attn_2d.Q_GEQ_256.DT_any_bf16.D_LEQ_256 on head_dim-256 bf16 prefill, chunked prefill and mixed batches (0.82x-0.97x), attn_2d.Q_LEQ_1 for fp8 KV and Q_LEQ_1.DT_fp8_fp8 on single-sequence 256-token decode (0.70x-0.85x; already behind on the previous kernel), attn_2d.any for fp8-KV speculative decode at head_dim 128 (0.80x), attn_2d.DT_fp8_fp8 on fp8 / fp8 speculative decode at head_dim 256 (0.86x), attn_3d.D_LEQ_1024.DT_any_fp8 with kv_split.any on 8-sequence 1k-token fp8-KV decode (0.88x), and kv_split.D_LEQ_256 on 8-sequence head_dim-256 decode (0.97x). Each was re-swept on the merged kernel. Rule: a value is taken only if it is at least 0.98x of main's value on every shape of its key, best geomean among those; otherwise the key keeps main's value. Where single-sequence and many-sequence decode, or head_dim 128 and larger heads, want different values, the key is split by head_dim. - attn_2d.Q_GEQ_256.DT_any_bf16.D_LEQ_256: back to main's value; the best candidate was within 2% of it. - attn_2d.Q_LEQ_1.DT_fp8_fp8: 16 / 4 / 1 / 2, tile 16-32 for head_dim 256 and 512 (1.28x of main, min 1.02x); new .D_LEQ_128: 16 / 4 / 1 / 8, tile 16 (1.09x, min 1.00x). - new attn_2d.Q_LEQ_1.DT_any_fp8: 16 / 4 / 1 / 2, tile 16-32 for head_dim 256 and 512 (1.91x of main, min 1.27x); new .D_LEQ_128: 16 / 2 / 1 / 0, tile 32-64 (1.34x, min 1.02x). These calls fell through to Q_LEQ_1. - new attn_2d.DT_any_fp8: main's catch-all value for head_dim 128 fp8-KV speculative decode; new .D_GEQ_256: 32 / 4 / 1 / 4, tile 16 (1.09x). - attn_2d.DT_fp8_fp8: 32 / 2 / 1 / 2, tile 16 for head_dim 256 and 512 (1.12x of main, min 1.06x); new .D_LEQ_128: main's value. - new kv_split.D_EQ_256.DT_any_bf16: 4 / 2 / 128 / 32, tile 32 for head_dim-256 bf16 decode (1.20x of main, min 1.03x); D_LEQ_256 keeps its value for head_dim 128. - new kv_split.D_EQ_512.DT_any_fp8: 2 / 4 / 128 / 16, tile 16, with the unchanged attn_3d.D_LEQ_1024.DT_any_fp8: Gemma-4 fp8-KV decode 1.03x-1.90x of main (was 0.78x-1.88x). Signed-off-by: Lin, KuanTing <[email protected]>


[Triton] unified_attention: merge the 2D and 3D kernels into one modular kernel, and allow a shuffled-KV tile that differs from the page size.
RDNA performance is verified by @amd-xavierwang , no big delta for unshuffled cases (the path that is taken for that arch).
Motivation
kernel_unified_attention_2d(prefill and unsplit decode) andkernel_unified_attention_3d(split-KV decode). They are near-copies of each other, about 500 and 400 lines, and have to be
kept in sync by hand. Fixes landed on one and not the other:
main's 3D split fixes are portedhere.
TILE_SIZE = block_size, because the kernels read a shuffled tile as one contiguous page. Thetuned tile was therefore ignored for shuffled layouts. That is very slow for head-256 prefill,
where the tuned tile is 32 and the page is 64.
Technical Details
Only two files change:
aiter/ops/triton/_triton_kernels/attention/unified_attention.pyand itswrapper,
aiter/ops/triton/attention/unified_attention.py.kernel_unified_attentionreplaceskernel_unified_attention_2dandkernel_unified_attention_3d.GRID_3Dconstexpr, andNUM_SEGMENTS_PER_SEQsets the split.initial_row_max,attention_loop, and the KV tileaddress and load steps.
_2d/_3dsuffix, via the kernel repr.NUM_SEGMENTS > 1writes fp32 partials(
segm_output/segm_max/segm_expsum), andreduce_segmentsappliesoutput_scale.Unsplit, it writes
outputdirectly and appliesout_scale. The 2D launch passesNoneforthe segment pointers.
tile may now span pages: it is addressed flat, and V keeps its page rows.
TILE_SIZE = block_sizeon either grid.block_size >= 32toTILE_SIZE >= 32.is folded into the causal mask.
main1eab5ae. There was one conflict, with the gfx12FILL_MIN_SEGMENTSblock ([Triton/Gluon] [GFX12] Add SPEC_DECODE mode to UA with tunned Qwen35 config #7100).
main's block was kept and reads the config tile size, now namedTILE_SIZE.The shuffled pin was dropped.
Test Plan
A/B of
main1eab5ae (baseline) against this branch rebased onto it (pr). The scripts and fulldata are in the A/B folder:
REPORT.md,RUN_DETAILS.mdandRESULTS_DETAIL.md.HIP 7.15 and triton 3.8.0.
backend="triton"is forced; Gluon is not touched.on gfx942).
q = kv.
block table.
median profiler device time of the attention kernel plus
reduce_segments. Both arms run backto back on the same GPU, one shard at a time, and noisy cases are retried.
ref_paged_attn| per arm, plus max |pr − baseline| on a 64Koutput sample per case.
mi300_r1,mi300_r2).variants built by both: launch config, VGPRs, spills, scratch, LDS and instruction count.
op_tests/triton_tests/attention/test_unified_attention.py(5,145 tests).Test Result
Correctness is unchanged on both GPUs.
Same specialization: 400 of 416 cases per GPU launch the same kernel constexprs in both
arms. The other 16 are the h256 shuffled prefills, which now use the tuned 32-token tile
instead of the 64-token page.
Performance, as geomean of pr / baseline − 1 (negative = pr faster):
For example, h256 shuffled 1×8K×8K full-attention prefill goes from 57.0 to 16.7 ms on MI300X.
MI300X-only regressions. Both reproduce in the repeat run. The same rows are flat or faster
on MI355X.
For example, B4 at 8K with window 1024 goes from 29.4 to 33.7 µs. Batch 128 is flat.
1469 → 1540 µs.
Codegen on gfx942.
0.95–1.00× (median 0.98).
reduce_segmentsis identical.stop spilling.
counts, as baseline. Head 256 spills heavily in both arms; pr reports 239 spilled VGPRs vs
226 but emits slightly fewer scratch stores (281 vs 288).
profile of the h128 shuffled window-1024 B4 kernel.
Run-to-run noise on MI300X: per-row Δ moves by a median of 0.8 points (p90 3.0), and by up
to 11 points on kernels under 20 µs.
MI355 Results
Geomean pr / baseline − 1 (negative = pr faster)
MI300 Results
Geomean pr / baseline (negative = pr faster)
Submission Checklist
PR Self-Review
Reviewed revision
31fb65704f01: the branch rebased ontomain1eab5ae. It has 14 commits; the net diff touchesaiter/ops/triton/_triton_kernels/attention/unified_attention.pyandaiter/ops/triton/attention/unified_attention.pyonly.Behavior and intent
kernel_unified_attention_2dandkernel_unified_attention_3dare replaced byone modular
kernel_unified_attention, built fromAttentionConfig,KVLoaderandAttentionProgramaggregates, with oneattention_loopfor unmasked and masked tiles.GRID_3Dselects the split-KV program order.NUM_SEGMENTS_PER_SEQ > 1writes partials forreduce_segments.attn_2d/attn_3d) and the 2d / 3d kernel names are unchanged.order differed between them, and main's 3d split fixes landed in only one. That made every fix
a double change.
TILE_SIZE = block_sizefor the shuffled layout, so tuned shuffledconfigs (e.g. gfx950
SHUFentries) were ignored.as a contiguous chunk, addressed flat so the K and V loads keep their 16-byte direct-to-LDS
copies on gfx950.
block_size >= 32toTILE_SIZE >= 32, so 16-tokenpages work with fp8.
dot. Output is unchanged.
padded segment layout into it. This fixes out-of-bounds writes for non-power-of-2 value heads
and adds the fp8 clamp.
split_window_tiles), asreduce_segmentsexpects;BLOCK_Qtokens are masked, so two q blocks no longer store segment stats forthe same token ([Triton/Gluon] unified_attention: keep 3D split-KV padding rows from storing segment stats #7472);
qq_biasload masks padded query rows.Validation and unverified scope
Validated: an A/B against
main1eab5ae on MI355X (gfx950), torch 2.12.0+rocm10.0.0,HIP 7.15, triton 3.8.0,
backend="triton"forced.and a page size of 64.
2×8K×8K.
torch.profilerdevice time of theunified_attentionandreduce_segmentskernels only. Botharms run on the same GPU, one shard at a time.
ref_paged_attnis neverworse than
main's. The largest pr-vs-main output difference is 3.9e-3. Every case selectsthe same grid in both arms.
−16% at windows 128 / 512 / 1024, and fp8 h128 plain is −3% / −9% / −11%.
varied by a median of 0.6 points (p90 1.8), and kernels under 20 µs by up to 14 points, so
these rows are within noise.
Unverified:
TILE_SIZE> page): no A/B case selected one. Allshuffled cases used page 64, with tile 64 or 32.
decode batches had uniform lengths.
qq_bias,output_scale, uint8 / FP4 KV caches andnon-power-of-2 value heads.
PR-specific question
The most important boundary: a shuffled KV tile whose
TILE_SIZEdiffers from the page size.This is the new addressing path. A wrong K or V un-shuffle there would silently return wrong
attention, not crash.
TILE_SIZE=32for bf16 h256 shuffled prefill;mainpinned it to 64. All 16 such cases (4shapes × 4 windows):
main's fp32-reference error exactly, where the reference fits;main's output to 3.9e-3;in commit dd0db30 (2d grid, lengths that end mid-page, fp8 on both tile cases). That test was
later removed from this PR, so this path currently has no test in the tree.
decode cases (same grid, same reference error), but not for non-power-of-2 value heads.
Changed op tests
None. The branch's commits added op tests and then removed them again (2a899c3, 7ff8d2e),
so the net diff against
mainchanges no file underop_tests/.