AI Logic

Optimizers

Adam

Updated:

How Adam works. The left shows the training loop that repeats the forward pass, gradient computation, and the Adam update; the right shows one step of computation: the first and second moments are computed from the gradient, bias-corrected, and used to update the parameters

Background and overview

Adam (Adaptive Moment Estimation) is an optimizer that sets the update size for each parameter using the mean of the gradient (first moment) and the mean of the squared gradient (second moment). Kingma and Ba proposed it in 2015 (ICLR 2015).

The most basic optimizer, SGD, updates all parameters with the same learning rate. In real networks, however, parameters whose gradients are always large are mixed with parameters that rarely receive gradients. If everything moves with the same learning rate, tuning it for the former leaves the latter barely moving, and tuning it for the latter makes the former unstable.

Adam eases this problem by combining two ideas.

  • Momentum: uses the average of past gradients to stabilize the update direction. Like a ball rolling down a slope that keeps its momentum, it cancels out small oscillations.
  • RMSProp and AdaGrad: divide by the average of squared gradients, so parameters with large gradients move less and those with small gradients move more.

The paper aims to combine the strengths of AdaGrad, which works well on problems where gradients arrive rarely (sparse gradients), and RMSProp, which works well on problems where the objective changes during training. Because training progresses on many tasks even with the defaults, it is used as a standard for training many kinds of models, starting with the Transformer.

Theory (one step of computation)

At each training step tt, Adam performs the following computation (Algorithm 1 of the paper). All operations are applied elementwise to the parameters.

  1. Compute the loss on a mini-batch and obtain the gradient gtg_t by backpropagation.
  2. Update the first moment (the mean of the gradient) with an exponential moving average. mt=β1mt−1+(1−β1) gtm_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t
  3. Update the second moment (the mean of the squared gradient) in the same way. vt=β2vt−1+(1−β2) gt2v_t = \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2
  4. Correct the bias in the early steps (bias correction). m^t=mt1−β1t,v^t=vt1−β2t\hat{m}_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat{v}_t = \frac{v_t}{1-\beta_2^t}
  5. Update the parameters. θt=θt−1−αm^tv^t+ϵ\theta_t = \theta_{t-1} - \alpha \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Here, θ\theta is the parameters, α\alpha is the learning rate (step size), β1,β2\beta_1, \beta_2 are decay rates that determine how much of the past values to keep, and ϵ\epsilon is a small value that prevents division by zero. β1t\beta_1^t is β1\beta_1 to the power tt. m0m_0 and v0v_0 start at 0. The defaults given in the paper are α=0.001\alpha = 0.001, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, and ϵ=10−8\epsilon = 10^{-8}, the same as the defaults of PyTorch's torch.optim.Adam.

Bias correction is needed because starting from m0=v0=0m_0 = v_0 = 0 pulls the early averages toward 0. For example, at t=1t = 1, m1=0.1 g1m_1 = 0.1\,g_1, only 1/10 of its proper value, but dividing by 1−β11=0.11-\beta_1^1 = 0.1 restores m^1=g1\hat{m}_1 = g_1. Without correction, v1\sqrt{v_1} becomes even smaller at 0.001 ∣g1∣≈0.032 ∣g1∣\sqrt{0.001}\,|g_1| \approx 0.032\,|g_1|, so the first step swells to about 3.2 times its intended size. The paper shows that without correction, when β2\beta_2 is close to 1, steps become too large and training tends to diverge.

Why update sizes are uniform

The size of a single Adam update is Δt=α⋅m^t/v^t\Delta_t = \alpha \cdot \hat{m}_t / \sqrt{\hat{v}_t} (ignoring ϵ\epsilon). This expression has the following properties.

  • The update stays roughly within α\alpha: when gradient directions are consistent, m^t/v^t\hat{m}_t / \sqrt{\hat{v}_t} is close to ±1, and the update is about α\alpha. The paper describes this as establishing "a trust region around the current parameters". Because the learning rate directly sets how far parameters can move in one step, it is easier to estimate a reasonable α\alpha.
  • It is unaffected by the scale of the gradient: if the gradient is multiplied by cc, m^t\hat{m}_t is multiplied by cc, v^t\sqrt{\hat{v}_t} is also multiplied by cc, and the factors cancel. Even tasks whose losses differ in scale by a factor of 1000 can start from the same learning rate.
  • The step size shrinks naturally near the optimum: near the optimum, the sign of the gradient fluctuates and the mean m^t\hat{m}_t approaches 0. Meanwhile v^t\hat{v}_t rarely becomes 0, so the update becomes small. The paper calls this "automatic annealing" (gradual cooling).

Comparison with other optimizers

The table lists Adam and the optimizers it is often compared with, from the same viewpoints.

MethodUses average of gradients (momentum)Varies step size per parameterMain uses and characteristics
SGDNoNoThe simplest. Requires learning rate tuning
MomentumYesNoStandard for CNNs in image recognition
AdaGradNoYes (divides by the sum of past squares)Strong on sparse gradients, but the learning rate keeps decreasing monotonically
RMSPropNoYes (divides by an exponential moving average of squares)Fixes AdaGrad's ever-shrinking step size
AdamYesYesMomentum plus RMSProp, with bias correction added
AdamWYesYesApplies Adam's weight decay decoupled from the gradient. Standard for large models

A rough guide for choosing:

  • When in doubt, start with Adam (AdamW if using weight decay): training often progresses with the defaults, reducing the effort spent tuning the learning rate.
  • To squeeze out final accuracy in image classification, also try SGD with momentum: adaptive methods have been reported to sometimes generalize worse (lower accuracy on unseen data) than SGD (Wilson et al., 2017).

Practical caveats

L2 regularization with Adam does not work well as weight decay. The weight_decay of torch.optim.Adam acts as L2 regularization that adds λθ\lambda\theta to the gradient. This term is also divided by v^t\sqrt{\hat{v}_t}, so weights with larger gradients are decayed less. To shrink weights by a constant fraction, use AdamW (Loshchilov and Hutter, 2019), which decouples decay from the gradient.

Also keep the following in mind.

  • There are cases where it does not converge: Reddi et al. (2018) showed examples where Adam fails to converge to the optimum even on simple convex problems. AMSGrad, which keeps the maximum of the second moment, was proposed to fix this.
  • It uses a lot of memory: since it keeps mtm_t and vtv_t for every parameter, it needs additional memory equal to two copies of the parameters. For large models, methods such as Adafactor, which store the second moment in compressed form, are used.
  • Combine it with a learning rate schedule: for large models, it is common to combine it with warmup, which gradually raises the learning rate at the start of training, and with cosine annealing.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of Adam, written exactly as in Algorithm 1 of the paper
def adam_step(theta, grad, m, v, t, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8):
    m = beta1 * m + (1 - beta1) * grad        # first moment (mean of the gradient)
    v = beta2 * v + (1 - beta2) * grad ** 2   # second moment (mean of the squared gradient)
    m_hat = m / (1 - beta1 ** t)              # bias correction
    v_hat = v / (1 - beta2 ** t)
    theta = theta - lr * m_hat / (v_hat.sqrt() + eps)
    return theta, m, v


# Check that it gives the same result as PyTorch's Adam
torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
m = torch.zeros_like(w_manual)
v = torch.zeros_like(w_manual)
optimizer = torch.optim.Adam([w], lr=1e-3, betas=(0.9, 0.999), eps=1e-8)

for t in range(1, 11):
    loss = ((w - 3.0) ** 2).sum()             # example: move toward 3
    optimizer.zero_grad()
    loss.backward()
    grad = w.grad.detach().clone()
    optimizer.step()
    w_manual, m, v = adam_step(w_manual, grad, m, v, t)

print(torch.allclose(w.detach(), w_manual, atol=1e-6))  # should be True


# Use in actual training (a fully connected network for MNIST-sized images)
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
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. How should the learning rate be chosen?
A.

Start with the paper's default of 0.001, and if the loss does not decrease, compare values such as 3 times and 1/3 of it. Large Transformers often use a value smaller than 0.001 combined with warmup. Since each update stays roughly within the learning rate, you can estimate it from how far you want parameters to move in one step.

Q. How do Adam and AdamW differ?
A.

They apply weight decay differently. Adam's weight_decay is added to the gradient, so it is divided by the second moment and its effect varies from parameter to parameter. AdamW shrinks the weights by a constant fraction separately from the gradient-based update. If weight decay is used, AdamW is the usual choice.

Q. Does ε (epsilon) need to be changed?
A.

Usually the default of 10^−8 is fine. ε is there to prevent division by zero. It is sometimes set larger when numerics become unstable, such as when computing in half precision (16-bit).

References

  1. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.
  2. I. Loshchilov and F. Hutter, "Decoupled Weight Decay Regularization," ICLR, 2019.
  3. S. J. Reddi, S. Kale, and S. Kumar, "On the Convergence of Adam and Beyond," ICLR, 2018.
  4. A. C. Wilson, R. Roelofs, M. Stern, N. Srebro, and B. Recht, "The Marginal Value of Adaptive Gradient Methods in Machine Learning," NeurIPS, 2017.
  5. PyTorch Documentation, "torch.optim.Adam."