TExcelTAD
Home › Math for Deep Learning & LLMs › Momentum and Nesterov

Momentum and Nesterov Acceleration

Plain gradient descent zig-zags across steep valleys and crawls along flat ones. Momentum keeps a running velocity that averages recent gradients: oscillating components cancel and consistent ones build up. Nesterov's variant evaluates the gradient at a look-ahead point, which gives provably faster convergence on convex problems and is a common default for SGD in vision.

Heavy-ball momentum

vt+1=βvt+∇L(θt),θt+1=θt−ηvt+1\mathbf{v}_{t+1} = \beta\mathbf{v}_t + \nabla\mathcal{L}(\boldsymbol{\theta}_t), \qquad \boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta\mathbf{v}_{t+1}

(This is the PyTorch convention; Polyak's original puts η\eta inside the velocity, which is equivalent for a constant η\eta.) With a constant gradient g\mathbf{g}, the velocity converges to g/(1−β)\mathbf{g}/(1 - \beta), so β=0.9\beta = 0.9 multiplies the effective step by 10 along consistent directions. The velocity is an exponentially weighted sum of past gradients with an "memory" of about 1/(1−β)1/(1 - \beta) steps.

Nesterov momentum

Nesterov computes the gradient where momentum is about to take the parameters:

vt+1=βvt+∇L(θt−ηβvt),θt+1=θt−ηvt+1\mathbf{v}_{t+1} = \beta\mathbf{v}_t + \nabla\mathcal{L}(\boldsymbol{\theta}_t - \eta\beta\mathbf{v}_t), \qquad \boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta\mathbf{v}_{t+1}

If the velocity is about to overshoot, the look-ahead gradient already points back and brakes earlier. On smooth convex problems it reaches error ε\varepsilon in O(1/ε)O(1/\sqrt{\varepsilon}) steps instead of O(1/ε)O(1/\varepsilon), and on strongly convex ones in about κ\sqrt{\kappa} instead of κ\kappa steps per digit (Conditioning).

python · try it yourself
import numpy as np

H = np.diag([1.0, 100.0])                                   # condition number 100
grad = lambda th: H @ th
def run(method, beta, lr=0.009, steps=150):
    th, v = np.array([1.0, 1.0]), np.zeros(2)
    for _ in range(steps):
        if method == "gd":
            th = th - lr * grad(th)
        elif method == "heavy-ball":
            v = beta * v + grad(th); th = th - lr * v
        else:
            v = beta * v + grad(th - lr * beta * v); th = th - lr * v
    return 0.5 * th @ H @ th
print(f"plain GD        : loss {run('gd', 0):.2e}")
print(f"heavy-ball, 0.9 : loss {run('heavy-ball', 0.9):.2e}")
print(f"Nesterov, 0.9   : loss {run('nesterov', 0.9):.2e}")
plain GD        : loss 3.32e-02
heavy-ball, 0.9 : loss 1.62e-06
Nesterov, 0.9   : loss 2.03e-09

Damping the zig-zag

In the steep direction the gradient flips sign every step, and the average of alternating values is small. In the flat direction it keeps its sign and accumulates. Momentum thus acts like a low-pass filter on the gradient sequence.

python · try it yourself
import numpy as np

H = np.diag([1.0, 100.0])
for beta in (0.0, 0.9):
    th, v = np.array([1.0, 1.0]), np.zeros(2)
    path = []
    for t in range(6):
        v = beta * v + H @ th; th = th - 0.019 * v
        path.append(th.copy())
    print(f"beta {beta}: steep coordinate", np.round([p[1] for p in path], 3))
    print(f"          flat coordinate ", np.round([p[0] for p in path], 3))
beta 0.0: steep coordinate [-0.9    0.81  -0.729  0.656 -0.59   0.531]
          flat coordinate  [0.981 0.962 0.944 0.926 0.909 0.891]
beta 0.9: steep coordinate [-0.9   -0.9    0.81   0.81  -0.729 -0.729]
          flat coordinate  [0.981 0.945 0.895 0.833 0.761 0.682]

In six steps momentum has moved the flat coordinate about three times as far (from 1 to 0.68, versus 0.89 without momentum), while the steep coordinate oscillates no worse than before; over more steps the velocity in the steep direction averages out.

Momentum with mini-batches

With stochastic gradients, momentum also averages out noise: the velocity is a smoothed gradient estimate over about 1/(1−β)1/(1 - \beta) batches. Adam's first moment is exactly this kind of average (Adam and AdamW).

In software

  • torch.optim.SGD(params, lr=0.1, momentum=0.9, nesterov=True, weight_decay=5e-4) is the classic ResNet recipe.
  • Increasing β\beta without lowering η\eta increases the effective step η/(1−β)\eta/(1 - \beta) and can cause divergence.
  • In practice Nesterov's look-ahead is implemented with a change of variables so that only one gradient per step at the stored parameters is needed.

Exercises

Exercise 1: Effective step

With η=0.01\eta = 0.01 and β=0.99\beta = 0.99, what is the steady-state step size along a constant gradient direction?

Answer

η/(1−β)=1\eta/(1 - \beta) = 1 times the gradient.

Solution

v→g/(1−0.99)=100g\mathbf{v} \to \mathbf{g}/(1 - 0.99) = 100\mathbf{g}, so each step moves 0.01⋅100 g=g0.01 \cdot 100\,\mathbf{g} = \mathbf{g}.

Exercise 2: Velocity by hand

Starting from v0=0\mathbf{v}_0 = 0 with β=0.5\beta = 0.5 and gradients 1,1,−11, 1, -1, compute v1,v2,v3v_1, v_2, v_3.

Answer

11, 1.51.5, −0.25-0.25.

Solution

v1=1v_1 = 1; v2=0.5+1=1.5v_2 = 0.5 + 1 = 1.5; v3=0.75−1=−0.25v_3 = 0.75 - 1 = -0.25.

Exercise 3: Memory of the average (code)

The velocity weights the gradient from kk steps ago by βk\beta^k. Check that for β=0.9\beta = 0.9 the weights sum to about 1/(1−β)1/(1 - \beta), and find after how many steps a gradient's weight falls below e−1e^{-1}.

Answer

Sum about 10; about 10 steps.

Solution
python · try it yourself
import numpy as np
w = 0.9 ** np.arange(1000)
print(round(w.sum(), 4), int(np.argmax(w < np.exp(-1))))
10.0 10

Test yourself

With momentum β=0.9\beta = 0.9 and a constant gradient, the steady-state velocity is…

  1. 0.9g0.9\mathbf{g}
  2. g\mathbf{g}
  3. 10g10\mathbf{g}
  4. 00

What distinguishes Nesterov momentum from heavy-ball momentum?

  1. It uses no velocity
  2. It evaluates the gradient at the look-ahead point θ−ηβv\boldsymbol{\theta} - \eta\beta\mathbf{v}
  3. It uses second derivatives
  4. It only works on GPUs

Why does momentum reduce zig-zagging in a steep valley?

  1. It increases the learning rate in every direction equally
  2. Gradients that alternate in sign cancel in the running average
  3. It normalizes the gradient
  4. It removes the steep direction