Skip to content

[Triton] unified_attention: share the split-loop tile body, extend it to shuffled KV (follow-up to #4761) - #5158

Closed
alexnails wants to merge 1 commit into
ROCm:mainfrom
alexnails:unified-attn-fasttile
Closed

alexnails wants to merge 1 commit into
ROCm:mainfrom
alexnails:unified-attn-fasttile

Conversation

@alexnails

@alexnails alexnails commented Sep 1, 2026 •

Copy link
Copy Markdown

What

Follow-up to #4761, as agreed in the review thread. #4761 split the 2-D prefill tile loop into an unmasked bulk pass plus a masked tail pass, behind the SPLIT_UNMASKED_LOOP config key. This builds on it; it does not replace it, and the gate stays in the tuned table.

  • Shared tile body. [Triton/Gluon] [PERF] Optimize Triton unified attention prefill and decode #4761 carried the bulk pass as a second inline copy of the tile body. It is now one helper, _attention_tile(MASKED: tl.constexpr), that both loops call, so masking and scaling changes cannot drift between two copies.

  • Shuffled KV support. The inline copy only implemented the per-token cache layout, so shuffled KV was excluded by static_assert. The shared helper already has the per-tile shuffled branch, so the exclusion is dropped.

  • Bulk-bound clamp. The bulk bound is clamped into [tile_start, tile_end]. context_len goes negative when a sequence has more query tokens than cached keys; without the clamp, the floor division hands the masked loop a negative first tile.

  • Sliding-window guard. The bulk pass drops the sliding-window bound along with the causal one. So:

    • a tl.static_assert refuses an unmasked pass with a window at compile time;
    • the wrapper strips SPLIT_UNMASKED_LOOP for windowed and decode calls, whatever the table says.

    Without these, a table entry missing its .SW. sibling would give silently wrong results rather than slow ones.

  • FUSE_QK_SCALE, an opt-in config key that folds qk_scale into the exp2 argument. It is refused in two places, since the folded maximum relies on scaling being monotone:

    • inside the kernel, for softcap, ALiBi and qq-bias;
    • in the wrapper, for a non-positive softmax_scale.

The tuned table is unchanged. The existing SPLIT_UNMASKED_LOOP entry behaves as before, and this PR enables no new entries. Which cases to opt in, and at what num_stages, is a tuning decision that belongs in a separate change (see the note below).

Tests

The tests force the config keys per case, rather than relying on which table entries are enabled.

  • Each shape is checked to actually reach the 2-D kernel. The suite's usual shapes route elsewhere, where a split-loop test would pass without running a single bulk tile.
  • Split is compared against stock elementwise, with a mixed tolerance: rtol of 4 bf16 ULP, and an atol of 1 ULP of the output scale for cancellation residue. The NaN pattern has to match exactly.
  • Coverage:
    • bf16 and fp8, with and without sinks;
    • head_size 64 and 512;
    • a ragged batch with negative context_len;
    • shuffled KV. The rest of the suite skips shuffled everywhere except gfx1250, so on gfx950 this branch had no coverage, even though it works there.
  • Unit tests check that the wrapper guard refuses windowed and decode calls, and refuses the fold for a non-positive scale.

Validated on gfx950 (MI350X) with the CI toolchain (torch 2.10, Triton 3.8): all 59 split-loop tests pass.

A note on num_stages for whoever tunes the table

This measures current main on the CI toolchain: gfx950, 64/8 heads, d=64, sinks, 4096 query tokens, backend="triton". On this stack num_stages=2 is faster than 1 at every context length, for both the stock and the split loop:

KV dtype stock s1 stock s2 split s1 split s2
16k bf16 1.876 −9.7% −14.6% −21.3%
128k bf16 16.843 −8.1% −15.0% −21.0%
16k fp8 1.505 −8.4% −17.7% −21.1%
128k fp8 13.642 −6.8% −17.7% −21.2%

Three things follow from this:

  • The effect is flat in context length, so it doesn't need a context axis.
  • The same A/B on the older Triton 3.4 image went the other way. The right depth depends on the toolchain.
  • With the default backend, gfx950 bf16/fp8 prefill now takes the Gluon kernel from [Triton/Gluon] [GFX950] Add Unified Attention Gluon Kernel #4614, which beats every Triton cell above. So on gfx950 this Triton path matters mainly as the fallback: forced backend="triton", softcap / ALiBi / qq-bias, head_size > 256, or mismatched q/KV dtypes.

🤖 Generated with Claude Code

@alexnails
alexnails requested a review from a team September 1, 2026 00:57
@github-actions

github-actions Bot commented Sep 1, 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; main branch always runs both MI35X and MI300X
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 5158 --add-label <label>

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 opt this PR out.

@github-actions github-actions Bot changed the title [Triton] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (KR_FASTTILE, −17% kernel / −18.5% serving TTFT) [Triton/Gluon] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (KR_FASTTILE, −17% kernel / −18.5% serving TTFT) Sep 1, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot September 1, 2026 03:44

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 opt-in fast-tile and tail-split scheduling for unified attention to improve gfx950 prefill performance.

Changes:

  • Splits attention processing into unmasked bulk and masked tail loops.
  • Adds optional fused scaling and pipelining controls.
  • Adds tail work partitioning and segment reduction.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 12 comments.

File Description
attention/unified_attention.py Adds feature dispatch and tuning flags.
attention/kr_ua.py Adds the tail-split wrapper and planning.
_triton_kernels/attention/unified_attention.py Refactors tile computation into a helper.
_triton_kernels/attention/kr_split.py Adds split-attention and reduction kernels.
Suppressed comments (1)

aiter/ops/triton/_triton_kernels/attention/kr_split.py:218

  • The new reduction kernel is launchable but lacks the required config-aware repr, leaving profiler/JIT trace names unable to distinguish BLOCK_M, HEAD_SIZE, and NUM_SEGMENTS specializations. Add make_kernel_repr and attach it via @triton.jit(repr=...).
@triton.jit
def reduce_segments_tail(

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

Comment thread aiter/ops/triton/attention/kr_ua.py Resolved
Comment thread aiter/ops/triton/attention/kr_ua.py Resolved
Comment on lines +176 to +180
if _KR2_BM:
BLOCK_M = _KR2_BM
BLOCK_Q = max(1, BLOCK_M // num_queries_per_kv)
if _KR2_NW:
num_warps = _KR2_NW

@alexnails alexnails Sep 2, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

num_stages is left as an override

Comment thread aiter/ops/triton/attention/kr_ua.py Resolved
Comment thread aiter/ops/triton/attention/kr_ua.py Resolved
@zufayu
zufayu requested review from a team and azaidy September 2, 2026 01:22
@alexnails
alexnails force-pushed the unified-attn-fasttile branch from 768f09f to e10841e Compare September 2, 2026 08:06
@alexnails alexnails changed the title [Triton/Gluon] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (KR_FASTTILE, −17% kernel / −18.5% serving TTFT) [Triton] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (−12.8% kernel, gfx950, default off) Sep 2, 2026
@alexnails
alexnails force-pushed the unified-attn-fasttile branch from e10841e to e32d731 Compare September 2, 2026 08:17
@github-actions github-actions Bot changed the title [Triton] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (−12.8% kernel, gfx950, default off) [Triton/Gluon] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (−12.8% kernel, gfx950, default off) Sep 2, 2026
@alexnails

Copy link
Copy Markdown
Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

To use Codex here, create a Codex account and connect to github.

@alexnails

Copy link
Copy Markdown
Author

@zufayu I have addressed all the comments and have rebased to the newly landed changes! Please let me know what the next steps are

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

The dtype gate, fused-scale invariant, and ULP validation currently leave correctness gaps.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 4
  • Review effort level: Balanced

Comment on lines +502 to +506
if _FASTTILE == "off" or DEVICE_ARCH not in _FASTTILE_ARCHS:
return False, False
if params.sliding_window > 0 or params.all_decode:
return False, False
return True, _FASTTILE == "on"

@alexnails alexnails Sep 2, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Validated fp8, but not nvfp4 so left check

num_stages override is not global, it applies only where _fasttile_modes returns split=True, so it never reaches decode, windowed layers, or any non-gfx950 device.

@alexnails
alexnails force-pushed the unified-attn-fasttile branch from e32d731 to 386fdb6 Compare September 2, 2026 18:03
@cagrikymk

Copy link
Copy Markdown
Contributor

@alexnails This PR is overlap quite a bit with #4761 , is it possible for you to sync. up with that PR ?

@alexnails

alexnails commented Sep 2, 2026 •

Copy link
Copy Markdown
Author

@cagrikymk @vorapolsiloai they are functionally the same optimization, however I believe 5158 is a bit more robust and cleaner.

why:
cleaner: standardized attention_tile
robust: env opt in, more gfx950 cases covered, shuffled kv works (adding more tests for this)

where 4761 is better:
the main perf difference was that 5158 uses num_stages 2, I think using num_stages 1 is good (updating to this now)
I would adopt the JSON config it uses if env opt in is not preferred

let me know what you guys are thinking!

@alexnails
alexnails force-pushed the unified-attn-fasttile branch 2 times, most recently from 9290284 to 4943830 Compare September 2, 2026 18:57
@vorapolsiloai

Copy link
Copy Markdown
Contributor

@alexnails thanks for comparing the two. Since #4761 has already been through several rounds of review and testing and is pretty close to landing, I’d prefer to merge the smaller, validated change first. I don’t have easy access to MI355 compute at the moment, so another round of E2E iteration and validation would take time and delay things further.

Could we use #5158 as a follow-up on top of #4761 to expand the supported configs, add shuffled KV support, and bring in the shared tile helper? @cagrikymk does that sound reasonable?

@cagrikymk

Copy link
Copy Markdown
Contributor

@alexnails thanks for comparing the two. Since #4761 has already been through several rounds of review and testing and is pretty close to landing, I’d prefer to merge the smaller, validated change first. I don’t have easy access to MI355 compute at the moment, so another round of E2E iteration and validation would take time and delay things further.

Could we use #5158 as a follow-up on top of #4761 to expand the supported configs, add shuffled KV support, and bring in the shared tile helper? @cagrikymk does that sound reasonable?

Yes, that sounds good. I think that is the most reasonable path. I will review this PR once the #4761 is merged and yours is rebased on top.

… to shuffled KV

Follow-up to ROCm#4761, which split the 2-D prefill tile loop into an unmasked
bulk pass plus a masked tail pass behind SPLIT_UNMASKED_LOOP. That change
carried the bulk pass as a second inline copy of the tile body, and the copy
implemented only the per-token cache layout, so shuffled KV was excluded by
static_assert.

- Factor the tile body into _attention_tile(MASKED: tl.constexpr), called by
  both loops. One body, so future masking/scaling changes cannot drift apart
  between them, and the shuffled-cache branch comes along for free: the
  static_assert excluding shuffled KV is dropped.
- Clamp the bulk bound into [tile_start, tile_end]. context_len goes negative
  when a sequence carries more query tokens than cached keys, and the floor
  division would otherwise hand the masked loop a negative first tile.
- tl.static_assert that the unmasked pass never sees a sliding window, and
  strip SPLIT_UNMASKED_LOOP in the wrapper for windowed and decode calls
  whatever the table says: the bulk pass drops the window bound along with the
  causal one, so an entry missing its SW sibling would otherwise be silently
  wrong rather than slow.
- Add FUSE_QK_SCALE, an opt-in config key that folds qk_scale into the exp2
  argument. Refused for softcap / ALiBi / qq-bias inside the kernel and for a
  non-positive softmax_scale in the wrapper, since the folded maximum relies
  on scaling being monotone.

The tuned table is unchanged: the existing SPLIT_UNMASKED_LOOP entry keeps
its behaviour and no new entries are enabled here.

Tests force the config keys per case, check each shape really reaches the 2-D
kernel, compare split against stock elementwise within a few bf16 ULP, and
cover bf16 and fp8, with and without sinks, head_size 64 and 512, a ragged
batch with negative context_len, and shuffled KV.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexnails
alexnails force-pushed the unified-attn-fasttile branch from 4943830 to 2eca6ce Compare September 29, 2026 22:12
@alexnails alexnails changed the title [Triton/Gluon] unified_attention: restructure the 2-D prefill tile loop — unmasked bulk + masked tail unlocks pipelining (−12.8% kernel, gfx950, default off) [Triton] unified_attention: share the split-loop tile body, extend it to shuffled KV (follow-up to #4761) Sep 29, 2026
@alexnails

Copy link
Copy Markdown
Author

@cagrikymk I think this is ready for rereview, one thing I want to note is that num_stages:= 2 seems to be a better choice in most cases from different workloads I have run. Any thoughts on this?

@cagrikymk

Copy link
Copy Markdown
Contributor

@cagrikymk I think this is ready for rereview, one thing I want to note is that num_stages:= 2 seems to be a better choice in most cases from different workloads I have run. Any thoughts on this?

@alexnails I went through the code a bit, while this is a step towards the right direction to keep the UA kernel easier to maintain, I think this will need a bigger rewrite.

What I have in mind is more aligned with the gfx950 gluon kernel: https://github.com/ROCm/aiter/blob/main/aiter/ops/triton/_gluon_kernels/gfx950/attention/unified_attention.py

Having single 2d/3d implementation and parameterizing it based on the workload.

It might better for me to manage this more closely so I can verify codegen doesnt change enough on any arch, given this kernel is used by many archs.

What do you think?

@cagrikymk

Copy link
Copy Markdown
Contributor

@cagrikymk I think this is ready for rereview, one thing I want to note is that num_stages:= 2 seems to be a better choice in most cases from different workloads I have run. Any thoughts on this?

@alexnails I went through the code a bit, while this is a step towards the right direction to keep the UA kernel easier to maintain, I think this will need a bigger rewrite.

What I have in mind is more aligned with the gfx950 gluon kernel: https://github.com/ROCm/aiter/blob/main/aiter/ops/triton/_gluon_kernels/gfx950/attention/unified_attention.py

Having single 2d/3d implementation and parameterizing it based on the workload.

It might better for me to manage this more closely so I can verify codegen doesnt change enough on any arch, given this kernel is used by many archs.

What do you think?

What I have in mind is alongside: https://github.com/ROCm/aiter/blob/21fd4b40f5c0d5ceba918e391c6ce8f1a656757b/aiter/ops/triton/_triton_kernels/attention/unified_attention.py

I need to verify the codegen on different archs to make sure this still produces ~identical code across archs.

I think we can close this PR and continue with the design I have for better modularity, if you also agree.

@alexnails alexnails closed this Oct 10, 2026
@alexnails

Copy link
Copy Markdown
Author

@cagrikymk I have closed this for now at your request, but please reach out once your new changes are ready, thank you

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