AI Logic

Optimizers

Adan

Updated:

How Adan works. Left: the flow of one step, computing the gradient average, the gradient-difference average, and the average of the squared difference-corrected gradient, then updating with weight decay applied by division in proximal form. Right: a graph comparing the top-1 accuracy of Adan and LAMB for ViT-S on ImageNet as the batch size varies from 1K to 32K

Background and Overview

Adan is an optimizer that brings the idea of Nesterov's accelerated gradient into Adam-style adaptive methods without extra gradient computation. The name stands for ADAptive Nesterov momentum. Xie, Zhou, and colleagues presented it in 2022.

The paper takes issue with the fact that in deep learning, the best-suited optimizer differs by task and network, so one has to try several and choose.

  • CNNs such as ResNet: SGD often generalizes better than Adam
  • Transformers such as ViT: SGD does not work well, and AdamW is the standard
  • Large batches: Specialized methods such as LAMB are used

Adan aims to be a method that trains quickly on any network. Nesterov's acceleration converges quickly by "computing the gradient at a point slightly ahead", but done as is, it requires extra computation and storage for that point ahead. Adan rewrites it to use the difference between the current gradient and the previous gradient, eliminating the extra gradient computation.

The paper reports that Adan outperformed each architecture's standard optimizer on ResNet, ConvNeXt, ViT, Swin Transformer, MAE, GPT-2, BERT, and others.

Rewriting Nesterov Acceleration with Gradient Differences

Ordinary Nesterov acceleration (AGD) can be written as follows in the paper's notation. Its defining feature is that the gradient is computed not at the current point ΞΈk\theta_k but at a point a little ahead in the momentum direction.

gk=βˆ‡f(ΞΈkβˆ’Ξ·(1βˆ’Ξ²1)mkβˆ’1)+ΞΎk,mk=(1βˆ’Ξ²1)mkβˆ’1+gk,ΞΈk+1=ΞΈkβˆ’Ξ·β€‰mkg_k = \nabla f\big(\theta_k - \eta(1-\beta_1) m_{k-1}\big) + \xi_k, \qquad m_k = (1-\beta_1) m_{k-1} + g_k, \qquad \theta_{k+1} = \theta_k - \eta\, m_k

Lemma 1 of the paper shows that if the stored point is replaced with the point ahead, the same procedure can be rewritten in the following form (AGD-II).

gkβ€²=gk+(1βˆ’Ξ²1)(gkβˆ’gkβˆ’1),mk=(1βˆ’Ξ²1)mkβˆ’1+gkβ€²,ΞΈk+1=ΞΈkβˆ’Ξ·β€‰mkg'_k = g_k + (1-\beta_1)(g_k - g_{k-1}), \qquad m_k = (1-\beta_1) m_{k-1} + g'_k, \qquad \theta_{k+1} = \theta_k - \eta\, m_k

Here gkg_k is the ordinary gradient at the current point. The gradient at the point ahead is replaced by the current gradient plus "the change since the previous step". Upon convergence, the difference between the point ahead and the current point vanishes, so in expectation it converges to the same point as the original procedure.

The gradient difference gkβˆ’gkβˆ’1g_k - g_{k-1} indicates which way the gradient is changing. Picture estimating the slope a little further along a hill by adding "how the slope is changing" to the current slope. Instead of actually going to the point ahead and measuring the gradient there, it extrapolates from the last two gradients.

Theory (Computation in One Step)

Adan averages the rewritten gradient gkβ€²g'_k with first and second moments, as in Adam. In addition, it splits the first moment into a "gradient term" and a "gradient difference term" and averages them with separate coefficients (Eq. (4)). Weight decay is decoupled from the gradient as in AdamW and applied in proximal-gradient form (Eq. (5)).

Following Algorithm 1 of the paper, the following computation is performed at each step kk, element-wise.

  1. Compute the gradient gkg_k at the current point.
  2. Update the gradient average mkm_k.
  3. Update the gradient-difference average vkv_k.
  4. Update the average of the squared difference-corrected gradient nkn_k, and compute the per-parameter step size Ξ·k\eta_k.
  5. Move in the direction mk+(1βˆ’Ξ²2)vkm_k + (1-\beta_2) v_k with step size Ξ·k\eta_k, then apply weight decay by dividing by 1+λη1 + \lambda\eta.
mk=(1βˆ’Ξ²1)mkβˆ’1+Ξ²1gk,vk=(1βˆ’Ξ²2)vkβˆ’1+Ξ²2(gkβˆ’gkβˆ’1)m_k = (1-\beta_1) m_{k-1} + \beta_1 g_k, \qquad v_k = (1-\beta_2) v_{k-1} + \beta_2 (g_k - g_{k-1}) nk=(1βˆ’Ξ²3)nkβˆ’1+Ξ²3[gk+(1βˆ’Ξ²2)(gkβˆ’gkβˆ’1)]2,Ξ·k=Ξ·nk+Ο΅n_k = (1-\beta_3) n_{k-1} + \beta_3 \big[g_k + (1-\beta_2)(g_k - g_{k-1})\big]^2, \qquad \eta_k = \frac{\eta}{\sqrt{n_k} + \epsilon} ΞΈk+1=ΞΈkβˆ’Ξ·k∘(mk+(1βˆ’Ξ²2)vk)1+λη\theta_{k+1} = \frac{\theta_k - \eta_k \circ \big(m_k + (1-\beta_2) v_k\big)}{1 + \lambda \eta}

The initial values are m0=g0m_0 = g_0, v0=0v_0 = 0, and n0=g02n_0 = g_0^2, with no Adam-style bias correction. The paper's defaults are Ξ²1=0.02\beta_1 = 0.02, Ξ²2=0.08\beta_2 = 0.08, Ξ²3=0.01\beta_3 = 0.01, and weight decay 0.02.

The paper's Ξ²\beta is defined in the opposite direction from Adam's Ξ²\beta. The paper's Ξ²1=0.02\beta_1 = 0.02 corresponds to 0.980.98 in Adam's notation. The documentation of the official implementation (GitHub) also warns that "the paper's Ξ²\beta is 1βˆ’Ξ²1-\beta in the code", and the code's default is betas=(0.98, 0.92, 0.99).

Only the second moment nkn_k averages the gradient and gradient difference together rather than separately. The paper explains that the correlation between adjacent gradients may be statistically meaningful. The paper also shows that for stochastic nonconvex problems, Adan finds an Ο΅\epsilon-approximate stationary point with O(Ο΅βˆ’3.5)O(\epsilon^{-3.5}) stochastic gradient evaluations, matching the known lower bound.

Experimental Results

The paper compares Adan with each task's standard optimizer on vision, language, and reinforcement learning tasks.

ViT and Swin on ImageNet (top-1 accuracy %) (Table 5 in the paper; AdamW's 300-epoch values are those reported in the original papers)

ModelAdamW 150 epochsAdan 150 epochsAdamW 300 epochsAdan 300 epochs
ViT-S78.379.679.980.9
ViT-B79.581.781.882.6
Swin-T79.981.381.281.6
Swin-S82.182.983.283.7
Swin-B82.683.383.583.8

Adan at 150 epochs reaches accuracy comparable to or higher than AdamW at 300 epochs.

Large batches (ViT-S, ImageNet, top-1 accuracy %) (Table 7 in the paper; right side of the figure at the top)

Batch size1K2K4K8K16K32K
LAMB78.979.279.879.779.578.4
Adan80.981.181.180.880.580.2

The paper states that AdamW cannot train ViT when the batch size exceeds 4,096. Adan's accuracy drops only slightly from 2K to 32K, and it beat LAMB at every batch size.

Other results are as follows.

  • Self-supervised learning with MAE (ViT-B): With 300 epochs of pretraining, it was 0.5 points higher than AdamW (83.4% vs. 82.9%), and Adan at 800 epochs (83.8%) beat AdamW at 1,600 epochs (83.6%).
  • Detection on COCO: Deformable DETR reached box AP 45.3 (AdamW 43.8/44.5), and Mask R-CNN (ConvNeXt-T) reached mask AP 42.2 (AdamW 41.7).
  • LSTM on Penn Treebank (test perplexity): 83.6, 65.2, and 59.8 with 1, 2, and 3 layers, lower than all 8 methods compared (such as AdaBelief at 84.2, 66.3, and 61.2).

Practical Considerations

  • Not included in PyTorch's torch.optim: Use the authors' official implementation (the adan-pytorch package, sail-sg/Adan on GitHub), or write Algorithm 1 yourself as in the implementation example below.
  • The learning rate is larger than for Adam and AdamW: According to the official implementation's documentation, Adan's learning rate was 5-10Γ— that of Adam and AdamW in many experiments (MAE pretraining and LSTM are exceptions). The paper also states that because it looks ahead and corrects like Nesterov acceleration, it can use about 3Γ— the learning rate of LAMB.
  • Uses more memory than Adam: Algorithm 1 keeps the previous gradient gkβˆ’1g_{k-1} in addition to three moments mkm_k, vkv_k, and nkn_k. According to the official implementation's documentation, on a single GPU it uses slightly more than Adam and AdamW, and about the same when the state is sharded with ZeroRedundancyOptimizer.
  • Check how weight decay is applied: The paper's default is the proximal form of dividing by 1+λη1 + \lambda\eta. The official implementation also has an option (no_prox) to apply it the same way as AdamW.
  • Restart is not used by default: Algorithm 1 includes a restart condition that resets momentum, but the paper does not use it in most experiments to keep the method simple.

Comparison with Other Optimizers

Adam-style methods and their acceleration mechanisms, side by side:

MethodQuantity used for the first momentAcceleration mechanismWeight decayState kept
AdamGradientHeavy ball (ordinary momentum)Added to gradient2Γ— parameters
AdamWGradientHeavy ballDecoupled from gradient2Γ— parameters
NadamGradient (combines the updated first moment with the gradient)NesterovAdded to gradient2Γ— parameters
LAMBGradientHeavy ball (layer-wise normalization of magnitude)Decoupled from gradient2Γ— parameters
AdanGradient and gradient difference (averaged with separate coefficients)Nesterov (look-ahead via gradient difference)Proximal form4Γ— parameters (including previous gradient)

The paper explains that Nadam also uses the Nesterov idea, but its first moment is an average of past gradients and becomes almost identical to Adam as training progresses, which distinguishes it from Adan (Eq. (3)).

Rough guidelines for choosing:

  • To shorten training time for ViT or large batches, use Adan: In the paper, there were many cases where it matched AdamW's accuracy in half the epochs.
  • If memory is tight, use AdamW: Adan's state grows by the previous gradient and the gradient-difference average.
  • If layer-wise adjustment matters for large batches, also compare with LAMB: Adan came out ahead in Table 7 of the paper, but it is worth checking per task.

PyTorch example

Show code
python
import torch
import torch.nn as nn


class Adan(torch.optim.Optimizer):
    # Algorithm 1 of the paper (without restart). betas use the paper's notation (Ξ²1, Ξ²2, Ξ²3) = (0.02, 0.08, 0.01)
    # Note: the official implementation's code takes them as "1 βˆ’ Ξ²", i.e., betas=(0.98, 0.92, 0.99)
    def __init__(self, params, lr=1e-3, betas=(0.02, 0.08, 0.01), eps=1e-8, weight_decay=0.02):
        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:
            b1, b2, b3 = group["betas"]
            lr, eps, wd = group["lr"], group["eps"], group["weight_decay"]
            for p in group["params"]:
                if p.grad is None:
                    continue
                g = p.grad.detach().clone()
                state = self.state[p]
                if not state:                                   # m_0 = g_0, v_0 = 0, n_0 = g_0^2
                    state["m"], state["v"] = g.clone(), torch.zeros_like(g)
                    state["n"], state["prev"] = g * g, g.clone()
                m, v, n, prev = state["m"], state["v"], state["n"], state["prev"]
                diff = g - prev                                 # gradient difference g_k βˆ’ g_{kβˆ’1}
                m.mul_(1 - b1).add_(g, alpha=b1)
                v.mul_(1 - b2).add_(diff, alpha=b2)
                n.mul_(1 - b3).add_((g + (1 - b2) * diff) ** 2, alpha=b3)
                step_size = lr / (n.sqrt() + eps)               # Ξ·_k
                p.sub_(step_size * (m + (1 - b2) * v)).div_(1 + wd * lr)  # weight decay in proximal form
                prev.copy_(g)


model = nn.Sequential(nn.Linear(32, 64), nn.GELU(), nn.Linear(64, 10))
optimizer = Adan(model.parameters(), lr=5e-3, weight_decay=0.02)  # larger learning rate than AdamW

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

FAQ

Q. Isn't Adan's Ξ²1 = 0.02 too small?
A.

The paper's Ξ²\beta is defined in the opposite direction from Adam's: mk=(1βˆ’Ξ²1)mkβˆ’1+Ξ²1gkm_k = (1-\beta_1) m_{k-1} + \beta_1 g_k. The paper's Ξ²1=0.02\beta_1 = 0.02 corresponds to 0.98 in Adam's notation, averaging gradients over a longer window than Adam's default (0.9). In the official implementation's code, pass betas=(0.98, 0.92, 0.99).

Q. How does it differ from Nadam?
A.

Both incorporate Nesterov acceleration, but the first moment of Nadam is an average of the past gradients themselves. Adan also averages the difference between the current and previous gradients to estimate the gradient at the point ahead. The paper states that Nadam becomes almost identical to Adam as training progresses.

Q. How should the learning rate be chosen?
A.

According to the official implementation's documentation, many experiments use 5-10Γ— the learning rate of Adam and AdamW (MAE pretraining and LSTM are exceptions). Start from a few times the value used with AdamW and adjust while watching the learning curve.

References

  1. X. Xie, P. Zhou, H. Li, Z. Lin, and S. Yan, "Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models," arXiv:2208.06677, 2022.
  2. Sea AI Lab, "Adan" (official implementation of the paper), GitHub.