Search

Search papers and lessons

FlashAttention: Fast and Memory-Efficient Exact Attention

Tri Dao, Daniel Y. Fu, Stefano Ermon et al. · 2022

FlashAttention computes exact attention in blocks that stay in fast on-chip memory, so the huge N by N attention matrix is never written to slow GPU memory: faster, and linear in memory.

On this page

  • Colour = topic mix
  • Linear algebra
  • Discrete math
  • Efficiency
  • Neural network basics
  • Algorithms
  • Architectures
  • Sign in to see your progress

TL;DR

Standard attention writes an N by N score matrix to GPU high-bandwidth memory (HBM), and reading and writing that matrix dominates the run time. FlashAttention computes the same exact attention output without ever materializing that matrix. It splits the inputs into blocks that fit in the GPU's small on-chip SRAM, and it keeps a running softmax so the blocks can be combined at the end. The result is up to 3 times faster than the standard PyTorch attention, with memory that grows linearly in the sequence length instead of quadratically.

Where you'll see it: almost every modern LLM training and inference stack uses a FlashAttention-style fused kernel, which is why long-context Transformers became practical.

The problem

Transformers compute self-attention, and its time and memory cost grow with the square of the sequence length NN. Many earlier "approximate attention" methods reduced the arithmetic with sparse or low-rank tricks, but they often did not run faster on real hardware. The paper's diagnosis is that they counted floating point operations (FLOPs) and ignored memory traffic. On a GPU, moving data is often the bottleneck, not the arithmetic. So a method with fewer FLOPs can still be slower.

The paper asks a narrower question: can exact attention be made fast and memory-light by being careful about where data lives while it is being computed?

Key idea

A modern GPU has a large, slow memory (HBM) and a tiny, very fast on-chip memory (SRAM). Standard attention runs as several separate kernels, and each one reads its inputs from HBM and writes its outputs back to HBM. The big intermediate matrices are written out and read back again.

FlashAttention changes the order of work. It loads a small block of keys and values into SRAM, then loads a block of queries, computes a partial attention result entirely on chip, and writes only the output block and two small per-row statistics back to HBM. Two classical techniques make this possible: tiling, which processes the sequence in blocks, and recomputation, which recreates the attention matrix in the backward pass instead of storing it.

flowchart LR
  subgraph HBM[GPU HBM: large, slow]
    K[K, V blocks]
    Q[Q blocks]
    O[Output O]
  end
  subgraph SRAM[On-chip SRAM: small, fast]
    S[Score block S_ij]
    P[Partial softmax and output]
  end
  K -->|load block j| S
  Q -->|load block i| S
  S --> P
  P -->|update running result| O

The score matrix exists only as one small block at a time, inside SRAM. It never touches HBM.

The method

Standard attention and why it is slow

Given queries, keys and values Q,K,V∈RN×d\mathbf{Q}, \mathbf{K}, \mathbf{V} \in \mathbb{R}^{N \times d}, where dd is the head dimension, standard attention computes

S=QK⊤∈RN×N,P=softmax(S)∈RN×N,O=PV∈RN×d.\mathbf{S} = \mathbf{Q}\mathbf{K}^{\top} \in \mathbb{R}^{N \times N}, \qquad \mathbf{P} = \mathrm{softmax}(\mathbf{S}) \in \mathbb{R}^{N \times N}, \qquad \mathbf{O} = \mathbf{P}\mathbf{V} \in \mathbb{R}^{N \times d}.

The softmax is applied row by row (see Softmax). The paper's implementation writes S\mathbf{S} to HBM, reads it back to compute P\mathbf{P}, writes P\mathbf{P}, and reads it again to multiply by V\mathbf{V}. Those HBM accesses scale as Θ(Nd+N2)\Theta(Nd + N^2).

Tiling a softmax

The difficulty is that softmax couples every entry in a row. To process a row one block at a time, the paper keeps a running maximum mm and a running normalizer ℓ\ell. For a vector xx split into two halves x(1)x^{(1)} and x(2)x^{(2)}, the softmax of the whole vector can be rebuilt from the halves:

m(x)=max⁡(m(x(1)),m(x(2))),ℓ(x)=em(x(1))−m(x) ℓ(x(1))+em(x(2))−m(x) ℓ(x(2)).m(x) = \max\big(m(x^{(1)}), m(x^{(2)})\big), \qquad \ell(x) = e^{m(x^{(1)}) - m(x)}\,\ell(x^{(1)}) + e^{m(x^{(2)}) - m(x)}\,\ell(x^{(2)}).

Here f(x)f(x) is the vector of shifted exponentials exi−m(x)e^{x_i - m(x)}, ℓ(x)\ell(x) is the sum of its entries, and softmax(x)=f(x)/ℓ(x)\mathrm{softmax}(x) = f(x) / \ell(x). The statistics (m,ℓ)(m, \ell) are all that is needed to merge a new block into the running result. This is the same idea as Online Softmax.

Algorithm 1 in words

The paper's Algorithm 1 loops over blocks of keys and values in an outer loop, and over blocks of queries in an inner loop. For each query block ii it keeps the partial output Oi\mathbf{O}_i and the statistics (mi,ℓi)(m_i, \ell_i). When a new key and value block jj arrives, it:

  1. Computes the small score block Sij=QiKj⊤\mathbf{S}_{ij} = \mathbf{Q}_i \mathbf{K}_j^{\top} on chip.
  2. Takes the row maximum m~ij\tilde{m}_{ij}, the exponentials P~ij=exp⁡(Sij−m~ij)\tilde{\mathbf{P}}_{ij} = \exp(\mathbf{S}_{ij} - \tilde{m}_{ij}), and their row sums ℓ~ij\tilde{\ell}_{ij}.
  3. Merges the statistics: minew=max⁡(mi,m~ij)m_i^{\text{new}} = \max(m_i, \tilde{m}_{ij}) and ℓinew=emi−minewℓi+em~ij−minewℓ~ij\ell_i^{\text{new}} = e^{m_i - m_i^{\text{new}}}\ell_i + e^{\tilde{m}_{ij} - m_i^{\text{new}}}\tilde{\ell}_{ij}.
  4. Rescales the old partial output and adds the new contribution, then writes Oi\mathbf{O}_i and the statistics back to HBM.

The paper proves that this returns exactly softmax(QK⊤)V\mathrm{softmax}(\mathbf{Q}\mathbf{K}^{\top})\mathbf{V}, using O(N2d)O(N^2 d) FLOPs, and needs only O(N)O(N) extra memory beyond the inputs and output.

Block sizes are chosen from the SRAM size MM: Bc=⌈M/4d⌉B_c = \lceil M / 4d \rceil for key and value blocks and Br=min⁡(⌈M/4d⌉,d)B_r = \min(\lceil M / 4d \rceil, d) for query blocks.

Recomputation in the backward pass

Backpropagation normally needs S\mathbf{S} and P\mathbf{P} to compute gradients with respect to Q\mathbf{Q}, K\mathbf{K} and V\mathbf{V}. Storing them costs O(N2)O(N^2) memory. FlashAttention stores only the output O\mathbf{O} and the statistics (m,ℓ)(m, \ell) from the forward pass. In the backward pass it rebuilds each block of S\mathbf{S} and P\mathbf{P} on chip from blocks of Q\mathbf{Q}, K\mathbf{K} and V\mathbf{V}. This does more arithmetic than reading the stored matrix, but it reads far less from HBM, so the backward pass is also faster. The paper describes this as a form of selective gradient checkpointing, except that earlier checkpointing schemes usually traded speed for memory and this one does not.

IO complexity

The paper's main analysis counts HBM accesses. With SRAM of size MM and d≤M≤Ndd \le M \le Nd:

  • Standard attention: Θ(Nd+N2)\Theta(Nd + N^2) HBM accesses.
  • FlashAttention: Θ(N2d2M−1)\Theta(N^2 d^2 M^{-1}) HBM accesses.

The second bound is smaller whenever d2<Md^2 < M, which holds for typical values (head dimension 64 to 128, and an SRAM of roughly 100 KB). The paper also proves a lower bound (its Proposition 3): no exact attention algorithm can achieve o(N2d2M−1)o(N^2 d^2 M^{-1}) accesses for all MM in the range [d,Nd][d, Nd]. So the algorithm is asymptotically optimal over that range of SRAM sizes, though not necessarily for any single value of MM.

Block-sparse extension

If a mask zeroes out some blocks of the attention matrix, FlashAttention can skip those blocks entirely. The paper's block-sparse variant has IO cost reduced by a factor proportional to the fraction of blocks kept. It is 2 to 4 times faster than FlashAttention and scales to sequences of 64K tokens.

Results

Training speed. On BERT-large with sequence length 512, FlashAttention reached the MLPerf 1.1 target accuracy of 72.0 percent in 17.4 minutes, against 20.0 minutes for Nvidia's MLPerf record implementation (averaged over 10 runs on 8 A100 GPUs). That is about 15 percent faster.

On GPT-2 trained on OpenWebText, the speedups were larger:

ModelImplementationPerplexityTraining timeSpeedup
GPT-2 smallHugging Face18.29.5 days1.0x
GPT-2 smallMegatron-LM18.24.7 days2.0x
GPT-2 smallFlashAttention18.22.7 days3.5x
GPT-2 mediumHugging Face14.221.0 days1.0x
GPT-2 mediumMegatron-LM14.311.5 days1.8x
GPT-2 mediumFlashAttention14.36.9 days3.0x

The paper does not change the model, so perplexity matches the baselines. Training curves were also checked to match.

Longer context. GPT-2 small with FlashAttention at context length 4K reached perplexity 17.5, against 18.2 for Megatron-LM at 1K, and it still trained about 30 percent faster (3.6 days against 4.7). On long-document classification with a pretrained RoBERTa, extending the input from 512 to 16K tokens raised MIMIC-III accuracy by 4.3 points, and extending to 8K raised ECtHR by 8.5 points.

Long-range arena. On the LRA benchmark, FlashAttention matched standard attention in average accuracy (59.8 against 59.3) while running 2.4 times faster. Block-sparse FlashAttention ran 2.8 times faster with average accuracy 59.6.

Path-X and Path-256. These tasks ask whether two points in a pixel sequence of a 128 by 128 or 256 by 256 image are connected by a path. Earlier Transformers had either run out of memory or stayed at chance. FlashAttention reached 61.4 percent accuracy on Path-X (sequence length 16K), and block-sparse FlashAttention reached 63.1 percent on Path-256 (sequence length 64K).

Attention benchmarks. Against PyTorch's attention, FlashAttention was up to 3 times faster for the forward and backward pass together, and up to 7.6 times faster on the attention computation in GPT-2. Its memory grows linearly with sequence length, and it used up to 20 times less memory than exact attention baselines. Every other baseline except Linformer ran out of memory on a 40 GB A100 before 64K, and FlashAttention was still 2 times more memory efficient than Linformer. The "up to 3 times" speedup holds for common lengths up to 2K; beyond 512 to 1024 some approximate methods, such as Linformer, start to run faster.

Why it mattered

The paper made the case that attention speed is an IO problem as much as a FLOP problem. Its open-source CUDA kernel became a default primitive in training and serving stacks, and later versions improved parallelism and hardware support. Its design also changed how people write GPU kernels: fusing several operations into one kernel, and recomputing cheap values instead of storing them, became standard tools. Longer context windows became much cheaper to train, which fed directly into the long-context models that followed.

Reading guide

Read the paper in this order and bring these prerequisites:

  1. Introduction. Needs Attention Mechanism and Transformer. The key claim is that FLOP counts do not predict wall-clock time.
  2. Section 2.1, hardware. Needs GPU Memory Hierarchy and IO Complexity. The distinction between compute-bound and memory-bound operations is here.
  3. Section 2.2, standard attention. Needs Matrix Multiplication and Softmax. Algorithm 0 is the baseline to beat.
  4. Section 3.1, algorithm. Needs Online Softmax for the block-wise softmax, and Backpropagation for the recomputation idea. Work through Algorithm 1 with a small example before reading the proofs.
  5. Section 3.2, analysis. Needs IO Complexity and Big-O Notation. The bounds and the lower bound are the theory core.
  6. Section 4, experiments. Needs Transformer for what is being trained. The tables are self-contained once the setup is clear.
  7. Appendix B. The forward and backward pass details, needed for Backpropagation.

Check yourself

QuestionWhy does a method with fewer FLOPs sometimes run slower than standard attention on a GPU?Show answer

GPU run time is often set by how much data moves between HBM and the compute units, not by arithmetic. A method can cut FLOPs but still read and write large intermediate matrices, or access memory in a scattered way, so its wall-clock time can stay the same or get worse. The paper's argument is that IO, not FLOPs, decides the speed of attention.

QuestionLet x = [1, 3, 2, 0] be split into x1 = [1, 3] and x2 = [2, 0]. Find the running maximum m and normalizer ell after both blocks, and check the first softmax entry.Show answer

For x1, m1 = 3 and the shifted exponentials are e^(-2) and 1, so ell1 = 1.1353. For x2, m2 = 2 and the shifted exponentials are 1 and e^(-2), so ell2 = 1.1353. Merging gives m = max(3, 2) = 3 and ell = e^(0) times 1.1353 plus e^(-1) times 1.1353, which is 1.5530. The full softmax of x is about [0.0871, 0.6439, 0.2369, 0.0321]. Dividing the merged shifted exponentials [0.1353, 1, 0.3679, 0.0498] by 1.5530 gives the same first entry, 0.0871, so the block merge is exact.

QuestionCompute the block sizes for head dimension d = 64 and SRAM size M = 50,000 elements. Then say how many HBM accesses the two methods need, up to constants, if N = 1024.Show answer

The key block size is ceil(M / 4d) = ceil(50000 / 256) = ceil(195.3) = 196. The query block size is min(196, 64) = 64. For the access counts, standard attention needs about N squared plus N d, which is 1,048,576 + 65,536 = 1,114,112. FlashAttention needs about N squared times d squared over M, which is 1,048,576 times 4096 divided by 50,000, or about 85,900. Constants are dropped, so the ratio of about 13 is a rough guide. The paper's measured reduction in Figure 2 (GPT-2 medium, N = 1024, d = 64) is about 9 times, because the constants matter in practice.

QuestionWhy does FlashAttention store only the output and the softmax statistics instead of the attention matrix, and why does that not make training slower?Show answer

The backward pass needs the attention matrix to compute gradients. Storing it costs N squared memory. Instead, FlashAttention stores the output and the running maximum and normalizer, which are O(N) in size, and rebuilds the needed blocks on chip. Rebuilding costs extra arithmetic, but it avoids the much larger HBM reads of the stored matrix. Since HBM traffic dominates, the backward pass is faster overall, as Figure 2 of the paper shows.

QuestionA team wants to train a model on 16K-token documents. Name one reason to choose FlashAttention and one situation where it would not help.Show answer

It helps because the memory cost grows linearly in N rather than quadratically, so a 16K context fits where standard attention would run out of memory, and it avoids the slow HBM traffic. It would not help much when the bottleneck is elsewhere, for example when sequences are very short so that the attention cost is small compared with the feedforward layers, or on hardware that does not have a comparable fast on-chip memory. The paper also notes that approximate methods can overtake it on very long sequences if they are allowed to trade quality for speed.

Sources

Read the full paper

Tri Dao, Daniel Y. Fu, Stefano Ermon et al., 2022. arXiv:2205.14135