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…

\(0.9^{50} \approx 0.005\). Depth turns a small per-layer factor into an enormous total one, which is why "close to 1" has to be exact enough.

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
  1. 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]\).
  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.
  3. 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\).
  4. 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).
  5. 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 normLayer norm
\(\mu, \sigma\) overthe batch, per featurethe features, per example
Training vs useDifferent: training uses the batch's numbers, use (eval) uses running averages saved during trainingThe same: every example normalizes itself
Whereimage 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?

In training mode a batch of one has mean = itself, so \(x - \mu = 0\) for every feature: the box's last line. 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 curveUsually meansTry
Flat at ln(classes) from step 1Nothing 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 NaNLearning rate too high, or exploding gradientsLower the rate, warm up, clip gradients
A slow straight slideLearning rate too lowRange test, raise the rate
Training falls, validation turns upOverfittingStop early, regularize, more data or augmentation
Both high and flat, far above the goalUnderfitting (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

6. What to carry forward

All lessons: AI from scratch. Andrej Karpathy's "A Recipe for Training Neural Networks" is the classic checklist.

Last updated