Highlights

Contents

Part VI
06

FlashAttention: Exact Attention That Respects Memory

Attention can spend more time moving intermediates than computing them. FlashAttention keeps score tiles near the processor. Online normalization and backward recomputation preserve dense attention without storing its full score grid.

YOU ARE HEREMODERN DECODER BLOCKATTENTION HALFRMSNormq, k, v projRoPE (q, k)GQA: 8 q, 2 kvSDPAFlash kernelo proj+MLP HALFRMSNormgate, up projSiLU(g) ⊙ udown proj+residual stream: x + Attn(Norm(x)), then h + MLP(Norm(h))what changed since GPT-2: positions, norm, MLP, K/V sharing, the attention kernel, and no biases

#Section 27The Real Bottleneck: Moving Data

A GPU has small, fast on-chip SRAM and larger main HBM, or high-bandwidth memory. Computation needs its inputs on-chip, so repeatedly transferring large intermediates can dominate execution.

GPU MEMORY HIERARCHY (NVIDIA A100 NUMBERS FROM THE FLASHATTENTION PAPER)SRAM (on-chip)≈ 20 MB total≈ 19 TB/sHBM (GPU main memory)40 or 80 GB1.5 to 2.0 TB/sCPU DRAM> 1 TB12.8 GB/sfast, tinyslow, hugethe game: do the work in SRAM, touch HBM as little as possible
Figure 2.41The memory hierarchy of an A100 GPU. SRAM is tiny and very fast; HBM is large and about ten times slower. Arithmetic happens on the chip, so every number must travel up from HBM first.

Arithmetic intensity is work per byte moved. Matrix multiplication can reuse data heavily; separate masking and softmax operations often do little work per transfer and become memory-limited.

#Section 28Standard Attention’s Round Trips

Now trace the hand-written attention of Chapter 1 through that hierarchy, for one head with TT tokens and head size dd. QQ, KK and VV live in HBM. The GPU reads QQ and KK onto the chip, computes the score grid S=QK⊤S = QK^\top, and, because SS is far too big to keep on the chip for long sequences, writes it back to HBM: T2T^2 numbers out. Then it reads SS back in, computes the softmax PP, and writes PP out: T2T^2 in, T2T^2 out. Then it reads PP and VV back in and computes the output OO: another T2T^2 in.

STANDARD ATTENTION’S TRIPS BETWEEN HBM AND THE CHIP (PER HEAD, T TOKENS, HEAD SIZE d)HBMQ, K, V (T × d each)S (T × T)P (T × T)O (T × d)chip (SRAM + compute)read Q, K → compute S = QKᵀwrite Sread S → softmax → Pwrite Pread P, V → O = PVwrite Othe two T × T grids each go out and come back: about 4T² extra elements moved, versus 4Td for the inputs and output
Figure 2.42Standard attention's memory traffic. The two T × T grids, S and P, each go out to HBM and come back, about 4T² elements of traffic, against only 4Td for the inputs and output.

The score and probability grids are large intermediates that are written and read again. Avoiding those round trips is the main opportunity, rather than changing the attention formula.

#Section 29Tiles and Online Softmax

FlashAttention, published by Tri Dao, Daniel Fu, Stefano Ermon, Atri Rudra and Christopher Ré in 2022, attacks exactly that traffic. Its idea is never to build the whole score grid. Cut QQ into blocks of rows and KK and VV into blocks of rows too. Load one query block into SRAM and keep it there. Then sweep across the key/value blocks one at a time. For each one, compute that tile of scores, use it immediately to update the output for the query block, and throw it away. When the sweep finishes, the query block's output is complete; write it to HBM once and move on to the next query block.

FLASHATTENTION: ONE QUERY BLOCK STAYS ON CHIP WHILE KEY/VALUE BLOCKS STREAM PASTQ0Q1Q2Q3K0V0K1V1K2V2K3V3grey dashed: above the diagonal, skippedIN SRAM RIGHT NOWquery block Q2key/value block K1, V1tile scores S = Q2 K1ᵀ (used, then discarded)per query row, three running quantities:m largest score so farℓ running sum of exp(s − m)O running sum of exp(s − m) · v
Figure 2.43FlashAttention's sweep. One query block stays in SRAM while key/value blocks stream past. Only the current tile of scores exists at any moment, plus three running quantities per query row.

The catch is softmax. To normalize a row you need the maximum score and the total of the exponentials across the whole row, but the sweep only ever sees one tile of the row at a time. The solution is the online softmax of Chapter 1, Section 57, extended to carry the output along. For each query row keep three running quantities: mm, the largest score seen so far; ℓ\ell, the running sum of es−me^{s - m}; and OO, the running sum of es−m ve^{s - m}\,v. When a new tile arrives with scores ss and values vv:

m′=max⁡(m,max⁡s)ℓ′=em−m′ ℓ+∑es−m′O′=em−m′ O+∑es−m′ vm' = \max(m, \max s) \qquad \ell' = e^{m - m'}\,\ell + \sum e^{s - m'} \qquad O' = e^{m - m'}\,O + \sum e^{s - m'}\,v

and at the very end the output is O/ℓO / \ell. Read the update in words: if the new tile contains a bigger maximum, everything accumulated so far was measured against the old maximum and is too large by a factor of em′−me^{m' - m}, so shrink it by em−m′e^{m - m'}; then add the new tile's contributions measured against the new maximum.

Why the running result stays correct

Each tile contributes scores and weighted values relative to a running maximum.

When a later tile raises that maximum, rescale the earlier sums to the new reference before adding the tile's contributions.

The final normalized sum agrees with the all-at-once calculation, up to floating-point rounding. The figure gives a small example.

ONLINE SOFTMAX WITH VALUES: ONE QUERY, TWO KEY BLOCKS OF THREE (SCALAR VALUES)block 1scores [1.0, 2.0, 0.0], values [10, 20, 30]m = 2.0ℓ = e⁻¹ + e⁰ + e⁻² = 1.5032O = 0.368·10 + 1·20 + 0.135·30 = 27.739block 2scores [3.0, 0.5, 1.0], values [40, 50, 60]m′ = 3.0, factor e^(2 − 3) = 0.3679ℓ′ = 0.3679 · 1.5032 + 1.2174 = 1.7704O′ = 0.3679 · 27.739 + 52.224 = 62.429resultout = O′ / ℓ′ = 35.262checksoftmax of all six scores, then weights · values= 35.262 ✓
Figure 2.44Online softmax carrying the output, worked by hand. After the second block raises the maximum, the old sum and output are rescaled by e to the power of minus one before the new terms are added. The final answer matches the all-at-once computation.

#Section 30What It Buys

Less traffic

Keeping score tiles on-chip reduces HBM traffic. The original paper measured faster training in its tested workloads; actual savings depend on shapes, hardware, and how much of the total runtime attention occupies.

HBM ELEMENTS MOVED PER HEAD, LOG-LOG (SHAPES FROM THE PAPER’S BOUNDS; SRAM = 100k ELEMENTS)1e51e71e91e115122,0488,19232,76865,536standardFlash d=128Flash d=64sequence length T
Figure 2.45HBM traffic against sequence length on log scales, using the shapes of the paper's bounds with an illustrative SRAM size. Both grow, but FlashAttention sits far below, and the gap depends on the head size.

Memory use falls even more dramatically. Standard attention stores the full T×TT \times T grid; FlashAttention stores nothing of size T2T^2, so its extra memory grows only linearly with TT. That is what made long context windows practical.

Backward: recompute instead of store

Backward needs attention probabilities, but retaining the entire grid is expensive. Save each row's log-sum-exp, then reconstruct probabilities tile by tile from queries and keys during backward.

WHAT THE BACKWARD PASS KEEPS FROM THE FORWARD PASS, PER HEAD (bf16 / fp32)T = 2,048P: 8 MiBlog-sum-exp: 8 KiBT = 8,192P: 128 MiBlog-sum-exp: 32 KiBT = 32,768P: 2 GiBlog-sum-exp: 128 KiBrecompute the scores tile by tile instead
Figure 2.46What the backward pass needs from the forward pass, per head. Standard attention keeps the full T × T grid P; FlashAttention keeps one log-sum-exp number per row and recomputes P's tiles.

That costs extra arithmetic, roughly redoing the forward computation. But arithmetic is cheap and memory traffic is expensive, so the backward pass ends up faster and uses a tiny fraction of the memory. "Recompute rather than store" is one of the most useful ideas in GPU programming, and FlashAttention is its best-known example.

Causal masking for free, at block level

Skip tiles wholly above the causal diagonal. Tiles below it need no causal masking; only tiles crossing it require cell-level checks.

CAUSAL MASKING AT BLOCK LEVEL: SKIP, FULL OR MASKED TILES4 × 4 blocks62.5% of tiles computed8 × 8 blocks56.3% of tiles computed16 × 16 blocks53.1% of tiles computedblue: full, no maskorange: diagonal, maskedwhite: skipped
Figure 2.47Tiles under a causal mask. Tiles above the diagonal are skipped, tiles below need no mask, and only diagonal tiles are masked. With more blocks, the computed share approaches one half.

#Section 31Three Versions

FlashAttention (2022) introduced the combination of tiling, online softmax and recomputation in the backward pass. FlashAttention-2 (Tri Dao, 2023) reorganized how work is divided among the GPU's processors, in particular parallelizing along the sequence dimension so that long sequences with small batches still keep every processor busy, and cut the non-matrix-multiply operations that GPUs run slowly. It is roughly twice as fast as the first version and reaches 50% to 73% of an A100's theoretical peak. FlashAttention-3 (Jay Shah, Tri Dao and colleagues, 2024) was written for NVIDIA's Hopper generation, such as the H100. It uses Hopper's asynchronous hardware to overlap loading the next tile with computing on the current one, and adds support for 8-bit floating-point (FP8) inputs.

THREE VERSIONS OF FLASHATTENTIONFlashAttention2022tiling, online softmax,recompute in backwardFlashAttention-22023better work split across the GPU,fewer non-matmul operations, ≈ 2× fasterFlashAttention-32024Hopper (H100): overlaps loadingwith compute, adds FP8
Figure 2.48Three versions of FlashAttention, each built on the previous one.

You rarely call FlashAttention directly. PyTorch's SDPA (Part V) dispatches to it automatically when your inputs qualify, and inference engines such as vLLM bundle their own variants. What matters is knowing what it requires and what it guarantees.

#Section 32Sharp Edges of FlashAttention

Exact, not approximate, but not bitwise identical. It computes the same mathematics in a different order. Floating-point addition rounds at every step, so results can differ in the last few digits from a hand-written version, the same way adding a column of numbers top to bottom and bottom to top can differ. Expect tiny numeric differences, not quality loss.

16-bit only. It is built for fp16 and bf16. With 32-bit inputs it will not run, and frameworks fall back quietly to slower code. Run attention under bf16 autocast.

Head size limits. The kernels are tuned for particular head sizes, up to 256 in FlashAttention-2. Unusual sizes are unsupported or slower. Keep head size at 64, 128 or 256.

Nondeterministic backward. In the backward pass, several processors add into the same gradient numbers in whatever order they finish (Chapter 1, Section 75). Results can vary very slightly between runs. Use the deterministic option when you need bitwise reproducibility, at some speed cost.

Packed sequences. When many short texts are packed together, padding each to the longest wastes work. FlashAttention's variable-length interface takes the real lengths, as cumulative offsets, and attends within each sequence only, with no padding at all.