Unit 3.5 · about 5 h
189 / 324Optimizers from SGD to AdamW
The optimizer is the difference between a loss that falls and one that stalls or explodes. Its state also persists across restarts, so a wrong mental model corrupts both training and resume.
- derive
- implement
You can now
- Write the SGD, heavy-ball momentum, Nesterov, AdaGrad, RMSProp, Adam and AdamW updates with their state.
- Derive the effective step of momentum and the bias correction of Adam.
- Implement momentum and AdamW from primitives and match reference trajectories on a quadratic.
Covers
- SGD, momentum and Nesterov intuition
- AdaGrad and RMSProp recognition and failure regimes
- Adam and AdamW state and update equations
Study, in this order
6 steps
- Optimizers from GD to AdamUnderstanding Deep Learning - fitting, gradients and regularization
Chapter 6, Sections 6.1 through 6.4 (pp. 77 to 90): gradient descent, SGD, momentum with Nesterov, and Adam with bias correction
- Momentum (heavy-ball form)D2L - optimization and regularization slice
The Momentum Method and Effective Sample Weight: heavy-ball update and the \(\eta/(1-\beta)\) effective step; Theoretical Analysis
- AdaGrad recognition and failure regimeD2L - optimization and regularization slice
Sparse Features, Preconditioning and The Algorithm: accumulating denominator and its decay
- RMSProp recognition and failure regimeD2L - optimization and regularization slice
The Algorithm: leaking average fix for the unbounded denominator
- Adam with bias correctionD2L - optimization and regularization slice
The Algorithm and Yogi: bias correction and the divergence fix
- AdamW state and update equationsPyTorch torch.optim.AdamW reference
AdamW algorithm box: decoupled decay step, moments, corrections and defaults
Focus on
- UDL writes momentum as an exponential average of gradients, while D2L and PyTorch use heavy-ball \(v \leftarrow \beta v + g\). Same direction, different scale: heavy-ball steps larger by \(1/(1-\beta)\).
- AdaGrad divides by the root of all past squared gradients, so its steps decay toward zero even far from the optimum on dense problems. RMSProp's leaking average keeps the denominator current.
- Adam debiases both moments because zero initialization drags early averages toward zero. For \(\beta_1 = 0.9\) the correction fades within a few dozen steps; for \(\beta_2 = 0.999\) it still multiplies \(v\) by about 10 at step 100 (\(1 - 0.999^{100}\) is about 0.095) and fades only after a few thousand steps.
- AdamW applies weight decay before the adaptive step, outside \(m\) and \(v\). The decay rate then means the same thing at every coordinate regardless of gradient scale.
Reproduce closed-book
Traps
- Mixing UDL and PyTorch momentum hyperparameters. \(\beta\) 0.9 means an effective step 10 times larger under heavy-ball than under UDL's averaged form at the same \(\eta\).
- Carrying a learning rate between SGD and Adam. Adam moves each coordinate by about
lrregardless of gradient scale, while an SGD step scales with the gradient, so a good SGD rate says nothing about a good Adam rate. - Tuning Adam's
weight_decayas if it were L2 strength. In plain Adam the penalty enters the moments; switch to AdamW for decoupled meaning.
Practice
Deep-ML 169: Implement AdamW Optimizer Step
Problem 169: implement the decoupled AdamW step; cross-check the decay placement against the PyTorch AdamW reference
This is the section's single Deep-ML drill; use changed constants and verify the decay sits outside the moments.
Exercises: the bias-correction-free rewrite and the Adam-diverges and Yogi-converges case
Self-test
-
Heavy-ball momentum \(\beta\) 0.9, \(\eta\) 0.1, constant gradient \(g\). What is the steady-state step?
\(v\) settles at \(g/(1-0.9) = 10g\), so the step is 0.1 times \(10g = g\). The effective learning rate is 10 times the nominal one. -
Why does AdaGrad stall on dense deep-learning objectives, and what does RMSProp change?
Its denominator sums every past squared gradient and grows without bound, driving per-coordinate rates toward zero. RMSProp replaces the sum with a leaking average at \(\gamma\) 0.9, so old gradients stop counting. -
Adam's first step on gradient 2 with default betas and \(\eta\) 0.001 is about 0.001 regardless of gradient size. Show why.
\(m_1 = 0.1 \times 2 = 0.2\), \(v_1 = 0.001 \times 4 = 0.004\); corrected \(m = 2\), \(v = 4\); update \(0.001 \times 2/(2+\epsilon)\), about 0.001. Debiasing restores the gradient scale, so the step is \(\eta\) times the sign. -
AdamW
weight_decay0.01,lr0.001. How much does a weight of 0.5 shrink per step from decay alone?\(\theta \leftarrow \theta - 0.001 \times 0.01 \times 0.5 = 0.5 - 0.000005\). The shrinkage is proportional to the weight and independent of gradient history.
Completion criterion
Stop when
Your from-scratch momentum and AdamW match the framework step for step on a quadratic, and you convert a \(\beta\) between UDL and heavy-ball forms without notes.
Mark passed, then open 3.6 Only mark this when you can do it without notes.Leads to
- 3.6 Schedules, gradient accumulation and clipping Schedule the learning rate and scale the batch around the optimizer you just built.
- 3.8 Diagnosing failed runs: divergence, stale state, slices and seeds Turn stalled or diverging optimizer behavior into ordered repair drills.
Comes after
- 5.2 Gradient descent, stochastic gradients and momentumApply these update and state tests to neural-network training.
- 5.3 Adaptive optimizers, schedules, clipping and stoppingUse the bias and decay derivations beneath the later optimizer comparison.
- 3.4 Regularization: dropout, label smoothing, augmentation and weight decaySee the decoupled AdamW update that completes the weight-decay story.
Resources for this unit
- Understanding Deep Learning - fitting, gradients and regularization Use Chapters 6-9 and targeted parts of Chapter 20 for optimization, initialization, measurement, regularization and why training works. Re-derive the update rules you keep in the trainer.
- D2L - optimization and regularization slice Use MLP implementation, dropout, deep generalization, numerical stability, optimization introduction, SGD, minibatch SGD, momentum, AdaGrad, RMSProp, Adam and learning-rate scheduler. Implement momentum, AdamW, initialization, dropout, one normalization, clipping and one schedule.
- PyTorch torch.optim.AdamW reference Read the AdamW algorithm box for the decoupled weight-decay step, the bias-corrected moments and the defaults, and follow the Decoupled Weight Decay Regularization link for the argument.
Also in this section
- PyTorch - optimization and automatic mixed precision examples Check optimizer, scheduler, gradient clipping and AMP API semantics. Preserve the correct order for zeroing, scaling, backward, unscaling, clipping, stepping and updating.
- Deep-ML candidate - optimization and normalization problems After the platform admission check, use at most one of 146 Momentum, 169 AdamW, 197 Global-Norm Clipping, 109 LayerNorm or 115 BatchNorm as a changed-prompt drill.
- TrenTorch - training mechanics questions Solve only the questions the units name: Weight Initialization, Layer Normalization, Label Smoothing, Gradient Accumulation, and Warmup and Cosine Decay. Read the tests first; they run in the browser IDE.
- PyTorch GroupNorm reference Read how input channels are split into
num_groupsgroups and which axes each group normalizes; comparenum_groups1 againstnum_channels. - PyTorch RMSNorm reference Read the RMS formula and which axes
normalized_shapecovers; note the missing mean centering and bias. - PyTorch CrossEntropyLoss reference Read Shape, Parameters (
weight,ignore_index,reduction,label_smoothing) and both Examples; extend the class-index example withignore_indexand a classweight. - Cyclical Learning Rates for Training Neural Networks (Smith, 2017) Read the abstract and the range test: increase the rate linearly for a few epochs and read usable bounds off the loss curve.
- Deep Learning Tuning Playbook FAQ: debugging optimization failures Read How can optimization failures be debugged and mitigated (identifying unstable workloads, warmup, clipping) and Batch normalization implementation details.
- Hands-On Machine Learning with Scikit-Learn and PyTorch Read the Chapter 11 sections named in the units for the PyTorch side of initialization, normalization, clipping and schedules.