Flash attention explained: exact attention, 2–4× faster, by moving less memory
At 128K tokens, standard attention's score matrix is 32 GiB for one head in one layer. FlashAttention never writes it to GPU memory: it streams small tiles through on-chip SRAM, keeps a running max and sum for softmax, and recomputes instead of storing. Same exact result, memory linear in sequence length, 2–4× faster. The A100 numbers, FlashAttention-2, -3 and -4, the exponential bottleneck on new GPUs, and where you meet it in PyTorch, vLLM, Ollama and llama.cpp.
On this page
- The number: why 32 GiB
- Standard attention: four trips with the biggest thing in the kitchen
- FlashAttention: trays, not bowls
- The running tally: online softmax
- Exact, not an approximation
- More math, and faster: recomputation
- FlashAttention-2, -3 and -4
- The twist: on new GPUs, the bottleneck is eˣ
- Where you meet it
- Flash attention vs paged attention
- The short version
- Sources
At a 128K-token context, the attention score matrix for one head in one layer has 131,072 × 131,072 = 17.2 billion entries. At two bytes each (FP16), that’s 32 GiB. Standard attention writes that matrix to GPU memory, reads it back, writes the softmax of it, and reads that back too.
FlashAttention never writes it at all. It computes the same result, exactly, 2–4× faster than standard attention, by moving less memory. This post explains how, with the numbers from the papers. Nothing here was run or benchmarked by us; every figure is quoted from a linked source or is arithmetic shown on the page.
The number: why 32 GiB
Attention, in one line: queries times keys give a grid of scores, softmax turns each row into weights, and the weights mix the values: O = softmax(QKᵀ) V. For a sequence of N tokens, the score grid S = QKᵀ is N × N. (If attention or the KV cache is new to you, start with how the KV cache works.)
The arithmetic for one head at 128K tokens:
| Step | Value |
|---|---|
| N | 128K = 131,072 tokens |
| N² scores | 17,179,869,184 |
| × 2 bytes (FP16/BF16) | 34,359,738,368 bytes = 32 GiB (34.4 GB) |
| × 32 heads per layer (Llama 3.1 8B) | 1 TiB, if one layer’s matrices were all materialised at once |
| K + V for that head (131,072 × 128 × 2 B × 2) | 64 MiB |
The scratch matrix is 512 times bigger than the keys and values it’s built from (in general N / 2d). Its size grows with the square of the context: 4× the tokens, 16× the memory.
Standard attention: four trips with the biggest thing in the kitchen
The FlashAttention paper (Dao et al., 2022) spells out the standard implementation as Algorithm 0:
- Load Q, K from HBM, compute S = QKᵀ, write S to HBM.
- Read S from HBM, compute P = softmax(S), write P to HBM.
- Load P and V from HBM, compute O = PV, write O to HBM.
HBM is the GPU’s main memory: big, but far from the compute units. Picture a chef with a tiny countertop and a huge fridge across the room. Standard attention makes every score, carries the whole bowl to the fridge, fetches it for softmax, carries it back, and fetches it again to mix the values. Four trips with an N × N bowl.
How far is the fridge? The paper gives the A100’s memory hierarchy:
| Size | Bandwidth | |
|---|---|---|
| HBM (the fridge) | 40–80 GB | 1.5–2.0 TB/s |
| On-chip SRAM (the countertop) | 192 KB per SM × 108 SMs ≈ 20 MB | “estimated around 19TB/s” |
The countertop is about 13× faster and about 2,000× smaller (40 GB vs 20 MB). The paper’s point: “most operations in Transformers are bottlenecked by memory accesses”. The slow part isn’t the math. It’s the walking.
FlashAttention: trays, not bowls
FlashAttention is “an IO-aware exact attention algorithm that uses tiling to reduce the number of memory reads/writes between GPU high bandwidth memory (HBM) and GPU on-chip SRAM” (abstract). In kitchen terms, it brings small trays:
- Load a tile of K and V and a tile of Q into SRAM.
- Compute that tile’s scores, use them immediately against V, then throw those scores away.
- Only the finished output O goes back to HBM. The N × N matrix never exists in HBM.
Everything happens in one fused GPU kernel. The paper proves standard attention needs Θ(Nd + N²) HBM accesses while FlashAttention needs Θ(N²d²/M), where d is the head dimension (64–128) and M the SRAM size (around 100 KB), so d² is many times smaller than M. It also proves no exact attention algorithm can do asymptotically better over all SRAM sizes.
The running tally: online softmax
There’s a catch. Softmax needs a whole row before it can divide: the row’s biggest score (subtracted for numerical stability) and the sum of the exponentials. With tiles, you see the row a piece at a time.
The fix is a running tally: keep the largest score so far (m) and a running sum (ℓ). When a new tile brings a bigger maximum, shrink the old sum to match, then add the new terms:
m_new = max(m_old, max(tile))
ℓ = ℓ · e^(m_old − m_new) + Σ e^(x − m_new)
Example with one row of nine scores arriving in three tiles, [2.1, 0.4, 3.0], [1.2, 5.3, 0.7], [2.2, 4.1, 0.9]: m goes 3.0 → 5.3 → 5.3 and ℓ goes 1.48 → 1.18 → 1.53. The 1.53 is exactly what you get computing over the whole row at once. The output accumulator is rescaled the same way, and you divide once at the end.
This trick is older than FlashAttention: Maxim Milakov and Natalia Gimelshein at NVIDIA published it in 2018 as “Online normalizer calculation for softmax”, to make plain softmax faster (up to 1.3×). FlashAttention cites it.
Exact, not an approximation
It’s in the title: “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness”. Theorem 1 says the algorithm “returns O = softmax(QKᵀ)V”, and in the paper’s training runs it “produces the same training / validation curves” as the baselines. The FlashAttention-2 paper describes the original as giving its speedup “with no approximation”. It’s fast because it moves less memory, not because it skips any of the math. Approximate attention methods (sparse, low-rank) are a different family; the paper notes many of them didn’t deliver wall-clock speedups because they ignored memory access.
More math, and faster: recomputation
Training needs S and P again in the backward pass, and FlashAttention never stored them. So it stores only the output and the softmax statistics (m, ℓ) and recomputes the scores from Q, K, V tiles in SRAM. That’s extra math. It’s still faster, because math is cheap and the walking isn’t:
On GPT-2 medium (Figure 2 of the paper): 75.2 GFLOPs instead of 66.6, but 4.4 GB of HBM traffic instead of 40.3, and 7.3 ms instead of 41.7: 5.7× faster while doing 13% more math. The paper reports up to 7.6× on the attention computation for GPT-2, 3× end-to-end GPT-2 training at 1K tokens, 15% on BERT-large against the MLPerf 1.1 record, and memory that “grows linearly with sequence length”, up to 20× less than exact baselines in its benchmarks.
That linear memory is why flash attention is the trick that makes long context fit (our Ollama context-length post leans on it): no N × N scratch, only Q, K, V, O and two numbers per row.
FlashAttention-2, -3 and -4
| Version | Year, GPU | Reported by the authors |
|---|---|---|
| FlashAttention-2 | Jul 2023, A100 | ~2× faster than FlashAttention, 50–73% of the A100’s theoretical peak FLOPs/s (FA1: 25–40%) |
| FlashAttention-3 | Jul 2024, H100 | 1.5–2.0× over FA2, up to 740 TFLOPs/s in FP16 (75% utilisation), close to 1.2 PFLOPs/s in FP8 |
| FlashAttention-4 | Mar 2026, Blackwell B200 | up to 1,613 TFLOPs/s in BF16 (71%), 1.3× over cuDNN 9.13, 2.7× over Triton; written in CuTe-DSL in Python |
The twist: on new GPUs, the bottleneck is eˣ
Softmax needs an exponential for every score. The FlashAttention-3 paper puts numbers on it: an H100 SXM5 has “989 TFLOPS of FP16 matmul but only 3.9 TFLOPS of special functions such as exponential”. With head dimension 128 there are 512× more matmul FLOPs than exponentials, but the exponential has 256× lower throughput, so it “can take 50% of the cycle compared to matmul”.
Blackwell made it worse: the B200 doubles tensor-core throughput over the H100 (2.25 vs 1 PFLOPS in FP16/BF16), while the exponential unit stays at 16 operations per clock per SM, “the same as Hopper”. So FlashAttention-4 computes some exponentials in software, with a polynomial approximation on ordinary FMA units, and skips softmax rescaling when it isn’t needed. Its roofline analysis finds shared-memory traffic and exponentials, not matrix math, now dominate attention time on Blackwell.
Where you meet it
- PyTorch:
torch.nn.functional.scaled_dot_product_attention“attempts to automatically select the most optimal implementation based on the inputs”: FlashAttention-2, memory-efficient attention, or the C++ math path. Force one withtorch.nn.attention.sdpa_kernel(SDPBackend.FLASH_ATTENTION). FlashAttention-2 arrived in PyTorch 2.2 with “around 2x speedups”. - vLLM: picks the first compatible backend;
FLASH_ATTNis first on Ampere and Hopper, FlashInfer first on Blackwell. The FLASH_ATTN version defaults to “FA4 on SM100+ (Blackwell), FA3 on SM90 (Hopper), FA2 otherwise”. Choose with--attention-backend(docs, v0.26.0). - Ollama: “uses Flash Attention automatically when the selected backend and devices support it”; force it with
OLLAMA_FLASH_ATTENTION=1, disable with=0(FAQ). - llama.cpp:
-fa, --flash-attn [on|off|auto], defaultauto(server README).
The setting that depends on it: a quantized V cache. In llama.cpp, -ctv q8_0 with -fa off fails with “quantized V cache requires flash_attn to be enabled”; with auto, it logs “enabling flash_attn since it is required for quantized V cache” (llama-context.cpp). Ollama’s FAQ says the same: the K/V cache “can be quantized to significantly reduce memory usage when Flash Attention is enabled” (OLLAMA_KV_CACHE_TYPE=q8_0).
Flash attention vs paged attention
They’re not rivals; they fix different problems.
| FlashAttention (2022) | PagedAttention (vLLM, 2023) | |
|---|---|---|
| Question | How is attention computed? | Where does the KV cache live? |
| Idea | Tiles in SRAM, online softmax, no N × N in HBM | Fixed-size KV blocks, “inspired by the classical virtual memory and paging techniques in operating systems” |
| Problem it fixes | HBM traffic and quadratic scratch memory | Fragmentation: “only 20.4% - 38.2% of the KV cache memory is used to store the actual token states in the existing systems” |
| Reported gain | 2–4× faster attention, linear memory | 2–4× serving throughput at the same latency |
vLLM uses both: its FLASH_ATTN backend runs FlashAttention kernels over the paged KV cache. Source: Kwon et al., arXiv 2309.06180.
The short version
Three ideas: small tiles on the countertop (SRAM), a running tally for softmax, and recompute instead of store. Same exact answer, memory that grows in a line instead of a square, and far fewer trips to HBM. On the newest GPUs, the next bottleneck isn’t memory at all: it’s the exponential.
Sources
- Dao, Fu, Ermon, Rudra, Ré, FlashAttention (arXiv 2205.14135v2, 2022)
- Dao, FlashAttention-2 (2023); Shah et al., FlashAttention-3 (2024); Zadouri et al., FlashAttention-4 (2026); Dao-AILab/flash-attention
- Milakov, Gimelshein, Online normalizer calculation for softmax (2018)
- Kwon et al., PagedAttention / vLLM (2023); vLLM attention backends
- PyTorch SDPA docs, PyTorch 2.2 release blog, Ollama FAQ, llama.cpp server README
- Llama 3.1 8B config (32 heads, head dim 128) on Hugging Face; matrix sizes are our arithmetic.