Transformer Training Explained
← /training

Chapter 5 of 16

Optimisers

SGD, momentum, Adam and AdamW, on a valley and on the real model.

Check yourself ↓ three questions and what to remember, at the end

Slides for this chapter: Transformer Training 04, Optimisers

The gradient says which way is downhill; the optimiser decides how far to step, and in which direction exactly. Below, five optimisers, the same code that trains the model in chapter 1, start from the same point in a long, narrow valley.

Loading the animation…

Concept

SGD (stochastic gradient descent) steps straight downhill, by the learning rate times the gradient: the learning rate η\eta sets the size of every step, and is the most important number to tune. In a valley much steeper across than along, the learning rate must be small enough not to overshoot across the steep walls, and is then far too small for the gentle slope along the floor: SGD zig-zags and crawls. Real loss surfaces are full of such directions, with curvatures that differ by orders of magnitude.

Momentum keeps a running sum of past gradients and steps along it. Across the valley successive gradients point in opposite directions and cancel; along it they agree and add up, so the optimiser builds speed where it is useful. The running sum is the momentum buffer: one number per weight, kept from step to step as part of the optimiser's state (Adam keeps two). Methods that compress what workers exchange, such as DeMo (chapter 13), work on this buffer rather than on a single step's gradient.

Nesterov momentum changes one thing: where the gradient is measured. Heavy-ball momentum, the kind above, takes the slope where the weights are and adds it to the speed it already has. Nesterov's version (Yurii Nesterov's 1983 method, brought to deep learning by Sutskever et al. 2013) first lets momentum carry the weights to where they are about to go, takes the slope there, and corrects from it. When momentum is about to carry the weights past the bottom of the valley, the slope at that look-ahead point already points back, so the brake arrives a step early: it damps the swing instead of feeding it. In the race (the dashed line) Nesterov runs at momentum's own learning rate and momentum, so the two differ only in where the gradient is taken. Along the floor it overshoots the minimum by 0.060 against momentum's 0.133, and its loss is below 10⁻³ from step 26 (momentum: step 49). Across the steep direction both swing past the floor once, by the same 2.0; Nesterov's swing is its first step, and at step 2 its error across the valley is 0.0 (exactly, because the learning rate times the steep curvature, 0.02 × 50, is 1 here), while momentum's is 2.0 and it keeps swinging. In PyTorch Nesterov is one flag, torch.optim.SGD(params, lr, momentum=0.9, nesterov=True), and it is the outer optimiser of DiLoCo (chapter 13).

Adam (Kingma & Ba 2014) keeps two running averages for every single weight: mm, of the gradient (momentum), and vv, of its square (how large that weight's gradients usually are). It steps by m/vm/\sqrt v, so each coordinate moves by roughly the learning rate whatever the scale of its gradient: the steep direction and the gentle one get similar step sizes. The numbers under the picture are Adam's mm and vv for xx and yy; vv for yy is far larger, because the valley is steeper in yy. The bias correction divides by 1−βt1 - \beta^t because mm and vv start at zero and would otherwise be too small for the first steps. Near the minimum, a constant-learning-rate Adam keeps taking steps of about the learning rate and jitters around it: this is one reason runs decay their learning rate at the end (chapter 6).

AdamW (Loshchilov & Hutter 2017) adds weight decay the direct way: each step first shrinks every weight by a factor 1−ηλ1-\eta\lambda. With plain Adam, adding the decay λθ\lambda\theta to the gradient (an L2 penalty) puts it through the 1/v1/\sqrt v rescaling, so weights with large gradients are barely decayed at all; decoupling it makes the decay the same for every weight. In the valley the decay pulls AdamW's end point towards the origin, away from the minimum of the loss alone: weight decay is a preference for small weights, traded against the loss. Here λ\lambda is set very high so that you can see it; in the default run it is 0.01, and it is applied only to the weight matrices, not to LayerNorm's γ,β\gamma, \beta or the biases.

On the real model. The chart below trains the Decoder's model with each of the four other optimisers (Nesterov is in the race and the PyTorch check, not in this comparison) at the best of three constant learning rates, 1,500 steps, three data seeds each (results.md §5). At their best rates the four end close together: Adam 2.185 ± 0.041, momentum 2.213 ± 0.008, AdamW 2.230 ± 0.041, SGD 2.241 ± 0.034 (mean ± standard deviation over the seeds). Those differences are about one standard deviation: at this scale the data say no more than that all four work. The learning rate matters far more: SGD at 0.1 instead of 1.0 ends at 2.897, still on the plateau. Single runs are not enough here: at the higher learning rates training is chaotic, and recomputing the same run on another computer moved its final loss by about 0.1. Comparing optimisers fairly means tuning each one's learning rate and repeating over seeds (chapter 6). For large language models AdamW is the usual choice: Llama 3 405B, for example, was pretrained with it (Grattafiori et al. 2024, §3.4.1).

validation loss22.533.54050010001500step (validation loss every 100 steps)
SGD (lr 1): 2.241 ± 0.034 · Momentum (lr 0.1): 2.213 ± 0.008 · Adam (lr 0.01): 2.185 ± 0.041 · AdamW (lr 0.01): 2.230 ± 0.041.Mean over three data seeds (± their standard deviation) at each optimiser’s best of three constant learning rates, 1,500 steps; results.md §5.

Newer optimisers, for context rather than measured here: Lion keeps only the sign of a momentum (Chen et al. 2023); Shampoo (Gupta et al. 2018) and SOAP (Vyas et al. 2024) precondition each weight matrix with its gradient's row and column statistics instead of per-weight scales; Muon orthogonalises each matrix's momentum update (Liu et al. 2025 report it at scale).

Maths

For a weight θ\theta with gradient gtg_t at step tt (all operations element by element):

SGD:θt=θt−1−η gtmomentum:bt=μ bt−1+gt,  b1=g1;θt=θt−1−η btNesterov (look-ahead):bt=μ bt−1+∇f(θt−1−ημ bt−1),  b0=0;θt=θt−1−η btNesterov (as PyTorch):bt=μ bt−1+gt,  b1=g1;ϕt=ϕt−1−η (gt+μ bt),  gt=∇f(ϕt−1)Adam:mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2θt=θt−1−η m^t/(v^t+ϵ),m^t=mt/(1−β1t), v^t=vt/(1−β2t)Adam + L2:gt←gt+λ θt−1 first (coupled)AdamW:θt−1←(1−ηλ) θt−1 first (decoupled)\begin{aligned} &\text{SGD:} && \theta_t = \theta_{t-1} - \eta\, g_t \\ &\text{momentum:} && b_t = \mu\, b_{t-1} + g_t,\ \ b_1 = g_1; \quad \theta_t = \theta_{t-1} - \eta\, b_t \\ &\text{Nesterov (look-ahead):} && b_t = \mu\, b_{t-1} + \nabla f\big(\theta_{t-1} - \eta\mu\, b_{t-1}\big),\ \ b_0 = 0; \quad \theta_t = \theta_{t-1} - \eta\, b_t \\ &\text{Nesterov (as PyTorch):} && b_t = \mu\, b_{t-1} + g_t,\ \ b_1 = g_1; \quad \phi_t = \phi_{t-1} - \eta\,(g_t + \mu\, b_t),\ \ g_t = \nabla f(\phi_{t-1}) \\ &\text{Adam:} && m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t,\quad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2 \\ & && \theta_t = \theta_{t-1} - \eta\, \hat m_t / (\sqrt{\hat v_t} + \epsilon),\quad \hat m_t = m_t/(1-\beta_1^t),\ \hat v_t = v_t/(1-\beta_2^t) \\ &\text{Adam + L2:} && g_t \leftarrow g_t + \lambda\, \theta_{t-1} \text{ first (coupled)} \\ &\text{AdamW:} && \theta_{t-1} \leftarrow (1 - \eta\lambda)\,\theta_{t-1} \text{ first (decoupled)} \end{aligned}

Heavy-ball momentum and Nesterov side by side: both keep bb, the running sum of gradients, and both step by ηbt\eta b_t; heavy-ball's gradient gtg_t is taken at the weights, ∇f(θt−1)\nabla f(\theta_{t-1}), Nesterov's at the look-ahead point θt−1−ημ bt−1\theta_{t-1} - \eta\mu\, b_{t-1}, where momentum alone would carry them. The third line is the "lookahead-free" form that frameworks implement: it stores ϕ=θ−ημ b\phi = \theta - \eta\mu\, b, the look-ahead point itself, so every gradient is taken at the stored weights and no second forward pass is needed. Substituting, ϕt−ϕt−1=−η bt−ημ (bt−bt−1)=−η (bt−μbt−1)−ημ bt=−η (gt+μ bt)\phi_t - \phi_{t-1} = -\eta\, b_t - \eta\mu\,(b_t - b_{t-1}) = -\eta\,(b_t - \mu b_{t-1}) - \eta\mu\, b_t = -\eta\,(g_t + \mu\, b_t), using bt−μbt−1=gtb_t - \mu b_{t-1} = g_t. This is torch.optim.SGD(momentum=μ, nesterov=True) (PyTorch docs). The reference checks both claims over the race's 60 steps: the two Nesterov forms agree to 4.4 × 10⁻¹⁶, and ours equals PyTorch's, stepping on its own autograd gradient, to 0.0 (largest difference); on the model, over 25 steps, to 0.0.

Defaults: μ=0.9\mu = 0.9, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 (0.99 in the default run), ϵ=10−8\epsilon = 10^{-8}. The valley is f(x,y)=12((x−2)2+50(y−1)2)f(x, y) = \tfrac12\big((x-2)^2 + 50(y-1)^2\big): SGD is stable only for η<2/50\eta < 2/50, and then its error along xx shrinks by a factor 1−η1 - \eta per step. These are PyTorch's definitions: each optimiser is checked against torch.optim over 25 steps on the model (largest difference 1.1 × 10⁻¹⁶ for AdamW).

Code

The Adam/AdamW update for one row of a weight, src/lib/training/optimizers.ts:

for (let j = 0; j < row.length; j++) {
  let pj = row[j]!;
  let gj = g[j]!;
  if (o.kind === "adamw") pj = pj * (1 - lr * wd);
  else if (wd) gj = gj + wd * pj;
  m[j] = o.beta1 * m[j]! + (1 - o.beta1) * gj;
  v[j] = o.beta2 * v[j]! + (1 - o.beta2) * gj * gj;
  const mhat = m[j]! / bc1;
  const vhat = v[j]! / bc2;
  row[j] = pj - (lr * mhat) / (Math.sqrt(vhat) + o.eps);
}

Momentum and Nesterov, from the same file: one buffer b, and Nesterov adds the fresh gradient once more on top of it:

b[j] = t === 1 ? g[j]! : o.momentum * b[j]! + g[j]!;
row[j] =
  o.kind === "nesterov"
    ? row[j]! - lr * (g[j]! + o.momentum * b[j]!)
    : row[j]! - lr * b[j]!;

The two moment buffers are why Adam needs two extra numbers per weight: with FP32 master weights and gradients, this is where the "16 bytes per parameter" of mixed-precision training comes from (chapter 10).

Check yourself

Commit to an answer before you reveal it: a wrong guess you can explain teaches more than a right one you skimmed. Every number in the answers comes from the same tested model as the chapter’s.

Q1In the race, momentum and Nesterov run at the same learning rate and momentum. Which overshoots the minimum less along the valley floor?
Reveal the answer

Answer: Nesterov momentum

Nesterov, by 0.060 against heavy-ball's 0.133: it takes the gradient where momentum is about to carry the weights, sees the slope turn before they pass the bottom, and brakes a step early.

Nesterov momentum →

Pick one, then reveal.

Q2Plain SGD in this valley (curvature 1 along it, 50 across it) is stable only below what learning rate?
Reveal the answer

Answer: 0.04 (counted right within ± 0.005)

2/50=2/50 = 0.04: above it, every step across the steep direction overshoots by more than it corrects. The race's SGD runs just under, at 0.036, and so crawls along the shallow direction.

SGD →

Commit to a number, then reveal.

Q3On the real model, each at its best of three learning rates over three seeds, how do SGD, momentum, Adam and AdamW compare?
Reveal the answer

Answer: They end within about one standard deviation of each other

Close together: Adam 2.185 ± 0.041, SGD 2.241 ± 0.034. At this scale the learning rate matters far more than the optimiser, which is why each one must be tuned before comparing.

On the real model →

Pick one, then reveal.

Comments

Be the first to leave a comment on this section.

Sign in (top-right) to leave a comment.