CodeRigor

LESSON

Schedules, clipping and accumulation

Build the pieces around the optimizer: warmup and cosine learning rates, weight decay groups, global gradient clipping, gradient accumulation and a wrapping batch loader.

A language model is trained by a loop around the optimizer, and the loop decides whether the optimizer behaves. This lesson covers five pieces of it: a learning rate that changes with the step, weight decay applied to the right tensors, gradient clipping, gradient accumulation and a loader that cuts a token stream into batches. This lesson pairs with Let's reproduce GPT-2 (124M) by Andrej Karpathy, linked under Watch & read. The video is long and builds and trains a GPT-2 sized model; its third section is about the optimizer settings used here. You build all five pieces in PyTorch and grade them against PyTorch's own clipping and a full-batch step.

The learning rate first. Adam with a large rate at step zero is unstable, because its running averages have seen almost no gradients yet. So the rate climbs linearly for warmup steps, then follows half a cosine from the peak down to a floor, and stays at the floor. With progress = (step - warmup) / (total - warmup), the rate is min_lr + ½ (1 + cos(π · progress)) (max_lr - min_lr). During warmup it is max_lr · (step + 1) / warmup. The + 1 matters: without it the very first step runs with a rate of exactly zero and learns nothing.

One schedule: warmup, cosine, floor
lr_at with max_lr = 6, min_lr = 0.6, warmup = 10 and total = 60, in units of 10⁻⁴. The points are computed by the function you write.
One schedule: warmup, cosine, floor
lr_at with max_lr = 6, min_lr = 0.6, warmup = 10 and total = 60, in units of 10⁻⁴. The points are computed by the function you write.
Python
import math


def lr_at(step, max_lr, min_lr, warmup, total):
    if step < warmup:
        return max_lr * (step + 1) / warmup
    if step >= total:
        return min_lr
    progress = (step - warmup) / (total - warmup)
    return min_lr + 0.5 * (1 + math.cos(math.pi * progress)) * (max_lr - min_lr)


print([round(lr_at(s, 1.0, 0.1, 4, 14), 3) for s in (0, 1, 2, 3, 4, 5, 9, 13, 14, 20)])

Weight decay comes next. AdamW shrinks each weight by a factor 1 - lr · weight_decay at every step, separately from the gradient. That is a sensible pull for the matrices of linear layers and for embeddings. It is a poor one for biases and for the gains of a normalisation layer, which are vectors that set an offset or a scale. The usual rule is by shape: tensors with two or more dimensions are decayed, the rest are not. An optimizer takes this as two parameter groups, each with its own weight_decay.

Clipping guards against a single bad batch. Compute one number, the global norm: the square root of the sum of squares of every gradient entry in every tensor. If it is above the limit, multiply all gradients by limit / norm. Every tensor shrinks by the same factor, so the direction of the update does not change, only its length.

Python
import numpy as np

grads = [np.array([3.0, 4.0]), np.array([12.0])]
norm = np.sqrt(sum((g * g).sum() for g in grads))
scale = min(1.0, 1.0 / norm)
print(norm, [(g * scale).round(4).tolist() for g in grads])
print([(g * min(1.0, 1.0 / np.linalg.norm(g))).round(4).tolist() for g in grads])

The second line shows the common mistake: clipping each tensor by its own norm. It returns [0.6, 0.8] and [1.0], so the tensors are rescaled by different factors and the update points somewhere else. The function also returns the norm from before clipping, because logging it is the cheapest way to see a run going unstable.

Gradient accumulation gives a large batch on small memory. Run several micro-batches, let backward() add their gradients together, and take one optimizer step. For that to equal one step on the whole batch, each micro-batch loss must be weighted by its share of the examples, n_i / N. A mean loss already divides by its own n_i, so leaving the weight out makes the gradient several times too large. Weighting by 1 / (number of micro-batches) is right only when every micro-batch has the same size. Clipping then happens once, after all micro-batches, on the summed gradient, because that is the gradient a full batch would have produced.

One accumulated step
start / 3
The loop over micro-batches repeats forward, scaled loss and backward; gradients add up in the .grad fields. Clipping and the single optimizer step come after the loop.
One accumulated step
The loop over micro-batches repeats forward, scaled loss and backward; gradients add up in the .grad fields. Clipping and the single optimizer step come after the loop.

Take a model with one weight at 0, squared error, inputs 1, 2, 3, 4 and targets 1. The gradient on all four examples is -5. Split them into micro-batches of 1 and 3 examples: their own gradients are -2 and -6. The weighted sum (1 · -2 + 3 · -6) / 4 is -5, the plain average of the two is -4, and the unweighted sum is -8.

Python
import numpy as np

grads, sizes = [-2.0, -6.0], [1, 3]
weighted = sum(g * n for g, n in zip(grads, sizes)) / sum(sizes)
print(weighted, np.mean(grads), sum(grads))

The loader is the plainest piece. Take batch × context + 1 consecutive tokens; the inputs are all but the last and the targets are all but the first, so each target is the token that follows its input. Advance by batch × context, and go back to the start when the next window would run past the end.

The hidden tests check the pieces against independent implementations: clip_grad_norm_ for clipping, a full-batch step for accumulation (with uneven micro-batch sizes, with and without clipping active) and a brute-force loop for the loader. Know what that does not show. Equality with a full-batch step is exact only up to floating-point summation order, and only for losses that are plain means over examples. A layer that computes statistics over the batch, such as batch normalisation, sees each micro-batch separately, so accumulation changes the model's behaviour there. And none of these checks says that a peak rate or clipping limit will train your model well. That takes a run.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A long build of a GPT-2 sized model and its training run. Its third section covers AdamW, gradient clipping, a warmup and cosine learning rate and gradient accumulation, the settings this lesson implements. Watch that section first.