Repository navigation
[Triton/Gluon] Add MXFP8 Flash Attention v2 (gfx950 / CDNA4) - #5578
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags & labels: |
1916984 to
4ec9455
Compare
4ec9455 to
950be3b
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved correctness, validation, configuration, and coverage issues block approval.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Adds a gfx950-only Triton MXFP8 Flash Attention v2 implementation with forward/backward kernels, wrappers, configuration, tests, and benchmarking.
Changes:
- Added MXFP8 attention kernels and public wrappers.
- Added gfx950 detection, export gating, and tuning configuration.
- Added correctness tests and performance benchmarking.
File summaries
| File | Reviewed change |
|---|---|
op_tests/triton_tests/attention/test_mxfp8_attention_kernel.py |
MXFP8 attention correctness tests |
op_tests/op_benchmarks/triton/bench_mxfp8_attention.py |
Attention performance benchmark |
aiter/ops/triton/utils/_triton/arch_info.py |
gfx950 architecture detection |
aiter/ops/triton/configs/gfx950/triton/attention/mxfp8_attn/DEFAULT.json |
gfx950 kernel tuning configuration |
aiter/ops/triton/attention/mxfp8_attention.py |
Forward and backward wrappers |
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py |
Forward/backward Triton kernels |
aiter/ops/triton/__init__.py |
Public export and architecture gating |
Review details
Suppressed comments (18)
aiter/ops/triton/init.py:177
- The new CDNA4 check is only in
__getattr__. The custom finder below handlesimport aiter.ops.triton.mxfp8_attentionand imports the module without this check, so the documented import-time restriction is bypassed for the other supported legacy import form. Apply the same gate in the finder or adjust the import contract.
_CDNA4_ONLY = frozenset({"mxfp8_attention"})
if name in _BACKWARD_COMPAT_MAP:
if name in _CDNA4_ONLY:
from aiter.ops.triton.utils._triton.arch_info import is_cdna4
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py:1361
- The backward autotune key contains
BLOCK_DMODEL, but neither backward entry kernel has that parameter; both receiveBLOCK_DMODEL_QKandBLOCK_DMODEL_Vinstead. Resolving the autotune key for either backward launch therefore cannot find the requested value. Key on the parameters that are present in both signatures.
"BLOCK_DMODEL",
"CAUSAL",
"use_mxfp8",
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py:1635
- For the valid combination
block_m_dkv_bwd=32and head dimension 32, bothSCALE_NUM_PER_MandSCALE_NUM_PER_D_Vare odd, so this branch does not assigndo_descaledbut the following dot still uses it. The quantized backward kernel then fails to compile for a supported public parameter combination; handle the odd-scale case or reject the combination.
dv += tl.dot(
tl.trans(p), do_descaled, out_dtype=tl.float32, allow_tf32=False
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py:1688
- For
block_m_dkv_bwd=32and head dimension 32,SCALE_NUM_PER_MandSCALE_NUM_PER_D_QKare both odd, soq_descaledis never assigned before this dot. This is another compile-time failure for a combination accepted by the wrapper; add the missing unpack path or validate the supported shape set.
_dk = tl.dot(
tl.trans(ds), q_descaled, out_dtype=tl.float32, allow_tf32=False
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py:2389
- For
block_n_dq_bwd=32and head dimension 32,SCALE_NUM_PER_NandSCALE_NUM_PER_D_QKare both odd, sok_descaledis not assigned in the preceding conditional but is used here. The quantized dQ kernel therefore cannot compile for this supported public combination; handle or reject it explicitly.
_dq = tl.dot(ds, k_descaled, out_dtype=tl.float32, allow_tf32=False)
dq += _dq
aiter/ops/triton/_triton_kernels/attention/mxfp8_attention_kernel.py:1196
- The implementation contradicts its own padding comment:
max(..., 16)leaves a 16-wide head dimension unchanged, but MXFP8 requires the 32-element quantization block and the wrapper rejects this at its divisibility assertion. A validhead_size=16call therefore fails; pad to at least 32 or explicitly reject/document that dimension.
# Get closest power of 2 over or equal to 32.
padded_d_model = 1 << (head_size - 1).bit_length()
# Smallest head_dim supported is 16. If smaller, the tile in the
# kernel is padded - there is no padding in memory for any dims.
padded_d_model = max(padded_d_model, 16)
aiter/ops/triton/attention/mxfp8_attention.py:200
- This hardcodes
matrix_instr_nonkdim=16in the wrapper instead of obtaining it from the JSON-backed tuning config. That prevents the new attention config from expressing this compile-time choice per architecture/shape; move the value into the MXFP8 attention config and pass the loaded entry through.
kernel_kwargs = {}
if padded_d_model_qk % 128 == 0 and block_n % 128 == 0:
kernel_kwargs["matrix_instr_nonkdim"] = 16
aiter/ops/triton/attention/mxfp8_attention.py:464
- The backward wrapper repeats the same hardcoded
matrix_instr_nonkdim=16tuning override here. Keeping this second path in Python makes the backward tile non-configurable; use the JSON-backed kernel configuration instead.
kernel_kwargs = {}
if (
block_n_dq_bwd % 128 == 0
and padded_d_model_qk % 128 == 0
and padded_d_model_v % 128 == 0
):
kernel_kwargs["matrix_instr_nonkdim"] = 16
aiter/ops/triton/attention/mxfp8_attention.py:551
- The dK/dV launch has a third hardcoded
matrix_instr_nonkdim=16override. This duplicates the tuning decision in another branch and can diverge from the published config; source it from the shared JSON-backed configuration.
if (
block_m_dkv_bwd % 128 == 0
and padded_d_model_qk % 128 == 0
and padded_d_model_v % 128 == 0
):
kernel_kwargs["matrix_instr_nonkdim"] = 16
else:
kernel_kwargs = {}
aiter/ops/triton/attention/mxfp8_attention.py:313
- The backward path has the same varlen failure: a
thdcall with omitted cu-sequences is converted to integer0, thenget_shape_from_layoutapplieslen()to it. Sincethdis part of the public layout contract, require/validate sequence tensors instead of using this sentinel.
if cu_seqlens_q is None:
cu_seqlens_q = 0
if cu_seqlens_k is None:
cu_seqlens_k = 0
aiter/ops/triton/attention/mxfp8_attention.py:356
- When only one of
dkordvis supplied, this branch allocates both new tensors and silently discards the caller's non-None buffer. The API marks both outputs independently optional, so handle the two buffers independently (or reject partial output buffers) rather than returning a different tensor than the one supplied.
if dk is None or dv is None:
dk = torch.zeros_like(k, dtype=bwd_dtype)
dv = torch.zeros_like(v, dtype=bwd_dtype)
aiter/ops/triton/attention/mxfp8_attention.py:75
- The public forward docstring says q, k, and v are always FP8, but the exposed
use_mxfp8=Falsemode (the mode used by the new test) accepts floating-point tensors. Document both input modes so callers do not pass the wrong dtype based on the API contract.
q, k, v: Query, Key, Value tensors in FP8 format.
aiter/ops/triton/attention/mxfp8_attention.py:94
is_cdna4()is an exact gfx950 check, so this message incorrectly suggests that newer architectures are supported. A caller on a newer or gfx942 device will still fail the assertion; report the actual gfx950-only requirement.
assert is_cdna4(), "mxfp8 attention requires gfx950 or newer"
aiter/ops/triton/attention/mxfp8_attention.py:304
- The backward assertion repeats the same inaccurate “or newer” message even though
is_cdna4()only returns true for gfx950. Use an error message that matches the implemented architecture gate.
assert is_cdna4(), "mxfp8 attention requires gfx950 or newer"
aiter/ops/triton/attention/mxfp8_attention.py:307
- Backward does not perform the alignment checks that forward performs for
quant_block_sizeand all four block sizes. A caller can pass a non-multiple (for example, 48), after which the kernels truncateBLOCK_* // QUANT_BLOCK_SIZEand use inconsistent scale layouts instead of rejecting the input. Validate these parameters and the padded head dimensions before launching.
use_exp2 = True
quant_size = 32
aiter/ops/triton/attention/mxfp8_attention.py:111
ois allocated as a leaf withrequires_grad=True, but this function does not connect it to q/k/v or register an autograd function; calling.backward()on the returned output therefore cannot invokemxfp8_attention_backwardor populate input gradients. Either remove the misleading flag or provide/document a real autograd integration.
o = torch.empty(
o_shape,
device=q.device,
dtype=torch.bfloat16 if use_mxfp8 else q.dtype,
requires_grad=True,
op_tests/op_benchmarks/triton/bench_mxfp8_attention.py:64
- The benchmark registers only the forward provider, so the three newly added backward entry kernels have no benchmark target. The kernel contribution should include a backward timing path as well, otherwise its performance is not measured by the shipped benchmark.
line_arg="provider",
line_vals=["attn_fwd_mxfp8"],
line_names=[
f"attn_fwd_mxfp8 ({'causal' if causal else 'non-causal'}) ({unit})"
op_tests/triton_tests/attention/test_mxfp8_attention_kernel.py:8
- The docstring says this test runs on gfx942 and gfx950, but the marker immediately skips every architecture except gfx950 and the wrapper also asserts gfx950. This makes the documented support scope incorrect.
Only runs on FP8-capable architectures (gfx942, gfx950).
- Files reviewed: 7/7 changed files
- Comments generated: 9
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
950be3b to
24d4bab
Compare
bddac3a to
e028d39
Compare
e028d39 to
f221811
Compare
vgokhale
left a comment
There was a problem hiding this comment.
Review: PR #5578 — MXFP8 Flash Attention v2 (gfx950 / CDNA4)
This is a Triton kernel, not Gluon. So the Gluon import and version-gate checks do not apply here. The mechanics are correct. The main concern is rule 5 and rule 6: the kernel copies the flash_attn_triton_amd reference instead of building on it.
What is correct
- The kernel is in the right folder:
_triton_kernels/attention/. The wrapper is inops/triton/attention/. The config is atconfigs/gfx950/triton/attention/mxfp8_attn/DEFAULT.json. This matches rule 4. - The new
is_cdna4()arch helper is small and clear. - Rule 1 (repr) is met. All four launched kernels have
repr=:attn_fwd_mxfp8,_bwd_kernel_dkdv_mxfp8,_bwd_kernel_dq_mxfp8, and_bwd_preprocess_use_o_mxfp8. - A benchmark and tests are present. The PR went through a review round.
- The mxfp8 scale math is new work. It uses e4m3 data with e8m0 group scales in the attention inner loop. The per-tensor fp8 path in
mha.pydoes not do this.
Rule 6 — the kernel re-defines shared helper functions
The kernel imports only kernel_repr, tuned_config_utils, and arch_info. It imports none of the shared attention code. Instead it defines the standard flash-attention helpers again in this file:
cdiv_fndropout_offsets,dropout_rng,dropout_maskload_fncompute_alibi_block_attn_fwd_inner, and the two backward inner loops
These functions are the AMD Triton flash-attention reference helpers. Two specific points:
compute_alibi_blockalready exists in_triton_kernels/flash_attn_triton_amd/common.py. This PR copies it. It should import it instead.cdiv_fnis now in 8 files in the attention tree. This is an older repo problem, not only this PR. But the PR adds one more copy.dropout_*andload_fnare the standard reference helpers, defined again here.
A large part of the 2779 lines is copied flash-attention code. The new part is the mxfp8 scale handling. Rule 6 asks that common functions go in utils. Please import the shared helpers and build on the flash_attn_triton_amd base.
Rule 5 — the non-quantized mode overlaps mha.py
The kernel is not mxfp8 only. use_mxfp8 is a constexpr with 43 branch sites. The public function mxfp8_attention_forward(..., use_mxfp8: bool = True) also supports use_mxfp8=False. In that mode the kernel runs as a plain bf16/fp16 flash attention. This mode does the same work as mha.py.
If the non-quantized mode is only a reference for tests, do not ship it as a public API mode. If it is for production, it is a duplicate of the existing flash attention. The mxfp8 work fits better as a quant mode on the shared flash-attention base, not as a second full kernel.
One fair point for the other side: the repo already splits attention kernels by quant scheme (fav3_sage_attention vs fav3_sage_attention_mxfp4). So a separate mxfp8 file has precedent. The problem is not the separate file. The problem is that the kernel re-defines the common helpers and the non-quantized path.
Tests — remove fp16
test_mxfp8_attention_kernel.py:154 uses dtype=[torch.bfloat16, torch.float16]. fp16 is not a target dtype. aiter targets bf16, fp8, and fp4. Please remove float16 and keep bfloat16. The rest of the coverage is good: use_mxfp8=[False, True], e4m3 plus e8m0 scales, and both causal modes, checked against an fp32 dequant reference.
Summary
The kernel meets rule 1, rule 4, and has a benchmark and tests. The mxfp8 inner-loop work is real. The main asks are rule 5 and rule 6. The kernel copies the flash_attn_triton_amd reference: it defines compute_alibi_block again (it is already in common.py), plus cdiv_fn, dropout_*, load_fn, and the flash-attention inner loops. It also ships a non-quantized mode that overlaps mha.py. Please import the shared helpers, build the mxfp8 mode on the common base, remove or re-route the non-quantized path, and drop fp16 from the tests.
Thanks for the review. Addressed the rule 5 and rule 6 items that are local to this kernel. Rule 5 —— use_mxfp8=False is no longer a public mode. mxfp8_attention_forward and mxfp8_attention_backward always run the MXFP8 path (e4m3 data, e8m0 group scales), and the non-quantized branches are removed from the kernels. Plain bf16/fp16 attention stays on mha.py / flash_attn_triton_amd. The MXFP8 inner loop is new work: the existing per-tensor FP8 path does not apply e8m0 block scales inside the attention loop, so this stays a separate kernel, same as fav3_sage vs fav3_sage_mxfp4. Rule 6 —— compute_alibi_block is now imported from triton_kernels/flash_attn_triton_amd/common.py. The copied dropout* helpers are removed. Dropout and bias are rejected by the wrapper and have no backward, so those paths are not part of this kernel. cdiv_fn and load_fn are still defined here. flash_attn_triton_amd inlines tl.cdiv and does not export load_fn. The only other copies are private helpers in mha.py (_cdiv_fn, _load_fn). I did not import those. The forward and backward inner loops stay in this file because that is where the MXFP8 scale unpack and tl.dot_scaled live. They are not a second copy of the bf16 flash-attention loop. Tests —— Dropped fp16 and the use_mxfp8=False cases. Coverage is bf16 only, quantized forward and backward, GQA, and causal, checked against an fp32 dequant reference. |
micmelesse
left a comment
There was a problem hiding this comment.
This pr has similar issues to #5577. It introduces a new public api rather than extending the existing mha api. We already have an mha api that supports fp8. If you want to add mxfp8 as a feature, it seems better to add the feature to the api.
|
@WuLei-AMD is this PR still relevant? Please address the review comments if so. Thanks! |
ab96788 to
1371abd
Compare
MXFP8 is now a mode of flash_attn_func, not a separate call that callers have to find. The existing FP8 arguments are q_descale, k_descale, and v_descale: one fp32 scalar per (batch, head) for the whole sequence. MXFP8 does not fit that layout. Q, K, and V are e4m3, and the e8m0 scales are (batch, seqlen/32, nheads, headdim/32), one scale per 32 elements on both the sequence and the head dimension. flash_attn_func now takes keyword-only q_mx_scale, k_mx_scale, v_mx_scale, and mx_p_scale (default 127). q, k, and v stay in (batch, seqlen, nheads, headdim). softmax_scale still defaults to 1/sqrt(headdim). If these arguments are omitted, the call takes the same path as before. backend="gluon", dropout, bias, sink, and sliding window are rejected for this mode. The public MXFP8 call is forward-only. The backward kernels write dq, dk, and dv that autograd cannot attach to fp8 inputs, so requires_grad=True raises instead of dropping the gradient. mxfp8_attention_backward is unchanged. |
1371abd to
ee16054
Compare
The comments have been addressed and fixed.
Adds a full MXFP8 (block-scaled FP8) Flash Attention v2 forward and
backward implementation targeting gfx950 (CDNA4 / MI350X).
New files:
_triton_kernels/attention/mxfp8_attention_kernel.py (~2700 lines):
attn_fwd_mxfp8, _bwd_kernel_dkdv_mxfp8, _bwd_kernel_dq_mxfp8,
_bwd_preprocess_use_o_mxfp8. Uses block-scaled e4m3 FP8 with
QUANT_BLOCK_SIZE-aligned scale tensors for Q, K, V.
attention/mxfp8_attention.py: Python wrappers
mxfp8_attention_forward / mxfp8_attention_backward with runtime
assert is_cdna4() guard and padded_head_dim alignment checks.
Also includes fp8_attention_kernel.py (shared kernel dependency from
the preceding FP8 attention PR).
Registered in _BACKWARD_COMPAT_MAP under "mxfp8_attention" with an
is_cdna4() gate in __getattr__ — importing on gfx942 or other archs
raises NotImplementedError instead of a cryptic AssertionError.
kernel: - Remove num_warps/num_stages from _FWD/_BWD_FALLBACK; tuning values live in JSON config, not Python fallback objects. wrapper: - Reject layout='thd' (varlen) in both forward and backward with NotImplementedError until implemented. - Reject bias and dropout_p > 0 in forward (no backward support). - Reject alibi_slopes in backward (not implemented). - Add GQA shape validation: num_q_heads must be divisible by num_kv_heads. - Add V batch size validation. - Fix num_block_m bug: dK/dV kernel used dQ's block size; now each kernel gets its own num_block_m computed from its block_m parameter. - Add backward docstring with args, returns, and unsupported options. bench: - Fix arch gate from FP8_ARCHS to gfx950 (MXFP8 requires CDNA4 only).
The previous tests and benchmark only ran use_mxfp8=False, so the block-scaled FP8 kernels and backward could regress while CI stayed green.
CI shard 5 failed at collection because autotune keyed on BLOCK_DMODEL, which is not a kernel argument. Also unpack dO/Q/K on every odd SCALE_NUM branch so Triton SSA can compile block=32 / head_dim=32.
The wrapper is imported via aiter.ops.triton.attention.mxfp8_attention; registering the compat alias was unnecessary and triggered Flash Attention integration CI.
Remove the public use_mxfp8 flag so the kernel only covers the MXFP8 path; plain bf16/fp16 attention stays on mha.py. Import compute_alibi_block from flash_attn_triton_amd.common and drop the unused dropout helpers. Tests are bf16 quantized only.
Add keyword-only MXFP8 scale arguments and dispatch to the MXFP8 kernel only when they are set, so existing flash_attn_func callers stay on the current Triton and Gluon paths.
Forward and backward tests now include a second batch, longer sequences with more scale rows, and a 96-token sequence whose last 64-wide tile is only half full. Co-authored-by: Cursor <[email protected]>
ee16054 to
8f273af
Compare
NOT READY FOR HUMAN REVIEWPR 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 |
* [Triton] Add MXFP8 Flash Attention v2 (gfx950 / CDNA4) Adds a full MXFP8 (block-scaled FP8) Flash Attention v2 forward and backward implementation targeting gfx950 (CDNA4 / MI350X).
Summary
Adds a pure-Triton MXFP8 Flash Attention v2 implementation for gfx950 (CDNA4 / MI300X), including forward and backward passes.
Uses MXFP8 block-scaling (E8M0 microscales, one uint8 per 32 elements along the head dimension). Requires gfx950; asserts at runtime on other architectures.
Changes
_triton_kernels/attention/mxfp8_attention_kernel.py: Triton kernels for forward (attn_fwd_mxfp8) and backward (_bwd_kernel_dkdv_mxfp8,_bwd_kernel_dq_mxfp8,_bwd_preprocess_use_o_mxfp8). All 6 public kernels have repr decorators. Autotune configs resolved viaget_tuned_kernel_config()backed by JSON. Dead code removed (get_padded_headsize,get_input_shapes).attention/mxfp8_attention.py: Python wrappersmxfp8_attention_forwardandmxfp8_attention_backward.utils/_triton/arch_info.py: Add canonicalis_cdna4()definition (was used in__init__.pyand the wrapper but missing from the module).configs/gfx950/triton/attention/mxfp8_attn/DEFAULT.json: Per-arch pinned tile config.__init__.py: Exportmxfp8_attentionunder the_CDNA4_ONLYgate.triton_tests/attention/test_mxfp8_attention_kernel.py: Correctness tests (skip on non-gfx950 architectures).bench_mxfp8_attention.py: Benchmark across representative shapes.Test results
Verified on MI350X (gfx950):
✅ MHA / GQA (num_q_heads ≠ num_kv_heads)
✅ causal on / off
✅ bf16 and fp16 (use_mxfp8=False: verifies core attention correctness without MXFP8 quantization)