4.1.9 · D4Transformer Architecture

Exercises — Residual connections and layer norm placement

3,479 words16 min readBack to topic

These graded problems test the parent topic: the residual formula , the two placements of layer normalization, and how each choice shapes the backward flow of gradients. Every symbol used here was built in the parent note; where a term is heavy we re-anchor it in plain words before using it.

Before we begin, one shared picture that all the algebra points back to.

Figure — Residual connections and layer norm placement

Notation reminder (all from the parent, plus symbols first used on this page):

  • = the activation vector entering layer (a list of numbers).
  • = a sublayer (attention or feed-forward). "" just means "some learned transformation."
  • = LayerNorm: subtract the mean, divide by the standard deviation, then scale by and shift by .
  • = a tiny fixed constant (e.g. ) added inside the square root, , so we never divide by zero. Defined properly in L2.4 below.
  • = the identity matrix (the do-nothing Jacobian — a diagonal of s).
  • = the Jacobian of LayerNorm: the matrix of partial derivatives . Written out in full in L3.2.
  • = that same Jacobian evaluated at layer (the superscript just says "which layer").
  • = a bound on how big a branch's contribution is, measured by operator norm; introduced in L5.2.
  • = the operator norm of a matrix : the largest factor by which can stretch any vector's length. .
  • = how much the final loss changes if you nudge ; this is the "gradient" that flows backward.

Level 1 — Recognition

L1.1

Classify each formula as Post-LN or Pre-LN:

(a) (b)

Recall Solution

(a) is Post-LN — the wraps the whole sum, so it is applied after the residual add. In figure s01 this is the bottom row: the white LN box sits directly on the cyan pipe. Read it inside-out: first (residual), then last. (b) is Pre-LN — the sits inside the branch, touching only the copy fed to ; the raw passes through untouched. This is the top row of s01, where the cyan bar runs unbroken and the LN box hangs below it on the branch. The bare $x_i +$ at the front is the un-normalized highway.

Rule of thumb: whatever is added last, un-normalized, is the residual stream. In (b) is added last untouched → clean highway.

L1.2

In , write (treating everything as scalars) and name the term that guarantees gradients survive.

Recall Solution

The ==== term is the guarantee. Even if has learned nothing (so ), the derivative is still , not . That "" is the pipe going straight through (the unbroken cyan bar in the top row of s01) — the gradient cannot vanish along the residual path.

L1.3

LayerNorm computes and across which axis — features, batch, or sequence? One line why Transformers prefer this to BatchNorm.

Recall Solution

Across the feature axis, per example independently: over the features of that one token. Preferred because Transformers see variable-length sequences with padding — batch statistics would wobble with sequence length and padding, whereas per-example feature statistics are stable regardless of what the rest of the batch looks like. See 4.1.01-Self-attention-mechanism for where these token vectors come from.


Level 2 — Application

L2.1

A feature vector for one token is (so ). Compute with , , and take . Give , , and the normalized vector.

Recall Solution

Step — WHAT: mean. . Step — variance. Deviations: . Squares: . , so . Step — normalize. . WHY it looks like this: subtracting the mean centered the cloud on ; dividing by set its spread to . The two middle entries were exactly average, so they map to . (We used here purely because made it safe; L2.4 shows why real code never dares set .)

L2.2

One Pre-LN layer with a single sublayer: Given and suppose . Compute . Then state what would be if output all zeros (an untrained branch).

Recall Solution

. If output zeros: identical to the input. This is the whole point: an untrained Pre-LN layer is a pass-through, so stacking many of them at initialization does nothing harmful. This is why Pre-LN starts training gently (see 4.2.02-Training-stability-and-convergence).

L2.3

For the same numbers, write the Post-LN update and compute it: with , , .

Recall Solution

Residual sum: . Mean: . Deviations: . , . Normalize: . So . Notice even with a tiny branch output, Post-LN rescales the whole stream every layer — the raw magnitudes of are erased. That is the "squeezed pipe" behaviour (the LN box on the cyan bar in the bottom row of s01).

L2.4

Why , and where it lives. LayerNorm's real forward formula divides by , not . (i) Give a concrete input vector where breaks the computation. (ii) With that input and , compute the normalized output (take ). (iii) Say in one line why the extra also appears in the backward pass.

Recall Solution

(i) The break. Take — all features identical. Then , every deviation is , so and . With the normalization divides — undefined (NaN in real code). This is the == degenerate case==. (ii) With . Numerator is , denominator is . So output — clean, finite, no NaN. turned a into a well-defined . (iii) Backward. Because the forward pass divides by , every derivative of LN carries that same in its denominator (the chain rule differentiates through it). So the LN gradient scale is really , not — the caps the gradient magnitude when : instead of the gradient exploding as , it saturates at . That bound is exactly what stops the case from destroying training.


Level 3 — Analysis

L3.1

Write the exact backward Jacobian for Pre-LN () and explain, term by term, why the gradient highway is "clean."

Recall Solution

Differentiate the sum:

  • The (identity) comes from the bare term — the untouched highway (the unbroken cyan bar, top row of s01). It is a constant, not shrinking with depth.
  • The second term is the branch: it can be small or large, but it is added to , never multiplied into it. When you chain this over layers, you get , which stays near if the branches are small — gradients neither vanish nor explode. See 5.1.03-Gradient-flow-in-deep-networks.

L3.2

For Post-LN (), the Jacobian is where is the LayerNorm Jacobian. Write out in full (with ), identify its diagonal and off-diagonal parts, then say why the multiplying out front makes Post-LN more fragile than Pre-LN.

Recall Solution

The exact matrix. Let be the input to LN, with mean , variance , and the normalized entries. Entry of the Jacobian is Reading the three pieces:

  • (the Kronecker delta, if else ) is the plain identity part — this is why people call "diagonal-ish."
  • is a constant subtracted from every entry — this is the mean-removal coupling ( depends on all features, so changing one shifts every output). It fills in the off-diagonal.
  • is the variance-removal coupling — changing changes , which rescales every output. This is the second off-diagonal contribution and it does not cancel in general; it only vanishes when the are orthogonal to the perturbation, which is not the typical case.
  • The whole matrix is scaled by this is where enters the gradient, capping the scale when (see L2.4).

Why fragile. In Pre-LN the identity is added (). In Post-LN the identity is inside a product with . Chaining layers gives — every one of those factors multiplies together. Because each carries the scale that depends on that layer's activation statistics, the product drifts far from and does so unevenly across depth. That uneven, multiplicative chain is why Post-LN needs learning-rate warmup.

L3.3

The LN gradient scale is the factor in front of . Take , . If a deep layer's residual sum has variance (so scale uses ) while a shallow layer has (), compute both gradient scales and their ratio. What does the ratio say about gradient uniformity?

Recall Solution

Deep-layer scale . Shallow-layer scale . Ratio (shallow / deep) . The gradient is amplified more in the shallow layer than the deep one purely because of differing . That non-uniformity across depth is precisely Xiong et al.'s "gradient imbalance" — it is why a single global learning rate is dangerous for Post-LN, and why warmup (ramping the LR slowly) is used to let settle first.


Level 4 — Synthesis

L4.1

Design a "1-sublayer-per-layer" Pre-LN stack. Suppose each layer's branch output is a fixed vector regardless of input (a toy "always writes the same correction"). Starting from , compute . What quantity grows linearly with depth, and why is this the "residual stream accumulation" the parent note describes?

Recall Solution

Pre-LN: (the branch adds every layer).

  • The stream grows linearly: . Because the residual path is never normalized in Pre-LN (the unbroken cyan bar in s01), each layer's contribution is permanently added into a shared, growing stream — later layers can read everything earlier layers wrote. This additive-memory picture is the "residual stream" interpretation.

L4.2

Now do the same toy in Post-LN with , , , starting . Compute and . Contrast the growth with L4.1.

Recall Solution

Layer 1: . . , . Normalize: . So . Layer 2: . , , . Normalize: . So . Contrast: Post-LN re-normalizes to the same magnitude every layer, no linear accumulation. The stream cannot "grow"; its scale is reset each layer. That's the fundamental representational difference: Pre-LN accumulates, Post-LN overwrites the scale.

L4.3

A team reports their 48-layer Post-LN model diverges in the first 500 steps at learning rate , but a 6-layer version trains fine at the same LR. Explain mechanistically (referencing your L3.2/L3.3 answers) why depth is the culprit, and name two fixes.

Recall Solution

Mechanism: Post-LN gradients chain multiplicatively through . With 6 layers that product stays near ; with 48 layers the same per-layer imperfections compound, and the depth-dependent imbalance (L3.3) makes the deepest layers receive wildly-scaled updates. A single large LR then overshoots → divergence. Fixes:

  1. Learning-rate warmup — ramp LR from ~0 over a few thousand steps so activation statistics () settle before big updates (the standard Post-LN remedy).
  2. Switch to Pre-LN — moves the identity out of the product into a sum (), giving depth-uniform gradients. See 6.2.05-Layer-scaling-and-initialization for a third fix (scaling the branch at init).

Level 5 — Mastery

L5.1

Prove that at initialization a Pre-LN sublayer whose branch outputs exactly acts as the identity, then use this to argue why "zero-init the last projection of each branch" is a sound initialization trick.

Recall Solution

Proof: Pre-LN is . If then . Identity, for any input — QED. Consequence: If you initialize the final linear projection inside each branch to zero, then outputs at step 0, so the entire deep stack is one giant identity map at initialization. The forward pass is therefore perfectly well-behaved no matter how deep, and gradients begin flowing through the clean highway before the branches have learned anything. Training then "grows" corrections from zero — the safest possible start. This is the logic behind branch/residual scaling schemes in 6.2.05-Layer-scaling-and-initialization.

L5.2

Setup and symbols. Consider a Pre-LN residual stream of layers. Write its full backward Jacobian as the product , where is the branch's Jacobian at layer (the "small correction" part), and suppose each is bounded in operator norm by (recall = the biggest stretch factor of ; ). Bound the operator norm of the whole product and show it stays finite (no explosion) when is small. Then evaluate the bound for , .

Recall Solution

Bound. By the triangle inequality, . Operator norm is submultiplicative (), so chaining all factors: This is finite for any finite and, crucially, grows only geometrically at rate — controllable by keeping each branch contribution () small (exactly what zero/scaled init in L5.1 does). Contrast Post-LN, where the analogous product carries the extra factors and lacks this clean shape. Evaluate. . So the total backward gain across 48 layers is at most ~ — no explosion.

L5.3

Give the single most compact reason Pre-LN scales to hundreds of layers where Post-LN struggles, in one sentence, then cloze the key phrase.

Recall Solution

Because Pre-LN places the identity in an added position () so gradients chain as a benign product, whereas Post-LN's identity sits inside a multiplicative LN-Jacobian chain that drifts unevenly with depth.

Pre-LN keeps the residual highway additive (never normalized), giving depth-uniform gradient flow.


Recall Self-test summary (cloze)

Post-LN puts LayerNorm ::: after the residual add — Pre-LN puts LayerNorm ::: inside the branch, before F — The term guaranteeing gradient survival in is ::: the +1 (identity) in LayerNorm divides variance by ::: (population form — the features ARE the whole population, nothing to correct for) Why nonzero in ? ::: to avoid dividing by zero when (all features equal), and to cap the gradient scale at off-diagonal terms come from ::: mean removal () and variance removal () Pre-LN gradient chains as because the identity is ::: added, not multiplied Does Pre-LN eliminate warmup? ::: No — it only reduces dependence on the warmup choice

Related: 4.1.08-Multi-head-attention, 4.3.01-Positional-encoding, 4.1.12-Encoder-decoder-attention.