Search

Search papers and lessons

FlashAttention-2: Faster Attention with Better Parallelism

Tri Dao · 2023

Dao (2023) makes exact attention about twice as fast as FlashAttention by reducing non-matmul work and spreading each attention head across more GPU thread blocks and warps.

On this page

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

TL;DR

FlashAttention computes exact attention without writing the N by N score matrix to slow GPU memory, but it reached only a fraction of the GPU's peak arithmetic speed. FlashAttention-2 keeps the same exact output and fixes the work split: it does fewer non-matmul operations, parallelises over the sequence length as well as batch and heads, and divides work between warps to avoid shared-memory traffic. The paper reports about 2 times the speed of FlashAttention, reaching up to 73 percent of peak forward throughput on an A100.

Where you'll see it: the attention kernel used to train and serve long-context Transformers on NVIDIA GPUs.

The problem

Attention needs time and memory that grow with the square of the sequence length. The first FlashAttention paper removed the memory growth by tiling, so memory became linear in NN and wall-clock time dropped by 2 to 4 times against optimised baselines. Dao points out that this was still far from the hardware limit. Optimised matrix-multiply (GEMM) kernels reach 80 to 90 percent of the device's peak, while FlashAttention's forward pass reached 30 to 50 percent of peak and its backward pass 25 to 35 percent in the paper's introduction. (The abstract gives a wider range, 25 to 40 percent, for the same gap.)

Dao's diagnosis is that the remaining gap is not in the maths but in how the work is laid out on the GPU. Two problems are named: some thread blocks sit idle because there are too few of them for long sequences with small batches, and inside each block the warps spend time moving partial results through shared memory when they could keep them in registers. Both lower the effective throughput even though the algorithm reads and writes HBM the same amount as before.

Key idea

Dao's core observation is that a GPU's matrix-multiply units are so much faster than its other arithmetic that every non-matmul operation is expensive. On an A100, FP16 and BF16 matmul has a theoretical peak of 312 TFLOPs/s, while non-matmul FP32 work peaks at 19.5 TFLOPs/s. The paper states this as each non-matmul FLOP costing about 16 times as much as a matmul FLOP. The goal is therefore to keep as much time as possible in matmul.

From that, three changes follow. Reduce the non-matmul work inside the online softmax, as in Online Softmax, by rescaling the output once at the end rather than on every block. Parallelise over the query rows of the attention matrix so that even one head of a long sequence can keep many thread blocks busy. Split the work inside a block across warps so that they do not need to combine partial sums through shared memory. None of these changes the output. The result is still exact attention.

flowchart TD
  A[FlashAttention: loop over key blocks inside one thread block per head] --> B[Low occupancy for long sequences and small batches]
  A --> C[Warps split K and V and must reduce partial sums through shared memory]
  A --> D[Extra non-matmul FLOPs in the softmax rescaling]
  B --> E[Parallelise over sequence length]
  C --> F[Split Q across warps instead]
  D --> G[Delay the output rescale to the end of the loop]

The method

The method has three parts, each an answer to one of the bottlenecks above. Notation follows the paper: Q,K,V∈RN×d\mathbf{Q}, \mathbf{K}, \mathbf{V} \in \mathbb{R}^{N \times d} with sequence length NN and head dimension dd, and O\mathbf{O} the output.

Fewer non-matmul operations in the forward pass

The paper starts from the online softmax identity used by FlashAttention: Fast and Memory-Efficient Exact Attention. For a block of scores, the running maximum mm and running sum ℓ\ell of exponentials are kept per row, and the output is rescaled when the maximum changes. FlashAttention rescales the output on every block. FlashAttention-2 keeps an unscaled accumulator O~\tilde{\mathbf{O}} and divides by the running sum only once, after the last block:

O~(j)=diag(em(j−1)−m(j))O~(j−1)+eS(j)−m(j)V(j),O=diag(ℓ(last))−1O~(last)\tilde{\mathbf{O}}^{(j)} = \mathrm{diag}\big(e^{m^{(j-1)} - m^{(j)}}\big) \tilde{\mathbf{O}}^{(j-1)} + e^{\mathbf{S}^{(j)} - m^{(j)}} \mathbf{V}^{(j)}, \qquad \mathbf{O} = \mathrm{diag}\big(\ell^{(\text{last})}\big)^{-1} \tilde{\mathbf{O}}^{(\text{last})}

Here S(j)=QKj⊤\mathbf{S}^{(j)} = \mathbf{Q}\mathbf{K}_j^{\top} is the score block for key block jj, and V(j)\mathbf{V}^{(j)} is the matching value block. The paper also stores only one statistic per row for the backward pass, the logsumexp L(j)=m(j)+log⁡ℓ(j)L^{(j)} = m^{(j)} + \log \ell^{(j)}, instead of both mm and ℓ\ell. Algorithm 1 in the paper is the complete loop, with the outer loop over row blocks of Q\mathbf{Q} and the inner loop over column blocks of K\mathbf{K} and V\mathbf{V}. This is the reverse of the original FlashAttention order, and the paper credits Phil Tillet's Triton implementation for the reordering and for the sequence-length parallelism.

Causal masking gets a separate saving. Blocks entirely above the diagonal are skipped, which is about half the blocks for long sequences, and only the diagonal blocks need the mask applied. The paper reports a 1.7 to 1.8 times speedup from this relative to attention without a causal mask.

Parallelism over the sequence length

FlashAttention assigns one thread block to each attention head, so the number of blocks is batch size times number of heads. On an A100 with 108 streaming multiprocessors, the paper says this keeps the GPU well used when that product is at least about 80. For long sequences with small batches it is not.

FlashAttention-2 adds the sequence-length dimension to the grid. In the forward pass, each thread block owns one block of rows of the output, and these blocks are independent, so they need no communication. In the backward pass, the natural parallel unit is a block of columns of K\mathbf{K} and V\mathbf{V}, but the gradient dQd\mathbf{Q} is then summed across blocks. The paper handles this with atomic adds into dQd\mathbf{Q} in HBM. Both changes raise occupancy, the fraction of the GPU's resources in use, when batch and head count are small.

Work partitioning between warps

A thread block typically has 4 or 8 warps. In FlashAttention, the forward pass split K\mathbf{K} and V\mathbf{V} across the 4 warps and kept Q\mathbf{Q} visible to all of them. Each warp computed a slice of QK⊤\mathbf{Q}\mathbf{K}^{\top}, then needed the others' partial results to multiply by V\mathbf{V}, which forced a round trip through shared memory and a synchronisation. This is the "split-K" scheme.

FlashAttention-2 splits Q\mathbf{Q} across the warps and gives every warp the whole of K\mathbf{K} and V\mathbf{V}. Each warp then multiplies its slice of Q\mathbf{Q} by K⊤\mathbf{K}^{\top}, then by V\mathbf{V}, and writes its own rows of the output. No communication between warps is needed in the forward pass. The backward pass still needs some synchronisation because of the dependencies between dQ\mathbf{dQ}, dK\mathbf{dK} and dV\mathbf{dV}, but the paper says avoiding split-K still reduces shared-memory traffic and speeds it up.

Block sizes are chosen from {64,128}×{64,128}\{64, 128\} \times \{64, 128\} depending on the head dimension and the shared-memory size of the device. The paper tunes them by hand for each head dimension and leaves auto-tuning to future work.

Backward pass and grouped attention

The backward pass is changed only in the statistic it uses. It needs LL alone, so the row maxima and sums are not stored. Multi-query and grouped-query attention, where several query heads share one key and value head, are handled by indexing: the kernel reads the shared key and value heads for each query head, and in the backward pass the gradients for the shared heads are summed across the heads that used them. This is the reason the method can serve the smaller KV cache used by Multi-Query Attention and Grouped-Query Attention without making copies.

Results

All benchmarks are on an A100 80GB SXM4. The attention benchmark uses 16k total tokens per batch, a hidden size of 2048, and head dimension 64 or 128. The paper computes forward FLOPs as 4⋅seqlen2⋅head dim⋅heads4 \cdot \text{seqlen}^2 \cdot \text{head dim} \cdot \text{heads}, halves it for causal attention, and takes the backward pass as 2.5 times the forward pass.

Attention kernel. Across sequence lengths from 512 to 16k, the paper reports FlashAttention-2 at 1.7 to 3.0 times the speed of FlashAttention, 1.3 to 2.5 times the speed of FlashAttention in Triton, and 3 to 10 times the speed of a standard PyTorch attention. The best case is about 230 TFLOPs/s, 73 percent of the A100's theoretical maximum. The text of Section 4.1 summarises the gain over FlashAttention as "around 2 times", which is the figure most often quoted.

Backward and forward. The introduction gives the peak fractions as up to 73 percent of maximum throughput in the forward pass and up to 63 percent in the backward pass. The abstract gives a range of 50 to 73 percent for the same comparison. The forward pass is the easier of the two because it has fewer matmuls: two per block, against five in the backward pass.

Other hardware. On an H100, running the same implementation with no Hopper-specific instructions reached up to 335 TFLOPs/s (Figure 7 in the paper). The paper expects a further 1.5 to 2 times from using the newer features, but leaves that to future work.

End to end. The paper trains GPT-style models with 1.3B and 2.7B parameters on 8 A100s, at sequence lengths 2k and 8k. Table 1 reports training throughput in TFLOPs/s per GPU:

ModelNo FlashAttentionFlashAttentionFlashAttention-2
GPT-3 1.3B, 2k context142189196
GPT-3 1.3B, 8k context72170220
GPT-3 2.7B, 2k context149189205
GPT-3 2.7B, 8k context80175225

At the largest setting, FlashAttention-2 reaches 225 TFLOPs/s per GPU, which the paper reports as 72 percent model FLOPs utilisation. Against the baseline without FlashAttention the speedup is up to 2.8 times, and against FlashAttention about 1.3 times. The paper computes model FLOPs with the Megatron-LM formula and does not halve the attention term for causal masking, for consistency with the literature.

Example
Reading a row of Table 1

Take the GPT-3 2.7B model at 8k context.

  1. FlashAttention: 175 TFLOPs/s per GPU.
  2. FlashAttention-2: 225 TFLOPs/s per GPU.
  3. Ratio: 225/175=1.286225 / 175 = 1.286, which the paper rounds to 1.3.
  4. Against the baseline without FlashAttention: 225/80=2.81225 / 80 = 2.81, which the paper rounds to 2.8.

Interpretation: at long context the end-to-end gain over FlashAttention is smaller than the kernel-level gain of about 2 times. The model also spends time in the feed-forward layers and in communication, which the attention kernel does not speed up. The 72 percent utilisation figure is a fraction of the A100's peak, so it is the efficiency the whole model reaches, not the efficiency of attention alone.

Why it mattered

The paper's own claim is practical: a 2 times faster attention kernel lets a model with 16k context be trained for about the price of an 8k model. It names long documents, high-resolution images, audio and video as the uses it has in mind, and it says FlashAttention-2 speeds up training, fine-tuning and inference of existing models without changing their weights.

The paper also says what it plans next: optimise for H100 features such as the TMA unit, fourth-generation Tensor Cores and FP8, and combine the kernel work with sparse or local attention patterns. Those are stated as plans. Later uses of the kernel are not part of the paper's own text and are not described here.

Reading guide

Read the paper in this order and bring these lessons with you.

  • Section 1, Introduction. Needs FlashAttention: Fast and Memory-Efficient Exact Attention for the baseline and the claim that FlashAttention is 2 to 4 times faster than standard attention. Also needs Attention Mechanism for what attention computes.
  • Section 2.1, Hardware characteristics. Needs GPU Memory Hierarchy for HBM, shared memory, thread blocks, warps and streaming multiprocessors. Without it the numbers 1.5 to 2 TB/s and 19 TB/s look arbitrary.
  • Section 2.2, Standard attention. Needs Matrix Multiplication for the three matmuls, and Softmax for the row-wise normalisation. Also needs IO Complexity to see why the N×NN \times N intermediates matter.
  • Section 2.3, FlashAttention. Needs Online Softmax, the streaming softmax with a running maximum and sum. Algorithm 1 in Section 3.1 is a variant of this loop, so read Section 2.3 closely first.
  • Section 3.1, Algorithm. Needs the online softmax identities above. The new idea is the unscaled accumulator and the logsumexp statistic. The causal-mask saving depends on the block structure, which is in the same section.
  • Section 3.2, Parallelism. Needs the idea of occupancy from GPU Memory Hierarchy. The atomic add into dQd\mathbf{Q} is the one communication point across thread blocks.
  • Section 3.3, Warps. Needs the difference between splitting K and V across warps and splitting Q. Figures 2 and 3 show it. Read this section alongside the warp layout diagrams.
  • Section 4, Empirical validation. Needs Transformer to know what the GPT-style models are, and the FLOP formulas. The table is short and can be read against the text.

Check yourself

QuestionFlashAttention-2 keeps the output of exact attention. What is the one place it changes how the online softmax is maintained, and why does that matter for speed?Show answer

It keeps an unscaled output accumulator and divides by the running sum once, after the last key block, instead of rescaling the output on every block. The rescaling is a non-matmul operation, and on an A100 a non-matmul FLOP costs about 16 times as much as a matmul FLOP, so removing most of the rescaling saves time without changing the result.

QuestionOn an A100 with 108 streaming multiprocessors, a model has batch size 2 and 16 heads, with one attention layer on a long sequence. Using the paper's rule that about 80 or more thread blocks keep the GPU busy, why does FlashAttention leave much of the GPU idle, and what does FlashAttention-2 change?Show answer

FlashAttention assigns one thread block per batch element and head, so there are only 2 times 16 equals 32 blocks, well under 80 and well under the 108 multiprocessors. FlashAttention-2 adds parallelism over the sequence length, so each head is split into independent row blocks, giving many more thread blocks that can run at once.

QuestionWhy does the paper split Q across warps in the forward pass instead of K and V?Show answer

With split-K, each warp computes a slice of the scores with a slice of K and then needs the others' partial results to multiply by V. The partial sums go through shared memory and need synchronisation. With Q split, each warp computes its own rows of the scores and output with the full K and V, so no partial results need to be combined between warps.

QuestionThe paper reports 225 TFLOPs/s per A100 at 8k context for the 2.7B model, against 175 TFLOPs/s for FlashAttention. What is the speedup, and why is it smaller than the roughly 2 times gain on the attention kernel?Show answer

The speedup is 225/175≈1.29225 / 175 \approx 1.29, which the paper rounds to 1.3. The attention kernel is only part of the model's compute. The feed-forward layers, the output projections and communication between GPUs run at their own speeds, so improving attention alone raises the end-to-end figure less than the kernel figure.

Sources

Read the full paper

Tri Dao, 2023. arXiv:2307.08691