FlashAttention Explained: How Tiling and Online Softmax Make Exact Attention Fast
FlashAttention computes exactly the same result as standard attention, yet runs several times faster and needs only linear extra memory. Here is how tiling, the online softmax trick, and recomputation make that possible, with runnable code.
Attention is the operation at the heart of every transformer, and for a long time it was also the part that made long sequences painful. The textbook implementation builds a full score matrix with one entry for every pair of tokens, so doubling the sequence length quadruples both the work and the memory. FlashAttention, introduced by Tri Dao and colleagues in 2022, changed how practitioners think about this cost. It does not approximate anything. It returns the same numbers as ordinary attention, but it reorganizes the computation so the GPU spends far less time moving data around.
This explainer walks through why standard attention is slow on real hardware, the two ideas that FlashAttention combines (tiling and online softmax), how the backward pass avoids storing the big matrix, what changed in FlashAttention-2 and FlashAttention-3, and how to actually use it from PyTorch today.
Why standard attention is memory-bound
For a single head with N tokens and head dimension d, attention computes S = QK^T scaled by 1/sqrt(d), applies a row-wise softmax to get P, and multiplies P by V to get the output O. The naive implementation materializes S and P as N x N matrices. Each of those steps reads its input from GPU main memory and writes its result back.
The FlashAttention paper frames the problem in terms of the GPU memory hierarchy. On an A100, the paper describes 40 to 80 GB of high-bandwidth memory (HBM) with roughly 1.5 to 2.0 TB/s of bandwidth, alongside 192 KB of on-chip SRAM in each of its 108 streaming multiprocessors, with SRAM bandwidth estimated around 19 TB/s. SRAM is an order of magnitude faster but tiny. Softmax, masking, and dropout perform very little arithmetic per byte, so when each of them round-trips an N x N matrix through HBM, the GPU's compute units mostly sit idle waiting for memory. The bottleneck is data movement, not FLOPs.
The paper quantifies this: standard attention needs on the order of Nd + N^2 HBM accesses, while FlashAttention needs on the order of N^2 d^2 / M, where M is the SRAM size. Because d squared is typically much smaller than M, the reduction in memory traffic is large.
Idea one: tiling
Tiling means splitting Q, K, and V into blocks small enough to fit in SRAM, loading a block once, doing as much work on it as possible on-chip, and writing only the final result back to HBM. Matrix multiplication has been tiled this way for decades. The obstacle for attention is the softmax in the middle: to normalize a row you need the maximum and the sum over the entire row, which seems to require seeing every key before producing any output.
Idea two: online softmax
The trick that removes this obstacle is that softmax can be computed incrementally if you carry two running statistics per row: the maximum score seen so far, m, and the sum of exponentials relative to that maximum, l. When a new block of scores arrives, you compute the new maximum. If it is larger than the old one, everything accumulated so far was exponentiated against a maximum that was too small, so you multiply the old sum and the old partial output by exp(m_old - m_new) to correct them. Then you add the contribution of the new block.
The FlashAttention paper writes this decomposition for two concatenated blocks: the combined maximum is the larger of the two block maxima, and the combined denominator is each block's denominator rescaled by the exponential of the difference between its maximum and the combined one, then summed. Because the rescaling is exact, the final answer equals ordinary softmax up to floating-point rounding. Subtracting the running maximum also keeps the exponentials from overflowing, which is the same stabilization a careful standard softmax uses.
A worked example in NumPy
The code below implements both versions for a single head. The tiled version never builds the N x N matrix; it only ever holds an N x block slice of scores, plus the running statistics m and l. Running it compares the two outputs.
import numpy as np
def naive_attention(Q, K, V):
S = Q @ K.T / np.sqrt(Q.shape[1]) # full N x N score matrix
P = np.exp(S - S.max(axis=1, keepdims=True))
P /= P.sum(axis=1, keepdims=True)
return P @ V
def tiled_attention(Q, K, V, block=64):
N, d = Q.shape
scale = 1.0 / np.sqrt(d)
O = np.zeros_like(Q)
m = np.full(N, -np.inf) # running row max
l = np.zeros(N) # running softmax denominator
for start in range(0, K.shape[0], block):
Kj = K[start:start + block]
Vj = V[start:start + block]
S = Q @ Kj.T * scale # only N x block scores
m_new = np.maximum(m, S.max(axis=1))
P = np.exp(S - m_new[:, None])
correction = np.exp(m - m_new) # rescale old partial sums
l = correction * l + P.sum(axis=1)
O = correction[:, None] * O + P @ Vj
m = m_new
return O / l[:, None]
rng = np.random.default_rng(0)
N, d = 1024, 64
Q, K, V = (rng.standard_normal((N, d)) for _ in range(3))
diff = np.abs(naive_attention(Q, K, V) - tiled_attention(Q, K, V)).max()
print(f"max abs difference: {diff:.2e}")On a typical machine this prints a maximum absolute difference on the order of 1e-15, which is double-precision rounding noise. Note what the loop does on the first iteration: m starts at negative infinity, so exp(m - m_new) is zero and the empty accumulators are simply discarded. A real kernel also tiles over the query rows and runs those tiles in parallel, but the per-row bookkeeping is exactly this.
The backward pass: recompute instead of store
Training needs gradients, and the standard backward pass reuses the attention probability matrix P saved from the forward pass. Storing P is precisely the quadratic memory cost FlashAttention is trying to avoid. Instead, the forward pass saves only the output O and the per-row softmax statistics. During the backward pass, the kernel reloads blocks of Q, K, and V into SRAM and recomputes the needed slices of S and P on-chip.
This does more arithmetic than the standard approach, but the paper reports that the backward pass is still faster because it avoids so much HBM traffic. The authors describe it as a form of selective gradient checkpointing. The result is that FlashAttention needs only O(N) extra memory beyond its inputs and output, rather than O(N^2).
What the speedups looked like
The original paper reported a 15% end-to-end wall-clock speedup training BERT-large at sequence length 512 compared with the MLPerf 1.1 record, a 3x speedup training GPT-2 at sequence length 1K, and a 2.4x speedup on the Long-Range Arena benchmark at lengths from 1K to 4K. Because memory no longer grew quadratically, it also enabled longer contexts, reporting 61.4% accuracy on the Path-X task at sequence length 16K and 63.1% on Path-256 at sequence length 64K.
FlashAttention-2 and FlashAttention-3
The algorithm stayed the same in later versions; the engineering around it improved. According to its abstract, the first version reached only 25 to 40% of the theoretical maximum FLOPs/s on an A100, which the FlashAttention-2 paper attributes to poor partitioning of work across thread blocks and warps.
- FlashAttention-2 (2023) reduces non-matmul operations, parallelizes across the sequence-length dimension so even a single head can occupy many thread blocks, and divides work between warps to cut shared-memory communication. It reports about a 2x speedup over the first version and 50 to 73% of theoretical peak on A100, with end-to-end GPT-style training up to 225 TFLOPs/s per A100.
- FlashAttention-3 (2024) targets NVIDIA Hopper GPUs such as the H100. It overlaps computation with data movement using the Tensor Memory Accelerator and warp specialization, interleaves block-wise matrix multiplies with softmax, and adds FP8 support using block quantization and incoherent processing. It reports a 1.5 to 2.0x speedup over FlashAttention-2 on H100, up to 740 TFLOPs/s in FP16 (about 75% utilization), and close to 1.2 PFLOPs/s in FP8.
The lesson generalizes beyond attention: on modern accelerators, an operation's cost is often decided by how many bytes it moves through slow memory, not by how many floating-point operations it performs.
— LeepCast
Using it from PyTorch
Most developers never call a FlashAttention kernel directly. PyTorch exposes torch. nn. functional. scaled_dot_product_attention, which dispatches to one of several implementations: a FlashAttention-2 kernel, a memory-efficient attention kernel, or a plain C++ implementation of the standard formula. All are enabled by default and PyTorch picks one based on the inputs and hardware. The torch. nn. attention. sdpa_kernel context manager restricts which backends may be used, which is handy for debugging or for checking that a fused kernel is really being selected.
import torch
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend
# (batch, heads, seq_len, head_dim)
q = torch.randn(2, 8, 1024, 64)
k = torch.randn(2, 8, 1024, 64)
v = torch.randn(2, 8, 1024, 64)
# Default: PyTorch picks the best available backend for these inputs.
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
# Reference: force the plain math implementation and compare.
with sdpa_kernel([SDPBackend.MATH]):
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape, torch.allclose(out, ref, atol=1e-5))This runs on CPU as written. On a supported CUDA GPU with fp16 or bf16 tensors, wrapping the call in sdpa_kernel([SDPBackend. FLASH_ATTENTION]) forces the flash kernel; if it cannot run for those inputs, PyTorch emits a warning explaining why.
Practical details worth knowing
- Pass is_causal=True for decoder-style masking instead of building your own triangular mask; you cannot set both attn_mask and is_causal at once.
- A boolean attn_mask uses True to mean the position takes part in attention, which is the opposite convention from MultiheadAttention's key_padding_mask, so invert old masks when migrating.
- The default scale is 1/sqrt(E), where E is the query and key embedding dimension; override it with the keyword-only scale argument.
- dropout_p is applied whenever it is above zero, even in evaluation, so pass 0.0 when not training.
- enable_gqa=True supports grouped-query attention, where the number of query heads must be divisible by the number of key and value heads; the documentation marks it as experimental.
When it matters and when it does not
The benefit of FlashAttention grows with sequence length, because that is where the N x N matrix dominates memory traffic. For short sequences, other parts of the model such as the feed-forward layers usually dominate runtime, and the attention kernel choice makes little difference. It also does not change model quality by itself: it is an exact algorithm, so any accuracy gains come from what the saved memory lets you do, such as training with longer contexts or larger batches.
The mental model to keep is simple. Standard attention computes a giant intermediate matrix and pays to move it through slow memory several times. FlashAttention computes the same answer in tiles that fit on-chip, uses running maximum and sum statistics to make softmax work piece by piece, and recomputes rather than stores what the backward pass needs. Once that clicks, the later versions read as increasingly careful scheduling of the same idea onto newer hardware.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter