Skip to content

FA4 phase 3: conditional rescaling, persistent ping-pong kernel, model integration (#35) - #39

Merged
feitreim merged 3 commits into
mainfrom
feat/issue-35-fa4-fwd-phase3
Jul 19, 2026
Merged

feitreim merged 3 commits into
mainfrom
feat/issue-35-fa4-fwd-phase3

Conversation

@feitreim

Copy link
Copy Markdown
Owner

Phase 3 of #35: the softmax-path optimizations and the model integration — conditional O-segment rescaling, the full-tile/diagonal loop split, a persistent two-Q-tile ping-pong kernel, and gpu/model routing tile-aligned attention through it. The forward now runs on tensor cores end-to-end in the trainer; backward stays on the fp32 tiled kernels until phase 4.

Kernel work

Conditional rescaling segments (softmax_tile, shared by all three forwards). O no longer drains from TMEM every tile: it accumulates in a segment under a fixed per-row max reference (enable_d across tiles), and P is exponentiated against that reference. Only when a tile's row max climbs more than CORRECTION_THRESHOLD (2⁸, a SWEEP const) above it does the warpgroup drain the segment into registers, rescale, and restart it. Because a restart is collective (one MMA covers all 128 rows), the decision is a warpgroup-wide vote: one vote.any per warp into four shared words, made collective by a single 128-count mbarrier phase per tile. The restart flag rides to the MMA warp through the existing p_full arrive/wait (mbarrier release/acquire), and the drain needs no new ordering — the previous tile's o_full wait already proves the segment is complete. Tile 0 always votes yes (the reference starts at MASKED_SCORE), which starts the first segment without special-casing; a drain at tile i is legal because O-MMA(i) cannot start until this tile's P is published. Measured correction rate: 0.00% at every gate and bench distribution — the first tile's reference survives entire key streams, so in practice the warpgroup never touches O TMEM mid-stream (this is most of why the pipelined kernel got 27% faster). correction_counts is a permanent kernel output (one word per workstream), so the rate stays observable on real training activations.

Full-tile vs diagonal-tile loop split. diagonal was a loop-variant runtime bool, so the compiler kept the mask selects in every tile. The warpgroup loops now run full tiles with a literal false and the diagonal tile as a separate literal true call (warpgroup_tile is #[inline(always)], so the masking folds out of the hot loop). The sync oracle keeps its runtime flag — it is the debug kernel, and its job is simplicity.

flash_forward_persistent — two-Q-tile ping-pong plus the static scheduler, in one kernel:

  • Warpgroup A (warps 0–3) owns query tile 2p, warpgroup B (warps 4–7) owns 2p+1; they share one K/V TMA ring (load warp 8) and one MMA warp (warp 9). TMEM: single-buffered S per stream + one O segment per stream = 384 of 512 columns. With TMEM pinning occupancy to one CTA/SM, the second warpgroup is the only way to put more softmax throughput on the SM — the checklist's ping-pong.
  • CTAs run a static strided work-item loop over (pair, head, batch), items ordered by descending pair index so the causally long pairs deal out first. Launching with grid = item count degenerates to one item per CTA — the non-persistent debug config, exercised implicitly by every small parity shape.
  • Every mbarrier re-initializes per work item behind a block sync, so each item's phase-parity arithmetic starts at zero and imbalanced arrivals are wiped rather than threaded through the parity math. That re-init is also what makes the odd-tail cases trivial: kv_free's arrival count is chosen per item (2 consumer streams normally, 1 when the last odd pair leaves stream B inactive), and stream A simply never arrives for the shared ring's B-only diagonal tile.
  • The MMA warp interleaves per shared tile: S-MMA(A), S-MMA(B) (each gated by its own s_free), then both streams' O-MMA(i−1) — the phase-2 stagger, per stream. Progress is a fixed sequence whose every wait depends only on earlier items, so the two streams can drift at most ~2 tiles apart and cannot deadlock.

Model integration

gpu/model includes flash-attn's host module (the Tcgen05Gemm pattern) and every binary loads flash.ptx; Tcgen05Flash captures the SM count at load for the persistent grid. A new FlashAttentionScratch workspace (allocated only when T % 128 == 0 && HD == 64) holds three packed-bf16 [B*H, T, 64] staging buffers, their TMA maps, and the correction-count output. The forward dispatch stages Q (with softmax_scale·log₂e folded in), K, V via the existing stage_attention_heads_bf16 kernel and launches the persistent forward; non-aligned shapes keep the fp32 tiled kernel. Both paths write the identical fp32 y / natural-log LSE contract, so the fp32 backward is oblivious. modal_app.py prepares flash.ptx for model runs and both sides of BASELINE_REF profiles (baselines predating the flash bin skip the baseline-side prep).

Gates (B200, same container per run)

  • flash bin: exp2/log2/swizzle/transpose probes unchanged; parity vs the staged-bf16 CPU reference at T=128/256/384/512 and a 152-item shape (4,256,38 — CTAs actually loop work items; T=384 exercises the inactive-stream-B pair). All three kernels produce bit-identical max errors at every shape (y ≤ 1.6e-3, LSE ≤ 7.3e-5) — the schedule changed, not one arithmetic result.
  • oracle harness: per-row + fp32 tiled chain and 200-round bit-stability unchanged; all three forwards vs both oracles at T up to 1024 (y ≤ 2.36e-3, lse ≤ 8.9e-4, again schedule-invariant).
  • model suite: tile-aligned MoE parity (T=128, now on bf16 attention), aligned/tiny overfits with AdamW and Muon, checkpoint gate — all green with no tolerance or lr re-tune (the re-tune the issue budgeted for was not needed).
  • bench (B=32, T=1024, H=24): sync 1.574→1.481 ms, pipelined 1.388→1.089 ms (+27% from segments + loop split), persistent 0.844 ms / 137.4 TFLOP/s (1.64× over the phase-2 result).
  • profile (BASELINE_REF=eb9fdff, 239.3M MoE, B=32 T=1024): 160.48 → 148.41 ms full step (−7.5%); forward.attention.flash 13.59 → 0.85 ms (16.0×), 1.23 ms including the new 0.38 ms staging row. The tail is now the fp32 attention backward (44.5 ms, 30.0% — phase 4) and the lm-head GEMM trio (54.2 ms, 36.5%).

Phase-3 checklist from #35

  • conditional rescaling segments (measured rate: 0.00%, permanently observable via correction_counts)
  • full-tile vs diagonal-tile loop split
  • two-Q-tile ping-pong per CTA (fits: 384/512 TMEM columns, 192 KiB SMEM at 3 stages)
  • persistent/static tile scheduler (descending-cost strided items; grid=items debug degenerate)
  • model integration + tile-aligned parity config (overfit gates passed untouched — no re-tune needed)

Next per the issue: phase 4 (tcgen05 backward — now 30% of the step and the single largest tail).

feitreim added 3 commits July 19, 2026 13:18
…op split, persistent ping-pong (#35)

- softmax_tile: O accumulates in a TMEM segment under a fixed per-row max
  reference; a warpgroup-collective vote (per-warp vote.any + one 128-count
  mbarrier phase) triggers drain+rescale only past CORRECTION_THRESHOLD
- full-tile vs diagonal-tile loop split in the pipelined/persistent
  warpgroup loops (mask logic folds out of the hot loop)
- flash_forward_persistent: two softmax warpgroups ping-pong adjacent query
  tiles over one shared K/V ring and MMA warp (TMEM 384/512 cols), with a
  static strided work-item loop, descending-cost ordering, and per-item
  barrier re-init; grid=items degenerates to non-persistent for debugging
- correction_counts output on all three forwards; flash bin reports the
  measured correction rate; parity adds T=384 (inactive stream B) and a
  152-item shape (multi-item persistent loop)
…05 forward (#35)

- gpu/model includes flash-attn's host module (Tcgen05Gemm pattern) and
  loads flash.ptx in every binary; Tcgen05Flash captures the SM count at
  load for the persistent grid
- FlashAttentionScratch workspace: three packed-bf16 [B*H, T, 64] staging
  buffers + TMA maps + correction counts, allocated only when T is
  tile-aligned and HD == 64; other shapes keep the fp32 tiled forward
- forward dispatch stages Q (with softmax_scale*log2e folded) / K / V and
  launches flash_forward_persistent; backward still consumes the unchanged
  fp32 y/LSE contract
- modal_app.py prepares flash.ptx for model runs and both sides of
  BASELINE_REF profiles
@feitreim
feitreim merged commit 7e5fea4 into main Jul 19, 2026
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