9.4 Momentum

In Section 9.1, we saw why plain gradient descent struggles on an ill-conditioned valley: the steepest curvature λmax⁡\lambda_{\max} imposes the stability ceiling η<2/λmax⁡\eta \lt 2/\lambda_{\max}, forcing the flattest direction λmin⁡\lambda_{\min} to contract by at most O(1/κ)O(1/\kappa) per step, where κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} is the condition number. Plain gradient descent is slow because each step relies solely on the instantaneous gradient gt\mathbf{g}_t. 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 O(κ)O(\kappa) to O(κ)O(\sqrt{\kappa}) 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 κ\sqrt{\kappa} 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 β\beta and η\eta.

import random

9.4.1 The Momentum Method#

9.4.1.1 Velocity and Effective Step Size#

Given gradient gt\mathbf{g}_t at step tt (exact or minibatch), heavy-ball momentum maintains a velocity vector vt\mathbf{v}_t initialized at v0=0\mathbf{v}_0 = \mathbf{0} and updates:

vt=β vt−1+gt,xt+1=xt−η vt,(9.4.1)\begin{aligned} \mathbf{v}_t &= \beta\, \mathbf{v}_{t-1} + \mathbf{g}_t, \\ \mathbf{x}_{t+1} &= \mathbf{x}_t - \eta\, \mathbf{v}_t, \end{aligned} \tag{9.4.1}

where β∈[0,1)\beta \in [0, 1) is the momentum coefficient (β=0\beta = 0 recovers gradient descent). Unrolling the recursion expresses the velocity as an exponentially weighted sum of all past gradients:

vt=∑k=0t−1βkgt−k=gt+β gt−1+β2 gt−2+⋯+βt−1 g1.\mathbf{v}_t = \sum_{k=0}^{t-1} \beta^k \mathbf{g}_{t-k} = \mathbf{g}_t + \beta\, \mathbf{g}_{t-1} + \beta^2\, \mathbf{g}_{t-2} + \cdots + \beta^{t-1}\, \mathbf{g}_1.

Consider what this weighted sum does to the two coordinates of the valley f(x)=0.1x12+2x22f(\mathbf{x}) = 0.1 x_1^2 + 2 x_2^2 (λ1=0.2,λ2=4\lambda_1 = 0.2, \lambda_2 = 4) at η=0.6\eta = 0.6—above the plain gradient descent stability limit 2/λ2=0.52/\lambda_2 = 0.5, where plain gradient descent diverges along x2x_2 by factor 1−4(0.6)=−1.41 - 4(0.6) = -1.4 per step. Adding momentum β=0.5\beta = 0.5 stabilizes the trajectory and brings both coordinates within 0.010.01 of the origin in 2020 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 (gt−k≈g\mathbf{g}_{t-k} \approx \mathbf{g}), the velocity builds up to vt≈(1+β+β2+⋯ )g=11−βg\mathbf{v}_t \approx (1 + \beta + \beta^2 + \cdots)\mathbf{g} = \frac{1}{1-\beta}\mathbf{g}, yielding the effective step size
ηeff=η1−β.(9.4.2)\eta_\textrm{eff} = \frac{\eta}{1-\beta}. \tag{9.4.2}
  • Alternating gradients (steep walls): When successive gradients alternate in sign (gt−k≈(−1)kg\mathbf{g}_{t-k} \approx (-1)^k \mathbf{g}), the geometric series sums to 1−β+β2−⋯=11+β1 - \beta + \beta^2 - \cdots = \frac{1}{1+\beta}, damped to an effective step size of η1+β\frac{\eta}{1+\beta}.

Figure 9.4.1 shows both cases for gradients of unit size.

Figure 9.4.1:

The velocity vt=βvt−1+gtv_t = \beta v_{t-1} + g_t (blue) for unit gradients gtg_t (gray bars) at β=0.5\beta = 0.5. Left: gradients of the same sign add up, and vtv_t approaches 1/(1−β)=21/(1-\beta) = 2. Right: gradients of alternating sign largely cancel, and vtv_t settles into an oscillation of amplitude 1/(1+β)=2/31/(1+\beta) = 2/3.

At η=0.6\eta = 0.6 and β=0.5\beta = 0.5, momentum amplifies progress along the valley floor to ηeff=0.6/0.5=1.2\eta_{\text{eff}} = 0.6 / 0.5 = 1.2 while damping oscillations across the steep wall to 0.6/1.5=0.4<0.50.6 / 1.5 = 0.4 \lt 0.5. Consequently, the stability ceiling for curvature λ\lambda rises from ηλ<2\eta\lambda \lt 2 to ηλ<2(1+β)\eta\lambda \lt 2(1 + \beta) (Exercise 3).

9.4.1.2 The Timescale of β\beta and Minibatch Noise#

Because the weights 1,β,β2,…1, \beta, \beta^2, \ldots sum to 1/(1−β)1/(1-\beta), the velocity has an effective memory window of τ=1/(1−β)\tau = 1/(1-\beta) steps and a half-life of log⁡(1/2)/log⁡β\log(1/2)/\log\beta 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 β\beta from 0.90.9 to 0.990.99 expands both the memory horizon and the effective step size ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta) tenfold (from 1010 steps to 100100 steps).

Under stochastic gradients gt=∇f(xt)+ξt\mathbf{g}_t = \nabla f(\mathbf{x}_t) + \boldsymbol{\xi}_t, does averaging over 1/(1−β)1/(1-\beta) steps shrink the stationary noise ball of Section 9.2? No: each noise perturbation ξt\boldsymbol{\xi}_t enters vt\mathbf{v}_t with weight 11 and decays as βk\beta^k over subsequent steps, contributing a cumulative displacement of η(1+β+β2+⋯ )ξt=ηeffξt\eta(1 + \beta + \beta^2 + \cdots)\boldsymbol{\xi}_t = \eta_{\text{eff}}\boldsymbol{\xi}_t. Thus, at matched effective step size ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta), SGD with and without momentum settle into stationary noise balls of nearly identical variance (Exercise 5). When increasing β\beta in a noise-limited run, η\eta should therefore be scaled proportional to 1−β1 - \beta to hold ηeff\eta_{\text{eff}} constant.

9.4.2 Acceleration and Critical Damping#

What choice of (η,β)(\eta, \beta) is optimal on a quadratic with eigenvalues λmin⁡≤⋯≤λmax⁡\lambda_{\min} \le \cdots \le \lambda_{\max} and condition number κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}? Polyak (1964) proved that setting

η⋆=4(λmax⁡+λmin⁡)2,β⋆=(κ−1κ+1)2(9.4.3)\eta^\star = \frac{4}{\left(\sqrt{\lambda_{\max}} + \sqrt{\lambda_{\min}}\right)^2}, \qquad \beta^\star = \left(\frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1}\right)^{2} \tag{9.4.3}

achieves the worst-case per-step contraction factor

ρ⋆=β⋆=κ−1κ+1≈1−2κ,\rho^\star = \sqrt{\beta^\star} = \frac{\sqrt{\kappa} - 1}{\sqrt{\kappa} + 1} \approx 1 - \frac{2}{\sqrt{\kappa}},

reducing the steps needed to reach relative accuracy ϵ\epsilon from κ2log⁡(1/ϵ)\frac{\kappa}{2}\log(1/\epsilon) to κ2log⁡(1/ϵ)\frac{\sqrt{\kappa}}{2}\log(1/\epsilon) (Section 23.1.3).

To see why the contraction factor equals β⋆\sqrt{\beta^\star}, substitute ηvt=xt−xt+1\eta v_t = x_t - x_{t+1} into the 1D velocity update along an eigenvector of curvature λ\lambda to obtain the second-order linear recurrence

xt+1=(1+β−ηλ) xt−β xt−1,(9.4.4)x_{t+1} = (1 + \beta - \eta\lambda)\, x_t - \beta\, x_{t-1}, \tag{9.4.4}

whose characteristic polynomial is z2−(1+β−ηλ)z+β=0z^2 - (1 + \beta - \eta\lambda)z + \beta = 0. By Vieta's formulas, the product of the two roots is z1z2=βz_1 z_2 = \beta. Whenever the discriminant Δ=(1+β−ηλ)2−4β\Delta = (1 + \beta - \eta\lambda)^2 - 4\beta is non-positive (which occurs for all β≥βc(λ)=(1−ηλ)2\beta \ge \beta_{\text{c}}(\lambda) = (1 - \sqrt{\eta\lambda})^2), the roots form a complex-conjugate pair of identical modulus ∣z1∣=∣z2∣=β|z_1| = |z_2| = \sqrt{\beta}, independent of the curvature λ\lambda (Figure 9.4.2).

Figure 9.4.2:

Per-step contraction factor of heavy-ball momentum along curvature λ\lambda as a function of β\beta. Convergence is fastest at the critical damping threshold βc=(1−ηλ)2\beta_\textrm{c} = (1 - \sqrt{\eta\lambda})^2; below βc\beta_\textrm{c} the mode is overdamped, while above βc\beta_\textrm{c} it oscillates with modulus β\sqrt{\beta}.

The optimal parameters (9.4.3) equate the critical damping thresholds of the flattest and steepest eigenvalues, (1−η⋆λmin⁡)2=(η⋆λmax⁡−1)2=β⋆(1 - \sqrt{\eta^\star\lambda_{\min}})^2 = (\sqrt{\eta^\star\lambda_{\max}} - 1)^2 = \beta^\star, critically damping both extreme modes while ensuring that every intermediate eigenvalue λ∈[λmin⁡,λmax⁡]\lambda \in [\lambda_{\min}, \lambda_{\max}] lies in the underdamped complex-root regime and contracts at rate β⋆\sqrt{\beta^\star}.

On our valley (κ=20\kappa = 20), (9.4.3) yields η⋆≈0.668,β⋆≈0.403\eta^\star \approx 0.668, \beta^\star \approx 0.403, reducing the asymptotic contraction factor from 0.9050.905 to β⋆≈0.635\sqrt{\beta^\star} \approx 0.635 and cutting the steps to reach 10−610^{-6} relative error from 139139 down to 4040:

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 (η=0.3,β=0.8\eta = 0.3, \beta = 0.8): choosing β\beta well above the critical threshold βc\beta_{\text{c}} leaves both coordinates underdamped with modulus 0.8≈0.894\sqrt{0.8} \approx 0.894, 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:

  1. Curvature-limited regime (accurate gradients, large κ\kappa): Momentum permits a larger effective step ηeff\eta_{\text{eff}} and reduces the required iteration count by a large factor.
  2. Noise-limited regime (small minibatches): The stationary noise floor is governed by ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta), so adding β=0.9\beta = 0.9 shifts the optimal learning rate down by a factor of 1−β=0.11 - \beta = 0.1 while achieving comparable convergence speed.

We verify both regimes on Fashion-MNIST by comparing β=0\beta = 0 and β=0.9\beta = 0.9 on (1) full-batch softmax regression (b=60,000b = 60{,}000, exact gradients, ill-conditioned due to non-negative pixel intensities) and (2) FashionCNN (Section 9.3.2) with small minibatches (b=32b = 32). 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 β∈{0.0,0.9}\beta \in \{0.0, 0.9\}, 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 β=0.9\beta = 0.9 increases the optimal learning rate from η=0.125\eta = 0.125 to η=0.4\eta = 0.4 (ηeff=4.0\eta_{\text{eff}} = 4.0, a 32×32\times larger effective step), cutting the steps needed to reach loss 0.50.5 by more than 6×6\times (625→100625 \to 100 steps) and lowering the final loss from 0.4720.472 to 0.3650.365.
  • On small-batch FashionCNN (b=32b = 32), the run is noise-limited: the optimal learning rate drops from η≈0.1\eta \approx 0.1–0.20.2 at β=0\beta = 0 to η≈0.02\eta \approx 0.02–0.040.04 at β=0.9\beta = 0.9 (a factor of 55–1010 that keeps the effective step ηeff\eta_{\text{eff}} within one step of the factor-of-two grid of its β=0\beta = 0 value), and both configurations reach loss 0.30.3 and final losses of 0.260.26–0.300.30 within the single-seed variation of Section 9.3.

9.4.4 Nesterov Momentum#

In the underdamped run (η=0.3,β=0.8\eta = 0.3, \beta = 0.8), heavy-ball momentum overshot the minimum because it evaluated the gradient at the current position xt\mathbf{x}_t rather than at the point where the velocity was about to carry it. Nesterov (1983) proposed evaluating the gradient at the look-ahead point xt−ηβvt−1\mathbf{x}_t - \eta\beta\mathbf{v}_{t-1} (Figure 9.4.3):

vt=β vt−1+∇f(xt−ηβ vt−1),xt+1=xt−η vt.(9.4.5)\begin{aligned} \mathbf{v}_t &= \beta\, \mathbf{v}_{t-1} + \nabla f(\mathbf{x}_t - \eta \beta\, \mathbf{v}_{t-1}), \\ \mathbf{x}_{t+1} &= \mathbf{x}_t - \eta\, \mathbf{v}_t. \end{aligned} \tag{9.4.5}
Figure 9.4.3:

One step of heavy-ball versus Nesterov momentum from the same iterate and velocity. Heavy-ball evaluates the gradient at xt\mathbf{x}_t and overshoots; Nesterov evaluates the gradient at the look-ahead point xt−ηβvt−1\mathbf{x}_t - \eta\beta\mathbf{v}_{t-1}, 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 β=(κ−1)/(κ+1)\beta = (\sqrt{\kappa} - 1)/(\sqrt{\kappa} + 1), Nesterov momentum attains the κ\sqrt{\kappa} rate on every smooth, strongly convex function, not only on quadratics. With the increasing schedule βt=(t−1)/(t+2)\beta_t = (t-1)/(t+2), it achieves the optimal O(1/t2)O(1/t^2) convergence rate on general smooth convex objectives (Nesterov, 2018) (Section 23.1.3). We use a constant β\beta 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, β=0.9\beta = 0.9 is a robust default across most architectures, with the learning rate tuned via the effective step ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta). 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 vt=βvt−1+gt\mathbf{v}_t = \beta\mathbf{v}_{t-1} + \mathbf{g}_t with memory horizon 1/(1−β)1/(1-\beta), amplifying persistent gradient directions to an effective step ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta) while damping sign-alternating directions to η/(1+β)\eta/(1+\beta) and raising the stability ceiling to ηλ<2(1+β)\eta\lambda \lt 2(1+\beta). On a quadratic bowl with condition number κ\kappa, critically damping the extreme eigenvalues at (η⋆,β⋆)(\eta^\star, \beta^\star) lowers the iteration complexity from O(κ)O(\kappa) to O(κ)O(\sqrt{\kappa}). Nesterov momentum evaluates the gradient at the look-ahead point xt−ηβvt−1\mathbf{x}_t - \eta\beta\mathbf{v}_{t-1}, 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 ηeff=η/(1−β)\eta_{\text{eff}} = \eta/(1-\beta), yielding large speedups in curvature-limited regimes while requiring η∝1−β\eta \propto 1 - \beta in noise-limited regimes.

9.4.6 Exercises#

  1. [code] Momentum and learning rate grid. Run momentum_2d on f_valley across β∈{0,0.25,0.5,0.8}\beta \in \{0, 0.25, 0.5, 0.8\} and η∈{0.1,0.3,0.6,1.0}\eta \in \{0.1, 0.3, 0.6, 1.0\} for up to 1,0001{,}000 steps. Tabulate the steps required to reach ∥xt∥≤10−3\|\mathbf{x}_t\| \le 10^{-3} (or divergence) and compare the empirical optimum at each η\eta against β⋆\beta^\star (9.4.3) and βc(λ)=(1−ηλ)2\beta_{\text{c}}(\lambda) = (1 - \sqrt{\eta\lambda})^2.

  2. Velocity noise-to-signal ratio. For gt=g+ξt\mathbf{g}_t = \mathbf{g} + \boldsymbol{\xi}_t with i.i.d. zero-mean noise of variance σ2\sigma^2 per coordinate, show that vt\mathbf{v}_t in (9.4.1) has stationary mean g/(1−β)\mathbf{g}/(1-\beta) and stationary variance σ2/(1−β2)\sigma^2/(1-\beta^2), reducing the velocity's noise-to-signal ratio by (1−β)/(1+β)\sqrt{(1-\beta)/(1+\beta)}.

  3. Equivalent forms of Nesterov momentum and stability.

    1. Show by induction that the library form vt=βvt−1+∇f(yt)\mathbf{v}_t = \beta\mathbf{v}_{t-1} + \nabla f(\mathbf{y}_t), yt+1=yt−η(∇f(yt)+βvt)\mathbf{y}_{t+1} = \mathbf{y}_t - \eta(\nabla f(\mathbf{y}_t) + \beta\mathbf{v}_t) produces the exact same velocities as (9.4.5) with yt=xt−ηβvt−1\mathbf{y}_t = \mathbf{x}_t - \eta\beta\mathbf{v}_{t-1}.
    2. Prove from (9.4.4) that both roots of z2−(1+β−ηλ)z+β=0z^2 - (1 + \beta - \eta\lambda)z + \beta = 0 lie strictly inside the unit circle for 0≤β<10 \le \beta \lt 1 if and only if 0<ηλ<2(1+β)0 \lt \eta\lambda \lt 2(1+\beta).
  4. The exponentially averaged momentum form. Compare (9.4.1) against the normalized EMA form mt=βmt−1+(1−β)gt\mathbf{m}_t = \beta\mathbf{m}_{t-1} + (1-\beta)\mathbf{g}_t, xt+1=xt−αmt\mathbf{x}_{t+1} = \mathbf{x}_t - \alpha\mathbf{m}_t used in Adam (Section 9.5). Show that mt=(1−β)vt\mathbf{m}_t = (1-\beta)\mathbf{v}_t, so both trajectories coincide when α=η/(1−β)=ηeff\alpha = \eta/(1-\beta) = \eta_{\text{eff}}.

  5. [code] Momentum under minibatch noise across batch sizes. ●

    1. On f(x)=λ2x2f(x) = \frac{\lambda}{2}x^2 with noisy gradient gt=λxt+ξtg_t = \lambda x_t + \xi_t, compare the stationary iterate variance of plain SGD at step size α\alpha against momentum (β=0.9\beta = 0.9) at η=(1−β)α\eta = (1-\beta)\alpha for αλ∈{0.05,0.2}\alpha\lambda \in \{0.05, 0.2\}.
    2. Train d2l.FashionCNN for 1,0001{,}000 steps at batch sizes b∈{32,500,6000}b \in \{32, 500, 6000\} with β∈{0,0.9}\beta \in \{0, 0.9\} at matched effective step η/(1−β)=0.2\eta/(1-\beta) = 0.2, then sweep η\eta at b=6000b = 6000 to verify that momentum accelerates training once the batch size is large enough to enter the curvature-limited regime.

Discussions