A GPU waits on memory far more often than on math. An H100 does 989.5 trillion bf16 FLOPs a second but moves only 3.35 trillion bytes. So an operation needs 295 FLOPs per byte to keep it busy. A ReLU does 0.25.
Pick an operation and a GPU. Watch how much of the compute the memory pipe can feed. Then we build the picture piece by piece: warps, the memory ladder, intensity, the roofline, and the four tricks that end in FlashAttention.
You need FLOP counting and bytes per number from Lecture 2. We build the rest from zero.
Lecture 5 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto; this lecture by Tatsunori Hashimoto). Previous: Lecture 4, Mixture of Experts. Next: Lecture 6, Kernels and Triton.
Peaks are NVIDIA's datasheet numbers for dense bf16 (the H100 lists 1,979 TFLOP/s "with sparsity"; dense is half). Matmuls are square, in bf16, with each matrix crossing memory once: the best case. The moving packets are illustrative.
Chapter 0
Time a kernel with two clocks, one for math and one for memory, and see which one you wait on
You run a ReLU over a billion bf16 numbers on an H100. The datasheet promises 989.5 trillion FLOPs a second. That is one FLOP per number, so the math should take one microsecond. The profiler says 1.2 milliseconds.
The math was never the problem. Every number has to come in from memory and go back out. A GPU has two speeds: how fast it computes, and how fast it moves bytes. Each kernel (one function launched on the GPU) pays for the slower one.
Name the four quantities. Call the FLOPs a kernel does F, and the bytes it moves to and from the GPU's main memory Q. Call the peak compute P, in FLOP/s, and the memory bandwidth B, in bytes per second. If math and loads overlap perfectly, the kernel takes at least:
t equals the max of F over P, and Q over B.
Divide the FLOPs F by the peak P: that is the math clock. Divide the bytes Q by the bandwidth B: that is the memory clock. The kernel takes as long as the slower clock.
ReLU on 109 bf16 numbers: F = 109, and Q = 2 bytes in + 2 bytes out per number = 4 × 109. F / P = 1.0 µs. Q / B = 1.19 ms. So t = 1.19 ms. The GPU waits 1,181 times longer for bytes than for math. It uses 0.085% of its peak.
Two clocks for one kernel over a billion bf16 numbers. Drag the FLOPs it does per number and watch which clock sets the time.
An illustrative kernel: read each bf16 number once, write it once, do k FLOPs on it. Times assume perfect overlap and the dense bf16 peak. Real kernels add launch overhead.
How much math would hide the memory? On an H100 the kernel needs 1,182 FLOPs per bf16 number, read once and written once. Few kernels do that much. A large matrix multiply does, because it uses every number it loads many times (Chapter 3).
The gap is growing. The lecture's chart shows compute scaling faster than memory. From the A100 to the H100, the dense bf16 peak grew 3.2 times and the bandwidth grew 1.6 times.
Symptom: a training step full of norms, activations and residual adds reaches a few percent of the peak FLOP/s.
Measure: for each kernel, compare Q / B with F / P. The larger one is the time you pay.
Fix: move fewer bytes: lower precision (Chapter 3), fused kernels (Chapter 5), tiles kept on chip (Chapter 7).
Chapter 1
Meet the parts that run a kernel: streaming multiprocessors, blocks, warps of 32 threads, and tensor cores
A CPU runs a few threads fast. It spends its chip on caches and branch prediction, so one thread finishes soon. A GPU runs many thousands of threads at once. It spends its chip on arithmetic units and gives each thread little help. The lecture's summary: CPUs optimize for latency, GPUs for throughput.
An A100 has 108 streaming multiprocessors (SMs). Each SM is an independent processor with its own registers and shared memory. You launch a kernel as a grid of blocks, and the GPU places each block on one SM. Threads in a block share data through that SM's shared memory. Threads in different blocks share data only through global memory.
Inside an SM, threads run in warps of 32 consecutive threads. A warp issues one instruction for all 32 lanes, each on its own data. NVIDIA calls this SIMT: single instruction, multiple threads. An A100 SM holds up to 64 warps, 2,048 threads, so the chip keeps 221,184 threads resident.
SIMT has a cost. If some lanes take the if-branch and others the else-branch, the warp runs both paths, one after the other. The lanes on the other path sit idle. This is control divergence. It is not a memory problem, but it wastes compute in the same way.
Each row is a lane of one warp; time runs to the right. Drag how many lanes take the if-branch. Then make the branch depend on the warp, not the lane.
Illustrative: each path costs 10 steps. Real hardware since Volta can interleave the two paths, but a warp still issues one path's instruction at a time.
With 16 lanes on each side and 10 steps per path, the warp takes 20 steps to do 10 steps of work per lane. Half of its lane-steps are idle.
Matrix multiplies get their own hardware. Tensor cores are circuits that multiply small matrix tiles in one operation. An A100 has 4 per SM, 432 in all. They give 312 TFLOP/s in bf16, against 19.5 TFLOP/s of ordinary float32 math: 16 times more. The H100's ratio is 14.8. The lecture's rule: matmuls are more than 10 times faster than other floating-point work.
Symptom: a kernel with an if on the thread index runs at half speed.
Measure: for a few warps, count how many of the 32 lanes take each side.
Fix: branch on the warp index (threadIdx.x / 32), so whole warps agree, or sort the data so neighbours take the same path.
Chapter 2
Climb from registers to HBM, and see why a GPU needs many loads in flight to hide the wait
Memory near the SM is fast and small. Memory far away is big and slow. The lecture's rule of thumb: on-chip SRAM costs about 100 times more per byte than DRAM, and is about 8 times faster. Main GPU memory is HBM, high-bandwidth memory: DRAM chips stacked next to the GPU die.
| Level | A100 80 GB SXM | H100 SXM | Latency (cycles) | Shared by |
|---|---|---|---|---|
| Registers | 65,536 × 32-bit per SM (256 KB) | the same | fastest | one thread (up to 255 each) |
| Shared memory and L1 | 192 KB per SM, up to 164 KB shared | 256 KB per SM, up to 228 KB shared | 19 to 33 | the threads of one block |
| L2 cache | 40 MB | 50 MB | 200 | all SMs |
| HBM | 80 GB at 2.039 TB/s | 80 GB at 3.35 TB/s | 290 | all SMs |
The latencies come from a measured table on the lecture's slide. A load from HBM takes about 290 cycles: 206 ns at the A100's 1.41 GHz boost clock. During that time the memory system must already be serving other loads, or the pipe has gaps. Call the bandwidth B and the latency of one load L. The bytes that must be in flight at every moment are:
D equals B times L.
Multiply the bandwidth B by the time one load takes, L. That many bytes D must be on their way at once. With fewer, the memory idles between loads.
A100: L = 290 / 1.41 GHz = 206 ns. D = 2.039 × 1012 × 206 × 10−9 = 419 KB over the chip, or 3.9 KB per SM. A warp that loads 32 floats asks for 128 bytes, so each SM needs about 30 warp-loads outstanding.
Those loads come from many resident warps. When one warp waits for memory, the SM issues instructions from another. Occupancy is the ratio of active warps on an SM to the most it can hold, 64. Registers often set the limit: an SM has 65,536, and each thread keeps its own.
warps that fit = 65,536 / (32 × registers per thread): 32 registers give 64 warps (100%), 64 give 32 (50%), 128 give 16 (25%).
Top: the SM's 64 warp slots. Bottom: bytes in flight if each warp has one 128-byte load out, against the 3.9 KB that keeps HBM busy. Drag the two budgets.
A100 limits: 65,536 registers, 164 KB shared memory, 64 warps and 32 blocks per SM; blocks of 256 threads. We ignore register allocation granularity. One load per warp is an illustrative assumption.
At 255 registers per thread only 8 warps fit. With one load each, that is 1 KB in flight per SM, a quarter of the 3.9 KB the memory needs. The SM stalls even though nothing is "wrong" in the code.
Symptom: a memory-bound kernel reaches a small share of the bandwidth.
Measure: registers per thread (nvcc -Xptxas -v prints them) and the achieved occupancy in a profiler.
Fix: use fewer registers or less shared memory per block, or give each warp several independent loads.
Chapter 3
Count the FLOPs per byte for a ReLU and a matmul, and see how precision and size move the number
Chapter 0 compared the math clock F / P with the memory clock Q / B. Divide F by Q and the hardware drops out. What is left belongs to the operation alone.
Call it the arithmetic intensity: the FLOPs an operation does for each byte it moves to or from HBM.
I equals F over Q.
Count the FLOPs F. Count the bytes Q that cross HBM, both ways. Divide F by Q.
ReLU in bf16: F = 1 per number, Q = 2 bytes read + 2 written = 4. I = 0.25 FLOPs per byte. In float32 Q = 8, so I = 0.125. The lecture writes the same as 8 and 4 bytes per FLOP.
This is the lecture's first trick: fewer bits per number means fewer bytes to move. It helps memory-bound kernels at once. Tensor cores also run bf16 and fp8 faster than float32, so it helps matmuls too.
Now a square matrix multiply, C = A × B, with all three n by n, in bf16. Each of the n2 outputs needs n multiplies and n adds, so F = 2n3. In the best case each matrix crosses HBM once: Q = 3 × n2 × 2 bytes.
I = 2n³ / (6n²) = n / 3. n = 64: 21. n = 512: 171. n = 4,096: 1,365.
The operation's bytes and FLOPs, and its intensity on a log scale with each GPU's ridge (Chapter 4). Pick an operation and a format; for the matmul, drag n.
Best case: each tensor crosses HBM once. Ridges are for dense bf16; fp8 and float32 have their own peaks, so the marks are a guide.
Intensity grows with n because each loaded number serves n outputs. Big matmuls can keep a GPU busy; elementwise operations cannot, at any size.
Symptom: many small matmuls (n = 64) run far below the peak.
Measure: I = 64 / 3 = 21 FLOPs per byte, under every ridge.
Fix: batch the small products into one large one, for example all attention heads in one call, so the effective n grows.
Chapter 4
Turn the two clocks into one plot, and find the ridge where an operation stops waiting on memory
Divide the FLOPs by the time from Chapter 0 and you get the speed a kernel can reach. Write the bytes as Q = F / I, and F cancels. Call that speed the attainable FLOP/s, Patt:
P-att equals the min of P, and I times B.
Multiply the intensity I by the bandwidth B: that is how many FLOPs a second memory can feed. The kernel gets that, or the peak P, whichever is smaller.
Matmul with n = 512, I = 171. A100: 171 × 2.039 TB/s = 348 TFLOP/s, above 312, so it gets the peak. H100: 171 × 3.35 TB/s = 572 TFLOP/s, below 989.5, so memory caps it at 58%.
The two limits meet at the ridge point, where I × B = P. Below it a kernel is memory-bound; above it, compute-bound.
ridge = P / B. A100: 312 / 2.039 = 153 FLOPs per byte. H100: 989.5 / 3.35 = 295.
The slanted part is memory, the flat part is compute, the yellow mark is the ridge. Drag the intensity, or pick an operation, and switch the GPU.
Dense bf16 peaks and HBM bandwidth from NVIDIA datasheets. The softmax intensity of 4 is a round illustrative value. A roofline gives a ceiling, not a prediction.
The lecture's roofline also draws roofs for shared memory and registers: faster memory, steeper line. The ridge moved from 153 to 295 between the A100 and the H100. A kernel can turn memory-bound on the newer chip with no change in its code.
Symptom: a kernel runs 1.6 times faster on an H100, not 3.2.
Measure: its intensity is under 295, so it sits on the slanted roof.
Fix: raise the intensity (fuse, tile, use fewer bytes per number), or expect only the bandwidth gain.
Chapter 5
Stop sending intermediate results back to memory, and recompute what is cheaper to redo than to reload
The lecture's picture: the GPU is a factory and memory is a warehouse. Each kernel is one round trip. PyTorch runs eagerly, so each operation is its own kernel: it reads its inputs from HBM and writes its output back.
Take sin2x + cos2x. Eager PyTorch launches 5 kernels: sin, square, cos, square, add. Count the trips: 6 tensor reads and 5 tensor writes, 11 passes over memory. A fused kernel reads x once, keeps every intermediate in registers, and writes the result once: 2 passes.
Top row: kernels. Bottom row: HBM. Each blue arrow is one pass over the whole tensor. Pick an example, then switch the trick on.
Pass counts are the lecture's. Times are ours: 100 million bf16 numbers per tensor at the H100's 3.35 TB/s, memory time only.
On 100 million bf16 values on an H100, the 11 passes move 2.2 GB in 657 µs. The fused kernel moves 0.4 GB in 119 µs: the same math, 5.5 times faster. torch.compile finds easy fusions like this one by itself. For a chain of k one-input elementwise operations, fusion cuts 2k passes to 2.
Backprop needs activations, so the forward pass usually stores them. The lecture's example stacks 3 sigmoids. Stored: the forward pass reads x and writes 3 activations; the backward pass reads 2 of them plus the incoming gradient, and writes 1 gradient. That is 8 trips.
Recomputation throws the activations away and recomputes them inside the backward kernel. The forward pass reads x and writes the output; the backward pass reads x and the incoming gradient and writes 1. That is 5 trips, 5/8 of the traffic, for some extra math. On a memory-bound chain the extra math is nearly free.
Symptom: norms, activations and residual adds take a large share of step time, with few FLOPs.
Measure: count the kernels and the HBM passes in a profiler trace.
Fix: torch.compile, or a hand-fused kernel (Lecture 6).
Chapter 6
Line up a warp's loads so they share the same 32-byte pieces of memory
DRAM does not hand out single bytes. It reads in bursts: opening a row is slow, so each read returns a run of neighbouring bytes. The lecture's rule: a warp's accesses coalesce when its threads fall within the same burst.
NVIDIA's CUDA guide gives the rule for current GPUs. A warp's loads combine into as many 32-byte transactions as it takes to cover them. If the 32 lanes read 32 neighbouring floats, that is 128 bytes in 4 transactions, and the warp wastes nothing.
Name the parts. A warp asks for U useful bytes, here 32 × 4 = 128. The hardware fetches S sectors of 32 bytes each. The efficiency η is:
eta equals U over thirty-two times S.
Count the sectors S that the 32 addresses touch. Multiply by 32 to get the bytes fetched. Divide the bytes the lanes wanted, U, by that.
Stride 1 float: S = 4, η = 128 / 128 = 100%. Stride 2: S = 8, η = 50%, as NVIDIA's guide states. Stride 8 or more: each lane hits its own sector, S = 32, η = 128 / 1,024 = 12.5%.
Top: the 32 lanes. Bottom: the sectors they touch, 8 floats each. Blue slots hold the lanes' floats; red slots come along unused. Drag the stride, then shift the start.
The 32-byte sector rule is from NVIDIA's CUDA C++ Best Practices Guide for compute capability 6.0 and later. Caches can turn wasted bytes into later hits; this counts one warp's request alone.
Matrices make this concrete. In a row-major matrix, neighbours along a row are neighbours in memory. If lane i reads row i of one column, the stride is the row length: 4,096 floats apart, η = 12.5%. Matmul kernels assign threads so that a warp walks along rows, or stage tiles through shared memory first.
Symptom: a transpose or a column sum runs at about one eighth of the bandwidth.
Measure: η from the stride; profilers report sectors per request.
Fix: give consecutive lanes consecutive addresses. Load a tile coalesced into shared memory, then read it there in any order.
Chapter 7
Load blocks of a matrix into shared memory once and reuse them, then mind the tile and wave counts
A naive matmul gives each output its own thread. The thread for C[i, j] reads row i of A and column j of B from HBM. So the threads read each element of A n times, once per column of C. For n = 4,096 in bf16 that is 275 GB of traffic, for inputs that hold 67 MB.
Tiling cuts the matrices into T by T tiles. A block loads one tile of A and one of B into shared memory and multiplies them there. Then it moves to the next pair. The lecture's statement: each input is read n / T times instead of n. Call the bytes per number b. Traffic is about 2n2 × (n / T) × b, and the intensity becomes:
I-tiled is about T over b.
Each input number crosses HBM n over T times instead of n times. Divide the 2n³ FLOPs by those bytes: n cancels, and T over b remains.
bf16, T = 128: I ≈ 64 FLOPs per byte (63 with the output write). Naive, T = 1: 0.5. For n = 4,096 the traffic falls from 275 GB to 2.2 GB.
Why not T = 4,096? The tiles must fit in shared memory. Two bf16 tiles take 4T2 bytes: 64 KB at T = 128, but 256 KB at T = 256, over the A100's 164 KB. And 64 is still under the A100's ridge of 153. Real kernels use wider rectangular tiles and lean on the 40 MB L2, where neighbouring blocks find the same tiles.
Tiles bring two quirks. If n is not a multiple of T, edge tiles are partly empty but cost a full tile: tile quantization. And tiles run in waves, one tile per SM at a time. With 256 by 128 tiles, n = 1,792 gives 7 × 14 = 98 tiles, one wave on 108 SMs. n = 1,793 gives 8 × 15 = 120 tiles. The second wave runs 12 tiles while 96 SMs idle, for 0.17% more work.
Traffic: pick T and watch the reads, the traffic and the shared memory. Waves: drag n and watch the tiles fill 108 SMs.
Traffic: both inputs read n / T times, the output written once, in bf16. Waves: one 256 × 128 tile per SM at a time on 108 SMs, the lecture's example.
Symptom: throughput drops when a dimension grows by 1.
Measure: tiles divided by SMs; a small last wave idles most SMs.
Fix: pad dimensions to multiples of 64 or 128.
Chapter 8
Put tiling, fusion and recomputation together, with an online softmax that never needs the whole row
Attention computes S = QKT / √d, then P = softmax(S), then O = PV, per head. With N tokens, S and P are N by N. Standard code writes S to HBM, reads it back for the softmax, writes P, and reads P again. At N = 4,096 one head's S is 33.6 MB in bf16.
FlashAttention (Dao et al., 2022) never writes S or P to HBM. It loads blocks of Q, K and V into shared memory and folds each block of scores into the output there. The lecture lists four parts: tiling, a fused exponential, an online softmax, and recomputation in the backward pass.
The hard part is the softmax. It needs the row's maximum, for safe exponentials, and the row's sum. A block never holds the whole row. The online softmax (Milakov and Gimelshein, 2018) keeps a running max m and a running sum ℓ. When a block of scores xj arrives, set mnew to the larger of m and the block's max, then:
ell-new equals ell times e to the m minus m-new, plus the sum over j of e to the x-j minus m-new.
Set m-new to the larger of m and the block's max. Shrink the old sum ell by e to the m minus m-new. Add the block's shifted exponentials. FlashAttention rescales the partial output the same way.
Scores 1, 3 | 0.5, 2 | 4, −1 | 2.5, 0 in blocks of 2. Block 1: m = 3, ℓ = e−2 + e0 = 1.135. Block 2 keeps m = 3: ℓ = 1.585. Block 3 has a 4: ℓ = 1.585 × e−1 + 1 + e−5 = 1.590. After block 4, ℓ = 1.831, the full row's sum.
Eight scores of one query row arrive two at a time. Press Next block; a new max shrinks the old sum.
The first scores are the worked example; new ones are illustrative random numbers. The device checks its sum against the full row.
The paper proves the traffic: Θ(Nd + N2) HBM accesses for standard attention, Θ(N2d2 / M) for FlashAttention, with M the SRAM size. For d = 64 and M near 100 KB, d2 is far below M. On GPT-2 medium (sequence 1,024, A100, forward plus backward), standard attention moved 40.3 GB in 41.7 ms. FlashAttention moved 4.4 GB in 7.3 ms, with more FLOPs (75.2 G against 66.6 G): 5.7 times faster.
Symptom: long sequences run out of memory in attention.
Measure: batch × heads × N2 × 2 bytes for S, and again for P.
Fix: a fused attention kernel: FlashAttention, or PyTorch's scaled_dot_product_attention, which can dispatch to one.
Chapter 9
Time every operation of one layer with the roofline, then turn on FlashAttention and fusion and watch the memory-bound share shrink
Every chapter in one tool. One layer of a GPT-style model: d = 4,096, 32 heads, MLP width 16,384, 16,384 tokens per batch, bf16. Each operation gets t = max(F / P, Q / B). Purple segments multiply by weights, blue segments are attention, and teal segments are elementwise operations on activations. The list says which ones wait on memory.
Top: the layer as one bar, each segment one operation. Below: the slowest operations with their intensity. Switch the tricks, the GPU and the sequence length.
A roofline bound for the forward pass: every op runs at its own ceiling and nothing else costs time. Real runs land well below these numbers. Elementwise FLOP counts are illustrative (LayerNorm 8, GELU 10, softmax 5 per number). FlashAttention traffic rereads K and V once per block of 128 queries; attention is not causal here.
Things to try. On the H100 at 2,048 tokens per sequence, the layer takes 10.1 ms at the bound, and memory-bound operations take 34% of it. Turn on both tricks: 8.2 ms and 19%. Drag to 16,384 tokens: standard attention pushes the layer to 28.1 ms; with both tricks it takes 17.2 ms.
Switch to the A100. The same layer spends a smaller share on memory, 21%, because its ridge is lower. The newer the chip, the more these tricks matter.
Check yourself. Before you touch it, name the largest memory-bound operation at 2,048 tokens. It is the softmax: it reads S and writes P, at 1.25 FLOPs per byte.
Chapter 10
Keep the numbers, the roofline in code, and the checks that find where a kernel waits
A kernel pays for the slower of its math and its memory. Intensity, FLOPs per byte, says which, against a ridge of 153 on the A100 and 295 on the H100. Every trick in the lecture moves fewer bytes: lower precision, fusion, recomputation, coalescing and tiling. FlashAttention uses all of them.
| Idea | Rule or number | Why it matters |
|---|---|---|
| Two clocks | t = max(F / P, Q / B) | a ReLU on 109 numbers: 1 µs of math, 1.19 ms of memory |
| Warps | 32 threads, one instruction | a split branch runs both paths |
| Bytes in flight | D = B × L | A100: 3.9 KB per SM; needs many resident warps |
| Intensity | I = F / Q | ReLU 0.25; square matmul n / 3 in bf16 |
| Roofline | Patt = min(P, I × B) | ridge P / B: 153 (A100), 295 (H100) |
| Fusion | 2k passes become 2 | sin² + cos²: 11 passes become 2 |
| Recomputation | redo cheap math, skip stored bytes | 3 sigmoids: 8 trips become 5 |
| Coalescing | η = U / (32 × S) | stride 8 or more: 12.5% |
| Tiling | I ≈ T / b | T = 128 in bf16: 64; tiles must fit shared memory |
| Waves | tiles / SMs, rounded up | n = 1,793: 120 tiles, 2 waves on 108 SMs |
| FlashAttention | Θ(N2d2 / M) accesses | GPT-2 medium: 40.3 GB down to 4.4 GB |
The roofline and the online softmax in code. We ran it. The 4,096 matmul reaches the H100's peak at intensity 1,365. The ReLU gets 0.085% of it. The online sum matches the full-row sum, 1.8314.
python import numpy as np GPUS = {'A100': (312e12, 2.039e12), 'H100': (989.5e12, 3.35e12)} # dense bf16 FLOP/s, HBM bytes/s def roofline(F, Q, gpu='H100'): P, B = GPUS[gpu] t = max(F / P, Q / B) # the slower clock sets the time return t, F / Q, F / t / P # seconds, intensity, share of peak n = 4096 print(roofline(2 * n**3, 3 * n * n * 2)) # square bf16 matmul: (0.000139, 1365.3, 1.0) print(roofline(1e9, 4e9)) # ReLU on 1e9 bf16 numbers: (0.00119, 0.25, 0.00085) def online_softmax_sum(x, block): m, l = -np.inf, 0.0 for i in range(0, len(x), block): xb = x[i:i + block] m_new = max(m, xb.max()) l = l * np.exp(m - m_new) + np.exp(xb - m_new).sum() # rescale the old sum, add the block m = m_new return m, l x = np.array([1, 3, .5, 2, 4, -1, 2.5, 0]) print(online_softmax_sum(x, 2), np.exp(x - x.max()).sum()) # (4.0, 1.8314) 1.8314
torch.compile, mixed precision and profiling in practice.Now teach it: press Present or Teach. Explain the two clocks, derive the ridge, and say which byte each trick saves. Then go back to the instrument and predict, before you switch, whether a matmul with n = 512 is compute-bound on each GPU.