Chapter 3 · Training Infrastructure and Stability¶
3.1 How do Adam and AdamW differ? Why are Transformers trained with Adam rather than SGD? ★★¶
One-sentence answer
Adam maintains the first and second moments of the gradient for every parameter and uses the second moment to scale each parameter's step size individually, which makes it insensitive to gradient scale; AdamW decouples weight decay from the gradient and applies it directly to the parameters, so every parameter decays by the same proportion. Transformers use Adam because their parameter blocks differ enormously in gradient scale and curvature, which SGD, with a single global learning rate, cannot accommodate.
I will address three aspects: what Adam does, what AdamW changes, and why Transformers need an adaptive optimizer.
(1) Adam uses the second moment of the gradient to scale each parameter's step size individually.
Adam (Kingma & Ba 2014) maintains two exponential moving averages per parameter. The first moment \(m\) is the moving average of the gradient; it acts as momentum and determines the direction of the update. The second moment \(v\) is the moving average of the squared gradient (computed element-wise) and measures how large this parameter's gradient usually is. The update divides \(m\) by \(\sqrt{v}\): a parameter whose gradients are consistently large has a large \(v\), so its effective step shrinks; a parameter whose gradients are consistently small has a small \(v\), so its effective step grows. Consequently, whether the raw gradient is large or small, each update has a magnitude on the order of the learning rate \(\eta\), as if every parameter had "its own learning rate". This makes Adam insensitive to gradient scale and much easier to tune than SGD. Its cost is memory: each parameter stores two extra fp32 states, 8 bytes in total (see 3.2).
(2) AdamW takes weight decay out of the gradient and applies it directly to the parameters.
Weight decay means pulling every parameter slightly back toward 0 at each step to keep parameters from growing too large. In SGD it is exactly equivalent to L2 regularization: adding \(\frac{\lambda}{2}\|\theta\|^2\) to the loss adds a term \(\lambda\theta\) to the gradient. In Adam, however, the two are no longer equivalent: if implemented as L2 regularization, the term \(\lambda\theta\) enters the gradient, flows into \(m\) and \(v\), and is finally divided by \(\sqrt{v}\). As a result, parameters with large past gradients receive weakened decay, while parameters with small past gradients receive amplified decay, so the regularization strength becomes entangled with gradient statistics. AdamW (Loshchilov & Hutter 2017) lets the decay term bypass the \(\sqrt{v}\) normalization and subtracts \(\eta\lambda\theta\) directly from the parameters, so every parameter shrinks by the same proportion \(\eta\lambda\) at every step. The decay is therefore uniform and predictable, and the learning rate and \(\lambda\) become easier to tune separately. For this reason, LLM training today almost universally uses AdamW.
(3) Transformers need Adam fundamentally because their parameters are highly heterogeneous.
- Curvature differs greatly across parameter blocks: Analyzing the Hessian, Zhang et al. (2024) found that different parameter blocks in a Transformer (such as the attention projections, the FFN, the embedding and the normalization layers) have very different Hessian spectra, which they call block heterogeneity, whereas CNNs do not show this. SGD has a single global learning rate: set it high and the steep blocks oscillate or even diverge; set it low and the flat blocks barely move. Adam's per-parameter step size compensates for exactly this.
- Word frequencies in language data are heavy-tailed: Many tokens appear rarely, so their embedding rows and output-layer parameters receive gradients only occasionally, and those gradients are small. Kunstner et al. (2024) found that under gradient descent the loss on infrequent words decreases much more slowly than on frequent ones; since infrequent words together make up most of the samples, the overall loss also decreases slowly. Adam's normalization lets these low-frequency parameters update with normal step sizes as well.
In summary: the essence of Adam is a per-parameter adaptive step size, and AdamW additionally removes the coupling between weight decay and that adaptive step size; the high heterogeneity of Transformer parameters makes such adaptivity nearly indispensable.
Going deeper: the update rules and common hyperparameters in LLMs
(1) The Adam and AdamW update rules differ only in where weight decay enters.
Let \(g_t\) be the gradient at step \(t\). The two moments are updated as
where \(\beta_1,\beta_2\) are the decay rates of the two moving averages. Since \(m\) and \(v\) both start at 0, the first few steps are pulled strongly toward 0, so a bias correction is applied:
On top of this, the two ways of implementing weight decay are
where \(\theta_t\) is the parameter, \(\eta\) the learning rate, \(\lambda\) the weight decay coefficient, and \(\epsilon\) a small constant that prevents division by zero. Note that in Adam + L2 the term \(\lambda\theta_t\) passes through the \(\sqrt{\hat v_t}\) normalization, whereas in AdamW it does not.
(2) Common values in LLM pretraining differ from the PyTorch defaults, especially \(\beta_2\).
| Hyperparameter | Common value | Notes |
|---|---|---|
| \(\beta_1\) | 0.9 | The first moment averages roughly the last \(1/(1-\beta_1)=10\) steps |
| \(\beta_2\) | 0.95 (default 0.999) | The second moment averages roughly the last 20 steps and tracks changes in gradient scale faster |
| \(\epsilon\) | On the order of \(10^{-8}\) (some models use \(10^{-5}\)) | When gradients are tiny it dominates the denominator and suppresses the update |
| \(\lambda\) | 0.1 | AdamW weight decay coefficient |
| Gradient clipping threshold | 1.0 | Upper bound on the global gradient L2 norm (see 3.8) |
GPT-3 and the Llama family all use \(\beta_1=0.9\), \(\beta_2=0.95\), \(\lambda=0.1\) and a gradient clipping threshold of 1.0.
(3) Biases and normalization gains usually receive no weight decay.
These parameters are few and do not cause overfitting, and pulling a normalization gain toward 0 only interferes with its job of controlling the scale of values. Some models also exclude the embedding from weight decay (e.g. OLMo 2).
Follow-up questions
Follow-up 1: Why does Adam need bias correction?
Because \(m\) and \(v\) are initialized at 0, their estimates early in training are strongly biased toward 0. For example, with \(\beta_2=0.95\), the first step gives \(v_1=0.05\,g_1^2\), only 5% of the true value. Dividing by \(1-\beta^t\) corrects exactly this bias: at the first step \(1-\beta_2^1=0.05\), so the corrected value is \(\hat v_1=g_1^2\). As training proceeds, \(\beta^t\to 0\) and the correction factor automatically approaches 1.
Follow-up 2: Why do LLMs often set \(\beta_2\) to 0.95 rather than the default 0.999?
So that the second moment keeps up with sudden changes in gradient scale, thereby avoiding abnormally large updates. With \(\beta_2=0.999\), \(v\) averages the squared gradients of roughly the last 1,000 steps. If a parameter's gradient suddenly becomes large (for example, on a batch of unusual data), \(m\) catches up quickly but \(v\) reacts too slowly and stays small, so \(m/\sqrt{v}\) becomes abnormally large and produces an oversized update that can trigger a loss spike. With \(\beta_2=0.95\), \(v\) averages only about 20 steps and adapts to such changes faster, so training is more stable.
Follow-up 3: LLM pretraining sees the data roughly once, so why is weight decay still needed?
Because in this regime the main role of weight decay is not to prevent overfitting but to control the parameter norm. When the data is seen only once, the model is closer to underfitting than to overfitting. A common view is that weight decay limits the continued growth of the parameter norm, and with a stable parameter norm an update of a given size has a more stable relative effect on the model, which keeps the effective step size more controllable during training.
Follow-up 4: What are Adam's drawbacks, and what alternatives exist?
Its main drawback is the memory taken by the optimizer states. Adam needs 8 bytes of state per parameter, more than the bf16 weight itself. Alternatives fall roughly into two groups. One compresses the states: Adafactor (Shazeer & Stern 2018) factorizes the second-moment matrix into a row vector and a column vector, and 8-bit Adam (Dettmers et al. 2021) quantizes the states to 8 bits. The other changes the form of the update: Muon (Jordan et al. 2024) orthogonalizes the updates of matrix parameters, and Kimi K2 used an improved version called MuonClip (Kimi Team 2025).
Common mistakes
- Do not say "AdamW is just Adam plus L2 regularization": Quite the opposite; the whole point of AdamW is that it differs from L2 regularization, because the decay term does not pass through the \(\sqrt{v}\) normalization.
- Do not say \(v\) is the variance of the gradient: \(v\) is the moving average of the squared gradient, i.e. the uncentered second moment; the mean is not subtracted.
- Do not say Adam needs no learning-rate tuning: Adam reduces sensitivity to gradient scale, but the peak learning rate, warmup and decay schedule remain critical (see Chapter 2).
3.2 Where does the memory go when training a large model, and how do you estimate it? ★★★¶
One-sentence answer
Training memory consists mainly of two parts: model states, i.e. weights, gradients and optimizer states, which take about 16 bytes per parameter under Adam with mixed precision and depend only on the parameter count; and activations, i.e. the intermediate results saved during the forward pass for the backward pass, which are proportional to the micro-batch size, sequence length, hidden size and number of layers. To estimate it, multiply 16 bytes by the parameter count, then add the activations and a small overhead.
I will address three aspects: model states, activations, and how to estimate and reduce memory on that basis.
(1) Model states take about 16 bytes per parameter, three-quarters of which relate to the optimizer.
Under the standard setup of Adam with mixed precision (see 3.3), each parameter requires the following copies:
- bf16 weight, 2 bytes: the copy of the weights used in the forward and backward passes.
- bf16 gradient, 2 bytes: the gradient produced by the backward pass.
- fp32 master weight, 4 bytes: used to accumulate each step's tiny update in high precision; see 3.3 for why.
- Adam's first and second moments, 4 bytes each, 8 bytes in total: stored in fp32; see 3.1.
That totals 16 bytes. Consequently, a 7B model needs about 112 GB for model states alone, more than the capacity of a single 80 GB GPU. Model states depend only on the parameter count, not on batch size or sequence length; the fp32 master weights and Adam states together take 12 of the 16 bytes, which is exactly what ZeRO shards first (see 3.4).
(2) Activations are the intermediate results saved during the forward pass for the backward pass, and they grow with batch size and sequence length.
When the backward pass computes a layer's gradients, it needs the inputs that layer received in the forward pass: for example, the weight gradient of a matrix multiplication needs its input, and the gradients of activation functions and normalization layers need their respective inputs. Therefore, these intermediate results of every layer must be kept from the forward pass until the backward pass has used them. Activation memory is proportional to the micro-batch size \(b\), the sequence length \(s\), the hidden size \(h\) and the number of layers \(L\); without FlashAttention, each attention head also stores an \(s\times s\) attention matrix, which grows quadratically with sequence length. So when sequences are long or micro-batches are large, activations easily exceed the model states and become the largest item in memory. In addition, communication buffers, temporary tensors and memory fragmentation take up some space, so the usable memory is always somewhat less than the calculation suggests.
(3) To estimate, compute the model states first, then estimate the activations, and then choose a method that targets whichever part is larger.
The estimate can be written as: total memory ≈ \(16N\) bytes + activations + overhead, where \(N\) is the parameter count; the formula for activations is given in "Going deeper" below. The two parts are reduced by different methods:
- Model states too large: shard them across GPUs with ZeRO/FSDP (see 3.4), or split the model itself with tensor or pipeline parallelism (see 3.5).
- Activations too large: trade compute for memory with activation checkpointing (see 3.7); use FlashAttention to avoid storing the \(s\times s\) attention matrix; or reduce the micro-batch and keep the global batch unchanged with gradient accumulation (computing the gradients of several micro-batches in a row, summing them, and then making one parameter update).
In summary: training memory can be remembered as "16 bytes times the parameter count, plus activations"; the former is mainly solved by sharding, the latter mainly by recomputation and parallelism.
Going deeper: the 16-byte breakdown, the activation formula and a 7B example
(1) Taking a 7B model as an example, the model states break down as follows.
| Component | Precision | Bytes per parameter | 7B model |
|---|---|---|---|
| Weights | bf16 | 2 | 14 GB |
| Gradients | bf16 | 2 | 14 GB |
| Master weights | fp32 | 4 | 28 GB |
| Adam first moment \(m\) | fp32 | 4 | 28 GB |
| Adam second moment \(v\) | fp32 | 4 | 28 GB |
| Total | 16 | 112 GB |
(2) Per-layer activation memory can be estimated with the formula of Korthikanti et al. (2022).
For a standard GPT architecture (FFN intermediate size \(4h\), with dropout), in 16-bit precision and without any parallelism or recomputation, the activations each Transformer layer must store are approximately
where \(s\) is the sequence length, \(b\) the micro-batch size, \(h\) the hidden size, and \(a\) the number of attention heads. The 34 in the parentheses comes from the inputs of the matrix multiplications, activation functions and normalization layers, plus the dropout masks; the \(5as/h\) term comes from the attention score matrix, the softmax output and its dropout mask, which expands to \(5as^2b\) bytes and grows quadratically with sequence length. With FlashAttention this term is not stored but recomputed in the backward pass. The total activation memory is this times the number of layers \(L\).
(3) A 7B example: without FlashAttention, the attention matrix is the largest part of the activations.
Take the same shape as Llama 2 7B, \(L=32\), \(h=4096\), \(a=32\), and set \(s=4096\), \(b=1\). A rough calculation with the formula above (the real architecture does not exactly match the formula's assumptions, so the numbers indicate orders of magnitude only):
| Item | Calculation | Memory |
|---|---|---|
| Model states | \(16\times 7\text{B}\) | About 112 GB |
| The \(34sbh\) part of activations | \(34\times4096\times4096\times32\) | About 18 GB |
| The attention-matrix part of activations | \(5\times32\times4096^2\times32\) | About 86 GB |
| Activations with full recomputation (only \(2sbh\) per layer) | \(2\times4096\times4096\times32\) | About 1 GB |
Activations are thus of the same order as the model states; and once ZeRO-3 shards the model states across 64 GPUs, leaving only about 1.75 GB per GPU, activations become the main bottleneck.
Follow-up questions
Follow-up 1: Is a single 80 GB GPU enough to fully fine-tune a 7B model? What about LoRA?
Not for full fine-tuning, but usually yes for LoRA. Full fine-tuning needs about 112 GB for model states alone, so they must be sharded across GPUs with ZeRO-3/FSDP, or the optimizer states must be offloaded to CPU memory. LoRA freezes the base weights, which then need neither gradients nor optimizer states and are simply stored in bf16 (about 14 GB); adding the small adapter, its optimizer states and the activations usually fits on one GPU (see Chapter 5).
Follow-up 2: Is the 16-byte figure fixed?
No, it is the most common approximation, and the exact figure depends on the implementation. For example, some implementations store and accumulate gradients in fp32, in which case gradients take 4 bytes and the total is about 18 bytes; with an 8-bit optimizer, Adam's two states can be compressed to about 2 bytes. Notably, pure fp32 training also needs 16 bytes of model states (4 bytes each for the weight, the gradient and the two moments), so mixed precision mainly saves activation memory rather than model-state memory (see 3.3).
Follow-up 3: How does inference memory compare with training memory?
Inference needs only the weights and the KV cache, far less than training. Inference needs no gradients, no optimizer states and no activations saved for a backward pass; bf16 weights take only 2 bytes per parameter, about one-eighth of the training model states. However, generation must cache the key and value of every existing token (the KV cache), which becomes large with long contexts and large batches; see the "Inference, Evaluation and Deployment" direction.
Common mistakes
- Do not count only the weights: 2 bytes per parameter is the inference-time weight memory; training model states are about 8 times that.
- Do not say ZeRO reduces activation memory: ZeRO shards only model states; activations are reduced by recomputation, sequence parallelism or tensor parallelism.
- Do not say activations are proportional to the parameter count: Activations are proportional to \(b\cdot s\cdot h\cdot L\) (plus an \(s^2\) term without FlashAttention), while the parameter count is proportional to \(h^2L\); the same model's activations change several-fold when the sequence length changes.
3.3 How does mixed-precision training work, and how do fp16, bf16 and fp8 differ? ★★¶
One-sentence answer
Mixed-precision training runs the forward and backward passes in 16-bit (or even 8-bit) floating point to save memory and bandwidth and to exploit Tensor Core acceleration, while keeping an fp32 copy of the master weights and performing the parameter update in fp32 so that tiny updates are not rounded away. The three formats differ in how they trade range against precision: fp16 has a narrow range and needs loss scaling; bf16 has the same range as fp32 and is the current default; fp8 is faster but must be paired with fine-grained scaling factors.
I will address three aspects: why low precision is used, why fp32 master weights must still be kept, and how the three formats differ.
(1) Low-precision computation brings benefits in memory, bandwidth and speed.
Replacing 32-bit with 16-bit floats halves the memory of weights and activations, and also halves the volume of memory traffic and cross-GPU communication. More importantly, the Tensor Cores on a GPU, which are dedicated to matrix multiplication, run 16-bit operations far faster than fp32. Since the vast majority of training compute is matrix multiplication, this directly determines training speed.
(2) But the parameter update must happen in fp32, so an fp32 copy of the master weights must be kept.
The problem lies in the parameter update. Each step's update is usually several orders of magnitude smaller than the parameter itself, and 16-bit floats have few mantissa bits, so when a small number is added to a large one, the small one gets rounded away. For example, the smallest gap bf16 can represent near 1.0 is \(2^{-7}\approx 0.0078\), so \(1+0.001\) is still 1 in bf16 and the update is simply lost; when thousands of small updates disappear this way, the model can no longer learn. Therefore, the standard recipe for mixed-precision training (Micikevicius et al. 2017) is: keep an fp32 copy of the weights (master weights) and keep the optimizer states in fp32; at each step, cast the master weights to 16-bit, run the forward and backward passes in 16-bit, and obtain 16-bit gradients; finally, update the master weights with the gradients in fp32. In addition, accumulation inside matrix multiplications is usually done in fp32, and precision-sensitive operations such as softmax, normalization and the loss are often kept in fp32 as well.
(3) fp16, bf16 and fp8 differ in how they allocate exponent and mantissa bits, that is, in how they trade range against precision.
The exponent bits determine the representable range of values, and the mantissa bits determine precision.
- fp16 (5 exponent bits, 10 mantissa bits): Its precision is relatively high but its range is very narrow: the maximum is about 65,504 and the smallest normal number is about \(6\times10^{-5}\). Many gradients in the backward pass are smaller than this lower limit and underflow to 0. fp16 training therefore needs loss scaling: before the backward pass, the loss is multiplied by a large number \(S\) so that all gradients are scaled up proportionally into the representable range, and before the update they are divided by \(S\) to restore them.
- bf16 (8 exponent bits, 7 mantissa bits): It has the same exponent bits as fp32 and hence the same dynamic range, so it almost never overflows or underflows and needs no loss scaling. Its precision is lower, but neural network training is quite tolerant of noise, whereas insufficient range makes training collapse outright, so range matters more than precision. Since hardware such as the A100 and TPUs began supporting it natively, bf16 has become the default format for LLM training.
- fp8 (two variants, E4M3 and E5M2): Starting with the H100, GPUs support fp8 Tensor Cores, with roughly twice the theoretical matrix-multiplication throughput of bf16. But its range is so narrow that real data cannot fit directly, so tensors must be paired with scaling factors that bring them into fp8's range before computing. Consequently, usually only matrix multiplications run in fp8, while master weights, optimizer states and sensitive operations stay in higher precision.
In summary: the core of mixed precision is "compute in low precision, update in high precision"; choosing a format is essentially a trade-off between range and precision, and training is more sensitive to range than to precision.
Going deeper: format comparison, dynamic loss scaling and fine-grained scaling for fp8
(1) Bit allocation and use of the five formats.
| Format | Sign / exponent / mantissa bits | Max value | Gap near 1.0 | Typical use |
|---|---|---|---|---|
| fp32 | 1 / 8 / 23 | About \(3.4\times10^{38}\) | \(2^{-23}\) | Master weights, optimizer states |
| fp16 | 1 / 5 / 10 | 65,504 | \(2^{-10}\) | Earlier mixed-precision training |
| bf16 | 1 / 8 / 7 | About \(3.4\times10^{38}\) | \(2^{-7}\) | Default for LLM training today |
| fp8 E4M3 | 1 / 4 / 3 | 448 | \(2^{-3}\) | Forward weights and activations |
| fp8 E5M2 | 1 / 5 / 2 | 57,344 | \(2^{-2}\) | Backward gradients |
(2) Dynamic loss scaling finds a suitable scale factor automatically.
Here \(L\) is the original loss, \(S\) the scale factor, and \(g\) the gradient restored in fp32 and used for the update. Since this only multiplies and divides by a constant, the direction and relative sizes of the gradients are unchanged. If \(S\) is too small, underflow remains; if it is too large, gradients overflow to inf. In practice it is therefore adjusted dynamically: start with a large \(S\); whenever inf or NaN appears in the gradients, skip that update and halve \(S\); after many consecutive steps without overflow (say 2,000), double \(S\).
(3) The difficulty of fp8 lies in outliers, and the solution is finer-grained scaling.
If a whole tensor shares one scaling factor, a few very large outliers inflate it, and all the normal values get only a handful of quantization levels, causing a severe loss of precision. DeepSeek-V3 (DeepSeek-AI 2024) computes separate scaling factors for \(1\times128\) tiles of activations and \(128\times128\) blocks of weights, so an outlier affects only its own small block; it also periodically promotes the partial sums of matrix multiplications to fp32 for accumulation, reducing accumulation error. In comparisons with a bf16 baseline, the relative loss error of fp8 training stayed consistently below 0.25%. (The newer Blackwell GPUs further support formats with built-in block-level scaling such as MXFP8 and NVFP4, and NVIDIA has reported training a 12B model on 10T tokens in NVFP4 with a loss curve close to the fp8 baseline (NVIDIA 2025).)
Follow-up questions
Follow-up 1: Why does bf16 not need loss scaling while fp16 does?
Because bf16 has the same exponent bits as fp32, its smallest normal number is about \(10^{-38}\), and gradients almost never underflow. fp16 has only 5 exponent bits and a smallest normal number of about \(6\times10^{-5}\), so many tiny gradients simply become 0; loss scaling exists precisely to shift these gradients as a whole into fp16's representable range. bf16 does not have this problem, so loss scaling is unnecessary, and with it go the skipped steps and the trouble of tuning \(S\).
Follow-up 2: Does mixed-precision training halve memory?
No; model-state memory is essentially unchanged, and the savings come mainly from activations. In pure fp32 training, the weight, gradient and Adam's two moments take 4 bytes each, 16 bytes in total; in mixed-precision training, the bf16 weight and gradient take 2 bytes each, plus 12 bytes for the fp32 master weight and two moments, again 16 bytes. What is actually halved is activations and communication volume, while the speedup comes mainly from Tensor Cores.
Follow-up 3: With bf16, can every operation run in bf16?
No; operations involving large sums or sensitive to precision still need fp32. bf16 has only about 2 to 3 significant decimal digits, so rounding error keeps accumulating when many values are added. Therefore, accumulation inside matrix multiplications and gradient reduction across GPUs are usually done in fp32; softmax, normalization and the loss are often kept in fp32; and master weights and optimizer states are always fp32.
Common mistakes
- Do not say bf16 is more precise than fp16: bf16 has fewer mantissa bits and lower precision; its advantage is range.
- Do not say loss scaling changes the direction of the gradient: It only multiplies and divides by a constant, and the scaling is undone before the update.
- Do not say fp8 training stores every tensor in fp8: Usually only matrix multiplications run in fp8, while master weights, optimizer states and sensitive operations stay in higher precision.
3.4 How do data parallelism and ZeRO/FSDP work? ★★¶
One-sentence answer
Data parallelism gives each GPU a full copy of the model to process different data, then averages gradients with an all-reduce so that all replicas stay identical; ZeRO and FSDP go further by sharding the optimizer states, the gradients and even the parameters across GPUs, eliminating the redundant copies so that per-GPU model-state memory falls linearly with the number of GPUs, at the cost of gathering parameters temporarily when they are used and at most 1.5 times the communication.
I will address three aspects: how data parallelism works, the three stages of ZeRO, and how FSDP relates to ZeRO.
(1) Data parallelism averages gradients with an all-reduce, keeping all model replicas identical.
Data parallelism (DP) is the simplest scheme: every GPU holds a full copy of the model and optimizer, and a global batch is split evenly across \(N_d\) GPUs. Each GPU runs the forward and backward passes on its own share and obtains its own gradients; then an all-reduce averages the gradients across all GPUs (an all-reduce is a collective communication operation that sums or averages a tensor across GPUs and gives every GPU the result), so every GPU receives the same averaged gradient and applies the same update, and all replicas therefore stay identical. Mathematically this is exactly equivalent to training with the large batch on a single GPU. When the all-reduce is implemented with the ring algorithm (ring all-reduce), each GPU sends and receives about twice the parameter count, almost independent of the number of GPUs; moreover, gradients can be bucketed and sent during the backward pass, overlapping with compute. Data parallelism therefore scales well. Its fundamental limit, however, is that every GPU must store the full model states at 16 bytes per parameter, and adding more GPUs does not reduce per-GPU memory.
(2) ZeRO has three stages by degree of sharding, progressively eliminating the redundancy of model states.
ZeRO (Rajbhandari et al. 2019) starts from the observation that in data parallelism every GPU stores an identical copy of the model states, an \(N_d\)-fold redundancy, whereas each GPU really only needs to update \(1/N_d\) of the parameters. It uses two collective operations: reduce-scatter (after summing across GPUs, each GPU receives only its own slice of the result) and all-gather (each GPU contributes one slice, and every GPU ends up with the full concatenation); one all-reduce is exactly one reduce-scatter plus one all-gather.
- ZeRO-1 shards the optimizer states: Each GPU keeps the fp32 master weights and Adam states, those 12 bytes, only for the \(1/N_d\) of the parameters it is responsible for. After the backward pass, a reduce-scatter gives each GPU the averaged gradient for its own slice only; it updates that slice, and an all-gather then sends the updated bf16 weights to every GPU. Since reduce-scatter plus all-gather costs exactly as much communication as one all-reduce, it saves memory without adding communication.
- ZeRO-2 also shards the gradients: During the backward pass, each gradient bucket is reduce-scattered as soon as it is computed, and the parts a GPU does not own are freed immediately, so each GPU keeps only its own slice of the gradients. Communication is still unchanged.
- ZeRO-3 also shards the parameters: Each GPU normally stores only \(1/N_d\) of the weights. Before computing a layer's forward pass, it temporarily all-gathers that layer's full parameters and discards them as soon as the computation is done; in the backward pass it gathers them again, and finally reduce-scatters the gradients. Communication becomes two all-gathers plus one reduce-scatter, about 1.5 times that of data parallelism; in exchange, model-state memory falls linearly with the number of GPUs, making it possible to train models far larger than a single GPU's memory.
(3) FSDP is PyTorch's native implementation of ZeRO-3, and it is still data parallelism at heart.
FSDP (Fully Sharded Data Parallel, Zhao et al. 2023) wraps the model into units, usually one Transformer block per unit; each unit's parameters are sharded across GPUs, the full parameters are all-gathered before the unit's forward or backward pass and freed after use, and gradients are reduce-scattered back to their respective shards. To hide communication, it prefetches the next unit's parameters so that communication overlaps with compute. It is worth stressing that ZeRO and FSDP are still data parallelism at heart: each GPU processes different data and computes every layer in full; the parameters are merely stored as shards and stitched back together when needed. This is completely different from tensor parallelism (see 3.5), which genuinely splits a layer's computation across GPUs.
In summary: data parallelism solves "too slow", while ZeRO/FSDP solves "does not fit" without changing how data parallelism computes.
Going deeper: memory and communication compared, and the example from the ZeRO paper
(1) Memory and communication at each stage.
Let the parameter count be \(\Psi\) and the data-parallel degree \(N_d\), with memory in bytes and communication in number of elements:
| Plain DP | ZeRO-1 | ZeRO-2 | ZeRO-3 / FSDP | |
|---|---|---|---|---|
| What is sharded | Nothing | Optimizer states (incl. fp32 master weights) | Plus gradients | Plus parameters |
| Model-state memory per GPU | \(16\Psi\) | \(4\Psi+12\Psi/N_d\) | \(2\Psi+14\Psi/N_d\) | \(16\Psi/N_d\) |
| Communication per step | \(2\Psi\) | \(2\Psi\) | \(2\Psi\) | \(3\Psi\) |
(2) The example from the ZeRO paper: a 7.5B model on 64 GPUs.
By the table above, per-GPU model states fall from 120 GB under plain data parallelism to 31.4 GB with ZeRO-1, 16.6 GB with ZeRO-2 and 1.9 GB with ZeRO-3. ZeRO-1 already saves most of the memory, but only ZeRO-3 makes memory fall linearly with the number of GPUs.
(3) Ring all-reduce communication is almost independent of the number of GPUs.
Ring all-reduce arranges the \(N_d\) GPUs in a ring and splits the gradient into \(N_d\) slices. The reduce-scatter phase takes \(N_d-1\) steps; in each step every GPU sends one slice to the next GPU, which adds it to its own, and at the end each GPU holds the sum of one slice. The all-gather phase then takes another \(N_d-1\) steps to pass each slice's result around the whole ring. Each step transfers \(\Psi/N_d\) elements, and the two phases take \(2(N_d-1)\) steps in total, so the total is about \(2\Psi\).
(4) FSDP's sharding strategies correspond to different ZeRO stages.
| Strategy | Equivalent to | Characteristics |
|---|---|---|
| FULL_SHARD | ZeRO-3 | Least memory, most communication |
| SHARD_GRAD_OP | ZeRO-2 | Keeps the full parameters from the forward pass until the backward pass finishes, saving one all-gather |
| HYBRID_SHARD | ZeRO-3 within a node, data parallelism across nodes | The frequent all-gathers stay on fast intra-node links; only gradients are synchronized across nodes |
(Llama 3's FSDP likewise does not reshard the parameters after the forward pass, to avoid the extra all-gather in the backward pass (Dubey et al. 2024). ZeRO-Offload and ZeRO-Infinity go further and offload states to CPU memory or NVMe.)
Follow-up questions
Follow-up 1: Why does ZeRO-1 not add communication?
Because it merely splits one all-reduce into a reduce-scatter and an all-gather, so the total communication is unchanged. Plain data parallelism uses an all-reduce so that every GPU gets the full averaged gradient; ZeRO-1 first uses a reduce-scatter so that each GPU gets only the slice of the gradient it is responsible for, and after the update uses an all-gather to synchronize the parameters. The two steps together cost exactly as much as one all-reduce, but each GPU needs to store only \(1/N_d\) of the optimizer states.
Follow-up 2: ZeRO-3 and tensor parallelism both split the parameters. What is the essential difference?
The difference is whether the computation itself is split. ZeRO-3 only stores the parameters as shards; when computing a layer, it gathers the full parameters back, and each GPU processes its own data with the full parameters, so what is communicated is parameters and gradients. Tensor parallelism splits the matrix multiplication of a layer itself across GPUs, and the GPUs process different parts of the same data, so what is communicated is activations. Consequently, ZeRO-3 does not reduce the per-GPU compute or activation memory for a sample, whereas tensor parallelism does.
Follow-up 3: When does ZeRO-3 become slow?
When communication cannot be hidden by compute. ZeRO-3 all-gathers the parameters for every layer; if the inter-node bandwidth is low, or the per-GPU batch is so small that one layer's compute time cannot cover the time to gather its parameters, communication becomes the bottleneck. Common remedies are to use HYBRID_SHARD, which confines parameter gathering to within a node, or to increase the per-GPU micro-batch.
Common mistakes
- Do not say ZeRO is model parallelism: It is data parallelism at heart; each GPU processes different data and computes every layer in full.
- Do not say ZeRO shards activations: ZeRO shards only model states; activations must be handled by other methods.
- Do not say data-parallel communication grows linearly with the number of GPUs: With ring all-reduce, each GPU communicates about \(2\Psi\), almost independent of the number of GPUs; more GPUs mainly affect latency.
3.5 How do tensor parallelism and pipeline parallelism split the model? ★★¶
One-sentence answer
Tensor parallelism splits within a layer: it divides each layer's matrices by columns or rows across GPUs, so each GPU computes part of every layer, and every layer requires an all-reduce of activations, so its communication is heavy and it suits only fast intra-node links. Pipeline parallelism splits between layers: it places consecutive groups of layers on different GPUs and passes activations only between adjacent stages, so its communication is light and it suits cross-node setups, but it suffers from pipeline bubbles.
I will address three aspects: how tensor parallelism splits, how pipeline parallelism splits, and what each costs.
(1) Tensor parallelism splits matrices first by columns, then by rows, so that each sublayer needs only one all-reduce.
Tensor parallelism (TP; Megatron-LM, Shoeybi et al. 2019) splits the matrices inside a layer across \(t\) GPUs. Take the FFN, which first computes \(Y=\sigma(XA)\) and then \(Z=YB\), where \(X\) is the input, \(A\) and \(B\) are the two weight matrices, and \(\sigma\) is an element-wise activation function. The first matrix \(A\) is split by columns: every GPU has the full input \(X\) and computes its own \(XA_i\), i.e. a slice of the hidden dimensions; since \(\sigma\) is element-wise, each GPU applies the activation to its own slice directly, with no communication at all. The second matrix \(B\) is split by rows: each GPU multiplies its slice \(Y_i\) by \(B_i\), producing a result of full shape that is only a partial sum, and one all-reduce adds the GPUs' results together. Columns must come first and rows second because, if the first matrix were split by rows, each GPU would hold partial sums that must be added before the activation (\(\sigma(a+b)\neq\sigma(a)+\sigma(b)\)), costing an extra synchronization. Attention splits even more naturally: the heads are computed independently anyway, so they can simply be divided among GPUs, with the Q, K and V projections split by columns and the output projection split by rows, followed by one all-reduce. Therefore, each Transformer layer needs 2 all-reduces in the forward pass and 2 in the backward pass.
(2) Pipeline parallelism splits by layer and fills the pipeline with micro-batches to reduce the bubble.
Pipeline parallelism (PP) divides the \(L\) layers into \(p\) stages, each placed on one GPU or a group of GPUs, and adjacent stages only need to pass the activations (forward) and gradients (backward) at their boundary, point to point. The naive approach starts the next stage only after the previous one finishes, so only one GPU works at any time and utilization is just \(1/p\). GPipe (Huang et al. 2018) splits a batch into \(m\) micro-batches and feeds them in like an assembly line: while stage 2 processes micro-batch 1, stage 1 is already working on micro-batch 2. However, during the fill phase at the start and the drain phase at the end, some stages still sit idle; this idle time is called the bubble, and its fraction is \((p-1)/(m+p-1)\), so more micro-batches mean a smaller bubble. In addition, the 1F1B schedule (Narayanan et al. 2021) has each stage alternate one forward pass and one backward pass once the pipeline is full, so each micro-batch's activations are freed as early as possible and activation memory no longer grows with \(m\).
(3) The two have different costs and therefore belong in different places.
- The cost of tensor parallelism is frequent, heavy activation communication: Every layer all-reduces activations of size \(b\times s\times h\), and this communication sits on the critical path of computation where it is hard to overlap, so it needs high-bandwidth intra-node links such as NVLink, and \(t\) usually does not exceed the number of GPUs per node (typically 8); when \(t\) is too large, the matrices on each GPU become too small and GPU utilization also drops. Its benefits are that parameters, gradients, optimizer states and in-layer activations are all cut to \(1/t\), and that there is no bubble.
- The cost of pipeline parallelism is the bubble and load balancing: Its communication happens only between adjacent stages and is small, so it can tolerate crossing nodes; but the bubble must be amortized with many micro-batches, and more micro-batches mean either smaller micro-batches with lower GPU efficiency or a larger global batch. In addition, the compute of the stages must be balanced (the stages holding the embedding and the output layer are often heavier), and implementation and scheduling are more complex.
In summary: tensor parallelism "splits matrices", with heavy and frequent communication, so it stays within a node; pipeline parallelism "splits layers", with light communication but a bubble, so it spans nodes.
Going deeper: the split formulas, the bubble calculation and pipeline schedules
(1) Tensor-parallel split of the FFN (for \(t=2\)).
Here \(A_i\) is the \(i\)-th group of columns of \(A\), \(B_i\) the \(i\)-th group of rows of \(B\), and \(Y_i\) stays on GPU \(i\); the final sum \(Y_1B_1+Y_2B_2\) is that one all-reduce.
(2) Deriving the bubble fraction.
The diagram below shows the forward pass for \(p=4\) and \(m=4\), where Fi is the forward pass of micro-batch i and a dot means idle:
GPU 0: F1 F2 F3 F4 . . .
GPU 1: . F1 F2 F3 F4 . .
GPU 2: . . F1 F2 F3 F4 .
GPU 3: . . . F1 F2 F3 F4
Each GPU works in only \(m\) of \(m+p-1\) time slots, so
For example, with \(p=4\) and \(m=32\) it is about 9%. When \(m\gg p\), it is approximately \((p-1)/m\).
(3) Comparing several schedules.
| Schedule | Bubble | Activation memory | Notes |
|---|---|---|---|
| GPipe (Huang et al. 2018) | \((p-1)/(m+p-1)\) | Grows with \(m\) | All forward passes first, then all backward passes |
| 1F1B (Narayanan et al. 2021) | Same as GPipe | At most \(p\) micro-batches in flight | Alternates forward and backward once the pipeline is full |
| Interleaved 1F1B (Narayanan et al. 2021) | Reduced to \(1/v\) | Similar to 1F1B | Each GPU holds \(v\) non-adjacent chunks of layers; point-to-point communication grows \(v\)-fold |
| Zero Bubble (Qi et al. 2023) | Close to 0 | Slightly higher | Splits the backward pass into input gradients and weight gradients and uses the latter to fill the bubble |
(DeepSeek-V3's DualPipe further overlaps computation and communication within the forward and backward passes.)
Follow-up questions
Follow-up 1: How many communication steps does one Transformer layer need under tensor parallelism?
Two all-reduces in the forward pass and two in the backward pass. Attention and the FFN each have one "columns then rows" split, with one all-reduce after the row-split matrix, giving 2 in the forward pass; in the backward pass, the input gradients at the corresponding positions also need to be summed, giving another 2.
Follow-up 2: Why does pipeline parallelism suit cross-node setups while tensor parallelism does not?
Because their communication frequency and volume differ greatly. In pipeline parallelism, each micro-batch makes one point-to-point transfer at each stage boundary, which can overlap with the computation of other micro-batches; in tensor parallelism, every layer performs 4 all-reduces, each involving all \(t\) GPUs and sitting on the critical path, so computation must wait for communication to finish. Inter-node bandwidth is usually far lower than intra-node NVLink and can only handle the former.
Follow-up 3: What is Megatron's sequence parallelism?
It complements tensor parallelism by removing the redundant activations of operations such as LayerNorm and dropout. Tensor parallelism splits only the matrix multiplications, while per-token operations such as LayerNorm and dropout are computed in full on every GPU in the TP group, each storing a full copy of the activations. Sequence parallelism (Korthikanti et al. 2022) splits these parts along the sequence dimension so that each GPU handles only some of the tokens; each all-reduce is replaced by a reduce-scatter plus an all-gather, with the same communication volume, but the activation memory of these parts drops to \(1/t\).
Common mistakes
- Do not say 1F1B shrinks the bubble: Plain 1F1B has the same bubble as GPipe; what it reduces is activation memory. Shrinking the bubble requires more micro-batches, an interleaved schedule or methods such as Zero Bubble.
- Do not say pipeline parallelism has no communication: Adjacent stages still pass activations and gradients; the volume is merely small and only point to point.
- Do not say more tensor-parallel GPUs is always better: Once \(t\) exceeds the GPUs in a node, communication must cross nodes, and at the same time the matrices on each GPU become smaller, so efficiency actually drops.
3.6 How is 3D parallelism combined? ★¶
One-sentence answer
3D parallelism combines data, tensor and pipeline parallelism, with the total GPU count equal to the product of the three degrees; the principle for combining them is to put the most communication-heavy dimension on the fastest links: tensor parallelism within a node, pipeline parallelism across nodes, and data parallelism (usually ZeRO or FSDP) as the outermost layer.
I will address two aspects: the principle for combining them, and how to design a parallel scheme for a concrete model.
(1) The core principle is to match each dimension's communication volume to the link bandwidth.
Large-model training uses several kinds of parallelism at once, and the total GPU count is the product of the degrees of each dimension, \(N=t\times p\times d\), where \(t\), \(p\) and \(d\) are the tensor, pipeline and data-parallel degrees (multiplied further by the context-parallel degree for long sequences and by the expert-parallel degree for MoE models). For example, 1,024 GPUs can be organized as TP 8 × PP 8 × DP 16. Because bandwidth inside a cluster is hierarchical, with intra-node NVLink the fastest and inter-node networking much slower, positions must be assigned by communication volume (Narayanan et al. 2021):
- Tensor parallelism stays inside a node: It all-reduces activations in every layer, on the critical path, so it must use the highest bandwidth.
- Pipeline parallelism spans nodes: It makes only small point-to-point transfers between adjacent stages, which slower networks can handle.
- Data parallelism is the outermost layer: Gradient synchronization happens only once per step and can overlap with the backward pass, so it is the least sensitive to latency.
(2) When designing a scheme, start from the simplest option and add dimensions as bottlenecks appear.
A practical approach: if the model fits with FSDP alone, use only FSDP, since it is the simplest; if a single layer's activations are too large, or the global batch is too small to divide among all data-parallel GPUs, add tensor parallelism within the node; if the model still does not fit with tensor parallelism, or the inter-node bandwidth cannot sustain FSDP's parameter gathering, add pipeline parallelism; and add context parallelism for very long sequences. At the same time, the global batch constraint must hold: data-parallel degree × micro-batch size × gradient accumulation steps = global batch size. Because the global batch cannot grow without limit for optimization reasons, the data-parallel degree cannot grow without limit either, which is another reason tensor and pipeline parallelism are needed.
In summary: the principle of 3D parallelism is "the heavier the communication, the closer together"; a design starts from FSDP and adds tensor and pipeline parallelism step by step according to the memory, batch and bandwidth bottlenecks.
Going deeper: comparing the dimensions, and the actual configuration of Llama 3 405B
(1) Comparing the parallel dimensions.
| Dimension | What is split | Communication | Typical placement | Main cost |
|---|---|---|---|---|
| Data (DP / FSDP) | The batch; model states under ZeRO | Gradient all-reduce, or reduce-scatter plus all-gather | Outermost, across nodes | Per-step volume; 1.5× for ZeRO-3 |
| Tensor (TP) | Matrices inside each layer | Activation all-reduce, 2 per layer in each of the forward and backward passes | Within a node (NVLink) | Needs very high bandwidth |
| Pipeline (PP) | Layers | Point-to-point activations between stages | Across nodes | Bubble, load balancing |
| Context (CP) | The sequence | Ring passing of K/V, or all-to-all | Within or across nodes | Extra attention communication |
| Expert (EP) | MoE experts | All-to-all token routing | Across GPUs | All-to-all latency, load imbalance |
(2) Llama 3 405B used 4D parallelism composed of TP, CP, PP and FSDP (Dubey et al. 2024).
GPUs are grouped from innermost to outermost in the order [TP, CP, PP, DP], where DP means FSDP. The three published configurations are:
| GPUs | TP | CP | PP | DP | Sequence length | Tokens per step | BF16 MFU |
|---|---|---|---|---|---|---|---|
| 8,192 | 8 | 1 | 16 | 64 | 8,192 | 16M | 43% |
| 16,384 | 8 | 1 | 16 | 128 | 8,192 | 16M | 41% |
| 16,384 | 8 | 16 | 16 | 8 | 131,072 | 16M | 38% |
TP always equals the 8 GPUs per node; in the long-context stage, to keep the tokens per step unchanged, the data-parallel degree drops from 128 to 8 while the context-parallel degree rises to 16.
Follow-up questions
Follow-up 1: Given 1,024 H100s to train a 70B model, how would you design the parallelism?
First estimate the model states, the batch constraint and the activations separately, then decide which dimensions to add. Assume a sequence length of 8K and a global batch of about 4M tokens, i.e. 512 sequences per step:
- Model states: \(16\times70\text{B}\approx1.12\) TB, which must be sharded; sharded with FSDP across all 1,024 GPUs, each GPU needs only about 1.1 GB.
- Batch constraint: With pure data parallelism, 512 sequences cannot be divided among 1,024 GPUs, so \(t\times p\) must be at least 2.
- Activations: A rough estimate with \(34sbhL\) (with FlashAttention, ignoring the attention matrix) gives about 183 GB per sequence at \(h=8192\) and \(L=80\), far beyond a single GPU; adding TP 8 within the node (with sequence parallelism) brings this down to about 23 GB.
A reasonable starting point is therefore TP 8 within each node and FSDP 128 across nodes, with each data-parallel group processing 4 sequences per step; if the inter-node bandwidth cannot sustain FSDP's parameter gathering, add pipeline parallelism, and use selective recomputation as memory requires.
Follow-up 2: Why is data parallelism the outermost layer?
Because it has the lowest bandwidth and latency requirements. Data parallelism synchronizes gradients only once per step, and they can be sent in buckets during the backward pass, overlapping with compute; FSDP can also prefetch the next layer's parameters. Therefore, even across the slowest network, it can hide the communication overhead fairly well.
Follow-up 3: What is context parallelism?
It splits a very long sequence into chunks across several GPUs, for training long contexts where a single sequence does not fit on one GPU. Most operations are per-token, so each GPU computes independently; only attention requires every token to see the K and V of all earlier tokens, which needs communication. Ring Attention (Liu et al. 2023) arranges the GPUs in a ring and passes K/V blocks around it, accumulating part of the attention result each time a block arrives, so communication overlaps with compute; DeepSpeed-Ulysses (Jacobs et al. 2023) instead uses an all-to-all to switch temporarily from sharding by sequence to sharding by head. Methods for modeling long context are covered in the "Model Architecture" direction.
Common mistakes
- Do not say more parallel dimensions are always better: Each added dimension brings new communication or bubbles; start from the simplest scheme and add dimensions only when a bottleneck appears.
- Do not ignore the global batch constraint: Data-parallel degree × micro-batch size × gradient accumulation steps must equal the global batch, so the data-parallel degree cannot grow without limit.
3.7 What is activation checkpointing? ★¶
One-sentence answer
Activation checkpointing trades compute for memory: in the forward pass it keeps only a few checkpoints (usually the input of each Transformer block) and discards the intermediate results inside each block; in the backward pass it reruns the forward computation from the checkpoint to rebuild those intermediates. The cost is roughly one extra forward pass, which increases total compute by about a third.
I will address three aspects: how it works, what it costs, and the finer-grained selective recomputation.
(1) How it works: keep only checkpoints in the forward pass, and recompute the intermediates from them in the backward pass.
As described in 3.2, the backward pass needs every layer's intermediate results from the forward pass, and these activations take a lot of memory. Activation checkpointing (also called gradient checkpointing) keeps only the input of each Transformer block during the forward pass and discards the intermediate results inside the block once they are used; when the backward pass reaches a block, it first reruns that block's forward pass from the saved input to rebuild the intermediates, and then computes gradients as usual. Activation memory thus drops from "every intermediate result of every layer" to "one input per layer, plus the intermediates of the one block currently being recomputed".
(2) The cost: one extra forward pass, raising compute by about 33%.
Training costs about \(6N\) per token, of which the forward pass is about \(2N\) and the backward pass about \(4N\) (\(N\) is the parameter count; see 3.9 for the derivation). Recomputation amounts to running the forward pass again, raising compute from \(6N\) to about \(8N\), an increase of about a third; Korthikanti et al. (2022) note that the actual time overhead can reach 30% to 40%. It is therefore suited to cases where memory is short but compute has headroom; if memory suffices, it should not be enabled.
(3) Selective recomputation recomputes only the parts that take a lot of memory but are cheap to compute.
Not all activations cost the same to recompute. Korthikanti et al. (2022) observed that the attention score matrix, the softmax output and its dropout mask grow quadratically with sequence length and take a lot of memory, yet require very little compute per element, whereas the inputs of matrix multiplications take less memory but are expensive to recompute. They therefore recompute only this part of attention and store everything else as usual, recovering most of the memory for very little extra compute. FlashAttention recomputing the attention scores in the backward pass instead of storing them follows the same idea.
In summary: activation checkpointing trades about a third more compute for most of the activation memory; selective recomputation recomputes only the most cost-effective parts, making the trade cheaper.
Going deeper: memory and compute of the three schemes compared
(1) Per-layer activation memory and extra compute.
Using the notation of 3.2 (\(s\) the sequence length, \(b\) the micro-batch size, \(h\) the hidden size, \(a\) the number of heads), the activation memory per Transformer layer is as follows (Korthikanti et al. 2022):
| Scheme | Activation memory per layer (bytes) | Extra compute |
|---|---|---|
| No recomputation | \(sbh\,(34+5as/h)\) | None |
| Selective recomputation | \(34\,sbh\) | Very small (about 2.7% of FLOPs for GPT-3) |
| Full recomputation | \(2\,sbh\) | About one full forward pass (about 33% of FLOPs) |
For GPT-3 (\(a=96\), \(s=2048\), \(h=12288\)), \(5as/h=80\), which exceeds 34, so selective recomputation saves about 70% of activation memory.
(2) The number of checkpoints can also be tuned.
Not every layer needs a checkpoint. Chen et al. (2016) showed that placing a checkpoint every \(\sqrt{L}\) layers or so in an \(L\)-layer network reduces activation memory to \(O(\sqrt{L})\), while the extra compute is still only one forward pass. In practice, recomputation is also often applied to only some of the layers, as a compromise between memory and speed.
Follow-up questions
Follow-up 1: Why are checkpoints usually placed at the input of each Transformer block?
Because the tensor there is the smallest, and a block is a self-contained unit of computation. The block input is just the residual stream of size \(b\times s\times h\), whereas the intermediate results inside the block (such as the \(4h\)-dimensional FFN hidden activations and the attention scores) are much larger; recomputing block by block also fits well with mechanisms such as FSDP that are organized by block.
Follow-up 2: Does activation checkpointing change the training result?
Not mathematically, but the implementation must make the recomputation exactly match the original forward pass. For example, if the model uses dropout, the recomputation must restore the same random-number state to generate the same masks; mainstream frameworks save and restore the random-number state automatically.
Follow-up 3: Do activation checkpointing and ZeRO solve the same problem?
No; they target different parts of memory and can be combined. ZeRO shards the model states (weights, gradients and optimizer states), while activation checkpointing reduces activations. Large-scale training usually uses both at once.
Common mistakes
- Do not say recomputation doubles compute: Only the forward pass is recomputed, and it is about a third of training compute, so compute rises by only about 33%.
- Do not count recomputation FLOPs in MFU: MFU counts only the computation the model requires (see 3.9).
3.8 What do you do when a loss spike appears during training? ★★¶
One-sentence answer
First use monitoring signals such as the gradient norm and logit magnitudes to determine where the spike comes from; if the loss does not recover on its own, roll back to a checkpoint before the spike and continue training after skipping nearby data batches or lowering the learning rate. In the long run, prevent spikes through the optimizer settings, numeric precision and model architecture (such as QK-Norm and z-loss).
I will address three aspects: the common causes of loss spikes, how to handle one once it occurs, and how to prevent them.
(1) A loss spike usually results from oversized updates interacting with the continued growth of numerical values.
A loss spike is a sudden jump in training loss, after which the loss may recover or may diverge and even become NaN. The larger the model, the higher the learning rate and the lower the numeric precision, the more likely spikes are. The common causes fall into four groups:
- The learning rate is too large relative to the setup: A step that goes too far along a high-curvature direction throws the parameters out of the region they were in.
- Logits keep growing: Attention logits (the dot products of query and key before the softmax) grow during training until the softmax approaches one-hot and saturates; the output-layer logits can also drift as a whole. These large values also amplify rounding error in low precision.
- Interaction with Adam: Some parameters have tiny gradients for a long time, so their second moment \(v\) becomes tiny too; when a large gradient suddenly appears, \(m/\sqrt{v}\) becomes huge and produces an abnormally large update.
- Data: Some batches contain unusual or highly repetitive data. However, PaLM found that retraining on the same batches that caused a spike, starting from an earlier checkpoint, did not cause the spike again, suggesting that spikes often arise from a particular combination of data and parameter state (Chowdhery et al. 2022).
(2) Once a spike occurs, first see whether it recovers on its own, then roll back and skip data or lower the learning rate.
Small spikes often recover on their own, in which case one can keep watching. If the loss does not recover, or the gradient norm keeps surging or NaN appears, one should roll back to a checkpoint before the spike rather than continue from the current state, because Adam's \(m\) and \(v\) have by then been contaminated by the abnormal gradients. After rolling back, one usually skips the data batches around the spike, or lowers the learning rate somewhat, and then continues. For example, PaLM 540B experienced about 20 spikes during training; each time it restarted from a checkpoint about 100 steps before the spike and skipped about 200 to 500 batches, after which the spike did not recur at the same point. At the same time, one should check which layer's gradient norm or logits became abnormal first, and whether the data around the spike has problems, in order to locate the root cause.
(3) Prevention matters more than repair, and it comes from three areas: the optimizer, numeric precision and the architecture.
- Optimizer and learning rate: Use warmup and a suitable peak learning rate; clip gradients by global norm (compute the L2 norm over all parameters' gradients together and scale the whole gradient down proportionally when it exceeds a threshold) to keep abnormal gradients out of the optimizer state; and set \(\beta_2\) to about 0.95 (see 3.1).
- Numeric precision: Use bf16 rather than fp16, and keep sensitive operations such as softmax, normalization and the loss in fp32 (see 3.3).
- Architecture: Use QK-Norm to normalize the query and key before computing the attention logits, which bounds the logits (Dehghani et al. 2023); use z-loss to constrain the normalizer of the output softmax, which prevents the output logits from drifting as a whole (Chowdhery et al. 2022).
In summary: the approach to loss spikes is "monitor to catch them early, roll back and skip data to recover, and prevent them through the optimizer, precision and architecture".
Going deeper: monitoring signals, z-loss and the stability practices of different labs
(1) Signals worth monitoring go beyond the loss.
| Signal | Meaning | Warning sign |
|---|---|---|
| Global gradient norm | L2 norm of all parameters' gradients | Frequent clipping or a sudden surge, often before the loss spikes |
| Update-to-parameter ratio | Norm of each step's parameter change divided by the norm of the parameters | A sudden increase in some layers indicates an abnormal effective step size there |
| Maximum attention logit | Scores before the softmax | Continued growth signals impending softmax saturation |
| \(\log Z\) of the output layer | Log of the output softmax normalizer | A persistent drift away from 0 indicates the output logits are drifting as a whole |
| Per-layer activation norms | Magnitude of each layer's output | Outliers appearing in a few channels |
(2) z-loss keeps the normalizer of the output softmax near 0.
Here \(z_j\) is the output-layer logit for word \(j\), \(Z\) is the softmax normalizer, and \(\lambda_z\) is a coefficient, set to \(10^{-4}\) in PaLM. Because adding the same constant to all logits does not change the softmax output, the logits can drift as a whole and keep growing without affecting the loss; z-loss penalizes \(\log Z\) for moving away from 0, which pins down the overall scale of the logits.
(3) Published stability practices of different labs.
| Model | Practice |
|---|---|
| PaLM (Chowdhery et al. 2022) | Rolled back about 100 steps before each spike and skipped about 200 to 500 batches; used z-loss |
| OLMo 2 (OLMo et al. 2024) | Filtered out documents with many repeated n-grams; used QK-Norm; moved the normalization to the outputs of attention and the FFN; used z-loss; no weight decay on the embedding; lowered Adam's \(\epsilon\) from \(10^{-5}\) to \(10^{-8}\) |
| Kimi K2 (Kimi Team 2025) | Used the MuonClip optimizer, whose QK-Clip rescales the query and key projection weights after each update when needed to bound the attention logits; reported no loss spike during pretraining on 15.5T tokens |
(4) Many instabilities can be reproduced in advance with small models.
Wortsman et al. (2023) found that two kinds of instability, attention logit growth and output logit drift, can be reproduced in small models simply by using a high learning rate, and that the mitigations used for large models are equally effective there. One can therefore stabilize the configuration at small scale first and then scale up to large-scale training, lowering the risk.
Follow-up questions
Follow-up 1: How can you tell whether a spike is caused by data or by optimization?
The most direct way is a controlled experiment. Retrain on the data batches around the spike starting from a different, earlier checkpoint: if the spike still occurs, the data itself is the problem; if it does not, the spike came from the combination of the data and the parameter state at that time, which is what PaLM observed. One can also check whether the abnormal gradients are concentrated in the embedding rows of a few tokens, or whether there is a large amount of repeated text around the spike.
Follow-up 2: Why does growth in attention logits make training unstable?
Because it saturates the softmax and amplifies numerical error in low precision. When the logits are large, the softmax output approaches one-hot and its gradient approaches 0, so attention can hardly keep learning; at the same time, large values have larger absolute rounding errors in bf16. Scaling by \(\sqrt{d_k}\) only guarantees suitable magnitudes at initialization (see the "Model Architecture" direction) and cannot stop growth during training, so methods such as QK-Norm are needed to keep constraining the size of the query and key.
Follow-up 3: What are the common causes of the loss suddenly becoming NaN?
Common causes include numerical overflow, division by zero and abnormal data. For example: activations or gradients exceeding 65,504 and overflowing in fp16; an \(\epsilon\) in a normalization layer that is too small, so a nearly all-zero input leads to division by a tiny number; or a sample whose tokens are all masked out by the loss mask, giving 0 divided by 0 when averaging over the token count. When debugging, first locate the first layer that produces NaN and the corresponding data.
Common mistakes
- Do not answer only "lower the learning rate": Diagnose the cause first, then roll back, skip data or adjust hyperparameters, and prevent recurrence through the architecture and precision.
- Do not assume a spike is always caused by bad data: PaLM's experiments showed that the same data did not cause a spike from a different parameter state.
- Do not continue training from the current state right after a spike: Adam's first and second moments have already been contaminated by the abnormal gradients, so roll back to a checkpoint before the spike.
3.9 What is MFU, and how do you estimate training time? ★¶
One-sentence answer
MFU (Model FLOPs Utilization) is the ratio of the achieved model compute throughput to the hardware's peak compute, counting only the computation the model itself requires (about \(6N\) FLOPs per training token, where \(N\) is the parameter count); large-scale training typically reaches around 40%. Training time is approximately the total compute \(6ND\) divided by "number of GPUs × peak compute per GPU × MFU", where \(D\) is the number of training tokens.
I will address three aspects: where the per-token compute comes from, how MFU is defined, and how to estimate training time.
(1) Training costs about \(6N\) FLOPs per token: \(2N\) for the forward pass and \(4N\) for the backward pass.
In the forward pass, every parameter takes part in one multiplication and one addition for every token, i.e. 2 floating-point operations (FLOPs), so the forward pass costs about \(2N\) per token. The backward pass computes two kinds of gradients: gradients with respect to activations, used to keep propagating backward, and gradients with respect to weights, used to update the parameters. Each costs about as much as the forward pass, so the backward pass costs about \(4N\). Together, training costs about \(6N\) per token, and the total compute for training on \(D\) tokens is about \(C\approx 6ND\). This estimate counts only the parameter-related matrix multiplications and ignores the attention score computation, which introduces little error when the context is not too long.
(2) MFU measures what fraction of the hardware's compute actually goes to the computation the model requires.
MFU was introduced by PaLM (Chowdhery et al. 2022) and is defined as the number of tokens processed per second times the model compute per token, divided by the hardware's peak compute. It counts only the computation the model itself requires, not the extra FLOPs from activation recomputation, so it compares the efficiency of different implementations fairly. Large-scale training typically reaches an MFU of around 40%: PaLM 540B reported 46.2%, and Llama 3 405B reported 38% to 43% (Dubey et al. 2024). The remaining time goes mainly to communication, pipeline bubbles, operators bound by memory bandwidth (such as element-wise operations like normalization and softmax), and various synchronization waits.
(3) Training time equals total compute divided by effective compute.
With \(6ND\) and MFU, training time can be estimated as
where \(G\) is the number of GPUs and \(P\) is the peak compute per GPU (FLOPs per second). The formula can also be used in reverse: given a budget and a schedule, one can work out how large a model and how many tokens can be trained. In practical estimates, some margin should also be reserved for hardware failures, restarts and evaluation.
In summary: training time ≈ \(6ND\) ÷ (number of GPUs × peak compute × MFU), with MFU usually taken as about 40%; this is the basic tool for quickly estimating training cost in an interview.
Going deeper: checking the estimate against Llama 2's published numbers
(1) Peak compute of common hardware (dense matrix multiplication).
| GPU | bf16 peak | fp8 peak |
|---|---|---|
| A100 | 312 TFLOPS | Not supported |
| H100 SXM | About 989 TFLOPS | About 1,979 TFLOPS |
(2) Example: training time for Llama 2 7B.
Llama 2 7B has about 6.7B parameters and was trained on about 2T tokens (Touvron et al. 2023), so the total compute is about \(6\times6.7\times10^9\times2\times10^{12}\approx8.0\times10^{22}\) FLOPs. On A100s at 40% MFU, each GPU delivers about 125 TFLOPS of effective compute, so this takes about \((8.0\times10^{22})/(1.25\times10^{14})\approx6.4\times10^{8}\) GPU-seconds, i.e. about 180,000 GPU-hours; with 1,024 GPUs, it would take about 7 days. The Llama 2 paper reports 184,320 GPU-hours for pretraining the 7B model, very close to the estimate. Conversely, working back from the published GPU-hours gives an MFU of about 39% for the 7B model and about 43% for the 70B model.
(3) For long contexts, attention compute must be added.
Attention scoring and the weighted sum involve no parameters and add about \(2\,L\,n_{\text{ctx}}\,d\) forward FLOPs per token (Kaplan et al. 2020), where \(L\) is the number of layers, \(n_{\text{ctx}}\) the context length, and \(d\) the hidden size. Its ratio to the parameter part is about \(n_{\text{ctx}}/(12d)\): when the context length and \(d\) are both 4,096, it adds only about 8% and can be ignored; but at contexts of hundreds of thousands of tokens, it becomes the dominant cost.
Follow-up questions
Follow-up 1: How do MFU and HFU differ?
HFU (Hardware FLOPs Utilization) also counts extra computation such as activation recomputation, whereas MFU does not. For example, with full recomputation each token actually executes about \(8N\) FLOPs, so HFU is about \(8/6\) times MFU. HFU reflects how busy the hardware is, while MFU reflects how much compute actually advances training, so MFU should be used when comparing schemes. PaLM 540B had an MFU of 46.2% and an HFU of 57.8%.
Follow-up 2: When MFU is low, where do you usually optimize?
In three areas: communication, bubbles and operator efficiency. For communication, overlap gradient synchronization and parameter gathering with compute, and keep the communication-heavy parallel dimensions within a node; for bubbles, increase the number of micro-batches or use an interleaved schedule; for operators, use FlashAttention and kernel fusion to reduce memory traffic, and avoid a tensor-parallel degree so large that the matrices become too small.
Follow-up 3: Why does inference cost about \(2N\) FLOPs per generated token?
Because inference has only the forward pass. Each parameter does one multiplication and one addition per token, giving \(2N\); there is no backward pass, so there is no additional \(4N\). However, the bottleneck in inference is often not compute but memory bandwidth; see the "Inference, Evaluation and Deployment" direction.
Common mistakes
- Do not count recomputation FLOPs in MFU: That yields HFU and overstates training efficiency.
- Do not compute MFU against a peak that includes sparsity acceleration: Vendor spec sheets often list figures doubled by structured sparsity; training should use the dense matrix-multiplication peak.