Lecture 12 · Optimizer Fundamentals

Scalable AI: Bridging Theory, Understanding, and Practice · Lecture 12。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: UC Berkeley EE 290/194 Scalable AI, Spring 2026 Lecture 9, Optimizer Fundamentals (slides lecture9.pdf, slides from Gireeja Ranade): SGD, momentum, sign descent, Adam and AdamW, steepest descent under norms, induced norms, Shampoo and Muon in outline, and µP learning-rate scaling. Also drawn on: Fall 2026 Lecture 8 §2, The training step (schedules, optimizer set-up, batch size). Muon, Shampoo and their systems side are the subject of Lecture 13. Recommended reading: Kingma and Ba, Adam (arXiv:1412.6980); Loshchilov and Hutter, Decoupled Weight Decay Regularization (AdamW, arXiv:1711.05101); Bernstein and Newhouse, Old Optimizer, New Norm (arXiv:2409.20325); McCandlish et al., An Empirical Model of Large-Batch Training (arXiv:1812.06162); Yang et al., Tensor Programs V (µP, arXiv:2203.03466); Chen et al., Symbolic Discovery of Optimization Algorithms (Lion, arXiv:2302.06675). Code: code/lecture12/ contains optim_lab.py (optimizers from scratch, checked against torch.optim; clipping, steepest-descent directions, quadratics, the gradient noise scale) and seven demos on Lecture 9’s Atlas World models. Reading time: ~2.5 hours for the prose; ~7 minutes to run all demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Write the optimizers down. SGD, momentum, sign descent, Adam (with bias correction), Adam + L2 vs AdamW, Lion. Say what each stores and costs in memory.

  2. Explain them geometrically. A step is the steepest descent direction inside a norm ball:

    • ℓ2\ell_2 gives the normalized gradient;
    • ℓ∞\ell_\infty gives sign descent, whose smoothed version is Adam;
    • the spectral norm gives UV⊤UV^\top (Muon).

    You should also be able to explain why plain GD is capped by the sharpest direction, and why Adam’s per-coordinate scaling helps when curvature lines up with the coordinates.

  3. Set the schedule. Warm-up, cosine vs WSD, and what WSD’s branching cooldowns buy.

  4. Get the numerics right. When ε matters; why BF16 optimizer states depend on β₂; stochastic rounding for BF16 weights.

  5. Choose a batch size. The gradient noise scale and the critical batch size; why bigger batches stop paying.

  6. Use weight decay correctly. Decoupled vs coupled; equilibrium weight sizes; the timescale 1/(ηλ)1/(\eta\lambda) and WSD.

  7. Derive µP’s learning-rate rule. Do it from the RMS-to-RMS norm, and say why the rule depends on the optimizer.

0.2 Prerequisites and scope

  • Prerequisites: Lecture 9 (AdamW settings, schedules, µP measured, numerics of mixed precision); calculus and linear algebra (gradients, eigenvalues, the SVD).
  • Scope: first-order optimizers and their geometry; schedules and warm-up; clipping; optimizer numerics; batch size; weight decay; µP’s derivation.
  • Not in scope today: Muon, Newton–Schulz, Shampoo, SOAP and Kron in depth, and optimizers at scale (sharded states, matrix owners): Lecture 13.

0.3 Section → code map

SectionIdeaCode in code/lecture12/
§1SGD, momentum, sign descent, Adam, AdamW, Lion; checked; compared; memoryoptim_lab.py, 01_optimizers_from_scratch.py
§2steepest descent under norms; conditioning; why Adam helps02_geometry_of_steps.py
§3warm-up, cosine, WSD, branching cooldowns, clipping03_schedules_and_warmup.py
§4ε, BF16 moments, stochastic rounding04_numerics.py
§5gradient noise scale, critical batch size05_batch_size.py
§6decoupled weight decay, equilibrium, 1/(ηλ)1/(\eta\lambda)06_weight_decay.py
§7the µP derivation07_mup_derivation.py

0.4 Notation

  • ww or θ\theta = parameters; g=∇wLg = \nabla_w \mathcal{L}; η\eta = learning rate.
  • β1,β2\beta_1, \beta_2 = Adam’s averaging factors; ϵ\epsilon = Adam’s epsilon; λ\lambda = weight decay.
  • BB = batch size.
  • ∥⋅∥2\lVert\cdot\rVert_2 for a matrix = its largest singular value (spectral norm).
  • κ\kappa = condition number (largest / smallest curvature).

1. The optimizers, written out

1.1 SGD and its two problems

wt+1=wt−η 1∣Bt∣∑i∈Bt∇wL(yi,fw(xi)).w_{t+1} = w_t - \eta\,\frac{1}{|B_t|}\sum_{i \in B_t} \nabla_w \mathcal{L}(y_i, f_w(x_i)).

SGD can be thought of as gradient descent with noise, and it shares GD’s pros and cons. The slide names one of each:

  • Pro: implicit regularization. Combined with early stopping, there is less movement along directions with small singular values.
  • Con: one learning rate for everything. It is bottlenecked by the largest singular value (to avoid instability), so directions with “medium” singular values make slow progress.

Section 2 makes the second point exact.

1.2 Momentum

mt+1=βmt+(1−β)∇wL(wt)m_{t+1} = \beta m_t + (1-\beta)\nabla_w \mathcal{L}(w_t), wt+1=wt−η mt+1w_{t+1} = w_t - \eta\, m_{t+1} (the slide’s EMA form). PyTorch’s form, b=μb+gb = \mu b + g, differs only by a factor absorbed into η\eta.

Averaging smooths the trajectory: components that flip sign from step to step cancel, and consistent ones accumulate. That permits larger learning rates and faster convergence on ill-conditioned problems (§2.3).

1.3 The spirit of sign descent

The dream is a different learning rate for each singular direction, so everything converges at once with no bottleneck. What is achievable cheaply is coordinate-wise normalization:

wt+1=wt−η sign(∇L)  ≈  wt−η ∇L(∇L)2+ϵ,w_{t+1} = w_t - \eta\,\text{sign}(\nabla \mathcal{L}) \;\approx\; w_t - \eta\,\frac{\nabla \mathcal{L}}{\sqrt{(\nabla \mathcal{L})^2} + \epsilon},

with every operation elementwise: equal-sized steps per coordinate. The caveat is that near an optimum the signs flip and the iterate bounces. Learning-rate decay solves this, one reason schedules end with a decay (§3).

1.4 Adam: momentum plus sign descent

Two exponential moving averages:

  • the first moment (the gradient) mm, with less averaging, β1=0.9\beta_1 = 0.9;
  • the second moment (the squared gradient) vv, with more averaging, β2=0.95\beta_2 = 0.95–0.9990.999.

mt+1=β1mt+(1−β1)gt,vt+1=β2vt+(1−β2)gt2,m_{t+1} = \beta_1 m_t + (1-\beta_1) g_t,\qquad v_{t+1} = \beta_2 v_t + (1-\beta_2) g_t^2, m^=mt+11−β1t+1,v^=vt+11−β2t+1,wt+1=wt−η m^v^+ϵ.\hat m = \frac{m_{t+1}}{1-\beta_1^{t+1}},\quad \hat v = \frac{v_{t+1}}{1-\beta_2^{t+1}},\qquad w_{t+1} = w_t - \eta\,\frac{\hat m}{\sqrt{\hat v} + \epsilon}.

Bias correction. mm and vv start at zero, so early estimates are biased toward zero. Without correction, the first update is (1−β1)/1−β2(1-\beta_1)/\sqrt{1-\beta_2} times the intended one (demo 01 Part D):

  • 3.16× too large for β2=0.999\beta_2 = 0.999;
  • 0.45× too small for β2=0.95\beta_2 = 0.95.

The error fades only as vv fills, over about 1/(1−β2)1/(1-\beta_2) steps; with β2=0.999\beta_2 = 0.999 the uncorrected step is still 6.1× the corrected one at step 6. Warm-up (§3) hides much of this.

Memory. SGD stores the weights (1×); momentum adds a buffer (2×); Adam adds two (3×). Under mixed precision (BF16 weights and gradients, FP32 master weights), demo 01 Part C counts:

optimizeroptimizer statebytes / parameterfor 405B parameters
SGD—83.24 TB
momentum, signum, Lionone FP32 buffer124.86 TB
Adam / AdamWmm and vv in FP32166.48 TB

Lion keeps the sign-descent idea plus momentum. It avoids storing the squared gradient by “dithering” between momentum and the current gradient: u=sign(β1m+(1−β1)g)u = \text{sign}(\beta_1 m + (1-\beta_1) g). The slide’s warning: with Lion you must change the weight decay (and the learning rate, about 3× lower in demo 01).

1.5 AdamW: decoupled weight decay

If λw\lambda w is added to the gradient (L2 regularization), it passes through Adam’s normalization by v\sqrt v. That couples the learning rate and the regularization strength in an undesirable way. AdamW decouples them:

wt+1=(1−ηλ) wt−η m^v^+ϵ.w_{t+1} = (1 - \eta\lambda)\, w_t - \eta\,\frac{\hat m}{\sqrt{\hat v} + \epsilon}.

The difference is not subtle. In demo 01, at the same λ=0.1\lambda = 0.1, Adam + L2 ends at 2.195 bits/byte and AdamW at 0.818 (§6 explains why). The slide adds that λ\lambda should be moved together with η\eta in WSD schedules (§6.3).

1.6 Checked and compared

optim_lab.py writes each optimizer out in a few lines.

  • Exactness. The self-test matches torch.optim.SGD, AdamW and Adam to 10−1210^{-12} over 50 steps in float64.
  • On a real run. In float32 on a 300-step LM run (demo 01 Part A), AdamW’s weights differ by at most 3.8×10−53.8 \times 10^{-5} from rounding order, and the validation loss is identical (0.8182). SGD at a high learning rate amplifies the same rounding to 9×10−39 \times 10^{-3}, with identical final quality.

Demo 01 Part B gives each optimizer its best of four learning rates on the same model and data (validation bits/byte; floor 0.718):

optimizerbest lrval bits/byte
SGD1.01.009
SGD + momentum 0.90.30.889
signum (sign of momentum)3e-30.820
Lion (wd 0.1)3e-30.807
AdamW (wd 0.1)1e-20.804
Adam (no decay)1e-20.801

Plain SGD is far behind; per-coordinate normalization (sign descent, Lion, Adam) closes most of the gap. The next section explains why.


2. A shift in perspective: the geometry of a step

2.1 Steepest descent in a norm ball

Take the linear (first-order Taylor) model of the loss, L(θ+Δθ)≈L(θ)+g⊤Δθ\mathcal{L}(\theta + \Delta\theta) \approx \mathcal{L}(\theta) + g^\top\Delta\theta. Choosing a step balances two competing goals:

  • safety: steps small enough that the linear approximation holds;
  • progress: steps large enough to converge quickly.

As an optimization problem (Bernstein and Newhouse):

u=arg⁡min⁡∥Δθ∥≤η  g⊤Δθ.u = \arg\min_{\lVert\Delta\theta\rVert \le \eta}\; g^\top \Delta\theta.

The answer depends on which norm defines “small”:

normthe ballbest stepvalue =−η ∥g∥dual= -\eta\,\lVert g\rVert_{\text{dual}}
ℓ2\ell_2a sphere−η g/∥g∥2-\eta\, g/\lVert g\rVert_2 (normalized GD)−η∥g∥2-\eta\lVert g\rVert_2
ℓ∞\ell_\inftya box: no parameter changes by more than η\eta−η sign(g)-\eta\,\text{sign}(g) (sign descent)−η∥g∥1-\eta\lVert g\rVert_1
spectral, for a matrix G=UΣV⊤G = U\Sigma V^\top∥ΔW∥2≤η\lVert\Delta W\rVert_2 \le \eta−η UV⊤-\eta\, UV^\top (orthogonalized update)−η∑iσi-\eta\sum_i\sigma_i (nuclear norm)
  • ℓ2\ell_2. Cauchy–Schwarz gives the closed form. With a penalty instead of a constraint, you get back classic GD.
  • ℓ∞\ell_\infty. A box pushes every coordinate to its limit, which is why sign descent is a natural steepest-descent rule.
  • Spectral. The slide’s proof: write Tr(G⊤B)=∑iσi ui⊤Bvi\text{Tr}(G^\top B) = \sum_i \sigma_i\, u_i^\top B v_i; if ∥B∥2≤1\lVert B\rVert_2 \le 1 then every ∣ui⊤Bvi∣≤1|u_i^\top B v_i| \le 1. The bound is achieved by B=UV⊤B = UV^\top: keep the directions, drop the magnitudes. This is the matrix analogue of sign descent.

Demo 02 Part A checks all three on a random 6 × 4 gradient. Each closed-form step achieves exactly minus the dual norm (−5.09, −21.90, −9.04), and none of 20,000 random unit steps does better.

Why parameter-space norms might not be enough. A step that is small in parameter space need not be small in function space: ΔW\Delta W small does not imply Δ(Wx)\Delta(Wx) small for typical xx. What we care about is stable activations across layers, bounded changes of outputs for typical inputs, and invariance to width. That leads to induced norms, ∥ΔW∥p→q=max⁡∥x∥p≤1∥ΔWx∥q\lVert\Delta W\rVert_{p\to q} = \max_{\lVert x\rVert_p \le 1}\lVert\Delta W x\rVert_q, and to the RMS-to-RMS norm of §7. Muon and µP come out of this view.

Shampoo’s identity. (GG⊤)−1/4 G (G⊤G)−1/4=UV⊤(GG^\top)^{-1/4}\, G\, (G^\top G)^{-1/4} = UV^\top. Matrix roots can be computed iteratively with GEMMs, which is fast on GPUs, and the factors can be cached and updated as EMAs across steps; that is Shampoo. Muon computes UV⊤UV^\top of the momentum with Newton–Schulz iterations. Both are Lecture 13.

2.2 Gradient descent is capped by the sharpest direction

On a quadratic f(x)=12(x−x⋆)⊤H(x−x⋆)f(x) = \tfrac12(x - x^\star)^\top H (x - x^\star) with eigenvalues λi\lambda_i, GD multiplies the error along eigenvector ii by (1−ηλi)(1 - \eta\lambda_i) each step. It diverges if η>2/λmax\eta > 2/\lambda_{max}; the slowest direction then converges like (1−2λmin/λmax)t(1 - 2\lambda_{min}/\lambda_{max})^t, so GD needs on the order of κ\kappa steps.

Demo 02 Part B uses 40 dimensions, κ=1,000\kappa = 1{,}000 and 500 steps:

step size0.5/λmax0.5/\lambda_{max}1/λmax1/\lambda_{max}1.9/λmax1.9/\lambda_{max}2.05/λmax2.05/\lambda_{max}
final / initial loss1.2e-33.7e-48.4e-52.5e+20 (diverged)

At 1.9/λmax1.9/\lambda_{max}, the flattest direction (λ=0.001\lambda = 0.001) has covered only 61% of the way, exactly as ∣1−ηλ∣t|1 - \eta\lambda|^t predicts, while the sharp directions converged to machine precision long ago.

2.3 Momentum and per-coordinate scaling

Each method gets its best learning rate, 500 steps (demo 02 Part C):

methodaxis-aligned curvaturerotated curvature
GD1.0e-47.3e-5
heavy-ball momentum1.4e-207.8e-21
sign descent (signum)8.8e-142.1e-08
Adam4.9e-269.2e-09
  • Momentum needs on the order of κ\sqrt\kappa steps, and like GD it is rotation-invariant. (The small differences between columns come from where the start point lies relative to the eigenvectors.)
  • Sign descent and Adam scale every coordinate separately, a diagonal preconditioner (对角预条件). When the curvature is axis-aligned, that matches it exactly and Adam reaches 4.9e-26. After a random rotation, the same Adam reaches only 9.2e-9: still better than GD thanks to momentum and a decaying rate, but a 10¹⁷-fold advantage is gone.

So why does Adam work for neural networks? Their Hessians are roughly block-structured: by layer, by neuron, by embedding row. Per-coordinate scaling captures much of the curvature, but not the correlations inside a weight matrix. That is what matrix-aware optimizers (Shampoo, Muon) add.


3. Schedules, warm-up and clipping

3.1 Why warm-up and why decay

  • Warm-up. Early in training the weights are poorly calibrated and Adam’s moment estimates are empty or noisy (§1.4), so large updates can destabilize activations and gradients. Warm-up raises the rate gradually; Llama 3 405B used 8,000 steps. The Spring slides call warm-up “not optional at scale”.
  • Decay. Sign-like steps bounce near an optimum (§1.3), and the noise in SGD-type updates has a floor set by the learning rate. Decaying η\eta at the end lowers both.
  • Two shapes of decay. Cosine decays over a fixed horizon. WSD (warm-up, stable, decay) holds the peak, then decays at the end (the “cooldown”).

Debugging tip (Spring slides): when a run diverges, check the actual learning rate vs the intended one, the scheduler state after a resume, and whether the effective batch size changed.

3.2 Measured (demo 03)

Five schedules, 600 steps, same model and data:

schedulefinal val bits/bytetrain loss, steps 461–480train loss, last 20 steps
constant after warm-up0.79341.8211.845
cosine to 10%0.77011.7661.788
WSD, last 10% decays0.77921.8211.811
WSD, last 20% decays0.77551.8211.799
WSD, last 40% decays0.77181.7931.791

The decay is where the gain appears. Before its decay starts, the WSD-20% run is identical to the constant run (1.821). Over the last 120 steps its loss falls to 1.799, while the constant run’s drifts to 1.845. In this short run cosine is best, and longer WSD decays close most of the gap.

WSD’s real advantage is that you choose when to stop. Demo 03 Part B runs one stable run and branches a 20% cooldown off it at three horizons:

horizonWSD branchdedicated cosine run
300 steps0.79580.7969
600 steps0.77550.7701
900 steps0.76460.7610

That is a finished model at every horizon for 1,080 training steps instead of 1,800, within a few thousandths of the dedicated runs. This is why Marin and Nemotron 3 Ultra use WSD, and why Nemotron could start its decay early after a divergence (Lecture 9 §5.4).

3.3 Warm-up and clipping at a high learning rate

At 10× the tuned rate (demo 03 Part C):

runloss ~step 10~step 100final val bits/byte
warm-up 60, clip 1.05.113.140.924
no warm-up, clip 1.04.933.751.149
warm-up 60, no clipping5.123.300.942
no warm-up, no clipping5.073.891.189

Skipping warm-up does not show up at first: the no-warm-up run even has the lower loss at step 10, and a similar peak gradient norm. But it ends far worse. Full-size steps taken while weights and moment estimates are poorly scaled put the model somewhere it does not recover from at this learning rate. Clipping does not substitute for warm-up. It bounds single bad steps (Lecture 9’s data spike), not a systematically too-large rate.

Clipping, precisely. Global-norm clipping rescales all gradients together so that ∑i∥gi∥2≤c\sqrt{\sum_i \lVert g_i\rVert^2} \le c (typically c=1.0c = 1.0), preserving the gradient’s direction. Log the norm before clipping. optim_lab.clip_global_norm matches torch.nn.utils.clip_grad_norm_.


4. Numerics of the optimizer step

ε. Adam’s steady-state step for a constant gradient gg is η ∣g∣/(∣g∣+ϵ)\eta\,|g|/(|g| + \epsilon):

∣g∣\lvert g\rvertϵ=10−8\epsilon = 10^{-8}10−510^{-5}10−310^{-3}
1e-21.0000.9990.909
1e-41.0000.9090.091
1e-50.9990.5000.010
1e-60.9900.0910.001

ϵ\epsilon only matters when gradients are comparable to it, but then it turns Adam into slow SGD for exactly the parameters with the smallest gradients. Demo 04 measures against a noise floor: three seeds of the same run span 0.0029 bits/byte. In this tiny model 26.7% of gradient entries are below 10−510^{-5}, yet ϵ=10−5\epsilon = 10^{-5} changes the result by −0.0021, within the noise; only ϵ=10−3\epsilon = 10^{-3} hurts (+0.0171). Large models have far smaller per-parameter gradients, which is why OLMo 2’s move from 10−510^{-5} to 10−810^{-8} mattered at 7B (Lecture 9 §5.4).

BF16 optimizer states. Storing mm and vv in BF16 saves half their memory. But vv‘s update moves it by (1−β2)(1 - \beta_2) of the gap per step. For β2=0.999\beta_2 = 0.999 that is 0.1%, below BF16’s 0.4% resolution, so vv stops tracking the gradient: one BF16 update of v=1.0v = 1.0 toward 1.2 gives 1.0000 instead of 1.0002. For β2=0.95\beta_2 = 0.95 the 5% step survives. In demo 04’s 300-step runs the effect stays within the noise floor (+0.0012 for β2=0.999\beta_2 = 0.999). The mechanism is real; whether it bites depends on the run. Low-precision states need the averaging horizon to fit the format.

BF16 weights and stochastic rounding. Lecture 9 showed that round-to-nearest BF16 weights lose small updates. Demo 04 Part C confirms it at Lecture 9’s learning rate (3e-3):

  • 72.9% of entries are unchanged by a late update, costing +0.0205 bits/byte (beyond the 0.0039 noise floor).
  • Stochastic rounding rounds up with probability proportional to the distance, so an update below half a BF16 step still moves the weight on average. It recovers the loss (+0.0005, within noise).
  • Stochastic rounding is a way to drop the FP32 master copy (4 bytes per parameter) at the cost of noise.

At 3× the learning rate the updates are larger and round-to-nearest loses less.


5. Batch size and the critical batch size

Why there is a critical batch size. A minibatch gradient is the true gradient GG plus noise with covariance Σ/B\Sigma/B. Two regimes follow:

  • Noise dominates (small BB): doubling BB halves the noise and nearly halves the steps needed.
  • The true gradient dominates (large BB): more examples per step barely change the step, so tokens are wasted.

McCandlish et al. model this as

S(B)=Smin(1+BnoiseB),E(B)=B S(B)=Emin(1+BBnoise),S(B) = S_{min}\left(1 + \frac{B_{noise}}{B}\right),\qquad E(B) = B\,S(B) = E_{min}\left(1 + \frac{B}{B_{noise}}\right),

where SS is steps and EE is examples to reach a target loss. The critical batch size (临界批大小) Bcrit≈BnoiseB_{crit} \approx B_{noise} is where both costs are twice their minimum. A cheap estimate is the simple noise scale

Bsimple=tr(Σ)∣G∣2,B_{simple} = \frac{\text{tr}(\Sigma)}{\lvert G\rvert^2},

measured from the spread of several small-batch gradients (optim_lab.noise_scale).

Demo 05 Part A measures it during a run:

step0501002006001,200
loss6.243.222.181.911.831.80
BsimpleB_{simple} (sequences of 64 tokens)11.122.047.445.291.094.4

The noise scale grows as the loss falls. Early on, every example’s gradient points roughly the same way. Later, the true gradient shrinks relative to per-example noise. So runs start with small batches and ramp up (Llama 3 405B: 4M → 8M → 16M tokens), and the critical batch grows with compute.

Demo 05 Part B measures steps to a fixed loss with learning rate 3×10−3B/163 \times 10^{-3}\sqrt{B/16}:

batch (sequences)48163264128256
steps to target287184126101877873
tokens / EminE_{min}1.33×1.70×2.33×3.73×6.43×11.5×21.6×

The fit gives Smin=72S_{min} = 72 steps and Bcrit=12B_{crit} = 12 sequences (766 tokens), and it matches every point to within 4 steps. Past BcritB_{crit}, doubling the batch saves a few steps and doubles the tokens. At 256 sequences the run spends 21.6× the minimum tokens.

The noise scale near the target loss (47 sequences) is within a factor of 4 of the fitted BcritB_{crit}. BsimpleB_{simple} treats all directions alike; the exact noise scale weights them by curvature (tr(HΣ)/G⊤HG\text{tr}(H\Sigma)/G^\top HG), and the two track each other up to a roughly constant factor.

Systems consequences:

  • Data parallelism adds tokens per step, so past BcritB_{crit} each extra GPU buys little progress.
  • Batch size and learning rate interact. Square-root scaling is a common heuristic for Adam; retune when you change BB.
  • A larger critical batch lets a run use more parallelism productively. That is one of Muon’s claimed advantages (Lecture 13), and the slide’s reason why “it is worth amortizing [Muon’s cost] over a larger batch size”.

6. Weight decay

6.1 Coupled vs decoupled

With L2 inside Adam, the decay term λw\lambda w is divided by v\sqrt v. For parameters with small gradients, v\sqrt v is small and the decay becomes a full-size step toward zero. Demo 06 Part A:

optimizerλ\lambdaval bits/byteRMS of attention/MLP weightsRMS of embeddings
no decay00.79780.08710.0932
Adam + L20.011.08330.00810.0153
AdamW0.010.79680.08640.0921
Adam + L20.11.73280.00070.0055
AdamW0.10.79690.08130.0838

AdamW shrinks every weight by the same factor (1−ηλ)(1 - \eta\lambda) per step, independent of its gradient history. That is the fix in Loshchilov and Hutter’s paper, and why every modern recipe uses AdamW. Lecture 9’s set-up also exempts embeddings and norms from decay (OLMo 2).

6.2 Equilibrium weight size

With decay, the weights are pulled toward a balance of updates and shrinkage. A random-walk model predicts an RMS of η/(2λ)\sqrt{\eta/(2\lambda)}: each Adam update adds about η\eta per entry in a random direction, and decay removes 2ηλ2\eta\lambda of w2w^2.

Demo 06 Part B finds the measured RMS within a factor of about 2.6 of that prediction (ratios 0.54–2.56), and not even monotone in η\eta. Two reasons:

  • Adam’s updates are correlated with where the loss wants the weights, not random.
  • With τ=1/(ηλ)\tau = 1/(\eta\lambda) near the run length, some runs have not settled.

For weights followed by a normalization layer, which are scale-invariant, the equilibrium becomes exact in shape. That is the “rotational equilibrium” behind treating weight decay as an angular step size (Lecture 13). Strong decay also costs quality: ηλ=0.1\eta\lambda = 0.1 ends at 2.55 bits/byte.

6.3 The timescale and WSD

AdamW’s weights behave like an exponential moving average of past updates with horizon τ=1/(ηλ)\tau = 1/(\eta\lambda) steps (Wang and Aitchison). If η\eta decays 10× during a WSD cooldown with λ\lambda fixed, τ\tau grows 10× (from 33K to 333K steps in demo 06’s example), and decay effectively switches off. Moving λ\lambda with η\eta keeps the horizon fixed. That is the Spring slide’s instruction to “move it together with the learning rate when doing WSD”.


7. µP: deriving the learning-rate rule

Lecture 9 showed µP working: under SP the best rate drifted from 2−62^{-6} to 2−102^{-10} as width grew 8×, and under µP it stayed at 2−62^{-6}. The Spring slides derive why, from the induced-norm view of §2.1.

7.1 The RMS-to-RMS norm

∥x∥RMS=∥x∥2/d\lVert x\rVert_{RMS} = \lVert x\rVert_2/\sqrt d controls the average per-coordinate scale, the quantity activations, Xavier/He initialization and normalization layers are stated in. The induced norm is

∥A∥RMS→RMS=max⁡∥x∥RMS=1∥Ax∥RMS=dindout  ∥A∥2.\lVert A\rVert_{RMS\to RMS} = \max_{\lVert x\rVert_{RMS} = 1}\lVert Ax\rVert_{RMS} = \sqrt{\frac{d_{in}}{d_{out}}}\;\lVert A\rVert_2.

Demo 07 Part A confirms it by power iteration for three shapes. Layer geometry (din,doutd_{in}, d_{out}) thus enters what counts as a “small” update.

7.2 Adam (sign descent) needs η∝1/din\eta \propto 1/d_{in}

  • Idealize Adam as sign descent. The update is ΔW=−η sign(∇WL)\Delta W = -\eta\,\text{sign}(\nabla_W\mathcal{L}). We want ∥ΔW∥RMS→RMS≤γ\lVert\Delta W\rVert_{RMS\to RMS} \le \gamma for each layer.
  • One input gives a rank-1 gradient. For a linear layer y=Wxy = Wx and batch size 1, ∇WL=(∇yL) x⊤\nabla_W\mathcal{L} = (\nabla_y\mathcal{L})\,x^\top is rank 1. Its sign, sign(u) sign(v)⊤\text{sign}(u)\,\text{sign}(v)^\top, is also rank 1. So ∥S∥2=∥S∥F=dindout\lVert S\rVert_2 = \lVert S\rVert_F = \sqrt{d_{in} d_{out}} (demo 07 Part B: exactly 64, 256 and 1,024 for d=64,256,1024d = 64, 256, 1024).
  • The bound. Then ∥ΔW∥RMS→RMS=ηdindoutdindout=η din≤γ⇒η≤γdin.\lVert\Delta W\rVert_{RMS\to RMS} = \eta\sqrt{\frac{d_{in}}{d_{out}}}\sqrt{d_{in}d_{out}} = \eta\, d_{in} \le \gamma \quad\Rightarrow\quad \eta \le \frac{\gamma}{d_{in}}.
  • Checked. Demo 07 Part C matches η din\eta\, d_{in} to every digit. With η∝1/din\eta \propto 1/d_{in} the change is the same at widths 64 to 4,096.

Takeaway (µP scaling): use η∝1/din\eta \propto 1/d_{in} for weight matrices when using Adam or sign descent. Widening the model while keeping activation RMS comparable keeps each layer’s update size comparable. That makes zero- or few-shot learning-rate transfer possible: sweep on small models, then only refine on big ones.

7.3 On a real batch

A real batch’s gradient is not exactly rank 1. In demo 07 Part D (Lecture 9’s model, 64 × 64 tokens) its stable rank is about 3, so one AdamW step changes the layer by less than ηdin\eta d_{in}, but the scaling survives:

width3264128256
SP: ∥ΔW∥RMS→RMS\lVert\Delta W\rVert_{RMS\to RMS}0.2040.3570.7011.309
µP0.2040.1790.1750.164

Under SP the change grows 6.4× from width 32 to 256; under µP it stays roughly flat. This is the mechanism behind Lecture 9’s sweep.

7.4 Careful: the math changes with the optimizer

The slide’s warning: without the underlying reasoning, one can mistake the scaling for a fixed formula.

For SGD, the batch-1 gradient has ∥∇WL∥F2=∥g∥2∥x∥2∼din/dout\lVert\nabla_W\mathcal{L}\rVert_F^2 = \lVert g\rVert^2\lVert x\rVert^2 \sim d_{in}/d_{out} (assuming later layers keep activations controlled), so ∥∇WL∥2∼din/dout\lVert\nabla_W\mathcal{L}\rVert_2 \sim \sqrt{d_{in}/d_{out}}. A “maximal” update wants ∥η∇WL∥2∼dout/din\lVert\eta\nabla_W\mathcal{L}\rVert_2 \sim \sqrt{d_{out}/d_{in}}, giving

ηSGD∼doutdin,\eta_{SGD} \sim \frac{d_{out}}{d_{in}},

which depends on shape, not scale, unlike Adam’s 1/din1/d_{in}.

Initialization from the same viewpoint. Xavier/He variance 1/din1/d_{in} keeps the expected RMS constant with depth. A safer target bounds the worst-case amplification, ∥W∥2∼dout/din\lVert W\rVert_2 \sim \sqrt{d_{out}/d_{in}}. With i.i.d. entries of variance σ2\sigma^2, the Frobenius energy σ2dindout\sigma^2 d_{in}d_{out} spread over min⁡(din,dout)\min(d_{in}, d_{out}) singular values gives

σ2∼min⁡(din,dout)din2.\sigma^2 \sim \frac{\min(d_{in}, d_{out})}{d_{in}^2}.

Demo 07 Part E checks this. Xavier overshoots the target most when the output is narrow (2.99× for a 256 × 1024 matrix). The “safe” variance halves that (1.50×) and keeps every shape within a factor of about 2. That remaining factor comes from the random-matrix edge, σ(din+dout)\sigma(\sqrt{d_{in}} + \sqrt{d_{out}}).

Muon uses the same constraint, but computes the semi-orthogonal direction dout/din UV⊤\sqrt{d_{out}/d_{in}}\,UV^\top directly instead of relying on sign descent’s rank-1 approximation. Lecture 13 continues from here.


8. Summary

  1. The optimizers are short. SGD, momentum (smooth, accelerate), sign descent (per-coordinate normalization), Adam = momentum + sign-like normalization + bias correction, AdamW = decoupled decay, Lion = signed momentum with one state. Adam costs 16 bytes per parameter under mixed precision. From-scratch versions match torch.optim to 10−1210^{-12}.
  2. Geometry. Steepest descent under ℓ2\ell_2, ℓ∞\ell_\infty and the spectral norm gives normalized GD, sign descent and UV⊤UV^\top. GD is capped at 2/λmax2/\lambda_{max} and needs about κ\kappa steps; momentum needs about κ\sqrt\kappa. Adam’s diagonal preconditioning is huge when curvature is axis-aligned and modest when it is not.
  3. Schedules. The gain comes in the decay. WSD gives a finished model at any horizon by branching cooldowns off one stable run (1,080 vs 1,800 steps for three horizons). Warm-up protects the start, and clipping does not replace it.
  4. Numerics. ε matters only for gradients comparable to it. BF16 moments fail when 1−β21 - \beta_2 is below BF16’s resolution. Round-to-nearest BF16 weights lose small updates (+0.02 bits/byte beyond noise), and stochastic rounding recovers them. Always compare against a noise floor.
  5. Batch size. The noise scale grows as the loss falls (11 → 94 sequences). Past the critical batch (12 sequences here), bigger batches waste tokens (21.6× the minimum at 256).
  6. Weight decay. Use decoupled decay: Adam + L2 at λ=0.1\lambda = 0.1 ruined the model (1.733 vs 0.797). Weights equilibrate on a scale set by η/λ\eta/\lambda, and the memory horizon 1/(ηλ)1/(\eta\lambda) says to move λ\lambda with η\eta.
  7. µP. In RMS-to-RMS norm, a sign step changes a layer by η din\eta\, d_{in}, so Adam needs η∝1/din\eta \propto 1/d_{in}, while SGD needs dout/dind_{out}/d_{in}. The rule is derived from the optimizer, not memorized.

9. Common pitfalls

  • Adam + L2 instead of AdamW (or “weight_decay” in torch.optim.Adam, which is L2).
  • Comparing optimizers at one learning rate each, or at grid edges. Sweep, and bracket the optimum.
  • Skipping warm-up because the first steps look fine. The damage shows later.
  • Expecting clipping to fix a learning rate that is too high.
  • ε = 1e-5 or larger in a large model.
  • BF16 optimizer states with β₂ = 0.999 without checking.
  • Scaling the batch past the critical batch and calling the throughput gain progress.
  • Keeping λ fixed while the learning rate decays 10× in a WSD cooldown, without meaning to.
  • Applying µP’s Adam rule to SGD, or a µP formula without knowing what it keeps constant.

10. Exercises

  1. Bias correction. With β1=0.9\beta_1 = 0.9, β2=0.99\beta_2 = 0.99, what is the ratio of uncorrected to corrected Adam step at t=1t = 1? At t=10t = 10, for a constant gradient?
Answer

At t=1t = 1: m=0.1gm = 0.1g, v=0.01g2v = 0.01g^2, so the uncorrected step is 0.1/0.1=1.00.1/0.1 = 1.0 times sign(g)\text{sign}(g), and the corrected step is also sign(g)\text{sign}(g): ratio 1. At t=10t = 10: m=(1−0.910)g=0.651gm = (1 - 0.9^{10})g = 0.651g, v=(1−0.9910)g2=0.0956g2v = (1 - 0.99^{10})g^2 = 0.0956g^2, so the uncorrected step is 0.651/0.0956=2.110.651/\sqrt{0.0956} = 2.11. Corrected: 1. With these betas the error is zero at step 1 but grows before fading over about 100 steps.

  1. Steepest descent. For g=(3,−1,0.5)g = (3, -1, 0.5), give the steepest-descent step of size η\eta under ℓ2\ell_2 and under ℓ∞\ell_\infty, and the first-order decrease of each.
Answer

ℓ2\ell_2: −η g/∥g∥=−η(0.937,−0.312,0.156)-\eta\, g/\lVert g\rVert = -\eta(0.937, -0.312, 0.156); decrease η∥g∥2=3.20η\eta\lVert g\rVert_2 = 3.20\eta. ℓ∞\ell_\infty: −η(1,−1,1)-\eta(1, -1, 1); decrease η∥g∥1=4.5η\eta\lVert g\rVert_1 = 4.5\eta. The ℓ∞\ell_\infty ball contains the ℓ2\ell_2 ball of the same radius, so it allows a larger first-order decrease; whether that step is safe depends on the curvature.

  1. Conditioning. A quadratic has eigenvalues from 0.01 to 10. What is GD’s largest stable learning rate, and roughly how many steps does it need to shrink the error along the flattest direction by e−10e^{-10}? With heavy-ball momentum?
Answer

η<2/10=0.2\eta < 2/10 = 0.2. At η=0.1\eta = 0.1 (= 1/λmax1/\lambda_{max}), the flattest direction shrinks by (1−0.001)(1 - 0.001) per step, so about 10,000 steps (κ = 1,000; at η≈0.2\eta \approx 0.2 about 5,000). With momentum the rate is about 1−2/κ≈0.9371 - 2/\sqrt\kappa \approx 0.937, so about 160 steps.

  1. Critical batch. A run’s measured noise scale is 2M tokens. You have 4,096 GPUs, each processing 4K tokens per step. What is your batch, how does it compare with BcritB_{crit}, and roughly how many more tokens than necessary will you spend to reach the same loss?
Answer

B=16.8B = 16.8M tokens, 8.4×Bcrit8.4\times B_{crit}. Tokens: E/Emin=1+B/Bnoise=9.4E/E_{min} = 1 + B/B_{noise} = 9.4, so about 9.4× the minimum. Steps: S/Smin=1+Bnoise/B=1.12S/S_{min} = 1 + B_{noise}/B = 1.12, only 12% more than the minimum possible. You are trading tokens (compute) for wall-clock. Options: fewer GPUs per run (or several runs at once), ramping the batch up as the noise scale grows, or an optimizer with a larger critical batch.

  1. Coupled decay. A parameter has a tiny gradient (v^≈10−6\sqrt{\hat v} \approx 10^{-6}), value w=0.05w = 0.05, Adam with L2 λ=0.1\lambda = 0.1, η=10−3\eta = 10^{-3}, ϵ=10−8\epsilon = 10^{-8}. Approximately how far does it move per step toward zero? Under AdamW?
Answer

Adam + L2: the decay term is λw=0.005\lambda w = 0.005, which dominates the tiny gradient. Normalized: 0.005/(vdecay+ϵ)0.005/(\sqrt{v_{decay}} + \epsilon); once vv tracks (λw)2(\lambda w)^2 the ratio is about 1, so the step is about η=10−3\eta = 10^{-3} per step toward zero. It reaches 0 in about 50 steps. AdamW: ηλw=5×10−6\eta\lambda w = 5 \times 10^{-6} per step, 200× smaller, with a horizon of 1/(ηλ)=10,0001/(\eta\lambda) = 10{,}000 steps.

  1. µP for a new optimizer. An optimizer’s update for a weight matrix is −η G/∥G∥F-\eta\, G/\lVert G\rVert_F (normalized gradient). At batch size 1, how must η\eta scale with width (din=dout=dd_{in} = d_{out} = d) to keep ∥ΔW∥RMS→RMS\lVert\Delta W\rVert_{RMS\to RMS} constant?
Answer

At batch 1, GG is rank 1, so ∥G∥2=∥G∥F\lVert G\rVert_2 = \lVert G\rVert_F and ∥G/∥G∥F∥2=1\lVert G/\lVert G\rVert_F\rVert_2 = 1. The RMS-to-RMS norm is din/dout⋅η=η\sqrt{d_{in}/d_{out}} \cdot \eta = \eta for square matrices. So η\eta should be constant in width (and scale as dout/din\sqrt{d_{out}/d_{in}} for non-square). Each optimizer’s normalization changes the rule, which is the slide’s point.

  1. BF16 v. For which β₂ does a BF16 second moment stop updating when the gradient is steady? (BF16 has 8 significant bits; a relative change below about 2−92^{-9} rounds away.)
Answer

The update changes vv by (1−β2)(1 - \beta_2) times the relative gap. With a steady gradient the gap shrinks to the noise level, but even a 20% gap gives a relative change of 0.2(1−β2)0.2(1 - \beta_2). That rounds away when 0.2(1−β2)<2−9≈0.0020.2(1 - \beta_2) < 2^{-9} \approx 0.002, i.e. β2>0.99\beta_2 > 0.99. So β₂ = 0.95 is safe, and 0.999 stalls for all but large gaps. FP32 states (or stochastic rounding, or Kahan-style compensation) avoid it.

The optimizer choices of Assignment 2 (pre-training from scratch on one node) follow directly:

  • AdamW with decoupled decay, not applied to embeddings and norms;
  • β2=0.95\beta_2 = 0.95 and ϵ=10−8\epsilon = 10^{-8};
  • warm-up, then cosine or WSD (WSD lets you decide when to stop and branch cooldowns for ablations);
  • a batch near, not far above, the critical batch for your loss range;
  • learning rates swept on small proxies with µP so they transfer.

Spring 2026’s student blog post “Optimizer Mismatch & Catastrophic Forgetting” (course site) studied how optimizer choice drives forgetting during fine-tuning, a reminder that optimizers matter beyond pre-training. No assignment solutions are given here.

12. Research directions

  • Geometry-aware optimizers. Which norm should each parameter type use: embeddings, attention, MLP, norms? Modular norms and “old optimizer, new norm” give a framework; measuring it at scale is open.
  • Critical batch size as a design target. Optimizers, schedules and architectures that raise BcritB_{crit} let runs use more data parallelism productively.
  • Low-precision optimizer states. FP8 or 4-bit moments with error compensation or stochastic rounding, and when the averaging horizon breaks them.
  • Schedules without a horizon. WSD and schedule-free methods remove the need to know the run length. What is lost, and can cooldowns be made cheaper still?
  • µP beyond width. Depth, batch size, training length and MoE sparsity each need transfer rules; unified “maximal update” reasoning across all of them.

13. Further reading

  • Kingma and Ba, Adam (arXiv:1412.6980); Loshchilov and Hutter, Decoupled Weight Decay Regularization (arXiv:1711.05101).
  • Bernstein and Newhouse, Old Optimizer, New Norm: An Anthology (arXiv:2409.20325); Bernstein et al., signSGD (arXiv:1802.04434).
  • Chen et al., Symbolic Discovery of Optimization Algorithms (Lion, arXiv:2302.06675).
  • McCandlish et al., An Empirical Model of Large-Batch Training (arXiv:1812.06162).
  • Hägele et al., Scaling Laws and Compute-Optimal Training Beyond Fixed Training Durations (WSD and cooldowns, arXiv:2405.18392).
  • Wang and Aitchison, How to set AdamW’s weight decay as you scale model and dataset size (arXiv:2405.13698).
  • Yang et al., Tensor Programs V (arXiv:2203.03466); Yang, Simon and Bernstein, A Spectral Condition for Feature Learning (arXiv:2310.17813).
  • Gupta, Koren and Singer, Shampoo (arXiv:1802.09568); Jordan et al., Muon (2024).

14. Next lecture

Lecture 13 · Modern Optimizers and Architectures. This lecture ended where the spectral norm gives UV⊤UV^\top. Lecture 13 builds the optimizers that use it:

  • Muon’s Newton–Schulz iterations and their coefficients (Polar Express); Shampoo, SOAP and Kron;
  • the systems problem of orthogonalizing matrices that are sharded across GPUs (gathers, matrix owners, Dion);
  • stability (QK-clip, gated attention) and weight decay as an angular step size, with fixed-norm variants;
  • how to evaluate an optimizer claim fairly;
  • memory-traffic-aware architecture (n-gram tables in host memory, hyper-connections).

术语表 (Glossary, English → 中文)

English中文
stochastic gradient descent (SGD)随机梯度下降
momentum / heavy-ball momentum动量 / 重球动量
exponential moving average (EMA)指数滑动平均
sign descent / signum符号下降 / 带动量的符号下降
Adam / bias correctionAdam / 偏差修正
first / second moment一阶矩 / 二阶矩
L2 regularization (coupled) / decoupled weight decay (AdamW)L2 正则(耦合) / 解耦权重衰减
LionLion 优化器
optimizer state优化器状态
steepest descent / norm ball / dual norm最速下降 / 范数球 / 对偶范数
spectral norm / nuclear norm / orthogonalization谱范数 / 核范数 / 正交化
induced (operator) norm / RMS-to-RMS norm诱导(算子)范数 / RMS 到 RMS 范数
condition number / curvature / Hessian条件数 / 曲率 / 海森矩阵
diagonal preconditioner / rotation invariance对角预条件 / 旋转不变性
warm-up / cosine decay / WSD / cooldown预热 / 余弦衰减 / 预热-稳定-衰减 / 冷却期
gradient clipping (global norm)梯度裁剪(全局范数)
epsilon (numerical stability term)ε(数值稳定项)
stochastic rounding / round to nearest随机舍入 / 就近舍入
gradient noise scale / critical batch size梯度噪声尺度 / 临界批大小
equilibrium norm / timescale平衡范数 / 时间尺度
rank-one / stable rank秩一 / 稳定秩
µP / hyperparameter transfer / width multiplier最大更新参数化 / 超参数迁移 / 宽度倍数
Xavier/He initializationXavier/He 初始化
← 返回课程目录