Simple Algorithm
Deep Learning · Representation · 24 min

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 102410^{24} 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 101510^{15} 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:

LevelCapacity (order of magnitude)Bandwidth (order of magnitude)
On-chip SRAM: registers, shared memory, cacheshundreds of KB per multiprocessor, tens of MB per chipover 10 TB/s in aggregate
HBM beside the chiptens to about a hundred GBa few TB/s
GPU to GPU within a servern/ahundreds of GB/s per GPU
Between serversn/atens of GB/s per GPU
Mid-2020s data-center accelerators, to an order of magnitude. Each step down the hierarchy is roughly ten times slower, which is why the layout of computation, not the FLOP count alone, decides speed.

The deciding quantity is arithmetic intensity: FLOPs performed per byte moved to and from HBM. A chip with peak Π\Pi FLOP/s and bandwidth β\beta bytes/s can sustain its peak only on operations with intensity above Π/β\Pi/\beta, a few hundred FLOPs per byte for numbers like 101510^{15} and 3×10123\times10^{12}.

  • A product of two n×nn\times n matrices in 16-bit does 2n32n^3 FLOPs on 3⋅2n23\cdot2n^2 bytes (two inputs, one output): intensity n/3n/3, 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.

Check your understanding

Which of these operations is most likely limited by memory bandwidth rather than arithmetic on a modern GPU?

  1. Multiplying two 8192×81928192\times8192 matrices
  2. A batch of 64 independent 4096×40964096\times4096 matrix products
  3. Layer normalization of a 4096×81924096\times8192 activation tensor
  4. A large convolution with many input and output channels
Show the answer

C. Layer normalization of a 4096×81924096\times8192 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:

FormatExponent / mantissa bitsLargest valueSmallest positive (normal)Spacing just above 1
FP328 / 233.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}2−23≈1.2×10−72^{-23}\approx1.2\times10^{-7}
FP165 / 1065,50465{,}5046.1×10−56.1\times10^{-5} (subnormals to 6.0×10−86.0\times10^{-8})2−10≈9.8×10−42^{-10}\approx9.8\times10^{-4}
BF168 / 73.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}2−7≈7.8×10−32^{-7}\approx7.8\times10^{-3}
BF16 is FP32 with the mantissa cut to 7 bits: the same dynamic range, much coarser precision. FP16 keeps three more mantissa bits but covers a far narrower range.

Mixed-precision training (Micikevicius et al., 2018) runs the forward and backward passes in 16 bits and protects accuracy three ways:

  1. 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 2−102^{-10}, so 1+10−41+10^{-4} rounds back to 11. 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.
  2. Loss scaling. Many gradients are smaller than FP16's smallest number and would flush to zero. Multiplying the loss by S=2kS=2^k scales every gradient by SS through the chain rule; dividing by SS in FP32 before the update undoes it exactly. Dynamic loss scaling starts with a large SS, skips the step and halves SS whenever an inf or NaN appears, and grows SS again after a run of clean steps.
  3. 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).

python
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 steps

Mixed 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

DerivationModel states: 16 bytes per parameter
  1. 2Ψ⏟weights+2Ψ⏟gradients\underbrace{2\Psi}_{\text{weights}}+\underbrace{2\Psi}_{\text{gradients}}

    Mixed-precision Adam with Ψ\Psi parameters keeps 16-bit weights for the passes and 16-bit gradients:

  2. 4Ψ⏟master weights+4Ψ⏟momentum+4Ψ⏟variance=12Ψ⟹(2+2+12)Ψ=16Ψ bytes\underbrace{4\Psi}_{\text{master weights}}+\underbrace{4\Psi}_{\text{momentum}}+\underbrace{4\Psi}_{\text{variance}}=12\Psi\quad\Longrightarrow\quad(2+2+12)\Psi=16\Psi\ \text{bytes}

    plus the optimizer state in FP32: the master copy of the weights and Adam's first and second moments, K=12K=12 bytes per parameter in the notation of Rajbhandari et al. (2020):

  3. 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, sbh (34+5as/h)sbh\,(34+5as/h) bytes in 16-bit with dropout masks, for sequence length ss, micro-batch bb, width hh and aa heads (Korthikanti et al., 2023). The 34sbh34sbh comes from the attention, MLP and normalization inputs; the 5as2b5as^2b from the attention scores, softmax and dropout, quadratic in ss. Activations grow with batch and context, not with the parameter count, and are cut by recomputation: gradient checkpointing keeps only each layer's input (2sbh2sbh bytes) and redoes the forward pass, while selective recomputation redoes only the attention-score operations behind the 5as2b5as^2b term, which are cheap in FLOPs but expensive in memory: for GPT-3 it cost 2.7% extra FLOPs.

Predict before you look

A GPT-3-sized layer has h=12,288h=12{,}288 and a=96a=96 heads. How many gigabytes of activations does it store for one sequence of s=2,048s=2{,}048 tokens (b=1b=1), using sbh (34+5as/h)sbh\,(34+5as/h) bytes?

Show the answer

2.87 GB

5as/h=5×96×2048/12288=805as/h=5\times96\times2048/12288=80, so 2048×12,288×(34+80)≈2.87×1092048\times12{,}288\times(34+80)\approx2.87\times10^9 bytes. Over 96 layers that is about 275 GB for a single sequence. Full recomputation would keep 2sbh≈502sbh\approx50 MB per layer, about 4.8 GB in all, at the price of an extra forward pass.

Splitting the work

StrategyWhat is splitWhat is communicatedWhere it fits
Data parallelismthe batch; each GPU has a full replicagradients, by an all-reduce each step; with a ring, each GPU sends about 2(p−1)/p2(p-1)/p times the gradient sizeanywhere; overlapped with the backward pass
Sharded data parallelism (ZeRO, FSDP)optimizer state, then gradients, then parameters, across the data-parallel GPUsreduce-scatter of gradients and all-gather of each layer's weights; stage 3 moves about 1.5 times the data of plain data parallelismthe default way to fit large models (Rajbhandari et al., 2020; Zhao et al., 2023)
Tensor parallelismeach weight matrixactivations, all-reduced twice per layer in each directionwithin a server, over fast links
Pipeline parallelismconsecutive layers into stagesactivations between neighboring stagesacross servers; costs a bubble
Sequence or context parallelismthe token dimensionkeys and values passed around a ring, or gatheredlong contexts
Expert parallelismthe experts of a mixture-of-experts layertokens, by all-to-all, to and from their expertssparse models
Large runs compose them: tensor parallelism inside a server, pipeline stages across servers, data parallelism over replicas of the whole arrangement, sharding throughout. Narayanan et al. (2021) ran training iterations of a trillion-parameter GPT model on 3,072 GPUs this way at 52% of the GPUs' peak throughput.
DerivationWhy one all-reduce suffices for a tensor-parallel MLP
  1. GeLU⁡(XA)=[GeLU⁡(XA1)  GeLU⁡(XA2)]\operatorname{GeLU}(XA)=\big[\operatorname{GeLU}(XA_1)\ \ \operatorname{GeLU}(XA_2)\big]

    The MLP computes Z=GeLU⁡(XA) BZ=\operatorname{GeLU}(XA)\,B. Split the first matrix by columns across two GPUs, A=[A1 A2]A=[A_1\ A_2]. Each GPU computes its half of the hidden layer, and since GeLU acts elementwise, no communication is needed:

  2. Z=GeLU⁡(XA1) B1+GeLU⁡(XA2) B2Z=\operatorname{GeLU}(XA_1)\,B_1+\operatorname{GeLU}(XA_2)\,B_2

    Split the second matrix by rows, B=[B1B2]B=\begin{bmatrix}B_1\\B_2\end{bmatrix}, so each GPU multiplies its own half of the hidden layer and gets a partial sum of the output:

  3. One all-reduce adds the partial sums. Splitting AA by rows instead would need a sum before the GeLU, since GeLU⁡(u+v)≠GeLU⁡(u)+GeLU⁡(v)\operatorname{GeLU}(u+v)\neq\operatorname{GeLU}(u)+\operatorname{GeLU}(v): 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 (6N6N 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 101510^{15} 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 16Ψ16\Psi bytes of model states; activations add sbh(34+5as/h)sbh(34+5as/h) 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 (p−1)/(m+p−1)(p-1)/(m+p-1) 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.

Question 1

Adding two FP16 vectors of length nn elementwise does nn FLOPs. What is its arithmetic intensity, counting reads of both inputs and the write of the output?

  1. About n/3n/3 FLOPs per byte
  2. 1 FLOP per byte
  3. 1/61/6 FLOP per byte
  4. 2 FLOPs per byte
Show the answer

C. 1/61/6 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.

Question 2

Why does mixed-precision training keep an FP32 copy of the weights?

  1. Because 16-bit numbers cannot represent negative weights
  2. Because small updates added to a 16-bit weight round away: near 1, FP16's spacing is 2−102^{-10}, so an update of 10−410^{-4} disappears
  3. Because the forward pass must run in FP32 for accuracy
  4. 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 2−102^{-10}, so an update of 10−410^{-4} 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.

Question 3

Why is loss scaling usually unnecessary with BF16 but often needed with FP16?

  1. BF16 has more mantissa bits
  2. BF16 rounds stochastically
  3. BF16 has FP32's 8 exponent bits, so small gradients stay above its smallest number
  4. 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 6.1×10−56.1\times10^{-5} (subnormals at 6.0×10−86.0\times10^{-8}), and many gradients are smaller. BF16 reaches down to about 10−3810^{-38}, so they survive, though with only 7 mantissa bits.

Question 4

Where do the 16 bytes per parameter of mixed-precision Adam go?

  1. 16-bit weights (2), 16-bit gradients (2), and FP32 master weights, momentum and variance (4 each)
  2. FP32 weights (4), FP32 gradients (4) and activations (8)
  3. 16-bit weights (2), FP32 gradients (4), momentum (4), variance (4), and 2 for the loss scale
  4. 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)

2+2+4+4+4=162+2+4+4+4=16. The FP32 optimizer state alone is 12 of the 16, which is why ZeRO's first stage, sharding it, gives the largest saving.

Question 5

In Megatron-style tensor parallelism, why is the MLP's first matrix split by columns and the second by rows?

  1. To balance memory between the GPUs
  2. So each GPU applies GeLU to its own slice of the hidden layer, and a single all-reduce sums the partial outputs
  3. Because GPUs multiply column-major matrices faster
  4. 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 XAXA are complete hidden units, and GeLU acts elementwise, so no sum is needed before it. Row slices of BB consume those units directly and produce partial outputs, summed once.

Go deeper

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