II · THE IDEA · ARTIFICIAL INTELLIGENCE
FlashAttention
▶ Listen · narrated
The bottleneck in a transformer is rarely the arithmetic. It is usually the time spent ferrying intermediate results back and forth between fast, tiny memory and slow, large memory.
At a glance
- What it is
- A mathematically equivalent reformulation of attention that minimises memory reads and writes
- Speed improvement
- Reported as 2–4× faster on long sequences in the original paper, depending on hardware and sequence length
- Memory saving
- Linear in sequence length instead of quadratic, because intermediate attention matrices are never fully materialised
- Correctness
- Exact, not approximate — produces bitwise identical output to standard attention in the forward pass
Imagine you are baking a cake and the recipe requires you to walk to a distant pantry every time you need an ingredient, even if you only need a pinch of salt. You spend more time walking than mixing. Now imagine you carry a small basket and fetch several ingredients at once, keeping them on the counter while you work. You make far fewer trips and finish much faster, even though the mixing itself takes the same amount of time.
FlashAttention does something similar with GPU memory. A GPU has a small, very fast memory built into each processor (like your counter) and a large, slower memory pool shared across the whole chip (like the pantry). Standard attention keeps writing intermediate results to the slow memory and reading them back, which wastes time. FlashAttention reorganises the work so that everything fits in the fast memory until the final answer is ready, then writes that answer once to the slow memory. The arithmetic is identical, but the data moves less, so the whole operation finishes faster.
FlashAttention is an IO-aware implementation of scaled dot-product attention that minimises data movement between HBM and SRAM by tiling the computation and fusing operations that would normally require separate kernel launches. The standard attention implementation computes Q K^T, writes the result to HBM, launches a softmax kernel that reads it back and writes the normalised scores to HBM again, then launches a final matmul kernel to compute the output. Each HBM read or write has a cost proportional to the size of the data moved, and for a sequence of length N with d-dimensional heads, the attention matrix is N² elements, so memory traffic scales quadratically.
FlashAttention tiles Q, K and V into blocks sized to fit in SRAM (typically 128 or 256 tokens per block, depending on head dimension and available SRAM). It processes one block of queries at a time, looping over all blocks of keys and values to compute the corresponding slice of the output. Within each iteration, it computes the attention scores for that query-key block pair, applies softmax, and accumulates the weighted sum of values, all in SRAM. The only HBM writes are the final outputs.
The core challenge is softmax, which requires a global maximum and sum over each row. FlashAttention uses online softmax: for each query block, it maintains a running maximum m and a running sum of exponentials l, both stored in registers or SRAM. When processing a new key block, it computes the block's local maximum m_new and updates the global maximum. If m_new > m, it rescales the previous partial sums by exp(m - m_new) to account for the shift in the softmax denominator. The rescaling is exact, so the final output is bitwise identical to standard attention (in forward pass; backward pass uses recomputation and has minor numerical differences due to operation reordering, though these are typically negligible).
The algorithm also fuses the attention computation with the dropout and masking operations, avoiding additional passes over the data. For the backward pass, FlashAttention recomputes the attention matrix on the fly in SRAM rather than storing it during the forward pass, which reduces peak memory usage at the cost of additional FLOPs — but because the recomputation happens in SRAM, it is faster than the memory traffic it avoids. FlashAttention-2 improves on this by changing the parallelisation strategy: instead of assigning each thread block to a subset of queries, it partitions over both queries and keys, reducing idle time and improving occupancy, particularly for shorter sequences. It also reduces non-matmul FLOPs by tuning the order of softmax operations and minimising thread-block synchronisation.
Look closer
The standard algorithm is memory-bound, not compute-bound
Computing attention for a sequence of length 4096 involves roughly 67 million multiply-add operations per head, which a modern GPU can retire in well under a millisecond. But the standard implementation writes the full attention matrix — 16 million floats — to high-bandwidth memory, then reads it back to apply the softmax, then writes it again, then reads it again to multiply by the values. On an A100, moving that much data takes longer than the arithmetic by a factor of five or more. The GPU spends most of its time waiting on memory, not computing.
FlashAttention tiles the work to fit in SRAM
Instead of computing the entire attention matrix at once, FlashAttention divides the queries, keys and values into blocks small enough to fit in the GPU's on-chip SRAM — typically 20 megabytes on an A100, versus 40 or 80 gigabytes of slower HBM. It computes attention one block at a time, accumulates partial results in registers and SRAM, and writes only the final output back to HBM. The full attention matrix never exists in memory. This is called tiling or blocking, and it is a standard technique in numerical computing, but applying it to attention requires careful handling of the softmax denominator, which couples every column.
The trick is online softmax with rescaling
Softmax needs the maximum value across a row before it can compute any output, which seems to require seeing the whole row at once. FlashAttention sidesteps this by tracking a running maximum and a running sum of exponentials, then rescaling previous blocks' contributions whenever a new block reveals a larger maximum. The maths is exact: you get the same answer you would have got from a single global softmax, but you never hold the full row in memory. This rescaling step is the algorithmic core that makes tiling possible.
The story
A transformer's attention mechanism computes a weighted sum of value vectors, where the weights come from comparing each query to every key. For a sequence of length N, that means N² comparisons, and the standard implementation writes all N² scores into memory as a dense matrix, applies softmax to each row, writes the result back, then uses it to weight the values. The matrices are large — for a 4096-token sequence, 16 million floats per head — and they live in high-bandwidth memory (HBM), the main DRAM pool on a GPU.
Modern GPUs have a three-tier memory hierarchy. At the top, each streaming multiprocessor has a small amount of SRAM, often called shared memory, with latencies under ten cycles and bandwidth measured in tens of terabytes per second. Below that sits HBM, with latencies in the hundreds of cycles and bandwidth around one or two terabytes per second. At the bottom, if the GPU runs out of its own memory, data must cross the PCIe bus to system RAM, which is slower still. The gap between SRAM and HBM is the critical one: moving a float from HBM into a register where the GPU can actually use it costs roughly a hundred times more energy and takes fifty times longer than performing a multiply-add on it once it arrives.
The standard attention implementation is written as if memory were free. It computes Q times K-transpose and writes the result — the full attention matrix — to HBM. It reads that matrix back, applies softmax row by row, and writes the softmaxed matrix back to HBM. It reads the softmaxed matrix again, multiplies it by V, and writes the final output. For a sequence of 4096 tokens with 128-dimensional heads, each of those reads and writes moves 64 megabytes. The arithmetic itself — a few tens of millions of FLOPs — finishes quickly, but the GPU spends most of its time stalled, waiting for data to arrive from HBM.
FlashAttention reorganises the computation so that intermediate matrices never leave SRAM. It divides Q, K and V into blocks sized to fit comfortably in on-chip memory, then computes attention one block of queries at a time. For each query block, it loops over the key and value blocks, computing partial attention scores and accumulating weighted sums in SRAM. The full N-by-N attention matrix is never materialised. Only the final output is written back to HBM.
The obstacle is softmax. To compute softmax over a row, you need the maximum value in that row, which is used to shift all the exponentials for numerical stability. If you are processing the row in chunks, you do not know the global maximum until you have seen every chunk. FlashAttention handles this with online softmax: it tracks a running maximum and a running sum of exponentials, and whenever a new block reveals a larger maximum, it rescales the contributions from previous blocks. The rescaling factor is exact, so the final result is bitwise identical to what you would get from a single global softmax over the full row. This technique was known in the numerical computing literature, but applying it to attention required working out how to thread it through the backward pass as well, which the FlashAttention paper describes in detail.
The result is an algorithm that performs the same arithmetic as standard attention but moves far less data. Memory traffic drops from quadratic in sequence length to linear, because the intermediate attention matrices are never written out. On an A100 GPU with a sequence length of 2048, the original FlashAttention paper reports wall-clock speedups of 2.4× for the forward pass and similar gains for the backward pass. The improvement grows with sequence length, because the memory bottleneck becomes more severe as N increases.
FlashAttention-2, published a year later, refines the algorithm further. It changes how work is partitioned across the GPU's thread blocks to reduce synchronisation overhead and improve parallelism, particularly for shorter sequences where the original version did not fully saturate the hardware. It also reduces the number of non-matmul FLOPs — the comparisons, exponentials and divisions involved in softmax — by tuning the order of operations. The paper reports speedups of around 2× over the original FlashAttention on typical workloads, which compounds with the earlier gains over the standard implementation.
Why it mattered then
When the FlashAttention paper appeared in 2022, transformers were already dominant in natural language processing and spreading into vision and other domains, but scaling them to longer sequences was expensive. Memory usage grew quadratically with sequence length, and training runs on sequences longer than a few thousand tokens required careful gradient checkpointing or model parallelism tricks to fit in GPU memory at all. Even when a model fit, training was slow, because attention was spending most of its time moving data rather than computing. The immediate practical appeal was that FlashAttention made long-context models cheaper to train and faster to run without changing the architecture or the output. It was a pure systems optimisation: the same mathematics, implemented in a way that respected the hardware's memory hierarchy. For researchers trying to scale context windows from 2048 to 8192 or beyond, it removed a major bottleneck. The technique was also exact, not an approximation, which mattered for adoption — there was no accuracy trade-off to evaluate, no new hyperparameter to tune. You could drop it into an existing codebase and get faster training with no other changes.
Why it matters now
FlashAttention and its successors are now part of the standard infrastructure for training and serving large language models. Most recent open-weight models — Llama 3, Mistral, Qwen — use FlashAttention or a variant during training, and many inference engines include it as an option or default. The technique has been extended to handle sparse attention patterns, sliding windows and other modifications, and the general principle — organise computation around the memory hierarchy, not around the mathematical notation — has influenced other parts of the training stack. The broader lesson is that algorithmic improvement at this scale is often about memory, not arithmetic. GPUs have become so fast at multiplication that the bottleneck has shifted to moving data between memory tiers. FlashAttention is a clean example of the gains available when you take the memory hierarchy seriously, and it has prompted similar work on other memory-bound operations in transformers. The fact that a 2× or 4× speedup was sitting there, requiring no new hardware and no approximation, just a careful reordering of the same operations, suggests that other parts of the stack may still have comparable headroom.
The surprising detail
The online softmax rescaling trick that makes FlashAttention possible was not new. Variants of it appear in older numerical computing papers, and the idea of processing a reduction operation incrementally with periodic rescaling has been used in other contexts for numerical stability. What was new was recognising that it could be applied to attention, working out how to make it efficient on GPU hardware with its particular memory hierarchy, and — less obviously — extending it to the backward pass, where you need to propagate gradients through the rescaling steps without materialising the full attention matrix there either. The FlashAttention paper includes several pages of careful index arithmetic to make the backward pass work, and that part of the algorithm is less widely explained than the forward pass, even though it is just as necessary for training.
Remember this
Memory bandwidth, not floating-point throughput, is usually the limit. FlashAttention is the same maths, reorganised so the GPU stops waiting.
Test yourself
FlashAttention reduces memory traffic by never writing the full attention matrix to HBM. Does this mean it uses less memory during training, less time, or both? If both, does the memory saving scale the same way as the time saving?
Both, but they scale differently. The time saving comes from reducing memory traffic, which grows quadratically with sequence length in standard attention — FlashAttention makes it linear. The memory saving is more nuanced. During the forward pass, FlashAttention uses linear memory instead of quadratic because it never stores the full attention matrix, which is a large win for long sequences. But during training, you also need to store activations for the backward pass, and standard implementations store the attention matrix so they can reuse it when computing gradients. FlashAttention does not store it, so it recomputes parts of it on the fly during the backward pass — a classic time-memory trade-off, except that the recomputation is fast because it happens in SRAM, so you get both less memory use and less wall-clock time. The memory saving is quadratic-to-linear in sequence length for the attention matrix itself, but total training memory also includes weights, optimizer states and other activations, so the overall saving is smaller than the attention-matrix term alone would suggest.
Go deeper
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness · arXiv · Tri Dao et al. · 2022-05-27
- FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning · arXiv · Tri Dao et al. · 2023-07-17
Image: Original diagram, The Daily Triptych. Licence: Original work. Source.