Papers · 2022 · Reading: 26 min, plus 3 in closed details.
Paper · NeurIPS 2022 · arXiv 2205.14135

FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (FlashAttention)

Tri Dao, Daniel Y. Fu, Stefano Ermon, Atri Rudra, Christopher Ré
Stanford University (Hazy Research) and University at Buffalo, SUNY · May 2022 (arXiv v1); v2 June 2022; published at NeurIPS 2022

In one line: Exact attention made up to 3x faster than standard attention at sequence lengths 128 to 2K (7.6x on GPT-2's attention) and linear in memory by tiling + online softmax + backward recomputation in one fused CUDA kernel, showing that HBM reads and writes, not FLOPs, bound attention's runtime on GPUs: the kernel does more FLOPs yet runs faster.

9× fewer HBM bytes
40.3 GB down to 4.4 GB, GPT-2 medium attention, forward + backward
5.7× faster although it does 13% more arithmetic · Figure 2
20× less memory
than PyTorch attention at sequence length 4K
memory linear in N; up to 3.3× faster for N = 128 to 2K · Table 21
61.4% on Path-X
the first Transformer above chance (50%) at 16K tokens
block-sparse: 63.1% on Path-256 at 64K · Table 6

How far to trust it: Believe the algorithm and the kernel benchmarks: exactness is proved, the IO argument is checkable, and every major framework has shipped it since. Treat the end-to-end training speedups and the long-context quality gains as single runs against baselines that were not always run like for like. The evidence, judged.

The idea in one sentence: attention on a GPU is slow because it pushes the N × N score matrix through slow high-bandwidth memory (HBM), not because of its arithmetic; FlashAttention computes exact attention tile by tile in on-chip SRAM, finishing the softmax block by block with a running maximum and sum and recomputing tiles in the backward pass, so the N × N matrix never touches HBM: on GPT-2 medium 9.2× less memory traffic and 5.7× faster, despite 13% more FLOPs.

Fig. 1 · Same output, far fewer trips to HBM

  1. Two memories. The large HBM slab: 40 to 80 GB at 1.5 to 2.0 TB/s. The small SRAM slab above it: 192 KB on chip in each of the A100's 108 streaming multiprocessors, about 19 TB/s. Q, K and V (N × d each) start in HBM.
  2. Standard attention, kernel 1: S = QKT goes to HBM. Q and K come up to the chip; the whole N × N score matrix S goes back down, 16 times the size of Q at N = 1,024 and d = 64.
  3. Kernel 2: softmax reads S and writes P. A second N × N round trip: softmax does a few operations per value, so this kernel is all memory traffic.
  4. Kernel 3: O = PV, and P stays for the backward pass. P and V come up, O goes down; P stays in HBM for the gradients. An N × N matrix crossed the HBM boundary four times.
  5. FlashAttention: one fused kernel, tiles stay on chip. Blocks of Q, K and V come up; each tile of S and P is computed in SRAM and dropped; only O and two numbers per row, the running maximum m and sum ℓ, go back. The N × N plates are never stored (faint).
  6. The bill, Figure 2. HBM traffic 40.3 GB against 4.4 GB, runtime 41.7 ms against 7.3 ms, with 66.6 against 75.2 GFLOPs: 13% more arithmetic (recomputation), yet far faster. Ratios: 40.3 / 4.4 = 9.2× less traffic, 41.7 / 7.3 = 5.7× faster.

Numbers from the paper's Figure 2 (GPT-2 medium attention: N = 1,024, d = 64, 16 heads × batch 64, forward and backward, one A100) and §2.1; the idea of its Figure 1 (left). Q, K, V, S and P are drawn to scale for N = 1,024, d = 64; the two slabs and the streams are schematic (stream width shows N × N against N × d, not exact bytes). Figure 2 below counts them exactly.

You need: what makes a kernel memory-bound (arithmetic intensity, the roofline) is taught on Performance math; the GPU's memory levels as a programmer sees them on Memory hierarchy; the FlashAttention algorithm across its four versions, written and measured as kernels, on Writing kernels. This page is the 2022 paper. New terms: HBM (the GPU's large off-chip memory); SRAM (the small on-chip memory of each streaming multiprocessor); IO-aware (designed around reads and writes between memory levels); M (SRAM size, in values); Br, Bc (rows per block of Q and of K, V); m, ℓ (each row's running maximum and running sum, the online softmax's state); recomputation (rebuilding S and P in the backward pass instead of storing them).

Problem

§1 Introduction

Self-attention costs time and memory quadratic in the sequence length N, and that is the binding constraint on how much context a Transformer can take (§1). A wave of approximate attention methods had attacked it: sparse approximations (Reformer, sparse attention), low-rank ones (Linformer, Performer) and combinations of the two. They cut the FLOP count to linear or near-linear in N, yet "many of them do not display wall-clock speedup against standard attention and have not gained wide adoption" (§1).

The diagnosis: FLOPs are the wrong cost model. On a GPU attention is memory-bound: what costs time is moving data between the large, slow high-bandwidth memory (HBM) and the small, fast on-chip SRAM. The paper's word for designing around that is IO-aware: an algorithm that carefully accounts for reads and writes between levels of memory (§1, after Aggarwal and Vitter's IO complexity of sorting).

Nobody had made attention IO-aware because the frameworks would not let them: "common Python interfaces to deep learning such as PyTorch and Tensorflow do not allow fine-grained control of memory access" (§1). It takes a hand-written CUDA kernel.

The GPU's memory, and why attention waits on it

§2.1 Hardware Performance

On an A100 the two levels look like this (§2.1): 40 to 80 GB of HBM at 1.5 to 2.0 TB/s, and 192 KB of on-chip SRAM in each of its 108 streaming multiprocessors, with bandwidth estimated around 19 TB/s. The SRAM is an order of magnitude faster and many orders of magnitude smaller.

A GPU runs an operation as a kernel: it loads inputs from HBM into registers and SRAM, computes, and writes the outputs back to HBM. Whether a kernel is limited by arithmetic or by memory depends on its arithmetic intensity, the operations per byte moved (§2.1; the roofline in general is on Performance math). Matrix multiplies with a large inner dimension are compute-bound. Most other operations are memory-bound: elementwise ones (activation, dropout) and reductions (sum, softmax, batch norm, layer norm). The usual cure for memory-bound work is kernel fusion: load the input once and apply several operations to it. Compilers fuse elementwise operations automatically, but in training the intermediate values still have to be written to HBM for the backward pass, which defeats naive fusion.

SRAM: about 13 times faster, nearly 2,000 times smaller

Drawn on log scales from the numbers in §2.1. Total SRAM is 108 × 192 KB = 20.25 MiB (21.2 MB); the bandwidth ratio is 19 / 1.5 = 12.7; 40 GB of HBM is 1,887 times the 21.2 MB of SRAM.

A Tesla P100 package photographed in near infrared: the large GP100 GPU die in the centre, with two HBM2 memory stacks on each side, all on one interposer
What is next to what. The GPU die in the centre carries every streaming multiprocessor and its SRAM; the four rectangles beside it are HBM stacks, millimetres away on the same interposer, yet every byte between them crosses the HBM bus. This is a P100 (2016), the A100's predecessor with the same layout of die plus HBM stacks. Photo: FritzchensFritz, CC0, Wikimedia Commons.

Standard attention (Algorithm 0, §2.2) computes S = QKT, P = softmax(S), O = PV for Q, K, V of size N × d, and writes both N × N matrices, S and P, to HBM. Often N ≫ d (GPT-2: N = 1024, d = 64). Each step is a separate kernel that reads its input from HBM and writes its output back, and masking applied to S or dropout applied to P add more round trips over the N × N matrix; frameworks had tried fusing some of them, such as masking with softmax (§2.2).

FlashAttention does more arithmetic than standard attention: it recomputes the attention matrix in the backward pass. For GPT-2 medium's attention, forward and backward on an A100, is it slower or faster?

Answer the question above before you look. Figure 2 (left) as printed: each pair scaled to its own maximum.

The idea: tiling, with the softmax done one block at a time

§3.1, Algorithm 1

The goal is to never read or write the N × N matrix in HBM. That needs two things (§1): (i) computing the softmax without access to a whole row of S at once, and (ii) not storing the attention matrix for the backward pass. Both use well-established techniques: tiling for the first, recomputation for the second.

The obstacle to tiling attention like a matrix multiply is that softmax couples a whole row: the safe softmax of a vector x subtracts the row maximum m(x) and divides by the row sum ℓ(x), so no output can be final until the whole row has been seen. The fix is to decompose the softmax (§3.1, the paper's references 60, 51, 66; "online softmax" after Milakov and Gimelshein). For a row split into two blocks x(1) and x(2):

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)
maxi xi, the running maximum (subtracted before exponentiating, for numerical stability)
ℓ(x)
Σi exi − m(x), the running sum; softmax(x) = f(x) / ℓ(x) with f(x)i = exi − m(x)

So if each row keeps two extra numbers, (m, ℓ), softmax can be computed one block at a time (§3.1; footnote 2 calls it algebraic aggregation). Whenever a new block raises the maximum, everything accumulated so far is rescaled by emold − mnew.

The output for a row has been accumulated over the first block of keys. The second block contains a larger score, so the row's maximum rises. What happens to the output accumulated so far?

The same merge drawn for one block of queries, with its running maximum and sum as bars, is Fig. 6 on Writing kernels, which owns online softmax as a kernel technique; this page follows the paper's whole loop and its HBM traffic.

Answer the question above before you look. One row of eight real scores, processed block by block and compared with the plain softmax.

Algorithm 1 (Algorithm 1) applies this to whole tiles. Split K and V into Tc blocks of Bc rows and Q into Tr blocks of Br rows, with Bc = ⌈M / 4d⌉ and Br = min(⌈M / 4d⌉, d) for an SRAM of M values, so that a K block, a V block, a Q block and an output block fit on chip. The outer loop loads Kj and Vj into SRAM (line 6); the inner loop loads Qi, Oi and the statistics ℓi, mi (line 8), computes the tile Sij = QiKjT on chip (line 9), its block maximum, exponentials and sum (line 10), updates the running (m, ℓ) (line 11), rescales the output accumulator and adds P̃ijVj (line 12), and writes Oi, ℓi, mi back (lines 12 and 13). Only Q, K, V, O and the O(N) statistics ever touch HBM.

Fig. 2 · One forward pass, three ways, tile by tile (toy: N = 32, d = 4, blocks of 8)

A real random 32 × 4 input, computed in your browser tile by tile, every running maximum and rescale included; at the end the output is compared with the plain formula. The large slab is HBM, the small raised one is SRAM; each matrix is a glass plate, one cell per value, and dots stream along every read and write. Try: step through standard attention and watch S and P fill HBM; switch to FlashAttention: the N × N area stays an outline, only tiles light up on chip, and the HBM counter ends at about half (a third with masking and dropout ticked). The third mode is the loop order FlashAttention-2 switched to (Q outer: each Q block loaded once and its output written once), the picture to have today; the later versions are on Then and now and, as kernels, on Writing kernels.

  1. Q, K and V sit in HBM. Each is N × d = 32 × 4 = 128 values. Standard attention (Algorithm 0) runs three separate kernels, and each writes its whole result back to HBM before the next can start.
  2. Kernel 1: S = QKT, written to HBM. Q and K come up by blocks; the full 32 × 32 score matrix S, 1,024 values, 8 times the size of Q, goes back down. HBM traffic so far: 1,280 values. This is the matrix FlashAttention never writes.
  3. Kernel 2: P = softmax(S), written to HBM. Softmax does a few operations per value but must read all of S and write all of P; each row needs its own maximum and sum before any output is final, which is why S had to be complete first. So far: 3,328.
  4. Kernel 3: O = PV, written to HBM. P and V come up, O goes down. The output is exact, but the N × N matrix crossed the HBM boundary four times. So far: 4,608.
  5. Saved for the backward pass: P stays in HBM. Algorithm 3 reads P to compute the gradients, so S and P, 2N2 = 2,048 values, stay: the O(N2) memory that limits context length. Whole run: 4,608 values moved.

Block size 4 nearly erases the advantage, 16 grows it: Theorem 2 in miniature. Whole-run HBM traffic of this toy (N = 32, d = 4), values read plus written, by block size.
Block sizeStandardwith masking and dropoutFlashAttentionFlashAttention-2 order
44,6088,7044,5442,336
8 (the animation)4,6088,7042,4961,312
164,6088,7041,472800
How the animation counts

Toy sizes so the picture fits: N = 32 rows, head dimension d = 4, square blocks (Br = Bc); real kernels use N in the thousands, d = 64 or 128 and blocks of 64 to 256 rows (real sizes are in the scale panel). Counts are values moved across the HBM boundary, read or written, exactly as the algorithms' load and write lines say; standard attention's "by blocks" matrix multiplies are counted as one read of each input, as in the proof of Theorem 2. Inputs are Gaussian, Q and K scaled by 1.5 so that the running maxima move. Each FlashAttention step plays the four inner iterations of one outer iteration. The table's counts are the page's simulator, checked against recompute.py.

Because the whole computation is one kernel, the steps between the matrix multiplies cost nothing extra: matrix multiply, softmax, optionally masking and dropout, matrix multiply, all on chip before the result goes back to HBM (§3.1, "Implementation details: kernel fusion"; the full version with the softmax scaling τ = 1/√d, a masking function and dropout is Algorithm 2). Theorem 1 (Theorem 1) states that Algorithm 1 returns exactly softmax(QKT)V, with O(N2d) FLOPs and O(N) memory beyond the inputs and output; the proof in Appendix C is an induction over the outer loop. In plain numbers the online and standard results differ only by rounding: .

Recomputation: the backward pass without the attention matrix

§3.1, Appendix B

Training normally stores S and P for the backward pass, and that is where the O(N2) memory goes. FlashAttention stores only the output O and the softmax statistics (m, ℓ), plus the state of the random-number generator so the dropout mask can be regenerated instead of stored (§B.3, §B.4). The backward pass (Algorithm 4) recomputes Sij and Pij tile by tile in SRAM from Q, K, V and the statistics.

The backward pass's one trick (§B.2, Eq. 4)

The derivation (§B.2) has one trick that keeps it linear in memory. The softmax gradient needs Di = Pi:TdPi:, a reduction over a row of length N that might not fit in SRAM; but it equals doiToi, a dot product of two vectors of length d (Eq. 4). Then dSij = Pij(dPij − Di), and dQ, dK, dV are sums over tiles.

This is a form of selective gradient checkpointing, but with a difference the paper insists on: every checkpointing implementation the authors knew traded speed for memory, whereas this recomputation speeds up the backward pass, despite the extra FLOPs, because it reads far less from HBM (§3.1). At Figure 2's size the attention matrix is 2.15 GB per copy in fp16 (N² × 16 heads × batch 64 × 2 bytes); the 40.3 GB that standard attention moves is total traffic, many passes over such matrices, not one matrix (this page's earlier summary had called it "a 40 GB attention matrix"). The backward pass's IO is the same order as the forward's: Θ(Nd + N2) accesses for standard attention against Θ(N2d2M−1) for FlashAttention (Theorem 5).

Against the closest prior work, Rabe and Staats (§B.5)

Rabe and Staats' memory-efficient attention (§B.5): both tile and both recompute, but Rabe and Staats minimise total memory and run at about the speed of standard attention or slightly slower, while FlashAttention minimises memory accesses and runs 2 to 4× faster; Rabe and Staats keep a temporary output per block and combine them at the end, FlashAttention updates one output incrementally; and Rabe and Staats get the backward by generic gradient checkpointing, recomputing the temporary outputs too, while FlashAttention simplifies it analytically and recomputes only the attention matrix.

The IO complexity argument (the paper's real thesis)

§3.2, Theorem 2, Proposition 3

Theorem 2 (Theorem 2): for SRAM size M with d ≤ M ≤ Nd, standard attention needs Θ(Nd + N2) HBM accesses and FlashAttention needs Θ(N2d2M−1). For typical d (64 to 128) and M (around 100 KB), d2 is many times smaller than M, so FlashAttention needs many times fewer accesses.

The proof idea of Theorem 2

K and V blocks of size Θ(M) are each loaded once; for each one, all of Q is streamed past, which is Θ(NdM−1) passes over Q, each loading Θ(Nd) values (Appendix C).

Give the GPU twice as much SRAM (double M), same N and d. What happens to FlashAttention's HBM accesses?

Proposition 3 (Proposition 3) adds a lower bound: no exact attention algorithm can make o(N2d2M−1) HBM accesses for all M in [d, Nd]. The authors call this a lower bound "over a subrange of M", common in streaming algorithms, and leave a bound for every M as future work; within this cost model FlashAttention is optimal, but the bound says nothing about the M of a real GPU (the proof uses the end of the range: at M = Θ(Nd) the bound is Θ(Nd), what reading the inputs alone costs).

The validation is Figure 2: left, more FLOPs but fewer HBM accesses and a much shorter runtime (the predict question above); middle, the forward runtime falls as the block size Bc grows, because there are fewer passes over the input, until beyond about 256 it is "bottlenecked by other factors (e.g., arithmetic operations)", and larger blocks would not fit SRAM anyway (§3.2). The closed block below draws the two lower bounds that produce that shape.

Answer the question above before you look. Algorithm 1's exact count, forward pass, one head, against the SRAM size.

The same counters at the paper's scale

The counts the animation keeps, as formulas from Algorithms 0 to 4, for forward and backward together, at any size. The defaults are Figure 2's GPT-2 medium workload: N = 1024, d = 64, 16 heads × batch 64, fp16, with the A100's 192 KB of SRAM per streaming multiprocessor (§2.1) setting the block size by Algorithm 1's rule B_c = ⌈M / 4d⌉.

Units and the two time bounds

GB is 109 bytes at 2 bytes per value. "Time at bandwidth" divides bytes by the A100's 1.5 TB/s (§2.1) and "time at peak" divides the matrix-multiply FLOPs by the A100's 312 TFLOPS fp16 tensor-core peak (NVIDIA A100 datasheet); both are lower bounds, not predictions. The block-sparse density s scales the T_c passes, as in Proposition 4.

Why bigger blocks stop helping (Figure 2, middle)

Figure 2 (middle) sweeps the block size B_c and reports that the forward runtime falls as blocks grow, until about 256, after which "the runtime is then bottlenecked by other factors (e.g., arithmetic operations)" (§3.2). The figure prints no values, so nothing here reproduces it; what can be drawn is the reason. Runtime can be no shorter than either the time to move the forward pass's HBM bytes or the time to do its matrix multiplies. The first falls as B_c grows; the second does not move.

Extension: block-sparse FlashAttention

§3.3, Proposition 4, Algorithm 5

Given a block-form mask (one bit per Br × Bc tile), skip the zero tiles (Algorithm 5, otherwise identical to Algorithm 2). Proposition 4 (Proposition 4): the IO falls to Θ(Nd + N2d2M−1s), where s is the fraction of nonzero blocks. With s set to N−1/2 or N−1log N, as sparse-attention work often does, that is Θ(N√N) or Θ(N log N). The experiments use the fixed butterfly pattern, which has been shown to approximate arbitrary sparsity. Runtime improves in proportion to the sparsity (Figure 2 right), and on the Long-Range Arena block-sparse FlashAttention gets a 2.8× speedup while matching standard attention's accuracy (§3.3). It is the version that reached 64K tokens; the scale panel has a density slider.

Results

§4 Experiments, Appendix E

Faster training (§4.1):

  • BERT-large (sequence length 512) trains to the MLPerf 1.1 target of 72.0% masked-LM accuracy in 17.4 ± 1.4 minutes against 20.0 ± 1.5 for Nvidia's record-setting MLPerf 1.1 implementation, 15% faster, on 8 × A100 GPUs, averaged over 10 runs from the same initialisation (Table 1).
  • GPT-2 on OpenWebText: up to 3× faster end to end than HuggingFace and 1.7× faster than Megatron-LM, at the same perplexity within 0.1, because the model definition does not change (Table 2). Small: 2.7 days against 4.7 (Megatron) and 9.5 (HuggingFace); medium: 6.9 against 11.5 and 21.0. The validation curves of the two implementations lie almost on top of each other (Figure 4).
  • Long-Range Arena (sequence lengths 1,024 to 4,096): 2.4× faster than standard attention, block-sparse 2.8×, with accuracy on par; block-sparse FlashAttention is faster than every approximate method tested (Table 3).
Training setups (§E.1, §E.2)

BERT-large: LAMB, learning rate 3.75e-3, batch 448, at most 7,100 steps, FP16 with Apex AMP O2, each run 16 to 19 minutes on A100-80GB (§E.1). GPT-2: 8 × A100-40GB, 400K steps each (§E.2).

Better models from longer context (§4.2):

  • GPT-2 small with a 4K context trains 30% faster than Megatron's GPT-2 at 1K and reaches 0.7 better perplexity (17.5 against 18.2, Table 4).
  • Long-document classification with a pretrained RoBERTa, positional embeddings repeated to extend it: 16K beats 512 by 4.3 micro-F1 points on MIMIC-III (ICU discharge summaries, average 2,395 tokens, longest 14,562) and 8K beats 512 by 8.5 on ECtHR (European Court of Human Rights cases, average 2,197, longest 49,392); the abstract's "6.4 points of lift" is the mean of the two (Table 5; the text calls it Table 6). The authors suggest MIMIC's smaller gain may come from a distribution shift in its specialised medical text.
  • Path-X and Path-256: classify whether two points in a 128 × 128 (or 256 × 256) black-and-white image are connected, fed one pixel at a time, so 16K or 64K tokens. Every earlier Transformer either ran out of memory or scored at chance. Pretrained on Path-64 and transferred by interpolating the positional embeddings, FlashAttention reaches 61.4% on Path-X, the first Transformer above chance; block-sparse FlashAttention reaches 63.1% on Path-256 (Table 6).

The attention kernel itself (§4.3, one A100-40GB, dropout and a padding mask, Figure 3 and Tables 9 to 21): up to 3× faster than PyTorch's attention for N from 128 to 2K, and it scales to 64K; memory grows linearly with N and is up to 20× smaller than exact baselines. Approximate methods, linear in N, overtake it between 512 and 1,024 (Linformer first); block-sparse FlashAttention is faster than every exact, sparse and approximate implementation the authors knew of, at every length. The speedup depends on the GPU as the IO analysis predicts: 2 to 4× on an A100, 2.5 to 4.5× on an RTX 3090 with its lower bandwidth, less on a T4 with its smaller SRAM (§E.5).

Against Apex FMHA, and the speedup by GPU in detail (Table 7, §E.5)

Against Apex FMHA, the fused kernel FlashAttention started from and the fastest for short sequences (at most 512), FlashAttention is slightly faster forward, slightly slower backward (it recomputes), and overall 4% slower at 128, 8% faster at 256, 5% faster at 512 (Table 7). On an A100 the speedup is larger with dropout and masking, smaller with head dimension 128 (smaller blocks) but up to 3× with a causal mask; the RTX 3090's bandwidth is roughly 900 GB/s against 1.5 TB/s (§E.5).

All of it rebuilt, sortable and checked: The paper's tables, rebuilt.

Limitations, in the authors' words

§5 Limitations and Future Directions
  • Compiling to CUDA. Every new attention variant needs a new hand-written CUDA kernel, in a far lower-level language than PyTorch, with significant engineering effort, possibly not portable across GPU architectures; they call for writing attention in a high-level language and compiling it to IO-aware CUDA, as Halide does for image processing.
  • IO-aware deep learning beyond attention: every layer touches HBM (§D.2 sketches sparse MLP layers and kernel machine learning, the KeOps library being a working example).
  • Multi-GPU. The method is optimal within constants on one GPU; across GPUs there is another level of the hierarchy (other GPUs' HBM) to account for.

How much of this to believe

the evidence in §3.2, §4 and Appendix E

What holds up. The central claim is a theorem plus a measurement, and both are solid. Exactness is proved (Theorem 1) and visible in training: GPT-2 trained with it matches the baselines' perplexity and validation curves (Table 2, Figure 4). The kernel benchmarks are the strongest evidence in the paper: each timing is the mean of 100 calls, every configuration (with and without dropout and masking; forward, backward, both) is printed in full, the baselines are reference implementations on the same GPU, and the authors were generous where a baseline broke (Block-Sparse, Longformer and BigBird measured without masking because of a bug in their backward pass) (§E.6). The speedup is reported on four GPUs, including the ones where it shrinks. And it has replicated about as thoroughly as a systems result can: PyTorch 2.0 shipped it as a backend of its built-in attention, and cuDNN and vLLM ship its successors (Then and now).

Where to be careful.

  • The BERT 15% is not like for like. The baseline is the training time Nvidia reported to MLPerf 1.1, not a rerun on the authors' machines (§E.1). The gap, 2.6 minutes, is 4.0 standard errors if the ± is a standard deviation over 10 runs each, so it is not noise; but the paper also reports that nearly all MLPerf BERT submissions already used Apex FMHA, a fused attention kernel, and at length 512 FlashAttention is only 5% faster than FMHA (Table 7). Attention is a fraction of a BERT step, so most of the 15% must come from something else in the implementation or setup, which the paper does not break down.
  • The GPT-2 speedups are single runs with no error bars, and the 3× is against HuggingFace's unfused implementation; Megatron-LM is the fair baseline, at 1.7× (Table 2). The summary in §4 says 1.8× over Megatron, which no row gives: 1.8× is Megatron's own speedup over HuggingFace on GPT-2 medium. The paper also does not say whether the non-attention parts of the three training codes are the same.
  • Figure 2's numbers cannot all be recomputed. Counting Algorithms 1 and 4 line by line gives 4.6 GB for FlashAttention against the printed 4.4, close; but Algorithms 0 and 3 give 25.2 GB for standard attention against the printed 40.3 (42.4 if masking and dropout each make separate passes), and the GFLOPs column is about 12 times smaller than the matrix multiplies of the stated workload. The ratios the argument rests on survive; the absolute numbers' accounting is not given (Every number checked).
  • The lower bound is weak. Proposition 3 is proved only at the end of the SRAM range, M = Θ(Nd), where every algorithm costs Θ(Nd); "optimal" means no algorithm beats it for all M at once, not that it is optimal at an A100's M. The authors say so themselves and leave the stronger bound open, which counts in their favour.
  • The Long-Range Arena comparison mixes sources. Where a baseline could not be reproduced on a task, the better of two published numbers was used (§E.3); "after hyperparameter tuning, almost all of the attention methods achieve similar accuracy", so the accuracy column barely separates the methods; Performer and Local Attention ran in FP32 (FP16 was unstable or unsupported), which inflates FlashAttention's speed advantage over those two; the 2.4× and 2.8× are geometric means of per-task speedups that are not printed. Accuracies are single runs, and one Transformer average (59.3) does not quite recompute from its five tasks (59.24).
  • The long-context quality gains are small and selected. The 6.4-point lift takes each dataset at its best of six lengths (16K for MIMIC-III, 8K for ECtHR); at a common 16K it is 5.6, MIMIC-III dips below its 512 score at 1K and 2K, and ECtHR falls again at 16K (Table 5). Path-X's 61.4% (chance is 50%) came after an extra 200 epochs of fine-tuning from the checkpoint chosen on validation accuracy, worth about 4 points by the authors' account, after which it overfit (§E.3). These are real firsts, but single runs.
  • "Up to" numbers come from different setups. The 7.6× (Figure 1, GPT-2 attention, a chart with no table), the 5.7× (Figure 2, batch 64 and 16 heads) and the 3.3× (Table 11, batch 16 and 8 heads) are all "FlashAttention against PyTorch attention"; they differ because the workloads differ.

Verdict: believe the algorithm and the kernel benchmarks: exactness is proved, the IO argument is checkable, and every major framework has shipped it since. Treat the end-to-end training speedups and the long-context quality gains as single runs against baselines that were not always run like for like.

Why it matters (beyond the paper)

This is the canonical fused kernel, and the paper that made IO-awareness the default lens for GPU kernel work. Exact attention became fast enough that the approximate-attention wave lost its reason to exist, and FlashAttention or a descendant now sits inside the major stacks: PyTorch 2.0 made it one of the three implementations behind its built-in scaled_dot_product_attention (PyTorch 2.0 docs), and HuggingFace transformers, DeepSpeed, Megatron-LM and others integrated it within months (the repo's adoption list); which stacks run which version today is in the dated block of Then and now. Long context went from a research problem to a product setting.

For a CUDA learner it is the ideal case study: memory hierarchy, tiling, kernel fusion, occupancy and a cost model that counts HBM bytes, not FLOPs, all in one algorithm.

The lineage since (details and sources in Then and now; each version as a kernel, with what it changed and why, on Writing kernels): FlashAttention-2 (Tri Dao, July 2023) kept the math and remapped it onto the GPU, about 2× faster; FlashAttention-3 (Jay Shah and others with Tri Dao, July 2024) rebuilt it for Hopper's asynchrony and FP8; FlashAttention-4 (Ted Zadouri and others with Tri Dao, paper March 2026) for Blackwell, written in the CuTe DSL in Python. The move from hand-written CUDA to C++ templates to a Python DSL is itself a snapshot of where kernel engineering is heading. And the paper's stated limitation, a hand-written kernel per variant, seeded its own research direction: Triton and torch.compile attention templates, FlexAttention ("the flexibility of PyTorch with the performance of FlashAttention", PyTorch blog, August 2024) and the CuTe DSL all answer "compile IO-aware attention from a high-level description".

Connections

  • Attention Is All You Need (2017): the O(N2) attention this paper makes fast without changing its output.
  • vLLM / PagedAttention (2023): the complementary inference-side memory result. FlashAttention optimises HBM to SRAM traffic inside the kernel; PagedAttention optimises KV-cache allocation across requests. Serving stacks use both.
  • Megatron-LM (2019): the training-systems baseline FlashAttention beats here, and which later integrated it (Megatron-LM pull request 267).
  • Mamba (2023): Tri Dao's other line of attack on sequence length; its selective scan uses "three classical techniques: kernel fusion, parallel scan, and recomputation", keeping the state in SRAM and recomputing it in the backward pass (Mamba §3.3).
  • DeepSeek-V3 (2024) and every modern LLM report: FlashAttention-class kernels are assumed infrastructure for the published long-context and MFU numbers.
  • BERT (2018): the model of Table 1. ZeRO (2019): the other half of training memory, the model states, which FlashAttention leaves alone.
  • Topics: cuda-and-gpu-programming (primary: the canonical fused kernel and IO-aware cost model), inference-and-serving (attention kernels in serving stacks), hardware (memory hierarchy and bandwidth math), llm-training-and-post-training (training speed and long-context training).