Repository navigation
One flash-attention forward, at 128 query rows (#68) - #74
Conversation
6c9407c to
b1e3f94
Compare
|
ferro-kittens #176 (the |
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.
5ceacd3 to
32d16cf
Compare
|
Rebased onto |
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.
|
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:
Three things worth pulling out:
The deferred
|
…nd the trainer takes the unified backward
Closes #68. Rebased onto
mainnow 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_pipelinedandflash_forward_persistentbecome one
flash_forward.The design, in one paragraph
What made them three was a 64-query tile against an
M128accumulator.Every MMA filled 64 real rows and 64 phantom ones — half the tensor core thrown
away, plus a
PHANTOM_PADon 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 oftile
i, so the tensor core is runningS(i+1)andO(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:
smem.add(n * TILE_BYTES)andstatic mut SharedArray<u64, N, 8>SharedPlancarve,FLASH_FORWARD_SMEMcomputed from itpipeline::run+ aJobif col <= rowacross two passesmake_causal_at(lane, query_base, key_base, fill)online_rescaleSemaphorephase, in three kernelsblock_reduce::<Max, 4>store_outputs' hand-written stridedyand LSE writesstore_rows+store_row_vecmake_causal_atis not just shorter: a 128-row query block crosses the diagonalin 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 andrestarted.
The backward kernels are untouched (#69) and now share the forward's
PairedPanel/PairedPTile/STmem/AccTmemrather than paralleldefinitions 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:
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
exp2is the more accurate of the two, whichis the opposite of what an "approx" instruction is usually reached for.
The two-oracle gate (
cargo oxide run flash-attn) againstops'materialized-probability attention and the fp32 tiled forward, tolerances
y 1e-2 / lse 5e-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, onecontainer per row:
flash_forward_persistent(SPEC 13, recorded at the current pin)exp2Read 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, onthe 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_STAGES3 → 2 and theprobability 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_SMthat is theminof what the shared plan and the tensor-memory allocation each admit(ferro #84 measured residency as exactly that
minat 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 + 1is exactly the tile the score MMA waits for, and the leader waitedfor 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 atevery 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.f32is ~2 ULP against the polynomial's measured7.5e-5 relative — and the LSE's max error drops 77x, from 7.33e-5 to
9.54e-7.
log2in the epilogue stays software: once per row, against 64exp2per thread per tile.
The correction vote (+2.3%, reverted).
block_reduceis twobar.sync; thereplacement 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, andblock_reducethrows 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 the128-register output accumulator put the band in the LLVM local depot. The PTX
census: 1328 B of frame and 3546
ld/st.localinflash_forward, thelargest in the module by a factor of three, with the
tcgen05.ldblock itselfstoring 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_tilepaid, for exactly thisreason. 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_accitself: both writers(
online_rescale,merge_output_tile) take it by&mut, so it isaddress-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:
forward246 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:
RegVechad no bridge to memory at all, and the LSE epilogue isexactly that: one f32 per query row, in the head's own column of a
[rows, heads]buffer at strideH. Fixed in A row statistic reaches global memory, and the row axis says which lane writes it (#130) ferro-kittens#170(
global::store_row_vec/load_row_vec, plusRowLayout::owns_row— thepart that could not be derived, since
row_ofis not injective across a warpand a store without an owner is four threads writing one address). Commented
on The pin reaches ferro main, and the module the driver refused loads: #227 confirmed downstream #130 with what the implementation sharpened.
mma_ab'sshapeis the output band's width, not thetile's, and two places said otherwise: the entry point's own doctest and
examples/src/flash_forward.rs:174, the file Rewrite flash-attention forward on current ferro-kittens #68 says to start from. Withp:[128,64]andv:[64,128]aM128_N128makes band 1 overwrite half ofband 0 and run 64 columns past a
[128,128]accumulator — a wrongOthatfaults nothing, because the columns are still inside the allocation. It has
been there since the example was written; ferro Residency is measured, and cuBLASLt's configuration is read (#80) #85 (no launcher, no CPU
reference) is why nothing caught it. Fixed in
mma_ab's shape is the band's, and the two callers that read it as the tile's (#175) ferro-kittens#176.
Weighed and not needed: #128's unchecked
alloc_blockcolumns — thiskernel's 256 is
2 * TILE + HDexactly and carries its own const assert; and#132's warp-asynchronous item stream — dissolving the warp roles is what made
pipeline::runfit, so the limitation did not bind.Pins
None left.
gpu/flash-attn,gpu/modelandgpu/gemmall point atferro-kittens
main(37ea9e7), which now contains both #170 and #176. Thebranch 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 figureidentical to the digit, bench 2.125 → 2.111 ms (container noise).
gpu/gemmmoves too — it was still on the pre-#66 rev, and a repo carrying tworevs of the same library is a composition difference nobody asked for
(register counts move with crate composition here).
What remains
out_accout of the depot.tcgen05.st— absent when this correctionscheme 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.
version that would actually help defers the output MMA by a tile.
FORWARD_STAGESis apub constand 2 is now the floor, so the sweepthat found this is one edit wide if the shape ever changes.