9.5 Adam and AdamW

In Section 9.3, plain minibatch SGD required a learning rate of η=0.5\eta = 0.5 on TinyLM to reach a loss of about 2.12.1 nats/byte. Adam with η=3×10−3\eta = 3 \times 10^{-3}, a learning rate more than a hundred times smaller, reaches 1.591.59 nats/byte in the same 2,0002{,}000 steps, as we will measure below. Why does an optimizer with a hundredfold smaller nominal learning rate train faster, and why is it the universal default for Transformers?

Momentum (Section 9.4) averages gradients over time but still applies a single scalar step size to every parameter. Yet in deep networks, and especially in Transformers, gradient magnitudes vary by orders of magnitude across embeddings, attention projections, MLP layers, and normalization parameters. Adam (Adaptive Moment Estimation, Kingma and Ba (2015)) combines momentum with a per-coordinate root-mean-square (RMS) gradient preconditioner developed through AdaGrad (Duchi et al., 2011) and RMSProp (Tieleman and Hinton, 2012). Dividing each coordinate's update by its own historical gradient scale makes the learning rate η\eta a direct step length in parameter space rather than a multiplier on raw gradients.

That same per-coordinate division, however, breaks standard ℓ2\ell_2 regularization: adding λ2∥x∥2\frac{\lambda}{2}\|\mathbf{x}\|^2 to the loss rescales each weight's decay rate by the inverse of its gradient scale. Loshchilov and Hutter (2019) resolved this by decoupling weight decay from the adaptive preconditioner, creating AdamW. In this section, we trace the progression from AdaGrad and RMSProp to Adam, measure coordinate gradient scales and compare Adam against SGD with momentum on TinyLM, derive AdamW and its weight-decay timescale τ=1/(ηλ)\tau = 1/(\eta\lambda) and equilibrium norm, and detail which parameter groups must be exempt from weight decay.

import copy
import random

9.5.1 Per-Coordinate Adaptive Learning Rates#

9.5.1.1 AdaGrad and RMSProp#

In models with sparse or heterogeneous features (such as token embeddings where common tokens appear in every minibatch and rare tokens appear only occasionally), a single global learning rate cannot serve all coordinates. AdaGrad (Duchi et al., 2011) accumulates the running sum of squared gradients st\mathbf{s}_t elementwise and scales each coordinate's step inversely by st+ϵ\sqrt{\mathbf{s}_t + \epsilon}:

st=st−1+gt2,xt+1=xt−ηst+ϵ⊙gt,(9.5.1)\mathbf{s}_t = \mathbf{s}_{t-1} + \mathbf{g}_t^2, \qquad \mathbf{x}_{t+1} = \mathbf{x}_t - \frac{\eta}{\sqrt{\mathbf{s}_t + \epsilon}} \odot \mathbf{g}_t, \tag{9.5.1}

where s0=0\mathbf{s}_0 = \mathbf{0} and ϵ>0\epsilon > 0 prevents division by zero. On an axis-aligned valley, scaling each coordinate by its own gradient magnitude automatically cancels the directional curvature difference, acting as a gradient-only approximation to the diagonal preconditioner of Section 9.1.5 (Section 23.5.1).

def adagrad_2d(x1, x2, s1, s2, f_grad, eta=2.0, eps=1e-6):
    g1, g2 = f_grad(x1, x2)
    s1, s2 = s1 + g1 ** 2, s2 + g2 ** 2
    x1 -= eta / math.sqrt(s1 + eps) * g1
    x2 -= eta / math.sqrt(s2 + eps) * g2
    return x1, x2, s1, s2

d2l.show_trace_2d(d2l.f_valley, d2l.train_2d(adagrad_2d, d2l.valley_grad))
step 20, x1: -0.002295, x2: -0.000000

Because st\mathbf{s}_t accumulates squared gradients monotonically without bound, AdaGrad's effective step size decays as O(t−1/2)O(t^{-1/2}) under persistent stochastic gradients, eventually halting progress on non-convex deep networks. RMSProp (Tieleman and Hinton, 2012) replaces the cumulative sum with an exponential moving average (EMA) vt\mathbf{v}_t of squared gradients over a window of ∼1/(1−β2)\sim 1/(1-\beta_2) steps:

vt=β2 vt−1+(1−β2) gt2,xt+1=xt−ηvt+ϵ⊙gt.(9.5.2)\mathbf{v}_t = \beta_2\, \mathbf{v}_{t-1} + (1 - \beta_2)\, \mathbf{g}_t^2, \qquad \mathbf{x}_{t+1} = \mathbf{x}_t - \frac{\eta}{\sqrt{\mathbf{v}_t + \epsilon}} \odot \mathbf{g}_t. \tag{9.5.2}

(Note: following standard optimization notation, vt\mathbf{v}_t here denotes the second-moment squared-gradient average rather than the velocity vector of Section 9.4.) By forgetting ancient gradients, RMSProp maintains a non-vanishing step size even from a moderate learning rate η=0.4\eta = 0.4:

def rmsprop_2d(x1, x2, v1, v2, f_grad, eta=0.4, beta2=0.9, eps=1e-6):
    g1, g2 = f_grad(x1, x2)
    v1 = beta2 * v1 + (1 - beta2) * g1 ** 2
    v2 = beta2 * v2 + (1 - beta2) * g2 ** 2
    x1 -= eta / math.sqrt(v1 + eps) * g1
    x2 -= eta / math.sqrt(v2 + eps) * g2
    return x1, x2, v1, v2

d2l.show_trace_2d(d2l.f_valley, d2l.train_2d(rmsprop_2d, d2l.valley_grad))
step 20, x1: -0.010599, x2: 0.000000

Notice two properties of (9.5.2):

  1. Early step amplification without bias correction: Because v0=0\mathbf{v}_0 = \mathbf{0}, the first step has v1=(1−β2)g12\mathbf{v}_1 = (1 - \beta_2)\mathbf{g}_1^2, causing an oversized initial jump of magnitude η/1−β2≈3.16 η\eta/\sqrt{1-\beta_2} \approx 3.16\,\eta at β2=0.9\beta_2 = 0.9 (and 31.6 η31.6\,\eta at β2=0.999\beta_2 = 0.999).
  2. Normalized step length: Whenever a coordinate's gradient has roughly steady magnitude, vt≈∣gt∣\sqrt{v_t} \approx |g_t| and the update has magnitude ≈η\approx \eta regardless of how small ∣gt∣|g_t| becomes. Near a minimum, a constant-rate adaptive method therefore oscillates within an O(η)O(\eta) neighborhood until η\eta is decayed by a schedule (Section 9.7).

9.5.1.2 Adam and Bias Correction#

Adam (Kingma and Ba, 2015) combines an EMA of the first moment (momentum, mt\mathbf{m}_t) with an EMA of the uncentered second moment (vt\mathbf{v}_t), and applies exact bias correction to both estimators. Unrolling vt=(1−β2)∑s=1tβ2t−sgs2\mathbf{v}_t = (1-\beta_2)\sum_{s=1}^t \beta_2^{t-s}\mathbf{g}_s^2 from v0=0\mathbf{v}_0 = \mathbf{0} shows that the weights sum to 1−β2t1 - \beta_2^t rather than 11. Dividing by 1−β1t1 - \beta_1^t and 1−β2t1 - \beta_2^t yields unbiased moment estimators m^t\hat{\mathbf{m}}_t and v^t\hat{\mathbf{v}}_t:

mt=β1 mt−1+(1−β1) gt,m^t=mt1−β1t,vt=β2 vt−1+(1−β2) gt2,v^t=vt1−β2t.(9.5.3)\begin{aligned} \mathbf{m}_t &= \beta_1\, \mathbf{m}_{t-1} + (1 - \beta_1)\, \mathbf{g}_t, \qquad & \hat{\mathbf{m}}_t &= \frac{\mathbf{m}_t}{1 - \beta_1^t}, \\ \mathbf{v}_t &= \beta_2\, \mathbf{v}_{t-1} + (1 - \beta_2)\, \mathbf{g}_t^2, \qquad & \hat{\mathbf{v}}_t &= \frac{\mathbf{v}_t}{1 - \beta_2^t}. \end{aligned} \tag{9.5.3}

The parameter update divides the bias-corrected first moment by the coordinate RMS scale v^t\sqrt{\hat{\mathbf{v}}_t}:

xt+1=xt−η m^tv^t+ϵ.(9.5.4)\mathbf{x}_{t+1} = \mathbf{x}_t - \eta\, \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}. \tag{9.5.4}

Standard defaults are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 (or β2=0.95\beta_2 = 0.95 in large language model training (Brown et al., 2020)), and ϵ=10−8\epsilon = 10^{-8}. At t=1t = 1, m^1=g1\hat{\mathbf{m}}_1 = \mathbf{g}_1 and v^1=g12\hat{\mathbf{v}}_1 = \mathbf{g}_1^2, so the initial step is exactly −η sign⁡(g1)-\eta\,\operatorname{sign}(\mathbf{g}_1).

More generally, rescaling any coordinate of the objective by a positive constant c>0c > 0 multiplies both m^t,i\hat{m}_{t,i} and v^t,i\sqrt{\hat{v}_{t,i}} by cc, leaving their ratio invariant (for ϵ→0\epsilon \to 0). Thus, under Adam, η\eta specifies a direct coordinate step length in parameter space: a coordinate with consistent gradient sign moves by ≈η\approx \eta per step, whereas a coordinate dominated by zero-mean noise moves by ≈η(1−β1)/(1+β1)≈0.23 η\approx \eta\sqrt{(1-\beta_1)/(1+\beta_1)} \approx 0.23\,\eta.

def adam_2d(x1, x2, s1, s2, f_grad, eta=0.4, beta1=0.9, beta2=0.999,
            eps=1e-8):
    def update(x, g, state):  # state: (m, v, t), 0 before the first step
        m, v, t = state if state else (0, 0, 0)
        m, v = beta1 * m + (1 - beta1) * g, beta2 * v + (1 - beta2) * g ** 2
        m_hat, v_hat = m / (1 - beta1 ** (t + 1)), v / (1 - beta2 ** (t + 1))
        return x - eta * m_hat / (math.sqrt(v_hat) + eps), (m, v, t + 1)
    g1, g2 = f_grad(x1, x2)
    (x1, s1), (x2, s2) = update(x1, g1, s1), update(x2, g2, s2)
    return x1, x2, s1, s2

path = d2l.train_2d(adam_2d, d2l.valley_grad, steps=200, beta2=0.999)
d2l.show_trace_2d(d2l.f_valley, path)
step 200, x1: 0.000022, x2: 0.000042

Implementing Adam from scratch requires maintaining the step counter tt and the two buffers (m,v)(\mathbf{m}, \mathbf{v}) for each parameter tensor:

class Adam(torch.optim.Optimizer):
    """Adam from scratch: steps scaled by two debiased moving averages."""
    def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8):
        super().__init__(params, dict(lr=lr, betas=betas, eps=eps))

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            (beta1, beta2), lr, eps = group['betas'], group['lr'], group['eps']
            for p in group['params']:
                if p.grad is None:  # A parameter that received no gradient
                    continue
                state = self.state[p]
                if not state:  # First step: t = 0 and m = v = 0
                    state.update(t=0, m=torch.zeros_like(p),
                                 v=torch.zeros_like(p))
                state['t'] += 1
                t, m, v = state['t'], state['m'], state['v']
                m.mul_(beta1).add_(p.grad, alpha=1 - beta1)
                v.mul_(beta2).add_(p.grad ** 2, alpha=1 - beta2)
                m_hat, v_hat = m / (1 - beta1 ** t), v / (1 - beta2 ** t)
                p.sub_(lr * m_hat / (v_hat.sqrt() + eps))

9.5.2 Adam on a Language Model#

9.5.2.1 Gradient Scales and Comparison with SGD on TinyLM#

Why is per-coordinate scaling so critical for Transformers? To measure gradient scales across TinyLM (Section 9.3.1), we first load the WikiText103 dataset (b=64b = 64, window length 6464):

data = d2l.WikiText103(batch_size=64, num_steps=64)

Next we define gradients(model, data) to compute the root-mean-square (RMS) gradient of each parameter tensor over 1010 minibatches, snapshot(model) to clone parameter values, and an initial TinyLM instance with Adam (η=3×10−3\eta = 3 \times 10^{-3}):

def gradients(model, data, num_batches=10):
    """RMS over num_batches minibatches of each parameter's gradient."""
    device = d2l.try_gpu()
    sq = {name: 0 for name, _ in model.named_parameters()}
    for _, (X, Y) in zip(range(num_batches), data.train_dataloader()):
        model.zero_grad()
        loss = F.cross_entropy(model(X.to(device)).flatten(0, 1),
                               Y.to(device).flatten())
        loss.backward()
        for name, p in model.named_parameters():
            sq[name] += p.grad ** 2 / num_batches
    return {name: v.sqrt() for name, v in sq.items()}

def snapshot(model):
    return {name: p.detach().clone() for name, p in model.named_parameters()}

model = d2l.TinyLM(len(data.vocab)).to(d2l.try_gpu())
optimizer = torch.optim.Adam(model.parameters(), lr=3e-3)

Grouping tensors into the 88 functional parameter kinds via rms_by_kind, we compare their RMS gradient magnitudes at step 00 and step 500500 alongside the normalized Adam step length ∥Δx∥RMS/η\|\Delta\mathbf{x}\|_{\text{RMS}} / \eta:

KINDS = ['token_emb', 'pos_emb', 'qkv', 'proj', 'mlp', 'head']

def rms_by_kind(tensors):
    """RMS of the entries of each kind of parameter, from {name: tensor}."""
    sums, counts = {}, {}
    for name, t in tensors.items():
        kind = (('LayerNorm' if 'norm' in name else 'biases')
                if len(t.shape) == 1 else
                next(k for k in KINDS if k in name))
        sums[kind] = sums.get(kind, 0) + float((t ** 2).sum())
        counts[kind] = counts.get(kind, 0) + math.prod(t.shape)
    return {kind: math.sqrt(sums[kind] / counts[kind]) for kind in sums}

grad_init = rms_by_kind(gradients(model, data))
d2l.train_steps(model, data, optimizer, num_steps=500)
grad_500 = rms_by_kind(gradients(model, data))
before = snapshot(model)
d2l.train_steps(model, data, optimizer, num_steps=1)
after = snapshot(model)
step = rms_by_kind({name: (before[name] - after[name]) / 3e-3
                    for name in before})
print(f'{"":<11}{"RMS gradient at step 0":>24}{"at step 500":>13}'
      f'{"Adam step / lr":>16}')
for kind in KINDS + ['LayerNorm', 'biases']:
    print(f'{kind:<11}{grad_init[kind]:>24.1e}{grad_500[kind]:>13.1e}'
          f'{step[kind]:>16.2f}')
ratio = lambda column: max(column.values()) / min(column.values())
print(f'{"max / min":<11}{ratio(grad_init):>24.0f}{ratio(grad_500):>13.0f}'
      f'{ratio(step):>16.1f}')
             RMS gradient at step 0  at step 500  Adam step / lr
token_emb                   2.0e-04      9.2e-05            0.21
pos_emb                     1.8e-04      1.6e-04            0.27
qkv                         8.2e-04      3.8e-04            0.23
proj                        1.4e-03      5.7e-04            0.21
mlp                         1.0e-03      2.6e-04            0.24
head                        4.5e-03      1.3e-03            0.12
LayerNorm                   4.8e-03      1.3e-03            0.18
biases                      7.0e-03      6.2e-04            0.15
max / min                        39           15             2.2

Raw gradient magnitudes span a 40×40\times range at initialization (from ∼2×10−4\sim 2 \times 10^{-4} on token embeddings to ∼7×10−3\sim 7 \times 10^{-3} on biases) and a 15×15\times range at step 500500. Under SGD, a single scalar learning rate moves the groups with the largest gradients (biases, LayerNorm, the output head) 15–40×15\text{--}40\times faster than the embeddings; under Adam, the normalized step size across all eight parameter groups lies within a narrow 2×2\times band (0.1η–0.3η0.1\eta\text{--}0.3\eta, close to the pure-noise ratio (1−β1)/(1+β1)≈0.23\sqrt{(1-\beta_1)/(1+\beta_1)} \approx 0.23).

Because gradient scales in TinyLM lie around 10−4–10−210^{-4}\text{--}10^{-2} and Adam's EMA includes (1−β1)=0.1(1-\beta_1) = 0.1, Adam at η∼3×10−3\eta \sim 3 \times 10^{-3} produces parameter steps comparable in magnitude to SGD with momentum 0.90.9 at η∼0.3\eta \sim 0.3. To compare both optimizers across 33 shared seeds, we first set up the model and optimizer closures make_lm, make_sgd, and make_adam:

make_lm = lambda: d2l.TinyLM(len(data.vocab))
make_sgd = lambda model, lr: torch.optim.SGD(model.parameters(), lr,
                                             momentum=0.9)
make_adam = lambda model, lr: torch.optim.Adam(model.parameters(), lr)
seeds = [random.getrandbits(31) for _ in range(3)]

We then sweep SGD with momentum across η∈{0.1,0.3,0.5,1.0}\eta \in \{0.1, 0.3, 0.5, 1.0\} and Adam across η∈{3×10−4,10−3,3×10−3,10−2,3×10−2}\eta \in \{3 \times 10^{-4}, 10^{-3}, 3 \times 10^{-3}, 10^{-2}, 3 \times 10^{-2}\} from identical initial weights per seed:

def sweep(make_optimizer, lrs):
    """Loss curves of one run per learning rate and seed, printing the final
    losses; the runs of one seed start from the same initialization."""
    runs = [d2l.lr_sweep(make_lm, make_optimizer, data, lrs, seed,
                         verbose=False)[0] for seed in seeds]
    for lr in lrs:
        print(f'  lr {lr:<7g}', *(f'{d2l.final_loss(run[lr]):6.3f}'
                                  for run in runs))
    return {lr: [run[lr] for run in runs] for lr in lrs}

print('final loss of three runs, SGD with momentum')
sgd_lm = sweep(make_sgd, [0.1, 0.3, 0.5, 1.0])
print('Adam')
adam_lm = sweep(make_adam, [3e-4, 1e-3, 3e-3, 1e-2, 3e-2])
final loss of three runs, SGD with momentum
  lr 0.1      1.835  1.857  1.867
  lr 0.3      1.644  1.900  1.694
  lr 0.5        inf    inf  1.754
  lr 1          inf    inf    inf
Adam
  lr 0.0003   1.930  1.913  1.932
  lr 0.001    1.655  1.662  1.660
  lr 0.003    1.587  1.591  1.587
  lr 0.01     1.642  1.644  1.649
  lr 0.03     2.847  2.781  2.794

Summarizing each optimizer at its best learning rate (best_rate), we compare the usable learning-rate range (within 0.150.15 nats of the optimum), steps to reach 1.81.8 nats, maximum single-step loss spikes, and smoothed loss trajectories:

def best_rate(curves):
    """The lr with the lowest mean final loss, and each lr's mean."""
    mean = {lr: sum(map(d2l.final_loss, runs)) / len(runs)
            for lr, runs in curves.items()}
    return min(mean, key=mean.get), mean

print(f'{"":6}{"best lr":>8}{"final loss":>17}   {"within 0.15 nats":<18}'
      f'{"steps to 1.8":<16}largest one-step rise')
for name, curves in [('SGD', sgd_lm), ('Adam', adam_lm)]:
    best, mean = best_rate(curves)
    runs = curves[best]
    finals = [d2l.final_loss(run) for run in runs]
    usable = [f'{lr:g}' for lr in curves if mean[lr] <= mean[best] + 0.15]
    steps = ' '.join(str(d2l.steps_to_reach(run, 1.8)) for run in runs)
    rises = ' '.join(f'{max(b - a for a, b in zip(run, run[1:])):.2f}'
                     for run in runs)
    print(f'{name:<6}{best:>8g}{min(finals):>8.3f} to {max(finals):.3f}   '
          f'{" ".join(usable):<18}{steps:<16}{rises}')
best_sgd, best_adam = best_rate(sgd_lm)[0], best_rate(adam_lm)[0]
d2l.plot(list(range(0, 2000, 25)),
         [d2l.smooth(sgd_lm[best_sgd][0]),
          d2l.smooth(adam_lm[best_adam][0])],
         'step', 'training loss',
         legend=[f'SGD + momentum, lr {best_sgd:g}',
                 f'Adam, lr {best_adam:g}'])
       best lr       final loss   within 0.15 nats  steps to 1.8    largest one-step rise
SGD        0.3   1.644 to 1.900   0.1 0.3           1100 None 1250  0.16 1.72 0.39
Adam     0.003   1.587 to 1.591   0.001 0.003 0.01  725 725 700     0.17 0.20 0.16

On TinyLM, Adam reaches a target loss of 1.81.8 nats in nearly half the steps of SGD with momentum (650–800650\text{--}800 vs. 1,100–1,5001{,}100\text{--}1{,}500), finishes at a lower final loss, operates across a 10×10\times usable learning-rate window (10−310^{-3} to 10−210^{-2}), and remains finite even at η=3×10−2\eta = 3 \times 10^{-2} because its normalized update length is bounded by η\eta. SGD's best rate, η=0.3\eta = 0.3, sits one grid step below divergence: its worst one-step loss spikes are several times Adam's, and at η=0.5\eta = 0.5 most runs diverge to inf. On larger Transformers with subword vocabularies, this gap widens further due to block-level Hessian heterogeneity (Zhang et al., 2024) and heavy-tailed token frequencies (Kunstner et al., 2023; Kunstner et al., 2024).

In this run, one spike sets an SGD seed back so far that it never reaches 1.81.8.

9.5.2.2 Role of ϵ\epsilon and Limits of the Second-Moment Estimate#

In (9.5.4), ϵ\epsilon caps the maximum effective coordinate learning rate at η/ϵ\eta / \epsilon; in the limit ϵ≫v^t,i\epsilon \gg \sqrt{\hat{v}_{t,i}}, Adam reduces to SGD with momentum at step size (1−β1)η/ϵ(1-\beta_1)\eta/\epsilon. Conversely, when β2\beta_2 is too small, a short-memory second-moment estimate can weight frequent small gradients more heavily than occasional large opposing gradients—a phenomenon used by Reddi et al. (2018) to construct a synthetic periodic convex counterexample (+4,−1,−1+4, -1, -1) on which small-β2\beta_2 Adam fails to converge (Section 23.5.2.2; Exercise 4). In practice, keeping β2∈[0.95,0.999]\beta_2 \in [0.95, 0.999] prevents this pathology without requiring monotonic running maxima (AMSGrad).

9.5.3 Decoupled Weight Decay (AdamW)#

9.5.3.1 Coupled ℓ2\ell_2 Regularization vs. Decoupled Weight Decay#

Under plain SGD (Section 2.7), adding an ℓ2\ell_2 penalty λ2∥x∥2\frac{\lambda}{2}\|\mathbf{x}\|^2 to the objective adds λxt\lambda\mathbf{x}_t to the gradient, which is mathematically identical to shrinking the weights by (1−ηλ)(1 - \eta\lambda) before each step:

xt+1=xt−η (gt+λxt)=(1−ηλ) xt−η gt.(9.5.5)\mathbf{x}_{t+1} = \mathbf{x}_t - \eta\,(\mathbf{g}_t + \lambda \mathbf{x}_t) = (1 - \eta\lambda)\,\mathbf{x}_t - \eta\,\mathbf{g}_t. \tag{9.5.5}

When the penalized gradient gt+λxt\mathbf{g}_t + \lambda\mathbf{x}_t is fed into Adam, however, the penalty term is divided by the coordinate preconditioner v^t,i+ϵ\sqrt{\hat{v}_{t,i}} + \epsilon:

η λv^t,i+ϵ  xt,i⏟coupled ℓ2 penalty in Adamversusη λ  xt,iηv^t,i⏟decoupled weight decay.(9.5.6)\underbrace{\frac{\eta\,\lambda}{\sqrt{\hat{v}_{t,i}} + \epsilon}\; x_{t,i}}_{\textrm{coupled $\ell_2$ penalty in Adam}} \qquad \textrm{versus} \qquad \underbrace{\eta\,\lambda\; x_{t,i}\vphantom{\frac{\eta}{\sqrt{\hat{v}_{t,i}}}}}_{\textrm{decoupled weight decay}}. \tag{9.5.6}

Under coupled ℓ2\ell_2 regularization, weights with small loss gradients are decayed up to 103×10^3\times more aggressively than weights with large gradients—or, when λ∣xt,i∣\lambda|x_{t,i}| dominates the loss gradient, Adam normalizes the penalty by its own magnitude and drives the weight toward zero at speed η\eta per step until λ∣x∣∼∣gloss∣\lambda|x| \sim |g_{\text{loss}}|.

Loshchilov and Hutter (2019) introduced AdamW, which decouples weight decay from the adaptive gradient step:

xt+1=(1−ηλ) xt−η m^tv^t+ϵ,(9.5.7)\mathbf{x}_{t+1} = (1 - \eta\lambda)\,\mathbf{x}_t - \eta\, \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}, \tag{9.5.7}

where m^t\hat{\mathbf{m}}_t and v^t\hat{\mathbf{v}}_t are computed solely from the data loss gradient gt\mathbf{g}_t.

class AdamW(torch.optim.Adam):
    """Adam with decoupled weight decay: shrink the weights, then step."""
    def __init__(self, params, lr=1e-3, weight_decay=0.01):
        super().__init__(params, lr)  # Adam's own weight_decay stays 0
        self.weight_decay = weight_decay

    @torch.no_grad()
    def step(self):
        for group in self.param_groups:
            for p in group['params']:
                if p.grad is not None:
                    p.mul_(1 - group['lr'] * self.weight_decay)
        super().step()

To compare no decay, coupled Adam + l2, and decoupled AdamW on TinyLM, we first define matrix_rms to measure the entrywise RMS of the 2D non-embedding weight matrices and train_tracked to record both the step losses and the matrix RMS every 250250 steps:

def matrix_rms(model):
    """RMS of the entries of the weight matrices, embeddings excluded."""
    W = torch.cat([p.detach().flatten() for name, p in model.named_parameters()
                   if p.ndim == 2 and 'emb' not in name])
    return float(W.square().mean().sqrt())

def train_tracked(make_optimizer, data, seed, num_steps, every=250):
    """Train TinyLM from seed with make_optimizer(params); return the losses,
    the matrix RMS at the start and every `every` steps, and the model."""
    torch.manual_seed(seed)
    model = d2l.TinyLM(len(data.vocab))
    optimizer = make_optimizer(model.parameters())
    losses, rms = [], [matrix_rms(model)]
    for _ in range(num_steps // every):
        losses += d2l.train_steps(model, data, optimizer, every)
        rms.append(matrix_rms(model))
    return losses, rms, model

Running all three configurations for 1,0001{,}000 steps at η=3×10−3\eta = 3 \times 10^{-3} and λ=0.1\lambda = 0.1 from a shared seed shows the dramatic difference between coupled ℓ2\ell_2 penalty and decoupled weight decay:

seed = random.getrandbits(31)
curves = {}
for name, make_optimizer in [
        ('no decay', lambda params: torch.optim.Adam(params, 3e-3)),
        ('Adam + ℓ2', lambda params: torch.optim.Adam(params, 3e-3,
                                                       weight_decay=0.1)),
        ('AdamW', lambda params: torch.optim.AdamW(params, 3e-3,
                                                    weight_decay=0.1))]:
    curves[name], rms, _ = train_tracked(make_optimizer, data, seed, 1000)
    print(f'{name:<10} final loss {d2l.final_loss(curves[name]):.3f}, RMS of '
          f'the weight matrices {rms[0]:.4f} -> {rms[-1]:.4f}')
d2l.plot(list(range(0, 1000, 25)), [d2l.smooth(c) for c in curves.values()],
         'step', 'training loss', legend=list(curves))
no decay   final loss 1.740, RMS of the weight matrices 0.0447 -> 0.1078
Adam + ℓ2  final loss 3.151, RMS of the weight matrices 0.0447 -> 0.0028
AdamW      final loss 1.736, RMS of the weight matrices 0.0447 -> 0.0969

Coupled Adam + l2 at λ=0.1\lambda = 0.1 collapses the hidden weight matrices from an initial RMS of 0.0450.045 down to <0.003\lt 0.003, destroying the network's representation and stalling at the unigram byte-frequency entropy (∼3.2\sim 3.2 nats/byte). Decoupled AdamW trains cleanly alongside the unregularized baseline while bounding weight growth.

9.5.3.2 The Timescale of Decay and Equilibrium Norm#

Writing ut=m^t/(v^t+ϵ)\mathbf{u}_t = \hat{\mathbf{m}}_t / (\sqrt{\hat{\mathbf{v}}_t} + \epsilon) for Adam's normalized update direction and unrolling (9.5.7) over tt steps yields

xt=(1−ηλ)t x0−η∑s=0t−1(1−ηλ)t−1−s us.(9.5.8)\mathbf{x}_t = (1 - \eta\lambda)^t\, \mathbf{x}_0 - \eta \sum_{s=0}^{t-1} (1 - \eta\lambda)^{t-1-s}\, \mathbf{u}_s. \tag{9.5.8}

Thus, AdamW expresses the parameters xt\mathbf{x}_t as an exponentially weighted moving average of past updates with decay factor 1−ηλ≈e−ηλ1 - \eta\lambda \approx e^{-\eta\lambda} and characteristic decay timescale

τ=1ηλ\tau = \frac{1}{\eta\lambda}

steps (Wang and Aitchison, 2025). At η=3×10−3\eta = 3 \times 10^{-3} and λ=0.1\lambda = 0.1, the decay timescale is τ=1/0.0003≈3,333\tau = 1 / 0.0003 \approx 3{,}333 steps. Over a TT-step run, weight decay acts across T/τ=TηλT / \tau = T\eta\lambda timescales.

Over runs longer than τ=1/(ηλ)\tau = 1/(\eta\lambda), the initial weights decay away and each coordinate xt,ix_{t,i} reaches a stochastic equilibrium norm where per-step shrinkage ηλxt,i\eta\lambda x_{t,i} balances the injection of normalized updates −ηnt,i-\eta n_{t,i} (with nt,i=gt,i/v^t,in_{t,i} = g_{t,i}/\sqrt{\hat{v}_{t,i}} of unit mean square σ2≈1\sigma^2 \approx 1). By the exact same variance recursion as the SGD noise ball (Section 9.2) with λdecay\lambda_{\text{decay}} in place of curvature:

E[xt+12]=(1−ηλ)2 E[xt2]+η2σ2⟹E[x∞2]≈η σ22λ≈η2λ.(9.5.9)\begin{aligned} \mathbb{E}\big[x_{t+1}^2\big] &= (1 - \eta\lambda)^2\, \mathbb{E}\big[x_t^2\big] + \eta^2 \sigma^2 \\ \Longrightarrow \quad \mathbb{E}\big[x_\infty^2\big] &\approx \frac{\eta\, \sigma^2}{2\lambda} \approx \frac{\eta}{2\lambda}. \end{aligned} \tag{9.5.9}

Stabilizing the root-mean-square weight magnitude at RMS(x∞)∝η/(2λ)\text{RMS}(\mathbf{x}_\infty) \propto \sqrt{\eta / (2\lambda)} stabilizes the relative angular update rate of normalized weight matrices at η/RMS(x∞)∝2ηλ\eta / \text{RMS}(\mathbf{x}_\infty) \propto \sqrt{2\eta\lambda} (rotational equilibrium, Kosson et al. (2024)), preventing the uncontrolled t\sqrt{t} random-walk growth of unregularized weights that would otherwise decay the effective angular step size as 1/t1/\sqrt{t} over long pretraining runs (D'Angelo et al., 2024). When sweeping η\eta, holding the per-step shrinkage s=ηλs = \eta\lambda (and thus the timescale τ=1/s\tau = 1/s) fixed decouples the learning-rate search from the decay timescale (Loshchilov and Hutter, 2019; Wang and Aitchison, 2025; Bergsma et al., 2025).

9.5.3.3 Parameters Exempt from Weight Decay and Optimizer State Memory#

Standard Transformer recipes apply decoupled weight decay to the weight matrices and exempt biases and normalization parameters. OLMo 2 additionally exempts the embedding tables, and we adopt that choice here. Decay is then applied only to 2D internal projection matrices (90%90\% of TinyLM), while two parameter groups are exempted (λ=0\lambda = 0):

  1. 1D biases and LayerNorm/RMSNorm gain and shift vectors: Normalization scales start near 11 and directly control feature variance; decaying them toward zero distorts layer activations rather than regulating angular update speed.
  2. Token and positional embedding tables (the OLMo 2 exemption): Token embedding rows receive gradients only when their token appears in a minibatch, whereas decoupled decay shrinks every row on every step, collapsing rare token representations and inflating downstream LayerNorm gradients (OLMo et al., 2025).
model = d2l.TinyLM(len(data.vocab))
decay = [p for name, p in model.named_parameters()
         if p.ndim == 2 and 'emb' not in name]
no_decay = [p for name, p in model.named_parameters()
            if p.ndim != 2 or 'emb' in name]
optimizer = torch.optim.AdamW([
    {'params': decay, 'weight_decay': 0.1},
    {'params': no_decay, 'weight_decay': 0.0}], lr=3e-3)
n_decay = sum(p.numel() for p in decay)
n = n_decay + sum(p.numel() for p in no_decay)
print(f'decayed: {n_decay} of {n} parameters')
decayed: 425984 of 470784 parameters

9.5.3.4 Optimizer State Memory#

Finally, maintaining the two per-parameter buffers (mt,vt)(\mathbf{m}_t, \mathbf{v}_t) doubles the static parameter memory footprint. In 32-bit floating point (44 bytes per scalar), each trainable parameter requires 1616 bytes of device memory: 44 bytes for the parameter x\mathbf{x}, 44 bytes for the gradient g\mathbf{g}, and 88 bytes for the AdamW state (m,v)(\mathbf{m}, \mathbf{v}) (Section 13.4). For a 10910^9-parameter model, the optimizer state alone consumes 8 GB8\text{ GB} before storing any activations. Freezing parameters (leaving them out of the optimizer) or quantizing/factoring (m,v)(\mathbf{m}, \mathbf{v}) directly eliminates or compresses this 88-byte-per-parameter overhead.

While AdamW normalizes each weight entry independently, 2D weight matrices act as linear operators on activation vectors. Section 9.6 asks whether we can do even better by normalizing the update of each 2D weight matrix as a whole operator rather than entry by entry.

9.5.4 Summary#

AdaGrad scales each coordinate inversely by the root of its cumulative squared gradients, RMSProp replaces that unbounded sum with a leaky exponential moving average vt\mathbf{v}_t, and Adam adds first-moment momentum mt\mathbf{m}_t together with bias corrections 1−β1t1 - \beta_1^t and 1−β2t1 - \beta_2^t. Dividing m^t\hat{\mathbf{m}}_t by v^t\sqrt{\hat{\mathbf{v}}_t} makes Adam invariant to diagonal rescaling of the gradient, turning η\eta into a direct coordinate step length in parameter space and equalizing update magnitudes across Transformer parameter groups whose raw gradients differ by 15–40×15\text{--}40\times. AdamW decouples weight decay xt+1=(1−ηλ)xt−ηm^t/(v^t+ϵ)\mathbf{x}_{t+1} = (1 - \eta\lambda)\mathbf{x}_t - \eta\hat{\mathbf{m}}_t/(\sqrt{\hat{\mathbf{v}}_t}+\epsilon) from the adaptive preconditioner, establishing a uniform decay timescale τ=1/(ηλ)\tau = 1/(\eta\lambda), an equilibrium weight RMS proportional to η/(2λ)\sqrt{\eta/(2\lambda)}, and a steady relative angular step proportional to 2ηλ\sqrt{2\eta\lambda}. Standard recipes decay only 2D weight matrices while exempting 1D biases and normalization parameters (and, following OLMo 2, embedding tables), with (mt,vt)(\mathbf{m}_t, \mathbf{v}_t) accounting for 88 of the 1616 bytes per trainable parameter in float32.

9.5.5 Exercises#

  1. [code] Coordinate rotation vs. diagonal scale invariance.

    1. Verify with adam_2d on d2l.f_valley that Adam is invariant to rescaling the objective by c>0c > 0 (for c≫ϵc \gg \epsilon) and to changing λ2\lambda_2 from 44 to 400400.
    2. Rotate the valley by 45∘45^\circ via f(x)=0.05(x1+x2)2+(x1−x2)2f(\mathbf{x}) = 0.05(x_1 + x_2)^2 + (x_1 - x_2)^2. Run adagrad_2d, rmsprop_2d, and adam_2d at η=0.4\eta = 0.4 for 2,0002{,}000 steps on the unrotated and rotated valleys (and with λ2=400\lambda_2 = 400), and explain why rotating the eigenbasis away from the coordinate axes restores ill-conditioning for diagonal preconditioners.
  2. [code] Constant-rate limit cycles and AMSGrad. ●

    1. Show that if a 1D coordinate alternates as xt=(−1)tax_t = (-1)^t a on f(x)=λ2x2f(x) = \frac{\lambda}{2}x^2 under Adam, its amplitude is a=1−β11+β1η2a = \frac{1-\beta_1}{1+\beta_1}\frac{\eta}{2} independent of λ\lambda.
    2. Run adam_2d on f_valley for 20,00020{,}000 steps and explain why the iterate approaches within 10−4010^{-40} of the origin while v^t\hat{v}_t remembers the initial gradients, then gets ejected once v^t\hat{v}_t decays below the momentum stability threshold. Verify that replacing v^t\hat{v}_t with max⁡s≤tv^s\max_{s \le t} \hat{v}_s (AMSGrad) prevents the ejection.
  3. [extended] Frequent and rare tokens and per-group learning rates.

    1. Following Kunstner et al. (2024), partition the 256256 byte values of WikiText103 into frequent (≥0.1%\ge 0.1\%) and rare (<0.1%\lt 0.1\%) tokens, and compare validation loss on each group under tuned SGD with momentum, Adam, and sign descent with momentum (η sign⁡(mt)\eta\,\operatorname{sign}(\mathbf{m}_t)).
    2. Assign separate learning rates to the three parameter groups of TinyLM (embeddings, 2D matrices, 1D vectors) under SGD with momentum, and measure how much of the SGD–Adam gap is closed by group-level versus coordinate-level scaling.
  4. [code] Adversarial periodic gradients and second-moment repairs. On the 3-periodic sequence ft(x)=4xf_t(x) = 4x (t≡1(mod3)t \equiv 1 \pmod 3) and ft(x)=−xf_t(x) = -x otherwise on x∈[−1,1]x \in [-1, 1] (Reddi et al., 2018), run Adam with β1=0,β2=1/17,ηt=0.5/t\beta_1 = 0, \beta_2 = 1/17, \eta_t = 0.5/\sqrt{t} and compare it against AMSGrad and Yogi (Zaheer et al., 2018).

  5. Two limits of AdamW and rotational equilibrium.

    1. For xt+1=(1−ηλ)xt−ηntx_{t+1} = (1 - \eta\lambda)x_t - \eta n_t, derive the deterministic equilibrium ∣x∞∣=1/λ|x_\infty| = 1/\lambda when nt=−1n_t = -1 is constant, the zero-mean noise equilibrium E[x∞2]≈η/(2λ)\mathbb{E}[x_\infty^2] \approx \eta/(2\lambda) when ntn_t is i.i.d. with E[nt]=0,E[nt2]=1\mathbb{E}[n_t]=0, \mathbb{E}[n_t^2]=1, and the mixed equilibrium E[x∞2]≈nˉ2/λ2+η/(2λ)\mathbb{E}[x_\infty^2] \approx \bar{n}^2/\lambda^2 + \eta/(2\lambda) when nt=nˉ+ξtn_t = \bar{n} + \xi_t.
    2. Simulate xt+1=(1−ηλ)xt−ηut\mathbf{x}_{t+1} = (1 - \eta\lambda)\mathbf{x}_t - \eta\mathbf{u}_t in R1000\mathbb{R}^{1000} with ut⊥xt\mathbf{u}_t \perp \mathbf{x}_t (Kosson et al., 2024) to verify that the equilibrium RMS matches η/(2λ)\sqrt{\eta/(2\lambda)} and the per-step rotation angle matches 2ηλ\sqrt{2\eta\lambda}.
  6. [code] Joint (η,λ)(\eta, \lambda) search and parameter-group exemptions. ●

    1. Train TinyLM on 8,0008{,}000 overlapping windows of d2l.TimeMachine for 800800 steps across a grid of η∈{10−3,3×10−3,10−2}\eta \in \{10^{-3}, 3 \times 10^{-3}, 10^{-2}\} and λ\lambda, comparing parametrization by λ\lambda versus per-step shrinkage s=ηλs = \eta\lambda.
    2. Compare validation perplexity on WikiText103 at λ∈{0.5,1.0}\lambda \in \{0.5, 1.0\} when decaying all parameters versus decaying only 2D weight matrices (Section 9.5.3.3), and identify whether exempting embeddings or 1D vectors accounts for most of the gain.

Discussions