Adam and AdamW: Adaptive Moment Estimation
Adam combines momentum with a per-coordinate RMS preconditioner built from exponential moving averages of gradients and squared gradients; AdamW decouples weight decay from that adaptive scaling so decay is a true multiplicative contraction of the weights.
1. Concept overview
Adam (Kingma & Ba, 2015) maintains two exponential moving averages per coordinate:
with , , and typical , . Because the averages start at zero, they are bias-corrected: , . The update is
The ratio is a normalised signal: coordinates with consistently large gradients are not drowned out, and coordinates with rare, large gradients do not blow up.
AdamW (Loshchilov & Hutter, 2019) changes only the regularisation:
The decay is decoupled from the adaptive denominator — a qualitative change, not a syntax tweak.
2. Why this concept exists
SGD with a single learning rate struggles on ill-conditioned problems: a step that is safe for high-curvature coordinates is tiny for flat ones. AdaGrad (2011) accumulated squared gradients to give per-coordinate rates, but its denominator grows monotonically and training stalls. RMSProp (Tieleman & Hinton, 2012) replaced the sum with an exponential moving average, fixing the stall; it lacked momentum.
Adam combined RMSProp's per-coordinate normalisation with momentum's smoothed direction, giving a method that is robust to gradient scale, sparse features and noisy minibatches — and requires almost no learning-rate tuning to get started. It became the default for transformers.
The L2-regularisation flaw: adding to the gradient before Adam's division makes the effective decay , i.e. inversely proportional to gradient magnitude. Coordinates with large gradients barely decay; coordinates with tiny gradients decay aggressively. Decoupled weight decay (AdamW) restores a uniform, interpretable contraction and is now the standard for LLM training.
3. Historical background
Duchi, Hazan and Singer (2011) introduced AdaGrad in the online-learning setting, with . Tieleman and Hinton (2012) presented RMSProp in a Coursera lecture (never a formal paper), using as an EMA. Sutskever, Martens, Dahl and Hinton (2013) systematised Nesterov momentum for deep networks. Kingma and Ba (2015) published Adam at ICLR, with bias correction and the update; the paper's convergence proof was later shown to contain a flaw. Reddi, Kale and Kumar (2019) constructed a convex counterexample where Adam converges to a suboptimal point and proposed AMSGrad (using a non-decreasing ). Loshchilov and Hutter (2019) introduced AdamW, showing decoupled decay restores the equivalence to L2 regularisation that holds for SGD. Zhang et al. (2020) showed AdamW can be improved by iterate averaging; You et al. (2020) proposed LAMB for large-batch training. AdamW is the default optimizer for BERT, GPT-style models and most diffusion transformers.
4. Fundamental problem
We want an update rule that (i) adapts a step size to each coordinate using only first-order information, (ii) is insensitive to rescaling the loss and to sparse/noisy gradients, (iii) retains the acceleration benefits of momentum, and (iv) applies regularisation in a way that is independent of the adaptive preconditioner.
The core design choice is what to use as a preconditioner in . Adam chooses the diagonal , an RMS estimate of gradient magnitude — a cheap, diagonal approximation to the Fisher information or the square root of the Hessian's diagonal. The remaining difficulties are estimator bias at early steps (fixed by bias correction), nonstationary gradients (fixed by the EMA), and the regularisation coupling (fixed by AdamW).
5. First-principles explanation
Fact 1 (EMA as a low-pass filter). is a weighted average with effective memory steps: averages ~10 steps, averages ~1000.
Fact 2 (bias correction). Starting from zero, for stationary gradients, so is too small early on. Dividing by makes it unbiased; at , exactly rather than . Similarly .
Fact 3 (signal-to-noise ratio). is roughly , a dimensionless quantity bounded by 1 in magnitude for a single random variable. The update is therefore approximately per coordinate — a sign-like step whose size is set by the learning rate, not the raw gradient scale.
Fact 4 (decoupled decay). Multiplying weights by each step implements , an exponential contraction independent of the gradient, which is what "weight decay" means.
6. Prerequisite concepts
You should know: (a) gradient descent and minibatch SGD; (b) momentum / Polyak averaging and Nesterov acceleration; (c) AdaGrad and RMSProp; (d) exponential moving averages and their bias when initialised at zero; (e) basic convex-analysis notions for the convergence caveats; (f) L2 regularisation versus explicit weight decay. See the linked concepts for each.
7. Complete mathematical formulation
Adam. For each parameter coordinate and step :
AdamW. Replace the last line by
Typical defaults: (LLM pretraining often to with warmup), , –, , –.
Shapes. For a parameter tensor of shape : all have shape ; the update is elementwise and broadcasting-free.
AMSGrad variant. Keep and divide by , making the denominator non-decreasing.
8. Notation dictionary
| Symbol | Meaning | Shape / type | |---|---|---| | | parameter vector at step | vector | | | minibatch gradient | vector in | | | first moment (EMA of ) | vector in | | | second moment (EMA of , elementwise) | vector in | | | bias-corrected moments | vectors | | | EMA decay rates | scalars | | | learning rate | scalar | | | numerical stabiliser (default ) | scalar | | | decoupled weight-decay coefficient | scalar | | | step index (starts at 1 for bias correction) | integer | | | diagonal preconditioner | matrix (never formed) | | | minibatch at step | set |
9. Step-by-step derivation
Step 1 — unroll the first moment. With ,
If constant, . Hence is unbiased; identically for with .
Step 2 — interpret the ratio. Expanding the EMA weights, , a normalised gradient. For a coordinate whose gradient is always positive, the step is ; if gradients change sign frequently, is small and the step shrinks.
Step 3 — early-step magnitude. At : , , so , and similarly . Without bias correction the first step would be times too small for — a large early discrepancy.
Step 4 — coupled versus decoupled decay. With L2 in the gradient, . Adam divides by , so the decay-induced parameter change is — inversely proportional to gradient magnitude. AdamW's explicit contraction gives exactly , independent of .
Step 5 — effective step on a quadratic. For , Adam's preconditioner is diagonal, so it cannot rotate the gradient into the eigenbasis. It normalises RMS magnitudes but does not eliminate cross-coordinate coupling; on ill-conditioned quadratics convergence still depends on the eigenstructure, though far less dramatically than SGD.
Step 6 — step-count dependence. Bias correction depends on , so resuming a checkpoint with a reset silently changes the first steps after resumption; save the step counter with the optimizer state.
10. Proofs and proof intuition
Lemma 1 (bias correction). If are i.i.d. with mean , then satisfies ; similarly . Proof. Geometric-series identity from Step 1.
Lemma 2 (gradient-scale invariance, ). Replacing by () leaves the Adam update unchanged. Proof. , hence , , and , unchanged. With invariance breaks when , exactly the regime the stabiliser is meant to protect.
Lemma 3 (decoupled decay is exact contraction). In AdamW (with ), after steps . Proof. Repeated multiplication; for small . Coupled L2 has no such statement because the denominator varies with .
Lemma 4 (nonconvergence counterexample, Reddi et al. 2019). There exist convex online problems on which Adam with constant converges to a point with nonzero regret / suboptimal objective, due to decreasing when gradients shrink. AMSGrad enforces non-decreasing and restores an regret bound. Proof sketch. Construct gradients where a large early makes the step tiny later just when a large step is needed; see Reddi et al. (2019), Theorem 2 and section 4.
Proof intuition. Adam is a sign-like step modulated by gradient reliability. Sign-like steps are scale-free and robust, but an unbounded, time-varying denominator can shrink steps at the wrong moment — the gap the AMSGrad fix closes.
11. Geometric interpretation
SGD takes a step in the Euclidean geometry; Adam takes a step in the geometry induced by the diagonal metric , i.e. . Each coordinate is rescaled by its own RMS gradient, so the update becomes approximately a vector of entries — a descent direction in a locally whitened coordinate system.
On a quadratic with elliptical contours, SGD zig-zags because the gradient is normal to the ellipses rather than pointing at the centre; Adam rescales coordinates so contours become more circular, but because is diagonal it cannot undo rotation. Weight decay in AdamW is a uniform contraction of the parameter vector toward the origin, geometrically a homothetic shrink independent of the loss landscape, whereas coupled L2 decay is a direction-dependent, gradient-normalised pull.
12. Visual explanation
Use the Optimizer Trajectory Playground: it plots contours of a quadratic (or a rotated version) and the trajectories of SGD, momentum, RMSProp, Adam and AdamW from the same start. Toggle: (i) condition number — stretch the ellipse and watch SGD's zig-zag versus Adam's near-isotropic steps; (ii) gradient scale — multiply the loss by 100 and verify Adam's path is unchanged while SGD's diverges unless is rescaled; (iii) weight decay — compare coupled L2 and decoupled decay by plotting the radial contraction on a flat direction with tiny gradients. A second panel shows , and as functions of for one coordinate, making the bias correction and the ~10/~1000-step memory visible.
13. Numerical worked example
Take one parameter with constant gradient , , , , , starting at .
Step 1: , ; , . Update . Without bias correction the step would be , over 3x larger in magnitude than intended.
After : , so ; , so for constant . Every step remains — sign-like.
Now a second coordinate with (100x smaller). Step 1: , , so . Step is also . This is the scale invariance: both coordinates move by despite a 100x gradient difference.
Decay comparison. Let and on coordinate 1, .
- Coupled L2: , and , so . The decay contribution is only — negligible.
- AdamW: . The decay is exactly regardless of the gradient magnitude.
This 100x discrepancy in decay rate between coordinates is precisely what decoupled weight decay fixes.
14. Real-world analogy
A runner descending a hilly landscape can choose how far to step in each direction. Plain SGD uses one stride length everywhere, so it overshoots on steep slopes and crawls on gentle ones. Adam gives the runner a memory of recent slopes: it shortens strides where the terrain has been consistently steep or jittery and normalises each direction, so progress is steady. Momentum is like carrying forward the direction of travel; the second moment is like remembering how rough each direction has been. Decoupled weight decay is a separate, constant "pull toward the trail centre" applied equally regardless of terrain — coupling it into the slope estimate would make it vanish on steep sections and dominate on flat ones.
15. Algorithm pseudocode
algorithm AdamW(theta, grad_fn, eta, beta1, beta2, eps, lambda, T):
m <- 0 ; v <- 0 ; t <- 0
for t = 1 .. T:
g <- grad_fn(theta)
m <- beta1 * m + (1 - beta1) * g
v <- beta2 * v + (1 - beta2) * (g * g)
mhat <- m / (1 - beta1^t)
vhat <- v / (1 - beta2^t)
theta <- (1 - eta * lambda) * theta # decoupled decay
theta <- theta - eta * mhat / (sqrt(vhat) + eps)
return theta
# Adam: omit the decoupled-decay line; to emulate L2, add lambda*theta to g
# (this is NOT equivalent — see sections 8 and 13).
# AMSGrad: keep vmax <- max(vmax, vhat) and divide by sqrt(vmax) + eps.
16. Implementation from scratch
import numpy as np
class AdamW:
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
self.p, self.lr, self.b1, self.b2, self.eps, self.wd = params, lr, *betas, eps, weight_decay
self.m = [np.zeros_like(x) for x in params]
self.v = [np.zeros_like(x) for x in params]
self.t = 0
def step(self, grads):
self.t += 1
bc1, bc2 = 1 - self.b1 ** self.t, 1 - self.b2 ** self.t
for i, (x, g) in enumerate(zip(self.p, grads)):
self.m[i] = self.b1 * self.m[i] + (1 - self.b1) * g
self.v[i] = self.b2 * self.v[i] + (1 - self.b2) * g * g
mhat, vhat = self.m[i] / bc1, self.v[i] / bc2
x *= (1 - self.lr * self.wd) # decoupled decay
x -= self.lr * mhat / (np.sqrt(vhat) + self.eps)
# Quadratic with very different curvatures: f = 0.5*(100 x^2 + y^2)
f = lambda w: 0.5 * (100*w[0]**2 + w[1]**2)
gf = lambda w: np.array([100*w[0], w[1]])
p = [np.array([1.0, 1.0])]
opt = AdamW(p, lr=0.01, weight_decay=0.0)
for t in range(500):
opt.step([gf(p[0])])
assert f(p[0]) < 1e-3, f(p[0])
print(p[0], f(p[0])) # both coordinates near zero despite 100x curvature ratio
# Bias-correction check at t=1 with g = 1:
o = AdamW([np.array([1.0])], lr=0.001)
o.step([np.array([1.0])])
assert abs(o.m[0] / (1 - o.b1) - 1.0) < 1e-12
The state arrays m and v have exactly the parameter shapes; self.t is part of the state and must be checkpointed.
17. Professional library implementation
import torch
model = torch.nn.Linear(64, 10)
optimizer = torch.optim.AdamW(
model.parameters(),
lr=3e-4, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1,
fused=True, # single CUDA kernel; much faster for many small tensors
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1000)
for x, y in loader:
optimizer.zero_grad(set_to_none=True)
loss = torch.nn.functional.cross_entropy(model(x), y)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
scheduler.step()
# Plain Adam with decoupled decay (PyTorch >= 1.12 when decoupled_weight_decay=True):
adam_decoupled = torch.optim.Adam(model.parameters(), lr=1e-3,
decoupled_weight_decay=True, weight_decay=0.01)
# Save/restore the step counter with the state dict:
state = optimizer.state_dict() # includes 'step' used for bias correction
For very large models use foreach=True or fused=True; for memory-constrained fine-tuning consider 8-bit Adam (bitsandbytes) or Adafactor.
18. Code walkthrough
Scratch version. self.m and self.v are allocated with zeros_like for each parameter tensor. The EMA updates are in-place elementwise operations. bc1 and bc2 implement using the step counter incremented at the start. The weight decay line comes before the adaptive step and multiplies x in place — this is the only difference from Adam. The assertions check convergence on a 100x-ill-conditioned quadratic and the bias correction.
PyTorch version. zero_grad(set_to_none=True) avoids stale gradients; clip_grad_norm_ is applied before step() so the clipped gradient is what enters the moments. fused=True launches one kernel over all parameters, which matters when there are thousands of small tensors. state_dict() contains per-parameter step, exp_avg () and exp_avg_sq (); restoring only the parameters breaks bias correction after a resume.
A subtle interaction. Gradient clipping changes and therefore both moments. If your training uses clipping, log the pre-clip gradient norm — a growing norm often precedes loss spikes.
19. Tensor and memory analysis
AdamW stores two state tensors per parameter, each the same shape as the parameter. In fp32 (4 bytes per element) with parameters:
- parameters: bytes;
- gradients: bytes;
- first moment : bytes;
- second moment : bytes;
- total: bytes, i.e. four times the parameter memory.
For (7B model) that is GB just for weights, gradients and Adam states — beyond a single 80 GB GPU. Mixed precision adds a master copy of weights (another ), and activation memory is extra. Techniques: 8-bit moments (halves the cost), Adafactor (factorised , often state), or sharded optimizers (ZeRO) that partition states across devices.
Per step, the optimizer reads and writes , , and at least once each, so it is memory-bandwidth bound: roughly bytes of traffic per step, ~112 GB for the 7B example. Fused kernels cut launch overhead and redundant reads.
20. Time complexity
One AdamW step is elementwise work (a few multiplies, one square root and one division per parameter). With steps, — linear in model size and independent of data size beyond the gradient computation. Compared with SGD ( with one state), AdamW's constant factor is higher but usually negligible relative to the forward/backward pass; it becomes significant for tiny batches or very large models with thousands of small parameter tensors, where fused kernels help.
21. Space complexity
parameters + gradients + moment states = scalar slots. SGD with momentum needs , plain SGD . AMSGrad adds another for ; Adafactor reduces second-moment storage from a full matrix to two low-rank factors. For checkpointing, the optimizer state is as large as the model and must be saved alongside it, including the integer step counter used for bias correction.
22. Experimental demonstration
Run four experiments. (1) On from , compare SGD (), momentum, RMSProp and AdamW () — record steps to ; expect SGD to be limited by the stiff direction while AdamW is far less sensitive. (2) Scale-invariance test: multiply the loss by and plot AdamW trajectories with — they should coincide; with they diverge only when . (3) Weight-decay ablation: train a small classifier with coupled L2 versus decoupled decay at matched nominal , and measure the norm of parameters whose gradients are large versus small; decoupled decay should contract both equally. (4) sweep () on a nonstationary objective; watch adaptation lag grow with .
23. Benchmark results
On the quadratic above, SGD with a safe needs thousands of steps for the flat coordinate, while AdamW at typically reaches in a few hundred — but tuning SGD's learning rate changes the comparison dramatically, so report the tuning budget. In vision, carefully tuned SGD+momentum often generalises a fraction of a point better than AdamW; in transformer pretraining and fine-tuning AdamW is the overwhelming default. Loshchilov & Hutter (2019) report AdamW outperforming Adam with L2 on image classification and language modelling, but later work (e.g. Zhang et al. 2020) shows the gap is task- and tuning-dependent. Treat any universal ranking as suspect: report dataset, architecture, tuning protocol, batch size and schedule.
24. Limitations
- Stores two additional state tensors per parameter ( extra memory).
- Not a second-order method: the diagonal RMS preconditioner ignores correlations between coordinates.
- Original convergence proof was flawed; standard Adam can fail on convex problems (Reddi et al. 2019); AMSGrad fixes the theory but is not always better in practice.
- breaks exact scale invariance and can dominate when gradients are tiny.
- High adapts slowly to changing gradient statistics; low is noisy.
- Generalisation can be worse than tuned SGD+momentum on some vision tasks.
- In fp16, can underflow to zero; keep moments in fp32.
- Decoupled decay requires a separate schedule for ; coupling it into the loss is subtly different.
25. Failure scenarios
- Loss spikes after resuming training: the optimizer's step counter was reset, so bias correction is wrong for the first steps; save and restore
state_dict(). - Weight decay has no effect: gradients are large, so coupled L2's effective decay is negligible; switch to AdamW.
- Parameters shrink too fast on flat directions: is too small and amplifies noise when ; increase or clip gradients.
- No adaptation to a regime change: averages ~1000 steps; after a data distribution shift, lags and steps are mis-scaled.
- fp16 moment underflow: underflows for small , making and steps explode; keep in fp32 (AMP does this by default).
- Divergence at large learning rate: Adam's step is ~ per coordinate, so a too-large produces bounded but destructive sign-like steps; use warmup.
- Wrong decay semantics: using Adam (not AdamW) with
weight_decay>0in a framework that couples it by default; check thedecoupled_weight_decayflag. - Memory OOM: two extra full-size moment tensors; use 8-bit optimizers or sharding.
26. Common misconceptions
- "Adam is a second-order method." It uses a diagonal RMS of gradients, not the Hessian or Fisher matrix; no cross-coordinate information is used.
- "AdamW is just Adam with L2 regularisation." Coupled L2 is divided by , giving gradient-dependent decay; decoupled decay is a uniform contraction.
- "Adam needs no learning-rate tuning." The step magnitude is ~ per coordinate, so still sets the scale; schedules matter enormously.
- "Larger is always better." It increases memory and slows adaptation to nonstationary gradients.
- "Bias correction is a minor detail." At it changes the step by a factor of ~3 for typical ; skipping it distorts early training.
- "Adam's update is proportional to the gradient." For constant-sign gradients it is approximately the sign, independent of gradient magnitude — that is the point.
- "AMSGrad always improves results." It fixes a theoretical pathology but can underperform Adam empirically.
27. Alternative approaches
- SGD + momentum / Nesterov: lower memory, often better generalisation in vision; needs careful learning-rate tuning.
- RMSProp: Adam without the first moment; good for nonstationary / reinforcement-learning settings.
- AdaGrad: monotonically shrinking rates; strong for sparse features, stalls in long training.
- Adafactor: factorised second moment, low memory, used for T5-scale models.
- LAMB / LARS: layerwise normalised adaptive steps for very large batches.
- Lion: sign-based update with one moment, lower memory.
- Shampoo / SOAP: richer preconditioners approximating the full Fisher; more compute and memory.
- 8-bit Adam: quantised moments with minimal quality loss for memory-bound training.
29. Research applications
- LLM pretraining and fine-tuning: AdamW with warmup + cosine decay is the de facto standard.
- Diffusion models: AdamW with EMA of weights for stable sampling.
- Reinforcement learning: Adam/RMSProp with carefully clipped gradients and slow .
- Sparse and continual learning: adaptive rates for rare features; studying decay's role in forgetting.
- Optimization theory: convergence under nonstationarity, heavy-tailed noise and relaxed smoothness.
- Large-batch training: LAMB/LARS layerwise scaling and the interaction of decay with batch size.
30. Important research papers
- Duchi J., Hazan E., Singer Y. (2011), Adaptive Subgradient Methods for Online Learning and Stochastic Optimization, JMLR 12:2121–2159.
- Tieleman T., Hinton G. (2012), Lecture 6.5 — RMSProp, Coursera Neural Networks for Machine Learning.
- Kingma D. P., Ba J. (2015), Adam: A Method for Stochastic Optimization, ICLR.
- Reddi S. J., Kale S. J., Kumar S. (2019), On the Convergence of Adam and Beyond, ICLR.
- Loshchilov I., Hutter F. (2019), Decoupled Weight Decay Regularization, ICLR.
- Zhang G. et al. (2020), Which Algorithms Should We Now Use for Neural Network Training?, arXiv:2002.04782 (iterative averaging with AdamW).
- You Y. et al. (2020), Large Batch Optimization for Deep Learning: Training BERT in 76 minutes, ICLR (LAMB).
31. Further reading
- Kingma & Ba (2015), arXiv:1412.6980 — original Adam.
- Loshchilov & Hutter (2019), arXiv:1711.05101 — derivation of decoupled decay.
- Reddi et al. (2019), arXiv:1904.09237 — convergence counterexample and AMSGrad.
- PyTorch optimizer docs: docs.pytorch.org/docs/stable/optim.html.
- "A Story of Weight Decay" blog posts and the fast.ai discussion threads on AdamW vs L2.
32. Practical exercises
- Implement AdamW from memory and reproduce the step-1 bias-correction numbers (, ) and the example.
- Verify scale invariance: run AdamW with on losses scaled by and confirm identical trajectories.
- On , compare step counts to for SGD, momentum, RMSProp and AdamW with a recorded tuning budget.
- Demonstrate the coupled-decay flaw: on a coordinate with and , compute the effective decay for coupled L2 and decoupled decay.
- Add AMSGrad to your implementation and reproduce a simple case where shrinks; compare trajectories.
- Log , and the step magnitude for a coordinate with sign-alternating gradients; explain the observed shrinkage.
33. Debugging challenges
- Training diverges immediately with AdamW: learning rate too large for a sign-like step; add warmup and reduce .
- Decay appears absent: you are using Adam with coupled L2; switch to decoupled
AdamW. - Loss spikes only after restoring a checkpoint: the step counter was lost, breaking bias correction.
- Gradients explode but Adam steps stay bounded: expected — monitor the pre-clip norm to detect instability early.
- NaN in
v: gradients contain NaN or fp16 overflow; enable anomaly detection and keep moments in fp32. - Large memory footprint: two moment buffers per parameter; try
fused, 8-bit moments or sharding. - Outperformed by SGD on a vision task: tune SGD momentum and schedule fairly before concluding; AdamW is not universally superior.
34. Advanced exercises
- Prove the bias-correction lemma and the scale-invariance lemma with ; quantify the invariance violation for .
- Reproduce the Reddi et al. (2019) counterexample numerically and show AMSGrad's different behaviour.
- Derive the exact effective decay of coupled L2 under Adam, , and plot it against .
- Implement AdamW with a per-parameter-group (no decay on biases/norms) and verify the norms are unaffected.
- Compare fused, foreach and naive PyTorch AdamW step times for a 100M-parameter model; explain the speedup.
- Replace the diagonal preconditioner with a block-diagonal Fisher approximation and discuss the memory/compute trade-off (Shampoo-style).
35. Interview questions
- Derive bias correction and explain why it matters at .
- Why is Adam approximately scale-invariant, and where does break that?
- Prove that AdamW's weight decay is an exact contraction and explain why coupled L2 is not.
- Is Adam a second-order method? Justify your answer using the shape of the preconditioner.
- What goes wrong with Adam in the Reddi et al. counterexample and how does AMSGrad fix it?
- How much memory does AdamW need relative to SGD for a model with parameters?
- Where in the training loop should gradient clipping happen, and why?
- When might you prefer SGD+momentum over AdamW, and how would you decide empirically?
36. Research questions
- Can a first-order method retain Adam's robustness while provably converging without AMSGrad-style modifications?
- What is the true role of in low-precision training, and can it be scheduled?
- How does decoupled weight decay interact with learning-rate schedules and batch size in LLM pretraining?
- Which moments should be quantised, and what error does 8-bit introduce in the update?
- Can adaptive preconditioners exploit cross-coordinate correlations affordably at 100B-parameter scale?
- Does Adam's implicit bias explain why transformer fine-tuning generalises differently from SGD?
37. Mastery assessment
To pass: (1) derive the moment recursions, bias correction and the numbers without notes; (2) prove scale invariance and the decoupled-decay contraction; (3) implement AdamW from scratch and verify the quadratic and bias-correction assertions; (4) explain the coupled-L2 flaw with actual numbers; (5) identify at least four failure scenarios; (6) answer the interview questions. Complete the linked assessment; reading the page is not mastery.
38. Implementation submission
Push a repository with adamw.py (scratch optimizer with state dict and bias correction), tests/test_adamw.py (bias correction, scale invariance, quadratic convergence, decay equivalence), experiments.ipynb (optimizer comparison with a tuning table, decay ablation, sweep), and a README.md deriving the moments, bias correction and decoupled decay, plus memory calculations for a 7B model. Include the exact reproduction command and a comparison of your step with torch.optim.AdamW to .
39. Completion criteria
All of: derivations reproduced on paper; scratch optimizer tests passing and matching PyTorch; optimizer comparison with recorded step counts and tuning budget; decay ablation showing the coupled/decoupled difference with numbers; four failure scenarios explained; assessment score at least 80%; one research question answered in a one-page note citing a paper. Only then mark the concept mastered.`