FlashAttention: exact softmax without the full score matrix
FlashAttention
Derive online normalization, compare blocked and dense attention, and separate IO savings from arithmetic.
flash-attentionYou can finish a weighted average without keeping every weight
Suppose three attention scores are zero, the natural logarithm of two, and the natural logarithm of four. Their unnormalized weights are 1, 2 and 4. With values 1, 3 and 8, the final weighted average is 39/7. You can calculate it by keeping all three weights, or by combining small blocks while carefully rescaling the running totals.
FlashAttention uses this kind of exact online normalization within a hardware-aware tiled attention algorithm. It reduces transfers between large, slower GPU memory and smaller, faster on-chip memory, rather than replacing softmax with a different function or dropping arbitrary keys. The dense attention operation is the one described in Attention Is All You Need.
Our program checks the forward numerical identity in NumPy. It is not a fused GPU kernel and does not measure the paper’s speedups. Keeping that distinction clear is essential: a correct blocked Python loop may be slower than a dense matrix operation while still teaching the mathematical idea accurately.
Rescale old totals whenever the maximum changes
For queries and keys of width , the scaled attention result with mask is:
Here masks permit or exclude entries, and softmax acts on each row. Focus on one query. Over the permitted scores already processed, store a maximum , a scalar normalizer and a vector numerator :
Subtracting the maximum protects the exponential from overflow. A new block may contain a larger score. Simply adding weights normalized by the new block’s own maximum would put old and new values on different scales. First choose a common maximum:
Then convert the old denominator to the new exponential scale and add the new block:
The vector numerator needs the same rescaling:
Why is this exact in real arithmetic? Multiplying an old term by gives . Every old and new term is now represented relative to the same maximum. Induction over blocks preserves the definitions of and . At the end:
Initialize to negative infinity and to zero. Skip a block with no permitted entries, so its nonexistent maximum is never subtracted from another negative infinity. If an entire row is masked, normalized attention has no distribution. Our teaching API explicitly returns a zero vector for that row; that is a convention, not a derivation of a valid softmax probability vector.
FlashAttention’s original analysis considers sequence length , head dimension and SRAM capacity , measured in scalar storage units. Under its stated range, the HBM access bounds are:
This is a memory-access analysis under a specified memory hierarchy. If and SRAM capacity remain fixed while grows, the displayed FlashAttention expression is still quadratic in . Do not turn an IO improvement into a blanket claim of linear-time attention. Exact dense forward arithmetic remains on the order of . The original algorithm also uses recomputation in backward to avoid storing the full score/probability matrices; our program implements no backward pass.
Check exact output with several block sizes
The complete NumPy example processes one query at a time and streams key/value blocks. It compares blocks of width 1, 2, 3 and 7 against dense attention for seven queries, seven keys and a causal mask. Different query and key counts are also covered by independent tests using explicit masks.
"""Forward-only blocked exact attention in NumPy; not a fused CUDA implementation."""
import json
import numpy as np
def dense(q,k,v,mask):
scores=q@k.T/np.sqrt(q.shape[-1]);out=np.zeros((len(q),v.shape[-1]))
for i in range(len(q)):
keep=mask[i]
if keep.any():
s=scores[i,keep];p=np.exp(s-s.max());out[i]=(p/p.sum())@v[keep]
return out
def blocked(q,k,v,mask,block=2):
if type(block) is not int or block<1:
raise ValueError('Block width must be a positive integer')
if q.ndim!=2 or k.ndim!=2 or v.ndim!=2 or q.shape[1]!=k.shape[1] or len(k)!=len(v) or mask.shape!=(len(q),len(k)):
raise ValueError('Incompatible attention shapes')
if not all(np.isfinite(a).all() for a in [q,k,v]):
raise ValueError('Finite inputs required')
outputs=np.zeros((len(q),v.shape[1]));traces=[];peak=0
for i,row in enumerate(q):
m=-np.inf;l=0.;u=np.zeros(v.shape[1]);trace=[]
for start in range(0,len(k),block):
end=min(start+block,len(k));keep=mask[i,start:end]
if not keep.any():
continue
scores=row@k[start:end].T/np.sqrt(q.shape[1]);peak=max(peak,len(scores))
scores=scores[keep];values=v[start:end][keep]
new_m=max(m,float(scores.max()))
factor=np.exp(m-new_m)
p=np.exp(scores-new_m)
l=factor*l+p.sum();u=factor*u+p@values;m=new_m
trace.append(dict(end=end,max=float(m),normalizer=float(l),output=(u/l).tolist()))
if l>0:outputs[i]=u/l
traces.append(trace)
return outputs,dict(peak_score_elements=peak,traces=traces)
def main():
rng=np.random.default_rng(41);q=rng.normal(size=(7,3));k=rng.normal(size=(7,3));v=rng.normal(size=(7,2))
mask=np.tril(np.ones((7,7),dtype=bool));ref=dense(q,k,v,mask);rows=[]
for b in [1,2,3,7]:
out,info=blocked(q,k,v,mask,b)
rows.append(dict(block=b,error=float(np.max(abs(out-ref))),peak_score_elements=info['peak_score_elements']))
_,info=blocked(q,k,v,mask,2)
print(json.dumps(dict(results=rows,dense_score_elements=49,last_row_trace=info['traces'][-1],
outputs=ref.tolist(),all_masked_policy='zero output, not a normalized probability distribution')))
if __name__=='__main__':
main()
All four block widths agree with the dense reference within ordinary float64 rounding; the largest reported differences are at the scale of . A width of two leaves a final partial key block when there are seven keys. That boundary is exercised rather than assuming the sequence divides evenly.
For the hand example from the opening, after the first two scores the normalized result is 7/3. After the third, the maximum is the logarithm of four, the normalizer is 7/4 and the result is 39/7. Another test uses scores 1000, 999 and −1000 with values 3, 7 and 9; subtraction of the running maximum yields a finite result instead of overflowing the exponential.
peak_score_elements counts the width of the current score block only. It is not measured process memory. For teaching inspection, this implementation accepts a complete boolean mask and retains per-row intermediate traces; those can use quadratic space. The dense reference also allocates a full score matrix. Therefore the whole demonstration program is not a linear-memory implementation or a reproduction of GPU allocation behavior.
This implementation computes dense query–key block products before applying the mask; its arithmetic therefore follows the dense pair count, even for masked entries. A fused kernel must additionally arrange tiles, reuse SRAM data and schedule operations efficiently. Python timing here would answer a different question from the paper’s hardware experiments.
Exact does not mean identical floating-point bits
Different block orders change the order of addition and the points at which rescaling occurs. In finite precision, results can differ slightly even when both compute the same real-valued function. Test with justified numeric tolerances, multiple masks and extreme but finite scores; do not silently accept a large mismatch as “rounding.” Extremely large inputs can still overflow the dot product before softmax stabilization.
Dropout, backward gradients, mixed precision and special masking layouts require additional implementation work. Fully masked rows need an explicit policy consistent with the surrounding model. The zero-output convention in this example must not be confused with a probability distribution summing to one.
The author’s repository contains later FlashAttention versions and hardware-specific implementations. This article explains the original 2022 online-normalization and IO argument. It makes no claim that a particular current GPU, package version or workload will achieve a fixed multiplier. MQA/GQA can reduce KV heads while FlashAttention changes execution; neither mechanism substitutes for evaluating model quality.
Combine the blocks correctly
- Why is averaging independently normalized block outputs generally wrong? Answer: Blocks can have different total unnormalized probability mass. Their outputs must be weighted using normalizers on a common exponential scale; equal averaging discards that information.
- With scores and values , compute the final result. Answer: The weight sum is 7 and weighted value sum is 39, giving 39/7. Relative to maximum , the normalizer is 7/4 and the numerator is 39/4, with the same ratio.
- What should happen when one tile has no permitted keys? Answer: Skip it, leaving the running state unchanged. If all tiles are empty, no normalized distribution exists; this API explicitly returns zero rather than dividing by zero.
- If block width is two, may
peak_score_elements=2be reported as the program’s peak memory? Answer: No. It counts only current score entries. Inputs, output, masks, stored diagnostic traces, temporaries and the dense reference consume additional memory; GPU allocation requires separate measurement.
A mathematical identity becomes a systems algorithm
The original attention paper defines the scaled dot-product operation. Dao and colleagues retain exact attention while organizing its computation around the memory hierarchy: tiled forward calculation, online normalization and selective recomputation for backward. The IO theorem and implementation together explain why counting FLOPs alone can miss an important bottleneck.
Our independently tested forward recurrence covers the identity and its boundary conventions. It does not establish the original kernel’s performance or gradients. To extend the exercise, first add an independently checked backward implementation, then benchmark a specified kernel, hardware, dtype, batch and sequence regime. Keep correctness, peak allocation and throughput as separate measurements.
Make a prediction, then check
Does dense FlashAttention eliminate quadratic pairwise attention arithmetic?
Learning objectives
- Combine block maxima, normalizers and weighted sums correctly.
- Check causal masks, extreme scores and fully masked rows.
- Interpret SRAM-dependent IO bounds without claiming linear compute.
Prerequisites & connections
Explore related knowledge →References
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — v1
Tri Dao; Daniel Y. Fu; Stefano Ermon; Atri Rudra; Christopher Ré · 2022 - Attention Is All You Need (v5)
Ashish Vaswani; Noam Shazeer; Niki Parmar; Jakob Uszkoreit; Llion Jones; Aidan N. Gomez; Łukasz Kaiser; Illia Polosukhin · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author visually read FlashAttention v1 PDF4–6/sections2.2–3.2/Algorithm1/Theorems1–2; reused exact Attention-v5 source. Seven paired equations and four explained exercises. Online m/l/u recurrence, dense/blocked equivalence, causal/random/full masks, partial tiles, extreme scores and 39/7 oracle verified. Stored masks/traces preclude whole-program linear-memory claim; no CUDA timing or backward replication.
- Single AI author visually read FlashAttention v1 PDF4–6/sections2.2–3.2/Algorithm1/Theorems1–2; reused exact Attention-v5 source. Seven paired equations and four explained exercises. Online m/l/u recurrence, dense/blocked equivalence, causal/random/full masks, partial tiles, extreme scores and 39/7 oracle verified. Stored masks/traces preclude whole-program linear-memory claim; no CUDA timing or backward replication.
- Four computed SVG variants per topic;12 numeric/geometry tests and36 responsive cases passed. Twelve final Chinese-mobile/English-desktop screenshots all directly inspected after revisions. Full article acceptance recorded separately.
Source locations checked:
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — v1 · Visually read PDF4–6, sections2.2–3.2 and Algorithm1, Theorems1–2: online normalization, tiling, recomputation and SRAM-dependent IO bound. Forward NumPy teaching code is not a CUDA kernel or measured memory benchmark.
- Attention Is All You Need (v5) · Read sections3.2.1-3.2.3; PDF4/5 viewed. v5 explicitly includes output projection unlike the inspected v1 formula. No translation benchmark reproduction.
Related topics