From FlashAttention-2 to FlashAttention-3: TMA, WGMMA, Warp Specialization, and FP8 on Hopper
A source-level explanation of how FlashAttention-3 turns FlashAttention-2 into a Hopper-native asynchronous kernel using TMA, WGMMA, warp-specialized pipelines, GEMM-softmax overlap, and FP8 layout transforms.
FlashAttention-2 established the modern work partition for exact attention: one CTA owns a Q tile, streams K/V tiles, updates online softmax state, and stores the output without materializing the quadratic score matrix. FlashAttention-3 keeps that algorithmic invariant but changes the schedule to match NVIDIA Hopper.
The key difference is asynchrony. Hopper provides:
- TMA, a Tensor Memory Accelerator that moves multidimensional tiles between HBM and shared memory;
- WGMMA, asynchronous Tensor Core matrix multiplication issued by a four-warp warpgroup; and
- named barriers and register reallocation that make producer/consumer warp specialization practical.
This post connects the FlashAttention-3 paper to the open-source Hopper implementation. All source links are pinned to Dao-AILab/flash-attention@b038b49.
1. What remains unchanged from FA2
For a Q tile and a sequence of K/V tiles, both FA2 and FA3 maintain:
\[m_j = \max(m_{j-1}, \operatorname{rowmax}(S_j)),\] \[\ell_j = e^{m_{j-1}-m_j}\ell_{j-1} + \operatorname{rowsum}(e^{S_j-m_j}),\] \[O_j = e^{m_{j-1}-m_j}O_{j-1} + e^{S_j-m_j}V_j.\]The final output is $O = O_T / \ell_T$. Score and probability tiles remain temporary on-chip values; the quadratic attention matrix is never written to HBM.
FA3 does not replace this recurrence. It reorganizes data movement, Tensor Core issue, and scalar score processing so that Hopper’s independent engines remain busy at the same time.
2. FA2 versus FA3 in one picture
FA2 already minimizes HBM traffic, but each warp still follows a relatively tight dependency chain: load a tile, compute QK, update softmax, and compute PV. FA3 breaks that chain into work for three hardware resources:
- TMA moves future tiles;
- Tensor Cores execute asynchronously queued matrix multiplications; and
- CUDA cores and SFUs update online-softmax state.
The optimization target is therefore temporal overlap. The mathematical result stays exact.
3. Hopper-native WGMMA
Ampere tensor-core instructions are issued by one warp and consume register-resident fragments. Hopper WGMMA is issued collectively by a four-warp, 128-thread warpgroup and can consume operands through shared-memory descriptors.
For QK, FA3 normally lets WGMMA read both Q and K from shared memory. For PV, the probability fragment can remain in registers while V is read from shared memory. In both cases, FP32 accumulators remain distributed across the warpgroup’s registers.
This removes an explicit shared-to-register Q load from the normal path and avoids keeping a large Q fragment live in every consumer warpgroup. It does not make shared-memory bandwidth free: swizzled layouts, alignment, and bank conflict avoidance still determine whether WGMMA can consume operands at full rate.
4. TMA and producer/consumer specialization
TMA turns a regular multidimensional transfer into a bulk asynchronous operation. One elected producer lane can describe a whole Q, K, or V tile, associate it with a transaction barrier, and let the TMA engine populate shared memory.
The CTA is divided into two roles:
- a producer slot owns tile movement and shared-memory pipeline state; and
- consumer warpgroups own WGMMA issue, online softmax, and output accumulation.
In the regular all-TMA path, the CTA still reserves a warpgroup-aligned producer slot so consumer warpgroups start on 128-thread boundaries. Only one producer warp remains active, and one elected lane issues each TMA transfer. All 128 producer threads participate only when the kernel needs software copies or transforms, such as packed-GQA Q gathering, non-TMA paged KV, or an FP8 V transpose.
K and V are not loaded in their entirety. For each scheduled Q tile, the producer streams the legal K/V blocks through a small circular set of shared-memory stages. A stage cannot be overwritten until its consumers release it.
5. Inter- and intra-warpgroup overlap
TMA overlap hides memory latency, but attention also alternates short Tensor Core bursts with reductions and exponentials. FA3 combines two schedules.
Intra-warpgroup overlap issues QK for block $j$ and PV for the previously prepared block $j+1$ before processing the score epilogue for $j$. Already issued WGMMA can execute while that same warpgroup updates softmax state.
Inter-warpgroup ping-pong lets another consumer warpgroup issue its QK/PV pair while the first warpgroup is occupied by scalar score processing. A named-barrier token controls issue order; the token is handed over after WGMMA issue, not after all Tensor Core work completes.
Each consumer warpgroup owns a different subset of the CTA’s Q rows and reads the same staged K/V blocks. Because the kernel traverses K/V blocks from right to left, $j+1$ denotes the block processed immediately before $j$.
Side note: why not use only intra-warpgroup overlap?
One warpgroup has one sequential instruction stream. While its threads run masking, reductions, exponentials, and rescaling, they cannot also issue another instruction.
Issuing QK for another future block first would keep an additional score accumulator and pipeline stage live, increasing register pressure and potentially reducing occupancy. Ping-pong instead gives the next issue opportunity to another warpgroup. Intra-warpgroup scheduling overlaps already-issued WGMMA with scalar work; ping-pong keeps supplying new WGMMA during that scalar work.
6. The complete online-softmax state transition
The region often labeled “softmax” contains much more than exponentiation. For every score block, FA3 must:
- apply masking;
- find the new per-row maximum;
- compute the scale that moves old state into the new maximum’s basis;
- rescale the previous row sum and output numerator;
- exponentiate the current score tile;
- accumulate its row sum;
- convert and arrange probabilities for PV; and
- eventually normalize O and construct LSE.
Two placements of output rescaling are legal. The kernel may rescale the existing O accumulator before adding the next PV result, or add a PV result that is still in the old basis and then rescale the combined accumulator. Both schedules preserve the same invariant as long as the two terms share a normalization basis at addition time.
The final cross-lane row-sum reduction produces:
\[\operatorname{LSE} = m + \log(\ell), \qquad \operatorname{output} = O / \ell.\]7. Persistent scheduling
A logical attention workload contains Q tiles across sequence blocks, heads, batches, and optional splits. FA3 does not need to launch one physical CTA for every logical tile. On the normal Hopper path it launches approximately one CTA per available SM and lets each persistent CTA request more work.
For uniform non-causal work, each CTA walks a deterministic grid-strided list of flattened Q tiles. For causal or local attention, later Q blocks generally process more K/V blocks than earlier ones. A dynamic scheduler therefore uses a global counter, longest-processing-time-first ordering, and L2-aware swizzling to improve load balance and K/V locality.
The scheduler chooses only the Q-side coordinate: Q block, head, batch, and split. The mainloop then derives the legal K/V range and streams those K/V tiles through shared memory.
8. FP8: layout repair and fused scaling
H100 offers much higher FP8 matrix throughput, but FP8 attention is not merely a datatype substitution.
The V operand must use a legal K-major WGMMA layout. If V arrives row-major, the producer performs an in-kernel shared-memory transpose before consumers use it. The FP32 QK accumulator also has a different register organization from the FP8 matrix-A operand expected by PV, so FA3 permutes and converts the probability fragment.
Scaling is fused into the attention recurrence. Q and K descales modify the score scale, while the V descale is folded into final output normalization. This avoids separate full-tensor passes.
The FA3 paper additionally proposes block quantization and randomized Hadamard transforms to spread outliers. The pinned open-source Hopper kernel demonstrates FP8 WGMMA, descales, register permutations, and V layout repair, but it does not integrate that Hadamard transform into the attention kernel.
9. Performance and the correct interpretation
The FA3 paper reports, on H100:
- 1.5-2.0x forward speedup over FA2 for FP16;
- up to 740 TFLOP/s for FP16, about 75% of H100’s theoretical maximum;
- close to 1.2 PFLOP/s for FP8; and
- 2.6x lower numerical error than baseline FP8 attention in the paper’s outlier experiment when block quantization and incoherent processing are applied.
These are the paper authors’ measurements, not benchmarks reproduced for this article. Performance depends on sequence length, head dimension, masking, datatype, GPU clocks, and the exact library revision.
10. Takeaways
FlashAttention-3 is not a new softmax identity. It is a Hopper-native schedule for the same exact tiled-attention recurrence:
- TMA moves future Q/K/V tiles with little issuing-thread overhead.
- WGMMA consumes shared-memory descriptors and executes asynchronously.
- Producer/consumer specialization separates movement from computation.
- Ping-pong warpgroups keep supplying Tensor Core work during scalar phases.
- Intra-warpgroup pipelining overlaps adjacent QK, PV, and score work.
- Persistent scheduling balances logical Q tiles across resident CTAs.
- FP8 requires explicit scaling, operand-layout repair, and conversion.
FA2’s central insight was to make attention IO-aware. FA3’s central insight is to make that IO-aware algorithm asynchrony-aware.
Appendix A: reading the Hopper forward path and its optimizations top to bottom
This appendix follows one ordinary fixed-length forward call through the source. The goal is not to enumerate every template branch, but to provide a stable route through the code that can be followed in an editor. Each optimization is introduced where its controlling type, branch, or instruction first appears in that route.
Snippets are shortened source excerpts: surrounding template qualifiers and unrelated branches may be elided, with pinned links provided for the complete context.
A.1 Fix one concrete configuration
Assume:
1
2
3
4
5
6
7
8
9
10
11
12
q, k, v: [batch, 384, heads, 128]
dtype: torch.bfloat16
GPU: H100 / SM90
flash_attn_func(
q, k, v,
causal=False,
window_size=(-1, -1),
num_splits=1,
pack_gqa=False,
softcap=0.0,
)
Also assume:
1
2
3
4
5
6
Q heads == KV heads
Q/K/V head dimensions are all 128
no variable-length metadata
no page table or KV cache append
no extra Qv tensor
row-major V
For this configuration, the important compile-time choices are:
1
2
3
4
5
6
7
8
9
10
11
12
Arch = 90
Element = cutlass::bfloat16_t
kHeadDim = 128
kHeadDimV = 128
Is_causal/local = false / false
Varlen = false
Split = false
PackGQA = false
PagedKVNonTMA = false
AppendKV / HasQv = false / false
V_colmajor = false
ClusterM = 1 for this three-Q-tile example
The SM90 tile selector returns:
1
2
return {128, 176, true, true};
// M N PV-RS intra-WG overlap
Source: tile_size.h, lines 10-45.
The complete call path is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
flash_attn_func
-> FlashAttnFunc.forward
-> _flash_attn_forward
-> torch.ops.flash_attn_3.fwd
-> boxed_mha_fwd
-> mha_fwd
-> run_mha_fwd
-> run_mha_fwd_constexpr
-> run_mha_fwd_<90, bf16, 128, 128, ...>
-> run_flash_fwd
-> device_kernel<FlashAttnFwdSm90>
-> FlashAttnFwdSm90::operator()
producer WG -> mainloop.load
consumer WGs -> mainloop.mma
consumer WGs -> epilogue.store
A.2 Python entry point
Start at flash_attn_func. It is a convenience wrapper around the autograd function:
1
2
3
4
5
6
return FlashAttnFunc.apply(
q, k, v,
softmax_scale,
causal,
...
)
Next open FlashAttnFunc.forward, lines 552-600. It supplies the default scale:
1
softmax_scale = q.shape[-1] ** (-0.5)
and makes the normal fixed-length call by passing None for:
1
2
3
4
k_new / v_new
cu_seqlens_q / cu_seqlens_k
page_table
rotary tensors
That distinction is important: the same lower-level API implements fixed length, varlen, paged KV, append-KV, and several other modes. The ordinary path is selected mostly by which optional pointers remain null.
A.3 Python custom op to the C++ extension
FlashAttnFunc.forward calls _flash_attn_forward, lines 60-151.
This wrapper:
- makes required tensors contiguous;
- calls
flash_attn_3_gpu.fwd; - converts optional accumulation outputs into empty tensors when unused; and
- returns
outandsoftmax_lse.
1
2
3
out, softmax_lse, out_accum, softmax_lse_accum = (
flash_attn_3_gpu.fwd(...)
)
On newer PyTorch builds, flash_attn_3_gpu is:
1
torch.ops.flash_attn_3
The build chooses flash_api_stable.cpp for newer PyTorch and flash_api.cpp otherwise. This appendix follows the stable API; the kernel path after argument unpacking is the same.
The operator schema is registered at flash_api_stable.cpp, lines 1896-1953. Its boxed adapter unpacks the operator stack and calls mha_fwd:
1
2
auto [out, lse, out_accum, lse_accum] =
mha_fwd(q, k, v, ...);
Source: boxed_mha_fwd, lines 1758-1805.
A.4 mha_fwd: validate tensors and construct runtime parameters
mha_fwd, lines 742-990 is the large runtime-validation layer. Read it in this order:
- validate GPU architecture and Q/K/V dtype;
- require contiguous head dimensions;
- determine fixed versus variable-length shapes;
- validate head-count divisibility;
- canonicalize causal/window arguments;
- allocate
outand FP32softmax_lse; and - populate
Flash_fwd_params.
For the normal path:
1
2
3
4
5
is_varlen_q = false;
is_varlen_k = false;
paged_KV = false;
head_size = 128;
head_size_v = 128;
set_params_fprop records pointers, strides, dimensions, the softmax scale, masking configuration, and device properties in Flash_fwd_params. The final launch occurs at:
1
run_mha_fwd(params, stream);
Source: flash_api_stable.cpp, lines 962-1244.
A useful debugging boundary is:
1
2
Above run_mha_fwd: runtime tensor validation and parameter packing
Below run_mha_fwd: compile-time kernel dispatch and device execution
A.5 Runtime flags become template parameters
run_mha_fwd, lines 432-450 turns runtime booleans into template constants:
1
2
3
4
5
ARCH_SWITCH(...)
SPLIT_SWITCH(...)
PAGEDKV_SWITCH(...)
PACKGQA_SWITCH(...)
SOFTCAP_SWITCH(...)
For the chosen configuration this becomes conceptually:
1
2
3
4
5
6
7
run_mha_fwd_constexpr<
90, // Arch
false, // Split
false, // PagedKVNonTMA
false, // PackGQA
false // Has_softcap
>(params, stream);
run_mha_fwd_constexpr then dispatches dtype and rounded head dimension:
1
2
3
4
5
6
7
run_mha_fwd_<
90,
cutlass::bfloat16_t,
128,
128,
false, false, false, false
>(params, stream);
Source: flash_api_stable.cpp, lines 321-430.
These explicit instantiations are generated from generate_kernels.py, lines 30-48 to keep compilation parallel and avoid instantiating every combination in one translation unit.
A.6 Final feature switches and tile selection
Open run_mha_fwd_, lines 202-220. It resolves the remaining feature switches:
1
2
3
4
5
6
causal versus local
V row-major versus column-major
fixed length versus varlen
extra Qv
append KV
one-CTA versus two-CTA cluster
For the concrete example, it calls:
1
2
3
4
5
6
7
8
run_flash_fwd<
90, 128, 128, 1,
cutlass::bfloat16_t,
cutlass::bfloat16_t,
false, false, false, false,
false, false, false, false,
false, false
>(params, stream);
Do not try to memorize this positional template list. Read the declaration immediately above it and annotate the values in an editor.
A.7 run_flash_fwd: assemble the kernel type
run_flash_fwd, lines 31-81 is the kernel type factory.
For this example:
1
2
3
4
5
TileShape_MNK = (128, 176, 128) # QK
TileShape_MNK_PV = (128, 128, 176) # PV
kStages = 2
MmaPV_is_RS = true
IntraWGOverlap = true
It combines three major types:
1
2
3
CollectiveMainloopFwdSm90<...>
CollectiveEpilogueFwd<...>
StaticPersistentTileScheduler<...>
into:
1
2
3
4
FlashAttnFwdSm90<
CollectiveMainloop,
CollectiveEpilogue,
Scheduler>
The same function also:
- converts raw pointers and strides into typed CuTe arguments;
- constructs scheduler arguments;
- converts them into device-side kernel parameters;
- asks the kernel for grid/block/shared-memory sizes; and
- launches
cutlass::device_kernel<AttnKernel>.
Source: flash_fwd_launch_template.h, lines 82-199.
A.8 Understand the persistent scheduler before the kernel
Optimization: persistent Q-tile scheduling
The launch layer chooses among variable-length, static, and dynamic persistent schedulers:
1
2
3
4
5
6
7
using SchedulerPersistent = std::conditional_t<
Varlen,
VarlenDynamicPersistentTileScheduler<...>,
std::conditional_t<
!Is_causal && !Is_local,
StaticPersistentTileScheduler<Split>,
DynamicPersistentTileScheduler<...>>>;
Source: flash_fwd_launch_template.h, lines 60-76.
For non-causal, non-local SM90 without splits, the selected scheduler is StaticPersistentTileScheduler.
The launch grid contains approximately one CTA per usable SM:
1
2
3
get_grid_shape(...) {
return {num_sm};
}
Each resident CTA repeatedly advances through logical attention tiles with a grid-sized stride:
1
2
3
4
5
6
7
8
9
WorkTileInfo get_initial_work(...) const {
return {int(blockIdx.x)};
}
WorkTileInfo get_next_work(
Params const&,
WorkTileInfo const& current) const {
return {current.tile_idx + int(gridDim.x)};
}
Source: tile_scheduler.hpp, lines 192-212.
get_block_coord converts one linear tile index into:
1
(m_block, attention_head, batch, split_idx)
This is why one physical CTA can process multiple Q tiles over its lifetime. The scheduler decides which Q tile to process; the mainloop decides how that tile streams through K/V.
For causal or local attention, the dynamic scheduler instead obtains work through a global counter before applying its ordering and swizzle:
1
2
3
current_work.tile_idx =
atomicAdd(params.tile_count_semaphore, 1)
+ int(gridDim.x);
Source: tile_scheduler.hpp, lines 334-360.
A.9 Enter the device kernel and split producer from consumers
The CUDA entry body is FlashAttnFwdSm90::operator(), lines 170-451.
The kernel contains:
1
2
one load warpgroup
one to three MMA warpgroups
Source: flash_fwd_kernel_sm90.h, lines 62-79.
For the normal TMA path, only the first warp of the producer warpgroup needs to issue most transfers, but reserving a warpgroup keeps role assignment and register reallocation simple.
Optimization: one active producer warp for regular TMA
The mainloop keeps a full producer warpgroup only for paths that need software copies or transformations:
1
2
3
4
static constexpr int NumProducerThreads =
!Transpose_V && Use_TMA_KV && Use_TMA_Q
? cutlass::NumThreadsPerWarp
: cutlass::NumThreadsPerWarpGroup;
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 117-123.
The source numbering differs from the conceptual diagram earlier:
1
2
3
source warp_group_idx == 0: producer warpgroup
source warp_group_idx > 0: consumer MMA warpgroups
diagram WG0 / WG1: the two consumer warpgroups
After pipeline/barrier initialization, the branch is explicit:
1
2
3
4
5
6
7
8
if (warp_group_idx == 0) {
// Producer
mainloop.load(...);
} else {
// Consumer
mainloop.mma(...);
epilogue.store(...);
}
The producer gives registers back:
1
warpgroup_reg_dealloc<LoadRegisterRequirement>();
while consumers request more:
1
warpgroup_reg_alloc<MmaRegisterRequirement>();
This is Hopper’s dynamic register redistribution in the actual kernel.
A.10 Producer path: construct tiles and issue TMA
The producer calls CollectiveMainloopFwdSm90::load, lines 591-925.
Read this function in five pieces:
- calculate legal K/V block bounds for the current Q tile;
- construct shared-memory Q/K/V tensors and layouts;
- construct global-memory TMA tensor views;
- partition global and shared tensors into TMA source/destination views; and
- run the descending K/V pipeline.
The actual K transfer is:
1
2
3
4
5
6
7
pipeline_k.producer_acquire(stage);
copy(
params.tma_load_K.with(
*pipeline_k.producer_get_barrier(stage),
mcast_mask_kv),
global_K_tile,
shared_K_stage);
V follows the same pattern: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 749-772.
This is the TMA optimization in its operational form: one elected lane binds an entire multidimensional transfer to the transaction barrier for the destination stage. The consumers wait on pipeline state rather than issuing per-thread address calculations and copies.
Q is loaded once per work tile through its own transaction barrier:
1
2
barrier_Q.arrive_and_expect_tx(TmaTransactionBytesQ);
copy(params.tma_load_Q.with(barrier_Q, ...), gQ, sQ);
The producer starts at:
1
int n_block = n_block_max - 1;
and walks toward smaller K/V block indices. As discussed earlier, this handles the right-edge mask first; causal configurations also handle their masked frontier before reaching the simpler fully valid blocks.
Optimization branch: repair row-major FP8 V in the producer
The concrete configuration is BF16, so it skips this branch. For FP8, row-major V is not directly legal for the selected WGMMA operand mode:
1
2
3
4
5
6
7
static constexpr bool Transpose_V =
Is_FP8 && !V_colmajor;
static constexpr GMMA::Major MmaMajorV =
!Is_FP8 && !V_colmajor
? GMMA::Major::MN
: GMMA::Major::K;
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 44-66.
The producer performs the byte-level shared-memory transpose at lines 720-742.
A.11 Consumer path: build WGMMA fragments
The consumer calls CollectiveMainloopFwdSm90::mma, lines 983-1390.
Optimization: WGMMA operand modes
The collective selects shared/shared QK and a register/shared PV operation:
1
2
3
4
5
6
7
8
9
10
using TiledMmaQK = decltype(cute::make_tiled_mma(
cute::GMMA::ss_op_selector<
Element, Element, ElementAccum, TileShape_MNK>(),
AtomLayoutQK{}));
using TiledMmaPV_RS = decltype(cute::make_tiled_mma(
cute::GMMA::rs_op_selector<
Element, Element, ElementAccum,
TileShape_MNK_PV, GMMA::Major::K, MmaMajorV>(),
AtomLayoutPV{}));
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 88-116.
The explicit Q shared-to-register path is disabled:
1
2
3
// Register bandwidth is actually a bottleneck
// so we don't want Q to be in registers.
static constexpr bool MmaQK_is_RS = false;
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 79-96.
The function first maps shared-memory tensors into warpgroup WGMMA fragments:
1
2
3
Tensor tSrQ = wg_mma_qk.partition_fragment_A(sQ);
Tensor tSrK = wg_mma_qk.partition_fragment_B(sK);
Tensor tOrV = wg_mma_pv.partition_fragment_B(sV);
It also allocates:
1
2
3
tSrS: FP32 QK score accumulator
tOrP: converted probability operand for PV
tOrO: FP32 output accumulator
The Q transaction barrier ensures Q is visible before WGMMA reads it:
1
barrier_Q.wait(work_idx % 2);
At this point, the templates and layouts are mostly resolved. The remaining code resembles the algorithm:
1
2
3
4
5
6
wait for K stage
QK WGMMA
mask and online softmax
convert scores to P
PV WGMMA
repeat
A.12 Prologue, steady state, and epilogue inside mma
With IntraWGOverlap=true, the prologue:
- waits for the rightmost K tile;
- computes its QK product;
- applies the right-edge mask;
- initializes
row_maxandrow_sum; - converts the first probability tile; and
- clears the output accumulator.
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1166-1198.
Optimization: ping-pong WGMMA issue
Before a consumer issues its WGMMA pair, it waits for its named-barrier token. After issue, it passes the token to the next consumer warpgroup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void warp_scheduler_barrier_sync() {
NamedBarrier::sync(
2 * NumThreadsPerWarpGroup,
WarpSchedulerWG1 - 1
+ canonical_warp_group_idx_nosync());
}
void warp_scheduler_barrier_arrive() {
int const cur_WG =
canonical_warp_group_idx_nosync() - 1;
int const next_WG = NumMmaWarpGroups == 2
? 1 - cur_WG
: (cur_WG < NumMmaWarpGroups - 1
? cur_WG + 1
: 0);
NamedBarrier::arrive(
2 * NumThreadsPerWarpGroup,
WarpSchedulerWG1 + next_WG);
}
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 920-950.
Example: two consumer warpgroups pass one issue token
NamedBarrier::sync(256, id) makes the calling warpgroup’s 128 threads arrive and then wait for 256 total thread arrivals. arrive(256, id) adds the calling warpgroup’s 128 arrivals without waiting. The count is 256 because one handoff combines the 128-thread sender and 128-thread receiver.
The source warpgroup indices and logical barriers are:
1
2
3
source warpgroup 0: producer
source warpgroup 1: first consumer, waits on B1
source warpgroup 2: second consumer, waits on B2
mma_init seeds B1 with 128 arrivals so the first consumer can start:
1
2
3
4
5
if (warp_group_idx == 1) {
NamedBarrier::arrive(
2 * NumThreadsPerWarpGroup,
WarpSchedulerWG1);
}
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 940-957.
The first cycle is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
initial: B1 has 128 arrivals; B2 has 0
consumer 0: sync(B1)
B1 = 128 seeded + 128 receiver -> released
consumer 1: sync(B2)
B2 = 128 receiver -> blocked
consumer 0: issue QK/PV; arrive(B2)
B2 = 128 receiver + 128 sender -> consumer 1 released
consumer 0 continues into its score epilogue
consumer 1: issue QK/PV; arrive(B1)
seeds consumer 0's next sync(B1)
Named barriers are reusable: completing the 256-arrival phase resets that barrier for its next phase. With three consumer warpgroups, the same arithmetic forms B1 -> B2 -> B3 -> B1.
This scheduler barrier answers only whose turn is it to issue WGMMA? It is different from consumer_wait, which waits for a K/V shared-memory stage, and warpgroup_wait<N>, which waits for asynchronous WGMMA results.
Optimization: intra-warpgroup QK/PV overlap
The steady-state fwd_step then performs:
1
2
3
4
5
6
7
8
QK[j]
PV[j+1]
named-barrier handoff
wait for QK[j]
mask / rowmax / alpha / exp / row_sum update
wait for PV[j+1]
prepare P[j]
rescale O
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1199-1238.
The source ordering is:
1
2
3
4
5
6
7
8
9
10
11
12
13
warp_scheduler_barrier_sync();
flash::gemm</*zero_init=*/true, /*wg_wait=*/-1>(
tiled_mma_qk, tSrQ, tSrK(...), tSrS);
flash::gemm</*zero_init=*/false, /*wg_wait=*/-1>(
tiled_mma_pv, tOrP, tOrV(...), tOrO);
warp_scheduler_barrier_arrive();
warpgroup_wait<1>();
mask_fn(tSrS, n_block);
cute::copy(
softmax.max_get_scale(tSrS),
scores_scale);
softmax.online_softmax(tSrS);
QK for the current block and PV for the preceding block are issued before the score epilogue reaches the QK dependency. Ping-pong and intra-warpgroup overlap are therefore visible in the same fwd_step.
IntraWGOverlap=true versus false
The two branches compute the same recurrence but schedule it differently. For the ordinary path without Qv:
IntraWGOverlap=true | IntraWGOverlap=false | |
|---|---|---|
| One steady step | QK for block j plus PV for block j+1 | QK, softmax, and PV for the same block j |
| WGMMA waits | wait<1> after issuing QK and PV, then wait<0> at the later dependency | wait<0> after QK and again after PV |
| Probability fragment | P[j] remains live for the next step | P[j] is produced and consumed in the same step |
| K/V stages | current K stage and preceding V stage | K and V from the same block |
| Loop shape | separate QK/softmax prologue and final PV drain | first iteration is handled by an Is_first_iter flag |
| Tradeoff | more overlap, more live registers | less overlap, shorter fragment lifetimes |
The overlap branch is a cross-block software pipeline:
1
2
3
4
5
6
7
8
prologue: QK[j+1] -> softmax[j+1] -> keep P[j+1]
steady step: issue QK[j]
issue PV[j+1]
wait until QK[j] is usable
softmax[j] -> keep P[j]
final drain: PV[last]
Its warpgroup_wait<1>() permits one later WGMMA group, normally PV, to remain outstanding while the warpgroup processes the current scores.
What exactly does warpgroup_wait<1>() mean?
Each flash::gemm ends by committing its WGMMA batch. CuTe implements the wait helper as:
1
2
3
4
5
6
template <int N>
void warpgroup_wait() {
asm volatile(
"wgmma.wait_group.sync.aligned %0;"
:: "n"(N) : "memory");
}
Source: mma_sm90_gmma.hpp, lines 59-80.
N is not a group identifier. It is the maximum number of committed WGMMA groups that may remain unfinished when the wait returns. Immediately before wait<1>, the overlap branch has committed:
1
2
oldest newest
[ QK[j] group ][ PV[j+1] group ]
The wait blocks until at most one group remains:
1
[ QK[j] completed ][ PV[j+1] may still be running ]
QK is now safe to consume, so the warpgroup may release the K stage and run masking and online softmax on tSrS. It must not yet release V or assume the output accumulator is ready.
Later:
1
warpgroup_wait<0>();
waits until no committed WGMMA group remains. PV is then complete, so the V stage can be released and O can be consumed or rescaled.
1
2
wait<1>: QK must be complete; PV may remain in flight
wait<0>: QK and PV must both be complete
This is independent of the named scheduler barrier:
1
2
NamedBarrier::sync whose turn is it to issue WGMMA?
warpgroup_wait<N> are this warpgroup's WGMMA results ready?
The non-overlap branch instead serializes each matrix dependency:
1
2
3
4
QK[j] -> wait<0>
-> mask + online softmax -> P[j]
-> rescale O
-> PV[j] -> wait<0>
It still uses ping-pong between consumer warpgroups, but the barrier placement changes. The warpgroup hands off after QK, waits for the token again before PV, and fully completes each WGMMA before consuming its result. It therefore does not keep QK for one block and PV for another block simultaneously in flight.
Sources: overlap branch, lines 1166-1282 and non-overlap branch, lines 1284-1369.
Optimization branch: convert FP8 QK output into the PV operand
After online softmax, FP8 requires register-layout repair before the score fragment can become WGMMA’s matrix-A operand:
1
2
3
4
5
6
7
if constexpr (Is_FP8 && !V_colmajor) {
permute_Cregs_fp8(tSrS);
}
convert_type_out(tOrP_acc, tOrP);
if constexpr (Is_FP8 && V_colmajor) {
permute_Aregs_fp8(tOrP);
}
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1185-1189.
The final iteration drains the remaining PV operation, calls softmax.finalize, waits for WGMMA completion, and applies the final normalization scale:
1
2
3
4
gemm(P[last], V[last], O);
scores_scale = softmax.finalize(v_descale);
warpgroup_wait<0>();
softmax.rescale_o(O, scores_scale);
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1266-1282.
A.13 Follow the online-softmax state separately
When the mainloop becomes difficult to read, keep hopper/softmax.h open beside it.
Optimization: keep the exact recurrence entirely on chip
max_get_scale updates the row maximum and moves the old row sum into the new normalization basis:
1
2
3
4
5
reduce_max<false>(scores, row_max);
scores_scale(mi) = exp2f(
(scores_max_prev(mi) - scores_max_cur)
* softmax_scale_log2);
row_sum(mi) *= scores_scale(mi);
The assignment that actually changes row_max is inside the reduction helper:
1
2
3
summary(mi) = zero_init && ni == 0
? tensor(mi, ni)
: op(summary(mi), tensor(mi, ni));
reduce_max supplies MaxOp<float> as op:
1
2
MaxOp<float> max_op;
reduce_<zero_init>(tensor, max, max_op);
For the first score tile, reduce_max<true> initializes row_max from that tile. For later tiles, reduce_max<false> starts with the existing row_max, computes max(old_row_max, current_scores), performs the four-thread all-reduce, and writes the result back into row_max.
Sources: softmax.h, lines 19-55 and softmax.h, lines 101-124.
online_softmax replaces scores with the current unnormalized probabilities and accumulates their row sum:
1
2
3
scale_apply_exp2(
scores, row_max, softmax_scale_log2);
reduce_sum<Is_first, false>(scores, row_sum);
The running sum is therefore updated in two stages:
1
2
3
4
5
// max_get_scale: move the old sum into the new maximum's basis
row_sum(mi) *= scores_scale(mi);
// online_softmax: add the current probability tile
reduce_sum<Is_first, false>(scores, row_sum);
reduce_sum supplies SumOp<float> to the same thread_reduce_ helper. On the first tile, Is_first=true initializes the partial sums. On later tiles, Is_first=false adds into the existing row_sum, giving:
1
2
3
row_sum =
alpha * old_row_sum
+ sum(exp(current_scores - new_row_max))
These remain per-thread partial sums during the mainloop because warp_reduce=false. finalize later calls quad_allreduce_ to combine the four threads that represent each logical row.
rescale_o applies the same basis change to the output numerator:
1
acc_o_rowcol(mi, ni) *= scores_scale(mi);
finalize performs the deferred cross-lane sum reduction, changes row_sum into LSE, and returns 1 / sum for final output normalization:
1
2
3
row_sum(mi) =
row_max(mi) * softmax_scale + log(sum);
scores_scale(mi) = 1.f / sum;
Source: hopper/softmax.h, lines 101-166.
A.14 Epilogue: store LSE and O
Back in FlashAttnFwdSm90::operator(), a valid tile calls:
1
2
3
4
5
epilogue.store(
params.epilogue,
tOrO,
softmax.row_sum,
...);
Source: flash_fwd_kernel_sm90.h, lines 438-447.
The epilogue:
- converts the FP32 output fragment to the output dtype;
- writes O from registers to shared memory;
- writes FP32 LSE directly to global memory; and
- uses TMA to store the fixed-length output tile when legal.
Source: epilogue_fwd.hpp, lines 240-390.
Optimization: TMA output store when the layout is regular
The epilogue enables TMA output stores only when the output tile has a regular fixed-length layout:
1
2
3
4
5
static constexpr bool Use_TMA_O =
ArchTag::kMinComputeCapability >= 90
&& !Varlen
&& !Split
&& !PackGQA;
Source: epilogue_fwd.hpp, lines 30-38.
The normal fixed-length Hopper path satisfies these conditions, so one elected thread launches the shared-to-global TMA store and waits for its completion before releasing the output/shared-memory barrier.
A.15 Return to Python
After the kernel completes:
1
2
3
4
5
mha_fwd returns O, LSE, and optional split accumulators
boxed_mha_fwd repacks operator outputs
_flash_attn_forward returns tensors to Python
FlashAttnFunc.forward saves Q/K/V/O/LSE for backward
flash_attn_func returns O
If return_attn_probs=True, the wrapper also returns LSE for inspection. It does not materialize the complete probability matrix.
A.16 A practical source-reading checklist
Read these files in order:
| Step | File | Question |
|---|---|---|
| 1 | flash_attn_interface.py | Which optional modes are absent or enabled? |
| 2 | flash_api_stable.cpp | What runtime parameters and template switches are selected? |
| 3 | tile_size.h | What are kBlockM, kBlockN, PV operand mode, and overlap mode? |
| 4 | flash_fwd_launch_template.h | Which mainloop, epilogue, scheduler, and kernel types are assembled? |
| 5 | tile_scheduler.hpp | Which logical Q tile does this persistent CTA own next? |
| 6 | flash_fwd_kernel_sm90.h | Which warpgroup is producer, and which are consumers? |
| 7 | mainloop_fwd_sm90_tma_gmma_ws.hpp | Which TMA stage and WGMMA fragment correspond to the current K/V block? |
| 8 | softmax.h | How are row_max, row_sum, and O kept in the same normalization basis? |
| 9 | epilogue_fwd.hpp | When are LSE and normalized O committed to global memory? |
For each function, write down only:
1
2
3
4
5
6
compile-time configuration
runtime tile coordinate
current K/V pipeline stage
values resident in registers
barrier waited on
barrier released
That is enough to reconstruct the normal FA3 forward path without expanding every CuTe type or optional feature branch.
Appendix B: what changes for varlen, GQA, and FP8?
Appendix A followed one fixed-length BF16 configuration with equal Q and KV head counts. This appendix keeps the same top-down route but highlights only the branches that change for three important variants.
| Variant | Logical layout change | Scheduler change | Mainloop/epilogue change |
|---|---|---|---|
| Varlen | Q/K/V are concatenated across sequences | work per batch depends on its actual sequence length | runtime offsets and predication; no TMA output store |
| GQA | multiple Q heads share one KV head | either schedule Q heads separately or pack them into the M dimension | KV-head mapping; packed Q uses cp.async and scattered output stores |
| FP8 | one-byte operands with explicit descales and stricter WGMMA layouts | FP8-specific tile choices | V transpose, register permutation, BF16 output, fused V descale |
B.1 Variable-length attention
B.1.1 Python passes concatenated tensors and prefix sums
The varlen API expects:
1
2
3
4
5
6
Q: [total_q, q_heads, d]
K: [total_k, kv_heads, d]
V: [total_k, kv_heads, dv]
cu_seqlens_q: [batch + 1]
cu_seqlens_k: [batch + 1]
For example:
1
2
Q sequence lengths: [3, 5, 2]
cu_seqlens_q: [0, 3, 8, 10]
Sequence 1 therefore starts at row 3 and has length 5. The Python path is flash_attn_varlen_func -> FlashAttnVarlenFunc.forward -> _flash_attn_forward; it passes the prefix sums and maximum sequence lengths through the same lower-level operator used by fixed-length attention.
Sources: FlashAttnVarlenFunc, lines 642-732 and flash_attn_varlen_func, lines 890-930.
B.1.2 Runtime validation switches tensor shapes
mha_fwd derives batch size from the prefix-sum arrays and validates packed three-dimensional tensors instead of [batch, sequence, head, dimension]:
1
2
3
4
5
6
batch_size = cu_seqlens_q.size(0) - 1;
seqlen_q = max_seqlen_q;
total_q = q.size(0);
CHECK_SHAPE(q, total_q, num_heads, head_size);
CHECK_SHAPE(k, total_k, num_heads_k, head_size);
The output is also packed:
1
2
O: [total_q, q_heads, dv]
LSE: [q_heads, total_q]
Source: flash_api_stable.cpp, lines 808-980.
The runtime condition becomes the compile-time Varlen template parameter:
1
2
3
4
5
6
7
8
VARLEN_SWITCH(
params.cu_seqlens_q
|| params.cu_seqlens_k
|| params.seqused_q
|| params.seqused_k
|| params.leftpad_k,
Varlen,
...);
Source: flash_fwd_launch_template.h, lines 202-220.
B.1.3 The scheduler must understand uneven batches
Fixed-length scheduling can decode a tile from uniform dimensions. Varlen selects VarlenDynamicPersistentTileScheduler, whose physical grid is still approximately one CTA per SM but whose logical tile list contains a different number of Q blocks for every batch.
Each warp lane examines one sequence:
1
2
3
4
5
int seqlen =
cu_seqlens[batch_idx + 1]
- cu_seqlens[batch_idx];
int num_m_blocks = ceil_div(seqlen, kBlockM);
Warp prefix sums convert those per-batch block counts into one flattened work range. Prepared metadata can additionally sort sequences and precompute block counts so long sequences are assigned earlier.
Source: VarlenDynamicPersistentTileScheduler, lines 493-715.
B.1.4 SeqlenInfo converts a batch index into offsets and lengths
At the start of each tile, the kernel reads the prefix sums once:
1
2
3
4
5
6
7
offset_q = cu_seqlens_q[bidb];
offset_k = cu_seqlens_k[bidb];
seqlen_q =
cu_seqlens_q[bidb + 1] - cu_seqlens_q[bidb];
seqlen_k =
cu_seqlens_k[bidb + 1] - cu_seqlens_k[bidb];
Source: seqlen.h, lines 30-100.
The mainloop applies those offsets to the global Q/K/V tensor views before tiling:
1
2
3
4
5
gQ = local_tile(
domain_offset((offset_q, 0), mQ), ...);
gK = local_tile(
domain_offset((offset_k, 0, 0), mK), ...);
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 591-690.
The attention recurrence itself is unchanged. The differences are tile bounds, tail masking, and where each sequence begins in the packed tensors.
B.1.5 Varlen disables the TMA output store
The fixed-length TMA output tile could cross into the next packed sequence. The epilogue therefore requires !Varlen:
1
2
3
4
5
static constexpr bool Use_TMA_O =
ArchTag::kMinComputeCapability >= 90
&& !Varlen
&& !Split
&& !PackGQA;
The varlen branch performs predicated per-thread copies instead:
1
2
// Don't use TMA in Varlen case since we don't want
// to overwrite the output of another sequence.
Source: epilogue_fwd.hpp, lines 30-38 and 330-390.
B.2 Grouped-query attention
Let:
1
2
3
q_heads = 16
kv_heads = 4
qhead_per_khead = 4
Q heads 0-3 share KV head 0, Q heads 4-7 share KV head 1, and so on. FA3 has two ways to schedule this.
B.2.1 Ordinary GQA: schedule each Q head separately
With PackGQA=false, the scheduler still returns a Q-head index. The mainloop maps it to the shared KV head:
1
2
int bidh_kv =
params.qhead_per_khead_divmod.divide(bidh);
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 625-650.
Each logical tile still contains one Q head, so regular TMA Q loading and TMA output stores remain legal. Multiple Q-head tiles reference the same K/V head; the scheduler’s head ordering and L2 swizzle try to keep that shared K/V data cache-resident.
B.2.2 Packed GQA: fold Q-head-within-group into the M dimension
For short Q sequences, scheduling one tile per Q head wastes most of a kBlockM tile. Packed GQA flattens:
1
(Q head within its KV group, sequence position)
into the row dimension:
1
2
effective M extent = seqlen_q * qhead_per_khead
scheduler head = KV head
The launch code reflects this directly:
1
2
3
4
5
6
7
8
int qhead_per_khead =
ceil_div(params.h, params.h_k);
int num_blocks_m = ceil_div(
params.seqlen_q * qhead_per_khead,
kBlockM);
scheduler_heads = params.h_k;
Source: flash_fwd_launch_template.h, lines 135-165.
The heuristic always packs varlen Q and otherwise compares the useful fraction of the unpacked and packed M tiles:
1
2
3
4
if (varlen_q) return true;
return nopack_gqa_efficiency
< 0.9 * pack_gqa_efficiency;
Source: heuristics.h, lines 9-17 and get_pack_gqa, lines 491-505.
B.2.3 Why packed Q uses cp.async
The flattened row number must be divided at runtime:
1
2
m_idx = qhead_per_khead_divmod.divmod(h_idx, idx);
q_ptr = &Q[h_idx, m_idx];
Rows in one logical tile may therefore come from different Q-head base pointers. The regular rectangular TMA Q descriptor cannot express this runtime gather:
1
static constexpr bool Use_TMA_Q = !PackGQA;
PackGQAManager::load_Q instead computes and shares row pointers, predicates the tail, and issues vectorized cp.async copies.
Sources: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 44-57 and pack_gqa.h, lines 12-119.
Packed output rows require the inverse mapping. The epilogue uses PackGQAManager::store_LSE and store_O to scatter each flattened row back to its (Q head, sequence position) destination. This irregular scatter also disables the TMA output store.
Source: pack_gqa.h, lines 120-240 and epilogue_fwd.hpp, lines 291-390.
B.3 FP8 attention
B.3.1 Dispatch changes the input and output types
The public Hopper path supports FP8 E4M3 input. Runtime dispatch selects cutlass::float_e4m3_t, requires head dimensions aligned to 16 elements, and uses BF16 output:
1
2
3
4
using T_out = std::conditional_t<
!Is_FP8,
T,
cutlass::bfloat16_t>;
Sources: flash_api_stable.cpp, lines 917-980 and flash_fwd_launch_template.h, lines 202-220.
Optional Q, K, and V descale tensors are indexed by batch and KV head:
1
2
q_descale, k_descale, v_descale:
[batch, kv_heads]
Source: flash_api_stable.cpp, lines 1183-1214.
B.3.2 Row-major FP8 V requires an in-kernel transpose
FP8 WGMMA requires V to use K-major layout. For row-major input:
1
2
static constexpr bool Transpose_V =
Is_FP8 && !V_colmajor;
The producer first loads V into a staging layout, then uses LDSM, byte permutation, and STSM to construct the WGMMA-compatible shared-memory layout:
1
2
3
4
tTransrV_64[j].x =
__byte_perm(upper, lower, 0x6420);
tTransrV_64[j].y =
__byte_perm(upper, lower, 0x7531);
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 44-66 and 709-798.
This transformation requires the full 128-thread producer warpgroup instead of the single active producer warp used by the ordinary all-TMA path.
B.3.3 The QK accumulator must become a legal FP8 PV operand
QK still accumulates into FP32 registers. Before PV, FA3 permutes that accumulator layout and converts the probabilities to FP8:
1
2
3
4
5
6
7
if constexpr (Is_FP8 && !V_colmajor) {
permute_Cregs_fp8(tSrS);
}
convert_type_out(tOrP_acc, tOrP);
if constexpr (Is_FP8 && V_colmajor) {
permute_Aregs_fp8(tOrP);
}
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1181-1190.
FP8 requires register/shared PV:
1
2
3
static_assert(
!(!MmaPV_is_RS && Is_FP8),
"MmaPV must be RS if FP8");
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 79-116.
B.3.4 Scaling is folded into the existing recurrence
The pinned kernel accepts per-batch/per-KV-head descale pointers. V descale is passed into softmax.finalize, so it is folded into the final output scale:
1
2
3
4
5
6
7
float v_descale =
ptr_v_descale == nullptr
? 1.0f
: ptr_v_descale[batch, kv_head];
scores_scale =
softmax.finalize(v_descale);
Source: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1266-1282.
In this pinned revision, Q/K descale pointers are read explicitly in the softcap path: mainloop_fwd_sm90_tma_gmma_ws.hpp, lines 1095-1105. Callers using other FP8 scaling conventions must ensure the score scale matches the quantization convention expected by the kernel.
B.4 A compact comparison checklist
When reading another FA3 configuration, check these compile-time values first:
1
2
3
4
5
6
7
Varlen
PackGQA
Is_FP8 / Transpose_V
Use_TMA_Q
Use_TMA_O
NumProducerThreads
Scheduler
They predict most structural differences:
1
2
3
4
5
6
7
8
9
10
11
Varlen:
dynamic per-sequence work + runtime offsets + predicated output
ordinary GQA:
Q-head tile + Q-head-to-KV-head division
packed GQA:
flattened Q rows + cp.async Q + scattered output
FP8:
transformed V layout + FP8 P operand + fused descale + BF16 output