19.3 Memory, precision, and parallelism
This part of Choosing Training and Adaptation Methods develops the mechanisms below. Work the numerical examples or trace the code before checking the answer.
Concepts from other sections (22)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics
- BF16: a 16-bit float with float32’s sign and exponent and 7 mantissa bits; the top half of a rounded float32. Read more: 6.7 Safetensors for every dtype, atomic checkpoints, and the token stream
- master weights: the float32 copy of the parameters and optimizer state that receives every update. Read more: 17.1 Mixed precision, loss scaling, gradient accumulation, and activation checkpointing
- First moment (,
exp_avg): the EMA of the gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics - Second moment (,
exp_avg_sq): the EMA of the elementwise squared gradient. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay in Mathematics - LoRA: fine-tuning a frozen matrix through a trainable low-rank update initialized to zero. Read more: 19.7 The training step and validation
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- Entropy: , the average surprise of a distribution. Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- Cross-entropy: , the average surprise when data from are predicted with . Read more: 17.1 Entropy, cross-entropy, KL, JS, and the k3 estimator in Mathematics
- ZeRO / FSDP: sharding optimizer states, gradients, and (at stage 3) parameters across data-parallel ranks instead of replicating them. Read more: 19.7 The training step and validation
- data parallelism (DDP): each rank holds a full model replica, computes the gradient of its batch slice, and all ranks average gradients before stepping. Read more: 17.3 Data parallelism and ZeRO stages 1 to 3
- all-reduce: every rank ends with the elementwise reduction (sum or mean) of all ranks’ arrays. Read more: 17.2 Collectives over processes: ring all-reduce
- reduce-scatter: every rank ends with one chunk of the reduction. Read more: 17.2 Collectives over processes: ring all-reduce
- all-gather: every rank ends with the concatenation of all ranks’ chunks, in rank order. Read more: 17.2 Collectives over processes: ring all-reduce
- LayerNorm: per-row normalization by the population mean and variance with inside the square root, then an affine map. Read more: 6.5 Module system and basic layers
- Dropout: randomly zeroing activations during training to approximate an ensemble of subnetworks. Read more: Chapter 2: Deep Learning
- Mixture of experts (MoE): a layer of many expert MLPs of which a router picks per token. Read more: 13.8 Mixture of Experts
- Pipeline bubble: time a stage cannot perform useful work because the schedule has not filled or drained. Read more: 17.4 Parallelism, topology, and the global training batch
- Transformation (JAX): a function such as
jit,grad,vmap, orpmapthat takes a pure function and returns a compiled, differentiated, batched, or parallel version of it. Read more: 16.3 Embeddings, small models, and platforms - GRPO: a PPO-style RL method that replaces the critic with the group-normalized reward of several samples of the same prompt. Read more: 19.7 The training step and validation
- E4M3: an fp8 format with 4 exponent and 3 mantissa bits, largest finite value 448. Read more: 21.5 Quantization: int8, int4 groups, fp8, and the KV cache
- E5M2: an 8-bit float with 5 exponent bits (bias 15) and 2 fraction bits, IEEE-style infinities and NaNs, largest finite value 57344. Read more: 15.4 FP8 and microscaling formats in Mathematics
Learning objectives
- Account for model states and select the dimension to shard.
Memory and parallelism
Section titled “Memory and parallelism”Compute tells you how long a run takes; memory tells you how many GPUs it needs before it can start. This section is the arithmetic and the current APIs, drawing on ZeRO, Megatron-LM, Narayanan et al., Korthikanti et al., and the PyTorch FSDP paper.
Sixteen bytes per parameter
Section titled “Sixteen bytes per parameter”A common mixed-precision AdamW accounting model (Micikevicius et al.) keeps the copies below. Actual frameworks can choose different gradient, master-weight, and optimizer-state representations, so inspect the installed implementation:
| Item | Bytes/param |
|---|---|
| BF16 weights (used in forward/backward) | 2 |
| BF16 gradients | 2 (4 if accumulated in FP32) |
| FP32 master weights | 4 |
| Adam first moment (FP32) | 4 |
| Adam second moment (FP32) | 4 |
| Total | 16 (18 with FP32 grads) |
So an 8B model needs about 128 GB of state and a 70B about 1.1 TB, before any activation. That single fact is why full fine-tuning of a 70B is a multi-node job, and why LoRA, later in this chapter, exists.
Activations come on top. A simplified transformer-layer model in BF16 with memory-efficient attention estimates roughly bytes (Korthikanti et al.) for sequence length , micro-batch , and width . For an 8B at and that is about 0.57 GB per layer, or about 18 GB across 32 layers. Activation checkpointing stores only each layer’s input ( bytes) and recomputes the rest during the backward pass, buying an order of magnitude less activation memory for about 33% more compute.
Warning: Do not forget the logits. They take bytes in FP32, which is 2.1 GB per 4K-token sequence at a vocabulary of . Fused or chunked cross entropy (Liger, Cut Cross-Entropy) avoids materializing them at all.
Sharding the states: ZeRO and FSDP2
Section titled “Sharding the states: ZeRO and FSDP2”The first and cheapest way to fit a model is to stop replicating its states on every data-parallel rank. ZeRO does this in three stages, each sharding one more kind of state across the ranks. The table compares them for a model of parameters:
| Stage | Shards across data-parallel ranks | Memory per GPU | Comms vs DDP |
|---|---|---|---|
| DDP | nothing | all-reduce grads () | |
| ZeRO-1 | optimizer states | same | |
| ZeRO-2 | + gradients | same (reduce-scatter instead of all-reduce) | |
| ZeRO-3 / FSDP | + parameters | 1.5x (all-gather params in forward and backward) |
These communication comparisons use an idealized bandwidth-volume model with matched dtypes and a particular gather/reduce schedule. Similar total bytes do not mean communication is free: launches, group size, overlap, offload, and topology affect wall time. ZeRO-3 can have extra parameter gathers, with resharding policy changing the schedule.
One concrete implementation is PyTorch FSDP2, documented in the 2.9 fully_shard reference. It uses per-parameter DTensor sharding rather than FSDP1’s flat-parameter wrapper. Sharding groups and precision policies must be chosen for the model and topology. A common pattern applies sharding block by block, then to the root:
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)for block in model.layers: # shard each block: its all-gather overlaps the previous block's compute fully_shard(block, mp_policy=mp)fully_shard(model, mp_policy=mp) # then the root (embeddings, head)model = torch.compile(model) # Dynamo + Inductor: fused kernels, same eager semanticsSharding per block matters: each block’s all-gather can overlap the previous block’s compute, so the communication hides behind useful work.
Splitting the model itself
Section titled “Splitting the model itself”Sharding states only helps until a single layer’s working set no longer fits, or until the batch stops being large enough to keep data parallelism efficient. Then you split the model. The useful way to think about this is that parallelism is a choice of what to split: the optimizer state (ZeRO/FSDP), each matrix (TP), the layers (PP), the sequence (CP), or the experts (EP). Name the dimension that does not fit, then pick the tool. The Megatron-LM family of axes compares as follows:
| Axis | Splits | Communication | Placement |
|---|---|---|---|
| TP (tensor) | each matmul: column-parallel then row-parallel, so an MLP needs one all-reduce forward and one backward | 2 all-reduces per layer per pass, on the critical path | inside a fast interconnect domain where feasible |
| SP (sequence, with TP) | the LayerNorm/dropout regions along the sequence | turns all-reduce into reduce-scatter + all-gather, same volume, less activation memory | with TP |
| PP (pipeline) | layers into stages; micro-batches fill the pipe (1F1B, interleaved, zero-bubble) | point-to-point activations | across nodes; bubble ≈ |
| CP (context) | the sequence across GPUs for attention (ring attention: pass K/V blocks around a ring) | K/V exchange per layer | long-context (64K-1M) training |
| EP (expert) | MoE experts across GPUs | all-to-all token dispatch and combine | MoE models |
The pipeline bubble formula, with stages and micro-batches, explains why pipelines want many micro-batches. Tensor parallelism benefits from a fast low-latency interconnect because collectives sit on its critical path. The suitable degree depends on the model and topology, not a universal eight-GPU limit.
Combining axes gives 3D parallelism, , and 4D or 5D when CP and EP are added. The canonical layout puts TP inside the node, PP across nodes, and FSDP or DP over everything else. The reference implementations are Megatron-LM / Megatron-Core from NVIDIA; torchtitan, the clean PyTorch-native reference with FSDP2, TP, PP, CP, EP, and Float8/MXFP8; and DeepSpeed, the home of ZeRO and offload.
The same ideas in JAX
Section titled “The same ideas in JAX”JAX expresses all of the above as sharding annotations on arrays, and the XLA partitioner (GSPMD, now Shardy) inserts the collectives for you:
import jaxfrom jax.sharding import NamedSharding, PartitionSpec as P
mesh = jax.make_mesh((8, 4), ("data", "model")) # 32 devices: FSDP/DP × TPw = jax.device_put(w, NamedSharding(mesh, P("data", "model"))) # FSDP on rows, TP on colsx = jax.device_put(x, NamedSharding(mesh, P("data", None))) # batch sharded on "data"step = jax.jit(train_step) # compiler inserts all-gathers / reduce-scatters
# drop to per-device code with explicit collectives when the compiler's choice is wrong@jax.shard_map(mesh=mesh, in_specs=(P("data", "model"), P("data", None)), out_specs=P("data", "model"))def local_matmul(w_blk, x_blk): ...A few API facts are worth knowing. jax.shard_map is now top-level, having graduated from jax.experimental; pjit has been merged into jax.jit, and pmap is legacy. Recent JAX defaults make_mesh to Explicit axis types, where shardings are part of each array’s type; pass axis_types=(AxisType.Auto, ...) to get classic GSPMD propagation, as train_step_jax.py does. MaxText is the reference JAX LLM trainer, on TPU and GPU, covering pretraining, SFT, and GRPO.
Mixed precision: BF16 and FP8
Section titled “Mixed precision: BF16 and FP8”BF16 has FP32’s 8-bit exponent, so loss scaling is usually unnecessary for its exponent range. It is common in training, but precision choices remain model-, operation-, and device-dependent. FP8 goes further (Micikevicius et al. 2022): E4M3 for the forward pass and E5M2 or E4M3 for gradients doubles the H100 matmul peak to about 1979 TFLOP/s. With so few bits it needs scaling factors, either per-tensor delayed or current scaling, or MXFP8 block scaling over 32-element blocks, which is native on Blackwell. DeepSeek-V3 trained in FP8 with fine-grained block scaling.
Two libraries supply FP8 training. In NVIDIA Transformer Engine you use te.Linear and friends under te.autocast(recipe=...); in TE 2.x, fp8_autocast is deprecated in favor of the recipe-agnostic autocast. In torchao, convert_to_float8_training(model) takes a "tensorwise", "rowwise", or "rowwise_with_gw_hp" recipe and composes with FSDP2 (including FP8 all-gather) and torch.compile.
Note what FP8 does not change: master weights and optimizer states stay in FP32. FP8 changes the matmuls, not the 16 bytes.
Summary
Section titled “Summary”Account for model states and select the dimension to shard. State the assumptions before applying the result to a different workload.
Review questions
Section titled “Review questions”-
Why can a model still run out of memory after its state fits?
Answer
Activations, logits, temporary collective buffers, workspaces, and allocator headroom also occupy memory.