Practice

Dive into Deep Learning · §9.10

Practical Optimization Diagnostics and Recipes
global-norm gradient clipping · guard vs. brake · AdamW spike recovery · weight EMA · end-to-end configuration

Three Pillars of a Production Pretraining Run

Motivation

  • 1. Guards against transient instabilities: Global-norm clipping (\theta = 1.0) prevents early high-curvature blow-ups under SGD and protects AdamW’s second moment \mathbf{v}_t from spikes, paired with \beta_2 = 0.95 and checkpoint rewind.
  • 2. Iterate smoothing (Weight EMA): Exponentially averaging live weights cancels late-stage noise-ball jitter without decaying \eta_t \to 0.
  • 3. Short-horizon proxy calibration: Calibrate peak \eta_0 and b_{\text{noise}} over 10\% of steps (300 of 3{,}000) before launching the full run.

Global-Norm Gradient Clipping: Direction-Preserving Cap

Clipping Mechanics

Global-norm gradient clipping treats the concatenated gradient across all parameters as a single vector \mathbf{g} \in \mathbb{R}^d and rescales it whenever its Euclidean norm \|\mathbf{g}\|_2 exceeds a threshold \theta > 0:

\mathbf{g} \leftarrow \min\!\left(1,\; \frac{\theta}{\|\mathbf{g}\|_2}\right)\mathbf{g}

  • Preserves cross-layer relative magnitudes: Unlike elementwise clipping (which distorts each layer’s direction into a sign vector), global-norm clipping multiplies every parameter’s gradient by the same scalar \theta / \|\mathbf{g}\|_2 < 1.
  • Bounds SGD step length: Under plain SGD, no parameter update can exceed Euclidean length \eta\theta.
class Clipped:
    """Clip the global gradient norm before every optimizer step."""
    def __init__(self, optimizer, params, max_norm=1.0):
        self.optimizer, self.params = optimizer, list(params)
        self.max_norm, self.norms = max_norm, []

    def step(self):
        self.norms.append(nn.utils.clip_grad_norm_(self.params, self.max_norm))
        self.optimizer.step()

    def zero_grad(self):
        self.optimizer.zero_grad()

Testing Two Hypotheses for SGD Divergence at η = 1.0

Guard vs. Brake Experiment

  • Why did SGD+momentum (\beta = 0.9) on TinyLM train at \eta = 0.3 but diverge within 20 steps at \eta = 1.0?
  • Hypothesis A — Transient initial sharpness: \eta = 1.0 is only too large during the opening steps; clipping at \theta = 1.0 fires on the first few dozen steps, then falls silent (guard).
  • Hypothesis B — Globally excessive LR: \eta exceeds 2/L everywhere; clipping fires on almost every step (>50\text{--}100\%, constant brake).

Clipping Fires on <2% of Steps and Rescues η = 1.0

Empirical Clipping Diagnostics on TinyLM

  • Running 2{,}000 steps across (\eta, \theta) \in \{(1.0, \infty), (1.0, 1.0), (0.3, \infty), (3.0, 1.0)\} over two seeds confirms Hypothesis A at \eta = 1.0:
    • At \eta = 1.0, \theta = \infty: Diverges to inf within 20 steps.
    • At \eta = 1.0, \theta = 1.0 (Guard): Clipping fires on only 14\text{--}17 steps (all before step 30), never fires again over the remaining 1{,}970 steps (median \|\mathbf{g}_t\|_2 \approx 0.25), and reaches 1.61\text{--}1.63 nats (beating unclipped \eta = 0.3).
    • At \eta = 3.0, \theta = 1.0 (Brake): Fires on every single step until overflowing or stalling above 100 nats.
  lr  clip at  final loss  steps clipped  last  median norm  largest / median
   1      inf         inf
   1        1       1.626             17    28         0.25               1.8
 0.3      inf       1.671
   3        1         inf           1997  1996          nan               nan
   1      inf         inf
   1        1       1.619             17    16         0.26               1.8
 0.3      inf       1.652
   3        1         inf           1636  1635          nan               nan

Distinguishing a Guard from a Brake in Training Logs

Setting the Clipping Threshold θ

  • Healthy Guard (\eta = 1.0, \theta = 1.0):
    • Fires on <2\%\text{--}5\% of steps (opening transient or rare spikes); steady-state median \|\mathbf{g}_t\|_2 \approx 0.25 \approx \theta/4.
  • Constant Brake (\eta = 3.0, \theta = 1.0):
    • Fires on >50\%\text{--}100\% of steps, turning the optimizer into fixed-step normalized descent.
  • Engineering rule: When clipping fires on >20\%\text{--}50\% of steps, lower the learning rate \eta first before tuning \theta.

Why Clipping Under AdamW Protects the Second Moment v_t

AdamW Spike Dynamics

  • Immediate step is already bounded: In AdamW, a spike g_t \gg \sqrt{v_{t-1}} appears in both \mathbf{m}_t and \sqrt{\mathbf{v}_t}, bounding |\Delta x_t| \approx \eta\frac{1-\beta_1}{\sqrt{1-\beta_2}} \le 3.16\eta.
  • Clipping protects the denominator state \mathbf{v}_t:
    • An unclipped 100\times spike injects (1-\beta_2)10^4 into v_t: at \beta_2 = 0.999, v_t jumps 11\times, shrinking subsequent effective LRs to 30\% for 2{,}300 steps.
    • Clipping at \theta = 4\times median norm caps injection below 2\%, and \beta_2 = 0.95 cuts recovery time 20\times (\sim 120 steps).

Operational Spike Recovery and Softmax z-Loss

Surviving Mid-Run Instabilities

  • Why mid-run spikes happen (PaLM, Chowdhery et al., 2022): Triggered by the coincidence of a marginal parameter state with a specific anomalous data batch.
  • Operational recovery protocol:
    1. Rewind to a checkpoint \sim 100 steps before the spike (restoring weights, \mathbf{m}_t, \mathbf{v}_t, step t).
    2. Skip the 200\text{--}500 minibatches surrounding the spike.
  • Softmax z-loss (10^{-4}\log^2 Z): Pulls \log Z \to 0 via restoring gradient 2{\times}10^{-4}(\log Z)\mathbf{p} without altering \mathbf{p}.

Weight Averaging (EMA): Smoothing the Noise Ball

Polyak–Ruppert Iterate Averaging

  • At any non-zero learning rate \eta, the live weights \mathbf{x}_t represent a single random draw from the stationary noise ball (§9.2).
  • Maintaining an exponential moving average (EMA) \bar{\mathbf{x}}_t of the live parameters with decay \alpha \in [0.99, 0.9999] (Polyak & Juditsky, 1992): \bar{\mathbf{x}}_t = \alpha\,\bar{\mathbf{x}}_{t-1} + (1 - \alpha)\,\mathbf{x}_t averages over a trailing window of \tau_{\text{EMA}} = \frac{1}{1 - \alpha} steps without altering the live training trajectory.
  • Choosing \alpha and start step: \tau_{\text{EMA}} must exceed the noise-ball autocorrelation time \frac{1}{\eta\lambda_{\text{curv}}} (e.g., \alpha = 0.999 \implies 1{,}000 steps), and averaging should start after the initial rapid descent phase so early high-loss weights do not lag the average.
def warmup_cosine(peak, warmup, num_steps):
    """A linear warmup to peak over warmup steps, then a cosine to zero."""
    def schedule(t):
        if t < warmup:
            return peak * t / warmup
        return peak * (1 + math.cos(math.pi * (t - warmup)
                                    / (num_steps - warmup))) / 2
    return schedule

Constant-Rate Weight EMA vs. Live Weights on FashionCNN

Eliminating Epoch-to-Epoch Jitter

  • Training FashionCNN for 15 epochs (235 steps/epoch = 3{,}525 steps) with plain SGD at a constant learning rate \eta = 0.3:
    • Live weights (blue): Bounce inside the noise ball, jittering across a test-accuracy band of several percentage points below \approx 91\% over the last five epochs, with an occasional deeper single-epoch drop.
    • Weight EMA (\alpha = 0.999, started at epoch 5, orange): Rises smoothly along the top of the band to about 91\% test accuracy, matching the full cosine-decayed trajectory (green).

Weight EMA Matches Cosine Decay Without Lowering η

Two-Seed Quantitative Comparison

  • Comparing constant-rate SGD (\eta = 0.3) against cosine decay (\eta: 0.3 \to 0) across two seeds on FashionCNN:
    • At a constant learning rate: The EMA improves final test accuracy by about 0.5\text{--}2 percentage points over the noisy live checkpoint, matching the \approx 91\% accuracy of a full cosine decay.
    • After cosine decay to zero: The live weights have already settled at the center of the noise ball (\eta_T = 0), so taking an EMA on top of a fully decayed run adds nothing (or lags by a few tenths of a point).
  • When to use Weight EMA: During constant-rate / WSD plateau training to obtain a usable model at any step without waiting for a cooldown branch (on language models it recovers part, not all, of the cooldown gain; Hägele et al., 2024).
test accuracy    live, last five epochs  live, final  EMA, final
constant rate            0.792 to 0.913        0.908       0.914
cosine decay             0.906 to 0.912        0.911       0.909
constant rate            0.870 to 0.902        0.902       0.910
cosine decay             0.899 to 0.908        0.908       0.906

Published Frontier Pretraining Recipes: What Agrees

Industry Reference Configurations

  • DeepSeek-V3 671B, OLMo 2 7B, and Kimi K2 1T agree wherever they publish a value (Llama 3 405B does not report \beta, \theta, or \lambda):
    • Moments: (\beta_1, \beta_2) = (0.9, 0.95) for fast spike recovery.
    • Decoupled weight decay: \lambda = 0.1 on 2D matrices only (biases & 1D norms exempt; OLMo 2 also exempts embeddings).
    • Global-norm clipping: \theta = 1.0.
    • Schedule & batch policy: 500\text{--}8{,}000 warmup steps + cosine or WSD cooldown to 0.01\text{--}0.1\eta_0, paired with multi-million-token batch ramps.

Diagnostic Playbook: Reading Failure Signatures in Logs

From Telemetry to Action

  • Always log 4 curves: Loss, pre-clip \|\mathbf{g}_t\|_2, clipping indicator (\|\mathbf{g}_t\|_2 > \theta), and relative step \|\Delta\mathbf{W}\|_{\text{RMS}}/\|\mathbf{W}\|_{\text{RMS}}:
    • Explodes in steps 1–20 / step-1 jump >10\%: Add linear warmup (1\text{--}5\%) and clipping (\theta = 1.0).
    • Stalls high behind warmup or clips >20\%: Peak \eta_0 is too high \to lower \eta_0 by 2\text{--}3\times.
    • Plateaus with high jitter: Decay \eta_t \to 0, use Weight EMA, or increase b.
    • Constant slope at step T: Under-budgeted B_T \to raise \eta_0 or extend T.

Case Study: Configuring a 3.3M-Parameter TinyLM

Putting All 10 Sections Together

We configure a 3{,}000-step training run for a new 4-block, width-256, 4-head TinyLM (3.3\text{M} parameters, 7\times larger than our 2-block model) without repeating the full 3{,}000-step run across a grid:

  1. Batch size (b = 256 sequences): Chosen where GPU throughput saturates and comparable to post-warmup b_{\text{noise}} \sim 100.
  2. Optimizer & guards: AdamW with (\beta_1, \beta_2) = (0.9, 0.95), decoupled weight decay \lambda = 0.1 on 2D matrices only, global-norm clipping \theta = 1.0, and weight EMA (\alpha = 0.995).
  3. Short-horizon peak LR calibration (10\% budget): Sweep \eta \in \{10^{-3}, 3{\times}10^{-3}, 10^{-2}\} for 300 steps.
  4. Schedule: 60-step linear warmup (2\%) + cosine decay to zero.
def train(seed, schedule, num_steps, max_norm=1.0, alpha=0.995):
    """AdamW with betas (0.9, 0.95) and weight decay 0.1 on the matrices at
    the rate schedule(t), clipped at max_norm, with an EMA of the weights;
    return the losses, the model, the EMA and the fraction of clipped steps."""
    model = tiny_lm(seed)
    matrices = [p for name, p in model.named_parameters()
                if p.ndim == 2 and 'emb' not in name]
    others = [p for name, p in model.named_parameters()
              if p.ndim != 2 or 'emb' in name]
    adamw = torch.optim.AdamW([{'params': matrices, 'weight_decay': 0.1},
                               {'params': others, 'weight_decay': 0.0}],
                              lr=1.0, betas=(0.9, 0.95))  # Times schedule
    scheduler = torch.optim.lr_scheduler.LambdaLR(adamw, schedule)
    ema = torch.optim.swa_utils.AveragedModel(
        model, multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(alpha))
    adamw.register_step_post_hook(lambda *_: scheduler.step())
    adamw.register_step_post_hook(lambda *_: ema.update_parameters(model))
    optimizer = Clipped(adamw, model.parameters(), max_norm)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    clip_rate = (torch.stack(optimizer.norms) > max_norm).float().mean()
    return losses, model, ema, float(clip_rate)

300-Step Proxy Calibration of Peak LR and Noise Scale

10%-Horizon Calibration

  • Before launching the 3{,}000-step run, we execute three 300-step trial runs (900 steps total, <30\% of one full run) across \eta \in \{10^{-3}, 3{\times}10^{-3}, 10^{-2}\}:
    • \eta = 10^{-3}: Slow (\approx 1.88 nats, 2\text{--}3\% clipped).
    • \eta = 3 \times 10^{-3}: Optimal (\approx 1.75 nats, 3\% of steps clipped, a healthy guard).
    • \eta = 10^{-2}: Stalls at \approx 2.5 nats (6\% clipped).
  • Noise-scale check: b_{\text{noise}} grows from \approx 2 sequences at step 0 to \sim 150 sequences at step 300, confirming that b = 256 sits near the critical batch size knee.
noise scale at initialization: 2
lr 0.001: loss 1.881 after 300 steps, 3% of the steps clipped
lr 0.003: loss 1.740 after 300 steps, 3% of the steps clipped
lr 0.01: loss 2.498 after 300 steps, 6% of the steps clipped
peak rate 0.003; noise scale after its 300 steps: 153

Full 3,000-Step Verification Across Seeds

Configured Recipe vs. Constant-Rate Baseline

  • Running the full 3{,}000-step warmup + cosine schedule at the calibrated peak rate \eta_0 = 3 \times 10^{-3} across two independent seeds:
    • Configured recipe: Reaches \approx 1.25 validation nats, beating the constant-rate baseline (\approx 1.30) by 0.05\text{--}0.06 nats (several times the <0.01-nat inter-seed spread).
    • Guard verification: Clipping fires on only 0.5\text{--}0.6\% of steps (\sim 15\text{--}18 steps out of 3{,}000).
    • Post-decay EMA: Matches the live weights to within 0.001 nats because cosine decay already reduced \eta_T \to 0.
validation loss  configured  its EMA  clipped  baseline    gap
seed 1                1.245    1.245     0.5%     1.303  0.058
seed 2                1.248    1.249     0.5%     1.300  0.052
spread between the seeds: configured 0.004, baseline 0.003

Concept Check: Clipping, Spike Recovery, and Weight EMA

Check Your Understanding

Diagnose and solve each practical training scenario:

  1. Diagnosing a stalled AdamW run: On the 3.3\text{M}-parameter TinyLM at \eta = 10^{-2} with clipping at \theta = 1.0, the loss stalls near 2.5 nats and clipping fires on 6\% of steps, twice as often as at the smaller rates. A colleague proposes lowering the clipping threshold to \theta = 0.2 to shorten the steps. Will that fix the stall?
  2. AdamW second-moment recovery time: Suppose an unclipped gradient spike of 100\times normal magnitude hits AdamW and multiplies v_t by 1 + (1-\beta_2)10^4. How many steps does it take for that excess contribution in v_t to decay by e^{-3} \approx 5\% under \beta_2 = 0.999 versus \beta_2 = 0.95?
  3. When does Weight EMA add zero gain? In our final 3{,}000-step verification table, why did the configured run’s live weights and its weight EMA achieve the same validation loss to within 0.001 nats?

Concept Check: Clipping, Spike Recovery, and Weight EMA (answers)

Check Your Understanding

Answers:

  1. No. Because AdamW divides \hat{\mathbf{m}}_t by \sqrt{\hat{\mathbf{v}}_t}, rescaling \mathbf{g}_t by a tighter global clipping threshold \theta = 0.2 rescales both numerator and denominator and leaves the steady-state coordinate step length \approx \eta unchanged. You must lower the learning rate \eta (e.g., to 3 \times 10^{-3}).
  2. Decay by e^{-3} takes 3\,\tau_2 = \frac{3}{1 - \beta_2} steps: 3{,}000 steps at \beta_2 = 0.999 versus only 60 steps at \beta_2 = 0.95 (50\times faster recovery).
  3. Because the configured run ended with cosine decay to \eta_T = 0, the noise ball had already shrunk to zero during the final steps; weight EMA shines when evaluating uncooled constant-rate or WSD-plateau checkpoints.

Summary: Practical Optimization Diagnostics and Recipes

Key Takeaways

Operational Pillar Mathematical Rule / Mechanism Healthy Telemetry Target Production Role
Global-Norm Clipping \mathbf{g} \leftarrow \min\!\left(1, \frac{\theta}{\|\mathbf{g}\|_2}\right)\mathbf{g} (\theta = 1.0) Fires on <2\%\text{--}5\% of steps (guard); if >20\%, lower \eta Caps early SGD steps; protects AdamW’s \mathbf{v}_t from spikes
\beta_2 = 0.95 & Rewind \tau_2 = \frac{1}{1-\beta_2} = 20 steps (vs. 1{,}000 at 0.999) Rewind \sim 100 steps & skip 200\text{--}500 batches on spike Prevents a single spike from paralyzing \sqrt{\hat{\mathbf{v}}_t} for 2{,}300 steps
Weight Averaging (EMA) \bar{\mathbf{x}}_t = \alpha\bar{\mathbf{x}}_{t-1} + (1-\alpha)\mathbf{x}_t (\alpha \in [0.995, 0.9999]) Window \frac{1}{1-\alpha} > \frac{1}{\eta\lambda_{\text{curv}}}; start after early descent Matches cosine-decayed accuracy on constant-rate trajectories
Short-Run Calibration Sweep \eta_0 over 10\% horizon (300 of 3{,}000 steps) Pick \eta_0 3\times below stall threshold; check b_{\text{noise}} Calibrates peak LR for <30\% of a single full training run
Modern Default Recipe AdamW (0.9, 0.95), matrix-only \lambda = 0.1, clip 1.0 1\text{--}5\% linear warmup + cosine or WSD decay to \le 0.1\eta_0 Reliable baseline across Transformers and modern deep networks