9.7 Schedules

Throughout the preceding sections, we held the learning rate η\eta constant across training—and twice observed why a fixed step size is suboptimal. Under minibatch SGD (Section 9.2), a constant learning rate traps the iterate in a stationary noise ball of variance O(ησ2/λ)O(\eta\sigma^2 / \lambda): halving η\eta halves the noise floor but doubles the transient steps required to reach it. Under normalized optimizers such as AdamW (Section 9.5) and Muon (Section 9.6), the update magnitude remains O(η)O(\eta) even as the gradient approaches zero, preventing the iterate from settling at a minimum until η\eta is reduced.

Modern training recipes resolve this trade-off with a learning-rate schedule ηt\eta_t that varies across steps t=0,…,T−1t = 0, \ldots, T-1. Almost every contemporary schedule combines two phases: an initial warmup ramp from zero to a peak learning rate η0\eta_0, followed by a decay phase toward zero. In this section, we first analyze learning-rate decay on the noisy quadratic valley in terms of two quantities—the cumulative learning-rate budget BT=∑t=0T−1ηtB_T = \sum_{t=0}^{T-1}\eta_t and the terminal learning rate ηT\eta_T. We then compare constant, cosine, and warmup–stable–decay (WSD) schedules on TinyLM, demonstrate why linear warmup prevents early step instability at high peak learning rates, and show how branching short decay phases off a constant-rate plateau produces competitive checkpoints across multiple training horizons.

import copy
import random

9.7.1 Learning-Rate Decay on the Noisy Valley#

Consider a single coordinate of the quadratic valley with curvature λ>0\lambda > 0 and zero-mean gradient noise ξt\xi_t of variance σ2\sigma^2 under time-varying step sizes ηt\eta_t:

xt+1=(1−ηtλ) xt−ηt ξt.(9.7.1)x_{t+1} = (1 - \eta_t \lambda)\, x_t - \eta_t\, \xi_t. \tag{9.7.1}

Over tt steps, the deterministic mean contracts by ∏s<t(1−ηsλ)≈e−λBt\prod_{s \lt t}(1 - \eta_s\lambda) \approx e^{-\lambda B_t}, where

Bt=∑s=0t−1ηs(9.7.2)B_t = \sum_{s=0}^{t-1} \eta_s \tag{9.7.2}

is the cumulative learning-rate budget (the area under the learning-rate curve up to step tt). Provided that ηt\eta_t changes slowly over the local relaxation window 1/(ηtλ)1/(\eta_t\lambda), the variance tracks the instantaneous noise ball ηtσ2/(2λ)\eta_t\sigma^2 / (2\lambda), yielding the mean-squared error decomposition

E[xt2]≈e−2λBt x02+ηt σ22λ.(9.7.3)\mathbb{E}\big[x_t^2\big] \approx e^{-2\lambda B_t}\, x_0^2 + \frac{\eta_t\, \sigma^2}{2\lambda}. \tag{9.7.3}

Equation (9.7.3) highlights the two requirements on any finite-horizon schedule over TT steps:

  1. Sufficient cumulative budget BTB_T: The total budget BT=∑t=0T−1ηtB_T = \sum_{t=0}^{T-1}\eta_t must be large enough that the initial bias e−2λmin⁡BTx02e^{-2\lambda_{\min} B_T} x_0^2 vanishes along the flattest direction.
  2. Small terminal learning rate ηT\eta_T with sufficient remaining budget: The terminal rate ηT\eta_T must decay toward zero slowly enough that noise injected at intermediate steps ss is contracted by the remaining budget Rs=∑u=sT−1ηu≳1/λmin⁡R_s = \sum_{u=s}^{T-1}\eta_u \gtrsim 1/\lambda_{\min}.

Three classical parametric schedule families are piecewise-constant (step) decay, exponential decay, and polynomial decay:

ηt=ηifor ti≤t<ti+1(piecewise constant),ηt=η0 γt(exponential),ηt=η0 (1+t/τ)−α(polynomial),(9.7.4)\begin{aligned} \eta_t &= \eta_i \quad \textrm{for } t_i \leq t \lt t_{i+1} && \textrm{(piecewise constant)}, \\ \eta_t &= \eta_0\, \gamma^t && \textrm{(exponential)}, \\ \eta_t &= \eta_0\, (1 + t/\tau)^{-\alpha} && \textrm{(polynomial)}, \end{aligned} \tag{9.7.4}

with decay factor γ∈(0,1)\gamma \in (0, 1), timescale τ>0\tau > 0, and exponent α>0\alpha > 0. Simulating 1,0001{,}000 independent SGD runs on the valley f(x)=0.1x12+2x22f(\mathbf{x}) = 0.1 x_1^2 + 2 x_2^2 over T=3,000T = 3{,}000 steps illustrates how the cumulative budget BTB_T and terminal rate ηT\eta_T govern convergence—and why overly rapid exponential decay freezes noise:

def sgd_valley(schedule, num_steps=3000, num_runs=1000):
    """Mean squared distance to the minimum of SGD runs on the valley."""
    rng = np.random.default_rng()
    h = np.array(d2l.VALLEY_CURVATURES)  # Curvatures along x1 and x2
    x = np.tile([-5.0, -2.0], (num_runs, 1))
    dist = []
    for t in range(num_steps):
        x = x - schedule(t) * (h * x + rng.normal(size=x.shape))
        dist.append((x ** 2).sum(axis=1).mean())
    return dist

valley_schedules = {
    'constant': lambda t: 0.1,
    'exponential': lambda t: 0.4 * 0.98 ** t,
    'polynomial 1/2': lambda t: 0.4 / (1 + t / 25) ** 0.5,
    'polynomial 1': lambda t: 0.4 / (1 + t / 25)}
dists = {}
for name, schedule in valley_schedules.items():
    dists[name] = sgd_valley(schedule)
    budget = sum(schedule(t) for t in range(3000))
    print(f'{name:15s} budget {budget:6.1f}, final rate {schedule(2999):.2g}, '
          f'mean squared distance {dists[name][-1]:.3f}')
d2l.plot(np.arange(1, 3001), list(dists.values()), 'step',
         'mean squared distance', legend=list(dists), xscale='log',
         yscale='log')
constant        budget  300.0, final rate 0.1, mean squared distance 0.286
exponential     budget   20.0, final rate 1.9e-27, mean squared distance 0.118
polynomial 1/2  budget  200.2, final rate 0.036, mean squared distance 0.089
polynomial 1    budget   48.2, final rate 0.0033, mean squared distance 0.012

The constant rate (η=0.1\eta = 0.1) plateaus at its stationary noise ball (0.25+0.016≈0.270.25 + 0.016 \approx 0.27). Polynomial decay with α=1/2\alpha = 1/2 (ηT≈0.036\eta_T \approx 0.036) and α=1\alpha = 1 (ηT≈0.0033\eta_T \approx 0.0033) track (9.7.3) down to 0.09–0.100.09\text{--}0.10 and 0.011–0.0120.011\text{--}0.012, respectively. By contrast, exponential decay (γ=0.98\gamma = 0.98) has a terminal rate of 10−2710^{-27} yet freezes at a mean-squared error of 0.12–0.130.12\text{--}0.13: because its remaining budget after step ss is only Rs≈ηs/(1−γ)=50ηsR_s \approx \eta_s / (1-\gamma) = 50\eta_s, noise injected once ηs≲0.1\eta_s \lesssim 0.1 (Rsλ1≲1R_s \lambda_1 \lesssim 1) is never contracted away, leaving a frozen variance of (1−γ)σ2/(4λ12)=0.125(1-\gamma)\sigma^2 / (4\lambda_1^2) = 0.125 (Exercise 1).

9.7.2 Decay Shapes on a Language Model#

On a fixed step budget TT, two decay profiles dominate modern deep learning:

  • Cosine decay (Loshchilov and Hutter, 2016), which follows a half-cosine wave from peak rate η0\eta_0 at t=0t = 0 to terminal rate ηT\eta_T at t=Tt = T:
ηt=ηT+η0−ηT2(1+cos⁡πtT).(9.7.5)\eta_t = \eta_T + \frac{\eta_0 - \eta_T}{2}\left(1 + \cos\frac{\pi t}{T}\right). \tag{9.7.5}

When ηT=0\eta_T = 0, cosine decay has cumulative budget BT=12η0TB_T = \frac{1}{2}\eta_0 T (half the budget of a constant rate η0\eta_0).

  • Stable–then–decay (late linear decay), which holds the peak rate η0\eta_0 constant until step tdecayt_{\text{decay}} (here 0.8 T=1,6000.8\,T = 1{,}600) and then decays linearly to 00 over the final 20%20\% of training, preserving 90%90\% of the constant-rate budget (BT=0.9 η0TB_T = 0.9\,\eta_0 T) while still finishing at ηT=0\eta_T = 0.

To compare constant, cosine, and stable–then–decay schedules (η0=3×10−3,T=2,000\eta_0 = 3 \times 10^{-3}, T = 2{,}000) with AdamW (λ=0\lambda = 0) on TinyLM, we first load WikiText103 and define the model constructor tiny_lm(seed) and scheduled optimizer wrapper adamw(model, schedule):

data = d2l.WikiText103(batch_size=64, num_steps=64)
new_seed = lambda: random.getrandbits(31)

def tiny_lm(seed):
    torch.manual_seed(seed)  # The initialization and the minibatch order
    return d2l.TinyLM(len(data.vocab)).to(d2l.try_gpu())

class Scheduled:
    """An optimizer whose learning rate at step t is schedule(t)."""
    def __init__(self, optimizer, schedule, start=0):
        self.optimizer = optimizer  # Its rate is 1, which LambdaLR multiplies
        self.scheduler = torch.optim.lr_scheduler.LambdaLR(
            optimizer, schedule, last_epoch=start - 1)

    def step(self):
        self.optimizer.step()
        self.scheduler.step()

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

def adamw(model, schedule):
    """AdamW without weight decay at the learning rate schedule(t)."""
    return Scheduled(torch.optim.AdamW(model.parameters(), lr=1.0,
                                       weight_decay=0), schedule)

Next we define the schedule functions constant, cosine, and stable_decay (which holds η0\eta_0 until decay_start=1600 before decaying linearly to zero at T=2,000T = 2{,}000), along with the linear ramp wrapper warmup:

def constant(t, eta=3e-3):
    return eta

def cosine(t, eta=3e-3, T=2000):
    return eta * (1 + math.cos(math.pi * t / T)) / 2

def stable_decay(t, eta=3e-3, decay_start=1600, T=2000):
    """eta until decay_start, then a linear decay to zero at step T."""
    return eta * min(1, (T - t) / (T - decay_start))

def warmup(schedule, num_steps):
    """schedule, ramped up linearly over its first num_steps steps."""
    return lambda t: min(1, (t + 1) / num_steps) * schedule(t)

We now train TinyLM under each of the three decay profiles across two seeds, recording the cumulative budget BTB_T and the validation loss at step 1,5001{,}500 (before late decay starts) and step 2,0002{,}000:

schedules = {'constant': constant, 'cosine': cosine,
             'stable, then decay': stable_decay}
val_loss = lambda model: math.log(d2l.lm_perplexity(model,
                                                    data.val_dataloader()))
seeds, curves = [new_seed(), new_seed()], {}
print(f'{"schedule":<20}{"budget":>7}  validation loss at step 1500, 2000')
for name, schedule in schedules.items():
    at_1500, at_2000 = [], []
    for seed in seeds:
        model = tiny_lm(seed)
        optimizer = adamw(model, schedule)
        losses = d2l.train_steps(model, data, optimizer, 1500)
        at_1500.append(val_loss(model))
        losses += d2l.train_steps(model, data, optimizer, 500)
        at_2000.append(val_loss(model))
    curves[name] = d2l.smooth(losses)
    budget = sum(float(schedule(t)) for t in range(2000))
    print(f'{name:<20}{budget:7.2f}  ', ' '.join(f'{v:.3f}' for v in at_1500),
          '  ', ' '.join(f'{v:.3f}' for v in at_2000))
d2l.plot(list(range(25, 2001, 25)), list(curves.values()), 'step',
         'training loss', legend=list(curves), xlim=[500, 2000],
         ylim=[1.45, 1.95])
schedule             budget  validation loss at step 1500, 2000
constant               6.00   1.609 1.609    1.568 1.564
cosine                 3.00   1.584 1.578    1.558 1.554
stable, then decay     5.40   1.609 1.609    1.507 1.507

At step 1,5001{,}500, cosine decay leads because its learning rate has already fallen to 15%15\% of the peak, damping high-frequency oscillation. However, between steps 1,6001{,}600 and 2,0002{,}000, when stable_decay linearly reduces ηt→0\eta_t \to 0, its loss drops sharply by ∼0.10\sim 0.10 nats—finishing 0.05–0.060.05\text{--}0.06 nats below the constant schedule and ∼0.05\sim 0.05 nats ahead of cosine decay, which had only half the cumulative travel budget (BT=3.0B_T = 3.0 vs. 5.45.4). Notice that comparing checkpoints before learning-rate decay completes can reverse the true end-of-training ranking (Wen et al., 2025).

9.7.3 Learning-Rate Warmup#

While decay settles the iterate at the end of training, learning-rate warmup stabilizes the opening steps by ramping ηt\eta_t linearly from 00 to η0\eta_0 over WW steps (typically 1%–5%1\%\text{--}5\% of TT).

Why is warmup needed? First, under Adam (Section 9.5), step 11 moves every coordinate by ±η0\pm\eta_0 based on a single minibatch before the momentum average mt\mathbf{m}_t and second-moment average vt\mathbf{v}_t have accumulated multi-batch statistics. On TinyLM, where initial linear weight matrices have RMS(W0)≈0.045\text{RMS}(\mathbf{W}_0) \approx 0.045, a cold start at η0=0.03\eta_0 = 0.03 alters every weight by ∼67%\sim 67\% of its initial magnitude on step 11, corrupting the initialization and causing the run to stall near 2.82.8 nats. Second, as shown in Section 9.1.4, gradually raising ηt\eta_t lowers the sharpness ceiling progressively (2/ηt2/\eta_t for gradient descent, about 38/ηt38/\eta_t on the preconditioned sharpness for Adam), guiding the network into a flat region that can tolerate the peak learning rate (Goyal et al., 2017; Kalra and Barkeshli, 2024).

Adding a 2020-step linear ramp (warmup(peak, 20), just 1%1\% of the 2,0002{,}000-step run) caps the initial relative weight change at about 10%10\% and rescues training at η0=0.03\eta_0 = 0.03, lowering the final validation loss by about a full nat. To measure the step-by-step weight change, linear_weights extracts the 2D non-embedding weight matrices of TinyLM:

def linear_weights(model):
    return [p.detach().clone() for name, p in model.named_parameters()
            if p.ndim == 2 and 'emb' not in name]

Using relative_change to compute ∥ΔW∥RMS/∥W∥RMS\|\Delta\mathbf{W}\|_{\text{RMS}} / \|\mathbf{W}\|_{\text{RMS}} at steps 1,5,20,1, 5, 20, and 100100, we compare a cold start at η0=0.03\eta_0 = 0.03 against a 2020-step linear warmup over 2,0002{,}000 steps:

def relative_change(old, new):
    """RMS change of a list of weight matrices relative to their RMS."""
    return math.sqrt(float(sum(((n - o) ** 2).sum() for o, n in zip(old, new))
                           / sum((o ** 2).sum() for o in old)))

peak = lambda t: constant(t, eta=3e-2)
seed = new_seed()
print('step size / weight size at steps 1, 5, 20, 100; final loss')
for name, schedule in [('cold start', peak),
                       ('20-step ramp', warmup(peak, 20))]:
    model = tiny_lm(seed)
    optimizer = adamw(model, schedule)
    losses, sizes = [], []
    for step in range(1, 101):
        before = linear_weights(model)
        losses += d2l.train_steps(model, data, optimizer, 1)
        if step in (1, 5, 20, 100):
            sizes.append(relative_change(before, linear_weights(model)))
    losses += d2l.train_steps(model, data, optimizer, 1900)
    print(f'{name:<14}', ' '.join(f'{s:.2f}' for s in sizes),
          f'  training {d2l.final_loss(losses):.3f},',
          f'validation {val_loss(model):.3f}')
step size / weight size at steps 1, 5, 20, 100; final loss
cold start     0.67 0.15 0.02 0.01   training 2.862, validation 2.865
20-step ramp   0.03 0.10 0.05 0.01   training 1.809, validation 1.769

9.7.4 Warmup–Stable–Decay (WSD) and Checkpoint Branching#

Cosine decay (9.7.5) requires fixing the total step horizon TT before step 11: intermediate checkpoints are still at elevated learning rates, and extending training beyond TT requires restarting or splicing schedules. Combining a short warmup with a constant peak-rate plateau and a short final decay yields the warmup–stable–decay (WSD) schedule (Hu et al., 2024; Hägele et al., 2024).

Geometrically, Wen et al. (2024) model the WSD trajectory via a river valley landscape (Figure 9.7.1): during the high-rate plateau, the iterate oscillates across the steep transverse walls while making rapid progress down the flat longitudinal river bed; the short final decay damps the transverse oscillations (which have large curvature λsteep\lambda_{\text{steep}} and therefore require only a small remaining budget R≳1/λsteepR \gtrsim 1/\lambda_{\text{steep}}) and drops the iterate directly onto the valley floor.

Figure 9.7.1:

The river-valley geometry of warmup–stable–decay (WSD): the high constant plateau makes rapid progress downstream while oscillating across steep transverse walls, and a short decay branch quickly settles onto the valley floor.

9.7.4.1 Branching Off the Plateau#

Because the plateau phase does not depend on the target horizon TT, we can maintain a single continuous plateau run and branch a short linear cooldown (250250 steps) from any checkpoint. First, branch(model, optimizer, schedule) clones both the model weights and AdamW's moment buffers (mt,vt)(\mathbf{m}_t, \mathbf{v}_t) to continue under a cooldown schedule:

def branch(model, optimizer, schedule):
    """Copies of model and optimizer that continue under schedule."""
    model, adam = copy.deepcopy((model, optimizer.optimizer))  # With moments
    return model, Scheduled(adam, schedule, optimizer.scheduler.last_epoch)

We now run a 2,0002{,}000-step constant-rate plateau on TinyLM, fork 250250-step linear decay branches at steps 500,1,000,500, 1{,}000, and 1,5001{,}500, and compare the step-1,000→1,2501{,}000 \to 1{,}250 branch against a dedicated 1,2501{,}250-step run planned from scratch:

seed = new_seed()  # The planned run below starts from the same weights
model = tiny_lm(seed)
optimizer = adamw(model, constant)
plateau, branched = {}, {}
for step in range(250, 2001, 250):
    d2l.train_steps(model, data, optimizer, 250)
    plateau[step] = val_loss(model)
    if step in (500, 1000, 1500):  # A 250-step decay on a copy
        decay = lambda t, s=step: stable_decay(t, decay_start=s, T=s + 250)
        twin, twin_optimizer = branch(model, optimizer, decay)
        d2l.train_steps(twin, data, twin_optimizer, 250)
        branched[step + 250] = val_loss(twin)
planned = tiny_lm(seed)  # Decays from step 1000 to 1250 by design
d2l.train_steps(planned, data, adamw(planned, lambda t: stable_decay(
    t, decay_start=1000, T=1250)), 1250)
print('step  plateau  branch')
for step, v in branched.items():
    print(f'{step:>4} {plateau[step]:8.3f} {v:7.3f}')
planned_loss = val_loss(planned)
print(f'planned run of 1250 steps: {planned_loss:.3f}')
d2l.plot([list(plateau), [1250]] + [[s - 250, s] for s in branched],
         [list(plateau.values()), [planned_loss]] +
         [[plateau[s - 250], v] for s, v in branched.items()],
         'step', 'validation loss', legend=['plateau', 'planned', 'branches'],
         fmts=('-', 'ko', 'r--', 'r--', 'r--'))
step  plateau  branch
 750    1.791   1.766
1250    1.655   1.604
1750    1.588   1.534
planned run of 1250 steps: 1.604

Every branched cooldown drops the validation loss sharply below the continuing plateau (0.05–0.060.05\text{--}0.06 nats at steps 1,2501{,}250 and 1,7501{,}750), and the branch at step 1,000→1,2501{,}000 \to 1{,}250 matches a dedicated 1,2501{,}250-step run planned from scratch—delivering finished models across three training horizons in 2,2502{,}250 total steps instead of 3,7503{,}750.

9.7.5 Summary#

A learning-rate schedule ηt\eta_t is governed by its cumulative learning-rate budget BT=∑t=0T−1ηtB_T = \sum_{t=0}^{T-1}\eta_t, which sets how far the iterate travels along flat directions, and its terminal learning rate ηT\eta_T, which determines the final noise floor provided the remaining budget Rs≳1/λR_s \gtrsim 1/\lambda decays slowly enough to damp earlier noise. On TinyLM, decaying the learning rate to zero at the end of training eliminates the O(η)O(\eta) step jitter of constant-rate AdamW and reduces validation loss by 0.05–0.060.05\text{--}0.06 nats. Linear warmup over the first 1%–5%1\%\text{--}5\% of steps prevents oversized initial Adam jumps before (mt,vt)(\mathbf{m}_t, \mathbf{v}_t) stabilize and steers the trajectory below the sharpness ceiling. Finally, warmup–stable–decay (WSD) holds η0\eta_0 constant after warmup and decays only over the final 10%–20%10\%\text{--}20\% of steps, preserving roughly 90%90\% of the travel budget and allowing short cooldown branches to be forked from any intermediate checkpoint.

9.7.6 Exercises#

  1. [code] Frozen noise under exponential decay. Under ηs=η0γs\eta_s = \eta_0\gamma^s with remaining budget Rs≈ηs/(1−γ)R_s \approx \eta_s/(1-\gamma), integrate ∑sηs2σ2e−2λRs\sum_{s} \eta_s^2 \sigma^2 e^{-2\lambda R_s} to show that the asymptotic frozen variance along curvature λ\lambda is (1−γ)σ2/(4λ2)(1-\gamma)\sigma^2 / (4\lambda^2) when 2λη0≫1−γ2\lambda\eta_0 \gg 1-\gamma. Verify this prediction with sgd_valley for γ∈{0.98,0.99,0.995}\gamma \in \{0.98, 0.99, 0.995\}.

  2. [code] Piecewise-constant step decay. Use (9.7.3) to design a 33-stage piecewise-constant schedule over 3,0003{,}000 steps on sgd_valley and compare its final mean-squared distance against α=1\alpha = 1 polynomial decay (about 0.010.01).

  3. [code] Schedules with identical cumulative budget BTB_T and terminal rate ηT\eta_T. ● Compare full-horizon linear decay ηt=η0(1−t/T)\eta_t = \eta_0(1 - t/T) and cosine decay (9.7.5) with ηT=0\eta_T = 0 (both of which have BT=η0T/2B_T = \eta_0 T / 2 and ηT=0\eta_T = 0) on sgd_valley (η0=0.4,T=3,000\eta_0 = 0.4, T = 3{,}000), and explain why cosine decay finishes at a lower terminal distance by comparing their remaining budgets RtR_t near t≈Tt \approx T.

  4. [code] Warmup duration and maximum tolerable peak rate. ● On TinyLM, vary the linear warmup length across W∈{2,5,10,20,50}W \in \{2, 5, 10, 20, 50\} steps at η0=0.03\eta_0 = 0.03, compare the minimum stable warmup against Adam's first-moment window 1/(1−β1)=101/(1-\beta_1) = 10, and find how much a 2020-step warmup increases the maximum trainable peak learning rate η0\eta_0.

Discussions