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.
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
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).
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.
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.
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.
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).
5.7× faster, with 13% more FLOPs (Figure 2, left): 41.7 ms against 7.3 ms, because the HBM traffic fell from 40.3 GB to 4.4 GB, 9.2× less.
Two checks of the printed numbers. At the A100's 1.5 TB/s, moving 40.3 GB alone takes 26.9 ms of standard attention's 41.7 ms, so it is memory-bound; FlashAttention's 4.4 GB takes 2.9 ms of its 7.3, so arithmetic now matters too. The GFLOPs column, however, cannot be recomputed from the stated workload: the matrix multiplies alone are GFLOP, about 12 times the printed values (their ratio, 1.13, is close to the 7/6 that recomputation adds). See Every number checked.
Answer the question above before you look. Figure 2 (left) as printed: each pair scaled to its own maximum.
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):
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.
It is rescaled and kept. Each exponential so far was taken against the old maximum; multiplying by emold − mnew moves it onto the new one, which is exact. Ignoring the rescale (the third answer) gives the wrong weights as soon as the maximum moves; tick "skip the rescale" below to see it.
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.
| Block size | Standard | with masking and dropout | FlashAttention | FlashAttention-2 order |
|---|---|---|---|---|
| 4 | 4,608 | 8,704 | 4,544 | 2,336 |
| 8 (the animation) | 4,608 | 8,704 | 2,496 | 1,312 |
| 16 | 4,608 | 8,704 | 1,472 | 800 |
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: .
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 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).
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.
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.
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).
Roughly halve, because the count is N2d2/M: twice as large blocks mean half as many passes over Q and O. It cannot fall forever: once one block holds all of K and V (M ≈ Nd), every input is read once and the count reaches the Θ(Nd) floor that any exact algorithm must pay.
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 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⌉.
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.
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.
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.
Faster training (§4.1):
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):
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, 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.
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.
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.
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".
Every table that carries the argument, transcribed from the arXiv HTML v2 with the printed precision kept (tables.json, made by mk_tables.py), with every derived number recomputed (recompute.py). Where a recomputation does not match, it says so.
Figure 3 plots a subset of baselines; Appendix E.6 prints the full numbers for 12 methods, 10 sequence lengths and every combination of pass, dropout and masking (one A100-40GB, 8 heads of dimension 64, batch 16, FP16 except Local Attention, mean of 100 calls). Lines here are those printed values; a gap means the method ran out of memory or does not support that length (Megatron stops at 2K, OpenAI's Block-Sparse at 4K, Longformer and BigBird at 8K).
Try: start on forward + backward with dropout and masking (Figure 3 left's setting) and find where Linformer drops below FlashAttention (1,024); then switch to memory and see FlashAttention's line run parallel to the linear-time methods while PyTorch's bends upward and stops at 4K.
Click a column to sort. "Avg (recomputed)" is the mean of the five printed task scores.
Each claim with where it is printed, what the tables or the algorithms give, and a verdict: yes, nearly, no, or cannot check (no data printed).
The math of FlashAttention has not changed since 2022: exact attention, tiles, online softmax, recomputation. What changed four times is how it is mapped onto each new GPU, because each generation moved the bottleneck. Step through the versions; each card says what the previous one left on the table and quotes the paper that fixed it.
Speedups are each paper's own, on its own target GPU, against the previous version or the vendor library; they are not comparable across cards. Abstracts and quoted sentences are saved in src/inputs/later_extracts.txt.
The paper's first limitation was that every attention variant needs its own CUDA kernel (§5). That became a research direction: Triton and torch.compile attention templates; FlexAttention, whose announcement names the problem directly ("You can no longer try out a new attention variant by writing a few PyTorch operators: you often need to write a new custom kernel!", PyTorch blog, August 2024) and which vLLM now lists as a backend of its own; and FA-4 itself, written in the CuTe DSL embedded in Python with 20 to 30× faster compile times than C++ templates.
| Stack | What it uses | Source |
|---|---|---|
| PyTorch | Since 2.0, FlashAttention is one of three implementations behind torch.nn.functional.scaled_dot_product_attention, chosen automatically; "readily available by default" | SDPA docs (2.0), PyTorch 2.0 release |
| NVIDIA cuDNN | Its scaled dot product attention computes "using the FlashAttention-2 algorithm", for training and inference, also in FP8 | cuDNN frontend docs |
| vLLM | The FLASH_ATTN backend runs FA2 on compute capability 8.0 and up, FA3 on 9.x (Hopper), FA4 on 10.0 and up (Blackwell) | attention backends |
| HuggingFace transformers, DeepSpeed, Megatron-LM, MosaicML Composer, GPT-NeoX, PaddlePaddle | Integrations listed by the authors, mostly from 2022 | usage.md |
| MLPerf | The authors report the fastest BERT training on cloud instances in MLPerf training 2.0 (June 2022) and 2.1 (November 2022) | usage.md (the authors' own claim) |
TensorRT-LLM documents its own fused attention (FMHA) kernels rather than the FlashAttention library, so it is not counted here.
Which attention library runs under PyTorch's SDPA, and FlashAttention as a library beside cuDNN and CUTLASS, are kept current on Libraries and tensor cores.
Every link opens in a new tab. Reading time of the resources below: 4h 00m.
NeurIPS 2022, the paper itself; the HTML version has the anchors this page links to. abstract page, PDF.
(1h)
the authors' kernels, now FlashAttention-2 to 4, BSD 3-Clause licence (repo, about 25 minutes for the README and entry path).
(25 min)
Aleksa Gordić: the best gentle walkthrough of the tiling and rescaling math, with diagrams of the block loops.
(25 min)
Zihao Ye, UW CSE 599M note: derives the algorithm the right way round, starting from 3-pass safe softmax, then online softmax, then the fused one-pass attention; the cleanest path to reconstructing the kernel yourself.
(40 min)
Tri Dao: the author's own explanation of the memory hierarchy argument and the algorithm.
(1h)
Horace He: not about FlashAttention specifically, but the compute-bound against memory-bound framing that makes the whole paper obvious in retrospect.
(25 min)
Tri Dao: the first author's papers and blog posts, including the FlashAttention-2 and -3 write-ups.
(5 min)
2017: the O(N²) attention this paper makes fast without changing its output.
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.
2019: the training-systems baseline FlashAttention beats in Tables 2 and 4, and later integrated into (Megatron-LM pull request 267).
2023: Tri Dao's other line of attack on sequence length; its selective-scan kernel reuses the same IO-aware recipe (fuse, keep state in SRAM, recompute in backward).
2024, and every modern LLM report: FlashAttention-class kernels are assumed infrastructure for the published long-context and MFU numbers.
2018: BERT-large is the model of Table 1's 15% training-speed result.
2019: the other half of training memory; ZeRO shards the model states, FlashAttention removes the N × N activations.
primary: the canonical fused kernel and IO-aware cost model.
attention kernels in serving stacks.
memory hierarchy and bandwidth math.
training speed and long-context training.
This page is one row of the Papers database; its properties (Paper, Takeaway, Topics, Year) live there.