SGD momentum and Adam
Quick answer
Stochastic gradient descent (SGD) moves parameters against gradients computed on a batch. Momentum carries information from previous gradients, while Adam adapts updates using estimates of the first and second moments. AdamW applies weight decay separately from the adaptive gradient update. Examples are static Python snippets tested locally on PyTorch CPU. ByteMind execution is unverified.
Momentum on two gradients
import torchw=torch.nn.Parameter(torch.tensor(2.,dtype=torch.float64))o=torch.optim.SGD([w],lr=.1,momentum=.5)for g in [3.,1.]: w.grad=torch.tensor(g,dtype=w.dtype); o.step() print(round(w.item(),4))Expected output (locally tested): 1.7 1.45. The buffer is 3 then 2.5, so the second step subtracts 0.25.
How it works
For learning rate eta and gradient g, plain SGD updates w <- w - etag. With momentum mu and zero initial buffer, v <- muv + g, then w <- w - etav (PyTorch SGD with dampening=0). Nesterov uses g + muv as the update direction under PyTorch’s convention. Adam tracks m <- beta1m+(1-beta1)g and s <- beta2s+(1-beta2)gg; bias-correct by dividing by 1-beta1t and 1-beta2t, respectively. Update by etam_hat/(sqrt(s_hat)+eps). Adam with coupled L2 adds lambdaw to g before updating moments; AdamW instead multiplies w by (1-etalambda) separately from the adaptive step. These differ even at zero task gradient. Defaults vary; specify learning rate, decay and betas explicitly. Batch size controls gradient noise and updates per epoch; compare update counts as well as epochs. An optimizer owns state; replacing it resets that state.
Coupled versus decoupled decay
import torchfor cls in [torch.optim.Adam,torch.optim.AdamW]: w=torch.nn.Parameter(torch.tensor(2.,dtype=torch.float64)); w.grad=torch.zeros_like(w) o=cls([w],lr=.1,weight_decay=.2); o.step() print(cls.__name__,round(w.item(),4))Expected output (locally tested): Adam 1.9 AdamW 1.96. Adam feeds decay into the adaptive moments; AdamW shrinks by 1-0.1*0.2.
Common mistakes
Do not interpret momentum as simply multiplying the learning rate, or treat Adam and AdamW as identical. A zero-valued gradient tensor is different from a missing gradient: parameters with grad=None can be skipped entirely.
Practice and next steps
Predict the next two scalar updates before running them. Inspect optimizer state after each update; use a fresh parameter and optimizer for each comparison.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
SGD momentum and Adam — knowledge check
Apply sgd momentum and adam to small examples and debugging scenarios.
What does momentum retain?
What changes when switching from full batch to mini-batches at fixed epochs?
Which optimizer separates weight decay from adaptive moments?
Why bias-correct Adam moments?
What may happen to a parameter with grad=None?