Skip to content

One flash-attention forward, at 128 query rows (#68) - #74

Merged
feitreim merged 15 commits into
mainfrom
feat/issue-68-flash-forward
Aug 3, 2026
Merged

feitreim merged 15 commits into
mainfrom
feat/issue-68-flash-forward

Conversation

@feitreim

@feitreim feitreim commented Aug 3, 2026 •

Copy link
Copy Markdown
Owner

Closes #68. Rebased onto main now that #71 has merged.

1.343 ms against the persistent kernel's 1.929 — 30.4% faster, over four
measured steps from a 2.635 ms first flight, with both parity gates green and
the LSE error 147x under the recorded maximum.

flash_forward_tcgen05, flash_forward_pipelined and flash_forward_persistent
become one flash_forward.

The design, in one paragraph

What made them three was a 64-query tile against an M128 accumulator.
Every MMA filled 64 real rows and 64 phantom ones — half the tensor core thrown
away, plus a PHANTOM_PAD on every plan to keep the phantom reads in bounds —
and phases 2 and 3 bought that half back with structure: a dedicated TMA warp
and MMA warp (pipelined), then two softmax warpgroups ping-ponging adjacent
query tiles over one ring (persistent). A CTA now owns 128 query rows. The
MMA is whole, the softmax warpgroup is naturally the accumulator's own four
warps, and the overlap that took three warp roles is one double-buffered score
segment: the leader issues S(i+1) before the warpgroup runs the softmax of
tile i, so the tensor core is running S(i+1) and O(i-1) throughout it.
128 threads where the persistent kernel had 192, and no phantom pad anywhere in
the module.

Everything else is the library:

was is
smem.add(n * TILE_BYTES) and static mut SharedArray<u64, N, 8> SharedPlan carve, FLASH_FORWARD_SMEM computed from it
the persistent kernel's hand-rolled item loop pipeline::run + a Job
~100 lines of per-value if col <= row across two passes one make_causal_at(lane, query_base, key_base, fill)
the running-max rescale, open-coded online_rescale
a votes array + a Semaphore phase, in three kernels block_reduce::<Max, 4>
store_outputs' hand-written strided y and LSE writes store_rows + store_row_vec

make_causal_at is not just shorter: a 128-row query block crosses the diagonal
in two key tiles, and the origin-free masking it replaces was only right for
the first. FA4's conditional correction survives unchanged in substance — the
output segment accumulates under a fixed per-row reference until some row's tile
max climbs past CORRECTION_THRESHOLD, and only then is it drained and
restarted.

The backward kernels are untouched (#69) and now share the forward's
PairedPanel / PairedPTile / STmem / AccTmem rather than parallel
definitions of the same shapes.

Parity — green, and better than the recorded maxima

cargo oxide run flash-attn --bin flash, staged-bf16 f64 CPU reference,
B200:

shape y max abs err lse max abs err
[2,128,3] 1.115e-3 4.768e-7
[1,256,2] 1.058e-3 4.768e-7
[1,384,2] 1.058e-3 4.768e-7
[1,512,2] 1.058e-3 9.537e-7
[4,256,38] 1.469e-3 9.537e-7

Tolerances are y 5e-3 / lse 1e-3; the recorded maxima for the kernels this
replaces were y 1.4e-3 and lse 1.4e-4, so y is at the recorded level and the
LSE is 147x under it
— the SFU exp2 is the more accurate of the two, which
is the opposite of what an "approx" instruction is usually reached for.

The two-oracle gate (cargo oxide run flash-attn) against ops'
materialized-probability attention and the fp32 tiled forward, tolerances
y 1e-2 / lse 5e-3:

shape y/naive y/tiled lse
[1,128,2] 2.086e-3 2.086e-3 1.083e-3
[2,256,3] 2.358e-3 2.358e-3 1.219e-3
[1,1024,4] 2.263e-3 2.263e-3 1.083e-3

The recorded maxima here were y 2.4e-3 and lse 8.9e-4, so y matches and the
LSE against the fp32 oracle is 1.4x looser
(4x inside its tolerance either
way). That direction is the opposite of the CPU-reference table above, and both
are the same fact: against a bf16-staged reference the wider query block is
more accurate, and against an fp32 oracle it moves which operand quantization
lands where. Nothing here is a change in the LSE's own formula, which is the
same LN2 * (m_ref + log2(sum)).

Backward parity is unchanged to the digit on all three shapes in both gates.

[4,256,38] is 304 work items against 148 SMs, so the persistent loop wraps;
[1,384,2] is an odd block count.

Performance — 1.343 ms against the persistent kernel's 1.929

Kernel bench at [32,1024,24,128], cargo oxide run flash-attn --bin flash, one
container per row:

ms vs 1.929 step
flash_forward_persistent (SPEC 13, recorded at the current pin) 1.929 — —
unified forward, whole-band softmax 2.635 +36.6% first flight
+ softmax walked in 16-column chunks 2.111 +9.4% −19.9%
+ SFU exp2 1.845 −4.4% −12.6%
+ one-barrier correction vote 1.888 −2.1% +2.3%, reverted
+ 2 K/V stages, 1 P buffer, exact launch request 1.343 −30.4% −27.2%

Read the milliseconds, not the TFLOP/s. The bench's FLOP count changes in
this PR from issued MMA work to algorithmic: issued was twice algorithmic only
because of the phantom half, the unified kernel issues no phantom rows, and the
two have converged. The old 226 TFLOP/s figures are 2x this scale.

What each lever bought

Two CTAs an SM (−27.2%, the big one). The plan was 164 KiB and the launch
requested 197
— a ceiling sized for the deepest supported FORWARD_STAGES, on
the argument that it kept stage sweeps a one-const edit and cost nothing at
1 CTA/SM. The second half of that stopped being true the moment the plan could
fit twice: the launch's request is what the driver charges an SM, so the
ceiling was pinning residency at its own. FORWARD_STAGES 3 → 2 and the
probability ring 2 → 1 puts the tiles at 114688 B — the plan measures 114836 —
under the 116736 that half of a B200 SM's 233472 admits, and the launch now
requests the plan itself. TMEM was never binding: 256 of 512 columns already
admitted two. The grid follows, via a FLASH_FORWARD_CTAS_PER_SM that is the
min of what the shared plan and the tensor-memory allocation each admit
(ferro #84 measured residency as exactly that min at every rung it tried).
This is ferro #85's question answered for this kernel: the threshold that issue
brackets but does not locate is at or above 114836 B.

It cost one bug worth recording. At three stages the refill ran one tile
further ahead than the score MMA's operand, so issuing the MMA first and
refilling second happened to work; at the ring's floor of two, refill == key_tile + 1 is exactly the tile the score MMA waits for, and the leader waited
for a load it had not issued. A hang, and only on a key stream longer than the
ring — [2,128,3] passed and [1,256,2] did not. Refilling first is correct at
every depth.

SFU exp2 (−12.6%). ferro #81 measured it at 2.7x the software polynomial,
timed, and this kernel is where that lands: 64 exponentials per thread per key
tile, in a four-warp warpgroup nowhere near tensor-core bound. The polynomial
was an FA4-shaped offload choice, made when the softmax warpgroup shared an SM
with a TMA warp and an MMA warp and the SFU was the contended resource;
dissolving those roles dissolved the reason. It is also the more accurate of
the two here — ex2.approx.f32 is ~2 ULP against the polynomial's measured
7.5e-5 relative — and the LSE's max error drops 77x, from 7.33e-5 to
9.54e-7. log2 in the epilogue stays software: once per row, against 64 exp2
per thread per tile.

The correction vote (+2.3%, reverted). block_reduce is two bar.sync; the
replacement was the shape all three extracted kernels used — a per-warp votes
ring and one mbarrier phase. It measured slower, against a bench the SPEC
records as stable to 0.7%, so the commit is reverted and kept as the data point.
The finding is the useful part: the cost of the vote is the rendezvous, not
the primitive it is spelled with.
A 128-arrival mbarrier is not cheaper than a
barrier.sync, and block_reduce throws in the fold. So the cheap form of
"don't pay the vote barriers" does not exist — the only version that removes a
rendezvous rather than renaming one is deferring the output MMA by a tile so the
vote reuses the barrier the P store already needs, which restructures the loop's
hand-offs and can deadlock in ways a swap cannot. Left undone deliberately.

What remains in the gap to a hypothetical zero is inherent: a 128-row query
block necessarily reads one fully-masked 64x64 pair per block, 8 of 144 at
T=1024 (5.9%).

The measurement that moved most, and why it is worth writing down

Holding the whole [32, 64] score band as a value — tile_x8, mask,
row_max, sub_row_assign, exp2, row_sum, store_tile — beside the
128-register output accumulator put the band in the LLVM local depot. The PTX
census: 1328 B of frame and 3546 ld/st.local in flash_forward, the
largest in the module by a factor of three, with the tcgen05.ld block itself
storing 64 words of what it had just read. That was the 2.635 ms.

Walking the band 16 columns at a time keeps every pass in registers. 2.111
ms, −19.9%, parity unchanged to the digit, at the price of a second drain of
the segment — which is exactly what softmax_tile paid, for exactly this
reason. So #61's risk 1 is real and it is about the width the register ops
are asked to work at, not about indexed writes specifically.

What is left in the depot (1072 B) is out_acc itself: both writers
(online_rescale, merge_output_tile) take it by &mut, so it is
address-taken and goes to memory whole. It is not hot — inside the key stream
its only reader is the correction path, and corrections fire on 0.00% of
visits at every gated shape
, including 49152 eligible visits at the bench
shape.

ptxas: forward 246 regs / 1072 B against the persistent kernel's 236 / 592 —
and now at 2 CTAs/SM against its 1, so the register file is the less
constrained of the two.
The backward pins moved by ±1–2 with nothing in those kernels changed — three
kernels left the shared artifact and the allocator re-rolled, the same crate
composition effect that has moved a GEMM by 68 registers, here worth one, and
in both directions.

ferro-kittens

Filed and fixed:

Weighed and not needed: #128's unchecked alloc_block columns — this
kernel's 256 is 2 * TILE + HD exactly and carries its own const assert; and
#132's warp-asynchronous item stream — dissolving the warp roles is what made
pipeline::run fit, so the limitation did not bind.

Pins

None left. gpu/flash-attn, gpu/model and gpu/gemm all point at
ferro-kittens main (37ea9e7), which now contains both #170 and #176. The
branch pin this PR was developed against is gone, and the numbers above are
from a full re-run on main: 244 regs / 1136 B and every parity figure
identical to the digit, bench 2.125 → 2.111 ms (container noise).

gpu/gemm moves too — it was still on the pre-#66 rev, and a repo carrying two
revs of the same library is a composition difference nobody asked for
(register counts move with crate composition here).

What remains

  1. out_acc out of the depot. tcgen05.st — absent when this correction
    scheme was designed, present in the library now — lets the correction rescale
    the O segment in place, and then the 128 registers are the epilogue's
    transient rather than the loop's resident. Filed as ferro-kittens #177
    rather than done here: the path would be exercised on 0.00% of visits by
    every gate in this repo, and ferro's own doc calls the fence discipline
    around STTM→MMA hand-off open. It wants a device case first, and that issue
    spells out which one.
  2. The vote's rendezvous. See above — the swap measured backwards, and the
    version that would actually help defers the output MMA by a tile.
  3. The masked half-tile, 5.9% and inherent to a 128-row query block.
  4. FORWARD_STAGES is a pub const and 2 is now the floor, so the sweep
    that found this is one edit wide if the shape ever changes.

@feitreim
feitreim force-pushed the feat/issue-68-flash-forward branch from 6c9407c to b1e3f94 Compare August 3, 2026 18:42
@feitreim

feitreim commented Aug 3, 2026

Copy link
Copy Markdown
Owner Author

ferro-kittens #176 (the mma_ab band-width fix) is merged. That one is not on this branch's pin path — it touches the example and the doctest, not anything this kernel calls — so the pin still points at #170's head and still moves back to ferro main when #170 merges.

The three generations of issue #35 — `flash_forward_tcgen05`,
`flash_forward_pipelined`, `flash_forward_persistent` — collapse into
`flash_forward`. What made them three was a 64-query tile against an `M128`
accumulator: every MMA filled 64 real rows and 64 phantom ones, half the tensor
core thrown away, and phases 2 and 3 bought it back with structure — a
dedicated TMA warp and MMA warp, then two softmax warpgroups ping-ponging
adjacent query tiles over one ring.

A CTA now owns 128 query rows. The MMA is whole, the softmax warpgroup is
naturally the accumulator's own four warps, and the overlap that took three
warp roles is one double-buffered score segment: the leader issues `S(i+1)`
before the warpgroup runs the softmax of tile `i`, so the tensor core is
running `S(i+1)` and `O(i-1)` throughout it. 128 threads where the persistent
kernel had 192, and no phantom-read pad in any plan in the module any more.

The rest is the library's, which is the other half of #68. `SharedPlan` carves
the plan instead of a column of `smem.add(n * TILE_BYTES)`. `pipeline::run` is
the persistent work-item loop. `make_causal_at` takes the two block origins, so
the hand-written per-value diagonal branch — a hundred lines of `if col <= row`
across two passes — is one call, and it is right for both diagonal tiles rather
than only the first. `online_rescale` is the flash rescale. `block_reduce` is
the correction vote three kernels open-coded as a votes array plus a barrier
phase. `tcgen05.ld.x8` drains a band 64 columns at a time where the old drain
took 16. `store_row_vec` writes the LSE, which is what ferro #130 was about.

FA4's conditional correction survives unchanged in substance: the output
segment accumulates under a fixed per-row reference until some row's tile max
climbs past `CORRECTION_THRESHOLD`, and only then is it drained and restarted.

The backward kernels are untouched (#69) and now share the forward's
`PairedPanel`/`PairedPTile`/`STmem`/`AccTmem` rather than parallel definitions.

The bench's FLOP count changes from *issued* MMA work to algorithmic: issued
was twice algorithmic only because of the phantom half, and the two have
converged. Compare the milliseconds against the recorded figures, not the
TFLOP/s.

`kittens` is pinned to feitreim/ferro-kittens#170's tested rev for
`global::store_row_vec`; the pin moves back to ferro main when that merges.
Holding the whole [32, TILE] score band as a value alongside the 128-register
output accumulator put it in the LLVM local depot: 1328 B of frame, 3546
ld/st.local, and the drain block itself storing 64 words of what it had just
read. 2.635 ms at the profile shape.

Walking it 16 columns at a time keeps every pass in registers, at the price of
a second drain of the segment — which is what softmax_tile paid too, for the
same reason. 2.125 ms, -19.4%, parity unchanged to the digit.

What is left in the depot (1136 B) is out_acc, address-taken by online_rescale
and merge_output_tile, and read inside the key stream only by the correction
path — which fires on 0.00% of visits at every gated shape.
The row-statistic store the LSE epilogue needs (ferro #130 -> #170) and the
mma_ab band-width fix (ferro #175 -> #176) both merged, so all three kernel
crates point at ferro main again. gemm comes along because a repo carrying two
revs of the same library is a composition difference nobody asked for.
@feitreim
feitreim force-pushed the feat/issue-68-flash-forward branch from 5ceacd3 to 32d16cf Compare August 3, 2026 18:46
@feitreim

feitreim commented Aug 3, 2026

Copy link
Copy Markdown
Owner Author

Rebased onto main — #71 merged while this was in flight, so the stack is gone and the diff is 12 files, all of them this change. Both ferro-kittens PRs (#170, #176) are merged too, so the branch pin is gone: all three kernel crates point at ferro main (37ea9e7), re-validated end to end there — 244 regs / 1136 B, every parity figure identical to the digit, bench 2.111 ms.

ferro #81 measured the SFU exp2 at 2.7x the software polynomial, timed. The
polynomial was an FA4-shaped offload choice made when the softmax warpgroup
shared an SM with a TMA warp and an MMA warp; this kernel is four warps and is
not tensor-core bound, so there is nothing to offload to. It is also the more
accurate of the two — ex2.approx.f32 is ~2 ULP against the polynomial's
measured 7.5e-5 relative.

log2 in the LSE epilogue stays software: once per row, against 64 exp2 per
thread per key tile.
block_reduce is a publish sync and a read sync, and this loop is barrier-bound
rather than reduction-bound: three block-wide rendezvous per key tile, for a
decision that fires on 0.00% of visits.

Back to the shape all three extracted kernels used — a per-warp votes ring in
shared memory and one mbarrier phase. Two parities, because the vote
rendezvouses the warpgroup every tile, so a warp is at most one tile ahead of
another and cannot reach a third.

The library op was the right instinct and the wrong trade here; block_reduce
folds to a scalar and costs two syncs, and this vote needs neither the fold nor
the second sync.
…mitive

Measured on B200 at [32,1024,24,128]: 1.845 ms with `block_reduce`, 1.888 with
the votes ring and one mbarrier phase. +2.3%, against a bench the SPEC records
as stable to 0.7% across containers, so it is a real regression and not noise.

The finding is the useful part. Going from two `bar.sync` to one mbarrier
arrive/wait made it *slower*, which says the cost of the vote is the
**rendezvous** — four warps of a 128-thread block having to meet — and not the
primitive the rendezvous is spelled with. A 128-arrival mbarrier is not cheaper
than a `barrier.sync`, and `block_reduce` gets a fold thrown in.

So the cheap form of "don't pay the vote barriers" does not exist: the only
version that removes a rendezvous rather than renaming it is deferring the
output MMA by one tile so the vote reuses the barrier the P store already
needs, which is a restructure of the loop's hand-offs and not a swap. Left
undone deliberately — the kernel is already past the persistent kernel's
number, and that change can deadlock in ways this one cannot.
The plan was 164 KiB and the launch requested 197 — a ceiling sized for the
deepest supported FORWARD_STAGES, on the argument that allocating it kept stage
sweeps a one-const edit and cost nothing at 1 CTA/SM. The second half of that
stopped being true the moment the plan could fit twice: the launch's request is
what the driver charges an SM, so the ceiling was pinning residency at its own.

FORWARD_STAGES 3 -> 2 and the probability ring 2 -> 1 puts the tiles at
114688 B, under the 116736 that half an SM's 233472 admits, and the launch now
requests the plan itself. TMEM was never the binding constraint: 256 of 512
columns already admitted two.

The grid follows — flash_forward_config multiplies the SM count by
FLASH_FORWARD_CTAS_PER_SM, which is the min of what the shared plan and the
tensor-memory allocation each admit (ferro-kittens #84 measured residency as
exactly that min at every rung it tried). A caller should not have to know the
multiplier, and a grid of one CTA per SM would leave half the SM idle.

The single probability buffer is the cost: tile i's store now waits on the
output MMA of tile i-1 rather than i-2.
246 regs / 1072 B. The frame comes down 1136 -> 1072 with the software exp2
polynomial's temporaries gone; the two registers back are ptxas re-rolling the
schedule against a shorter softmax and a shallower ring, at an occupancy that
is now shared-memory-bound at two CTAs rather than one.
At three stages the refill was one tile further ahead than the score MMA's
operand, so issuing first and refilling second happened to work. At the ring's
floor of two, refill == key_tile + 1 is exactly the tile the score MMA waits
for, and the leader waits for a load it has not issued: a hang, and only on a
key stream longer than the ring, which is why [2,128,3] passed and [1,256,2]
did not.

Refilling first is correct at every depth and costs the leader the wait for the
previous output MMA before it can feed the tensor core — which is what a
two-stage ring is, stated honestly.
@feitreim

feitreim commented Aug 3, 2026

Copy link
Copy Markdown
Owner Author

1.343 ms against the persistent kernel's 1.929 — 30.4% faster. Both parity gates green, LSE error 147x under the recorded maximum. Body updated with the per-lever table.

Levers, one container each:

step ms step delta
chunked softmax (already in this PR) 2.111 −19.9%
SFU exp2 1.845 −12.6%
one-barrier correction vote 1.888 +2.3%, reverted
2 K/V stages, 1 P buffer, exact launch request 1.343 −27.2%

Three things worth pulling out:

  • The launch request was the occupancy. The plan was 164 KiB and the launch asked for 197 — a ceiling sized for the deepest FORWARD_STAGES, on the argument that it cost nothing at 1 CTA/SM. It was the 1 CTA/SM. Requesting the plan itself, at 114836 B, is 2 CTA/SM, and that is ferro Residency is measured, and cuBLASLt's configuration is read (#80) #85's threshold located from below for this kernel.
  • The vote lever measured backwards and is reverted as a data point, per this repo's gemm_ws precedent. Two bar.sync → one 128-arrival mbarrier is slower: the cost is the rendezvous, not the primitive.
  • The SFU exp2 is the more accurate of the two, not a precision trade — LSE max error 7.33e-5 → 9.54e-7.

The deferred tcgen05.st work is ferro-kittens #177, filed rather than done: the path would run on 0.00% of visits at every gate here, and ferro's own doc calls the STTM→MMA fence discipline open. The issue specifies the device case that would close it.

kittens stays pinned at 37ea9e7 — a merged ferro-main commit carrying #170, #171 and #176, and the rev everything above was measured on. ferro #173 has merged since; it adds an entry point nothing here calls, so moving the pin is a no-op for this kernel and I have left it at the measured rev rather than re-validate for nothing.

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 forward on current ferro-kittens

1 participant