Repository navigation
[Triton/Gluon] [GFX950] Productize gluon mha kernel from GFX950-gluon-tutorials - #5153
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
a0f2ec4 to
7a545a5
Compare
There was a problem hiding this comment.
Pull request overview
Adds a new gfx950-specific Gluon-based MHA forward kernel and wires it into the existing Triton MHA dispatch so eligible forward-only (no-grad) calls can run on the Gluon implementation for improved throughput.
Changes:
- Route
aiter/ops/triton/attention/mha.pyforward to a new Gluon MHA kernel when gradients aren’t being built and unsupported features are absent. - Introduce a new Gluon kernel implementation for gfx950 dense MHA forward (
mha_fwd.py) including host-side eligibility checks and launch code.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| aiter/ops/triton/attention/mha.py | Adds a Gluon forward eligibility gate and dispatches forward-only calls to the gfx950 Gluon kernel. |
| aiter/ops/triton/_gluon_kernels/gfx950/attention/mha_fwd.py | New gfx950 Gluon dense MHA forward kernel + host predicate/launcher. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.
Suppressed comments (2)
Previously missed (1) — in code that hasn't changed since the last review.
aiter/ops/triton/_gluon_kernels/gfx950/attention/mha_fwd.py:614
- This comment says dead rows write
+infto LSE, but the value actually written isDEAD_ROW_LSE(passed from the host, and currently set to 0.0 inattention/mha.py, matching the Triton MHA kernel’s behavior). Please update the comment to reflect the actual semantics so future call sites don’t rely on the wrong contract.
This issue also appears on line 1237 of the same file.
if n_blocks <= 0:
# Every row of this Q block is fully masked: write zeros to O and +inf to LSE.
offs_m_z = start_m * BLOCK_M + gl.arange(0, BLOCK_M, layout=offs_m_layout)
aiter/ops/triton/_gluon_kernels/gfx950/attention/mha_fwd.py:1240
dead_row_lsedefaults to-inf, but the main wrapper (attention/mha.py) passes0.0to match the existing Triton MHA behavior for fully-masked rows. Consider defaulting this to0.0(and documenting it) so direct callers ofmha_fwd_gluon()don’t accidentally get behavior that diverges from the rest of the attention stack.
layout: str = "bshd",
out: torch.Tensor | None = None,
dead_row_lse: float = float("-inf"),
) -> tuple[torch.Tensor, torch.Tensor]:
0485bd1 to
1107c9b
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
It introduces a large new architecture-specific GPU kernel and a new dispatch path that needs stronger robustness (import-guarding) and dedicated test coverage/hardware validation before approval.
Review details
Suppressed comments (1)
aiter/ops/triton/attention/mha.py:428
- This PR adds a new launch path to a new Gluon MHA kernel (
mha_fwd_gluon), but there are no accompanying test updates to exercise the new selection logic / kernel correctness. The existing MHA tests underop_tests/triton_tests/attention/don’t reference the Gluon path, so regressions in_use_gluon_fwdgating or the Gluon kernel would go unnoticed.
# The Gluon kernel is forward-only: it produces no residuals for this
# module's backward, so it is taken only when no gradient is being built.
# `is_grad` already answers that question exactly.
if not is_grad and _use_gluon_fwd(
- Files reviewed: 2/2 changed files
- Comments generated: 2
- Review effort level: Lite
6baf8ad to
db9a708
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The fallback stub for is_mha_gluon_avail will raise at runtime when the Gluon import fails, and the new dispatch path needs targeted unit coverage to prevent silent regressions.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Review details
Suppressed comments (2)
aiter/ops/triton/attention/mha.py:447
- A new forward-only Gluon execution path is added here, but the existing MHA tests do not exercise it (no tests reference
is_mha_gluon_avail/mha_fwd_gluon). Please add a unit test that runs on gfx950 (skipping otherwise) to validate correctness for at least one causal and one non-causal shape and to ensure this branch is actually taken.
# The Gluon kernel is forward-only: it produces no residuals for this
# module's backward, so it is taken only when no gradient is being built.
# `is_grad` already answers that question exactly.
if not is_grad and _use_gluon_fwd(
q,
k,
v,
causal,
dropout_p=dropout_p,
window_size=window_size,
bias=bias,
alibi_slopes=alibi_slopes,
sink=sink,
config=config,
):
out_padded, softmax_lse = mha_fwd_gluon(
q, k, v, softmax_scale, causal, dead_row_lse=0.0
)
aiter/ops/triton/_gluon_kernels/gfx950/attention/mha_fwd.py:614
- This comment says the kernel writes "+inf" to LSE for fully-masked rows, but the code actually stores
DEAD_ROW_LSE(a constexpr parameter, defaulting to-infand passed as0.0from the wrapper). The comment should match the implemented behavior to avoid confusion when debugging numerics.
if n_blocks <= 0:
# Every row of this Q block is fully masked: write zeros to O and DEAD_ROW_LSE to LSE.
offs_m_z = start_m * BLOCK_M + gl.arange(0, BLOCK_M, layout=offs_m_layout)
- Files reviewed: 2/2 changed files
- Comments generated: 1
- Review effort level: Lite
There was a problem hiding this comment.
🔵 Needs a closer look
The Gluon import fallback currently introduces a runtime TypeError when the import fails (stub signature mismatch), and the new kernel path also lacks a dedicated unit test to validate selection/accuracy on gfx950.
Review details
Suppressed comments (2)
aiter/ops/triton/attention/mha.py:18
- Fallback stub for is_mha_gluon_avail has an incompatible signature: _use_gluon_fwd calls it with positional args (q, k, v, causal), but the stub only accepts **kwargs, so if the import fails this will raise TypeError and break MHA forward. Also, the bare
exceptwill silently swallow real bugs in the gluon module; this should only fall back on ImportError/ModuleNotFoundError.
except: # noqa: E722
is_mha_gluon_avail = lambda **kwargs: False
mha_fwd_gluon = None
aiter/ops/triton/attention/mha.py:437
- This PR adds a new forward-only Gluon MHA fast-path, but there is no unit test that exercises the Gluon selection/accuracy on gfx950 (existing tests like op_tests/triton_tests/attention/test_mha.py cover the default path, but do not assert the gluon path is correct/selected). Per the Triton ops review rules, new kernels should ship with a matching unit test under op_tests/triton_tests/attention/.
if not is_grad and _use_gluon_fwd(
q,
k,
v,
causal,
- Files reviewed: 2/2 changed files
- Comments generated: 0 new
- Review effort level: Lite
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved FP16 overflow and FP8 scale-handling defects can produce incorrect attention outputs.
6 open findings
Preserve causal mask when scaling FP8 scores · New Apply FP16 softmax scaling after FP32 score computation · New Add Gluon tests for non-PE head sizes 96 and 192 · New Use row minimum for negative FP8 softmax scales · New Share FP8 staging loop with attention inner loop · New Move dispatch cutoff from Python into MHA JSON · New
3 resolved since last review
🧠 Review effort: Balanced
|
The new kernel is pretty large and a bit hard to read. Is it possible to try to simplify somewhat, maybe even split into multiple kernels? For example it seems that _attn_fwd_inner and _attn_fwd_pipelined are quite different kernel strategies that could be split into different kernels with some common utils/functions and chosen by the python wrapper instead of doing it inside the kernel itself. Just an idea, other ways to more it less dense/more readable would work too. |
Rework the gfx950 Gluon MHA forward kernel (_attn_fwd): - K/V (and the PE slice) are staged global->LDS by async copy into row-staggered padded shared layouts, double buffered, so no tile passes through VGPRs. The host checks the copy's alignment needs (kv_async_copy_ok) and copies K/V into contiguous buffers when a view fails them. - Full key blocks run a rotated four-cluster warp pipeline (_attn_fwd_pipelined): the two waves of a SIMD run one cluster apart, so the softmax issues in the shadow of the other wave's MFMAs. Masked, windowed and short ranges keep the one-tile loop (_attn_fwd_inner), and a sliding window's interior blocks take the pipeline too. - A padded head dim that splits into power-of-two slices (96 -> 64 + 32, ...) is issued as two MFMA chains instead of one padded tile (_head_slices). - fp8 scales P statically onto e4m3's range instead of quantizing it with a per-tile amax, and applies descale_v once in the epilogue. - bf16 folds the softmax scale into Q once (SCALE_ON_Q); fp16 does not, since q * scale can overflow it. The host requires sm_scale >= 0, and a zero fp8 scale is clamped so masked scores stay -inf. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Pick the tile per shape instead of one per dtype (BLOCK_M = 32 * num_warps): - bf16/fp16 default: 256 x 64 with 8 waves. Two waves per SIMD let the pipeline overlap the softmax with MFMA. - Causal below causal_wide_min_seqlen_k (4096) keys, and a causal sliding window: 128 x 64 with 4 waves, which wastes less on the masked diagonal. - V head dim > 128: 128 x 32; the default tile spills. - PE: 256 x 64 / 8 waves for a V head <= 64, else 128 x 32. - fp8 with a 64-wide head: 128 x 128, to amortise the softmax. The tiles and the causal cutoff live in mha.json. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
af43ca1 to
cfce124
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Pre-scaling Q in BF16 can alter attention weights through rounding or overflow even when FP32 scores remain finite, and regression tests for these cases are missing.
7 open issues
Preserve FP32 score scaling to avoid BF16 rounding and overflow · New Remove PyTorch dependency from torch-free kernel utilities · New Clone only K or V when that tensor fails alignment checks · New Use consistently rounded scores for FP16 softmax Compute the row maximum after scaling Cover split accumulators and stores for V head sizes 80 and 96 · New Add regression coverage for strided and misaligned K/V clone paths · New
1 resolved since last review
Review effort: Balanced
Hi @lburzawa , thanks for your comment. I have refactored the kernel file to reduce the line number from 3077 to 1997. Which include 1) merge fp8 kernel function into
|
…-tutorials (#5153) This PR aims to productize the gluon fmha_v3 from [gfx950-gluon-tutorials/kernels/attention/fmha_v3.py](https://github.com/ROCm/gfx950-gluon-tutorials/blob/main/kernels/attention/fmha_v3.py) The main changes include: - Double-buffer and Async_copy on K/V with padded shared layout. - Introduce rotated four-stage warp pipeline(_attn_fwd_pipelined) as the Fast Path. Keep and optimize the origin one-tile loop(_attn_fwd_inner) as a fall-back. - Adopt split head dims: a padded head dim (e.g. 96 → 64 + 32) runs as two power-of-two MFMA slices instead of one padded tile. - Mha config tuning: 256×64 with 8 waves by default, 128×64 with 4 waves for causal below 4096 keys and causal sliding windows
…-tutorials (ROCm#5153) This PR aims to productize the gluon fmha_v3 from [gfx950-gluon-tutorials/kernels/attention/fmha_v3.py](https://github.com/ROCm/gfx950-gluon-tutorials/blob/main/kernels/attention/fmha_v3.py) The main changes include: - Double-buffer and Async_copy on K/V with padded shared layout. - Introduce rotated four-stage warp pipeline(_attn_fwd_pipelined) as the Fast Path. Keep and optimize the origin one-tile loop(_attn_fwd_inner) as a fall-back. - Adopt split head dims: a padded head dim (e.g. 96 → 64 + 32) runs as two power-of-two MFMA slices instead of one padded tile. - Mha config tuning: 256×64 with 8 waves by default, 128×64 with 4 waves for causal below 4096 keys and causal sliding windows



This PR aims to productize the gluon fmha_v3 from gfx950-gluon-tutorials/kernels/attention/fmha_v3.py
The main changes include:
cc: @Dewei-Wang-sh