CodeRigor

LESSON

Learning rates, momentum and Nesterov

Why a step size above 2/L diverges on a quadratic bowl, and how momentum and Nesterov lookahead speed up the slow directions of a ravine.

Plain gradient descent has one knob, the learning rate, and a loss surface decides how wide the good range of that knob is. This lesson shows where the range ends on a quadratic bowl, why a long narrow valley makes the range painfully small, and how momentum and Nesterov lookahead get more out of the same gradients. This lesson pairs with Lecture 6 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the momentum step, the Nesterov step and a driver that runs them, and compare them with torch.optim.SGD.

Start with the smallest bowl, f(w) = (L/2) w², whose gradient is L·w. One step gives w ← w − lr·L·w = (1 − lr·L)·w, so every step multiplies w by the same factor. The factor has magnitude below 1 only when 0 < lr < 2/L. At lr = 1/L it is exactly 0 and one step reaches the minimum. Between 1/L and 2/L the sign flips each step while the size still shrinks. Above 2/L the size grows. Here L = 4, so the threshold is 0.5.

Python
import numpy as np

L = 4.0                                   # f(w) = (L/2) w^2, gradient L w
for lr in (0.15, 0.25, 0.4, 0.55):
    w = 1.0
    for _ in range(10):
        w -= lr * L * w
    print(f"lr={lr}: factor {1 - lr * L:+.2f}, w after 10 steps = {w:.4f}")
One bowl, three learning rates
w per step on f(w) = 2w², so L = 4 and 2/L = 0.5. Below 1/L = 0.25 the iterate decays smoothly, between 1/L and 2/L it flips sign while shrinking, above 2/L it flips sign and grows.
One bowl, three learning rates
w per step on f(w) = 2w², so L = 4 and 2/L = 0.5. Below 1/L = 0.25 the iterate decays smoothly, between 1/L and 2/L it flips sign while shrinking, above 2/L it flips sign and grows.

Real losses have many directions with different curvature. Take f(w) = ½(1·w₀² + 100·w₁²), a ravine: steep across, flat along. The learning rate must stay below 2/100 or the steep coordinate blows up. But that same rate multiplies the flat coordinate by 1 − lr·1, about 0.98, so it shrinks by only two percent per step. The ratio of the curvatures, here 100, is the condition number, and the number of steps needed grows in proportion to it: at the best fixed rate, curvatures 1 and 10 need 37 steps to get within 1e-3 of the minimum from (1, 1), curvatures 1 and 100 need 363, curvatures 1 and 1000 need 3628. No single learning rate fixes both directions.

Momentum keeps a velocity that remembers earlier steps:

  • v ← β·v − lr·grad
  • w ← w + v

Along a direction where the gradient keeps its sign, the velocity builds toward lr·g/(1 − β), about 1/(1 − β) times a single step. With β = 0.9 that is ten times: the first velocities for a steady gradient of 1 at lr = 0.01 are −0.01, −0.019, −0.0271, and they approach −0.1. Along a direction where the gradient flips sign every step, the contributions cancel and the velocity settles near lr/(1 + β), nineteen times smaller than in the steady case.

Python
lr, beta = 0.01, 0.9

for name, signs in (("steady gradient", lambda t: 1.0), ("flipping gradient", lambda t: (-1.0) ** t)):
    v = 0.0
    for t in range(200):
        v = beta * v - lr * signs(t)
    print(f"{name}: |velocity| = {abs(v):.5f}")
print("limits:", round(lr / (1 - beta), 5), round(lr / (1 + beta), 5))

That is why momentum helps on a ravine: the flat direction sees a steady gradient and speeds up, and the steep direction sees a flipping gradient and calms down. Momentum also moves the stability limit on the learning rate, to 2(1 + β)/L on a bowl.

Nesterov changes one thing. It evaluates the gradient at the lookahead point w + β·v, where the velocity is about to carry you, and uses that gradient in the same update. If the velocity is about to overshoot, the lookahead gradient already points back and shrinks the velocity before the overshoot happens. Its stability limit is lower: 2(1 + β)/((1 + 2β)·L).

Python
import numpy as np

curv = np.array([1.0, 100.0])             # f(w) = 0.5 * (1 w0^2 + 100 w1^2)

def steps_to_minimum(lr, beta, nesterov=False):
    w, v = np.array([1.0, 1.0]), np.zeros(2)
    for t in range(1, 5000):
        look = w + beta * v if nesterov else w
        v = beta * v - lr * curv * look
        w = w + v
        if np.linalg.norm(w) < 1e-3:
            return t
    return None

print("plain, lr 2/101:", steps_to_minimum(2 / 101, 0.0))
print("momentum 0.9, lr 0.01:", steps_to_minimum(0.01, 0.9))
print("Nesterov 0.9, lr 0.01:", steps_to_minimum(0.01, 0.9, nesterov=True))

These counts are for one setting, not a ranking. With β = 0.9 and lr = 0.01 Nesterov needs 62 steps to momentum's 126, but with β = 0.8 the same pair needs 110 and 101. For L = 100 and β = 0.9, momentum is stable below lr = 0.038 and Nesterov below 0.0136; running just under and just over each limit confirms both.

Loss on the ravine
Loss per step on f = ½(w₀² + 100·w₁²) from (1, 1), with a logarithmic loss axis. Plain descent crawls along the flat direction, momentum overshoots across the steep one with large swings, and Nesterov swings far less.
Loss on the ravine
Loss per step on f = ½(w₀² + 100·w₁²) from (1, 1), with a logarithmic loss axis. Plain descent crawls along the flat direction, momentum overshoots across the steep one with large swings, and Nesterov swings far less.

Two details cause most wrong implementations. The position moves by the new velocity, w + v_new, and if you add the old one every step lags by one. And the lookahead uses the old velocity, w + β·v: a Nesterov step that evaluates the gradient at w is plain momentum with a different name, and nothing crashes to tell you.

PyTorch writes the same thing differently. torch.optim.SGD stores buf = β·buf + grad and moves by −lr·buf, so its buffer is the velocity divided by −lr. With a constant learning rate the positions match this lesson's. With nesterov=True the parameter torch holds after t steps equals your w_t + β·v_t, the lookahead point. The hidden tests use both facts, and both were confirmed numerically before the tests relied on them.

How do you know the code is right? The public tests use arithmetic you can do by hand. The hidden tests compare whole trajectories with torch.optim.SGD on a quadratic and on a quartic, and check that momentum reaches the minimum of the ravine in far fewer steps than plain descent at each of the fixed rates it tries. What they do not show is that any of this transfers to a network. Everything above is exact for quadratics. A real loss surface is only locally like one, its curvature changes along the path, and minibatch noise adds a source of error that these tests leave out. Treat 2/L and the condition number as the right way to think, and the learning rate of a real run as something you measure.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

The lecture this lesson is built around: how the choice of step size and the shape of the loss surface govern gradient descent, and the momentum and Nesterov fixes. Watch it first, then build the three update rules here and measure them.