9.7 Schedules
Throughout the preceding sections, we held the learning rate 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 : halving 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 even as the gradient approaches zero, preventing the iterate from settling at a minimum until is reduced.
Modern training recipes resolve this trade-off with a learning-rate schedule that varies across steps . Almost every contemporary schedule combines two phases: an initial warmup ramp from zero to a peak learning rate , 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 and the terminal learning rate . 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 random9.7.1 Learning-Rate Decay on the Noisy Valley#
Consider a single coordinate of the quadratic valley with curvature and zero-mean gradient noise of variance under time-varying step sizes :
Over steps, the deterministic mean contracts by , where
is the cumulative learning-rate budget (the area under the learning-rate curve up to step ). Provided that changes slowly over the local relaxation window , the variance tracks the instantaneous noise ball , yielding the mean-squared error decomposition
Equation (9.7.3) highlights the two requirements on any finite-horizon schedule over steps:
- Sufficient cumulative budget : The total budget must be large enough that the initial bias vanishes along the flattest direction.
- Small terminal learning rate with sufficient remaining budget: The terminal rate must decay toward zero slowly enough that noise injected at intermediate steps is contracted by the remaining budget .
Three classical parametric schedule families are piecewise-constant (step) decay, exponential decay, and polynomial decay:
with decay factor , timescale , and exponent . Simulating independent SGD runs on the valley over steps illustrates how the cumulative budget and terminal rate 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 () plateaus at its stationary noise ball (). Polynomial decay with () and () track (9.7.3) down to and , respectively. By contrast, exponential decay () has a terminal rate of yet freezes at a mean-squared error of : because its remaining budget after step is only , noise injected once () is never contracted away, leaving a frozen variance of (Exercise 1).
9.7.2 Decay Shapes on a Language Model#
On a fixed step budget , two decay profiles dominate modern deep learning:
- Cosine decay (Loshchilov and Hutter, 2016), which follows a half-cosine wave from peak rate at to terminal rate at :
When , cosine decay has cumulative budget (half the budget of a constant rate ).
- Stable–then–decay (late linear decay), which holds the peak rate constant until step (here ) and then decays linearly to over the final of training, preserving of the constant-rate budget () while still finishing at .
To compare constant, cosine, and stable–then–decay schedules () with AdamW () 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 until decay_start=1600 before decaying linearly to zero at ), 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 and the validation loss at step (before late decay starts) and step :
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 , cosine decay leads because its learning rate has already fallen to of the peak, damping high-frequency oscillation. However, between steps and , when stable_decay linearly reduces , its loss drops sharply by nats—finishing nats below the constant schedule and nats ahead of cosine decay, which had only half the cumulative travel budget ( vs. ). 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 linearly from to over steps (typically of ).
Why is warmup needed? First, under Adam (Section 9.5), step moves every coordinate by based on a single minibatch before the momentum average and second-moment average have accumulated multi-batch statistics. On TinyLM, where initial linear weight matrices have , a cold start at alters every weight by of its initial magnitude on step , corrupting the initialization and causing the run to stall near nats. Second, as shown in Section 9.1.4, gradually raising lowers the sharpness ceiling progressively ( for gradient descent, about 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 -step linear ramp (warmup(peak, 20), just of the -step run) caps the initial relative weight change at about and rescues training at , 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 at steps and , we compare a cold start at against a -step linear warmup over 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 before step : intermediate checkpoints are still at elevated learning rates, and extending training beyond 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 and therefore require only a small remaining budget ) and drops the iterate directly onto the valley floor.
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 , we can maintain a single continuous plateau run and branch a short linear cooldown ( steps) from any checkpoint. First, branch(model, optimizer, schedule) clones both the model weights and AdamW's moment buffers 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 -step constant-rate plateau on TinyLM, fork -step linear decay branches at steps and , and compare the step- branch against a dedicated -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 ( nats at steps and ), and the branch at step matches a dedicated -step run planned from scratch—delivering finished models across three training horizons in total steps instead of .
9.7.5 Summary#
A learning-rate schedule is governed by its cumulative learning-rate budget , which sets how far the iterate travels along flat directions, and its terminal learning rate , which determines the final noise floor provided the remaining budget decays slowly enough to damp earlier noise. On TinyLM, decaying the learning rate to zero at the end of training eliminates the step jitter of constant-rate AdamW and reduces validation loss by nats. Linear warmup over the first of steps prevents oversized initial Adam jumps before stabilize and steers the trajectory below the sharpness ceiling. Finally, warmup–stable–decay (WSD) holds constant after warmup and decays only over the final of steps, preserving roughly of the travel budget and allowing short cooldown branches to be forked from any intermediate checkpoint.
9.7.6 Exercises#
-
[code] Frozen noise under exponential decay. Under with remaining budget , integrate to show that the asymptotic frozen variance along curvature is when . Verify this prediction with
sgd_valleyfor . -
[code] Piecewise-constant step decay. Use (9.7.3) to design a -stage piecewise-constant schedule over steps on
sgd_valleyand compare its final mean-squared distance against polynomial decay (about ). -
[code] Schedules with identical cumulative budget and terminal rate . ● Compare full-horizon linear decay and cosine decay (9.7.5) with (both of which have and ) on
sgd_valley(), and explain why cosine decay finishes at a lower terminal distance by comparing their remaining budgets near . -
[code] Warmup duration and maximum tolerable peak rate. ● On
TinyLM, vary the linear warmup length across steps at , compare the minimum stable warmup against Adam's first-moment window , and find how much a -step warmup increases the maximum trainable peak learning rate .