Skip to content

One flash-attention backward per direction, at one block barrier a key tile (#69) - #75

Merged
feitreim merged 4 commits into
mainfrom
feat/issue-69-flash-backward
Aug 3, 2026
Merged

feitreim merged 4 commits into
mainfrom
feat/issue-69-flash-backward

Conversation

@feitreim

@feitreim feitreim commented Aug 3, 2026

Copy link
Copy Markdown
Owner

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_pipelined become flash_backward_q, and
flash_backward_kv_tcgen05 / flash_backward_kv_pipelined become flash_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_threads per 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 issues S(i+1)/dP(i+1) before the register pass of tile i, which is #68's move applied to kernels that already owned 128 rows. A CTA is now 128 threads — exactly the four warps an M128 accumulator is drained by — and takes one block barrier per key tile, the one that publishes dS to the async proxy. The tensor core runs S(i+1) and the gradient MMA of i-1 throughout the pass of i.

What stays in TMEM, what stages, how the gradients accumulate

kernel A (dQ) kernel B (dK/dV)
resident operand Q, dY as [128, 128] K, V as [128, 128]
streamed K, V, BACKWARD_STAGES deep Q, dY, same depth
TMEM S,dP double-buffered (2×64 each) + dQ = 384 of 512 columns Sᵀ,dPᵀ + dV, dK = all 512
shared gradient operand dS, 2 buffers Pᵀ and dSᵀ, 2 each
statistic load_row_vec → RegVec load_col_vec → ColVec
mask make_causal_at make_causal_t_at

The 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_x8 drain into store_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:

was is
smem.add(n * TILE_BYTES) SharedPlan carve, FLASH_BACKWARD_*_SMEM computed from it
a fixed (T/128, H, B) grid pipeline::run over work items, longest streams dealt first
backward_q_tile_paired / backward_kv_tile_paired, ~130 lines of per-value Fragment loops RegTile ops on SCORE_CHUNK chunks
a hand-written keep predicate rebuilt in four kernels make_causal_at / make_causal_t_at on the score
static mut LSE2: SharedArray<f32, 128> staged by hand, and in kernel B a whole BACKWARD_STAGES-deep ring of them with its own warp::sync_mask load_row_vec / load_col_vec
store_grad_tile's hand-written strided fp32 writes store_rows
a TMA warp and an MMA warp the leader of the gradient warpgroup

Masking the score rather than the gradient is what lets one call replace the predicate: a masked score exp2s to zero and multiplies the finite dP − D to nothing, so the if 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.

pipelined baseline this PR
kernel A (dQ) 2.125 ms 1.298 ms −38.9%
kernel B (dK/dV) 2.631 ms 1.990 ms −24.4%
both 4.756 ms 3.285 ms −30.9%

(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 was 65536/1024 and 65536/192 per thread and is now 65536/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:

shape dq dk dv
[2,128,3] 7.299e-4 7.322e-4 2.933e-3
[1,256,2] 5.203e-4 7.437e-4 2.717e-3
[1,1024,4] 6.458e-4 7.084e-4 2.911e-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_at on the score and the exp2 moved to the SFU with the forward's, and neither shifted a digit.

The two-oracle gate (cargo oxide run flash-attn) against ops' materialized-probability backward, tolerances 5e-3/1e-2:

shape dq dk dv
[1,128,2] 1.033e-3 1.363e-3 4.159e-3
[2,256,3] 2.726e-3 1.615e-3 5.377e-3
[1,1024,4] 1.121e-3 1.730e-3 5.080e-3

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_identical between 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 main

gpu/model switches 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/model did not build on main before this PR. #74 renamed the imported flash_persistent_config to flash_forward_config, which collides with this module's own generic flash_forward_config for the fp32 tiled path — error[E0255], plus the error[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_at existed and make_causal_t had only the origin-free diagonal. The argument for the _at form is stronger on that side: a CTA owning keys streams the queries at and after them, so key_base − query_base is negative on every visit but the first, and the u32 subtraction a call site would otherwise write masks nothing.
  • global::load_col_vec — load_row_vec's addresses delivered as the ColVec a sub_col_assign takes. Deliberately not load_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 statistic beside global column map, over the same matrix, where the wrong walk delivers an element that names itself).

Weighed and not needed:

Pin

gpu/flash-attn and gpu/model are pinned to ferro-kittens 75d714b (the #179 branch, the rev all four checks above ran on). Both move to ferro main once #179 merges; gpu/gemm is untouched on 37ea9e7.

What remains

  1. The split costs 40% of the tensor-core work, and this is the largest lever left. Each kernel recomputes 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.
  2. 2 CTAs/SM, in kernel A only. It takes 384 of 512 TMEM columns and single-buffering the score and gradient segments lands exactly on 256 — but that deletes the overlap that is the whole design. Worth a sweep, not a guess. Kernel B has no version of this: two accumulators is 512 columns.
  3. 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 a pub const.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rewrite flash-attention backward on current ferro-kittens (first backward consumer — expect library gaps)

1 participant