On this page
FlashAttention is one of those ideas that sounds like it must involve an approximation. It doesn't. It computes exactly the same attention as the textbook formula, and it's faster because it moves far less data. Understanding why is a short lesson in how GPUs really work.
This guide walks through what standard attention does wrong, how tiling and the online softmax fix it (with a worked numerical example), how much it saves, how the versions differ, and why decode needs its own kernels.
#A one-paragraph GPU primer
A GPU has two kinds of memory that matter here. High-bandwidth memory (HBM) is the big pool (80 GB on an H100) where weights and activations live; it's fast by everyday standards, at a few TB/s, but slow compared with the chip's arithmetic. On-chip memory (registers and shared memory, a couple of hundred KB per streaming multiprocessor) is tiny but an order of magnitude faster. A kernel that does a lot of arithmetic per byte it reads from HBM runs at full speed; a kernel that reads and writes HBM for every small operation waits on memory (what is a GPU kernel).
#What standard attention does
For a sequence of tokens with head dimension , attention computes
The straightforward implementation does it in steps, each a separate GPU kernel:
- Compute the scores : an matrix. Write it to GPU memory.
- Read , compute the softmax . Write to memory.
- Read , multiply by . Write the output.
The problem is the size of and . At tokens, one head's score matrix has about a billion entries: 2 GB in FP16. Writing it and reading it back, for every head of every layer, swamps the memory bandwidth. Most of the time goes to moving a matrix nobody needs to keep.
#Worked example: an 8B model reading an 8K prompt
Take Llama 3.1 8B (32 layers, 32 query heads) prefilling an 8,192-token prompt in FP16:
- One head's score matrix: million entries, about 134 MB.
- Write , read , write , read : about 537 MB per head per layer.
- Times 32 heads and 32 layers: about 550 GB of memory traffic.
At an effective 2.35 TB/s on an H100, that's about 0.23 seconds, roughly as long as all the rest of the prefill's maths (about 0.27 seconds at half the GPU's BF16 peak). Standard attention would nearly double the time to first token, and it gets quadratically worse as prompts grow.
#The FlashAttention idea: tile and never materialise
FlashAttention splits , and into tiles that fit in the GPU's fast on-chip memory. For each tile of queries, it loops over tiles of keys and values:
- Load a tile of and into on-chip memory.
- Compute that tile's scores with the query tile.
- Update a running softmax and a running output.
- Move on to the next tile.
The full matrix is never written to main memory. Each tile of scores lives on chip just long enough to be used.
Score matrix in HBM
N × N
Output rows written
–
Standard attention writes the whole score matrix
Compute QKᵀ (N × N), write it to HBM, read it back for softmax, write the probabilities, read them again to multiply by V. At long context those round trips dominate.
Grid = the score matrix (query tiles down, key tiles across). Red = written to HBM. Blue = computed in on-chip SRAM and discarded.
To get a feel for the sizes: with 128 queries per tile, 64 keys per tile and a head dimension of 128, a query tile is 32 KB in FP16, each key and value tile is 16 KB, and the 128 × 64 tile of scores in FP32 is 32 KB. Together they fit comfortably in an H100's on-chip memory, with room for double-buffering the next tile while the current one is used.
#The trick that makes tiling possible: online softmax
Softmax needs the maximum and the sum over the whole row before it can normalise anything, which seems to require seeing every score first. The online softmax removes that requirement. Keep a running max and a running sum . When a new tile of scores arrives with its own max, rescale what you've accumulated so far:
The running output is rescaled by the same factor . At the end, divide by . The result is identical to the textbook softmax, computed in one pass over the keys.
#A worked example with four scores
Suppose one query's scores arrive in two tiles: , then .
After tile 1: , and .
Tile 2 arrives with max 5, so . Rescale the old sum by , then add the new terms:
Check against the direct calculation over all four scores with max 5: . Identical.
Subtracting the running max keeps every exponent at or below zero, so nothing overflows, even in FP16. The reductions lesson walks through this recurrence with an animated example.
#How much traffic it saves
Count memory traffic for one head, ignoring , , and the output (which both versions must read and write):
- Standard: write , read , write , read . About values.
- FlashAttention: none of that. The extra cost is re-reading and once per query tile, which is much smaller for realistic tile sizes.
At in FP16, values is about 8.6 GB per head per layer. That's why FlashAttention's speed-ups grow with sequence length, and why it made long-context training and inference practical. It also cuts memory capacity: no buffer to allocate, so attention memory grows linearly with sequence length instead of quadratically.
#Free extras from tiling
Because attention is computed tile by tile, several common variations become cheap:
- Causal masks: tiles entirely above the diagonal (future tokens) are skipped outright, halving the work for decoder models.
- Sliding-window attention: tiles outside the window are skipped too.
- Grouped-query attention: several query heads share one loaded K and V tile (GQA vs MQA vs MLA).
- Variable-length batches: sequences of different lengths can be packed together without padding.
#The versions
| Version | Main change |
|---|---|
| FlashAttention (2022) | Tiling plus online softmax; exact attention without the matrix in memory |
| FlashAttention 2 (2023) | Better work split across warps and thread blocks, parallelism over the sequence; roughly twice as fast; Ampere and newer |
| FlashAttention 3 (2024) | Hopper-specific: asynchronous tensor-core instructions, TMA copies, warp specialisation, FP8 support |
| Later versions | Ports to Blackwell and further tuning for newer tensor-core features |
Each version keeps the same maths and changes how well it keeps the newest GPUs' tensor cores fed. In training, FlashAttention also avoids storing the attention matrix for the backward pass: it recomputes tiles when needed, trading a few extra FLOPs for a large memory saving.
#Decode is a different problem
FlashAttention was designed for prefill and training, where there are many queries. In decode there's one query token per sequence, so there's little parallelism over queries, and the work is dominated by reading the KV cache. Decode needs different kernels:
- Split-KV (flash-decoding): split the long KV cache across many thread blocks, each computing a partial result, then merge them with the same log-sum-exp rescaling. This fills the GPU even at batch 1.
- Paged kernels: read KV from scattered blocks via a block table (PagedAttention explained).
- Libraries: FlashInfer, FlashAttention's decode paths and engine-specific kernels specialise in this.
Blocks
8
SMs busy
6%
Waves
1
Batch 1, no split: 8 blocks
One thread block per (sequence, KV head). With 8 KV heads that is 8 blocks for 132 SMs: 94% of the GPU idles while a few SMs stream the long cache.
132 squares = the SMs of an H100. Lit squares are busy in the first wave.
The merge step in split-KV is the online softmax again: each block returns its partial output, max and sum, and the partial results are combined by rescaling, exactly as in the worked example above.
#How to use it
You rarely call FlashAttention directly; frameworks pick it for you:
- PyTorch:
torch.nn.functional.scaled_dot_product_attentionchooses a FlashAttention-style backend automatically on supported GPUs and inputs. - Hugging Face Transformers: load a model with
attn_implementation="flash_attention_2"(needs theflash-attnpackage) or"sdpa". - vLLM and SGLang: use FlashAttention or FlashInfer backends by default on supported hardware.
- llama.cpp: enable it with
-fa; it's also required for a quantised V cache.
If a model runs out of memory on long prompts, check first that a flash backend is actually in use. A silent fallback to the standard path is a common cause.
#Common misconceptions
- "It's an approximation." It's exact, up to normal floating-point rounding differences.
- "It reduces FLOPs." It does slightly more FLOPs (some recomputation in training). It's faster because it moves far fewer bytes.
- "It makes long context free." Attention FLOPs still grow with in prefill, and the KV cache still grows with in decode. FlashAttention removes the memory-traffic penalty, not the maths.
- "It shrinks the KV cache." No; it changes how attention is computed, not what's stored. For a smaller cache, see GQA, MLA or KV quantisation (KV cache explained).
#FAQ
Does FlashAttention work on consumer GPUs? FlashAttention 2 supports NVIDIA Ampere and newer, including RTX 30, 40 and 50 series cards. Other vendors and older GPUs use similar fused attention kernels from their own libraries.
Will it change my model's outputs? Only at the level of floating-point rounding, because operations happen in a different order. It isn't a quality trade-off.
Is it still relevant with newer attention designs? Yes. Most new designs (GQA, MLA, sliding windows) still need a fused, tiled kernel to run fast; FlashAttention's ideas are the basis of those kernels.
#Go deeper
Attention optimisations covers FlashAttention, paged KV, GQA and sliding windows together. Attention kernels for serving covers split-KV decoding, MLA and FlashAttention 3 and 4. To write the kernels yourself, the GPU Kernels for Inference course builds online softmax in CUDA and a paged decode-attention kernel in Triton.
flash-attentionattentionkernelslong-contextinference-engineering
Found this useful?
Send it to someone who is learning the same thing.
Preparing for an interview?
Next: learn it step by step, free
The CUDA programming model
Threads, blocks, warps and memory: the model every inference kernel is written against. A free lesson with step-through diagrams and a quiz.