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 , , and weight decay ; LLaMA (Touvron et al., 2023) used AdamW with , , weight decay , 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 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 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 . SGD with weight decay gives . The affine maps of agree for every if and only if .
∎The clean equivalence hides its basis: is treated like the gradient, and in SGD that means multiplying by scalar . With any diagonal preconditioner the calculation changes:
With L2, coordinate shrinks at step by factor ; with decay, factor is identical for all. For agreement is required for each and , and a single scalar can only satisfy this if is a multiple of identity. In Adam, : historically large-gradient coordinates receive far less decay with L2 than small-gradient coordinates. A second-order effect: with L2, also enters , so the preconditioner itself depends on regularization.
Adam(weight_decay=λ) to AdamW(weight_decay=λ). Increase : Adam with L2's final point (red) slides toward unregularized , 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 : Adam with L2 still goes to the L2 optimum, while AdamW slowly approaches (long memory) the corner of box , its point nearest .The interactive shows a property worth stating precisely, the fundamental reason to prefer decoupled decay in an adaptive method.
Proof
With , moving-average linearity gives and (likewise after bias correction). Coordinate-wise, , so Adam’s direction is unchanged. AdamW adds , independent of gradient, and induction over yields identical iterates. Adam with L2 averages , which is not times something independent of : with and the ratio changes. The interactive illustrates this: as , 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 , continuity gives (plus for L2). An exponential moving average of a convergent sequence reaches the same limit, and bias corrections tend to 1, so and coordinate-wise. Take limits in the update and subtract from both sides:
- L2: , requiring .
- AdamW: , the stated equality.
Since , . If does not approach zero as , the quotient tends to and : the weight is on the box boundary and descent direction points outside (gradient points inside), the KKT condition with multiplier .
∎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 subject to . 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 includes gradient variance and AdamW does shrink interior coordinates: in equilibrium acts like L2 with coefficient , 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 , where is the base rate and the schedule multiplier, and decay is : multiplied by schedule but not . Thus and are independent hyperparameters, and the authors show the loss heatmap in becomes nearly separable. PyTorch (and Optax’s adamw) multiplies decay by full rate: the fraction subtracted each step is . With typical LLM values and weight_decay=0.1, each step removes only % of each weight. Transferring between conventions changes actual decay by factor (or ), between and at typical rates.
Decay as a moving average
Write constant-rate AdamW as , with . Unroll the recurrence,
The second term is an exponential moving average of rescaled updates with coefficient : AdamW weights remember approximately the last updates and forget initialization at the same rate. With and , steps. Two consequences. First, the relevant timescale is product , not alone; compare it to training duration to know whether decay acts (Wang and Aitchison, 2024, propose fixing as a fraction of total steps when scaling models and data). Second, as below, is bounded by a constant depending only on and , so : the box of size 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 and identical noise throughout.
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 come only from . Adam with L2 follows the penalized optimum (ridge column, , apart from averaging stochastic-iterate noise), and moves from to : practically unregularized. In both variants 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 .
# 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- coordinate (from to ) and barely the curvature-100 one. AdamW leaves the first coordinate at optimum because it fits in the box, and clips the other two to : exactly , 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 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.
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 ), because ridge shrinks curvature- directions by 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 at step . After steps, from decay alone,
with negligible relative error when . Accumulated decay depends on the area under the rate schedule. With the cosine schedule from to 0 over steps, ; with , and , the factor is . Three practical consequences:
- Changing rate changes regularization. In PyTorch doubling
lralso doubles per-step decay. To explore rate at fixed regularization, holdlr * weight_decayconstant, or use the paper’s convention, decoupling and . - Changing horizon changes regularization. At fixed , doubling steps doubles the exponent. Loshchilov and Hutter therefore proposed normalized decay , with batch size, number of examples and number of epochs; Wang and Aitchison (2024) argue measured in epochs transfers well across scales.
- The schedule’s end barely decays. When at cosine’s end, decay vanishes with it. The same occurs in the paper’s convention because decay is multiplied by .
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 ( 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 and requiring . Adam’s original paper included a proof of . Reddi, Kale and Kumar (2018) found an error and, more importantly, a one-dimensional counterexample.
Watch Adam with (no momentum, which only complicates the calculation) and small . After gradient , and the step is toward . In the next two steps quickly forgets , , and each gradient produces a step toward . Two against one: Adam goes to . 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 and rate nearly constant inside a period, reaches a periodic regime of three values, just after gradient and , after the two s. Imposing periodicity,
and a period’s net displacement is proportional to . If , Adam drifts to ; if , to . As , and ; as , . Between lies threshold : for it is , approaching 1 as .
Reddi et al. turn this observation into theorems. For and (problem-dependent), the above problem has . They generalize: for any with 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 not to increase with , namely,
and in Adam, when forgets a large gradient, becomes negative: effective rate rises just after the informative gradient.
In the example, AMSGrad remembers forever, so three period steps share (almost) the same denominator and their total is proportional to : toward optimum. Reddi et al. prove AMSGrad has for online convex optimization with bounded domain, bounded gradients and decreasing ; later analysis (Alacaoglu et al., 2020) extends to constant . 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.
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 , Adam ends at with mean regret ; just below threshold () drift is so slow it has not arrived in 3000 steps; above it converges like AMSGrad. The threshold spans as varies: for , for . This is Reddi’s precise theorem: the bad problem is chosen after fixing .
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 appearing in all theorems.
Proof
Unrolling moving averages, and . Write and apply Cauchy–Schwarz:
Equality in Cauchy–Schwarz requires , i.e. , which as also saturates the geometric sum. If , the same sequence makes and the ratio grows at least as (exactly if , geometrically if ).
∎With defaults , the bound is ; with LLM values , . Without sustained gradient growth the ratio is much smaller (around 1 or less), but its existence matters: each coordinate moves at most per step regardless of gradient. Adam is by construction a trust-region method in norm; bias correction adds only factor , tending to 1.
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 (), the extreme sequence gives : growing as , 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 bounded below, -smooth and with stochastic gradients bounded in norm almost surely, they give an explicit bound on for random iterate , in terms of , gradient bound, dimension , , , and steps . With constant and , the bound contains a term not vanishing as : default Adam converges not to a stationary point but a neighborhood, like constant-step SGD. With and the bound is , the rate of AdaGrad and, apart from logarithm and dimension, nonconvex SGD. They also improve momentum dependence from to under .
- Zhang, Chen, Shi, Sun and Luo (2022). They note the quantifier mismatch: Reddi et al. choose the problem after , while practice fixes the problem then tunes . In that order, for finite sums, if is sufficiently large (problem-dependent threshold, particularly number of terms) and , 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 a large hyperparameter region makes Adam diverge. Increasing yields a phase transition, exactly as in the Reddi figure.
The third piece is smoothness. Deep networks are poorly described as -smooth with a reasonable global : measured local curvature grows with gradient norm during training. Generalized smoothness, , 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, , and no . Then and , and the step is : Adam is signSGD, (Bernstein et al., 2018). You will prove this carefully in an exercise. What remains of the identity with 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 and variance , and moving averages are long enough to average noise, and , so
The first factor is sign direction; the second damps it, nearly 1 when signal-to-noise ratio is high and when low. Adam is sign descent damped coordinate-wise by signal-to-noise ratio. With the step is , whose mean for Gaussian gradients damps differently.
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 , Adam takes steps of size with the mean gradient’s sign: pure sign descent. With weak signal the step shrinks in proportion to .
ℓ∞ geometry
Why is sign a natural direction? It is steepest descent when distances use norm, precisely Adam’s trust-region geometry (each coordinate moves at most , around ).
Proof
For any with , . Both inequalities are equalities if and only if, on every coordinate with , . The norm appears as the dual of .
∎Compare with gradient descent using the descent lemma in each geometry. If , step with best guarantees decrease , versus gradient descent’s . For diagonal quadratic with , and , so the sign guarantee is better exactly when
Both ratios lie between 1 and . 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.
Two things to notice. Sign advances diagonally until the high-curvature coordinate oscillates around its minimum with amplitude ; then only the other progresses, at constant speed. SGD, limited by maximum curvature (, with the largest eigenvalue of ), 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:
- 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.
- 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.
- 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.
- 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 (one row per class), loss is , where is class ‘s frequency, and
The signal training class is proportional to its frequency, as is the corresponding Hessian block. Gradient descent moves row at speed , with limited by frequent-class curvature. With , class 100 is times slower than class 1. Adam divides each coordinate by its scale and moves all rows at speed .
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).
| Intervention | Heavy-tailed noise | Sign | Class imbalance | Block Hessian |
|---|---|---|---|---|
| Full batch instead of minibatches | gap disappears | persists | persists | persists |
| Rebalance classes (subsample or reweight) | no clear change | no clear change | gap shrinks greatly | no clear change |
| Momentum sign instead of Adam, full batch | no gap to explain | like Adam | like Adam | depends |
| SGD with a different rate per block | little effect | little effect | little effect (imbalance is within output block) | gap shrinks |
| Measure loss by class frequency | uniform | uniform | SGD stalled on rare classes | uniform |
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.
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")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 leaves rare classes at nats, matching Adam. The most plausible explanation is near-separability: as the model gets frequent classes right, and curvature vanishes, allowing rates initially unstable. An SGD grid ending at would have “shown” SGD stuck at 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 nats on rare classes with , and the next grid rate already diverges; Adam and AdamW reach . 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 ( versus ): with and , timescale steps is comparable to the whole run, and decay holds back large weights required by a separable problem. This is the preceding section’s – 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.
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))npm run lab and open the connection link.The first two differences are order : 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 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
weight_decay , what fraction of each weight does decay remove per step (before the Adam update)?torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.1) apply?More than one answer may be correct.
Step 1 of 4. How is an SGD step with L2 written?
Step 1 of 4. What is with ?
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 , not entering moments; then moments, bias correction with t (starting at 1) and update . 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, vSummary
- In SGD, L2 with and weight decay with are the same algorithm if . In Adam with L2, coordinate receives decay , tiny for large gradients; AdamW applies to all.
- Adam with L2 converges (if it converges) to penalized-objective stationary points; full-batch AdamW to KKT points of with . With noise, AdamW shrinks large-gradient coordinates more.
- In PyTorch per-step decay is , weights are a moving average of the last updates, and accumulated decay is : 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 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 .
- If , each Adam coordinate moves at most per step. With fixed problem and near 1, Adam converges to a stationary-point neighborhood; with and rate , at rate .
- With Adam is signSGD, steepest descent in ; generally it is sign damped by .
- 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.