Skip to content

[Triton/Gluon] Add MXFP8 Flash Attention v2 (gfx950 / CDNA4) - #5578

Merged
ZhangDanyang-AMD merged 8 commits into
ROCm:mainfrom
WuLei-AMD:dev_lumen_pr10_mxfp8_attention
Nov 3, 2026
Merged

ZhangDanyang-AMD merged 8 commits into
ROCm:mainfrom
WuLei-AMD:dev_lumen_pr10_mxfp8_attention

Conversation

@WuLei-AMD

@WuLei-AMD WuLei-AMD commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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 via get_tuned_kernel_config() backed by JSON. Dead code removed (get_padded_headsize, get_input_shapes).
  • attention/mxfp8_attention.py: Python wrappers mxfp8_attention_forward and mxfp8_attention_backward.
  • utils/_triton/arch_info.py: Add canonical is_cdna4() definition (was used in __init__.py and the wrapper but missing from the module).
  • configs/gfx950/triton/attention/mxfp8_attn/DEFAULT.json: Per-arch pinned tile config.
  • __init__.py: Export mxfp8_attention under the _CDNA4_ONLY gate.
  • 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)

@WuLei-AMD
WuLei-AMD requested a review from a team September 16, 2026 07:26
@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; 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 5578 --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.

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

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 handles import aiter.ops.triton.mxfp8_attention and 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 receive BLOCK_DMODEL_QK and BLOCK_DMODEL_V instead. 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=32 and head dimension 32, both SCALE_NUM_PER_M and SCALE_NUM_PER_D_V are odd, so this branch does not assign do_descaled but 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=32 and head dimension 32, SCALE_NUM_PER_M and SCALE_NUM_PER_D_QK are both odd, so q_descaled is 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=32 and head dimension 32, SCALE_NUM_PER_N and SCALE_NUM_PER_D_QK are both odd, so k_descaled is 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 valid head_size=16 call 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=16 in 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=16 tuning 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=16 override. 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 thd call with omitted cu-sequences is converted to integer 0, then get_shape_from_layout applies len() to it. Since thd is 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 dk or dv is 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=False mode (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_size and all four block sizes. A caller can pass a non-multiple (for example, 48), after which the kernels truncate BLOCK_* // QUANT_BLOCK_SIZE and 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

  • o is allocated as a leaf with requires_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 invoke mxfp8_attention_backward or 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.

@WuLei-AMD
WuLei-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch from 950be3b to 24d4bab Compare September 16, 2026 11:59
@zufayu
zufayu requested review from a team and Dewei-Wang-sh September 17, 2026 01:11
@ZhangDanyang-AMD
ZhangDanyang-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch 5 times, most recently from bddac3a to e028d39 Compare September 23, 2026 04:05
@WuLei-AMD
WuLei-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch from e028d39 to f221811 Compare September 23, 2026 04:09

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

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 in ops/triton/attention/. The config is at configs/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.py does 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_fn
  • dropout_offsets, dropout_rng, dropout_mask
  • load_fn
  • compute_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_block already exists in _triton_kernels/flash_attn_triton_amd/common.py. This PR copies it. It should import it instead.
  • cdiv_fn is 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_* and load_fn are 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.

@WuLei-AMD

Copy link
Copy Markdown
Contributor Author

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 in ops/triton/attention/. The config is at configs/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.py does 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_fn
  • dropout_offsets, dropout_rng, dropout_mask
  • load_fn
  • compute_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_block already exists in _triton_kernels/flash_attn_triton_amd/common.py. This PR copies it. It should import it instead.
  • cdiv_fn is 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_* and load_fn are 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 micmelesse 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.

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.

@vgokhale

vgokhale commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@WuLei-AMD is this PR still relevant? Please address the review comments if so. Thanks!

@WuLei-AMD
WuLei-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch from ab96788 to 1371abd Compare October 8, 2026 04:25
@WuLei-AMD

Copy link
Copy Markdown
Contributor Author

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.

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.

@WuLei-AMD
WuLei-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch from 1371abd to ee16054 Compare October 21, 2026 04:47
@WuLei-AMD
WuLei-AMD requested a review from micmelesse October 21, 2026 04:49
@ZhangDanyang-AMD
ZhangDanyang-AMD dismissed stale reviews from micmelesse and vgokhale November 3, 2026 05:16

The comments have been addressed and fixed.

WuLei-AMD and others added 8 commits November 3, 2026 13:18
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]>
@ZhangDanyang-AMD
ZhangDanyang-AMD force-pushed the dev_lumen_pr10_mxfp8_attention branch from ee16054 to 8f273af Compare November 3, 2026 05:18
@aiter-bot

Copy link
Copy Markdown

NOT READY FOR HUMAN REVIEW

PR Self-Review

Revision 8f273afb54a7 · mode shadow

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

  1. What behavior does this PR change, and why is the existing behavior insufficient?
  2. What did you validate, and what remains unverified? Include commands, hardware/configuration and results.
  3. Which exact workload keys consume these configuration changes, and what evidence shows that unrelated shapes keep their previous selection?
  4. For every changed op_tests/ file, what behavior does it cover and why is it not redundant? Write None if no op test changed.

Edit the PR Self-Review section in the PR description. Include the current revision SHA; this comment refreshes automatically.

Missing or invalid answers

  • FAIL — missing ### Reviewed revision in the PR description
  • FAIL — missing ### Behavior and intent in the PR description
  • FAIL — missing ### Validation and unverified scope in the PR description
  • FAIL — missing ### PR-specific question in the PR description
  • FAIL — missing ### Changed op tests in the PR description
  • FAIL — Reviewed revision must contain at least the first 7 characters of the current head SHA
  • FAIL — Behavior and intent has no substantive answer
  • FAIL — Validation and unverified scope has no substantive answer
  • FAIL — PR-specific question has no substantive answer
  • FAIL — changed op test not explained in Changed op tests: op_tests/op_benchmarks/triton/bench_mxfp8_attention.py
  • FAIL — changed op test not explained in Changed op tests: op_tests/triton_tests/attention/test_mxfp8_attention_kernel.py
  • FAIL — Changed op tests must explain why each changed op test is necessary and non-redundant

Shadow mode reports what would block but keeps the status successful. Set AITER_PR_SELF_REVIEW_MODE=enforce only after reviewing real false positives.

@ZhangDanyang-AMD
ZhangDanyang-AMD merged commit bc12ddf into ROCm:main Nov 3, 2026
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
* [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).
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.

7 participants