Adam vs AdamW: Understanding Optimizers in Deep Learning

Training cost comparison of using different optimizers
Title: Training cost comparison of using different optimizers
Source: Adam – A Method for Stochastic Optimization by Kingma et. al.

What is Adam (Adaptive Moment Estimation)?

Adam was introduced by Diederik P. Kingma and Jimmy Ba in the paper “Adam: A Method for Stochastic Optimization” (2015), and has become the default optimizer in many applications due to its efficiency and ease of use. It combines the benefits of Momentum and RMSProp, maintaining both a moving average of gradients (first moment) and squared gradients (second moment) to adaptively adjust the learning rate for each parameter.

How Adam Works

Adam maintains two running averages:

  • $m_t$: Exponentially decaying average of past gradients (like momentum)
  • $v_t$: Exponentially decaying average of squared gradients (like RMSProp) To correct initialization bias, Adam computes bias-corrected estimates of these terms:

Update Rules:

  1. Gradient update:
$$g_t = \nabla J(\theta_t)$$
  1. Biased first moment estimate update: 
$$m_t = \beta_1 \cdot m_{t-1} + (1 – \beta_1) \cdot g_t$$ 
  1. Biased second moment estimate Update : 
$$ v_t = \beta_2 \cdot v_{t-1} + (1 – \beta_2) \cdot g_t^2 $$
  1. Compute bias-corrected estimates: 
$$ \hat{m}_t = \frac{m_t}{1 – \beta_1^t}, \quad \hat{v}t = \frac{v_t}{1 – \beta_2^t}$$ 
  1. Update parameters: 
$$ \theta_t = \theta{t-1} – \eta \cdot \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} $$ 

Where:

  • $\beta_1$: Decay rate for first moment (default 0.9)
  • $\beta_2$: Decay rate for second moment (default 0.999)
  • $\epsilon$: Small constant to prevent division by zero (default 1e-8)
  • $\eta$: Learning rate

This process is also illustrated in the original algorithm provided in the paper.

Why Does Adam Need Bias Correction?

Adam uses exponentially moving averages to track the first moment ($m_t$) and second moment ($v_t$) of the gradients: $m_t = \beta_1 m_{t-1} + (1 – \beta_1) g_t,\quad v_t = \beta_2 v_{t-1} + (1 – \beta_2) g_t^2$ However, at the start of training ($m_0 = v_0 = 0$), these estimates are biased toward zero, especially when $\beta_1$ and $\beta_2$ are close to 1 (e.g., 0.9 or 0.999).

To correct this initialization bias, Adam applies bias correction: $\hat{m}_t = \frac{m_t}{1 – \beta_1^t},\quad \hat{v}_t = \frac{v_t}{1 – \beta_2^t}$ This rescales the estimates during early steps to better approximate the true moments. As training progresses, the correction factors converge to 1 and no longer affect the updates.

Example:

If $g_1 = 1$ and $\beta_1 = 0.9$, then:

$m_1 = 0.1$, but $\hat{m}_1 = \frac{0.1}{1 – 0.9} = 1$ — fully restoring the unbiased value.

Code Example 

This PyTorch code defines a simple two-layer feedforward neural network for a classification task and trains it using the Adam with a learning rate of 0.001. The model is trained on a batch of 64 randomly generated input samples and labels using cross-entropy loss. The optimizer.step() call updates the model parameters based on the computed gradients.

Python
import torch
import torch.nn as nn
import torch.optim as optim

# Simple network
model = nn.Sequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Linear(256, 10)
)

# Loss function
criterion = nn.CrossEntropyLoss()

# Adam optimizer
optimizer = optim.Adam(model.parameters(), lr=0.001)

# Training step
x = torch.randn(64, 784)
y = torch.randint(0, 10, (64,))

optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()

Advantages of Adam

  • No need to manually tune the learning rate schedule → Adam adaptively adjusts learning rates for each parameter based on gradient history.
  • Fast convergence, suitable for large datasets and deep networks → Combines the benefits of momentum and adaptive learning, accelerating training.
  • Works well out of the box in most scenarios → It often requires minimal hyperparameter tuning to achieve strong performance.
  • Combines benefits of Momentum (stability) and RMSProp (adaptivity) → Maintains directionality with past gradients while scaling updates per parameter.

Disadvantages of Adam

  • Can lead to overfitting if regularization is not applied → Its aggressive updates may cause the model to fit noise in the training data.
  • SGD with momentum can outperform Adam in generalization → Especially in tasks like image classification where simpler optimizers generalize better.

What is AdamW?

AdamW is a modified version of the Adam optimizer that decouples weight decay from the gradient update, leading to better generalization and more stable convergence especially in large models like Transformers and BERT.

Problem with Weight Decay in Adam

In standard Adam, L2 regularization (weight decay) is added directly to the gradient during parameter updates:

$$\nabla_\theta = \nabla_\theta \text{loss} + \lambda \theta$$ 

This causes two issues:

  • The regularization term gets entangled with Adam’s adaptive mechanisms (momentum and variance scaling).
  • The effect of weight decay changes over time. For instance, when the learning rate decays, the effective regularization also weakens. This behavior undermines the consistency of regularization, especially in long training runs or when fine-tuning large pre-trained models.

AdamW: Decoupled Weight Decay

To fix this, AdamW updates parameters using two separate steps:

$$ \theta_t = \theta_{t-1} – \eta \cdot \frac{\hat{m}_t}{\sqrt{\hat{v}t} + \epsilon} – \eta \cdot \lambda \theta{t-1}$$
  • The first term handles standard Adam updates (using adaptive moment estimates).
  • The second term applies weight decay directly to the parameters, without involving it in the momentum or variance estimates.

Additionally, the paper also illustrates the distinctions between the Adam and AdamW algorithms:

Adam and AdamW algorithm comparison
Title: Adam and AdamW algorithm comparison
Source: Decoupled Weight Decay Regularization by Loshchilov et. al.

Why AdamW works better:

  • Stable Regularization: Weight decay applies consistently throughout training, unaffected by changes in learning rate or momentum.
  • True to L2: More faithfully implements L2 regularization penalizing large weights directly.
  • Better Convergence: Helps maintain sufficient regularization even in later stages of training.
  • Ideal for Transformers: Proven especially effective in fine-tuning large-scale models like BERT, GPT, and ViT, where long training and learning rate decay are common.

Code Example (AdamW):

The usage is nearly identical to Adam, just a single line needs to modify:

Python
optimizer = optim.AdamW(model.parameters(), lr=0.001, weight_decay=0.01)

When to Use Adam vs AdamW?

We outline different scenarios to help guide the choice of optimizer based on the specific task at hand.

  • First, in general, Adam serves as a solid default choice for most deep learning tasks because it combines fast convergence with ease of use.
  • Next, when training Transformers or large language models (LLMs), AdamW is usually the better option, since it handles weight decay more effectively, leading to greater stability and improved generalization.
  • In addition, if you use explicit L2 regularization, AdamW is also a strong choice, as it decouples weight decay from the gradient update.
  • Finally, for scenarios where high generalization performance is especially important, you might consider AdamW or even SGD, both of which often achieve stronger final test accuracy, particularly in vision tasks.

Video Explanation

  • The video by Andrew Ng offers an excellent introduction and clear explanation of the Adam optimization algorithm (Runtime: 7 mins):
YouTube video
Introduction of Adam by Andrew Ng
  • The video by DataMListic explores the key differences between Adam and AdamW and provides practical guidance on when to use each optimizer (Runtime: 3 mins):
YouTube video
Differences between Adam and AdamW explained by DataMListic

Related Articles:

Author

  • Brown University CS

    Machine Learning Content Writer

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute