Contents
Figure 1: FlashAttention Explained: Why Attention Was Memory-Bound — the arithmetic units are fast; the trip to memory is not, and attention makes that trip repeatedly
Attention looks like a maths problem: multiply some matrices, apply a softmax, multiply again. So you would expect a faster GPU with more arithmetic units to speed it up proportionally. It did not, because standard attention spends most of its time waiting for data, not computing.
FlashAttention fixed that by changing how attention moves data, not what it computes. This post covers the bottleneck, the tiling and online-softmax trick, and a NumPy implementation whose output I compared against the naive version on this machine.
The Hidden Cost of Attention
Recall the standard algorithm. You compute the score matrix S = QKᵀ, apply softmax to get P, then compute O = PV. Q, K, and V each have shape N × d, where N is the sequence length — but S and P have shape N × N.
That N × N matrix is the problem. Time and memory complexity are quadratic in sequence length, and it hurts quickly. I computed the size of one fp16 score matrix for a single head and a single sequence:
| Sequence length | Score matrix (fp16) |
|---|---|
| 2,048 | 0.008 GB |
| 8,192 | 0.134 GB |
| 32,768 | 2.147 GB |
| 131,072 | 34.360 GB |
Quadrupling the context multiplies the matrix by 16. At 128K tokens, a single head's score matrix would need 34.4 GB, and a real model has dozens of heads and layers.
The naive implementation makes it worse by shuttling that matrix back and forth. It writes the scores to GPU main memory, reads them back for the softmax, writes the probabilities, then reads them again for the multiplication with V. Each trip costs time, and none of it is arithmetic.
Compute-Bound vs. Memory-Bound
A GPU has two speeds: how fast it computes, and how fast it moves data. A workload is compute-bound when arithmetic limits it, and memory-bound when data movement limits it. The central observation behind FlashAttention is that attention on modern GPUs is memory-bound.
Here is the hardware picture:
- HBM (high-bandwidth memory): large, tens of gigabytes, around 1.5 to 2 TB/s on an A100.
- SRAM (on-chip memory): tiny, around 192 KB per streaming multiprocessor on an A100 and 256 KB on an H100, but roughly ten times faster.
The ratio is what matters. An A100 80GB delivers about 312 TFLOP/s in fp16 against 2.0 TB/s of HBM bandwidth — roughly 153 FLOPs per byte. Any kernel doing less arithmetic per byte than that is waiting on memory, no matter how many tensor cores you add.
The FlashAttention paper made this the headline argument. Existing approximate attention methods tried to reduce compute and often failed to produce wall-clock speedups, because compute was not the bottleneck [1]. The missing principle was making attention algorithms IO-aware: accounting for reads and writes between levels of GPU memory.
The Core Idea: Never Build the N × N Matrix
FlashAttention computes exact attention without ever writing the full score matrix to HBM. It relies on two classical techniques: tiling and recomputation.
Tiling
Split Q, K, and V into blocks small enough to fit in SRAM. Load one block of Q and stream through blocks of K and V, computing attention on each small tile entirely on chip, then discard the tile. The big matrix never exists in slow memory.
One obstacle blocks the plan: softmax couples every column of a row. You cannot compute a row's softmax without seeing all its scores. That is where the next trick comes in.
Online Softmax
The solution computes softmax one block at a time. Keep two running statistics per row: the maximum score seen so far (m) and the running sum of exponentials (l). When a new block arrives, update the max, rescale everything accumulated earlier, and fold in the new block.
As FlashAttention-2 describes it, online softmax computes a local softmax per block and rescales at the end to get the correct output, with no approximation [2]. The same idea was published independently as a way to compute attention without ever materialising the N × N matrix [4].
Here is the whole algorithm in NumPy. I ran it against standard attention:
import numpy as np
def standard_attention(Q, K, V):
S = Q @ K.T / np.sqrt(Q.shape[1]) # full N x N score matrix
S = S - S.max(axis=1, keepdims=True)
P = np.exp(S); P /= P.sum(axis=1, keepdims=True)
return P @ V
def tiled_attention(Q, K, V, block=64):
N, d = Q.shape
O = np.zeros_like(Q)
for i in range(0, N, block): # loop over query blocks
q = Q[i:i+block]
m = np.full(q.shape[0], -np.inf) # running row max
l = np.zeros(q.shape[0]) # running softmax denominator
acc = np.zeros((q.shape[0], d)) # running unnormalized output
for j in range(0, N, block): # stream K/V blocks
s = q @ K[j:j+block].T / np.sqrt(d) # only a block x block tile
m_new = np.maximum(m, s.max(axis=1))
p = np.exp(s - m_new[:, None])
scale = np.exp(m - m_new) # rescale earlier accumulation
l = l * scale + p.sum(axis=1)
acc = acc * scale[:, None] + p @ V[j:j+block]
m = m_new
O[i:i+block] = acc / l[:, None]
return O
With N = 512, d = 64, and blocks of 64, the two outputs matched:
max abs diff: 2.359e-16
allclose: True
largest temporary: 262,144 elements (standard) vs 4,096 elements (tiled)
The difference sits at floating-point rounding level, and the tiled version never builds anything larger than a 64 × 64 tile. That is the essence: exact results, tiny working set. The rescaling line scale = np.exp(m - m_new) is the heart of the trick.
Block size does not change the answer, which is the point — I re-ran the comparison at five tile sizes:
| Block | Max abs diff vs standard | allclose |
|---|---|---|
| 16 | 2.637e-16 | True |
| 32 | 2.498e-16 | True |
| 64 | 2.359e-16 | True |
| 128 | 3.469e-16 | True |
| 256 | 2.637e-16 | True |
The real implementation runs this inside a GPU kernel with explicit memory management, not a Python loop — but the arithmetic is identical.
Recomputation in the Backward Pass
Training needs gradients, and standard backpropagation would store the N × N matrices from the forward pass. FlashAttention stores neither. It keeps small statistics and recomputes the scores on the fly during the backward pass [1]. That costs extra arithmetic, yet the paper reports recomputation still speeds up the backward pass because it reduces HBM accesses. Doing more maths makes it faster, because maths is cheap and memory traffic is expensive.
Kernel Fusion
Tiling also lets the whole pipeline fuse into a single GPU kernel: load inputs from HBM, run the matrix multiply, softmax, optional masking and dropout, and the second matrix multiply, then write only the result back. No intermediate round trips.
What It Buys You
Speed
The original paper reports a 3× wall-clock speedup on GPT-2 training at sequence length 1K, along with a 15% end-to-end speedup on BERT-large [1]. FlashAttention-2 reports roughly 2× over the first version, reaching 50 to 73% of the A100's theoretical peak FLOPs [2]. Exact numbers depend on sequence length, head size, and hardware, so benchmark your own shape rather than quoting a headline.
Memory
Memory use becomes linear in sequence length instead of quadratic, because the full matrix is never stored. The paper's IO analysis puts HBM traffic at Θ(N²d²M⁻¹), where M is SRAM size — a smaller count than standard attention's, and one that shrinks as on-chip memory grows [1].
Longer Context
Linear memory makes long sequences practical. The original paper demonstrated attention at context lengths up to 64K on the Path-256 benchmark, which standard attention could not fit [1].
The Sequels
- FlashAttention-2 improved parallelism and work partitioning, mainly by reducing non-matmul FLOPs and splitting work across thread blocks more evenly [2].
- FlashAttention-3 targets Hopper GPUs with asynchrony and low-precision computation. It reports 1.5 to 2× over FlashAttention-2 in FP16, up to 740 TFLOP/s, and roughly 1.2 PFLOP/s in FP8 on an H100 [3].
What FlashAttention Does Not Do
Keep the claims honest:
- It is not approximate. Tiling and online softmax produce numerically the same output as standard attention, so you can swap it in without changing model accuracy.
- It does not cut compute. Compute stays
O(N²). FlashAttention changes memory traffic, not the number of score entries. - It depends on hardware. The tiling strategy exploits SRAM sizes that vary by GPU generation, and FlashAttention-3's FP8 speedups are unavailable on Ampere and earlier.
- It does not fix every bottleneck. Token-by-token generation with a KV cache is memory-bound for a different reason: each decoding step reads the entire cache to produce a single token, so the arithmetic per byte is terrible no matter how the forward pass is tiled.
How to Use It
You rarely write kernels yourself. FlashAttention is integrated into PyTorch's scaled dot-product attention, so the call you already use may dispatch to it [5]:
import torch.nn.functional as F
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
On supported GPUs and dtypes, PyTorch selects a fused FlashAttention-style kernel automatically. The conditions to check in your version's docs: fp16 or bf16 dtype, a head dimension the kernel supports, CUDA hardware of the right generation, and no feature combination the fused path lacks (custom masks and some dropout settings force a fallback). If throughput looks wrong, check whether PyTorch fell back to the maths path — torch.backends.cuda.sdp_kernel and the profiler will tell you.
Hugging Face models expose an attention-implementation option too, and the argument name has changed across versions, so check the docs for the version you have installed.
Common Pitfalls
- Expecting a speedup on short sequences. The benefit grows with sequence length; at small
Nthe overhead can eat it. - Calling it an approximation. It is exact apart from floating-point rounding, as the table above shows.
- Assuming it is the same everywhere. Support varies by GPU generation and dtype.
- Ignoring dtype. Fused kernels want fp16 or bf16, and fp32 often falls back to a slower path.
- Forgetting the compute cost. Long contexts still cost quadratic arithmetic, in attention and in the KV cache.
- Confusing training and inference gains. Prefill is compute-heavy and benefits a lot; decoding is bandwidth-bound and benefits differently.
- Benchmarking one shape. Head dimension and sequence length change which kernel wins.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Programming Massively Parallel Processors | the memory hierarchy, tiling, and roofline chapters are the mental model FlashAttention is built on. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read the tiling and memory-coalescing chapters after this post. Once you have seen why a block of shared memory changes the arithmetic-intensity calculation, the FlashAttention paper reads like applied version of that chapter rather than a trick.
Wrapping Up
Attention was memory-bound because standard implementations shuttle a huge N × N matrix between slow and fast GPU memory. FlashAttention computes the same exact result by tiling the inputs, using an online softmax to merge blocks, recomputing instead of storing in the backward pass, and fusing everything into one kernel. The payoff: faster training, linear memory, and far longer contexts.
The one number to remember is the ratio. On an A100 80GB, roughly 153 FLOPs per byte is the break-even point; standard attention falls well below it, and FlashAttention raises arithmetic per byte by keeping tiles on chip.
Run the NumPy comparison above, then change the block size and N. Watching the largest temporary shrink while the answer stays identical is the whole idea in one experiment.
Frequently Asked Questions
Is FlashAttention an approximation?
No. Tiling and online softmax change the order of operations, not the mathematics, so the output equals standard attention up to floating-point rounding. In my NumPy test the maximum difference from the naive implementation was 2.4e-16, which is machine precision.
Does FlashAttention reduce the O(N²) compute cost?
No. The score matrix still has N² entries and the arithmetic is still quadratic in sequence length. FlashAttention reduces memory traffic and memory footprint, which is what was actually limiting the GPU. Compute stays quadratic.
Why is attention memory-bound on a GPU?
A GPU computes far faster than it can read from HBM. An A100 80GB delivers about 312 TFLOP/s in fp16 against 2.0 TB/s of bandwidth, a ratio of roughly 153 FLOPs per byte. A kernel that does less arithmetic per byte than that ratio is waiting on memory, and standard attention writes and rereads an N × N matrix several times.
When does FlashAttention not help?
On short sequences the kernel launch and tiling overhead can cancel the gain, since the N × N matrix is small enough to stay cheap either way. Autoregressive decoding with a KV cache is also memory-bound for a different reason: each step reads the whole cache to produce one token, which tiling does not fix.
Do I have to write a CUDA kernel to use it?
No. PyTorch's scaled_dot_product_attention dispatches to a fused FlashAttention-style kernel when the device, dtype, and head dimension qualify. You write the same one-line call and PyTorch picks the backend.
Sources
[1]Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — the IO analysis, recomputation, and the GPT-2 speedup: arxiv.org[2]Dao, FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning — online softmax recap and the A100 utilisation figures: arxiv.org[3]Shah et al., FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision — Hopper asynchrony and the FP16/FP8 throughput numbers: arxiv.org[4]Rabe and Staats, Self-attention Does Not Need O(n²) Memory — the independent derivation of blockwise attention without the full matrix: arxiv.org[5]PyTorch, scaled_dot_product_attention — the fused-kernel dispatch and its dtype constraints: pytorch.org
