rumblr Work in progressWIP

● The AI Primer · Lesson 5 · Part 1: how a language model works

Training deep neural networks

why deep stacks fail to train, and the fixes that made them work

This lesson covers Why deep stacks stop learning, and the fixes inside every transformer block

Members · open during launch 30 min8 figures and diagrams6 interactive

What this is

Why are deep neural networks hard to train?

A deep neural network (an AI model with many stacked layers) can stop learning because the signal it learns from fades or blows up on its way back through the layers. That signal is the gradient, and each layer it passes multiplies it by a factor of its own. Thirty factors below 1 multiply out to almost nothing, the vanishing gradient. Thirty above 1 multiply out to something enormous, the exploding gradient. The fixes hold each layer's factor near 1: a well-chosen activation, the right starting weights, residual connections and normalization, with gradient clipping as a safety net.

Why it matters: You need this when a deep neural network stops improving although its loss only looks slow, when a training run turns to NaN in its first steps, or when a config is full of normalization and initialization settings you want to understand.

At a glance

Key takeaways

  1. Passing the gradient back multiplies it by one factor per layer, so with depth it shrinks (vanishes) or grows (explodes) exponentially.
  2. Initialization sizes the starting weights so each layer passes the signal on at the same size: Xavier for tanh and sigmoid, He (2 / fan-in) for ReLU.
  3. Residual connections add each block's input to its output, which gives the gradient a path back that is multiplied by 1.
  4. Normalization rescales each layer's values into a steady range: BatchNorm across the batch, in convolutional networks, and LayerNorm or RMSNorm within each example, in transformers.
  5. Gradient clipping scales a rare oversized gradient down to a set length without changing its direction.

How it works, from scratch

The problem shows up in the smallest deep network there is, a chain of ten layers that each hold one number, so it is worked there first, by hand. The fixes are then measured on a network of realistic shape: 30 layers of 64 neurons.

Chapter 1

The gradient is a product of slopes

Training sends a learning signal backward from the loss to every weight: the gradient, how much each weight should change (see Neural networks). It travels one layer at a time, and each layer multiplies it by a number of its own, the layer's weight times its activation's slope (derivative). Think of a message passed down a line of ten people, each repeating it at a quarter of the volume they heard. After ten people it is down to about a millionth of its first volume. If each speaks 1.5 times louder instead, it ends up 58 times louder. A factor below 1 at every layer drives the gradient toward zero, the vanishing gradient, and a factor above 1 drives it up without limit, the exploding gradient.

Here are three chains of ten one-number layers, each unit at its steepest point.

chain slope per layer gradient after 10 layers
sigmoid units, weight 1 0.25 0.25¹⁰ = 0.00000095
linear units, weight 1 1 1¹⁰ = 1
linear units, weight 1.5 1.5 1.5¹⁰ = 57.7

Figure 1 · Diagram

Reading it: read right to left, the direction the gradient travels. The loss hands layer 10 a gradient of 1, and every arrow multiplies it by 0.25, a sigmoid's slope at its steepest. Layer 1 receives about a millionth of it, so its weights barely move: the first layers stop learning while the later ones carry on.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the input to the first layer
the output of the last layer
the number of layers 10
a counter over the layers 1 to 10
"multiply together the following, for every layer" (like Σ, but multiplying) ten factors
layer 's weight 1
the activation's slope at layer 's input 0.25
how much the loss changes when changes 1 at the top

In words: "the gradient reaching the first layer is the gradient at the top times every layer's weight times every layer's slope."

With the numbers: .

In Python
def gradient_at_input(w_l, slope, L=10):
    # ∂L/∂h_L: the loss hands the top layer 1
    grad = 1.0
    # Π over the layers: a running product
    for l in range(L):
        # × w_l φ'(z_l)
        grad *= w_l * slope
    return grad
# sigmoid at its steepest
f"{gradient_at_input(1, 0.25):.1e}"  # → '9.5e-07'
# linear, weight 1
gradient_at_input(1, 1)  # → 1.0
# linear, weight 1.5
round(gradient_at_input(1.5, 1), 1)  # → 57.7

New to Σ, ∂ or ‖x‖? The symbols reference decodes each one as a few lines of Python.

In code: chain_gradient builds the chain and passes the gradient back through it. View source

Every fix that follows works the same way: it holds the per-layer factor near 1.

Pass the gradient back one layer at a time, then change the activation, the weight and the number of layers, and watch what reaches layer 1.

Chapter 2

The gradient in a 30-layer network

In the chain each layer had one weight. In a real layer each neuron adds up many inputs, here 64, so the factor per layer depends on three things together: the size of the weights, how many inputs each neuron adds up, and the activation's slope. A 30-layer network with 64 neurons per layer shows what that does. The table gives the gradient at the first layer divided by the gradient at the last, for ReLU with weights of three sizes (the right size is the He rule, which the next chapter derives) and for sigmoid:

setup ratio first / last
ReLU, He initialization ≈ 4 (healthy)
ReLU, weights too small (std 0.01) ≈ 10⁻³⁶ (vanished)
ReLU, weights too large (std 1) ≈ 10²² (exploded)
sigmoid, Xavier initialization ≈ 10⁻¹⁸ (vanished)

Figure 2 · Chart

0 5 10 15 20 25 30 layer (1 = next to the input) 1 0 − 3 6 1 0 − 3 0 1 0 − 2 4 1 0 − 1 8 1 0 − 1 2 1 0 − 6 1 0 0 1 0 6 1 0 1 2 1 0 1 8 1 0 2 4 gradient size ÷ size at layer 30 Gradient flow through 30 layers ReLU, He init ReLU, weights too small ReLU, weights too large sigmoid, Xavier init sigmoid, Xavier, residual

Gradient size at every layer, relative to layer 30: ReLU with He stays near 1, too-small weights dive 36 orders of magnitude, sigmoid dives 18, too-large weights climb 22, and sigmoid with skip connections stays flat

Reading it: the horizontal axis is the layer (1 is next to the input, 30 next to the loss). The vertical axis is the gradient reaching that layer divided by the gradient at layer 30, on a log scale where each gridline is a factor of 10⁶. Every line starts at 1 on the right; read it right to left, the way the gradient travels, and its height at layer 1 is the ratio in the table. The ReLU + He line stays within a factor of about 5 of 1. The too-small line dives about 36 orders of magnitude and the too-large line climbs about 22. The sigmoid line dives 18 orders: Xavier keeps the weights' own gain near 1, so what shrinks the gradient is sigmoid's slope, at most 0.25, about 4× per layer. The dashed line is the same sigmoid network with skip connections, which stays flat; residual connections explain why.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the standard deviation (typical size) of the random starting weights 0.01 (too small)
"fan-in": how many inputs each neuron adds up 64
a sum of random terms grows like , not 8
typical the average slope the activation passes back ≈ 0.7 for ReLU's "half on"

In words: "each layer multiplies the gradient by roughly the weight size, times the square root of how many inputs it sums, times the activation's typical slope."

With the numbers: too small: per layer, and . Too large: per layer, and .

In Python
import math
n_in, typical_slope = 64, 0.7
for sigma_w in (0.01, 1.0):
    # σ_w √n_in · typical φ'
    gain = sigma_w * math.sqrt(n_in) * typical_slope
    # per layer, then over 30 layers
    print(round(gain, 3), f"{gain ** 30:.0e}")  # → 0.056 3e-38 5.6 3e+22

In code: gradient_norms measures the gradient at every layer, and first_to_last_gradient_ratio fills the table. View source

The loss curve does not show any of this. A network whose early layers get no gradient still trains a little, because its late layers learn, so its loss falls slowly instead of stopping. A plot of the gradient's size at each layer shows the problem at once.

Drag the size of the starting weights and find where the gradient neither dies nor explodes, then switch to sigmoid and try again.

Chapter 3

Initialization

With ReLU and nothing else changed, the size of the starting weights alone took the ratio in that table from 10⁻³⁶ to 10²². Initialization is the rule that picks the size: the random starting weights are drawn at a scale where each layer passes on a signal of the same size, forward and backward. Two rules cover the common activations. Each works from the layer's fan-in and, for Xavier, its fan-out (how many outputs the layer has):

scheme rule for the weight standard deviation example
Xavier (Glorot), for tanh/sigmoid √(2 / (fan-in + fan-out)) 100 in, 100 out → √(2/200) = 0.1
He (Kaiming), for ReLU √(2 / fan-in) 50 in → √(2/50) = 0.2

He uses twice Xavier's variance because ReLU zeroes about half its inputs, throwing away half the signal's energy; the factor 2 puts it back.

Figure 3 · Diagram

Reading it: start from the activation on the left. ReLU and GELU take the He rule; tanh, sigmoid and linear units take Xavier. Both arrows end in the same box, because both rules aim at a layer that neither shrinks nor grows what passes through it.

Figure 4 · Chart

0 5 10 15 20 25 30 layer (0 = the input) 1 0 − 4 0 1 0 − 3 2 1 0 − 2 4 1 0 − 1 6 1 0 − 8 1 0 0 1 0 8 1 0 1 6 1 0 2 4 typical activation size (RMS) Forward signal through 30 layers ReLU, He init ReLU, weights too small ReLU, weights too large sigmoid, Xavier init

Forward signal size at every layer: ReLU with He stays near 1, too-small weights fade to 10⁻³⁸, too-large weights grow to 10²², and sigmoid holds flat near 0.5 even though its gradient vanishes

Reading it: this chart shows the forward direction: the typical size of the values entering each layer, on a log scale. With He initialization the ReLU network's signal stays near 1 for all 30 layers. With weights too small it fades to nothing within a few layers, and with weights too large it grows by about 5.6× per layer. For the three ReLU lines the gradient chart mirrors this one, because the same weights scale both directions. The sigmoid line breaks the mirror. Its signal holds steady near 0.5 for all 30 layers, since sigmoid's outputs sit around 0.5 whatever comes in, yet its gradient lost 18 orders of magnitude. The forward pass only sends values through sigmoid, while the backward pass multiplies by sigmoid's slope, at most 0.25, at every layer. A healthy forward signal does not prove a healthy gradient, so check both.
The formula and its symbols

Symbols

Symbol Meaning here In the example
one neuron's weighted sum
variance: the average squared distance from the mean (standard deviation squared)
one weight
one input to the neuron (the previous layer's output)
the average of ("E" for expected value, the long-run average) half the pre-ReLU variance
fan-in 50
"therefore"

In words: "the variance of a neuron's sum is the number of inputs times the weight variance times the average squared input; ReLU halves that average, so to keep the variance steady the weights need variance 2 over the fan-in."

With the numbers: , so the standard deviation is .

In Python
import math
n_in = 50
# Var(w) = 2 / n_in, for ReLU
var_w = 2 / n_in
# the variance, then the standard deviation
var_w, round(math.sqrt(var_w), 3)  # → (0.04, 0.2)
# Xavier for comparison: 100 in, 100 out
round(math.sqrt(2 / (100 + 100)), 3)  # → 0.1

In code: init_std gives each rule's standard deviation, and forward_signal_rms measures the forward signal. View source

Frameworks apply a rule like this to their own layers: PyTorch's nn.Linear draws its starting weights from a range scaled by the fan-in (a Kaiming-style uniform init). A layer you write yourself gets no such rule unless you add it, and without it a deep stack can fail to train with no error to say why.

Pick an activation and a rule, change the number of neurons per layer, and compare the signal going forward with the gradient coming back.

Chapter 4

Residual connections

Initialization sets the weights' size, but it cannot change the activation's slope: the sigmoid network with Xavier weights still lost 18 orders of magnitude. A residual connection (or skip connection) gets around the slope. A block of layers computes a correction and adds it to its input, instead of replacing the input. On the way back, the gradient then has a path around every block that multiplies it by 1, whatever the block's own slope. That path is what keeps the dashed sigmoid line in the gradient chart flat.

Take ten blocks, each with a slope of 0.025 of its own:

per-block factor after 10 blocks
plain: h ← f(h) 0.025 0.025¹⁰ ≈ 9.5 × 10⁻¹⁷
residual: h ← h + f(h) 1 + 0.025 1.025¹⁰ = 1.28

Figure 5 · Diagram

Reading it: follow the input from the top. One copy goes through the block, the other goes straight around it, and the two are added. Going backwards, the gradient splits the same way: one part flows back through the block and may shrink, the other passes through the "+" untouched. The untouched part is the "1" in 1 + 0.025, and it means some gradient reaches the early layers however deep the stack is.
The formula and its symbols

Symbols

Symbol Meaning here In the example
the signal entering block
what the block computes (its layers and activation) slope 0.025
how the block's output changes with its input
the identity: "1" for a single number, the do-nothing matrix for vectors 1
the block's own slope 0.025

In words: "the output is the input plus a correction, so its slope is one plus the correction's slope, never just the correction's slope."

With the numbers: instead of .

In Python
# each block's own slope
dF_dh = 0.025
plain, residual = 1.0, 1.0
for l in range(10):
    # h ← F(h): the slope is just ∂F/∂h
    plain *= dF_dh
    # h ← h + F(h): the slope is I + ∂F/∂h
    residual *= 1 + dF_dh
f"{plain:.1e}", round(residual, 2)  # → ('9.5e-17', 1.28)

Figure 6 · Chart

2.5 5.0 7.5 10.0 12.5 15.0 17.5 20.0 number of blocks 1 0 − 2 9 1 0 − 2 4 1 0 − 1 9 1 0 − 1 4 1 0 − 9 1 0 − 4 1 0 1 gradient reaching the input Skip connections keep the gradient alive plain: × 0.025 per block residual: × 1.025 per block

Gradient reaching the input as blocks are stacked: without skip connections it falls 40× per block to 10⁻¹⁶ after 10 blocks, with them it stays near 1

Reading it: the horizontal axis counts stacked blocks, and the vertical axis, on a log scale, is how much gradient survives the trip back to the input (1 means all of it). The plain line drops by a factor of 40 with every block, a straight line down on a log scale, and after 10 blocks it is at 10⁻¹⁶, so the early layers receive almost nothing. The residual line stays near 1 at every depth, because each block's "1 +" passes the gradient through.

In code: residual_chain_gradient multiplies the per-block factors, with or without the skip path. View source

ResNet (2015) used residual connections to train networks over 100 layers deep, and every transformer wraps both its attention and its feed-forward sub-layers in one (see The transformer). The skip path has a cost. Each block adds its correction on top of what it received, so the signal grows with depth: a 30-layer residual ReLU stack here grows its gradient about 7 million times.

Switch the skip connections off one block at a time and watch what reaches the input.

Chapter 5

Normalization

That growth is why residual connections come paired with normalization. A normalization layer re-centres and rescales the numbers passing through it into a steady range, so no layer is swamped by huge or tiny values, however many corrections have piled up. The kinds differ in which numbers each value is compared with, the way a teacher can grade on a curve in two ways. Batch normalization (BatchNorm) curves each question across the whole class: your score on question 3 is compared with everyone else's score on question 3, so your grade depends on who else sat the exam. Layer normalization (LayerNorm) curves each student across their own answers, so your grade depends only on you. RMSNorm is LayerNorm without the step that subtracts the average.

All three, on numbers small enough to check:

  • BatchNorm, batch [[1, 2], [3, 6]]: column means (2, 4), standard deviations (1, 2), so the output is [[−1, −1], [1, 1]]. The value 1 becomes −1.22 in the batch (1, 3, 5) but −0.93 in the batch (1, 3, 11).
  • LayerNorm, one row (1, 2, 3, 4): mean 2.5, standard deviation 1.118, so the output is (−1.342, −0.447, 0.447, 1.342), whatever else is in the batch.
  • RMSNorm, the same row: root-mean-square √((1+4+9+16)/4) = 2.739, so the output is (0.365, 0.730, 1.095, 1.461). No mean is subtracted.

Figure 7 · Diagram

Reading it: the same grid of activations can be normalized in two directions. BatchNorm takes statistics down each column, across the examples, so every example's output depends on its batch-mates. LayerNorm and RMSNorm take statistics along each row, within a single example, so an example is normalized the same way alone or in any batch.
The formula and its symbols

Symbols

Symbol Meaning here In the example
one example's activations (a row) (1, 2, 3, 4)
number of features in the row 4
the -th feature
"mu", the row's mean 2.5
"sigma squared", the row's variance 1.25
a tiny number so we never divide by zero
"gamma, beta", a learned scale and shift per feature, so the network can undo the normalization if it helps 1 and 0 at the start
multiply feature by feature

In words: "LayerNorm subtracts the row's mean, divides by its standard deviation, then applies a learned scale and shift; RMSNorm skips the mean and just divides by the root-mean-square."

With the numbers: LayerNorm: . RMSNorm: .

BatchNorm is the column version of the same formula, with and computed across the batch for each feature.

In Python:

import math
x = [1, 2, 3, 4]
d, eps, gamma, beta = len(x), 1e-5, 1.0, 0.0
# the row's mean
mu = sum(x) / d
# σ², the row's variance
var = sum((x_i - mu) ** 2 for x_i in x) / d
mu, var  # → (2.5, 1.25)
# LayerNorm
[round(gamma * (x_i - mu) / math.sqrt(var + eps) + beta, 3) for x_i in x]  # → [-1.342, -0.447, 0.447, 1.342]
# √((1/d) Σ x_i² + ε)
rms = math.sqrt(sum(x_i ** 2 for x_i in x) / d + eps)
round(rms, 3)  # → 2.739
# RMSNorm: no mean subtracted
[round(gamma * x_i / rms, 3) for x_i in x]  # → [0.365, 0.73, 1.095, 1.461]

In code: batch_norm, layer_norm and rms_norm compute the three examples. View source

Transformers use LayerNorm or RMSNorm rather than BatchNorm. Their sequences have different lengths, a batch at inference is often a single example, and an example's output must not depend on its batch-mates. Llama and other recent language models use RMSNorm, which is cheaper and works as well, and place it before each sub-layer ("pre-norm"), which keeps the residual path clean and trains more stably. BatchNorm is used in convolutional networks trained on large batches: ResNet puts one after every convolution.

Change another example's numbers and watch whether your own result moves under each kind of normalization.

Chapter 6

Gradient clipping

Initialization, residual connections and normalization keep the per-layer factor near 1, but one unusual batch can still produce a spike: a gradient far larger than usual, and a weight update to match. Gradient clipping caps the update. It measures all the gradients in the network together as one length (their global norm), and when that length is over a set limit it scales every gradient down by the same factor, so the update keeps its direction and loses only its size.

The network with weights too large, from the 30-layer chart, has gradients whose combined length is about 8 × 10⁴⁶. Clipped at a limit of 1, the update has length 1 and points the same way.

Figure 8 · Diagram

Reading it: follow the arrows from the left. All the layers' gradients are measured together as one long list; if the list is longer than the limit, every entry is scaled by the same factor, and otherwise nothing changes.
The formula and its symbols

Symbols

Symbol Meaning here In the example
every weight gradient, as one long list the 30 layers' gradients
its length: square every entry, add them up, take the square root enormous
the limit 1

In words: "if the gradient is longer than the limit, rescale it to the limit."

With the numbers: in the too-large network ; with every entry is multiplied by about and the new length is exactly 1. For a case small enough to check by hand, see Optimizers, where (3, 4) is clipped to (0.6, 0.8).

In Python
import math
# a stand-in with the same enormous length
g = [4.8e46, 6.4e46]
# ‖g‖
norm = math.sqrt(sum(g_i ** 2 for g_i in g))
f"{norm:.0e}"  # → '8e+46'
c = 1
# min(1, c / ‖g‖)
scale = min(1, c / norm)
f"{scale:.0e}"  # → '1e-47'
# the new length
round(math.sqrt(sum((g_i * scale) ** 2 for g_i in g)), 6)  # → 1.0

In code: layer_gradients collects the too-large network's gradients, and global_norm_after_clipping clips them. View source

Clipping makes a rare spike harmless. It does not fix a network that explodes on every step: that needs better initialization or normalization, and clipping would only hide it. GPT-3 and Llama 2 both trained with a clipping limit of 1.0.

Drag the arrow past the circle and watch it scaled back onto it, then compare a run with one bad batch with a run that explodes on every step.

Test yourself

6 questions

Answer each one out loud or on paper before you open it.

Question 1Why do gradients vanish in deep sigmoid networks?Think it through, then reveal

Backprop multiplies the gradient by each layer's slope, and sigmoid's slope is at most 0.25. Thirty layers can shrink it by 0.25³⁰, so early layers stop learning.

Question 2What's the difference between Xavier and He initialization?Think it through, then reveal

Both choose the weight variance so signal size is preserved. Xavier uses 2 / (fan-in + fan-out), suited to symmetric activations like tanh. He uses 2 / fan-in, doubling the variance to compensate for ReLU zeroing half its inputs.

Question 3How do residual connections fix vanishing gradients?Think it through, then reveal

The block's output is input + F(input), so its derivative is 1 + F′. The gradient always has an identity path back to early layers that isn't multiplied by small slopes.

Question 4Why do transformers use LayerNorm instead of BatchNorm?Think it through, then reveal

BatchNorm's statistics come from the batch, which breaks for variable-length sequences, tiny or single-example batches at inference, and makes an example's output depend on its batch-mates. LayerNorm normalizes each token across its own features, independent of the batch.

Question 5What is RMSNorm and why do modern LLMs use it?Think it through, then reveal

LayerNorm without the mean subtraction and shift: divide by the root-mean-square and apply a learned scale. It's cheaper and trains as well.

Question 6Gradient clipping or better initialization: which fixes exploding gradients?Think it through, then reveal

Initialization (and normalization) fix the cause, keeping per-layer gain near 1. Clipping is a safety net for occasional spikes.

Primary sources

The papers behind this lesson

Bengio, Simard & Frasconi, Learning long-term dependencies with gradient descent is difficult (IEEE Trans. Neural Networks, 1994): Proved that gradients shrink or explode exponentially through many steps, the root of the problem.

The paper

Glorot & Bengio, Understanding the difficulty of training deep feedforward neural networks (AISTATS 2010): Diagnosed saturation and derived Xavier initialization to keep variance steady across layers.

The paper

He, Zhang, Ren & Sun, Delving Deep into Rectifiers (2015): Derived the 2 / fan-in (He) initialization for ReLU networks.

The paper

He, Zhang, Ren & Sun, Deep Residual Learning for Image Recognition (2015): Introduced residual connections and trained networks over 100 layers deep.

Read on rumblr →The paper

Ioffe & Szegedy, Batch Normalization (2015): Normalized activations across the batch, allowing much higher learning rates.

The paper

Ba, Kiros & Hinton, Layer Normalization (2016): Normalized within each example instead, independent of batch size; the version transformers use.

Read on rumblr →The paper

Zhang & Sennrich, Root Mean Square Layer Normalization (2019): Dropped LayerNorm's mean subtraction for a cheaper normalization with the same benefit.

The paper

Xiong et al., On Layer Normalization in the Transformer Architecture (2020): Showed why putting the norm before each sub-layer (pre-norm) trains more stably.

The paper

Researcher's shelf

Further reading

  • CS231n notes, Neural Networks Part 2 (initialization, batch norm): https://cs231n.github.io/neural-networks-2/
  • Michael Nielsen, Why are deep neural networks hard to train?: http://neuralnetworksanddeeplearning.com/chap5.html
  • Goodfellow, Bengio & Courville, Deep Learning, ch. 8 (optimization for training deep models): https://www.deeplearningbook.org/contents/optimization.html
  • PyTorch nn.init docs: https://pytorch.org/docs/stable/nn.init.html
  • PyTorch nn.LayerNorm: https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html

About this lesson. This is the illustrated edition of a lesson from the open-source AI Primer ↗. Its text, figures and numbers are generated from the Primer's source at commit f8b43d1, so the two always agree: the explanation, the code that builds it and the tests that prove it.