9.10  Practice

In our small experiments so far, training took a few seconds per run, allowing us to sweep grids of learning rates and repeat runs whenever an update diverged. Production training runs are different: when a single training run takes days or weeks, most settings must be fixed in advance, a single unguarded gradient spike can corrupt hours of progress, and the final checkpoint must not depend on the luck of the last minibatch draw.

Even at extreme scale (such as the \(540\)-billion-parameter PaLM model trained across \(6{,}144\) TPU chips, which experienced roughly \(20\) sudden loss spikes despite active gradient clipping (Chowdhery et al. 2022)), reliable training rests on three operational pillars:

  1. Guards against transient instabilities: Global-norm gradient clipping (Section 8.4.2) caps anomalous steps under SGD and protects AdamW’s second-moment accumulator \(\mathbf{v}_t\) from transient gradient spikes, paired with checkpoint-and-rewind recovery.
  2. Iterate smoothing: Maintaining an exponential moving average (EMA) of model weights eliminates high-frequency noise-ball fluctuations without requiring a full learning-rate decay to zero.
  3. Systematic calibration from short proxy runs: Selecting the batch size from device throughput and \(b_{\text{noise}}\) (Section 9.8), adopting battle-tested optimizer defaults, and calibrating the peak learning rate on a short run (\(10\%\) of the horizon) before executing the full warmup-and-decay schedule (Section 9.7).

In this section, we examine each of these three pillars and assemble them into a complete end-to-end configuration for an untuned \(3.3\)-million-parameter, \(4\)-block TinyLM.

import random

9.10.1 Gradient Clipping and Spike Recovery

As introduced for recurrent networks in Section 8.4.2, global-norm gradient clipping treats the concatenated gradient across all parameters as a single vector \(\mathbf{g}\) and rescales it whenever its Euclidean norm \(\|\mathbf{g}\|_2\) exceeds a threshold \(\theta\):

\[ \mathbf{g} \leftarrow \min\left(1,\; \frac{\theta}{\|\mathbf{g}\|_2}\right) \mathbf{g}. \tag{9.10.1}\]

Because the scaling factor \(\theta / \|\mathbf{g}\|_2\) is global, clipping preserves the relative direction across all layers while capping the Euclidean norm of the gradient entering the optimizer at \(\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()
def record_norms(num_steps):
    """Pass the gradients through unchanged, storing each step's norm."""
    def init(params):
        return dict(norms=jnp.zeros(num_steps), step=jnp.zeros((), jnp.int32))

    def update(grads, state, params=None):
        norm = optax.global_norm(grads)
        norms = state['norms'].at[state['step']].set(norm)
        return grads, dict(norms=norms, step=state['step'] + 1)

    return optax.GradientTransformation(init, update)

def clipped(tx, num_steps, max_norm=1.0):
    """Clip the global gradient norm before an optimizer's update, recording
    the norm before clipping on each of the first num_steps steps."""
    return optax.chain(record_norms(num_steps),
                       optax.clip_by_global_norm(max_norm), tx)

9.10.1.1 Clipping as a Guard vs. a Constant Brake

In Section 9.5, SGD with momentum \(0.9\) on TinyLM diverged to inf at \(\eta = 1.0\) within the first \(20\) steps. Is \(\eta = 1.0\) too large for the entire loss surface, or only during the initial transient steps where freshly initialized weights produce large gradients? We first load the WikiText103 stream (\(b = 64\), window length \(64\)):

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

Next, run(seed, lr, max_norm) trains TinyLM for \(2{,}000\) steps of SGD with momentum \(0.9\) clipped at max_norm, returning both the step losses and the pre-clip gradient norms:

new_seed = lambda: random.getrandbits(31)

def run(seed, lr, max_norm, num_steps=2000):
    """SGD with momentum 0.9 on TinyLM, clipped at max_norm (math.inf: not
    at all); return the losses and the gradient norms before clipping."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    model = d2l.TinyLM(len(data.vocab))
    optimizer = Clipped(torch.optim.SGD(model.parameters(), lr, momentum=0.9),
                        model.parameters(), max_norm)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    return losses, torch.stack(optimizer.norms).cpu().numpy()
new_seed = d2l.get_seed

def run(seed, lr, max_norm, num_steps=2000):
    """SGD with momentum 0.9 on TinyLM, clipped at max_norm (math.inf: not
    at all); return the losses and the gradient norms before clipping."""
    model = d2l.TinyLM(len(data.vocab), rngs=nnx.Rngs(seed))
    tx = clipped(optax.sgd(lr, momentum=0.9), num_steps, max_norm)
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    return losses, np.asarray(optimizer.opt_state[0]['norms'][...])

We now test \((\eta, \theta) \in \{(1.0, \infty), (1.0, 1.0), (0.3, \infty), (3.0, 1.0)\}\) across two seeds, logging how many steps trigger clipping (\(\|\mathbf{g}_t\|_2 > \theta\)), the last step on which clipping fires, and the median gradient norm:

settings = [(1.0, math.inf), (1.0, 1.0), (0.3, math.inf), (3.0, 1.0)]
seeds, runs = [new_seed() for _ in range(2)], {}
print(f'{"lr":>4}{"clip at":>9}{"final loss":>12}{"steps clipped":>15}'
      f'{"last":>6}{"median norm":>13}{"largest / median":>18}')
for seed in seeds:
    for lr, max_norm in settings:
        losses, norms = runs[seed, lr, max_norm] = run(seed, lr, max_norm)
        line = f'{lr:4g}{max_norm:9g}{d2l.final_loss(losses):12.3f}'
        if max_norm < math.inf:
            fired = np.nonzero(norms > max_norm)[0]  # Steps clipping changed
            median = np.median(norms)
            line += (f'{len(fired):15d}{fired.max(initial=0):6d}{median:13.2f}'
                     f'{norms[100:].max() / median:18.1f}')  # After step 100
        print(line)
  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
settings = [(1.0, math.inf), (1.0, 1.0), (0.3, math.inf), (3.0, 1.0)]
seeds, runs = [new_seed() for _ in range(2)], {}
print(f'{"lr":>4}{"clip at":>9}{"final loss":>12}{"steps clipped":>15}'
      f'{"last":>6}{"median norm":>13}{"largest / median":>18}')
for seed in seeds:
    for lr, max_norm in settings:
        losses, norms = runs[seed, lr, max_norm] = run(seed, lr, max_norm)
        line = f'{lr:4g}{max_norm:9g}{d2l.final_loss(losses):12.3f}'
        if max_norm < math.inf:
            fired = np.nonzero(norms > max_norm)[0]  # Steps clipping changed
            median = np.median(norms)
            line += (f'{len(fired):15d}{fired.max(initial=0):6d}{median:13.2f}'
                     f'{norms[100:].max() / median:18.1f}')  # After step 100
        print(line)
  lr  clip at  final loss  steps clipped  last  median norm  largest / median
   1      inf         inf
   1        1       1.613             14    13         0.26               1.7
 0.3      inf       1.669
   3        1     197.921           2000  1999        43.59               1.7
   1      inf         inf
   1        1       1.616             15    23         0.26               1.5
 0.3      inf       1.679
   3        1     103.020           2000  1999        35.99              13.0

At \(\eta = 1.0\), clipping at \(\theta = 1.0\) fires on only the first few dozen steps (all before step \(50\)) and never fires again over the remaining \(1{,}950\) steps (where the median gradient norm is \(\sim 0.25\)), rescuing the run from inf down to \(\sim 1.61\text{--}1.64\) nats. Here clipping acts as a guard: it intervenes on \(<2\%\) of steps to prevent early transient blow-up (and handle heavy-tailed gradient noise (Zhang et al. 2020)). By contrast, at \(\eta = 3.0\), clipping fires on every step for as long as the gradient norm stays finite, and the run still fails to train (its loss stalls at \(100\text{--}200\) nats or overflows to inf): when clipping is permanently active as a brake, the learning rate \(\eta\) is simply too large (Godbole et al. 2023). In practice, set \(\theta\) roughly \(3\text{--}5\times\) above the steady-state median gradient norm (typically \(\theta = 1.0\)) and monitor the clipping fraction.

9.10.1.2 Clipping Under AdamW and Operational Spike Recovery

Under AdamW (Section 9.5), a single anomalous gradient \(g \gg \sqrt{v_{t-1}}\) already produces a bounded step of at most \(\eta(1-\beta_1)/\sqrt{1-\beta_2}\) (\(\approx 3.2\,\eta\) at \(\beta_2 = 0.999\), or \(0.45\,\eta\) at \(\beta_2 = 0.95\)). Instead of bounding the immediate step, clipping under AdamW protects the second-moment state \(\mathbf{v}_t\): an unclipped \(100\times\) gradient spike injects \((1-\beta_2) \times 10^4\) times the normal squared gradient into \(v_t\), inflating the denominator \(\sqrt{\hat{v}_t}\) and paralyzing learning for the next \(\sim 1/(1-\beta_2)\) steps (\(1{,}000\) steps at \(\beta_2 = 0.999\); \(20\) steps at \(\beta_2 = 0.95\)).

When a sudden loss spike occurs despite gradient clipping (and auxiliary logit regularizers such as PaLM’s \(z\)-loss \(10^{-4}\log^2(\sum_j e^{o_j})\); Exercise 2), the standard operational remedy (Chowdhery et al. 2022; Zhang et al. 2022) is to rewind to a checkpoint saved \(\sim 100\) steps prior to the spike and skip the \(200\text{--}500\) minibatches surrounding the trigger, which requires checkpointing the model weights, optimizer moments \((\mathbf{m}_t, \mathbf{v}_t)\), scheduler step counter, and data-stream cursor at regular intervals.

9.10.2 Weight Averaging (EMA)

At a constant or non-zero learning rate, stochastic iterates fluctuate continuously around the optimum inside the noise ball (Section 9.2), where a mode of curvature \(\lambda_{\text{curv}}\) has autocorrelation time \(\sim 1/(\eta\lambda_{\text{curv}})\) steps. Maintaining an exponential moving average (EMA) \(\bar{\mathbf{x}}_t\) of the live parameters \(\mathbf{x}_t\) with decay coefficient \(\alpha \in [0.99, 0.9999]\) (Polyak and Juditsky 1992),

\[ \bar{\mathbf{x}}_t = \alpha\, \bar{\mathbf{x}}_{t-1} + (1 - \alpha)\, \mathbf{x}_t, \tag{9.10.2}\]

averages over a trailing window of \(1/(1-\alpha)\) steps to cancel noise-ball fluctuations at evaluation time without altering the live training trajectory.

We compare constant-rate SGD (\(\eta = 0.3\)) with and without weight EMA (\(\alpha = 0.999\), window \(1{,}000\) steps \(\approx 4.2\) epochs, started after epoch \(5\) to avoid initial lag) against cosine learning-rate decay over \(15\) epochs (\(3{,}525\) steps) on FashionCNN. First we load FashionMNIST (\(b = 256\)) and define the validation accuracy helper test_acc:

fashion = d2l.FashionMNIST(batch_size=256)
num_epochs, num_batches = 15, len(fashion.train_dataloader())
test_acc = lambda model: d2l.evaluate_accuracy(model, fashion.val_dataloader())
fashion = d2l.FashionMNIST(batch_size=256)
num_epochs, num_batches = 15, len(fashion.train_dataloader())
test_acc = lambda model: d2l.evaluate_accuracy(model, fashion.val_dataloader())

Next we define the warmup_cosine schedule helper and a weight EMA:

PyTorch’s torch.optim.swa_utils.AveragedModel keeps the EMA, so only the schedule needs defining here.

ema_of_weights is an optax transformation that keeps the EMA in the optimizer state, and averaged clones the model with those weights.

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
warmup_cosine = lambda peak, warmup, num_steps: (
    optax.warmup_cosine_decay_schedule(0.0, peak, warmup, num_steps))

def ema_of_weights(alpha=0.999, start=0):
    """Pass the updates through unchanged, keeping an EMA of the updated
    weights that averages from step start on (copies them before)."""
    def init(params):
        return dict(ema=params, step=jnp.zeros((), jnp.int32))

    def update(updates, state, params):
        new = optax.apply_updates(params, updates)
        rate = jnp.where(state['step'] < start, 1.0, 1 - alpha)
        ema = optax.incremental_update(new, state['ema'], rate)
        return updates, dict(ema=ema, step=state['step'] + 1)

    return optax.GradientTransformation(init, update)

def averaged(model, optimizer):
    """A copy of model with the EMA kept by the last transformation."""
    ema = nnx.clone(model)
    nnx.update(ema, optimizer.opt_state[-1]['ema'])
    return ema

The training loop train_fashion runs plain SGD under schedule(t) for num_epochs=15 epochs, recording held-out test accuracy at the end of every epoch for both the live weights and their EMA (started at epoch start=5):

def train_fashion(seed, schedule, alpha=0.999, start=5):
    """Plain SGD on FashionCNN at the rate schedule(t); the test accuracy
    after every epoch of the weights and of their EMA from epoch start on."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    model = d2l.FashionCNN().to(d2l.try_gpu())
    optimizer = torch.optim.SGD(model.parameters(), lr=1.0)  # Times schedule
    scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, schedule)
    optimizer.register_step_post_hook(lambda *_: scheduler.step())
    ema = torch.optim.swa_utils.AveragedModel(
        model, multi_avg_fn=torch.optim.swa_utils.get_ema_multi_avg_fn(alpha))
    live, avg = [], []
    for epoch in range(num_epochs):
        if epoch == start:  # Its first update copies the current weights
            optimizer.register_step_post_hook(
                lambda *_: ema.update_parameters(model))
        d2l.train_steps(model, fashion, optimizer, num_batches)
        live.append(test_acc(model))
        avg.append(test_acc(ema) if epoch >= start else math.nan)
    return live, avg
def train_fashion(seed, schedule, alpha=0.999, start=5):
    """Plain SGD on FashionCNN at the rate schedule(t); the test accuracy
    after every epoch of the weights and of their EMA from epoch start on."""
    model = d2l.FashionCNN(rngs=nnx.Rngs(seed))
    tx = optax.chain(optax.sgd(schedule),
                     ema_of_weights(alpha, start * num_batches))
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    live, avg = [], []
    for epoch in range(num_epochs):
        d2l.train_steps(model, fashion, optimizer, num_batches)
        live.append(test_acc(model))
        avg.append(test_acc(averaged(model, optimizer)) if epoch >= start
                   else math.nan)
    return live, avg

We run train_fashion across two seeds for both a constant learning rate (\(\eta = 0.3\)) and cosine decay (\(\eta: 0.3 \to 0\)), comparing the range of live accuracies over the last five epochs against the final EMA accuracy:

schedules = {'constant rate': lambda t: 0.3,
             'cosine decay': warmup_cosine(0.3, 0, num_epochs * num_batches)}
cnn_seeds, curves = [new_seed() for _ in range(2)], {}
print(f'{"test accuracy":<15}{"live, last five epochs":>24}{"live, final":>13}'
      f'{"EMA, final":>12}')
for seed in cnn_seeds:
    for name, schedule in schedules.items():
        live, avg = curves[seed, name] = train_fashion(seed, schedule)
        print(f'{name:<15}{min(live[-5:]):15.3f} to {max(live[-5:]):.3f}'
              f'{live[-1]:13.3f}{avg[-1]:12.3f}')
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
schedules = {'constant rate': lambda t: 0.3,
             'cosine decay': warmup_cosine(0.3, 0, num_epochs * num_batches)}
cnn_seeds, curves = [new_seed() for _ in range(2)], {}
print(f'{"test accuracy":<15}{"live, last five epochs":>24}{"live, final":>13}'
      f'{"EMA, final":>12}')
for seed in cnn_seeds:
    for name, schedule in schedules.items():
        live, avg = curves[seed, name] = train_fashion(seed, schedule)
        print(f'{name:<15}{min(live[-5:]):15.3f} to {max(live[-5:]):.3f}'
              f'{live[-1]:13.3f}{avg[-1]:12.3f}')
test accuracy    live, last five epochs  live, final  EMA, final
constant rate            0.890 to 0.906        0.890       0.913
cosine decay             0.910 to 0.913        0.912       0.911
constant rate            0.863 to 0.904        0.904       0.911
cosine decay             0.903 to 0.910        0.910       0.906

Plotting the epoch-by-epoch test accuracy trajectories for the first seed visualizes how the constant-rate EMA eliminates the noise-ball jitter of the live weights:

(live, avg), (decayed, _) = (curves[cnn_seeds[0], name] for name in schedules)
d2l.plot(list(range(1, num_epochs + 1)), [live, avg, decayed], 'epoch',
         'test accuracy', ylim=[0.85, 0.925], figsize=(5, 2.5),
         legend=['constant rate, live weights', 'constant rate, EMA',
                 'cosine decay, live weights'], legend_loc='outside')

(live, avg), (decayed, _) = (curves[cnn_seeds[0], name] for name in schedules)
d2l.plot(list(range(1, num_epochs + 1)), [live, avg, decayed], 'epoch',
         'test accuracy', ylim=[0.85, 0.925], figsize=(5, 2.5),
         legend=['constant rate, live weights', 'constant rate, EMA',
                 'cosine decay, live weights'], legend_loc='outside')

At a constant learning rate, the live weights jitter over a test-accuracy band of a few percentage points across the last five epochs, and occasionally far more when a single epoch goes badly, whereas their EMA rises smoothly along the top of the band to about \(91\%\)—matching the final accuracy of the cosine-decayed run without ever lowering the learning rate. Thus, during the constant plateau of a WSD schedule, weight EMA is a cheap approximation to a cooldown branch (Section 9.7.4.1): it costs no extra steps. It is not a full replacement. On language models, averaging along the plateau recovers part of the cooldown gain, not all of it (Hägele et al. 2024).

9.10.3 A Worked End-to-End Configuration

We now synthesize the entire chapter to configure a \(3{,}000\)-step training run for an untuned \(4\)-block, width-\(256\), \(4\)-head TinyLM (\(3.3\) million parameters). Table 9.10.1 summarizes the published optimizer configurations of four frontier pretraining runs, and Table 9.10.2 provides a diagnostic lookup table mapping training log symptoms to their remedies.

Table 9.10.1: Published optimizer configurations for four large language model pretraining runs.
Model Optimizer \(\beta_1, \beta_2\) Peak LR & schedule Warmup Clip \(\theta\) Weight decay \(\lambda\) Batch size
Llama 3 405B (Grattafiori et al. 2024) AdamW — \(8{\times}10^{-5}\), cosine to \(8{\times}10^{-7}\) 8k steps — — ramp 4M \(\to\) 16M tokens
DeepSeek-V3 (DeepSeek-AI et al. 2024) AdamW 0.9, 0.95 \(2.2{\times}10^{-4}\), WSD cosine to \(2.2{\times}10^{-5}\) 2k steps 1.0 0.1 ramp 3,072 \(\to\) 15,360 seqs
OLMo 2 7B (Team OLMo et al. 2025) AdamW 0.9, 0.95 \(3{\times}10^{-4}\), cosine to \(3{\times}10^{-5}\) 2k steps 1.0 0.1 (no emb) 1,024 seqs
Kimi K2 (Kimi Team 2025) MuonClip — \(2{\times}10^{-4}\), WSD cosine to \(2{\times}10^{-5}\) 500 steps — 0.1 67M tokens
Table 9.10.2: Diagnosing optimization failures from logged metrics (loss, pre-clip gradient norm, clipping fraction, and relative step size \(\|\Delta\mathbf{W}\|_{\text{RMS}}/\|\mathbf{W}\|_{\text{RMS}}\)).
Logged symptom Diagnosis Primary remedy
Loss diverges in first few steps with exploding gradient norms Step size exceeds initial local sharpness \(2/L\) Add linear warmup or global-norm clipping
Loss stalls high under Adam; initial relative weight updates \(>10\%\) Cold-start step corrupts initialization Add linear warmup (\(1\%\text{--}5\%\) of steps)
Loss stalls high under Adam even behind warmup Peak learning rate \(\eta_0\) too large Lower \(\eta_0\) by \(2\text{--}3\times\)
Clipping fires on \(>20\%\text{--}50\%\) of steps throughout training Clipping acting as a constant brake Lower \(\eta_0\) before adjusting \(\theta\)
Loss plateaus early with high step-to-step variance Stationary noise ball at current \(\eta / b\) Decay \(\eta_t \to 0\), evaluate weight EMA, or increase \(b\)
Loss descends smoothly at constant slope until final step Under-budgeted cumulative travel \(B_T\) Increase peak \(\eta_0\) or total steps \(T\)

Following Table 9.10.1, we configure our \(3.3\text{M}\)-parameter TinyLM with:

  1. Batch size: \(b = 256\) sequences (where hardware throughput saturates and comparable to the post-warmup gradient-noise scale \(b_{\text{noise}} \sim 100\text{--}200\)).
  2. Optimizer & guards: AdamW with \((\beta_1, \beta_2) = (0.9, 0.95)\), decoupled weight decay \(\lambda = 0.1\) applied exclusively to 2D hidden matrices (Section 9.5.3.3), global-norm gradient clipping at \(\theta = 1.0\), and a short-window weight EMA (\(\alpha = 0.995\)).
  3. Peak learning rate calibration: Three \(300\)-step (\(10\%\)-horizon) trial runs across \(\eta \in \{10^{-3}, 3 \times 10^{-3}, 10^{-2}\}\) identify \(\eta_0 = 3 \times 10^{-3}\) as optimal (with \(<5\%\) of steps clipped, confirming that \(\theta = 1.0\) acts purely as a guard).
  4. Schedule: \(60\)-step linear warmup (\(2\%\) of \(T = 3{,}000\)) followed by cosine decay to zero, which lowers validation loss by \(0.05\text{--}0.06\) nats below the constant-rate baseline (\(<0.01\)-nat seed spread).

We first define tiny_lm(seed) to instantiate the \(4\)-block, width-\(256\), \(4\)-head TinyLM and sample_lm(b) to draw random training windows for noise-scale estimation:

def tiny_lm(seed):
    """A TinyLM of four blocks of width 256 on the GPU."""
    torch.manual_seed(seed)  # The initialization and the minibatch order
    return d2l.TinyLM(len(data.vocab), d_model=256, num_heads=4,
                      num_blks=4).to(d2l.try_gpu())

def sample_lm(b):  # b windows at random offsets in the training text
    starts = torch.randint(len(data.train) - data.num_steps, (b,))
    X, Y = data.windows(data.train, starts.numpy())
    return X.to(d2l.try_gpu()), Y.to(d2l.try_gpu())
def tiny_lm(seed):
    """A TinyLM of four blocks of width 256."""
    return d2l.TinyLM(len(data.vocab), d_model=256, num_heads=4, num_blks=4,
                      rngs=nnx.Rngs(seed))

rng = np.random.default_rng(d2l.get_seed())

def sample_lm(b):  # b windows at random offsets in the training text, on the GPU
    X, Y = data.windows(data.train,
                        rng.integers(len(data.train) - data.num_steps, size=b))
    return jnp.asarray(X), jnp.asarray(Y)

The harness train(seed, schedule, num_steps) configures AdamW with \((\beta_1, \beta_2) = (0.9, 0.95)\) and weight decay \(0.1\) restricted to 2D non-embedding matrices, wraps it in global-norm clipping (max_norm=1.0) and weight EMA (alpha=0.995), and returns the losses, live model, EMA model, and clipping rate:

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)
def decay_mask(params):  # True for the matrices, False for the rest
    return jax.tree_util.tree_map_with_path(
        lambda path, p: p.ndim == 2 and 'emb' not in str(path), params)

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)
    adamw = optax.adamw(schedule, b1=0.9, b2=0.95, weight_decay=0.1,
                        mask=decay_mask)
    tx = optax.chain(clipped(adamw, num_steps, max_norm), ema_of_weights(alpha))
    optimizer = nnx.Optimizer(model, tx, wrt=nnx.Param)
    losses = d2l.train_steps(model, data, optimizer, num_steps)
    norms = optimizer.opt_state[0][0]['norms'][...]  # Recorded by clipped
    clip_rate = (norms > max_norm).mean()
    return losses, model, averaged(model, optimizer), float(clip_rate)

At \(b = 256\), we measure d2l.noise_scale at initialization, run three \(300\)-step (\(10\%\)-horizon) proxy trials across \(\eta \in \{10^{-3}, 3 \times 10^{-3}, 10^{-2}\}\) to select the peak learning rate peak, and re-estimate noise_scale after \(300\) steps:

data.batch_size = 256  # Where the throughput levels off
seed, short = new_seed(), {}
print('noise scale at initialization: '
      f'{d2l.noise_scale(tiny_lm(seed), sample_lm, b_small=8, b_big=256):.0f}')
for lr in [1e-3, 3e-3, 1e-2]:
    losses, model, _, clip_rate = train(seed, lambda t: lr, num_steps=300)
    short[lr] = (d2l.final_loss(losses), model)
    print(f'lr {lr:g}: loss {short[lr][0]:.3f} after 300 steps, '
          f'{clip_rate:.0%} of the steps clipped')
peak = min(short, key=lambda lr: short[lr][0])
print(f'peak rate {peak:g}; noise scale after its 300 steps: '
      f'{d2l.noise_scale(short[peak][1], sample_lm, b_small=8, b_big=256):.0f}')
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
data.batch_size = 256  # Where the throughput levels off
seed, short = new_seed(), {}
print('noise scale at initialization: '
      f'{d2l.noise_scale(tiny_lm(seed), sample_lm, b_small=8, b_big=256):.0f}')
for lr in [1e-3, 3e-3, 1e-2]:
    losses, model, _, clip_rate = train(seed, lambda t: lr, num_steps=300)
    short[lr] = (d2l.final_loss(losses), model)
    print(f'lr {lr:g}: loss {short[lr][0]:.3f} after 300 steps, '
          f'{clip_rate:.0%} of the steps clipped')
peak = min(short, key=lambda lr: short[lr][0])
print(f'peak rate {peak:g}; noise scale after its 300 steps: '
      f'{d2l.noise_scale(short[peak][1], sample_lm, b_small=8, b_big=256):.0f}')
noise scale at initialization: 2
lr 0.001: loss 1.880 after 300 steps, 2% of the steps clipped
lr 0.003: loss 1.769 after 300 steps, 3% of the steps clipped
lr 0.01: loss 2.482 after 300 steps, 6% of the steps clipped
peak rate 0.003; noise scale after its 300 steps: 173

Finally, we execute the full \(3{,}000\)-step run across two seeds comparing our configured schedule (warmup_cosine(peak, 60, 3000)) and its weight EMA against a constant-rate baseline at peak:

num_steps = 3000
val_loss = lambda model: math.log(d2l.lm_perplexity(model, data.val_dataloader()))
print(f'{"validation loss":<16}{"configured":>11}{"its EMA":>9}'
      f'{"clipped":>9}{"baseline":>10}{"gap":>7}')
results = []
for seed in [new_seed() for _ in range(2)]:
    _, model, ema, clip_rate = train(
        seed, warmup_cosine(peak, num_steps // 50, num_steps), num_steps)
    _, baseline, _, _ = train(seed, lambda t: peak, num_steps)
    results.append((val_loss(model), val_loss(baseline)))
    print(f'{"seed " + str(len(results)):<16}{results[-1][0]:11.3f}'
          f'{val_loss(ema):9.3f}{clip_rate:9.1%}{results[-1][1]:10.3f}'
          f'{results[-1][1] - results[-1][0]:7.3f}')
(c1, b1), (c2, b2) = results
print(f'spread between the seeds: configured {abs(c1 - c2):.3f}, '
      f'baseline {abs(b1 - b2):.3f}')
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
num_steps = 3000
val_loss = lambda model: math.log(d2l.lm_perplexity(model, data.val_dataloader()))
print(f'{"validation loss":<16}{"configured":>11}{"its EMA":>9}'
      f'{"clipped":>9}{"baseline":>10}{"gap":>7}')
results = []
for seed in [new_seed() for _ in range(2)]:
    _, model, ema, clip_rate = train(
        seed, warmup_cosine(peak, num_steps // 50, num_steps), num_steps)
    _, baseline, _, _ = train(seed, lambda t: peak, num_steps)
    results.append((val_loss(model), val_loss(baseline)))
    print(f'{"seed " + str(len(results)):<16}{results[-1][0]:11.3f}'
          f'{val_loss(ema):9.3f}{clip_rate:9.1%}{results[-1][1]:10.3f}'
          f'{results[-1][1] - results[-1][0]:7.3f}')
(c1, b1), (c2, b2) = results
print(f'spread between the seeds: configured {abs(c1 - c2):.3f}, '
      f'baseline {abs(b1 - b2):.3f}')
validation loss  configured  its EMA  clipped  baseline    gap
seed 1                1.247    1.247     0.6%     1.300  0.053
seed 2                1.249    1.249     0.6%     1.305  0.056
spread between the seeds: configured 0.002, baseline 0.006

9.10.4 Summary

Global-norm gradient clipping (\(\mathbf{g} \leftarrow \min(1, \theta/\|\mathbf{g}\|_2)\mathbf{g}\)) acts as a guard when it fires on a small fraction (\(<5\%\)) of early or anomalous steps, preventing initial blow-up under SGD and protecting AdamW’s second-moment buffer \(\mathbf{v}_t\) from gradient spikes, whereas continuous firing signals that \(\eta\) is too large and clipping has become a brake. Exponential moving averaging (EMA) of model weights (\(\bar{\mathbf{x}}_t = \alpha\bar{\mathbf{x}}_{t-1} + (1-\alpha)\mathbf{x}_t\)) smooths out stationary noise-ball fluctuations without modifying the live trajectory, matching the accuracy of a full cosine decay on constant-rate runs. Reliable large-scale training combines hardware-saturated batch sizes positioned near \(b_{\text{noise}}\), AdamW with \((\beta_1, \beta_2) = (0.9, 0.95)\) and decoupled weight decay \(\lambda = 0.1\) restricted to 2D weight matrices, global-norm clipping at \(\theta = 1.0\), short-horizon peak-LR calibration, and linear warmup followed by cosine or WSD cooldown.

9.10.5 Exercises

  1. [code] Clipping regimes: guard vs. brake. Sweep \(\theta \in \{0.01, 0.1, 0.5, 1.0, 4.0, \infty\}\) at \(\eta = 1.0\) with run on TinyLM, recording the final loss and clipping fraction, and compare clipping against replacing clipping with a \(20\)-step or \(100\)-step linear warmup.

  2. Softmax logit drift and PaLM’s \(z\)-loss. For output logits \(\mathbf{o} \in \mathbb{R}^V\) and partition function \(Z = \sum_{j=1}^V e^{o_j}\), show that the cross-entropy gradient has zero sum (\(\mathbf{1}^\top \nabla_{\mathbf{o}}\ell_{\text{CE}} = 0\)) whereas adding the auxiliary penalty \(10^{-4}\log^2 Z\) (Chowdhery et al. 2022) introduces a restoring gradient \(2 \times 10^{-4}(\log Z)\,\mathbf{p}\) that pulls \(\log Z\) toward \(0\) without altering the uniform-shift invariance of \(\mathbf{p} = \operatorname{softmax}(\mathbf{o})\).

  3. [code] Weight EMA window and start time. Sweep the EMA decay \(\alpha \in \{0.9, 0.99, 0.999, 0.9999\}\) and start epoch start \(\in \{0, 5, 10\}\) on train_fashion at constant \(\eta = 0.3\), relating the accuracy trajectories to the effective window \(1/(1-\alpha)\) in epochs.

  4. [code] Ablating the worked configuration. ● On the \(4\)-block width-\(256\) TinyLM of train, run two-seed ablations testing: (a) WSD late linear decay vs. cosine decay, (b) removing warmup or removing gradient clipping, (c) shifting the peak rate to \(10^{-3}\) or \(10^{-2}\), and (d) evaluating the weight EMA of the constant-rate baseline at \(\alpha \in \{0.995, 0.999\}\).

Discussions