AI Logic

Optimizers

Nesterov's Accelerated Gradient

Updated:

How Nesterov's accelerated gradient works. The left side shows one step: measure the gradient at the point reached by moving ahead by the momentum, then update the velocity and parameters (the point where the gradient is measured, which differs from momentum, is shown in the yellow frame). The right side compares, on loss contours, the widely oscillating trajectory of momentum with the same coefficient and learning rate against that of Nesterov, which suppresses the oscillation and heads toward the minimum

Background and Overview

Nesterov's accelerated gradient (NAG) is an optimizer that measures the gradient at the point reached by moving ahead with the momentum and corrects the velocity from there. The only difference from momentum is where the gradient is measured.

It was originally proposed by Nesterov in 1983 as a method for minimizing smooth convex functions. Ordinary gradient descent can only reduce the loss error to something proportional to 1/k1/k after kk iterations, whereas Nesterov's method reduces it at a rate proportional to 1/k21/k^2. The paper states that, for this class of problems, this rate cannot be improved by any method that uses only gradients.

The method came into use in deep learning through the 2013 paper by Sutskever et al. They rewrote Nesterov's method in the same form as momentum and presented it as "momentum that uses the gradient at the point reached by the momentum." Hinton's lecture (6c) summarizes it as follows.

  • Momentum: measure the gradient at the current position, then take a big jump in the direction of the accumulated velocity.
  • Nesterov: first take a big jump in the direction of the previous velocity, then measure the gradient where it lands and correct.

Hinton explains this as "it is better to correct a mistake after you have made it." It is like riding a bicycle quickly down a hill and braking based not on the slope where you are, but on the slope a few meters ahead if you keep going. It notices overshooting sooner, so the oscillation is smaller.

Theory (One Step of the Computation)

In the form used in deep learning (Eqs. (3)(4) of Sutskever et al., 2013), with learning rate ε\varepsilon, momentum coefficient μ\mu, and velocity vtv_t (v0=0v_0 = 0), each step tt performs the following computation.

  1. Find the point θt+μvt\theta_t + \mu v_t reached by moving ahead by the current velocity.
  2. At that point, compute the gradient of the mini-batch loss ∇f(θt+μvt)\nabla f(\theta_t + \mu v_t).
  3. Keep μ\mu times the previous velocity and add the correction opposite to the gradient measured in step 2 to obtain the new velocity vt+1v_{t+1}.
  4. Move the parameters by the new velocity.

As equations:

vt+1=μvt−ε∇f(θt+μvt),θt+1=θt+vt+1v_{t+1} = \mu v_t - \varepsilon \nabla f(\theta_t + \mu v_t), \qquad \theta_{t+1} = \theta_t + v_{t+1}

Compared with the momentum equation vt+1=μvt−ε∇f(θt)v_{t+1} = \mu v_t - \varepsilon \nabla f(\theta_t), the only change is that the point where the gradient is measured moves from θt\theta_t to θt+μvt\theta_t + \mu v_t. The figure below shows the difference between the two for one step from the same position and velocity, using the same elements. Both are drawn in the order "move by the momentum μvt\mu v_t" → "correct with the gradient", and the only difference is the point where the gradient is measured (the yellow dot).

One step of momentum and Nesterov's accelerated gradient. On the left, momentum corrects with the gradient measured at the current position, so it overshoots past the valley floor. On the right, Nesterov corrects with the gradient measured at the point reached by the momentum, so it is pulled back toward the valley floor

With momentum on the left, the correction uses the gradient at the current position, so it fails to notice how far the momentum has carried it past the valley floor and keeps going down. With Nesterov on the right, the gradient is measured beyond the valley floor, so the correction points back toward the valley floor and the overshoot is smaller.

Nesterov's Original Form

When the Lipschitz constant LL of the gradient (an upper bound on how fast the gradient changes) is known, the method in Nesterov's paper can be written as follows with learning rate α=1/L\alpha = 1/L (Eqs. (3)–(5) in the paper, with a0=1a_0 = 1 and x−1=y0x_{-1} = y_0).

xk=yk−α∇f(yk),ak+1=1+4ak2+12,yk+1=xk+ak−1ak+1(xk−xk−1)x_k = y_k - \alpha \nabla f(y_k), \qquad a_{k+1} = \frac{1 + \sqrt{4a_k^2 + 1}}{2}, \qquad y_{k+1} = x_k + \frac{a_k - 1}{a_{k+1}}(x_k - x_{k-1})

yky_k is the point where the gradient is measured, and xkx_k is the sequence of approximate solutions. Setting θt=xt\theta_t = x_t, vt=xt−xt−1v_t = x_t - x_{t-1}, and μ=(ak−1)/ak+1\mu = (a_k - 1)/a_{k+1} gives the same form as the equations of Sutskever et al. above. In the original method the coefficient μ\mu starts at 0 and approaches 1, but in deep learning a constant value (e.g., 0.9) is usually used. The paper proved the following guarantee for this method (Theorem 1), where f∗f^* is the minimum value and x∗x^* is a point that attains it.

f(xk)−f∗≤2L∥y0−x∗∥2(k+2)2f(x_k) - f^* \le \frac{2L \lVert y_0 - x^* \rVert^2}{(k+2)^2}

The paper states explicitly that with this method the loss does not necessarily decrease at every iteration (it is not monotone). In exchange, it achieves the 1/k21/k^2 rate with only one gradient computation per iteration. The paper calls the update of yky_k "a step along the ravine."

Why It Is More Stable than Momentum

Sutskever et al. (2013) showed exactly how momentum (CM) and Nesterov (NAG) differ when the loss is quadratic (Theorem 2.1 in the paper). Looking at each direction with curvature λ\lambda (each eigenvector direction of the Hessian), Nesterov behaves the same as momentum with the coefficient μ(1−λε)\mu(1 - \lambda\varepsilon) instead of μ\mu.

  • The momentum automatically weakens in high-curvature directions: in directions where λ\lambda is large (steep), 1−λε1 - \lambda\varepsilon becomes small and the effective momentum coefficient drops. This prevents oscillation and divergence, so a larger μ\mu can be used than with momentum.
  • With a small learning rate, they are almost the same: if λε\lambda\varepsilon is much smaller than 1 in every direction, then μ(1−λε)≈μ\mu(1-\lambda\varepsilon) \approx \mu, and the two barely differ. The difference appears when the learning rate is reasonably large.

The right side of the figure at the top compares the two with the same μ=0.9\mu = 0.9 and the same learning rate in a long, narrow valley that is steep vertically. Momentum keeps oscillating widely, while Nesterov heads toward the minimum with almost no oscillation. Sutskever et al. likewise show, on a similar elongated quadratic, that momentum oscillates widely in the high-curvature vertical direction while Nesterov almost entirely avoids that oscillation. They explain that even if the difference per step is small, it accumulates over many iterations.

Experimental Results

Sutskever et al. (2013) trained 7- to 11-layer autoencoders (three tasks: Curves, MNIST, and Faces) for 750,000 updates with mini-batches of 200 and compared the squared error on the training data of momentum (CM) and Nesterov (NAG) for each upper limit μmax⁡\mu_{\max} of the momentum coefficient (Table 1 in the paper; the coefficient starts small and is gradually raised to μmax⁡\mu_{\max}, and the best learning rate is chosen for each setting).

Taskμmax⁡\mu_{\max}MomentumNesterov
Curves0.90.150.16
Curves0.990.100.096
Curves0.9990.100.074
MNIST0.91.01.0
MNIST0.990.770.73
MNIST0.9990.900.80
Faces0.915.314.2
Faces0.998.78.5
Faces0.9999.37.7

The error of SGD without momentum was 0.48 on Curves, 2.1 on MNIST, and 36.4 on Faces.

  • The larger the coefficient, the greater Nesterov's advantage: at μmax⁡=0.9\mu_{\max} = 0.9 the two barely differ, but at 0.999 Nesterov had lower error on every task. This matches the theorem above, which shows that Nesterov handles large coefficients well.
  • Results approached those of second-order optimizers: the paper reports that Nesterov achieved errors comparable to the best results of the second-order method of the time (Hessian-free optimization).

The same paper also reports that after training with Nesterov, lowering the coefficient to 0.9 for only the last 1000 updates reduced the error further (Curves 0.096 → 0.074, MNIST 1.20 → 0.73, Faces 10.83 → 7.7; Table 2 in the paper). It further states that on RNN tasks requiring long-range dependencies, increasing the coefficient improved results with Nesterov but not with momentum.

Practical Considerations

PyTorch's nesterov=True is implemented with equations that look different from those above. PyTorch computes the gradient gtg_t at the current parameters θt−1\theta_{t-1} and updates bt=μbt−1+gtb_t = \mu b_{t-1} + g_t, θt=θt−1−γ(gt+μbt)\theta_t = \theta_{t-1} - \gamma (g_t + \mu b_t) (γ\gamma is the learning rate). Instead of computing the gradient separately at "the look-ahead point", it is a rewritten form that treats the parameters PyTorch holds as the look-ahead point θ+μv\theta + \mu v itself. With a constant learning rate, it follows the same sequence of points as the equations of Sutskever et al. (this can be checked in the implementation example below). As a result, only one gradient computation is needed, and the cost is the same as momentum. However, if the learning rate is changed mid-training, the update differs slightly from the paper's equations because the learning rate is applied at a different place.

  • Only usable when momentum is greater than 0 and dampening is 0: setting nesterov=True with any other combination makes PyTorch raise an error.
  • With a small learning rate, it is almost the same as momentum: as the theorem above shows, the difference appears when the learning rate is reasonably large. If switching from momentum shows no difference, try whether there is room to raise the momentum coefficient.
  • The 1/k21/k^2 guarantee is about noise-free gradients and convex functions: Sutskever et al. (2013) cite prior work showing that with noisy gradients, such as mini-batch gradients, the advantage in the speed of the final fine convergence is lost. In deep learning, it helps in the stage before fine convergence begins.
  • Lowering the coefficient at the end helps fine convergence: as in the experiments above, lowering the coefficient at the end of training can reduce the error. However, the paper also reports that lowering the coefficient early made the final error worse.

Comparison with Other Optimizers

The table lines up Nesterov's accelerated gradient and closely related methods from the same perspectives.

MethodWhere the gradient is measuredRobustness to a large momentum coefficientComputation per stepExtra memory
SGDCurrent position(no coefficient)One gradientNone
MomentumCurrent positionTends to oscillate with a large coefficientOne gradientOne copy of the parameters
Nesterov's accelerated gradientPoint reached by the momentumMomentum weakens in steep directions, so it oscillates lessOne gradientOne copy of the parameters

Rough guidelines for choosing:

  • If using SGD with momentum, nesterov=True is worth trying first: computation and memory are the same, and it suppresses oscillation when the coefficient is large.
  • With a small learning rate and a coefficient around 0.9, expect little difference: the results may be almost the same either way.
  • To change the step size per parameter, use Adam-family methods: there is also Nadam (Dozat, 2016), which brings Nesterov momentum into Adam.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of Nesterov's accelerated gradient, written exactly as Eqs. (3)(4) of Sutskever et al. (2013)
def nag_step(theta, v, grad_fn, lr, mu):
    lookahead = theta + mu * v           # Point reached by moving ahead by the momentum
    v = mu * v - lr * grad_fn(lookahead) # Measure the gradient at the look-ahead point and correct
    theta = theta + v
    return theta, v


def grad_fn(x):                          # Example: gradient of f(x) = Σ (x - 3)^2
    return 2 * (x - 3.0)


# Compare with PyTorch's SGD(nesterov=True)
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
theta = w.detach().clone()
v = torch.zeros_like(theta)
mu, lr = 0.9, 0.1
optimizer = torch.optim.SGD([w], lr=lr, momentum=mu, nesterov=True)

for t in range(10):
    loss = ((w - 3.0) ** 2).sum()
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    theta, v = nag_step(theta, v, grad_fn, lr, mu)

# The parameters PyTorch holds correspond to the look-ahead point θ + μv
print(torch.allclose(w.detach(), theta + mu * v, atol=1e-5))  # Should be True


# Use in actual training: just add nesterov=True to SGD with momentum
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9, nesterov=True,
                            weight_decay=5e-4)   # Keep dampening at 0 (the default)
criterion = nn.CrossEntropyLoss()

images = torch.randn(64, 1, 28, 28)              # Dummy mini-batch
labels = torch.randint(0, 10, (64,))
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()

FAQ

Q. Should momentum or Nesterov's accelerated gradient be used?
A.

Computation and memory are the same, so if using SGD with momentum, Nesterov is worth trying. Especially when raising the momentum coefficient to something like 0.99, Nesterov oscillates less. With a small learning rate, the two barely differ.

Q. Does the gradient need to be computed twice?
A.

No. Implementations such as PyTorch's rewrite the equations by treating the stored parameters as the look-ahead point, so only one gradient computation is needed per step.

Q. Is the $1/k^2$ rate of the original paper achieved in deep learning too?
A.

It is not guaranteed. The 1/k21/k^2 guarantee concerns noise-free gradients and smooth convex functions. Deep learning losses are not convex, and mini-batch gradients are noisy. Even so, experiments report that it suppresses oscillation and progresses faster from the beginning to the middle of training.

References

  1. Ю. Е. Нестеров, "Метод решения задачи выпуклого программирования со скоростью сходимости O(1/k²)," Доклады АН СССР, т. 269, № 3, с. 543–547, 1983 (English title: A method of solving a convex programming problem with convergence rate O(1/k²)).
  2. I. Sutskever, J. Martens, G. Dahl, and G. Hinton, "On the importance of initialization and momentum in deep learning," ICML, 2013.
  3. G. Hinton, N. Srivastava, and K. Swersky, "Neural Networks for Machine Learning, Lecture 6c: The momentum method," 2012.
  4. PyTorch Documentation, "torch.optim.SGD."