AI from scratch · Toolkit 4 · Stage 4: the engineer's toolkit
Making deep nets train
Stack twenty layers, press train, and very often nothing happens: the loss sits at its starting value, or turns into NaN. For years this is why deep networks "didn't work". The fixes turned out to be a handful of small ideas, now in every model: start the weights at the right size, keep each layer's numbers on a steady scale, switch off random neurons while training, and give the signal a shortcut around each layer. This lesson shows why each one is needed, then teaches you to read a loss curve like a doctor reads a chart.
1. Signals that vanish or explode
Push 200 random inputs through 20 layers of 128 neurons, each layer a random matrix and a bend, and watch the spread (standard deviation) of the numbers at each layer. Each layer multiplies the spread by roughly the same factor. A factor of 0.7 twenty times is 0.0008; 1.3 twenty times is 190. Only a factor near 1 survives depth.
When the signal shrinks to nothing on the way forward, the blame shrinks the same way on the way back (chapter 4: backprop multiplies by the same weights), and the early layers never learn: vanishing gradients. When it grows, the loss overflows: exploding gradients. The cure starts with the first numbers you put in the weights.
\[ \text{He initialization (ReLU):}\quad w \sim \mathcal{N}\!\left(0,\ \tfrac{2}{n_{\text{in}}}\right) \qquad \text{Xavier (tanh):}\quad w \sim \mathcal{N}\!\left(0,\ \tfrac{1}{n_{\text{in}}}\right) \]
PyTorch's nn.Linear uses a uniform version scaled by \(1/\sqrt{n_{\text{in}}}\) by default, which is why stacks of a few layers just work; for deep ReLU stacks, nn.init.kaiming_normal_ is He.
Each layer multiplies the spread by 0.9. After 50 layers it's about…
- 45
- 0.005
- 0.9
Each layer multiplies the signal's spread by about the same factor, so depth needs that factor to be almost exactly 1, and the starting weights set it.
Why He uses 2/n: the ReLU throws away half
- One neuron computes \(z = \sum_{i=1}^{n} w_i x_i\). With independent weights of mean 0, the variance of a sum is the sum of the variances: \(\operatorname{Var}(z) = n \operatorname{Var}(w)\, \mathbb{E}[x^2]\).
- \(z\) is symmetric around 0, and ReLU sets the negative half to 0. So \(\mathbb{E}[\operatorname{ReLU}(z)^2] = \tfrac12 \operatorname{Var}(z)\): half the energy is gone.
- That ReLU output is the next layer's \(x\). For \(\mathbb{E}[x^2]\) to stay the same from layer to layer we need \(\tfrac12 \cdot n \operatorname{Var}(w) = 1\).
- So \(\operatorname{Var}(w) = 2/n\). With \(1/n\) instead, each layer halves the energy: 20 layers divide it by about a million (the widget's \(1/\sqrt n\) setting: spread about 0.001 at layer 20).
- tanh keeps both halves and is close to the identity near 0, so its natural choice is \(1/n\) (Xavier, which averages \(n_{\text{in}}\) and \(n_{\text{out}}\)).
2. Normalization: reset the scale at every layer
Good initialization sets the scale at the start, but training moves the weights, and the scale drifts. Normalization fixes it on every forward pass: shift and scale the numbers to mean 0 and spread 1, then let the network re-scale them with two learned numbers per feature, \(\gamma\) and \(\beta\).
\[ \hat x = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}}, \qquad y = \gamma\, \hat x + \beta \]
| Batch norm | Layer norm | |
|---|---|---|
| \(\mu, \sigma\) over | the batch, per feature | the features, per example |
| Training vs use | Different: training uses the batch's numbers, use (eval) uses running averages saved during training | The same: every example normalizes itself |
| Where | image networks (CNNs, chapter 6) | language networks (transformers, chapter 7; RNNs), small batches |
A model with batch norm scores 92% in validation, but in the app (one photo at a time) its answers are nonsense. The most likely bug?
- The photos are too small
- The model was saved wrong
- The app forgot
model.eval(): each single photo is normalized by its own mean, which erases it
model.eval() switches batch norm (and dropout) to their use-time behavior.Normalization resets every layer's numbers to mean 0 and spread 1 on each pass, then lets two learned numbers per feature set the scale it actually wants.
3. Dropout: train a crowd, use the average
During training, dropout sets each neuron's output to 0 with probability \(p\) (often 0.1 to 0.5) and scales the survivors by \(1/(1 - p)\) so the expected total stays the same. No neuron can rely on one particular partner being there, so the network learns redundant, spread-out features, which overfit less (chapter 11). In use (model.eval()), nothing is dropped: it's like averaging the predictions of all the thinned networks seen in training.
Dropout switches random neurons off while training, so none can lean on a particular partner, and scales the rest so the totals match use time.
4. Residual connections: a shortcut around every layer
A residual block outputs its input plus a correction: \(y = x + f(x)\). Chapter 7's transformer blocks are built this way, and so is ResNet, which first trained networks over 100 layers deep in 2015. Two things happen. The signal always has a path that skips the layer, so it can't vanish. And in backprop, the derivative of \(x + f(x)\) is \(1 + f'(x)\): the blame reaching the top flows back to the bottom unchanged, plus whatever the layers add.
A residual block adds a correction to its input instead of replacing it, so both the signal and the blame always have a path straight through.
5. The loss-curve doctor
A loss curve is the main thing you get to watch while training. Each pattern below has a cause and a standard fix. Look at the chart, pick the diagnosis. The score is just for you.
training loss validation loss ln(10) ≈ 2.3, the loss of uniform guessing over 10 classes
| The curve | Usually means | Try |
|---|---|---|
| Flat at ln(classes) from step 1 | Nothing is learning: a bug (labels shuffled apart from inputs, frozen weights, no optimizer.step()) | Overfit one batch (training in PyTorch) |
| Falls, then jumps or turns NaN | Learning rate too high, or exploding gradients | Lower the rate, warm up, clip gradients |
| A slow straight slide | Learning rate too low | Range test, raise the rate |
| Training falls, validation turns up | Overfitting | Stop early, regularize, more data or augmentation |
| Both high and flat, far above the goal | Underfitting (high bias) | Bigger model, train longer, better features |
A loss curve is a diagnosis: flat at ln(classes) is a bug, spikes are a rate that's too high, a slow slide is one that's too low, and a gap is overfitting.
Where it breaks: when the fixes cause trouble
- Batch norm with tiny batches. With 2 examples per batch, each batch's mean and spread are mostly noise, and training gets unstable. Detection and segmentation models, which fit only a few big images per GPU, switch to group norm or layer norm, which don't depend on the batch.
- Forgetting the mode switch. Dropout left on at test time makes every prediction random; batch norm left in training mode normalizes each example by itself. Both are one missing
model.eval(), and both look like "the model got worse after deployment". - Initialization can't save a saturated bend. A sigmoid or tanh layer whose inputs are large sits on its flat tails, where the slope is near 0, whatever the starting scale. That's one reason hidden layers use ReLU-like bends and keep normalization before them.
6. What to carry forward
- Initialization: He (\(2/n_{\text{in}}\)) for ReLU, Xavier (\(1/n_{\text{in}}\)) for tanh: keeps the per-layer factor near 1.
- Normalization: batch norm in CNNs (eval mode uses saved averages), layer norm in transformers.
- Dropout while training, scaled by \(1/(1 - p)\); off in eval.
- Residuals: \(y = x + f(x)\) gives the signal and the gradient a straight path.
- Read the curve: flat at ln(classes), spikes, slow slide, a widening gap. And
model.train()/model.eval(), always.
All lessons: AI from scratch. Andrej Karpathy's "A Recipe for Training Neural Networks" is the classic checklist.
Last updated