Repository navigation
[MHA] Route flash_attn_varlen_func gfx950 hd256 BF16 THD forward to mha_v4 - #8704
Conversation
🏷️ CI GuideRuns automatically on every PR:
Extended tests (opt-in via labels):
One backend per PR: PR title tags & labels: Reviews: |
READY FOR HUMAN REVIEWPR Self-ReviewRevision Author self-review accepted. Readiness report: Author answers
Show the author's self-review answersBehavior and intentValidation and unverified scopePR-specific questionChanged op testsPR state
Copilot findings
Code and op-test hygiene
Required CI
Shadow mode reports what would block but keeps the status successful. Set |
|
@aiter-bot review |
9bddfbf to
12f6a94
Compare
|
FA failures look like an issue on main related to triton kernel, not asm |
There was a problem hiding this comment.
Thanks John. Getting the THD kernels behind flash_attn_varlen_func is exactly the follow-up #8067 left open, and the numbers are great 👌 I also like the gate: requiring one cu_seqlens tensor for Q and K avoids a sync, and the new test goes through backward.
My concern is with how the kernel gets there. As far as I can tell this PR doesn't route to the v4 kernel, it adds a second copy of it inside v3:
fwd_hd256_bf16_varlen.coandfwd_hd256_bf16_varlen_causal.counderhsa/gfx950/fmha_v3_fwd/are byte-identical to the ones infmha_v4_fwd/(same git blobs).init_fmha_fwd_v3_thd_argsand the THD branch offmha_fwd_v3repeatfmha_v4_fwd_thd: the kernarg fill, the KV-split descriptor at0x1E0(here through theptr_qseq_paddingslot), the grid sizing and thepair_extrarule.- The v4 manifest carries
kv_rangeandpair_splitfor these rows and the v4 launcher reads them. Here they turn into "mode 3" and "causal" in code. fmha_fwd_v3_thd_kv_splitsre-implements_resolve_thd_kv_splitsfrommha_v4.pyin C++.thd_kv_split_merge_kernelis a second LSE merge next tolse_merge.
This worries me for this kernel in particular because its launch contract is tight and we already got it wrong once. In #8067 the launcher sized the grid from max_seqlen while the kernel decided per document, which gave GPU memory faults and a few wrong outputs that the test suite didn't catch. Fixing it meant rebuilding both objects, changing the launcher and adding a manifest column, all together. With two copies of the objects and two launchers, nothing makes the next rebuild update both. The coverage is uneven too: test_mha_v4.py has nine THD test functions (the slice layouts from that fault, packs past 4 GiB, the check that pair-split rows load cu_budget), all on the v4 copy, while the v3 copy gets five cases, one of them with slices. And the v4 launcher is changing right now (#8684, #8801).
The alternative I have in mind is a Python dispatch. _flash_attn_varlen_forward already selects other backends that way before it reaches v3 and CK (the OPUS varlen kernels, the gfx1250 ASM path), so one more branch behind your is_fmha_v3_thd_bf16_hd256() gate could call the v4 launcher:
mha_v4(..., cu_seqlens=..., max_seqlen=..., causal=..., return_lse=True)returns the BF16 output and an FP32[heads, total]LSE, the layoutfmha_v3_varlen_fwdreturns, soFlashAttnVarlenFuncand the backward wouldn't change.- The first revision of #8067 had this routing in about 50 lines of
mha.py(213c33e). We only took it out so it could come back tested through this entry point, backward included. - Your own measurement has the two entry points running these kernels within 1% of each other, so the copy isn't buying speed.
- The PR would shrink to
mha.pyand the tests: no second set of objects, and no changes tomha_fwd.cu,mha_fwd.h,asm_mha_varlen_fwd.cuor the v3 CSV.
So my main question: what was the reason for copying the kernels and their launcher into v3 instead of dispatching to mha_v4 from Python? The one thing I can see the copy buying is that direct C++ callers of fmha_v3_varlen_fwd / mha_fwd() reach the kernel too, but only when they pass the same offsets array for Q and K. Is there such a caller, or another constraint I'm missing (the lazy import of mha_v4, its JIT module, something on the training side)? If there is one, could we at least keep a single copy of the objects and a single launcher that both entry points call?
Two smaller things:
- KV splits are chosen by
AITER_FMHA_V3_FWD_THD_KV_SPLITS, a process-wide setting for whatmha_v4takes per call (kv_splits=). With the Python dispatch the same variable could simply feed that argument. - Agreed on the red Flash Attention check: it aborts in the Triton
test_flash_attn_outputat head dim 128, which doesn't go through this code.
To be clear about what I checked: this is from reading the diff at 12f6a94, I haven't run it on a GPU. Reading it, I didn't find a correctness problem in the new path itself; the Python and C++ gates agree on the cases I traced (causal and window handling, padded lengths, GQA). My concern is the duplication, not the behavior.
12f6a94 to
b7fab68
Compare
|
Added a WA for FA integration ( removed 2 tests ) The two removed tests are the alibi=True variants (kvpacked True and False) of the one configuration that crashes: dropout 0.17, 2048×2048, head dim 128, causal, MHA. Its alibi=False variants were already skipped for the same Triton bug. |
|
@jcaraban as the description says, running this through flash_attn_varlen_func for training is tricky, because v4 has no support for bwd kernel whatsoever. |
|
Thanks John. I think we mean two different things here, so let me separate them. You're right that That works because the backward doesn't depend on which launcher ran the forward:
To be sure, I tried it on an MI355X. On top of b7fab68 I added one branch to
The Python route has two costs, so they're on the table:
So, is there something else that needs the kernels and their launcher inside v3? If it is a direct C++ caller of The branch I tested (inserted before
|
We need this kernel in order to be able to run traning (bwd + fwd) attention using aiter.flash_attn_varlen_func.
…r to launch asm v3 kernel
mha_v4 when shapes allow
10d3c4e to
25c469f
Compare
|
Thanks @jcaraban , agreed. The PR now dispatches to mha_v4 from _flash_attn_varlen_forward, as you suggested: no copied .co files, no second launcher or merge kernel, no v3 CSV or C++ changes. The KV-split variable feeds mha_v4's kv_splits=. The description has updated MI355X numbers through flash_attn_varlen_func. |
jcaraban
left a comment
There was a problem hiding this comment.
Thanks! here my empty approval (づ ᴗ _ᴗ)づ🎁
|
@slippedJim could you approve the PR? This kernel is needed for a customer to support training ( fwd + bwd). |
Conflict in op_tests/test_mha_varlen.py: keep main's SEQ_PADDING_NHEADS next to the PR's EXPANDED_LAYOUTS and expanded-inputs test. Main's #8704 routes gfx950 hd256 BF16 self-attention to mha_v4's THD rows, which misread a token stride of 0 the same way the v3/OPUS kernels do (expanded q/k/v: out off by up to 3.3, no error). Add the same token stride check to can_impl_fmha_v4_thd so such inputs go to CK, and run the expanded-inputs test at hd256 too, with one cu_seqlens tensor so it takes the v4 route. Co-authored-by: Claude <[email protected]> Signed-off-by: Andreas Karatzas <[email protected]>
Summary
aiter.flash_attn_varlen_funcnow runs the gfx950 BF16 hd256 forward of packed self-attention onmha_v4's THD kernels (#8067), for MHA and GQA, causal or not. Training (forward + backward)through
flash_attn_varlen_funcgets these kernels; the backward is unchanged. The PR adds nokernel, launcher or manifest: it is a dispatch in
_flash_attn_varlen_forwardtomha_v4.Forward pass on MI355X, compared with what
flash_attn_varlen_funcruns today:splits).
Motivation
We need these kernels to train with
aiter.flash_attn_varlen_func(forward + backward).They exist in
mha_v4(#8067), butmha_v4is forward-only and has no autograd/backwardintegration, so they could not be used for training. #8067 left routing from
flash_attn_varlen_functo a follow-up that is tested through that entry point, backward included.Today,
flash_attn_varlen_funcsends gfx950 BF16 hd256 calls to:fwd_hd256_bf16_group.co/fwd_hd256_bf16_causal_group.co, but only whennhead_q == nhead_k, because they index K/V by the Q head;FlashAttnVarlenFunc.backwardonly needs the forward's output and LSE, andmha_v4returns bothin the layout the v3 path returns, so the existing backward consumes them as is. The forward is
routed to
mha_v4itself rather than to a copy of its kernels and launcher in v3, so there is oneset of code objects and one launcher to keep correct (review feedback).
Changes
_flash_attn_varlen_forwardgains a branch, ahead of v3 and CK, that callsmha_v4(..., cu_seqlens=, max_seqlen=, causal=, return_lse=, out=, kv_splits=)whencan_impl_fmha_v4_thd()holds: gfx950, BF16, head dims 256/256,nhead_q % nhead_k == 0, Q and Kpassing the same
cu_seqlenstensor (checked by pointer, so no device sync and safe under graphcapture), no window other than causal, and none of dropout, bias, ALiBi, soft cap, sink, descales,
padded
cu_seqlens,block_table,min_seqlen_qorreturn_softmax.mha_v4needs Triton; it isimported lazily, and without it calls keep their current path. Every other call keeps its current
path too, including a separate
cu_seqlens_ktensor with equal contents (v3 group kernels for MHA,CK for GQA).
AITER_FMHA_V4_THD=0restores the previous routing. KV splits are off by default andopt-in through
AITER_FMHA_V4_THD_KV_SPLITS(autoor a count, clamped to whatmha_v4takes),because
autoranged from 0.58x to 1.47x of one slice on MI355X.Tests:
generate_qkvnow shares onecu_seqlenstensor for QKV-packed inputs (-i QKVPACKED), andop_tests/test_mha_varlen.pygetstest_flash_attn_varlen_func_thd_hd256, which also runs from__main__as CI runs the file. The file's seq-padding benchmark skips GQA ratios that don't divideits 8 heads, which crashed every
-gr 6run..github/scripts/flash_attention/test.shdeselectsthe two
alibi=Truevariants of the dropout/causal/head-dim-128 case that aborts in the Tritonbackward kernel (
bwd_kernel_fused_causal, LLVM miscompile), as it already does for thealibi=Falsevariants, and on RDNA3 skips the dropout/causal/head-dim-32 case without alibi, whichfails its output check there. Both are Triton-backend failures that do not go through this code.
Performance (if applicable)
All numbers come from
op_tests/test_mha_varlen.pyat 10d3c4e on MI355X (gfx950, 256 CUs). Thetest times
aiter.flash_attn_varlen_funcwithrun_perftest;fwd_us/fwd_tflopsare from itssummary table (profiler device time).
-i QKVPACKEDgives whole documents with onecu_seqlenstensor for Q and K. "Before" is the same command with
AITER_FMHA_V4_THD=0.GQA, one causal document per pack, hd256 BF16 (the shapes of the #8067 table):
(*) 24/4 heads at 32K: the test's FP32 torch reference runs out of memory after the timing, so
there is no summary row. That row uses the
AITER_LOG_MORE=1profiler kernel time, in both columns.Opt-in KV splits (
AITER_FMHA_V4_THD_KV_SPLITS=autoadded to the same command) on the shapes whereautosplits:autosplitsMHA, 2 documents, 24 heads, hd256 BF16:
AITER_LOG_MORE=1 python3 op_tests/test_mha_varlen.py -b 2 -nh 24 -s N,N -d_qk_v 256,256 \ -dt bf16 -gr 1 -c <False|True> -l False -det False -i QKVPACKEDBackward time is unchanged: the same backward kernels run in both columns
(
fmha_bwd_hd256_odo_bf16_group,fmha_bwd_fused_dkdv_dq_hd256_bf16_[non]causal_varlen).Testing
Documentation
The
flash_attn_varlen_funcdocstring describes the fast path, the one-cu_seqlensrequirement,AITER_FMHA_V4_THD=0andAITER_FMHA_V4_THD_KV_SPLITS.Dependencies
The new path uses Triton through
mha_v4(lse_merge,arch_info). It is imported lazily; withoutTriton, calls take the existing path.
Breaking Changes
None. Qualifying gfx950 BF16 hd256 varlen forward calls now run a different kernel by default. Its
output error against an FP32 reference is lower than the previous kernel's (see below).
AITER_FMHA_V4_THD=0restores the previous routing.PR Self-Review
Reviewed revision
5df4536
Behavior and intent
aiter.flash_attn_varlen_funcon gfx950 with BF16 hd256 Q/K/V runs the forward of packedself-attention (Q and K sharing one
cu_seqlenstensor, no padding) onmha_v4's THD kernels,MHA and GQA, causal or not. Before this change, MHA calls used the slower v3 group kernels and GQA
calls fell back to CK, and the THD kernels could not be used for training because
mha_v4has nobackward. The backward path is unchanged and consumes the output and LSE
mha_v4returns. The PRadds no kernel and no launcher:
mha_v4's code objects and launcher are the only copy.Validation and unverified scope
Hardware: MI355X (gfx950, 256 CUs), ROCm 7.2, PyTorch 2.13, Triton 3.9. All runs at 10d3c4e;
5df4536 has the same
aiter/code, rebased on main, plus thetest.shdeselects.CI at 5df4536 passed, including the MI35X standard tests, which run
op_tests/test_mha_varlen.pyas a script (its
-d_qk_vsweep and the THD cases from__main__), and both Flash AttentionTriton jobs.
op_tests/test_mha_varlen.py:python3 -m pytest op_tests/test_mha_varlen.py -k thd_hd256: 5 passed (one-slice MHA and GQA,causal and not, and a 2-slice case that checks
_lse_merge_kernelruns).reference, except 24/4 heads at 32K, where the reference ran out of memory. The profiler showed
fmha_fwd_hd256_bf16_varlen[_causal]in every "after" run and_lse_merge_kernelonly in theautoruns.An ad-hoc script calls
aiter.flash_attn_varlen_funcwithreturn_lse=Trueagainst an FP32per-document reference (FP32 autograd for gradients) and checks the launched kernels: 60/60 pass.
257-token documents and documents up to 8192 tokens; packed (strided) QKV; causal and
non-causal; backward for 16/16, 24/4 and 6/1.
whose 0- and 1-token documents leave slices without keys for some rows;
auto; backward with 4slices and with
auto.cu_seqlens_ktensor with equal contents (MHA: v3 group kernel;GQA: CK), forward and backward; per-document Q and K lengths that differ while totals and maxima
match;
AITER_FMHA_V4_THD=0.Errors on the
mha_v4rows: max |O error| <= 0.0104 on the forward packs (previous kernel: 0.0132)and <= 0.0154 on the backward packs; max |LSE error| < 1e-5 (previous kernel: 0.0042); max
dQ/dK/dV relative error <= 0.0061.
Packs over 4 GiB (16/16 heads, Q/K/V/O each 4.07 GiB, 535 documents): the default (one slice)
passes. With KV splits requested,
mha_v4raisesper-slice output stride ... does not fit the 32-bit kernarg slotinstead of computing: its split resolver does not drop to one slice when theFP32 partials pass 4 GiB. That is opt-in only and a
mha_v4limit.Unverified:
mha_v4()costs a few microseconds more on the host than theprevious C++ path; the times above include it.
fmha_v3_varlen_fwd/mha_fwd()do not reach these kernels; onlyflash_attn_varlen_funcroutes to them.predates this PR and needs a separate fix in those kernels.
PR-specific question
Which architecture, dtype and shape boundaries select the changed kernel path, and what invariant
prevents unsupported inputs from reaching it?
The
mha_v4branch of_flash_attn_varlen_forwardis taken only whencan_impl_fmha_v4_thd()holds:
get_gfx() == "gfx950").max_seqlen_q == max_seqlen_k > 0and equalQ/K/V token counts;
nhead_q % nhead_k == 0, any ratio; Q and K pass the samecu_seqlenstensor (same
data_ptr, shape, int32, contiguous), so every document has the same Q and Klength.
window_size_left == -1, right -1 or 0).cu_seqlens,block_table, dropout, bias/ALiBi, soft cap, sink,min_seqlen_q,return_softmax,zero_tensors, anoutof another shape/dtype/device.AITER_FMHA_V4_THDnot0, andmha_v4importable (Triton installed).Invariant: one
cu_seqlensarray for Q and K is the only host-visible proof that every document hasthe same Q and K length; equal totals and maxima are not enough (CI's
test_mha_varlen.pyinputshit exactly that). The gate checks tensor identity, not contents, so it never syncs with the
device. Inside
mha_v4, the THD launcher checks the tensors again (TORCH_CHECKon ranks, dtypes,devices, head counts, unit-stride head dim, and every byte stride fitting its 32-bit kernarg slot)
and raises rather than computing a wrong result. A call that fails the gate keeps its current
path.
Changed op tests
aiter/test_mha_common.py:generate_qkv(..., qkvpacked=True)returns onecu_seqlenstensor forQ and K, as packed self-attention callers pass it. Before, it built two equal tensors, so
-i QKVPACKEDnever reached this path.op_tests/test_mha_varlen.py:test_flash_attn_varlen_func_thd_hd256(gfx950 only; skipped without Triton or withAITER_FMHA_V4_THD=0): three ragged documents, 12 heads, d=256 BF16, GQA ratios 1 and 6, causaland non-causal, plus one 2-slice KV-split case. It asserts the THD kernel launched and that
_lse_merge_kernellaunched only when splitting, and checks forward and backward against thefile's torch reference with its tolerances. CI runs this file as a script, so
__main__alsoruns these cases when
-d_qk_vincludes256,256and-dtincludesbf16. No existing testreaches this path: the default sweep gives Q and K different lengths.
__main__skips the seq-padding benchmark when its fixedSEQ_PADDING_NHEADS = 8is notdivisible by
-gr(for example-gr 6), instead of failing its assert and losing the summarytable of the main test. That benchmark always passes padded
cu_seqlens, which this path doesnot take, so skipping it loses no coverage of this change.