Adam and AdamW
Adam (Kingma and Ba, 2014) combines momentum's running average of gradients with RMSProp's running average of squared gradients, plus a bias correction for the first steps. With decoupled weight decay (AdamW, Loshchilov and Hutter) it is the default optimizer for transformers and almost every LLM. Its update fits in five lines, but each line has a reason.
The algorithm
With gradient at step and :
Typical values: , (LLMs often use ), .
Why bias correction?
Because , the averages start biased toward zero: after one step . Taking expectations with stationary gradients, , so dividing by removes the bias. Without it, the second moment (with ) would be tiny for the first thousand steps and the first updates huge.
import numpy as np
b1, b2 = 0.9, 0.999
g = 0.5 # a constant gradient
m = v = 0.0
for t in range(1, 6):
m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
raw = m / np.sqrt(v); corrected = (m / (1 - b1**t)) / np.sqrt(v / (1 - b2**t))
print(f"t={t}: m={m:.4f} v={v:.6f} uncorrected step {raw:.3f} corrected step {corrected:.3f}")t=1: m=0.0500 v=0.000250 uncorrected step 3.162 corrected step 1.000
t=2: m=0.0950 v=0.000500 uncorrected step 4.250 corrected step 1.000
t=3: m=0.1355 v=0.000749 uncorrected step 4.950 corrected step 1.000
t=4: m=0.1719 v=0.000999 uncorrected step 5.442 corrected step 1.000
t=5: m=0.2048 v=0.001248 uncorrected step 5.797 corrected step 1.000
With a constant gradient the corrected step is exactly per coordinate from the very first step. Uncorrected, the first steps would be 3 to 6 times too large, because the second moment (with ) starts out even more biased toward zero than the first.
Properties
- Scale invariance: multiplying the loss by a constant leaves the update unchanged.
- Bounded steps: each coordinate moves by roughly at most per step, which makes an interpretable "trust region" in parameter space.
- Signal-to-noise: is near for consistent gradients and small for noisy ones whose sign keeps flipping.
AdamW: decoupled weight decay
Adding an L2 penalty to the loss puts into , where Adam then divides it by : parameters with large gradients get almost no decay. AdamW applies the decay directly to the weights instead:
so every weight shrinks by the same factor per step, as with SGD (Regularization).
import numpy as np
def adam_step(theta, g, state, lr=0.01, lam=0.1, decoupled=True, b1=0.9, b2=0.999, eps=1e-8):
m, v, t = state
if not decoupled: g = g + lam * theta # L2 inside the gradient
t += 1; m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
step = (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps)
if decoupled: step = step + lam * theta
return theta - lr * step, (m, v, t)
# two weights of equal size: one with large data gradients, one with zero data gradient
for decoupled in (False, True):
th, st = np.array([1.0, 1.0]), (np.zeros(2), np.zeros(2), 0)
for _ in range(500):
g = np.array([np.sin(_) * 10.0, 0.0]) # noisy large gradient, zero gradient
th, st = adam_step(th, g, st, decoupled=decoupled)
print(("AdamW " if decoupled else "Adam+L2"), "weights after 500 steps:", np.round(th, 3))Adam+L2 weights after 500 steps: [0.89 0. ]
AdamW weights after 500 steps: [0.585 0.606]
With L2-in-the-gradient, the parameter with zero data gradient decays at full speed (its is just , so its normalized step is about 1), while the one with large gradients barely decays. AdamW shrinks both at the same rate .
Memory cost
Adam keeps two extra numbers per parameter (, ), usually in fp32. In standard mixed-precision training (bf16 weights and gradients, plus an fp32 master copy and the two fp32 moments: bytes), that is 16 bytes per parameter: a 7B model needs about 112 GB just for weights, gradients and optimizer state, before activations (Counting Parameters and FLOPs). Memory-light variants (Adafactor, 8-bit Adam) and sharding (ZeRO) attack that cost.
In software
torch.optim.AdamW(params, lr=3e-4, betas=(0.9, 0.95), weight_decay=0.1, eps=1e-8)is a typical LLM setting.torch.optim.Adam(weight_decay=…)implements the L2 version, not AdamW.- Adam is used with a warmup and decay schedule (Schedules and Clipping).
Go further: Comparing Optimizers and Checking Them Against torch.optim runs these updates through one interface, with practical defaults.
Exercises
Exercise 1: First step
At with gradient (scalar, ), what is Adam's step?
Answer
.
Solution
, , so the step is . The first step has size in every coordinate with a nonzero gradient, whatever the gradient's magnitude.
Exercise 2: Bias correction factor
With , what is at and ?
Answer
About and .
Solution
; . Without correction, would be about 100 times too small at step 10.
Exercise 3: Optimizer memory (code)
Compute the training memory for weights (fp32 master copy), bf16 gradients and Adam's two fp32 moments for a 1.3B-parameter model.
Answer
About 18.2 GB (14 bytes per parameter).
Solution
4 (weights) + 2 (gradients) + 4 + 4 (moments) = 14 bytes; with fp32 gradients it would be 16.
N = 1.3e9
print(round(N * (4 + 2 + 4 + 4) / 1e9, 1), "GB")18.2 GB
Test yourself
Adam's and are…
- the weights and biases
- moving averages of the gradient and the squared gradient
- the learning rate and momentum
- the Hessian and its inverse
Why does Adam divide by ?
- To decay the learning rate
- To correct the bias toward zero caused by initializing the averages at zero
- To add noise
- To clip gradients
How does AdamW differ from Adam with an L2 penalty?
- It uses no second moment
- It applies weight decay directly to the weights instead of through the adaptive gradient
- It has no momentum
- It is identical