ELLMEngineering Large
Language Models
Download PDF

Chapter 32

FlashAttention and IO-Aware Exact Attention

On this page

FlashAttention computes dense attention through a tiled memory schedule that avoids writing the quadratic score and probability matrices to HBM.

Online softmax made the merge rule available. FlashAttention is that rule applied to attention tiles so the running example's prefill path never writes S or P to HBM. Exact here means the same dense-attention operation without a sparsity or low-rank approximation; floating-point order and kernel precision can still change numerical results.

Attention combines QK scores, masking and softmax, then a weighted V reduction. The performance question is which intermediates must cross HBM.
Open full diagram ↗

Attention combines QK scores, masking and softmax, then a weighted V reduction. The performance question is which intermediates must cross HBM.

The naive schedule

For one head, standard attention is:

2026-10-12T12:02:55.793920 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.799926 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.804571 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

A naive implementation writes S to HBM, reads it for softmax, writes P, reads P for the V product, and writes O. S and P each contain sequence^2 elements.

Even if the GEMMs are efficient, moving quadratic intermediates can dominate memory and prevent long contexts from fitting.

Running-example HBM contrast

For one head during prefill with S_q = 2048 and FP16 scores:

  • S or P alone is 2048^2 * 2 = 8 MiB per head;
  • across H = 32 heads, one complete score or probability tensor is 256 MiB;
  • merely storing both tensors consumes 512 MiB, and writing then rereading each produces at least 1 GiB of quadratic HBM traffic before counting Q, K, V, or output traffic;
  • FlashAttention keeps per-row state (m, l) and a query-tile output accumulator on chip, and writes an output of size S_q * d. Saved attention intermediates are linear in sequence length. Total HBM traffic is not necessarily linear: different query tiles may reread K/V, with the amount governed by tile size, on-chip capacity, and cache reuse.

The arithmetic may increase because tiles are rescaled and scores are recomputed in backward. The potential wall-clock gain comes from reducing traffic on a limiting memory path; short sequences or unfavorable tile shapes may not benefit.

Tiled forward algorithm

Partition Q into row tiles and K/V into column tiles. For each Q tile:

  1. load Q and initialize per-row maximum m, sum l, and output accumulator o;
  2. load a K/V tile;
  3. compute local scores with tensor-core or SIMT matrix multiply;
  4. apply scale, causal or explicit mask, and local row maxima;
  5. rescale old state and add local exponentials;
  6. update the output accumulator with local probabilities times V;
  7. continue across K/V tiles;
  8. normalize and store O plus compact row statistics.

Q can remain on chip while K/V tiles stream through, or the work can be repartitioned based on sequence length and hardware resources.

Deriving the output recurrence

Suppose existing state uses reference max m_a, denominator l_a, and unnormalized output o_a = sum exp(s_i - m_a) v_i. A new tile has state (m_b, l_b, o_b).

Set:

2026-10-12T12:02:55.707192 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.807691 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.811474 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Then:

2026-10-12T12:02:55.814823 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.817937 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The normalized output is o / l. Every term is now expressed relative to the same maximum.

Merge independently computed attention partitions

A key partition stores (m,l,u), where m=max(scores), l=sum(exp(score-m)), and vector u=sum(exp(score-m)*value). To merge partitions A and B, set m=max(m_A,m_B), a=exp(m_A-m), and b=exp(m_B-m). Then l=a*l_A+b*l_B and u=a*u_A+b*u_B; normalize only once, as u/l. This is the same algebra needed by split-K decode and distributed context attention.

An empty partition has l=0 and u=0; return the other partition directly before subtracting maxima. If both are empty, retain an empty state and apply the API's masked-row policy at finalization. Evaluating exp(-infinity-(-infinity)) first creates NaNs even though the mathematical partition contributes zero.

Merging normalized local outputs requires the weights a*l_A and b*l_B. Taking their arithmetic mean gives equal weight to partitions rather than to the softmax denominator. The merge is associative over exact real arithmetic, so partitions can form a tree; floating-point reassociation changes rounding and need not be bitwise reproducible. The companion algebra test permutes partitions, includes an empty shard, and compares with one dense softmax-weighted sum.

Causal and ragged workloads

For causal attention, a Q tile does not need future K/V tiles. Diagonal tiles require element-level masking; tiles entirely above the causal diagonal can be skipped. This creates different work per Q tile, so static assignment can leave tail imbalance.

Ragged batches add per-sequence lengths and offsets. Pack sequences to avoid padding, but ensure no tile crosses sequence identity. Sort or bucket by length only if reordering cost and output restoration are controlled.

Work partitioning

The original IO schedule is only the first step. Efficient implementations reduce non-matmul scalar work, increase parallelism across sequence tiles, and assign warp roles to minimize shared-memory exchange.

At short sequence or small batch, there may be too few heads and Q tiles to occupy the GPU. Splitting one head across more blocks increases parallelism but requires combining partial softmax/output states. The merge uses the same max-and-sum recurrence.

Backward equations

Let upstream gradient be dO. The conceptual backward is:

2026-10-12T12:02:55.821345 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.825536 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.830527 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.836446 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
2026-10-12T12:02:55.840989 image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

The kernel recomputes score tiles and P from Q, K, and saved row statistics rather than reading a stored quadratic P. This adds arithmetic and saves quadratic storage and HBM traffic.

Backward partitioning is difficult because K and V receive contributions from many Q tiles. Strategies assign ownership to avoid atomics, use separate kernels, or accumulate partials with controlled reductions. The fastest plan depends on head dimension, sequence, and batch.

What must be saved

At minimum, backward needs Q, K, V or access to recompute them, output O or equivalent state for some formulations, per-row log-sum-exp or max/sum statistics, masks or lengths, scale, and dropout RNG information if dropout is used.

Saving less increases recomputation. Saving more increases activation memory. The chosen boundary belongs in the model's activation-checkpointing plan.

Dropout and reproducibility

Attention dropout must regenerate the same mask in backward. Counter-based RNG can derive mask bits from batch, head, row, column, and a seed/offset. Tiling and work partition changes must not silently change the logical random mask when reproducibility is promised.

Training versus decode attention

FlashAttention-style training and prefill process many queries and exploit matrix-multiply reuse. Decode has one new query per sequence and reads a long KV cache. It is usually memory-bandwidth and latency sensitive, with a very different optimal schedule.

Calling every fused attention kernel "FlashAttention" hides this distinction. State whether the workload is training, prefill, or decode, and model the corresponding shapes.

For the running example's decode step, each of B = 8 sequences contributes one query row of length d = 128 per head and must read S = 4096 cached keys and values. With GQA, H = 32 query heads share H_kv = 8 KV heads, so each KV stream is reused by four query heads. The kernel problem is no longer "avoid S^2 materialization"; it is "stream paged KV efficiently and keep online softmax state compact."

Fusion boundaries

Useful attention fusion may include Q/K scaling, RoPE, masking, bias, softmax, dropout, or output transformations. Fusion loses when it inflates live state, reduces occupancy, complicates recomputation, or creates a variant explosion.

Design Exercises

  1. Why can FlashAttention perform more arithmetic yet run faster?
  2. Derive the running max, sum, and output update.
  3. What must be saved for backward?
  4. How does causal masking affect work partitioning?
  5. When does attention fusion reduce performance?
  6. Why is a decode-attention kernel different from a training kernel?

Worked Solutions

1. More arithmetic, less time

FlashAttention recomputes or performs extra scalar work but removes reads and writes of quadratic score/probability matrices. When the avoided HBM traffic controls runtime, spending additional FLOPs can lower wall time while reducing saved attention intermediates. The gain depends on sequence length, tile shape, and hardware; it is not guaranteed for every attention call.

2. Running state

Merge old and new tile maxima into m = max(m_a, m_b). Rescale the old denominator and output by exp(m_a - m) and the new tile by exp(m_b - m). Add the rescaled sums and weighted outputs. This preserves the exact softmax numerator and denominator relative to one stable maximum.

3. Backward state

The backward derivation above identifies the saved Q/K/V, output, row-normalization statistics and mask/scale/RNG metadata. Recompute score tiles instead of storing the full probability matrix.

4. Causal work partitioning

Q tiles near the beginning attend to fewer K/V tiles than later Q tiles, and tiles above the causal diagonal are skipped. This creates triangular work and tail imbalance. Assign tiles dynamically, process longer rows first, or split long rows across blocks and merge partial states. Diagonal tiles still need fine-grained masking.

5. Fusion losses

Compare saved launches/intermediate bytes with added register/shared-memory pressure, lost library paths, shape padding and compilation variants. Reduced launch count alone cannot decide whether fusion wins.

6. Decode versus training

Training/prefill has many query rows and large tiles, enabling compute reuse and tensor-core efficiency. Decode has one new query per active sequence, streams a long and often paged KV cache, and is commonly bandwidth- and latency-bound. Its schedule emphasizes KV layout, vectorized loads, batch mapping, and low launch overhead rather than quadratic-score avoidance.

Backward and masked-row acceptance

Check backward independently: perturb Q/K/V in FP64, including a chunk boundary and masked key, and compare finite differences with autodiff before the target kernel. Use the differentiable decoder and online-merge references as separate oracles.

All-masked softmax can produce NaNs. Define both its output and backward policy; a zero forward output alone is insufficient. Reference and optimized paths must agree before tolerances are meaningful.