AI Logic

Optimizers

Momentum

Updated:

How momentum works. The left side shows one step: measure the gradient at the current position, then move the parameters by a velocity that keeps the previous velocity and adds the gradient. The right side compares, on loss contours, the zigzag trajectory of gradient descent with that of momentum at the same learning rate, which damps the oscillation and heads toward the minimum

Background and Overview

Momentum is an optimizer that keeps a fixed fraction of the previous update direction and adds a correction from the current gradient to move the parameters. Polyak proposed it in 1964 and named it the "heavy ball method" in his paper. In deep learning, "SGD with momentum", which adds momentum to SGD, is still a standard choice for tasks such as image classification.

Gradient descent always moves in the steepest downhill direction at the current point (opposite to the gradient). But when the loss landscape is shaped like a long, narrow valley, the steepest direction points toward the opposite slope rather than along the valley floor. As a result, it bounces back and forth across the valley and makes little progress along the valley floor.

Momentum solves this problem with "inertia". Polyak showed that the method is described by the same equation as the motion of a body moving in a potential. A heavy ball does not change direction abruptly even if the slope keeps changing; it keeps its momentum and rolls along the valley floor. Gradients across the valley flip sign between the way there and the way back and cancel out, while gradients along the valley floor point the same way every time and accumulate.

It is like riding a bicycle down a gentle slope: building speed by pedaling gets you there faster than making small steering corrections back and forth.

Polyak proved that this method approaches the minimum in far fewer iterations than gradient descent, with almost no extra computation. Later, in 2013, Sutskever et al. showed that with a suitably large momentum coefficient, SGD with momentum can successfully train deep networks and RNNs that had been considered hard to train, which brought renewed attention to it in deep learning.

Theory (One Step of the Computation)

In Polyak's paper, momentum (the heavy ball method) is written as the following single equation (Eq. (9) in the paper). α\alpha is the learning rate, β\beta is the momentum coefficient, and ∇f\nabla f is the gradient of the loss.

θt+1=θt−α∇f(θt)+β(θt−θt−1)\theta_{t+1} = \theta_t - \alpha \nabla f(\theta_t) + \beta(\theta_t - \theta_{t-1})

The last term on the right, β(θt−θt−1)\beta(\theta_t - \theta_{t-1}), keeps β\beta times the previous update (the amount moved). With β=0\beta = 0 it is plain gradient descent.

In deep learning, it is common to store the previous update as a "velocity" vt=θt−θt−1v_t = \theta_t - \theta_{t-1} and write the update in two stages (Eqs. (1)(2) of Sutskever et al., 2013). Writing the learning rate as ε\varepsilon and the momentum coefficient as μ\mu, each step tt performs the following computation.

  1. At the current position θt\theta_t, compute the gradient of the mini-batch loss ∇f(θt)\nabla f(\theta_t).
  2. Keep μ\mu times the previous velocity vtv_t and add the correction −ε∇f(θt)-\varepsilon \nabla f(\theta_t) opposite to the gradient to obtain the new velocity vt+1v_{t+1}.
  3. Move the parameters by the new velocity.

As equations, the velocity starts at v0=0v_0 = 0.

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

Since vt+1=θt+1−θtv_{t+1} = \theta_{t+1} - \theta_t, substituting the second equation into the first gives Polyak's equation (α=ε\alpha = \varepsilon, β=μ\beta = \mu).

Expanding the velocity equation gives vt+1=−ε∑k=0tμk∇f(θt−k)v_{t+1} = -\varepsilon \sum_{k=0}^{t} \mu^{k} \nabla f(\theta_{t-k}): a sum of past gradients, with older ones shrunk by a factor of μ\mu per step. On a slope with constant incline (the same gradient gg every time), the velocity approaches −εg/(1−μ)-\varepsilon g / (1-\mu) (Hinton's Lecture 6c). With μ=0.9\mu = 0.9, it moves about 10 times as fast as gradient descent with the same learning rate.

Why It Converges Faster

Polyak compared the convergence speed of gradient descent and momentum for the case where the loss near the minimum can be approximated by a quadratic function whose curvature (the eigenvalues of the Hessian) lies between mm and MM (Theorem 9 in the paper). In both cases the error shrinks like a geometric sequence, and the factor by which the error is multiplied per iteration (the ratio) is as follows.

MethodParameter choiceRatio (smaller is faster)
Gradient descentα=2M+m\alpha = \dfrac{2}{M+m}M−mM+m\dfrac{M-m}{M+m}
Momentumα=4(M+m)2\alpha = \dfrac{4}{(\sqrt{M}+\sqrt{m})^2}, β=(M−mM+m)2\beta = \left(\dfrac{\sqrt{M}-\sqrt{m}}{\sqrt{M}+\sqrt{m}}\right)^2M−mM+m\dfrac{\sqrt{M}-\sqrt{m}}{\sqrt{M}+\sqrt{m}}

The difference grows when the curvature ratio ρ=M/m\rho = M/m (the condition number) is large, that is, for a long, narrow valley that is steep in one direction and nearly flat in another. Polyak estimated the number of iterations needed to reduce the error by a factor of e−ke^{-k} as about kρ/2k\rho/2 for gradient descent and about kρ/2k\sqrt{\rho}/2 for momentum. For example, with ρ=100\rho = 100, the ratio is about 0.98 for gradient descent and about 0.82 for momentum, and the required number of iterations drops to about one tenth. Polyak notes that many practical functions near the minimum "barely change in some directions and change sharply in others", so this difference matters.

The reason can be seen on the right side of the figure at the top. In a valley that is steep vertically (θ2\theta_2) and gentle horizontally (θ1\theta_1), gradient descent bounces up and down. With momentum, the vertical gradient flips direction every step, so it cancels against the retained velocity and the oscillation shrinks. The horizontal gradient points the same way every time, so the velocity builds up. Hinton's lecture (6c) also explains that momentum "damps oscillations in directions of high curvature by combining gradients with opposite signs, and builds up speed in directions with a gentle but consistent gradient."

Polyak also lists as an advantage of the method that its inertia lets it jump over small dips (local minima).

The guarantee above concerns the neighborhood of the minimum with noise-free gradients. Sutskever et al. (2013) cite prior work showing that with noisy gradients, such as mini-batch gradients, this advantage is lost in the speed of the final fine convergence, but argue that in deep learning the "transient phase" before fine convergence begins takes up most of the training time, and momentum helps greatly there.

Experimental Results

Polyak tried the method on several problems and reported that in many cases it converged clearly faster than gradient descent (up to about 10 times).

Sutskever et al. (2013) studied the effect of momentum in deep learning in detail. They trained 7- to 11-layer autoencoders (three tasks: Curves, MNIST, and Faces) for 750,000 updates with mini-batches of 200, varying the upper limit μmax⁡\mu_{\max} of the momentum coefficient, and compared the squared error on the training data. They used a schedule in which the coefficient starts small and gradually increases to μmax⁡\mu_{\max}, and picked the best learning rate for each setting (only the momentum columns of Table 1 in the paper are extracted here).

TaskSGD (μ=0\mu = 0)μmax⁡=0.9\mu_{\max} = 0.9μmax⁡=0.99\mu_{\max} = 0.99μmax⁡=0.995\mu_{\max} = 0.995μmax⁡=0.999\mu_{\max} = 0.999
Curves0.480.150.100.100.10
MNIST2.11.00.770.840.90
Faces36.415.38.78.39.3
  • Simply adding momentum reduced the error substantially: on all three tasks, even μmax⁡=0.9\mu_{\max} = 0.9 cut the error to less than half that of SGD.
  • Coefficients larger than 0.9 worked better: raising μmax⁡\mu_{\max} to 0.99 or more reduced the error further. However, going up to 0.999 made MNIST and Faces worse.

The same paper also compared Nesterov's accelerated gradient under the same conditions and reported that it gives lower error when the coefficient is large. It further concluded that both initialization and momentum matter, since with poor weight initialization training failed even with momentum.

Practical Considerations

The momentum in PyTorch's torch.optim.SGD applies the learning rate at a different place than the equations above. PyTorch uses bt=μbt−1+gtb_t = \mu b_{t-1} + g_t (with b1=g1b_1 = g_1 only at the first step) and θt=θt−1−γbt\theta_t = \theta_{t-1} - \gamma b_t, multiplying by the learning rate γ\gamma outside the velocity. With a constant learning rate, the updates are identical via v=−γbv = -\gamma b, but when the learning rate is lowered mid-training, PyTorch shrinks all the momentum accumulated so far by the new learning rate at once. In the paper's equations, the past velocity is kept as is and only the new gradient contribution becomes smaller. Also, setting dampening (τ\tau) to a nonzero value multiplies the gradient by (1−τ)(1-\tau) before it is added. Keep this difference in mind when porting settings from other frameworks or papers.

  • The effective step size is 1/(1−μ)1/(1-\mu) times the learning rate: on a constant slope the velocity approaches ε/(1−μ)\varepsilon/(1-\mu) times the gradient, so raising μ\mu from 0.9 to 0.99 makes it move about 10 times as fast with the same learning rate. When changing μ\mu, revisit the learning rate as well.
  • The loss does not decrease monotonically: Polyak cautions that with this method the loss does not necessarily decrease at every iteration and may rise over some intervals. He recommends lowering the learning rate and β\beta only when the loss keeps rising.
  • Choosing the coefficient: Polyak recommends first choosing the learning rate with β=0\beta = 0, then adding β\beta once convergence slows; the slower the convergence, the closer β\beta should be to 1 (usually 0.8 to 0.99), and the learning rate can then also be increased. In deep learning, 0.9 is commonly used.
  • Use a smaller coefficient early in training: Hinton's lecture (6c) recommends starting with a small coefficient (e.g., 0.5), because gradients can be very large early in training, and raising it smoothly to 0.9 or 0.99 once the large gradients have died down. Sutskever et al. (2013) also used a schedule that increases the coefficient gradually.
  • Lowering the coefficient at the end helps fine convergence: Sutskever et al. report that lowering the coefficient to 0.9 only for the last 1000 updates reduced the error further, whereas lowering it early made the final error worse.
  • Combined with Weight Decay, the decay term also enters the momentum: the λθ\lambda\theta added to the gradient by weight_decay also accumulates in the velocity. See the SGD article for details.

Comparison with Other Optimizers

The table lines up momentum and optimizers it is often compared with, from the same perspectives.

MethodWhere the gradient is measuredHow past gradients are usedPer-parameter step sizeExtra memory
SGDCurrent positionNot usedNoNone
MomentumCurrent positionAccumulated as a velocityNoOne copy of the parameters
Nesterov's accelerated gradientPoint reached by the momentumAccumulated as a velocityNoOne copy of the parameters
RMSpropCurrent positionDivides by a moving average of squared gradientsYesOne copy of the parameters
AdamCurrent positionMoving averages of gradients and squared gradientsYesTwo copies of the parameters

Rough guidelines for choosing:

  • For image classification CNNs, SGD with momentum (μ=0.9\mu = 0.9) is the standard: it is used in many papers, including ResNet. Combine it with a learning rate scheduler to lower the learning rate over time.
  • To use a larger coefficient or reduce oscillation, use Nesterov's accelerated gradient: in PyTorch it only takes nesterov=True, with almost no extra computation.
  • To reduce tuning effort, use Adam: Adam combines the idea of momentum (a moving average of gradients) with per-parameter step size adaptation.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of momentum (the heavy ball method), written exactly as Eqs. (1)(2) of Sutskever et al. (2013)
def momentum_step(theta, grad, v, lr, mu):
    v = mu * v - lr * grad      # Keep mu times the previous velocity and add a correction opposite to the gradient
    theta = theta + v           # Move by the velocity
    return theta, v


# Check that it matches PyTorch's SGD(momentum=...) (with a constant learning rate)
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
v = torch.zeros_like(w_manual)                   # v_0 = 0
optimizer = torch.optim.SGD([w], lr=0.1, momentum=0.9)   # PyTorch uses b = mu*b + g, w -= lr*b

for t in range(1, 11):
    loss = ((w - 3.0) ** 2).sum()                # Example: drive w toward 3
    optimizer.zero_grad()
    loss.backward()
    grad = w.grad.detach().clone()
    optimizer.step()
    w_manual, v = momentum_step(w_manual, grad, v, lr=0.1, mu=0.9)

print(torch.allclose(w.detach(), w_manual, atol=1e-6))  # True (with a constant learning rate, v = -lr * b)


# Use in actual training: start with a smaller coefficient and raise it to 0.9 (as recommended in Hinton's Lecture 6c)
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.5, weight_decay=5e-4)
criterion = nn.CrossEntropyLoss()

for epoch in range(10):
    momentum = min(0.9, 0.5 + 0.1 * epoch)       # Raise smoothly from 0.5 to 0.9
    for group in optimizer.param_groups:
        group["momentum"] = momentum
    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. What value should the momentum coefficient be?
A.

In deep learning, μ=0.9\mu = 0.9 is commonly used. Polyak gives 0.8 to 0.99 as a guideline and recommends values closer to 1 for problems that converge slowly. Raising the coefficient increases the effective step size to 1/(1−μ)1/(1-\mu) times the learning rate, so revisit the learning rate when changing the coefficient.

Q. How does momentum differ from Adam?
A.

Momentum moves with a velocity built up from past gradients, and the step size is the same for all parameters. Adam uses a moving average of gradients (the part corresponding to momentum) and additionally divides by a moving average of squared gradients, changing the step size for each parameter.

Q. What is dampening in PyTorch?
A.

It is the fraction τ\tau by which a new gradient is weakened when added to the velocity. The velocity update becomes bt=μbt−1+(1−τ)gtb_t = \mu b_{t-1} + (1-\tau) g_t. The default is 0; keep it at 0 to follow the paper's equations. nesterov=True can only be used with dampening=0.

References

  1. B. T. Polyak, "Some methods of speeding up the convergence of iteration methods," USSR Computational Mathematics and Mathematical Physics, vol. 4, no. 5, pp. 1–17, 1964 (original: Ж. вычисл. матем. и матем. физ., 4(5), 791–803).
  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."