Recover FA2, then construct a fresh Hopper program
flash-attention-resynth normalizes an admitted FA2 function, recovers its
arithmetic, constructs a complete logical attention program, transforms its
loop and work mapping, and lowers a fresh selected kernel body. The current
normalization uses independently constructed instruction forms. The pinned
FA3 file supplies the publication ABI container; its selected instruction
body is replaced completely.
The built-in example includes the exact noncausal input and output from the accepted October 14 study. No upload is needed. Its comparison uses the experimental browser lifter to inspect the two binaries. The native compiler IR and generation receipt are separate artifacts from the actual native pass. The browser does not execute the native transformation or GPU code.
Arithmetic witnesses and reviewed program facts
recover_flash_attention checks the complete instructions and metadata of
two reviewed FP16 D64 SM90 source programs, allowing supported parameter
relocation. The reference must match the full pinned SM90a ABI-image hash.
An attention-like name or compatible-looking function signature is insufficient.
The HGMMA normalization stage constructs its own instruction forms, then
attention_semantic_recover follows actual SSA dependencies for matrix
endpoints and online maximum, exponentiation, denominator, FP16 probability
packing and output rescaling. Changed or unexplained arithmetic refuses.
Mask, iteration and epilogue construction additionally depend on the admitted
reviewed program profile. The IR explicitly labels that boundary
reviewed-program-profile-not-dynamic-ssa-proof.
Recovery is tied to the reviewed source program and its recorded numerical policy. Retiling changes rounding and reduction structure. FTZ, approximate exponent/reciprocal behavior, FMA and empty-state handling remain explicit obligations; the browser’s structural comparison does not establish numerical equivalence or a broader runtime contract.
Follow the code from equations to an image
The orchestration is mlrw_attention_program in dialect/lib/SassPasses.cpp.
The implementations below live in passes/flash-attn-resynth/mlir/:
| Stage | Implementation | Result and contract |
|---|---|---|
| Recover | attention_semantic.cpp, attention_semantic_ir.cpp | Bind source arithmetic to SSA witnesses and express the recovered equations in vector/arith/math IR. |
| Construct | attention_program.cpp | Build Q/K/V reads, descending key tiles, masking, online softmax, PV and O/LSE stores over fresh tensor arguments. |
| Overlap | attention_program_overlap.cpp | Rewrite the loop into a prologue, carried state and final drain: current QK precedes previous PV, which finishes before the current online update rescales its output. |
| Map work | attention_program_schedule.cpp | Construct persistent ticket iteration and plan three M64 math groups, one producer group, two K stages and two V stages. |
| Lower | attention_program_lower.cpp and the producer/consumer/transfer lowerings | Emit physical TMA, HGMMA, scalar fragments, addresses, barriers and epilogue. |
| Schedule and allocate | attention_program_controls.cpp, attention_program_allocate.cpp | Assign ordinary completion controls and registers; check complete matrix groups, physical conflicts and outstanding accesses. |
| Publish | attention_program_publish.cpp, attention_program_image.cpp | Recheck the physical protocol, finalize a selected function, require every word to be regenerated and rebuild its ELF resources/metadata in the pinned ABI container. |
A good pass keeps these contracts separate. Logical QK/PV overlap does not prove that emitted matrix operations complete before register or shared-memory reuse. Persistent work assignment must cover each tile exactly once and keep producer/consumer tickets consistent. TMA needs correct descriptors, transaction sizes, stage generations and releases. Ordinary scoreboard waits, asynchronous matrix completion and shared-stage ownership each require their own checks. Structural changes invalidate allocation and scheduling; the lowering and publication paths rerun the required checks before emitting an image.
Instruction normalization is followed by whole-body regeneration
The early normalizer converts the original N128 matrix windows: QK uses
four HGMMA.64x128x16.F32 operations per M64 source half; PV uses eight
HGMMA.64x64x16.F32 operations per M64 source half for the N128 reduction
(two M64 halves in the source window). It constructs
these forms independently and refuses if any source HMMA remains.
The final noncausal program then uses N192. One logical M64×N192×D64 QK contraction needs four K16 issues; one M64×N192 by N192×D64 PV contraction needs twelve. Thread roles, descriptors, registers and instruction addresses change with that reconstruction. The following are actual representative regions of the two bundled functions, not replacements at matching PCs:
// Original FA2 matrix region
/*1180*/ LDSM.16.M88.4 R12, [R3+0x4000];
/*11a0*/ LDSM.16.M88.4 R4, [R234+0x2000];
/*1230*/ HMMA.16816.F32 R56, R4.reuse, R12, RZ;
// Fresh program: one complete QK contraction
/*0b20*/ WARPGROUP.ARRIVE;
/*0b30*/ HGMMA.64x192x16.F32 R24, gdesc[UR32], RZ, !UPT;
/*0b40*/ HGMMA.64x192x16.F32 R24, gdesc[UR36], R24;
/*0b50*/ HGMMA.64x192x16.F32 R24, gdesc[UR40], R24;
/*0b60*/ HGMMA.64x192x16.F32 R24, gdesc[UR44], R24, gsb0;
/*0b70*/ WARPGROUP.DEPBAR.LE gsb0, 0x0;The instruction excerpts also include source transport, the generated TMA transaction, probability packing/publication and the recurrent PV sequence, with exact function PCs.
Why previous PV must finish before the current rescale
For processing step t, use A for the unnormalized output and m for the
unscaled row maximum. Actual key-tile indices descend. The base-two scale is
λ = fp32(0.125 × log2(e)):
S_t = Q × K_tᵀ // masked invalid scores → −∞
m_t = max(m_previous, rowmax(S_t))
p_t = 2^(S_t × λ − m_t × λ)
α_t = 2^((m_previous − m_t) × λ)
l_t = α_t × l_previous + rowsum(p_t)
P_t = fp16(p_t)
A_t = α_t × A_previous + P_t × V_tThe denominator reduces the FP32 weights; PV consumes their FP16 rounding. The readable equations omit explicit FTZ/FMA and empty-state guards that are retained in the emitted IR. The final epilogue uses a guarded reciprocal for O and computes LSE from the unscaled maximum and denominator.
The transformed carry is (m, l, B, P_pending, V_pending), where
B_t = α_t × A_previous is the output seed before tile t is accumulated.
QK for the next tile does not consume that seed, so it can run first.
Previous PV then completes A_previous; the current online update must use
that completed result before forming its next rescaled seed. A final PV
outside the loop drains the last pending tile, even if the recurrent loop
has no iterations.
The decisive bundled IR lines are 629 (current QK), 646 (previous PV), and 647 (the recurrent online call consuming the result of line 646). Lines 671 and 673 show the five-value carry and final drain. This is a dependency rewrite of a logical program, not a proof that a particular hardware wait can be removed.
Data arrival, matrix completion and ownership are separate
The CTA reserves four 128-thread warpgroups. TIDs 0–31 execute the producer;
TIDs 32–127 exit after register deallocation. TIDs 128–511 are three math
groups, each covering 64 rows. The noncausal work ticket starts at CTAID.X,
advances by grid.x, and decodes into batch, head and one M192 query tile.
The K/V slot cursor and stage generations continue across query tickets.
They are different state from that work ticket.
Each K/V stage has a ready barrier initialized to count 1 and an empty
barrier initialized to count 3. The producer waits for ownership, declares
exactly 0x6000 (24,576) expected bytes and issues UTMALDG.4D. Consumers
must establish the matching ready epoch before reading. One leader per
math group releases the stage only after its relevant HGMMA reads retire.
In the recurrent overlap path, the current QK batch is older than previous
PV. A gsb0, 0x1 wait can retire QK and expose an independent maximum
prefix while PV remains in flight. A gsb0, 0x0 wait then retires PV before
its result is consumed, V is released or shared P is overwritten. Compact
wait cleanup needs the matching CFG proof. Ordinary scoreboard controls
cannot prove those matrix and ownership obligations.
Q has its own handoff: named barrier 10 with 416 participants (384 math + 32 producer threads). Math hands Q back after its final QK; final PV and output use separate P/V/O storage. Applying the K/V empty-barrier cycle to this Q path would describe the wrong program.
Inspect the program, then publish the image
Choose one admitted source section. SOURCE_SYMBOL is its full symbol from
inspect; fa3.cubin stands for the pinned ABI container.
build/sass-mlir inspect original.cubin
build/sass-mlir optimize original.cubin \
--passes flash-attention-program --reference fa3.cubin \
--kernel SOURCE_SYMBOL --out attention.mlir
build/sass-mlir research parse-check attention.mlirflash-attention-program runs the source-program construction through physical
lowering. Its diagnostic module retains logical functions and unfinished
publication markers. It has no launch contract; lower refuses to treat it
as a runnable kernel. Publication uses the exclusive image pass:
build/sass-mlir optimize original.cubin \
--passes flash-attention-resynth --reference fa3.cubin \
--kernel SOURCE_SYMBOL --out converted.cubinThe interface alone does not reproduce an experimental schedule. The bundled
receipt pins the measured
compiler and input/output hashes, and records completion=dependencies,
pipeline=overlap, transport=prefetch, mapping=persistent,
scalar=batched, mask=columns and mma_waits=compact policies.
The published image is accompanied by converted.cubin.launch.json.
The sidecar is part of the result
The hash-bound sidecar describes lowering=source-program, both image hashes,
typed parameters, work mapping, 512-thread blocks and mask-specific shared
memory. The supported adapter prepares tensor maps and parameter bindings.
These are the publication contracts for the measured images; resource sizes belong to these exact images:
| Mask | Tile | P storage | Selected words | Dynamic shared memory | Work assignment |
|---|---|---|---|---|---|
| Causal | M192 × N128 | Registers | 2,234 | 115,712 bytes | Dynamic queue; reset counter before every invocation. |
| Noncausal | M192 × N192 | Shared | 1,929 | 222,208 bytes | Static persistent tickets. |
The bundled noncausal source has 3,112 instruction words. Its output has 1,929 fresh words and a 2,944-byte target parameter layout. The full cubins contain other functions; the example selects only the exact symbols in its manifest.
The causal counter reset belongs inside a captured complete invocation too. Replacing a cubin alone cannot adapt FA2’s parameter buffer, block size or shared-memory request. Use the supported adapter and its exact bound sidecar.
What the measured program establishes
The accepted study crosses B=1/2/4, H=8, D=64, nine power-of-two lengths S=128–32,768, both masks and native/complete-invocation CUDA Graph submission: 108 cells on H100 NVL. Each cell averages three balanced process means, each with 128 warmups and 1,024 timed complete invocations.
| Submission | Mask | FA2/generated latency ratio | FA3/generated latency ratio |
|---|---|---|---|
| Native | Causal | 1.3223× | 0.9668× |
| Native | Noncausal | 1.1223× | 0.9775× |
| Graph | Causal | 1.3344× | 0.9707× |
| Graph | Noncausal | 1.1199× | 0.9778× |
For a concrete workload, the retained raw times at B1/H8/S4096/D64 are:
| Submission | Mask | Original FA2 (µs) | Rebuilt pass (µs) | Native FA3 (µs) |
|---|---|---|---|---|
| Native | Causal | 134.248 | 62.165 | 61.088 |
| Native | Noncausal | 142.722 | 132.847 | 125.674 |
| CUDA Graph | Causal | 133.606 | 61.557 | 60.825 |
| CUDA Graph | Noncausal | 142.832 | 131.491 | 124.701 |
These are complete-invocation means, not sums of workload cells. The Encoding Lab bundles the noncausal image; causal rows describe the separately measured causal image. Download all 108 timing cells, including unrounded means and each process mean in milliseconds. The table above converts those values to microseconds.
Across equally weighted cells the geometric means are 1.220× FA2 throughput and 97.32% of FA3 throughput: 18.06% lower latency than FA2 and 2.75% higher than FA3. 32 cells are slower than FA2; 90 are slower than FA3. Native and graph measurements remain separate; these are descriptive ratios, not statistical-significance claims.
The retained verification accepts 432 numerical validations and 1,296 gates
across ordinary execution, memcheck and synccheck. This covers recorded inputs,
not every finite FP16 value; finite extreme-input counterexamples remain.
Full Nsight profiling is not accepted: a causal B1/H8/S4096/D64 application
passed replay 1 numerics but raised CUDA_ERROR_ILLEGAL_INSTRUCTION on replay 2.
Only 25 of 162 captures completed; the cause remains unresolved. Accepted
ordinary timing and sanitizer evidence does not resolve that profiling fault.
The October 14 full measurement record and corresponding paper evidence retain the complete case data and audit witnesses. The earlier study and older donor or retained-scaffold results remain historical evidence for their own images. These results do not validate arbitrary current builds or other fixtures.
Use the pass tutorial to develop a smaller transformation with explicit admission and refusal cases first.