Repository navigation
One flash-attention backward per direction, at one block barrier a key tile (#69) - #75
Merged
Merged
Conversation
…nd the trainer takes the unified backward
…207), which now carries it
This was referenced Aug 4, 2026
Merged
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.
Closes #69. Based on
main— #74 merged while this was in flight, so there is no stack; the diff is 6 files.flash_backward_q_tcgen05/flash_backward_q_pipelinedbecomeflash_backward_q, andflash_backward_kv_tcgen05/flash_backward_kv_pipelinedbecomeflash_backward_kv.The design, in one paragraph
What made them two was four block barriers. The synchronous pair ran TMA →
sync_threads→ score MMA →sync_threads→ register pass →sync_threads→ gradient MMA →sync_threadsper key tile, tensor cores idle through every register pass; the warp-specialized pair bought those back with structure — a dedicated TMA warp and MMA warp over 192 threads, six barrier sets, and kernel B re-staging its per-query statistics through a shared ring because specialization deleted the block sync it used to hide behind. Neither is needed once the leader issuesS(i+1)/dP(i+1)before the register pass of tilei, which is #68's move applied to kernels that already owned 128 rows. A CTA is now 128 threads — exactly the four warps anM128accumulator is drained by — and takes one block barrier per key tile, the one that publishes dS to the async proxy. The tensor core runsS(i+1)and the gradient MMA ofi-1throughout the pass ofi.What stays in TMEM, what stages, how the gradients accumulate
[128, 128][128, 128]BACKWARD_STAGESdeepS,dPdouble-buffered (2×64 each) + dQ = 384 of 512 columnsSᵀ,dPᵀ+ dV, dK = all 512dS, 2 buffersPᵀanddSᵀ, 2 eachload_row_vec→RegVecload_col_vec→ColVecmake_causal_atmake_causal_t_atThe gradient accumulators never leave tensor memory until the item ends, and there are no atomics. A query block owns every key its rows attend to and a key block owns every query that attends to it, so each output tile has exactly one writer and the epilogue is a
tile_x8drain intostore_rows. That is the whole reason ferro #42's TMA reduction stores — which #69 pre-listed as a candidate — are not wanted here, and it is also what the split costs; see "What remains".Everything else is the library:
smem.add(n * TILE_BYTES)SharedPlancarve,FLASH_BACKWARD_*_SMEMcomputed from it(T/128, H, B)gridpipeline::runover work items, longest streams dealt firstbackward_q_tile_paired/backward_kv_tile_paired, ~130 lines of per-valueFragmentloopsRegTileops onSCORE_CHUNKchunkskeeppredicate rebuilt in four kernelsmake_causal_at/make_causal_t_aton the scorestatic mut LSE2: SharedArray<f32, 128>staged by hand, and in kernel B a wholeBACKWARD_STAGES-deep ring of them with its ownwarp::sync_maskload_row_vec/load_col_vecstore_grad_tile's hand-written strided fp32 writesstore_rowsMasking the score rather than the gradient is what lets one call replace the predicate: a masked score
exp2s to zero and multiplies the finitedP − Dto nothing, so theif keep { … } else { 0.0 }that four kernels each rebuilt is now the mask itself.Performance — the pair is 30.9% faster
Kernel bench at
[32,1024,24,128], and the containers are the same machine: the untouched forward measures 1.339 ms here against the baseline run's 1.338.(The synchronous pair, which this also replaces, was 2.386 / 3.121 / 5.508.) Re-run in a second container: 1.300 / 1.982 / 3.281 — under half a percent.
ptxas gives both kernels 244 registers / 528 B frame, against 52–70 / 512–1024 before. That is
.maxntid, not the code: the kernels this replaces declared 192 and 1024 threads, so ptxas' budget was65536/1024and65536/192per thread and is now65536/128. 244 × 128 threads is 31.2K of the 64K file — still two blocks' worth — and residency is pinned at 1 CTA/SM by tensor memory either way, which is also why these plans are sized for the ring rather than, like the forward's, against a two-CTA shared-memory budget.Parity — green, and the same numbers
cargo oxide run flash-attn --bin flash, staged-bf16 f64 CPU reference, tolerance 5e-3:The baseline's maxima in the same run were 7.660e-4 / 7.322e-4 / 2.933e-3. The same numbers, which is the point: the masking moved from a per-value predicate to
make_causal_aton the score and theexp2moved to the SFU with the forward's, and neither shifted a digit.The two-oracle gate (
cargo oxide run flash-attn) againstops' materialized-probability backward, tolerances 5e-3/1e-2:Recorded maxima for the kernels this replaces were 2.8e-3 / 1.8e-3 / 5.4e-3 — at or just under each. Forward parity is untouched at every shape.
What is not gated any more is
assert_identicalbetween the two schedules. It was the right gate for a pure scheduling change and has no meaning once there is one kernel of each.The trainer, and a build break on
maingpu/modelswitches to both kernels and all 14 gates pass (modal run modal_app.py::main --kernel model), the MoE overfit landing 2.949803 → 0.000028. It does not land bit-identically on the recorded 2.949433 → 0.000060, and should not: the backward's arithmetic changed by exactly the two things above.gpu/modeldid not build onmainbefore this PR. #74 renamed the importedflash_persistent_configtoflash_forward_config, which collides with this module's own genericflash_forward_configfor the fp32 tiled path —error[E0255], plus theerror[E0061]it cascades into at the call site. Fixed here by dropping it from the import list and qualifying the call, which is what the backward configs beside it already did.ferro-kittens
Filed and fixed: #178, in ferro-kittens#179 (build / device-surface / regcount / device-tests on a B200 all green). The transposed score band had neither of its halves, and the backward is the first kernel in either repo to score
K·Qᵀ:RegTile::make_causal_t_at—make_causal_atexisted andmake_causal_thad only the origin-freediagonal. The argument for the_atform is stronger on that side: a CTA owning keys streams the queries at and after them, sokey_base − query_baseis negative on every visit but the first, and theu32subtraction a call site would otherwise write masks nothing.global::load_col_vec—load_row_vec's addresses delivered as theColVecasub_col_assigntakes. Deliberately notload_cols(#173, merged three days ago), which reads a run along a row; two movers returning one type off one argument list is a hazard, so the doc on each names the other and the device case is separate (global column statisticbesideglobal column map, over the same matrix, where the wrong walk delivers an element that names itself).Weighed and not needed:
FragmentLayout(GAPS §1.3, §3.4) — Rewrite flash-attention backward on current ferro-kittens (first backward consumer — expect library gaps) #69 pre-listed this as the likely gap and it is not one.mma_abt(K, Q)produces the key-major band directly and the operand-order square covers every site in both kernels.tcgen05.stvalidation) — the backward has no in-place accumulator rescale to do. Its accumulators are plain running sums.[128, 128]fp32 tiles per work item, but once per item rather than once per key tile.Pin
gpu/flash-attnandgpu/modelare pinned to ferro-kittens75d714b(the #179 branch, the rev all four checks above ran on). Both move to ferromainonce #179 merges;gpu/gemmis untouched on37ea9e7.What remains
S, so the pair issues 5 GEMM-equivalents per causal (query tile, key tile) pair where a fused kernel would issue 3. Fusing needs cross-CTA gradient accumulation whichever axis it parallelizes — a query-block CTA can hold dQ but must atomically add dK/dV, and vice versa — so it wants atomics or ferro Convert the flash attention kernels to HD=128 #42, would pay roughly 4.5x the dK/dV write traffic at T=1024, and would give up determinism. Rewrite flash-attention backward on current ferro-kittens (first backward consumer — expect library gaps) #69 says "unless a fused form measures better"; it cannot be measured until that surface exists, which is the honest answer.BACKWARD_STAGES. Three, chosen so the stage a score MMA waits for was loaded a whole iteration earlier rather than by the refill immediately above it. Never swept, and it is apub const.