Repository navigation
FA4 phase 1: synchronous tcgen05 flash-attention forward (#35) - #36
Merged
Merged
Conversation
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Phase 1 of #35: the synchronous tcgen05/TMA attention forward, landed standalone in
gpu/flash-attnbehind 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.rsincludes onlysrc/tcgen05.rs, so its device artifact takes the pure-PTX path (binary-target crate name selects the artifact stem, exactly likegemm.ptx). The harness (main.rs) and latergpu/modelload it at runtime through the new host-onlysrc/host.rs(Tcgen05Flash, 3D head-panel TMA maps, the >48 KiB dynamic-SMEM opt-in), mirroringTcgen05Gemm.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, finiteMASKED_SCOREdiagonal masking, softwareexp2) → bf16 P via swizzle-awarestmatrixinto two stacked SWIZZLE_128B subtiles →O = P·V(M128_N64,transpose_bV) → per-tile TMEM drain and rescale-merge into registers (the "always drain" phase-1 form of FA4's conditional correction) → fp32y[N, H·64]+ natural-log LSE. Output contract unchanged.Software math —
exp2as Cody-Waite split + degree-3 minimax (max rel err 7.5e-5, matches the fitted bound exactly on hardware),log2as 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_bf16de-interleaves fp32[B·T, H·64]into packed-bf16 head panels[B·H, T, 64], foldingsoftmax_scale·log2(e)into Q. It lives inlib.rswith 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_probevalidates the transposed V-operand descriptor path and the TMEM fragment decode against CPU before the forward depends on them;swizzle_probedumps a TMA-loaded tile and verifies the SWIZZLE_128B placement formula empirically.Gates (B200, same container)
chunk ^ ((row + phase) & 7)Debugging notes (also in the code comments)
Two toolchain traps worth knowing about:
f32::max/minlower to libdevice__nv_fmaxf/__nv_fminf, which silently switches the artifact to NVVM-IR mode (no.ptxemitted; NVVM would reject the tcgen05 ops at load time). The kernels use comparison-selectfmax/fmin;_prepare_flash_ptxnow fails loudly ifflash.ptxis missing after a successful build.stmatrixswizzle 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, andswizzle_proberegression-gates the formula.cargo oxide buildalso needed--arch sm_100a(unlikerunit doesn't auto-detect, and the oracle binaries' atomics are rejected by legacy NVVM IR).Phase-1 checklist from #35
scale·log₂efolded in), staged workspace buffersflash.ptxbuild + host-only launcher module +modal_app.pyplumbing + dynamic-SMEM opt-in helpertranspose_borientation validation for the V operand (works — no transposed-staging fallback needed)exp2+log2with standalone accuracy parity testsNext up per the issue: phase 2 (K/V TMA rings, S double-buffer, warp specialization).