AI Logic

Optimizers

Nadam

Updatedïžš

How Nadam works. The left side shows one step: compute the first and second moments from the gradient, add the current gradient to form a direction m˄t that anticipates the next step's momentum, divide by the second moment, and update (the difference from Adam is shown in the yellow frame). The right side compares, on loss contours, Adam with the same learning rate and coefficients, which overshoots the minimum and swings widely around it, with Nadam, which curbs the overshoot and approaches the minimum

Background and Overview

Nadam (Nesterov-accelerated Adaptive Moment Estimation) is an optimizer that replaces the momentum in Adam with the "look-ahead" form of Nesterov's accelerated gradient. Dozat proposed it in 2016 (ICLR 2016 Workshop). The only difference from Adam is how the mean of the gradients (the first moment) is used; the part that adjusts the step size with the mean of the squared gradients is unchanged.

Adam combines the following two ideas.

  • Momentum: uses the mean of past gradients to keep the update direction consistent.
  • RMSprop: divides by the mean of squared gradients to change the step size for each parameter.

Momentum, on the other hand, has an improved version called Nesterov's accelerated gradient (NAG), which measures the gradient at the point reached by moving ahead by the momentum. Sutskever et al. (2013) showed that NAG oscillates less than momentum and gives better results. Dozat reasoned that "replacing the momentum inside Adam with NAG should then work even better."

However, NAG cannot be dropped into Adam as is. NAG measures the gradient at "the point moved ahead", but in Adam the denominator that sets the step size depends on the current gradient, so the amount to move ahead cannot be determined before the gradient. Nadam solved this by rewriting NAG not as "changing where the gradient is measured" but as "using the momentum of the next step in the current step ahead of time". It is like steering a car while anticipating not only the current speed but also how much it will accelerate in the next moment.

Theory (One Step of the Computation)

At each training step tt, Nadam performs the following computation (Algorithm 8 in the paper). All computations are element-wise over the parameters. The notation follows the Adam article (the paper's Ξ\mu, Î―\nu, ntn_t, and η\eta correspond to Îē1\beta_1, Îē2\beta_2, vtv_t, and Îą\alpha, respectively).

  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. Apply bias correction to the current gradient gtg_t and the first moment mtm_t to obtain g^t\hat{g}_t and m^t\hat{m}_t.
  4. Combine the two into the update direction mˉt\bar{m}_t. m^t\hat{m}_t is multiplied by the coefficient ξt+1\mu_{t+1} of the next step, and g^t\hat{g}_t by 1−ξt1-\mu_t, built from the current step's coefficient.
  5. As in Adam, divide by the second moment and update the parameters.

The equations for step 2 are the same as in Adam, starting from m0=v0=0m_0 = v_0 = 0.

mt=Îē1mt−1+(1−Îē1) gt,vt=Îē2vt−1+(1−Îē2) gt2m_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

The equations for steps 3 to 5 are as follows.

g^t=gt1−∏i=1tΞi,m^t=mt1−∏i=1t+1Ξi,v^t=vt1−Îē2t\hat{g}_t = \frac{g_t}{1-\prod_{i=1}^{t}\mu_i}, \qquad \hat{m}_t = \frac{m_t}{1-\prod_{i=1}^{t+1}\mu_i}, \qquad \hat{v}_t = \frac{v_t}{1-\beta_2^t} mˉt=(1−ξt) g^t+Ξt+1 m^t,Îļt=Îļt−1−α mˉtv^t+Ïĩ\bar{m}_t = (1-\mu_t)\,\hat{g}_t + \mu_{t+1}\,\hat{m}_t, \qquad \theta_t = \theta_{t-1} - \alpha\,\frac{\bar{m}_t}{\sqrt{\hat{v}_t} + \epsilon}

Ξt\mu_t is the momentum coefficient at step tt. The paper states that momentum works best when its coefficient is small at the start of training and gradually increased (warmed up), so it allows the coefficient to change at every step. The paper's experiments use Ξt=ξ (1−0.5×0.96t/250)\mu_t = \mu\,(1 - 0.5 \times 0.96^{t/250}) with Ξ=0.99\mu = 0.99. ∏i=1tΞi\prod_{i=1}^{t}\mu_i is the product of Ξ1\mu_1 through Ξt\mu_t; with a constant coefficient (Ξt=Îē1\mu_t = \beta_1) it becomes Îē1t\beta_1^t, the same as Adam's bias correction.

The difference is clearest when compared with Adam for a constant coefficient (Ξt=Îē1\mu_t = \beta_1). Ignoring bias correction, Adam's update direction is Îē1mt−1+(1−Îē1)gt\beta_1 m_{t-1} + (1-\beta_1) g_t, while Nadam's is Îē1mt+(1−Îē1)gt\beta_1 m_t + (1-\beta_1) g_t. Adam uses the momentum up to the previous step, mt−1m_{t-1}, whereas Nadam uses the momentum that already includes the current gradient, mtm_t; that is, it uses the momentum meant for the next step in the current step ahead of time. On the left of the figure at the top, only the part in the yellow frame differs from Adam.

How Nesterov's Look-Ahead Is Brought into Adam

In the paper, the Nadam equations are derived in the following order.

  • Rewrite NAG in a "use the momentum ahead of time" form: NAG in the form of Sutskever et al. moves the parameters ahead by the momentum and then measures the gradient. Dozat rewrote it as "measure the gradient gtg_t at the current position, compute mt=Ξtmt−1+gtm_t = \mu_t m_{t-1} + g_t, and move in the direction gt+Ξt+1mtg_t + \mu_{t+1} m_t" (Algorithm 7 in the paper). Because the momentum Ξt+1mt\mu_{t+1} m_t that would have been applied before measuring the gradient in the next step is included in the current update ahead of time, there is no need to measure the gradient at a different location.
  • Split Adam's update into a previous-momentum term and a current-gradient term: ignoring bias correction, Adam's update is the sum of "the Îē1mt−1\beta_1 m_{t-1} term" and "the (1−Îē1)gt(1-\beta_1) g_t term", divided by vt+Ïĩ\sqrt{v_t} + \epsilon (Eq. (3) in the paper). Since the denominator vtv_t depends on the current gradient gtg_t, the previous-momentum term alone cannot be used ahead of time as is.
  • Approximate the denominator vtv_t with vt−1v_{t-1}: Îē2\beta_2 is usually chosen larger than 0.9, so the difference between vt−1v_{t-1} and vtv_t is very small. The paper argues that replacing the denominator of the previous-momentum term with vt−1v_{t-1} barely affects accuracy (Eq. (4) in the paper), which makes the rewrite above usable. Finally, the bias corrections are chosen so that gtg_t is treated as a value of the current step and mtm_t as a value of the next step.

The paper explains why Nadam works better than Adam as follows. The RMSprop part makes the step size very large for parameters with a small denominator and makes it hard to change what has already been learned for parameters with a large denominator. That makes improving the quality of the update direction and reducing noise as much as possible especially important. Momentum (classical momentum) uses an older momentum built only from past gradients, while Nesterov momentum uses a newer momentum that includes the current gradient, so it can pass a better direction to the RMSprop part.

The right side of the figure at the top compares Adam and Nadam with the same learning rate and coefficients in a long, narrow valley that is steep vertically. Adam overshoots the minimum and swings widely around it, while Nadam overshoots less and settles near the minimum sooner.

Experimental Results

The paper compared nine methods on three tasks. All methods used Îē2=0.999\beta_2 = 0.999, Ïĩ=10−8\epsilon = 10^{-8}, bias correction, and the momentum coefficient Ξt=0.99 (1−0.5×0.96t/250)\mu_t = 0.99\,(1 - 0.5 \times 0.96^{t/250}); only the learning rate was tuned per method and task. The table below shows test values for six of those methods (Figures 1 to 3 in the paper; lower is better for all).

TaskMetricGradient descentMomentumNAGRMSpropAdamNadam
Word embeddings (word2vec)Analogy error0.3680.3610.3580.3160.3250.284
MNIST (CNN)Loss0.02020.02630.02830.01720.01750.0183
Penn Treebank (2-layer LSTM)Perplexity100.899.399.8106.7111.0105.5

The word2vec "analogy error" is computed from the cosine similarity between a vector built from a word analogy (e.g., "king − man + woman") and the embedding of the correct word (the mean of (1−cos⁡)/2(1-\cos)/2).

  • Nadam was best on word2vec: methods that include RMSprop did well overall, and among them Nadam outperformed RMSprop and Adam. Comparing by type of momentum, methods using Nesterov momentum always outperformed those using classical momentum.
  • On MNIST, Nadam was best on the validation data but lost to RMSprop on the test data: the paper suggests possible reasons such as the small model and easy task, the use of default settings, fluctuation from Dropout, and slight overfitting. It also notes that in another run, a larger Ïĩ\epsilon clearly improved Nadam's results.
  • On language modeling, all methods with RMSprop did poorly, but among them Nadam clearly outperformed Adam: the best method used momentum alone. The paper sums this up as showing that if RMSprop is used, adding Nesterov momentum is better.

The paper's conclusion is that "Nadam is not always the best, but when combining momentum with RMSprop, it is better to make the momentum Nesterov momentum." The values in this table are based on the public version of the report by the paper's author (Stanford CS229, 2015).

Practical Considerations

In PyTorch's torch.optim.NAdam, the momentum coefficient Ξt\mu_t starts at a value much smaller than betas[0] (Îē1\beta_1). PyTorch sets the coefficient as Ξt=Îē1 (1−0.5×0.96tψ)\mu_t = \beta_1\,(1 - 0.5 \times 0.96^{t\psi}), where ψ\psi is the argument momentum_decay (default 0.004, the same as the paper's 1/2501/250). With the default Îē1=0.9\beta_1 = 0.9, it starts at Ξ1≈0.45\mu_1 \approx 0.45 and approaches Îē1\beta_1 very slowly: about 0.52 at 1000 steps, about 0.70 at 5000 steps, and about 0.88 at 20000 steps. In short training runs, the momentum actually in effect is about half of Îē1\beta_1. To approach Îē1\beta_1 faster, increase momentum_decay. Note also that with momentum_decay=0, 0.960=10.96^0 = 1, so Ξt\mu_t stays constant at 0.5 Îē10.5\,\beta_1 and never approaches Îē1\beta_1.

  • The default learning rate differs from Adam's: the default lr of PyTorch's NAdam is 0.002, unlike Adam's 0.001. When switching from Adam and comparing, decide in advance whether to match the learning rates.
  • Decouple weight decay with decoupled_weight_decay=True: by default, weight_decay acts as L2 regularization that adds ÎŧÎļ\lambda\theta to the gradient, which is then divided by the second moment. To shrink the weights by a fixed fraction as in AdamW, set decoupled_weight_decay=True (known as NAdamW). The differences in weight decay are summarized in the Weight Decay article.
  • Results can depend on the size of Ïĩ\epsilon: in the paper's MNIST experiments, there was a run where a larger Ïĩ\epsilon improved the results. Like warmup, it is one of the values to try when training does not go well.
  • Adam's convergence issue remains: Nadam does not change how Adam handles the second moment. Reddi et al. (2018) gave examples where Adam fails to converge to the optimum even on simple convex problems and state that their analysis applies to Nadam as well. AMSGrad, which keeps the maximum of the second moment, addresses this problem.

Comparison with Other Optimizers

The table lines up Nadam and closely related methods from the same perspectives.

MethodHow momentum (first moment) is usedStep size adaptationExtra memoryCharacteristics
MomentumMomentum up to the previous stepNoneOne copy of the parametersStandard for image recognition CNNs
Nesterov's accelerated gradientMeasures the gradient at the point reached by the momentumNoneOne copy of the parametersOscillates less than momentum
AdamMomentum up to the previous step (an average updated with the current gradient)Divides by the second momentTwo copies of the parametersThe default for many models
NadamUses the next step's momentum ahead of timeDivides by the second momentTwo copies of the parametersAdam with Nesterov-style momentum
RAdamSame as AdamCorrects the variance early in trainingTwo copies of the parametersStabilizes training without warmup

Rough guidelines for choosing:

  • If using Adam and wanting the loss to go down a bit faster and more stably, Nadam is worth trying: computation and memory are almost the same as Adam. In PyTorch, just switch to torch.optim.NAdam.
  • Whether it makes a difference depends on the task: even in the paper's experiments, Nadam was best on only one of three tasks. Compare it against Adam with a tuned learning rate and other settings.
  • It can be combined with other improvements: Nesterov momentum only changes the first moment, so it can be added to other methods. For example, the LAMB paper also tried N-LAMB, which gives LAMB's first moment the same form as Nadam, and reported accuracy comparable to LAMB.

PyTorch example

Show code
python
import torch
import torch.nn as nn


# One step of Nadam, written exactly as Algorithm 8 of the paper
# Ξ_t = Îē1 (1 − 0.5 × 0.96^(t ψ)) is the same schedule as PyTorch's NAdam (ψ = momentum_decay)
def nadam_step(theta, grad, m, v, t, mu_prod, lr=2e-3, beta1=0.9, beta2=0.999,
               eps=1e-8, psi=4e-3):
    mu_t = beta1 * (1 - 0.5 * 0.96 ** (t * psi))           # Coefficient Ξ_t for the current step
    mu_next = beta1 * (1 - 0.5 * 0.96 ** ((t + 1) * psi))  # Coefficient Ξ_{t+1} for the next step
    mu_prod = mu_prod * mu_t                                 # Product of Ξ_1 through Ξ_t
    m = beta1 * m + (1 - beta1) * grad                       # First moment (same as Adam)
    v = beta2 * v + (1 - beta2) * grad ** 2                  # Second moment (same as Adam)
    g_hat = grad / (1 - mu_prod)                             # Bias correction of the current gradient
    m_hat = m / (1 - mu_prod * mu_next)                      # Bias correction of the next step's momentum
    m_bar = (1 - mu_t) * g_hat + mu_next * m_hat             # Update direction that uses the momentum ahead of time
    v_hat = v / (1 - beta2 ** t)
    theta = theta - lr * m_bar / (v_hat.sqrt() + eps)
    return theta, m, v, mu_prod


# Check that it matches PyTorch's NAdam
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)
mu_prod = 1.0
optimizer = torch.optim.NAdam([w], lr=2e-3, betas=(0.9, 0.999), eps=1e-8, momentum_decay=4e-3)

for t in range(1, 11):
    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, mu_prod = nadam_step(w_manual, grad, m, v, t, mu_prod)

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


# Use in actual training
# - The default lr is 0.002 (unlike Adam's 0.001)
# - The larger momentum_decay (default 0.004), the sooner Ξ_t approaches Îē1.
#   With the default, Ξ_t starts at about 0.45 and is only about 0.88 even after 20000 steps
# - To decouple weight decay as in AdamW, use decoupled_weight_decay=True (NAdamW)
model = nn.Sequential(nn.Flatten(), nn.Linear(28 * 28, 256), nn.ReLU(), nn.Linear(256, 10))
optimizer = torch.optim.NAdam(model.parameters(), lr=2e-3, betas=(0.9, 0.999),
                              momentum_decay=4e-3,
                              weight_decay=1e-2, decoupled_weight_decay=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()

FAQ

Q. How differently do Nadam and Adam behave?
A.

Only the use of the first moment differs. With a constant coefficient, Adam's update direction is Îē1mt−1+(1−Îē1)gt\beta_1 m_{t-1} + (1-\beta_1) g_t and Nadam's is Îē1mt+(1−Îē1)gt\beta_1 m_t + (1-\beta_1) g_t, so Nadam is somewhat more strongly influenced by the current gradient. Its advantage is noticing an overshoot sooner when the gradient direction changes abruptly. Computation and memory are almost the same.

Q. What does PyTorch's `momentum_decay` control?
A.

It is the ψ\psi in the momentum coefficient Ξt=Îē1(1−0.5×0.96tψ)\mu_t = \beta_1(1 - 0.5 \times 0.96^{t\psi}) and sets how quickly the coefficient moves from half of Îē1\beta_1 toward Îē1\beta_1. The default 0.004 is the same as the paper's 1/2501/250; with Îē1=0.9\beta_1 = 0.9, the coefficient is about 0.70 at 5000 steps. Larger values approach Îē1\beta_1 sooner.

Q. Is Nadam's momentum the same as Nesterov's accelerated gradient?
A.

The idea is the same, but the form differs. Nesterov's accelerated gradient measures the gradient at the point reached by the momentum, whereas Nadam measures the gradient at the current position and includes the momentum meant for the next step in the current update ahead of time. Because Adam's denominator depends on the current gradient, the paper approximates the denominator vtv_t with vt−1v_{t-1} to obtain this form.

References

  1. T. Dozat, "Incorporating Nesterov Momentum into Adam," ICLR Workshop, 2016.
  2. T. Dozat, "Incorporating Nesterov Momentum into Adam," Stanford CS229 Project Report, 2015.
  3. I. Sutskever, J. Martens, G. Dahl, and G. Hinton, "On the importance of initialization and momentum in deep learning," ICML, 2013.
  4. D. P. Kingma and J. Ba, "Adam: A Method for Stochastic Optimization," ICLR, 2015.
  5. S. J. Reddi, S. Kale, and S. Kumar, "On the Convergence of Adam and Beyond," ICLR, 2018.
  6. PyTorch Documentation, "torch.optim.NAdam."