Optimization/Momentum & Adaptive Methods

Lesson 4.22,587 words

Momentum & Adaptive Methods

Plain gradient descent zig-zags across ravines and moves slowly along flat valleys, because one global learning rate cannot suit a surface with wildly different curvature in different directions. Two fixes address the two problems: momentum accumulates a velocity that damps the oscillation and accelerates the drift, and adaptive methods give every parameter its own learning rate scaled by the history of its gradients.

╌╌╌╌

Plain stochastic gradient descent takes the same step rule everywhere: , one scalar , applied identically to every coordinate. Two structural facts of the loss surface break this. First, curvature differs by direction: a ravine is steep across and shallow along, so a step large enough to make progress down the valley overshoots across it and the path zig-zags. Second, curvature differs by coordinate, since some weights see huge gradients, others tiny ones, yet a single serves all of them. This lesson addresses each in turn: momentum for the first, adaptive learning rates for the second, and Adam combining them into the modern default.1

The pathology: ill-conditioning

Near a minimum the loss is locally quadratic, , with Hessian . Rotate to the eigenbasis of and the coordinates decouple: along eigenvector with eigenvalue , gradient descent with rate contracts the error by a fixed factor each step,

Stability demands for every axis, so the largest eigenvalue caps the step at . But convergence along the flattest axis proceeds at rate , which drives very close to .

The next figure shows the geometry: on elliptical contours plain SGD oscillates across the steep direction while making little progress along the shallow one.

A ravine (). SGD (red) zig-zags across the steep axis; momentum (blue) cancels the side-to-side motion and accelerates down the valley.

Momentum

Momentum addresses the zig-zag with memory. Rather than stepping by the current gradient, accumulate an exponentially-weighted running sum of gradients (a velocity) and step by that. Oscillating components alternate sign and cancel in the sum; the consistent down-valley component survives and compounds.

The name is literal. Read as the position of a ball of unit mass, as the force from the potential , and as a friction (drag) coefficient: the velocity update is a discrete-time Newtonian dynamics with viscous damping. The ball does not teleport down the gradient; it coasts, carrying its momentum through small bumps and across narrow ravines.2

QuantityPhysical reading
position of the particle
velocity
force ( is the potential energy)
friction / drag (closer to = less drag)
time step inverse mass
The "heavy ball" reading. A particle rolls on the loss surface under the force with friction; inertia carries it through small ripples that trap plain GD.

Effective step size

Unrolling the velocity recurrence with a constant gradient exposes why momentum accelerates. With ,

The terminal velocity is the geometric series times a single SGD step. The effective learning rate along any direction the gradient persistently points is therefore amplified:

That asymmetry is the entire mechanism. Down the shallow valley the gradient is consistent, so momentum compounds it and the path accelerates; across the steep ravine the gradient reverses every step, so the contributions annihilate and the oscillation is damped. One coefficient produces both behaviors.

For example, fix , , and a constant unit gradient along a persistent direction. The velocity magnitude grows step by step,

each term being of the previous velocity plus . The steady state is ten times a single SGD step of . Now flip the sign of every step, as it does across a ravine: the velocity oscillates within a small band around zero instead of growing, because each contribution partly cancels the last. The same recurrence, fed a consistent signal, integrates it; fed an alternating signal, filters it out.

Velocity accumulation under a constant unit gradient (, ). Each bar is ; the sequence climbs the geometric series toward the terminal step .

The dependence on is steep near : the effective step is a hyperbola, so the last tenth of carries most of the amplification. That is also why close to is delicate: it lengthens the memory (a horizon of steps) and can overshoot on curvature that turns before the velocity can respond.

Effective step versus momentum coefficient . The curve is a hyperbola: gives , gives .
Algorithm:Momentum(L,θ,η,μ)\textsc{Momentum}(L, \theta, \eta, \mu) — SGD with a velocity buffer
  1. 1
    initialize θ\theta randomly,\ v0v \gets 0
  2. 2
    repeat
  3. 3
    sample a minibatch (X,y)(X, y)
  4. 4
    gθL(θ;X,y)g \gets \nabla_\theta L(\theta; X, y)
    backward pass
  5. 5
    vμvηgv \gets \mu \cdot v - \eta \cdot g
    accumulate velocity
  6. 6
    θθ+v\theta \gets \theta + v
    step by velocity
  7. 7
    until converged
  8. 8
    return θ\theta

Nesterov accelerated gradient

Momentum measures the force where the ball is; Nesterov's variant measures it where the ball is about to be. Take the momentum step first to the lookahead point , and evaluate the gradient there, so the correction anticipates the surface ahead instead of reacting to the surface behind.

The lookahead gives a stiffer, self-correcting response: if the velocity is about to overshoot, the gradient at the projected point already points back, so NAG brakes a step earlier than classical momentum. On smooth convex problems this sharpens the worst-case rate from to .3

Classical momentum vs. Nesterov. Momentum (red) evaluates at ; Nesterov (blue) evaluates it at the lookahead point, anticipating the surface ahead.

Adaptive learning rates

Momentum still uses one global . The second pathology is that different parameters need different rates: a weight that consistently sees large gradients should take small steps, a weight that rarely receives gradient should take large ones. Adaptive methods give each coordinate its own effective rate, scaled by the history of . The arithmetic is per-coordinate; the figure below shows the geometric effect: rescaling a stretched ellipse back toward a circle so a single step heads straight at the minimum.

Per-parameter rescaling. Raw GD (red) stalls along the flat axis; an adaptive method (blue) divides each coordinate by its gradient RMS, reshaping the ellipse toward a circle.

AdaGrad

AdaGrad accumulates the sum of squared gradients per coordinate and divides the step by its square root. Let be the running accumulator (a vector, one entry per parameter), elementwise product, division elementwise:

A coordinate with a long history of large gradients gets a large and so a small effective rate; a rarely-updated coordinate keeps a large rate. The only guards the division.4

The flaw is structural: only ever grows, so the effective rate decays monotonically to zero. On a long training run AdaGrad's steps shrink toward zero before reaching the minimum.

RMSProp

RMSProp removes the flaw with one change: replace the cumulative sum by an exponential moving average, so old gradients decay out of the accumulator and tracks only the recent gradient magnitude.

The decay (typically or ) gives a finite effective memory of about steps. The accumulator no longer grows without bound, so the effective rate stabilizes instead of vanishing.

Adam

Adam (Adaptive Moment Estimation) is the synthesis: momentum's first moment and RMSProp's second moment, each an exponential moving average, each bias-corrected. It is the default optimizer of modern deep learning.5

The numerator is the momentum direction; the denominator is the RMSProp per-parameter scale. Their ratio is a momentum step normalized by recent gradient magnitude: direction from the first moment, step-size from the second.

Why bias correction

The moving averages start at , which biases the early estimates toward zero. The correction undoes this exactly. Unroll the first-moment recurrence from zero, assuming a stationary gradient with :

Take expectations and pull out the constant mean:

The geometric sum leaves the factor , so underestimates by exactly that factor. Dividing it out gives an unbiased estimate, . The identical argument with corrects .

The correction factor is enormous at and decays to within a few hundred steps. It is a warm-up baked into the math: early steps, when the averages are unreliable, are scaled up to compensate.

At the very first step the correction is essential. With and a single gradient ,

Without correction the update would be , which for the defaults , carries a raw scale of instead of the intended — the first step would be more than too large. Bias correction restores it:

so and the first step has magnitude exactly , as intended. The correction and the initialization bias cancel term for term.

The bias-correction factor versus step . It decays to as a built-in warm-up; settles in tens of steps, in thousands.

The whole update is a five-stage pipeline: the gradient feeds two exponential moving averages, each is bias-corrected, and their ratio becomes a normalized step. The figure traces one gradient through it.

The Adam update as dataflow. The gradient feeds the first-moment EMA (direction) and second-moment EMA (scale); both are bias-corrected, then the normalized ratio scaled by updates .
Algorithm:Adam(L,θ,η,β1,β2,ϵ)\textsc{Adam}(L, \theta, \eta, \beta_1, \beta_2, \epsilon) — adaptive moment estimation
  1. 1
    initialize θ\theta randomly,\ m0, v0, t0m \gets 0,\ v \gets 0,\ t \gets 0
  2. 2
    repeat
  3. 3
    tt+1t \gets t + 1
  4. 4
    sample a minibatch; gθL(θ)g \gets \nabla_\theta L(\theta)
  5. 5
    mβ1m+(1β1)gm \gets \beta_1 \cdot m + (1 - \beta_1)\cdot g
    first moment EMA
  6. 6
    vβ2v+(1β2)(gg)v \gets \beta_2 \cdot v + (1 - \beta_2)\cdot (g \odot g)
    second moment EMA
  7. 7
    m^m/(1β1t)\hat m \gets m / (1 - \beta_1^{\,t})
    bias-correct
  8. 8
    v^v/(1β2t)\hat v \gets v / (1 - \beta_2^{\,t})
  9. 9
    θθηm^/(v^+ϵ)\theta \gets \theta - \eta \cdot \hat m / (\sqrt{\hat v} + \epsilon)
    per-parameter step
  10. 10
    until converged
  11. 11
    return θ\theta

AdamW: decoupled weight decay

Adding regularization to the loss is not the same as weight decay once an adaptive denominator is in play. The gradient enters , gets divided by , and so decays large-gradient weights less than small-gradient ones, the opposite of the intent. AdamW fixes this by applying the decay directly to the parameters, outside the adaptive update:6

Reading the defaults

Each default addresses a specific concern:

  • gives the first moment a memory of about steps — long enough to smooth minibatch noise in the direction, short enough to turn when the loss surface turns.
  • gives the second moment a memory of about steps. The per-parameter scale should reflect the typical gradient magnitude over a long window, so it is deliberately slower than the direction. A set too low makes jumpy and the effective rate spikes on any single large gradient.
  • only guards the division from a zero denominator. It is not a learning-rate knob, though raising it to or caps the effective rate for coordinates whose gradients are tiny, which stabilizes some models.
  • is the common starting point. Because is already normalized to roughly unit magnitude per coordinate, Adam's transfers across problems far better than SGD's, which must absorb the raw gradient scale.

Failure modes. Adam is not uniformly safe. Three recur:

  1. Second-moment stalls. A coordinate that saw one enormous gradient inflates ; its effective rate collapses and can take the full horizon to recover. This is why gradient clipping and tuning matter on RNNs and transformers.
  2. Worse generalization than SGD. On some vision benchmarks Adam converges faster but lands in sharper minima that test slightly worse; SGD with momentum remains a competitive final-accuracy baseline.5
  3. The /decay confusion. Passing a weight_decay to a plain-Adam implementation applies coupled , not true decay, and the effective regularization is uneven across parameters; AdamW is the fix and the modern transformer default.

The optimizer zoo

Every method here is one skeleton (accumulate something from the gradient history, step by a function of it) with different choices of what to keep. The master table collapses the family onto that axis.

OptimizerUpdate ruleState keptKey hyperparametersWhen to use
SGDnoneconvex / well-tuned baselines
Momentumvelocity ravines; large-batch vision
Nesterovvelocity smoother convex problems
AdaGradsum of sparse features (NLP)
RMSPropEMA of RNNs; non-stationary loss
Adam stepEMAs default for almost everything
AdamWAdam decoupledEMAs transformers; default with decay

On the ravine of the opening figure the three trajectories diverge in character: SGD zig-zags across the steep axis, momentum cancels the oscillation and coasts along the valley, and Adam heads almost straight at the minimum because its per-parameter denominator has already rescaled the steep axis down.

Trajectories on the same ravine. SGD (red) oscillates across the steep axis; momentum (green) damps the zig-zag; Adam (blue) rescales per axis and cuts a near-straight path.

The qualitative training curves separate the three regimes: SGD descends slowest and ripples, momentum smooths and steepens the descent, Adam drops fastest in the early phase by adapting per-parameter rates.

Qualitative loss-vs-iteration. SGD (black) descends slowly, momentum (green) accelerates it, and Adam (blue) drops fastest early; all reach a similar floor.

Optimizer refinements

Goodfellow's chapter predates most of the optimizer refinements now standard in practice; each is a public, named result that patches a specific failure listed above.

  • AdamW. The -vs-decay distinction of the previous section matters in practice: Loshchilov and Hutter showed that decoupled weight decay measurably improves generalization and makes the decay strength independent of the adaptive denominator. AdamW is now the default for transformer training, and the coupled form the original Adam paper used is treated as a bug.7
  • A convergence hole in the original proof. Reddi, Kale, and Kumar found a counterexample on which Adam fails to converge even on a convex problem, traced to the second moment being able to shrink between steps. Their AMSGrad fix enforces a non-decreasing , restoring the guarantee.8
  • Decoupling direction from scale, taken further. LAMB (You et al.) layer-wise normalizes the Adam step so that very large batches (used to train BERT in minutes) stay stable — the natural extension of the linear-scaling and warmup ideas to adaptive optimizers.9
  • Lion: a learned optimizer. Chen et al. used program search to discover an optimizer, Lion, which keeps only a momentum buffer and steps by the sign of the interpolated update — cheaper state than Adam and competitive or better on large vision and language models.10

Every one of these keeps the momentum-plus-per-parameter- scale skeleton and changes exactly one choice: how decay is applied, how is bounded, how the step is normalized across layers, or what nonlinearity maps the moments to the update.

Takeaways

  • Plain SGD fails on ill-conditioned surfaces (): one global must satisfy for stability, which leaves convergence along very slow.
  • Momentum accumulates a velocity and steps ; it amplifies persistent directions to an effective step and cancels oscillating ones, damping zig-zag.
  • Nesterov evaluates the gradient at the lookahead , braking before overshoot and improving the convex rate to .
  • AdaGrad gives per-parameter rates but the monotonically growing accumulator drives the rate to zero; RMSProp fixes it with an EMA of .
  • Adam fuses momentum (first moment) and RMSProp (second moment) with exact bias correction , and is the default; AdamW decouples weight decay so regularization strength is uniform across parameters.

Footnotes

  1. Goodfellow, Deep Learning, §8.3 — Basic Algorithms: SGD, momentum, and Nesterov as successive cures for the geometry of the loss surface.
  2. Goodfellow, Deep Learning, §8.3.2 — Momentum: the velocity recurrence read as a heavy ball with viscous friction.
  3. Goodfellow, Deep Learning, §8.3.3 — Nesterov Momentum: evaluating the gradient at the lookahead point and the convex rate.
  4. Goodfellow, Deep Learning, §8.5.1 — AdaGrad: per-parameter rates scaled by the accumulated squared gradient, and the vanishing-rate flaw.
  5. Goodfellow, Deep Learning, §8.5.3 — Adam: first- and second-moment EMAs with bias correction, the default adaptive optimizer. 2
  6. Chollet, Deep Learning with Python, §2.4, §3.6 — Optimizers in practice: choosing RMSProp/Adam and the role of weight decay in Keras training loops.
  7. Loshchilov & Hutter, Decoupled Weight Decay Regularization, ICLR 2019 — AdamW: applying weight decay to the parameters, not the gradient, so its strength is independent of .
  8. Reddi, Kale & Kumar, On the Convergence of Adam and Beyond, ICLR 2018 — a convex counterexample where Adam diverges, and the AMSGrad fix that keeps non-decreasing.
  9. You et al., Large Batch Optimization for Deep Learning: Training BERT in 76 Minutes, ICLR 2020 — LAMB, a layer-wise normalized Adam variant for very large batches.
  10. Chen et al., Symbolic Discovery of Optimization Algorithms, NeurIPS 2023 — Lion, a program-searched optimizer using only a momentum buffer and a sign update.

╌╌ END ╌╌