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 t, 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 Ξ, Î―, ntâ, and η correspond to Îē1â, Îē2â, vtâ, and Îą, respectively).
Compute the gradient gtâ on a mini-batch.
As in Adam, update the first moment mtâ and the second moment vtâ with exponential moving averages.
Apply bias correction to the current gradient gtâ and the first moment mtâ to obtain g^âtâ and m^tâ.
Combine the two into the update direction mËtâ. m^tâ is multiplied by the coefficient Ξt+1â of the next step, and g^âtâ by 1âΞtâ, built from the current step's coefficient.
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â=0.
Ξtâ is the momentum coefficient at step t. 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) with Ξ=0.99. âi=1tâΞiâ is the product of Ξ1â through Ξtâ; with a constant coefficient (Ξtâ=Îē1â) it becomes Îē1tâ, the same as Adam's bias correction.
The difference is clearest when compared with Adam for a constant coefficient (Ξtâ=Îē1â). Ignoring bias correction, Adam's update direction is Îē1âmtâ1â+(1âÎē1â)gtâ, while Nadam's is Îē1âmtâ+(1âÎē1â)gtâ. Adam uses the momentum up to the previous step, mtâ1â, whereas Nadam uses the momentum that already includes the current gradient, mtâ; 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 gtâ at the current position, compute mtâ=Ξtâmtâ1â+gtâ, and move in the direction gtâ+Ξt+1âmtâ" (Algorithm 7 in the paper). Because the momentum Ξt+1âmtâ 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 Îē1âmtâ1â term" and "the (1âÎē1â)gtâ term", divided by vtââ+Ïĩ (Eq. (3) in the paper). Since the denominator vtâ depends on the current gradient gtâ, the previous-momentum term alone cannot be used ahead of time as is.
Approximate the denominator vtâ with vtâ1â: Îē2â is usually chosen larger than 0.9, so the difference between vtâ1â and vtâ is very small. The paper argues that replacing the denominator of the previous-momentum term with vtâ1â barely affects accuracy (Eq. (4) in the paper), which makes the rewrite above usable. Finally, the bias corrections are chosen so that gtâ is treated as a value of the current step and mtâ 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, Ïĩ=10â8, bias correction, and the momentum coefficient Ξtâ=0.99(1â0.5Ã0.96t/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).
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).
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 Ïĩ 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â starts at a value much smaller than betas[0] (Îē1â). PyTorch sets the coefficient as Ξtâ=Îē1â(1â0.5Ã0.96tÏ), where Ï is the argument momentum_decay (default 0.004, the same as the paper's 1/250). With the default Îē1â=0.9, it starts at Ξ1ââ0.45 and approaches Îē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â. To approach Îē1â faster, increase momentum_decay. Note also that with momentum_decay=0, 0.960=1, so Ξtâ stays constant at 0.5Îē1â and never approaches Îē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 ÎŧÎļ 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 Ïĩ: in the paper's MNIST experiments, there was a run where a larger Ïĩ 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.
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 Îē1âmtâ1â+(1âÎē1â)gtâ and Nadam's is Îē1âmtâ+(1âÎē1â)gtâ, 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 Ï in the momentum coefficient Ξtâ=Îē1â(1â0.5Ã0.96tÏ) and sets how quickly the coefficient moves from half of Îē1â toward Îē1â. The default 0.004 is the same as the paper's 1/250; with Îē1â=0.9, the coefficient is about 0.70 at 5000 steps. Larger values approach Îē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 vtâ with vtâ1â to obtain this form.