Lesson 5.3: Learning-rate schedules, batch size and gradient clipping
Vary the learning rate over a run with warm-up and cosine decay, measure how batch size changes gradient noise, and cap runaway gradients with clipping.
By the end of this lesson you will be able to write a warm-up and cosine schedule, explain why a constant learning rate is a compromise, measure how the noise in a gradient falls with batch size and find the batch size beyond which more data per step stops helping, clip the gradient by its global norm, and say when warm-up matters and when it does not. You will show that a cosine schedule beats a constant learning rate at every peak we tried (1.0013 against 1.0064, 1.0016 against 1.0096 and 1.0030 against 1.1759 at peaks of 0.003, 0.01 and 0.03); that the squared noise in a batch gradient falls as one over the batch size (2.387 for one window, 0.645, 0.170, 0.0379 and 0.0109 for 4, 16, 64 and 256), which puts the point of diminishing returns near 100 windows; that clipping at 1.0 cut the loss after a corrupted batch from 1.096 to 1.029 and left the median gradient length untouched; and that at a very high peak of 0.03 on eight blocks the effect of warm-up was erratic: it helped on two seeds and hurt on one. You need Python and NumPy and the files from Lessons 5.1 and 5.2.
Lesson 5.2 gave us an optimiser and a learning rate. We used one constant rate for the whole run. That is simple, and it is a compromise. This lesson replaces the compromise with a schedule, and then deals with two other settings that shape each step: how many examples to average, and how large a gradient to allow.
Why a constant rate is a compromise
At the start of training the model is far from any good solution, and large steps make fast progress. Later, when it is close, large steps overshoot, and the loss jitters around the minimum without settling, because each batch gradient is noisy and a big step follows the noise. A small rate settles well and starts slowly. A single rate is too small early or too large late.
The standard answer varies the rate over the run:
1. Warm-up. Start the rate near zero and raise it linearly to the peak over the first few hundred steps.
2. Decay. Reduce it from the peak, smoothly, to a small final value. The usual shape is a half cosine, which falls slowly at first, then faster, then slowly again near the end.
The code gives the schedule as a function of the step, and also the gradient clipping we need later. Save it as schedules.py.
python
# schedules.py
import numpy as np
def lrat(step, total, peak, warmup=100, floor=0.1):
"""Linear warm-up to peak, then a cosine decline to floor peak."""
if step < warmup:
return peak (step + 1) / warmup
t = (step - warmup) / max(1, total - warmup)
return floor peak + 0.5 (1 - floor) peak (1 + np.cos(np.pi t))
def clipglobalnorm(grads, maxnorm):
"""Scale all gradients together so their combined length is at most maxnorm. Returns the length before clipping."""
norm = float(np.sqrt(sum((g 2).sum() for g in grads.values())))
if norm > maxnorm:
for k in grads:
grads[k] = grads[k] (maxnorm / norm)
return norm
For a peak of 0.01, 1,500 steps and a warm-up of 100 steps, the learning rate is 0.0001 at step 0, 0.0051 at step 50, 0.01 at steps 99 and 100, 0.0055 at step 800 and 0.001 at the last step. It rises in a straight line, peaks, and then follows the cosine down to a tenth of the peak.
Does it matter? A test
We train the two-block GPT for 1,500 steps with Adam at three peak rates, once with a constant rate and once with warm-up and cosine decay.
python
from train import
from optim import
from schedules import
steps = 1500
print("learning rate at steps 0, 50, 99, 100, 800, 1499 (peak 0.01):",
[round(lrat(s, steps, 0.01), 5) for s in (0, 50, 99, 100, 800, 1499)])
def fit(peak, schedule, seed=0):
Pos = sinusoidal(T, 32)
p = initgpt(V, 32, 2, seed=seed)
opt = AdamW(p, peak)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, 2, 2, Pos)
if not np.isfinite(loss):
return float("inf")
opt.step(g, lr=lrat(step, steps, peak) if schedule else peak)
return validation(p)
for peak in (0.003, 0.01, 0.03):
with np.errstate(all="ignore"):
print(f"peak {peak:<6} constant: {fit(peak, False):.4f} warm-up + cosine: {fit(peak, True):.4f}", flush=True)
learning rate at steps 0, 50, 99, 100, 800, 1499 (peak 0.01): [0.0001, 0.0051, 0.01, 0.01, 0.0055, 0.001]
peak 0.003 constant: 1.0064 warm-up + cosine: 1.0013
peak 0.01 constant: 1.0096 warm-up + cosine: 1.0016
peak 0.03 constant: 1.1759 warm-up + cosine: 1.0030
At every peak, the schedule wins. At 0.003, the gentlest, it gains 0.005: the end of the run, at a small rate, settles the noise. At 0.01, the gain is 0.008. At 0.03, a rate that is too high to keep for the whole run, the constant rate ends at 1.1759, jittering and far from the floor (0.9885), while the schedule ends at 1.0030, almost as good as at the gentle peaks. The schedule lets us use a high rate early, for speed, without paying for it at the end.
What warm-up is for
The schedule above combines two ideas, and it is worth separating them. The decay at the end is the one with the large and reliable effect, as the table shows. The warm-up at the start has a narrower job: to protect the first steps. Early in training the weights are random, the gradients are large and unrepresentative, and Adam's running averages have not yet settled. A large step then can push the model into a bad region from which it recovers slowly or not at all. A few hundred small steps first give the averages time to settle.
How much that matters depends on the model and the peak. We test it at an extreme setting: 8 blocks of width 16 at a peak of 0.03, with and without a 100-step warm-up, on three seeds.
python
from train import
from optim import
from schedules import
def fit(warmup, steps=800, peak=0.03, seed=0):
d, L = 16, 8
Pos = sinusoidal(T, d)
p = initgpt(V, d, L, seed=seed)
opt = AdamW(p, peak)
rng = np.random.defaultrng(seed)
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
loss, g = lossandgrads(p, x, y, L, 2, Pos)
lr = peak min(1.0, (step + 1) / warmup) if warmup else peak # linear warm-up, then constant
opt.step(g, lr=lr)
return validation(p, d=d, L=L)
for seed in (0, 1, 2):
with np.errstate(all="ignore"):
print(f"seed {seed}: no warm-up {fit(0, seed=seed):.4f} 100-step warm-up {fit(100, seed=seed):.4f}", flush=True)
seed 0: no warm-up 1.0035 100-step warm-up 1.2566
seed 1: no warm-up 1.0571 100-step warm-up 1.0124
seed 2: no warm-up 1.0162 100-step warm-up 1.0115
The result is not clean. Warm-up helped on seeds 1 and 2 (1.0124 against 1.0571, and 1.0115 against 1.0162) and hurt on seed 0 (1.2566 against 1.0035). At this peak the run sits at the edge of stability: whether it settles depends on small differences, and one run tells you little. (It is also why the 1.0484 reported for these settings in Lesson 4.3 differs from the 1.0035 here: the optimiser code was rewritten, the arithmetic differs in the last digits, and the outcome moved.) Take two lessons. Warm-up is cheap insurance, and is standard in large models, where the risk of an early blow-up is worst. And do not trust a single run at a learning rate near the limit. The better remedy is a lower peak, as the schedule test showed.
Batch size and the noise in a gradient
Every step uses the gradient of a batch, an average over some windows. Its true value is the gradient over all the data, and the batch gradient scatters around it. The scatter, the gradient noise, shrinks as the batch grows. How fast? We measure it on the trained model of Lesson 5.1. The code takes a large reference batch of 2,048 windows as the "true" gradient, then draws 30 batches of each size and measures how far their gradients lie from it, squared and summed over all the model's numbers.
python
from train import
p = dict(np.load("base.npz")) # the trained model of Lesson 4.3, saved by Lesson 5.1
Pos = sinusoidal(T, 32)
def gradvector(x, y):
g = lossandgrads(p, x, y, 2, 2, Pos)[1]
return np.concatenate([g[k].ravel() for k in sorted(g)])
bigx, bigy = getbatch(trainids, 2048, T, np.random.defaultrng(0))
gtrue = gradvector(bigx, bigy) # a good estimate of the full-data gradient
print("length of the full gradient:", round(float(np.linalg.norm(gtrue)), 4))
rng = np.random.defaultrng(1)
for B in (1, 4, 16, 64, 256):
err = [np.sum((gradvector(getbatch(trainids, B, T, rng)) - gtrue) 2) for in range(30)]
print(f"batch of {B:3d} windows: squared noise in the gradient {np.mean(err):.5f} times batch size {np.mean(err) B:.4f}")
length of the full gradient: 0.1614
batch of 1 windows: squared noise in the gradient 2.38712 times batch size 2.3871
batch of 4 windows: squared noise in the gradient 0.64500 times batch size 2.5800
batch of 16 windows: squared noise in the gradient 0.16981 times batch size 2.7170
batch of 64 windows: squared noise in the gradient 0.03785 times batch size 2.4227
batch of 256 windows: squared noise in the gradient 0.01091 times batch size 2.7919
The squared noise falls in proportion to one over the batch size: multiplied by the batch size it stays near 2.6 (between 2.39 and 2.79, within the scatter of 30 draws). Quadrupling the batch cuts the noise by a factor of four, so its length by a factor of two.
Now compare that noise with the signal. The model has been trained, so the true gradient is small: its length is 0.1614, so its square is 0.0261. With a single window, the squared noise is 2.39, about 90 times the signal. The gradient the optimiser sees is nearly all noise. The batch size at which noise and signal are equal is the noise level times the batch size, divided by the squared signal: 2.58 ÷ 0.0261 = about 99 windows. Below that, each doubling of the batch really improves the direction of the step. Beyond it, the direction is already dominated by the signal, and a larger batch buys little more per step, while costing proportionally more compute. This is the critical batch size (or gradient noise scale). It is not a constant: it is larger early in training, when the gradient is large and clear, and larger for harder tasks, and it grows as the loss falls. The number for our trained toy model, about 100 windows, shows that our batches of 32 are on the noisy side, which is why the final steps of a constant-rate run jitter.
Batch size and the learning rate
Two rules of thumb connect them. A larger batch has a less noisy gradient, so it tolerates and often wants a larger learning rate. For SGD, a common rule is to scale the rate in proportion to the batch size (the linear scaling rule), up to the critical batch size. For Adam the relationship is gentler, closer to the square root of the batch size. These are guides, not laws, and should be checked by a short sweep. And since compute per step grows with the batch, the question is always the cost: to reach a given loss, how much total data and compute? Below the critical size, doubling the batch halves the steps needed, so the total work stays the same and the steps can run in parallel. Above it, doubling the batch no longer halves the steps, and the work grows.
Gradient clipping
Occasionally a batch produces a gradient far larger than usual: an unusual window, a numerical glitch, a point where the loss surface is steep. A step of the usual size times a huge gradient can throw the model far off course, and recovery can take hundreds of steps or never come.
Gradient clipping by global norm caps it. Compute the length of the whole gradient, over all the model's numbers together. If it exceeds a limit, say 1.0, multiply every gradient by the limit divided by the length, so that the total length equals the limit. The direction does not change, only the size. A normal gradient is untouched.
We test it by corrupting two batches during training (at steps 500 and 900 the targets are random words, which produces a large and meaningless gradient), with and without a clip at 1.0, and recording the loss in the three steps after each.
python
from train import
from optim import
from schedules import
def fit(clip, steps=1500, peak=0.01, seed=0):
Pos = sinusoidal(T, 32)
p = initgpt(V, 32, 2, seed=seed)
opt = AdamW(p, peak)
rng = np.random.defaultrng(seed)
norms, after = [], []
for step in range(steps):
x, y = getbatch(trainids, 32, T, rng)
if step in (500, 900): # a corrupted batch: the targets are random words
y = rng.integers(0, V, y.shape)
loss, g = lossandgrads(p, x, y, 2, 2, Pos)
norms.append(clipglobalnorm(g, clip) if clip else float(np.sqrt(sum((v 2).sum() for v in g.values()))))
if step in (501, 502, 503, 901, 902, 903):
after.append(loss)
opt.step(g, lr=lrat(step, steps, peak))
return validation(p), np.array(norms), np.mean(after)
for clip in (None, 1.0):
with np.errstate(all="ignore"):
v, norms, spike = fit(clip)
print(f"clip {str(clip):5s} validation {v:.4f} loss in the 3 steps after each bad batch {spike:.3f} "
f"gradient length: median {np.median(norms):.2f}, 99th percentile {np.percentile(norms, 99):.2f}, largest {norms.max():.2f}", flush=True)
clip None validation 1.0016 loss in the 3 steps after each bad batch 1.096 gradient length: median 0.29, 99th percentile 0.95, largest 3.03
clip 1.0 validation 1.0009 loss in the 3 steps after each bad batch 1.029 gradient length: median 0.29, 99th percentile 0.86, largest 2.80
Three things to read. The median gradient length is 0.29 in both runs, and the 99th percentile is under the clip limit: clipping at 1.0 does nothing to the ordinary steps. The largest gradient is about 3, ten times the median, at the corrupted batches. The recovery differs: after a corrupted batch the unclipped run's next three steps have a loss of 1.096, and the clipped run's 1.029. The clip kept the damage smaller. At the end the two runs reach almost the same validation loss (1.0016 and 1.0009), since this model is small and recovers either way. In large runs, where a loss spike can cost days of compute, clipping is standard, at a limit of about 1.0, set from the gradient lengths seen in normal training: a little above the typical maximum.
Putting the settings together
For the training run of Lesson 5.4 the choices are:
Setting · Value · ReasonOptimiser · AdamW · Forgiving over a range of step sizes (Lesson 5.2)
Peak learning rate · 0.01 · The schedule makes the peak less critical
Warm-up · 100 steps · Cheap insurance for the first steps
Decay · Cosine to 10% of the peak · Settles the noise at the end
Batch · 32 windows of 16 tokens · Cheap, and noisier than the critical size, as the schedule's decay compensates
Clip · 1.0 · Above the 99th percentile of ordinary gradient lengths (0.95)
Weight decay · 0.01 · Mild, since our data is not tiny
## Key takeaways
A constant learning rate is a compromise: too small early, too large late. A schedule raises the rate during warm-up and then lowers it, usually along a half cosine to a tenth of the peak.
With the schedule, validation losses were 1.0013, 1.0016 and 1.0030 at peaks of 0.003, 0.01 and 0.03. Constant rates gave 1.0064, 1.0096 and 1.1759.
Warm-up protects the first steps. At an extreme peak it helped on two seeds of three and hurt on one, so a single run at the edge of stability proves little.
The squared noise of a batch gradient falls as one over the batch size: 2.387, 0.645, 0.170, 0.0379 and 0.0109 for 1, 4, 16, 64 and 256 windows.
The critical batch size, where noise equals signal, is the noise constant divided by the squared gradient length: about 99 windows for the trained toy model. Beyond it, larger batches help little per step.
Larger batches tolerate larger learning rates: in proportion for SGD up to the critical size, and more gently for Adam. Check with a short sweep.
Clipping by global norm scales all gradients so their combined length is at most the limit, leaving the direction alone. At 1.0 it left the median gradient (0.29) untouched and cut the loss after a corrupted batch from 1.096 to 1.029.
Common mistakes
A constant learning rate, with the jitter blamed on the model. Decay the rate.
A schedule defined in the wrong unit. The total number of steps in the cosine must be the real length of the run.
Warm-up as a cure for a peak that is too high. Lower the peak.
Believing one run at the edge of stability. Use several seeds or a lower rate.
Comparing batch sizes at equal steps. Compare at equal data or equal compute.
Clipping each tensor separately. It changes the direction. Clip the global norm.
A clip limit far below ordinary gradient lengths. It then acts as a smaller learning rate on every step.
Not logging the gradient length. It is the first sign of trouble, and it is how you set the limit.
Check yourself
1. A schedule has a peak of 0.002, 200 warm-up steps and 2,000 steps in all. What is the rate at step 99?
0.002 × 100 ÷ 200 = 0.001, halfway up the warm-up.
2. The squared noise of a gradient is 1.6 at a batch of 8. About what is it at a batch of 128?
128 is 16 times larger, so the squared noise falls by 16: 0.1.
3. A model's squared gradient length is 0.04 and its noise constant is 4. What is the critical batch size?
4 ÷ 0.04 = 100 windows.
4. A gradient has length 5 and the clip limit is 1.0. By what factor is every gradient scaled?
1 ÷ 5 = 0.2.
5. Why clip the global norm and not each tensor?
Scaling all gradients by one factor preserves the direction of the step. Clipping tensors separately changes the relative sizes and so the direction.
6. Why does the cosine schedule help at the end of training?
A small rate takes small steps, so the model settles instead of following the noise of each batch gradient.
Try this
Set aside two hours. You need Python, NumPy and the files from Lessons 5.1 and 5.2.
1. Plot the schedule for a peak of 0.01, 1,500 steps and warm-ups of 0, 100 and 500. Describe the shape.
2. Change the final value of the cosine from 10% of the peak to 0% and to 50%. Which gives the lowest validation loss?
3. Train with a linear decay in place of the cosine. Compare the final loss.
4. Repeat the batch noise measurement at the start of training (the untrained model) and compare the critical batch size with the trained one.
5. Train with batches of 8, 32 and 128 windows, with the same number of steps, then with the same total number of tokens. What do you notice?
6. Run the clipping test with limits of 0.1, 0.3, 1.0 and 3.0. At what point does the clip begin to slow ordinary training?
7. Run the warm-up test for five seeds at a peak of 0.01. Does the effect become clearer?
A good result is a schedule that beats every constant rate, a measured critical batch size and a clip limit chosen from the gradient lengths. The next lesson uses them all in one full training run, and reads the curves it produces.
Read more
Ilya Loshchilov and Frank Hutter, "SGDR: Stochastic Gradient Descent with Warm Restarts" (2016), describes the cosine schedule. Priya Goyal and colleagues, "Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour" (2017), gives the linear scaling rule with warm-up. Sam McCandlish and colleagues, "An Empirical Model of Large-Batch Training" (2018), defines the gradient noise scale and the critical batch size. Razvan Pascanu, Tomas Mikolov and Yoshua Bengio, "On the difficulty of training recurrent neural networks" (2013), introduced gradient norm clipping.
Tags: Build an LLM Learning rate schedule Warm-up Batch size Gradient clipping