Skip to content
Deep learning Core 22 min read

A recipe for training (and debugging) networks

Neural networks fail silently: a wrong axis, a forgotten zero_grad or a mislabelled batch rarely crashes anything — the loss just ends up a bit worse. The defence is a disciplined process: build up from something trivially correct, verify invariants you can check cheaply, change one thing at a time, and read the curves.

10,000 ft

Everything earlier in this track — backpropagation, initialisation and normalisation, optimisers, regularisation, architectures — is ingredients. This page is the cooking. Practitioners consistently report that most of their time goes on debugging and tuning, not on designing models (the Full Stack Deep Learning course puts it at 80–90%). The good news is that the workflow is learnable and largely universal: the same steps that train a CIFAR classifier also guided the logbooks of hundred-billion-parameter language-model runs. It connects forward to MLOps (tracking and reproducing experiments), statistics for experiments (is that improvement real?) and the project ladder, where you will use it.

2,000 ft

Six stages, each of which rules out a class of failure before you pay for the next. The ordering is adapted from Andrej Karpathy's A Recipe for Training Neural Networks (2019) and Google's Deep Learning Tuning Playbook.

The recipe: each stage removes one kind of doubt
The recipe: each stage removes one kind of doubt. 1. Become one with the data look, count, find the mess, 2. End-to-end skeleton + dumb baselines verify loss at init, eval pipeline, 3. Overfit one batch loss → 0, or there is a bug, 4. Fit the training set known architecture, Adam, no tricks, 5. Regularise more data, augmentation, decay, early stop, 6. Tune and squeeze LR first, then the rest; enseThe recipe: each stage removes one kind of doubt. 1. Become one with the data look, count, find the mess, 2. End-to-end skeleton + dumb baselines verify loss at init, eval pipeline, 3. Overfit one batch loss → 0, or there is a bug, 4. Fit the training set known architecture, Adam, no tricks, 5. Regularise more data, augmentation, decay, early stop, 6. Tune and squeeze LR first, then the rest; ense

Ground level

Why training needs a recipe

A normal program fails loudly: wrong types, exceptions, failed tests. A training script with a bug usually still runs, the loss still decreases, and you get a model that is 3% worse than it should be. Karpathy's examples: you forgot to flip the labels when you flipped the image; your autoregressive model accidentally sees the token it is predicting; you clipped the loss instead of the gradients; you initialised from a checkpoint but not its mean; you messed up a regularisation setting, the learning rate or the decay. None of these throws an error. The network, being a powerful function-fitter, partially compensates for the bug, which hides it further.

The response is to work like a scientist: make predictions that can be checked cheaply ("the loss at step 0 should be 2.303"), add complexity one piece at a time, and never change two things at once.

Stage 1: become one with the data

Before touching code, look at thousands of examples. Sort them by label, by length, by loss later on. You are looking for duplicates, corrupted files, label noise, class imbalance, leakage between train and test (the same patient, user or document in both — see metrics, validation and leakage), and which features you yourself use to solve the task. If you, looking at the data, cannot tell what the label should be, the model will struggle too. Write small scripts to filter and count; the distributions you find become checks later.

Stage 2: an end-to-end skeleton with dumb baselines

Get a tiny model training and evaluating end to end, and make it boringly correct before it is good:

  • Fix the random seed, so reruns are identical while you debug.
  • Disable everything fancy: no augmentation, no scheduler, no mixed precision.
  • Check the loss at initialisation. For a \(C\)-class softmax with near-uniform initial predictions, the cross-entropy is \(-\ln(1/C) = \ln C\): 2.303 for 10 classes, 6.908 for 1,000, 10.82 for a 50,257-token vocabulary. If your step-0 loss is far from this, the initialisation or the loss is wrong. (Our code measures 2.309.)
  • Initialise the output layer sensibly. Small final-layer weights give near-uniform predictions; for imbalanced classes set the final bias to the log class priors; for regression, to the mean target. The "hockey stick" at the start of a loss curve is often the network learning a bias you could have set.
  • Establish baselines: predict the majority class; a linear model; an input-independent model (feed zeros) — if your network does not beat the zero-input baseline, it is not using the input.
  • Visualise exactly what goes into the network, immediately before model(x): decoded tokens, de-normalised images with their labels. This one check catches a remarkable fraction of data bugs.
  • Evaluate on the full validation set, with the metric you actually care about, not only the loss.

Stage 3: overfit a single batch

Take one batch of 2–16 examples and train on it repeatedly with a reasonable learning rate. A correct network with enough capacity will drive the loss towards zero (our code reaches 0.0013 from 2.31 in 300 steps). If it cannot, there is a bug in the model, the loss, the gradient flow or the optimiser step. Also check the predictions match the labels exactly — a network that overfits the wrong labels has a data-pipeline bug.

Stage 4: fit the training set

Now scale to the full training set with a model you believe is big enough, chosen from the literature rather than invented ("don't be a hero"): a ResNet for images, a standard transformer for sequences. Use Adam(W) at \(3\times10^{-4}\) or a learning rate found by a range test, no regularisation, and a constant learning rate. The goal is a training loss that goes low. If it won't, the problem is capacity or optimisation, and regularising would only make it worse. Add one piece of complexity at a time — a bigger input, more layers, the real augmentation — and confirm the expected improvement after each.

Stage 5: regularise

Once training loss is low and validation lags, trade training performance for validation performance, in roughly this order of reliability: get more real data (nothing else is as reliable); augment (regularisation); pre-train or fine-tune from a model trained on more data; reduce input dimensionality or remove spurious features; use a smaller model; weight decay; dropout; early stopping. Watch the first-layer filters or attention patterns for noise that suggests overfitting.

Stage 6: tune and squeeze

Tune the learning rate first. It interacts with everything and matters most. A cheap learning-rate range test (Smith, 2015): train for a few hundred steps while increasing the learning rate exponentially from \(10^{-7}\) to \(10\), plot loss against learning rate, and pick a peak value about an order of magnitude below where the loss starts to blow up.

01234050100150200stepln 10 = 2.30lr 30: too highlr 0.003: too lowlr 0.3: about right
Training loss of the small MLP from Build it at three learning rates (full batch, 200 steps; real runs). Every curve starts at ln 10 ≈ 2.30, the loss of a uniform guess over 10 classes. Too low barely moves; too high jumps above the starting loss and thrashes; a good rate falls fast and keeps falling.

Then tune the rest with random search, not grid search (Bergstra and Bengio, 2012): if only a few of the hyperparameters matter, a grid wastes most trials repeating the same values of the important ones, while random search tries a new value of every hyperparameter in every trial. The Tuning Playbook adds a crucial distinction: in each round of experiments decide which hyperparameters are scientific (what you are testing, e.g. depth), which are nuisance (must be re-optimised for each setting for a fair comparison, e.g. learning rate), and which are fixed. Comparing two depths at the same learning rate is not a fair comparison.

To squeeze out the last few per cent: ensembles (Karpathy calls them "a pretty much guaranteed way to gain 2% of accuracy on anything", at multiplied inference cost — distil them afterwards); train longer than seems necessary (many models keep improving long after the validation loss looks flat); keep an exponential moving average of the weights or average checkpoints (stochastic weight averaging, Izmailov et al., 2018).

Reading the curves

What you see Most likely causes First thing to try
Loss is NaN or inf within a few steps LR far too high; log(0); division by zero; fp16 overflow Lower LR 10×; log-softmax/CrossEntropyLoss on logits; check inputs for NaN; torch.autograd.set_detect_anomaly(True)
Loss stays at its initial value (\(\ln C\)) gradients not reaching weights (detached tensor, requires_grad=False, optimiser given the wrong params), LR far too low, dead ReLUs Overfit one batch; print gradient norms per layer
Loss falls, then suddenly spikes or explodes LR too high for the current curvature; a bad batch; no warm-up Lower peak LR; add warm-up; gradient clipping; inspect the batch at the spike
Training loss low, validation loss high and rising overfitting Stage 5; early stopping
Training and validation both high and close underfitting or a bug Bigger model; train longer; recheck Stage 3
Validation better than training dropout/augmentation active only in training; train loss averaged over an epoch while improving Usually harmless; compare in eval() mode
Very noisy loss batch too small; LR too high; shuffling problem Larger batch or lower LR; log a smoothed curve
Validation metric worse after a "harmless" refactor data order, normalisation constants, train()/eval() modes, tokenizer changes Diff the inputs to the model, not the code

Watch the internals, not just the loss

The loss is one number averaged over everything; problems hide inside it. Log, per layer, at least every few hundred steps:

  • Activation statistics: mean, standard deviation, and the fraction of saturated tanh units or dead ReLUs. Exploding or collapsing standard deviations through depth point to initialisation or normalisation problems (residual networks shows how fast these compound).
  • Gradient norms per layer, and the global norm. Sudden growth precedes loss spikes.
  • The update-to-weight ratio \(\|\eta\,\Delta\mathbf w\|/\|\mathbf w\|\) per layer. The CS231n notes give a rough heuristic of about \(10^{-3}\) per step: much lower means that layer is barely learning; much higher means it is being rewritten every step. Karpathy's makemore part 3 lecture builds these plots step by step and is the best way to learn to read them.
  • Predictions on a fixed set of inputs over training: for a generative model, sample from the same prompts; for a classifier, track a few hard examples.

Gradient checking

When you write a layer or loss by hand, compare its analytic gradient with centred finite differences, \(\frac{f(\theta+\epsilon)-f(\theta-\epsilon)}{2\epsilon}\), using the relative error \(\frac{|g_a-g_n|}{|g_a|+|g_n|}\). In float64 with \(\epsilon\approx10^{-5}\), relative errors around \(10^{-7}\) or smaller mean the gradient is right; \(10^{-2}\) means it is wrong (our MLP gets \(1.8\times10^{-8}\)). Kinks (ReLU at 0, max) can produce isolated large errors; check several points. Frameworks' autograd removes most of the need, but custom CUDA/Triton kernels and hand-written backward passes still deserve it.

The batch-independence check

Most layers must treat the examples in a batch independently (batch normalisation in training mode is the deliberate exception). A common silent bug — x.view(...) where x.permute(...) was needed, or a reduction over the wrong axis — mixes information across examples. The check: perturb (or compute the gradient with respect to) example \(j\) and verify that example \(i\)'s output does not change. Our code shows a transpose-then-reshape bug that makes example 0's logits change by \(1.1\times10^{-4}\) when only example 3 moves; the correct model gives exactly zero. For autoregressive models, the same test with time steps verifies the causal mask: the output at position \(t\) must not depend on inputs at positions \(> t\).

Experiment hygiene

  • Log everything that defines a run: code commit, config, data version, seed, hardware. Tools such as Weights & Biases, MLflow or TensorBoard make this cheap (MLOps).
  • Measure seed variance before believing a difference. Run the baseline with 3–5 seeds. If your "improvement" is smaller than the spread across seeds, you have not shown anything; report mean and standard deviation (statistics for experiments).
  • Hold the test set back until the end. Every decision made by looking at a set leaks information from it.
  • Change one thing at a time, and keep a lab notebook. Large-model teams publish theirs: Meta's OPT-175B logbook ("chronicles") records the restarts, loss spikes and hyperparameter changes of a real 175B-parameter run, and is an education in what goes wrong at scale.

Performance is part of the recipe

A run that is 3× faster is three times as many experiments. Before tuning anything else: check GPU utilisation (a data loader that cannot keep up shows as low, spiky utilisation); use mixed precision (bf16 where supported — mixed precision); pick the largest batch that fits and is below the critical batch size (optimisers); consider torch.compile; profile before optimising. The PyTorch performance tuning guide lists the standard wins.

When the run is too big to iterate on

You cannot run five seeds of a frontier model. Teams instead study small-scale proxies: Wortsman et al. (2023) reproduced large-model instabilities (attention-logit growth, output-logit divergence) in small models by raising the learning rate, and showed which mitigations (QK-layernorm, z-loss) transfer. μP (Yang et al., 2022) parameterises the network so that the best learning rate found on a narrow model transfers to a wide one. And scaling laws predict the large run's loss from a sweep of small ones, so a run that falls off its predicted curve is a bug signal.

In Finny

The same discipline applies to LLM applications. Jarvis's answers are checked against a fixed golden set before any prompt or routing change ships — the application-level version of "overfit one batch, then change one thing at a time". See evals in practice and the Jarvis case study.

First principles

Why does this ordering work? Because debugging is search, and the cheapest search is bisection. Each stage tests a hypothesis that is cheap to check and, if false, makes everything after it meaningless:

  1. The data are what I think they are (Stage 1). Otherwise no model can be right.
  2. The pipeline computes what I think it computes — the loss at init matches theory, the eval matches the metric, the inputs look right (Stage 2).
  3. The model can represent and the optimiser can find a fit to a handful of points (Stage 3). This isolates implementation bugs from generalisation problems: a correct over-parameterised network can always memorise 16 examples.
  4. The model has enough capacity for the task (Stage 4) — the bias side of bias and variance.
  5. The model generalises (Stage 5) — the variance side.
  6. The settings are good (Stage 6) — only meaningful once 1–5 hold, which is why tuning first is the most common waste of compute.

The checks themselves follow from mathematics you have already seen. The initial loss is \(\ln C\) because a softmax over near-equal logits is uniform and cross-entropy against uniform is \(-\ln(1/C)\) (information theory). Gradient checking works because the centred difference has error \(O(\epsilon^2)\) (Taylor's theorem: the odd terms cancel), while floating-point cancellation contributes error \(O(\varepsilon_{\text{mach}}/\epsilon)\); balancing them gives \(\epsilon\approx10^{-5}\) in float64. The batch-independence test is a statement about the Jacobian of the network: for a per-example function, \(\partial f(\mathbf x)_i/\partial\mathbf x_j = 0\) for \(i\ne j\), so the full Jacobian is block-diagonal. And the learning-rate curves are the stability limit from optimisers seen in a real network: below \(2/\lambda_{\max}\) progress is slow but steady; above it, the loss climbs above where it started.

The maths

Expected initial loss. Logits \(\mathbf z\approx\mathbf 0\) ⇒ \(\operatorname{softmax}(\mathbf z)_k = 1/C\) ⇒ \(\mathcal L_0 = -\ln(1/C) = \ln C\). With final-layer weights of standard deviation \(s\) and hidden features of norm \(r\), logits have standard deviation about \(sr\); the expected loss rises above \(\ln C\) by roughly half the logit variance for small \(sr\), which is why a step-0 loss of, say, 4.5 on a 10-class problem means the initial logits are far too large.

Derivation: why centred differences, and why ε ≈ 1e-5

Taylor-expand \(f\) around \(\theta\): \(f(\theta\pm\epsilon) = f(\theta)\pm\epsilon f'(\theta)+\tfrac{\epsilon^2}{2}f''(\theta)\pm\tfrac{\epsilon^3}{6}f'''(\theta)+\dots\). Subtracting, the even terms cancel:

\[ \frac{f(\theta+\epsilon)-f(\theta-\epsilon)}{2\epsilon} = f'(\theta)+\frac{\epsilon^2}{6}f'''(\theta)+O(\epsilon^4). \]

The one-sided difference \((f(\theta+\epsilon)-f(\theta))/\epsilon\) has error \(O(\epsilon)\) instead. Rounding error in computing \(f\) is about \(\varepsilon_{\text{mach}}|f|\), and dividing by \(2\epsilon\) magnifies it to \(\sim\varepsilon_{\text{mach}}|f|/\epsilon\). Total error \(\sim\epsilon^2|f'''|/6+\varepsilon_{\text{mach}}|f|/\epsilon\) is minimised near \(\epsilon\sim\varepsilon_{\text{mach}}^{1/3}\): about \(6\times10^{-6}\) in float64 (\(\varepsilon_{\text{mach}}\approx2.2\times10^{-16}\)), but about \(5\times10^{-3}\) in float32 — which is why gradient checks must run in float64.

Update ratio. For SGD, \(\Delta\mathbf w = -\eta\mathbf g\), so the ratio is \(\eta\|\mathbf g\|/\|\mathbf w\|\); for Adam it is roughly \(\eta\sqrt{n}/\|\mathbf w\|\) for a tensor with \(n\) entries, since each coordinate moves by about \(\eta\) (optimisers).

Seed variance. If a metric has standard deviation \(\sigma\) across seeds, the difference of two means from \(n\) seeds each has standard error \(\sigma\sqrt{2/n}\). With \(\sigma = 0.3\) points and \(n = 3\), the standard error is \(0.24\), so an observed 0.3-point improvement is about 1.2 standard errors — not convincing. Detecting it reliably needs more seeds or a larger effect.

Random vs grid search. With a budget of \(n\) trials over \(d\) hyperparameters, a grid tries only \(n^{1/d}\) distinct values of each; random search tries \(n\) distinct values of each. If one hyperparameter matters and the others do not, random search explores it \(n^{1-1/d}\) times more finely: with 64 trials and 3 hyperparameters, 64 values instead of 4.

Build it

NumPy. A two-layer MLP on a synthetic 10-class problem, with the four sanity checks from this page: loss at initialisation, a gradient check, a batch-independence check that catches a real bug, and overfitting one batch; then three learning rates.

import numpy as np
rng = np.random.default_rng(0)
N, D, H, C = 512, 20, 64, 10                              # examples, inputs, hidden, classes
X = rng.normal(size=(N, D)); y = (X[:, :C] + 0.5 * rng.normal(size=(N, C))).argmax(1)

def init(scale=0.01):  # small last layer -> near-uniform predictions at step 0
    return {"W1": rng.normal(size=(D, H)) * np.sqrt(2 / D), "b1": np.zeros(H),
            "W2": rng.normal(size=(H, C)) * scale, "b2": np.zeros(C)}

def loss_and_grads(p, X, y):
    h = np.maximum(X @ p["W1"] + p["b1"], 0)
    z = h @ p["W2"] + p["b2"]; z -= z.max(1, keepdims=True)
    logP = z - np.log(np.exp(z).sum(1, keepdims=True))                # log-softmax, never log(0)
    P, loss = np.exp(logP), -logP[np.arange(len(y)), y].mean()
    dz = P.copy(); dz[np.arange(len(y)), y] -= 1; dz /= len(y)
    dh = (dz @ p["W2"].T) * (h > 0)
    return loss, {"W2": h.T @ dz, "b2": dz.sum(0), "W1": X.T @ dh, "b1": dh.sum(0)}

# Check 1: the loss at initialisation should be -ln(1/C)
p = init(); print(f"check 1  initial loss {loss_and_grads(p, X, y)[0]:.3f}  vs ln(C) = {np.log(C):.3f}")

# Check 2: analytic gradients vs centred finite differences (relative error)
_, g = loss_and_grads(p, X[:8], y[:8]); worst = 0.0
for k in p:
    for idx in [tuple(rng.integers(0, s) for s in p[k].shape) for _ in range(5)]:
        old = p[k][idx]; p[k][idx] = old + 1e-5; lp = loss_and_grads(p, X[:8], y[:8])[0]
        p[k][idx] = old - 1e-5; lm = loss_and_grads(p, X[:8], y[:8])[0]; p[k][idx] = old
        num = (lp - lm) / 2e-5
        worst = max(worst, abs(num - g[k][idx]) / max(1e-12, abs(num) + abs(g[k][idx])))
print(f"check 2  worst relative gradient error {worst:.1e}")

# Check 3: examples in a batch must not influence each other. A classic bug: transpose-then-reshape.
def out0(xb, buggy):  # logits of example 0, computed from the whole batch
    xb = xb.T.reshape(xb.shape) if buggy else xb                       # the bug mixes rows
    return (np.maximum(xb @ p["W1"] + p["b1"], 0) @ p["W2"])[0]
for buggy in (False, True):
    xb = X[:4].copy(); base = out0(xb, buggy); xb[3] += 1e-3           # perturb example 3 only
    print(f"check 3  buggy={buggy!s:5}  change in example 0's logits: {np.abs(out0(xb, buggy) - base).max():.1e}")

# Check 4: overfit one small batch; then compare learning rates on the full set
def train(lr, steps, Xb, yb):
    q = init(); curve = []
    for _ in range(steps):
        l, g = loss_and_grads(q, Xb, yb); curve.append(l)
        for k in q: q[k] -= lr * g[k]
    return curve
print(f"check 4  one batch of 16, 300 steps: loss {train(0.5, 300, X[:16], y[:16])[-1]:.4f}")
for lr in (0.003, 0.3, 30.0):
    c = train(lr, 200, X, y)
    print(f"lr={lr:<6} loss after 1, 50, 200 steps: {c[0]:.3f} {c[49]:.3f} {c[-1]:.3f}")

Output:

check 1  initial loss 2.309  vs ln(C) = 2.303
check 2  worst relative gradient error 1.8e-08
check 3  buggy=False  change in example 0's logits: 0.0e+00
check 3  buggy=True   change in example 0's logits: 1.1e-04
check 4  one batch of 16, 300 steps: loss 0.0013
lr=0.003  loss after 1, 50, 200 steps: 2.299 2.244 2.104
lr=0.3    loss after 1, 50, 200 steps: 2.311 0.952 0.360
lr=30.0   loss after 1, 50, 200 steps: 2.321 3.209 3.186

The same checks in PyTorch take a few lines each:

import torch
# loss at init
with torch.no_grad(): print(loss_fn(model(xb), yb).item(), "vs", torch.log(torch.tensor(num_classes)).item())
# batch independence: gradient of example 0's output w.r.t. the whole batch
xb = xb.clone().requires_grad_(True)
model(xb)[0].sum().backward()
print((xb.grad[1:].abs().sum() == 0).item())      # True unless something mixes examples (or BatchNorm in train mode)
# gradient check a custom op in float64
torch.autograd.gradcheck(my_op, (torch.randn(4, 8, dtype=torch.float64, requires_grad=True),))

Things to try

  • Set init(scale=1.0) and rerun check 1. How far above \(\ln 10\) is the initial loss, and how much of the first 50 steps does the network spend undoing it?
  • Introduce a deliberate bug in loss_and_grads (drop the /= len(y) or the ReLU mask) and see which check catches it.
  • Implement a learning-rate range test: one run, LR rising from \(10^{-4}\) to \(10^{2}\) over 200 steps, plot loss against LR on a log axis, and compare its suggestion with the three runs above.
  • Run the lr=0.3 training with five different seeds and compute the mean and standard deviation of the final loss. How big would an improvement have to be before you believed it?
  • Take a training script you have written before and add per-layer gradient-norm and update-ratio logging. Which layer learns slowest?

Check yourself

Your 1,000-class classifier starts with a loss of 6.9 and stays there for 5,000 steps. What do you check first?

6.9 ≈ ln 1000 is the uniform-guess loss, so the network is not learning at all. Check that gradients are non-zero and reach the parameters (optimiser given the right parameters, nothing detached, no requires_grad=False), that the learning rate is not tiny, then try to overfit a single batch.

Why should you overfit a single batch before training on the full dataset?

It separates implementation bugs from learning problems. A correct, sufficiently large network can always memorise a handful of examples; if it cannot, something in the model, loss, gradient flow or update is broken, and no amount of data or tuning will fix it.

Training accuracy 99%, validation 75%. You add dropout and validation rises to 76% but training falls to 90%. What next?

You are in the regularisation stage; dropout helped a little. The most reliable next steps are more data or stronger augmentation, or starting from a pre-trained model; also check the validation set for distribution shift or label noise. Tune the dropout rate and weight decay jointly with the learning rate (a nuisance parameter) before concluding.

Why is random search better than grid search with the same budget?

Usually only a few hyperparameters matter. A grid tries each value of an important hyperparameter many times (once per combination of the unimportant ones), so it sees only \(n^{1/d}\) distinct values; random search sees \(n\) distinct values of every hyperparameter.

What does an update-to-weight ratio of 1e-1 per step in one layer suggest?

That layer's weights change by about 10% every step — far too fast; the learning rate is too high for it (or its weights are tiny). Expect instability. Lower the learning rate, use per-layer rates or check its initialisation.

Hard: a model's validation loss is lower with batch size 1 at test time than with batch size 64. What kind of bug does that suggest, and how would you confirm it?

Something makes predictions depend on other examples in the batch: BatchNorm left in training mode, padding or masking that differs with batch composition, or a reshape/permute bug. Confirm with the batch-independence check (perturb one example and watch the others' outputs) in eval() mode.

Hard: why must gradient checks run in float64?

The centred difference's truncation error is \(O(\epsilon^2)\) and its rounding error is \(O(\varepsilon_{\text{mach}}/\epsilon)\). In float32 (\(\varepsilon_{\text{mach}}\approx1.2\times10^{-7}\)) the best achievable relative error is around \(10^{-4}\)–\(10^{-5}\), too close to the size of real bugs to distinguish them; in float64 you can reach \(10^{-8}\)–\(10^{-10}\).

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads