Training deep networks: normalisation, regularisation, AdamW and debugging

  • Intermediate
  • 1 h 10 min
  • Lesson 2 of 4 in Deep learning and transformers
  • Last verified

Open slides(22 slides)

Before you start

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.

ProblemTool in this lesson
Activations drift in scale between layersBatch norm or layer norm
Training error far below validation errorDropout, weight decay, early stopping
Adam shrinks weights unevenlyAdamW (decoupled decay)
Early steps are unstable; late steps too largeWarmup, cosine decay
A rare gradient spikeClipping by global norm
NaN or flat lossA 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: y=γ (x−E[x])/Var[x]+ϵ+βy=\gamma\,(x-\mathrm{E}[x])/\sqrt{\mathrm{Var}[x]+\epsilon}+\beta. 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 (−0.447,0.447,−1.183)(-0.447, 0.447, -1.183). Replace a different row and row 0 becomes (−0.576,0.798,−1.069)(-0.576, 0.798, -1.069): batch norm’s output for one example depends on the others in its batch. Layer norm gives (−1.225,0,1.225)(-1.225, 0, 1.225) 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 β\beta.

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 1/B1/\sqrt B.

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 λ2∥W∥2\tfrac{\lambda}{2}\lVert W\rVert^2 to the loss, so each weight gradient gains λW\lambda W (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 pp and multiplies the survivors by 1/(1−p)1/(1-p); 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 p=0.2p=0.2 averages 3.005 over 200,000 masks (standard deviation 1.496), and with p=0.5p=0.5 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:

SettingTrain lossTest lossTest accuracyTest loss at best-validation epoch
No regularisation0.1230.6160.8260.380
Weight decay 0.010.2060.4170.8280.382
Dropout 0.30.1630.5950.8220.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, λw\lambda w is added to the gradient and goes through the same division by v^\sqrt{\hat v} as everything else. AdamW applies the decay directly, θ←θ−γλθ\theta\leftarrow\theta-\gamma\lambda\theta, 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 10−810^{-8} and weight decay 0.01. The script measures the extra shrinkage per step that the decay term causes, holding w=1w=1 with decay 0.01 and learning rate 0.001, for a loss gradient that alternates between +G+G and −G-G (mean zero), averaged over the last 2,000 of 4,000 steps:

Loss gradient scale GGExtra shrinkage per step, Adam with L2Extra shrinkage per step, AdamW
01.0×10−31.0\times10^{-3}1.0×10−51.0\times10^{-5}
0.0019.95×10−49.95\times10^{-4}1.0×10−51.0\times10^{-5}
0.017.07×10−47.07\times10^{-4}1.0×10−51.0\times10^{-5}
0.19.95×10−59.95\times10^{-5}1.0×10−51.0\times10^{-5}
11.0×10−51.0\times10^{-5}1.0×10−51.0\times10^{-5}
1001.0×10−71.0\times10^{-7}1.0×10−51.0\times10^{-5}

With L2 inside Adam the strength of the decay depends on the size of the loss gradient. The extra step is about γλw/G2+(λw)2\gamma\lambda w/\sqrt{G^2+(\lambda w)^2} (derived here), which is nearly a full learning rate when GG is much smaller than λw\lambda w (here 0.01) and about γλw/G\gamma\lambda w/G when GG is much larger. AdamW’s decay is γλw\gamma\lambda w at every GG. The two meet near G=1G=1 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 1/G1/G 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 ww, 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 β2=0.98\beta_2=0.98, 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, ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡(πt/T))\eta_t=\eta_{\min}+\tfrac12(\eta_{\max}-\eta_{\min})(1+\cos(\pi t/T)) with tt counted from the end of warmup and TT 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 10−310^{-3}, the script gives:

Step04999100325550775999
Rate10−510^{-5}5×10−45\times10^{-4}10−310^{-3}10−310^{-3}8.54×10−48.54\times10^{-4}5×10−45\times10^{-4}1.46×10−41.46\times10^{-4}3×10−93\times10^{-9}

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 3×10−43\times10^{-4} 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 (3,4)(3,4) has norm 5 and becomes (0.6,0.8)(0.6,0.8) 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 f(w)=w4f(w)=w^4 from w=3w=3 at learning rate 0.1, the unclipped iterates are −7.8, 182, −2.41×106-7.8,\ 182,\ -2.41\times10^{6} and then reach 1.4×101671.4\times10^{167} 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 0/00/0 appeared. Find the first step at which anything is non-finite before changing anything else.

Diagram: First ask whether the loss is already NaN at step 0, which points to data or the loss computation.

yes

no, after some steps

yes

no, sudden

Loss is NaN or inf

Is it NaN at step 0?

Check data and labels for NaN or inf,
then the loss code: log(0), softmax overflow

Did the loss rise first?

Learning rate too high:
lower it, add warmup, add clipping

Bad batch, division by zero,
exploding activations: check inputs and init

Overfit 4 examples;
run a gradient check

Diagram summary: First ask whether the loss is already NaN at step 0, which points to data or the loss computation. If it appears later, check whether it rose first, which points to the learning rate. A sudden jump points to a bad batch or a numerical hazard. In every case the next step is to shrink the problem: overfit a handful of examples and gradient-check.
  • Overflow in softmax or exp. exp(1000) raises an error in Python; array libraries return infinity and the next step ∞/∞\infty/\infty gives NaN (the script prints nan, as does 0⋅∞0\cdot\infty). Subtract the largest logit and compute the loss as logsumexp minus the true logit: for logits (1000,0)(1000,0) and class 1 that is exactly 1000.0. Softmax followed by log hits a probability that underflows to 0, and log of it raises an error in Python.
  • A learning rate that is too high. The loss rises for a few steps first, as in the w4w^4 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 ϵ\epsilon in the denominator (10−510^{-5} 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 10610^{6} 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 ln⁡C\ln C: 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).

SymptomFirst suspects
Loss flat from the startLearning rate too low, dead units or tiny initialisation, wrong labels or loss
Initial loss far from ln⁡C\ln COutput layer scale too large, labels misaligned with inputs, wrong loss
Training falls, validation rises earlyOverfitting: weight decay, dropout, more data, early stopping
Validation loss below training lossDropout 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 productionDistribution shift or train-serving skew
Eval results differ from expectationModel left in training mode: dropout on, batch norm using batch statistics

Common bugs that produce a healthy-looking run with poor results:

BugWhy it hurtsCheck
Softmax applied before the lossPyTorch’s CrossEntropyLoss expects unnormalised logits, so the loss sees probabilities as scoresPass raw logits (PyTorch, CrossEntropyLoss)
Evaluating in training modeDropout stays on and batch norm uses batch statistics; eval() switches the layers that behave differently, including Dropout and BatchNormCall model.eval() for validation (PyTorch, Module)
Tracking gradients while validatingtorch.no_grad() disables gradient calculation and saves memory; it is separate from eval()Use both (PyTorch, no_grad)
Wrong inputsPreprocessing or augmentation bugs reach the model unseenVisualise exactly what goes into the network (Karpathy)
Learning rate decayed too earlySchedule defaults can drive the rate to zero too soonPlot 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 notLarge minibatches need a learning-rate scaling rule and warmupGoyal et al. give one (Goyal et al.)
Data not shuffledBatches follow the file order, so each step sees a skewed slice and the curves can look healthy yet generalise worseShuffle the training set every epoch (common practice)
Validation data in the normalisation statisticsScaling or feature statistics fitted on all rows leak validation information, so validation scores are optimisticFit them on the training set only (scikit-learn, cross-validation)
No visibility into gradientsSpikes and collapses go unseenLog 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 10610^{6} 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.

Python

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 w4w^4 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 tt 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 1/B1/\sqrt{B}. 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 pp, scale survivors by 1/(1−p)1/(1-p) 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 v^\sqrt{\hat v}, 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

Further reading

Research papers

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.

0 of 14 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveCompare batch norm and layer norm by what their statistics are computed over, and explain how train and eval mode change batch norm and dropout.

  1. Question 1 of 14A model with dropout and batch norm is served after training. Sending the identical request twice returns two slightly different scores. What is the most likely cause?

    Choose one answer.

  2. Question 2 of 14Which statements about batch norm and layer norm are true? Select all that apply.

    Choose all that apply.

  3. Question 3 of 14A team trains a tabular MLP with batch norm (BatchNorm1d) using only 2 rows per step. Validation scores jump around from epoch to epoch. Which explanation fits best?

    Choose one answer.

  4. Question 4 of 14A layer uses dropout with p = 0.25 in a modern library. Which statements are true? Select all that apply.

    Choose all that apply.

ObjectiveExplain 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.

  1. Question 5 of 14A fine-tuning run uses Adam with an L2 penalty of 0.01. Some embedding rows are absent from the batch for many steps in a row, so their loss gradient is exactly 0. At learning rate 0.001 and weight 1, how does the penalty act on them per step, compared with AdamW (decay 0.01)?

    Choose one answer.

  2. Question 6 of 14You train with early stopping, restore the weights from the epoch with the lowest validation loss, and report that validation loss as the model's expected error on new data. What is wrong with that report?

    Choose one answer.

  3. Question 7 of 14Which statement is supported by the lesson's two-moons experiment (30 training points, 8 seeds)?

    Choose one answer.

  4. Question 8 of 14Which statement about an L2 penalty and weight decay is correct?

    Choose one answer.

ObjectiveSet 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.

  1. Question 9 of 14A run uses 2,000 steps, a peak learning rate of 6e-4, 200 warmup steps, and cosine decay to 0 afterwards. What is the learning rate at step 650?

    Choose one answer.

  2. Question 10 of 14A training step produces a gradient with L2 norm 0.4, and the code clips by global norm with max_norm = 1. What does clipping do to this gradient?

    Choose one answer.

  3. Question 11 of 14A new model prints loss = nan on the very first batch, before any weight update. Printing the logits shows values near 1000 for some rows because the inputs were not scaled. What should you do first?

    Choose one answer.

  4. Question 12 of 14A run has been steady for 12,000 steps with a loss near 0.8. At one step the loss is NaN, with no earlier rise. Reloading the previous checkpoint and replaying the same batch gives NaN again. What is the most likely cause?

    Choose one answer.

  5. Question 13 of 14A balanced two-class model prints a training loss of 0.693 at step 0 and at step 10,000. The code runs without errors. Which check comes first?

    Choose one answer.

  6. Question 14 of 14A 3-class model ends with a softmax layer, and the loss is torch's CrossEntropyLoss on that output. What is the effect?

    Choose one answer.