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 . Its gradient is . The bowl curves 2 along and 20 along , so plain gradient descent multiplies by and by at every step. With those factors are and : flips sign every step and shrinks only 10% at a time, while 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 (P1.B12 explains eigen-directions). Along a direction with eigenvalue the error is multiplied by at every step. That is smaller than 1 in size only if . So the steepest direction, with the largest eigenvalue , caps the step size at . The shallowest direction, with , then shrinks by only per step, which is close to 1.
The ratio is the condition number. In this lesson the bowl is , so the curvatures are and , the ratio is , and the limit is . How many steps does plain gradient descent need? Start at , take (just inside the limit), and count the steps until the loss is below for good:
- (the bowl of P1.F3): 33 steps.
- : 186 steps.
- : 1870 steps.
For large the count grows roughly in proportion to .
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 be the gradient at the current point. Keep a second vector , the velocity, which starts at zero. At every step:
The number with is the momentum coefficient. A common default is . 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 is a weighted sum of all the gradients so far, the newest first:
The weights fade away, so recent gradients count most. With nothing is remembered, , and this is plain gradient descent from P1.F3.
The ball picture: the gradient is a force that changes the velocity, and says how much of the old velocity is kept at each step. A real ball has friction, and 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 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:
- , then . Here , so the sequence of positions is exactly the same, with the same and .
- A moving average: , then . Here , so the positions are the same exactly when . Adam is written this way.
The rule in this lesson, with , is the one the PyTorch documentation gives for torch.optim.SGD with momentum, with its default dampening of 0. Running the code on the bowl confirms that the three forms give the same positions to about . 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, , with gradient . Start at with and . At the start .
Step 1. The gradient is . The velocity is . The point moves to . This is the same as plain gradient descent, because the first velocity is just the gradient.
Step 2. The gradient is . The velocity is . The part of the gradient pushes down, but the remembered velocity pushes up, and they nearly cancel. The point moves to .
Step 3. The gradient is . The velocity is , and the point is .
Here is the same start under plain gradient descent, which multiplies by and by every step:
- Plain gradient descent after 2 steps: , loss . After 3 steps: , loss .
- Momentum after 2 steps: , loss . After 3 steps: , loss .
After two steps momentum is much closer to the valley floor ( near 0), and it has moved further along it ( is instead of ). The sideways swing was cut down by the memory, and the steady push along the valley was kept. After 4 steps momentum has loss and plain gradient descent has . (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 and a one-number gradient of size 1.
- The gradient keeps its sign. The velocity is After steps it is , which climbs toward . It reaches 90% of that after 22 steps. So in a region with a steady slope, momentum ends up taking steps about times as long as plain gradient descent with the same .
- The gradient flips sign every step. The velocity is It never builds up. Its size settles near .
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 where 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 . The step size is set as a multiple of , so the value 1.00 is exactly the edge where plain gradient descent stops being stable.
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 steps). Plain gradient descent zig-zags across the valley and is still at loss after 100 steps. It would need 186 (set the number of steps to 200 to see it arrive). Momentum is below for good from step 47. The first five positions show why: plain gradient descent has and momentum has , which wobbles but shrinks faster.
- Set . The pink path lies exactly on the blue one: the two methods are then the same numbers.
- Raise with the same (set the number of steps to 300 first). For it takes 87 steps, and for it takes 181, almost as slow as plain gradient descent. At it has not settled after 300 steps. A big memory with the same means the ball rings back and forth. Count the “steps that raised the loss”: 7 for and 16 for .
- Raise the step size. At 1.05 times plain gradient descent diverges after 25 steps, but momentum with 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 . At 1.8 both diverge, momentum after 5 steps. The widget stops a path when its loss passes .
- Change the stretch. With and : needs 33 steps for plain gradient descent and 23 for momentum. 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 ), only turned. Plain gradient descent and momentum do not care which way the valley points.
Edge cases and limits
is plain gradient descent, as the widget shows.
When is momentum stable? On a quadratic, look at one eigen-direction with curvature . The gradient there is , and the update becomes . This converges to zero if and only if both of these hold:
For this is the familiar . A bigger even raises the stable limit of . On our bowl that limit is . For and it is , twice the plain limit of . Running the code confirms it: converges and blows up.
Stable is not fast. On the bowl with the same , plain gradient descent needs 33 steps. Momentum with needs 12, with it needs 23, and with it needs 72. The reason is ringing. With the update in each direction has complex roots of size (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 and . Momentum helps only when and fit each other and the problem, so people usually tune them together. Which is best depends on the problem; is a common starting point, not a result of this lesson.
It can overshoot and come back. Take the one-number bowl from P1.F3 (curvature 2), start at , and use , . Plain gradient descent just multiplies by each step, so it goes , , , and so on, and never changes sign. Momentum goes , , , , , , , and so on. It passes through the minimum at step 4, swings to , 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 , the loss changes by about , so the step goes downhill, to first order, exactly when that number is negative. A momentum step is , so it goes downhill when . Because , this is
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: . Downhill, and the loss falls from to .
- Step 4: . Still downhill to first order, but the loss rises from to . The step is so long that the straight-line estimate fails: it overshot.
- Step 5: . Uphill even to first order, because the old velocity still points toward the wrong side. The loss rises from to .
- Step 6: , and the loss rises again to .
- Step 7: , and the loss falls again, to .
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 and slide the step to see steps where the pink arrow’s first-order change is positive. Plain gradient descent on a quadratic with below the limit never raises the loss, even while it zig-zags: in every eigen-direction the loss part is multiplied by , which is below 1.
Go deeper How much faster can momentum be, at best?
For a quadratic bowl with curvatures between and , Polyak showed that the best constant choice is
The error then shrinks by a factor per step. The best plain gradient descent shrinks it by . For these are and . 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 . For the ratio is about 32. Computing the spectral radius numerically confirms the rates.
So the step count scales like instead of . 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:
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 rather than ). 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 and it needs , where the heavy ball allows . On the bowl () that means below about : converges and blows up. So at 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 the path hovers in a noise ball. Momentum averages about the last gradients, but its sum is also that much bigger. For one parameter in a quadratic bowl, with small 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 , the mean squared distance from the minimum is larger by a factor of about for and about for , which is for small . (For curvature 1, noise size 1 and the exact factors are and .)
So at the same , momentum does not shrink the hovering. It behaves like plain SGD with a step size of . To keep the noise ball the same size you lower by the factor , 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 from with , plain gradient descent is at after 100 steps and after 1000 (the numbers in P1.F3). With it passes through zero and is at after 100 steps and after 1000.
- A shallow valley. On the two-valley curve of P1.F3, from with , plain gradient descent settles in the shallow right valley at . Momentum with carries the ball over the hill and ends in the deeper left valley at . But with 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 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 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 starts at 0:
Here sets how long the average remembers, and is a tiny number ( here) that keeps the division safe when is nearly zero. The quantity is the typical size of that coordinate’s recent gradients. So the step is about 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 per step.
On the ravine that is what you want. The gradient is about times bigger in than in , yet the first step is in each coordinate, because the average starts at zero and so is after the first step. In the widget, tick “Add an RMSProp-style path” with and . The first step is , 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 . With the short average , each step has a size of about regardless of how near the minimum is, so the path hovers around it. In the widget at , : the lowest loss in 100 steps is , but the loss at step 100 is . That is the same hovering as in P1.F4, and one reason learning rates are shrunk over time (P4.14). With a smaller , such as 0.02, it is still travelling at step 100 (loss about ). 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 , especially with noisy gradients, which is why 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 bowl becomes at 0°, at 15°, at 30° and 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 when the bowl is untilted and at 45° (same , 100 steps), while the blue and pink paths do not change.
- It still needs a learning rate. It replaces “which fits every parameter” with “which one overall size fits”, but you still choose , 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:
The paper’s suggested defaults are , , and . At the first step the correction makes and , so each coordinate moves by almost exactly (a numerical check confirms this). Without the correction both averages start too small, because they start at zero, but is shrunk far more (by against ). With a steady gradient the first step would be about and the tenth about : 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: for momentum is a very common starting value. For Adam the paper’s values are , , . Check the defaults of your library: in PyTorch the
momentumargument oftorch.optim.SGDis 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 with a large ) 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 and :
- Unrolled: .
- Steady gradient : .
- Gradient that flips sign every step: .
- Quadratic, one direction with curvature : the characteristic equation is . Both roots lie inside the unit circle exactly when and . When the roots are complex their size is : the error rings and shrinks by per step.
- Downhill test: to first order the step goes downhill exactly when .
RMSProp-style, per coordinate: , . Its step direction (elementwise) has a negative dot product with whenever , 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 thetaIn 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)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 and limits appear.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Check your understanding
In a long narrow valley, why can plain gradient descent not simply use a much bigger learning rate to go faster?
Along the steepest direction the error is multiplied by per step, and this grows in size once passes . The gradient still points the right way, the shallow direction is not the one that blows up, and nothing in the rule forbids large values; what matters is the curvature, not the number 1.
In the heavy-ball update , , what happens when ?
With the old velocity is forgotten, so and the step is . The velocity cannot grow without limit for any below 1 when the gradient stays bounded, and Adam needs the squared-gradient average as well.
A gradient equals 1 at every step and . What does the velocity approach?
The velocity is , a geometric sum that approaches . The value 0.53 is where a gradient that flips sign every step settles, and 1 and 0.9 would mean the old velocity was ignored.
Why does momentum help in a ravine?
Momentum only changes how past gradients are combined; it does not change the surface or compute curvature. Dividing by curvature is Newton's method (P1.F6), and a separate step size per parameter is the adaptive idea.
A bowl is tilted by 45 degrees so that its long valley runs diagonally. Which statement is right?
Plain gradient descent and heavy ball use the gradient as a whole vector, so turning the bowl just turns their paths. A per-coordinate rescaling can only act along the coordinate axes, so a diagonal valley is out of its reach. The adaptive method is not Newton's method, and nothing diverges because of a tilt alone.
Exercises
- With and a gradient of 1 at every step, what are the velocities after steps 1, 2 and 3?
Show answer
, , . - In the moving-average form , , with and , which gives the same positions in this lesson’s form?
Show answer
, since . - A bowl has (curvatures and ). What are the largest stable for plain gradient descent and for momentum with ?
Show answer
Plain: . Momentum: . - A parameter has gradient at the first RMSProp-style step (, before, ignore ), and another has . How big is each step?
Show answer
, so the step is in size for both: for the first and for the second. The gradients differ by a factor of 1500 and the steps do not. - Momentum with , 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 ?
Show answer
Momentum: about per step. Plain: . Momentum is ten times faster here. - For the bowl with 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 answer
Nothing: 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.