AI Logic

Optimizers

AdaBelief

Updated:

How AdaBelief works. Left: the flow of one update step, computing the average of the gradient (the prediction) and the average of the squared deviation from the prediction. Right: a graph comparing the per-step update size of Adam and AdaBelief over an interval with a constant gradient and an interval where the sign alternates

Background and Overview

AdaBelief is an optimizer that replaces the quantity used in the denominator of Adam, the average of the squared gradient gt2g_t^2, with the average of the squared difference between the gradient and its moving average, (gt−mt)2(g_t - m_t)^2. Zhuang et al. presented it at NeurIPS in 2020. The change from Adam is a single line, and no hyperparameters are added.

The paper splits deep learning optimizers into two families and points out the weakness of each.

  • Adaptive methods such as Adam: They converge quickly, but on CNNs and similar models their generalization tends to be worse than that of SGD.
  • SGD with momentum: It generalizes well, but is hard to use for unstable training such as GANs, where Adam is the default.

AdaBelief aims to achieve three things at once: "the speed of adaptive methods", "generalization close to SGD", and "stability that does not break down even on GANs".

The name Belief comes from the idea behind the update. The moving average of the gradient mtm_t is regarded as "a prediction of the next gradient": if the observed gradient gtg_t is close to the prediction, the optimizer trusts it and takes a large step; if it deviates far from the prediction, the optimizer distrusts it and takes a small step. In weather-forecast terms, it acts boldly on a forecast that is always right and cautiously on a forecast that is hit or miss.

Theory (Computation in One Step)

Following Algorithm 2 of the paper, the following computation is performed at each step tt. The computation is element-wise over the parameters and starts from m0=0m_0 = 0, s0=0s_0 = 0.

  1. Compute the gradient gtg_t on a mini-batch.
  2. Update the moving average of the gradient mtm_t (the gradient prediction). This is the same as Adam.
  3. Update the moving average sts_t of the squared difference between the gradient and the prediction. This is the only difference from Adam.
  4. Apply bias correction to mtm_t and sts_t.
  5. Move the parameters by m^t\hat{m}_t divided by s^t\sqrt{\hat{s}_t}.

In formulas:

mt=β1mt−1+(1−β1) gt,st=β2st−1+(1−β2) (gt−mt)2+ϵm_t = \beta_1 m_{t-1} + (1-\beta_1)\, g_t, \qquad s_t = \beta_2 s_{t-1} + (1-\beta_2)\,(g_t - m_t)^2 + \epsilon m^t=mt1−β1t,s^t=st1−β2t,θt=θt−1−α m^ts^t+ϵ\hat{m}_t = \frac{m_t}{1-\beta_1^t}, \qquad \hat{s}_t = \frac{s_t}{1-\beta_2^t}, \qquad \theta_t = \theta_{t-1} - \alpha\, \frac{\hat{m}_t}{\sqrt{\hat{s}_t} + \epsilon}

The paper's default values are the same as Adam's: α=10−3\alpha = 10^{-3}, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, ϵ=10−8\epsilon = 10^{-8}.

Unlike Adam, ϵ\epsilon is also added at the end of the sts_t formula. The paper explains that this keeps sts_t always at least ϵ\epsilon, matching an assumption of the convergence analysis (sts_t has a positive lower bound). If the gradient never changes, (gt−mt)2(g_t - m_t)^2 is nearly 0, so without this lower bound the denominator would get too close to 0.

sts_t measures how much the gradient fluctuates around its mean; in other words, it is an estimate of the gradient variance. Adam's vtv_t is the average of the squared gradient, which corresponds to "squared mean + variance". The more aligned the gradient direction and the smaller the variance, the larger the difference between the denominators of Adam and AdaBelief.

Why It Works (Step Size Set by Gradient Change)

The paper divides the loss landscape into three cases and compares how an ideal optimizer should behave (Figure 1 and Table 1 in the paper).

CaseGradient magnitude (vtv_t)Gradient change (sts_t)Ideal stepSGDAdamAdaBelief
1. Flat regionSmallSmallLargeSmallLargeLarge
2. Oscillating in a steep, narrow valleyLargeLargeSmallLargeSmallSmall
3. Large gradient but small curvatureLargeSmallLargeLargeSmallLarge

The difference appears in case 3. The gradient is large but barely changes from step to step (small curvature), so a large step is appropriate. Adam's denominator grows simply because the gradient is large, shrinking the step. AdaBelief looks at the change in the gradient, so it keeps the step large. Since the change in the gradient is related to the Hessian (second derivative), the paper explains that AdaBelief uses curvature information.

The right side of the figure at the top computes this difference for a single parameter. For the first 100 steps the gradient is always 1; after that it alternates between +1+1 and −1-1.

  • While the gradient is aligned: Adam has vt≈1v_t \approx 1, so the step stays at 1× the learning rate. AdaBelief's sts_t keeps shrinking, so its step grows to about 5× by step 100.
  • When the sign alternates: mtm_t approaches 0, so both steps shrink to about 0.05-0.07×.

The paper also explains with a 2D example f(x,y)=∣x∣+∣y∣f(x, y) = |x| + |y|. When the gradient in the xx direction is always +1+1 and in the yy direction alternates between ±1\pm 1, Adam has v≈1v \approx 1 in both directions and takes the same step size. AdaBelief has sx≈0s_x \approx 0 and sy≈1s_y \approx 1, so it moves far in the xx direction it should follow and little in the oscillating yy direction.

The paper points out that when the gradient variance is small, Adam's update mt/vtm_t / \sqrt{v_t} becomes approximately sign(E[gt])\mathrm{sign}(\mathbb{E}[g_t]), approaching "sign-only descent" that discards the gradient magnitude (Eq. (5)). In 2D it moves at 45° to the axes, deviating from the true gradient direction. AdaBelief moves in the same direction as the gradient if the variance is the same in every coordinate. The paper suggests that this sign-only update may be one reason for the generalization gap between Adam and SGD.

Experimental Results

The paper compares AdaBelief with SGD, Adam, AdamW, RAdam, and others on image classification, language modeling, and GANs. For image classification and language modeling, AdaBelief uses Adam's default values as is, while the other methods have their learning rate and β1\beta_1 tuned.

Top-1 accuracy (%) of ResNet-18 on ImageNet (Table 2 in the paper). AdaBelief is trained with ϵ=10−8\epsilon = 10^{-8} and decoupled weight decay (as in AdamW); the other methods use the best values reported in prior papers.

AdaBeliefSGDAdaBoundYogiAdamMSVAGRAdamAdamW
70.0870.2368.1368.2363.79 (66.54 in another report)65.9967.6267.93

It is the highest among adaptive methods, 0.15 points behind SGD (70.23%).

FID of SN-GAN (ResNet generator) (Table 3 in the paper, CIFAR-10, lower is better)

AdaBeliefRAdamAdamRMSPropYogiFromageMSVAGSGDAdaBound
12.52 ± 0.1612.70 ± 0.1213.05 ± 0.1913.13 ± 0.1214.25 ± 0.1542.75 ± 0.1548.35 ± 5.4449.70 ± 0.4155.65 ± 2.15

While some methods such as SGD and AdaBound failed to train well, AdaBelief achieved the lowest FID.

Other results are as follows.

  • CIFAR-10/100 (VGG-11, ResNet-34, DenseNet-121): It converged as fast as Adam and reached higher test accuracy than SGD and others (Figure 4; mean and standard deviation over 3 runs).
  • LSTM language model on Penn Treebank: It achieved the lowest perplexity with 2 and 3 layers, and was on par with the other methods with 1 layer.
  • WGAN and WGAN-GP (small CNN generator): Over 5 runs, it achieved lower FID than the other methods.
  • Experiments added after publication: On IWSLT'14 translation with a Transformer, it reached BLEU 35.85 (Adam 35.60, RAdam 35.51, AdaHessian 35.90); with Faster R-CNN on PASCAL VOC, it reached mAP 81.02 (Adam 71.47, RAdam 76.58, SGD 79.50).

Practical Considerations

AdaBelief's ϵ\epsilon acts differently from Adam's ϵ\epsilon. Because ϵ\epsilon is also added inside sts_t, the lower bound of the denominator is about ϵ\sqrt{\epsilon}. The documentation of the official implementation (GitHub) states that setting AdaBelief's ϵ\epsilon to the square of Adam's ϵ\epsilon gives roughly the same effect, and the default after version 0.1.0 is 10−1610^{-16}. The paper trains image classification with 10−810^{-8}, and GANs with 10−1210^{-12} (small GANs) and 10−1610^{-16} (SN-GAN). Copying Adam's settings as is can result in a larger ϵ\epsilon than intended.

  • Not built into PyTorch: Use the authors' official implementation (the adabelief-pytorch package), or change one line of Adam as in the implementation example below. The defaults of the official implementation (such as the weight decay handling weight_decouple and the RAdam rectification rectify) have changed between versions, so check the defaults of the version you use.
  • Guidance from the official implementation: Its documentation recommends ϵ=10−8\epsilon = 10^{-8} for tasks where SGD beats Adam (such as image classification) and ϵ=10−16\epsilon = 10^{-16} for tasks where Adam beats SGD (such as GANs and Transformers).
  • Apply weight decay separately: The paper's ImageNet experiments decouple weight decay from the gradient, as in AdamW. Used as L2 regularization added to the gradient, weights shrink unevenly from one weight to another, just as with Adam.
  • Be careful with comparisons: In the ImageNet table, the values other than AdaBelief are quoted from prior papers, not retrained under the same conditions.

Comparison with Other Optimizers

The Adam-family methods side by side:

MethodQuantity in the denominatorWhen the step becomes largeExtra hyperparametersExtra memory
AdamAverage of squared gradient vtv_tWhen the gradient is smallNone2× parameters
AMSGradRunning maximum of vtv_tWhen the gradient is small (but the denominator never decreases)None3× parameters
RAdamvtv_t (correction weakened early on according to variance)When the gradient is smallNone2× parameters
AdaBeliefAverage of squared deviation from prediction sts_tWhen the gradient direction is alignedNone2× parameters

Rough guidelines for choosing:

  • To try a drop-in replacement for Adam, use AdaBelief: It takes only a one-line change, and in the paper it matched or beat Adam on image classification, language modeling, and GANs. Re-tune ϵ\epsilon, though.
  • To squeeze out final accuracy on image classification, also compare SGD with momentum: Even on ImageNet in the paper, SGD was slightly ahead.
  • For large models that rely heavily on weight decay, use AdamW: AdaBelief can adopt the same idea by applying weight decay separately.

PyTorch example

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


class AdaBelief(torch.optim.Optimizer):
    # AdaBelief following Algorithm 2 of the paper (projection omitted; weight decay applied separately as in AdamW)
    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-16, weight_decay=0.0):
        super().__init__(params, dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay))

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            beta1, beta2 = group["betas"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                g = p.grad
                state = self.state[p]
                if not state:
                    state["t"] = 0
                    state["m"] = torch.zeros_like(p)   # m_0 = 0
                    state["s"] = torch.zeros_like(p)   # s_0 = 0
                state["t"] += 1
                t, m, s = state["t"], state["m"], state["s"]
                if group["weight_decay"] != 0:
                    p.mul_(1 - group["lr"] * group["weight_decay"])
                m.mul_(beta1).add_(g, alpha=1 - beta1)                       # gradient prediction m_t
                s.mul_(beta2).addcmul_(g - m, g - m, value=1 - beta2).add_(group["eps"])  # difference from Adam
                m_hat = m / (1 - beta1 ** t)
                s_hat = s / (1 - beta2 ** t)
                p.addcdiv_(m_hat, s_hat.sqrt().add_(group["eps"]), value=-group["lr"])


# Usage (image classification example; the paper uses eps=1e-8 for image classification and values such as 1e-16 for Transformers and GANs)
model = nn.Sequential(nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(),
                      nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(16, 10))
optimizer = AdaBelief(model.parameters(), lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=5e-4)

model.train()
x = torch.randn(8, 3, 32, 32)
y = torch.randint(0, 10, (8,))
loss = nn.functional.cross_entropy(model(x), y)
optimizer.zero_grad()
loss.backward()
optimizer.step()

FAQ

Q. What is the difference between AdaBelief and Adam?
A.

Only the quantity in the denominator differs. Adam divides by the average of the squared gradient vtv_t, while AdaBelief divides by the average of the squared difference between the gradient and its moving average, sts_t (an estimate of the gradient variance). The more consistent the gradient direction, the smaller AdaBelief's denominator and the larger its step.

Q. What value should eps be set to?
A.

The paper uses 10−810^{-8} for image classification and 10−1210^{-12} or 10−1610^{-16} for GANs. The official implementation states that using the square of Adam's ϵ\epsilon gives roughly the same effect and sets the default to 10−1610^{-16}. When switching from Adam, revisit ϵ\epsilon.

Q. Can it be used in PyTorch?
A.

It is not included in torch.optim. Use the authors' official implementation adabelief-pytorch, or an implementation that changes Adam's second-moment line to (gt−mt)2(g_t - m_t)^2. The official implementation's defaults differ between versions, so check the documentation of the version you use.

References

  1. J. Zhuang, T. Tang, Y. Ding, S. Tatikonda, N. Dvornek, X. Papademetris, and J. S. Duncan, "AdaBelief Optimizer: Adapting Stepsizes by the Belief in Observed Gradients," NeurIPS, 2020.
  2. J. Zhuang, "AdaBelief-Optimizer" (official implementation), GitHub.
  3. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.