AI Logic

Optimizers

AMSGrad

Updated:

How AMSGrad works. The left shows one step: the first and second moments are computed from the gradient, the running maximum of the second moment is kept and used as the divisor, and the parameters are updated (the difference from Adam is marked with a yellow frame). The right is a graph on a logarithmic step axis for the paper's synthetic problem, showing Adam's parameter heading to the worst point +1 while AMSGrad converges to the optimal point −1

Background and overview

AMSGrad is an optimizer that replaces the average of squared gradients vtv_t, which Adam uses to set its step size, with its running maximum, so that the step size never grows back. Reddi, Kale, and Kumar proposed it in 2018 in "On the Convergence of Adam and Beyond" (ICLR 2018). It differs from Adam by a single line.

Adam and RMSprop divide by an exponential moving average of squared gradients to set the step size per parameter. Because an exponential moving average quickly forgets the influence of old gradients, it avoids the drawback of AdaGrad, whose learning rate keeps shrinking. The paper, however, points out that this "quick forgetting" can in turn prevent convergence.

  • Information from rare large gradients fades quickly: consider a problem where most mini-batches give small gradients and, very rarely, a large gradient arrives. The large gradient is the one indicating the correct direction, yet with an exponential moving average its influence vanishes quickly, and the small gradients make the step size grow back.
  • As a result, it can fail to converge to the optimum even on simple convex problems: the paper proves, with the simplest possible example of a one-dimensional linear function, that Adam converges not to the optimum but to the worst point.
  • The convergence proof in the Adam paper contained an error: the proof implicitly assumed that the step size (the learning rate divided per parameter) does not increase over time, but this does not hold for Adam.

By keeping the maximum, AMSGrad guarantees that this assumption always holds. As an analogy, on a road where you once met a steep slope, you keep your stride cautious even while the flat stretch continues.

Theory (one step of computation)

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

  1. Compute the gradient gtg_t on a mini-batch.
  2. As in Adam, update the first moment mtm_t and the second moment vtv_t with exponential moving averages.
  3. Compute the running maximum v^t\hat{v}_t of the second moment.
  4. Update the parameters by dividing by v^t\hat{v}_t instead of vtv_t.

In equations, starting from m0=v0=v^0=0m_0 = v_0 = \hat{v}_0 = 0:

mt=β1t mt−1+(1−β1t) gt,vt=β2vt−1+(1−β2) gt2m_t = \beta_{1t}\, m_{t-1} + (1-\beta_{1t})\, g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2)\, g_t^2 v^t=max⁡(v^t−1, vt),θt+1=θt−αtmtv^t\hat{v}_t = \max(\hat{v}_{t-1},\, v_t), \qquad \theta_{t+1} = \theta_t - \alpha_t \frac{m_t}{\sqrt{\hat{v}_t}}

αt\alpha_t is the learning rate, and β1t\beta_{1t} and β2\beta_2 are decay rates. Algorithm 2 of the paper is written with a β1t\beta_{1t} that changes every step, but the paper notes that a constant β1\beta_1 is typically used in practice (the convergence proof requires β1t\beta_{1t} to decrease). The paper's equations also have no bias correction and no ϵ\epsilon. Because the paper deals with constrained problems (where the parameter range is fixed), it also projects back onto that range after each update; without constraints, as in ordinary deep learning, the projection does nothing.

Since v^t\hat{v}_t never decreases, the per-parameter step size αt/v^t\alpha_t / \sqrt{\hat{v}_t} never increases as long as the learning rate αt\alpha_t is constant or decreasing. The paper writes this property as Γt+1=v^t+1/αt+1−v^t/αt≥0\Gamma_{t+1} = \sqrt{\hat{v}_{t+1}}/\alpha_{t+1} - \sqrt{\hat{v}_t}/\alpha_t \ge 0 (the inverse step size does not decrease). SGD and AdaGrad satisfy it, but Adam and RMSprop do not.

Why Adam fails to converge, and why the maximum fixes it

The paper shows why Adam fails to converge with the following example (Section 3 of the paper).

  • Problem setup: the parameter xx ranges over [−1,1][-1, 1]; once every three steps the loss is ft(x)=Cxf_t(x) = Cx (gradient +C+C, C>2C > 2), and the other two steps it is ft(x)=−xf_t(x) = -x (gradient −1-1). The total loss is minimized at x=−1x = -1.
  • How Adam behaves: the large gradient +C+C arrives only once every three steps, and in the two steps between, the small opposite gradient −1-1 moves xx in the wrong direction. With β1=0\beta_1 = 0 and β2=1/(1+C2)\beta_2 = 1/(1+C^2), the large gradient is divided by roughly its own magnitude, down to about 1/C1/C, and cannot cancel the two opposite steps. Adam therefore converges to the worst point in the range, x=+1x = +1 (Theorem 1).

This example is not limited to a special setting. The paper also shows the following.

  • A non-convergent example can be built for any constants satisfying β1<β2\beta_1 < \sqrt{\beta_2} (Theorem 2). This condition holds even for the commonly used values (β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999).
  • Non-convergent examples also exist in the stochastic setting (mini-batch gradients) (Theorem 3).
  • Non-convergent examples exist for any value of the ϵ\epsilon added to the denominator (Theorem 6 in the appendix).

The paper states that this problem is common to all methods that use exponential moving averages, and that the same analysis applies to AdaDelta and Nadam.

In AMSGrad, v^t\hat{v}_t remembers having seen a large gradient once, so the step size does not grow back even when small gradients continue. The paper explains this by comparison with Adam and AdaGrad. Suppose at some point vt−1>gt2>0v_{t-1} > g_t^2 > 0 (the current gradient is smaller than the average). Then:

  • Adam: vtv_t decreases, so the step size widens considerably. This is what prevents convergence.
  • AdaGrad: the sum of squares increases slightly, so the step size shrinks slightly. In long training runs the step size often shrinks too much.
  • AMSGrad: the maximum does not change, so the step size neither widens nor shrinks.

The paper proves that with a learning rate of αt=α/t\alpha_t = \alpha/\sqrt{t} and a decreasing β1t\beta_{1t}, the regret of AMSGrad (the difference between the total loss up to that point and the total loss of the best fixed parameter) is bounded by O(T)O(\sqrt{T}) (Theorem 4, Corollary 1). Since the average regret divided by TT approaches 0, it catches up on average with the performance of the optimal point. The paper also shows that when gradients are sparse, this can be considerably better than SGD's O(dT)O(\sqrt{dT}) (dd is the number of parameters).

Experimental results

The paper compared Adam and AMSGrad on a synthetic problem and on logistic regression and neural networks. The results are shown as graphs; there are no numerical tables.

Synthetic problem (Figure 1 of the paper). The right side of the figure at the top of this article recomputes this problem from its equations.

  • Setup: xx ranges over [−1,1][-1, 1]; once every 101 steps the gradient is +1010+1010, and otherwise it is −10-10. The optimum is x=−1x = -1. Both use β1=0.9\beta_1 = 0.9 and β2=0.99\beta_2 = 0.99 (values commonly used in practice).
  • Results: for Adam, the average regret did not approach 0, and xx converged to the worst point x=+1x = +1. For AMSGrad, the average regret approached 0, and it converged to the optimum x=−1x = -1. In a stochastic setting where the gradient +1010+1010 arrives with probability 0.01, Adam also converged to x=+1x = +1.

Real data (Figure 2 of the paper). All use mini-batches of 128 examples with β1=0.9\beta_1 = 0.9, and β2\beta_2 chosen from 0.99 and 0.999 by grid search together with the learning rate.

TaskModelLearning ratePaper's report
MNISTLogistic regression (convex)α/t\alpha/\sqrt{t}AMSGrad beat Adam on both training and test loss. Also robust to parameter changes
MNISTFully connected network with one hidden layer (100 ReLUs)ConstantAMSGrad beat Adam
CIFAR-10CNN with 2 convolutional and 2 fully connected layers (CIFARNET)ConstantAMSGrad was considerably better in training loss and accuracy, and also better in test loss

The paper positions these experiments as "preliminary" and states that the main purpose of the proposal is to expose Adam's problem from a theoretical standpoint.

Practical caveats

PyTorch's torch.optim.Adam(amsgrad=True) is not exactly Algorithm 2 of the paper. PyTorch keeps the maximum of the non-bias-corrected vtv_t, vtmax⁡=max⁡(vt−1max⁡,vt)v_t^{\max} = \max(v_{t-1}^{\max}, v_t), divides it by 1−β2t1-\beta_2^t, takes the square root, and adds ϵ\epsilon. It also bias-corrects the first moment as Adam does. The paper's equations have neither bias correction nor ϵ\epsilon. Moreover, 1−β2t1-\beta_2^t approaches 1 as training progresses, so even when the maximum does not change, the value after division slowly decreases. As a result, in PyTorch the step size can gradually increase early in training, and the paper's property that "the step size never increases" does not strictly hold. Keep this difference in mind when comparing closely with the paper's results.

  • A single large gradient keeps that parameter's step size small for good: since v^t\hat{v}_t never decreases, if an outlier-like large gradient arrives once during training, that parameter is updated with a small step size from then on. This property is what guarantees convergence, but it can also slow training. In training where the loss spikes suddenly, consider it together with countermeasures against exploding gradients.
  • It needs extra memory: PyTorch keeps one more buffer of the same size as the parameters (max_exp_avg_sq) to hold the maximum. Where Adam uses memory equal to two copies of the parameters, it uses three.
  • The convergence guarantee is for convex problems: the paper's theorems assume a convex loss, a learning rate decreasing as α/t\alpha/\sqrt{t}, and a decreasing β1t\beta_{1t}. They are not guarantees for use with a constant learning rate on non-convex problems such as deep learning.
  • Use weight decay through AdamW: torch.optim.AdamW also has an amsgrad argument. To apply weight decay decoupled from the gradient, add amsgrad=True to AdamW.

Comparison with other optimizers

The table lists AMSGrad and methods that handle the second moment differently, from the same viewpoints.

MethodValue that sets the step sizeCan the step size grow?Convergence guarantee (convex problems)Extra memory
AdaGradSum of squared gradientsNo (keeps shrinking)YesOne copy of the parameters
RMSpropExponential moving average of squared gradientsYesNon-convergent examples existOne copy of the parameters
AdamExponential moving average of squared gradientsYesNon-convergent examples existTwo copies of the parameters
AMSGradRunning maximum of the exponential moving averageNoYesThree copies of the parameters (PyTorch)
AdamNC (same paper)Moves β2\beta_2 toward 1 over timeNo, under conditionsYes, under conditionsTwo copies of the parameters

AdamNC is another fix presented in the same paper: it keeps Adam's structure but changes β1\beta_1 and β2\beta_2 every step. For example, with β2t=1−1/t\beta_{2t} = 1 - 1/t, vtv_t becomes a simple average of squared gradients, making it like AdaGrad with momentum. The Adafactor paper builds on this idea of increasing β2\beta_2 over time and uses schedules such as β^2t=1−t−0.8\hat{\beta}_{2t} = 1 - t^{-0.8}.

A rough guide for choosing:

  • Try it when Adam training becomes unstable partway through or the loss does not fully decrease: in PyTorch, just add amsgrad=True and compare with all other settings unchanged.
  • For everyday use, Adam or AdamW is fine: the paper's experiments are preliminary, and results depend on the task. Check on your actual task whether the benefit justifies the extra memory and the property that step sizes never grow back.
  • If instability early in training is the problem, use RAdam or warmup: AMSGrad addresses the convergence problem caused by fading information from rare large gradients, which is a different problem from the large variance early in training.

PyTorch example

Show code
python
import math
import torch
import torch.nn as nn


# 1. The paper's synthetic problem (Section 5): gradient +1010 once every 101 steps, otherwise −10. x ranges over [−1, 1]; the optimum is −1
#    Run Adam and AMSGrad in the form of Algorithms 1 and 2 of the paper (no bias correction)
def run(amsgrad, steps=200000, alpha=0.5, beta1=0.9, beta2=0.99):
    x, m, v, v_max = 0.0, 0.0, 0.0, 0.0
    for t in range(1, steps + 1):
        g = 1010.0 if t % 101 == 1 else -10.0
        m = beta1 * m + (1 - beta1) * g
        v = beta2 * v + (1 - beta2) * g * g
        v_max = max(v_max, v)                    # AMSGrad: keep the running maximum
        denom = math.sqrt(v_max if amsgrad else v)
        x = x - alpha / math.sqrt(t) * m / denom
        x = min(1.0, max(-1.0, x))               # bring back into [−1, 1] (projection)
    return x

print("Adam:", round(run(False), 3), "AMSGrad:", round(run(True), 3))  # Adam ends near +1, AMSGrad near −1


# 2. The same computation as PyTorch's Adam(amsgrad=True)
#    Unlike the paper, both m and the maximum are bias-corrected, and ε is added
def amsgrad_step_torch(theta, grad, m, v, v_max, t, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8):
    m = beta1 * m + (1 - beta1) * grad
    v = beta2 * v + (1 - beta2) * grad ** 2
    v_max = torch.maximum(v_max, v)              # maximum of v before bias correction
    m_hat = m / (1 - beta1 ** t)
    v_hat = v_max / (1 - beta2 ** t)
    theta = theta - lr * m_hat / (v_hat.sqrt() + eps)
    return theta, m, v, v_max


torch.manual_seed(0)
w = torch.randn(5, requires_grad=True)
w_manual = w.detach().clone()
m, v, v_max = (torch.zeros_like(w_manual) for _ in range(3))
optimizer = torch.optim.Adam([w], lr=1e-3, betas=(0.9, 0.999), eps=1e-8, amsgrad=True)

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, v_max = amsgrad_step_torch(w_manual, grad, m, v, v_max, t)

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


# 3. Use in actual training: just add amsgrad=True (AdamW has the same argument)
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2, amsgrad=True)
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()
print(optimizer.state[model[1].weight].keys())   # holds max_exp_avg_sq in addition to exp_avg and exp_avg_sq

FAQ

Q. What does the name AMSGrad stand for?
A.

The paper does not explain the abbreviation. The paper's title is "On the Convergence of Adam and Beyond", and the method is presented as "AMSGRAD" in Algorithm 2.

Q. If $\beta_2$ in Adam is made larger, is AMSGrad unnecessary?
A.

A larger β2\beta_2 remembers old gradients longer, so the problem becomes less likely. However, the paper shows that a non-convergent example for Adam can be built for any constants satisfying β1<β2\beta_1 < \sqrt{\beta_2} (Theorem 2). No β2\beta_2 can be called safe, so AMSGrad keeps the maximum to guarantee that the step size never grows back.

Q. Can AMSGrad make training slower?
A.

Yes. Since v^t\hat{v}_t never decreases, once a large gradient arrives during training, that parameter's step size stays small from then on. The paper describes AMSGrad as a method that uses a smaller learning rate than Adam. If speed is a concern, compare with a slightly larger learning rate.

References

  1. S. J. Reddi, S. Kale, and S. Kumar, "On the Convergence of Adam and Beyond," ICLR, 2018.
  2. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.
  3. N. Shazeer and M. Stern, "Adafactor: Adaptive Learning Rates with Sublinear Memory Cost," ICML, 2018.
  4. PyTorch Documentation, "torch.optim.Adam."