← All notes
Course chapters
On this page

Lesson 24 · Large language models

Residual connections and layer normalisation

Follow gradient paths through residual additions, calculate LayerNorm step by step, and compare pre-norm, post-norm and RMSNorm without treating them as guarantees of stable training.

1. Can the gradient cross a deep network?

The previous lesson described stacks of Transformer blocks. During training, the loss must send a useful signal back through that stack to the earlier parameters.

The chain rule multiplies derivatives along a path. To see why depth matters, imagine a scalar network with 96 identical local derivatives:

0.996≈4.05×10−5,1.196≈9.41×103.0.9^{96}\approx4.05\times10^{-5},\qquad 1.1^{96}\approx9.41\times10^3.

One product becomes very small; the other grows substantially. Neither number by itself establishes overflow or a training failure, but they illustrate how repeated multiplication can change the scale of a learning signal.

Real networks multiply Jacobian matrices, not one average scalar per layer. Direction, singular values, nonlinearities and the current inputs matter. The example is a way to understand the chain rule, not a prediction of a particular model's gradient.

We encountered a related problem in backpropagation and recurrent networks. In an RNN, the repeated path runs through time; here it runs through depth.

Pause and think

Can we create a path that lets an input contribute to the output without passing through every operation in the learned branch?

I've thought about it — show the answerHide answer

Yes. Add the input directly to the learned branch's output. This introduces an identity path as well as the transformed path.

It helps change the optimisation problem, but does not remove the need to train the branch or guarantee stable gradients.

2. Residual connections: learn an update

A plain layer computes y=f(x)y=f(x). An identity residual layer computes:

y=x+f(x).y=x+f(x).

The branch can learn an update to the existing representation rather than replacing it entirely. If a desired mapping is H(x)H(x), the branch's target can be expressed as H(x)−xH(x)-x.

When leaving the representation nearly unchanged is useful, making f(x)f(x) small produces an approximately identity mapping. This can be easier to optimise than asking a complicated plain branch to reproduce its input.

The addition still changes the model. A learned branch does not automatically compensate perfectly, and adding a residual path does not guarantee that performance improves. The architecture is trained with that path included.

Input x

Learned branch
f(x)
Identity branch
x unchanged

↓ Add the two branches ↓

y=x+f(x),Jy=I+Jfy=x+f(x),\qquad J_y=I+J_f
Figure 24-1. The identity branch supplies an additional path. The total derivative includes both paths, so it can still grow, shrink or cancel.

For vectors, differentiating gives:

Jy=I+Jf,∇xL=(I+Jf)T∇yL.J_y=I+J_f, \qquad \nabla_x\mathcal L=(I+J_f)^{\mathsf T}\nabla_y\mathcal L.

The identity term provides a direct contribution to the gradient. But the total gradient includes the learned branch too. In a scalar example, f′(x)=−1f'(x)=-1 cancels the identity term, while f′(x)=0.9f'(x)=0.9 gives a derivative of 1.91.9, which can amplify across depth.

If every scalar branch has derivative 0.010.01, then:

(1+0.01)96≈2.60.(1+0.01)^{96}\approx2.60.

This is a particular favourable example, not a rule that residual derivatives are always close to one.

Plain derivative product aⁿ: 1.0000e-192

Residual derivative product (1 + a)ⁿ: 2.5993e+0

Derivative of one residual layer: 1.01

All layers use the same fixed scalar slope, with no normalisation. Try a = −1 to see cancellation or a = 0.9 to see amplification. These products do not predict gradients in a real Transformer.

Experiment 24-A. Compare repeated scalar derivatives with and without an identity branch.

To add xx and f(x)f(x) directly, their shapes must match. Transformer sublayers normally return the model width, so each residual addition works row by row on the sequence representation. Other network designs can use a projected shortcut when dimensions differ; that shortcut's derivative is no longer exactly the identity.

3. LayerNorm: standardise one feature row

Repeated updates can change activation scales. Very large values can affect numerical precision and attention scores, while changing scales can complicate optimisation. But residual additions do not necessarily make the vector larger at every layer.

For a residual update:

xℓ+1=xℓ+fℓ(xℓ),x_{\ell+1}=x_\ell+f_\ell(x_\ell),

its squared length satisfies:

∥x+f(x)∥2=∥x∥2+2⟨x,f(x)⟩+∥f(x)∥2.\|x+f(x)\|^2=\|x\|^2+2\langle x,f(x)\rangle+\|f(x)\|^2.

The middle term can be negative, so the result depends on the direction of the update.

Start with x = [1, 0]

Aligned increment · norm increases

Add [0.5, 0] → [1.5, 0] · norm 1.500

Opposing increment · norm decreases

Add [-0.5, 0] → [0.5, 0] · norm 0.500

Perpendicular increment · direction changes

Add [0, 0.5] → [1, 0.5] · norm 1.118

Figure 24-2. Residual additions are signed vector updates. Their magnitude does not necessarily increase monotonically with depth.

In Transformer LayerNorm, statistics are normally computed across the feature coordinates of one token row, separately for each token and example. They are not a shared mean across the whole sequence or minibatch.

For x∈Rdx\in\mathbb R^d:

μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2,\mu=\frac1d\sum_{i=1}^{d}x_i,\qquad \sigma^2=\frac1d\sum_{i=1}^{d}(x_i-\mu)^2, x^i=xi−μσ2+ε,LN⁡(x)i=γix^i+βi.\widehat x_i=\frac{x_i-\mu}{\sqrt{\sigma^2+\varepsilon}},\qquad \operatorname{LN}(x)_i=\gamma_i\widehat x_i+\beta_i.

A positive ε\varepsilon protects the denominator when the feature variance is zero or very small. The variance uses division by dd, not the sample-estimation correction d−1d-1.

The learned vectors γ\gamma and β\beta allow coordinate-wise scale and shift. They are parameters shared across token positions, while the statistics depend on each input row.

Work through four coordinates

For x=[8,2,2,4]x=[8,2,2,4], the mean is 44 and the variance is 66:

σ2=(8−4)2+(2−4)2+(2−4)2+(4−4)24=6.\sigma^2=\frac{(8-4)^2+(2-4)^2+(2-4)^2+(4-4)^2}{4}=6.
x=[8,2,2,4],μ=4,σ2=6x=[8,2,2,4],\quad\mu=4,\quad\sigma^2=6x^=[4,−2,−2,0]6+ε≈[1.633,−0.816,−0.816,0]\widehat x=\frac{[4,-2,-2,0]}{\sqrt{6+\varepsilon}}\approx[1.633,-0.816,-0.816,0]LN⁡(x)=γ⊙x^+β\operatorname{LN}(x)=\gamma\odot\widehat x+\beta
Figure 24-3. Centre and standardise one row, then apply learned scale and shift. The final affine output need not have zero mean or unit variance.

The centred vector has mean zero. With finite epsilon, its standardised variance is σ2/(σ2+ε)\sigma^2/(\sigma^2+\varepsilon), slightly below one for positive variance. After the learned affine transformation, the output need not have zero mean or unit variance at all.

LayerNorm also does not turn every vector into a unit-length vector. Before the affine step and ignoring epsilon, a nonconstant standardised row has squared norm dd and length d\sqrt d.

Mean μ: 4.0000

Variance σ²: 6.0000

Denominator √(σ² + ε): 2.4495

Standardised: [1.6330, -0.8165, -0.8165, 0.0000]

LayerNorm affine output: [1.6330, -0.8165, -0.8165, 0.0000]

RMSNorm output (same γ; no β): [1.7056, 0.4264, 0.4264, 0.8528]

ε = 0.00001. This uses one shared γ and β to make the example easy to inspect; real LayerNorm normally learns a separate scale and shift for each feature. RMSNorm does not subtract the mean and usually omits the shift.

Experiment 24-B. Calculate LayerNorm statistics and affine outputs, then compare RMSNorm on the same input.

Choose the constant input to see why epsilon matters: after centring, all coordinates are zero, and LayerNorm's output is its shift. RMSNorm behaves differently because it does not subtract the mean.

What normalisation helps with

Normalisation provides more controlled inputs to subsequent calculations. It is not clipping, does not make all coordinates equally important and cannot guarantee numerical safety by itself.

Large differences between attention scores can make Softmax highly concentrated; adding the same constant to every score does not change Softmax. Learned projections, scaling and normalisation interact to determine those scores.

Finite-precision addition can also lose a small increment beside a much larger value. The exact outcome depends on the number format and operations used. These are reasons to pay attention to numerical scale, rather than proof that any particular activation magnitude always causes a crash.

4. Put normalisation before or after the branch?

Two familiar arrangements use the same ingredients in different orders:

Post-norm · normalise after adding

y=LN⁡(x+f(x))y=\operatorname{LN}(x+f(x))

Both contributions pass through LayerNorm after the sum.

Pre-norm · normalise the branch input

y=x+f(LN⁡(x))y=x+f(\operatorname{LN}(x))

The identity path bypasses this sublayer's normalisation.

Figure 24-4. Normalisation placement changes the computation and gradient paths. Pre-norm retains a direct identity term but does not guarantee stable total gradients.

Ignoring dropout, a post-norm block with attention A\mathcal A and feed-forward network F\mathcal F can be written:

a=LN⁡1(x+A(x)),y=LN⁡2(a+F(a)).\begin{aligned} a&=\operatorname{LN}_1(x+\mathcal A(x)),\\ y&=\operatorname{LN}_2(a+\mathcal F(a)). \end{aligned}

A pre-norm block instead uses:

a=x+A(LN⁡1(x)),y=a+F(LN⁡2(a)).\begin{aligned} a&=x+\mathcal A(\operatorname{LN}_1(x)),\\ y&=a+\mathcal F(\operatorname{LN}_2(a)). \end{aligned}

The original Transformer used post-norm. In pre-norm, the main residual stream bypasses that sublayer's normalisation; the branch receives a normalised input. A final normalisation is commonly applied after the stack.

The gradient distinction is visible in the Jacobians:

Jpost=JLN(I+Jf),Jpre=I+JfJLN.\begin{aligned} J_{\mathrm{post}}&=J_{\mathrm{LN}}(I+J_f),\\ J_{\mathrm{pre}}&=I+J_fJ_{\mathrm{LN}}. \end{aligned}

The Jacobians are evaluated at their corresponding inputs. Pre-norm retains an explicit identity term; post-norm passes both contributions through a normalisation derivative.

Pre-norm often makes deep-network optimisation easier. But “post-norm cannot train” and “pre-norm never needs warm-up” would both be too strong. Initialisation, learning rates, residual scaling, depth and other design choices also matter. Both arrangements can train successfully.

A pre-norm residual stream itself is not reset to a fixed norm after each addition. It is the branch's input that is normalised, so claims that LayerNorm always forces every block output back to length one miss the placement distinction.

RMSNorm: normalise by root mean square

A common alternative omits mean subtraction and usually omits the learned shift:

RMSNorm⁡(x)i=γixi1d∑jxj2+ε.\operatorname{RMSNorm}(x)_i =\gamma_i\frac{x_i}{\sqrt{\frac1d\sum_j x_j^2+\varepsilon}}.

This uses the mean of squared coordinates rather than centred variance. It can simplify computation, but it is not identical to LayerNorm and is not invariant to adding a constant offset. Comparable performance in some settings does not mean the two are interchangeable in every trained model.

Pause and think

If pre-norm keeps an identity path, is it now safe to choose any branch scale or learning rate?

I've thought about it — show the answerHide answer

No. The branch still contributes to the output and total gradient. Its derivative can amplify or cancel the identity contribution, while training updates can also become too large.

Residual paths and normalisation are useful tools within a complete training design, not guarantees that remove all optimisation choices.

5. What you have discovered

  • Residual connections add a learned update to an existing representation and introduce an identity contribution to its Jacobian.
  • That identity contribution can help gradient propagation, but total gradients are not guaranteed to stay near one.
  • LayerNorm computes each token row's feature statistics, standardises with epsilon and applies learned scale and shift.
  • Pre-norm and post-norm place normalisation on different computation paths; this changes their optimisation behaviour.
  • RMSNorm controls scale without subtracting the mean, so its behaviour differs from LayerNorm.

We now have the architecture and its stabilising components. Next, we will follow pretraining, supervised fine-tuning and reinforcement learning, and see how training objectives turn a language model into an assistant.

Check your understanding

1. What does an identity residual connection contribute to gradient propagation?
2. How is LayerNorm normally applied to Transformer token representations?