Transformer Decoder Explained
← /learn

LayerNorm & residuals

Why residuals; why LayerNorm; pre-norm vs post-norm.

Check yourself ↓ three questions and what to remember, at the end

Every sub-layer reads a normalised copy of the residual stream and adds its result back. Below, one position's vector is normalised step by step (the mean, the spread, the shift to 0, the rescale to 1, then γ and β), attention reads that copy and returns a small update Δ, and the stream carries on as x + Δ; then the same happens again around the feed-forward network.

Loading the animation…

Concept

Two ideas glue the rest of the decoder together: residual connections and LayerNorm. They sound prosaic next to attention, but every deep-network choice in the last decade has either kept them or re-invented them.

Residual connections add the input of a sub-layer back to its output:

h = x + Attn(LN(x))
y = h + FFN(LN(h))

The residual stream is the running "this is what the model believes about position i" vector. Each sub-layer contributes to it instead of replacing it. That's why a Transformer can be 96 layers deep without the gradient vanishing — gradients flow straight along the residual path and only sample each sub-layer's contribution.

LayerNorm keeps the residual stream from blowing up or vanishing. For each position, it shifts the vector to have zero mean and rescales it to unit variance, then applies a learned scale (γ) and shift (β):

Input

A fixed vector with a wide spread.

[0] -3.000[1] -1.000[2] 0.000[3] 1.000[4] 2.000[5] 5.000[6] 7.000

γ · (x − μ)/σ + β

After LayerNorm with γ=1.0, β=0.0.

[0] -1.428[1] -0.803[2] -0.491[3] -0.179[4] 0.134[5] 1.071[6] 1.696

Notice how γ scales the spread and β shifts the centre. With γ=1 and β=0 the output has zero mean and (very nearly) unit variance.

Concept

Drag the sliders. With γ = 1 and β = 0, LayerNorm is doing what its description says: it removes the position's overall scale and offset, keeping only the direction of the vector. The residual addition then re-introduces the scale on top of the normalised contribution.

Pre-norm vs post-norm: where you put the LayerNorm matters. The original Transformer applied LN after the residual addition (post-norm). Modern decoders (GPT-2 onwards) apply LN before each sub-layer (pre-norm). Pre-norm trains more stably and is what we use.

Maths

For an input vector x∈Rdx \in \mathbb{R}^{d}:

μ=1d∑i=1dxi,σ2=1d∑i=1d(xi−μ)2,LN⁡(x)=γ⊙x−μσ2+ε+β\mu = \frac{1}{d}\sum_{i=1}^{d} x_i, \qquad \sigma^2 = \frac{1}{d}\sum_{i=1}^{d} (x_i - \mu)^2, \qquad \operatorname{LN}(x) = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \varepsilon}} + \beta

with ε=10−5\varepsilon = 10^{-5} for numerical stability and σ2\sigma^2 the population variance. γ\gamma and β\beta are learned vectors of length dd, applied elementwise (⊙\odot).

The pre-norm decoder block is then

h=x+MultiHeadAttention⁡(LN⁡(x))y=h+FFN⁡(LN⁡(h))\begin{aligned} h &= x + \operatorname{MultiHeadAttention}\big(\operatorname{LN}(x)\big) \\ y &= h + \operatorname{FFN}\big(\operatorname{LN}(h)\big) \end{aligned}

…and stacking blocks just iterates this NN times.

Code

// src/lib/transformer/layernorm.ts (excerpt)
export function layernorm(x, gamma, beta, eps = 1e-5) {
  let mean = 0;
  for (const v of x) mean += v;
  mean /= x.length;

  let varSum = 0;
  for (const v of x) varSum += (v - mean) ** 2;
  const invStd = 1 / Math.sqrt(varSum / x.length + eps);

  return x.map((v, i) => (v - mean) * invStd * gamma[i]! + beta[i]!);
}
// src/lib/transformer/block.ts (excerpt)
export function block(x, w, nHeads) {
  const ln1 = layernormRows(x, w.ln1.gamma, w.ln1.beta);
  const h = addMat(x, multiHeadAttention(ln1, w.attn, nHeads));
  const ln2 = layernormRows(h, w.ln2.gamma, w.ln2.beta);
  return addMat(h, ffn(ln2, w.ffn));
}

That's the whole decoder block: two normalisations, two sub-layers, two residual additions.

Check yourself

Commit to an answer before you reveal it: a wrong guess you can explain teaches more than a right one you skimmed. Every number in the answers comes from the same tested model as the chapter’s.

Q1LayerNorm with γ = 1 and β = 0, applied to x = (1, 2, 3, 4): what is the largest output?
Reveal the answer

Answer: 1.342 (counted right within 5%)

About 1.342: the mean is 2.5 and the (population) variance 1.25, so the last element becomes (4−2.5)/1.25(4 - 2.5)/\sqrt{1.25}. The output has mean 0 and variance 1 whatever the input's scale.

LayerNorm →

Commit to a number, then reveal.

Q2Multiply every element of x by 10 before LayerNorm (γ = 1, β = 0). The output is…
Reveal the answer

Answer: Unchanged, up to the tiny ε

Unchanged: subtracting the mean and dividing by the standard deviation removes the vector's offset and scale and keeps only its direction. Try it with the widget's sliders.

What LayerNorm removes →

Pick one, then reveal.

Q3And x = (5, 5, 5, 5)? Give the largest output, in absolute value.
Reveal the answer

Answer: 0 (counted right within ± 0.01)

0, everywhere. x−μx - \mu is zero, and ε=10−5\varepsilon = 10^{-5} under the square root stops the 0/00/0; the output is just β\beta.

Why ε is there →

Commit to a number, then reveal.

Comments

Be the first to leave a comment on this section.

Sign in (top-right) to leave a comment.