Optimizers
Momentum, Adam, and AdamW: practical modifications that make gradient descent faster and more reliable.
The previous article introduced gradient descent: at each step, compute the gradient of the loss with respect to every weight, and subtract a scaled version of it. This works, but two practical problems arise in real networks. First, a single learning rate applies to every weight, even though different parameters may require very different step sizes. Second, on loss surfaces with elongated valleys, gradient descent oscillates across the narrow dimension while making slow progress along the long one. Optimizers are modifications to the basic update rule that address these problems.
SGD (Stochastic Gradient Descent) with Momentum
Plain gradient descent updates the weight directly from the current gradient:
where at step . The update depends entirely on the current gradient, with no memory of past steps.
Momentum introduces a velocity variable that accumulates an exponential moving average of past gradients:
with and a momentum coefficient typically set to .
The intuition is physical: behaves like a velocity. Each step blends the current gradient with the previous velocity. When gradients consistently point in the same direction, the velocity grows and steps accelerate. When gradients alternate signs, they partially cancel and the velocity stays small.
Example. Consider a parameter whose gradient is consistently over three steps ():
Now compare with oscillating gradients :
In the consistent case, the velocity grows to . In the oscillating case, it stays near zero. Consistent directions build up speed; oscillations cancel out.
On an elongated loss landscape, SGD oscillates back and forth across the narrow axis while creeping along the long one. Momentum damps the oscillations and follows the valley floor toward the minimum.
Adaptive Learning Rates
Momentum addresses oscillation but not the second problem: parameters in a network see very different gradient magnitudes. Weights connected to frequently activated neurons accumulate large gradient updates; weights connected to rarely activated neurons receive small or infrequent gradients. A uniform is simultaneously too large for some parameters and too small for others.
The solution is to give each parameter its own effective learning rate, scaled automatically by the history of its gradient magnitudes. A parameter that has consistently seen large gradients should take smaller steps; one that has seen small or rare gradients should take larger steps.
Adam
Adam (Adaptive Moment Estimation) combines momentum with per-parameter adaptive scaling. It maintains two running statistics for every weight:
First moment — an exponential moving average of the gradient, tracking direction:
Second moment — an exponential moving average of the squared gradient, tracking scale:
Both accumulators start at zero. Early in training this causes them to be systematically underestimated, so bias correction is applied before the update:
At step with : the denominator is , which exactly compensates for the factor in . As , and the correction factor approaches — the accumulators have warmed up.
The weight update divides the bias-corrected momentum by the square root of the bias-corrected variance:
where prevents division by zero when is near zero.
Why this normalizes the step size. At step , bias correction recovers and . The update becomes:
A parameter with gradient and one with both receive an update of approximately . The gradient magnitude does not control the step size — only the sign (direction) matters. Over subsequent steps, the ratio adapts as the accumulated statistics diverge across parameters, but the effective step size remains close to throughout.
Default Hyperparameters
Adam's defaults work well across a very wide range of architectures and datasets with little tuning:
| Parameter | Default | Role |
|---|---|---|
| Decay for first moment (momentum) | ||
| Decay for second moment (variance) | ||
| Numerical stability | ||
| Learning rate |
The learning rate remains the most important hyperparameter to tune. , , and rarely need adjustment.
AdamW
A common technique for preventing overfitting is weight decay: after each update, shrink every weight slightly toward zero. The naive way to implement this with Adam is to add to the gradient before the update:
This is equivalent to L2 regularization, but it interacts badly with Adam's adaptive scaling. Because the update is divided by , the weight decay term also gets divided by . Parameters with large gradient variance (large ) end up receiving less effective weight decay than parameters with small gradient variance. The intended regularization is inconsistent across the network.
AdamW fixes this by decoupling weight decay from the gradient update. Instead of mixing into the gradient, it applies the decay directly to the weights after the Adam step:
The second term, , is the weight decay. It is proportional to the current weight value and scaled by , not by the adaptive denominator. Every parameter is decayed by the same factor, regardless of its gradient history.
Example. For a weight with and , the decay term alone subtracts from each step, independently of whatever Adam computes for the gradient term.
The weight decay coefficient is typically set to –. A common default for transformer training is .
Which Optimizer to Use
AdamW is the standard choice for training transformer-based models and most modern architectures. It combines Adam's fast convergence with well-behaved regularization. Virtually all recent large language model training uses AdamW.
Adam works well when weight decay is not needed or is handled separately. For tasks where regularization is less critical, plain Adam is a simpler option.
SGD with momentum is preferred in some computer vision settings. When a learning rate schedule is carefully tuned, it can reach lower final loss values than adaptive methods on image classification benchmarks, at the cost of more careful hyperparameter search.
For a new project, AdamW with and is a reliable starting point.
In Code
import torch
# SGD with momentum
w = torch.tensor([4.0], requires_grad=True)
optimizer = torch.optim.SGD([w], lr=0.3, momentum=0.9)
for step in range(5):
optimizer.zero_grad() # reset the gradients left by the previous step
loss = (w - 2) ** 2 # forward pass
loss.backward() # backward pass: fills w.grad
optimizer.step() # update w from w.grad (and the velocity kept by the optimizer)
print(f"step {step+1}: w={w.item():.4f}")
# Adam
w = torch.tensor([4.0], requires_grad=True)
optimizer = torch.optim.Adam([w], lr=5e-2, betas=(0.9, 0.999), eps=1e-8)
for t in range(200):
optimizer.zero_grad()
loss = (w - 2) ** 2
loss.backward()
optimizer.step()
# After ~200 steps: w ≈ 2.000
print(w.item()) # 2.0001...
# AdamW — Adam with decoupled weight decay
w = torch.tensor([0.8], requires_grad=True)
optimizer = torch.optim.AdamW([w], lr=1e-2, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.1)
for t in range(200):
optimizer.zero_grad()
loss = w ** 2 # minimum at 0; weight decay also pushes toward 0
loss.backward()
optimizer.step()
print(w.item()) # ≈ 0.000 (gradient + weight decay both pull toward 0)
We now have the three components of a training step: a loss function that measures the error, backpropagation that computes the gradient of that error with respect to every weight, and an optimizer that applies the resulting updates. What remains is the structure that ties these together: iterating over training data, deciding how many passes to run, and measuring whether the model has actually learned. That is the subject of the next article.