Simple Algorithm
Machine Learning · Descent · 22 min

Adaptive & Second-Order Methods

AdaGrad, RMSProp, Adam and Newton’s method.

Gradient descent takes the same step size in every direction, so one steep direction forces tiny steps everywhere else. This lesson fixes that in two ways. Adaptive methods (AdaGrad, RMSProp, Adam) give each parameter its own step size, learned from the gradients seen so far; second-order methods (Newton and quasi-Newton) use curvature to take the right step in every direction at once.

What you’ll learn

  • Explain why ill-conditioning slows gradient descent, and how a preconditioner changes the geometry the method sees.
  • Write the AdaGrad, RMSProp and Adam updates, derive Adam's bias correction, and contrast an L2 penalty with AdamW's decoupled weight decay.
  • Derive Newton's method from a quadratic model, prove its local quadratic convergence for strongly convex functions with a Lipschitz Hessian, and count its cost.
  • Describe how quasi-Newton methods such as BFGS and L-BFGS build curvature from gradients, and choose a method for a given problem.

One step size for every direction

Take a quadratic f(x)=12x⊤Hxf(\mathbf x)=\frac12\mathbf x^\top H\mathbf x whose Hessian is diagonal, with curvatures h1≥⋯≥hd>0h_1\ge\dots\ge h_d>0. Gradient descent with learning rate η\eta multiplies coordinate ii by 1−ηhi1-\eta h_i at every step. Stability in the steepest direction needs η<2/h1=2/L\eta<2/h_1=2/L, and at the standard choice η=1/L\eta=1/L the flattest direction shrinks by only 1−hd/h1=1−1/κ1-h_d/h_1=1-1/\kappa per step, so about κlog⁡(1/ε)\kappa\log(1/\varepsilon) steps are needed. The condition number κ=L/μ\kappa=L/\mu, not the dimension, sets the cost.

The cure is a preconditioner, a positive definite matrix PP that reshapes the step:

xt+1=xt−η P−1∇f(xt).\mathbf x_{t+1}=\mathbf x_t-\eta\,P^{-1}\nabla f(\mathbf x_t).

In the coordinates z=P1/2x\mathbf z=P^{1/2}\mathbf x this is plain gradient descent on g(z)=f(P−1/2z)g(\mathbf z)=f(P^{-1/2}\mathbf z), whose Hessian is P−1/2HP−1/2P^{-1/2}HP^{-1/2}. The ideal P=HP=H makes every direction equally curved, and one step with η=1\eta=1 lands exactly on the minimum of a quadratic. Every method in this lesson is a way to approximate a good PP cheaply: from the history of gradients (adaptive methods) or from second derivatives (Newton and quasi-Newton methods).

AdaGrad and RMSProp: a step size per coordinate

Adaptive methods build a diagonal preconditioner out of the gradients themselves. With g\mathbf g the (stochastic) gradient at the current step and every operation applied coordinate by coordinate:

text
AdaGrad (Duchi, Hazan & Singer, 2011)
    s ← s + g ⊙ g                        # running SUM of squared gradients
    x ← x − η · g / (sqrt(s) + ε)

RMSProp (Tieleman & Hinton, 2012)
    s ← ρ·s + (1 − ρ)·(g ⊙ g)            # running AVERAGE, typically ρ = 0.9
    x ← x − η · g / (sqrt(s) + ε)

⊙\odot is the elementwise product, and ε≈10−8\varepsilon\approx10^{-8} only prevents division by zero.

AdaGrad (Duchi, Hazan & Singer, 2011, with concurrent work by McMahan & Streeter, 2010) was designed for online learning with sparse features, as in text classification or click prediction. A rare feature has a small accumulated sum, so when it does appear it takes a large step; a frequent one takes small steps. For online convex problems this gives a regret bound that adapts to the geometry of the gradients (Adaptive Methods in Depth proves it). The price is that the sum only grows, so when gradients persist the effective step η/si\eta/\sqrt{s_i} decays roughly like 1/t1/\sqrt t: right for convex problems, but often too fast for deep networks, which must travel far through nonconvex terrain. RMSProp, proposed by Tieleman and Hinton in a 2012 lecture of their online neural networks course and never formally published, replaces the sum with an exponential moving average, so old gradients are forgotten and the steps stop shrinking.

Check your understanding

You multiply your training loss by 10001000 and keep η\eta fixed. What happens to the size of RMSProp's steps (ignoring ε\varepsilon)?

  1. They become 10001000 times larger
  2. They become about 1000≈32\sqrt{1000}\approx32 times larger
  3. They stay the same
  4. They become 10001000 times smaller
Show the answer

C. They stay the same

Every gradient is multiplied by 10001000, and so is s\sqrt s, the root of an average of their squares; the ratio g/sg/\sqrt s is unchanged. Plain gradient descent would take steps 10001000 times larger and almost certainly diverge.

Adam: momentum meets RMSProp

Adam (Kingma & Ba, 2015) combines a momentum-style average of gradients with RMSProp's average of squared gradients, and corrects both for starting at zero.

text
ADAM(η = 0.001, β1 = 0.9, β2 = 0.999, ε = 1e-8)      # the paper's defaults
  m ← 0;  v ← 0
  for t = 1, 2, ...:
      g ← stochastic gradient at x
      m ← β1·m + (1 − β1)·g                     # first moment: momentum
      v ← β2·v + (1 − β2)·(g ⊙ g)               # second moment, per coordinate
      m_hat ← m / (1 − β1^t);  v_hat ← v / (1 − β2^t)   # bias correction
      x ← x − η · m_hat / (sqrt(v_hat) + ε)
DerivationWhy bias correction
  1. vt=(1−β2)∑s=1tβ2 t−sgs2,(1−β2)∑s=1tβ2 t−s=1−β2 tv_t=(1-\beta_2)\sum_{s=1}^t\beta_2^{\,t-s}g_s^2,\qquad(1-\beta_2)\sum_{s=1}^t\beta_2^{\,t-s}=1-\beta_2^{\,t}

    Unroll the second-moment average from v0=0v_0=0 (one coordinate): it is a weighted sum of past squared gradients whose weights add up to less than one.

  2. E[vt]=(1−β2 t) c⟹E[vt1−β2 t]=c\E[v_t]=(1-\beta_2^{\,t})\,c\qquad\Longrightarrow\qquad\E\Big[\frac{v_t}{1-\beta_2^{\,t}}\Big]=c

    If the squared gradients have a stationary mean E[gs2]=c\E[g_s^2]=c, the average is biased toward zero by exactly that factor, which bias correction divides out. The same holds for mtm_t with β1\beta_1:

  3. m1v1=(1−β1) g11−β2 ∣g1∣=1−β11−β2 sign⁡(g1)\frac{m_1}{\sqrt{v_1}}=\frac{(1-\beta_1)\,g_1}{\sqrt{1-\beta_2}\,\abs{g_1}}=\frac{1-\beta_1}{\sqrt{1-\beta_2}}\,\sign(g_1)

    Without the correction the early steps are distorted. At t=1t=1 the ratio depends only on the two decay rates, and with β2\beta_2 close to 11 the first steps are much larger than η\eta:

Predict before you look

With β1=0.9\beta_1=0.9 and β2=0.999\beta_2=0.999, how many times η\eta is Adam's first step without bias correction (ignoring ε\varepsilon)?

Show the answer

3.16

(1−β1)/1−β2=0.1/0.001≈0.1/0.0316≈3.16(1-\beta_1)/\sqrt{1-\beta_2}=0.1/\sqrt{0.001}\approx0.1/0.0316\approx3.16. With the correction, m^1=g1\hat m_1=g_1 and v^1=g12\hat v_1=g_1^2, so the first step is exactly η\eta per coordinate, against the sign of g1g_1. The two versions agree only once β2 t\beta_2^{\,t} has faded, which takes a few thousand steps when β2=0.999\beta_2=0.999.

Weight decay, decoupled. With plain SGD, adding an L2 penalty λ2∥x∥2\frac\lambda2\norm{\mathbf x}^2 to the loss and shrinking the weights directly are the same thing: x−η(∇f+λx)=(1−ηλ)x−η∇f\mathbf x-\eta(\nabla f+\lambda\mathbf x)=(1-\eta\lambda)\mathbf x-\eta\nabla f. With Adam they differ. The penalty's gradient λx\lambda\mathbf x is divided by v^\sqrt{\hat v} along with everything else, so weights whose gradients have been large are regularized less. AdamW (Loshchilov & Hutter, 2019) applies the weight decay outside the adaptive scaling,

x←x−η(m^v^+ε+λx),\mathbf x\leftarrow\mathbf x-\eta\Big(\frac{\hat{\mathbf m}}{\sqrt{\hat{\mathbf v}}+\varepsilon}+\lambda\mathbf x\Big),

which shrinks every weight at the same relative rate. (In this form, PyTorch's, the decay is also scaled by the learning rate.) As of the mid-2020s AdamW is the most common choice for training transformers.

Newton's method: let curvature choose the step

DerivationNewton's step from a quadratic model
  1. f(x+d) ≈ m(d)=f(x)+∇f(x)⊤d+12 d⊤∇2f(x) df(\mathbf x+\mathbf d)\ \approx\ m(\mathbf d)=f(\mathbf x)+\nabla f(\mathbf x)^\top\mathbf d+\tfrac12\,\mathbf d^\top\nabla^2f(\mathbf x)\,\mathbf d

    Approximate ff near x\mathbf x by its second-order Taylor expansion, built from the gradient and the Hessian ∇2f(x)\nabla^2f(\mathbf x):

  2. ∇f(x)+∇2f(x) d=0⟹xt+1=xt−[∇2f(xt)]−1∇f(xt)\nabla f(\mathbf x)+\nabla^2f(\mathbf x)\,\mathbf d=\mathbf 0\qquad\Longrightarrow\qquad\mathbf x_{t+1}=\mathbf x_t-\big[\nabla^2f(\mathbf x_t)\big]^{-1}\nabla f(\mathbf x_t)

    If ∇2f(x)≻0\nabla^2f(\mathbf x)\succ0, the model has a unique minimizer, where its gradient vanishes. Newton's method jumps there:

  3. x1=x0−H−1(Hx0−b)=H−1b=x⋆\mathbf x_1=\mathbf x_0-H^{-1}\big(H\mathbf x_0-\mathbf b\big)=H^{-1}\mathbf b=\mathbf x^\star

    On a quadratic f=12x⊤Hx−b⊤xf=\frac12\mathbf x^\top H\mathbf x-\mathbf b^\top\mathbf x with H≻0H\succ0 the model is exact, so one step lands on x⋆=H−1b\mathbf x^\star=H^{-1}\mathbf b from anywhere, whatever the condition number. Newton's method is preconditioned gradient descent with the ideal P=∇2fP=\nabla^2f, re-evaluated at every step.

DerivationProof
  1. et+1=et−Ht−1∇f(xt)=Ht−1∫01[Ht−∇2f(x⋆+τet)] et dτ\mathbf e_{t+1}=\mathbf e_t-H_t^{-1}\nabla f(\mathbf x_t)=H_t^{-1}\int_0^1\Big[H_t-\nabla^2f(\mathbf x^\star+\tau\mathbf e_t)\Big]\,\mathbf e_t\,d\tau

    Write et=xt−x⋆\mathbf e_t=\mathbf x_t-\mathbf x^\star and Ht=∇2f(xt)H_t=\nabla^2f(\mathbf x_t). Since ∇f(x⋆)=0\nabla f(\mathbf x^\star)=\mathbf 0, the gradient at xt\mathbf x_t is an integral of the Hessian along the segment from x⋆\mathbf x^\star:

  2. ∥et+1∥ ≤ 1μ∫01M(1−τ) ∥et∥2 dτ=M2μ∥et∥2\norm{\mathbf e_{t+1}}\ \le\ \frac1\mu\int_0^1M(1-\tau)\,\norm{\mathbf e_t}^2\,d\tau=\frac M{2\mu}\norm{\mathbf e_t}^2

    The two Hessians in the bracket are evaluated (1−τ)∥et∥(1-\tau)\norm{\mathbf e_t} apart, so they differ by at most M(1−τ)∥et∥M(1-\tau)\norm{\mathbf e_t}, and strong convexity gives ∥Ht−1∥≤1/μ\norm{H_t^{-1}}\le1/\mu:

  3. rt+1≤rt2⟹rt≤r0 2tr_{t+1}\le r_t^2\qquad\Longrightarrow\qquad r_t\le r_0^{\,2^t}

    With rt=M2μ∥et∥r_t=\frac M{2\mu}\norm{\mathbf e_t} the recursion becomes rt+1≤rt2r_{t+1}\le r_t^2, so the error is doubly exponentially small once r0<1r_0<1:

Predict before you look

Newton's method starts with r0=0.1r_0=0.1 in the recursion rt+1=rt2r_{t+1}=r_t^2. Write r3=10−kr_3=10^{-k}. What is kk?

Show the answer

8

r1=10−2r_1=10^{-2}, r2=10−4r_2=10^{-4}, r3=10−8r_3=10^{-8}: the exponent doubles at every step. A linearly convergent method that shrinks the error by a factor 0.90.9 per step would need about 150150 steps to go from 10−110^{-1} to 10−810^{-8}.

The catch is cost and reach. Forming the Hessian of a generalized linear model, X⊤DXX^\top DX, costs O(nd2)\order{nd^2} and solving the Newton system O(d3)\order{d^3}, with O(d2)\order{d^2} memory: routine for dd in the thousands, impossible for a network with 10810^8 parameters, whose Hessian would have 101610^{16} entries. And the guarantee is local. Far from x⋆\mathbf x^\star the quadratic model can mislead: on f(x)=1+x2f(x)=\sqrt{1+x^2}, convex with minimizer 00, the pure Newton step is x↦−x3x\mapsto-x^3, which diverges from every ∣x0∣>1\abs{x_0}>1. On nonconvex functions Newton's method is attracted to any nondegenerate stationary point, saddles and maxima included. Practical Newton methods therefore damp the step with a line search or a trust region. For logistic regression, Newton's method, safeguarded by a line search, is the classical fitting method: iteratively reweighted least squares (Logistic Regression in Depth).

Quasi-Newton methods, and which method when

Quasi-Newton methods get curvature from gradients alone. After a step st=xt+1−xt\mathbf s_t=\mathbf x_{t+1}-\mathbf x_t with gradient change yt=∇f(xt+1)−∇f(xt)\mathbf y_t=\nabla f(\mathbf x_{t+1})-\nabla f(\mathbf x_t), the Hessian must satisfy yt≈∇2f st\mathbf y_t\approx\nabla^2f\,\mathbf s_t, exactly for a quadratic. BFGS, named for Broyden, Fletcher, Goldfarb and Shanno, who proposed it independently in 1970, keeps an approximation HtH_t of the inverse Hessian and corrects it by a rank-two update so that the new one satisfies this secant condition, Ht+1yt=stH_{t+1}\mathbf y_t=\mathbf s_t:

Ht+1=(I−ρtstyt⊤)Ht(I−ρtytst⊤)+ρtstst⊤,ρt=1yt⊤st.H_{t+1}=\big(I-\rho_t\mathbf s_t\mathbf y_t^\top\big)H_t\big(I-\rho_t\mathbf y_t\mathbf s_t^\top\big)+\rho_t\mathbf s_t\mathbf s_t^\top,\qquad\rho_t=\frac1{\mathbf y_t^\top\mathbf s_t}.

Each step costs O(d2)\order{d^2} instead of O(d3)\order{d^3}, and near a nondegenerate minimizer BFGS converges superlinearly. L-BFGS (Liu & Nocedal, 1989) keeps only the last mm pairs (s,y)(\mathbf s,\mathbf y), typically 55 to 2020, and applies HtH_t to a vector in O(md)\order{md} time without ever forming it. It is a strong default for smooth, deterministic problems with up to millions of variables; with noisy mini-batch gradients its curvature pairs are corrupted, one reason it rarely trains deep networks.

python
import numpy as np
from scipy.optimize import minimize
from scipy.special import expit            # the sigmoid

def loss_and_grad(w, X, y, lam):           # logistic regression, labels y in {0, 1}
    z = X @ w
    loss = np.mean(np.logaddexp(0, z) - y * z) + 0.5 * lam * w @ w
    grad = X.T @ (expit(z) - y) / len(y) + lam * w
    return loss, grad

# X: (n, d) design matrix, y: (n,) array of 0/1 labels
res = minimize(loss_and_grad, np.zeros(X.shape[1]), args=(X, y, 1e-3),
               jac=True, method='L-BFGS-B')
w_hat = res.x

jac=True tells SciPy that the function returns the loss and its gradient together, and np.logaddexp(0, z) computes log⁡(1+ez)\log(1+e^z) without overflow. The small ridge term makes the objective strongly convex, so the minimizer exists and is unique even on separable data.

MethodExtra memoryTypical use
SGD with momentumddlarge or noisy problems; still competitive for many vision models
AdaGradddconvex problems with sparse features
Adam, AdamW2d2ddeep networks, especially transformers
Newton (damped)d2d^2small dd and high accuracy: generalized linear models, interior-point solvers
L-BFGS2md2mdsmooth deterministic problems with up to millions of variables
Approximate curvature (K-FAC, Shampoo)per-layer matrix factorsresearch and some large-scale training (Newton & Quasi-Newton Methods)
Memory is counted beyond the parameters themselves. Per step, every method needs one gradient; L-BFGS adds O(md)\order{md} work, and Newton also needs the Hessian and an O(d3)\order{d^3} linear solve.

Key takeaways

  • Gradient descent's speed is set by the condition number κ\kappa, because one step size must suit both the steepest and the flattest directions. A preconditioner PP reshapes the geometry, and P=∇2fP=\nabla^2f is ideal.
  • AdaGrad divides each coordinate's step by the root of its summed squared gradients (strong on sparse convex problems, but steps decay like 1/t1/\sqrt t); RMSProp uses a moving average instead. Both make steps scale-free, close to sign descent.
  • Adam adds momentum and bias correction, stepping by m^/(v^+ε)\hat{\mathbf m}/(\sqrt{\hat{\mathbf v}}+\varepsilon) with v^=v/(1−β2 t)\hat v=v/(1-\beta_2^{\,t}); AdamW decouples weight decay from the adaptive scaling. Per-coordinate scaling fixes only axis-aligned ill-conditioning.
  • Newton's method minimizes the local quadratic model: one step on a quadratic, and quadratic convergence near a nondegenerate minimizer, but O(d3)\order{d^3} work per step and only local guarantees. BFGS and L-BFGS recover much of its speed from gradients through the secant condition.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why was RMSProp proposed as a replacement for AdaGrad when training neural networks?

  1. AdaGrad cannot handle sparse gradients
  2. AdaGrad's sum of squared gradients only grows, so its steps keep shrinking; RMSProp's moving average forgets old gradients
  3. RMSProp uses second derivatives, which AdaGrad lacks
  4. AdaGrad's steps grow without bound late in training
Show the answer

B. AdaGrad's sum of squared gradients only grows, so its steps keep shrinking; RMSProp's moving average forgets old gradients

AdaGrad's effective step η/∑sgs,i2\eta/\sqrt{\sum_sg_{s,i}^2} decays roughly like 1/t1/\sqrt t when gradients persist: fine for convex online problems, too fast for long nonconvex training runs. An exponential moving average keeps the denominator at the scale of recent gradients.

Question 2

You train with Adam and add an L2 penalty λ2∥x∥2\frac\lambda2\norm{\mathbf x}^2 to the loss. Which weights does the penalty pull toward zero most weakly at each step?

  1. Weights whose gradients stayed small throughout training
  2. All weights equally, as with SGD
  3. Weights whose gradients have been large, because the penalty's gradient is divided by v^\sqrt{\hat v}
  4. The bias terms only
Show the answer

C. Weights whose gradients have been large, because the penalty's gradient is divided by v^\sqrt{\hat v}

Roughly, coordinate ii decays at rate ηλ/v^i\eta\lambda/\sqrt{\hat v_i}, which is small where gradients are large. AdamW applies ηλx\eta\lambda\mathbf x outside the adaptive scaling, so every weight decays at the same relative rate.

Question 3

Newton's method with step 11 is applied to a strictly convex quadratic whose condition number is 10610^6. How many steps does it need, in exact arithmetic?

  1. One, from any starting point
  2. About κ=1000\sqrt\kappa=1000
  3. About κlog⁡(1/ε)\kappa\log(1/\varepsilon)
  4. It may diverge, because ill-conditioning breaks Newton's method
Show the answer

A. One, from any starting point

The quadratic model is exact, so the Newton step lands on H−1bH^{-1}\mathbf b. Rescaling coordinates changes κ\kappa but not Newton's iterates, a property called affine invariance. In floating point a huge κ\kappa does cost accuracy in the linear solve, but not iterations.

Question 4

What problem does Adam's bias correction fix?

  1. Mini-batch gradients are biased estimates of the full gradient
  2. Adam's final solution is biased toward the origin
  3. Late in training Adam's steps become too small
  4. The moment estimates start at zero, so early in training they are biased toward zero and distort the first steps
Show the answer

D. The moment estimates start at zero, so early in training they are biased toward zero and distort the first steps

Both moving averages start at 00, so E[vt]=(1−β2 t)E[g2]\E[v_t]=(1-\beta_2^{\,t})\E[g^2] when the gradient statistics are stationary; dividing by 1−β2 t1-\beta_2^{\,t} (and by 1−β1 t1-\beta_1^{\,t} for mtm_t) removes the shrinkage. It matters only in the first few thousand steps when β2=0.999\beta_2=0.999.

Question 5

L-BFGS excels on full-batch logistic regression. Why is it rarely used to train large neural networks with mini-batches?

  1. It needs the full Hessian at every step
  2. Noisy mini-batch gradients corrupt its curvature pairs (s,y)(\mathbf s,\mathbf y), and its line searches assume consistent function values
  3. It needs O(d2)\order{d^2} memory
  4. It only works on quadratic functions
Show the answer

B. Noisy mini-batch gradients corrupt its curvature pairs (s,y)(\mathbf s,\mathbf y), and its line searches assume consistent function values

L-BFGS needs only gradients and O(md)\order{md} memory, but its curvature estimate yt=∇f(xt+1)−∇f(xt)\mathbf y_t=\nabla f(\mathbf x_{t+1})-\nabla f(\mathbf x_t) is swamped by noise when the two gradients come from different mini-batches. Stochastic quasi-Newton methods exist, but as of the mid-2020s none has displaced first-order methods in deep learning.

Go deeper

Further reading

  • J. Duchi, E. Hazan & Y. Singer, "Adaptive subgradient methods for online learning and stochastic optimization," Journal of Machine Learning Research 12, 2121–2159 (2011).
  • D. P. Kingma & J. Ba, "Adam: a method for stochastic optimization," ICLR (2015).
  • I. Loshchilov & F. Hutter, "Decoupled weight decay regularization," ICLR (2019).
  • J. Nocedal & S. J. Wright, Numerical Optimization, 2nd ed. (Springer, 2006), chapters 3, 6 and 7.