Hardware, Precision & Parallelism
GPUs, mixed precision and splitting one model across thousands of chips.
A 70-billion-parameter model needs more than a terabyte of memory for its weights, gradients and optimizer state, and a training run of around floating-point operations. No single chip holds the first or finishes the second in less than decades. Training at scale is the craft of feeding fast arithmetic units from slow memory, doing the arithmetic in 16 bits without losing accuracy, and splitting one model and one batch across thousands of accelerators without letting communication eat the gains.
What you’ll learn
- Explain the GPU memory hierarchy, and use arithmetic intensity to decide whether an operation is limited by compute or by memory bandwidth.
- Describe mixed-precision training with FP16 or BF16 (FP32 master weights, loss scaling, FP32 accumulation) and why each piece is needed.
- Derive the 16 bytes per parameter of mixed-precision Adam, and estimate the activation memory of a transformer layer.
- Compare data, sharded, tensor, pipeline, sequence and expert parallelism by what they split and what they communicate, and define model FLOPs utilization.
Feeding the arithmetic
A matrix product is a huge number of independent dot products, exactly what a GPU is built for. A data-center GPU has on the order of a hundred streaming multiprocessors, each with tensor cores that multiply small tiles of 16-bit (or 8-bit) numbers and accumulate the results in FP32 in a single instruction. As of the mid-2020s that gives around 16-bit FLOP/s per chip; ordinary FP32 arithmetic runs more than ten times slower. The arithmetic is rarely the hard part. Moving the data to it is:
| Level | Capacity (order of magnitude) | Bandwidth (order of magnitude) |
|---|---|---|
| On-chip SRAM: registers, shared memory, caches | hundreds of KB per multiprocessor, tens of MB per chip | over 10 TB/s in aggregate |
| HBM beside the chip | tens to about a hundred GB | a few TB/s |
| GPU to GPU within a server | n/a | hundreds of GB/s per GPU |
| Between servers | n/a | tens of GB/s per GPU |
The deciding quantity is arithmetic intensity: FLOPs performed per byte moved to and from HBM. A chip with peak FLOP/s and bandwidth bytes/s can sustain its peak only on operations with intensity above , a few hundred FLOPs per byte for numbers like and .
- A product of two matrices in 16-bit does FLOPs on bytes (two inputs, one output): intensity , so large matrix products are compute-bound.
- An elementwise operation such as adding a bias or applying GELU does one or a handful of FLOPs per element while reading and writing it: an intensity of order 1 or below, so it is memory-bound. So are normalization, softmax and, in batch-1 text generation, the matrix–vector products of every layer.
Fusing elementwise operations into the matrix product that precedes them keeps the data on chip; FlashAttention applies the same idea to attention. The Roofline Model & Compute Efficiency makes this quantitative.
Which of these operations is most likely limited by memory bandwidth rather than arithmetic on a modern GPU?
- Multiplying two matrices
- A batch of 64 independent matrix products
- Layer normalization of a activation tensor
- A large convolution with many input and output channels
Show the answer
C. Layer normalization of a activation tensor
Layer normalization reads each activation, computes a few FLOPs per element (mean, variance, scale, shift) and writes it back: an intensity of order one FLOP per byte, far below the hundreds a GPU needs to be compute-bound. The others reuse each loaded number many times.
Mixed precision
A floating-point number stores a sign, an exponent that sets its scale and a mantissa that sets its precision. Halving the bits halves memory and traffic and unlocks the tensor cores, but the two 16-bit formats spend their bits differently:
| Format | Exponent / mantissa bits | Largest value | Smallest positive (normal) | Spacing just above 1 |
|---|---|---|---|---|
| FP32 | 8 / 23 | |||
| FP16 | 5 / 10 | (subnormals to ) | ||
| BF16 | 8 / 7 |
Mixed-precision training (Micikevicius et al., 2018) runs the forward and backward passes in 16 bits and protects accuracy three ways:
- FP32 master weights. An update smaller than half the spacing of the weight's 16-bit neighbors is rounded away: near 1, FP16's spacing is , so rounds back to . The optimizer therefore updates an FP32 copy and casts it to 16 bits for each pass; in their speech model, updating FP16 weights directly cost 80% relative accuracy.
- Loss scaling. Many gradients are smaller than FP16's smallest number and would flush to zero. Multiplying the loss by scales every gradient by through the chain rule; dividing by in FP32 before the update undoes it exactly. Dynamic loss scaling starts with a large , skips the step and halves whenever an inf or NaN appears, and grows again after a run of clean steps.
- FP32 accumulation. Tensor cores add up FP16 products in FP32, and reductions such as sums, softmax and normalization statistics run in FP32.
BF16 has FP32's range, so gradients rarely underflow and loss scaling is usually unnecessary; its coarse mantissa still calls for FP32 master weights and accumulation. As of the mid-2020s BF16 is the common choice for training large models, and 8-bit formats are used for parts of the computation (Number Formats & Mixed Precision).
scaler = torch.amp.GradScaler("cuda") # dynamic loss scaling, for FP16
for x, y in loader:
optimizer.zero_grad(set_to_none=True)
with torch.autocast(device_type="cuda", dtype=torch.float16):
loss = F.cross_entropy(model(x), y) # matmuls in FP16; softmax, norms, loss in FP32
scaler.scale(loss).backward() # backpropagate S * loss
scaler.unscale_(optimizer) # divide the gradients by S before clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(optimizer) # skipped if any gradient is inf or NaN
scaler.update() # halve S after an overflow, grow it after clean stepsMixed precision in PyTorch. The model's parameters stay in FP32 (the master weights); autocast casts them to FP16 for each matrix product. With dtype=torch.bfloat16 the scaler can usually be dropped. Older PyTorch versions spell the scaler torch.cuda.amp.GradScaler().
Where the memory goes
Mixed-precision Adam with parameters keeps 16-bit weights for the passes and 16-bit gradients:
plus the optimizer state in FP32: the master copy of the weights and Adam's first and second moments, bytes per parameter in the notation of Rajbhandari et al. (2020):
GPT-2's 1.5 billion parameters need 24 GB of model states, against 3 GB for its 16-bit weights alone; a 70-billion-parameter model needs about 1.1 TB, before a single activation is stored.
Activations are the other half. The backward pass needs the inputs of every matrix product and nonlinearity, so a transformer stores, per layer, bytes in 16-bit with dropout masks, for sequence length , micro-batch , width and heads (Korthikanti et al., 2023). The comes from the attention, MLP and normalization inputs; the from the attention scores, softmax and dropout, quadratic in . Activations grow with batch and context, not with the parameter count, and are cut by recomputation: gradient checkpointing keeps only each layer's input ( bytes) and redoes the forward pass, while selective recomputation redoes only the attention-score operations behind the term, which are cheap in FLOPs but expensive in memory: for GPT-3 it cost 2.7% extra FLOPs.
A GPT-3-sized layer has and heads. How many gigabytes of activations does it store for one sequence of tokens (), using bytes?
Show the answer
2.87 GB
, so bytes. Over 96 layers that is about 275 GB for a single sequence. Full recomputation would keep MB per layer, about 4.8 GB in all, at the price of an extra forward pass.
Splitting the work
| Strategy | What is split | What is communicated | Where it fits |
|---|---|---|---|
| Data parallelism | the batch; each GPU has a full replica | gradients, by an all-reduce each step; with a ring, each GPU sends about times the gradient size | anywhere; overlapped with the backward pass |
| Sharded data parallelism (ZeRO, FSDP) | optimizer state, then gradients, then parameters, across the data-parallel GPUs | reduce-scatter of gradients and all-gather of each layer's weights; stage 3 moves about 1.5 times the data of plain data parallelism | the default way to fit large models (Rajbhandari et al., 2020; Zhao et al., 2023) |
| Tensor parallelism | each weight matrix | activations, all-reduced twice per layer in each direction | within a server, over fast links |
| Pipeline parallelism | consecutive layers into stages | activations between neighboring stages | across servers; costs a bubble |
| Sequence or context parallelism | the token dimension | keys and values passed around a ring, or gathered | long contexts |
| Expert parallelism | the experts of a mixture-of-experts layer | tokens, by all-to-all, to and from their experts | sparse models |
The MLP computes . Split the first matrix by columns across two GPUs, . Each GPU computes its half of the hidden layer, and since GeLU acts elementwise, no communication is needed:
Split the second matrix by rows, , so each GPU multiplies its own half of the hidden layer and gets a partial sum of the output:
One all-reduce adds the partial sums. Splitting by rows instead would need a sum before the GeLU, since : an extra synchronization. Attention splits the same way, by heads. The backward pass needs one all-reduce at the block's input, so each MLP and attention block costs one all-reduce forward and one backward (Shoeybi et al., 2019).
Measuring efficiency. Model FLOPs utilization (MFU) is the throughput actually achieved, counted with the model's FLOPs ( per token plus attention), divided by the hardware's peak. Recomputed activations do not count, so MFU cannot be inflated by redoing work; hardware FLOPs utilization counts them. PaLM, trained on 6,144 TPU v4 chips, reported 46.2% MFU and 57.8% hardware FLOPs utilization, against 21–33% for several earlier large models (Chowdhery et al., 2022).
Key takeaways
- GPUs offer around 16-bit FLOP/s but only a few TB/s from HBM: an operation is compute-bound only if its arithmetic intensity exceeds a few hundred FLOPs per byte. Large matrix products qualify; elementwise operations, normalization and batch-1 decoding do not.
- Mixed precision computes in 16 bits with FP32 master weights, FP32 accumulation and, for FP16, loss scaling against underflow; BF16 keeps FP32's range and usually needs no scaling.
- Mixed-precision Adam needs bytes of model states; activations add bytes per layer and are cut by full or selective recomputation.
- Data parallelism all-reduces gradients, ZeRO/FSDP shard the model states, tensor parallelism splits matrices (column then row, one all-reduce per block), pipelines split layers at the cost of a bubble; MFU measures how much of the peak the model's own FLOPs achieve.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Adding two FP16 vectors of length elementwise does FLOPs. What is its arithmetic intensity, counting reads of both inputs and the write of the output?
- About FLOPs per byte
- 1 FLOP per byte
- FLOP per byte
- 2 FLOPs per byte
Show the answer
C. FLOP per byte
Each element moves 6 bytes (2 + 2 read, 2 written) for 1 FLOP. At a few hundred FLOPs per byte needed to keep the arithmetic busy, such operations run at memory speed, which is why they are fused into neighboring kernels.
Why does mixed-precision training keep an FP32 copy of the weights?
- Because 16-bit numbers cannot represent negative weights
- Because small updates added to a 16-bit weight round away: near 1, FP16's spacing is , so an update of disappears
- Because the forward pass must run in FP32 for accuracy
- Because GPUs store weights in FP32 by default
Show the answer
B. Because small updates added to a 16-bit weight round away: near 1, FP16's spacing is , so an update of disappears
An update smaller than half the gap to the next representable number is lost. Accumulating updates in FP32 and casting to 16 bits for each pass keeps them.
Why is loss scaling usually unnecessary with BF16 but often needed with FP16?
- BF16 has more mantissa bits
- BF16 rounds stochastically
- BF16 has FP32's 8 exponent bits, so small gradients stay above its smallest number
- BF16 gradients are computed in FP32
Show the answer
C. BF16 has FP32's 8 exponent bits, so small gradients stay above its smallest number
FP16's 5 exponent bits put its smallest normal number at (subnormals at ), and many gradients are smaller. BF16 reaches down to about , so they survive, though with only 7 mantissa bits.
Where do the 16 bytes per parameter of mixed-precision Adam go?
- 16-bit weights (2), 16-bit gradients (2), and FP32 master weights, momentum and variance (4 each)
- FP32 weights (4), FP32 gradients (4) and activations (8)
- 16-bit weights (2), FP32 gradients (4), momentum (4), variance (4), and 2 for the loss scale
- Four FP32 copies of the weights, one per pipeline stage
Show the answer
A. 16-bit weights (2), 16-bit gradients (2), and FP32 master weights, momentum and variance (4 each)
. The FP32 optimizer state alone is 12 of the 16, which is why ZeRO's first stage, sharding it, gives the largest saving.
In Megatron-style tensor parallelism, why is the MLP's first matrix split by columns and the second by rows?
- To balance memory between the GPUs
- So each GPU applies GeLU to its own slice of the hidden layer, and a single all-reduce sums the partial outputs
- Because GPUs multiply column-major matrices faster
- So that no communication is needed at all
Show the answer
B. So each GPU applies GeLU to its own slice of the hidden layer, and a single all-reduce sums the partial outputs
Column slices of are complete hidden units, and GeLU acts elementwise, so no sum is needed before it. Row slices of consume those units directly and produce partial outputs, summed once.
Go deeper
- Number Formats & Mixed Precision · From FP32 to 8- and 4-bit formats: range, precision, scaling and rounding.
- Data, Tensor & Pipeline Parallelism · Sharded optimizer states, tensor-parallel layers and pipeline bubbles.
- The Roofline Model & Compute Efficiency · Arithmetic intensity, memory bandwidth, kernel fusion and FLOPs utilization.
Further reading
- P. Micikevicius et al., "Mixed precision training," ICLR (2018).
- S. Rajbhandari, J. Rasley, O. Ruwase & Y. He, "ZeRO: Memory optimizations toward training trillion parameter models," SC20 (2020).
- M. Shoeybi et al., "Megatron-LM: Training multi-billion parameter language models using model parallelism," arXiv:1909.08053 (2019).
- D. Narayanan et al., "Efficient large-scale language model training on GPU clusters using Megatron-LM," SC21 (2021).
- V. Korthikanti et al., "Reducing activation recomputation in large transformer models," MLSys (2023).