Skip to content

FA4 phase 1: synchronous tcgen05 flash-attention forward (#35) - #36

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

feitreim merged 4 commits into
mainfrom
feat/issue-35-fa4-fwd-phase1

Conversation

@feitreim

Copy link
Copy Markdown
Owner

Phase 1 of #35: the synchronous tcgen05/TMA attention forward, landed standalone in gpu/flash-attn behind the three-tier oracle chain. The model keeps running the fp32 tiled kernels — integration is phase 3.

What's here

New pure-PTX artifact (flash.ptx) — src/bin/flash.rs includes only src/tcgen05.rs, so its device artifact takes the pure-PTX path (binary-target crate name selects the artifact stem, exactly like gemm.ptx). The harness (main.rs) and later gpu/model load it at runtime through the new host-only src/host.rs (Tcgen05Flash, 3D head-panel TMA maps, the >48 KiB dynamic-SMEM opt-in), mirroring Tcgen05Gemm.

flash_forward_tcgen05 — one CTA per 128-query tile of one (batch, head), streaming 128-key tiles synchronously (gemm-style): TMA Q/K/V → S = Q·Kᵀ in fp32 TMEM (M128_N128) → register softmax in the base-2 domain (per-thread fragment ownership decoded from the gemm epilogue, quad-shuffle row stats, finite MASKED_SCORE diagonal masking, software exp2) → bf16 P via swizzle-aware stmatrix into two stacked SWIZZLE_128B subtiles → O = P·V (M128_N64, transpose_b V) → per-tile TMEM drain and rescale-merge into registers (the "always drain" phase-1 form of FA4's conditional correction) → fp32 y[N, H·64] + natural-log LSE. Output contract unchanged.

Software math — exp2 as Cody-Waite split + degree-3 minimax (max rel err 7.5e-5, matches the fitted bound exactly on hardware), log2 as an atanh series (1.9e-7). No libdevice anywhere in the artifact — which is also FA4's SFU-offload optimization.

Staging kernel — stage_attention_heads_bf16 de-interleaves fp32 [B·T, H·64] into packed-bf16 head panels [B·H, T, 64], folding softmax_scale·log2(e) into Q. It lives in lib.rs with the attention kernels rather than tensor-gpu (deviation from the issue's §6 wording): it's attention-specific and this keeps the harness free of the tensor-core/tensor-cpu dependency chain. Gated bit-exactly against a CPU mirror.

Probes as gates — transpose_b_probe validates the transposed V-operand descriptor path and the TMEM fragment decode against CPU before the forward depends on them; swizzle_probe dumps a TMA-loaded tile and verifies the SWIZZLE_128B placement formula empirically.

Gates (B200, same container)

  • per-row + fp32 tiled oracle parity and 200-round bit-stability: unchanged, pass
  • staging kernel vs CPU mirror: bit-exact
  • exp2 7.5e-5 rel / log2 1.9e-7 abs vs libm
  • transpose_b probe 2.9e-6; swizzle probe confirms chunk ^ ((row + phase) & 7)
  • forward vs staged-bf16 CPU reference (T=128/256/512): y ≤ 1.4e-3, LSE ≤ 1.4e-4
  • forward vs both fp32 oracles (T=128/256/1024): y ≤ 2.4e-3, LSE ≤ 8.9e-4 — bf16-operand-quantization dominated, tolerances set at ~4× measured
  • bench at the profile shape (B=32, T=1024, H=24): 1.436 ms, 80.7 TFLOP/s issued-MMA throughput. The fp32 tiled kernels spend 57.5 ms on forward+backward combined at this shape (FA4-shaped flash attention: warp-specialized tcgen05/TMA pipeline (forward first) #35 motivation table), so the synchronous forward alone is roughly an 11× forward speedup before any pipelining. The §10.1 same-container full-step profile applies at phase-3 model integration.

Debugging notes (also in the code comments)

Two toolchain traps worth knowing about:

  • f32::max/min lower to libdevice __nv_fmaxf/__nv_fminf, which silently switches the artifact to NVVM-IR mode (no .ptx emitted; NVVM would reject the tcgen05 ops at load time). The kernels use comparison-select fmax/fmin; _prepare_flash_ptx now fails loudly if flash.ptx is missing after a successful build.
  • The 128B swizzle XORs absolute SMEM address bits [9:7], not tile-relative rows. TMA writes and descriptor reads are self-consistent, but dynamic SMEM starts just past the static barrier words (base row phase 1), so the manual stmatrix swizzle was one phase off — every P row's chunks displaced by (r%8)^((r+1)%8), caught because LSE was perfect while y was wrong. The P write now derives the phase from the base pointer at runtime, and swizzle_probe regression-gates the formula.

cargo oxide build also needed --arch sm_100a (unlike run it doesn't auto-detect, and the oracle binaries' atomics are rejected by legacy NVVM IR).

Phase-1 checklist from #35

  • fp32→bf16 de-interleave/quantize kernel (Q gets scale·log₂e folded in), staged workspace buffers
  • flash.ptx build + host-only launcher module + modal_app.py plumbing + dynamic-SMEM opt-in helper
  • transpose_b orientation validation for the V operand (works — no transposed-staging fallback needed)
  • software exp2 + log2 with standalone accuracy parity tests
  • gemm-style single-buffered kernel
  • parity gates + first profile (standalone kernel bench; full-step profile lands with phase-3 integration)

Next up per the issue: phase 2 (K/V TMA rings, S double-buffer, warp specialization).

feitreim added 4 commits July 18, 2026 20:47
New pure-PTX flash.ptx artifact (src/bin/flash.rs + src/tcgen05.rs), the
gemm.ptx pattern: the harness and model artifacts go through libNVVM
(libdevice oracles), which rejects tcgen05, so the new kernels load from a
separately built PTX at runtime.

- flash_forward_tcgen05: single-buffered TMA + tcgen05 forward. S = Q.K^T
  in fp32 TMEM (M128_N128), register softmax in the base-2 domain (software
  exp2, quad-shuffle row stats, finite masked-score diagonal), bf16 P via
  swizzle-aware stmatrix, O = P.V (M128_N64, transpose_b V), per-tile O
  drain/rescale-merge in registers, fp32 y + natural-log LSE out.
- software exp2 (Cody-Waite + degree-3 minimax, max rel err 7.5e-5) and
  log2 (atanh series), both libdevice-free, with standalone accuracy gates.
- transpose_b_probe: one-CTA GEMM validating the transposed V-operand
  descriptor path and the TMEM fragment decode against CPU before the
  forward depends on both.
- stage_attention_heads_bf16 (lib.rs): fp32 [B*T, H*64] -> packed-bf16
  [B*H, T, 64] head panels, softmax_scale*log2(e) folded into Q.
- host.rs: 3D head-panel TMA maps, launch configs, flash.ptx loader with
  the >48KiB dynamic-smem opt-in (80 KiB plan).
- harness: staging bit-parity vs CPU mirror, tcgen05 forward vs both fp32
  oracles at tile-aligned shapes; flash bin self-tests vs staged-bf16 CPU
  reference and reports TFLOP/s at the profile shape.
- modal_app.py: _prepare_flash_ptx staging alongside _prepare_gemm_ptx.
- f32::max/min lower to libdevice __nv_fmaxf/__nv_fminf in cuda-oxide,
  silently switching the artifact to NVVM IR (which rejects tcgen05 and
  emits no .ptx). Replace with comparison-select fmax/fmin helpers; all
  scores are finite by construction so NaN semantics don't change.
- cargo oxide build doesn't auto-detect the GPU arch like run does, so the
  libdevice oracle binaries fell to legacy NVVM IR, which rejects ops'
  atomic RMW. Pin --arch sm_100a in _prepare_flash_ptx and fail loudly if
  flash.ptx is still missing after a successful build.
- allow(dead_code) on the host module include (not every binary uses it).
The 128B swizzle XORs physical address bits [9:7], not tile-relative rows.
Dynamic shared memory begins just past the static barrier words (base row
phase 1 here), so TMA-written tiles and descriptor reads agreed with each
other but not with the manual stmatrix swizzle, displacing every P row's
chunks by (r%8)^((r+1)%8). Derive the phase from the P base pointer at
runtime and fold it into the XOR.

Adds a swizzle_probe kernel + harness gate that dumps a TMA-loaded tile
with its base phase and verifies the placement formula empirically, plus
per-row y/LSE diagnostics in the forward parity check.

Self-test on B200: swizzle probe and transpose_b probe pass; forward
parity y <= 1.4e-3, LSE <= 1.4e-4 across T=128/256/512; 1.436 ms /
80.7 TFLOP/s at the B=32, T=1024, H=24 profile shape (fp32 tiled baseline:
~57.5 ms forward+backward combined).
Self-test vs staged-bf16 CPU reference: y 5e-3 (measured 1.4e-3), lse
atol 1e-3 (measured 1.4e-4). Harness vs fp32 oracles: y 1e-2 (measured
2.4e-3 at T=1024), lse atol 5e-3 (measured 8.9e-4).
@feitreim
feitreim merged commit 15b877b into main Jul 19, 2026
@feitreim
feitreim deleted the feat/issue-35-fa4-fwd-phase1 branch July 19, 2026 02:09
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