FlashAttention in Depth
Tiling, the online softmax and partitioning work across a GPU.
In 2022 an attention kernel that did more arithmetic than the standard one ran several times faster, and its output was exact. The explanation is that attention's running time is set by the bytes moved between memory levels, not by its FLOPs. This lesson works that out: the GPU's memory hierarchy, the online softmax as an associative merge, the tiled algorithm, its IO complexity and the lower bounds that make it optimal, and how FlashAttention-2 and -3 split the work across a GPU, across a KV cache during decoding, and across devices.
What you’ll learn
- Model a GPU as a small fast SRAM in front of a large slow HBM, and count the HBM traffic of standard attention.
- Prove that the online-softmax state merges associatively and commutatively, so blocks of keys can be processed in any order and in parallel.
- Derive FlashAttention's HBM accesses and its recomputing backward pass, and state the lower bounds that make it optimal for .
- Explain how FlashAttention-2 and -3 partition the work and hide non-matmul costs, and how split-KV decoding and ring attention apply the same merge across a cache and across devices.
Bytes, not FLOPs
Two memories matter on a GPU. HBM, the main memory, holds tens of gigabytes. SRAM on the chip, the registers and shared memory of each streaming multiprocessor, holds a few hundred kilobytes per multiprocessor and tens of megabytes in total, with roughly ten times the bandwidth. For the A100 on which FlashAttention was developed, Dao et al. (2022) cite 40–80 GB of HBM at 1.5–2.0 TB/s against 192 KB of SRAM in each of 108 multiprocessors, with an estimated 19 TB/s. A kernel loads its inputs from HBM, computes in SRAM and registers, and writes its outputs back; an operation with few FLOPs per byte, such as a softmax, is limited by that traffic (The Roofline Model & Compute Efficiency).
Model this with two levels: a slow memory that holds everything and a fast memory of numbers where all arithmetic happens. The IO complexity of an algorithm is the number of values it moves between the two. Standard attention for one head, with (in this lesson is the head size), runs three kernels:
STANDARD-ATTENTION(Q, K, V) // Q, K, V: T x d, in HBM
S <- Q K^T / sqrt(d) read 2Td, write T^2 // kernel 1: a matrix product
P <- softmax(S) read T^2, write T^2 // kernel 2: memory-bound
O <- P V read T^2 + Td, write Td // kernel 3: a matrix product
keep P in HBM for the backward passHBM accesses per head, dominated by the intermediates. Fusing the mask and the softmax into one kernel removes a pass, not the .
| Measured | Standard attention | FlashAttention |
|---|---|---|
| FLOPs | 66.6 G | 75.2 G |
| HBM reads and writes | 40.3 GB | 4.4 GB |
| Runtime | 41.7 ms | 7.3 ms |
In 16-bit numbers, how many GiB does the score matrix of a single head occupy at ?
Show the answer
2 GiB
bytes GiB, per head, per layer, per sequence: 64 GiB for the 32 heads of one layer. Standard attention writes it, reads it, writes , reads again and keeps for the backward pass. FlashAttention's per-row statistics for the same head take 128 KiB.
The online softmax is an associative merge
Tiling needs one fact: the softmax over a set of keys can be assembled from pieces computed over parts of the set. Milakov and Gimelshein (2018) introduced the one-pass version for a single vector, the online softmax: keep a running maximum and a running normalizer , and for each new entry update . That cut a numerically safe softmax from four memory accesses per element to three. Attention adds an output accumulator, and the update generalizes from one entry to a whole block.
Map a state to the two unnormalized sums it encodes, and :
Under the merge becomes plain addition, because each factor cancels against :
So and encode the same sums and carry the same first coordinate, the largest score in the union. Given , a state is determined by its sums (, ), so the two are equal. Associativity and commutativity are inherited from and :
Dividing recovers attention. The state is a floating-point representation of with a shared exponent chosen from the data, which is why it stays finite where itself would overflow, for any score above about 88 in FP32:
Every later step uses associativity. Folding key blocks in from left to right gives FlashAttention's inner loop; computing them in parallel and merging along a tree gives split-KV decoding; holding them on different devices gives ring attention. For the backward pass one number per query row is enough: with , any weight can be recomputed from and alone.
A query has folded in a first block of keys with scores and , so its state has . The next block contains one key with score . Before adding the new block's terms, by what factor must the old and be multiplied?
- : earlier terms never change
Show the answer
A.
The old terms were stored relative to and must be re-expressed relative to the new maximum : multiply by . With values , and for the three keys, the merged state gives and output , the exact softmax average.
Tiling and its IO complexity
FlashAttention (Dao, Fu, Ermon, Rudra & Ré, 2022) fuses the whole computation into one kernel. Queries are cut into blocks of rows, keys and values into blocks of rows, small enough that a query block, a key–value block and their tile of scores fit in SRAM together; with SRAM of numbers the paper takes and . For each pair of blocks the kernel forms the score tile, folds it into the query rows' states with , and moves on. The original algorithm looped over key–value blocks on the outside, re-reading and re-writing every query block's output state in HBM on each pass; FlashAttention-2 swapped the loops, an order first used in Phil Tillet's Triton implementation, so each query block's state stays on chip until it is finished (Dao, 2024):
import torch
import torch.nn.functional as F
def flash_forward(q, k, v, Br=64, Bc=64):
"""Exact attention for one head, block by block (FlashAttention-2 loop order). q, k, v: (T, d)."""
T, d = q.shape
out, lse = torch.empty_like(q), torch.empty(T)
for i in range(0, T, Br): # query blocks are independent: one thread block each
qi = q[i:i + Br] / d ** 0.5
m = torch.full((qi.shape[0],), float('-inf')) # running row maxima
l = torch.zeros(qi.shape[0]) # running sums of exp(s - m)
acc = torch.zeros(qi.shape[0], d) # running unnormalized outputs
for j in range(0, T, Bc): # stream key/value blocks through fast memory
s = qi @ k[j:j + Bc].T # a Br x Bc tile of scores, never stored in full
m_new = torch.maximum(m, s.max(dim=1).values)
p = torch.exp(s - m_new[:, None])
scale = torch.exp(m - m_new) # re-express the old state at the new maximum
l = scale * l + p.sum(dim=1)
acc = scale[:, None] * acc + p @ v[j:j + Bc]
m = m_new
out[i:i + Br] = acc / l[:, None] # normalize once, at the end
lse[i:i + Br] = m + torch.log(l) # the one number per row the backward pass needs
return out, lse
q, k, v = (torch.randn(256, 64) for _ in range(3))
o, L = flash_forward(q, k, v)
assert torch.allclose(o, F.scaled_dot_product_attention(q[None], k[None], v[None])[0], atol=1e-5)
assert torch.allclose(L, torch.logsumexp(q @ k.T / 64 ** 0.5, dim=1), atol=1e-5)The algorithm, not the kernel: on a GPU each pass of the outer loop is a thread block and the inner loop runs out of SRAM and registers. The asserts check that the tiles reproduce PyTorch's attention and the row log-sum-exp to rounding error.
Count HBM accesses for one head with . A key–value block must fit, , so take . In the original loop order every key and value is read once, and each of the key–value blocks triggers one pass over all of and the output state:
Swapping the loops exchanges the roles of the two block sizes and gives the same order; what it removes is the repeated reading and writing of the output state. Against the of standard attention the saving for long sequences is a factor of order : from several to a few dozen for head sizes of 128 to 64 and on-chip memories of order numbers, before constant factors; the reduction measured above was ninefold.
The backward pass needs to form with (Deriving Backward Passes). FlashAttention saves only and the softmax statistics of each row (the original kept and ; FlashAttention-2 keeps just ), recomputes each tile of and from blocks of and , and pays one extra matrix product; its HBM traffic is again against , and its extra memory is :
A fixed block-sparse mask skips whole tiles: with a fraction of nonzero blocks the count becomes (Dao et al., 2022). The causal mask is the commonest case: about half the tiles are skipped, and only those on the diagonal need an elementwise mask.
Partitioning the work: FlashAttention-2 and -3
A GPU runs a kernel as a grid of thread blocks, each scheduled on one streaming multiprocessor and made of warps of 32 threads that share the block's SRAM; tensor cores carry out small matrix products. The first FlashAttention reached only 25–40% of the A100's peak throughput (Dao, 2024). FlashAttention-2 changed three things:
- Fewer non-matmul FLOPs. Tensor cores multiply matrices far faster than the rest of the chip does anything else: for the A100, Dao (2024) cites 312 TFLOP/s for 16-bit matrix products against 19.5 TFLOP/s for 32-bit arithmetic outside them, so every non-matmul FLOP costs as much time as 16 matmul FLOPs. The kernel keeps the output unnormalized, divides by once at the end, and saves only for the backward pass.
- Parallelism over the sequence. The first version gave each (sequence, head) pair one thread block, so with long sequences, small batches and few heads, many of the 108 multiprocessors sat idle. Once the loops are swapped, query blocks are independent and each becomes its own thread block. The backward pass parallelizes over key blocks instead and accumulates with atomic additions.
- Work inside a block. The first version split and across four warps, which then had to write partial outputs to shared memory and add them up ("split-K"). FlashAttention-2 splits across the warps instead: each warp owns its query rows and needs nothing from the others.
Together these roughly doubled the speed, reaching up to 73% of the A100's peak in the forward pass and 225 TFLOP/s per GPU (72% model FLOPs utilization) when training GPT-style models end to end (Dao, 2024).
FlashAttention-3 (Shah, Bikshandi, Zhang, Thakkar, Ramani & Dao, 2024) targets the H100, on which FlashAttention-2 reached about 35% of peak. Its starting point is a count. Each score costs FLOPs in the two matrix products ( for , for adding ) and one exponential, computed by a separate multi-function unit whose throughput on the H100 is about 256 times lower than the tensor cores' 16-bit rate:
FlashAttention-3 therefore overlaps them, using the H100's asynchronous hardware:
- Warp specialization. Producer warps issue asynchronous bulk copies from HBM to shared memory (through the Tensor Memory Accelerator); consumer warps run the matrix products, so loading the next blocks hides behind computing the current ones.
- Ping-pong scheduling. Two groups of warps alternate, so that one group's softmax runs while the other group's matrix products occupy the tensor cores; within a group, the softmax of one block overlaps the matrix product of the next.
- FP8 with less error. The E4M3 format keeps 3 mantissa bits, and outliers ruin a single scale per tensor. FlashAttention-3 keeps one scale per block of , and , and multiplies and by the same random orthogonal matrix before quantizing: , while each entry of mixes many entries of and spreads the outliers out. is a Hadamard matrix times random signs, applied in operations (Number Formats & Mixed Precision covers the formats).
The result was 1.5–2.0 times FlashAttention-2's forward speed, up to 740 TFLOP/s (75% of peak) in FP16 and close to 1.2 PFLOP/s in FP8, with 2.6 times lower error than FP8 attention with per-tensor scaling on inputs with outliers (Shah et al., 2024).
One query, many keys: decoding and many devices
In decoding, a sequence brings one query per head, so parallelism over query blocks has nothing to split. When batch times heads is below the number of multiprocessors most of the GPU idles; at batch 1, FlashAttention used less than 1% of the GPU (Dao, Haziza, Massa & Sizov, 2023). Split-KV decoding, their Flash-Decoding, cuts the cached keys and values into chunks, lets separate thread blocks compute each chunk's partial output together with its log-sum-exp, and combines them in a second, small kernel: the of the merge theorem, applied along a tree. In the authors' benchmarks the attention kernel ran up to 50 times faster than FlashAttention at long contexts, and generation with CodeLlama-34B up to 8 times faster, at contexts up to 64K tokens.
Ring attention applies the same merge across devices (Liu, Zaharia & Abbeel, 2024). Each of devices holds a block of queries together with that block's keys and values. In each of rounds, every device folds the key–value block it currently holds into its queries' states, passes the block to its neighbor in a ring and receives the next one at the same time. After rounds every query has seen every key, the result is exact, and no device ever holds more than a few blocks, so the context that fits grows linearly with the number of devices. The communication hides behind the computation when attending to a block takes longer than sending it:
Key takeaways
- Standard attention moves values per head through HBM, mostly intermediates; because the softmax is memory-bound, time follows bytes. On GPT-2 medium FlashAttention did 13% more FLOPs, moved 9 times fewer bytes and ran 5.7 times faster.
- The online-softmax state encodes with a shared exponent; its merge is addition in disguise, hence associative, commutative and overflow-free.
- Tiling gives HBM accesses, optimal up to constants for (Saha & Ye, 2024); recomputing tiles from the stored log-sum-exp keeps the backward pass at extra memory.
- FlashAttention-2 cut non-matmul work, parallelized over query blocks and split queries across warps; FlashAttention-3 overlaps exponentials with asynchronous matrix products and adds FP8 with block scaling and incoherent processing.
- Split-KV decoding and ring attention apply the same merge across a cache and across devices; ring attention hides its communication when each device's block holds at least tokens.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
FlashAttention's backward pass performs more FLOPs than that of standard attention, yet it runs faster. Why?
- It runs the backward pass in 8-bit arithmetic
- It approximates the softmax in the backward pass
- Attention is limited by HBM traffic, and recomputing score tiles on chip costs less time than writing and reading matrices
- It skips the attention weights that are close to zero
Show the answer
C. Attention is limited by HBM traffic, and recomputing score tiles on chip costs less time than writing and reading matrices
The softmax and the reads and writes of and are memory-bound. Recomputing and tile by tile from , and the stored log-sum-exp adds one matrix product of tensor-core work and removes HBM traffic: on GPT-2 medium, 13% more FLOPs and 9 times fewer bytes gave a 5.7-fold speedup.
In split-KV decoding, eight thread blocks each compute a partial result over a different chunk of one sequence's cache. Which combination gives the exact attention output?
- The plain average of the eight normalized outputs
- The -merge of their states , in any order
- The output of the chunk with the largest maximum score
- Only a merge in the original left-to-right order of the chunks
Show the answer
B. The -merge of their states , in any order
Each state encodes the sums with a shared exponent, and adds them, so it is associative and commutative. Averaging normalized outputs would weight every chunk equally instead of by its share of the total normalizer.
What do the known lower bounds say about FlashAttention's HBM accesses?
- Dao et al. (2022) proved it optimal separately for each SRAM size
- It is optimal up to constants whenever , even against algorithms that use fast matrix multiplication; for a different tiling does better
- Exact attention can be done with accesses for any
- No lower bound is known, so much better algorithms may exist in the practical regime
Show the answer
B. It is optimal up to constants whenever , even against algorithms that use fast matrix multiplication; for a different tiling does better
Saha and Ye (2024) showed for standard matrix multiplication and extended the bound for to fast matrix multiplication. Dao et al.'s own bound only excluded beating at every simultaneously.
What did FlashAttention-2 gain by putting the loop over query blocks outside and the loop over key–value blocks inside?
- Fewer FLOPs per score
- The ability to skip the causal mask
- An approximation of the softmax that needs no maximum
- Each query block's running state stays on chip until it is done, and the query blocks become independent units of parallel work
Show the answer
D. Each query block's running state stays on chip until it is done, and the query blocks become independent units of parallel work
In the original order every key–value block forced a re-read and re-write of all query blocks' in HBM. With queries outside, a query block is loaded once, its state lives in SRAM and registers while all keys stream past, and different query blocks can run on different multiprocessors, which matters when batch times heads is small.
Further reading
- T. Dao, D. Y. Fu, S. Ermon, A. Rudra & C. Ré, "FlashAttention: Fast and memory-efficient exact attention with IO-awareness," NeurIPS (2022).
- T. Dao, "FlashAttention-2: Faster attention with better parallelism and work partitioning," ICLR (2024).
- J. Shah, G. Bikshandi, Y. Zhang, V. Thakkar, P. Ramani & T. Dao, "FlashAttention-3: Fast and accurate attention with asynchrony and low-precision," NeurIPS (2024).
- M. Milakov & N. Gimelshein, "Online normalizer calculation for softmax," arXiv:1805.02867 (2018).
- B. Saha & C. Ye, "I/O complexity of attention, or how optimal is FlashAttention?," ICML (2024).
- H. Liu, M. Zaharia & P. Abbeel, "RingAttention with blockwise transformers for near-infinite context," ICLR (2024).