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 tile | Maximum | Denominator | Numerator | Output |
|---|---|---|---|---|
| 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
Derivation
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
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.
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.