Search

Search papers and lessons

FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision

Jay Shah, Ganesh Bikshandi, Ying Zhang et al. · 2024

FlashAttention-3 makes exact attention faster on Hopper GPUs by overlapping data movement, matrix multiplies and softmax, and it adds an FP8 path that stays accurate through block quantization.

On this page

  • Colour = topic mix
  • Systems
  • Discrete math
  • Neural network basics
  • Linear algebra
  • Efficiency
  • Calculus
  • ReadReady to readNot yet

TL;DR

Attention is the expensive step in a Transformer, and the earlier FlashAttention papers made it fast by keeping its large intermediate matrices out of slow GPU memory. FlashAttention-3 rebuilds that kernel for NVIDIA's Hopper GPUs, so that data copies, matrix multiplies and softmax run at the same time instead of one after another. It also adds a low-precision FP8 version that keeps its error low with two scaling tricks. On an H100 the forward pass runs 1.5 to 2.0 times faster than FlashAttention-2, reaching up to 740 TFLOPs/s.

Builds on: FlashAttention, Tensor Core, Warp Specialization, GPU Memory Hierarchy, Quantization · Leads to: kernels in current attention libraries that target newer GPUs and FP8 hardware

Why it mattered

Long-context language models spend much of their run time in attention, so a faster attention kernel changes what is practical. The paper's code is open source in the Dao-AILab flash-attention repository, and the authors planned to integrate it with PyTorch and Hugging Face, so model code could pick up the speedups without changes to the model. The paper reports that FP8 attention with its accuracy fixes reaches close to 1.2 PFLOPs/s on an H100, which is the kind of number that makes low precision worth the engineering. Semantic Scholar records about 880 citations for it.

It also showed a pattern that later kernel work follows: on a new GPU, the fastest code is written around the chip's asynchronous units, not around a generic programming model. FlashAttention-2 reached only about 35 percent of the H100's peak, while well-tuned matrix multiplication kernels reach 80 to 90 percent on the same chip. Closing that gap was the paper's goal.

The problem

FlashAttention-2 was already exact and memory-efficient, but it ran on Hopper as if the GPU were the older Ampere design. It issued its work in a synchronous sequence: load a block, multiply, apply softmax, multiply again, write out. Each step waited for the one before it. Hopper has hardware that can do these jobs concurrently. A dedicated copy unit (the Tensor Memory Accelerator, TMA) moves data from the large memory into shared memory, and the matrix units (Tensor Cores, driven by an asynchronous WGMMA instruction) can run while the ordinary arithmetic units do other work.

Two problems stood in the way. First, softmax depends on the output of the first matrix multiply and feeds the second one, so the three cannot simply run in parallel. Second, the Tensor Cores can run in FP8, which doubles their throughput, but FP8 has only 3 mantissa bits and 4 exponent bits (the e4m3 format). Large language models contain outlier values that are far larger than most entries, and with one scale per whole tensor those outliers push the other values into a few coarse levels. The paper asks how to use asynchrony and FP8 without losing the exactness and accuracy that made FlashAttention useful.

How it works

The forward pass is organized as a pipeline inside one GPU thread block. The paper gives three pieces, and they are easiest to follow as a single traced flow.

  1. The inputs are the query, key and value matrices Q, K and V, stored in the GPU's large memory (HBM). The kernel splits the query rows into tiles and the keys and values into blocks. One tile of Q is processed against all key-value blocks in turn.
  2. Warp specialization splits the thread block into two roles. A producer warpgroup does only data movement: it uses TMA to load the next key and value block into a small ring of shared memory buffers and signals when the block is ready. Consumer warpgroups do only computation: they wait for the signal, multiply, and release the buffer. The producer never waits on arithmetic, so loads overlap with compute.
  3. Each consumer multiplies its query tile by the key block (the first matrix multiply, S = Q times K-transpose), then computes softmax on the resulting score block and multiplies by the value block (the second matrix multiply). A running maximum and running sum, as in Online Softmax, let each block be processed on its own.
  4. The third idea is to overlap step 3 across blocks. While softmax works on the scores of block j, the Tensor Cores compute the scores of block j+1. The paper calls this a 2-stage pipeline. It keeps one extra score block, S_next, in registers alongside the current one.
  5. Two warpgroups can also be scheduled in turn, so one warpgroup's softmax runs while the other's matrix multiplies run. The paper calls this pingpong scheduling.
  6. The output tile and a per-row log-sum-exp value are written back to HBM once, at the end.

Check after each step: no full N by N score matrix is ever written to HBM, the producer and consumer roles never swap, and the output is the same exact attention as before.

To see why overlap helps, take a toy case with made-up round numbers (these are illustrative, not from the paper): each block needs 10 time units on the Tensor Cores and 4 units of softmax work. Run in sequence, each block costs 14 units. Run with softmax of block j overlapping the matrix multiply of block j+1, each block after the first costs about 10 units, because the 4 units hide inside the 10. The paper's real gains are smaller than this ideal, since the compiler reorders instructions and extra registers are needed, but the direction is the same.

The math

Attention for one head, with sequence length N and head dimension d, is

S=αQK⊤,P=softmax(S),O=PV,\mathbf{S}=\alpha\mathbf{Q}\mathbf{K}^{\top},\qquad \mathbf{P}=\mathrm{softmax}(\mathbf{S}),\qquad \mathbf{O}=\mathbf{P}\mathbf{V},

where α=1/d\alpha = 1/\sqrt{d} is a scaling constant and softmax is applied row by row. Every entry of S\mathbf{S} and P\mathbf{P} is an N by N table, which is why standard attention is memory-heavy.

Step 2 in symbols: the producer and the buffer

The producer loads blocks Kj,Vj\mathbf{K}_j, \mathbf{V}_j into a ring of ss buffer stages. Stage (j mod s)(j \bmod s) is reused for block jj only after the consumers have released it. This is a standard bounded buffer: the producer can run at most ss blocks ahead of the consumers.

Step 3 in symbols: the running softmax

For one query tile, keep a running maximum mm, a running sum ℓ\ell and a running output O\mathbf{O}. When block jj arrives, with scores S(j)\mathbf{S}^{(j)},

mnew=max⁡(mold,rowmax(S(j))),P~(j)=exp⁡(S(j)−mnew),m^{\text{new}} = \max\left(m^{\text{old}}, \mathrm{rowmax}(\mathbf{S}^{(j)})\right), \qquad \widetilde{\mathbf{P}}^{(j)} = \exp\left(\mathbf{S}^{(j)} - m^{\text{new}}\right), ℓ=exp⁡(mold−mnew)ℓ+rowsum(P~(j)),O←diag(exp⁡(mold−mnew))O+P~(j)Vj.\ell = \exp\left(m^{\text{old}} - m^{\text{new}}\right)\ell + \mathrm{rowsum}\left(\widetilde{\mathbf{P}}^{(j)}\right), \qquad \mathbf{O} \leftarrow \mathrm{diag}\left(\exp(m^{\text{old}} - m^{\text{new}})\right)\mathbf{O} + \widetilde{\mathbf{P}}^{(j)}\mathbf{V}_j.

At the end, O\mathbf{O} is divided by ℓ\ell. This is the same rescaling that makes softmax streamable, so the blocks can be processed in any order that keeps the update consistent.

Step 4 in symbols: when the overlap is possible

Softmax of block jj needs S(j)\mathbf{S}^{(j)}, and the second multiply for block jj needs P~(j)\widetilde{\mathbf{P}}^{(j)}. The 2-stage schedule computes Snext=QKj+1⊤\mathbf{S}^{\text{next}} = \mathbf{Q}\mathbf{K}_{j+1}^{\top} while the softmax of Scur\mathbf{S}^{\text{cur}} runs on the arithmetic units. The two operations touch different data, so they do not wait for each other.

FP8 scaling in symbols

With one scalar per block, a block X\mathbf{X} is stored as X≈cX⋅X^\mathbf{X} \approx c_X \cdot \hat{\mathbf{X}}, where X^\hat{\mathbf{X}} is the FP8 values and cXc_X is that block's scale. Incoherent processing uses an orthogonal matrix M\mathbf{M} (a square matrix whose transpose is its inverse, so MM⊤=I\mathbf{M}\mathbf{M}^{\top} = \mathbf{I}). Replacing Q\mathbf{Q} and K\mathbf{K} by QM\mathbf{Q}\mathbf{M} and KM\mathbf{K}\mathbf{M} leaves the scores unchanged, because

(QM)(KM)⊤=QMM⊤K⊤=QK⊤.(\mathbf{Q}\mathbf{M})(\mathbf{K}\mathbf{M})^{\top} = \mathbf{Q}\mathbf{M}\mathbf{M}^{\top}\mathbf{K}^{\top} = \mathbf{Q}\mathbf{K}^{\top}.

The rotation spreads a single large outlier across many entries, which narrows the range each FP8 block has to cover. The paper's choice of M\mathbf{M} is a product of a random diagonal matrix of plus and minus ones and a Hadamard matrix, a structured orthogonal matrix that can be applied in O(dlog⁡d)O(d \log d) operations instead of O(d2)O(d^2).

Cost of the benchmark

The paper counts forward attention FLOPs as 4⋅N2⋅d⋅h4 \cdot N^2 \cdot d \cdot h for hh heads, halves the count for causal masking (which zeroes out half the score matrix), and counts the backward pass as 2.5 times the forward pass, because the backward pass runs five matrix multiplies to the forward pass's two.

Results

On an H100 SXM5 with FP16 inputs, the forward pass of FlashAttention-3 is 1.5 to 2.0 times faster than FlashAttention-2 and reaches up to 740 TFLOPs/s, about 75 percent of the chip's theoretical peak. The backward pass is 1.5 to 1.75 times faster. Against a standard PyTorch attention, the gap is up to 3 to 16 times. For medium and long sequences (1k tokens and up) the paper reports that it also beats the closed-source cuDNN attention on this chip.

The ablation in the paper isolates the two asynchrony ideas. For one fixed setting, the full kernel runs at 661 TFLOPs/s. Removing the GEMM-softmax pipelining but keeping warp specialization gives 582, and keeping the pipelining but removing warp specialization gives 570. The paper also reports that pingpong scheduling raised one FP16 setting (head dimension 128, sequence length 8192) from 570 to 620-640 TFLOPs/s.

For FP8, the paper reports close to 1.2 PFLOPs/s in the forward pass. Accuracy is measured against an FP64 reference, on inputs built to contain outliers, with each entry drawn from a normal distribution with standard deviation 1 plus, for 0.1 percent of entries, an extra term with standard deviation 10. In FP16, the standard attention baseline has a root-mean-square error of 3.2e-4, and FlashAttention-2 and FlashAttention-3 both have 1.9e-4, because the softmax intermediate values are kept in FP32. In FP8, FlashAttention-3 with block quantization and incoherent processing has 2.6 times lower error than an FP8 baseline that uses one scale per tensor.

Limits. The paper focuses on Hopper and on the forward pass in FP8. It notes that FP8 FlashAttention-3 does not use a persistent kernel and load balancing as the FP16 version does, so it trails cuDNN's FP8 kernels for short sequences and for causal masking. It leaves inference-specific optimization and long-run training effects of low precision to future work. Its results are benchmarks on one GPU model, so the speedups are a statement about that hardware.

Common misreadings. It is tempting to think FlashAttention-3 approximates attention to go faster. In fact it computes the same exact softmax attention in FP16; the approximation is only in the FP8 path, and it is measured against a reference. It is tempting to think the speedup comes from fewer operations. In fact the FLOP count is the same; the gain comes from keeping the matrix units busy while the arithmetic units do softmax.

Reading guide

The chain of ideas is: the GPU's memory levels and its asynchronous units, the warp-specialized pipeline that uses them, the softmax rescaling that lets blocks overlap, and the FP8 accuracy fixes. Read the sections in this order.

Check yourself

QuestionFlashAttention-2 reaches about 35 percent of the H100's peak on attention, while good matrix multiply kernels reach 80 to 90 percent. Which parts of the GPU does FlashAttention-3 try to keep busy at the same time, and why does that help?Show answer

The producer warpgroup keeps the data copy unit busy, moving the next key and value blocks into shared memory, while the consumer warpgroups keep the matrix units busy. Softmax runs on the ordinary arithmetic units during the same stretch of time, so the matrix units are not idle while softmax runs. Overlapping work that uses different hardware removes waiting time without changing the number of operations.

QuestionThe 2-stage pipeline keeps one extra score block, S_next, in FP32 registers. If a thread block's score block has 16 rows and 128 columns, how many bytes does S_next take?Show answer

S_next has 16 times 128 = 2048 entries, each a 4-byte FP32 value, so it takes 2048 times 4 = 8192 bytes, or 8 KiB. The example shows why the paper warns about register pressure: the cost grows with the product of the block sizes.

QuestionWhy does multiplying Q and K by the same orthogonal matrix M leave the attention scores unchanged, and why does that help FP8 quantization?Show answer

The scores are Q times K-transpose. With the rotation, they become (QM)(KM) transposed, which equals Q M M-transpose K-transpose. Since M M-transpose is the identity, this is again Q K-transpose, so the scores are the same. The rotation changes the entries of Q and K, spreading any large outlier across many entries, so each FP8 block covers a smaller range and rounds less coarsely. The result is the same in exact arithmetic; only the rounding error changes.

Sources

Read the full paper

Jay Shah, Ganesh Bikshandi, Ying Zhang et al., 2024. arXiv:2407.08608