Training deep networks: normalisation, regularisation, AdamW and debugging
- Intermediate
- 1 h 10 min
- Lesson 2 of 4 in Deep learning and transformers
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:The learning problem: generalization, bias-variance and regularizationML foundations
- Completed:Linear models, loss functions and gradient descentML foundations
- Completed:Neural networks and backpropagation: gradients, checks and initialisation
You will be able to
- Compare batch norm and layer norm by what their statistics are computed over, and explain how train and eval mode change batch norm and dropout.
- Explain what dropout, weight decay and early stopping each do, how AdamW differs from Adam with an L2 penalty, and read a small regularisation experiment without over-claiming.
- Set up AdamW with a warmup-plus-cosine schedule and gradient clipping by global norm, and work through a debugging checklist for a NaN or flat loss.
Concept
The previous lesson showed how the gradient of a network is computed, checked, and kept from vanishing or exploding by the choice of activation and initialisation. This lesson covers what keeps a run stable and well generalised once the gradients flow: normalisation layers, regularisation, the AdamW optimizer with a learning-rate schedule, gradient clipping, and a checklist for when the loss goes NaN or stays flat. It pays off three threads: the linear-models lesson deferred AdamW, schedules and clipping, the first lesson named early stopping and regularisation as fixes for overfitting, and both left their deep-learning details here.
| Problem | Tool in this lesson |
|---|---|
| Activations drift in scale between layers | Batch norm or layer norm |
| Training error far below validation error | Dropout, weight decay, early stopping |
| Adam shrinks weights unevenly | AdamW (decoupled decay) |
| Early steps are unstable; late steps too large | Warmup, cosine decay |
| A rare gradient spike | Clipping by global norm |
| NaN or flat loss | A debugging flow |
Why It Matters
A network that trains at all can still fail in quiet ways: validation loss rising while training loss falls, results that change with batch size, a model that behaves differently in serving than in testing, a loss that turns NaN at step 5,000. Each has a short mechanism, and the questions are standard in interviews (common industry pattern).
Mental Model
Keep the relay from the previous lesson: a message passed down a line of people, each multiplying it by a number. Normalisation resets the volume at checkpoints so no one shouts or whispers. Regularisation stops the line from memorising one specific message. The schedule controls how hard each person pushes while learning: gently at first, boldly in the middle, gently again at the end. Clipping caps any single shout.
Normalisation: batch norm and layer norm
A normalisation layer standardises activations then applies a learned scale and shift: . The two layers differ only in what the mean and variance are computed over. Batch norm uses each feature across the examples in the mini-batch (PyTorch, BatchNorm1d). Layer norm uses each example across the features of the layer (PyTorch, LayerNorm).
The consequence is who each output depends on. In the script, a batch of four rows has row 0 normalised to . Replace a different row and row 0 becomes : batch norm’s output for one example depends on the others in its batch. Layer norm gives both times. A batch of one makes the variance zero, so the normalised value is exactly 0 for every feature and the layer outputs just .
In practice PyTorch’s BatchNorm1d in training mode refuses a single value per channel and raises an error (“Expected more than 1 value per channel when training”; this is library behaviour that the documentation page does not describe).
That dependence has three costs. The statistics are noisy in small batches: the batch mean of standard normal data has a spread of 0.701, 0.358, 0.178 and 0.089 at batch sizes 2, 8, 32 and 128, matching .
Training and evaluation differ: evaluation uses running estimates accumulated during training (default momentum 0.1), so forgetting eval() is a classic bug.
And sequences are awkward: the layer norm paper says batch norm’s effect depends on mini-batch size and is not obvious to apply to recurrent networks (Ba et al.). Layer norm computes the same thing in both modes, which is one reason it is the usual choice for transformers (common practice); batch norm remains common in image models with large batches (common practice).
The batch norm paper credits it with allowing much higher learning rates, lower sensitivity to initialisation, and a regularising effect that can sometimes replace dropout (Ioffe and Szegedy); its explanation, reduced internal covariate shift, is the authors’ account.
Regularisation
Networks often have more parameters than data points and fit noise easily. The first lesson gave the diagnosis (low training error, much higher validation error). These are the deep learning versions of the fixes.
Weight decay
The L2 form adds to the loss, so each weight gradient gains (Dive into Deep Learning, backpropagation). It is the ridge penalty from the first lesson, usually applied to weights and not biases, a common convention. For plain SGD the L2 penalty and weight decay are equivalent once the decay is scaled by the learning rate; for adaptive optimizers such as Adam they are not, which is why AdamW exists (Loshchilov and Hutter).
Dropout
In training, dropout zeroes each element with probability and multiplies the survivors by ; in evaluation it is the identity (PyTorch, Dropout). The scaling keeps the expected activation unchanged (Dive into Deep Learning, dropout). The script checks it: an activation of 3.0 with averages 3.005 over 200,000 masks (standard deviation 1.496), and with averages 3.004 (standard deviation 3.000). The original paper used the opposite convention, one network with scaled-down weights at test time (Srivastava et al.); the two agree in expectation (derived here).
The paper says dropout prevents units from co-adapting too much and that one unthinned network with scaled-down weights approximates averaging many thinned ones; the textbook calls the co-adaptation justification up for debate. The mechanics are safe to rely on: noise in training only, so train and eval modes must be set correctly. Karpathy suggests adding it sparingly, since it does not combine well with batch norm (Karpathy).
Early stopping
Training loss keeps falling, but validation loss usually turns up once the network fits noise. Early stopping ends training near the lowest validation loss (Karpathy); the usual implementation saves the weights from the best epoch and restores them. The epoch count becomes a regularisation setting chosen on held-out data, the role the number of rounds played in boosting in the trees lesson. Choosing the epoch uses up the validation set, so report the final number on a separate test set.
What the experiment shows
The script trains the network above on the “two moons” problem: 30 training points, noise 0.35, 16 ReLU hidden units, full-batch gradient descent at learning rate 0.5 for 300 epochs (long on purpose; dropout masks are redrawn for every example), a 200-point validation set and a 1,000-point test set. Each of 8 seeds draws new data and weights. Means over the seeds:
| Setting | Train loss | Test loss | Test accuracy | Test loss at best-validation epoch |
|---|---|---|---|---|
| No regularisation | 0.123 | 0.616 | 0.826 | 0.380 |
| Weight decay 0.01 | 0.206 | 0.417 | 0.828 | 0.382 |
| Dropout 0.3 | 0.163 | 0.595 | 0.822 | 0.382 |
- With no regularisation the gap is large (0.123 against 0.616): high variance, as in the first lesson.
- Weight decay cut the mean final test loss from 0.616 to 0.417 and was better on 7 of 8 seeds. Dropout at 0.3 did so on only 3 of 8 and the mean barely moved (0.595 against 0.616), which is within the noise of 8 seeds. That is a result for this tiny network and this rate, not a verdict on dropout.
- Test accuracy is about the same for all three (0.822 to 0.828): here weight decay improved the probabilities, not the accuracy, and dropout changed neither noticeably.
- Early stopping beat the last epoch on all 8 seeds, with best epochs of 4, 3, 18, 163, 2, 143, 25 and 188, so no single fixed count matches the best epoch on every seed. It took the unregularised network from 0.616 to 0.380, about what weight decay and dropout reach at their best epoch (0.382 each).
AdamW, warmup, cosine decay and clipping
The linear-models lesson derived momentum and Adam. Four additions make the usual recipe for networks.
AdamW. With an L2 penalty in Adam, is added to the gradient and goes through the same division by as everything else. AdamW applies the decay directly, , before the moment updates, so it does not accumulate in the momentum or variance (PyTorch, AdamW). PyTorch’s defaults are learning rate 0.001, betas 0.9 and 0.999, epsilon and weight decay 0.01. The script measures the extra shrinkage per step that the decay term causes, holding with decay 0.01 and learning rate 0.001, for a loss gradient that alternates between and (mean zero), averaged over the last 2,000 of 4,000 steps:
| Loss gradient scale | Extra shrinkage per step, Adam with L2 | Extra shrinkage per step, AdamW |
|---|---|---|
| 0 | ||
| 0.001 | ||
| 0.01 | ||
| 0.1 | ||
| 1 | ||
| 100 |
With L2 inside Adam the strength of the decay depends on the size of the loss gradient. The extra step is about (derived here), which is nearly a full learning rate when is much smaller than (here 0.01) and about when is much larger. AdamW’s decay is at every . The two meet near only because of the units of this example, so the lesson is not that Adam with L2 is stronger or weaker: it is that its strength follows for each parameter, far above the nominal decay for parameters with small gradients and far below it for parameters with large ones. This is a stylised case (fixed , alternating gradient), not a training run. The paper reports that decoupling makes the best decay value largely independent of the learning rate and improves Adam’s generalisation (Loshchilov and Hutter).
Warmup starts with a tiny learning rate and ramps it up. It was used for large-minibatch SGD (Goyal et al.) and in the original transformer, with 4,000 warmup steps, Adam with , and a rate that rose linearly then decayed with the inverse square root of the step (Vaswani et al.). One proposed reason for adaptive optimizers is that the adaptive learning rate has a large variance early on, which warmup reduces (Liu et al.); the practice is established and the explanation is still being studied.
Cosine decay then lowers the rate along a half cosine, with counted from the end of warmup and the decay length, the closed form from SGDR; PyTorch’s CosineAnnealingLR implements a recursive approximation of it, without restarts (PyTorch, CosineAnnealingLR). With 100 warmup steps, 1,000 in total and a peak of , the script gives:
| Step | 0 | 49 | 99 | 100 | 325 | 550 | 775 | 999 |
|---|---|---|---|---|---|---|---|---|
| Rate |
A quarter of the way down the decay (step 325) the rate is still at 85% of the peak, where a straight line would be at 75%. The older alternative is a step schedule that divides the rate by a fixed factor, often 10, at chosen epochs (common practice). Warmup plus cosine is a widely used recipe (common practice), and Adam near is a safe first baseline in Karpathy’s experience (Karpathy).
Gradient clipping. PyTorch computes one norm over all parameter gradients as if concatenated into one vector and modifies them in place (PyTorch, clip_grad_norm_). The standard rule (common practice), used in the script and homework, multiplies every gradient by the limit over the norm when the norm exceeds the limit. It was proposed for exploding gradients in recurrent networks (Pascanu et al.).
The gradient has norm 5 and becomes for a limit of 1: the direction is kept and only the length changes. A gradient of norm 0.5 is untouched. In the toy case from at learning rate 0.1, the unclipped iterates are and then reach at the sixth step, with overflow close behind; with the limit at 1 they are 2.9, 2.8, 2.7, 2.6, 2.5, 2.4. Clipping guards against rare spikes. If clipping fires on nearly every step of a small model, check the learning rate and the initialisation first; in some large-model runs it is routinely active.
Debugging a NaN loss
A NaN loss means an infinity or a appeared. Find the first step at which anything is non-finite before changing anything else.
- Overflow in softmax or exp.
exp(1000)raises an error in Python; array libraries return infinity and the next step gives NaN (the script printsnan, as does ). Subtract the largest logit and compute the loss as logsumexp minus the true logit: for logits and class 1 that is exactly 1000.0. Softmax followed byloghits a probability that underflows to 0, andlogof it raises an error in Python. - A learning rate that is too high. The loss rises for a few steps first, as in the run.
- Bad data. A NaN in an input or label, or a division by a zero-variance feature, usually fails at the first step. Check the batch before the model.
- Zero variance in a normalisation. The in the denominator ( by default in PyTorch’s norm layers) prevents it; a custom layer without one fails on constant inputs.
- Exploding activations. In the previous lesson’s table the 2 times He row grew by over 20 layers, enough to overflow the logits.
PyTorch’s clip_grad_norm_ has an error_if_nonfinite option, off by default, that raises an error when the total gradient norm is NaN or infinite; turning it on moves the failure to the step where it first happens.
A flat loss
A loss that sits still from the first step has not received a useful update, which narrows the list. Check in this order. First, the initial loss against : a wrong value points to the output-layer scale, the labels or the loss. Second, whether the model can overfit four examples; if not, the bug is in the data, the loss or the backward pass, so gradient-check as in the previous lesson. Third, the learning rate, including whether the schedule has already decayed it towards zero. Fourth, the initial weight scale, since a tiny initialisation or dead units give vanishing gradients. The classic loss slip is a softmax applied before a loss that expects logits (see the bug table below).
| Symptom | First suspects |
|---|---|
| Loss flat from the start | Learning rate too low, dead units or tiny initialisation, wrong labels or loss |
| Initial loss far from | Output layer scale too large, labels misaligned with inputs, wrong loss |
| Training falls, validation rises early | Overfitting: weight decay, dropout, more data, early stopping |
| Validation loss below training loss | Dropout or augmentation only in training, training loss averaged over an improving epoch, an easier validation set, or leakage (common explanations) |
| Fine on validation, bad in production | Distribution shift or train-serving skew |
| Eval results differ from expectation | Model left in training mode: dropout on, batch norm using batch statistics |
Common bugs that produce a healthy-looking run with poor results:
| Bug | Why it hurts | Check |
|---|---|---|
| Softmax applied before the loss | PyTorch’s CrossEntropyLoss expects unnormalised logits, so the loss sees probabilities as scores | Pass raw logits (PyTorch, CrossEntropyLoss) |
| Evaluating in training mode | Dropout stays on and batch norm uses batch statistics; eval() switches the layers that behave differently, including Dropout and BatchNorm | Call model.eval() for validation (PyTorch, Module) |
| Tracking gradients while validating | torch.no_grad() disables gradient calculation and saves memory; it is separate from eval() | Use both (PyTorch, no_grad) |
| Wrong inputs | Preprocessing or augmentation bugs reach the model unseen | Visualise exactly what goes into the network (Karpathy) |
| Learning rate decayed too early | Schedule defaults can drive the rate to zero too soon | Plot the rate against the step and sweep the peak rate (common practice); Karpathy advises not to trust learning-rate decay defaults (Karpathy) |
| Batch size changed, rate not | Large minibatches need a learning-rate scaling rule and warmup | Goyal et al. give one (Goyal et al.) |
| Data not shuffled | Batches follow the file order, so each step sees a skewed slice and the curves can look healthy yet generalise worse | Shuffle the training set every epoch (common practice) |
| Validation data in the normalisation statistics | Scaling or feature statistics fitted on all rows leak validation information, so validation scores are optimistic | Fit them on the training set only (scikit-learn, cross-validation) |
| No visibility into gradients | Spikes and collapses go unseen | Log the global gradient norm each step (common practice) |
On the choice of optimizer, Karpathy reports that a well-tuned SGD almost always slightly outperforms Adam for ConvNets, while Adam is much more forgiving of hyperparameters (Karpathy).
Code
This standard-library script produced every number in the lesson that is computed here (the growth quoted in the NaN list comes from the previous lesson’s script). It has fixed seeds and runs in about 12 seconds (Python 3.14); almost all of that is section 6. Another Python version may draw different random data, which moves the exact numbers in section 6 but not their pattern.
import math
import random
import statistics
import time
T0 = time.time()
def matvec(W, v):
return [sum(w * x for w, x in zip(row, v)) for row in W]
def softmax(z):
m = max(z)
e = [math.exp(a - m) for a in z]
s = sum(e)
return [a / s for a in e]
# ---- a 2-layer network: x -> ReLU(W1 x + b1) -> softmax(W2 a1 + b2) ----
def forward(P, x, mask=None):
W1, b1, W2, b2 = P
z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
a1 = [max(0.0, z) for z in z1]
if mask:
a1 = [a * m for a, m in zip(a1, mask)]
z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
return z1, a1, z2, softmax(z2)
def backward(P, x, y, cache, mask=None):
W1, b1, W2, b2 = P
z1, a1, z2, p = cache
dz2 = [pk - (1.0 if k == y else 0.0) for k, pk in enumerate(p)]
dW2 = [[d * a for a in a1] for d in dz2]
da1 = [sum(W2[k][j] * dz2[k] for k in range(len(dz2))) for j in range(len(a1))]
if mask:
da1 = [d * m for d, m in zip(da1, mask)]
dz1 = [d if z > 0 else 0.0 for d, z in zip(da1, z1)]
dW1 = [[d * xi for xi in x] for d in dz1]
return [dW1, dz1, dW2, dz2], dz2, da1, dz1
def cells(T):
for t in T:
if isinstance(t[0], list):
for row in t:
for j in range(len(row)):
yield row, j
else:
for j in range(len(t)):
yield t, j
print("\n== 1. Clipping ==")
def clip_norm(g, max_norm):
n = math.sqrt(sum(v * v for v in g))
s = max_norm / n if n > max_norm else 1.0
return [v * s for v in g], n
for g in ([3.0, 4.0], [0.3, 0.4]):
out, n = clip_norm(g, 1.0)
print("gradient", g, "has norm %.1f; clipped to max norm 1:" % n, [round(v, 3) for v in out])
for clip in (None, 1.0):
w, path = 3.0, []
for _ in range(6):
g = 4 * w ** 3
if clip:
g = clip_norm([g], clip)[0][0]
w -= 0.1 * g
path.append(w)
print("f(w)=w^4, lr 0.1, start 3, clip", clip, ["%.3g" % v for v in path])
print("\n== 2. Batch norm vs layer norm ==")
eps = 1e-5
def bn(X):
cols = list(zip(*X))
mu = [statistics.fmean(c) for c in cols]
var = [statistics.pvariance(c) for c in cols]
return [[(v - m) / math.sqrt(s + eps) for v, m, s in zip(r, mu, var)] for r in X]
def ln(X):
out = []
for r in X:
m, s = statistics.fmean(r), statistics.pvariance(r)
out.append([(v - m) / math.sqrt(s + eps) for v in r])
return out
X = [[1.0, 2.0, 3.0], [2.0, 0.0, 4.0], [0.0, 1.0, 5.0], [3.0, 3.0, 3.5]]
X2 = [r[:] for r in X]
X2[3] = [30.0, -9.0, 8.0]
print("row 0 unchanged input; other row replaced")
print(" batch norm row 0:", [round(v, 3) for v in bn(X)[0]], "->", [round(v, 3) for v in bn(X2)[0]])
print(" layer norm row 0:", [round(v, 3) for v in ln(X)[0]], "->", [round(v, 3) for v in ln(X2)[0]])
print(" batch norm with batch of 1:", bn([[5.0, 6.0, 7.0]]))
rng = random.Random(1)
for B in (2, 8, 32, 128):
means = [statistics.fmean(rng.gauss(0, 1) for _ in range(B)) for _ in range(4000)]
print(" batch size %3d: spread (sd) of the batch mean of N(0,1) data %.3f (1/sqrt(B) = %.3f)" % (B, statistics.pstdev(means), 1 / math.sqrt(B)))
print("\n== 3. Dropout arithmetic ==")
rng = random.Random(2)
for p in (0.2, 0.5):
s = [(0.0 if rng.random() < p else 1 / (1 - p)) * 3.0 for _ in range(200000)]
print("p=%.1f: a=3.0 -> mean of dropped activation %.3f, sd %.3f" % (p, statistics.fmean(s), statistics.pstdev(s)))
print("\n== 4. Adam with L2 versus AdamW (w held at 1, decay 0.01, lr 0.001, loss gradient alternating +G, -G) ==")
def mean_update(G, wd, decoupled, steps=4000, lr=0.001, b1=0.9, b2=0.999, e=1e-8):
m = v = 0.0
ups = []
for t in range(1, steps + 1):
g = G if t % 2 else -G
if not decoupled:
g += wd * 1.0
m, v = b1 * m + (1 - b1) * g, b2 * v + (1 - b2) * g * g
u = lr * (m / (1 - b1 ** t)) / (math.sqrt(v / (1 - b2 ** t)) + e)
ups.append(u + (lr * wd * 1.0 if decoupled else 0.0))
return statistics.fmean(ups[steps // 2:])
print("extra shrinkage of w per step caused by the decay term (mean over the last 2000 steps):")
for G in (0.0, 0.001, 0.01, 0.1, 1.0, 100.0):
print(" loss gradient scale %-6s Adam+L2 %.2e AdamW %.2e" % (G, mean_update(G, 0.01, False) - mean_update(G, 0.0, False), mean_update(G, 0.01, True) - mean_update(G, 0.0, True)))
def lr_at(t, total=1000, warm=100, peak=1e-3, floor=0.0):
if t < warm:
return peak * (t + 1) / warm
c = (t - warm) / (total - warm)
return floor + 0.5 * (peak - floor) * (1 + math.cos(math.pi * c))
print("warmup 100 + cosine to 0 over 1000 steps, peak 1e-3:", [(t, "%.3g" % lr_at(t)) for t in (0, 49, 99, 100, 325, 550, 775, 999)])
print("\n== 5. NaN sources ==")
try:
math.exp(1000)
except OverflowError as ex:
print("exp(1000) in Python raises:", ex)
print("array libraries return inf instead, and inf/inf =", float("inf") / float("inf"), "; 0*inf =", 0.0 * float("inf"))
z = [1000.0, 0.0]
lse = max(z) + math.log(sum(math.exp(v - max(z)) for v in z))
print("softmax of [1000, 0] with the max subtracted:", softmax(z), "; loss for class 1 = logsumexp - z[1] =", lse - z[1])
print("naive softmax then log of an underflowed probability: log(exp(-1000)) ->", end=" ")
try:
print(math.log(math.exp(-1000.0)))
except ValueError as ex:
print("ValueError:", ex)
print("ln(2) = %.4f, ln(10) = %.4f" % (math.log(2), math.log(10)))
# ---- section 6: a small network trained on two moons ----
def moons(n, noise, rng):
X, Y = [], []
for i in range(n):
c, t = i % 2, rng.uniform(0, math.pi)
px, py = (math.cos(t), math.sin(t)) if c == 0 else (1 - math.cos(t), 0.5 - math.sin(t))
X.append([px + rng.gauss(0, noise), py + rng.gauss(0, noise)])
Y.append(c)
return X, Y
def init(rng, H, d=2, k=2, out_scale=1.0):
return [[[rng.gauss(0, math.sqrt(2 / d)) for _ in range(d)] for _ in range(H)], [0.0] * H,
[[rng.gauss(0, math.sqrt(2 / H) * out_scale) for _ in range(H)] for _ in range(k)], [0.0] * k]
def evaluate(P, X, Y):
L, ok = 0.0, 0
for x, y in zip(X, Y):
p = forward(P, x)[3]
L -= math.log(max(p[y], 1e-12))
ok += p.index(max(p)) == y
return L / len(X), ok / len(X)
def fit(seed, wd=0.0, drop=0.0, epochs=300, lr=0.5, H=16, ntrain=30):
rng = random.Random(seed)
Xtr, Ytr = moons(ntrain, 0.35, rng)
Xva, Yva = moons(200, 0.35, rng)
Xte, Yte = moons(1000, 0.35, rng)
P = init(rng, H)
best = (1e9, None, 0)
for ep in range(epochs):
acc = None
for x, y in zip(Xtr, Ytr):
mask = [0.0 if rng.random() < drop else 1 / (1 - drop) for _ in range(H)] if drop else None
G = backward(P, x, y, forward(P, x, mask), mask)[0]
acc = G if acc is None else [[[a + b for a, b in zip(r1, r2)] for r1, r2 in zip(t1, t2)] if isinstance(t1[0], list) else [a + b for a, b in zip(t1, t2)] for t1, t2 in zip(acc, G)]
n = len(Xtr)
for (c, j), (g, k) in zip(cells(P), cells(acc)):
c[j] -= lr * g[k] / n
for t in (P[0], P[2]): # weight decay on weights, not biases
for row in t:
for j in range(len(row)):
row[j] -= lr * wd * row[j]
vl = evaluate(P, Xva, Yva)[0]
if vl < best[0]:
best = (vl, [[r[:] for r in P[0]], P[1][:], [r[:] for r in P[2]], P[3][:]], ep + 1)
return evaluate(P, Xtr, Ytr), evaluate(P, Xte, Yte), evaluate(best[1], Xte, Yte), best[2]
print("\n== 6. Two moons, 30 training points, 16 hidden units, full-batch GD lr 0.5, 300 epochs, 8 seeds ==")
t0 = time.time()
res = {}
for name, kw in (("no regularisation", {}), ("weight decay 0.01", {"wd": 0.01}), ("dropout 0.3", {"drop": 0.3})):
res[name] = [fit(s, **kw) for s in range(8)]
print("%-22s %10s %10s %10s %10s" % ("setting", "train loss", "test loss", "test acc", "test@best-val"))
for name, rs in res.items():
print("%-22s %10.3f %10.3f %10.3f %10.3f" % (name, statistics.fmean(r[0][0] for r in rs), statistics.fmean(r[1][0] for r in rs), statistics.fmean(r[1][1] for r in rs), statistics.fmean(r[2][0] for r in rs)))
base = res["no regularisation"]
print("early stopping (best validation epoch) vs last epoch, test loss, per seed:")
print(" best epoch", [r[3] for r in base])
print(" last", [round(r[1][0], 3) for r in base])
print(" best", [round(r[2][0], 3) for r in base])
for name in ("weight decay 0.01", "dropout 0.3"):
print("%s beats no regularisation (test loss) on %d of 8 seeds" % (name, sum(a[1][0] < b[1][0] for a, b in zip(res[name], base))))
print("early stopping beats last epoch on %d of 8 seeds" % sum(r[2][0] < r[1][0] for r in base))
print("section 6 took %.1f s" % (time.time() - t0))
print("total %.1f s" % (time.time() - T0))What to look for: section 1 (clipping and the run), section 2 (batch norm row 0 changes, layer norm row 0 does not), section 3 (dropout keeps the mean), section 4 (Adam with L2 against AdamW, and the schedule), section 5 (NaN sources), section 6 (weight decay, dropout and early stopping over 8 seeds). In PyTorch the equivalents are nn.BatchNorm1d, nn.LayerNorm, nn.Dropout, torch.optim.AdamW, CosineAnnealingLR and clip_grad_norm_, with model.train() and model.eval() switching dropout and batch norm.
Real-World Application
A sound recipe for a new network: AdamW, a short warmup and cosine decay, gradient clipping at a modest norm and early stopping on a validation set, keeping a separate test set for the final number. Watch the training and validation curves together and log the gradient norm. When something breaks, use the NaN flow for a loss that blows up, the flat-loss checks for one that does not move, and check train() and eval() mode before blaming the model.
Interview Perspective
Expect “batch norm versus layer norm”, “what does dropout do at inference”, “what is the difference between Adam with L2 and AdamW”, “why warmup”, “how do you debug a NaN loss” and “your validation loss is lower than your training loss”. A strong answer names what the statistics are computed over, the train and eval difference, and gives an ordered checklist. A weak answer lists remedies without saying how it would find the cause.
Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.
Practice Questions
- Basic: What changes between training and evaluation in a network with batch norm and dropout?
- Intermediate: Why does a batch norm model give different outputs for the same example depending on its batch, and how do you avoid it at serving time?
- Intermediate: Write the learning rate at step for linear warmup followed by cosine decay, and say what each phase is for.
- Advanced: Why does Adam with an L2 penalty regularise rarely updated parameters more strongly than frequently updated ones?
- Product-Company (Generated practice): A training run is healthy for 5,000 steps and then the loss turns NaN. List what you check, in order, and what you change.
Activity
Run the script, then change the weight decay in section 6 to 0.1 and 0.001 and note which seeds flip. Next, add one more batch-size case to section 2 and check that the spread still follows . Finally, take a training loop of your own, deliberately leave it in training mode while validating, and write down what changes in the numbers.
Homework
Implement the training-stability pieces: an L2 penalty with its gradient, global-norm gradient clipping, a warmup-plus-cosine learning-rate schedule, and a single Adam step with either an L2 penalty or decoupled weight decay. The code is in homework/; run the tests until they pass.
Quick Revision
- Batch norm: statistics per feature over the batch, so one example’s output depends on the others, noisy for small batches, running estimates in eval mode. Layer norm: per example over features, the same in train and eval.
- Dropout: zero with probability , scale survivors by in training only;
eval()turns it off. Weight decay shrinks weights. Early stopping uses the best validation epoch; report on a separate test set. - Adam with L2 divides the penalty by , so its strength depends on the gradient scale. AdamW shrinks the weight directly.
- Warmup, then cosine; clip by global norm to keep the direction and cap the length.
- NaN: find the first bad step; data and loss code if at step 0, learning rate if it rose first. Flat: initial loss, overfit four examples, learning rate, initial scale.
Check yourself
- Walk-through: Without notes, explain what happens to a batch norm layer and a dropout layer when you switch a model from training to evaluation.
- Variation: Validation loss is lower than training loss from the first epoch. List three possible causes and one check for each.
- Common misconception: “Dropout stays on at inference to keep the scale right”, “batch norm and layer norm differ only in name”, and “L2 penalty and weight decay are the same in Adam”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
torch.nn.BatchNorm1d (opens in a new tab)
The running-statistics update rule and the train versus eval behaviour, on one page.
Further reading
A Recipe for Training Neural Networks (opens in a new tab)Essential
A practitioner's order of operations for training a network: verify the loss at initialisation, overfit one batch, then regularise. It turns this lesson's debugging flow into a habit.
Research papers
The original batch norm paper, to compare its claims with what the layer actually does in eval mode.
Decoupled Weight Decay Regularization (opens in a new tab)
The argument for why decay must be decoupled from the gradient in adaptive optimizers. Read it after you can write the Adam update from memory.
SGDR: Stochastic Gradient Descent with Warm Restarts (opens in a new tab)
Where the cosine schedule PyTorch implements comes from, with warm restarts.
More for this module: Deep learning and transformers resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Deep learning and transformers.
Check yourself14 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.