16.2 The Optimizer protocol: SGD, momentum, Nesterov, weight decay
The gradient_descent of Convexity, smoothness, gradient descent, and Armijo line search takes a function and returns a trajectory. That is fine for a two-dimensional quadratic and wrong for training. When you train the bigram in Training loop and the autograd bigram from AI Engineering, its weights live inside a model, gradients arrive from the autograd one minibatch at a time, the loop runs for thousands of steps, and a run that stops (a closed laptop, a killed worker in a distributed job) must resume exactly where it was.
Concepts from other sections (5)
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.
- Decoupled weight decay (AdamW): multiplying the weights by outside the gradient path. Read more: 16.3 Adam and AdamW: bias correction and decoupled weight decay
- Condition number: how much the exact answer of a problem moves relative to a change in its input. Read more: 15.3 Error analysis, condition numbers, and tolerance budgets
- Structural typing: type compatibility decided by shape: a value fits a type when it has the required members, whatever it was declared as; TypeScript’s types and Go’s interfaces both work this way. Read more: Chapter 23: TypeScript in Programming and Algorithms
- Test double: a stand-in for a real dependency in a test: a fake (a working lightweight implementation), a stub (canned answers), or a mock (asserts how it was called). Fakes are preferred because mock-heavy tests couple to the implementation and break on refactors. Read more: Chapter 3: The Testing Mentality in Software Engineering
- state dict: an ordered mapping from dotted parameter names to arrays, used for checkpoints. Read more: 6.5 Module system and basic layers in AI Engineering
Training therefore needs an object: one that holds the parameters by reference, updates them in place, keeps per-parameter state such as a momentum buffer, and can save and restore that state. Once every optimizer has that shape, the training loop reads opt.zero_grad(); loss.backward(); opt.step() whatever the optimizer is: SGD here, AdamW in Adam and AdamW: bias correction and decoupled weight decay, and more exotic ones such as Muon later.
This section defines that protocol and builds SGD with momentum, Nesterov momentum, and coupled weight decay, following torch.optim.SGD exactly. Plain SGD reproduces the previous section’s gradient descent bit for bit. The reference solution is course/solutions/python/tinyllm/optim/sgd.py, which defines the Param and Optimizer protocols and SGD (step, zero_grad, state_dict, load_state_dict); the contract is course/contracts/py/tinyllm/optim/sgd.pyi.
Learning objectives
- Describe the four-method
Optimizerprotocol and why each method exists.- Derive heavy-ball momentum and Nesterov momentum in PyTorch’s variables and compute their steps by hand.
- Explain why the learning rate multiplies the momentum buffer instead of living inside it, and why that matters under a schedule.
- Distinguish coupled weight decay from decoupled weight decay.
- Implement
SGDso that updates are in place,Nonegradients are skipped, and save-and-resume is bit-exact.
Notation
Section titled “Notation”These are the symbols the section uses, with their types in code.
| Symbol | Meaning | Type / shape |
|---|---|---|
one parameter tensor (p.data) | float array | |
its gradient at step (p.grad), or None | same shape | |
learning rate (lr) | float | |
momentum coefficient (momentum) | float in | |
| momentum buffer of one parameter | same shape as | |
weight decay coefficient (weight_decay) | float | |
| , , | smoothness, strong convexity, condition number | floats |
Stochastic gradients and the protocol
Section titled “Stochastic gradients and the protocol”A training loss is an average over examples, and its gradient is an average of per-example gradients. A minibatch gives an unbiased estimate of it, so SGD is gradient descent with a noisy gradient. Everything below works per parameter tensor, with whatever gradient the backward pass produced.
A parameter is anything with a float array data and a grad that is an array of the same shape or None. An optimizer has four methods:
| Method | Does |
|---|---|
step() | update every parameter’s data in place from its grad |
zero_grad() | set every grad to None |
state_dict() | return a deep copy of everything needed to resume |
load_state_dict(sd) | restore it, copying arrays in |
zero_grad exists because backward accumulates, as you saw in Scalar reverse mode: the Value graph: without it the second step would use the sum of two steps’ gradients. Setting None instead of zeros (PyTorch’s default) lets step skip parameters that received no gradient at all, such as a frozen layer: no update, no decay, no buffer change.
Momentum and Nesterov
Section titled “Momentum and Nesterov”Plain gradient descent pays the full rate on an ill-conditioned problem. Momentum is the oldest fix. Keep a buffer per parameter:
with on the first step. This is PyTorch’s convention: no dampening, and the learning rate multiplies the buffer. Unrolled, , an exponentially weighted sum of past gradients. When gradients agree from step to step (a long shallow valley) they add up, to times one gradient in the limit; when they flip sign (bouncing across a steep valley) they cancel. On a quadratic with condition number , choosing and gives a per-step rate of , against for plain gradient descent. For that is about 0.82 instead of 0.99.
Notice that the buffer holds gradients, not steps. multiplies when the step is taken and never enters the buffer. With a constant that is only bookkeeping: a buffer with update produces the same trajectory. It stops being the same the moment changes, and the schedules of Learning-rate schedules (cosine, WSD, Noam) and gradient clipping change it before every step. With outside, a new learning rate scales the whole next step at once; with inside, the old rate lingers in the buffer for about steps.
Nesterov’s method evaluates the gradient at a look-ahead point. Rewritten in the variables PyTorch stores, it becomes one extra term:
It needs momentum to mean anything, so nesterov=True with is an error.
Coupled weight decay
Section titled “Coupled weight decay”The L2 penalty adds to the gradient. SGD applies it first, so it flows through the momentum buffer like any other gradient:
With plain SGD this is the same as shrinking the weights, ; with a zero gradient, . With momentum the decay accumulates in the buffer, so adding after the buffer instead (“decoupled” decay, SGDW) is a different optimizer with a different trajectory. AdamW, in the next section, is built on exactly that difference.
In place, and resumable
Section titled “In place, and resumable”Two engineering properties complete the design. First, updates happen in place, in the parameter’s dtype. The model, its tied weights, and the checkpoint writer hold references to each data array. p.data -= lr * g changes that array; p.data = p.data - lr * g builds a new one and leaves every other reference pointing at the old weights. In-place arithmetic also keeps a float32 parameter float32.
Second, the state can be saved and restored bit for bit. SGD’s state is one momentum buffer per parameter, keyed by the parameter’s position in the list. state_dict copies the buffers and the hyperparameters in PyTorch’s layout, {"state": {i: {"momentum_buffer": ...}}, "param_groups": [{...}]}. It must be a copy, because a checkpoint must not change when training continues. Since every operation is deterministic, 10 steps, save, load into a fresh optimizer, and 10 more steps give exactly the bits of 20 uninterrupted steps.
Working it by hand
Section titled “Working it by hand”Minimize , whose gradient is , from with . With momentum , the first three steps are:
| 1 | 1 | 1 | 0.9 |
| 2 | 0.9 | ||
| 3 | 0.72 |
Plain gradient descent would give : the buffer has already doubled the effective step. With Nesterov the step direction picks up the extra :
| step direction | ||||
|---|---|---|---|---|
| 1 | 1 | 1 | 1.9 | 0.81 |
| 2 | 0.81 |
With weight decay and no momentum, the gradient becomes , so , which is .
Finally, change the learning rate mid-run with momentum . Take the first momentum step above with (, ), then set . The buffer is as before, and the step is , so . A buffer that had absorbed would hold , then , and land on : ten times the step the schedule asked for.
Designing the interface
Section titled “Designing the interface”The protocols and the class signature fit in a few lines:
@runtime_checkableclass Param(Protocol): data: NDArray; grad: NDArray | None@runtime_checkableclass Optimizer(Protocol): def step(self) -> None; def zero_grad(self) -> None def state_dict(self) -> dict; def load_state_dict(self, sd: dict) -> Noneclass SGD: def __init__(self, params, lr: float, momentum: float = 0.0, nesterov: bool = False, weight_decay: float = 0.0)SGD follows torch.optim.SGD with dampening 0, so the contract’s update order is PyTorch’s: weight decay, then the buffer, then Nesterov, then the in-place update. The constructor raises ValueError for a negative lr, momentum, or weight_decay, and for Nesterov without momentum. load_state_dict refuses a state for a different number or shape of parameters.
A correct implementation reproduces the hand tables above, including the learning-rate change (, ), since schedules set opt.lr before every step. It matches 20-step torch.optim.SGD golden trajectories for five settings and two parameters, so recipes from PyTorch transfer, and plain SGD equals the previous section’s gradient_descent bit for bit. After step, p.data is the same array object, and float32 stays float32. A None grad means no move, no decay, and no buffer, and zero_grad sets None. Ten steps, save, load, and ten more equal twenty steps exactly; saved buffers do not change when training continues, and loading copies. Bad hyperparameters raise. Two property checks show why the features exist: at , plain SGD leaves a gap above 0.02 while a tuned heavy ball gets below ; and with zero gradient, decay gives . Two parameters with opposite gradients must keep separate buffers, and SGD must pass isinstance against both runtime-checkable protocols so that loops accept any optimizer.
Building it step by step
Section titled “Building it step by step”The reasoning chain behind the solution runs in eight steps.
- The protocol is structural. A training loop needs only
step,zero_grad,state_dict, andload_state_dict, and a parameter onlydataandgrad. Declaring them asruntime_checkableProtocols lets any class with those members qualify, without inheritance, and letsisinstancecheck it. - Validate at construction. PyTorch rejects negative
lr,momentum, andweight_decay, and Nesterov without momentum. Checking in__init__turns a typo into an immediate error instead of a silently odd run. - Skip what has no gradient. A
Nonegrad means the parameter took no part in the loss (a frozen layer). It must not move, decay, or create a buffer, sostepskips it before anything else. - Follow PyTorch’s order. Decay is added to the gradient, then the buffer is updated with that decayed gradient, then Nesterov’s look-ahead term is formed, then the parameter moves. Any other order is a different optimizer.
- The buffer holds gradients; multiplies at the end. So a schedule’s new
lrscales the very next step, as in the 0.882 example. - One buffer per parameter, keyed by position. Parameters have different shapes and different gradients; a dict from list index to array keeps them apart and matches PyTorch’s
statelayout. - Mutate
datain place.p.data -= ...keeps every other reference to the array (the model, tied weights, the checkpoint writer) current and keeps the dtype. - State out and in are copies. A checkpoint must not change when training continues, and a loaded state must not alias the caller’s dict; with deterministic arithmetic, that makes save and resume bit-exact.
The protocols and the constructor come first:
@runtime_checkableclass Param(Protocol): data: NDArray grad: NDArray | None
@runtime_checkableclass Optimizer(Protocol): def step(self) -> None: ... def zero_grad(self) -> None: ... def state_dict(self) -> dict: ... def load_state_dict(self, sd: dict) -> None: ...
class SGD: """torch.optim.SGD semantics with dampening 0 (see the contract)."""
def __init__(self, params, lr, momentum=0.0, nesterov=False, weight_decay=0.0) -> None: if lr < 0: raise ValueError(f"lr must be >= 0, got {lr}") if momentum < 0: raise ValueError(f"momentum must be >= 0, got {momentum}") if weight_decay < 0: raise ValueError(f"weight_decay must be >= 0, got {weight_decay}") if nesterov and momentum == 0: raise ValueError("nesterov needs momentum > 0") self.params = list(params) # references, not copies: step mutates them self.lr = float(lr) # public: schedules assign opt.lr self.momentum = float(momentum) self.nesterov = bool(nesterov) self.weight_decay = float(weight_decay) self.buffers: dict[int, NDArray] = {} # created lazily, one per parameter indexlist(params) materializes a generator once, so the same parameters are seen on every step, while keeping references to the caller’s objects. Buffers are created on first use rather than as zeros up front, which is how a parameter that never gets a gradient never gets a buffer.
The update itself is the heart of the class:
def step(self) -> None: for i, p in enumerate(self.params): if p.grad is None: continue # no move, no decay, no buffer g = np.asarray(p.grad, dtype=p.data.dtype) # compute in the parameter's dtype if self.weight_decay != 0: g = g + self.weight_decay * p.data # coupled decay: before the buffer if self.momentum != 0: buf = self.buffers.get(i) if buf is None: buf = np.array(g, copy=True) # v_1 = g_1, a private copy else: buf *= self.momentum # v_t = beta v_{t-1} + g_t, in place buf += g self.buffers[i] = buf g = g + self.momentum * buf if self.nesterov else buf # look-ahead: g + beta v p.data -= self.lr * g # eta outside the buffer, in place
def zero_grad(self) -> None: for p in self.params: p.grad = None # None, not zeros: see step's skipTrace the momentum table through it. On step 1 there is no buffer, so buf = [1] and moves by to . On step 2, buf = 0.9 * 1 + 0.9 = 1.8 and . With nesterov=True, step 1 moves by to . Writing g = g + ... (not g += ...) matters in the decay line: np.asarray may return p.grad itself, and an in-place add would change the caller’s gradient. The first buffer is a copy for the same reason: the later buf *= ... must not modify the gradient array it came from.
Saving and loading close the loop:
def state_dict(self) -> dict: return { "state": {i: {"momentum_buffer": b.copy()} for i, b in self.buffers.items()}, "param_groups": [{ "lr": self.lr, "momentum": self.momentum, "nesterov": self.nesterov, "weight_decay": self.weight_decay, "params": list(range(len(self.params))), }], }
def load_state_dict(self, sd: dict) -> None: (group,) = sd["param_groups"] # exactly one group, or it raises if len(group["params"]) != len(self.params): raise ValueError(...) buffers = {} for i, st in sd["state"].items(): i = int(i) # keys may come back as strings b = np.array(st["momentum_buffer"], copy=True) # never alias the caller's arrays if not 0 <= i < len(self.params) or b.shape != self.params[i].data.shape: raise ValueError(f"momentum buffer {i} does not match parameter shapes") buffers[i] = b self.lr = float(group["lr"]) # ... momentum, nesterov, weight_decay likewise ... self.buffers = buffers # assigned only after every checkload_state_dict validates everything before assigning anything, so a bad checkpoint leaves the optimizer unchanged. int(i) accepts keys that a JSON round trip turned into strings. Restoring lr matters: a resumed run continues with the learning rate it had, not the one passed to the constructor.
The full solution is in sgd.py.
Why this design
Section titled “Why this design”The cost is one pass over the parameters per step with array operations each; memory is one buffer per parameter with momentum, none without.
The solution follows PyTorch’s conventions over textbook ones. The “average” form and folding into the buffer are both common in texts. The solution follows torch.optim.SGD (sum form, outside) so that published recipes transfer unchanged and schedules behave as expected.
Decay is coupled here and decoupled in AdamW. SGD’s decay goes through the buffer because that is the L2 penalty’s gradient and PyTorch’s definition; the next section shows why decoupling matters once the update is normalized.
A protocol beats a base class. Structural typing lets SGD, AdamW, and a test double all satisfy Optimizer with no shared code, and keeps the loop independent of the optimizer.
Some tradeoffs are accepted on purpose: one parameter group only, no dampening, and a Python loop over tensors instead of fused multi-tensor kernels (see Further reading). These keep the update readable and bit-checkable against PyTorch’s single-tensor path.
What can go wrong
Section titled “What can go wrong”Each of these mistakes produces a working-looking optimizer that is quietly different from the one you meant:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| adding weight decay after the momentum buffer | a different optimizer (SGDW); matches PyTorch only without momentum | g = g + weight_decay * p.data comes before the buffer |
| one momentum buffer for every parameter | velocity leaks between tensors, or shapes fail to broadcast | self.buffers is keyed by parameter index |
p.data = p.data - lr * g | the model keeps training on stale weights it still references | p.data -= self.lr * g |
a state_dict of live buffers, or a load that drops them | a checkpoint that changes after saving; a resumed run that diverges from the original | b.copy() out, np.array(..., copy=True) in, and lr and buffers restored |
| momentum as an average, | steps times smaller than PyTorch’s | buf *= momentum; buf += g, the sum form |
| Nesterov ignored or with its terms swapped | plain momentum where look-ahead was asked for | g + self.momentum * buf when nesterov |
zeros instead of None, or decaying parameters without a gradient | frozen layers shrink every step | zero_grad sets None and step skips it first |
| the sign of the decay term | weights pushed away from zero | decay is added to the gradient, which is then subtracted |
| folding into the momentum buffer | identical while is constant; under a schedule the old rate lingers for about steps | lr multiplies only at the final update |
Warning: The folded- bug passes every test with a constant learning rate. Always test a learning-rate change mid-run.
Where this leads
Section titled “Where this leads”Every model in AI Engineering trains through this protocol. Training loop and the autograd bigram uses zero_grad, backward, step, and state_dict in the checkpoint. Bengio’s neural probabilistic language model trains with SGD and momentum, and RNN language model with stateful TBPTT trains through the same protocol, as do Safetensors for every dtype, atomic checkpoints, and the token stream, Mixed precision, loss scaling, gradient accumulation, and activation checkpointing, and the resumable runs of Capstone: TinyStories, owned end to end. Within this chapter, Adam and AdamW: bias correction and decoupled weight decay implements the same four methods with decoupled decay, and Learning-rate schedules (cosine, WSD, Noam) and gradient clipping sets lr between steps and rescales grad before step.
Further reading
Section titled “Further reading”- Goh, Why Momentum Really Works (Distill, 2017); Sutskever, Martens, Dahl, and Hinton, “On the importance of initialization and momentum in deep learning” (ICML 2013).
- PyTorch
torch.optim.SGD(torch/optim/sgd.py,_single_tensor_sgd) adds parameter groups with their own hyperparameters, dampening, andforeachand fused multi-tensor kernels. - optax (
optax/_src/alias.py,sgd) builds optimizers as composable pure gradient transformations (tracefor momentum,add_decayed_weights,scale). - PyTorch distributed checkpointing (
torch/distributed/checkpoint/) saves sharded optimizer state and reshards it across ranks.
Key terms
Section titled “Key terms”- Optimizer protocol: the four methods
step,zero_grad,state_dict, andload_state_dictthat every optimizer exposes. - Stochastic gradient: a minibatch estimate of the full-loss gradient, unbiased for the average.
- Heavy-ball momentum: the update , .
- Nesterov momentum: momentum with a look-ahead, stepping along .
- Coupled weight decay: adding to the gradient before the momentum buffer; the gradient of an L2 penalty.
- Decoupled weight decay: shrinking the weights outside the gradient path, as in SGDW and AdamW.
Summary
Section titled “Summary”- An optimizer is an object: it holds references to the parameters and the state it carries between steps, and every optimizer in this book exposes the same four methods.
- Momentum accumulates past gradients, , which on an ill-conditioned problem turns a rate of into roughly .
- The learning rate multiplies the buffer at the final update, so a schedule’s new rate takes effect on the next step.
- Coupled weight decay adds to the gradient before the momentum buffer; for plain SGD that is the same as shrinking by , a coincidence Adam breaks.
- Updates happen in place, parameters without a gradient are skipped, and
state_dictmakes a stopped run resume bit for bit.
Review questions
Section titled “Review questions”-
Why does
stepadd weight decay before the momentum update and not after?Answer
Coupled decay is the gradient of the L2 penalty , so it belongs to the gradient and must flow through the buffer like any other gradient; that is
torch.optim.SGD’s definition. Adding it after the buffer is decoupled decay (SGDW), a different optimizer whose trajectory differs whenever momentum is non-zero. -
Why is the learning rate applied in
p.data -= self.lr * grather than stored in the buffer?Answer
With a constant rate the two are equivalent, but schedules change
lrbefore every step. With outside, a new rate scales the next whole step immediately; with inside, the buffer still carries steps scaled by the old rate for about steps. In the hand example, going from 0.1 to 0.01 gives with the solution and with a folded buffer. -
What would break if
stepwrotep.data = p.data - self.lr * g?Answer
It would bind
p.datato a new array. The model, tied weights, and any checkpoint writer that hold the old array would keep the old weights, so the forward pass would not see the update. The in-place-=modifies the shared array and keeps its dtype. -
Why does
zero_gradsetNoneinstead of zero arrays?Answer
stepskips parameters whosegradisNone: no update, no decay, no buffer. A zero array would still be decayed (the weights would shrink every step) and would get a momentum buffer that keeps moving the parameter from old velocity.Noneis how a frozen or unused parameter says “I did not take part”. -
Why must
state_dictcopy the buffers?Answer
stepupdates the buffers in place (buf *= self.momentum; buf += g). A state dict holding the live arrays would change as training continued, so a checkpoint taken at step 10 would contain step 20’s momentum. Copying makes the checkpoint a snapshot, and resuming from it reproduces the uninterrupted run bit for bit.