Skip to content
Deep learning Core 31 min read

Optimisers: SGD, momentum, Adam, AdamW and schedules

Backpropagation tells you which way is downhill; the optimiser decides how far to step, how much to trust the last few gradients, and how to rescale each parameter. Almost every modern network is trained with the same few lines — AdamW plus warm-up and decay — and this page shows exactly why each line is there.

10,000 ft

Training a network means minimising a loss over millions to trillions of parameters, using only noisy gradient estimates from small batches of data. The loss is not convex, it is badly conditioned (steep in some directions, nearly flat in others), and the gradient is a random variable. The optimiser is the algorithm that turns that noisy gradient into a parameter update. It sits between backpropagation (which supplies the gradient) and everything about training quality and cost: how big a learning rate you can use, how large a batch, how many GPU-hours, how much memory per parameter (optimiser state is most of it), and even how well the model generalises (weight decay lives here). The family tree is short: stochastic gradient descent, plus momentum, plus per-parameter scaling (Adam), plus decoupled weight decay (AdamW), wrapped in a learning-rate schedule.

2,000 ft

One optimiser step, in the order a modern trainer does it:

  1. Estimate the gradient \(\mathbf{g}_t\) on a mini-batch (noisy, unbiased).
  2. Clip it if its global norm exceeds a threshold (guards against rare spikes).
  3. Smooth it in time — momentum keeps an exponential moving average \(\mathbf{m}_t\) so consistent directions accumulate and oscillating ones cancel.
  4. Rescale per coordinate — Adam also tracks the average squared gradient \(\mathbf{v}_t\) and divides by \(\sqrt{\mathbf{v}_t}\), so every parameter moves at roughly the same speed whatever its gradient scale.
  5. Pick today's step size from a schedule: warm up from near zero, then decay.
  6. Shrink the weights a little (decoupled weight decay) and apply the update.

The optimiser family tree
The optimiser family tree. SGD (Robbins–Monro 1951), Momentum (Polyak 1964), Nesterov momentum, AdaGrad (2011), RMSProp (2012), Adam (2014), AdamW (2017), Lion, Shampoo/SOAP, Muon, schedule-free, average gradients in time, look ahead, scale per parameter, forget old gradients, + momentum, bias correction, decouple weight decay, change the geometryThe optimiser family tree. SGD (Robbins–Monro 1951), Momentum (Polyak 1964), Nesterov momentum, AdaGrad (2011), RMSProp (2012), Adam (2014), AdamW (2017), Lion, Shampoo/SOAP, Muon, schedule-free, average gradients in time, look ahead, scale per parameter, forget old gradients, + momentum, bias correction, decouple weight decay, change the geometry

Ground level

Stochastic gradient descent and why the noise is fine

The loss of a network is an average over training examples, \(L(\boldsymbol\theta) = \frac{1}{N}\sum_{i=1}^N \ell(\boldsymbol\theta; x_i, y_i)\). Its exact gradient needs a pass over all \(N\) examples. Stochastic gradient descent (SGD) instead samples a mini-batch \(B\) of \(|B|\) examples and uses

\[ \mathbf{g}_t = \frac{1}{|B|}\sum_{i\in B}\nabla_{\boldsymbol\theta}\,\ell(\boldsymbol\theta_t; x_i, y_i), \qquad \boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta\,\mathbf{g}_t . \]

Because the batch is sampled at random, \(\mathbb{E}[\mathbf{g}_t] = \nabla L(\boldsymbol\theta_t)\): the estimate is unbiased. Its covariance shrinks like \(1/|B|\), so the standard deviation of the noise shrinks only like \(1/\sqrt{|B|}\). Doubling the batch doubles the compute per step but removes only ~29% of the noise. That asymmetry is why mini-batches of a few hundred to a few million tokens win over full-batch gradient descent: early in training, a cheap, rough direction is worth far more than an exact one. Robbins and Monro proved in 1951 that such stochastic updates converge if the step sizes satisfy \(\sum_t \eta_t = \infty\) and \(\sum_t \eta_t^2 < \infty\) — the first condition lets you travel arbitrarily far, the second makes the noise die out. Every learning-rate decay schedule you will meet is a practical descendant of that second condition.

The learning rate and the stability limit

The single most important hyperparameter is \(\eta\). To see what sets its scale, look at the simplest non-trivial loss, a quadratic bowl \(L(\mathbf{w}) = \tfrac12 \mathbf{w}^\top H \mathbf{w}\) whose Hessian \(H\) has eigenvalues \(\lambda_1 \ge \dots \ge \lambda_d > 0\). In the eigenbasis each coordinate evolves independently:

\[ w_i^{(t+1)} = w_i^{(t)} - \eta\lambda_i w_i^{(t)} = (1-\eta\lambda_i)\,w_i^{(t)} . \]

Each coordinate is multiplied by \((1-\eta\lambda_i)\) every step. It shrinks only if \(|1-\eta\lambda_i| < 1\), i.e. \(\eta < 2/\lambda_i\). The steepest direction sets the ceiling: \(\eta < 2/\lambda_{\max}\), or training diverges. Meanwhile the flattest direction shrinks by only \((1-\eta\lambda_{\min})\) per step. With the largest legal step, that factor is about \(1 - 2/\kappa\), where \(\kappa = \lambda_{\max}/\lambda_{\min}\) is the condition number. Gradient descent needs on the order of \(\kappa\) steps to make progress along the flat directions.

Worked example: a bowl with condition number 100

Take \(L = \tfrac12(w_1^2 + 100\,w_2^2)\), so \(\lambda = (1, 100)\) and \(\kappa = 100\), starting at \((1, 1)\). The ceiling is \(\eta < 2/100 = 0.02\).

  • At \(\eta = 0.019\) the steep coordinate is multiplied by \(1 - 1.9 = -0.9\) each step: it flips sign and shrinks (the zig-zag). The flat one is multiplied by \(0.981\). To push the loss below \(10^{-6}\) you need \(|w_1| < 1.41\times10^{-3}\), i.e. \(\ln(1.41\times10^{-3})/\ln 0.981 \approx 342\) steps. The code below measures 343.
  • At \(\eta = 0.021\) the steep coordinate is multiplied by \(-1.1\): after 2,000 steps the loss is \(1.9\times10^{167}\). A 10% change in learning rate is the difference between converging and exploding.

Real networks have \(\kappa\) in the thousands or worse, and the Hessian changes as you train. Everything below is a way of beating the \(\kappa\)-step tax.

Real networks add a twist. Cohen et al. (2021) found that with full-batch gradient descent the largest Hessian eigenvalue (the sharpness) climbs during training until it reaches \(2/\eta\), then hovers there while the loss keeps falling non-monotonically — the "edge of stability". The network adapts its own curvature to the step size you chose. The quadratic picture tells you the right scale for \(\eta\); it does not tell you the whole dynamics.

Momentum: averaging away the zig-zag

Polyak's heavy-ball method (1964) keeps a velocity — a running sum of past gradients:

\[ \mathbf{v}_{t} = \beta\,\mathbf{v}_{t-1} + \mathbf{g}_t,\qquad \boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta\,\mathbf{v}_t . \]

Two things happen. In a direction where the gradient keeps the same sign, the velocity grows to \(\mathbf{g}/(1-\beta)\): with \(\beta = 0.9\) the effective learning rate along consistent directions is \(10\eta\). In a direction where the gradient alternates sign (the steep walls of the valley), successive terms cancel and the velocity stays small. Momentum is a low-pass filter on the gradient sequence.

▬ gradient descent, η = 0.18▬ momentum, η = 0.06, β = 0.625 steps each from the black dot on f = ½(x² + 10y²); green dot = minimum
Real iterates, not a sketch. On an elongated bowl, plain gradient descent spends its steps bouncing across the steep direction; momentum averages the bounces away and accelerates along the shallow one. After 25 steps GD's loss is 3.3×10⁻⁵, momentum's 1.8×10⁻⁶.

For a quadratic, the best heavy-ball settings are known in closed form (derived in The maths): \(\eta^\star = 4/(\sqrt{\lambda_{\max}}+\sqrt{\lambda_{\min}})^2\) and \(\beta^\star = \big((\sqrt\kappa-1)/(\sqrt\kappa+1)\big)^2\), giving a per-step contraction of \((\sqrt\kappa-1)/(\sqrt\kappa+1)\). For \(\kappa = 100\) that is \(9/11 \approx 0.82\) instead of plain GD's \(0.98\): the step count drops from order \(\kappa\) to order \(\sqrt\kappa\). On the bowl above, tuned momentum converges in 69 steps against GD's 343; the everyday setting \(\beta = 0.9,\ \eta = 0.01\) takes 138. Gabriel Goh's Distill article Why Momentum Really Works lets you drag these sliders and watch the eigen-components; it is the best visual treatment anywhere.

Nesterov momentum evaluates the gradient at the point the velocity is about to carry you to, \(\mathbf{g}_t = \nabla L(\boldsymbol\theta_t - \eta\beta\mathbf{v}_{t-1})\), so it brakes before overshooting. It has a provably better worst-case rate on smooth convex problems, and Sutskever et al. (2013) showed that momentum (classical or Nesterov) with a well-chosen schedule was enough to train deep and recurrent networks that had been thought to need second-order methods.

Per-parameter step sizes: AdaGrad, RMSProp, Adam

Momentum fixes the time axis; it does nothing for the fact that different parameters live on wildly different gradient scales. An embedding row for a rare token sees a gradient once in a thousand batches; a layer-norm gain sees one every batch. One global \(\eta\) is too big for some and too small for others.

AdaGrad (Duchi, Hazan and Singer, 2011) divides each coordinate's step by the root of the sum of all its past squared gradients: rarely-updated parameters get large steps. But the sum only grows, so the step size decays to zero — fine for convex problems, fatal for long non-convex training. RMSProp (Hinton, Coursera lecture 6e, 2012 — never formally published) swaps the sum for an exponential moving average so old gradients are forgotten. Adam (Kingma and Ba, 2014) combines RMSProp's second-moment scaling with momentum's first moment and adds a bias correction:

\[ \begin{aligned} \mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1)\,\mathbf{g}_t &&\text{(mean of } \mathbf g)\\ \mathbf{v}_t &= \beta_2 \mathbf{v}_{t-1} + (1-\beta_2)\,\mathbf{g}_t^{2} &&\text{(mean of } \mathbf g^2\text{, elementwise)}\\ \hat{\mathbf{m}}_t &= \mathbf{m}_t/(1-\beta_1^t),\quad \hat{\mathbf{v}}_t = \mathbf{v}_t/(1-\beta_2^t) &&\text{(bias correction)}\\ \boldsymbol\theta_{t+1} &= \boldsymbol\theta_t - \eta\,\hat{\mathbf{m}}_t \big/ \big(\sqrt{\hat{\mathbf{v}}_t} + \epsilon\big). \end{aligned} \]

The ratio \(\hat m/\sqrt{\hat v}\) is a signal-to-noise ratio per coordinate. If a parameter's gradient is consistent, \(\hat m \approx \sqrt{\hat v}\) and the step is about \(\eta\). If the gradient is mostly noise around zero, \(\hat m\) is small relative to \(\sqrt{\hat v}\) and the step shrinks. Crucially, the step is invariant to rescaling the gradient: multiply the loss by 1,000 and Adam's updates do not change. That is why one learning rate such as \(3\times10^{-4}\) works across very different architectures, and why Adam's \(\eta\) is best read as "roughly the largest change any single weight may make per step".

Worked example: what bias correction is for

Suppose the gradient is a constant \(g = 0.5\) and we use \(\beta_1 = 0.9\), \(\beta_2 = 0.999\), starting from \(\mathbf m_0 = \mathbf v_0 = 0\).

  • After step 1: \(m_1 = 0.1 \times 0.5 = 0.05\) and \(v_1 = 0.001 \times 0.25 = 0.00025\).
  • Uncorrected ratio: \(m_1/\sqrt{v_1} = 0.05/0.0158 = 3.16\). The first step would be 3.16× too large — exactly \((1-\beta_1)/\sqrt{1-\beta_2}\), independent of \(g\).
  • Corrected: \(\hat m_1 = 0.05/0.1 = 0.5\), \(\hat v_1 = 0.00025/0.001 = 0.25\), ratio \(= 1\).

Both moving averages start at zero and so underestimate their targets for the first \(\sim 1/(1-\beta)\) steps — 10 steps for \(\beta_1\), 1,000 for \(\beta_2\). Dividing by \(1-\beta^t\) removes the bias exactly when the gradient statistics are stationary. And notice: at step 1, Adam's update is \(\eta\cdot\operatorname{sign}(g)\) for any \(g\). Adam starts life as sign descent.

On the \(\kappa = 100\) bowl, Adam with \(\eta = 0.1\) converges in 82 steps without knowing the curvature at all, because the per-coordinate normalisation equalises the two directions (it is axis-aligned here, which flatters Adam; a rotated bowl would not be equalised by a diagonal rescaling).

AdamW: weight decay is not L2 regularisation (for Adam)

With plain SGD, adding an L2 penalty \(\tfrac{\lambda}{2}\|\boldsymbol\theta\|^2\) to the loss and "decaying" weights by \(\boldsymbol\theta \leftarrow (1-\eta\lambda)\boldsymbol\theta\) each step are the same thing: the penalty's gradient \(\lambda\boldsymbol\theta\) gets multiplied by \(\eta\) either way. Loshchilov and Hutter (2017) pointed out that with Adam they are not the same. The L2 gradient \(\lambda\boldsymbol\theta\) is added to \(\mathbf g\) and then divided by \(\sqrt{\hat{\mathbf v}}\) — so parameters with large gradient variance are regularised less.

Worked example: two weights, same value, different gradient scales

Two weights both equal 1; L2 coefficient \(\lambda = 0.01\). Weight A has gradients of typical size 1 (\(\sqrt{\hat v} \approx 1\)); weight B has gradients of size 0.01 (\(\sqrt{\hat v} \approx 0.01\), ignoring the small L2 contribution).

  • Adam + L2: the decay part of each step is \(\eta\lambda w/\sqrt{\hat v}\). A gets \(\eta \times 0.01\); B gets \(\eta \times 1\). B is decayed 100× harder than A.
  • AdamW: the decay is applied outside the adaptive scaling, \(\boldsymbol\theta \leftarrow \boldsymbol\theta - \eta\lambda\boldsymbol\theta\), so both shrink by \(\eta\times 0.01\) per step — exactly what "weight decay" promises.

AdamW's update is

\[ \boldsymbol\theta_{t+1} = \boldsymbol\theta_t - \eta_t\Big(\hat{\mathbf m}_t/(\sqrt{\hat{\mathbf v}_t}+\epsilon) + \lambda\boldsymbol\theta_t\Big), \]

and the paper showed it both generalised better and made the best \(\lambda\) far less coupled to the best \(\eta\). It is now the default almost everywhere: LLaMA (Touvron et al., 2023) used AdamW with \(\beta_1 = 0.9\), \(\beta_2 = 0.95\), weight decay 0.1, gradient clipping at 1.0, 2,000 warm-up steps and cosine decay to 10% of the peak learning rate (\(3\times10^{-4}\) for the 7B and 13B models). Note that PyTorch multiplies the decay by the current learning rate, so a schedule that lowers \(\eta\) also lowers the effective decay. Regularisation covers what weight decay actually does to a network with normalisation layers (mostly: it controls the effective learning rate).

Learning-rate schedules

A constant learning rate is almost never best. Two phases matter.

Warm-up. At step 0 the weights are random, the gradients can be large and the Adam second-moment estimate is built from a handful of samples. A large step here can push the network into a region it never recovers from (dead units, exploding logits, a loss spike). Linear warm-up over the first few hundred to few thousand steps avoids this. Goyal et al. (2017) made warm-up famous when they trained ResNet-50 on ImageNet with batch 8,192 in one hour: they scaled the learning rate linearly with batch size (the linear scaling rule: \(\eta = 0.1 \times B/256\)) and needed a 5-epoch gradual warm-up for the large rate to be stable.

Decay. Late in training, the gradient noise keeps the parameters bouncing around a basin at a "temperature" proportional to \(\eta\). Lowering \(\eta\) lets them settle into the bottom; the loss typically drops sharply during the decay. Standard shapes:

Schedule Formula (after warm-up, progress \(s = t/T \in [0,1]\)) Where you see it
Step multiply by 0.1 at fixed epochs (e.g. 30, 60, 90) classic ResNet/ImageNet
Cosine \(\eta_{\min} + \tfrac12(\eta_{\max}-\eta_{\min})(1+\cos\pi s)\) most LLM pre-training (SGDR, 2016)
Linear to zero \(\eta_{\max}(1-s)\) BERT-era fine-tuning, many recent runs
One-cycle warm up for ~30%, anneal to ~0 fast vision training (Smith, 2017)
Warm-up–stable–decay (WSD) constant \(\eta_{\max}\), then a short final decay (~10–20%) MiniCPM (2024); lets you branch checkpoints at any length

Cosine's weakness is that you must fix \(T\) in advance: stopping early leaves you at a high learning rate with an un-annealed model. WSD keeps a constant rate and decays only at the end, so one long run can be "cooled" at several points; Hägele et al. (2024) found it matches cosine and makes scaling-law sweeps much cheaper. Schedule-Free AdamW (Defazio et al., 2024) removes the schedule altogether by averaging iterates, and won the self-tuning track of the AlgoPerf benchmark competition.

Batch size, learning rate and the critical batch

Bigger batches mean less noise per step, so you can take bigger steps — up to a point. For SGD the linear scaling rule holds while the batch is small compared with the critical batch size; beyond it, extra batch gives diminishing returns and you are buying parallelism, not progress. McCandlish et al. (2018) showed the critical batch is predicted by the gradient noise scale \(B_{\text{noise}} = \operatorname{tr}(\Sigma)/\|\nabla L\|^2\) (gradient variance over squared gradient norm), and that it grows as the loss falls — late training tolerates much bigger batches than early training, which is why large runs ramp the batch size up. For Adam a square-root rule (\(\eta \propto \sqrt{B}\)) is a common starting heuristic, but in practice the peak rate is re-tuned whenever the batch changes by more than ~4×.

What it costs: optimiser memory

Adam keeps two extra numbers per parameter. In mixed-precision training the ZeRO paper (Rajbhandari et al., 2019) counts the bill exactly: 2 bytes for the bf16/fp16 weights, 2 for their gradients, and 12 for the fp32 master copy plus \(\mathbf m\) and \(\mathbf v\) — 16 bytes per parameter before any activations. A 7-billion-parameter model therefore needs about 112 GB just for weights, gradients and Adam state, more than one 80 GB GPU holds. That number is why optimiser-state sharding (ZeRO/FSDP) exists, and why memory-lean optimisers (8-bit Adam, Adafactor, Lion's single moment) keep being invented. See compute maths for the full accounting.

Beyond Adam

As of 2026 AdamW is still the default for most training, but three lines of work are worth knowing:

  • Lion (Chen et al., 2023) was found by a program search over update rules: it applies \(\operatorname{sign}(\beta_1\mathbf m + (1-\beta_1)\mathbf g)\), keeping one moment instead of two. Every coordinate moves by exactly \(\eta\), so it needs a smaller learning rate than AdamW (the authors suggest 3–10× smaller).
  • Shampoo (Gupta, Koren and Singer, 2018) and SOAP (Vyas et al., 2024) precondition each weight matrix with Kronecker-factored curvature estimates instead of a diagonal — closer to Newton's method, at the cost of periodic matrix roots.
  • Muon (Keller Jordan, 2024) takes the momentum matrix for each 2-D weight and replaces it by the nearest orthogonal matrix (via a few Newton–Schulz iterations), so the update has all singular values equal. It set speed records on the modded-nanoGPT benchmark, and Moonshot AI (Liu et al., 2025, Muon is Scalable for LLM Training) added weight decay and per-parameter update scaling and reported about 2× the computational efficiency of AdamW in compute-optimal scaling-law experiments.

The first-principles section explains why these are all the same idea with a different notion of "distance".

First principles

Why should the update be a step against the gradient at all? Take the first-order Taylor expansion of the loss around the current point and ask for the step \(\Delta\) that decreases it most, subject to not moving too far (because the linear approximation is only trustworthy nearby):

\[ \Delta^\star = \arg\min_{\Delta}\; \Big[\, \mathbf g^\top\Delta + \frac{1}{2\eta}\,\|\Delta\|^2 \Big]. \]

Everything depends on which norm \(\|\cdot\|\) measures "too far". That one choice generates the whole family tree:

  • Euclidean norm \(\|\Delta\|_2\): setting the gradient of the bracket to zero gives \(\Delta^\star = -\eta\,\mathbf g\). Plain gradient descent is steepest descent in a world where every parameter direction is equally expensive.
  • A scaled norm \(\|\Delta\|_D^2 = \Delta^\top D\,\Delta\) with diagonal \(D\): the answer is \(-\eta D^{-1}\mathbf g\). Choosing \(D = \operatorname{diag}(\sqrt{\hat{\mathbf v}})\) is Adam without momentum. Choosing \(D = H\) (the Hessian) is Newton's method — which solves any quadratic in one step and makes the condition number irrelevant.
  • The max-norm \(\|\Delta\|_\infty\) (no coordinate may move more than a set amount): the answer is \(-\eta'\operatorname{sign}(\mathbf g)\), sign descent. Adam with \(\beta_1 = \beta_2 = 0\) is exactly this, which is why Adam behaves like sign descent early on, and why Lion works.
  • The spectral norm of a weight matrix (how much the layer can stretch any input): the steepest step is \(-\eta'\,UV^\top\) where \(G = U\Sigma V^\top\) is the gradient's SVD. That is Muon's orthogonalised update.
One question, four answers: which norm measures a step?
One question, four answers: which norm measures a step?. minimise gᵀΔ + ‖Δ‖²/2η, Euclidean ‖Δ‖₂, diagonal scale √v, max-norm ‖Δ‖∞, spectral norm of each W, SGD: −ηg, Adam / RMSProp: −ηg/√v, sign descent, Lion, Muon: −η·UVᵀOne question, four answers: which norm measures a step?. minimise gᵀΔ + ‖Δ‖²/2η, Euclidean ‖Δ‖₂, diagonal scale √v, max-norm ‖Δ‖∞, spectral norm of each W, SGD: −ηg, Adam / RMSProp: −ηg/√v, sign descent, Lion, Muon: −η·UVᵀ

Bernstein and Newhouse (2024) make this precise in Old Optimizer, New Norm. The lesson is that an optimiser is a hypothesis about the geometry of parameter space. Euclidean geometry is a poor hypothesis for a network, where a weight matrix acts on activations as an operator and a 0.01 change in one entry can matter more than a 1.0 change in another.

What breaks if you change the other ingredients?

  • No noise (full batch). Cleaner steps, but each costs the whole dataset. Worse, SGD noise helps: it bounces the parameters out of narrow, sharp basins, and Keskar et al. (2016) found large-batch training converged to sharper minima that generalised worse. The noise is part of the algorithm, not just an approximation error.
  • No decay. With constant \(\eta\) the iterate never stops moving; its stationary spread around a minimum scales with \(\eta\) times the gradient noise. You get a rough, high-loss answer.
  • Momentum too high. \(\beta \to 1\) raises the effective step \(\eta/(1-\beta)\) and lowers damping; the iterate overshoots and spirals. On the quadratic, \(\beta\) above \(\beta^\star\) makes every mode oscillate.
  • \(\epsilon\) too small or too large in Adam. \(\epsilon\) caps the step for coordinates whose \(\hat v\) is near zero. In low precision, \(\epsilon = 10^{-8}\) can underflow or let rare tokens take enormous steps; some large-model recipes use \(10^{-6}\) or smaller \(\beta_2\) (0.95) so \(\hat v\) reacts faster to a sudden gradient spike.

The maths

Notation. \(\boldsymbol\theta_t \in \mathbb R^d\) parameters at step \(t\); \(\mathbf g_t \in \mathbb R^d\) mini-batch gradient; \(\eta\) learning rate; \(\beta, \beta_1, \beta_2 \in [0,1)\) decay rates; all squares, roots and divisions of vectors are elementwise. For a weight matrix \(W \in \mathbb R^{m\times n}\) the moments \(M, V\) have the same shape \(m\times n\).

Derivation: gradient descent on a quadratic, and the 2/λ limit

Let \(L(\mathbf w) = \tfrac12 (\mathbf w-\mathbf w^\star)^\top H (\mathbf w-\mathbf w^\star)\) with \(H = Q\Lambda Q^\top\) symmetric positive definite. Then \(\nabla L = H(\mathbf w-\mathbf w^\star)\) and the error \(\mathbf e_t = \mathbf w_t - \mathbf w^\star\) obeys

\[ \mathbf e_{t+1} = (I-\eta H)\,\mathbf e_t \;\Rightarrow\; \mathbf e_t = Q(I-\eta\Lambda)^t Q^\top \mathbf e_0 . \]

In eigen-coordinates \(z_i = \mathbf q_i^\top\mathbf e\), \(z_i^{(t)} = (1-\eta\lambda_i)^t z_i^{(0)}\). Convergence of every mode requires \(|1-\eta\lambda_i|<1\), i.e. \(0<\eta<2/\lambda_{\max}\). The worst-mode rate \(\rho(\eta) = \max_i|1-\eta\lambda_i|\) is minimised when the two extreme modes balance, \(1-\eta\lambda_{\min} = \eta\lambda_{\max}-1\), giving \(\eta^\star = 2/(\lambda_{\min}+\lambda_{\max})\) and \(\rho^\star = (\kappa-1)/(\kappa+1)\). Reducing the error by a factor \(\varepsilon\) takes \(\ln(1/\varepsilon)/\ln(1/\rho^\star) \approx \tfrac{\kappa}{2}\ln(1/\varepsilon)\) steps.

Derivation: heavy-ball momentum, and the √κ speed-up

Write momentum as a second-order recurrence. From \(\mathbf v_t = \beta\mathbf v_{t-1}+\mathbf g_t\) and \(\mathbf w_{t+1} = \mathbf w_t - \eta\mathbf v_t\) we get \(\mathbf w_{t+1} = \mathbf w_t - \eta\nabla L(\mathbf w_t) + \beta(\mathbf w_t-\mathbf w_{t-1})\). For one eigen-mode with curvature \(\lambda\):

\[ \begin{pmatrix} z_{t+1}\\ z_t\end{pmatrix} = \underbrace{\begin{pmatrix} 1+\beta-\eta\lambda & -\beta\\ 1 & 0\end{pmatrix}}_{R_\lambda} \begin{pmatrix} z_t\\ z_{t-1}\end{pmatrix}. \]

The eigenvalues of \(R_\lambda\) solve \(\mu^2-(1+\beta-\eta\lambda)\mu+\beta=0\). Their product is \(\beta\), so when they are complex (the oscillating regime) both have modulus exactly \(\sqrt\beta\) — independent of \(\lambda\). They are complex when \((1+\beta-\eta\lambda)^2 < 4\beta\), i.e. \((1-\sqrt\beta)^2 < \eta\lambda < (1+\sqrt\beta)^2\). Choose \(\eta,\beta\) so that the whole spectrum \([\lambda_{\min},\lambda_{\max}]\) sits in that window with equality at both ends: \(\eta\lambda_{\min} = (1-\sqrt\beta)^2\) and \(\eta\lambda_{\max} = (1+\sqrt\beta)^2\). Dividing, \(\sqrt\kappa = (1+\sqrt\beta)/(1-\sqrt\beta)\), so

\[ \sqrt{\beta^\star} = \frac{\sqrt\kappa-1}{\sqrt\kappa+1},\qquad \eta^\star = \frac{4}{(\sqrt{\lambda_{\max}}+\sqrt{\lambda_{\min}})^2}, \]

and every mode contracts at rate \(\sqrt{\beta^\star} = (\sqrt\kappa-1)/(\sqrt\kappa+1)\), roughly \(1-2/\sqrt\kappa\). Steps needed scale with \(\sqrt\kappa\) instead of \(\kappa\). For \(\lambda = (1,100)\): \(\eta^\star = 4/121 = 0.0331\), \(\beta^\star = (9/11)^2 = 0.669\), matching the code output.

Derivation: why Adam divides by 1 − βᵗ

Unroll the first moment from \(\mathbf m_0 = 0\): \(\mathbf m_t = (1-\beta_1)\sum_{i=1}^t \beta_1^{t-i}\mathbf g_i\). If the gradients are drawn from a stationary distribution with mean \(\mathbb E[\mathbf g]\),

\[ \mathbb E[\mathbf m_t] = (1-\beta_1)\,\mathbb E[\mathbf g]\sum_{i=1}^{t}\beta_1^{t-i} = (1-\beta_1^t)\,\mathbb E[\mathbf g], \]

using the geometric sum \(\sum_{k=0}^{t-1}\beta_1^k = (1-\beta_1^t)/(1-\beta_1)\). So \(\hat{\mathbf m}_t = \mathbf m_t/(1-\beta_1^t)\) is unbiased. The same argument with \(\mathbf g^2\) gives \(\hat{\mathbf v}_t\). Because \(\beta_2 = 0.999\) makes \(1-\beta_2^t\) tiny early on (0.001 at \(t=1\), 0.095 at \(t=100\), 0.63 at \(t=1000\)), the second-moment correction matters for the first thousand-odd steps; without it, early steps are inflated by \((1-\beta_1^t)/\sqrt{1-\beta_2^t}\).

Adam's step is bounded. Kingma and Ba show that, ignoring \(\epsilon\), \(|\Delta_t| \le \eta\,(1-\beta_1)/\sqrt{1-\beta_2}\) when \((1-\beta_1) > \sqrt{1-\beta_2}\), and \(|\Delta_t| \le \eta\) otherwise. With the defaults, \(1-\beta_1 = 0.1 > \sqrt{0.001} \approx 0.032\), so the worst case is \(3.16\,\eta\) — reached only in the most extreme sparsity, a gradient that was zero at every earlier step and is non-zero now. Typical steps have \(|\Delta_t| \lesssim \eta\). This trust-region-like property is why Adam is forgiving: no single weird batch can move a weight by more than a few \(\eta\).

Convergence caveat. Reddi, Kale and Kumar (2018) constructed a simple convex problem on which Adam provably fails to converge: a rare large gradient is "forgotten" by the \(\mathbf v\) average before it can have its due influence. Their fix, AMSGrad, keeps the running maximum of \(\hat{\mathbf v}\). In deep learning practice AMSGrad rarely helps; the counterexample's lesson is that \(\beta_2\) sets how long Adam remembers gradient scale, and very rare large gradients (rare tokens, loss spikes) are where Adam is fragile.

Schedules. With linear warm-up of \(W\) steps to peak \(\eta_{\max}\) and cosine decay to \(\eta_{\min}\) by step \(T\):

\[ \eta_t = \begin{cases} \eta_{\max}\, t/W, & t < W\\[2pt] \eta_{\min} + \tfrac12(\eta_{\max}-\eta_{\min})\Big(1+\cos\big(\pi\,\tfrac{t-W}{T-W}\big)\Big), & W\le t\le T. \end{cases} \]

Gradient clipping. If \(\|\mathbf g_t\|_2 > c\), replace \(\mathbf g_t\) by \(c\,\mathbf g_t/\|\mathbf g_t\|_2\). The norm is computed over all parameters jointly, so clipping changes the step's length but not its direction. Introduced for recurrent networks by Pascanu, Mikolov and Bengio (2013); see RNNs and LSTMs.

Build it

NumPy, no frameworks. Plain GD, heavy-ball momentum and Adam/AdamW on the \(\kappa = 100\) bowl, counting the steps to reach a loss below \(10^{-6}\).

import numpy as np

H = np.array([1.0, 100.0])                  # curvatures: f(w) = 0.5 * sum(H * w**2), kappa = 100
loss = lambda w: 0.5 * np.sum(H * w**2)
grad = lambda w: H * w

def sgd(lr):
    def step(w, g, s): return w - lr * g
    return step

def momentum(lr, beta):
    def step(w, g, s):
        s["v"] = beta * s.get("v", 0) + g          # heavy-ball velocity
        return w - lr * s["v"]
    return step

def adam(lr, b1=0.9, b2=0.999, eps=1e-8, wd=0.0):
    def step(w, g, s):
        t = s["t"] = s.get("t", 0) + 1
        s["m"] = b1 * s.get("m", 0) + (1 - b1) * g
        s["v"] = b2 * s.get("v", 0) + (1 - b2) * g**2
        m_hat, v_hat = s["m"] / (1 - b1**t), s["v"] / (1 - b2**t)
        return w - lr * (m_hat / (np.sqrt(v_hat) + eps) + wd * w)   # wd > 0 -> AdamW
    return step

def run(step, n=2000, tol=1e-6):
    w, s = np.array([1.0, 1.0]), {}
    for t in range(1, n + 1):
        w = step(w, grad(w), s)
        if loss(w) < tol: return t
    return f">{n} (loss {loss(w):.2e})"

print("GD, lr=0.019        :", run(sgd(0.019)))
print("GD, lr=0.021        :", run(sgd(0.021)))   # above 2/100 -> diverges
k = H.max() / H.min()
lr_opt = (2 / (np.sqrt(H.max()) + np.sqrt(H.min())))**2
beta_opt = ((np.sqrt(k) - 1) / (np.sqrt(k) + 1))**2
print(f"momentum, lr={lr_opt:.4f}, beta={beta_opt:.4f}:", run(momentum(lr_opt, beta_opt)))
print("momentum, lr=0.01, beta=0.9 :", run(momentum(0.01, 0.9)))
for lr in (0.01, 0.1):
    print(f"Adam, lr={lr}          :", run(adam(lr)))

Output:

GD, lr=0.019        : 343
GD, lr=0.021        : >2000 (loss 1.86e+167)
momentum, lr=0.0331, beta=0.6694: 69
momentum, lr=0.01, beta=0.9 : 138
Adam, lr=0.01          : 305
Adam, lr=0.1          : 82

In PyTorch the same choices are one line each; a standard modern setup is:

import torch
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1)
warm = torch.optim.lr_scheduler.LinearLR(opt, start_factor=1e-3, total_iters=2000)
cos = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=total_steps - 2000, eta_min=3e-5)
sched = torch.optim.lr_scheduler.SequentialLR(opt, [warm, cos], milestones=[2000])
# each step: loss.backward(); torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
#            opt.step(); sched.step(); opt.zero_grad(set_to_none=True)

Things to try

  • Rotate the bowl: replace H * w by R.T @ (H * (R @ w)) for a 45° rotation R. Adam's advantage over momentum mostly disappears — a diagonal preconditioner cannot fix off-axis curvature. This is the gap Shampoo and Muon target.
  • Remove the bias correction (m_hat, v_hat = s["m"], s["v"]) and print the first five steps' sizes. Compare with \(\eta(1-\beta_1)/\sqrt{1-\beta_2}\).
  • Add Gaussian noise to grad (std 1.0) and compare a constant learning rate with one that decays as \(\eta_0/\sqrt t\). Plot the final loss: the noise floor is visible.
  • Implement Nesterov: evaluate grad(w - lr * beta * s["v"]) before updating v. Does it beat heavy-ball on this bowl with the same \(\eta, \beta\)?
  • Implement Lion (update = sign(b1*m + (1-b1)*g); m = b2*m + (1-b2)*g with \(\beta_1=0.9, \beta_2=0.99\)) and find the learning rate that matches Adam.

In practice

Situation Sensible starting point
Transformers / LLM pre-training AdamW, \(\beta = (0.9, 0.95)\), wd 0.1, clip 1.0, warm-up ~1–2k steps, cosine or WSD to ~10% of peak
Fine-tuning a pre-trained model AdamW, peak LR 10–100× smaller than pre-training (e.g. 1e-5 to 5e-5 for full fine-tunes), short warm-up, linear decay
CNNs on images SGD + Nesterov momentum 0.9, LR 0.1 per 256 images, wd 5e-5 to 1e-4, cosine; or AdamW with stronger augmentation
Small MLP / quick experiment Adam, LR 1e-3 or 3e-4 — then actually sweep it
  • Sweep the learning rate first and on a log scale (factors of ~3). It matters more than any other optimiser choice; the training recipe shows a cheap LR range test.
  • Don't decay everything. Biases, normalisation gains and often embeddings are excluded from weight decay in most recipes (nanoGPT, for example, decays only 2-D weight tensors).
  • Loss spikes in large runs usually mean the step was too big for the current curvature. The usual remedies are lower peak LR, longer warm-up, lower \(\beta_2\), tighter clipping, or QK-normalisation in attention (Wortsman et al., 2023, reproduce these instabilities at small scale so you can study them cheaply).
  • Re-tune when you scale. The best LR falls as width grows under standard parameterisation; μP (Yang et al., 2022) re-parameterises the network so the best LR transfers from a small proxy to a large model.

Common misconceptions

\"Adam generalises worse than SGD\"

Wilson et al. (2017) found adaptive methods generalising worse on several vision tasks, and the belief spread. Much of that gap came from coupling L2 with Adam and from under-tuned hyperparameters; with AdamW, proper decay and a schedule, Adam-family optimisers train essentially every state-of-the-art language and vision transformer. SGD with momentum remains competitive for CNNs.

\"The optimiser finds the minimum\"

It doesn't, and you don't want it to. Deep networks have no unique minimum; training stops long before convergence, and which region of the landscape you end in depends on the learning rate, batch noise and schedule. The optimiser is part of the model's inductive bias.

Check yourself

On a quadratic with Hessian eigenvalues between 0.5 and 400, what is the largest stable learning rate for plain gradient descent, and roughly how many times slower than momentum is it?

\(\eta < 2/400 = 0.005\). \(\kappa = 800\). Plain GD needs order \(\kappa = 800\) steps per factor-\(e\) reduction (more precisely \(\kappa/2\)); tuned heavy-ball needs order \(\sqrt\kappa \approx 28\) (more precisely \(\sqrt\kappa/2\)). Momentum is about \(\sqrt{800} \approx 28\times\) faster.

Why is Adam's update invariant to multiplying the loss by a constant c? What is not invariant?

\(\hat{\mathbf m}\) scales by \(c\), \(\sqrt{\hat{\mathbf v}}\) scales by \(|c|\), so the ratio is unchanged. The \(\epsilon\) term breaks exact invariance (it matters relatively more when \(c\) is small), and decoupled weight decay is unaffected by \(c\), so the balance between the data term and the decay shifts — with AdamW, scaling the loss does not change the effective regularisation strength, unlike L2.

With β = 0.9, what is momentum's effective learning rate along a direction whose gradient is constant? Why does that matter when switching from SGD to SGD+momentum?

The velocity converges to \(g/(1-\beta) = 10g\), so the effective rate is \(10\eta\). If you add momentum and keep the same \(\eta\), you have effectively multiplied the step by ten and may diverge; frameworks that use the "dampened" form \(\mathbf v = \beta\mathbf v + (1-\beta)\mathbf g\) avoid this but then need a larger \(\eta\).

Explain, with the two-weight example, why Adam with an L2 penalty under-regularises the weights that matter most.

The L2 gradient \(\lambda w\) is divided by \(\sqrt{\hat v}\). Weights with large, frequent gradients (the heavily used ones) have large \(\hat v\) and so receive a small relative decay; weights with tiny gradients are decayed hard. AdamW applies \(\eta\lambda w\) directly, giving every weight the same proportional shrinkage.

Why do large-model recipes warm the learning rate up rather than starting at the peak?

Early on the weights are random and the loss surface near initialisation can be very sharp; Adam's \(\hat{\mathbf v}\) is estimated from few samples and gradient magnitudes are atypical. A full-size step can exceed the local stability limit (\(2/\lambda_{\max}\)) and push the network into a bad region (saturated units, huge logits). Warm-up lets curvature fall and statistics settle; the edge-of-stability work shows sharpness itself adapts to the step size used.

A colleague doubles the batch size and the training loss per step improves but loss per token gets worse. What is happening?

The batch is above the critical batch size for this stage of training: the gradient estimate was already accurate enough, so the extra examples barely improve each step. You pay twice the compute per step for little extra progress. Raise the learning rate (it may now tolerate it) or keep the smaller batch; the gradient noise scale estimates where the knee is.

Hard: show that sign descent is steepest descent under the ∞-norm, and say what that implies about Adam's first steps.

Minimise \(\mathbf g^\top\Delta\) subject to \(\|\Delta\|_\infty \le r\): each coordinate is chosen independently, \(\Delta_i = -r\,\operatorname{sign}(g_i)\), giving \(-r\|\mathbf g\|_1\). With the squared-norm penalty form, \(r = \eta\|\mathbf g\|_1\). Adam with bias correction at \(t=1\) gives \(\hat m/\sqrt{\hat v} = g/|g| = \operatorname{sign}(g)\), so Adam's first step is exactly a sign step of size \(\eta\) on every coordinate — every weight moves by the same amount regardless of its gradient's size.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads