Adam and AdamW

Dive into Deep Learning · §9.5

Adaptive Learning-Rate Methods: AdaGrad, RMSProp, Adam, and AdamW
per-coordinate RMS scaling · bias correction · step-length invariance · decoupled weight decay · timescale & equilibrium norm

Why Transformers Need Per-Coordinate Learning Rates

Motivation

  • 40× cross-layer gradient disparity: In a Transformer, raw gradient magnitudes differ by 15\text{--}40\times across token embeddings, attention projections, MLP layers, and LayerNorm parameters—starving embeddings under any scalar SGD step size.
  • Adaptive RMS preconditioning: Dividing each coordinate’s update by its historical RMS gradient scale turns \eta into a direct coordinate step length in parameter space (\eta^\star \approx 3 \times 10^{-3} vs. 0.5 for SGD) and requires decoupling weight decay (AdamW).

AdaGrad: Cumulative Squared-Gradient Preconditioning

Per-Coordinate Scaling

AdaGrad (Duchi et al., 2011) accumulates the running elementwise sum of squared gradients \mathbf{s}_t = \mathbf{s}_{t-1} + \mathbf{g}_t^2 from \mathbf{s}_0 = \mathbf{0} and scales each coordinate inversely by \sqrt{\mathbf{s}_t + \epsilon}:

\mathbf{x}_{t+1} = \mathbf{x}_t - \frac{\eta}{\sqrt{\mathbf{s}_t + \epsilon}} \odot \mathbf{g}_t

  • Rare vs. frequent features: Infrequently updated coordinates (e.g., rare token embeddings) keep a small denominator \sqrt{s_{t,i}} and take full steps whenever their feature appears.
  • Automatic axis-aligned preconditioning: Because |g_i| = \lambda_i |x_i| is proportional to curvature, dividing by \sqrt{s_{t,i}} cancels the \kappa = 20 disparity between x_1 and x_2 on the valley.
step 20, x1: -0.002295, x2: -0.000000

RMSProp: Leaky Moving Averages of Squared Gradients

Forgetting Ancient Gradients

  • Why AdaGrad stalls on deep networks: Because \mathbf{s}_t = \sum_{s=1}^t \mathbf{g}_s^2 grows monotonically without bound (\mathbf{s}_t \propto t), AdaGrad’s effective step size decays as O(t^{-1/2}) and prematurely halts learning.
  • RMSProp (Tieleman & Hinton, 2012) replaces the cumulative sum with an exponential moving average (EMA) over a memory window of \tau_2 = \frac{1}{1-\beta_2} steps: \mathbf{v}_t = \beta_2\,\mathbf{v}_{t-1} + (1 - \beta_2)\,\mathbf{g}_t^2
  • By forgetting ancient gradients (\beta_2 = 0.9 \implies 10-step window), RMSProp maintains a non-vanishing step size and converges rapidly on the valley at \eta = 0.4.
step 20, x1: -0.010599, x2: 0.000000

Two Consequences of Uncorrected RMS Normalization

Early Jumps & Late Oscillation

  • 1. Cold-start step amplification: From \mathbf{v}_0 = \mathbf{0}, step 1 evaluates \mathbf{v}_1 = (1-\beta_2)\mathbf{g}_1^2, producing an oversized jump |\Delta x_{1,i}| = \frac{\eta}{\sqrt{1-\beta_2}} (3.16\,\eta at \beta_2=0.9; 31.6\,\eta at \beta_2=0.999).
  • 2. Non-vanishing late-stage steps: Near a minimum where |g_t| is locally steady, \sqrt{v_t} \approx |g_t| and the update becomes -\eta\,\operatorname{sign}(g_t) of fixed length \eta, hopping within \pm\eta/2 until \eta_t \to 0 (§9.7).

Adam: First and Second Moments with Bias Correction

Adaptive Moment Estimation

  • Dual moving averages (\mathbf{m}_0 = \mathbf{v}_0 = \mathbf{0}): \mathbf{m}_t = \beta_1\mathbf{m}_{t-1} + (1-\beta_1)\mathbf{g}_t, \quad \mathbf{v}_t = \beta_2\mathbf{v}_{t-1} + (1-\beta_2)\mathbf{g}_t^2
  • Bias-corrected update: \hat{\mathbf{m}}_t = \frac{\mathbf{m}_t}{1-\beta_1^t}, \quad \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1-\beta_2^t}, \quad \mathbf{x}_{t+1} = \mathbf{x}_t - \eta\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t}+\epsilon}
  • Dividing by 1 - \beta^t normalizes the geometric weights at every step t \ge 1 (defaults: \beta_1 = 0.9, \beta_2 \in \{0.95, 0.999\}, \epsilon = 10^{-8}).

Scale Invariance: η Is a Direct Coordinate Step Length

Geometry of Adam

  • Exact step-1 magnitude: At t = 1, \hat{\mathbf{m}}_1 = \mathbf{g}_1 and \hat{\mathbf{v}}_1 = \mathbf{g}_1^2, so for \sqrt{\hat{v}_{1,i}} \gg \epsilon: \Delta x_{1,i} = -\eta\,\frac{g_{1,i}}{|g_{1,i}|} = -\eta\,\operatorname{sign}(g_{1,i}) Every coordinate moves by \pm\eta on step 1 (45^\circ diagonal on the valley).
  • Diagonal scale invariance: Multiplying the loss or rescaling coordinate i by c > 0 scales g_{t,i} \to c\,g_{t,i}, \hat{m}_{t,i} \to c\,\hat{m}_{t,i}, and \sqrt{\hat{v}_{t,i}} \to c\sqrt{\hat{v}_{t,i}}, canceling c from the ratio.
  • Step-length bounds: Persistent gradients step by \approx \eta; zero-mean noise steps by \approx \eta\sqrt{\frac{1-\beta_1}{1+\beta_1}} \approx 0.23\,\eta.

step 200, x1: 0.000022, x2: 0.000042

Implementing Adam from Scratch

Code Implementation

Each trainable parameter tensor keeps a step counter t and two buffers (\mathbf{m}, \mathbf{v}) of its shape:

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))

40× Gradient Disparity vs. 2× Adam Step Disparity

Gradient Scales in TinyLM

  • Measuring the RMS gradient magnitude across 10 minibatches for all 8 functional parameter groups of TinyLM reveals why scalar-LR SGD struggles:
    • At step 0: Raw gradient RMS spans a 40\times range (from 2 \times 10^{-4} on token_emb to 7 \times 10^{-3} on biases).
    • At step 500: Gradient RMS still spans a 15\times range.
  • Adam’s equalization: Dividing by \sqrt{\hat{\mathbf{v}}_t} compresses the actual RMS parameter update \|\Delta\mathbf{x}\|_{\text{RMS}}/\eta across all 8 groups into a tight 2\times band (0.12\text{--}0.28\,\eta).
             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

Learning-Rate Sweep: Adam vs. SGD with Momentum

3-Seed Grid Comparison

  • We sweep SGD with momentum (\beta = 0.9) across \eta \in \{0.1, 0.3, 0.5, 1.0\} and Adam across \eta \in \{3{\times}10^{-4}, 10^{-3}, 3{\times}10^{-3}, 10^{-2}, 3{\times}10^{-2}\} over 3 seeds (2{,}000 steps on TinyLM):
    • 100× nominal scale shift: SGD’s best rate is \eta = 0.3, whereas Adam’s is \eta = 3 \times 10^{-3} (\approx 0.1 \times \frac{0.3}{\text{scale}}).
    • Graceful high-LR degradation: SGD diverges to inf at \eta = 0.5 (less than 2\times above its optimum), whereas Adam remains finite even at \eta = 3 \times 10^{-2} (10\times above its optimum) because its step length is bounded by \eta.
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

Adam Reaches Target Loss in Half the Steps of SGD

Speed, Range, and Stability

  • Comparing the 3 runs at each optimizer’s best learning rate shows three decisive advantages for Adam on TinyLM:
    1. Convergence speed: Reaches 1.8 nats in 650\text{--}775 steps vs. 1{,}125\text{--}1{,}550+ steps for SGD+momentum.
    2. Usable LR window (within +0.15 nats): 10\times range (10^{-3} to 10^{-2}) vs. a single fragile grid point (0.3) for SGD.
    3. Spike resilience: Worst single-step loss rise is <0.20 nats under Adam vs. >0.4\text{--}1.0 nats under SGD.

       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

Sign Descent, Role of ε, and Small-β₂ Pathologies

Mechanics & Edge Cases

  • Adam as smoothed sign descent: Setting \beta_1 = \beta_2 = 0, \epsilon = 0 gives \mathbf{x}_{t+1} = \mathbf{x}_t - \eta\,\operatorname{sign}(\mathbf{g}_t); adding momentum matches Adam’s lead over SGD on Transformers (Kunstner et al., 2023).
  • \epsilon as a maximum-LR cap: \frac{\eta}{\sqrt{\hat{v}_{t,i}} + \epsilon} \le \frac{\eta}{\epsilon}; for \epsilon \gg \sqrt{\hat{v}_{t,i}}, Adam reduces to SGD with momentum at rate (1-\beta_1)\eta/\epsilon.
  • Why \beta_2 must not be too small (Reddi et al., 2018): A short-memory \beta_2 lets rare large gradients inflate \sqrt{v_t} while small opposite gradients step further; keeping \beta_2 \in [0.95, 0.999] prevents this.

Why Standard ℓ₂ Regularization Breaks Under Adam

Coupled vs. Decoupled Decay

  • Coupled \ell_2 penalty inside Adam (\mathbf{g}_t \leftarrow \mathbf{g}_t + \lambda\mathbf{x}_t): Divides the decay penalty by each coordinate’s preconditioner: \Delta x_{t,i}^{\text{decay}} = -\frac{\eta\,\lambda}{\sqrt{\hat{v}_{t,i}} + \epsilon}\; x_{t,i}
  • Pathology: Weights with small loss gradients are decayed up to 10^3\times more harshly than active weights—or normalize the penalty by itself to collapse x_{t,i} \to 0 at speed \eta/step.

AdamW: Decoupling Weight Decay from the Preconditioner

Loshchilov & Hutter (2019)

AdamW computes \hat{\mathbf{m}}_t and \hat{\mathbf{v}}_t purely from the data loss gradient \mathbf{g}_t and applies uniform multiplicative shrinkage (1 - \eta\lambda) directly to the weights:

\mathbf{x}_{t+1} = (1 - \eta\lambda)\,\mathbf{x}_t - \eta\,\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon}

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()

Coupled ℓ₂ Collapses Weight Matrices; AdamW Trains

1,000-Step Comparison at λ = 0.1

  • Training TinyLM for 1{,}000 steps at \eta = 3 \times 10^{-3} and \lambda = 0.1 from identical initial weights (initial matrix RMS = 0.0447):
    • No decay (\lambda = 0): Final loss \approx 1.74 nats; matrix RMS grows to 0.108\text{--}0.110.
    • Decoupled AdamW (\lambda = 0.1): Final loss 1.72\text{--}1.74 nats; matrix RMS bounded at 0.097\text{--}0.100.
    • Coupled Adam + ℓ2 (\lambda = 0.1): Collapses matrix RMS 16\times down to 0.0027\text{--}0.0028, erasing internal representations so the model stalls at 3.15\text{--}3.16 nats (unigram byte frequency entropy 3.18).

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

Unrolling AdamW: The Decay Timescale τ = 1/(ηλ)

Weights as an EMA of Updates

  • Unrolled EMA of normalized updates \mathbf{u}_s = \frac{\hat{\mathbf{m}}_s}{\sqrt{\hat{\mathbf{v}}_s}+\epsilon} (Wang & Aitchison, 2025): \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
  • Weight-decay timescale: \tau = \frac{1}{\eta\lambda} steps (3{,}333 steps at \eta = 3 \times 10^{-3}, \lambda = 0.1).
  • Hyperparameter decoupling: When sweeping \eta, hold per-step shrinkage s = \eta\lambda = 1/\tau fixed (\lambda = s/\eta).

Equilibrium Weight Norm and Rotational Equilibrium

Steady-State Weight Dynamics

  • Stochastic norm equilibrium (t \gtrsim 2\tau): Balancing decay (1-\eta\lambda)x_t against unit-RMS steps -\eta n_t gives: \text{RMS}(\mathbf{x}_\infty) \approx \sqrt{\frac{\eta}{2\lambda}}
  • Why \lambda = 0 slows angular learning: Without decay, \text{RMS}(\mathbf{x}_t) \propto \eta\sqrt{t} grows via random walk, shrinking the relative angular step across scale-invariant LayerNorm sublayers as 1/\sqrt{t}.
  • Rotational equilibrium (Kosson et al., 2024): Under AdamW, \frac{\eta}{\text{RMS}(\mathbf{x}_\infty)} \approx \sqrt{2\eta\lambda} stays constant across layers.

Parameters Exempt from Weight Decay and State Memory

Parameter Groups & 16-Byte Footprint

  • Decay only 2D internal projection matrices (90\% of TinyLM): the first exemption is standard, the second follows OLMo 2.
    • Exempt 1D biases & LayerNorm scales/shifts (\lambda = 0): LayerNorm gains control feature variance directly around 1.0; decaying them distorts activations.
    • Exempt token & positional embeddings (\lambda = 0): Rare token rows receive gradients only when sampled, so every-step decay collapses rare embeddings and inflates downstream LayerNorm gradients (OLMo 2, 2025).
  • 16 bytes per parameter in float32: Weight (4\text{ B}) + Gradient (4\text{ B}) + AdamW state \mathbf{m}, \mathbf{v} (8\text{ B}) = 16\text{ B} (8\text{ GB} of optimizer state alone for a 1\text{B}-parameter model).
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')

Concept Check: Bias Correction, Timescales, and VRAM

Check Your Understanding

Test your understanding with three concrete calculations:

  1. Missing bias correction: If you run Adam with \beta_1 = 0.9, \beta_2 = 0.999, \eta = 10^{-3} without bias correction, what is the magnitude of the parameter update |\Delta x_{1,i}| on step t = 1 compared to corrected Adam?
  2. Timescale & relative step invariance: A run uses AdamW at \eta = 3 \times 10^{-3} and \lambda = 0.5. If you halve the learning rate to \eta = 1.5 \times 10^{-3} and double weight decay to \lambda = 1.0, how do the decay timescale \tau, the equilibrium weight RMS, and the relative angular step \eta / \text{RMS} change?
  3. VRAM accounting: You train a 7-billion-parameter Transformer with AdamW keeping master weights, gradients, and (\mathbf{m}, \mathbf{v}) in float32. How many gigabytes do these static buffers occupy before activations?

Answers:

  1. Without bias correction, |\Delta x_{1,i}| = \eta\frac{1 - \beta_1}{\sqrt{1 - \beta_2}} = \eta\frac{0.1}{\sqrt{0.001}} \approx 3.16\,\eta = 3.16 \times 10^{-3} (3.16\times larger than corrected Adam’s exact step length \eta = 10^{-3}).
  2. Because \eta\lambda = 1.5 \times 10^{-3} is invariant, both the timescale \tau = \frac{1}{\eta\lambda} \approx 667 steps and the relative angular step \sqrt{2\eta\lambda} \approx 0.055 stay unchanged, while the equilibrium norm \sqrt{\eta/(2\lambda)} halves (which scale-invariant LayerNorm sublayers ignore).
  3. At 16\text{ bytes/parameter}, static memory is 7 \times 10^9 \times 16\text{ B} = 112\text{ GB}, of which 56\text{ GB} (50\%) is the AdamW state (\mathbf{m}, \mathbf{v}).

Summary: Adaptive Coordinate Methods and AdamW

Key Takeaways

Optimizer / Concept Mathematical Update / Invariant Memory & Timescale Deep Learning Role
AdaGrad \mathbf{s}_t = \mathbf{s}_{t-1} + \mathbf{g}_t^2,\; \Delta\mathbf{x}_t = -\frac{\eta}{\sqrt{\mathbf{s}_t+\epsilon}}\odot\mathbf{g}_t 1 buffer (4\text{ B}/param); step decays as O(t^{-1/2}) Sparse convex features; stalls on deep non-convex networks
RMSProp \mathbf{v}_t = \beta_2\mathbf{v}_{t-1} + (1-\beta_2)\mathbf{g}_t^2 1 buffer; scale window \tau_2 = \frac{1}{1-\beta_2} Non-vanishing adaptive steps; lacks momentum & bias correction
Adam \hat{\mathbf{m}}_t = \frac{\mathbf{m}_t}{1-\beta_1^t},\; \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1-\beta_2^t},\; \Delta\mathbf{x}_t = -\eta\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t}+\epsilon} 2 buffers (8\text{ B}/param); \tau_1 = 10, \tau_2 = 1{,}000 Invariant to diagonal rescaling; equalizes 40\times layer gradient spread
AdamW \mathbf{x}_{t+1} = (1 - \eta\lambda)\mathbf{x}_t - \eta\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t}+\epsilon} Decay timescale \tau = \frac{1}{\eta\lambda} Bypasses \sqrt{\hat{v}_t} scaling; decay 2D weight matrices only
Equilibrium Norm \text{RMS}(\mathbf{x}_\infty) \approx \sqrt{\frac{\eta}{2\lambda}},\quad \frac{\eta}{\text{RMS}(\mathbf{x}_\infty)} \approx \sqrt{2\eta\lambda} Settles after \sim 2\tau = \frac{2}{\eta\lambda} steps Prevents \sqrt{t} weight growth and 1/\sqrt{t} effective LR decay