Key takeaways
- GPU memory comes in levels: HBM (high bandwidth memory) is big and slow, SRAM (on-chip memory) is small and fast, and computation only happens on the chip.
- Arithmetic intensity (operations per byte moved) decides the bottleneck. When it's too low, you're memory-bound, and moving less matters more than computing less.
- Naive attention writes the T×T score matrix to HBM and reads it back, again and again, at a cost that grows with T squared.
- Online softmax tracks just the running maximum m and sum ℓ, multiplies the old sum by a rescaling factor whenever the maximum changes, and finishes in a single pass.
- FlashAttention fuses tiling and online softmax into one kernel, and in the backward pass it would rather recompute than store. It's exact, it saves memory, and it's faster.
A strange result
Here's attention, from episode 7:
O=softmax(dQK⊤)V
The same formula can be implemented two ways: the straightforward way, and FlashAttention. Compare them:
|
Straightforward |
FlashAttention |
| Compute (GFLOPs) |
66.6 |
75.2 |
| Run time |
41.7 ms |
7.3 ms |
| HBM reads/writes |
40.3 GB |
4.4 GB |
A GFLOP is a billion floating-point operations. FlashAttention does more work, yet runs more than five times faster, and the two produce exactly the same result: FlashAttention is not an approximation. The clue is the last row: the data read from and written to HBM, the GPU's main memory, drops from 40.3 GB to 4.4 GB, about a ninth.
The plan: get to know GPU memory, pin down what makes attention slow, derive the key idea (online softmax), and put it all together into FlashAttention.
What's inside a GPU
The GPU is the workhorse for training and running large models. What it does best is an enormous number of multiplications and additions, all at once. Take the A100, a classic training GPU:
- Its chip has 108 streaming multiprocessors (SMs). Think of each SM as a small workshop: a big crew of compute units doing the arithmetic, plus a small patch of storage right next to them, called SRAM.
- Off the chip sit a few stacks of HBM (high bandwidth memory). When people say a card has "80 GB of memory", this is what they mean.
The model's parameters and every layer's activations normally live in HBM. To compute anything, the data first has to be moved onto the chip, and the results moved back afterward.
Big and slow, small and fast
GPU memory comes in several levels; we'll focus on the two that matter most:
- HBM: the GPU's main memory, and it's big. The A100 comes in 40 GB and 80 GB versions, and HBM moves roughly 1.5 to 2 TB per second.
- SRAM (static RAM): small, on-chip memory, and it's tiny. Each SM gets just 192 KB; all 108 together come to only about 20 MB. 20 MB against 80 GB is a factor of 4,000. But SRAM is much faster: it sits right beside the compute units, with an estimated bandwidth of around 19 TB per second, roughly ten times that of HBM.
Watch out: HBM has "high bandwidth" right in its name, so it sounds fast. Speed is relative: compared with CPU memory it really is much faster, but from the compute units' point of view, next to on-chip SRAM, it's the big, slow warehouse, and fetching from it means waiting.
Intuition: HBM is like a big freezer in the basement: it holds lots of food, but every time you need something, you have to go downstairs. SRAM is the countertop in front of you: it fits only a few things, but they're within arm's reach. The cooking (computation) can only happen at the countertop, and a good chef's secret is making as few trips to the basement as possible.
Faster to compute, or to move?
Compare two speeds:
- Compute: doing matrix math in half precision, an A100 manages about 312 trillion floating-point operations (additions or multiplications) per second.
- Move: HBM delivers only about 2 trillion bytes per second, or 2 TB.
Divide one by the other:
2×1012 bytes/s312×1012 FLOP/s≈156 FLOP/byte
For every byte you read from HBM, you have to do 156 operations with it, or the compute units sit idle. That suggests a useful measure, arithmetic intensity:
arithmetic intensity=bytes movedFLOPs
Two examples:
- Multiply every number in a vector by two: in half precision each number is 2 bytes, so we read 2, write 2, and do one multiplication. Intensity is just 1/4=0.25, more than 600 times below 156. The compute units spend nearly all their time waiting for data: this is memory-bound.
- Matrix multiplication: multiplying two 4096×4096 matrices takes 2n3 operations, but we only move three matrices (two inputs, one output):
3×n2×2 bytes2n3=3n≈1365
More than 1,300, way above 156. Now the bottleneck is the compute itself: this is compute-bound.
The roofline and the memory wall
Put both cases on one chart: arithmetic intensity across, achieved speed up the side, with each step on both axes ten times bigger than the last (log scale).
- When intensity is low, data can't arrive fast enough. Speed equals bandwidth times intensity, so you can only climb a sloped line.
- Only when intensity is high enough do you hit the compute ceiling, 312 trillion operations per second.
speed=min(peak compute, bandwidth×intensity)
The two lines meet at the ridge point, right at 156. The elementwise multiply sits far to the left, reaching less than 1% of peak; the big matrix multiply lands to the right of the ridge and can use all of the compute. This chart is the roofline.
And the ridge keeps moving right. From V100 to A100 to H100, compute has grown faster than bandwidth, so the ridge has climbed from about 140 to nearly 300. This is the memory wall: on today's GPUs, the key to going fast is often not computing less, but moving less.
Kernels and kernel fusion
There's a general-purpose fix for memory-bound work. First, a new idea: every operation on a GPU runs as its own small program, called a kernel. Each kernel reads its input from HBM when it starts and writes its result back when it finishes; whatever was in SRAM is gone the moment the kernel ends.
Say we take x, multiply by two, add one, and take e to that power. As three kernels, the data makes three round trips between HBM and the chip. Fuse the three steps into one kernel instead: read once, do all three steps on the chip, write once. One trip. This is kernel fusion. Not a single operation was saved, but data movement dropped by two thirds, so memory-bound work runs nearly three times faster.
And that's exactly what FlashAttention does: it fuses all of attention into a single kernel.
The big matrices inside attention
Say the sequence length is T and each head has dimension d. Q, K and V are all T×d matrices, one row per position:
- S=QK⊤/d: the score matrix, T×T, one score for every pair of positions.
- P=softmax(S), applied to each row: the weight matrix, also T×T.
- O=PV: the output.
Plug in real numbers: T=8192, d=128, 32 heads, half precision at 2 bytes per number. Q, K and V are 64 MB each. And S?
81922×32×2 bytes≈4 GB
S is a full 64 times bigger than Q, which is exactly T/d. And it gets worse with longer sequences: double T, and S becomes four times as big.
The straightforward implementation actually builds that matrix and stores it in memory:
import torch
import torch.nn.functional as F
import math
def standard_attention(q, k, v):
# q, k, v are all (batch, num_heads, seq_len, head_dim)
scale = math.sqrt(q.size(-1))
# Materialize full N×N attention matrix
attn_weights = torch.matmul(q, k.transpose(-2, -1)) / scale # (batch, num_heads, seq_len, seq_len)
attn_weights = F.softmax(attn_weights, dim=-1)
output = torch.matmul(attn_weights, v) # (batch, num_heads, seq_len, head_dim)
return output
attn_weights has shape (batch, num_heads, seq_len, seq_len): that's the 4 GB monster.
Naive attention: trip after trip
The straightforward implementation takes three steps. Each is a separate kernel, so every intermediate result goes back to HBM:
- Read Q and K from HBM, compute S, write all 4 GB of S back to HBM.
- Read all of S back in, apply softmax to get P, write P back out.
- Read P and V, multiply to get O, write O back to HBM.
The big T×T matrix was written twice and read twice: 16 GB of traffic just to move it around. The softmax step gets the worst deal: a few operations per element, but 4 bytes of reading and writing, a textbook case of memory-bound. At 2 TB per second, moving all that data takes over 8 milliseconds, while the actual matrix math at peak compute needs only about 3.5. Moving the data is slower than doing the math.
Training is even worse. Backpropagation needs P, so P has to be kept around: 4 GB per layer, 128 GB for 32 layers. A single 80 GB card simply can't hold it.
The root of the problem is the T×T intermediate matrix. Could we simply never write it to HBM?
Tiling: one small block at a time
The first half of the solution is tiling. Split Q into blocks of rows, and split K the same way. Matrix multiplication has a handy property: each small block of S depends on just one block of Q and one block of K. For example,
S23=Q2K3⊤
The second block of Q times the transpose of the third block of K gives the block of S in row two, column three.
How big is a block? Say 64 rows of 128 numbers in half precision: 16 KB. One block each of Q, K and V, plus a block of scores and an output accumulator, comes to about 100 KB, which fits in one SM's SRAM (192 KB). So S can be computed one block at a time, right there in SRAM: compute a block, use it, throw it away, never writing it back to HBM.
But here's the catch. We don't want S itself; we want a softmax over each row of S, and softmax needs the whole row: the row's maximum and the sum of its exponentials. Yet at any moment we hold only a small piece of that row. It's like working out each person's share of the total score when you can only see a few people's scores at a time.
Why softmax needs three passes
Softmax raises e to each score and divides by the sum of all those exponentials. As episode 5 showed, computing it directly can overflow: the largest number half precision can represent is 65504, but e12 is already more than 160,000. So in practice we use the stable version, subtracting the row's maximum M in both numerator and denominator:
softmax(x)i=∑jexj−Mexi−M
The largest term becomes e0=1, so nothing overflows, and the result doesn't change. But now it takes three passes:
- Scan from start to finish to find the maximum M.
- Scan again, adding up exj−M to get the denominator.
- Only then compute each weight, multiply it by its v, and add everything up.
With the whole row in front of us, three passes would be no big deal. But with tiling, the row is spread across several blocks, so every pass means reading K from HBM all over again. Could we do all three jobs in one pass? Yes.
Online softmax: update as you read
This is online softmax: as you read through the data, keep track of just two numbers.
- m: the largest value seen so far.
- ℓ ("ell"): the sum of exponentials so far, with the current m subtracted from every term. (Episode 5's preview called this running denominator d; it's the same thing.)
Walk through the four numbers 1, 3, 2, 4:
| Read |
m |
Rescale |
ℓ |
| 1 |
1 |
— |
1 |
| 3 |
3 |
0.135 |
1.135 |
| 2 |
3 |
1 |
1.503 |
| 4 |
4 |
0.368 |
1.553 |
- Read 1: the maximum is 1, and the sum is e1−1=1.
- Read 3: bigger than 1, so the maximum becomes 3. Problem: the sum we hold was computed against the old maximum, 1. Against the new maximum, that term should have been e1−3. So multiply the old sum by exactly that (0.135) and add the new term, e0=1: ℓ=1.135.
- Read 2: doesn't beat 3, so the maximum stays put, the rescaling factor is 1, and we just add e2−3=0.368: ℓ=1.503.
- Read 4: a new maximum again. Multiply the old sum by e3−4=0.368 and add 1: ℓ=1.553.
Check it the old way: the maximum is 4, and the four values of ex−4 are 0.050, 0.368, 0.135 and 1, totaling 1.553. A single pass, exactly right. The whole secret is one rule: whenever the maximum changes, multiply the old sum by a rescaling factor.
Deriving the update rule
Definitions: mk is the maximum of the first k numbers, and ℓk is the sum of exponentials over the first k terms, each with mk subtracted:
mk=max(x1,…,xk),ℓk=j=1∑kexj−mk
When number k+1 arrives, updating the maximum is easy:
mk+1=max(mk, xk+1)
The interesting one is ℓ. In the exponent, subtract the old mk and add it right back, then use the fact that adding exponents is the same as multiplying powers:
exj−mk+1=exj−mk+mk−mk+1=exj−mk⋅emk−mk+1
So:
ℓk+1=j=1∑k+1exj−mk+1=j=1∑kexj−mk+1+exk+1−mk+1=j=1∑kexj−mk⋅emk−mk+1+exk+1−mk+1=(j=1∑kexj−mk)emk−mk+1+exk+1−mk+1=ℓk⋅emk−mk+1+exk+1−mk+1
Line two pulls the last term out on its own; line three splits each term into two factors, the second of which doesn't depend on j; line four pulls that factor outside the sum; and what's left in the brackets is exactly the old ℓk!
That's the online softmax update: take the old sum, multiply by the rescaling factor emk−mk+1, and add the new term.
- The new maximum is never smaller than the old, so the rescaling factor is never more than 1: exactly 1 if the maximum stays the same, and if the maximum grows, it shrinks the old sum to the new reference point.
- Every exponent is zero or less, so nothing can ever overflow.
- After the last number, m is the row's maximum and ℓ is exactly the stable softmax denominator.
Computing the output as we go
Attention needs more than the denominator. It needs a weighted sum of V using the softmax weights:
O=j∑pjvj=ℓ∑jexj−Mvj
The good news: the numerator can also be computed on the fly. Keep a third number, o, the running total of each exponential times its v:
ok=j=1∑kexj−mkvj
Its update rule is just like the one for ℓ, except the new term is multiplied by v:
ℓk+1ok+1=ℓk⋅emk−mk+1+exk+1−mk+1=ok⋅emk−mk+1+exk+1−mk+1vk+1
Back to the example, giving the scores values v of 10, 20, 30 and 40 (each v is a single number, to keep it simple):
- o=1×10=10.
- The maximum changed, so the old o is multiplied by 0.135, then we add 20: 21.35.
- Add 0.368×30: 32.39.
- Multiply by the rescaling factor 0.368 and add 40: 51.92.
Finally o/ℓ=51.92/1.553=33.43. Check: the four softmax weights are 0.032, 0.237, 0.087 and 0.644, and the weighted sum of v is also 33.43.
The whole process read the data only once and never stored all the weights. That's exactly what FlashAttention needs.
Intuition: Nearly every numerical-stability trick is the same move: subtract a big constant (usually the maximum) from the exponent, then account for it afterward. Online softmax just does the accounting as it reads.
Reading a whole block at once
So far we've read one number at a time, but reading a whole block follows exactly the same rule. Split the four scores into two blocks:
- Block one is 1 and 3: the block maximum is 3, the sum of exponentials is 0.135+1=1.135, and o=21.35.
- Block two is 2 and 4: the new maximum is 4. The old ℓ and o are both multiplied by the rescaling factor e3−4, and then the contributions of every term in this block are added.
The result is still 1.553 and 51.92, exactly as before.
Now bring this into attention. In a block Sij (query block i against key block j), every row has its own m and ℓ. In matrix form, the update is four lines:
minewP~ijℓiOi=max(mi, rowmax(Sij))=eSij−minew←emi−minewℓi+rowsum(P~ij)←emi−minewOi+P~ijVj
Line one updates each row's maximum. Line two exponentiates the block of scores using the new maximum; call the result P~ ("P tilde"). In the last two, ℓ and O are first multiplied by the rescaling factor, then we add the row sums of P~ to ℓ, and P~ times V to O. That second one is a small matrix multiply, which is exactly what GPUs do best. Once every block has been read, Oi/ℓi gives the final attention output for those rows.
The FlashAttention forward pass
Now put the pieces together. Down below is HBM, holding the full Q, K and V; up top is the SRAM of one SM.
- Load one block of Q (say 64 rows) into SRAM and set up three things for those rows: the maximum m, the sum ℓ, and the output accumulator O, starting at −∞, 0 and 0.
- Stream K and V through, one block at a time: load a block, compute that small block of scores in SRAM, and update m, ℓ and O with the rule above. Use it, toss it, move on.
- Once every block has streamed through, divide O by ℓ to get the final output for these rows, and write only that final output back to HBM, along with each row's m and ℓ, because backpropagation will need them.
- Move on to the next block of Q and repeat until every row is done.
In this whole process, the T×T score matrix never once goes into HBM. It only ever appears in SRAM, one small block at a time, and only briefly. The price is that K and V get read over and over, once for every block of Q. But the big matrix never moves in or out of HBM, and in the opening example that cut HBM traffic by a factor of nine.
As pseudocode, it's just two nested loops: the outer loop over blocks of Q, the inner loop over blocks of K and V. The five lines after S = ... in the inner loop are exactly the online softmax update we derived, and the whole loop is fused into a single kernel, so the intermediate results never leave the chip.
for i in range(n_q_blocks): # Q blocks are independent
load Q_i; m = -inf; l = 0; O = 0
for j in range(n_kv_blocks):
load K_j, V_j
S = Q_i @ K_j.T / sqrt(d)
m_new = maximum(m, S.max(axis=1))
P = exp(S - m_new)
l = exp(m - m_new) * l + P.sum(axis=1)
O = exp(m - m_new) * O + P @ V_j
m = m_new
write O / l, and m, l, to HBM
Parallelism: each block of Q in the outer loop is independent of the others, so different SMs can work on them at the same time. Every sequence and every attention head is completely independent too, so you have batch × num_heads parallel workers, each handling an m × head_dim tile of Q, K and V (where m is the tile size), and all 108 SMs stay busy.
Causal mask: in a language model, each position can only look at the positions before it. With tiling, the blocks above the diagonal are completely masked out, so we skip them entirely, which saves nearly half the computation. The mask is handled efficiently inside the kernel, without ever materializing a mask matrix.
Backward pass: recompute, don't store
Training also needs backpropagation. Gradients use intermediate results from the forward pass, and attention's gradients depend on the weight matrix P almost everywhere. The straightforward implementation stores all of P: 4 GB per layer. FlashAttention stores no big matrix at all, just the output O plus each row's m and ℓ.
In fact m and ℓ combine into a single number, the logsumexp, written L:
Li=mi+logℓi
It's exactly the stable logsumexp from episode 5: log∑jexj=xmax+log∑jexj−xmax. With L, any weight can be computed in one step. Moving ℓ up into the exponent turns it into −logℓ:
pij=ℓiesij−mi=esij−mi−logℓi=esij−Li
So during backpropagation, FlashAttention reads small blocks of Q and K back into SRAM, recomputes that block of S, uses L to get the matching block of P in one step, immediately computes that block's contribution to the gradients, and throws it away. This trick is called recomputation: do one extra matrix multiply, and in exchange never store or move the big matrix.
What has to be stored drops from 4 GB per layer to about 1 MB: 8192 positions times 32 heads, with one 4-byte number each.
And that solves the opening puzzle. FlashAttention does more computation because it recomputes in the backward pass, but it reads and writes HBM nine times less, so it's much faster anyway.
What FlashAttention buys us
- It saves memory: attention's intermediate results (its activation memory) used to grow with T squared, O(n2), and now grow only linearly, O(n). In episode 10's per-layer activation count 14BSD+BNS2 (B batch size, N heads, S sequence length), the second term becomes BNS under FlashAttention. With the standard implementation, doubling the sequence length makes this part of memory four times as big; avoiding that is one of the key reasons today's models can handle such long contexts.
- It's faster, because it's no longer held back by HBM bandwidth.
- It's exact: every step is a strict algebraic rewrite, so it differs from standard attention only by tiny floating-point rounding. It is not an approximation.
Using it is easy. PyTorch's F.scaled_dot_product_attention automatically picks the best backend (Flash Attention, memory-efficient, or math), and FlashAttention is one of the candidates; setting is_causal=True fuses the causal mask efficiently into the kernel:
def flash_attention(q, k, v):
# Same input shapes: (batch, num_heads, seq_len, head_dim)
# PyTorch picks the best backend automatically (Flash Attention, memory-efficient, or math)
output = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return output
When loading a model with Hugging Face for inference, you can pass attn_implementation="flash_attention_2" to from_pretrained(), or call model.to_bettertransformer(). FlashAttention has since gone through a second and a third version, each faster on newer GPUs, but the core idea hasn't changed: fewer trips to HBM.
Recap
- GPU memory comes in levels: HBM is the main memory (40 or 80 GB on an A100), big but slow from the compute units' point of view; SRAM sits on the chip (about 20 MB on an A100), tiny but very fast. Computation only happens on the chip.
- Arithmetic intensity decides the bottleneck. The A100's ridge point is about 156 FLOP per byte; below it you're memory-bound, and moving less matters more than computing less. Kernel fusion cuts data movement without cutting any operations.
- Naive attention writes the T×T matrix to HBM twice and reads it twice, and training has to keep P around, at a cost that grows with T squared.
- Online softmax tracks just m and ℓ (plus the output accumulator o), multiplies by the rescaling factor emk−mk+1 whenever the maximum changes, and finishes in one pass with exactly the stable softmax result.
- FlashAttention fuses tiling and online softmax into one kernel, so the T×T matrix never touches HBM. In the backward pass it stores only O and the logsumexp L, and recomputes instead of storing. Exact, memory-saving, and faster.
This episode was about making a single computation fast. Next time we zoom out: how big should the model be, how much data should it see, and how should the compute budget be spent? That's what scaling laws are about.