Skip to content

[FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 - #4875

Merged
coderfeli merged 11 commits into
ROCm:mainfrom
amd-wangfan:main
Sep 14, 2026
Merged

coderfeli merged 11 commits into
ROCm:mainfrom
amd-wangfan:main

Conversation

@amd-wangfan

@amd-wangfan amd-wangfan commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

MLA-style attention has an asymmetric head dim -- d_qk = 192, d_v = 128 -- and aiter has no backward kernel native to that shape on gfx942. Both existing fast-path gates require hdim_q == hdim_v, so a causal varlen (THD) backward at this shape falls through to the generic CK-tile path. The only way to reach the ASM v3 backward today is to zero-pad v / out / dout from 128 to 192 to open that gate, which spends a third of the dV and dP work on zeros plus the pad and narrow-back traffic.

This PR adds a FlyDSL backward specialised for the unpadded shape and wires it into _flash_attn_varlen_backward behind a gate, so the shape family neither v3 gate accepts gets a native kernel instead of the CK fallback. It is 2.68x the CK path and 1.79x the v-padded ASM v3 alternative on the target shape.

And the GEAK is able to generate well-optimized flydsl kernels without any help from developers. All the kernels in this PR are auto-generated by GEAK.

Deliverable files

  • aiter/ops/flydsl/kernels/fmha_bwd_gfx942/fmha_bwd_core.py — the kernels: k_delta pre-pass, the fused k_bwd, and the split-K reduction
  • aiter/ops/flydsl/kernels/fmha_bwd_gfx942/fmha_bwd_kernel.py — host side: grid planning, dispatch-mode selection, cached CompiledFunction launch
  • aiter/ops/flydsl/kernels/fmha_bwd_gfx942/__init__.py — new package
  • aiter/ops/flydsl/fmha_kernels.py — exports flydsl_flash_attn_varlen_bwd, the mha_varlen_bwd-shaped wrapper
  • aiter/ops/mha.py — can_impl_fmha_bwd_flydsl gate + dispatch branch in _flash_attn_varlen_backward
  • op_tests/test_mha_flydsl_varlen_bwd.py — correctness vs. an fp32 torch reference
  • op_tests/op_benchmarks/flydsl/bench_mha_bwd.py — cross-backend benchmark (flydsl / ck / asm_vpad)
  • .github/scripts/split_tests.sh — CI time estimate for the new test file

Technical Details

  • Two kernels, no atomics. A k_delta pre-pass computes D = rowsum(dO*O), then one fused
    k_bwd carries all five backward GEMMs. dq / dk / dv are each written exactly once in
    bf16, so there is no ConvertQGrad pass and the result is deterministic either way. d_v = 128
    is native, so nothing is padded.

  • MFMA layout. v_mfma_f32_16x16x16_bf16_1k's accumulator fragment is bit-identical to an
    operand fragment of the transpose, so score fragments are reused as their own transpose and
    only operands contracting over the token index go through LDS.

  • Two job types on one grid. Job A owns a key block and streams queries (S, dP, then
    dV, dK); job B owns a query block and streams keys, computing scores transposed so its
    dSᵀ is already the operand dQ needs. Each alone leaves a causal drain that separate
    dispatches cannot overlap, so they share one grid with the dQ jobs dispatched last. Co-resident
    grids additionally split the streamed index three ways and reduce in a third kernel.

  • Dispatch gate. can_impl_fmha_bwd_flydsl in _flash_attn_varlen_backward admits only
    gfx942 / bf16 / causal / hdim_q == 192, hdim_v == 128 / nhead_q == nhead_k / contiguous,
    with no dropout, alibi, sliding window, sink, or padded cu_seqlens. Anything outside that
    envelope keeps its current path.

Test Plan

Env: gfx942 (MI300X/MI325X) inside the ROCm docker, FlyDSL installed. Supported envelope:
causal varlen THD self-attention, d_qk=192 / d_v=128, bf16, no GQA. Both the test and the
benchmark self-skip elsewhere.

Correctness -- FlyDSL gradients vs. an fp32 torch reference over three ragged sequence-length
patterns (main = 13 sequences over 32K tokens, the target workload; uniform = 8x4096;
small = a 5-sequence case whose whole grid is co-resident, which is what exercises the split-K
path). out and softmax_lse come from aiter's real varlen forward, so the LSE convention
under test is the one the model produces:

python op_tests/test_mha_flydsl_varlen_bwd.py
python op_tests/test_mha_flydsl_varlen_bwd.py -c main -nh 2 8

Performance -- the three ways aiter can produce this shape's gradients: flydsl, ck (what the
router reaches today, since the v3 gate rejects hdim_q != hdim_v), and asm_vpad (ASM v3 with
v zero-padded to 192; v/out come pre-padded from the padded forward such a model would
already run, while padding dout and narrowing dv back to 128 are charged to the backward).
Speedup baseline is ck:

python op_tests/op_benchmarks/flydsl/bench_mha_bwd.py 2>/dev/null
python op_tests/op_benchmarks/flydsl/bench_mha_bwd.py --seqlens 4096 3840 3584 3072 --nheads 8 2>/dev/null
python op_tests/op_benchmarks/flydsl/bench_mha_bwd.py --sweep -o bwd.csv 2>/dev/null

Dispatch -- confirm the gate routes and that out-of-envelope configs are unaffected (non-causal,
GQA, d_qk == d_v, fp16 all still take their previous path).

Test Result

Correctness

bf16, causal varlen THD, d_qk=192 / d_v=128, nheads=2, gfx942. All three cases pass: err is
the checkAllclose mismatch ratio at rtol=atol=2e-2, and mean_rel is mean|Δ| / mean|ref|
against the fp32 reference, ~3.4e-3 on every gradient, which is bf16 output rounding.

case total_tokens max_seqlen us TFLOPS TB/s dq mean_rel dk mean_rel dv mean_rel err
main 32768 4096 584.505 264.3 0.287 3.43e-3 3.44e-3 3.44e-3 0
uniform 32768 4096 708.336 315.4 0.237 3.44e-3 3.45e-3 3.45e-3 0
small 8192 2200 155.517 158.3 0.270 3.50e-3 3.55e-3 3.55e-3 0

uniform is slower in wall time but higher in TFLOPS than main at the same token count: 8x4096
has more causal (i, j) pairs than 13 ragged sequences summing to 32K, so it is simply more work.
small sits lower because its whole grid is co-resident on one dispatch round -- that is the
regime the split-K path exists for.

Cross-backend

num_seqs=8, max_seqlen=4096, nheads=2, 32768 tokens (the uniform shape), 25 warmup / 100 reps:

group backend median_ms p20 p80 TFLOPS speedup vs its CK
192/128 flydsl 0.7061 0.6961 0.72 316.4 3.07x
192/128 asm_vpad 1.3031 1.2886 1.3221 171.4 1.66x
192/128 ck 2.167 2.1455 2.1886 103.1 1.00x
128/128 asm_128 0.4272 0.4161 0.4391 402.3 2.49x
128/128 ck_128 1.0628 1.0586 1.0749 161.7 1.00x

ck is the incumbent -- what the router reaches today for this shape -- so the headline is
2.68x. Against asm_vpad, the best result obtainable by padding v to 192 to open the v3
gate, it is 1.79x, which is roughly what avoiding a third of wasted dV/dP work plus the pad
traffic should buy.

Submission Checklist

Note: All the kernels are auto-generated by https://github.com/AMD-AGI/GEAK

Adds a FlyDSL backward kernel covering the causal varlen self-attention
shape family that both can_impl_fmha_v3_bwd gates exclude by requiring
hdim_q == hdim_v, plus the dispatch gate in _flash_attn_varlen_backward,
a unit test and a benchmark.

Co-authored-by: Cursor <[email protected]>
@amd-wangfan
amd-wangfan requested a review from a team August 20, 2026 06:42
@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
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 4875 --add-label <label>

PR title tags:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf] and op tags like [MLA] are left untouched. Add the no-auto-title label to opt this PR out of title tagging.

@github-actions github-actions Bot changed the title [flydsl] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 [FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 Aug 20, 2026
@amd-wangfan amd-wangfan changed the title [FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 [FlyDSL] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 Aug 20, 2026
The file carried a python3 shebang while committed non-executable, which ruff's EXE001 flags. The script is documented and invoked as 'python bench_mha_bwd.py', so the shebang bought nothing, and dropping it matches test_mha_flydsl_varlen_bwd.py. Setting the exec bit instead would satisfy EXE001 but leaves the fix dependent on file modes surviving every checkout.

Co-authored-by: Cursor <[email protected]>
@github-actions github-actions Bot changed the title [FlyDSL] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 [FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 Aug 20, 2026
@amd-wangfan amd-wangfan changed the title [FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 [FlyDSL] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 Aug 20, 2026
@zufayu
zufayu requested a review from coderfeli August 21, 2026 01:15
@github-actions github-actions Bot changed the title [FlyDSL] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 [FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 Aug 26, 2026

@coderfeli coderfeli left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Plz use flydsl-kernel-code-cleanup skill and api-stability skill to clean up kernel codes. Too many low level IR which are not needed. Also use test clean skill to clean ut.

Comment thread aiter/ops/flydsl/fmha_bwd_gfx942.py Resolved
bryan and others added 2 commits September 9, 2026 17:11
… guard

Move the host launcher up to aiter/ops/flydsl/fmha_bwd_gfx942.py, alongside the
other flydsl entry points, and port the device kernel off the raw MLIR dialects
onto the stable fx.* surface: buffer_ops gives way to make_buffer_tensor views,
the raw rocdl.mfma_* calls to fx.make_mma_atom, and the deprecated
constant_vector / Numeric.shrui / Numeric.shuffle_xor to their current
equivalents.

The workspace guard also admitted shapes the addressing cannot reach. _flat
derives its byte count from Tlen * Hn in i32 and sizes the layout extent for a
1 << 31 byte span, so the real ceiling is 2 GiB rather than the descriptor's 4.
The assert now rejects at 1 << 31, instead of letting a dq/dk workspace between
2 and 4 GiB wrap silently and corrupt gradients.

Co-authored-by: Cursor <[email protected]>
…rk table

The test module only tabulated numbers, so a wrong gradient still exited zero.
It now has a pytest entry point asserting both the mismatch ratio and the
aggregate relative error, and covers the 16-head shape -- the 128-head MLA case
at TP=8 -- next to the 2-head one, keeping both the split-K and the nsp == 1
dispatch paths under test.

The benchmark reports one row per (group, backend) with the median and the
20th/80th percentiles of the per-iteration GPU latency rather than a single
mean, because a stray host-side stall skews a mean and leaves no trace in the
table. A square d=128 group (asm_128, ck_128) joins the 192/128 one as a
reference point for what this hardware does on a head dim the ASM path was
written for, and every row's speedup divides by its own group's CK baseline.
make_varlen_inputs and flops_bytes take the head dims as parameters to serve
both groups; their defaults leave the 192/128 callers unchanged.

--no-check skips the fp32 reference, which is a per-(sequence, head) Python
loop and otherwise dominates the wall time of a sweep.

Co-authored-by: Cursor <[email protected]>
amd-wangfan and others added 2 commits September 9, 2026 17:15
ROCm#5116 removed aiter/ops/flydsl/utils.py and made flydsl a hard dependency --
fused_moe imports aiter.ops.flydsl at module scope, setup.py pins
flydsl==0.3.2 and checks it, and aiter/ops/flydsl/__init__.py raises ImportError
on a missing or too-old install. The guards here outlived the helper they
called: mha.py's bwd gate still did `from .flydsl.utils import
is_flydsl_available`, which now raises ImportError on gfx942 at dispatch time
rather than falling through to CK.

Drop the import and the `ret &= is_flydsl_available()` term from the gate, and
the matching skip conditions from the test and the benchmark. The remaining
gfx942 arch check is what actually decides eligibility.

Co-authored-by: Cursor <[email protected]>
Comment thread aiter/ops/flydsl/fmha_bwd_gfx942.py Resolved
bryan and others added 3 commits September 14, 2026 10:13
Drop the a/b job prefixes so the dK/dV and dQ branches share unprefixed names, trim the inline measurement logs, and key the CU-count heuristics off chip_info.get_cu_num so they agree with mha.py.

Co-authored-by: Cursor <[email protected]>
@coderfeli
coderfeli merged commit 4c5dfd7 into ROCm:main Sep 14, 2026
79 checks passed
sammysun0711 pushed a commit to sammysun0711/aiter that referenced this pull request Sep 16, 2026
…=128 (ROCm#4875)

* [flydsl] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128

Adds a FlyDSL backward kernel covering the causal varlen self-attention
shape family that both can_impl_fmha_v3_bwd gates exclude by requiring
hdim_q == hdim_v, plus the dispatch gate in _flash_attn_varlen_backward,
a unit test and a benchmark.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] drop shebang from bench_mha_bwd.py to satisfy ruff EXE001

The file carried a python3 shebang while committed non-executable, which ruff's EXE001 flags. The script is documented and invoked as 'python bench_mha_bwd.py', so the shebang bought nothing, and dropping it matches test_mha_flydsl_varlen_bwd.py. Setting the exec bit instead would satisfy EXE001 but leaves the fix dependent on file modes surviving every checkout.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] modernize the gfx942 FMHA backward and fix its i32 workspace guard

Move the host launcher up to aiter/ops/flydsl/fmha_bwd_gfx942.py, alongside the
other flydsl entry points, and port the device kernel off the raw MLIR dialects
onto the stable fx.* surface: buffer_ops gives way to make_buffer_tensor views,
the raw rocdl.mfma_* calls to fx.make_mma_atom, and the deprecated
constant_vector / Numeric.shrui / Numeric.shuffle_xor to their current
equivalents.

The workspace guard also admitted shapes the addressing cannot reach. _flat
derives its byte count from Tlen * Hn in i32 and sizes the layout extent for a
1 << 31 byte span, so the real ceiling is 2 GiB rather than the descriptor's 4.
The assert now rejects at 1 << 31, instead of letting a dq/dk workspace between
2 and 4 GiB wrap silently and corrupt gradients.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] assert accuracy in the FMHA backward test, group the benchmark table

The test module only tabulated numbers, so a wrong gradient still exited zero.
It now has a pytest entry point asserting both the mismatch ratio and the
aggregate relative error, and covers the 16-head shape -- the 128-head MLA case
at TP=8 -- next to the 2-head one, keeping both the split-K and the nsp == 1
dispatch paths under test.

The benchmark reports one row per (group, backend) with the median and the
20th/80th percentiles of the per-iteration GPU latency rather than a single
mean, because a stray host-side stall skews a mean and leaves no trace in the
table. A square d=128 group (asm_128, ck_128) joins the 192/128 one as a
reference point for what this hardware does on a head dim the ASM path was
written for, and every row's speedup divides by its own group's CK baseline.
make_varlen_inputs and flops_bytes take the head dims as parameters to serve
both groups; their defaults leave the 192/128 callers unchanged.

--no-check skips the fp32 reference, which is a per-(sequence, head) Python
loop and otherwise dominates the wall time of a sweep.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] drop the is_flydsl_available guards from the FMHA backward path

ROCm#5116 removed aiter/ops/flydsl/utils.py and made flydsl a hard dependency --
fused_moe imports aiter.ops.flydsl at module scope, setup.py pins
flydsl==0.3.2 and checks it, and aiter/ops/flydsl/__init__.py raises ImportError
on a missing or too-old install. The guards here outlived the helper they
called: mha.py's bwd gate still did `from .flydsl.utils import
is_flydsl_available`, which now raises ImportError on gfx942 at dispatch time
rather than falling through to CK.

Drop the import and the `ret &= is_flydsl_available()` term from the gate, and
the matching skip conditions from the test and the benchmark. The remaining
gfx942 arch check is what actually decides eligibility.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] rename gfx942 FMHA backward locals and use chip_info.get_cu_num

Drop the a/b job prefixes so the dK/dV and dQ branches share unprefixed names, trim the inline measurement logs, and key the CU-count heuristics off chip_info.get_cu_num so they agree with mha.py.

Co-authored-by: Cursor <[email protected]>

* [FlyDSL] fix Black formatting and ruff BLE001 on gfx942 FMHA backward

---------

Co-authored-by: bryan <[email protected]>
Co-authored-by: Cursor <[email protected]>
Signed-off-by: Xiake Sun <[email protected]>
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.

2 participants