Skip to content

The dY staging pass keeps the row dot it was already holding - #114

Merged
feitreim merged 5 commits into
mainfrom
flash-backward-dot-fused
Aug 6, 2026
Merged

feitreim merged 5 commits into
mainfrom
flash-backward-dot-fused

Conversation

@feitreim

@feitreim feitreim commented Aug 6, 2026

Copy link
Copy Markdown
Owner

Fusion item A3 from #107. The flash backward opened with two kernels reading
the same fp32 [N, D] gradient back to back:

flash_attention_backward_dot_bf16(dy, y) -> softmax_dot     [N, H]
stage_attention_heads_bf16(dy)           -> scratch.dy      packed [B*H, T, HD]

The dot needs exactly the numbers the staging pass already holds in registers.
stage_attention_dy_dot_bf16 produces both in one traversal, so dy is read
once instead of twice: 4.50 GiB/step and 12 launches, as #107 priced it.

Only the staged arm has a dY panel to write. The Wide oracle arms keep the
standalone backward_dot, which is why both kernels stay.

The bit-exact part

check_fused_staging (#88/#90) set the precedent: when everything a fusion
drops was storage between two kernels, the substitution owes exact parity,
not a tolerance. That is reachable here for the dot too, and the new gate
asserts it — every staged word and every dot bit.

The reduction is what makes it work. The twin walks a shared-memory tree over
HD = 128 lanes: P[i] += P[i+64], then 32, 16, … The fused pass gives each
(row, head) one warp and each lane pairs lane and lane + 32 — the twin's
elements i and i + 64. So the twin's first tree step is the lane's own add,
and the five shfl.bfly steps that follow pair the same indices the remaining
tree levels do. Lane 0 ends holding the twin's number, not an equivalent one.

One thing had to be said out loud. The first device run matched every staged
word and missed the dot by two ulp: nothing separates the fused kernel's two
products from the add that consumes them, so the backend contracted them into
an fma the twin cannot reach (its products go through shared memory first).
float::mul_rn_f32 / float::add_rn_f32 spell the twin's arithmetic, and the
gate then passes exactly.

Measured

bin/train.rs, B=16, B200, same shard and seed, step 1 outside the timing
window. Three baseline/candidate pairs, each pair inside one container:

pair steps main dc6f533 this branch delta
A 100 81 928.8 tok/s 82 723.3 +0.97%
B 300 78 771.4 79 945.0 +1.49%
C 100 83 313.0 84 692.9 +1.66%
pair MFU main MFU branch delta
A 36.38% 36.73% +0.35 pt
B 34.98% 35.50% +0.52 pt
C 36.99% 37.61% +0.62 pt

Call it ~+1.4%. Note the baseline itself reads 78.8k / 81.9k / 83.3k across
the three containers — a 5.7% spread on identical code. That is the whole
reason SPEC §11 wants the pair from one container, and it is why the between
container numbers in #107's thread should not be differenced.

Where the time goes

compare_profile, both binaries in one container (modal run modal_app.py::main --kernel model --baseline-ref dc6f533):

span main this branch
backward.attention.flash_dot 5.1145 ms (0.68%) —
backward.attention.stage_bf16 2.5305 ms (0.34%) —
backward.attention.stage_dot_bf16 — 1.8124 ms (0.24%)
the pair 7.6450 ms (1.02%) 1.8124 ms (0.24%)
full step 749.4846 ms 741.8651 ms (−1.02%)

The traffic argument does not explain this, and it is worth saying so.
4.50 GiB/step at the B200's HBM rate is worth roughly 0.6 ms; the measured
saving is 5.83 ms. Read it as achieved bandwidth instead:

bytes moved time achieved
flash_dot 6.75 GiB 5.11 ms 1.4 TB/s
stage_bf16 6.75 GiB 2.53 ms 2.9 TB/s
fused 6.75 GiB 1.81 ms 4.0 TB/s

Half the win is the halved traffic. The other half is that flash_dot's shape
was the problem: 786 432 blocks of 128 lanes, each spending seven
__syncthreads on a shared-memory tree to emit one float, at 1.4 TB/s. A warp
per row with five shuffles and no barrier is simply a better way to reduce 128
elements, and the fused pass ends up faster than the staging kernel alone
(1.81 ms vs 2.53 ms) despite reading the y panel the staging kernel never
touched — it also does the %// decode of the head layout once per two
pairs instead of once per pair.

Registers and occupancy

Fusion raises liveness, so the harness now asks the driver directly
(bench_util::function_profile, which already existed for this; ncu's counter
library does not load on the B200 container, so it is the driver or nothing):

dY pass residency (registers/thread, spill bytes, blocks/SM)
  stage_attention_heads_bf16           24      0    8 at 256 threads
  flash_attention_backward_dot_bf16    16      0   16 at 128 threads
  stage_attention_dy_dot_bf16          28      0    8 at 256 threads

+4 registers over the staging kernel, no spill, and 8 × 256 = 2048
threads/SM — the same ceiling both kernels it replaces already sat at. No
occupancy step is crossed. (Numbers are the flash-attn crate's composition.)

Gates

  • modal run modal_app.py::main --kernel flash-attn — the new third-tier gate
    passes at (1,128,2), (2,256,3), (1,1024,4), asserting the fused kernel's
    staged words and dot bits against stage_attention_heads_bf16 +
    flash_attention_backward_dot_bf16 exactly. Every existing flash gate
    still green.
  • modal run modal_app.py::main --kernel model — all 15 end-to-end gates green
    at the existing tolerances (BF16_ATOL = 3e-3, BF16_RTOL = 3e-2).
    Nothing loosened.

Since both device outputs are bit-for-bit the twin's, the trajectory can only
move through the trainer's existing atomics nondeterminism (#108 measured that
at |Δloss| = 0.077 over 100 steps for main against itself); the logged losses
across the six runs above are consistent with that and step 1 is identical to
the last digit in all of them.

compare_train

compare_profile builds a retained baseline beside the mounted candidate and
runs them back to back, but only for bin/profile. A throughput claim is made
with bin/train.rs, and SPEC §11 wants the pair from one container, so this
adds the same shape for train: clone the ref, rewrite both trees' compile-time
B the way batch_sweep does, run both.

modal run modal_app.py::compare_train --baseline-ref dc6f533 --steps 300 --batch 16

Two operational notes for whoever uses it next. It refuses a baseline pinning a
different cuda-oxide revision rather than silently installing one —
compare_profile is the entry point that handles historical refs. And with
several agents running against the same Modal app, the CLI log stream can
interleave another run's output into yours: check that the log holds exactly
two training shard= lines at the step count you asked for before differencing
it. One of my pairs had to be discarded for this.

Not in this PR

A3 is the smallest of #107's three attention-adjacent items. A8 (stop
materializing the V head panel, 6.75 GiB) is untouched and still needs flash's
TMA descriptor over the fp32 qkv panel. The Wide arms keep the standalone
backward_dot because they have no dY panel to fold it into — the fp32 tiled
and per-row oracle paths are unchanged, which is what keeps them oracles.

`flash_attention_backward_dot_bf16` and `stage_attention_heads_bf16` open the
flash backward by reading the same fp32 `[N, D]` gradient back to back: one
reduces the per-row `sum_d dy * y`, the other de-interleaves dY into the
packed-bf16 head panels the tcgen05 kernels stream with TMA. The dot needs
exactly the values the staging pass already has in registers.

`stage_attention_dy_dot_bf16` does both in one traversal. One warp owns each
`(row, head)` and each lane owns pairs `lane` and `lane + 32` — the twin's
elements `i` and `i + 64` — so the twin's first tree step is the lane's own
add and the rest is a butterfly over the same pairings. The staged words are
the same arithmetic on the same bytes. Both outputs are the composition's bit
for bit, which is what the new third-tier gate asserts.

Only the staged arm has a dY panel; the oracle arms keep the standalone dot.
The staged words matched on the first run; the dot was two ulp off. Nothing
separates the fused kernel's two products from the add that consumes them, so
the backend contracted them into an fma the twin cannot reach — its products
go through shared memory first. Spelling the mul and the add rn makes the two
kernels compute the same number, and the third-tier gate now passes exactly.
`compare_profile` builds a retained baseline beside the mounted candidate and
runs them back to back, but only for `bin/profile`. Throughput is claimed with
`bin/train.rs`, and SPEC 11 wants the pair from one container, so give train
the same shape: clone the ref, rewrite both trees' compile-time batch, run.
… it correct

Fusion raises liveness, and a kernel that crosses an occupancy step can lose
on the clock while winning on traffic — so the parity harness now prints what
ptxas gave all three kernels and how many blocks the driver will resident.
`bench_util::function_profile` already existed for exactly this; ncu's counter
library does not load on the B200 container, so the driver is the readout.
@feitreim

feitreim commented Aug 6, 2026

Copy link
Copy Markdown
Owner Author

Heads-up on overlap: there is a compare-train-harness worktree in flight locally that appears to build the same same-container train comparison. If that lands first, drop this PR's compare_train hunk in modal_app.py and keep theirs — the measurement above does not depend on which copy survives, only on the pair coming from one container. The kernel change is confined to gpu/flash-attn/src/ and the one call site in gpu/model/src/lib.rs.

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.

1 participant