FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness
FlashAttention computes exact attention block by block in the GPU's on-chip SRAM, so the N×N score matrix never goes to GPU memory. HBM accesses fall from Θ(Nd+N²) to Θ(N²d²/M); BERT trains about 15% faster, GPT-2 3.0 to 3.5 times faster than HuggingFace. A breakdown of the paper.
On this page
- Why this paper matters
- Background: why approximate attention did not get faster
- The core idea: tiling, online softmax and recomputation
- Tiling and online softmax
- Recomputation and kernel fusion
- IO complexity: why it is faster, and by how much
- Block-sparse FlashAttention
- Experiments: what the paper reports
- Faster training
- Longer context, better models
- Speed and memory of the attention layer itself
- What to keep in mind when reading the numbers
- Limitations and follow-ups
- What to take away from this paper
- Further Reading
- FAQ
Why this paper matters
FlashAttention (Dao et al., NeurIPS 2022) is an exact attention algorithm: it does not change the mathematical definition of attention, only the order of the computation. The paper splits , and into blocks, does the matrix multiplications and the softmax inside the GPU’s on-chip SRAM, and never writes the attention matrix back to GPU memory (HBM). It proves that the number of HBM accesses is ( is the head dimension and the SRAM size), against for the standard implementation. In the paper’s GPT-2 medium measurement, the attention layer’s HBM traffic falls from 40.3 GB to 4.4 GB and the forward plus backward time from 41.7 ms to 7.3 ms, at the price of about 13% more FLOPs.
The result corrects a popular assumption, namely that attention is slow because its quadratic cost means too many arithmetic operations. The paper’s argument is that on modern GPUs many approximate attention methods reduced FLOPs without getting faster, because they ignored the cost of memory reads and writes (IO). FlashAttention does not approximate anything. It only rearranges how data moves between GPU memory and on-chip memory, and that alone gives end-to-end training speedups. The FlashAttention-2 paper later describes it as widely adopted in large-scale training and inference.
This breakdown follows the order problem, idea, algorithm, analysis, experiments, limitations and follow-ups. The derivation, runnable blocked-attention code, and the ways MQA, GQA and MLA shrink the KV cache are on the wiki page Efficient Attention.
Background: why approximate attention did not get faster
Both the compute and the memory of attention grow quadratically with the sequence length . A lot of earlier work approximated attention with sparsity, low-rank structure or a mix of the two, bringing the cost down to linear or near-linear. The paper points out that many of these methods show no wall-clock speedup over standard attention, because they chase FLOPs and neglect memory access.
GPU memory is a hierarchy in which smaller means faster. The paper uses the A100 as its example (Figure 1 and Section 2.1):
| Level | Capacity | Bandwidth |
|---|---|---|
| On-chip SRAM | 192 KB per streaming multiprocessor, 108 of them, about 20 MB in total | About 19 TB/s (the paper’s estimate) |
| HBM (GPU memory) | 40 to 80 GB | 1.5 to 2.0 TB/s |
| CPU memory (DRAM) | Over 1 TB | 12.8 GB/s |
SRAM is an order of magnitude faster than HBM and many orders of magnitude smaller. A GPU program (a kernel) typically loads its inputs from HBM into registers and SRAM, computes, and writes the result back to HBM. By arithmetic intensity (arithmetic operations per byte of memory traffic), operations fall into two classes:
- Compute-bound: the time is set by the number of arithmetic operations, for example a matrix multiplication with a large inner dimension.
- Memory-bound: the time is set by the number of memory accesses, for example element-wise operations (activations, dropout) and reductions (softmax, normalization).
Standard attention writes the two matrices and to HBM in full and reads them back. The paper’s Algorithm 0 has three steps: compute and write it out; read , apply softmax, write ; read and , compute and write it out. Softmax, masking and dropout are all memory-bound. For GPT-2, and , so and the intermediates dominate the traffic. Training adds a complication: the backward pass needs and , so intermediate results must be saved, which limits what naive kernel fusion can do.
Putting standard attention and FlashAttention side by side makes the difference clearer:
The core idea: tiling, online softmax and recomputation
The goal is to avoid reading and writing the attention matrix in HBM. That raises two technical obstacles: a softmax needs a whole row of scores to normalize, and the backward pass needs the intermediate attention matrix. The paper handles them with two existing techniques:
- Tiling. Split the inputs into blocks, process them one block at a time, and compute the softmax reduction incrementally while doing so.
- Recomputation. The forward pass does not save the matrices, only the normalization statistics. The backward pass recomputes the attention blocks it needs from blocks of , , in SRAM.
The paper does not hide that these techniques are not new. For the blocked softmax it cites earlier work such as Milakov and Gimelshein (2018) and Rabe and Staats (2021, whose title is “Self-attention does not need memory”). FlashAttention’s contribution is to combine them with an IO analysis: it implements them in one fused CUDA kernel and proves that, over a range of SRAM sizes, the resulting number of HBM accesses is optimal.
Tiling and online softmax
For a vector , the numerically stable softmax is
The softmax of two concatenated segments and can be assembled from the statistics of each segment:
So storing two extra numbers per row is enough to compute a softmax one block at a time. The paper’s Algorithm 1 organizes the loops as follows:
- Choose block sizes from the SRAM size and the head dimension : and . Split into blocks and , into blocks.
- The outer loop runs over the blocks of and ; each block is loaded from HBM into SRAM once.
- The inner loop runs over the blocks of : load , plus , and kept in HBM; compute on chip together with the block’s row maxima and row sums; update and with the merge rule above; then update the output block with the formula below and write it back to HBM.
- After the last block, is exactly .
In this update, and are the current block’s row maxima and unnormalized probabilities. The old accumulated result only has to be multiplied by the scalar to move it to the new maximum, so a full row of scores never exists at once. Theorem 1 of the paper states that Algorithm 1 returns exactly using FLOPs and only extra memory beyond the inputs and output.
Recomputation and kernel fusion
The backward pass normally needs and to compute the gradients with respect to , and . FlashAttention saves only the output and the statistics , and recomputes and from blocks of , , in SRAM when it needs them; the paper calls this a form of selective gradient checkpointing. Ordinary gradient checkpointing trades speed for memory. Here the backward pass gets faster even though it performs more FLOPs, because the HBM accesses it saves are worth more than the extra arithmetic.
Tiling also lets the whole computation fit into one CUDA kernel: read the inputs from HBM, do the matrix multiplication, the softmax, the optional masking and dropout and the second matrix multiplication on chip, then write the result back. Intermediate results no longer travel between operators through HBM.
IO complexity: why it is faster, and by how much
The paper answers this quantitatively with an IO analysis. Let be the sequence length, the head dimension and the SRAM size, with :
- Standard attention needs HBM accesses.
- FlashAttention needs (Theorem 2). The proof idea: SRAM holds blocks of and of size , and for each block the whole of has to be scanned, which gives passes, each moving elements.
- Lower bound (Proposition 3): there is no exact attention algorithm that achieves HBM accesses simultaneously for every in . The paper concludes that FlashAttention is optimal over a range of SRAM sizes, and notes that lower bounds over a sub-range of are common in the streaming-algorithms literature.
Typical values are of 64 to 128 and of about 100 KB, so is far smaller than and FlashAttention needs many times fewer accesses than the standard implementation. Figure 2 (left) of the paper checks this on the GPT-2 medium configuration (sequence length 1024, head dimension 64, 16 heads, batch size 64, A100, forward plus backward):
| Metric | Standard attention | FlashAttention | Change |
|---|---|---|---|
| Compute (GFLOPs) | 66.6 | 75.2 | About 13% more |
| HBM reads and writes (GB) | 40.3 | 4.4 | About 89% less (about 9×) |
| Time (ms) | 41.7 | 7.3 | About 82% less (about 5.7× faster) |
The last column is computed here from the paper’s numbers. The extra 13% of FLOPs comes from recomputation in the backward pass, yet the time drops to less than a fifth: the runtime is governed by HBM traffic, not by FLOPs. Figure 2 (middle) varies the block size as a control: larger blocks mean fewer passes over the input, fewer HBM accesses and a faster forward pass, until beyond a block size of 256 the bottleneck moves elsewhere (for example arithmetic), and larger blocks would not fit into the small SRAM anyway.
Block-sparse FlashAttention
The paper also extends FlashAttention to approximate attention. Given a sparsity mask defined over blocks, the algorithm is Algorithm 1 with the all-zero blocks skipped. Proposition 4 gives its IO complexity as , where is the fraction of non-zero blocks, so the speedup over FlashAttention scales with the sparsity. The downstream experiments use a fixed butterfly sparsity pattern. This is a proof of concept for the claim that FlashAttention can serve as a building block for approximate attention methods, not the main act: the FlashAttention-2 paper says that, as far as its authors know, most large-scale training still uses standard (exact) attention.
Experiments: what the paper reports
Faster training
BERT-large. Starting from the same initialization provided by MLPerf and training on Wikipedia, the time to reach 72.0% accuracy on masked language modeling (average of 10 runs on 8 A100 GPUs):
| Implementation | Training time (minutes) |
|---|---|
| Nvidia MLPerf 1.1 | 20.0 ± 1.5 |
| FlashAttention | 17.4 ± 1.4 |
That is 13% less time, or about 15% more speed (20.0 ÷ 17.4 ≈ 1.15). The opponent is the Nvidia implementation that held the MLPerf 1.1 training-speed record at the time, and the paper calls this the fastest single-node BERT training it knows of.
GPT-2. Trained on OpenWebText with 8 A100 GPUs:
| Implementation | OpenWebText perplexity | Training time | Speedup over HuggingFace |
|---|---|---|---|
| GPT-2 small, HuggingFace | 18.2 | 9.5 days | 1.0× |
| GPT-2 small, Megatron-LM | 18.2 | 4.7 days | 2.0× |
| GPT-2 small, FlashAttention | 18.2 | 2.7 days | 3.5× |
| GPT-2 medium, HuggingFace | 14.2 | 21.0 days | 1.0× |
| GPT-2 medium, Megatron-LM | 14.3 | 11.5 days | 1.8× |
| GPT-2 medium, FlashAttention | 14.3 | 6.9 days | 3.0× |
All three implementations reach the same perplexity, because FlashAttention does not change the model definition; the paper’s appendix shows the validation-perplexity curves during training, and they agree. The speedup over HuggingFace is 3.0 to 3.5 times. Over the better-optimized Megatron-LM the table’s numbers give 1.7 times (4.7 ÷ 2.7 and 11.5 ÷ 6.9). So “3× faster” depends on who the opponent is.
Long Range Arena (LRA). Five tasks with sequence lengths from 1K to 4K:
| Model | ListOps | Text | Retrieval | Image | Pathfinder | Average | Speedup |
|---|---|---|---|---|---|---|---|
| Transformer | 36.0 | 63.6 | 81.6 | 42.3 | 72.7 | 59.3 | 1× |
| FlashAttention | 37.6 | 63.9 | 81.4 | 43.5 | 72.7 | 59.8 | 2.4× |
| Block-sparse FlashAttention | 37.0 | 63.0 | 81.3 | 43.6 | 73.3 | 59.6 | 2.8× |
| Linformer | 35.6 | 55.9 | 77.7 | 37.8 | 67.6 | 54.9 | 2.5× |
| Linear Attention | 38.8 | 63.2 | 80.7 | 42.6 | 72.5 | 59.6 | 2.3× |
| Performer | 36.8 | 63.6 | 82.2 | 42.1 | 69.9 | 58.9 | 1.8× |
| Local Attention | 36.1 | 60.2 | 76.7 | 40.6 | 66.6 | 56.0 | 1.7× |
| Reformer | 36.5 | 63.8 | 78.5 | 39.6 | 69.4 | 57.6 | 1.3× |
| Smyrf | 36.1 | 64.1 | 79.0 | 39.6 | 70.5 | 57.9 | 1.7× |
Exact FlashAttention is 2.4 times faster than standard attention with a slightly higher average score (59.8 against 59.3). Linformer’s speedup (2.5 times) is comparable, but its average is almost 5 points lower (54.9); Linear Attention’s average is close (59.6) with a speedup of only 2.3 times. A footnote in the paper warns that LRA accuracy depends heavily on tuning, and that its reproduced baselines are better than those in the original comparison.
Longer context, better models
Faster training means the same budget can train on longer sequences. The paper runs three experiments.
Language modeling. GPT-2 small with the context stretched from 1K to 4K is still cheaper to train than Megatron-LM at 1K:
| Implementation | Context length | Perplexity | Training time | Speedup over Megatron-LM |
|---|---|---|---|---|
| Megatron-LM | 1K | 18.2 | 4.7 days | 1.0× |
| FlashAttention | 1K | 18.2 | 2.7 days | 1.7× |
| FlashAttention | 2K | 17.6 | 3.0 days | 1.6× |
| FlashAttention | 4K | 17.5 | 3.6 days | 1.3× |
At 4K the perplexity is 0.7 lower than at 1K and the training time is still about 23% shorter (3.6 ÷ 4.7); the paper’s “30% faster” is the speed ratio 1.3.
Long-document classification. A pretrained RoBERTa is extended to longer inputs by repeating its position embeddings (the approach of Longformer); the metric is micro F1:
| Sequence length | 512 | 1,024 | 2,048 | 4,096 | 8,192 | 16,384 |
|---|---|---|---|---|---|---|
| MIMIC-III | 52.8 | 50.7 | 51.7 | 54.6 | 56.4 | 57.1 |
| ECtHR | 72.2 | 74.3 | 77.1 | 78.6 | 80.7 | 79.2 |
MIMIC-III is 4.3 points higher at 16K than at 512, and ECtHR is 8.5 points higher at 8K than at 512; the average of the two is the “6.4 points of lift” in the abstract. Neither curve is monotonic: MIMIC-III dips to 50.7 at 1,024, and ECtHR falls from 80.7 to 79.2 at 16,384. The paper attributes the difference in gains between the two datasets to a possible distribution shift: MIMIC-III is specialized medical text and may be more sensitive to a change in document-length distribution, while ECtHR is general language.
Path-X and Path-256. These are the two hardest tasks in LRA: decide whether two points in a (or ) black-and-white image are connected by a path, with the image fed to the Transformer one pixel at a time, giving sequence lengths of 16K and 64K. Earlier Transformers either ran out of memory or only reached random performance. The paper pretrains on Path-64 and transfers to Path-X by spatially interpolating the position embeddings:
| Model | Path-X (16K) | Path-256 (64K) |
|---|---|---|
| FlashAttention | 61.4 | ✗ |
| Block-sparse FlashAttention | 56.0 | 63.1 |
| Other Transformers and approximations (6 in the paper’s table) | ✗ | ✗ |
A ✗ is a failure in the paper’s table: earlier Transformers either ran out of memory or only reached random performance on these tasks. The paper reports these as the first Transformers to beat random performance on them. A footnote cautions that Path-256 has longer sequences but relatively shorter paths than Path-X, which makes a higher accuracy easier, so 63.1 cannot be compared directly with 61.4.
Speed and memory of the attention layer itself
The paper also measures the attention step alone on one A100 (40 GB): 8 heads, head dimension 64, batch size 16, random inputs, no projections. First the time (appendix Table 11: forward plus backward, with dropout and a padding mask, FP16):
| Sequence length | PyTorch (ms) | FlashAttention (ms) | Speedup |
|---|---|---|---|
| 512 | 2.35 | 0.95 | 2.5× |
| 1,024 | 8.29 | 2.55 | 3.3× |
| 2,048 | 31.75 | 9.56 | 3.3× |
| 4,096 | 124.19 | 37.49 | 3.3× |
| 8,192 | Out of memory | 147.75 | n/a |
Then the memory (appendix Table 21: forward plus backward, without dropout or mask):
| Sequence length | PyTorch (MB) | FlashAttention (MB) | Memory ratio |
|---|---|---|---|
| 512 | 336 | 104 | 3.2× |
| 1,024 | 1,184 | 209 | 5.7× |
| 2,048 | 4,416 | 418 | 10.6× |
| 4,096 | 17,024 | 836 | 20.4× |
| 8,192 | Out of memory | 1,672 | n/a |
The speedup and memory-ratio columns are computed here from the paper’s numbers. Three things to read from the two tables:
- Time. Both grow quadratically (FlashAttention’s time grows about 3.9 times from 4,096 to 8,192); FlashAttention just has a smaller constant, about 30% of PyTorch’s time from length 1,024 on, which the paper summarizes as “up to 3× faster”.
- Memory. The standard implementation grows quadratically (3.9 times from 2,048 to 4,096) and FlashAttention linearly (2 times). At 4,096 the gap is already 20 times, and the paper’s phrasing is “up to 20× more memory efficient than exact attention baselines”.
- Against approximate methods. For sequences shorter than 512 to 1,024, FlashAttention is even faster than the approximate and sparse methods because it moves less data; for longer sequences, linear-complexity methods such as Linformer start to be faster. Block-sparse FlashAttention is faster than every exact, approximate and sparse method the paper tested at all lengths: at length 4,096 its forward plus backward takes 4.12 ms against FlashAttention’s 37.49 ms.
What to keep in mind when reading the numbers
- The opponents and the hardware are from 2022. The BERT and GPT-2 experiments ran on 8 A100 GPUs against the HuggingFace and Megatron-LM implementations of the time. Today’s frameworks mostly ship fused attention kernels already (for example, PyTorch’s
scaled_dot_product_attentioncan use FlashAttention-style kernels on CUDA, see its documentation), so a multiplier measured against “standard attention” depends on whether your current implementation is already fused. If it is, switching gains much less. - “3× faster” depends on the opponent. Against the HuggingFace GPT-2 it is 3.0 to 3.5 times, against Megatron-LM 1.7 times, BERT is only 15% faster, and the attention step alone is at most 3.3 times faster. The end-to-end gain depends on the share of time attention takes.
- Equal perplexity is a consequence of an unchanged model. FlashAttention is exact, so with the same weights and data it differs from the standard implementation only by floating-point rounding. The lower perplexity (17.5 against 18.2) comes from the longer context; FlashAttention just makes that affordable within the same budget.
- “First” is the paper’s own claim. The Path-X and Path-256 results depend on the paper’s own pretraining and position-embedding interpolation, and LRA numbers are sensitive to tuning, so read them as observations under the paper’s setup.
Limitations and follow-ups
Section 5 of the paper lists three limitations and directions:
- A new CUDA kernel for every attention variant. This means writing the algorithm in a much lower-level language than PyTorch, which takes a lot of engineering and may not transfer across GPU generations. The paper imagines a way to write attention algorithms in a high-level language and compile them into IO-aware implementations, similar to Halide in image processing.
- IO-awareness is not specific to attention. Every layer of a deep network touches HBM, and the paper hopes to inspire IO-aware implementations of other modules.
- Multiple GPUs. The implementation is optimal within constants on a single GPU; across GPUs the IO analysis has to account for data transfer between devices.
After this paper, the authors and collaborators released two more versions that target the efficiency of the kernel itself:
| Version | Problem addressed | Reported result |
|---|---|---|
| FlashAttention-2 (2023) | The original reached only 25% to 40% of the theoretical peak FLOPs/s on an A100, because of poor work partitioning between thread blocks and warps. Fixes: fewer non-matmul FLOPs, parallelism over the sequence length, a better split of work between warps within a thread block | About 2× faster than FlashAttention, reaching 50% to 73% of the A100’s theoretical peak; up to 225 TFLOPs/s (72% model FLOPs utilization) when training GPT-style models end to end |
| FlashAttention-3 (2024) | On an H100, FlashAttention-2 reaches only 35% utilization. Fixes: use the asynchrony of Tensor Cores and TMA to overlap computation and data movement, and support FP8 | On an H100, FP16 is 1.5 to 2.0× faster than FlashAttention-2, up to 740 TFLOPs/s (75% utilization); FP8 reaches close to 1.2 PFLOPs/s; the FP8 numerical error is 2.6× lower than a baseline FP8 attention |
It is also worth being clear about what FlashAttention does not solve. It does not turn the theoretical complexity of attention from quadratic into linear; it relieves the memory-traffic and memory-footprint pressure of real systems. It does not directly address how well a model uses a long context, which is what work such as Lost in the Middle studies. And it does not shrink the KV cache; that takes structural changes such as GQA and MLA.
FlashAttention, the KV cache and PagedAttention are often mentioned together, but they act on three different layers and are not substitutes:
What to take away from this paper
- Attention is often slow because of IO, not only because of FLOPs. Doing 13% more FLOPs bought about 89% less HBM traffic and about 82% less time, which shows that for memory-bound operations, data movement is the main item on the bill.
- Tiling plus online softmax keeps the result exact. Two extra statistics per row are enough to compute a softmax block by block, and recomputing in the backward pass instead of storing keeps the extra memory at .
- The paper gives both an upper and a lower bound on IO complexity. against , with a proof that over a range of SRAM sizes nothing does asymptotically better. That makes it an analysis framework you can keep citing, not just an engineering trick.
- Read the experimental numbers together with the opponent and the hardware. 3.0×, 1.7×, 15% and 3.3× are different comparisons.
With these in mind, training-optimization, long-context and kernel-level systems papers become much easier to read.
Further Reading
- For the online-softmax update, runnable blocked-attention code, and the ways MQA, GQA and MLA shrink the KV cache, see the wiki page Efficient Attention.
- To start from attention itself, go back to Attention Is All You Need.
- For another key optimization at serving time, see vLLM and PagedAttention: Managing the KV Cache Like Paged Memory, which explains the paper Efficient Memory Management for Large Language Model Serving with PagedAttention.
- To see why a model can still fail to use a long context well even when attention is cheap, read the Lost in the Middle explainer.
- The papers: Dao et al., FlashAttention (2022); Dao, FlashAttention-2 (2023); Shah et al., FlashAttention-3 (2024).
FAQ
- What does FlashAttention do, and is its result exact?
- FlashAttention does not change the mathematical definition of attention, and its result is exact, differing from the standard implementation only by floating-point rounding. What it changes is the execution: it loads blocks of Q, K and V into the GPU's on-chip SRAM, merges the blocks with an online softmax, and never writes the full N×N attention matrix to GPU memory (HBM). The backward pass recomputes the blocks it needs instead of storing them, which cuts HBM reads and writes.
- Why is FlashAttention called IO-aware?
- The bottleneck of standard attention is often not the number of floating-point operations but the data movement between GPU memory (HBM) and on-chip SRAM. In the paper's GPT-2 medium measurement FlashAttention actually does about 13% more FLOPs (66.6 to 75.2 GFLOPs), yet HBM traffic falls from 40.3 GB to 4.4 GB and the time from 41.7 ms to 7.3 ms, which shows that runtime is governed mainly by HBM accesses.
- What is online softmax?
- Online softmax computes a softmax block by block. While processing each block it keeps the running maximum m and the normalizer ℓ, and when a new block arrives it rescales the accumulated result by the difference between the old and new maxima. A full row of scores is never needed at once, yet the output is the exact softmax, which is what makes blocked attention work.
- How much faster is FlashAttention than standard attention, and how much memory does it save?
- It depends on the opponent and the setting. The paper reports: BERT-large trains about 15% faster than the Nvidia MLPerf 1.1 implementation; GPT-2 trains 3.0 to 3.5 times faster than the HuggingFace implementation and about 1.7 times faster than Megatron-LM; for the attention step alone, forward plus backward is up to about 3.3 times faster from sequence length 1,024 on, and at length 4,096 it uses about one twentieth of the memory (836 MB against 17,024 MB), with memory growing linearly in the sequence length. These numbers come from A100 GPUs and 2022 baselines.
- How do FlashAttention, the KV cache and PagedAttention relate?
- They address different layers. FlashAttention optimizes the IO and memory footprint of one attention computation, which mainly matters for training and prefill. The KV cache avoids recomputing the keys and values of past tokens during decoding. PagedAttention manages the paging and fragmentation of KV-cache memory when serving. Modern training and inference systems often use all three together.
- What did FlashAttention-2 and FlashAttention-3 change?
- Both keep attention exact and improve how well the kernel uses the GPU. FlashAttention-2 reduces non-matmul work, parallelizes over the sequence length and improves the work split inside a thread block, making it about 2 times faster than the original and reaching 50% to 73% of an A100's theoretical peak FLOPs/s. FlashAttention-3 targets the H100: it overlaps computation and data movement using the asynchrony of Tensor Cores and TMA and adds FP8, running 1.5 to 2.0 times faster than FlashAttention-2 in FP16 at up to 740 TFLOPs/s.