Module contents
Lesson 21 of 27Advanced 110 min

AdamW, weight decay and the theory of Adam

Explain why L2 regularization and weight decay coincide for SGD but not Adam, and how AdamW decouples them. Critically review Adam theory: its nonconvergence counterexample and AMSGrad, modern convergence analyses, sign descent and explanations for Adam's advantage over SGD in transformers.

After this lesson you can

  • Prove L2 and weight decay are equivalent in SGD after coefficient reparameterization but not with adaptive preconditioners.
  • Implement AdamW and explain interactions between learning rate, weight decay and schedule.
  • Reproduce Reddi et al.'s Adam nonconvergence counterexample and explain AMSGrad's correction.
  • Summarize modern Adam convergence guarantees and their conditions on β₁ and β₂.
  • Explain hypotheses about the Adam–SGD gap in transformers and design an experiment distinguishing them.

Before you start

Motivation: almost every LLM optimizer has an extra letter

Open the training appendix of almost any large language model and find the same line. GPT-3 (Brown et al., 2020) used Adam with β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, ε=10−8\eps = 10^{-8} and weight decay 0.10.1; LLaMA (Touvron et al., 2023) used AdamW with β1=0.9\beta_1 = 0.9, β2=0.95\beta_2 = 0.95, weight decay 0.10.1, gradient clipping to norm 1 and a cosine schedule ending at 10% of peak rate. W is the only letter distinguishing this optimizer from last lesson’s Adam, but it is not cosmetic: it distinguishes two regularizers.

The history is instructive. For years, Adam’s weight_decay option in widely used libraries added λθ\lambda\theta to the gradient, as an L2 penalty does. For SGD this is exactly the same as shrinking weights each step, and nobody distinguished them. Loshchilov and Hutter (2017, published at ICLR 2019) observed that with Adam they differ, that the “correct” version (shrinking outside the preconditioner) closed much of the generalization gap between Adam and SGD with momentum in image classification, and made optimal λ\lambda much less dependent on optimal rate. Today torch.optim.Adam(weight_decay=...) still does L2 and torch.optim.AdamW does the other: confusing them is a common silent mistake.

This lesson has two halves. The first is practical and exact: why L2 and weight decay agree in SGD but not Adam, what AdamW does, how rate, decay and schedule interact, and which parameters should not receive it. The second critically reviews Adam: Reddi et al.’s nonconvergence counterexample, AMSGrad’s correction, modern guarantees, why to view Adam as damped sign descent, and hypotheses explaining its advantage over SGD on transformers.

L2 versus weight decay

There are two ways to ask an optimizer to prefer small weights.

Proof

SGD with L2 gives θt+1=θt−η(gt+λ′θt)=(1−ηλ′)θt−ηgt\theta_{t+1} = \theta_t - \eta(\vb{g}_t + \lambda'\theta_t) = (1 - \eta\lambda')\theta_t - \eta\vb{g}_t. SGD with weight decay gives θt+1=(1−λ)θt−ηgt\theta_{t+1} = (1 - \lambda)\theta_t - \eta\vb{g}_t. The affine maps of (θt,gt)(\theta_t, \vb{g}_t) agree for every θt\theta_t if and only if 1−ηλ′=1−λ1 - \eta\lambda' = 1 - \lambda.

∎

The clean equivalence hides its basis: λ′θt\lambda'\theta_t is treated like the gradient, and in SGD that means multiplying by scalar η\eta. With any diagonal preconditioner Pt=diag⁡(pt,1,…,pt,d)\mat{P}_t = \diag(p_{t,1}, \dots, p_{t,d}) the calculation changes:

θt+1=θt−ηPt(gt+λ′θt)⏟L2frente aθt+1=(1−λ)θt−ηPtgt⏟decaimiento.\underbrace{\theta_{t+1} = \theta_t - \eta\mat{P}_t(\vb{g}_t + \lambda'\theta_t)}_{\text{L2}} \qquad\text{frente a}\qquad \underbrace{\theta_{t+1} = (1 - \lambda)\theta_t - \eta\mat{P}_t\vb{g}_t}_{\text{decaimiento}}.

With L2, coordinate ii shrinks at step tt by factor 1−ηλ′pt,i1 - \eta\lambda' p_{t,i}; with decay, factor 1−λ1 - \lambda is identical for all. For agreement λ′=λ/(ηpt,i)\lambda' = \lambda/(\eta p_{t,i}) is required for each ii and tt, and a single scalar λ′\lambda' can only satisfy this if Pt\mat{P}_t is a multiple of identity. In Adam, pt,i=1/(v^t,i+ε)p_{t,i} = 1/(\sqrt{\hat v_{t,i}} + \eps): historically large-gradient coordinates receive far less decay with L2 than small-gradient coordinates. A second-order effect: with L2, λ′θt\lambda'\theta_t also enters vt\vb{v}_t, so the preconditioner itself depends on regularization.

InteractiveL2 versus decoupled weight decay
θ*
  • Unregularized Adam
  • Adam + L2 (torch.optim.Adam)
  • AdamW
  • θ∗\theta^* and L2 optimum (hollow)
  • box ∥θ∥∞≤1/λ\norm{\theta}_\infty \le 1/\lambda
Decay received by each coordinate per step (fraction of weight subtracted)
  • L2, coordinate 1
  • L2, coordinate 2
  • AdamW, both
100
0.50
0.50
0.020
step 3000
Adam + L2, final(1.507, 0.998)
AdamW, final(1.140, 1.132)
Optimum with L2(1.493, 1.000)
L2: decay per step1.9e−4 and 0.019
AdamW: decay, ηλ\eta\lambda0.010
AdamW: change versus c=1c = 15.7e−9
Coordinate 1 has gradients 100 times larger. With L2, the preconditioner also divides λθ1\lambda\theta_1: its per-step decay is about 102 times smaller than that of θ2\theta_2 and ends at θ1≈1.507\theta_1 \approx 1.507, almost unregularized. AdamW decays both by ηλ\eta\lambda per step.
Quadratic fc(θ)=12c(θ1−1.5)2+12(θ2−1.5)2f_c(\theta) = \tfrac12 c(\theta_1 - 1.5)^2 + \tfrac12(\theta_2 - 1.5)^2 with noisy gradient; cc multiplies coordinate 1's entire gradient, noise included. Both variants use the same λ\lambda, as when changing Adam(weight_decay=λ) to AdamW(weight_decay=λ). Increase cc: Adam with L2's final point (red) slides toward unregularized θ1=1.5\theta_1 = 1.5, while AdamW's (aqua) does not move even a thousandth. The bottom panel shows why: actual decay rate per coordinate per step. Then lower noise to zero and set λ=1\lambda = 1: Adam with L2 still goes to the L2 optimum, while AdamW slowly approaches (long v^\hat v memory) the (1,1)(1, 1) corner of box ∥θ∥∞≤1/λ\norm{\theta}_\infty \le 1/\lambda, its point nearest θ∗\theta^*.

The interactive shows a property worth stating precisely, the fundamental reason to prefer decoupled decay in an adaptive method.

Proof

With Sgt\mat{S}\vb{g}_t, moving-average linearity gives mt′=Smt\vb{m}_t' = \mat{S}\vb{m}_t and vt′=S2vt\vb{v}_t' = \mat{S}^2\vb{v}_t (likewise after bias correction). Coordinate-wise, m^t,i′/v^t,i′=sim^t,i/(siv^t,i)=m^t,i/v^t,i\hat m'_{t,i}/\sqrt{\hat v'_{t,i}} = s_i\hat m_{t,i}/(s_i\sqrt{\hat v_{t,i}}) = \hat m_{t,i}/\sqrt{\hat v_{t,i}}, so Adam’s direction is unchanged. AdamW adds −ηλθt-\eta\lambda\theta_t, independent of gradient, and induction over tt yields identical iterates. Adam with L2 averages Sgt+λ′θt\mat{S}\vb{g}_t + \lambda'\theta_t, which is not S\mat{S} times something independent of S\mat{S}: with θt≠0\theta_t \ne 0 and si≠1s_i \ne 1 the ratio changes. The interactive illustrates this: as c→∞c \to \infty, coordinate 1 of Adam with L2 tends to unregularized Adam’s.

∎

Where do the two variants lead? With exact gradient and convergent iterates, the limit can be characterized without knowing the trajectory.

Proof

If θt→θˉ\theta_t \to \bar\theta, continuity gives gt→gˉ\vb{g}_t \to \bar{\vb{g}} (plus λ′θˉ\lambda'\bar\theta for L2). An exponential moving average of a convergent sequence reaches the same limit, and bias corrections tend to 1, so m^t→gˉ\hat{\vb{m}}_t \to \bar{\vb{g}} and v^t→gˉ2\hat{\vb{v}}_t \to \bar{\vb{g}}^2 coordinate-wise. Take limits in the update and subtract θˉ\bar\theta from both sides:

  • L2: 0=−η (gˉi+λ′θˉi)/(∣gˉi+λ′θˉi∣+ε)0 = -\eta\,(\bar g_i + \lambda'\bar\theta_i)/(\abs{\bar g_i + \lambda'\bar\theta_i} + \eps), requiring gˉi+λ′θˉi=0\bar g_i + \lambda'\bar\theta_i = 0.
  • AdamW: 0=−ηλθˉi−η gˉi/(∣gˉi∣+ε)0 = -\eta\lambda\bar\theta_i - \eta\,\bar g_i/(\abs{\bar g_i} + \eps), the stated equality.

Since ∣gˉi∣/(∣gˉi∣+ε)<1\abs{\bar g_i}/(\abs{\bar g_i} + \eps) < 1, λ∣θˉi∣<1\lambda\abs{\bar\theta_i} < 1. If gˉi\bar g_i does not approach zero as ε→0\eps \to 0, the quotient tends to sign⁡(gˉi)\operatorname{sign}(\bar g_i) and λθˉi→−sign⁡(gˉi)\lambda\bar\theta_i \to -\operatorname{sign}(\bar g_i): the weight is on the box boundary and descent direction −gˉi-\bar g_i points outside (gradient points inside), the KKT condition with multiplier μi=∣gˉi∣≥0\mu_i = \abs{\bar g_i} \ge 0.

∎

The proposition concerns only limit points, but Xie and Li (2024) proved a stronger result: with full batch and a suitable schedule, if AdamW converges, it converges to a KKT point of min⁡f\min f subject to ∥θ∥∞≤1/λ\norm{\theta}_\infty \le 1/\lambda. This is very different regularization. L2 changes the objective and shrinks all coordinates toward zero, especially low-curvature ones; noise-free AdamW leaves coordinates fitting inside the box untouched and clips the others. With noise v^\hat{\vb{v}} includes gradient variance and AdamW does shrink interior coordinates: in equilibrium λθi≈−E[gi]/E[gi2]\lambda\theta_i \approx -\E[g_i]/\sqrt{\E[g_i^2]} acts like L2 with coefficient λE[gi2]\lambda\sqrt{\E[g_i^2]}, larger on large-gradient coordinates, opposite to Adam with L2.

AdamW: decoupled decay

Two conventions coexist and should not be mixed. In the original paper, rate is α st\alpha\,s_t, where α\alpha is the base rate and sts_t the schedule multiplier, and decay is stλθs_t\lambda\theta: multiplied by schedule but not α\alpha. Thus α\alpha and λ\lambda are independent hyperparameters, and the authors show the loss heatmap in (α,λ)(\alpha, \lambda) becomes nearly separable. PyTorch (and Optax’s adamw) multiplies decay by full rate: the fraction subtracted each step is ηtλ\eta_t\lambda. With typical LLM values η=3⋅10−4\eta = 3\cdot 10^{-4} and weight_decay=0.1, each step removes only 0.0030.003% of each weight. Transferring λ\lambda between conventions changes actual decay by factor α\alpha (or 1/α1/\alpha), between 10310^{3} and 10410^{4} at typical rates.

Decay as a moving average

Write constant-rate AdamW as θt=(1−ηλ)θt−1−ηut\theta_t = (1 - \eta\lambda)\theta_{t-1} - \eta\vb{u}_t, with ut=m^t/(v^t+ε)\vb{u}_t = \hat{\vb{m}}_t/(\sqrt{\hat{\vb{v}}_t} + \eps). Unroll the recurrence,

θt=(1−ηλ)t θ0  +  ηλ∑k=1t(1−ηλ)t−k(−ukλ).\theta_t = (1 - \eta\lambda)^t\,\theta_0 \;+\; \eta\lambda\sum_{k=1}^{t}(1 - \eta\lambda)^{t-k}\Big(-\frac{\vb{u}_k}{\lambda}\Big).

The second term is an exponential moving average of rescaled updates −uk/λ-\vb{u}_k/\lambda with coefficient ηλ\eta\lambda: AdamW weights remember approximately the last τ=1/(ηλ)\tau = 1/(\eta\lambda) updates and forget initialization at the same rate. With η=3⋅10−4\eta = 3\cdot 10^{-4} and λ=0.1\lambda = 0.1, τ≈33 000\tau \approx 33\,000 steps. Two consequences. First, the relevant timescale is product ηλ\eta\lambda, not λ\lambda alone; compare it to training duration to know whether decay acts (Wang and Aitchison, 2024, propose fixing τ\tau as a fraction of total steps when scaling models and data). Second, as below, ∣uk,i∣\abs{u_{k,i}} is bounded by a constant CβC_\beta depending only on β1\beta_1 and β2\beta_2, so ∣θt,i∣≤(1−ηλ)t∣θ0,i∣+Cβ/λ\abs{\theta_{t,i}} \le (1 - \eta\lambda)^t\abs{\theta_{0,i}} + C_\beta/\lambda: the box of size 1/λ1/\lambda returns.

From scratch: Adam with L2 and AdamW

The two NumPy variants differ by one line. The experiment reproduces the interactive: the same quadratic with coordinate 1 multiplied by cc and identical noise throughout.

[ ]Adam with L2 and AdamW from scratchBrowser
import numpy as np

def adam_l2_step(theta, g, m, v, t, lr, lam, b1=0.9, b2=0.999, eps=1e-8):
    """Adam con penalización L2 (lo que hace torch.optim.Adam con weight_decay)."""
    g = g + lam * theta                          # el regularizador entra en el gradiente...
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g * g                # ...y también en el segundo momento
    m_hat, v_hat = m / (1 - b1**t), v / (1 - b2**t)
    return theta - lr * m_hat / (np.sqrt(v_hat) + eps), m, v

def adamw_step(theta, g, m, v, t, lr, lam, b1=0.9, b2=0.999, eps=1e-8):
    """AdamW con la convención de PyTorch: el decaimiento va multiplicado por la tasa."""
    theta = theta * (1 - lr * lam)               # decaimiento desacoplado, fuera del precondicionador
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g * g
    m_hat, v_hat = m / (1 - b1**t), v / (1 - b2**t)
    return theta - lr * m_hat / (np.sqrt(v_hat) + eps), m, v

# f_c(θ) = ½ c (θ1 − 1.5)² + ½ (θ2 − 1.5)²: c multiplica el gradiente entero de la coordenada 1
target, T, lr, lam, sigma = np.array([1.5, 1.5]), 6000, 0.02, 0.5, 0.5
xi = np.random.default_rng(2).standard_normal((T, 2))      # el mismo ruido para todos

def run(step, c):
    s = np.array([c, 1.0])
    theta, m, v = np.array([-0.3, -0.3]), np.zeros(2), np.zeros(2)
    tail = []
    for t in range(1, T + 1):
        g = s * (theta - target) + s * sigma * xi[t - 1]
        theta, m, v = step(theta, g, m, v, t, lr, lam)
        if t > T // 2:
            tail.append(theta)
    return np.mean(tail, axis=0)                  # media de la segunda mitad: el equilibrio

ref = run(adamw_step, 1.0)
print("    c    Adam + L2 (θ1, θ2)   ridge θ1   AdamW (θ1, θ2)   |AdamW(c) − AdamW(1)|")
for c in [1, 10, 100, 1000]:
    a, w = run(adam_l2_step, c), run(adamw_step, c)
    print(f"{c:5d}     ({a[0]:.3f}, {a[1]:.3f})      {c * 1.5 / (c + lam):.3f}     "
          f"({w[0]:.3f}, {w[1]:.3f})        {np.abs(w - ref).max():.1e}")

The table puts invariance into numbers. AdamW’s column is unchanged when coordinate 1’s gradient is multiplied by a thousand: differences of order 10−910^{-9} come only from ε\eps. Adam with L2 follows the penalized optimum (ridge column, c⋅1.5/(c+λ)c \cdot 1.5/(c + \lambda), apart from averaging stochastic-iterate noise), and θ1\theta_1 moves from 1.01.0 to 1.491.49: practically unregularized. In both variants θ2\theta_2 shrinks, but with L2 each coordinate’s regularization depends on a scale unrelated to what you intended to penalize.

Check the fixed-point proposition just as quickly, now with exact gradient and three coordinates of very different curvature, two with optimum outside the box ∥θ∥∞≤1/λ\norm{\theta}_\infty \le 1/\lambda.

[ ]Without noise: ridge versus the ℓ∞ boxBrowser
# Gradiente exacto de f(θ) = ½ Σ h_i (θ_i − θ*_i)², con curvaturas muy distintas
h = np.array([100.0, 1.0, 0.01])
theta_star = np.array([0.5, 1.5, -3.0])
lam, lr, T = 1.0, 0.01, 20000

for nombre, paso in [("Adam + L2", adam_l2_step), ("AdamW", adamw_step)]:
    theta, m, v = np.zeros(3), np.zeros(3), np.zeros(3)
    for t in range(1, T + 1):
        theta, m, v = paso(theta, h * (theta - theta_star), m, v, t, lr, lam)
    print(f"{nombre:10s} θ_T = {np.round(theta, 4)}")
print("ridge h θ*/(h + λ)       =", np.round(h * theta_star / (h + lam), 4))
print("clip(θ*, −1/λ, 1/λ)      =", np.clip(theta_star, -1 / lam, 1 / lam))

Adam with L2 lands exactly on the ridge solution, which heavily shrinks the curvature-0.010.01 coordinate (from −3-3 to −0.03-0.03) and barely the curvature-100 one. AdamW leaves the first coordinate at optimum 0.50.5 because it fits in the box, and clips the other two to ±1=±1/λ\pm 1 = \pm 1/\lambda: exactly clip⁡(θ∗,−1/λ,1/λ)\operatorname{clip}(\theta^*, -1/\lambda, 1/\lambda), the constrained problem’s KKT point (for a separable quadratic, projection of the optimum onto the box).

Now a small version of Loshchilov and Hutter’s original design: linear regression with two groups of features on very different scales (standard deviations 10 and 1) and same-size true weights. Group A has tenfold gradients. For a fair comparison, sweep λ\lambda and plot the frontier: how much A shrinks at each B shrinkage level, measured as group norm divided by the least-squares solution’s norm.

[ ]Regression with differently scaled features: the regularization frontierBrowser
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
n, dA, dB = 512, 10, 10
X = np.hstack([10.0 * rng.standard_normal((n, dA)), 1.0 * rng.standard_normal((n, dB))])
w_true = rng.standard_normal(dA + dB)
y = X @ w_true + 1.0 * rng.standard_normal(n)
w_ols = np.linalg.lstsq(X, y, rcond=None)[0]
norma = lambda w: (np.linalg.norm(w[:dA]) / np.linalg.norm(w_ols[:dA]), np.linalg.norm(w[dA:]) / np.linalg.norm(w_ols[dA:]))

def entrenar(paso, lam, lr=1e-2, T=2000, bs=32, seed=1):
    r = np.random.default_rng(seed)
    w, m, v = np.zeros(dA + dB), np.zeros(dA + dB), np.zeros(dA + dB)
    for t in range(1, T + 1):
        idx = r.integers(0, n, bs)
        g = X[idx].T @ (X[idx] @ w - y[idx]) / bs
        w, m, v = paso(w, g, m, v, t, lr, lam)
    return w

fronteras = {}
for nombre, paso, lams in [("Adam + L2", adam_l2_step, [0.1, 0.3, 1, 3, 10]),
                           ("AdamW", adamw_step, [0.03, 0.1, 0.3, 1, 3])]:
    puntos = [norma(entrenar(paso, lam)) for lam in lams]
    fronteras[nombre] = puntos
    print(nombre)
    for lam, (a, b) in zip(lams, puntos):
        print(f"   λ = {lam:<5}  grupo A (gradientes grandes) {a:.3f}   grupo B {b:.3f}")

# comprobación: Adam + L2 acaba en la solución ridge, con o sin precondicionador
lam = 1.0
w_ridge = np.linalg.solve(X.T @ X / n + lam * np.eye(dA + dB), X.T @ y / n)
print("ridge con λ = 1:", np.round(norma(w_ridge), 3))

for nombre, color in [("Adam + L2", "C3"), ("AdamW", "C2")]:
    b, a = zip(*[(p[1], p[0]) for p in fronteras[nombre]])
    plt.plot(b, a, "o-", color=color, label=nombre)
plt.plot([0, 1], [0, 1], ":", color="gray", label="encogimiento igual")
plt.xlabel("norma relativa del grupo B (gradientes pequeños)")
plt.ylabel("norma relativa del grupo A (gradientes grandes)")
plt.legend(); plt.show()

The Adam-with-L2 frontier is almost horizontal: to shrink B to one quarter its norm, A retains 97%. This frontier is exactly ridge’s (the final check confirms at λ=1\lambda = 1), because ridge shrinks curvature-hh directions by h/(h+λ)h/(h + \lambda) and group A’s curvature is 100 times B’s. AdamW distributes shrinkage: with B at the same quarter, A stays around half. Neither frontier is abstractly “correct”; the experiment shows that with L2, feature scale answers “how much should each weight be regularized?”, not you. AdamW’s distribution generalizing better in deep networks is an empirical observation (Loshchilov and Hutter’s, later reinforced by nearly all LLM pretraining practice), not a theorem.

η, λ and the learning-rate schedule

In PyTorch’s convention a weight loses fraction ηtλ\eta_t\lambda at step tt. After TT steps, from decay alone,

∏t=1T(1−ηtλ)  =  exp⁡(∑t=1Tlog⁡(1−ηtλ))  ≈  exp⁡(−λ∑t=1Tηt),\prod_{t=1}^{T}(1 - \eta_t\lambda) \;=\; \exp\Big(\sum_{t=1}^{T}\log(1 - \eta_t\lambda)\Big) \;\approx\; \exp\Big(-\lambda\sum_{t=1}^{T}\eta_t\Big),

with negligible relative error when ηtλ≪1\eta_t\lambda \ll 1. Accumulated decay depends on the area under the rate schedule. With the cosine schedule from ηmax⁡\eta_{\max} to 0 over TT steps, ∑tηt=ηmax⁡(T+1)/2\sum_t\eta_t = \eta_{\max}(T + 1)/2; with ηmax⁡=3⋅10−4\eta_{\max} = 3\cdot 10^{-4}, λ=0.1\lambda = 0.1 and T=105T = 10^5, the factor is e−1.5≈0.22e^{-1.5} \approx 0.22. Three practical consequences:

  1. Changing rate changes regularization. In PyTorch doubling lr also doubles per-step decay. To explore rate at fixed regularization, hold lr * weight_decay constant, or use the paper’s convention, decoupling α\alpha and λ\lambda.
  2. Changing horizon changes regularization. At fixed ηλ\eta\lambda, doubling steps doubles the exponent. Loshchilov and Hutter therefore proposed normalized decay λ=λnormb/(BT)\lambda = \lambda_{\text{norm}}\sqrt{b/(BT)}, with bb batch size, BB number of examples and TT number of epochs; Wang and Aitchison (2024) argue τ=1/(ηλ)\tau = 1/(\eta\lambda) measured in epochs transfers well across scales.
  3. The schedule’s end barely decays. When ηt→0\eta_t \to 0 at cosine’s end, decay vanishes with it. The same occurs in the paper’s convention because decay is multiplied by sts_t.

Parameters to exclude from decay

Decay controls the scale of weights multiplying activations. Applying it indiscriminately has concrete costs:

  • Biases. Few in number, they do not usefully control model capacity and pushing them to zero only introduces systematic bias.
  • Normalization gains (γ\gamma in LayerNorm or RMSNorm). Their natural value is 1, not 0. Decaying them shrinks each normalized block’s output scale, which the network must compensate using other weights.
  • Embeddings. Debatable. AdamW decay acts at every step, but a token row’s gradient is nonzero only when that token appears in the batch: rare-token embeddings shrink continuously and are corrected occasionally. minGPT excluded embeddings from decay; nanoGPT decays every parameter with two or more dimensions (linear-layer matrices and embeddings), and nothing else. Both practices coexist; the choice deserves an experiment, not habit.

nanoGPT’s p.dim() >= 2 rule is the shortest way to separate groups and appears in the PyTorch section.

Adam that does not converge: Reddi et al.’s counterexample

Last lesson showed Adam arose in online convex optimization, measuring regret RT=∑t=1Tft(xt)−min⁡x∈F∑t=1Tft(x)R_T = \sum_{t=1}^T f_t(x_t) - \min_{x \in \mathcal{F}}\sum_{t=1}^T f_t(x) and requiring RT/T→0R_T/T \to 0. Adam’s original paper included a proof of RT=O(T)R_T = \bigO(\sqrt T). Reddi, Kale and Kumar (2018) found an error and, more importantly, a one-dimensional counterexample.

Watch Adam with β1=0\beta_1 = 0 (no momentum, which only complicates the calculation) and small β2\beta_2. After gradient CC, vt≈C2v_t \approx C^2 and the step is αt C/vt≈αt\alpha_t\,C/\sqrt{v_t} \approx \alpha_t toward −1-1. In the next two steps vv quickly forgets C2C^2, vt≈1v_t \approx 1, and each −1-1 gradient produces a step ≈αt\approx \alpha_t toward +1+1. Two against one: Adam goes to +1+1. Normalization, exactly what makes Adam useful when coordinate scales differ, erases magnitude information distinguishing the rare important gradient from frequent small ones.

We can locate the exact threshold. With β1=0\beta_1 = 0 and rate nearly constant inside a period, vtv_t reaches a periodic regime of three values, vav_a just after gradient CC and vbv_b, vcv_c after the two −1-1s. Imposing periodicity,

va=(1−β2)(C2+β2+β22)1−β23,vb=β2va+(1−β2),vc=β2vb+(1−β2),v_a = \frac{(1 - \beta_2)(C^2 + \beta_2 + \beta_2^2)}{1 - \beta_2^3}, \qquad v_b = \beta_2 v_a + (1 - \beta_2), \qquad v_c = \beta_2 v_b + (1 - \beta_2),

and a period’s net displacement is proportional to Δ(β2)=−C/va+1/vb+1/vc\Delta(\beta_2) = -C/\sqrt{v_a} + 1/\sqrt{v_b} + 1/\sqrt{v_c}. If Δ>0\Delta > 0, Adam drifts to +1+1; if Δ<0\Delta < 0, to −1-1. As β2→1\beta_2 \to 1, va,vb,vc→(C2+2)/3v_a, v_b, v_c \to (C^2 + 2)/3 and Δ→(2−C)/(C2+2)/3<0\Delta \to (2 - C)/\sqrt{(C^2 + 2)/3} < 0; as β2→0\beta_2 \to 0, Δ→−1+1+1=1>0\Delta \to -1 + 1 + 1 = 1 > 0. Between lies threshold β2∗(C)\beta_2^*(C): for C=3C = 3 it is 0.4720.472, approaching 1 as C→2C \to 2.

InteractiveAdam that does not converge
Iterate xtx_t in [−1,1][-1, 1] (the optimum is x∗=−1x^* = -1)
  • Adam
  • AMSGrad
  • optimum x∗=−1x^* = -1
Average regret Rt/tR_t/t: it tends to 0 only if the method learns
  • Adam
  • AMSGrad
0.100
3.00
3.00−1−13.00−1−13.00−1−1…
t = 3000
Threshold β2∗(C)\beta_2^*(C)0.472
Adam: xtx_t1.000
AMSGrad: xtx_t−0.994
Adam: step with CC−0.0096
Adam: step with each −1-1+0.0079
Net per period, Adam+0.0062
Net per period, AMSGrad−0.0032
Rt/tR_t/t, Adam0.672
Rt/tR_t/t, AMSGrad0.012
Con β2=0.100<β2∗≈0.472\beta_2 = 0.100 < \beta_2^* \approx 0.472, Adam normalizes each gradient almost by itself: gradient CC pushes toward −1-1 by a step of size ≈αt\approx\alpha_t and each −1-1 pushes toward +1+1 by the same amount. Two against one: xt→+1x_t \to +1, the worst point. AMSGrad converges to x∗=−1x^* = -1.
Adam (orange) and AMSGrad (violet) iterate xtx_t on Reddi et al.'s problem, with β1=0\beta_1 = 0, step αt=0.5/t\alpha_t = 0.5/\sqrt t and projection onto [−1,1][-1, 1]. Boxes show gradient sequence. At initial β2\beta_2, Adam goes to +1+1 and mean regret plateaus at 2(C−2)/32(C - 2)/3; AMSGrad converges to −1-1. Increase β2\beta_2 past readout threshold β2∗\beta_2^* and watch Adam switch destination. Then move CC close to 2: the threshold rises toward 1, and for every fixed β2<1\beta_2 < 1 some CC breaks Adam.

Reddi et al. turn this observation into theorems. For β1=0\beta_1 = 0 and β2=1/(1+C2)\beta_2 = 1/(1 + C^2) (problem-dependent), the above problem has RT/T↛0R_T/T \not\to 0. They generalize: for any β1,β2∈[0,1)\beta_1, \beta_2 \in [0, 1) with β1<β2\beta_1 < \sqrt{\beta_2} there is an online convex problem, and also a stochastic one, where Adam fails to converge to optimum. The flaw is identified in the original proof: analysis needs the effective coordinate rate αt/v^t,i\alpha_t/\sqrt{\hat v_{t,i}} not to increase with tt, namely,

Γt+1,i  =  v^t+1,iαt+1−v^t,iαt  ≥  0,\Gamma_{t+1,i} \;=\; \frac{\sqrt{\hat v_{t+1,i}}}{\alpha_{t+1}} - \frac{\sqrt{\hat v_{t,i}}}{\alpha_t} \;\ge\; 0,

and in Adam, when vv forgets a large gradient, Γ\Gamma becomes negative: effective rate rises just after the informative gradient.

In the example, AMSGrad remembers v≥(1−β2)C2v \ge (1 - \beta_2)C^2 forever, so three period steps share (almost) the same denominator and their total is proportional to −C+1+1=−(C−2)<0-C + 1 + 1 = -(C - 2) < 0: toward optimum. Reddi et al. prove AMSGrad has RT=O(T)R_T = \bigO(\sqrt T) for online convex optimization with bounded domain, bounded gradients and decreasing β1\beta_1; later analysis (Alacaoglu et al., 2020) extends to constant β1\beta_1. PyTorch offers amsgrad=True. It has not become standard in deep learning: it rarely improves tuned Adam, suggesting the counterexample does not describe Adam’s operating regime.

[ ]Reddi's counterexample and β2 thresholdBrowser
import numpy as np

def reddi(C, b2, T=3000, alpha=0.5, amsgrad=False):
    """Adam con β1 = 0 y sin corrección de sesgo (como en el artículo), proyectado en [-1, 1]."""
    x, v, v_max, regret = 0.0, 0.0, 0.0, 0.0
    for t in range(1, T + 1):
        g = C if t % 3 == 1 else -1.0
        regret += g * x - g * (-1.0)              # f_t(x_t) − f_t(x*), con x* = −1
        v = b2 * v + (1 - b2) * g * g
        v_max = max(v_max, v)
        denom = np.sqrt(v_max if amsgrad else v)
        x = float(np.clip(x - alpha / np.sqrt(t) * g / denom, -1.0, 1.0))
    return x, regret / T

def drift(C, b):
    """Saldo de un periodo en el régimen periódico de v (paso constante dentro del periodo)."""
    va = (1 - b) * (C * C + b + b * b) / (1 - b**3)    # v justo tras el gradiente C
    vb = b * va + (1 - b)
    vc = b * vb + (1 - b)
    return -C / np.sqrt(va) + 1 / np.sqrt(vb) + 1 / np.sqrt(vc)

def umbral(C, lo=1e-9, hi=1 - 1e-9):
    for _ in range(80):                                # bisección: drift decrece con β2
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if drift(C, mid) > 0 else (lo, mid)
    return (lo + hi) / 2

C = 3.0
print(f"C = {C}: umbral β2* = {umbral(C):.4f}   (β2 del artículo: 1/(1 + C²) = {1 / (1 + C * C):.3f})")
print("  β2     Adam: x_T   R_T/T    AMSGrad: x_T   R_T/T")
for b2 in [0.1, 0.3, 0.45, 0.5, 0.9, 0.99]:
    xa, ra = reddi(C, b2)
    xm, rm = reddi(C, b2, amsgrad=True)
    print(f"{b2:5.2f}      {xa:+.3f}    {ra:.3f}        {xm:+.3f}     {rm:.3f}")
print("R_T/T límite si x_t → +1:", round(2 * (C - 2) / 3, 4))
print("umbral según C:", {c: round(umbral(c), 3) for c in [2.1, 2.5, 3, 5, 10]})

Simulation confirms periodic-regime analysis. Below β2∗=0.472\beta_2^* = 0.472, Adam ends at +1+1 with mean regret ≈0.67=2(C−2)/3\approx 0.67 = 2(C - 2)/3; just below threshold (0.450.45) drift is so slow it has not arrived in 3000 steps; above it converges like AMSGrad. The threshold spans (0,1)(0, 1) as CC varies: 0.8860.886 for C=2.1C = 2.1, 0.0980.098 for C=10C = 10. This is Reddi’s precise theorem: the bad problem is chosen after fixing β2\beta_2.

What modern analyses guarantee

The counterexample left a question: if Adam can fail on a one-dimensional convex problem, why does it work in networks with billions of parameters? Recent answers have three pieces. The first is elementary and explains condition β1<β2\beta_1 < \sqrt{\beta_2} appearing in all theorems.

Proof

Unrolling moving averages, mt=(1−β1)∑j=0t−1β1jgt−jm_t = (1 - \beta_1)\sum_{j=0}^{t-1}\beta_1^j g_{t-j} and vt=(1−β2)∑j=0t−1β2jgt−j2v_t = (1 - \beta_2)\sum_{j=0}^{t-1}\beta_2^j g_{t-j}^2. Write β1jgt−j=γj⋅β2j/2gt−j\beta_1^j g_{t-j} = \gamma^j\cdot\beta_2^{j/2}g_{t-j} and apply Cauchy–Schwarz:

∣mt∣≤(1−β1)(∑j=0t−1γ2j)1/2(∑j=0t−1β2jgt−j2)1/2≤(1−β1) 11−γ2 vt1−β2.\abs{m_t} \le (1 - \beta_1)\Big(\sum_{j=0}^{t-1}\gamma^{2j}\Big)^{1/2}\Big(\sum_{j=0}^{t-1}\beta_2^j g_{t-j}^2\Big)^{1/2} \le (1 - \beta_1)\,\frac{1}{\sqrt{1 - \gamma^2}}\,\sqrt{\frac{v_t}{1 - \beta_2}}.

Equality in Cauchy–Schwarz requires β2j/2gt−j∝γj\beta_2^{j/2}g_{t-j} \propto \gamma^j, i.e. gt−j∝(β1/β2)jg_{t-j} \propto (\beta_1/\beta_2)^j, which as t→∞t \to \infty also saturates the geometric sum. If γ≥1\gamma \ge 1, the same sequence makes ∑jγ2j≥t\sum_j\gamma^{2j} \ge t and the ratio grows at least as t\sqrt t (exactly t\sqrt t if γ=1\gamma = 1, geometrically if γ>1\gamma > 1).

∎

With defaults (0.9,0.999)(0.9, 0.999), the bound is 7.277.27; with LLM values (0.9,0.95)(0.9, 0.95), 1.161.16. Without sustained gradient growth the ratio is much smaller (around 1 or less), but its existence matters: each coordinate moves at most Cβ ηC_\beta\,\eta per step regardless of gradient. Adam is by construction a trust-region method in ℓ∞\ell_\infty norm; bias correction adds only factor 1−β2t/(1−β1t)\sqrt{1 - \beta_2^t}/(1 - \beta_1^t), tending to 1.

[ ]Adam's step bound attainedBrowser
import numpy as np

def cociente(g, b1, b2):
    """|m_t| / sqrt(v_t) al final de la secuencia de gradientes g (sin corrección de sesgo)."""
    m = v = 0.0
    for gt in g:
        m = b1 * m + (1 - b1) * gt
        v = b2 * v + (1 - b2) * gt * gt
    return abs(m) / np.sqrt(v)

rng = np.random.default_rng(0)
T = 2000
for b1, b2 in [(0.9, 0.999), (0.9, 0.95), (0.0, 0.5), (0.9, 0.81)]:
    gamma = b1 / np.sqrt(b2)
    cota = (1 - b1) / np.sqrt((1 - b2) * (1 - gamma**2)) if gamma < 1 else np.inf
    extremo = (b2 / b1) ** np.arange(-T, 0, dtype=float) if b1 > 0 else np.r_[np.zeros(T - 1), 1.0]
    azar = max(cociente(rng.standard_normal(T) + 0.5, b1, b2) for _ in range(30))
    print(f"β1 = {b1}, β2 = {b2}:  γ = {gamma:.3f}   cota = {cota:6.3f}   "
          f"secuencia extrema = {cociente(extremo, b1, b2):6.3f}   gradientes al azar ≤ {azar:5.3f}")

With β2=0.81=β12\beta_2 = 0.81 = \beta_1^2 (γ=1\gamma = 1), the extreme sequence gives 10.26=0.1/0.19⋅200010.26 = 0.1/\sqrt{0.19}\cdot\sqrt{2000}: growing as t\sqrt t, unbounded.

The second piece is nonconvex convergence proofs, relevant to deep learning. We call Adam convergence analysis the results since 2018 responding to Reddi et al. The two most cited are:

  • Défossez, Bottou, Bach and Usunier (2022). For ff bounded below, LL-smooth and with stochastic gradients bounded in ℓ∞\ell_\infty norm almost surely, they give an explicit bound on E∥∇f(θτ)∥2\E\norm{\grad f(\theta_\tau)}^2 for random iterate τ\tau, in terms of LL, gradient bound, dimension dd, α\alpha, β1\beta_1, β2\beta_2 and steps NN. With constant α\alpha and β2\beta_2, the bound contains a term not vanishing as N→∞N \to \infty: default Adam converges not to a stationary point but a neighborhood, like constant-step SGD. With β2=1−1/N\beta_2 = 1 - 1/N and α∝1/N\alpha \propto 1/\sqrt N the bound is O(dln⁡N/N)\bigO(d\ln N/\sqrt N), the rate of AdaGrad and, apart from logarithm and dimension, nonconvex SGD. They also improve momentum dependence from (1−β1)−3(1 - \beta_1)^{-3} to (1−β1)−1(1 - \beta_1)^{-1} under β1<β2\beta_1 < \beta_2.
  • Zhang, Chen, Shi, Sun and Luo (2022). They note the quantifier mismatch: Reddi et al. choose the problem after (β1,β2)(\beta_1, \beta_2), while practice fixes the problem then tunes β\beta. In that order, for finite sums, if β2\beta_2 is sufficiently large (problem-dependent threshold, particularly number of terms) and β1<β2\beta_1 < \sqrt{\beta_2}, unmodified Adam converges to a critical-point neighborhood sized by individual-term gradient noise, and to critical points under strong growth (that noise vanishes when the total gradient does). Bounded gradients are unnecessary. They also prove the other half: for small β2\beta_2 a large hyperparameter region makes Adam diverge. Increasing β2\beta_2 yields a phase transition, exactly as in the Reddi figure.

The third piece is smoothness. Deep networks are poorly described as LL-smooth with a reasonable global LL: measured local curvature grows with gradient norm during training. Generalized (L0,L1)(L_0, L_1) smoothness, ∥∇2f(θ)∥≤L0+L1∥∇f(θ)∥\norm{\hess f(\theta)} \le L_0 + L_1\norm{\grad f(\theta)}, proposed by Zhang, He, Sra and Jadbabaie (2020) to explain why gradient clipping accelerates training, fits measurements much better; Li, Rakhlin and Jadbabaie (2023) prove Adam convergence under it. A method with a built-in bounded step, like Adam by the previous theorem, suits a function whose curvature explodes where gradients are large.

Adam as sign descent

Take extreme Adam: no averaging, β1=β2=0\beta_1 = \beta_2 = 0, and no ε\eps. Then m^t=gt\hat{\vb{m}}_t = \vb{g}_t and v^t=gt2\hat{\vb{v}}_t = \vb{g}_t^2, and the step is gt,i/∣gt,i∣=sign⁡(gt,i)g_{t,i}/\abs{g_{t,i}} = \operatorname{sign}(g_{t,i}): Adam is signSGD, θt+1=θt−ηsign⁡(gt)\theta_{t+1} = \theta_t - \eta\operatorname{sign}(\vb{g}_t) (Bernstein et al., 2018). You will prove this carefully in an exercise. What remains of the identity with β\beta near 1 and noisy gradients?

Balles and Hennig (2018) suggest reading Adam as a product of two factors. If a coordinate’s stochastic gradient has mean μi\mu_i and variance σi2\sigma_i^2, and moving averages are long enough to average noise, mt,i≈μim_{t,i} \approx \mu_i and vt,i≈μi2+σi2v_{t,i} \approx \mu_i^2 + \sigma_i^2, so

m^t,iv^t,i  ≈  μiμi2+σi2  =  sign⁡(μi)⋅11+σi2/μi2.\frac{\hat m_{t,i}}{\sqrt{\hat v_{t,i}}} \;\approx\; \frac{\mu_i}{\sqrt{\mu_i^2 + \sigma_i^2}} \;=\; \operatorname{sign}(\mu_i)\cdot\frac{1}{\sqrt{1 + \sigma_i^2/\mu_i^2}}.

The first factor is sign direction; the second damps it, nearly 1 when signal-to-noise ratio ∣μi∣/σi\abs{\mu_i}/\sigma_i is high and ≈∣μi∣/σi\approx\abs{\mu_i}/\sigma_i when low. Adam is sign descent damped coordinate-wise by signal-to-noise ratio. With β=0\beta = 0 the step is sign⁡(gt,i)\operatorname{sign}(g_{t,i}), whose mean E[sign⁡(gt,i)]=2Φ(μi/σi)−1\E[\operatorname{sign}(g_{t,i})] = 2\Phi(\mu_i/\sigma_i) - 1 for Gaussian gradients damps differently.

[ ]Adam's mean step versus signal-to-noise ratioBrowser
import numpy as np
from math import erf, sqrt

def paso_medio(mu, sigma, b1, b2, T=20000, seed=0):
    """Media de la actualización de Adam, m̂/√v̂, con gradientes iid N(mu, sigma²) en una coordenada."""
    g = mu + sigma * np.random.default_rng(seed).standard_normal(T)
    m = v = 0.0
    u = np.empty(T)
    for t in range(1, T + 1):
        m = b1 * m + (1 - b1) * g[t - 1]
        v = b2 * v + (1 - b2) * g[t - 1] ** 2
        u[t - 1] = (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + 1e-12)
    return u[T // 2:].mean()

print(" μ/σ    β=(0, 0)   2Φ(μ/σ)−1    β=(0.9, 0.999)   μ/sqrt(μ²+σ²)")
for snr in [10, 3, 1, 0.3, 0.1]:
    print(f"{snr:5.1f}    {paso_medio(snr, 1.0, 0, 0):.3f}      {erf(snr / sqrt(2)):.3f}         "
          f"{paso_medio(snr, 1.0, 0.9, 0.999):.3f}           {snr / sqrt(snr**2 + 1):.3f}")

The two columns of each pair agree up to Monte Carlo noise. With strong signal μ/σ=10\mu/\sigma = 10, Adam takes steps of size η\eta with the mean gradient’s sign: pure sign descent. With weak signal the step shrinks in proportion to μ/σ\mu/\sigma.

ℓ∞ geometry

Why is sign a natural direction? It is steepest descent when distances use ℓ∞\ell_\infty norm, precisely Adam’s trust-region geometry (each coordinate moves at most Cβ ηC_\beta\,\eta, around η\eta).

Proof

For any d\vb{d} with ∣di∣≤1\abs{d_i} \le 1, ⟨g,d⟩=∑igidi≥−∑i∣gi∣∣di∣≥−∑i∣gi∣\inner{\vb{g}}{\vb{d}} = \sum_i g_i d_i \ge -\sum_i\abs{g_i}\abs{d_i} \ge -\sum_i\abs{g_i}. Both inequalities are equalities if and only if, on every coordinate with gi≠0g_i \ne 0, di=−sign⁡(gi)d_i = -\operatorname{sign}(g_i). The ℓ1\ell_1 norm appears as the dual of ℓ∞\ell_\infty.

∎

Compare with gradient descent using the descent lemma in each geometry. If f(y)≤f(x)+⟨∇f(x),y−x⟩+L∞2∥y−x∥∞2f(\vb{y}) \le f(\vb{x}) + \inner{\grad f(\vb{x})}{\vb{y} - \vb{x}} + \tfrac{L_\infty}{2}\norm{\vb{y} - \vb{x}}_\infty^2, step −ηsign⁡(∇f)-\eta\operatorname{sign}(\grad f) with best η\eta guarantees decrease ∥∇f∥12/(2L∞)\norm{\grad f}_1^2/(2L_\infty), versus gradient descent’s ∥∇f∥22/(2L2)\norm{\grad f}_2^2/(2L_2). For diagonal quadratic 12∑ihixi2\tfrac12\sum_i h_i x_i^2 with hi≥0h_i \ge 0, L2=max⁡ihiL_2 = \max_i h_i and L∞=sup⁡∥d∥∞≤1d⊤diag⁡(h)d=∑ihiL_\infty = \sup_{\norm{\vb{d}}_\infty \le 1}\vb{d}\T\diag(\vb{h})\vb{d} = \sum_i h_i, so the sign guarantee is better exactly when

∥g∥12∥g∥22  >  ∑ihimax⁡ihi.\frac{\norm{\vb{g}}_1^2}{\norm{\vb{g}}_2^2} \;>\; \frac{\sum_i h_i}{\max_i h_i}.

Both ratios lie between 1 and dd. The left counts how many gradient coordinates really matter; the right counts how many have curvature comparable to the maximum. Dense gradient and curvature concentrated on a few coordinates: sign wins. Gradient concentrated on a few coordinates and distributed curvature: gradient wins. The price is lack of rotation invariance: sign sees only coordinate axes. General steepest-descent theory in other norms, and methods such as Lion (Chen et al., 2023), explicitly using sign, are covered in sign descent in lesson 26.

InteractiveAdam as sign
Trajectories in the bowl
  • SGD
  • signSGD
  • Adam
Adam steps, ut=−Δθt/ηu_t = -\Delta\theta_t/\eta
ℓ∞ unit ball
0.90
0.999
0.50
100
0°
0.060
0.50
step 160
Mean cosine with sign⁡(g)\operatorname{sign}(g)0.296
Steps at a corner4 %
Mean ∥ut∥∞\norm{u_t}_\infty0.273
ff, SGD0.0797
ff, signSGD0.0208
ff, Adam1.62e−5
With noise, v^\hat v includes variance and steps shrink in low-signal coordinates: Adam is sign multiplied by an estimated signal-to-noise ratio. Reduce noise and the β\beta values.
Trajectory panel: SGD (blue), signSGD (magenta) and Adam (orange) on elongated bowl f=12θ⊤Hθf = \tfrac12\theta\T\mat{H}\theta, with H\mat{H} eigenvalues 1 and κ\kappa. Step panel: each normalized Adam update ut=−Δθt/ηu_t = -\Delta\theta_t/\eta inside the ℓ∞\ell_\infty unit ball (square) and ℓ2\ell_2 unit ball (dashed circle). With defaults, steps start from corner (−1,1)(-1, 1), sign of the first gradient, and shrink toward the center as mean gradient fades relative to noise and v^\hat v memory. Select limit (β1=β2=0\beta_1 = \beta_2 = 0, no noise): the cloud collapses to corners (±1,±1)(\pm 1, \pm 1) and Adam's trajectory overlays sign's characteristic 45° diagonal path. Rotate the bowl 45°: sign stops being a good direction because it only sees axes.

Two things to notice. Sign advances diagonally until the high-curvature coordinate oscillates around its minimum with amplitude η\eta; then only the other progresses, at constant speed. SGD, limited by maximum curvature (η<2/κ\eta < 2/\kappa, with κ\kappa the largest eigenvalue of H\mat{H}), progresses very slowly in the flat direction, where sign gains most by ignoring scale.

Why does Adam win on transformers?

In convolutional vision networks, well-tuned SGD with momentum matches or beats Adam, and Wilson et al. (2017) showed overparameterized problems where adaptive methods generalize worse. For transformers and language models the reverse holds: SGD is clearly worse and nobody trains an LLM with it. The Adam–SGD gap is this persistent performance difference depending on architecture and data. Four main, nonexclusive hypotheses explain it:

  1. Heavy-tailed noise. Zhang et al. (2020) measured much heavier stochastic-gradient noise tails in attention models than convolutional networks; SGD suffers extremes, while clipping or Adam normalization controls them.
  2. Sign, not noise. Kunstner, Chen, Lavington and Schmidt (2023) trained with ever-larger batches to full batch: the gap persists even without noise. Noise cannot be the main cause. Momentum sign descent, ignoring magnitude, instead behaves like Adam at full batch.
  3. Heavy-tailed class imbalance. Kunstner et al. (2024) identify a data property: language-model “classes” are vocabulary tokens, with approximately Zipf-distributed frequencies. Gradient descent progresses very slowly on rare-class loss, collectively significant; Adam and sign descent do not. They show this in language transformers, CNNs trained on deliberately imbalanced ImageNet, and linear models.
  4. Block-heterogeneous Hessian. Zhang et al. (2024) observe very different Hessian spectra among transformer parameter blocks (query/key, value, MLP and embedding matrices), while CNN blocks are similar. SGD’s single rate cannot suit blocks with curvatures orders of magnitude apart; a coordinate preconditioner can.

The third hypothesis has a one-line mechanism. For a linear softmax model with weights W\mat{W} (one row wk\vb{w}_k per class), loss is ∑kπk E[ℓ(Wx,k)∣y=k]\sum_k\pi_k\,\E[\ell(\mat{W}\vb{x}, k) \given y = k], where πk\pi_k is class kk‘s frequency, and

∇wk=πk E[(pk(x)−1) x∣y=k]⏟empuje hacia arriba, ∝ πk  +  ∑j≠kπj E[pk(x) x∣y=j]⏟empuje hacia abajo.\grad_{\vb{w}_k} = \underbrace{\pi_k\,\E\big[(p_k(\vb{x}) - 1)\,\vb{x} \given y = k\big]}_{\text{empuje hacia arriba, } \propto\, \pi_k} \;+\; \underbrace{\sum_{j \ne k}\pi_j\,\E\big[p_k(\vb{x})\,\vb{x} \given y = j\big]}_{\text{empuje hacia abajo}}.

The signal training class kk is proportional to its frequency, as is the corresponding Hessian block. Gradient descent moves row kk at speed ∝ηπk\propto \eta\pi_k, with η\eta limited by frequent-class curvature. With πk∝k−s\pi_k \propto k^{-s}, class 100 is 100s100^s times slower than class 1. Adam divides each coordinate by its scale and moves all rows at speed ≈η\approx\eta.

InteractiveRare classes and Adam
Gradient descent (full batch)
  • classes 1 to 3
  • 4 to 10
  • 11 to 30
  • 31 to 100
  • log K (no learning)
Adam (full batch)
  • classes 1 to 3
  • 4 to 10
  • 11 to 30
  • 31 to 100
  • log K (no learning)
2.00
18
1.0
Mass per group (%)83.2 · 11.5 · 3.8 · 1.4
Classes 1 to 3: GD / Adam0.79 / 0.78
4 to 10: GD / Adam0.83 / 0.82
11 to 30: GD / Adam2.18 / 0.95
31 to 100: GD / Adam4.88 / 1.27
Total: GD / Adam0.879 / 0.792
The 70 rarest classes account for 1.4 % of the data. Gradient descent leaves them at 4.88 nats (almost no learning: starting from log⁡K=4.61\log K = 4.61), while Adam lowers them to 1.27. Their gradient is proportional to πk\pi_k; Adam normalizes it coordinate by coordinate.
Linear softmax model with 100 classes of frequencies πk∝k−s\pi_k \propto k^{-s}, full-batch gradient (no noise), 150 steps. Each panel shows loss for four class groups from the three most frequent (blue) to the seventy rarest (red); dashed line is log⁡K\log K, unlearned loss. Labels are smoothed (ρ=0.1\rho = 0.1) so weights do not grow without bound, hence no loss falls below 0.78; the axis is clipped at top because high rates give larger transient early spikes. With initial s=2s = 2 and tuned rates, gradient descent learns frequent classes and leaves rare ones near their start; Adam learns all. Lower ss to 1.5, 1 and 0: the gap narrows and disappears. Tune η after each change: comparison is fair only with each method's best rate.

An experiment distinguishing hypotheses

The four hypotheses predict different things, allowing experiments that distinguish them. The principle is to change one factor and hold the others fixed, with each optimizer tuned on the same budget (same rate grid, step count and several seeds).

InterventionHeavy-tailed noiseSignClass imbalanceBlock Hessian
Full batch instead of minibatchesgap disappearspersistspersistspersists
Rebalance classes (subsample or reweight)no clear changeno clear changegap shrinks greatlyno clear change
Momentum sign instead of Adam, full batchno gap to explainlike Adamlike Adamdepends
SGD with a different rate per blocklittle effectlittle effectlittle effect (imbalance is within output block)gap shrinks
Measure loss by class frequencyuniformuniformSGD stalled on rare classesuniform

Published evidence says noise is not the main cause (first row) and supports both class imbalance and block heterogeneity; they are compatible because class imbalance specifically creates heterogeneity in output and embedding layers. Check on a small scale: the next cell trains, in seconds on CPU, a linear softmax model (imbalance only in outputs) and an MLP with embeddings on bigram-like pairs (Zipf-distributed input and output tokens), using SGD with momentum, Adam and AdamW, each at its best grid rate with optimum enclosed (the cell warns if best rate falls at an edge), and measures loss by frequency group.

[ ]Adam versus SGD with Zipf-like classesLocal GPU
import time, numpy as np, torch, torch.nn as nn, torch.nn.functional as F

t0 = time.time()
torch.set_num_threads(2)
device = "cpu"                     # el experimento es pequeño: unos segundos en CPU
K, s, steps, B = 128, 1.5, 200, 128
g = torch.Generator().manual_seed(0)
pi = torch.arange(1, K + 1, dtype=torch.float32) ** -s
pi /= pi.sum()
grupos = [(0, 4), (4, 16), (16, 48), (48, K)]

# A) lineal softmax: x = prototipo de la clase + ruido; el desequilibrio está solo en las salidas
d = 16
mu = torch.randn(K, d, generator=g) / d**0.5
def lote_lineal(n, gen):
    y = torch.multinomial(pi, n, replacement=True, generator=gen)
    return mu[y] + 0.05 * torch.randn(n, d, generator=gen), y

# B) MLP con embeddings sobre bigramas: la ficha de entrada determina la de salida (una permutación),
#    y las dos siguen la ley de Zipf, como en un modelo de lenguaje
siguiente = torch.randperm(K, generator=g)
def lote_bigrama(n, gen):
    y = torch.multinomial(pi, n, replacement=True, generator=gen)
    return siguiente[y], y

def modelo(tipo):
    torch.manual_seed(1)
    if tipo == "lineal":
        return nn.Linear(d, K)
    return nn.Sequential(nn.Embedding(K, 32), nn.Linear(32, 64), nn.ReLU(), nn.Linear(64, K))

def entrenar(tipo, nombre, lr):
    net = modelo(tipo).to(device)
    opt = {"SGD": lambda p: torch.optim.SGD(p, lr=lr, momentum=0.9),
           "Adam": lambda p: torch.optim.Adam(p, lr=lr),
           "AdamW": lambda p: torch.optim.AdamW(p, lr=lr, weight_decay=0.01)}[nombre](net.parameters())
    gen = torch.Generator().manual_seed(2)
    lote = lote_lineal if tipo == "lineal" else lote_bigrama
    for _ in range(steps):
        x, y = lote(B, gen)
        loss = F.cross_entropy(net(x), y)
        opt.zero_grad(); loss.backward(); opt.step()
    # evaluación: pérdida media de cada clase, agrupada por frecuencia
    x, y = lote(20000, torch.Generator().manual_seed(3))
    with torch.no_grad():
        l = F.cross_entropy(net(x), y, reduction="none")
    cuenta = torch.bincount(y, minlength=K)
    por_clase = torch.zeros(K).index_add_(0, y, l) / cuenta.clamp(min=1)
    por_grupo = [por_clase[a:b][cuenta[a:b] > 0].mean().item() for a, b in grupos]
    return l.mean().item(), por_grupo

# una rejilla por modelo y optimizador, ampliada hasta que la mejor tasa quede en el interior:
# si el óptimo cae en un extremo, la comparación mide la rejilla, no el optimizador
rejillas = {"lineal": {"SGD": [10, 30, 60, 100], "Adam": [0.1, 0.3, 0.5, 1.0], "AdamW": [0.1, 0.3, 0.5, 1.0]},
            "bigrama": {"SGD": [0.3, 0.5, 0.7, 1.0], "Adam": [0.01, 0.03, 0.1], "AdamW": [0.01, 0.03, 0.1]}}
for tipo, por_opt in rejillas.items():
    print(f"\n{tipo}: pérdida por grupo de clases (de frecuentes a raras), mejor tasa de cada rejilla")
    for nombre, rejilla in por_opt.items():
        res = [entrenar(tipo, nombre, lr) + (lr,) for lr in rejilla]
        total, por_grupo, lr = min(res, key=lambda r: r[0] if np.isfinite(r[0]) else np.inf)
        borde = "   ¡en el borde de la rejilla!" if lr in (rejilla[0], rejilla[-1]) else ""
        print(f"  {nombre:6s} lr={lr:<5g} total {total:.3f}   grupos " + "  ".join(f"{v:.2f}" for v in por_grupo) + borde)
print("\nmasa de cada grupo:", [round(pi[a:b].sum().item(), 3) for a, b in grupos], "  log K =", round(np.log(K), 3))
print(f"{time.time() - t0:.1f} s")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In both models frequent classes are learned by every optimizer; inspect the rare group: the 80 rarest classes, 4.5% of data. The result is nuanced and instructive:

  • There is no gap in the linear model. SGD with momentum and enormous rate η=60\eta = 60 leaves rare classes at 0.040.04 nats, matching Adam. The most plausible explanation is near-separability: as the model gets frequent classes right, pk→1p_k \to 1 and curvature vanishes, allowing rates initially unstable. An SGD grid ending at η=10\eta = 10 would have “shown” SGD stuck at 1.061.06 nats on rare classes: precisely the error of unequal tuning budgets. The interactive uses smoothed labels, preventing curvature from vanishing, and gradient descent without momentum; there the gap is visible.
  • In the bigram MLP the gap persists at optimal rates. SGD reaches 0.170.17 nats on rare classes with η=0.7\eta = 0.7, and the next grid rate 1.01.0 already diverges; Adam and AdamW reach 0.020.02. Rare tokens appear infrequently as both input and output, and SGD cannot raise their rate without destabilizing frequent ones.
  • AdamW is worse than Adam on the linear model (0.330.33 versus 0.040.04): with η=0.3\eta = 0.3 and λ=0.01\lambda = 0.01, timescale 1/(ηλ)≈3301/(\eta\lambda) \approx 330 steps is comparable to the whole run, and decay holds back large weights required by a separable problem. This is the preceding section’s η\eta–λ\lambda interaction.

Turning this illustration into evidence would require the table’s interventions, several seeds and real data; exactly the experiment in the pretraining module project.

The professional version: PyTorch

In PyTorch the above are arguments to an optimizer inside the training loop. This cell checks exact equivalence with the from-scratch implementations and shows nanoGPT-style parameter groups.

[ ]AdamW, Adam with L2 and PyTorch parameter groupsLocal GPU
import numpy as np, torch, torch.nn as nn

torch.set_default_dtype(torch.float64)

# las celdas locales no comparten sesión con las del navegador: repetimos las dos versiones desde cero
def adam_l2_step(theta, g, m, v, t, lr, lam, b1=0.9, b2=0.999, eps=1e-8):
    g = g + lam * theta
    m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
    return theta - lr * (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps), m, v

def adamw_step(theta, g, m, v, t, lr, lam, b1=0.9, b2=0.999, eps=1e-8):
    theta = theta * (1 - lr * lam)
    m = b1 * m + (1 - b1) * g; v = b2 * v + (1 - b2) * g * g
    return theta - lr * (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps), m, v

A = torch.tensor([[3.0, 1.0], [1.0, 0.5]]); b = torch.tensor([1.0, -2.0])
perdida = lambda w: 0.5 * w @ A @ w - b @ w            # gradiente A w − b

def con_torch(opt_cls, steps=50, **kw):
    w = torch.tensor([1.0, 1.0], requires_grad=True)
    opt = opt_cls([w], **kw)
    for _ in range(steps):
        opt.zero_grad(); perdida(w).backward(); opt.step()
    return w.detach().numpy()

def a_mano(paso, steps=50, lr=0.05, lam=0.1):
    w, m, v = np.array([1.0, 1.0]), np.zeros(2), np.zeros(2)
    for t in range(1, steps + 1):
        w, m, v = paso(w, A.numpy() @ w - b.numpy(), m, v, t, lr, lam)
    return w

lr, lam = 0.05, 0.1
print("AdamW(weight_decay)          frente a adamw_step  :", np.abs(con_torch(torch.optim.AdamW, lr=lr, weight_decay=lam) - a_mano(adamw_step)).max())
print("Adam(weight_decay)           frente a adam_l2_step:", np.abs(con_torch(torch.optim.Adam, lr=lr, weight_decay=lam) - a_mano(adam_l2_step)).max())
print("Adam(decoupled_weight_decay) frente a AdamW       :", np.abs(con_torch(torch.optim.Adam, lr=lr, weight_decay=lam, decoupled_weight_decay=True)
                                                                   - con_torch(torch.optim.AdamW, lr=lr, weight_decay=lam)).max())
print("Adam(weight_decay)           frente a AdamW       :", np.abs(con_torch(torch.optim.Adam, lr=lr, weight_decay=lam) - con_torch(torch.optim.AdamW, lr=lr, weight_decay=lam)).max())
print("weight_decay por defecto: Adam", torch.optim.Adam([torch.zeros(1, requires_grad=True)]).defaults["weight_decay"],
      "  AdamW", torch.optim.AdamW([torch.zeros(1, requires_grad=True)]).defaults["weight_decay"])

# Grupos de parámetros: decaimiento solo en las matrices (regla de nanoGPT: p.dim() >= 2)
torch.set_default_dtype(torch.float32)
bloque = nn.ModuleDict({"emb": nn.Embedding(1000, 64), "ln": nn.LayerNorm(64), "fc": nn.Linear(64, 256), "out": nn.Linear(256, 64)})
con_decay = [p for p in bloque.parameters() if p.dim() >= 2]
sin_decay = [p for p in bloque.parameters() if p.dim() < 2]
opt = torch.optim.AdamW([{"params": con_decay, "weight_decay": 0.1},
                         {"params": sin_decay, "weight_decay": 0.0}], lr=3e-4, betas=(0.9, 0.95))
for nombre, p in bloque.named_parameters():
    print(f"  {nombre:12s} {str(tuple(p.shape)):12s} decaimiento {'sí' if p.dim() >= 2 else 'no'}")
print("parámetros con decaimiento:", sum(p.numel() for p in con_decay), "  sin:", sum(p.numel() for p in sin_decay))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first two differences are order 10−1610^{-16}: AdamW is exactly adamw_step and Adam(weight_decay=...) exactly adam_l2_step, coupled L2 penalty. Recent PyTorch adds Adam argument decoupled_weight_decay=True, making it AdamW (difference 0). Notice defaults too: Adam applies no decay and AdamW uses weight_decay=0.01, much less than the 0.10.1 common in LLMs. In the grouping example embeddings enter the decay group by p.dim() >= 2; to exclude them (as minGPT), do so manually by name or module type.

Common mistakes

Exercises

NumericAmount removed by decay each step
With PyTorch convention, η=3⋅10−4\eta = 3\cdot 10^{-4} and weight_decay λ=0.1\lambda = 0.1, what fraction of each weight does decay remove per step (before the Adam update)?
NumericA weight's half-life
With constant ηλ=3⋅10−5\eta\lambda = 3\cdot 10^{-5} and no gradient, what is the smallest number of steps kk after which the weight has halved or less, (1−ηλ)k≤1/2(1 - \eta\lambda)^k \le 1/2?
NumericAccumulated decay with cosine schedule
With cosine schedule ηt=ηmax⁡2(1+cos⁡(πt/T))\eta_t = \tfrac{\eta_{\max}}{2}\big(1 + \cos(\pi t/T)\big) for t=0,…,T−1t = 0, \dots, T - 1, ηmax⁡=3⋅10−4\eta_{\max} = 3\cdot 10^{-4}, T=105T = 10^5 and λ=0.1\lambda = 0.1 (PyTorch convention), what fraction of initial weight survives decay alone, ∏t(1−ηtλ)\prod_t(1 - \eta_t\lambda)?
NumericThe step bound with LLM betas
With β1=0.9\beta_1 = 0.9 and β2=0.95\beta_2 = 0.95, calculate the tight bound on ∣mt∣/vt\abs{m_t}/\sqrt{v_t} from the bounded-step theorem, 1−β1(1−β2)(1−γ2)\dfrac{1 - \beta_1}{\sqrt{(1 - \beta_2)(1 - \gamma^2)}} with γ=β1/β2\gamma = \beta_1/\sqrt{\beta_2}.
NumericAdam regret in the counterexample
In Reddi et al.'s problem with C=3C = 3, suppose Adam stays at xt=+1x_t = +1. What does mean regret RT/TR_T/T approach as T→∞T \to \infty?
QuizWhat does this code do?
What regularization does torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.1) apply?
QuizWhat not to decay
In a transformer trained with AdamW, which parameters are usually excluded from decay for a principled reason rather than habit? Select all that apply.

More than one answer may be correct.

QuizReconciling Reddi with modern theorems
Reddi et al. prove that for any β1<β2<1\beta_1 < \sqrt{\beta_2} < 1 some convex problem makes Adam fail to converge. Zhang et al. (2022) prove unmodified Adam converges to a critical-point neighborhood if β2\beta_2 is large and β1<β2\beta_1 < \sqrt{\beta_2}. What reconciles them?
ProofL2 and weight decay: SGD equivalence, Adam mismatch
Prove: SGD with L2 coefficient λ′\lambda' and rate η\eta equals SGD with weight decay λ\lambda if and only if λ′=λ/η\lambda' = \lambda/\eta; in Adam, no scalar λ′\lambda' reproduces weight decay on two coordinates with different gradient scales.
0
Let gt\vb{g}_t be the gradient of ff at θt\theta_t. Weight decay: θt+1=(1−λ)θt−η dt\theta_{t+1} = (1 - \lambda)\theta_t - \eta\,\vb{d}_t, where dt\vb{d}_t is the method's direction calculated from gt\vb{g}_t.

Step 1 of 4. How is an SGD step with L2 written?

ProofAdam in the limit β1 = β2 = 0
Prove: With β1=β2=0\beta_1 = \beta_2 = 0 and ε=0\eps = 0, Adam's step is θt+1=θt−ηsign⁡(gt)\theta_{t+1} = \theta_t - \eta\operatorname{sign}(\vb{g}_t) (with convention sign⁡(0)=0\operatorname{sign}(0) = 0), i.e. sign descent.
0
Adam computes mt=β1mt−1+(1−β1)gt\vb{m}_t = \beta_1\vb{m}_{t-1} + (1 - \beta_1)\vb{g}_t, vt=β2vt−1+(1−β2)gt2\vb{v}_t = \beta_2\vb{v}_{t-1} + (1 - \beta_2)\vb{g}_t^2, corrects bias by dividing by 1−β1t1 - \beta_1^t and 1−β2t1 - \beta_2^t, and steps θt+1=θt−η m^t/(v^t+ε)\theta_{t+1} = \theta_t - \eta\,\hat{\vb{m}}_t/(\sqrt{\hat{\vb{v}}_t} + \eps).

Step 1 of 4. What is m^t\hat{\vb{m}}_t with β1=0\beta_1 = 0?

CodeAdamW with PyTorch convention
Implement adamw_step(theta, grad, m, v, t, lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01), returning (theta, m, v) after an AdamW step exactly as torch.optim.AdamW: first decoupled decay θ←(1−ηλ)θ\theta \leftarrow (1 - \eta\lambda)\theta, not entering moments; then moments, bias correction with t (starting at 1) and update θ←θ−η m^/(v^+ε)\theta \leftarrow \theta - \eta\,\hat m/(\sqrt{\hat v} + \eps). Tests compare precomputed PyTorch trajectories in float64.
import numpy as np

def adamw_step(theta, grad, m, v, t, lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.01):
  """Un paso de AdamW (convención de PyTorch). Devuelve (theta, m, v) nuevos; t empieza en 1."""
  b1, b2 = betas
  # tu código: decaimiento desacoplado, momentos, corrección de sesgo y actualización
  return theta, m, v
Shift+Enter to run

Summary

Key idea
With a preconditioner, regularizing gradients (L2) and shrinking weights (weight decay) differ; AdamW shrinks outside the preconditioner and retains Adam’s coordinate-scale invariance. Adam is, more than approximate second order, bounded-step sign descent damped by signal-to-noise ratio.
  • In SGD, L2 with λ′\lambda' and weight decay with λ\lambda are the same algorithm if λ′=λ/η\lambda' = \lambda/\eta. In Adam with L2, coordinate ii receives decay ηλ′/(v^i+ε)\eta\lambda'/(\sqrt{\hat v_i} + \eps), tiny for large gradients; AdamW applies ηλ\eta\lambda to all.
  • Adam with L2 converges (if it converges) to penalized-objective stationary points; full-batch AdamW to KKT points of min⁡f\min f with ∥θ∥∞≤1/λ\norm{\theta}_\infty \le 1/\lambda. With noise, AdamW shrinks large-gradient coordinates more.
  • In PyTorch per-step decay is ηλ\eta\lambda, weights are a moving average of the last 1/(ηλ)1/(\eta\lambda) updates, and accumulated decay is exp⁡(−λ∑tηt)\exp(-\lambda\sum_t\eta_t): changing rate, schedule or horizon changes regularization. Biases and normalization gains are not decayed; embeddings depend on the experiment.
  • Reddi et al.’s counterexample shows that for every fixed β2\beta_2 some convex problem makes Adam fail to converge, because effective rate rises after an infrequent large gradient. AMSGrad fixes this with the historical maximum of v\vb{v}.
  • If β1<β2\beta_1 < \sqrt{\beta_2}, each Adam coordinate moves at most η(1−β1)/(1−β2)(1−β12/β2)\eta(1 - \beta_1)/\sqrt{(1 - \beta_2)(1 - \beta_1^2/\beta_2)} per step. With fixed problem and β2\beta_2 near 1, Adam converges to a stationary-point neighborhood; with β2=1−1/N\beta_2 = 1 - 1/N and rate ∝1/N\propto 1/\sqrt N, at rate O(dln⁡N/N)\bigO(d\ln N/\sqrt N).
  • With β1=β2=0\beta_1 = \beta_2 = 0 Adam is signSGD, steepest descent in ℓ∞\ell_\infty; generally it is sign damped by 1/1+σi2/μi21/\sqrt{1 + \sigma_i^2/\mu_i^2}.
  • The Adam–SGD gap on transformers appears not due to noise (it persists at full batch); heavy-tailed class imbalance and block Hessian heterogeneity have the strongest support, distinguishable with experiments changing one factor at a time and tuning each optimizer with equal budget.