FlashAttention
Follow tiled exact attention and the online-softmax invariant that avoids a full intermediate score matrix.
Jump to a section
Attention spends its time moving scores
For one head over 4,096 tokens, the score matrix has 16.8 million entries, 32 MiB in fp16. A standard implementation writes it to GPU main memory (HBM), reads it back to take the softmax, writes the probabilities, and reads them again to multiply by . The arithmetic on each entry is a handful of operations; the bytes moved per entry are what set the speed.
The FlashAttention paper puts numbers on the gap. An A100 has 40 to 80 GB of HBM with 1.5 to 2.0 TB/s of bandwidth, and 192 KB of on-chip SRAM in each of its 108 streaming multiprocessors, with bandwidth estimated around 19 TB/s. The SRAM is an order of magnitude faster and thousands of times smaller.
FlashAttention is a way of computing exact softmax attention that keeps the score matrix out of HBM entirely. It is a kernel, not a new attention rule: the output is the same function as standard attention, up to floating-point rounding. An attention architecture and the kernel that executes it are separate choices, and a dense layer running FlashAttention still does quadratic arithmetic in sequence length.
Tiles that fit on chip
The kernel splits , and into blocks and loads them into SRAM. For each pair of a query block and a key block it computes a tile of scores, turns them into weights, and adds their contribution to the output, all on chip. A 64 by 64 tile holds 4,096 scores, 16 KiB even in fp32, which fits easily in SRAM. Doubling the sequence length quadruples the full matrix but leaves the tile the same size.
Splitting a matrix product into tiles is routine. The hard part is the softmax. Each query's weights are normalized by a sum over the entire row, and the kernel sees that row one tile at a time. When a later tile contains a larger score than anything seen so far, every earlier contribution was computed against the wrong reference and has to be corrected.
Same attention. Less memory traffic.
Tiles of Q, K and V move through fast on-chip memory. An online softmax combines their contributions without storing the full score or probability matrix in high-bandwidth memory.
- Dense score entries / head
- 16,777,216
- One 64 × 64 score tile
- 4,096
Element counts with fixed head width 64. Excludes model weights, other intermediates, batching and layers; not peak GPU memory or a speed benchmark.
Exact dense softmax attention up to floating-point rounding. Arithmetic remains quadratic in sequence length; this is not a linear-attention architecture. Dao et al., 2022
The online softmax update
For one query row, keep three running quantities: the maximum score , the denominator , and the unnormalized weighted sum of values . Start with and . For each new block of scores with values :
After the last block, the output is . Subtracting the running maximum keeps every exponent at or below zero, so nothing overflows, and the factor moves the old sums onto the new reference.
A concrete case: a new tile raises the running maximum from 5 to 10. Both the old numerator and the old denominator must be multiplied by before the new tile's contributions are added. Rescaling only one of them changes the result.
The same care applies to what you store. If you keep a normalized running output instead of , its update has to include the old denominator as well. Mixing the two conventions is a common implementation bug.
Recomputing instead of storing
Training needs the attention probabilities again in the backward pass, and storing them would bring back the matrix. FlashAttention stores only the output and the per-row softmax statistics, then recomputes the scores tile by tile from , and during the backward pass. That costs extra FLOPs and saves far more in memory traffic, which is the trade the whole design is built on.
The backward pass has numerical traps of its own. Each row of the softmax gradient must sum to zero, and rounding can break that identity; see softmax and cross-entropy numerics.
The paper's analysis makes the saving precise. For sequence length , head dimension and SRAM size , standard attention needs HBM accesses, and FlashAttention needs . With between 64 and 128 and around 100 KB, is many times smaller than . Memory use beyond the inputs and output grows linearly with sequence length instead of quadratically.
The arithmetic count does not change. Dense attention still forms every pairwise interaction, so FLOPs remain quadratic in . The paper reports a 15% end-to-end training speedup on BERT-large at sequence length 512 against the MLPerf 1.1 record, 3x on GPT-2 at length 1K, and 2.4x on Long Range Arena at 1K to 4K.
In code
This scalar-value example checks the online invariant with two-score tiles. The scores 1001 and 1002 would overflow a naive exp; the running maximum keeps them in range. It is a correctness illustration, not a GPU kernel.
1from math import exp
2scores, values = [1., 2., 1001., 1002.], [2., -1., 4., 8.]
3m, denominator, numerator = float('-inf'), 0., 0.
4for start in range(0, len(scores), 2):
5 block = scores[start:start + 2]
6 new_m = max(m, max(block))
7 scale = exp(m - new_m)
8 denominator *= scale
9 numerator *= scale
10 for offset, score in enumerate(block):
11 weight = exp(score - new_m)
12 denominator += weight
13 numerator += weight * values[start + offset]
14 m = new_m
15online = numerator / denominator
16weights = [exp(s - max(scores)) for s in scores]
17reference = sum(w*v for w,v in zip(weights, values)) / sum(weights)
18assert abs(online - reference) < 1e-12
19print(online)When the second tile arrives, the maximum jumps from 2 to 1002 and the scale factor is , which underflows to zero. That is the correct answer here: the first two scores carry no weight in fp64 next to the last two.
What it is not
Not sparse attention. Standard FlashAttention computes every query-key interaction. Sparsity decides which interactions to keep, which is a separate design choice and changes the function being computed.
Not linear attention. Linear attention replaces softmax over the token history with a fixed-size recurrent state. That changes the model; FlashAttention changes only how the same model runs.
Not a guaranteed speedup. Tiling, kernel fusion and recomputation target memory traffic and temporary storage. The actual gain depends on the GPU, the shapes, the dtype, the masking pattern and the kernel version, so measure it on your workload.
Not what "Flash" means in every model name. DeepSeek V4.1-Flash is not a FlashAttention paper. Its documented attention system uses compression and sparse indexing; the model breakdown covers it separately.
Sources and further reading
- Dao et al., FlashAttention (2022): the tiled exact algorithm, its IO analysis and the reported speedups.
- Official implementation and supported kernels: the maintained code and the GPUs and dtypes it supports.