AI from scratch · Toolkit 5 · Stage 4: the engineer's toolkit
GPUs and scale
A laptop CPU does a few hundred billion multiply-adds a second. A data-center GPU does a few hundred trillion, and it's the reason today's models exist. But a GPU is only that fast at one kind of work, it has a fixed amount of memory, and most "my training is slow" or "CUDA out of memory" problems come from not knowing the numbers. This lesson is the numbers: what a GPU is good at, how much memory a model needs, how smaller number formats double the speed, and how work gets split when one GPU isn't enough.
1. Why a GPU
A CPU has a few dozen fast, clever cores; a GPU has thousands of simple ones that all do the same thing to different numbers at once. A matrix product is exactly that: every output entry is its own dot product, independent of the others. So the work that dominates deep learning (chapter 1's matrix products, in every layer, for every example in the batch) is the work GPUs are built for.
A FLOP is one multiply or one add, so an \(n \times n\) product costs \(2n^3\) FLOPs. Your browser's number above is probably between 1 and 50 GFLOP/s (it runs NumPy compiled for the web, on one core). That gap of four to five orders of magnitude is why nobody trains on a laptop CPU.
About how many billion FLOPs (GFLOP) is one \(4096 \times 4096\) matrix product? (Use \(2n^3\).)
A GPU is thousands of simple cores doing the same arithmetic on different numbers, which is exactly the shape of a matrix product.
2. Compute-bound or memory-bound
A GPU can only compute on numbers it has fetched from its memory, and fetching is far slower than computing. An NVIDIA A100 does about 312 trillion bfloat16 FLOPs a second but moves only about 2 trillion bytes a second: it needs some 150 FLOPs per byte fetched to keep its cores busy. Big matrix products reuse each number thousands of times and get there. Element-wise work (adding, ReLU, normalizing) does one FLOP per number and spends its time waiting for memory.
Why a big matmul keeps the cores busy and a ReLU can't
- Arithmetic intensity = FLOPs done ÷ bytes moved. It decides which limit you hit.
- A \(4096 \times 4096\) product in bfloat16 (2 bytes a number): \(2 \cdot 4096^3 \approx 1.4 \times 10^{11}\) FLOPs, while reading two matrices and writing one moves \(3 \cdot 4096^2 \cdot 2 \approx 10^8\) bytes. Intensity ≈ 1,365.
- A ReLU on the same numbers: one comparison per number, 2 bytes read and 2 written. Intensity ≈ 0.25.
- The A100's balance point is \(312 \times 10^{12} / 2 \times 10^{12} \approx 156\) FLOPs per byte. The matmul is far above it (compute-bound: the cores are the limit); the ReLU is 600 times below it (memory-bound: the cores wait).
- That's why libraries fuse element-wise steps into the matmul that precedes them (one trip to memory instead of three), and why FlashAttention is faster while doing the same arithmetic: attention (chapter 7) compares every word with every other in an \(n \times n\) table of scores, and FlashAttention never writes that table to memory.
A GPU computes far faster than it fetches, so work that reuses each number many times (matrix products) runs at full speed and element-wise work waits on memory.
3. The memory math of a model
Out of memory is the most common GPU error, and it's predictable. Each parameter needs bytes for itself and, while training, for its gradient and the optimizer's state:
| What | Bytes per parameter |
|---|---|
| Running it (inference), float32 / float16 / 8-bit / 4-bit | 4 / 2 / 1 / 0.5 |
| Training with Adam, float32: weights 4 + gradients 4 + Adam's \(m\) 4 + \(s\) 4 | 16 |
| Training with Adam, mixed precision: float16 weights 2 + gradients 2 + float32 master copy 4 + \(m\) 4 + \(s\) 4 | 16 |
| Plus activations: every layer's outputs, kept for backprop (chapter 4), growing with batch size × sequence length | often as much again, or more |
How many GB does a 7-billion-parameter model need just for its weights in float16?
Memory is parameters times bytes: about 2 per parameter to run in float16, about 16 to train with Adam, plus activations that grow with the batch.
4. Smaller numbers: float16, bfloat16 and loss scaling
Halving the bytes per number halves memory traffic and, on modern GPUs, roughly doubles matrix-product speed. Two 16-bit formats split the bits differently:
| float32 | float16 | bfloat16 | |
|---|---|---|---|
| Largest number | 3.4 × 10³⁸ | 65,504 | 3.4 × 10³⁸ |
| Significant digits | about 7 | about 3 | about 2 |
| Trouble | none, but slow | overflows to inf, small gradients round to 0 | coarse: 257 is stored as 256 |
Mixed precision does the heavy matrix products in 16 bits and keeps the master weights and the sums that need precision in float32. In PyTorch it's a few lines: with torch.autocast("cuda", dtype=torch.bfloat16): around the forward pass. With float16 you also need a GradScaler, which multiplies the loss by a big number so small gradients survive the trip through float16 (chapter 4's underflow), then divides it back out. bfloat16 has float32's range, so it needs no scaler, which is why newer GPUs default to it.
Training in float16, the loss turns into inf after a few hundred steps, but trains fine in bfloat16. Why?
- Some number grew past 65,504, float16's largest; bfloat16's range goes to 10³⁸
- bfloat16 is more precise
- bfloat16 is faster
16-bit numbers halve memory and double speed; float16 can overflow and lose tiny gradients (loss scaling rescues them), bfloat16 keeps float32's range at lower precision.
5. Batches, and gradient accumulation
A GPU runs at full speed only with enough work at once, so throughput (examples per second) rises with batch size until the GPU is saturated, then flattens; memory grows the whole way. When the batch you want doesn't fit, gradient accumulation runs several small batches, adds up their gradients (PyTorch's .backward() adds, remember), and steps once:
accum = 4 # 4 micro-batches of 16 act like one batch of 64
for i, (xb, yb) in enumerate(loader):
loss = F.cross_entropy(model(xb), yb) / accum # divide, so the sum is the mean over 64
loss.backward() # gradients add up in .grad
if (i + 1) % accum == 0:
opt.step(); opt.zero_grad()
Same gradients as the big batch (exactly, for losses that are means and models without batch norm), a quarter of the activation memory, a bit slower. The other common slowdown isn't the GPU at all: a data loader that can't decode images fast enough leaves the GPU waiting. DataLoader(..., num_workers=4, pin_memory=True) prepares batches in parallel; nvidia-smi showing 30% utilization usually means the data is the bottleneck.
Gradient accumulation adds up several small batches' gradients before one step, buying a big batch's gradient for a small batch's memory.
6. More than one GPU
| Split | How | When |
|---|---|---|
| Data parallel (DDP) | Every GPU holds the whole model and gets a different slice of the batch; after backward, the GPUs average their gradients (an all-reduce) and all take the same step | The model fits on one GPU; you want more examples per second |
| Sharded (FSDP, ZeRO) | Like data parallel, but the weights, gradients and Adam states are split across GPUs and gathered just in time | The 16 bytes per parameter don't fit on one GPU |
| Tensor parallel | Each big matrix is split by columns or rows across GPUs | Single layers too big, or latency matters |
| Pipeline parallel | Layers 1–10 on GPU 1, 11–20 on GPU 2…, with micro-batches flowing through | Very deep models across machines |
Data parallel on 8 GPUs, each with a batch of 32. What batch size does the optimizer effectively see?
- 32
- 256
- 4
When one GPU isn't enough, split the batch (data parallel), the memory (sharding), the matrices (tensor parallel) or the layers (pipeline).
Where it breaks: the limits of "just add GPUs"
- Talking costs time. Every step, data parallel must all-reduce a full gradient: 14 GB for a 7B model in float16. Between machines that can take longer than the step's arithmetic, so 64 GPUs don't train 64 times faster; frameworks overlap the communication with the backward pass to hide some of it.
- Bigger batches stop helping. More GPUs mean a bigger effective batch, and past the "critical batch size" doubling it no longer halves the steps needed (the training-in-PyTorch lesson). Past that point extra GPUs buy almost nothing.
- 16-bit surprises. Some operations (softmax sums, loss reductions, norms) need float32 to stay accurate; autocast keeps a list of them. Hand-written code that sums thousands of float16 numbers loses digits, as NumPy in depth showed for float32.
7. What to carry forward
- A GPU is fast at matrix products (compute-bound) and merely fast-memoried at everything else (memory-bound).
- Memory: ~2 bytes per parameter to run in float16, ~16 to train with Adam, plus activations. Estimate before you rent.
- Mixed precision: autocast with bfloat16; float16 needs a GradScaler.
- Too big a batch for memory: gradient accumulation. A slow GPU at low utilization: the data loader.
- Many GPUs: data parallel first, sharding when the model's training state doesn't fit.
All lessons: AI from scratch. Horace He's essay "Making Deep Learning Go Brrrr From First Principles" covers sections 2 and 4 in depth.
Last updated