9.4 Momentum
In Section 9.1, we saw why plain gradient descent struggles on an ill-conditioned valley: the steepest curvature imposes the stability ceiling , forcing the flattest direction to contract by at most per step, where is the condition number. Plain gradient descent is slow because each step relies solely on the instantaneous gradient . Yet the history of recent gradients carries clear geometric information: along the valley floor, successive gradients point consistently in the same direction, whereas across the steep walls they alternate in sign as the iterate overshoots from side to side.
Polyak (1964) proposed stepping along an exponentially weighted sum of past gradients, called the velocity, so that persistent components along flat directions accumulate while oscillating components across steep directions cancel. Analogous to a heavy ball rolling down a trough against friction, heavy-ball momentum reduces the worst-case iteration count on a quadratic bowl from to at the cost of storing a single velocity buffer per parameter.
In this section, we analyze the velocity recursion, its effective step size and memory timescale, and the acceleration law via critical damping. We then test momentum on full-batch softmax regression and minibatch training of FashionCNN, introduce Nesterov look-ahead momentum, and establish practical rules for tuning and .
import random9.4.1 The Momentum Method#
9.4.1.1 Velocity and Effective Step Size#
Given gradient at step (exact or minibatch), heavy-ball momentum maintains a velocity vector initialized at and updates:
where is the momentum coefficient ( recovers gradient descent). Unrolling the recursion expresses the velocity as an exponentially weighted sum of all past gradients:
Consider what this weighted sum does to the two coordinates of the valley () at —above the plain gradient descent stability limit , where plain gradient descent diverges along by factor per step. Adding momentum stabilizes the trajectory and brings both coordinates within of the origin in steps:
h1, h2 = d2l.VALLEY_CURVATURES
f_valley, valley_grad = d2l.f_valley, d2l.valley_grad
def momentum_2d(x1, x2, v1, v2, f_grad, eta, beta):
g1, g2 = f_grad(x1, x2)
v1, v2 = beta * v1 + g1, beta * v2 + g2
return x1 - eta * v1, x2 - eta * v2, v1, v2
d2l.show_trace_2d(f_valley, d2l.train_2d(momentum_2d, valley_grad, eta=0.6,
beta=0.5))step 20, x1: 0.007188, x2: 0.002553
Two limiting cases explain why momentum simultaneously accelerates the flat coordinate and stabilizes the steep one:
- Persistent gradients (flat floor): When successive gradients remain nearly constant (), the velocity builds up to , yielding the effective step size
- Alternating gradients (steep walls): When successive gradients alternate in sign (), the geometric series sums to , damped to an effective step size of .
Figure 9.4.1 shows both cases for gradients of unit size.
The velocity (blue) for unit gradients (gray bars) at . Left: gradients of the same sign add up, and approaches . Right: gradients of alternating sign largely cancel, and settles into an oscillation of amplitude .
At and , momentum amplifies progress along the valley floor to while damping oscillations across the steep wall to . Consequently, the stability ceiling for curvature rises from to (Exercise 3).
9.4.1.2 The Timescale of and Minibatch Noise#
Because the weights sum to , the velocity has an effective memory window of steps and a half-life of steps:
print('beta window half-life weight inside the window')
for beta in [0.5, 0.9, 0.99]:
window = 1 / (1 - beta)
half_life = np.log(0.5) / np.log(beta)
inside = 1 - beta ** window
print(f'{beta:4} {window:6.0f} {half_life:9.1f} {inside:24.2f}')beta window half-life weight inside the window
0.5 2 1.0 0.75
0.9 10 6.6 0.65
0.99 100 69.0 0.63
Increasing from to expands both the memory horizon and the effective step size tenfold (from steps to steps).
Under stochastic gradients , does averaging over steps shrink the stationary noise ball of Section 9.2? No: each noise perturbation enters with weight and decays as over subsequent steps, contributing a cumulative displacement of . Thus, at matched effective step size , SGD with and without momentum settle into stationary noise balls of nearly identical variance (Exercise 5). When increasing in a noise-limited run, should therefore be scaled proportional to to hold constant.
9.4.2 Acceleration and Critical Damping#
What choice of is optimal on a quadratic with eigenvalues and condition number ? Polyak (1964) proved that setting
achieves the worst-case per-step contraction factor
reducing the steps needed to reach relative accuracy from to (Section 23.1.3).
To see why the contraction factor equals , substitute into the 1D velocity update along an eigenvector of curvature to obtain the second-order linear recurrence
whose characteristic polynomial is . By Vieta's formulas, the product of the two roots is . Whenever the discriminant is non-positive (which occurs for all ), the roots form a complex-conjugate pair of identical modulus , independent of the curvature (Figure 9.4.2).
Per-step contraction factor of heavy-ball momentum along curvature as a function of . Convergence is fastest at the critical damping threshold ; below the mode is overdamped, while above it oscillates with modulus .
The optimal parameters (9.4.3) equate the critical damping thresholds of the flattest and steepest eigenvalues, , critically damping both extreme modes while ensuring that every intermediate eigenvalue lies in the underdamped complex-root regime and contracts at rate .
On our valley (), (9.4.3) yields , reducing the asymptotic contraction factor from to and cutting the steps to reach relative error from down to :
def steps_to(tol, eta, beta, steps=400):
"""Steps after which |x1|, |x2| stay below tol times their start."""
x1, x2, v1, v2, last = -5.0, -2.0, 0.0, 0.0, 0
for t in range(1, steps + 1):
x1, x2, v1, v2 = momentum_2d(x1, x2, v1, v2, valley_grad, eta, beta)
if abs(x1) > 5 * tol or abs(x2) > 2 * tol:
last = t
return last + 1
def contraction(eta, beta):
return max(abs(np.roots([1, -(1 + beta - eta * lam), beta])).max()
for lam in (h1, h2))
eta_opt = 4 / (np.sqrt(h2) + np.sqrt(h1)) ** 2
beta_opt = ((np.sqrt(h2 / h1) - 1) / (np.sqrt(h2 / h1) + 1)) ** 2
print(' eta beta factor steps to 1% steps to 1e-6')
for eta, beta in [(2 / (h1 + h2), 0), (0.6, 0.5), (eta_opt, beta_opt),
(0.3, 0.8)]:
print(f'{eta:5.3f} {beta:5.3f} {contraction(eta, beta):7.3f} '
f'{steps_to(1e-2, eta, beta):12d} {steps_to(1e-6, eta, beta):14d}') eta beta factor steps to 1% steps to 1e-6
0.476 0.000 0.905 47 139
0.600 0.500 0.707 16 42
0.668 0.403 0.635 18 40
0.300 0.800 0.894 42 126
Notice the fourth row (): choosing well above the critical threshold leaves both coordinates underdamped with modulus , causing the trajectory to overshoot and ring around the origin:
d2l.show_trace_2d(f_valley, d2l.train_2d(momentum_2d, valley_grad, eta=0.3,
beta=0.8))step 20, x1: 0.195696, x2: -0.249649
9.4.3 Momentum on Data#
Our analysis predicts two distinct regimes when training on data:
- Curvature-limited regime (accurate gradients, large ): Momentum permits a larger effective step and reduces the required iteration count by a large factor.
- Noise-limited regime (small minibatches): The stationary noise floor is governed by , so adding shifts the optimal learning rate down by a factor of while achieving comparable convergence speed.
We verify both regimes on Fashion-MNIST by comparing and on (1) full-batch softmax regression (, exact gradients, ill-conditioned due to non-negative pixel intensities) and (2) FashionCNN (Section 9.3.2) with small minibatches (). First we preload the normalized Fashion-MNIST tensors onto the accelerator inside an in-memory Batches loader:
fashion = d2l.FashionMNIST()
X = fashion.train.data[:, None].to(d2l.try_gpu()) / 255 # NCHW
y = fashion.train.targets.to(d2l.try_gpu())
class Batches:
"""The examples X, y on the GPU, in a new random order on every pass."""
def __init__(self, X, y, batch_size):
self.X, self.y, self.batch_size = X, y, batch_size
def train_dataloader(self):
order = torch.randperm(len(self.y), device=self.y.device)
return ((self.X[i], self.y[i])
for i in order.view(-1, self.batch_size))Next we define the zero-initialized linear softmax_regression model and the momentum-parameterized SGD constructor make_sgd(beta):
def softmax_regression():
"""A linear layer from the pixels to the logits, starting at zero."""
net = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 10))
nn.init.zeros_(net[1].weight)
nn.init.zeros_(net[1].bias)
return net
make_sgd = lambda beta: lambda model, lr: torch.optim.SGD(
model.parameters(), lr, momentum=beta)
new_seed = lambda: random.getrandbits(31)We now sweep d2l.lr_sweep across grids for both models at , recording each configuration's best learning rate, steps to reach its target loss, and final loss:
# Model, batch size, steps, target loss
setups = {'softmax regression': (softmax_regression, 60000, 1000, 0.5),
'FashionCNN': (d2l.FashionCNN, 32, 3000, 0.3)}
grids = {('softmax regression', 0.0): [0.0625, 0.125, 0.25, 0.5, 1],
('softmax regression', 0.9): [0.1, 0.2, 0.4, 0.8],
('FashionCNN', 0.0): [0.05, 0.1, 0.2, 0.4],
('FashionCNN', 0.9): [0.005, 0.01, 0.02, 0.04]}
best = {}
for (name, beta), lrs in grids.items():
make_model, b, num_steps, target = setups[name]
curves, _ = d2l.lr_sweep(make_model, make_sgd(beta), Batches(X, y, b),
lrs, new_seed(), num_steps, verbose=False)
best[name, beta] = min(lrs, key=lambda lr: d2l.final_loss(curves[lr]))
c = curves[best[name, beta]]
print(f'{name:<18} beta={beta} best lr {best[name, beta]:<5g} steps to '
f'{target}: {d2l.steps_to_reach(c, target)} final loss '
f'{d2l.final_loss(c):.3f}')softmax regression beta=0.0 best lr 0.125 steps to 0.5: 625 final loss 0.472
softmax regression beta=0.9 best lr 0.4 steps to 0.5: 100 final loss 0.365
FashionCNN beta=0.0 best lr 0.2 steps to 0.3: 1550 final loss 0.293
FashionCNN beta=0.9 best lr 0.02 steps to 0.3: 1425 final loss 0.280
Both predictions hold quantitatively:
- On full-batch softmax regression, adding momentum increases the optimal learning rate from to (, a larger effective step), cutting the steps needed to reach loss by more than ( steps) and lowering the final loss from to .
- On small-batch
FashionCNN(), the run is noise-limited: the optimal learning rate drops from – at to – at (a factor of – that keeps the effective step within one step of the factor-of-two grid of its value), and both configurations reach loss and final losses of – within the single-seed variation of Section 9.3.
9.4.4 Nesterov Momentum#
In the underdamped run (), heavy-ball momentum overshot the minimum because it evaluated the gradient at the current position rather than at the point where the velocity was about to carry it. Nesterov (1983) proposed evaluating the gradient at the look-ahead point (Figure 9.4.3):
One step of heavy-ball versus Nesterov momentum from the same iterate and velocity. Heavy-ball evaluates the gradient at and overshoots; Nesterov evaluates the gradient at the look-ahead point , applying an immediate restoring correction.
Evaluating the gradient at the look-ahead point introduces anticipatory damping that suppresses steep-direction oscillations. The guarantees are also broader than those of heavy-ball momentum. With the constant , Nesterov momentum attains the rate on every smooth, strongly convex function, not only on quadratics. With the increasing schedule , it achieves the optimal convergence rate on general smooth convex objectives (Nesterov, 2018) (Section 23.1.3). We use a constant here:
def nesterov_2d(x1, x2, v1, v2, f_grad, eta, beta):
g1, g2 = f_grad(x1 - eta * beta * v1, # Gradient at the look-ahead
x2 - eta * beta * v2) # point, not at (x1, x2)
v1, v2 = beta * v1 + g1, beta * v2 + g2
return x1 - eta * v1, x2 - eta * v2, v1, v2
d2l.show_trace_2d(f_valley, d2l.train_2d(nesterov_2d, valley_grad, eta=0.3,
beta=0.8))step 20, x1: 0.217791, x2: -0.000070
In practice, is a robust default across most architectures, with the learning rate tuned via the effective step . However, momentum still applies a single scalar step size to all coordinates. When gradient scales differ by orders of magnitude across layers, as in Transformers, we need per-coordinate adaptive scaling (Section 9.5).
9.4.5 Summary#
Heavy-ball momentum updates parameters along an exponentially decaying velocity with memory horizon , amplifying persistent gradient directions to an effective step while damping sign-alternating directions to and raising the stability ceiling to . On a quadratic bowl with condition number , critically damping the extreme eigenvalues at lowers the iteration complexity from to . Nesterov momentum evaluates the gradient at the look-ahead point , providing anticipatory damping that suppresses underdamped ringing and extends acceleration to general smooth convex functions. Under minibatch noise, momentum preserves the stationary noise ball at matched effective step , yielding large speedups in curvature-limited regimes while requiring in noise-limited regimes.
9.4.6 Exercises#
-
[code] Momentum and learning rate grid. Run
momentum_2donf_valleyacross and for up to steps. Tabulate the steps required to reach (or divergence) and compare the empirical optimum at each against (9.4.3) and . -
Velocity noise-to-signal ratio. For with i.i.d. zero-mean noise of variance per coordinate, show that in (9.4.1) has stationary mean and stationary variance , reducing the velocity's noise-to-signal ratio by .
-
Equivalent forms of Nesterov momentum and stability.
-
The exponentially averaged momentum form. Compare (9.4.1) against the normalized EMA form , used in Adam (Section 9.5). Show that , so both trajectories coincide when .
-
[code] Momentum under minibatch noise across batch sizes. ●
- On with noisy gradient , compare the stationary iterate variance of plain SGD at step size against momentum () at for .
- Train
d2l.FashionCNNfor steps at batch sizes with at matched effective step , then sweep at to verify that momentum accelerates training once the batch size is large enough to enter the curvature-limited regime.