Skip to content
The Daily Triptych039 / 365
GPU memory hierarchy on an A100

Bandwidth and latency for four memory tiers. FlashAttention keeps intermediate attention matrices in SRAM, avoiding the HBM bottleneck.

II · THE IDEA · ARTIFICIAL INTELLIGENCE

FlashAttention

Tri Dao and collaborators · 2022 (FlashAttention-2 in 2023) · Transformers

▶ 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.

Look closer

  1. 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.

  2. 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.

  3. 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?

Go deeper

Image: Original diagram, The Daily Triptych. Licence: Original work. Source.

← Back to day 39