Repository navigation
[FlyDSL] [CI] add gfx942 FMHA varlen backward kernel for d_qk=192/d_v=128 - #4875
Merged
Merged
Conversation
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]>
Contributor
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
PR title tags: |
3 tasks
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]>
coderfeli
requested changes
Sep 2, 2026
coderfeli
left a comment
Collaborator
There was a problem hiding this comment.
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.
coderfeli
reviewed
Sep 2, 2026
coderfeli
reviewed
Sep 2, 2026
coderfeli
reviewed
Sep 2, 2026
coderfeli
reviewed
Sep 2, 2026
… 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]>
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]>
coderfeli
reviewed
Sep 10, 2026
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]>
Co-authored-by: Cursor <[email protected]>
coderfeli
approved these changes
Sep 14, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 requirehdim_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-padv/out/doutfrom 128 to 192 to open that gate, which spends a third of thedVanddPwork 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_backwardbehind 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_deltapre-pass, the fusedk_bwd, and the split-K reductionaiter/ops/flydsl/kernels/fmha_bwd_gfx942/fmha_bwd_kernel.py— host side: grid planning, dispatch-mode selection, cachedCompiledFunctionlaunchaiter/ops/flydsl/kernels/fmha_bwd_gfx942/__init__.py— new packageaiter/ops/flydsl/fmha_kernels.py— exportsflydsl_flash_attn_varlen_bwd, themha_varlen_bwd-shaped wrapperaiter/ops/mha.py—can_impl_fmha_bwd_flydslgate + dispatch branch in_flash_attn_varlen_backwardop_tests/test_mha_flydsl_varlen_bwd.py— correctness vs. an fp32 torch referenceop_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 fileTechnical Details
Two kernels, no atomics. A
k_deltapre-pass computesD = rowsum(dO*O), then one fusedk_bwdcarries all five backward GEMMs.dq/dk/dvare each written exactly once inbf16, so there is no
ConvertQGradpass and the result is deterministic either way.d_v = 128is native, so nothing is padded.
MFMA layout.
v_mfma_f32_16x16x16_bf16_1k's accumulator fragment is bit-identical to anoperand 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, thendV,dK); job B owns a query block and streams keys, computing scores transposed so itsdSᵀis already the operanddQneeds. Each alone leaves a causal drain that separatedispatches 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_flydslin_flash_attn_varlen_backwardadmits onlygfx942 / 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 thatenvelope 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 thebenchmark 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-Kpath).
outandsoftmax_lsecome from aiter's real varlen forward, so the LSE conventionunder test is the one the model produces:
Performance -- the three ways aiter can produce this shape's gradients:
flydsl,ck(what therouter reaches today, since the v3 gate rejects
hdim_q != hdim_v), andasm_vpad(ASM v3 withvzero-padded to 192;v/outcome pre-padded from the padded forward such a model wouldalready run, while padding
doutand narrowingdvback to 128 are charged to the backward).Speedup baseline is
ck: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:erristhe
checkAllclosemismatch ratio at rtol=atol=2e-2, andmean_relismean|Δ| / mean|ref|against the fp32 reference, ~3.4e-3 on every gradient, which is bf16 output rounding.
uniformis slower in wall time but higher in TFLOPS thanmainat the same token count: 8x4096has more causal (i, j) pairs than 13 ragged sequences summing to 32K, so it is simply more work.
smallsits lower because its whole grid is co-resident on one dispatch round -- that is theregime the split-K path exists for.
Cross-backend
num_seqs=8, max_seqlen=4096, nheads=2, 32768 tokens (the
uniformshape), 25 warmup / 100 reps:ckis the incumbent -- what the router reaches today for this shape -- so the headline is2.68x. Against
asm_vpad, the best result obtainable by paddingvto 192 to open the v3gate, it is 1.79x, which is roughly what avoiding a third of wasted
dV/dPwork plus the padtraffic should buy.
Submission Checklist
Note: All the kernels are auto-generated by https://github.com/AMD-AGI/GEAK