Momentum and Nesterov
Gradient descent only looks at the slope where it stands. In a long, narrow valley, the steepest direction points mostly across the valley, not along it, so the path zig-zags from wall to wall and crawls towards the minimum; and because the step size must be small enough for the steep walls, progress along the gentle floor is slow. Momentum gives the optimizer a memory: it keeps a running sum of past gradients, so consistent directions add up and alternating ones cancel. Nesterov's variant evaluates the gradient a little ahead, which damps overshooting. Both are one extra line of code, and SGD with momentum is still a top choice for training vision models.
The update
Heavy-ball momentum (Polyak, 1964), in the form PyTorch uses:
with and usually 0.9. Unrolled, : a geometrically weighted sum of all past gradients. If the gradient is constant, the step settles at times the gradient, ten times plain GD's for . If the gradient flips sign every step, the terms cancel and the step shrinks. Writing gives the physical picture, a ball with friction rolling downhill:
Textbooks also write , (the lab below uses this form). With a constant learning rate it produces exactly the same iterates; it differs only when changes during training.
Nesterov momentum computes the gradient at the point the momentum is about to carry you to, , instead of at . Rewritten so that only the gradient at the current point is needed (the form in torch.optim.SGD(nesterov=True)):
If the velocity is about to carry you up the far wall, the gradient there already points back, and the step is corrected before the overshoot happens. The derivations and convergence rates are in Momentum and Nesterov (Mathematics for Deep Learning) and Step Size and Momentum.
Watch it
The lab runs 60 steps on a valley with curvatures 1 and 10, turned by 25 degrees, starting at . Start with momentum at , : the path swings far past the valley floor and spirals in, reaching a loss of about 0.0145 after 60 steps. Now set to 0, which is plain GD: it zig-zags down the walls and reaches about , better. Then try , or switch the surface to the Rosenbrock banana.
Momentum is not automatically faster: too much of it on a short valley just overshoots. The code below counts steps to a loss below on the same valley:
import numpy as np
c, s = np.cos(np.radians(25)), np.sin(np.radians(25))
R = np.array([[c, s], [-s, c]]) # turns (x, y) into the valley's own axes (u, v)
A = R.T @ np.diag([1.0, 10.0]) @ R # f = 1/2 p^T A p: curvatures 1 and 10
f = lambda p: 0.5 * p @ A @ p
grad = lambda p: A @ p
def gd_step(p, g, state, lr, beta):
return p - lr * g
def momentum_step(p, g, state, lr, beta): # PyTorch form: v <- beta v + g
state["v"] = beta * state.get("v", 0) + g
return p - lr * state["v"]
def nesterov_step(p, g, state, lr, beta): # look ahead along the velocity
state["v"] = beta * state.get("v", 0) + g
return p - lr * (g + beta * state["v"])
def steps_to(step_fn, lr, beta=0.0, tol=1e-8, max_steps=2000):
p, state = np.array([-2.0, 1.5]), {}
for k in range(1, max_steps + 1):
p = step_fn(p, grad(p), state, lr, beta)
if not np.isfinite(f(p)) or f(p) > 1e6:
return "diverged"
if f(p) < tol:
return k
return f"> {max_steps}"
print("loss below 1e-8 after how many steps?")
for name, fn, lr, beta in [("GD", gd_step, 0.08, 0), ("GD", gd_step, 0.18, 0), ("GD", gd_step, 0.21, 0),
("momentum", momentum_step, 0.08, 0.9), ("Nesterov", nesterov_step, 0.08, 0.9),
("momentum", momentum_step, 0.23, 0.27), ("Nesterov", nesterov_step, 0.08, 0.5)]:
print(f" {name:9s} lr {lr:.2f} beta {beta:.2f}: {steps_to(fn, lr, beta)}")loss below 1e-8 after how many steps?
GD lr 0.08 beta 0.00: 109
GD lr 0.18 beta 0.00: 50
GD lr 0.21 beta 0.00: diverged
momentum lr 0.08 beta 0.90: 176
Nesterov lr 0.08 beta 0.90: 61
momentum lr 0.23 beta 0.27: 20
Nesterov lr 0.08 beta 0.50: 46
Plain GD is stable only for and does best near (50 steps). Momentum with the default needs 176 steps here, worse than GD; Nesterov's look-ahead brings the same setting down to 61. With the theoretically best heavy-ball values for a quadratic with curvatures and ,
momentum needs only 20 steps. The error then shrinks per step by a factor of about instead of GD's best . That in place of is the whole point of momentum: the worse the conditioning, the bigger the gain. Real networks are badly conditioned, which is why is the usual default even though it is too much for this small toy valley.
Where momentum shines: a curved valley
The Rosenbrock banana has a long, curved, almost flat floor. Plain GD crawls along it; momentum builds up speed. Same starting point, 1000 steps:
import numpy as np
def f(p): # the lab's Rosenbrock banana, minimum 0 at (1, 1)
x, y = p
return 0.1 * ((1 - x) ** 2 + 10 * (y - x ** 2) ** 2)
def grad(p):
x, y = p
return 0.1 * np.array([-2 * (1 - x) - 40 * x * (y - x ** 2), 20 * (y - x ** 2)])
def run(lr, beta, nesterov=False, steps=1000):
p, v, out = np.array([-2.0, 1.5]), np.zeros(2), []
for k in range(1, steps + 1):
g = grad(p)
v = beta * v + g
p = p - lr * (g + beta * v if nesterov else v)
if np.abs(p).max() > 1e6:
return f"diverged at step {k}"
if k in (60, 300, 1000):
out.append(f"{f(p):.2e}")
return " / ".join(out) + f" end ({p[0]:.3f}, {p[1]:.3f})"
print("loss after 60 / 300 / 1000 steps from (-2, 1.5)")
for name, lr, beta, nest in [("GD", 0.01, 0.0, False), ("GD", 0.08, 0.0, False),
("momentum", 0.01, 0.9, False), ("Nesterov", 0.01, 0.9, True),
("momentum", 0.08, 0.9, False)]:
print(f" {name:9s} lr {lr:.2f} beta {beta:.1f}: {run(lr, beta, nest)}")loss after 60 / 300 / 1000 steps from (-2, 1.5)
GD lr 0.01 beta 0.0: 5.10e-01 / 4.40e-01 / 1.72e-01 end (-0.297, 0.151)
GD lr 0.08 beta 0.0: 2.69e-01 / 5.40e-03 / 3.47e-05 end (0.982, 0.963)
momentum lr 0.01 beta 0.9: 2.34e-02 / 1.01e-03 / 2.39e-06 end (0.995, 0.990)
Nesterov lr 0.01 beta 0.9: 2.12e-01 / 2.25e-03 / 4.70e-06 end (0.993, 0.986)
momentum lr 0.08 beta 0.9: diverged at step 15
At the same small learning rate 0.01, GD is still on the far side of the banana after 1000 steps (loss 0.172), while momentum and Nesterov reach and . Momentum at 0.01 even beats GD at 0.08. But momentum multiplies the effective step by , so with is like GD at 0.8, far above the stability limit of about 0.197: it diverges at step 15. When you add momentum, lower the learning rate. In the lab, choose the Rosenbrock surface with and to watch the ball roll along the curve; raise to 0.08 to see the divergence message.
In PyTorch
torch.optim.SGD(params, lr=0.1, momentum=0.9, nesterov=True, weight_decay=5e-4) is a classic recipe for image classifiers. PyTorch's buffer starts at the first gradient () and has an optional dampening that turns the update into . The optimizer comparison checks our NumPy versions against it number by number.
Pitfalls
- Adding momentum without lowering the learning rate. The effective step is ; going from to at the same is a tenfold step increase.
- "Momentum" in the EMA form. Some libraries average, , which divides the step by 10 compared with PyTorch. Hyperparameters copied between the two conventions are off by .
- Resuming without the buffer. A checkpoint must save the optimizer state (
optimizer.state_dict()); restarting with causes a bump in the loss (Checkpointing).
Practice
- With , by what factor does momentum multiply the step for a constant gradient?
Answer
.
- For a quadratic with curvatures and , compare the best per-step error factor of GD and of heavy-ball momentum.
Answer
. GD: , so about 115 steps per factor of 10 (). Momentum: , about 11.5 steps per factor of 10, ten times fewer.
- Show that the two momentum forms, and , give the same iterates for a constant .
Answer
Set . Then becomes , the first form's update, and . If changes between steps, the identity breaks, and the two forms differ.
Test yourself
Why does momentum help in a narrow valley?
- It computes the exact Hessian
- Gradient components that keep the same sign accumulate while the ones that alternate across the valley cancel
- It reduces the learning rate automatically
- It uses second derivatives
You switch from plain SGD with to momentum . To keep a similar effective step, use about…
Where does Nesterov momentum evaluate the gradient?
- At the current point
- At the look-ahead point the momentum would carry the parameters to
- At the previous point
- At the origin
In the lesson, momentum with needed 176 steps on the small valley while plain GD at 0.08 needed 109. What explains it?
- Momentum is broken
- is too much for a valley with condition number 10, so the iterates overshoot and spiral
- The valley has no minimum
- GD used a better starting point