Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsOptimization

Momentum and adaptive steps (preview)

P1.F530 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Loss surfaces often contain long, narrow valleys where plain gradient descent zig-zags and crawls. Momentum and per-parameter step sizes are the two standard remedies, and the optimizers among the most widely used for deep networks are built from them.

  • SGD with momentum and the Adam family are among the most widely used optimizers for deep networks. Both are built from the two ideas in this lesson. (P4.13: Optimizers)
  • Valleys with very different curvature in different directions (a large condition number of the Hessian) are what make plain gradient descent slow, and what these methods try to fix. (P1.C8: The Hessian, curvature and Taylor approximation)
  • Large language models are commonly trained with AdamW, an Adam variant, which combines momentum, a separate step size for each parameter and weight decay. (P4.13: Optimizers)
  • Newton's method uses curvature directly to choose the step. Per-parameter step sizes are a much cheaper, rougher stand-in, so the next lesson is a good place to compare them. (P1.F6: Second-order methods)

Before this: Gradient descent, Stochastic and mini-batch gradient descent, The Hessian, curvature and Taylor approximation

After this lesson you can

  • Explain why plain gradient descent zig-zags in a narrow valley, and why a bigger learning rate does not fix it
  • Write the heavy-ball momentum update, run a few steps by hand, and say what β does
  • Say when momentum helps, when it hurts, and when a momentum step goes uphill
  • Describe the idea of per-parameter step sizes, and say when it helps and when it does not
  • Name Nesterov momentum, AdaGrad, RMSProp and Adam, and say what each adds

Picture a long, narrow valley with steep walls and a nearly flat floor that slopes gently down to a lake. An ant at the top of one wall feels only the slope under its feet. It steps down the steep wall, over-shoots to the other wall, steps back, and creeps along the valley floor a tiny bit each time. A heavy ball dropped in the same place does something different. It rolls across, but its inertia keeps it moving along the valley when the sideways pushes cancel, and it glides toward the lake.

This lesson turns the ball into an algorithm, and then adds a second idea: giving each parameter its own step size. It is a preview. P4.13 covers the optimizers used in practice in full.

The problem: a ravine

P1.F3 ended with the bowl x2+10y2x^2 + 10y^2. Its gradient is (2x,20y)(2x, 20y). The bowl curves 2 along xx and 20 along yy, so plain gradient descent multiplies xx by 1−2η1 - 2\eta and yy by 1−20η1 - 20\eta at every step. With η=0.095\eta = 0.095 those factors are 0.810.81 and −0.9-0.9: yy flips sign every step and shrinks only 10% at a time, while xx shrinks 19% at a time.

The same thing happens in any quadratic bowl. P1.C8 showed that the curvature along each eigen-direction of the Hessian is its eigenvalue λ\lambda (P1.B12 explains eigen-directions). Along a direction with eigenvalue λ\lambda the error is multiplied by 1−ηλ1 - \eta\lambda at every step. That is smaller than 1 in size only if η<2/λ\eta < 2/\lambda. So the steepest direction, with the largest eigenvalue λmax⁡\lambda_{\max}, caps the step size at η<2/λmax⁡\eta < 2/\lambda_{\max}. The shallowest direction, with λmin⁡\lambda_{\min}, then shrinks by only 1−ηλmin⁡1 - \eta\lambda_{\min} per step, which is close to 1.

The ratio κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} is the condition number. In this lesson the bowl is L(x,y)=x2+κy2\mathcal{L}(x, y) = x^2 + \kappa y^2, so the curvatures are 22 and 2κ2\kappa, the ratio is κ\kappa, and the limit is η<1/κ\eta < 1/\kappa. How many steps does plain gradient descent need? Start at (−3.5,1)(-3.5, 1), take η=0.95/κ\eta = 0.95/\kappa (just inside the limit), and count the steps until the loss is below 0.010.01 for good:

  • κ=10\kappa = 10 (the bowl of P1.F3): 33 steps.
  • κ=100\kappa = 100: 186 steps.
  • κ=1000\kappa = 1000: 1870 steps.

For large κ\kappa the count grows roughly in proportion to κ\kappa.

Look at what the gradient does in the two directions. Across the valley it flips sign at every step. Along the valley it keeps the same sign, but it is small. A method that remembers recent gradients could add up the part that keeps its sign and cancel the part that flips. That is momentum.

Heavy-ball momentum

Let g=∇L(θ)\mathbf{g} = \nabla\mathcal{L}(\boldsymbol{\theta}) be the gradient at the current point. Keep a second vector v\mathbf{v}, the velocity, which starts at zero. At every step:

v←β v+g,θ←θ−η v.\begin{aligned} \mathbf{v} &\leftarrow \beta\,\mathbf{v} + \mathbf{g},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\mathbf{v}. \end{aligned}

The number β\beta with 0≤β<10 \le \beta < 1 is the momentum coefficient. A common default is β=0.9\beta = 0.9. That is a habit that works for many networks, not a law. This rule is the heavy-ball method of Polyak (1964).

Unroll the first line and the velocity after step tt is a weighted sum of all the gradients so far, the newest first:

vt+1=gt+β gt−1+β2 gt−2+⋯\mathbf{v}_{t+1} = \mathbf{g}_t + \beta\,\mathbf{g}_{t-1} + \beta^2\,\mathbf{g}_{t-2} + \cdots

The weights 1,β,β2,…1, \beta, \beta^2, \dots fade away, so recent gradients count most. With β=0\beta = 0 nothing is remembered, v=g\mathbf{v} = \mathbf{g}, and this is plain gradient descent from P1.F3.

The ball picture: the gradient is a force that changes the velocity, and β\beta says how much of the old velocity is kept at each step. A real ball has friction, and 1−β1 - \beta plays that role. The picture breaks in one way: a real ball has a mass and moves smoothly through time, while this algorithm takes discrete jumps, so with a large η\eta it can behave in ways a ball would not.

Go deeper Other ways books write the momentum rule

Different books write the same idea in different forms. Two common ones:

  • u←βu−ηg\mathbf{u} \leftarrow \beta\mathbf{u} - \eta\mathbf{g}, then θ←θ+u\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} + \mathbf{u}. Here u=−ηv\mathbf{u} = -\eta\mathbf{v}, so the sequence of positions is exactly the same, with the same η\eta and β\beta.
  • A moving average: m←βm+(1−β)g\mathbf{m} \leftarrow \beta\mathbf{m} + (1 - \beta)\mathbf{g}, then θ←θ−η′m\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta'\mathbf{m}. Here m=(1−β)v\mathbf{m} = (1 - \beta)\mathbf{v}, so the positions are the same exactly when η′=η/(1−β)\eta' = \eta/(1 - \beta). Adam is written this way.

The rule in this lesson, v←βv+g\mathbf{v} \leftarrow \beta\mathbf{v} + \mathbf{g} with θ←θ−ηv\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{v}, is the one the PyTorch documentation gives for torch.optim.SGD with momentum, with its default dampening of 0. Running the code on the κ=10\kappa = 10 bowl confirms that the three forms give the same positions to about 10−1510^{-15}. When you read a paper or compare libraries, check which form is used before you compare learning rates.

A worked example by hand

Take the bowl of P1.F3, L=x2+10y2\mathcal{L} = x^2 + 10y^2, with gradient (2x,20y)(2x, 20y). Start at (−3.5,1)(-3.5, 1) with η=0.095\eta = 0.095 and β=0.5\beta = 0.5. At the start v=(0,0)\mathbf{v} = (0, 0).

Step 1. The gradient is (−7,20)(-7, 20). The velocity is 0.5⋅(0,0)+(−7,20)=(−7,20)0.5\cdot(0, 0) + (-7, 20) = (-7, 20). The point moves to (−3.5+0.095⋅7, 1−0.095⋅20)=(−2.835,−0.9)(-3.5 + 0.095\cdot 7,\ 1 - 0.095\cdot 20) = (-2.835, -0.9). This is the same as plain gradient descent, because the first velocity is just the gradient.

Step 2. The gradient is (−5.67,−18)(-5.67, -18). The velocity is 0.5⋅(−7,20)+(−5.67,−18)=(−9.17,−8)0.5\cdot(-7, 20) + (-5.67, -18) = (-9.17, -8). The yy part of the gradient pushes down, but the remembered velocity pushes up, and they nearly cancel. The point moves to (−2.835+0.871, −0.9+0.76)=(−1.964,−0.14)(-2.835 + 0.871,\ -0.9 + 0.76) = (-1.964, -0.14).

Step 3. The gradient is (−3.928,−2.8)(-3.928, -2.8). The velocity is 0.5⋅(−9.17,−8)+(−3.928,−2.8)=(−8.513,−6.8)0.5\cdot(-9.17, -8) + (-3.928, -2.8) = (-8.513, -6.8), and the point is (−1.155,0.506)(-1.155, 0.506).

Here is the same start under plain gradient descent, which multiplies xx by 0.810.81 and yy by −0.9-0.9 every step:

  • Plain gradient descent after 2 steps: (−2.296,0.81)(-2.296, 0.81), loss 11.8311.83. After 3 steps: (−1.86,−0.729)(-1.86, -0.729), loss 8.778.77.
  • Momentum after 2 steps: (−1.964,−0.14)(-1.964, -0.14), loss 4.054.05. After 3 steps: (−1.155,0.506)(-1.155, 0.506), loss 3.893.89.

After two steps momentum is much closer to the valley floor (yy near 0), and it has moved further along it (xx is −1.96-1.96 instead of −2.30-2.30). The sideways swing was cut down by the memory, and the steady push along the valley was kept. After 4 steps momentum has loss 0.460.46 and plain gradient descent has 6.576.57. (All numbers here were computed with code.)

Why the zig-zag cancels

Two small cases show what the velocity does with a gradient that does not change its size. Take β=0.9\beta = 0.9 and a one-number gradient of size 1.

  • The gradient keeps its sign. The velocity is 1, 1.9, 2.71, 3.439,…1,\ 1.9,\ 2.71,\ 3.439, \dots After tt steps it is (1−0.9t)/(1−0.9)(1 - 0.9^t)/(1 - 0.9), which climbs toward 1/(1−β)=101/(1 - \beta) = 10. It reaches 90% of that after 22 steps. So in a region with a steady slope, momentum ends up taking steps about 1/(1−β)=101/(1 - \beta) = 10 times as long as plain gradient descent with the same η\eta.
  • The gradient flips sign every step. The velocity is 1, −0.1, 0.91, −0.181, 0.837,…1,\ -0.1,\ 0.91,\ -0.181,\ 0.837, \dots It never builds up. Its size settles near 1/(1+β)≈0.531/(1 + \beta) \approx 0.53.

So the steady component along the valley is boosted by about 10, the flipping component across it by about 0.53, and the ratio is about 19. That is the whole trick. A small cell at the end of the lesson lets you run these two sequences.

The ravine race

In the widget below, the bowl is x′2+κy′2x'^2 + \kappa y'^2 where (x′,y′)(x', y') are the plot’s coordinates turned by a tilt you choose. All paths start at the circle. Blue is plain gradient descent, pink is momentum with the same η\eta. The step size is set as a multiple of 1/κ1/\kappa, so the value 1.00 is exactly the edge where plain gradient descent stops being stable.

Stretch κ (steep curvature ÷ shallow):
−4−2−2002244xy
plain GD (dots) momentum (squares) shared start minimum

Plain GD (blue) is not below 0.01 within 100 steps; its loss is 0.264 at the end. Momentum (pink) gets below 0.01 and stays there from step 47, while plain GD has not.

Loss 𝓛 against the step number, log scale (lower is better)

0.00010.0010.010.11101001000020406080100step

Values below 0.0001 are drawn on the bottom line.

Plain gradient descent
below 0.01 for good: not within 100 steps
loss at step 100: 0.264
lowest loss reached: 0.264
steps that raised the loss: 0
Momentum, β = 0.7
below 0.01 for good: step 47
loss at step 100: 1.6e−6
lowest loss reached: 1.6e−6
steps that raised the loss: 7
Loss 𝓛 = x′² + κ·y′², where (x′, y′) are the plot's coordinates turned by the tilt. Plain GD is stable for η below 1/κ and heavy-ball momentum for η below (1 + β)/κ. All paths start at the circle.

A step counts as raising the loss when the loss is higher than at the step before. “Below 0.01 for good” means the loss is under 0.01 at that step and at every step after it, up to the last step you chose.

Blue: plain gradient descent (dots). Pink: heavy-ball momentum (squares), same step size. Tick the box to add a third path, an RMSProp-style method (grey, dashed, diamonds) that you meet in the next sections. Press Play, then change β, the step size, the stretch κ and the tilt. Tick the arrows box and move the step slider to compare a gradient step (orange) with the momentum step (pink).

Things to try, all checked against the widget’s own rules (“below 0.01 for good” means the loss is under 0.01 at that step and at every step after it):

  • The defaults (κ=100\kappa = 100, η=0.0095\eta = 0.0095, β=0.7\beta = 0.7, 100 steps). Plain gradient descent zig-zags across the valley and is still at loss 0.2640.264 after 100 steps. It would need 186 (set the number of steps to 200 to see it arrive). Momentum is below 0.010.01 for good from step 47. The first five positions show why: plain gradient descent has y=1,−0.9,0.81,−0.729,…y = 1, -0.9, 0.81, -0.729, \dots and momentum has y=1,−0.9,−0.52,0.73,0.22,…y = 1, -0.9, -0.52, 0.73, 0.22, \dots, which wobbles but shrinks faster.
  • Set β=0\beta = 0. The pink path lies exactly on the blue one: the two methods are then the same numbers.
  • Raise β\beta with the same η\eta (set the number of steps to 300 first). For β=0.9\beta = 0.9 it takes 87 steps, and for β=0.95\beta = 0.95 it takes 181, almost as slow as plain gradient descent. At β=0.99\beta = 0.99 it has not settled after 300 steps. A big memory with the same η\eta means the ball rings back and forth. Count the “steps that raised the loss”: 7 for β=0.7\beta = 0.7 and 16 for β=0.9\beta = 0.9.
  • Raise the step size. At 1.05 times 1/κ1/\kappa plain gradient descent diverges after 25 steps, but momentum with β=0.7\beta = 0.7 is still stable and settles at step 42. At 1.5 plain gradient descent diverges after 4 steps and momentum still settles (step 31). Momentum is stable up to (1+β)/κ=1.7/κ(1 + \beta)/\kappa = 1.7/\kappa. At 1.8 both diverge, momentum after 5 steps. The widget stops a path when its loss passes 10,00010{,}000.
  • Change the stretch. With η=0.95/κ\eta = 0.95/\kappa and β=0.7\beta = 0.7: κ=10\kappa = 10 needs 33 steps for plain gradient descent and 23 for momentum. κ=300\kappa = 300 needs 560 against 161.
  • Tilt the bowl. Blue and pink follow exactly the same numbers at 45° as at 0° (186 and 47 steps for κ=100\kappa = 100), only turned. Plain gradient descent and momentum do not care which way the valley points.

Edge cases and limits

β=0\beta = 0 is plain gradient descent, as the widget shows.

When is momentum stable? On a quadratic, look at one eigen-direction with curvature λ\lambda. The gradient there is λθ\lambda\theta, and the update becomes θt+1=(1+β−ηλ) θt−β θt−1\theta_{t+1} = (1 + \beta - \eta\lambda)\,\theta_t - \beta\,\theta_{t-1}. This converges to zero if and only if both of these hold:

0≤β<1,0<ηλ<2(1+β).\begin{gathered} 0 \le \beta < 1,\\ 0 < \eta\lambda < 2(1 + \beta). \end{gathered}

For β=0\beta = 0 this is the familiar ηλ<2\eta\lambda < 2. A bigger β\beta even raises the stable limit of η\eta. On our bowl that limit is η<(1+β)/κ\eta < (1 + \beta)/\kappa. For κ=10\kappa = 10 and β=0.9\beta = 0.9 it is 0.190.19, twice the plain limit of 0.10.1. Running the code confirms it: η=0.189\eta = 0.189 converges and η=0.191\eta = 0.191 blows up.

Stable is not fast. On the κ=10\kappa = 10 bowl with the same η=0.095\eta = 0.095, plain gradient descent needs 33 steps. Momentum with β=0.5\beta = 0.5 needs 12, with β=0.7\beta = 0.7 it needs 23, and with β=0.9\beta = 0.9 it needs 72. The reason is ringing. With β=0.9\beta = 0.9 the update in each direction has complex roots of size 0.9≈0.95\sqrt{0.9} \approx 0.95 (see the Math tab), so the error swings back and forth and shrinks by only about 5% per step, slower than plain gradient descent’s factors of 0.90.9 and 0.810.81. Momentum helps only when η\eta and β\beta fit each other and the problem, so people usually tune them together. Which β\beta is best depends on the problem; 0.90.9 is a common starting point, not a result of this lesson.

It can overshoot and come back. Take the one-number bowl L=θ2\mathcal{L} = \theta^2 from P1.F3 (curvature 2), start at θ=3\theta = 3, and use η=0.1\eta = 0.1, β=0.9\beta = 0.9. Plain gradient descent just multiplies θ\theta by 0.80.8 each step, so it goes 33, 2.42.4, 1.921.92, and so on, and never changes sign. Momentum goes 33, 2.42.4, 1.381.38, 0.1860.186, −0.926-0.926, −1.741-1.741, −2.127-2.127, and so on. It passes through the minimum at step 4, swings to −2.13-2.13, and comes back. It crosses zero again at steps 10, 17 and 24, with shrinking swings.

Is a momentum step downhill?

P1.C6 gave the test. For a small step in direction d\mathbf{d}, the loss changes by about g⋅d\mathbf{g}\cdot\mathbf{d}, so the step goes downhill, to first order, exactly when that number is negative. A momentum step is d=−ηv\mathbf{d} = -\eta\mathbf{v}, so it goes downhill when g⋅v>0\mathbf{g}\cdot\mathbf{v} > 0. Because v=βvold+g\mathbf{v} = \beta\mathbf{v}_{\text{old}} + \mathbf{g}, this is

g⋅v=∥g∥2+β g⋅vold.\mathbf{g}\cdot\mathbf{v} = \lVert\mathbf{g}\rVert^2 + \beta\,\mathbf{g}\cdot\mathbf{v}_{\text{old}}.

For plain gradient descent only the first term is there, so it is always positive. For momentum the second term can be negative and large, when the old velocity points against the current gradient. In the one-number example above:

  • Step 3: g⋅v=33.0\mathbf{g}\cdot\mathbf{v} = 33.0. Downhill, and the loss falls from 1.9041.904 to 0.0350.035.
  • Step 4: g⋅v=4.14\mathbf{g}\cdot\mathbf{v} = 4.14. Still downhill to first order, but the loss rises from 0.0350.035 to 0.8570.857. The step is so long that the straight-line estimate fails: it overshot.
  • Step 5: g⋅v=−15.1\mathbf{g}\cdot\mathbf{v} = -15.1. Uphill even to first order, because the old velocity still points toward the wrong side. The loss rises from 0.8570.857 to 3.033.03.
  • Step 6: g⋅v=−13.4\mathbf{g}\cdot\mathbf{v} = -13.4, and the loss rises again to 4.524.52.
  • Step 7: g⋅v=3.33\mathbf{g}\cdot\mathbf{v} = 3.33, and the loss falls again, to 4.204.20.

So the loss under momentum is not monotone: it can rise for several steps in a row while the ball swings through the valley. In the widget, tick the arrows box, set β=0.9\beta = 0.9 and slide the step to see steps where the pink arrow’s first-order change is positive. Plain gradient descent on a quadratic with η\eta below the limit never raises the loss, even while it zig-zags: in every eigen-direction the loss part is multiplied by (1−ηλ)2(1 - \eta\lambda)^2, which is below 1.

Go deeper How much faster can momentum be, at best?

For a quadratic bowl with curvatures between λmin⁡\lambda_{\min} and λmax⁡\lambda_{\max}, Polyak showed that the best constant choice is

η=4(λmax⁡+λmin⁡)2,β=(κ−1κ+1)2.\begin{aligned} \eta &= \frac{4}{(\sqrt{\lambda_{\max}} + \sqrt{\lambda_{\min}})^2},\\ \beta &= \left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^2. \end{aligned}

The error then shrinks by a factor (κ−1)/(κ+1)(\sqrt{\kappa} - 1)/(\sqrt{\kappa} + 1) per step. The best plain gradient descent shrinks it by (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1). For κ=100\kappa = 100 these are 0.8180.818 and 0.9800.980. To shrink the error by a factor of a million takes about 69 steps with tuned momentum and about 691 without it. The ratio is about κ=10\sqrt{\kappa} = 10. For κ=1000\kappa = 1000 the ratio is about 32. Computing the spectral radius numerically confirms the rates.

So the step count scales like κ\sqrt{\kappa} instead of κ\kappa. This is a result for quadratics. For general losses nothing this clean is guaranteed, and for neural networks the benefit is shown by experience, not by this formula.

Go deeper Nesterov momentum: look ahead first

Nesterov (1983) changed one thing: evaluate the gradient at the point the velocity is about to carry you to, not at the current point:

v←βv+∇L(θ−ηβ v),θ←θ−η v.\begin{aligned} \mathbf{v} &\leftarrow \beta\mathbf{v} + \nabla\mathcal{L}\big(\boldsymbol{\theta} - \eta\beta\,\mathbf{v}\big),\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\mathbf{v}. \end{aligned}

The idea: if the ball is about to overshoot, the gradient at the look-ahead point already says “turn back”, so the correction comes one step earlier. With suitable coefficients it has a better worst-case guarantee than plain gradient descent for smooth convex functions (an error shrinking like 1/k21/k^2 rather than 1/k1/k). Libraries often write it in an algebraically rearranged form, and running the code shows that the form above and the common textbook form give the same positions. P4.13 compares it with the heavy ball in practice. The form above has a narrower stable range than the heavy ball. On a quadratic with curvature λ\lambda and β=0.9\beta = 0.9 it needs ηλ<2(1+β)/(1+2β)≈1.36\eta\lambda < 2(1 + \beta)/(1 + 2\beta) \approx 1.36, where the heavy ball allows ηλ<3.8\eta\lambda < 3.8. On the κ=100\kappa = 100 bowl (λmax⁡=200\lambda_{\max} = 200) that means η\eta below about 0.00680.0068: η=0.0066\eta = 0.0066 converges and 0.00680.0068 blows up. So at η=0.0095\eta = 0.0095 it diverges, while the heavy ball settles at step 87. It is not simply a better version for every setting.

Momentum and noisy gradients

P1.F4 said that momentum “averages recent gradients”, and an average smooths noise. That is true, with a catch. In P1.F4 the mini-batch gradient is the true gradient plus random noise, and with a fixed η\eta the path hovers in a noise ball. Momentum averages about the last 1/(1−β)1/(1 - \beta) gradients, but its sum is also that much bigger. For one parameter in a quadratic bowl, with small η\eta and fresh, independent noise at every step, the size of the wobble can be computed exactly, and a seeded simulation of a million steps agrees. Compared with plain SGD at the same η\eta, the mean squared distance from the minimum is larger by a factor of about 22 for β=0.5\beta = 0.5 and about 1010 for β=0.9\beta = 0.9, which is 1/(1−β)1/(1 - \beta) for small η\eta. (For curvature 1, noise size 1 and η=0.01\eta = 0.01 the exact factors are 1.9971.997 and 9.989.98.)

So at the same η\eta, momentum does not shrink the hovering. It behaves like plain SGD with a step size of η/(1−β)\eta/(1 - \beta). To keep the noise ball the same size you lower η\eta by the factor 1−β1 - \beta, and then what momentum gives you is the faster travel along the valley that this lesson showed. This is the simple case of one bowl direction with independent noise. Real networks are messier.

Rolling through flat parts and small dips

P1.F2 and P1.F3 showed that gradient descent can crawl across flat regions and settle in the first valley it finds. Momentum can change both, but “can” is the right word.

  • Flat stretch. On f(x)=x4f(x) = x^4 from x=1x = 1 with η=0.1\eta = 0.1, plain gradient descent is at x=0.109x = 0.109 after 100 steps and 0.0350.035 after 1000 (the numbers in P1.F3). With β=0.9\beta = 0.9 it passes through zero and is at ∣x∣=0.049|x| = 0.049 after 100 steps and 0.0110.011 after 1000.
  • A shallow valley. On the two-valley curve x4/4−x2+0.4xx^4/4 - x^2 + 0.4x of P1.F3, from x=2x = 2 with η=0.1\eta = 0.1, plain gradient descent settles in the shallow right valley at x≈1.30x \approx 1.30. Momentum with β=0.9\beta = 0.9 carries the ball over the hill and ends in the deeper left valley at x≈−1.51x \approx -1.51. But with β=0.8\beta = 0.8 or less it still ends in the right valley.

So momentum can carry a ball over a bump or across a plateau, and the result depends on β\beta and the start. It is not a reliable way to find the best valley.

Adaptive steps: a step size for each parameter

Momentum fixes the ravine by remembering the past. A second idea attacks the same trouble from another side. In a real model the parameters can have gradients of very different sizes, so one η\eta is too big for some and too small for others. What if every parameter had its own step size?

The simplest recipe keeps, for each parameter separately, a running average of its squared gradient, and divides that parameter’s step by the square root of it. Here is the RMSProp-style version used in the widget. Everything is done one coordinate at a time, and ss starts at 0:

s←ρ s+(1−ρ) g2,θ←θ−η gs+ε.\begin{aligned} s &\leftarrow \rho\,s + (1 - \rho)\,g^2,\\ \theta &\leftarrow \theta - \frac{\eta\, g}{\sqrt{s} + \varepsilon}. \end{aligned}

Here ρ=0.9\rho = 0.9 sets how long the average remembers, and ε\varepsilon is a tiny number (10−810^{-8} here) that keeps the division safe when ss is nearly zero. The quantity s\sqrt{s} is the typical size of that coordinate’s recent gradients. So the step is about η\eta times the direction of the gradient (its sign), whatever its size. A steep coordinate with big gradients and a shallow coordinate with tiny gradients both move by roughly η\eta per step.

On the ravine that is what you want. The gradient (2x,2κy)(2x, 2\kappa y) is about κ\kappa times bigger in yy than in xx, yet the first step is η⋅3.16\eta\cdot 3.16 in each coordinate, because the average starts at zero and so ss is 0.1 g20.1\,g^2 after the first step. In the widget, tick “Add an RMSProp-style path” with κ=100\kappa = 100 and η=0.05\eta = 0.05. The first step is (+0.158,−0.158)(+0.158, -0.158), and the path heads for the valley floor without the sideways swings of plain gradient descent.

Three honest limits:

  • This rule does not settle with a constant η\eta. With the short average ρ=0.9\rho = 0.9, each step has a size of about η\eta regardless of how near the minimum is, so the path hovers around it. In the widget at κ=100\kappa = 100, η=0.05\eta = 0.05: the lowest loss in 100 steps is 1.9×10−51.9\times 10^{-5}, but the loss at step 100 is 0.0600.060. That is the same hovering as in P1.F4, and one reason learning rates are shrunk over time (P4.14). With a smaller η\eta, such as 0.02, it is still travelling at step 100 (loss about 2.12.1). This is shown for this rule only. Other adaptive methods behave differently: AdaGrad’s steps keep shrinking, and Adam with its default settings can converge on a smooth, noise-free bowl like this one. They can still keep moving at a scale set by η\eta, especially with noisy gradients, which is why η\eta is usually reduced over time (P4.14).
  • It works best when the valley lines up with the axes. A per-coordinate rule can only treat the coordinates separately. Tilt the bowl and the valley floor no longer runs along an axis. With the ideal diagonal rescaling (divide each coordinate by the square root of the bowl’s curvature along that coordinate), the condition number of the κ=100\kappa = 100 bowl becomes 11 at 0°, 26.526.5 at 15°, 75.575.5 at 30° and 100100 at 45°, where both coordinates have the same curvature (101) and rescaling changes nothing. These numbers come from computing the eigenvalues with code. A real adaptive method is not exactly this ideal rescaling, but in the widget the grey path ends at loss 0.0600.060 when the bowl is untilted and 0.3960.396 at 45° (same η=0.05\eta = 0.05, 100 steps), while the blue and pink paths do not change.
  • It still needs a learning rate. It replaces “which η\eta fits every parameter” with “which one overall size η\eta fits”, but you still choose η\eta, and it changes the result a lot.

A related caution for the next lesson. Dividing a step by the curvature is what Newton’s method does (P1.F6), and on a bowl whose axes are the coordinates this is exactly the per-coordinate rescaling above. Adaptive methods divide by the size of recent gradients, not by curvature, so they are only a rough, cheap stand-in.

Go deeper AdaGrad, RMSProp and Adam: who added what
  • AdaGrad (Duchi, Hazan and Singer, 2011) divides each coordinate by the square root of the sum of all its past squared gradients. The sum only grows, so steps keep shrinking, which helps convergence and can make training stall.
  • RMSProp replaces the sum with the moving average used above. It was introduced in Geoffrey Hinton’s lecture notes for his 2012 Coursera course, not in a paper.
  • Adam (Kingma and Ba, posted in December 2014, published at ICLR 2015) adds momentum to the gradient and uses an RMSProp-style average of squares, with a correction for the fact that both averages start at zero:
m←β1m+(1−β1) g,s←β2s+(1−β2) g2,m^=m1−β1 t,s^=s1−β2 t,θ←θ−η m^s^+ε.\begin{aligned} \mathbf{m} &\leftarrow \beta_1\mathbf{m} + (1 - \beta_1)\,\mathbf{g},\\ \mathbf{s} &\leftarrow \beta_2\mathbf{s} + (1 - \beta_2)\,\mathbf{g}^2,\\ \hat{\mathbf{m}} &= \frac{\mathbf{m}}{1 - \beta_1^{\,t}},\\ \hat{\mathbf{s}} &= \frac{\mathbf{s}}{1 - \beta_2^{\,t}},\\ \boldsymbol{\theta} &\leftarrow \boldsymbol{\theta} - \eta\,\frac{\hat{\mathbf{m}}}{\sqrt{\hat{\mathbf{s}}} + \varepsilon}. \end{aligned}

The paper’s suggested defaults are η=0.001\eta = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 and ε=10−8\varepsilon = 10^{-8}. At the first step t=1t = 1 the correction makes m^=g\hat{\mathbf{m}} = \mathbf{g} and s^=g2\hat{\mathbf{s}} = \mathbf{g}^2, so each coordinate moves by almost exactly η\eta (a numerical check confirms this). Without the correction both averages start too small, because they start at zero, but s\mathbf{s} is shrunk far more (by 1−β2=0.0011-\beta_2 = 0.001 against 1−β1=0.11-\beta_1 = 0.1). With a steady gradient the first step would be about 3.16 η3.16\,\eta and the tenth about 6.5 η6.5\,\eta: the early steps would be too large, not too small.

P4.13 covers these in full, including AdamW, which handles weight decay separately and is the variant commonly used for large language models.

In practice

  • SGD with momentum and Adam-family optimizers are among the most widely used choices for training deep networks. Which one is better depends on the model, the data and the tuning, and practitioners disagree. P4.13 compares them.
  • Defaults: β=0.9\beta = 0.9 for momentum is a very common starting value. For Adam the paper’s values are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ε=10−8\varepsilon = 10^{-8}. Check the defaults of your library: in PyTorch the momentum argument of torch.optim.SGD is 0 unless you set it.
  • Everything still needs a learning rate, and it is usually changed during training (P4.14).
  • Mini-batch noise (P1.F4) is there with all of these. The momentum and the per-parameter scaling are applied to the noisy batch gradient.

The recipe in one place

Intuition

A heavy ball in a narrow valley. The sideways pushes alternate, so they cancel in its velocity. The push along the valley keeps the same sign, so it adds up, and the ball speeds up along the valley floor. If it has too much speed (a large β\beta with a large η\eta) it overshoots the bottom and rolls back and forth before it settles.

A per-parameter step size is a different fix: each parameter gets a gain, turned down for parameters that have had big gradients and up for parameters that have had small ones, so all of them move at a similar pace.

Math

Heavy ball, with gradient gt=∇L(θt)\mathbf{g}_t = \nabla\mathcal{L}(\boldsymbol{\theta}_t) and v0=0\mathbf{v}_0 = \mathbf{0}:

vt+1=β vt+gt,θt+1=θt−η vt+1.\begin{aligned} \mathbf{v}_{t+1} &= \beta\,\mathbf{v}_t + \mathbf{g}_t,\\ \boldsymbol{\theta}_{t+1} &= \boldsymbol{\theta}_t - \eta\,\mathbf{v}_{t+1}. \end{aligned}
  • Unrolled: vt+1=∑k=0tβk gt−k\mathbf{v}_{t+1} = \sum_{k=0}^{t}\beta^k\,\mathbf{g}_{t-k}.
  • Steady gradient g\mathbf{g}: vt=1−βt1−β g→g1−β\mathbf{v}_t = \frac{1 - \beta^t}{1 - \beta}\,\mathbf{g} \to \frac{\mathbf{g}}{1 - \beta}.
  • Gradient that flips sign every step: ∣v∣→∣g∣1+β\lvert\mathbf{v}\rvert \to \frac{\lvert\mathbf{g}\rvert}{1 + \beta}.
  • Quadratic, one direction with curvature λ\lambda: the characteristic equation is z2−(1+β−ηλ) z+β=0z^2 - (1 + \beta - \eta\lambda)\,z + \beta = 0. Both roots lie inside the unit circle exactly when 0≤β<10 \le \beta < 1 and 0<ηλ<2(1+β)0 < \eta\lambda < 2(1 + \beta). When the roots are complex their size is β\sqrt{\beta}: the error rings and shrinks by β\sqrt{\beta} per step.
  • Downhill test: to first order the step goes downhill exactly when g⋅vt+1>0\mathbf{g}\cdot\mathbf{v}_{t+1} > 0.

RMSProp-style, per coordinate: s←ρs+(1−ρ)g2s \leftarrow \rho s + (1 - \rho)g^2, θ←θ−ηg/(s+ε)\theta \leftarrow \theta - \eta g/(\sqrt{s} + \varepsilon). Its step direction −g/(s+ε)-\mathbf{g}/(\sqrt{\mathbf{s}} + \varepsilon) (elementwise) has a negative dot product with g\mathbf{g} whenever g≠0\mathbf{g} \ne \mathbf{0}, so it is a downhill direction to first order.

Code

import numpy as np

def heavy_ball(grad, theta, eta, beta, steps):
    v = np.zeros_like(theta)
    for _ in range(steps):
        v = beta * v + grad(theta)      # the velocity remembers past gradients
        theta = theta - eta * v         # beta = 0 gives plain gradient descent
    return theta

In PyTorch the same rule is a keyword, and Adam is a different class. Adam is written here with the paper’s values. P4.13 uses them in a full training loop.

opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
opt = torch.optim.Adam(model.parameters(), lr=1e-3,
                       betas=(0.9, 0.999), eps=1e-8)
Try it: plain gradient descent, momentum and an RMSProp-style rule

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Now the two velocity sequences from the “zig-zag cancels” section, so you can see the 1/(1−β)1/(1 - \beta) and 1/(1+β)1/(1 + \beta) limits appear.

Try it: the velocity of a steady and a flipping gradient

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Check your understanding

  1. In a long narrow valley, why can plain gradient descent not simply use a much bigger learning rate to go faster?

  2. In the heavy-ball update v←βv+g\mathbf{v} \leftarrow \beta\mathbf{v} + \mathbf{g}, θ←θ−ηv\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\mathbf{v}, what happens when β=0\beta = 0?

  3. A gradient equals 1 at every step and β=0.9\beta = 0.9. What does the velocity approach?

  4. Why does momentum help in a ravine?

  5. A bowl is tilted by 45 degrees so that its long valley runs diagonally. Which statement is right?

Exercises

  1. With β=0.9\beta = 0.9 and a gradient of 1 at every step, what are the velocities after steps 1, 2 and 3?
    Show answerv1=1v_1 = 1, v2=0.9⋅1+1=1.9v_2 = 0.9\cdot 1 + 1 = 1.9, v3=0.9⋅1.9+1=2.71v_3 = 0.9\cdot 1.9 + 1 = 2.71.
  2. In the moving-average form m←βm+(1−β)g\mathbf{m} \leftarrow \beta\mathbf{m} + (1 - \beta)\mathbf{g}, θ←θ−η′m\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta'\mathbf{m}, with β=0.9\beta = 0.9 and η′=0.5\eta' = 0.5, which η\eta gives the same positions in this lesson’s form?
    Show answerη=η′(1−β)=0.5×0.1=0.05\eta = \eta'(1 - \beta) = 0.5 \times 0.1 = 0.05, since m=(1−β)v\mathbf{m} = (1 - \beta)\mathbf{v}.
  3. A bowl has κ=50\kappa = 50 (curvatures 22 and 100100). What are the largest stable η\eta for plain gradient descent and for momentum with β=0.9\beta = 0.9?
    Show answerPlain: 2/λmax⁡=2/100=0.022/\lambda_{\max} = 2/100 = 0.02. Momentum: 2(1+0.9)/100=0.0382(1 + 0.9)/100 = 0.038.
  4. A parameter has gradient g=3g = 3 at the first RMSProp-style step (ρ=0.9\rho = 0.9, s=0s = 0 before, ignore ε\varepsilon), and another has g=−0.002g = -0.002. How big is each step?
    Show answers=0.1 g2s = 0.1\,g^2, so the step is ηg/(0.1 ∣g∣)=η⋅3.16\eta g/(\sqrt{0.1}\,\lvert g\rvert) = \eta\cdot 3.16 in size for both: −3.16 η-3.16\,\eta for the first and +3.16 η+3.16\,\eta for the second. The gradients differ by a factor of 1500 and the steps do not.
  5. Momentum with β=0.9\beta = 0.9, η=0.01\eta = 0.01 moves along a long, gentle slope where the gradient is steady at 2. After a long time, how far does it move per step, and how far would plain gradient descent move with the same η\eta?
    Show answerMomentum: about η⋅2/(1−0.9)=0.2\eta\cdot 2/(1 - 0.9) = 0.2 per step. Plain: 0.01⋅2=0.020.01\cdot 2 = 0.02. Momentum is ten times faster here.
  6. For the bowl with κ=100\kappa = 100 tilted by 45 degrees, both coordinates have curvature 101 on the diagonal of the Hessian. What does diagonal rescaling do to the condition number?
    Show answerNothing: it stays 100, because every coordinate is divided by the same number. The ravine runs along the diagonal, which no per-coordinate rescaling can see.

Next: P1.F6 uses curvature itself to choose the step (Newton’s method). P4.13 returns to momentum, Nesterov, AdaGrad, RMSProp, Adam and AdamW with full training runs, and P4.14 shows how learning rates are changed during training.

Key takeaways

  • In a stretched bowl, plain gradient descent must keep η below 2/λmax, set by the steepest direction. It then crawls along the shallow direction, and the number of steps grows roughly in proportion to the condition number κ.
  • Heavy-ball momentum keeps a velocity: v ← βv + g, then θ ← θ − ηv. The velocity is a weighted sum of past gradients, with weights 1, β, β², and so on.
  • A gradient that keeps its sign builds up the velocity, up to 1/(1 − β) times the gradient (10 times for β = 0.9). A gradient that flips sign every step mostly cancels.
  • β = 0 is plain gradient descent. On a quadratic, momentum is stable when 0 ≤ β < 1 and ηλ < 2(1 + β) in every curvature direction λ. Stable is not the same as fast: with a big β the same η can ring and be slower than plain gradient descent.
  • A momentum step can overshoot the minimum and can go uphill. To first order it goes downhill exactly when the gradient and the velocity have a positive dot product.
  • Adaptive methods divide each coordinate's step by a running scale of its own gradients, so every parameter moves by a similar amount. This works best when the valley lines up with the coordinate axes.
  • AdaGrad (2011), RMSProp (about 2012) and Adam (2014) build on this. Adam adds momentum and a correction for its start-up. They still need a learning rate. With a constant one they can keep moving at a scale set by η, especially with noisy gradients, so η is usually reduced over time.
  • Momentum with a fixed η makes the noise from mini-batches larger, by about 1/(1 − β) in the simple case checked here. Its main gain is speed along the valley. P4.13 gives the full treatment.
Found a mistake? Tell us