concept / adam-w
Next task →
University/Optimization/First-order methods/Adam and AdamW: Adaptive Moment Estimation
Optimization · First-order methods · Adaptive optimization

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.

39 sectionsadvanced190 minhand-authored · structural 80/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Adam (Kingma & Ba, 2015) maintains two exponential moving averages per coordinate:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,m_t=\beta_1 m_{t-1}+(1-\beta_1)g_t,\qquad v_t=\beta_2 v_{t-1}+(1-\beta_2)g_t^2,

with gt=∇θf(θt)g_t=\nabla_\theta f(\theta_t), m0=v0=0m_0=v_0=0, and typical β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999. Because the averages start at zero, they are bias-corrected: m^t=mt/(1−β1t)\hat m_t=m_t/(1-\beta_1^t), v^t=vt/(1−β2t)\hat v_t=v_t/(1-\beta_2^t). The update is

 θt+1=θt−η m^tv^t+ϵ .\boxed{\ \theta_{t+1}=\theta_t-\eta\,\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}\ } .

The ratio m^/v^\hat m/\sqrt{\hat v} 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:

θt+1=(1−ηλ)θt−η m^tv^t+ϵ.\theta_{t+1}=(1-\eta\lambda)\theta_t-\eta\,\frac{\hat m_t}{\sqrt{\hat v_t}+\epsilon}.

The decay ηλθt\eta\lambda\theta_t 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 λθ\lambda\theta to the gradient before Adam's division makes the effective decay ≈ηλθi/∣gi∣\approx\eta\lambda\theta_i/|g_i|, 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 ηi=η/∑ au≤tg au,i2\eta_i=\eta/\sqrt{\sum_{\ au\le t}g_{\ au,i}^2}. Tieleman and Hinton (2012) presented RMSProp in a Coursera lecture (never a formal paper), using E[g2]\mathbb{E}[g^2] 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 m^/v^\hat m/\sqrt{\hat v} 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 v^\hat v). 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 PtP_t in θt+1=θt−ηPt−1gt\theta_{t+1}=\theta_t-\eta P_t^{-1}g_t. Adam chooses the diagonal Pt≈diag(v^t)P_t\approx\mathrm{diag}(\sqrt{\hat v_t}), 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). mt=(1−β1)∑i=0tβ1t−igim_t=(1-\beta_1)\sum_{i=0}^{t}\beta_1^{t-i}g_i is a weighted average with effective memory 1/(1−β1)1/(1-\beta_1) steps: β1=0.9\beta_1=0.9 averages ~10 steps, β2=0.999\beta_2=0.999 averages ~1000.

Fact 2 (bias correction). Starting from zero, E[mt]=(1−β1t)E[g]\mathbb{E}[m_t]=(1-\beta_1^t)\mathbb{E}[g] for stationary gradients, so mtm_t is too small early on. Dividing by 1−β1t1-\beta_1^t makes it unbiased; at t=1t=1, m^1=g1\hat m_1=g_1 exactly rather than 0.1g10.1g_1. Similarly v^1=g12\hat v_1=g_1^2.

Fact 3 (signal-to-noise ratio). m^/v^\hat m/\sqrt{\hat v} is roughly E[g]/E[g2]\mathbb{E}[g]/\sqrt{\mathbb{E}[g^2]}, a dimensionless quantity bounded by 1 in magnitude for a single random variable. The update is therefore approximately ±η\pm\eta 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 (1−ηλ)(1-\eta\lambda) each step implements θT≈e−ληTθ0\theta_T\approx e^{-\lambda\eta T}\theta_0, 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 ii and step tt:

gt,i=∇θifBt(θt),g_{t,i}=\nabla_{\theta_i} f_{B_t}(\theta_t), mt,i=β1mt−1,i+(1−β1)gt,i,vt,i=β2vt−1,i+(1−β2)gt,i2,m_{t,i}=\beta_1 m_{t-1,i}+(1-\beta_1)g_{t,i},\qquad v_{t,i}=\beta_2 v_{t-1,i}+(1-\beta_2)g_{t,i}^2, m^t,i=mt,i1−β1t,v^t,i=vt,i1−β2t,θt+1,i=θt,i−ηm^t,iv^t,i+ϵ.\hat m_{t,i}=\frac{m_{t,i}}{1-\beta_1^t},\qquad \hat v_{t,i}=\frac{v_{t,i}}{1-\beta_2^t},\qquad \theta_{t+1,i}=\theta_{t,i}-\eta\frac{\hat m_{t,i}}{\sqrt{\hat v_{t,i}}+\epsilon}.

AdamW. Replace the last line by

θt+1,i=(1−ηλ)θt,i−ηm^t,iv^t,i+ϵ.\theta_{t+1,i}=(1-\eta\lambda)\theta_{t,i}-\eta\frac{\hat m_{t,i}}{\sqrt{\hat v_{t,i}}+\epsilon}.

Typical defaults: η=10−3\eta=10^{-3} (LLM pretraining often 10−410^{-4} to 3×10−43\times10^{-4} with warmup), β1=0.9\beta_1=0.9, β2=0.95\beta_2=0.95–0.9990.999, ϵ=10−8\epsilon=10^{-8}, λ=0.01\lambda=0.01–0.10.1.

Shapes. For a parameter tensor of shape SS: g,m,v,m^,v^g,m,v,\hat m,\hat v all have shape SS; the update is elementwise and broadcasting-free.

AMSGrad variant. Keep vtmax⁡=max⁡(vt−1max⁡,v^t)v_t^{\max}=\max(v_{t-1}^{\max},\hat v_t) and divide by vtmax⁡+ϵ\sqrt{v_t^{\max}}+\epsilon, making the denominator non-decreasing.

8. Notation dictionary

| Symbol | Meaning | Shape / type | |---|---|---| | θt∈Rd\theta_t\in\mathbb{R}^d | parameter vector at step tt | vector | | gt=∇fBt(θt)g_t=\nabla f_{B_t}(\theta_t) | minibatch gradient | vector in Rd\mathbb{R}^d | | mtm_t | first moment (EMA of gg) | vector in Rd\mathbb{R}^d | | vtv_t | second moment (EMA of g2g^2, elementwise) | vector in Rd\mathbb{R}^d | | m^t,v^t\hat m_t,\hat v_t | bias-corrected moments | vectors | | β1,β2∈[0,1)\beta_1,\beta_2\in[0,1) | EMA decay rates | scalars | | η>0\eta>0 | learning rate | scalar | | ϵ>0\epsilon>0 | numerical stabiliser (default 10−810^{-8}) | scalar | | λ≥0\lambda\ge0 | decoupled weight-decay coefficient | scalar | | tt | step index (starts at 1 for bias correction) | integer | | Pt=diag(v^t)P_t=\mathrm{diag}(\sqrt{\hat v_t}) | diagonal preconditioner | matrix (never formed) | | BtB_t | minibatch at step tt | set |

9. Step-by-step derivation

Step 1 — unroll the first moment. With m0=0m_0=0,

mt=(1−β1)∑i=1tβ1t−igi.m_t=(1-\beta_1)\sum_{i=1}^{t}\beta_1^{t-i}g_i .

If E[gi]=μ\mathbb{E}[g_i]=\mu constant, E[mt]=μ(1−β1)∑i=1tβ1t−i=μ(1−β1t)\mathbb{E}[m_t]=\mu(1-\beta_1)\sum_{i=1}^t\beta_1^{t-i}=\mu(1-\beta_1^t). Hence m^t=mt/(1−β1t)\hat m_t=m_t/(1-\beta_1^t) is unbiased; identically for vv with β2\beta_2.

Step 2 — interpret the ratio. Expanding the EMA weights, m^t/v^t≈E[g]/E[g2]\hat m_t/\sqrt{\hat v_t}\approx\mathbb{E}[g]/\sqrt{\mathbb{E}[g^2]}, a normalised gradient. For a coordinate whose gradient is always positive, the step is ≈−η\approx-\eta; if gradients change sign frequently, m^\hat m is small and the step shrinks.

Step 3 — early-step magnitude. At t=1t=1: m1=(1−β1)g1m_1=(1-\beta_1)g_1, 1−β11=1−β11-\beta_1^1=1-\beta_1, so m^1=g1\hat m_1=g_1, and similarly v^1=g12\hat v_1=g_1^2. Without bias correction the first step would be (1−β1)/(1−β2)1/2≈0.1/0.0316=3.16(1-\beta_1)/(1-\beta_2)^{1/2}\approx0.1/0.0316=3.16 times too small for g1>0g_1>0 — a large early discrepancy.

Step 4 — coupled versus decoupled decay. With L2 in the gradient, gi′=∇fi+λθig_i'=\nabla f_i+\lambda\theta_i. Adam divides by v^i≈∣gi′∣\sqrt{\hat v_i}\approx|g_i'|, so the decay-induced parameter change is ≈−ηλθi/∣gi′∣\approx-\eta\lambda\theta_i/|g_i'| — inversely proportional to gradient magnitude. AdamW's explicit contraction gives exactly −ηλθi-\eta\lambda\theta_i, independent of gig_i.

Step 5 — effective step on a quadratic. For f(θ)=12θ⊤Aθf(\theta)=\tfrac12\theta^\top A\theta, 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 tt, so resuming a checkpoint with a reset tt 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 gig_i are i.i.d. with mean μ\mu, then m^t=mt/(1−β1t)\hat m_t=m_t/(1-\beta_1^t) satisfies E[m^t]=μ\mathbb{E}[\hat m_t]=\mu; similarly E[v^t]=E[g2]\mathbb{E}[\hat v_t]=\mathbb{E}[g^2]. Proof. Geometric-series identity from Step 1. □\square

Lemma 2 (gradient-scale invariance, ϵ=0\epsilon=0). Replacing ff by cfc f (c>0c>0) leaves the Adam update unchanged. Proof. g→cgg\to cg, hence m→cmm\to cm, v→c2vv\to c^2v, and m^/v^→cm^/(cv^)\hat m/\sqrt{\hat v}\to c\hat m/(c\sqrt{\hat v}), unchanged. □\square With ϵ>0\epsilon>0 invariance breaks when v^≲ϵ\sqrt{\hat v}\lesssim\epsilon, exactly the regime the stabiliser is meant to protect.

Lemma 3 (decoupled decay is exact contraction). In AdamW (with g=0g=0), after TT steps θT=(1−ηλ)Tθ0≈e−ηλTθ0\theta_T=(1-\eta\lambda)^T\theta_0\approx e^{-\eta\lambda T}\theta_0. Proof. Repeated multiplication; log⁡(1−ηλ)≈−ηλ\log(1-\eta\lambda)\approx-\eta\lambda for small ηλ\eta\lambda. □\square Coupled L2 has no such statement because the denominator varies with gg.

Lemma 4 (nonconvergence counterexample, Reddi et al. 2019). There exist convex online problems on which Adam with constant β2\beta_2 converges to a point with nonzero regret / suboptimal objective, due to v^t\hat v_t decreasing when gradients shrink. AMSGrad enforces v^tmax⁡\hat v_t^{\max} non-decreasing and restores an O(T)O(\sqrt T) regret bound. Proof sketch. Construct gradients where a large early vv makes the step tiny later just when a large step is needed; see Reddi et al. (2019), Theorem 2 and section 4. □\square

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 −ηg-\eta g in the Euclidean geometry; Adam takes a step in the geometry induced by the diagonal metric Pt=diag(v^t)P_t=\mathrm{diag}(\sqrt{\hat v_t}), i.e. −Pt−1ηm-P_t^{-1}\eta m. Each coordinate is rescaled by its own RMS gradient, so the update becomes approximately a vector of ±η\pm\eta 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 PtP_t 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 f(x,y)=12(10x2+y2)f(x,y)=\tfrac12(10x^2+y^2) (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 η\eta 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 mtm_t, vtv_t and m^t/v^t\hat m_t/\sqrt{\hat v_t} as functions of tt for one coordinate, making the bias correction and the ~10/~1000-step memory visible.

13. Numerical worked example

Take one parameter with constant gradient g=+1g=+1, β1=0.9\beta_1=0.9, β2=0.999\beta_2=0.999, η=0.001\eta=0.001, ϵ=10−8\epsilon=10^{-8}, starting at θ0=1\theta_0=1.

Step 1: m1=0.1m_1=0.1, v1=0.001v_1=0.001; m^1=0.1/0.1=1\hat m_1=0.1/0.1=1, v^1=0.001/0.001=1\hat v_1=0.001/0.001=1. Update θ1=1−0.001(1/1)=0.999\theta_1=1-0.001(1/1)=0.999. Without bias correction the step would be −0.001(0.1/0.001)=−0.00316-0.001(0.1/\sqrt{0.001})=-0.00316, over 3x larger in magnitude than intended.

After t=5t=5: β15=0.59049\beta_1^5=0.59049, so m^5=g=1\hat m_5=g=1; β25=0.99501\beta_2^5=0.99501, so v^5=1\hat v_5=1 for constant gg. Every step remains −0.001-0.001 — sign-like.

Now a second coordinate with g2=0.01g_2=0.01 (100x smaller). Step 1: v^1=g22=10−4\hat v_1=g_2^2=10^{-4}, m^1=g2\hat m_1=g_2, so m^/(v^+ϵ)=0.01/(0.01+10−8)≈0.999999\hat m/(\sqrt{\hat v}+\epsilon)=0.01/(0.01+10^{-8})\approx0.999999. Step is also −0.001-0.001. This is the scale invariance: both coordinates move by η\eta despite a 100x gradient difference.

Decay comparison. Let λ=0.1\lambda=0.1 and ∇f=100\nabla f=100 on coordinate 1, θ1=1\theta_1=1.

  • Coupled L2: g′=100.1g'=100.1, and m^/v^≈1\hat m/\sqrt{\hat v}\approx1, so Δθ≈−0.001\Delta\theta\approx-0.001. The decay contribution is only ≈−ηλθ/∣g′∣=−0.001(0.1)/100.1≈−10−6\approx-\eta\lambda\theta/|g'|=-0.001(0.1)/100.1\approx-10^{-6} — negligible.
  • AdamW: Δθ=−ηλθ−η sign(g)=−0.0001−0.001=−0.0011\Delta\theta=-\eta\lambda\theta-\eta\,\mathrm{sign}(g)=-0.0001-0.001=-0.0011. The decay is exactly ηλθ=10−4\eta\lambda\theta=10^{-4} 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 1−βt1-\beta^t 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 t=1t=1 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 (mm) and exp_avg_sq (vv); restoring only the parameters breaks bias correction after a resume.

A subtle interaction. Gradient clipping changes gg 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 dd parameters:

  • parameters: 4d4d bytes;
  • gradients: 4d4d bytes;
  • first moment mm: 4d4d bytes;
  • second moment vv: 4d4d bytes;
  • total: 16d16d bytes, i.e. four times the parameter memory.

For d=7×109d=7\times10^9 (7B model) that is 28+28+28+28=11228+28+28+28=112 GB just for weights, gradients and Adam states — beyond a single 80 GB GPU. Mixed precision adds a master copy of weights (another 4d4d), and activation memory is extra. Techniques: 8-bit moments (halves the m,vm,v cost), Adafactor (factorised vv, often O(d)O(\sqrt d) state), or sharded optimizers (ZeRO) that partition states across devices.

Per step, the optimizer reads and writes mm, vv, gg and θ\theta at least once each, so it is memory-bandwidth bound: roughly 16d16d 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 O(d)O(d) elementwise work (a few multiplies, one square root and one division per parameter). With TT steps, O(Td)O(Td) — linear in model size and independent of data size beyond the O(B cost(f))O(B\,\mathrm{cost}(f)) gradient computation. Compared with SGD (O(d)O(d) 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

O(d)O(d) parameters + O(d)O(d) gradients + O(2d)O(2d) moment states = O(4d)O(4d) scalar slots. SGD with momentum needs O(2d)O(2d), plain SGD O(d)O(d). AMSGrad adds another O(d)O(d) for vmax⁡v^{\max}; 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 f=12(100x2+y2)f=\tfrac12(100x^2+y^2) from (1,1)(1,1), compare SGD (η=0.001\eta=0.001), momentum, RMSProp and AdamW (η=0.01\eta=0.01) — record steps to f<10−3f<10^{-3}; expect SGD to be limited by the stiff direction while AdamW is far less sensitive. (2) Scale-invariance test: multiply the loss by c∈{0.01,1,100}c\in\{0.01,1,100\} and plot AdamW trajectories with ϵ=0\epsilon=0 — they should coincide; with ϵ=10−8\epsilon=10^{-8} they diverge only when v^∼ϵ\sqrt{\hat v}\sim\epsilon. (3) Weight-decay ablation: train a small classifier with coupled L2 versus decoupled decay at matched nominal λ\lambda, and measure the norm of parameters whose gradients are large versus small; decoupled decay should contract both equally. (4) β2\beta_2 sweep (∈{0.9,0.99,0.999,0.9999}\in\{0.9,0.99,0.999,0.9999\}) on a nonstationary objective; watch adaptation lag grow with β2\beta_2.

23. Benchmark results

On the quadratic above, SGD with a safe η=0.001\eta=0.001 needs thousands of steps for the flat coordinate, while AdamW at η=0.01\eta=0.01 typically reaches f<10−3f<10^{-3} 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 (O(2d)O(2d) 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.
  • ϵ\epsilon breaks exact scale invariance and can dominate when gradients are tiny.
  • High β2\beta_2 adapts slowly to changing gradient statistics; low β2\beta_2 is noisy.
  • Generalisation can be worse than tuned SGD+momentum on some vision tasks.
  • In fp16, g2g^2 can underflow to zero; keep moments in fp32.
  • Decoupled decay requires a separate schedule for λ\lambda; coupling it into the loss is subtly different.

25. Failure scenarios

  1. 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().
  2. Weight decay has no effect: gradients are large, so coupled L2's effective decay ηλθ/∣g∣\eta\lambda\theta/|g| is negligible; switch to AdamW.
  3. Parameters shrink too fast on flat directions: ϵ\epsilon is too small and m^/v^\hat m/\sqrt{\hat v} amplifies noise when v≈0v\approx0; increase ϵ\epsilon or clip gradients.
  4. No adaptation to a regime change: β2=0.999\beta_2=0.999 averages ~1000 steps; after a data distribution shift, vv lags and steps are mis-scaled.
  5. fp16 moment underflow: g2g^2 underflows for small gg, making v^=0\hat v=0 and steps explode; keep vv in fp32 (AMP does this by default).
  6. Divergence at large learning rate: Adam's step is ~η\eta per coordinate, so a too-large η\eta produces bounded but destructive sign-like steps; use warmup.
  7. Wrong decay semantics: using Adam (not AdamW) with weight_decay>0 in a framework that couples it by default; check the decoupled_weight_decay flag.
  8. 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 v^\sqrt{\hat v}, giving gradient-dependent decay; decoupled decay is a uniform contraction.
  • "Adam needs no learning-rate tuning." The step magnitude is ~η\eta per coordinate, so η\eta still sets the scale; schedules matter enormously.
  • "Larger β2\beta_2 is always better." It increases memory and slows adaptation to nonstationary gradients.
  • "Bias correction is a minor detail." At t=1t=1 it changes the step by a factor of ~3 for typical β\beta; 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 β2\beta_2.
  • 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

  1. Implement AdamW from memory and reproduce the step-1 bias-correction numbers (m^1=g1\hat m_1=g_1, v^1=g12\hat v_1=g_1^2) and the θ1=0.999\theta_1=0.999 example.
  2. Verify scale invariance: run AdamW with ϵ=0\epsilon=0 on losses scaled by 0.01,1,1000.01,1,100 and confirm identical trajectories.
  3. On f=12(100x2+y2)f=\tfrac12(100x^2+y^2), compare step counts to f<10−3f<10^{-3} for SGD, momentum, RMSProp and AdamW with a recorded tuning budget.
  4. Demonstrate the coupled-decay flaw: on a coordinate with ∣∇f∣=100|\nabla f|=100 and λ=0.1\lambda=0.1, compute the effective decay for coupled L2 and decoupled decay.
  5. Add AMSGrad to your implementation and reproduce a simple case where vtv_t shrinks; compare trajectories.
  6. Log mm, vv 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 η\eta.
  • 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

  1. Prove the bias-correction lemma and the scale-invariance lemma with ϵ=0\epsilon=0; quantify the invariance violation for ϵ>0\epsilon>0.
  2. Reproduce the Reddi et al. (2019) counterexample numerically and show AMSGrad's different behaviour.
  3. Derive the exact effective decay of coupled L2 under Adam, Δθdecay≈−ηλθi/v^i≈−ηλθi/∣gi∣\Delta\theta_{\text{decay}}\approx-\eta\lambda\theta_i/\sqrt{\hat v_i}\approx-\eta\lambda\theta_i/|g_i|, and plot it against ∣gi∣|g_i|.
  4. Implement AdamW with a per-parameter-group λ\lambda (no decay on biases/norms) and verify the norms are unaffected.
  5. Compare fused, foreach and naive PyTorch AdamW step times for a 100M-parameter model; explain the speedup.
  6. 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 t=1t=1.
  • Why is Adam approximately scale-invariant, and where does ϵ\epsilon 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 dd 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 ϵ\epsilon 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 vv 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 t=1t=1 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, \eta2\eta_2 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 10−610^{-6}.

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.`

Research papers linked to this concept