TExcelTAD

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:

vt=β vt−1+∇f(wt−1),wt=wt−1−η vt\mathbf{v}_{t} = \beta \, \mathbf{v}_{t-1} + \nabla f(\mathbf{w}_{t-1}), \qquad \mathbf{w}_{t} = \mathbf{w}_{t-1} - \eta \, \mathbf{v}_{t}

with v0=0\mathbf{v}_0 = 0 and β\beta usually 0.9. Unrolled, vt=∑k≥0βk∇f(wt−1−k)\mathbf{v}_t = \sum_{k \ge 0} \beta^k \nabla f(\mathbf{w}_{t-1-k}): a geometrically weighted sum of all past gradients. If the gradient is constant, the step settles at η/(1−β)\eta / (1 - \beta) times the gradient, ten times plain GD's for β=0.9\beta = 0.9. If the gradient flips sign every step, the terms cancel and the step shrinks. Writing wt−wt−1=−ηvt\mathbf{w}_{t} - \mathbf{w}_{t-1} = -\eta \mathbf{v}_t gives the physical picture, a ball with friction rolling downhill:

wt=wt−1−η∇f(wt−1)+β (wt−1−wt−2).\mathbf{w}_{t} = \mathbf{w}_{t-1} - \eta \nabla f(\mathbf{w}_{t-1}) + \beta \, (\mathbf{w}_{t-1} - \mathbf{w}_{t-2}) .

Textbooks also write v←βv−η∇f\mathbf{v} \leftarrow \beta \mathbf{v} - \eta \nabla f, w←w+v\mathbf{w} \leftarrow \mathbf{w} + \mathbf{v} (the lab below uses this form). With a constant learning rate it produces exactly the same iterates; it differs only when η\eta changes during training.

Nesterov momentum computes the gradient at the point the momentum is about to carry you to, w−ηβv\mathbf{w} - \eta \beta \mathbf{v}, instead of at w\mathbf{w}. Rewritten so that only the gradient at the current point is needed (the form in torch.optim.SGD(nesterov=True)):

vt=β vt−1+∇f(wt−1),wt=wt−1−η (∇f(wt−1)+β vt).\mathbf{v}_{t} = \beta \, \mathbf{v}_{t-1} + \nabla f(\mathbf{w}_{t-1}), \qquad \mathbf{w}_{t} = \mathbf{w}_{t-1} - \eta \, \big( \nabla f(\mathbf{w}_{t-1}) + \beta \, \mathbf{v}_{t} \big) .

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 (−2,1.5)(-2, 1.5). Start with momentum at η=0.08\eta = 0.08, β=0.9\beta = 0.9: the path swings far past the valley floor and spirals in, reaching a loss of about 0.0145 after 60 steps. Now set β\beta to 0, which is plain GD: it zig-zags down the walls and reaches about 3×10−53 \times 10^{-5}, better. Then try β=0.5\beta = 0.5, or switch the surface to the Rosenbrock banana.

−2−1012−202Loss contours: narrow valleyxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimum

Momentum is not automatically faster: too much of it on a short valley just overshoots. The code below counts steps to a loss below 10−810^{-8} on the same valley:

python · try it yourself
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 η<2/λmax⁡=0.2\eta < 2/\lambda_{\max} = 0.2 and does best near η=2/(λmin⁡+λmax⁡)≈0.18\eta = 2/(\lambda_{\min} + \lambda_{\max}) \approx 0.18 (50 steps). Momentum with the default β=0.9\beta = 0.9 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 μ=1\mu = 1 and L=10L = 10,

η∗=4(L+μ)2≈0.23,β∗=(κ−1κ+1)2≈0.27,κ=Lμ=10,\eta^* = \frac{4}{(\sqrt{L} + \sqrt{\mu})^2} \approx 0.23, \qquad \beta^* = \left( \frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1} \right)^2 \approx 0.27, \qquad \kappa = \frac{L}{\mu} = 10,

momentum needs only 20 steps. The error then shrinks per step by a factor of about κ−1κ+1≈0.52\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1} \approx 0.52 instead of GD's best κ−1κ+1≈0.82\frac{\kappa - 1}{\kappa + 1} \approx 0.82. That κ\sqrt{\kappa} in place of κ\kappa is the whole point of momentum: the worse the conditioning, the bigger the gain. Real networks are badly conditioned, which is why β=0.9\beta = 0.9 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:

python · try it yourself
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 (0.995,0.990)(0.995, 0.990) and (0.993,0.986)(0.993, 0.986). Momentum at 0.01 even beats GD at 0.08. But momentum multiplies the effective step by 1/(1−β)=101/(1 - \beta) = 10, so η=0.08\eta = 0.08 with β=0.9\beta = 0.9 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 η=0.01\eta = 0.01 and β=0.9\beta = 0.9 to watch the ball roll along the curve; raise η\eta to 0.08 to see the divergence message.

−1012−2−1012Loss contours: Rosenbrock bananaxy10−610−410−211001040204060stepLoss f(x, y), log scalepath / lossstartminimum

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 (v1=∇f\mathbf{v}_1 = \nabla f) and has an optional dampening dd that turns the update into v←βv+(1−d)g\mathbf{v} \leftarrow \beta \mathbf{v} + (1 - d) \mathbf{g}. The optimizer comparison checks our NumPy versions against it number by number.

Pitfalls

  • Adding momentum without lowering the learning rate. The effective step is η/(1−β)\eta/(1 - \beta); going from β=0\beta = 0 to 0.90.9 at the same η\eta is a tenfold step increase.
  • "Momentum" in the EMA form. Some libraries average, v←βv+(1−β)g\mathbf{v} \leftarrow \beta \mathbf{v} + (1 - \beta) \mathbf{g}, which divides the step by 10 compared with PyTorch. Hyperparameters copied between the two conventions are off by 1−β1 - \beta.
  • Resuming without the buffer. A checkpoint must save the optimizer state (optimizer.state_dict()); restarting with v=0\mathbf{v} = 0 causes a bump in the loss (Checkpointing).

Practice

  1. With β=0.95\beta = 0.95, by what factor does momentum multiply the step for a constant gradient?
Answer

1/(1−0.95)=201/(1 - 0.95) = 20.

  1. For a quadratic with curvatures μ=1\mu = 1 and L=100L = 100, compare the best per-step error factor of GD and of heavy-ball momentum.
Answer

κ=100\kappa = 100. GD: 99101≈0.980\frac{99}{101} \approx 0.980, so about 115 steps per factor of 10 (ln⁡10/−ln⁡0.980\ln 10 / -\ln 0.980). Momentum: 10−110+1≈0.818\frac{10 - 1}{10 + 1} \approx 0.818, about 11.5 steps per factor of 10, ten times fewer.

  1. Show that the two momentum forms, v←βv+g,w←w−ηv\mathbf{v} \leftarrow \beta \mathbf{v} + \mathbf{g}, \mathbf{w} \leftarrow \mathbf{w} - \eta \mathbf{v} and u←βu−ηg,w←w+u\mathbf{u} \leftarrow \beta \mathbf{u} - \eta \mathbf{g}, \mathbf{w} \leftarrow \mathbf{w} + \mathbf{u}, give the same iterates for a constant η\eta.
Answer

Set u=−ηv\mathbf{u} = -\eta \mathbf{v}. Then u←βu−ηg\mathbf{u} \leftarrow \beta \mathbf{u} - \eta \mathbf{g} becomes −ηv←−η(βv+g)-\eta \mathbf{v} \leftarrow -\eta(\beta \mathbf{v} + \mathbf{g}), the first form's update, and w+u=w−ηv\mathbf{w} + \mathbf{u} = \mathbf{w} - \eta \mathbf{v}. If η\eta changes between steps, the identity u=−ηv\mathbf{u} = -\eta \mathbf{v} breaks, and the two forms differ.

Test yourself

Why does momentum help in a narrow valley?

  1. It computes the exact Hessian
  2. Gradient components that keep the same sign accumulate while the ones that alternate across the valley cancel
  3. It reduces the learning rate automatically
  4. It uses second derivatives

You switch from plain SGD with η=0.1\eta = 0.1 to momentum β=0.9\beta = 0.9. To keep a similar effective step, use about…

  1. η=1\eta = 1
  2. η=0.1\eta = 0.1
  3. η=0.01\eta = 0.01
  4. η=0.09\eta = 0.09

Where does Nesterov momentum evaluate the gradient?

  1. At the current point
  2. At the look-ahead point the momentum would carry the parameters to
  3. At the previous point
  4. At the origin

In the lesson, momentum with η=0.08,β=0.9\eta = 0.08, \beta = 0.9 needed 176 steps on the small valley while plain GD at 0.08 needed 109. What explains it?

  1. Momentum is broken
  2. β=0.9\beta = 0.9 is too much for a valley with condition number 10, so the iterates overshoot and spiral
  3. The valley has no minimum
  4. GD used a better starting point