AI Logic

Optimizers

RAdam

Updated:

How RAdam works. The left side shows one step: from the same first and second moments as Adam, compute the length ρt of the approximating simple moving average; if ρt is 4 or less, update without the adaptive learning rate, and if it is greater than 4, update with the variance rectification term rt multiplied in. The right side is a graph comparing how the rectification term rt with β2 = 0.999 grows from 0 to 1 over the steps against linear warmup

Background and Overview

RAdam (Rectified Adam) is an optimizer that fixes the problem that Adam's adaptive learning rate (per-parameter step size adjustment) varies too much early in training, by estimating that variation (variance) and correcting for it. Liu et al. published it in 2019 (ICLR 2020).

When using Adam or RMSprop, warmup, which keeps the learning rate small for only the first few thousand steps, is commonly used. The paper showed that when training a Transformer on German→English translation (IWSLT'14), simply removing warmup worsens the training loss from about 3 to about 10. However, why warmup works and how long it should be had been decided by trial and error.

The paper explained the cause as follows.

  • Early in training, there are few samples for estimating the mean of squared gradients: Adam sets the step size by dividing by the square root of the moving average of squared gradients vtv_t. At first, vtv_t is estimated from very few gradients, so the estimate fluctuates greatly.
  • As a result, the variance of the adaptive learning rate becomes very large: for example, at t=1t = 1 the step size is proportional to 1/∣g1∣1/|g_1| and becomes extremely large if the gradient happens to be close to 0. The paper showed that, assuming the gradients follow a zero-mean normal distribution, the variance at this point is infinite.
  • Warmup works by reducing this variance: a smaller learning rate also makes the variance of the step size smaller.

RAdam estimates this variance analytically and multiplies by a coefficient that corrects it so the variance always stays the same. In the very first steps, when the variance cannot be estimated, it does not use the adaptive learning rate at all. As a result, it automatically achieves an effect similar to warmup without the extra hyperparameter of warmup length. It is like not changing course drastically based on the opinions of just a few people: acting cautiously while few have been heard, and more boldly as their number grows.

Theory (One Step of the Computation)

At each training step tt, RAdam performs the following computation (Algorithm 2 in the paper). All computations are element-wise over the parameters. Ξ±t\alpha_t is the learning rate, and Ξ²1,Ξ²2\beta_1, \beta_2 are the same decay rates as in Adam.

  1. Compute the gradient gtg_t on a mini-batch.
  2. As in Adam, update the second moment vtv_t and the first moment mtm_t with exponential moving averages, and apply bias correction to mtm_t to obtain m^t\hat{m}_t.
  3. Compute the length ρt\rho_t of the simple moving average that approximates the exponential moving average (how many gradients it can be regarded as averaging).
  4. If ρt>4\rho_t > 4, compute the adaptive learning rate ltl_t and the variance rectification term rtr_t, and update with both multiplied in.
  5. If ρt≀4\rho_t \le 4, do not use the adaptive learning rate and update with m^t\hat{m}_t alone (the same form as SGD with momentum).

The equations for steps 2 and 3 are as follows, starting from m0=v0=0m_0 = v_0 = 0.

mt=Ξ²1mtβˆ’1+(1βˆ’Ξ²1)gt,vt=Ξ²2vtβˆ’1+(1βˆ’Ξ²2)gt2,m^t=mt1βˆ’Ξ²1tm_t = \beta_1 m_{t-1} + (1-\beta_1) g_t, \qquad v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2, \qquad \hat{m}_t = \frac{m_t}{1-\beta_1^t} ρ∞=21βˆ’Ξ²2βˆ’1,ρt=Οβˆžβˆ’2tΞ²2t1βˆ’Ξ²2t\rho_\infty = \frac{2}{1-\beta_2} - 1, \qquad \rho_t = \rho_\infty - \frac{2t\beta_2^t}{1-\beta_2^t}

The equations for step 4 are as follows.

lt=1βˆ’Ξ²2tvt,rt=(ρtβˆ’4)(ρtβˆ’2)ρ∞(Οβˆžβˆ’4)(Οβˆžβˆ’2)ρt,ΞΈt=ΞΈtβˆ’1βˆ’Ξ±t rt m^t ltl_t = \sqrt{\frac{1-\beta_2^t}{v_t}}, \qquad r_t = \sqrt{\frac{(\rho_t-4)(\rho_t-2)\rho_\infty}{(\rho_\infty-4)(\rho_\infty-2)\rho_t}}, \qquad \theta_t = \theta_{t-1} - \alpha_t\, r_t\, \hat{m}_t\, l_t

The equation for step 5 is ΞΈt=ΞΈtβˆ’1βˆ’Ξ±tm^t\theta_t = \theta_{t-1} - \alpha_t \hat{m}_t. ltl_t is the same as Adam's 1/v^t1/\sqrt{\hat{v}_t}, so with rt=1r_t = 1 the update is the same as Adam (excluding Ο΅\epsilon).

With Ξ²2=0.999\beta_2 = 0.999 (the default), ρ∞=1999\rho_\infty = 1999, and ρt\rho_t is almost equal to tt at first (ρ1=1\rho_1 = 1, ρ4β‰ˆ3.997\rho_4 \approx 3.997, ρ5β‰ˆ4.996\rho_5 \approx 4.996). Therefore, the first 4 steps do not use the adaptive learning rate, and from step 5 it switches to the rectified update. As shown on the right of the figure at the top, the rectification term rtr_t starts at about 0.017 at step 5 and slowly approaches 1: about 0.65 at 1000 steps, about 0.83 at 2000 steps, and about 0.98 at 5000 steps. The paper notes that this shape resembles linear warmup (a term of min⁑(t,Tw)/Tw\min(t, T_w)/T_w).

Deriving the Rectification Term

The rectification term rtr_t is a coefficient that "keeps the variance of the adaptive learning rate ψ=lt\psi = l_t the same at every point in training." The paper derived it in the following order.

  • Treat the inverse of the mean of squared gradients as following a scaled inverse chi-squared distribution: assuming the gradients gig_i follow a normal distribution with mean 0 and variance Οƒ2\sigma^2, ψ2\psi^2 built from the simple average of ρ\rho gradients follows a scaled inverse chi-squared distribution with ρ\rho degrees of freedom. The paper showed that the variance of ψ\psi decreases monotonically as ρ\rho grows (Theorem 1). In other words, the variance is larger early in training, when fewer gradients are used for the estimate.
  • Approximate the exponential moving average with a simple moving average that has the same "center of mass": Adam's vtv_t is an exponential moving average. The paper found the length ρt\rho_t of the simple moving average whose weights have the same center of mass (how far back the gradients are on average) and regarded it as the degrees of freedom. This is the equation for ρt\rho_t above, and its upper limit as tβ†’βˆžt \to \infty is ρ∞\rho_\infty.
  • Compute the variance with a first-order approximation and multiply by the square root of its ratio to the minimum variance: the variance is finite only when ρt>4\rho_t > 4, and the first-order approximation is Var[ψ]β‰ˆΟt/[2(ρtβˆ’2)(ρtβˆ’4)Οƒ2]\mathrm{Var}[\psi] \approx \rho_t / [2(\rho_t-2)(\rho_t-4)\sigma^2] (Eq. (5) in the paper). The minimum variance occurs at ρt=ρ∞\rho_t = \rho_\infty, so multiplying by rt=Var[ψ]ρ∞/Var[ψ]ρtr_t = \sqrt{\mathrm{Var}[\psi]_{\rho_\infty} / \mathrm{Var}[\psi]_{\rho_t}} makes the variance always equal to the minimum variance. Simplifying this gives the equation for rtr_t.

According to the paper, the variance at ρt=5\rho_t = 5 is more than 100 times that at ρt=500\rho_t = 500. For ρt≀4\rho_t \le 4 the variance diverges (is not finite), so the adaptive learning rate is not used. Also, with Ξ²2≀0.6\beta_2 \le 0.6, Οβˆžβ‰€4\rho_\infty \le 4, and RAdam is always the same as SGD with momentum.

Experimental Results

The paper tested RAdam on image classification, language modeling, and machine translation. In the experiments, every method applies weight decay decoupled from the gradient (the same way as AdamW).

Test accuracy (%) on image classification (a 20-layer ResNet for CIFAR-10, an 18-layer ResNet for ImageNet) (Table 1 in the paper).

DatasetSGD (momentum 0.9)AdamRAdam
CIFAR-1091.5190.5491.38
ImageNet69.8666.5467.62

BLEU scores for machine translation (Transformer) (Table 2 in the paper; IWSLT'14 shows the mean and standard deviation over 5 runs). Adam with warmup uses linear warmup over the first 4000 updates.

MethodIWSLT'14 De→EnIWSLT'14 En→DeWMT'16 En→De
Adam (with warmup)34.66 Β± 0.01428.56 Β± 0.06727.03
RAdam (no warmup)34.76 Β± 0.00328.48 Β± 0.05427.27
  • Accuracy improved more reliably than with Adam: RAdam outperformed Adam on both image classification tasks. However, its test accuracy did not reach that of SGD with momentum (on training data, RAdam was highest on ImageNet: SGD 69.57, Adam 69.12, RAdam 70.30).
  • Without warmup, it matched Adam with warmup: on the three translation tasks, the BLEU differences were small, with RAdam ahead on some tasks and behind on others.
  • It became robust to the choice of learning rate: on CIFAR-10, varying the learning rate over 0.1, 0.03, 0.01, and 0.003 changed the results of Adam and SGD substantially, while RAdam's test accuracy curves almost overlapped. At a learning rate of 0.1, Adam with 100 steps of warmup reached 90.13% accuracy, while RAdam reached 91.06%.

The paper's appendix also reports that on CIFAR-10 (learning rate 0.1, mean of 5 runs), replacing only the first 4 steps with Adam updates lowered test accuracy from 91.08% to 89.98%. This shows that the updates in the first few steps, when the variance diverges, leave a lasting negative effect on the whole training run.

Practical Considerations

PyTorch's torch.optim.RAdam uses a different switching threshold from the paper, applying the rectified update when ρt>5\rho_t > 5 (the paper uses ρt>4\rho_t > 4). With Ξ²2=0.999\beta_2 = 0.999, the first 4 steps in the paper and the first 5 steps in PyTorch are updates without the adaptive learning rate. The authors' official implementation (GitHub) also uses ρtβ‰₯5\rho_t \ge 5, with a comment saying "since the value is approximated, be more conservative." In addition, the current version of the official implementation does not update the parameters at all in the first few steps by default (degenerated_to_sgd=False). Keep these differences in mind when comparing results with the paper or the official implementation.

  • Updates in the first few steps are directly proportional to the gradient size: while the adaptive learning rate is not used, the update is ΞΈt=ΞΈtβˆ’1βˆ’Ξ±tm^t\theta_t = \theta_{t-1} - \alpha_t \hat{m}_t, which does not divide by the gradient size. Unlike Adam, the amount moved per step is not "roughly at most the learning rate," so depending on the loss scale, the parameters may move a lot in these few steps.
  • Decouple weight decay with decoupled_weight_decay=True: by default, PyTorch's weight_decay acts as L2 regularization that adds λθ\lambda\theta to the gradient. To apply weight decay decoupled from the gradient as in the paper's experiments, set decoupled_weight_decay=True (the same idea as AdamW, also called RAdamW).
  • A schedule to lower the learning rate is still needed: RAdam replaces only the warmup at the start of training. In the paper's experiments too, image classification lowered the learning rate in steps (CIFAR-10: to 1/10 at epochs 81 and 122), and translation lowered it linearly. Combine it with a learning rate scheduler as usual.
  • The analysis assumes gradients follow a zero-mean normal distribution: the paper also examined the nonzero-mean case by simulation and confirmed that the variance of the rectified learning rate stays nearly constant, but the rectification term is derived from an approximation.

Comparison with Other Optimizers

The table lines up RAdam and methods that handle early-training instability differently, from the same perspectives.

MethodHandling early-training instabilityExtra hyperparametersAmount moved per stepExtra memory
AdamNone (bias correction only)NoneRoughly at most the learning rateTwo copies of the parameters
Adam + warmupRaise the learning rate graduallyWarmup length TwT_wRoughly at most the learning rateTwo copies of the parameters
Adam (large Ο΅\epsilon)Add a large value to the denominator to suppress variationΟ΅\epsilonSuppressedTwo copies of the parameters
RAdamEstimate the variance and multiply by the rectification term rtr_tNone (determined automatically by Ξ²2\beta_2)Small at first, gradually approaching AdamTwo copies of the parameters
SGD (with momentum)Does not use an adaptive learning rate, so the problem does not ariseNoneProportional to the gradient sizeOne copy of the parameters

The paper also tried Adam with a large Ο΅\epsilon (10βˆ’410^{-4}) and reported that while it avoids the convergence problem, it introduces a large bias into the adaptive learning rate, so its performance was much worse than Adam with warmup or Adam that updates only the second moment for the first 2000 updates (Adam-2k).

Rough guidelines for choosing:

  • If tuning the warmup length for Adam is a struggle, use RAdam: even without warmup, performance comparable to Adam with warmup can be expected. In PyTorch, just replace Adam with torch.optim.RAdam.
  • If the warmup length is already settled, staying with Adam + warmup is fine: in the paper's translation experiments, the difference between the two was small, and which one was ahead varied by task.
  • To squeeze out final accuracy in image classification, also try SGD with momentum: in the paper's image classification experiments, SGD had the highest test accuracy.

PyTorch example

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


# One step of RAdam, written exactly as Algorithm 2 of the paper
# threshold: 4 in the paper, 5 in PyTorch. eps: not in the paper, but PyTorch adds it outside √v
def radam_step(theta, grad, m, v, t, lr=1e-3, beta1=0.9, beta2=0.999,
               threshold=4.0, eps=0.0):
    m = beta1 * m + (1 - beta1) * grad                 # First moment
    v = beta2 * v + (1 - beta2) * grad ** 2            # Second moment
    m_hat = m / (1 - beta1 ** t)                       # Bias correction
    rho_inf = 2 / (1 - beta2) - 1
    rho_t = rho_inf - 2 * t * beta2 ** t / (1 - beta2 ** t)   # Length of the approximated simple moving average
    if rho_t > threshold:
        l_t = math.sqrt(1 - beta2 ** t) / (v.sqrt() + eps)    # Adaptive learning rate
        r_t = math.sqrt((rho_t - 4) * (rho_t - 2) * rho_inf
                        / ((rho_inf - 4) * (rho_inf - 2) * rho_t))  # Variance rectification term
        theta = theta - lr * r_t * m_hat * l_t
    else:
        theta = theta - lr * m_hat                      # Do not use the adaptive learning rate
    return theta, m, v


# Check that it matches PyTorch's RAdam (threshold set to 5 to match PyTorch)
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.RAdam([w], lr=1e-3, betas=(0.9, 0.999), eps=1e-8)

for t in range(1, 21):
    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, m, v = radam_step(w_manual, grad, m, v, t, threshold=5.0, eps=1e-8)

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


# Use in actual training: no warmup, weight decay decoupled as in AdamW
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.RAdam(model.parameters(), lr=1e-3,
                              weight_decay=1e-4, decoupled_weight_decay=True)
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[81, 122], gamma=0.1)  # Lowering the learning rate is done separately
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()
scheduler.step()                                        # Call at the end of each epoch

FAQ

Q. Does RAdam make warmup unnecessary?
A.

In the paper's experiments, RAdam without warmup performed comparably to Adam with warmup, because the rectification term rtr_t automatically does something similar to warmup. However, a schedule that lowers the learning rate in the later part of training should still be combined separately.

Q. When do RAdam and Adam behave the same?
A.

As the rectification term rtr_t approaches 1, the update becomes almost the same as Adam's. With Ξ²2=0.999\beta_2 = 0.999, rtr_t is about 0.83 at 2000 steps and about 0.98 at 5000 steps. The difference appears mainly in the first few thousand steps of training.

Q. Why do PyTorch's results differ slightly from the paper and the official implementation?
A.

Because the switching threshold differs (the paper uses ρt>4\rho_t > 4, PyTorch ρt>5\rho_t > 5), as does whether ϡ\epsilon is added to the denominator. In addition, the authors' official implementation does not update the parameters in the first few steps by default. Only the first few steps are affected, but as the paper's appendix shows, those few steps can affect the final accuracy.

References

  1. L. Liu, H. Jiang, P. He, W. Chen, X. Liu, J. Gao, and J. Han, "On the Variance of the Adaptive Learning Rate and Beyond," ICLR, 2020.
  2. L. Liu, "RAdam" (official implementation by the author), GitHub.
  3. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.
  4. PyTorch Documentation, "torch.optim.RAdam."