16.3 Adam and AdamW: bias correction and decoupled weight decay
The training loop you build in Training loop and the autograd bigram from AI Engineering needs an optimizer that trains every model in that book without retuning: a bigram table, a 64-unit MLP on digits, an LSTM, a Transformer, and the 10M-parameter Llama-style model of Capstone: TinyStories, owned end to end. Plain SGD with momentum, from The Optimizer protocol: SGD, momentum, Nesterov, weight decay, needs a learning rate tuned per model. Worse, inside one model it is too slow for layers with small gradients and unstable for layers with large ones: an embedding row that sees a rare token gets a gradient a thousand times smaller than a layer norm gain.
Concepts from other sections (3)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Geometric sum: the sum of the first terms, for and for . Read more: 6.3 Sequences, geometric series, and frequency ladders
- Noam schedule: , linear rise then inverse-square-root decay. Read more: 16.4 Learning-rate schedules (cosine, WSD, Noam) and gradient clipping
- ZeRO / FSDP: sharding parameters, gradients, and optimizer state across data-parallel ranks, gathering each layer only when it is needed. Read more: 16.3 Embeddings, small models, and platforms in AI Engineering
Adam fixes this by rescaling each coordinate by its own gradient history, and AdamW is the version every modern language model trains with. The capstone’s training spec defaults to adamw with betas (0.9, 0.95), and the checkpoint format already reserves exp_avg and exp_avg_sq for its state, so that a platform workflow such as Platform workflows: TrainRun and EvalSuite in Systems Engineering can kill a training worker and resume it. This section builds that optimizer and checks that it equals torch.optim.AdamW step for step.
The section builds on the Optimizer protocol of the previous section and on the exponential moving average and its bias correction from Series convergence, the EMA as a geometric series, and bias correction. The Adam derivation problems in Optimization problem set, part a check the algebra by hand. The reference solution is course/solutions/python/tinyllm/optim/adamw.py, which provides Adam and AdamW with step, zero_grad, state_dict, and load_state_dict; the contract is course/contracts/py/tinyllm/optim/adamw.pyi, and the checkpoint keys are fixed by formats/checkpoint.md.
Learning objectives
- Write Adam’s two moving averages and its normalized update, and explain why the update is invariant to the gradient’s scale.
- Derive the bias correction from the geometric sum and show that the first step is exactly per coordinate.
- Explain why weight decay as an L2 gradient fails under Adam and how AdamW’s decoupled decay fixes it.
- Implement
AdamandAdamWthat match torch’s arithmetic, including where goes, and resume bit for bit.
Notation
Section titled “Notation”The symbols below follow torch’s names where they appear in code. All operations on vectors are elementwise: squares each coordinate, takes each square root, and divides coordinate by coordinate.
| Symbol | Meaning | Type / shape |
|---|---|---|
| one parameter tensor (the optimizer treats each coordinate the same way) | float32[...], p.data | |
| the gradient of the loss with respect to at step | same shape as , p.grad | |
| the step counter: 1 for the first update | int | |
| the learning rate, read on every step | float, opt.lr | |
| decay rates of the two moving averages, in | float, opt.betas | |
| first moment: moving average of | same shape as , exp_avg | |
| second moment: moving average of (elementwise) | same shape as , exp_avg_sq | |
| bias-corrected moments, and | same shape as | |
| a small constant that keeps the denominator away from 0 | float, default | |
| the weight decay coefficient | float, opt.weight_decay |
Moving averages of the gradient
Section titled “Moving averages of the gradient”Gradient descent moves against the gradient: . A minibatch gradient is noisy, and its direction changes from step to step. Momentum smooths it with an exponential moving average (EMA):
Unrolling the recursion shows what is: a weighted sum of all past gradients with geometrically decaying weights, . With the last 10 or so steps carry most of the weight. Adam keeps a second EMA, of the squared gradient:
With it remembers about 1000 steps. estimates , the mean squared size of this coordinate’s gradient.
Normalizing by the second moment
Section titled “Normalizing by the second moment”The second average exists so that Adam can divide by it. The update divides the first moment by the square root of the second:
has the units of the gradient, so the ratio has no units. Multiplying every gradient by a constant multiplies both and by and leaves the update unchanged (when is negligible). Each coordinate’s step is therefore about in size when its gradient keeps a consistent sign, and smaller when the sign flips, because positive and negative gradients cancel in but not in , so . The learning rate becomes a step length in parameter space, which is why one value such as works across many models. only matters when is near or below it, for coordinates whose gradients are almost always zero.
Bias correction
Section titled “Bias correction”The hats in that formula need explaining. Both averages start at 0, so early on they are too small. Take every equal to the same value . Then by the geometric sum from Sequences, geometric series, and frequency ladders. The average is short of by exactly the factor , and dividing by it removes the bias:
For random gradients with constant mean the same argument holds in expectation. The factor matters most for : with , , so the uncorrected is 1000 times too small and the first step would be times too large in the ratio . That is partly offset by the uncorrected , which is 10 times too small, for a net of times too large. After a few thousand steps both factors are 1 and the correction disappears.
At the corrections give and , so the first update is : exactly times the sign of when . torch folds the corrections into the step for speed, and the solution uses the same arrangement, because it decides where goes:
Decoupled weight decay
Section titled “Decoupled weight decay”Weight decay shrinks the weights toward 0 a little on every step, which regularizes the model. For SGD it is the same as adding the penalty to the loss, whose gradient is : the step decays by the factor .
For Adam the two are not the same, and the normalization you just saw is the reason. Adam with L2 (torch.optim.Adam(weight_decay=...)) adds to before both moments see it, and then the normalization divides it by . A coordinate with large gradients gets almost no decay, and with the penalty itself becomes a normalized step of size , whatever the weight’s size. AdamW applies the decay directly to the weights, before the Adam update, and leaves the gradient alone:
Every coordinate shrinks by the same factor, as intended. The decay is scaled by , so a schedule that lowers (the subject of the next section) lowers the decay with it. Parameters whose gradient is None (the loss did not reach them this step) are skipped entirely: no decay, no moment update.
Saving and restoring the state
Section titled “Saving and restoring the state”The optimizer state is , , and for every parameter, plus the hyperparameters. Training that stops and resumes must continue as if it never stopped, so state_dict returns copies of everything, and load_state_dict restores all of it, including : with reset to 0 the bias correction would restart and the next step would be badly mis-scaled. formats/checkpoint.md writes the moments as <name>.exp_avg and <name>.exp_avg_sq, in the parameter’s dtype.
Working it by hand
Section titled “Working it by hand”Take one scalar parameter , gradients then (given, not computed from a loss), , , , , and no weight decay. The two steps work out as follows:
| Step | update | |||||||
|---|---|---|---|---|---|---|---|---|
| 1 | ||||||||
| 2 |
Two things are worth seeing. Step 1 moves by exactly : that is bias correction at work (without it, ). Step 2 has a negative gradient, yet keeps decreasing: still points the old way, and the step is smaller because remembers the large first gradient.
Now add weight decay . AdamW first multiplies by : step 1 gives ; step 2 gives . Adam with L2 instead feeds and to the moments. Step 1 still moves by exactly (the first step is times a sign, whatever the gradient), to ; step 2 lands at . The penalty changed by under L2 and by under AdamW.
Designing the interface
Section titled “Designing the interface”The two classes share one interface:
class Adam: lr: float; betas: tuple[float, float]; eps: float; weight_decay: float def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0) -> None def step(self) -> None # one update of every p whose grad is not None, in place def zero_grad(self) -> None # every p.grad = None def state_dict(self) -> dict # {"step", "lr", "betas", "eps", "weight_decay", "exp_avg": [...], "exp_avg_sq": [...]} def load_state_dict(self, sd: dict) -> None
class AdamW(Adam): # decoupled decay; weight_decay defaults to 0.01 def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01) -> NoneA parameter is any object with data (a float ndarray) and grad (an ndarray or None). A two-attribute class is enough, and the training loop passes the autograd tensors of Tensor, broadcasting backward, and no_grad. The step counter is one global count of step() calls, as formats/checkpoint.md stores one step. torch keeps a counter per parameter instead; the two agree whenever every parameter has a gradient on every step, which is how the models in this series train. A schedule changes the learning rate by assigning opt.lr before step().
The tests hold the implementation to a long list of behaviors, each tied to a downstream need. It must reproduce both hand-worked steps to float64 precision, and the variants for both kinds of decay, since that is the one difference between the classes. It must match 20 steps of torch AdamW on two tensors, including the final moments, and 20 steps of torch Adam with weight_decay = 0.1, where L2 coupling feeds both moments. A learning rate changed on every step (with betas (0.9, 0.95)) must be used, because schedules write opt.lr. Gradients of size with must match torch, which is where the placement of becomes visible. float32 parameters must follow torch’s float32 trajectory, with float32 moments, because model parameters are float32 (see Module system and basic layers).
Two laws are checked as properties: with the first step is at every scale, and gradients multiplied by or give the same trajectory. With zero gradient, starting from the test’s weights, AdamW gives and Adam with L2 gives : decoupling, in one line. A parameter with grad = None gets no decay and no moment change, while still advances. The update is in place: p.data keeps its identity and a view writes through to its buffer, because the model and the flat buffers of large-scale training hold the arrays. zero_grad sets every grad to None, since the autograd accumulates into grad. Five steps, save, load into a fresh optimizer, and five more equal ten steps bit for bit; a saved dict does not change after later steps; the layout’s keys and shapes are checked, hyperparameters restored, and mismatches rejected. Finally, bad hyperparameters (negative lr, eps, or decay, a beta outside , no parameters, integer data) are errors at construction, not NaN at step 9000.
Building it step by step
Section titled “Building it step by step”The design follows from the principles in eight steps.
- Two EMAs per coordinate. tracks the gradient’s direction, its squared size. They have the parameter’s shape and dtype and start at 0.
- Normalize to make the step a length. Dividing by removes the gradient’s scale, so is a step size in parameter space.
- Correct the zero start. Dividing by and makes the first step exactly , which requires to count from 1 at the first
step(). - Put where torch does. Folding both corrections into one scalar
step_size = lr / (1 - beta1^t)and dividing by before adding reproduces torch to the last bit; adding elsewhere changes small-gradient coordinates. - Two kinds of decay, one flag. Adam folds into (so both moments see it); AdamW multiplies by before the update and leaves alone. Everything else is shared, so
AdamWisAdamwith a class flag and a different default. - Read hyperparameters on every step. Schedules assign
opt.lrbetween steps, sostepreadsself.lreach call. - Update in place, skip
Nonegradients. The arrays are shared with the model; a parameter that got no gradient must not decay or change its moments, while the global still advances. - State is , , , and the hyperparameters, copied. Restoring keeps the bias correction where it was.
The constructor validates and allocates:
class Adam: _decoupled = False # AdamW decays the weights directly instead
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0) -> None: _check_hyper(lr, betas, eps, weight_decay) # lr, eps, decay >= 0; betas in [0, 1) self.params = list(params) if not self.params: raise ValueError("params is empty: nothing to optimize") for i, p in enumerate(self.params): d = getattr(p, "data", None) if not isinstance(d, np.ndarray) or not np.issubdtype(d.dtype, np.floating): raise ValueError(f"parameter {i}: data must be a floating-point ndarray") self.lr = float(lr) self.betas = (float(betas[0]), float(betas[1])) self.eps = float(eps) self.weight_decay = float(weight_decay) self.t = 0 # becomes 1 on the first step # Moments in the parameter's own dtype, allocated up front so every # parameter has an entry in the checkpoint even before its first grad. self.exp_avg = [np.zeros_like(p.data) for p in self.params] self.exp_avg_sq = [np.zeros_like(p.data) for p in self.params]Integer data is rejected because p.data -= ... on an integer array would truncate every update (or raise), a failure that shows up thousands of steps later as a model that never trains. The _check_hyper conditions are written not lr >= 0.0, so NaN is rejected too. Moments are allocated eagerly, unlike SGD’s lazy buffers, because the checkpoint format stores one exp_avg and exp_avg_sq per parameter.
The step is a direct transcription of torch’s single-tensor path:
def step(self) -> None: self.t += 1 # t = 1 on the first call lr, (beta1, beta2), eps, wd = self.lr, self.betas, self.eps, self.weight_decay # read now bias_correction1 = 1.0 - beta1**self.t bias_correction2_sqrt = math.sqrt(1.0 - beta2**self.t) step_size = lr / bias_correction1 # torch's arrangement: one scalar for p, m, v in zip(self.params, self.exp_avg, self.exp_avg_sq): g = p.grad if g is None: continue # no decay, no moment update g = np.asarray(g, dtype=p.data.dtype) if g.shape != p.data.shape: raise ValueError(f"grad shape {g.shape} != parameter shape {p.data.shape}") if self._decoupled: p.data *= 1.0 - lr * wd # AdamW: shrink w, leave g alone elif wd != 0.0: g = g + wd * p.data # Adam: L2 gradient, seen by m and v m *= beta1 m += (1.0 - beta1) * g # m_t = b1 m + (1 - b1) g v *= beta2 v += (1.0 - beta2) * (g * g) # v_t = b2 v + (1 - b2) g^2 denom = np.sqrt(v) / bias_correction2_sqrt + eps # eps after the correction p.data -= step_size * (m / denom) # in place, in p's dtypeTrace the hand example’s step 1 through it. With , bias_correction1 , bias_correction2_sqrt , and step_size . With : , , denom , and moves by to . Step 2 with gives , , step_size , denom , and . With AdamW and , the decay line first multiplies by , and the same arithmetic lands at ; with Adam and L2 the gradients become and , landing at . The moments are updated with *= and +=, so they stay the same arrays and keep the parameter’s dtype; a float32 model never silently gets float64 moments.
Saving, loading, and the AdamW subclass complete the code:
def state_dict(self) -> dict: return { "step": self.t, "lr": self.lr, "betas": [self.betas[0], self.betas[1]], "eps": self.eps, "weight_decay": self.weight_decay, "exp_avg": [m.copy() for m in self.exp_avg], # snapshots, not live arrays "exp_avg_sq": [v.copy() for v in self.exp_avg_sq], }
def load_state_dict(self, sd: dict) -> None: ms, vs = list(sd["exp_avg"]), list(sd["exp_avg_sq"]) # ... same number of moments as parameters, each with the parameter's shape ... betas = (float(sd["betas"][0]), float(sd["betas"][1])) _check_hyper(float(sd["lr"]), betas, float(sd["eps"]), float(sd["weight_decay"])) self.t = int(sd["step"]) # restore t: the correction continues # ... lr, betas, eps, weight_decay ... self.exp_avg = [np.array(m, dtype=p.data.dtype, copy=True) for p, m in zip(self.params, ms)] self.exp_avg_sq = [np.array(v, dtype=p.data.dtype, copy=True) for p, v in zip(self.params, vs)]
class AdamW(Adam): _decoupled = True
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01) -> None: super().__init__(params, lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)As with SGD, validation happens before assignment so a bad checkpoint leaves the optimizer unchanged, and loaded moments are copied and cast to the parameter’s dtype. AdamW changes only the flag and the default weight_decay (0.01, torch’s default).
The full solution is in adamw.py.
Why this design
Section titled “Why this design”Per step and parameter, the cost is about ten elementwise array operations and one square root. Memory is two moment arrays per parameter, twice the model size, which is the main reason production systems shard or quantize optimizer state (see Further reading).
The code matches torch’s arithmetic exactly. Writing the textbook form is mathematically the same but places differently relative to the correction and rounds differently; matching _single_tensor_adam statement for statement is what makes the golden trajectories agree.
There is one global step counter. torch keeps one per parameter; with one counter the checkpoint stores one step, and the two agree whenever every parameter gets a gradient every step. The tradeoff is that a parameter that starts receiving gradients late gets a slightly wrong correction.
Inheritance beats duplication here. The two optimizers differ in one branch, and a class flag keeps the shared update in one place, so a fix to one is a fix to both.
What can go wrong
Section titled “What can go wrong”Most Adam bugs are scaling bugs that train, just badly. These are the ones to look for:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| no bias correction, or correcting only one moment | the first steps are about 3 times too large (or too small); early loss spikes | step_size = lr / (1 - beta1**t) and sqrt(v) / sqrt(1 - beta2**t) |
| counting from 0 inside the correction, or using | divides by zero, or every step is mis-scaled | self.t += 1 is the first line of step, so on the first update |
| AdamW adding to the gradient | AdamW behaves like Adam with L2: decay is normalized away for large-gradient weights | the _decoupled branch multiplies p.data; only Adam adds to g |
| decaying by instead of | with the weights lose 10% per step and collapse toward 0 | p.data *= 1.0 - lr * wd |
| inside the square root, or before the correction | rare-feature coordinates take steps of the wrong size; only visible when gradients are near | np.sqrt(v) / bias_correction2_sqrt + eps |
| caching the learning rate at construction | the schedule is silently ignored | step reads self.lr on every call |
p.data = p.data - ... instead of p.data -= ... | the optimizer updates a copy; the model keeps its old weights | p.data -= ... and p.data *= ... |
returning live arrays from state_dict, or not restoring | a resumed run differs from the uninterrupted one; bias correction restarts after every resume | copies out and in, and self.t = int(sd["step"]) |
decaying parameters whose grad is None | embeddings of tokens absent from the batch shrink anyway | the None check comes before the decay line |
Where this leads
Section titled “Where this leads”From here on, nearly every model in AI Engineering trains with this optimizer. In Training loop and the autograd bigram, train_step calls opt.zero_grad(), the backward pass, then opt.step() on every model of its part. Safetensors for every dtype, atomic checkpoints, and the token stream stores state_dict() as <name>.exp_avg, <name>.exp_avg_sq, and the step, and resume calls load_state_dict. The next section, Learning-rate schedules (cosine, WSD, Noam) and gradient clipping, sets opt.lr between steps and clips before step().
Later, AdamW trains the encoder-decoder of Encoder-decoder with teacher forcing, the 2017 Transformer with the Noam schedule in Encoder-decoder Transformer: post-LN and pre-LN, Noam, label smoothing, the pretraining objectives starting with GPT: the decoder-only language model, the fine-tuning heads of Fine-tuning heads and the linear-head export, and the recurrent models of RNN language model with stateful TBPTT. The modern decoder of The Llama-Family Model: Config, Weight Loading, and Download and the TinyStories capstone use betas and , with checkpoints holding exp_avg and exp_avg_sq. Mixed precision, loss scaling, gradient accumulation, and activation checkpointing and Supervised fine-tuning: chat rendering, assistant-only loss, packing train with it too.
Further reading
Section titled “Further reading”- Kingma and Ba, “Adam: A Method for Stochastic Optimization” (2015), sections 2 and 3; Loshchilov and Hutter, “Decoupled Weight Decay Regularization” (2019), sections 2 and 3; the torch source
torch/optim/adam.py,_single_tensor_adam. torch.optim.AdamW’sforeachandfusedpaths (torch/optim/adam.py,_multi_tensor_adam,_fused_adam) update all parameters in one kernel launch; the fused CUDA kernel also handles AMP grad scaling.- torch’s per-parameter
state["step"]gives correct bias correction for parameters that start receiving gradients late. - Dettmers et al., “8-bit Optimizers via Block-wise Quantization” (2022): bitsandbytes quantizes and block-wise, cutting optimizer memory by 4 times.
- Rajbhandari et al., “ZeRO” (2020): with ZeRO stage 1 (DeepSpeed, FSDP) each data-parallel rank owns a shard of and ; see Data parallelism and ZeRO stages 1 to 3.
- Jordan et al., “Muon” (2024): orthogonalized momentum for 2-D weights, AdamW for the rest.
Key terms
Section titled “Key terms”- Exponential moving average (EMA): a recursive average whose weights decay geometrically with age.
- First moment (,
exp_avg): the EMA of the gradient. - Second moment (,
exp_avg_sq): the EMA of the elementwise squared gradient. - Bias correction: dividing and by and to undo the zero initialization.
- Adam with L2: weight decay added to the gradient, so it passes through the normalization.
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path.
Summary
Section titled “Summary”- Adam keeps two exponential moving averages per coordinate, of the gradient and of its square, and moves each coordinate by .
- Bias correction divides by and by , which undoes the pull toward the zero they start from; the first step is then exactly per coordinate.
- Dividing by makes the update invariant to the scale of the gradient, so one learning rate serves layers whose gradients differ by orders of magnitude.
- AdamW decouples weight decay: it multiplies the weights by instead of adding to the gradient, where Adam’s normalization would wash the penalty out.
- The optimizer state is part of the model: a save and load between steps must reproduce the uninterrupted run bit for bit.
Review questions
Section titled “Review questions”-
Why is the first Adam step exactly per coordinate when ?
Answer
At , and . Dividing by and gives and , so the update is , whatever the gradient’s scale.
-
Why does AdamW multiply the weights by instead of adding to the gradient?
Answer
Anything added to the gradient is divided by . For a coordinate with large gradients the penalty becomes negligible; for one with zero gradient it becomes a full normalized step of size regardless of the weight’s size. Shrinking the weights directly applies the same relative decay to every coordinate, which is what weight decay is meant to do. In the zero-gradient test case, AdamW gives 3.8 and Adam with L2 gives 3.9.
-
Where exactly is added, and why does it matter?
Answer
To , that is, after the second moment is bias-corrected and square-rooted. This is torch’s placement. Adding it inside the square root, or before the correction, changes the denominator by an amount comparable to for coordinates whose gradients are near (rare features), so their steps would differ from torch’s.
-
What goes wrong after a resume if
load_state_dictdoes not restorestep?Answer
restarts at 0, so the next step uses in both corrections while the moments already hold thousands of steps of history. becomes about 1000 times too large and about 10 times too large; the result is a step about times the right size at first, and the trajectory no longer matches the uninterrupted run.
-
Why does the optimizer read
self.lrat the start of everystepinstead of storing it once?Answer
Schedules change the learning rate by assigning
opt.lrbefore each step. A value cached at construction would silently ignore the schedule, and both the Adam step and AdamW’s decay must use the current rate.