2 Foundations 6 / 6
  1. In this chapter
  2. Python and tensor shapes
  3. From Language Modeling to Next-Token Prediction
  4. Neural Network Basics
  5. Information Theory Refresher
  6. Tokenizers and Embeddings
  7. Optimizers and Training Stability
All chapters →

Chapter 2 · Foundations 2.6

Optimizers and Training Stability: AdamW, Warmup, Mixed Precision, Loss Spikes

Large-model pretraining almost always uses AdamW with linear warmup plus cosine (or WSD) decay, gradient clipping and mixed precision. This page explains what each hyperparameter is for and gives a checklist for loss spikes and NaNs.

Intermediate 15 min read Updated Companion code ↓

After this page you will be able to

  • Name the typical pretraining recipe: AdamW, linear warmup with cosine (or WSD) decay, gradient clipping and mixed precision.
  • Explain what each step from SGD to Adam and AdamW fixes, and see the differences in the optimizer lab.
  • Compare several learning-rate schedules and say why warmup is needed.
  • Explain why mixed precision keeps an FP32 copy and how gradient clipping tames loss spikes.
  • Work through loss spikes and NaNs in a fixed order.
On this page
  1. Start with real training recipes
  2. From SGD to AdamW
  3. Hands-on: the optimizer lab
  4. Learning-rate schedules: warmup and decay
  5. Hands-on: compare four schedules
  6. Mixed precision: why keep FP32
  7. Gradient clipping and loss spikes
  8. Hands-on code
  9. Summary and exercises
  10. Quick self-check
  11. Further reading
  12. FAQ

Start with real training recipes

The table below lists the optimizer settings reported for the pretraining of three public LLMs. GPT-3 and Llama 2 are almost identical: β2=0.95\beta_2=0.95, weight decay 0.1, gradient clipping at 1.0, and linear warmup followed by cosine decay to 10% of the peak. The public part of the Llama 3 405B recipe is also AdamW with linear warmup and cosine decay, only with a lower end point (1% of the peak).

SettingGPT-3 (2020)Llama 2 (2023)Llama 3 405B (2024)
OptimizerAdam, β1=0.9\beta_1=0.9, β2=0.95\beta_2=0.95, ϵ=10−8\epsilon=10^{-8}, weight decay 0.1AdamW, β1=0.9\beta_1=0.9, β2=0.95\beta_2=0.95, ϵ=10−5\epsilon=10^{-5}, weight decay 0.1AdamW
Gradient clipping (global norm)1.01.0—
Peak learning rateVaries with model size3.0×10−43.0\times10^{-4} for 7B and 13B, 1.5×10−41.5\times10^{-4} for 34B and 70B8×10−58\times10^{-5}
WarmupLinear over the first 375 million tokens2,000 steps, linear8,000 steps, linear
DecayCosine decay to 10%, then held at 10%Cosine decay to 10%Cosine decay to 8×10−78\times10^{-7} (1% of the peak) over 1.2 million steps

(”—” means the paper does not state it there. The GPT-3 column is from Appendix B of the paper, Llama 2 from Section 2.2 and Table 1, and Llama 3 from Section 3.4.1 and Table 3.)

The rest of this page explains, item by item, why the table looks the way it does.

From SGD to AdamW

SGD. Each step moves a small distance along the negative gradient: θ←θ−η g\theta \leftarrow \theta - \eta\, g. For a quadratic loss 12∑iλiθi2\tfrac12\sum_i\lambda_i\theta_i^2 it diverges unless η<2/λmax⁡\eta<2/\lambda_{\max}, while the speed of convergence is set by the flattest direction λmin⁡\lambda_{\min}. The larger their ratio κ=λmax⁡/λmin⁡\kappa=\lambda_{\max}/\lambda_{\min} (the condition number), the harder SGD is to tune: the learning rate is capped by the steepest direction, yet progress along the flat directions is very slow.

Momentum. Accumulate past gradients into a velocity v←μv+gv\leftarrow\mu v+g and update the parameters along vv. In flat directions consecutive gradients share a sign, so the velocity builds up and the effective learning rate is amplified by about 1/(1−μ)1/(1-\mu). In steep directions the gradient flips sign back and forth and the contributions cancel out.

Adaptive learning rates (RMSProp, Adam). Scale the step of every parameter separately: divide by the square root of a moving average vv of the squared gradients, so parameters with large gradients move slowly and parameters with small gradients move fast. Adam adds a moving average mm of the gradient itself (momentum) and a bias correction:

mt=β1mt−1+(1−β1) gt,vt=β2vt−1+(1−β2) gt2m_t = \beta_1 m_{t-1} + (1-\beta_1)\,g_t,\qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)\,g_t^2 m^t=mt1−β1 t,v^t=vt1−β2 t,θt=θt−1−η m^tv^t+ϵ\hat m_t = \frac{m_t}{1-\beta_1^{\,t}},\qquad \hat v_t = \frac{v_t}{1-\beta_2^{\,t}},\qquad \theta_t = \theta_{t-1} - \eta\,\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}

The bias correction is there because m0=v0=0m_0=v_0=0, which makes the early moving averages too small. The defaults in the Adam paper (Kingma and Ba, 2014) are β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999 and ϵ=10−8\epsilon=10^{-8}. Large models often lower β2\beta_2 to 0.95: the effective memory of vv is about 1/(1−β2)1/(1-\beta_2) steps, which is about 1000 steps for 0.999 but only about 20 for 0.95, so it reacts much faster when the gradients suddenly grow.

AdamW. Weight decay shrinks the parameters by a small proportion every step: θ←(1−ηλ)θ\theta\leftarrow(1-\eta\lambda)\theta (following the PyTorch convention, the decay coefficient λ\lambda is multiplied by the learning rate η\eta). In SGD it is equivalent to L2 regularization, but in Adam an L2 term added to the loss has its gradient scaled by v^t\sqrt{\hat v_t} too, so different parameters are decayed by different amounts. AdamW (Loshchilov and Hutter, 2017) pulls the decay out and applies it directly to the parameters:

θt=θt−1−η(m^tv^t+ϵ+λ θt−1)\theta_t = \theta_{t-1} - \eta\left(\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon} + \lambda\,\theta_{t-1}\right)

This decouples the decay coefficient λ\lambda from the gradient scaling, so it is no longer altered by v^t\sqrt{\hat v_t}, and the best λ\lambda depends less on the learning rate. In torch.optim.AdamW, lr is η\eta and weight_decay is λ\lambda.

Hands-on: the optimizer lab

The widget below starts four optimizers from the same point and lets them descend the valley f(x,y)=12(x2+κy2)f(x,y)=\tfrac12(x^2+\kappa y^2) at the same time. Change the steepness κ\kappa, the learning rate and the noise, and watch the trajectories.

  1. SGD’s stability limit is 2/κ2/\kappa. With κ=30\kappa=30 the learning rate must stay below 2/30≈0.0672/30\approx0.067: at 0.063 the loss after 100 steps is 1.7×10−51.7\times10^{-5}, and at 0.071 it diverges to 4.7×10114.7\times10^{11}.
  2. RMSProp and Adam are insensitive to gradient scale. Without noise, stretching κ\kappa from 1 to 100 barely changes their trajectories (positions differ by less than 10−710^{-7}, because of ϵ\epsilon). At a learning rate of 0.05, κ=100\kappa=100 exceeds SGD’s stability limit of 2/100=0.022/100=0.02, so SGD and momentum SGD both diverge while RMSProp and Adam descend as usual. This is why the layers of a Transformer can have very different gradient scales and still train with a single learning rate.
  3. Adam’s step is about the size of the learning rate and does not shrink on its own as it nears the bottom. The Adam paper notes that its effective step is roughly bounded by the learning rate. So with the default setup (κ=30\kappa=30, learning rate 0.05, 100 steps) Adam’s loss is still 0.113, the largest of the four optimizers, against 2.8×10−42.8\times10^{-4} for SGD and 1.8×10−51.8\times10^{-5} for RMSProp. Only after stretching to 300 steps does Adam fall to 3.3×10−123.3\times10^{-12}. To converge more cleanly at the end of training you have to lower the learning rate, which leads into the next section.

Learning-rate schedules: warmup and decay

Warmup. At the start of training the second moment vtv_t has accumulated only a few steps of gradients and is a poor estimate, so using the peak learning rate right away risks a step that is far too large. The learning rate therefore rises linearly from near 0 to the peak, typically over a few hundred to a few thousand steps (2,000 for Llama 2 and 8,000 for Llama 3 405B). On why warmup works, one explanation from Liu et al. (2019) is that the variance of the adaptive learning rate is too large early in training, and warmup reduces that variance.

Decay. The peak learning rate lets the loss fall quickly, but a large step also makes the parameters bounce around near the bottom of the valley. Lowering the learning rate late in training produces a visible drop in the loss. The most common choice is cosine decay (all three models in the table use it, ending at 10%, 10% and 1% of the peak). Another is WSD (Warmup-Stable-Decay, Hu et al., 2024), proposed with MiniCPM: after warmup the learning rate stays at the peak and decays only in a final stretch. Its advantage is that you do not have to decide the total number of steps in advance: from any checkpoint in the stable phase, a short decay yields a finished model, which suits continued training and domain adaptation. MiniCPM observed on a 0.036B model that the loss drops quickly once the decay phase starts, soon reaching the same level as, or lower than, a cosine schedule matched to the total step count.

Hands-on: compare four schedules

  1. Cosine and linear decay have the same average learning rate. With 20,000 total steps, 1,000 warmup steps and an end point of 10% of the peak, both average 0.548 times the peak over the whole run. The difference is that cosine is still at 0.905 at the 25% mark while linear is only at 0.811: cosine is higher early and falls faster later.
  2. WSD has the largest “learning budget”. With the same settings, WSD (decaying over the last 20%) averages 0.885 over the whole run, about 1.6 times cosine (0.885/0.548≈1.620.885/0.548\approx1.62), because it spends most of the time at the peak learning rate.
  3. Inverse-square-root decay never reaches an end point. The original Transformer paper used it. At 25%, 50% and 75% of training it is 0.447, 0.316 and 0.258, and at the last step it is still 0.224. The WSD decay stage in the widget is linear; the original paper only requires the decay function to be monotonically decreasing.

Mixed precision: why keep FP32

Training often uses a 16-bit format for the forward and backward passes to save memory and bandwidth (this page covers the recipe; how the formats spend their bits and the three ways they fail are analyzed in Numerical Precision), but the numeric formats differ a lot:

FormatExponent / mantissa bitsMax valueSmallest normalMachine epsilon
FP328 / 233.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}1.2×10−71.2\times10^{-7}
FP165 / 10655046.1×10−56.1\times10^{-5}9.8×10−49.8\times10^{-4}
BF168 / 73.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}7.8×10−37.8\times10^{-3}

(Values are from torch.finfo.)

  • FP16 has a narrow range and needs loss scaling. Small gradients (below about 6×10−56\times10^{-5}) underflow to 0, so the loss is multiplied by a large factor before the backward pass and the gradients are scaled back before the update (Micikevicius et al., 2017).
  • BF16 has the same range as FP32 and usually needs no loss scaling, but it is less precise, with only about 2–3 significant decimal digits.
  • The optimizer needs FP32 master weights. The update, the learning rate times the gradient, is often far smaller than the parameter itself and would be rounded away when added to a 16-bit parameter. The mainstream recipe therefore keeps an FP32 master copy of the weights plus FP32 mm and vv, and uses BF16 for the forward and backward passes. The Llama 3 report also mentions that gradients are accumulated in FP32 across micro-batches and that the reduce-scatter in data parallelism also runs in FP32, to keep training convergent.

This gives the model state per parameter: BF16 weights 2 bytes + BF16 gradients 2 bytes + FP32 master weights 4 bytes + FP32 mm 4 bytes + FP32 vv 4 bytes, 16 bytes in total. For a 7B model that alone is 112 GB (about 104 GiB). How ZeRO shards this state across GPUs, together with activations and the rest of the memory ledger, is worked out in The Compute and Memory Ledger of Training.

Gradient clipping and loss spikes

Gradient clipping. Compute the global L2L_2 norm ∥g∥\lVert g\rVert of all parameter gradients concatenated, and if it exceeds a threshold cc, scale everything down together:

g←g⋅min⁡ ⁣(1, c∥g∥)g \leftarrow g\cdot\min\!\Big(1,\ \frac{c}{\lVert g\rVert}\Big)

GPT-3, Llama 2 and PaLM all set cc to 1.0. It caps the largest single step that an abnormal batch can cause.

Loss spikes. Even with gradient clipping, large-model training still sees sudden spikes in the loss. The largest PaLM model had about 20 spikes during training, at irregular intervals, while the smaller models had none. The team’s remedy was to restart from a checkpoint about 100 steps before the spike began and skip roughly 200–500 batches, after which the spike did not reappear at the same place. Their ablations showed that training on the data around a spike from an earlier checkpoint did not trigger a spike, so the problem is not the “bad data” itself but the combination of particular data with a particular parameter state. PaLM also added an auxiliary loss 10−4⋅log⁡2Z10^{-4}\cdot\log^2 Z (ZZ is the softmax normalizer) to keep log⁡Z\log Z close to 0, which they found improved training stability. By contrast, the Llama 3 report says its 405B pretraining was stable, with no non-trivial loss spikes and no need to intervene to correct training divergences.

The table below turns the common symptoms into a troubleshooting order:

SymptomCommon causesWhat to do first
Loss spikes suddenly, then slowly recoversA particular batch combined with the current parameter state; learning rate too high; vv lagging behind a change in gradientsCheck that gradient clipping is in effect; lower β2\beta_2 (for example to 0.95); roll back to a checkpoint before the spike and skip the batches involved
Loss becomes NaN or InfFP16 overflow or underflow; division by zero; bad samplesSwitch to BF16 or enable loss scaling; check ϵ\epsilon; use anomaly detection to find the first layer that produces NaN
Gradient norm keeps risingLearning rate too high; warmup too short; sudden shift in the data distributionLower the peak learning rate and lengthen warmup, while monitoring the gradient norm and how often clipping triggers
Loss stops fallingLearning rate decayed too early; batch too small; repeated dataCompare against the learning-rate curve; check for repeated data or a drop in data quality

Hands-on code

The code below puts AdamW, linear warmup with cosine decay, and gradient clipping into a minimal PyTorch training loop:

import math

import torch

torch.manual_seed(0)
model = torch.nn.Linear(16, 1)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)

warmup, total, floor = 100, 1000, 0.1


def lr_scale(step: int) -> float:
    if step < warmup:  # linear warmup
        return (step + 1) / warmup
    progress = (step - warmup) / (total - 1 - warmup)  # cosine decay to 10% of the peak
    return floor + (1 - floor) * 0.5 * (1 + math.cos(math.pi * progress))


sched = torch.optim.lr_scheduler.LambdaLR(opt, lr_scale)
x = torch.randn(256, 16)
y = x @ torch.randn(16, 1)

for step in range(total):
    loss = torch.nn.functional.mse_loss(model(x), y)
    opt.zero_grad()
    loss.backward()
    grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)  # returns the global norm before clipping
    lr = opt.param_groups[0]["lr"]
    opt.step()
    sched.step()
    if step in (0, 99, 100, 500, 999):
        print(f"step {step:3d}  lr {lr:.2e}  grad_norm {grad_norm:.3f}  loss {loss.item():.4f}")

Output:

step   0  lr 3.00e-06  grad_norm 7.770  loss 16.4080
step  99  lr 3.00e-04  grad_norm 7.666  loss 16.0073
step 100  lr 3.00e-04  grad_norm 7.664  loss 15.9993
step 500  lr 1.88e-04  grad_norm 6.959  loss 13.4174
step 999  lr 3.00e-05  grad_norm 6.674  loss 12.4340

The learning rate reaches its peak of 3×10−43\times10^{-4} at step 99 and falls to 10% of the peak at the last step. clip_grad_norm_ returns the norm before clipping. The gradient norm of this toy problem stays above 1, so every step is scaled down to 1.

Summary and exercises

Key points:

  1. Adam-style optimizers scale each parameter’s step by the second moment of its gradient and are insensitive to gradient scale. AdamW decouples weight decay from the gradient update.
  2. The learning rate warms up linearly and then decays to about 10% of the peak. WSD puts the decay in a final stretch, so the total number of steps need not be fixed in advance.
  3. The model state in mixed-precision training is 16 bytes per parameter. BF16 has the same range as FP32 and generally needs no loss scaling.
  4. Gradient clipping caps the largest single update. Loss spikes are handled with checkpoint rollback, a lower β2\beta_2, auxiliary losses and similar measures.

Quick self-check

1. What is the key difference between Adam and SGD?

  • It does not need to compute gradients
  • It scales each parameter’s step by that parameter’s own second-moment estimate of the gradient
  • It guarantees that the loss decreases monotonically
  • It can only be used with Transformers

Adam’s denominator v^t+ϵ\sqrt{\hat v_t}+\epsilon is separate for every parameter, which shrinks the step of parameters with large gradients. This makes it insensitive to gradient scale, but it does not guarantee a monotonically decreasing loss.

2. Why use AdamW instead of Adam with an L2 penalty added to the loss?

  • Because AdamW does not need a learning rate
  • Because L2 regularization turns model parameters into integers
  • Because in an adaptive optimizer the gradient of the L2 term is also scaled by the second moment, so the decay strength varies by parameter, while AdamW applies the decay to the parameters separately and is not affected by the scaling
  • Because AdamW uses less memory

In SGD, L2 regularization and weight decay are equivalent, but in Adam they are not. AdamW uses the same memory as Adam, since both store mm and vv.

3. Which of the following statements about learning-rate warmup are correct? (select all that apply)

  • Early in training the second-moment estimate is noisy, so warmup raises the step size gradually from a small value
  • Llama 2 used 2,000 steps of linear warmup
  • The longer the warmup, the better
  • Warmup only helps SGD and does nothing for Adam

Warmup is motivated precisely by the early-stage instability of Adam-style optimizers. An overly long warmup wastes training budget, and there is no “longer is better” rule.

4. Why does BF16 usually not need loss scaling the way FP16 does?

  • Because BF16 has a longer mantissa
  • Because BF16 has the same number of exponent bits as FP32, so its range is just as large and gradients rarely underflow
  • Because BF16 uses less memory
  • Because BF16 produces no rounding error

BF16 has 8 exponent bits and 7 mantissa bits: the same range as FP32 but lower precision. FP16 has only 5 exponent bits and a maximum of 65504, so small gradients underflow easily.

Exercises:

  1. For a cosine schedule with 2,000 warmup steps, 100,000 total steps and an end point at 10% of the peak, what fraction of the peak is the learning rate at step 51,000?
  2. For κ=30\kappa=30, what is the largest learning rate at which SGD is stable? Check your answer with the optimizer lab.
  3. With AdamW and BF16 mixed-precision training, how much memory does the model state (weights, gradients, master weights, mm, vv) of a 70B model need?
Reference answers
  1. The cosine progress is (51000−2000)/(100000−1−2000)≈0.5(51000-2000)/(100000-1-2000)\approx0.5, so the fraction is 0.1+0.9×12(1+cos⁡π2)≈0.550.1+0.9\times\tfrac12(1+\cos\tfrac{\pi}{2})\approx0.55.
  2. 2/κ=2/30≈0.0672/\kappa=2/30\approx0.067: 0.06 converges and 0.07 diverges.
  3. 16×70×109=1.12×101216\times70\times10^9=1.12\times10^{12} bytes, about 1.12 TB (about 1043 GiB), not counting activations.

Further reading

FAQ

Why do large models train with AdamW instead of SGD?
The gradients of different Transformer weight matrices differ widely in scale. Adam-style optimizers scale each parameter's step by that parameter's own second-moment estimate, so they are insensitive to gradient scale and the learning rate is easier to tune. For SGD the largest stable learning rate is set by the steepest direction, which is hard to balance on a long, narrow loss surface. AdamW also decouples weight decay from the gradient update. The Llama 2 and Llama 3 reports both use AdamW, and GPT-3 used Adam with a weight decay of 0.1 and cited the AdamW paper.
What is the difference between AdamW and Adam with L2 regularization?
When an L2 penalty is added to the loss in Adam, the gradient of the penalty is scaled by the second moment as well, so different parameters are decayed by different amounts and the best decay coefficient is coupled to the learning rate. AdamW applies weight decay as a separate step directly on the parameters, bypassing the adaptive scaling, so the decay coefficient and the learning rate can be tuned independently (Loshchilov and Hutter, 2017).
What is learning-rate warmup for?
At the start of training, Adam's second-moment estimate has accumulated only a few steps of gradients and is very noisy. Warmup raises the step size gradually from a tiny value to the peak, which avoids a huge first step. There is no standard length. Llama 2 used 2,000 steps of linear warmup and Llama 3 405B used 8,000.
How do cosine decay and the WSD schedule differ?
Cosine decay needs the total number of steps in advance and the learning rate falls all the way, so a checkpoint saved midway still has a high learning rate and a higher loss. WSD (warmup-stable-decay) keeps the learning rate at its peak during the stable phase and decays only in a final stretch, so you can branch from any stable-phase checkpoint and run a short decay to get a finished model, which suits continued training. In MiniCPM's experiments on a 0.036B model, the loss in the decay phase quickly fell to the same level as, or lower than, a cosine schedule matched to the total step count.
Why is BF16 recommended over FP16 for mixed precision training?
BF16 has the same 8 exponent bits as FP32, so its range is just as large (a maximum of about 3.4e38) and gradients rarely overflow or underflow, which usually makes loss scaling unnecessary. FP16 has a maximum of only 65504, and small gradients underflow to 0, so it needs loss scaling. BF16 has only 7 mantissa bits and is less precise, which is why optimizer states and master weights are still kept in FP32.