Skip to content
BIASED

Training networks in practice

A debugging recipe for training: loss at initialization, overfitting one batch, a learning-rate range test, reading curves, reproducibility and compute budget; course recap and pointers to NLP, generative models and Bayesian methods.

Silent failures

Model compression closed the catalogue of methods. Until now the course covered methods under settings that were already chosen and checked; reproducible runs and optional notebooks are a separate practice layer, not a promise that every topic already shipped a Code section with a trained net. On a new problem nobody has tuned those settings yet. The hard part is not the method but the process: a bug in the labels, a learning rate ten times too large or a forgotten model.eval() all give a network that trains — just worse — and no error message says so.

Key idea. Before each step, predict what you should see, run the smallest experiment that tests the prediction, and move on only when it holds. Look at raw examples and labels first; put up baselines that ignore the input or stay linear. Then check the loss at initialization, overfit one batch, find the learning rate, read the curves, and only then spend compute on full runs — one change at a time, every run recorded and seeded.

Loss at initialization

At initialization logits are small, so the softmax is nearly uniform and every class has probability about 1/C1/C. Cross-entropy of the true class is then

L0≈−log⁡1C=ln⁡C.L_0 \approx -\log\frac1C = \ln C.

For C=10C = 10, ln⁡10=2.303\ln 10 = 2.303. A second-order expansion adds about 12σ2(1−1/C)\tfrac12\sigma^2(1 - 1/C) when logits have variance σ2\sigma^2. Much larger L0L_0 means logits are too large: last layer too wide, or inputs not normalized. The topic’s MLP starts at 2.3102.310; with the last layer drawn from N(0,1)\mathcal N(0,1) it starts at 3.0443.044.

Set the last bias to log⁡πk\log\pi_k (class frequencies) so the initial prediction matches π\pi and the expected loss equals the label entropy. For a 10%10\% positive binary problem that entropy is 0.3250.325, against ln⁡2=0.693\ln 2 = 0.693 with a zero bias. For regression, set the last bias to the mean target. Hidden-layer initialization is Normalization and initialization.

Overfit one batch

A network with enough capacity, trained on one fixed batch with augmentation and regularization off, must drive the training loss to about zero. If it cannot, something between the data and the gradient is broken, and no amount of tuning will help. The test takes seconds.

Two classic failures and one diagnostic trap. A softmax applied twice — probabilities fed into cross_entropy, which applies softmax again — has a floor log⁡(e+C−1)−1=1.461\log(e + C - 1) - 1 = 1.461 for C=10C = 10; the run stalls near 1.551.55. Fixed, even deliberately wrong labels (one shift or one permutation for the whole run) a capable net can usually memorize: the loss goes to zero, as in Losses and regularization on random labels. A floor near the batch’s label entropy (≈2.08\approx 2.08 here, at most ln⁡C\ln C) appears when the input→label map is broken fresh every step — independent resampling or reshuffling labels inside the step: with nothing consistent to learn, the net only learns frequencies. A forgotten zero_grad is shown in PyTorch and automatic differentiation.

Learning-rate range test

The learning rate matters most, and good values sit in a narrow log band. A range test (Smith, 2017) grows η\eta geometrically over KK steps from ηmin⁡\eta_{\min} to ηmax⁡\eta_{\max},

ηk=ηmin⁡(ηmax⁡ηmin⁡)k/(K−1),\eta_k = \eta_{\min}\Big(\frac{\eta_{\max}}{\eta_{\min}}\Big)^{k/(K-1)},

records a smoothed training loss, and stops when that loss exceeds a few times its minimum. The loss stays flat while η\eta is too small, falls fastest in the useful band, and turns up when steps are too large. Pick a rate about 33–10×10\times below the curve’s minimum — the minimum itself is late on a rising schedule, near divergence.

On digits with SGD and momentum 0.90.9, the smoothed loss minimized at η=0.31\eta = 0.31; the recipe suggested 0.030.03–0.10.1. Ten-epoch checks: 0.10.1 reached 0.9780.978 validation accuracy; 1.01.0 collapsed to one class. Redo the test when batch size or optimizer changes; build schedules and warm-up around the peak (Optimizing deep networks).

Reading the curves

Once single batches fit and the rate is set, judge the full run by training and validation loss against epoch:

curves diagnosis try
both high and close underfitting larger model, longer training, higher rate; check for bugs
train near 0, val much higher overfitting more data, augmentation, weight decay, dropout, early stopping
val loss rises, val accuracy holds overconfidence early-stop on loss, label smoothing
flat at ln⁡C\ln C not learning rate, init, labels
spikes or NaN unstable steps lower rate, warm-up, grad clip, loss scaling in fp16

Karpathy’s order: first make the model large enough to overfit the training set — that shows the pipeline can fit — then regularize to trade training loss for validation loss. On all 12571257 digits a large net reached train loss ≈0\approx 0, val loss minimum 0.0730.073 at epoch 2020, then a slow rise to 0.0840.084 with accuracy 0.9830.983: early-stop on the loss. On 100100 images the gap was crude (train 0.0010.001, val ≈0.48\approx 0.48).

Seeds, logs and budget

A difference between runs means something only if the same run repeats. Seed torch, random, numpy and each DataLoader’s Generator before the model is built. Deterministic algorithms help on GPU but do not guarantee bit-identity across versions or hardware. Five seeds here spread validation accuracy by up to four images (0.9700.970–0.9780.978): half a point on one seed proves nothing.

Record every run: commit and dirty tree, full config and seed, data version and split, environment, per-epoch metrics, checkpoints, and one sentence of purpose. Change one thing at a time.

For a dense net, training costs about 6NDE6NDE FLOPs with NN weights: forward ≈ 2N2N per example, backward ≈ 4N4N. That estimate is for dense matmul under this accounting, not a universal CNN counter — one kernel weight is reused at many spatial positions, so forward cost is counted layer-wise through H′W′H'W' (Convolution) or profiled, with backward estimated separately. The digit net’s sixty epochs are ≈3.8⋅1010\approx 3.8\cdot 10^{10} FLOPs; ImageNet-scale ResNet-50 is order 101810^{18}. Spend most of the budget on cheap experiments: debug small, search log-uniformly at random, stop bad runs early, keep seeds for the final comparison.

Course recap and where next

This course asked one question: how do we train deep networks that work on raw high-dimensional inputs, and keep them reliable when we change the task, the compute budget or the attacker?

  • Training module — autograd, losses and regularization, normalization and initialization, optimizers — made the loop trustworthy.
  • Convolutional module — convolution, CNN architectures, detection, segmentation — adapted the architecture to labelled vision.
  • Representations — self-supervised learning and Vision Transformers — learned features without labels and with attention over patches.
  • Robustness and deployment — adversarial examples and model compression — hardened and shrank a trained net.
  • This topic — the debugging recipe — closes the process.

Prerequisites stay where they were: Machine Learning through backpropagation and training deep networks, and Programming in Python. Do not re-learn them here.

Three courses build on what you have now. Natural Language Processing takes sequences and attention into text and language models — ViT and CLIP already stood on that border. Generative Models turns encoders and decoders into VAEs, GANs and diffusion — the autoencoder bottleneck and likelihood thinking start there. Bayesian Methods in Machine Learning puts a distribution over weights instead of a point estimate, when one θ\theta is not enough uncertainty.

The deep-learning course ends here.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • One batch — labels and double softmaxoptional

    NumPy one-batch model on X=I₈. A fixed label shift is memorizable; freshly resampled labels each step keep loss near ln 8; double softmax hits floor log(e+C-1)-1. Self-check in the notebook.

    ~30 min · easier on a computer · The Training in practice topic read; softmax cross-entropy basics.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.