Skip to content
mlmentorship

FlashAttention

Derive a mergeable softmax row, rescale its numerator and denominator across tiles, and distinguish mathematical equivalence, storage, traffic, and latency.

Published · 12 min read ·Core ·Intermediate
Reading depth

Summary

Attention needs a normalized weighted sum, not a permanently stored score matrix. FlashAttention tiles that computation to reduce global-memory storage and data movement while preserving the mathematical attention operator. Floating-point reduction order can change bits; validate numerical tolerance rather than claiming bitwise identity.

Task: one query sees scores with scalar values . Process one score/value pair per tile without retaining prior scores. Recover the same output as dense softmax, then change masking and the performance regime.

Use finite allowed scores and a float64 reference tolerance of for these checks. Production tolerances depend on dtype, shape, and kernel.

The mechanism

A materialized baseline writes score and probability matrices of size to high-bandwidth memory, HBM. The tiled algorithm keeps a score tile and row summaries in on-chip working storage. It still computes every allowed dense pair; memory traffic, auxiliary storage, arithmetic, and latency are different quantities.

For processed scores and value vectors , retain

Here is an unnormalized numerator; output is . For a new valid block, set

Changing reference from to multiplies every earlier exponential by . Rescaling both totals preserves their ratio and admits the new block under a common reference. Initialize , , and ; the first valid block has old-state scale zero. Skip entirely forbidden blocks without evaluating an undefined .

Processed tileMaximumDenominatorNumeratorOutput
Score , value
Then score , value

The second maximum rescales old totals by . Dense evaluation agrees: . Forgetting rescaling gives , a useful failing check.

Avoid quadratic intermediate round trips, not all memory traffic

Remove quadratic intermediate round trips, not all memory movementThe standard route writes and reads the score matrix. Tiled attention still reads inputs and writes outputs while keeping temporary scores on chip.Keep the fitting intermediate insidethe SRAM boundaryUnfused: intermediate write thenrereadSRAMHBMFused: on-chip intermediate reuseSRAMInput reads and output writes stillremain.
Derivation
The avoided HBM round trips belong to intermediates, not every tensorA declared two-byte-intermediate toy compares a materialized attention baseline with exact tiled attention. Scores and probabilities each incur one n-squared-element write and read in the baseline. Tiling avoids those global intermediates but still moves inputs, weights as applicable, and final output and retains dense quadratic arithmetic.Toy 2-byte intermediates; count onlyscore/probability trafficMATERIALIZEDTILED EXACTScores: n by nwrite 2n^2 bytesread 2n^2 bytestile stays onchipno global scorematrixProbabilities: n by nwrite 2n^2 bytesread 2n^2 bytesonline softmaxstateno global PmatrixWhat does not disappearQ, K, V, outputdense attentionworkQ, K, V, outputdense attentionwork
For these declared two-byte intermediates, four transfers total 8n^2 bytes in the baseline. Avoiding them does not eliminate all HBM traffic or quadratic arithmetic. Actual intermediate precision can differ.
Check: Which quadratic materializations does tiled attention avoid without eliminating all HBM reads and writes?
Read it this way: The standard route writes and reads the score matrix. Tiled attention still reads inputs and writes outputs while keeping temporary scores on chip.
Are QKV reads and output writes removed with temporary score storage?

Change masking

New task: the second score/value pair is future-only for this causal query. Exclude it before local reductions and skip that empty tile. Check: retained state stays , giving output , not . Use when: visibility, padding, or a window restricts the allowed pairs. This reference rejects a fully masked row; match the chosen library’s declared empty-row behavior rather than dividing by zero.

Change the performance regime

New task: compare a short sequence on a different GPU. Keep output tolerance checks and measure kernel time, launch overhead, utilization, and peak memory separately. Check: illustrative baseline microseconds versus tiled gives speedup , despite unchanged mathematical output. Those timings are invented inputs to the comparison, not measurements. Use when: shape or hardware changes the bottleneck; asymptotics cannot supply a universal crossover length.

Backward pass: trade memory for compute

Backward can recompute score/probability tiles from Q/K and saved row normalization information. It need not retain the entire probability matrix. Saved outputs, statistics, and RNG requirements depend on the algorithm and dropout convention. This is a kernel-level recompute-versus-store tradeoff, not cost-free memory removal.

Dense arithmetic remains . Auxiliary attention storage can be , linear in sequence length at fixed width. This does not imply linear HBM traffic or latency; tile sizes, on-chip capacity, and scheduling matter.

Reconstruct: does reducing quadratic storage make dense attention subquadratic in sequence length?

Answer

No. The algorithm still evaluates the allowed dense query/key pairs. Sparse attention changes that pair set; linear-attention methods change the operator or its representation.

Learning objective

Keep running row statistics while discarding each temporary score tile

Keep the running statistics, discard temporary score tilesThese illustrative tiles retain a maximum, normalizer, and weighted-value accumulator. Stable rescaling merges both tiles to the same weighted output as complete softmax. Temporary score storage can then be discarded.Merge retained statistics, thendiscard temporary scoresTile 1: retain M, L, O21.1353.135Tile 2: retain M, L, O115Merge at M=2: L=1.503, O=4.975Output O/L = 3.309
Derivation

The grid represents the full score matrix; only a query-key tile enters working storage here. Each tile updates row summaries before the next key/value block arrives.

FlashAttention streams one score tile through SRAM instead of materializing the full matrix The conceptual score grid highlights one Bq by Bk tile. HBM supplies query and key/value blocks to on-chip storage. The running maximum m, denominator ell, and unnormalized numerator u are updated. Output O equals u divided by ell. The final output block and row statistics are written, not the global score matrix. Global score matrix S n query rows x n key columns K blocksQ blocks K1K2K3K4 Q1Q2Q3Q4 SijOnly this tile is resident One SRAM tile at a timestream blocks, update state, evict the tile HBMQiKj, Vjload blocks GPU SRAM QiKj, VjSij Bq x dBk x dBq x Bk streaming softmax updatemi, elli, ui -> next tile Final write: Oi and row statistics; never S
the left grid is conceptual, not a retained global matrix. A query block consumes key/value tiles, updating its maximum, denominator, and unnormalized numerator. After all allowed keys, divide numerator by denominator and write the output. Actual on-chip residency and saved statistics depend on the kernel version.
Check: Which state survives between tiles? Which large matrix is never retained globally?
Read it this way: These illustrative tiles retain a maximum, normalizer, and weighted-value accumulator. Stable rescaling merges both tiles to the same weighted output as complete softmax. Temporary score storage can then be discarded.
Which retained quantities let a second tile merge without keeping the first score tile?

What an interviewer expects you to say

Report mathematical equivalence, numerical tolerance, arithmetic, auxiliary memory, traffic, and observed latency as distinct claims. Memory-boundedness depends on the actual shape, device, and implementation.

At , , the term ratio compares tensor sizes only. It is not a measured traffic ratio or speedup.

The original normalized-output recurrence is an alternative state convention:

m_new = max(m_i, max(S_ij))
ell_new = exp(m_i - m_new) * ell_i + sum(exp(S_ij - m_new))
O_new   = (exp(m_i - m_new) * ell_i * O_i + exp(S_ij - m_new) @ V_j) / ell_new

Here is already normalized; multiplying by reconstructs its numerator before merging. Do not substitute unnormalized into that recurrence unchanged.

Common confusions

Mathematical equivalence does not imply identical floating-point bits or equal low-precision errors. Validate forward and backward against a stable reference across masks, extreme logits, and dtypes. Recomputation increases some arithmetic while removing stored intermediates.

Why interviewers care

FlashAttention-2 changes work partitioning; FlashAttention-3 adds hardware-oriented asynchrony and low-precision techniques. Check supported device, head dimensions, masks, and dtype in the version being deployed. Low-precision variants need their own error characterization.

Reading list

  • FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Dao et al., 2022)
  • FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (Dao, 2023)
  • FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision (Shah et al., 2024)
  • Tri Dao’s implementation notes complement the papers; they are not a substitute for workload-specific measurements.

Related: speculative decoding, LayerNorm versus BatchNorm, and production LLM inference design.