Repository navigation
Description
FA4-shaped flash attention: warp-specialized tcgen05/TMA pipeline
Tracking issue for rebuilding gpu/flash-attn around the FlashAttention-4 architecture (async tcgen05 MMA pipeline, TMA loads, TMEM accumulation, software-emulated exp2, conditional softmax rescaling), forward first, backward to follow. Phases below are sized so each lands behind the standard gates (SPEC §10.1 same-container profile, §11 three-tier oracle chain). Sub-issues can be split off per phase when work starts.
1. Motivation
Post-7e9 profile (B200, B=32, T=1024, H=24, HD=64, 152.14 ms full step): flash attention is the #1 tail at 57.5 ms combined forward+backward, 37.8% of the step.
The current *_tiled kernels (gpu/flash-attn/src/lib.rs) are FlashAttention-2 shaped — staged SMEM tiles, register-tiled score fragments, query/key-block parallelism — but executed as fully synchronous fp32 SIMT: every stage is separated by sync_threads, all math runs on FMA/SFU units, and the tensor cores are completely idle.
Roofline at the profile shape:
| Quantity | Value |
|---|---|
| Forward FLOPs (causal, 2 GEMMs) | ≈ 4·B·H·T²·HD / 2 ≈ 103 GFLOP |
| Backward FLOPs (≈2.5× forward) | ≈ 258 GFLOP |
| Achieved (361 GFLOP / 57.5 ms) | ≈ 6.3 TFLOP/s |
| B200 bf16 dense peak | 2,250 TFLOP/s (≈0.3% achieved) |
| FA4 reported (paper, fwd, bf16) | 1,613 TFLOP/s (71%) |
| This plan at a modest 15% util | ≈ 1.1 ms combined → ~50× tail reduction |
Even the non-pipelined phase 1 (tensor cores + halved operand bandwidth, no overlap) should capture the bulk of the win; the pipeline phases convert the remainder from "waiting in lockstep" to "overlapped".
2. What FA4 is, in one paragraph
FA4 (Dao et al., arXiv 2603.05451; see also Modal's teardown, modal.com/blog/reverse-engineer-flash-attention-4) restructures attention for Blackwell's asymmetric scaling: tensor cores got 2.25× faster while SMEM bandwidth and SFU (exp) throughput stayed flat. It responds with (a) a warp-specialized producer/consumer pipeline — load warp (TMA), MMA warp (tcgen05 issue, single leader thread), softmax warpgroups, correction warpgroup, epilogue warp — synchronized entirely by SMEM mbarriers so one tile's softmax overlaps the next tile's MMA and the one after's loads; (b) softmax exponentials computed by a cubic-polynomial software exp2 on FMA units instead of queueing on the SFU; (c) conditional softmax rescaling — correct the output accumulator only when the running max moves enough to threaten numerical stability (~10× fewer corrections); (d) in backward, TMEM staging and 2-CTA MMA to cut SMEM traffic and atomic adds.
3. Capability audit: cuda-oxide v0.2.1
Everything below verified against the pinned tag's crates/cuda-device sources.
| FA4 ingredient | v0.2.1 | Notes |
|---|---|---|
| TMA async bulk tensor loads/stores | ✅ tma.rs |
1D–5D, multicast, commit/wait_group |
| tcgen05 MMA, fp32 TMEM accumulation | ✅ tcgen05.rs |
bf16/tf32 kinds; shapes M128_N64…M128_N256; transpose_a/b descriptor bits; enable_d accumulate flag |
| TMEM alloc/dealloc, TMEM→register loads | ✅ | tcgen05_alloc, tcgen05_ld_16x256b[_x8]_pure |
| register→SMEM matrix stores | ✅ | stmatrix_m8n8_x2/x4[_trans] |
| mbarrier init/arrive/expect_tx/try_wait_parity | ✅ barrier.rs |
proven in gpu/gemm's tcgen05 kernel |
register→TMEM tcgen05.st |
❌ | still absent on upstream main as of 2409204 — see #34 and §5.4 workaround |
Named barriers (bar.sync N, thread subsets) |
❌ | use mbarrier phase-parity spins for warp-role handoff (FA4 does the same) |
2-CTA MMA (cta_group::2) + cluster multicast |
✅ *_cg2 fns |
stretch phase only |
| >48 KiB dynamic SMEM | ✅ DynamicSharedArray |
needs CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES opt-in via cuda_core::sys on the raw-launch path |
Two hard constraints that shape the whole design
- Artifact split (libNVVM vs tcgen05).
f32::exp/ln/sqrtlower through libdevice, which forces the artifact through libNVVM, which rejects tcgen05 constructs — this is exactly whygemm.ptxis built separately andgpu/modelloads it via the host-onlygpu/gemm/src/host.rs(Tcgen05Gemm::load_from_ptx). The new attention kernels therefore (a) ship as a separately builtflash.ptxwith a host-only launcher module, and (b) may not use libdevice math at all — softmax needs a softwareexp2and the LSE epilogue a softwarelog2. Conveniently, softwareexp2is also FA4's SFU-offload optimization: the constraint and the optimization are the same work. - bf16 operands. tcgen05 wants bf16 (fp32 accumulate). The model's Q/K/V are fp32. SPEC §7 phase 2 already adopted bf16-compute/fp32-accumulate for the block linears (7e9); attention follows the identical precision contract: bf16 Q/K/V/P operands, fp32 TMEM accumulators, fp32 outputs and LSE.
4. Decisions already made
- De-interleaved bf16 staging, no strided-TMA spike (recorded on Bump cuda-oxide pin from v0.2.1 to current upstream main #34): a new quantize kernel converts fp32
[N, H·HD]→ packed-bf16[B·H, T, HD](contiguous per head) for Q, K, V, foldingsoftmax_scale·log₂einto Q so downstream softmax math is base-2 native. TMA maps become the plain contiguous kindgpu/gemmalready exercises; head selection is a base-pointer/coordinate offset, not descriptor gymnastics. The strided-map-over-interleaved-layout idea stays on record in Bump cuda-oxide pin from v0.2.1 to current upstream main #34 as a later optimization (relevant if quantize is ever fused into the QKV projection epilogue). - Segment-restart correction instead of in-TMEM rescaling, because
tcgen05.stdoesn't exist (§5.4). Escape hatch if the drain path ever dominates: add the intrinsic via cuda-oxide's new generated-intrinsics infra after the Bump cuda-oxide pin from v0.2.1 to current upstream main #34 bump — deliberately off the critical path. - Old kernels are never deleted. The per-row and fp32 tiled kernels remain in the normal
#[cuda_module]as parity oracles (three-tier chain), and remain the fallback for non-tile-aligned shapes. - Forward first, backward keeps running on the existing fp32 tiled kernels during rollout — the new forward preserves today's output contract (fp32
y[N, H·HD], fp32logsumexp[N, H]), so nothing downstream changes until phase 4.
5. Forward kernel design
5.1 Tiling and grid
- CTA tile: BQ=128 query rows, streaming K/V in BK=128 chunks; HD=64 fixed (
TILE_HD). - Grid
(T/128, H, B)initially; persistent/static tile scheduler is phase 3. - MMA shapes:
S = Q·Kᵀis M128×N128×K64 — four chained K=16 MMAs, same pattern as gemm'sTC_BK=64loop.O += P·Vis M128×N64×K128. Q stays operand-A resident; V's orientation uses the descriptortranspose_bbit (validated in phase 1 against the oracle before anything else is built on it; fallback is a transposed V staging layout — nearly free since the quantize pass writes the staging buffers anyway). - Causal structure: keep the existing
key_tilesupper bound (never touch fully-masked tiles), and split the key loop into full tiles (no masking branch) plus one diagonal partial tile (masking applied in softmax registers, in base-2 domain, with the existing finiteMASKED_SCOREconvention so row statistics stay NaN-free).
5.2 Memory plan
TMEM (512-column budget; column = 128 lanes × 4 B):
| Buffer | Shape | Columns |
|---|---|---|
| S accumulator | 128×128 f32 | 128 (×2 if double-buffered for MMA/softmax overlap) |
| O segment accumulator | 128×64 f32 | 64 |
One workstream with double-buffered S = 320 cols; two Q workstreams (phase 3 ping-pong) with single-buffered S each = 384. Both fit.
SMEM (dynamic, ~227 KiB ceiling), representative single-workstream budget:
| Buffer | Bytes |
|---|---|
| Q tile (bf16 128×64, swizzled) | 16 KiB |
| K ring, 2–3 stages × 16 KiB | 32–48 KiB |
| V ring, 2–3 stages × 16 KiB | 32–48 KiB |
P tile (bf16 128×128, via stmatrix) |
32 KiB |
| O epilogue staging (fp32 128×64) | 32 KiB |
| mbarrier array + row stats | <1 KiB |
| Total | ~145–177 KiB |
Stage counts, BK, and warp-role ratios are pub const SWEEP knobs per SPEC §10.
Global staging: three packed-bf16 buffers [B·H, T, HD] = N·D·2 B ≈ 96 MiB each at N=32,768 — same scale as the existing 7e9 workspace buffers; reuse that machinery.
5.3 Pipeline and warp roles
Roles connected by SMEM mbarrier rings (phase-parity spin waits; one barrier array indexed by stage — no named barriers needed):
- Load warp: TMA Q once, then K/V ring (2–3 stages ahead),
mbarrier_arrive_expect_txper stage. - MMA warp (single leader thread issues, like gemm): S MMAs into TMEM, then O MMAs consuming the P buffer; signals K/V stages free;
tcgen05_commit→ mbarrier. - Softmax warpgroup(s): drain S TMEM→registers (
tcgen05_ld), apply diagonal mask, update running row max/sum, softwareexp2, pack bf16 pairs,stmatrixP→SMEM; decide whether a correction is needed (§5.4). - Correction/epilogue warpgroup: on correction or at stream end, drain O TMEM segment→registers, rescale-merge into the per-thread fp32 register accumulator (128×64/CTA = 64 regs/thread across a 128-thread group); final
1/rowsumscale; fp32 O + LSE → SMEM → TMA store.
The point of all of it: softmax(tile i) overlaps S-MMA(tile i+1) overlaps TMA(tile i+2), replacing today's five block-wide sync_threads per key tile.
5.4 Numerics
- Base-2 softmax.
scale·log₂efolded into Q at quantize time; scores arrive aslog₂-domain values.2^x= Cody-Waite split (integer part via exponent-bit insertion, fractional part via degree-3 Horner polynomial — 3 FMAs; FA4 shows this matches SFU precision at bf16). No SFU, no libdevice. - LSE:
lse = ln2 · (m₂ + log2(rowsum))with a polynomiallog2; gated by a dedicated parity check against the oracle'smax + ln(sum)before model wiring, since backward consumes it. - Conditional rescaling without
tcgen05.st— the one genuine architectural adaptation. FA4's correction warps rescale O in TMEM; v0.2.1 cannot write TMEM from registers. Instead, O accumulates in a TMEM segment under a fixed max referencem_ref(MMAs useenable_dacross tiles). Softmax warps trigger a correction only when a tile's max exceedsm_refby a safety threshold (the FA4 insight: ~10× rarer than "new max observed"). A correction = drain segment→registers, rescale-merge into the register accumulator, restart the segment (enable_d=falseon the next O MMA). Threshold chosen so bf16 P values stay ≤ ~2⁸ above reference — comfortably inside bf16 range and fp32 accumulation headroom. Phase 1 ships the always-drain-every-tile version first (correctness-identical, simpler); the conditional segments land in phase 3 with the measured correction rate reported.
6. Integration
gpu/flash-attngains the new kernels but they compile into a separate pure-PTXflash.ptx(no libdevice anywhere in that artifact).gpu/modelgets a host-only mirror module (pattern:Tcgen05Gemmingpu/gemm/src/host.rs) with raw launchers + TMA map creation + the dynamic-SMEM attribute opt-in.modal_app.pygrows a_prepare_flash_ptxstep alongside_prepare_gemm_ptx(both mounted-candidate andBASELINE_REFpaths).- Quantize/staging kernel lives with the other conversion kernels; fusing it into the QKV projection epilogue is a recorded follow-up (SPEC §11 explicit-variant rule), not part of this work.
- Index-width audit: launches at B≥128 shapes previously hit u32 ceilings (7e7 landing note) — the staging and epilogue indexing must be checked at the largest intended shape.
7. Phases and gates
Every phase: parity vs both oracles (per-row + fp32 tiled) at T=4, T=80 (partial tiles), T=1024; bf16-appropriate tolerances (7e9 precedent); perf claims only via same-container BASELINE_REF profile (§10.1); bench.rs extended to report TFLOP/s.
Phase 1 — synchronous tcgen05 forward (the long pole)
- fp32→bf16 de-interleave/quantize kernel (Q gets
scale·log₂efolded in), staged workspace buffers -
flash.ptxbuild + host-only launcher module in gpu/model +modal_app.pyplumbing + dynamic-SMEM opt-in helper -
transpose_borientation validation for the V operand against the oracle (fallback: transposed V staging) - software
exp2+log2with standalone accuracy parity tests - gemm-style single-buffered kernel: TMA in → S MMA → SIMT softmax (registers) →
stmatrixP → O MMA → per-tile drain/rescale in registers → fp32 O + LSE out - parity gates + first same-container profile
Phase 2 — pipelining
- K/V TMA rings (2–3 stages) with mbarrier ring plumbing
- S TMEM double-buffer; softmax(i) ∥ MMA(i+1) overlap
- warp specialization (load / MMA / softmax / correction+epilogue roles)
-
__launch_bounds_configregister budgeting; SWEEP stages × BK × role ratios
Phase 3 — softmax-path optimizations
- conditional rescaling segments (report measured correction rate)
- full-tile vs diagonal-tile loop split
- two-Q-tile ping-pong per CTA (budget permitting)
- persistent/static tile scheduler
- model integration + tile-aligned parity config + tiny-overfit gate re-tune if needed (7e7 lesson: attention rounding is load-bearing)
Phase 4 — backward
- keep the three-kernel split (
backward_dot, query-parallel dQ, key-parallel dK/dV) so gradient writes stay disjoint — no atomics - tcgen05 recompute-softmax backward with bf16 operands / fp32 accumulate;
stmatrix_*_trans+ descriptor transpose bits for the transposed stagings - pipeline it (backward is SMEM-bandwidth-bound per the FA4 paper — TMEM staging discipline over MMA shape)
- evaluate fused single-pass backward (FA4 uses TMEM + 2-CTA to kill dQ atomics) only after profiling the split version
Phase 5 — stretch
- 2-CTA MMA (
_cg2) + K/V TMA multicast across cluster pairs - quantize fused into QKV projection epilogue (revisits interleaved-layout TMA, see Bump cuda-oxide pin from v0.2.1 to current upstream main #34 note)
- fp8 P operand
8. Risks
| Risk | Mitigation |
|---|---|
Missing tcgen05.st makes corrections cost a TMEM drain |
Segment-restart design amortizes to ~zero at FA4's measured correction rates; escape hatch = intrinsic via #34's generated-intrinsics path |
| bf16 attention shifts rounding; overfit gate is knife-edged (7e7) | tile-aligned parity config at bf16 tolerances (7e9 playbook); expect gate re-tune; CPU noise-probe methodology already exists |
| exp2/log2 polynomial accuracy in LSE feeds backward | standalone parity gate before model wiring |
| mbarrier pipeline deadlocks/hangs are miserable to debug | phase 2 builds on a working phase-1 kernel; single-stage degenerate config kept as a debug mode; compute-sanitizer wired in modal_app.py |
| SMEM/TMEM budgets force tile-size compromises | budgets in §5.2 have slack; all contested sizes are SWEEP consts |
| u32 index ceilings at large B | explicit audit item in §6 |
9. References
- FA4 paper: FlashAttention-4: Algorithm and Kernel Pipelining Co-Design for Asymmetric Hardware Scaling (arXiv 2603.05451)
- Modal teardown: modal.com/blog/reverse-engineer-flash-attention-4
- In-repo template for every tcgen05/TMA/mbarrier idiom used here:
gpu/gemm/src/lib.rs(gemm_tcgen05_bf16_impl) +gpu/gemm/src/host.rs - Related: Bump cuda-oxide pin from v0.2.1 to current upstream main #34 (cuda-oxide bump;
tcgen05.stfollow-up; interleaved-TMA note)
Activity
Merge pull request #36 from feitreim/feat/issue-35-fa4-fwd-phase1
Merge pull request #37 from feitreim/feat/issue-35-fa4-fwd-phase2
Merge pull request #39 from feitreim/feat/issue-35-fa4-fwd-phase3
Merge pull request #40 from feitreim/feat/issue-35-fa4-bwd-phase4
One flash-attention forward, at 128 query rows