Lesson 4.1: Residual connections and layer normalisation
See why deep stacks are hard to train, how residual connections keep gradients alive, and how layer normalisation keeps each layer's input in a steady range.
By the end of this lesson you will be able to explain why a deep stack of layers makes gradients shrink, show how a residual connection fixes it, write layer normalisation with its gradient, and say where a transformer places it and why. You will show that a gradient pushed back through 4, 16, 64 and 256 plain layers shrinks to 0.378, 0.210, 0.0793 and 0.00639 of its size, while the same layers with a residual connection leave it at 1.0, 0.99, 1.21 and 2.0, that a layer norm output has mean 0 and spread 1 for every vector whatever its scale or position, with a gradient that matches a numerical one to eight digits, and that the spread of a residual stream grows as the square root of one plus the number of sublayers (1.42, 2.24, 4.1 and 8.09 for 1, 4, 16 and 64). You need Python and NumPy. The code of this lesson does not depend on earlier files.
Module 3 built attention, and our models so far have used one attention layer. A real language model stacks many. A stack of layers is only useful if it can be trained, and that is not automatic: the deeper a plain stack, the harder it is to train. Two ideas, both short, solve it, and every transformer uses both. This lesson explains them. The next three build the rest of the block and assemble it into a GPT.
Why depth is hard
Training sends a gradient from the loss back through every layer. By the chain rule, the gradient at the input of the stack is the gradient at the output multiplied by the Jacobian of each layer in turn. A Jacobian is the matrix of how each output of a layer changes with each of its inputs. A product of many matrices is a product of many numbers in disguise. If the typical layer shrinks a gradient a little, say by a factor of 0.9, then after 64 layers it has shrunk by 0.9 to the power 64, which is about 0.0012. The early layers receive a gradient a thousand times smaller than the late ones, and learn a thousand times more slowly. If the typical layer enlarges it by 1.1, the product after 64 layers is about 445, and training blows up. Only a gain of exactly 1 survives, and no ordinary layer has it.
We can measure this. The code pushes a vector through L layers, each of the form tanh(W h) with a random matrix W, and then sends a gradient of length 1 back from the output. It reports the length of the gradient that arrives at the input.
python
import numpy as np
def gradientratio(L, residual, d=64, branch=0.1, seed=0):
"""Push a vector through L layers, then pull a gradient back. Return |grad at input| / |grad at output|."""
rng = np.random.defaultrng(seed)
h = rng.standardnormal(d)
jac = [] # the Jacobian of every layer, at the point we reach
for in range(L):
W = rng.standardnormal((d, d)) / np.sqrt(d)
pre = W @ h
local = (1 - np.tanh(pre) 2)[:, None] W # d tanh(Wh) / dh
if residual:
jac.append(np.eye(d) + branch local)
h = h + branch np.tanh(pre)
else:
jac.append(local)
h = np.tanh(pre)
g = rng.standardnormal(d)
g /= np.linalg.norm(g) # a unit gradient at the output
for J in reversed(jac):
g = J.T @ g
return np.linalg.norm(g)
for L in (4, 16, 64, 256):
print(L, "plain", f"{gradientratio(L, False):.2e}", " residual", round(gradientratio(L, True), 2))
The first column is the plain stack, and the last is the same layers with a residual connection:
Layers · Plain stack · With residual connections4 · 0.378 · 1.00
16 · 0.210 · 0.99
64 · 0.0793 · 1.21
256 · 0.00639 · 2.00
## The residual connection
The fix is to give the gradient a path that does nothing to it. A residual connection adds a layer's input to its output:
y = x + f(x)
where f is the layer's own computation. The Jacobian of y with respect to x is the identity matrix plus the Jacobian of f. The identity part passes the gradient through unchanged. Through a hundred such layers, a gradient has a straight road from the output to the input along the identity paths, plus whatever each layer adds. That is what the right-hand column shows: the gradient stays near 1 at every depth.
In the code, the residual layers are h + 0.1 tanh(W h). The factor 0.1 makes each layer a small change to its input, as real transformer layers are at the start of training. Without it, each layer would double the stream, and the product would explode. The slight growth at 256 layers (2.0) is the sum of many small contributions along many paths.
There is a second way to see a residual connection, which is how people think about transformers. Picture a residual stream: a vector of d numbers for each token that runs through the whole model from the embedding at the bottom to the output at the top. Each layer reads the stream, computes something and adds its result back. Nothing is overwritten. Attention layers move information between tokens, feed-forward layers transform it within a token, and each leaves its contribution on the stream for later layers to read. The stream is the model's shared working memory. In Lesson 3.2, the line H1 = H0 + Oc @ Wo was exactly this: the attention layer adding to the stream.
A new problem: the stream grows
The residual stream solves one problem and makes another. Every layer adds to it. If each addition has about the same size, the stream grows with depth. For independent additions, the spread grows as the square root of the number of additions. A transformer block adds twice (attention and then feed-forward), so a model with 12 blocks has added 24 times. We can watch it.
python
import numpy as np
rng = np.random.defaultrng(0)
d, n = 256, 2000
def layernorm(x):
return (x - x.mean(-1, keepdims=True)) / np.sqrt(x.var(-1, keepdims=True) + 1e-5)
x = rng.standardnormal((n, d)) # the residual stream: n vectors, spread 1
for k in range(1, 65):
W = rng.standardnormal((d, d)) / np.sqrt(d) # a sublayer that returns a spread-1 vector from a spread-1 input
x = x + layernorm(x) @ W # pre-norm: the sublayer reads a normalised copy and adds its output
if k in (1, 4, 16, 64):
print(k, "sublayers: spread of the stream", round(float(x.std()), 2), " sqrt(1+k) =", round(float(np.sqrt(1 + k)), 2))
The output:
1 sublayers: spread of the stream 1.42 sqrt(1+k) = 1.41
4 sublayers: spread of the stream 2.24 sqrt(1+k) = 2.24
16 sublayers: spread of the stream 4.1 sqrt(1+k) = 4.12
64 sublayers: spread of the stream 8.09 sqrt(1+k) = 8.06
The measured spread follows the square root of one plus the number of sublayers: 1.42 after 1, 2.24 after 4, 4.1 after 16 and 8.09 after 64. (Each sublayer here reads a normalised copy of the stream and returns a vector of spread 1.) The stream is not wrong to grow, but a layer that reads it now sees inputs of very different scales at different depths. A sublayer tuned for a stream of spread 1 receives one of spread 8. Its softmax saturates, its activations misbehave and the training settings that suited the early layers do not suit the late ones.
Layer normalisation
The fix for the second problem is to normalise a layer's input, so that whatever the scale of the stream, the layer always sees vectors of the same size. The version used in transformers is layer normalisation, introduced by Ba, Kiros and Hinton in 2016. For each token's vector x of d numbers, separately, it:
1. subtracts the mean of its d numbers,
2. divides by their spread (the standard deviation),
3. multiplies by a learned gain g and adds a learned offset b, each a vector of d numbers.
xhat = (x − mean) ÷ sqrt(variance + eps), then y = g × xhat + b.
The small constant eps (here 1e-5) prevents a division by zero for a constant vector. At the start, g is all ones and b all zeros, so the output is simply the standardised vector. The code below writes the forward pass and the backward pass, and checks them.
python
import numpy as np
def lnfwd(x, g, b, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
xhat = (x - mu) / np.sqrt(var + eps)
return g xhat + b, (xhat, g, var, eps)
def lnbwd(dy, cache):
xhat, g, var, eps = cache
dxhat = dy g
dx = (dxhat - dxhat.mean(-1, keepdims=True) - xhat (dxhat xhat).mean(-1, keepdims=True)) / np.sqrt(var + eps)
return dx, (dy xhat).reshape(-1, xhat.shape[-1]).sum(0), dy.reshape(-1, xhat.shape[-1]).sum(0)
rng = np.random.defaultrng(0)
x = rng.standardnormal((3, 8)) 5 + 2 # three vectors, badly scaled and off-centre
g, b = np.ones(8), np.zeros(8)
y, cache = lnfwd(x, g, b)
print(np.round(y.mean(axis=-1), 6), np.round(y.std(axis=-1), 4)) # every row: mean 0, spread 1
print(np.allclose(lnfwd(10 x, g, b)[0], y, atol=1e-4)) # a rescaled input gives the same output
print(np.allclose(lnfwd(x + 7, g, b)[0], y)) # so does a shifted one
gradient check on a random loss
w = rng.standardnormal((3, 8))
loss = lambda x, g, b: (lnfwd(x, g, b)[0] w).sum()
dx, dg, db = lnbwd(w, cache)
eps = 1e-6
xp, xm = x.copy(), x.copy(); xp[1, 3] += eps; xm[1, 3] -= eps
print(dx[1, 3], (loss(xp, g, b) - loss(xm, g, b)) / (2 eps))
gp, gm = g.copy(), g.copy(); gp[5] += eps; gm[5] -= eps
print(dg[5], (loss(x, gp, b) - loss(x, gm, b)) / (2 eps))
RMS norm: skip the mean, divide by the root of the mean square
def rmsnorm(x, g, eps=1e-5):
return g x / np.sqrt((x 2).mean(axis=-1, keepdims=True) + eps)
x0 = x - x.mean(axis=-1, keepdims=True) # centre first, then the two agree
print(np.allclose(rmsnorm(x0, g), lnfwd(x0, g, b)[0], atol=1e-4))
The output tells us four things.
[-0. 0. -0.] [1. 1. 1.]
True
True
-0.0532679 -0.0532679
-0.6567165 -0.6567165
True
Every row has mean 0 and spread 1. The vectors were badly scaled (spread 5) and off-centre (mean 2). The output is standard.
A rescaled input gives the same output. Multiplying x by 10 changes nothing (True). So does adding 7. Layer norm discards the size and the position of the vector, and keeps its shape.
The gradients are right. The analytic gradient with respect to one entry of x and one entry of g match the numerical ones to eight digits. The backward formula is dx = (dxhat - mean(dxhat) - xhat mean(dxhat xhat)) / sqrt(var + eps): it removes from the incoming gradient the parts that run along the two directions that the normalisation ignores, the constant direction and the direction of x itself.
RMS norm agrees when the vector is centred. The last check compares layer norm with a cheaper variant, RMS norm (Zhang and Sennrich, 2019), which skips the mean and the offset and divides only by the root of the mean of squares. Many recent models use it. For a vector whose mean is already zero, the two are the same (True).
Why not normalise over the batch
Image models of the early 2010s used batch normalisation, which takes the mean and spread of each feature across the examples in a batch. That does not suit language models. A batch of sequences has different lengths and padding. At generation time there may be a single sequence, and the statistics of a batch of one are meaningless. Batch norm needs running averages to use at test time, which add complexity and mismatch. Layer norm uses only the vector in front of it, in training and at generation alike.
Where to put the norm
Two arrangements are in use, and the difference matters.
Post-norm, the arrangement of the original transformer paper of 2017: add first, then normalise.
x = LayerNorm(x + Sublayer(x))
Pre-norm, used by GPT-2 and almost every model since: normalise the input of the sublayer, and add the output to an un-normalised stream.
x = x + Sublayer(LayerNorm(x))
In pre-norm, the residual stream is never normalised on its way up. It remains a plain sum, so the identity path for the gradient is untouched, and each sublayer sees a normalised view of it. That is the combination this lesson has argued for: the clean road for the gradient and the steady input for the layer. In post-norm, the normalisation sits on the main road, and the gradient has to pass through it at every layer. Xiong and colleagues (2020) analysed this and showed that post-norm makes training sensitive to the learning rate, so that it needs a careful warm-up. Lesson 4.3 measures it: at a high learning rate and 8 layers, a pre-norm model trains while a post-norm model does not. One more norm is placed after the last block, before the output matrix, so that the output sees a normalised vector as well.
Key takeaways
The gradient at the bottom of a deep stack is the product of one Jacobian per layer. If the typical gain is below 1 it vanishes, and if above 1 it explodes. A gain of 0.9 over 64 layers gives 0.0012.
In a plain stack of random layers, the gradient reaching the input was 0.378, 0.210, 0.0793 and 0.00639 of its size after 4, 16, 64 and 256 layers.
A residual connection, y = x + f(x), gives the gradient an identity path. With it, the same layers left the gradient at 1.0, 0.99, 1.21 and 2.0.
The residual stream is a vector per token that every layer reads from and adds to. Nothing is overwritten.
Additions make the stream grow as the square root of one plus the number of sublayers: 1.42, 2.24, 4.1 and 8.09 for 1, 4, 16 and 64.
Layer normalisation standardises each token's vector (mean 0, spread 1) and then applies a learned gain and offset. It ignores the scale and position of its input, and works the same in training and generation, since it uses only one vector.
Its backward pass removes the components of the gradient along the constant direction and along x. It matches numerical gradients to eight digits.
RMS norm skips the mean and the offset, and equals layer norm for centred vectors.
Pre-norm (x + Sublayer(LayerNorm(x))) keeps the identity path clean and is the standard. Post-norm puts the norm on the path and is more sensitive to the learning rate.
Common mistakes
Normalising over the wrong axis. Layer norm acts on the feature axis of each token. Normalising across tokens or across the batch is a different operation.
Forgetting the learned gain and offset. Without them, the layer cannot undo the standardisation where it should.
Dividing by zero. Without eps, a constant vector gives NaN.
Putting the norm on the residual path. In pre-norm, only the input of the sublayer is normalised, not the stream that is added to.
Residual layers that are not small at the start. If each branch begins with a large output, the stream explodes with depth. Lesson 4.4 shows how initialisation prevents it.
Mismatching the shapes in a residual add. The sublayer must return the same shape as its input.
Assuming a residual connection is free. It adds the input to the output, and it keeps the input alive in memory for the backward pass.
Check yourself
1. Every layer of a stack multiplies the gradient by 0.8. What is the gradient after 20 layers?
0.8²⁰ = 0.0115, about 1.2% of its original size.
2. What is the derivative of y = x + f(x) with respect to x, and why does it help?
It is 1 plus the derivative of f (the identity matrix plus the Jacobian of f, for vectors). The identity part passes the gradient through unchanged, so it cannot vanish through the layer.
3. Layer-normalise the vector [1, 2, 3, 4], ignoring eps and using the learned gain 1 and offset 0.
Mean 2.5, variance 1.25, spread 1.118. The result is [−1.342, −0.447, 0.447, 1.342].
4. After 100 sublayers that each add a vector of spread 1 to a stream of spread 1, what is the spread of the stream?
The square root of 1 + 100, about 10.05.
5. Why does layer norm suit language models better than batch norm?
It uses only each token's own vector, so it behaves the same with a batch of one, with padding and at generation time. Batch norm needs batch statistics and running averages.
6. In pre-norm, what is normalised, and what is left alone?
The input to each sublayer is normalised. The residual stream that the output is added to is not.
Try this
Set aside ninety minutes. You need Python and NumPy.
1. Run the gradient-ratio code. Change the residual branch factor from 0.1 to 0.5 and to 1.0. What happens to the gradient at 64 and 256 layers?
2. Change the plain layers to use a larger weight scale (W times 2) and then a smaller one (W times 0.5). Does the gradient vanish or explode?
3. Run the layer norm check with a vector of 512 numbers and a different seed. Do the gradients still match to eight digits?
4. Add a second RMS-norm check where the input is not centred. How big is the difference from layer norm?
5. Run the stream-growth experiment without the normalisation of the sublayer input. What happens to the spread, and to the spread of the sublayer outputs?
6. Add eps = 0 to the layer norm and feed it a constant vector. What do you get?
A good result is a table of gradient sizes for plain and residual stacks, a layer norm that passes its gradient check, and a clear picture of the residual stream. The next lesson adds the other half of the block: the feed-forward network and its activation function.
Read more
Kaiming He, Xiangyu Zhang, Shaoqing Ren and Jian Sun, "Deep Residual Learning for Image Recognition" (2015), introduced residual connections and showed that they let networks of over a hundred layers train. Jimmy Lei Ba, Jamie Ryan Kiros and Geoffrey Hinton, "Layer Normalization" (2016), defines the layer. Ruibin Xiong and colleagues, "On Layer Normalization in the Transformer Architecture" (2020), compares pre-norm and post-norm. Biao Zhang and Rico Sennrich, "Root Mean Square Layer Normalization" (2019), introduced RMS norm. Nelson Elhage and colleagues, "A Mathematical Framework for Transformer Circuits" (2021), describes the residual stream.
Tags: Build an LLM Residual connection Layer normalisation Transformer Deep networks