Skip to content

5.1 GPUs and performance

ready≈ 14 hoursNeeds: 4.6Unlocks: 5.2, 5.3, 5.7
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (GPU memory calculator, Roofline explorer)
  4. 4 Do
  5. 5 Check

Memory. Training with AdamW keeps, for every parameter, the weights, a gradient and two optimizer moments. That is 16 bytes per parameter in fp32. Mixed precision does not shrink it: 16-bit weights and gradients need a 4-byte master copy beside them (Rajbhandari et al. 2020, §3.1). So a 7 B-parameter model needs over 100 GB before a single activation. Activations, saved for the backward pass, grow with batch × sequence length. The attention scores add a term in the square of the sequence length (Korthikanti et al. 2022, §4). During generation, a KV cache of every past key and value takes their place.

Compute. A matrix product of shapes (m, k) and (k, n) costs 2mkn FLOPs. Almost all of a transformer’s work is such products with its weights, so training costs about 6 FLOPs per parameter per token (Kaplan et al. 2020, §2.1). Divide the FLOP rate this implies by the GPU’s peak and you get model FLOPs utilization, MFU. Good large-scale training reaches 40–50% (Chowdhery et al. 2022, appendix B).

The roofline. A GPU can do far more arithmetic per second than it can fetch numbers from its memory. An operation’s arithmetic intensity is its FLOPs divided by the bytes it moves. Below the ridge point, peak FLOP/s divided by bandwidth, memory is the bottleneck; above it, compute is (How to Scale Your Model, part 1). Large matrix products are compute-bound. Elementwise operations, normalisations and generating one token at a time are memory-bound.

Measuring. GPU calls return before the work is done, so a timer must synchronize before reading the clock. Warm-up calls exclude one-time costs, and the median ignores outliers. A profiler then shows which operations take the time (CS336 lecture 6). Running the matrix products in 16 bits uses the tensor cores, often several times faster, with loss scaling for fp16 (Micikevicius et al. 2018).

Training costs about 6 FLOPs per parameter per tokenstep 1 of 5
  1. Y=XW,X∈Rn×din, W∈Rdin×dout\mathbf{Y} = \mathbf{X}\mathbf{W},\quad \mathbf{X}\in\mathbb{R}^{n\times d_\text{in}},\ \mathbf{W}\in\mathbb{R}^{d_\text{in}\times d_\text{out}}

★ GPU memory calculator

Where memory goes: weights, gradients, optimizer states, activations, KV cache

Static view on small screens. Open this page on a laptop to interact.

124 M parameters · d = 768, 12 layers, 12 heads
A100: 80 GB
  • weights (bf16) 236 MiB (2%)
  • fp32 master weights 471 MiB (5%)
  • gradients (bf16) 236 MiB (2%)
  • optimizer states (fp32) 943 MiB (9%)
  • activations (16-bit) 8.02 GiB (81%)
total 9.86 GiB fits on one A100 (13% full) fixed state 16 bytes per parameter

The estimates of module 5.1: state that lives through training costs a fixed number of bytes per parameter (16 with AdamW, with or without mixed precision), while activations grow with batch × sequence length, and the stored attention matrices with the square of the sequence length. FlashAttention removes that square term; checkpointing keeps only each layer's input and recomputes the rest, at about a third more compute. Real usage is higher: the framework, temporary buffers and the fp32 logits (vocabulary × tokens × 4 bytes) come on top.

A stacked bar splits GPU memory for a chosen model into weights, fp32 master weights, gradients, optimizer states and activations (training), or weights and KV cache (inference), against a dashed line at the chosen GPU’s capacity. Controls choose the model size from 0.8 M to 13 B parameters, batch size and sequence length, mixed precision, the optimizer, FlashAttention, activation checkpointing and int8 weights for inference. The readout gives the total, whether it fits, and the fixed bytes per parameter. Keyboard: Tab to the selects, buttons and sliders; arrow keys move the sliders.

Roofline explorer

Compute-bound vs memory-bound kernels

Static view on small screens. Open this page on a laptop to interact.

peak 312 TFLOP/s · 2039 GB/s
0.010.11101001000100000.0010.010.11101001000ridge 153arithmetic intensity (FLOP per byte moved), log scale · y: attainable TFLOP/s

matmul 4096×4096×4096. A square matrix product, as in training with many tokens per batch. Its intensity grows with the size: about n/3 FLOP per byte in 16 bits.

intensity 1365 FLOP/byte attainable 312 TFLOP/s (100% of peak) compute-bound best-case time 440.5 µs

The roofline model (Williams et al. 2009): a kernel cannot run faster than the peak FLOP rate, nor faster than memory can deliver its bytes. Left of the ridge, adding FLOP/s does nothing; only moving fewer bytes helps. Big matrix products sit far to the right, which is why GPUs are built around them. Token-by-token generation, elementwise operations and normalisations sit to the left, however fast the GPU's arithmetic. Real kernels reach perhaps 60–80% of the roof at best; the 5.1 notebook measures how close PyTorch gets.

A log-log roofline chart for a chosen GPU and number format: attainable TFLOP/s against arithmetic intensity, with a sloped memory roof, a flat compute roof and the ridge point between them. Four operations are plotted: a square matrix product of adjustable size, a decoding step of B tokens through a 4096 × 4096 weight matrix, an elementwise add and a row softmax. The readout gives the selected operation’s intensity, attainable throughput, whether it is memory- or compute-bound and its best-case time. Keyboard: Tab to the GPU and format selects, the operation buttons and the sliders.

First the accounting, in the browser or locally: parameter counts, memory per part, FLOPs, rooflines and a correct benchmark timer.

Memory, FLOPs, rooflines and timing stubs/m5_1_perf.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m5_1_perf.py and run mlc check 5.1. The tests are identical; import the results on the progress page.

Hints · training_state_bytes 0/3 revealed
Hints · activation_bytes 0/3 revealed
Hints · time_fn 0/3 revealed

Then measure a real GPU. Open notebooks/5.1-gpu-benchmarks.ipynb on Kaggle as in module 0.3, paste in your finished file, turn the GPU on and run everything (about five minutes). Using your functions, it compares matrix-product throughput in each number format with the roofline. It also measures the bandwidth of a memory-bound add, checks allocated memory after an AdamW step against 16 bytes per parameter, and profiles a transformer layer. Finally it compares an fp32 training step with mixed precision and reports MFU. Without a GPU it runs everything small on the CPU as a smoke test.

1. Mixed-precision training with AdamW needs how many bytes of persistent state per parameter?
2. A kernel has arithmetic intensity 10 FLOP/byte on a GPU whose ridge point is 150. Which upgrade speeds it up?
3. Why is generating one token at a time memory-bound?
4. Without torch.cuda.synchronize() after the call, a GPU timer mostly measures…
5. Training a 1 B-parameter model on 20 B tokens costs about…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.