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\).)

\(2 \times 4096^3 \approx 1.37 \times 10^{11}\), about 137 GFLOP. A GPU at 300 TFLOP/s does it in under half a millisecond.

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
  1. Arithmetic intensity = FLOPs done ÷ bytes moved. It decides which limit you hit.
  2. 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.
  3. A ReLU on the same numbers: one comparison per number, 2 bytes read and 2 written. Intensity ≈ 0.25.
  4. 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).
  5. 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:

WhatBytes per parameter
Running it (inference), float32 / float16 / 8-bit / 4-bit4 / 2 / 1 / 0.5
Training with Adam, float32: weights 4 + gradients 4 + Adam's \(m\) 4 + \(s\) 416
Training with Adam, mixed precision: float16 weights 2 + gradients 2 + float32 master copy 4 + \(m\) 4 + \(s\) 416
Plus activations: every layer's outputs, kept for backprop (chapter 4), growing with batch size × sequence lengthoften as much again, or more

How many GB does a 7-billion-parameter model need just for its weights in float16?

\(7 \times 10^9 \times 2\) bytes = 14 GB. Training it with Adam needs about \(7 \times 10^9 \times 16\) = 112 GB before activations: more than one 80 GB GPU.

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:

float32float16bfloat16
Largest number3.4 × 10³⁸65,5043.4 × 10³⁸
Significant digitsabout 7about 3about 2
Troublenone, but slowoverflows to inf, small gradients round to 0coarse: 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?

float16 spends more bits on precision and fewer on range; bfloat16 the reverse. For training, range matters more: activations and logits easily pass 65,504.

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

SplitHowWhen
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 stepThe 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 timeThe 16 bytes per parameter don't fit on one GPU
Tensor parallelEach big matrix is split by columns or rows across GPUsSingle layers too big, or latency matters
Pipeline parallelLayers 1–10 on GPU 1, 11–20 on GPU 2…, with micro-batches flowing throughVery deep models across machines

Data parallel on 8 GPUs, each with a batch of 32. What batch size does the optimizer effectively see?

The all-reduce averages 8 gradients of 32 examples each: one step on 256 examples. So the learning rate and warmup tuned for 32 need re-tuning (the optimizers lesson).

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"

7. What to carry forward

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