advanced attention-transformers 45 min read

The Transformer Block and the Residual Stream

Attention alone averages tokens into one another; the residual connection keeps each token itself, and turns the block into a shared channel that heads read with linear maps and write into by addition, which makes the logits an exact sum of paths, keeps an identity path open for the gradient, and lets two heads compose into an induction head

Overview & Motivation

The attention topic read attention as a kernel smoother: each token’s output is a weighted average of the values of the tokens it attends to. Averaging has a consequence when we do it twice. Average a set of points, average the averages, and keep going, and every point drifts toward one consensus. Take ten tokens in the plane and send them through twelve layers of attention with nothing else in the block. At a moderate temperature their cloud, whose widest pair starts 2.5742.574 apart, shrinks until every token sits at the same point to within 10−1010^{-10}. Add one term to each layer, the token itself, and the same twelve layers leave every token distinct, with the cloud 28622862 times wider than it began.

That added term is the residual connection, and this topic is about what it builds. With it, a transformer block stops being a map that replaces its input and becomes a write into a shared vector, the residual stream, which every later layer can read. We develop the consequences in order:

  1. Attention alone collapses. A row-stochastic matrix shrinks the cloud of tokens by at least a computable factor, so wide-kernel attention stacks lose every distinction between tokens. With the skip, and value maps of norm at most 11, each layer keeps at least one minus that factor of the cloud’s diameter.
  2. LayerNorm is a sphere in a hyperplane. It projects onto the hyperplane orthogonal to the all-ones vector, then radially onto a sphere, and its Jacobian forgets the radial direction.
  3. The identity path. The Jacobian of a residual stack multiplies out into a sum over every subset of layers, and the empty subset is the identity. Every layer receives the top gradient unchanged, and where LayerNorm sits decides what happens to the rest.
  4. The stream as a channel. An attention-only model’s logits are exactly a sum over chains of heads, and two heads talk only through the subspaces where one writes and the other reads.
  5. Induction heads. We train a two-layer model from scratch and watch two heads compose through the stream, a previous-token head and a head whose keys read it, into a circuit that completes [A][B] … [A] with [B]. One layer cannot do this, and we show why.

Then the finance case. On filings about companies that never occur in training, a model trained on the filings completes none of their multi-word names, and the induction model, which never saw a filing, completes 0.7680.768 of them.


The block, assembled

We write a sequence of nn tokens as a matrix X∈Rn×dX \in \mathbb{R}^{n \times d}, one row xix_i per position, and let matrices act on the right, x↦xWx \mapsto xW. Write 1\mathbf{1} for the all-ones vector.

Definition 1 (The transformer block).

A head hh has maps WQh,WKh,WVh∈Rd×dhW_Q^h, W_K^h, W_V^h \in \mathbb{R}^{d \times d_h} and WOh∈Rdh×dW_O^h \in \mathbb{R}^{d_h \times d} and sends XX to

head⁡h(X)=softmax⁡ ⁣(XWQh(XWKh)⊤dh+B) XWVhWOh,\operatorname{head}_h(X) = \operatorname{softmax}\!\Bigl(\frac{XW_Q^h (XW_K^h)^\top}{\sqrt{d_h}} + B\Bigr)\, X W_V^h W_O^h,

with the softmax taken row by row and BB either 00 or the causal mask (−∞-\infty above the diagonal). Rotary positions (Definition 4 of the positional-encodings topic) may rotate the queries and keys. Multi-head attention is MHA⁡(X)=∑hhead⁡h(X)\operatorname{MHA}(X) = \sum_h \operatorname{head}_h(X), and an MLP is MLP⁡(x)=σ(xW1+b1)W2+b2\operatorname{MLP}(x) = \sigma(xW_1 + b_1)W_2 + b_2 on each row, with σ=ReLU⁡\sigma = \operatorname{ReLU} here. The pre-LN block is

X←X+MHA⁡(LN⁡X),X←X+MLP⁡(LN⁡X),X \leftarrow X + \operatorname{MHA}(\operatorname{LN} X), \qquad X \leftarrow X + \operatorname{MLP}(\operatorname{LN} X),

and the post-LN block is X←LN⁡(X+MHA⁡X)X \leftarrow \operatorname{LN}(X + \operatorname{MHA} X), then X←LN⁡(X+MLP⁡X)X \leftarrow \operatorname{LN}(X + \operatorname{MLP} X), with LN⁡\operatorname{LN} the LayerNorm of Definition 3. The residual stream is the sequence of matrices X0,X1,…X_0, X_1, \dots that the blocks pass along: each sublayer reads it and writes back by addition.

The post-LN block is Vaswani and colleagues’ (2017) original; the pre-LN block is what most large models use now, for a reason Theorem 2 makes precise. The skip itself is He and colleagues’ (2016).

Proposition 1 (Heads are smoothers that write; the MLP is a memory).

(i) Without rotary positions or query and key biases, MHA⁡(X)=∑hAttn⁡(XWQh,XWKh,XWVh) WOh\operatorname{MHA}(X) = \sum_h \operatorname{Attn}(XW_Q^h, XW_K^h, XW_V^h)\, W_O^h, where Attn⁡\operatorname{Attn} is the attention topic’s scaled dot-product attention. Each head is a Nadaraya–Watson smoother, and the block adds HH smoothed copies of the stream, each mapped into it by its own WOhW_O^h.

(ii) MLP⁡(x)=b2+∑i=1wσ(⟨x,ki⟩+b1,i) vi\operatorname{MLP}(x) = b_2 + \sum_{i=1}^{w} \sigma(\langle x, k_i \rangle + b_{1,i})\, v_i, where the key kik_i is the ii-th column of W1W_1 and the value viv_i is the ii-th row of W2W_2.

Proof.

For (i), the head’s formula is the attention topic’s Definition 2 applied to XWQhXW_Q^h, XWKhXW_K^h, and XWVhXW_V^h, followed by WOhW_O^h; summing over heads is block matrix multiplication of the concatenated head outputs by the stacked output maps WOhW_O^h, and that attention is a Nadaraya–Watson smoother is that topic’s Proposition 1. For (ii), the entries of xW1+b1xW_1 + b_1 are ⟨x,ki⟩+b1,i\langle x, k_i\rangle + b_{1,i}, and multiplying the vector σ(xW1+b1)\sigma(xW_1 + b_1) by W2W_2 sums its entries times the rows viv_i.

∎

Read (ii) beside attention. Attention takes a weighted sum of values whose keys come from the context, with weights normalized by a softmax. The MLP takes a sum of values whose keys are parameters, gated by an unnormalized σ\sigma. Geva and colleagues (2021) read trained MLPs this way, as memories keyed on patterns in the input. The notebook checks (i) head by head against the attention topic’s attention function and (ii) row by row, both to 10−1210^{-12}.


Attention alone collapses

Every row of an attention matrix is a probability vector, so the matrix is row-stochastic, a Markov transition matrix on positions. formalML’s random-walks topic proves that a mixing chain forgets where it started (its Theorem 3), by a spectral argument about one fixed chain. A stack applies a different matrix at every layer, so we need a bound that survives a product of different matrices, and Dobrushin’s contraction is that tool. Write diam⁡(X)=max⁡i,j∥xi−xj∥\operatorname{diam}(X) = \max_{i,j} \lVert x_i - x_j \rVert for the diameter of the cloud of rows of XX, in any norm on Rd\mathbb{R}^d, and ∥W∥\lVert W \rVert for the operator norm of x↦xWx \mapsto xW in the same norm.

Definition 2 (The Dobrushin coefficient; the smoothing stack).

For a row-stochastic A∈Rn×nA \in \mathbb{R}^{n \times n}, the Dobrushin coefficient is

τ(A)=12max⁡i,j∥Ai⋅−Aj⋅∥1=1−min⁡i,j∑kmin⁡(Aik,Ajk)∈[0,1].\tau(A) = \tfrac12 \max_{i,j} \lVert A_{i\cdot} - A_{j\cdot} \rVert_1 = 1 - \min_{i,j} \sum_k \min(A_{ik}, A_{jk}) \in [0, 1].

The pure attention stack is Xl+1=AlXlWlX_{l+1} = A_l X_l W_l, and the stack with the skip is Xl+1=Xl+AlXlWlX_{l+1} = X_l + A_l X_l W_l.

The two forms of τ\tau agree because ∣ak−bk∣=ak+bk−2min⁡(ak,bk)\lvert a_k - b_k \rvert = a_k + b_k - 2\min(a_k, b_k) for any numbers, and two probability vectors each sum to 11. So τ(A)=0\tau(A) = 0 exactly when all rows are equal, and τ(A)=1\tau(A) = 1 when two rows have disjoint supports. Dobrushin (1956) introduced it for nonstationary Markov chains; Seneta’s book (1981) calls it a coefficient of ergodicity.

Theorem 1 (Attention contracts toward consensus).

Let AA be row-stochastic.

(i) diam⁡(AX)≤τ(A)diam⁡(X)\operatorname{diam}(AX) \le \tau(A)\operatorname{diam}(X), in every norm.

(ii) If each row of a score matrix SS has range max⁡kSik−min⁡kSik≤r\max_k S_{ik} - \min_k S_{ik} \le r, then τ(softmax⁡S)≤1−e−r\tau(\operatorname{softmax} S) \le 1 - e^{-r}.

(iii) The pure attention stack satisfies diam⁡(XL)≤(∏l<Lτ(Al) ∥Wl∥)diam⁡(X0)\operatorname{diam}(X_L) \le \bigl(\prod_{l \lt L} \tau(A_l)\, \lVert W_l \rVert\bigr) \operatorname{diam}(X_0).

Proof.

For (i), fix rows ii and jj and let c=Ai⋅−Aj⋅c = A_{i\cdot} - A_{j\cdot}. Then ∑kck=0\sum_k c_k = 0 and ∥c∥1=2τij\lVert c \rVert_1 = 2\tau_{ij}, with τij≤τ(A)\tau_{ij} \le \tau(A). If τij=0\tau_{ij} = 0 the two rows are equal. Otherwise the positive and negative parts of cc, which sum to zero together, have equal mass τij\tau_{ij}, so c=τij(p−q)c = \tau_{ij}(p - q) for two probability vectors pp and qq. Then

(AX)i−(AX)j=∑kckxk=τij(∑kpkxk−∑mqmxm)=τij∑k,mpkqm(xk−xm),(AX)_i - (AX)_j = \sum_k c_k x_k = \tau_{ij}\Bigl(\sum_k p_k x_k - \sum_m q_m x_m\Bigr) = \tau_{ij} \sum_{k,m} p_k q_m (x_k - x_m),

whose norm is at most τij∑k,mpkqm∥xk−xm∥≤τ(A)diam⁡(X)\tau_{ij} \sum_{k,m} p_k q_m \lVert x_k - x_m \rVert \le \tau(A) \operatorname{diam}(X). Maximize over ii and jj.

For (ii), every entry of row ii satisfies Aik=eSik/∑meSim≥emin⁡mSim/(n emax⁡mSim)≥e−r/nA_{ik} = e^{S_{ik}} / \sum_m e^{S_{im}} \ge e^{\min_m S_{im}} / (n\, e^{\max_m S_{im}}) \ge e^{-r}/n. So ∑kmin⁡(Aik,Ajk)≥e−r\sum_k \min(A_{ik}, A_{jk}) \ge e^{-r} for every pair of rows, and Definition 2 gives τ≤1−e−r\tau \le 1 - e^{-r}.

For (iii), ∥xiW−xjW∥≤∥W∥ ∥xi−xj∥\lVert x_i W - x_j W \rVert \le \lVert W \rVert\, \lVert x_i - x_j \rVert, so diam⁡(XW)≤∥W∥diam⁡(X)\operatorname{diam}(XW) \le \lVert W \rVert \operatorname{diam}(X). By (i), diam⁡(AlXlWl)≤τ(Al)diam⁡(XlWl)≤τ(Al)∥Wl∥diam⁡(Xl)\operatorname{diam}(A_l X_l W_l) \le \tau(A_l)\operatorname{diam}(X_l W_l) \le \tau(A_l)\lVert W_l \rVert \operatorname{diam}(X_l), and we induct on ll.

∎

Part (ii) is the attention topic’s temperature talking. Scores at inverse temperature β\beta have range proportional to β\beta, so a wide kernel (small β\beta, high temperature) keeps τ\tau well below 11 and the collapse in (iii) is geometric. Dong, Cordonnier, and Loukas (2021) prove more: pure self-attention with value maps loses rank doubly exponentially in depth. We prove the geometric rate and cite theirs.

The laboratory’s cloud makes this concrete. Ten tokens in the plane pass through twelve layers of Al=softmax⁡(βXlXl⊤)A_l = \operatorname{softmax}(\beta X_l X_l^\top) with W=IW = I, so queries, keys, and values are the tokens themselves. The first layer’s τ\tau is 0.1880.188, 0.3690.369, 0.6670.667, 0.9400.940, and 0.9990.999 at β=0.25\beta = 0.25, 0.50.5, 11, 22, and 44. For β≤2\beta \le 2, the pure stack’s diameter falls below 10−1010^{-10} by layer twelve, under the bound of (iii) at every layer. At β=4\beta = 4, τ\tau stays above 0.970.97 through layer twelve, so the bound falls slowly: it allows 2.3332.333 at layer twelve, and the diameter is 1.9971.997. Attention here is not close to the identity. The scores are dot products, so long tokens win: six of the ten tokens put less than half their weight on themselves, and every row’s largest weight in the first layer falls on one of four long tokens, which act as leaders. By layer twelve the cloud has gathered into two tight clusters, of eight tokens and two, with a relative spread of 0.6140.614. It looks frozen, and it is not. Run on, and the clusters merge: the diameter is 0.2080.208 at layer sixteen and 1.07⋅10−81.07 \cdot 10^{-8} at layer eighteen, still under the bound. Theorem 1 holds throughout; over twelve layers its rate is too slow to force the collapse. Geshkovski and colleagues (2023) observe two such timescales numerically in a related dynamics, a continuous-time flow of tokens on a sphere: clusters form fast and merge slowly, toward the single point they prove is the long-time limit.

Proposition 2 (The skip keeps the diameter).

For X′=X+AXWX' = X + AXW, diam⁡(X′)≥(1−τ(A)∥W∥)diam⁡(X)\operatorname{diam}(X') \ge (1 - \tau(A)\lVert W\rVert)\operatorname{diam}(X), and every pair satisfies ∥xi′−xj′∥≥∥xi−xj∥−τ(A)∥W∥diam⁡(X)\lVert x'_i - x'_j \rVert \ge \lVert x_i - x_j \rVert - \tau(A)\lVert W\rVert \operatorname{diam}(X). Over a stack, if every τ(Al)∥Wl∥≤1\tau(A_l)\lVert W_l \rVert \le 1, then

diam⁡(XL)≥∏l<L(1−τ(Al)∥Wl∥)diam⁡(X0)≥(1−∑l<Lτ(Al)∥Wl∥)diam⁡(X0).\operatorname{diam}(X_L) \ge \prod_{l \lt L} \bigl(1 - \tau(A_l)\lVert W_l\rVert\bigr) \operatorname{diam}(X_0) \ge \Bigl(1 - \sum_{l \lt L} \tau(A_l)\lVert W_l \rVert\Bigr)\operatorname{diam}(X_0).
Proof.

For any pair, xi′−xj′=(xi−xj)+((AXW)i−(AXW)j)x'_i - x'_j = (x_i - x_j) + \bigl((AXW)_i - (AXW)_j\bigr), and by Theorem 1 (i) applied to XWXW, with diam⁡(XW)≤∥W∥diam⁡(X)\operatorname{diam}(XW) \le \lVert W \rVert \operatorname{diam}(X), the second term has norm at most τ(A)∥W∥diam⁡(X)\tau(A)\lVert W \rVert \operatorname{diam}(X). The reverse triangle inequality gives the pairwise claim, and a pair with ∥xi−xj∥=diam⁡(X)\lVert x_i - x_j \rVert = \operatorname{diam}(X) gives the first claim. Iterating gives the product, and ∏l(1−al)≥1−∑lal\prod_l (1 - a_l) \ge 1 - \sum_l a_l for al∈[0,1]a_l \in [0, 1] by induction.

∎

Pure attention multiplies the diameter by at most τ∥W∥\tau\lVert W\rVert per layer. The skip adds each token back, so every old difference survives inside the new one, beside a correction of norm at most τ∥W∥diam⁡(X)\tau\lVert W\rVert \operatorname{diam}(X), and a stack of small updates, with ∑lτ(Al)∥Wl∥<1\sum_l \tau(A_l)\lVert W_l \rVert \lt 1, cannot erase the diameter. A smaller gap can go. Take X=(0,0.1,10)⊤X = (0, 0.1, 10)^\top, W=IW = I, and AA with rows (0.9,0,0.1)(0.9, 0, 0.1), (0.91,0,0.09)(0.91, 0, 0.09), and (0.9,0,0.1)(0.9, 0, 0.1), so τ(A)=0.01\tau(A) = 0.01. Then X+AX=(1,1,11)⊤X + AX = (1, 1, 11)^\top: the first two tokens merge, and the diameter stays 1010. The proposition protects the widest gap, and any gap wider than the correction, not every pair. In all five of the laboratory’s runs with the skip, the diameter never shrinks.

What the skip keeps is the diameter, though, not its share of the stream. If every row of AA is the same, AXAX is one common vector, and X+AXX + AX adds that vector to every token: the differences stay where they were while the common part grows. A wide kernel heads there, and not by staying wide. At β=0.25\beta = 0.25 the first AA is close to uniform, but the stream grows, the scores grow with it, and τ\tau runs 0.1880.188, 0.2460.246, 0.3540.354, 0.5590.559, 0.7130.713, 0.1620.162, 0.0010.001, 00 over the first eight layers. It falls at the end because the rows agree, not because they are flat: within seven layers every row sits on one token, the same for all of them. From there the cloud only translates. Its diameter stops at 3.583.58 times its start, and its relative spread ∥X−1xˉ⊤∥F/∥X∥F\lVert X - \mathbf{1}\bar{x}^\top \rVert_F / \lVert X \rVert_F halves each layer, to 0.00160.0016 at layer twelve. Proposition 2 is a statement about the first quantity, not the second.


LayerNorm is a sphere in a hyperplane

Every sublayer of a pre-LN block reads the stream through LayerNorm, so its geometry is the geometry of every read.

Definition 3 (LayerNorm and RMSNorm).

For x∈Rdx \in \mathbb{R}^d, d≥2d \ge 2, not a multiple of 1\mathbf{1}, with mean μ\mu and variance σ2=1d∑k(xk−μ)2>0\sigma^2 = \frac1d \sum_k (x_k - \mu)^2 \gt 0, LayerNorm is LN⁡(x)=(x−μ1)/σ\operatorname{LN}(x) = (x - \mu\mathbf{1})/\sigma, with its learned gain 11 and bias 00, as at initialization. For x≠0x \ne 0, RMSNorm is RMS⁡(x)=d x/∥x∥\operatorname{RMS}(x) = \sqrt d\, x/\lVert x \rVert.

LayerNorm is Ba, Kiros, and Hinton’s (2016), who add a small constant to σ2\sigma^2 that we take to be 00; RMSNorm is Zhang and Sennrich’s (2019). Picture d=3d = 3: the plane x+y+z=0x + y + z = 0 through the origin, and on it the circle of radius 3\sqrt 3. LayerNorm drops each point onto the plane, then moves it along its ray to the circle, outward or inward.

Proposition 3 (LayerNorm is a sphere in a hyperplane).

Let d≥2d \ge 2, P=I−11⊤/dP = I - \mathbf{1}\mathbf{1}^\top/d, and Px≠0Px \ne 0. Then LN⁡(x)=d Px/∥Px∥\operatorname{LN}(x) = \sqrt d\, Px / \lVert Px \rVert: the orthogonal projection onto the hyperplane 1⊥\mathbf{1}^\perp, followed by the radial projection onto the sphere of radius d\sqrt d inside it. Consequently LN⁡(cx+s1)=LN⁡(x)\operatorname{LN}(cx + s\mathbf{1}) = \operatorname{LN}(x) for c>0c \gt 0 and any ss, LN⁡∘LN⁡=LN⁡\operatorname{LN} \circ \operatorname{LN} = \operatorname{LN}, and LN⁡(x)=RMS⁡(Px)\operatorname{LN}(x) = \operatorname{RMS}(Px).

Proof.

Px=x−μ1Px = x - \mu\mathbf{1}, and σ2=∥Px∥2/d\sigma^2 = \lVert Px \rVert^2/d, so (x−μ1)/σ=Px/(∥Px∥/d)(x - \mu\mathbf{1})/\sigma = Px / (\lVert Px \rVert/\sqrt d). Next, P(cx+s1)=cPxP(cx + s\mathbf{1}) = cPx, and normalizing removes c>0c \gt 0. A point yy already on the sphere in 1⊥\mathbf{1}^\perp has Py=yPy = y and ∥y∥=d\lVert y \rVert = \sqrt d, so LN⁡(y)=y\operatorname{LN}(y) = y. The last identity is Definition 3 applied to PxPx.

∎

Brody, Alon, and Yahav (2023) give this reading and argue that each of its two parts matters to the attention that follows. The first part is a projection of the kind formalStatistics’ linear-regression topic builds least squares from (its Theorem 1): centering is the projection off the intercept direction.

Corollary 1 (LayerNorm's Jacobian).

Let d≥2d \ge 2, Px≠0Px \ne 0, and u=Px/∥Px∥u = Px / \lVert Px \rVert. Then

∂LN⁡∂x=d∥Px∥(P−uu⊤),\frac{\partial \operatorname{LN}}{\partial x} = \frac{\sqrt d}{\lVert Px \rVert}\bigl(P - uu^\top\bigr),

a symmetric matrix that sends both 1\mathbf{1} and xx itself to 00. Its singular values are d/∥Px∥\sqrt d / \lVert Px \rVert, with multiplicity d−2d - 2, and 00, twice.

Proof.

With c=Pxc = Px, the differential of d c/∥c∥\sqrt d\, c/\lVert c \rVert is (d/∥c∥)(I−uu⊤) dc(\sqrt d / \lVert c \rVert)(I - uu^\top)\, dc, and dc=P dxdc = P\, dx. Since u⊥1u \perp \mathbf{1}, uu⊤P=uu⊤uu^\top P = uu^\top, which gives the formula. P1=0P\mathbf{1} = 0 and u⊤1=0u^\top \mathbf{1} = 0, so 1\mathbf{1} is sent to 00. Px=cPx = c and u⊤x=u⊤Px=∥c∥u^\top x = u^\top Px = \lVert c \rVert, so (P−uu⊤)x=c−∥c∥u=0(P - uu^\top)x = c - \lVert c \rVert u = 0. Finally P−uu⊤P - uu^\top is the orthogonal projection onto the (d−2)(d-2)-dimensional complement of span⁡{1,u}\operatorname{span}\{\mathbf{1}, u\}.

∎

LayerNorm does not care how long its input is, and its gradient says so: it loses the radial component and is scaled by 1/∥Px∥1/\lVert Px \rVert. That scale is where depth enters. For a standard Gaussian vector, x∼N(0,Id)x \sim \mathcal{N}(0, I_d), ∥Px∥\lVert Px \rVert concentrates near d\sqrt d, the thin shell of formalRAG’s high-dimensional-geometry topic (its Theorem 1), so at large dd LayerNorm’s radial step barely moves such a vector: the notebook’s median ∥LN⁡(x)−Px∥/∥Px∥\lVert \operatorname{LN}(x) - Px \rVert / \lVert Px \rVert is below 0.0250.025 at d=512d = 512 and above 0.10.1 at d=8d = 8. Measured from xx itself, so that the centering counts too, the median at d=512d = 512 is 0.0440.044. The radius belongs to unit variance: at N(0,9Id)\mathcal{N}(0, 9I_d) the same radial change is about 2/32/3. LayerNorm acts when the stream’s norm drifts away from d\sqrt d, and in a pre-LN stack it does.


The identity path

Theorem 2 (The identity path).

(i) For a residual stack xk+1=xk+fk(xk)x_{k+1} = x_k + f_k(x_k), with JkJ_k the Jacobian of fkf_k at the point the forward pass visits,

∂xL∂xl=(I+JL−1)⋯(I+Jl)=∑{k1<⋯<km}⊆{l,…,L−1}Jkm⋯Jk1,\frac{\partial x_L}{\partial x_l} = (I + J_{L-1}) \cdots (I + J_l) = \sum_{\{k_1 \lt \dots \lt k_m\} \subseteq \{l, \dots, L-1\}} J_{k_m} \cdots J_{k_1},

a sum of 2L−l2^{L-l} terms in which the empty subset contributes II. So the gradient of a loss at xlx_l is the gradient at xLx_L, unchanged, plus a term for every nonempty set of sublayers.

(ii) In a pre-LN stack with d≥3d \ge 3, fk=Fk∘LN⁡f_k = F_k \circ \operatorname{LN}, so Jk=JFk JLN⁡(xk)J_k = J_{F_k}\, J_{\operatorname{LN}}(x_k) with ∥JLN⁡(xk)∥=d/∥Pxk∥\lVert J_{\operatorname{LN}}(x_k) \rVert = \sqrt d / \lVert P x_k \rVert. As the stream grows, that LayerNorm factor of JkJ_k shrinks, and the identity term has no such factor. This bounds one factor of each branch, not a whole gradient.

(iii) In a post-LN stack, xk+1=LN⁡(xk+Fk(xk))x_{k+1} = \operatorname{LN}(x_k + F_k(x_k)) and ∂xk+1/∂xk=JLN⁡(xk+Fk(xk)) (I+JFk)\partial x_{k+1}/\partial x_k = J_{\operatorname{LN}}(x_k + F_k(x_k))\,(I + J_{F_k}). Every path, the skip-only path included, passes through L−lL - l LayerNorm Jacobians.

Proof.

For (i), the multivariate chain rule of formalCalculus’ Jacobian topic (its Theorem 2) gives ∂xk+1/∂xk=I+Jk\partial x_{k+1}/\partial x_k = I + J_k and composes these by multiplication. Multiplying out the product of L−lL - l binomials chooses, at each layer, either II or JkJ_k, which gives one term per subset with its factors in layer order. Parts (ii) and (iii) are the chain rule applied to the two block forms, with Corollary 1 for the norm.

∎

Veit, Wilber, and Belongie (2016) read (i) as an ensemble of paths of different lengths. It is also the attention topic’s one-hop property (its Proposition 5) one level up: there, the gradient from a later position reached an earlier one in a single hop through an attention weight; here, the gradient from the top of the stack reaches every layer through a single identity.

Parts (ii) and (iii) are where LayerNorm’s placement matters. Xiong and colleagues (2020, their Theorem 1) show by mean-field arguments that at initialization the gradient of the last block’s MLP weights is O(dln⁡d)O(d\sqrt{\ln d}) in a post-LN stack and O(dln⁡d/L)O(d\sqrt{\ln d / L}) in a pre-LN one, and they trace post-LN’s need for learning-rate warmup to the first bound. We do not prove their theorem. We measure the scaling it predicts, on random stacks with d=64d = 64, four heads, and a ReLU MLP of width 256256, read out by a random linear map through one final LayerNorm, as root-mean-squares over eight draws:

depth LLpre-LN, last ∥∂L/∂W2∥F\lVert\partial\mathcal{L}/\partial W_2\rVert_Fpost-LNpre-LN ∥xL∥\lVert x_L \rVert
6610.16910.16922.01922.01924.65924.659
12127.6737.67323.41623.41633.64133.641
24245.2185.21822.71822.71849.28149.281

From L=6L = 6 to 2424 the pre-LN gradient falls by a factor of 1.951.95, against 4=2\sqrt 4 = 2; the post-LN gradient does not move, and at L=24L = 24 it is 4.354.35 times the pre-LN one. The last column is the mechanism, and it is the readout’s. In a pre-LN stack each block adds to the stream, its squared norm grows linearly in depth, and the gradient reaches the last block through the final LayerNorm, whose Jacobian scales as 1/∥PxL∥1/\lVert Px_L \rVert, so like 1/L1/\sqrt L: the first and last columns multiply to 251251, 258258, and 257257. It is a statement about the last block, not every branch. The first block’s gradient is 23.40323.403, 24.20824.208, and 23.90423.904 at the same depths, and does not shrink. A post-LN stack pins the stream at ∥x∥=d=8\lVert x \rVert = \sqrt d = 8. The shape of the gradient across layers depends on the initialization, and ours differs from the figure Xiong and colleagues report; we claim the scaling, not the shape.


The stream as a channel

To see the stream at work we remove everything that is not attention.

Definition 4 (The attention-only model; circuits; composition).

The attention-only model has an embedding E∈RV×dE \in \mathbb{R}^{V \times d} and an unembedding U∈Rd×VU \in \mathbb{R}^{d \times V}; it reads tokens t1,…,tnt_1, \dots, t_n as x0=E[t]x_0 = E[t] (one row per token), updates xl+1=xl+MHA⁡l(xl)x_{l+1} = x_l + \operatorname{MHA}_l(x_l) with causal heads, rotary positions, and query and key biases, and outputs logits xLUx_L U. It has no MLP and no LayerNorm. Head (l,h)(l, h) writes through its OV circuit WOVlh=WVlhWOlh∈Rd×dW_{OV}^{lh} = W_V^{lh} W_O^{lh} \in \mathbb{R}^{d \times d}, of rank at most dhd_h. A path is a chain of heads (l1,h1),…,(lm,hm)(l_1, h_1), \dots, (l_m, h_m) with l1<⋯<lml_1 \lt \dots \lt l_m. The composition score of heads (0,h)(0, h) and (1,h′)(1, h') is ∥WOV0hM∥F/(∥WOV0h∥F∥M∥F)\lVert W_{OV}^{0h} M \rVert_F / (\lVert W_{OV}^{0h}\rVert_F \lVert M \rVert_F), with M=WK1h′M = W_K^{1h'} for K-composition, WQ1h′W_Q^{1h'} for Q-composition, and WOV1h′W_{OV}^{1h'} for V-composition.

This is the setting of Elhage and colleagues’ (2021) framework, which names the residual stream and the two circuits. The OV circuit’s rank bound is the singular-value picture of formalML’s SVD topic (its Theorem 1), and it is the same kind of bound as the attention topic’s one-head rank bound (its Proposition 7), which limits rank⁡log⁡A\operatorname{rank} \log A, seen from the write side. The composition score measures how much of what one head writes the other reads.

Theorem 3 (The path expansion).

Let AlhA^{lh} be the attention matrix of head (l,h)(l, h) in the forward pass. Then

xLU=∑pathsAlmhm⋯Al1h1  x0  WOVl1h1⋯WOVlmhm  U,x_L U = \sum_{\text{paths}} A^{l_m h_m} \cdots A^{l_1 h_1}\; x_0\; W_{OV}^{l_1 h_1} \cdots W_{OV}^{l_m h_m}\; U,

where the empty path contributes the direct path x0U=E[t]Ux_0 U = E[t]U. With LL layers of HH heads there are (1+H)L(1 + H)^L paths.

Proof.

Each layer is xl+1=xl I+∑hAlhxlWOVlhx_{l+1} = x_l\, I + \sum_h A^{lh} x_l W_{OV}^{lh}. An attention matrix acts on the token index, from the left, and WOVW_{OV} on the feature index, from the right, so A(XW)=(AX)WA(XW) = (AX)W and the two kinds of factor can be collected separately. Substituting xlx_l into xl+1x_{l+1} for each ll and distributing chooses, at each layer, either the skip or one head, and the chosen heads form a path. Collecting the left factors and the right factors gives the formula; at each layer there are 1+H1 + H choices.

∎

The direct path is a function of the current token alone: a bigram model, built into the embedding and unembedding. The one-head paths copy what a head attends to; the two-head paths compose. The expansion is exact, and the notebook checks it against the forward pass of the trained model of the next section, whose two layers of two heads give 99 paths, to about 2⋅10−142 \cdot 10^{-14}. Dong, Cordonnier, and Loukas use a decomposition of this kind to prove their collapse rate. One caution keeps it honest: the AlhA^{lh} depend on the stream, so the expansion is linear in the values, not in the attention. Q- and K-composition live inside the patterns, and only V-composition appears in the products of OV circuits.

Proposition 4 (Orthogonal subspaces do not talk).

If WOV0hWK1h′=0W_{OV}^{0h} W_K^{1h'} = 0 for every layer-0 head hh, then the keys of head (1,h′)(1, h') computed from x1x_1 equal those computed from x0x_0, and its K-composition scores are 00. If also WOV0hWQ1h′=0W_{OV}^{0h} W_Q^{1h'} = 0 for every hh, the same holds for its queries, and its attention pattern is the same with or without layer 0’s output.

Proof.

x1WK1h′=x0WK1h′+∑hA0hx0 WOV0hWK1h′=x0WK1h′x_1 W_K^{1h'} = x_0 W_K^{1h'} + \sum_h A^{0h} x_0\, W_{OV}^{0h} W_K^{1h'} = x_0 W_K^{1h'}, and the key bias and the rotation are applied after this product. The same computation with WQ1h′W_Q^{1h'} gives the queries, and the pattern depends on the stream only through queries and keys.

∎

The stream is one dd-dimensional space shared by every head, and heads communicate only through the subspaces where one writes and another reads. The notebook builds a model whose layer-0 heads write into the first 1616 of 3232 coordinates while the layer-1 keys read only the last 1616, and computing those keys from x0x_0 leaves the pattern unchanged to 10−1210^{-12}. The keys are only half of a score, though. The queries still read x1x_1, and removing layer 0’s output moves each row of the pattern by a mean total variation of 0.1040.104. Restrict the queries to the last 1616 coordinates as well, and the pattern with and without layer 0’s output agrees to 10−1210^{-12}.


Induction heads

Here is a task that needs two heads to talk. Draw a random block of tokens from a vocabulary of V=256V = 256, of period pp between 66 and 2424, and repeat it to 4848 tokens. From position pp on, the next token is predictable, by a rule Olsson and colleagues (2022) call induction: find where the current token occurred before, and copy what came after it, [A][B] … [A] → [B]. We train attention-only models with d=32d = 32 and two heads of width 1616 per layer, rotary positions, and hand-written gradients, for 10001000 Adam steps on fresh sequences, and test on 10001000 more, scoring the positions from pp on:

modelloss (nats)accuracy
two layers0.1570.1570.9740.974
one layer4.2804.2800.1080.108
two layers, layer 1’s keys read from x0x_06.1356.1350.0750.075

Guessing uniformly costs ln⁡256=5.545\ln 256 = 5.545 nats. The two-layer model solves the task; the one-layer model does not come close. The last row cuts one connection: layer 1’s keys are computed from the embeddings instead of the stream, so they cannot read anything layer 0 wrote, and the solved model falls apart, below even the one-layer model.

The two-layer model’s heads say how it works. Head (0,0)(0, 0) puts 0.8870.887 of its weight on the previous token, on average. Its content-free score, the part that comes from its query and key biases alone, is bq⊤R(−Δ) bk/dhb_q^\top R(-\Delta)\, b_k / \sqrt{d_h} for a key Δ\Delta positions back: the positional-encodings topic’s kernel over offsets, and it peaks at Δ=1\Delta = 1, with 7.7837.783 against 6.7096.709 at Δ=0\Delta = 0. So head (0,0)(0,0) is a positional head: through position 3737 its weight on the previous token is about 0.980.98, and it writes a copy of each token’s predecessor into the stream at that token. The mean hides a drop. From position 3939 the mean weight is under 0.50.5, shared about evenly with the key 3939 positions back, where the kernel has its next peak, 6.6876.687. The model’s accuracy does not fall there: it stays between 0.9680.968 and 0.9830.983 from position 3939 on. Both layer-1 heads put 0.5930.593 and 0.5940.594 of their weight on the position i−p+1i - p + 1, just after the current token’s occurrence one period back, the induction target, and 0.9430.943 and 0.9400.940 on the positions after any earlier occurrence. Nearly all of those hold a correct copy of the next token. A block can repeat a token by chance, and then, at 4.85%4.85\% of the scored positions, one of them holds another token; the heads put about 0.020.02 of their weight on such positions. Every K-composition score is between 0.2450.245 and 0.2720.272, against 0.0460.046 to 0.0750.075 for Q-composition and 0.0360.036 to 0.0760.076 for V-composition, and above the largest K-score the same model had at its initialization, 0.1880.188. Those scores do not separate the two layer-0 heads, so we cut them one at a time. Give layer 1’s keys x0x_0 plus head (0,0)(0, 0)‘s write alone, and the model stays solved, at 0.2280.228 nats and accuracy 0.9690.969. Give them head (0,1)(0, 1)‘s write alone, and it fails, at 5.3915.391 nats and 0.0840.084. Their keys read what head (0,0)(0, 0) wrote.

Proposition 5 (What one layer's keys see).

In a one-layer model, the score sh(i,j)s_h(i, j) of head hh is a function of (ti,i,tj,j)(t_i, i, t_j, j) alone. In particular it does not change when the token at position j−1j - 1 changes. In two layers, the key at jj reads x1[j]=x0[j]+∑h∑kAjk0h x0[k] WOV0hx_1[j] = x_0[j] + \sum_h \sum_k A^{0h}_{jk}\, x_0[k]\, W_{OV}^{0h}, which contains x0[j−1]x_0[j-1] when some layer-0 head attends to the previous token.

Proof.

In one layer, the query at ii is the rotation by ii of E[ti]WQ+bqE[t_i]W_Q + b_q and the key at jj is the rotation by jj of E[tj]WK+bkE[t_j]W_K + b_k. The two-layer formula is Definition 4’s update at l=0l = 0.

∎

Induction must attend to the position whose predecessor is the current token, and a one-layer score cannot see predecessors, so it cannot pick that position out by its content. Two layers can, through K-composition. Proposition 5 is about information, not a bound on loss: a one-layer model can still raise the probability of every token it has seen, and how close it gets to that in training is a measurement. The notebook changes the token before position jj and recomputes the last layer’s score at (i,j)(i, j): in the one-layer model it moves by less than 10−1210^{-12}, and in the two-layer model by 4.454.45 nats on average.

Theorem 3 shows where the answer lives. At the scored positions, the paths that end in a layer-1 head carry more than 90%90\% of the correct token’s centered logit (the median over positions), and the direct path and layer-0 paths alone rank the correct token first less than 5%5\% of the time. The logit lens (nostalgebraist 2020) reads the stream through the unembedding between layers, xlUx_l U. This model has no final LayerNorm, so the lens is its own readout, and the probability of the correct token after the embedding, after layer 00, and after layer 11 is 0.0040.004, 0.0040.004, and 0.9580.958, with chance 1/256=0.0041/256 = 0.004. The answer exists only after the second layer reads the first. On models with a final LayerNorm the lens reads UU applied to LN⁡(xl)\operatorname{LN}(x_l), a heuristic that Belrose and colleagues (2023) refine by training a probe for each layer.


The stream, interactively

The laboratory has two figures. Figure A is the geometry: the ten tokens of the collapse experiment, layer by layer, with and without the skip at five temperatures, beside their diameters and Theorem 1’s bound, and the LayerNorm picture at d=3d = 3, where you can center a cloud, normalize it, and scale it without moving the result. Figure B is the trained model: the previous-token head’s and the induction head’s attention on a test sequence of period 1111, the correct token’s logit split into its 99 paths at any position you pick, the logit lens, the ablation, and the filing from the case study below.

A · Smoothing without a self — collapse, the skip, LayerNorm, and the identity path
l = 12
drawn at the input’s scale≤10⁻¹²10⁻⁸10⁻⁴110000024681012diameter of the cloud, β = 1 (log scale)layer l
pure attentionwith the skipTheorem 1 bound, ∏τ · diam(X₀)
diameter
0
τ of layer 12
0.000
relative spread ‖X − 1x̄ᵀ‖/‖X‖
0.0000
diam(X₁₂) / diam(X₀)
0

A wide kernel (small β) keeps τ below 1, and the pure stack shrinks the cloud to a point, under Theorem 1’s bound. A narrow kernel (β = 4) lets a few long tokens win the rows: τ stays near 1, the bound falls slowly, and at layer 12 the cloud holds two clusters, which merge by layer 18, past this slider. With the skip the diameter never shrinks in these runs (Proposition 2 is the floor beneath them), but at β = 0.25 the relative spread still falls: the skip keeps the diameter, not its share.

B · Two heads that compose — the trained two-layer model on a sequence of period 11
i = 47
001212242436364747key position j → (rows: query i)
token at i, then the next
84 → 65
largest weight in row i
0.55 on j = 26
induction target i − p + 1
37

The previous-token head’s weight sits just left of the diagonal, at j = i − 1, until position 39, where part of it moves to j = i − 39. The induction head attends to the earlier positions whose predecessor is the current token: i − p + 1 (outlined), and one or more periods further back on a long repetition. Unless the block repeats a token by chance, each holds a copy of the next token. Its keys can find them because the previous-token head wrote predecessors into the stream (Proposition 5).


Finance case study: completing a company’s name


Where this goes next

  • Contextual embeddings. The same block without the causal mask, trained to fill in masked tokens, gives contextual word vectors; the contextual-embeddings topic builds it on this one.
  • Scaling laws. Depth and width are the axes along which models scale, and the growing pre-LN stream of Theorem 2 (ii) is one reason depth is not free; the scaling-laws topic takes the empirical side.
  • Euler steps. A residual block x+f(x)x + f(x) is one step of Euler’s method for the flow x′=f(x)x' = f(x), whose global error formalCalculus’ numerical-ODEs topic bounds (its Theorem 1); a deep stack of small updates discretizes a trajectory of the tokens, and Geshkovski and colleagues study the clusters of a related flow.
  • Superposition. A 3232-dimensional stream carried 256256 embeddings, drawn at random and then trained, that the induction head still copied. Many nearly orthogonal directions fit in few dimensions: the trained table’s root-mean-square cosine is 0.2010.201. That is the concentration idea behind formalRAG’s Johnson–Lindenstrauss topic, though its Theorem 3 needs more than 133133 dimensions for 256256 points, so it does not cover this case.

Honest caveats


Implementation

The companion notebook (notebookPath) imports transformer_block_residual_stream.py, which owns every number on this page. That module imports the positional-encodings topic’s module for its rotations, and through it the attention topic’s attention function and rounding conventions, the neural-language-models topic’s gradient checker and Adam constants, and the shared finance corpus. It trains three attention-only models from scratch in NumPy, two on repeated random sequences and one on filings, with hand-written gradients, and runs a harness of 2222 assertion-based tests in about twenty-five seconds on a laptop CPU. The tests cover:

  • Proposition 1 against the attention topic’s attention function, and the MLP as a key–value sum.
  • Proposition 3 and Corollary 1 at d=2d = 2, 33, 88, and 6464, against central differences, and the thin shell.
  • Theorem 1 on 300300 random instances in three norms, and Theorem 1 and Proposition 2 on the laboratory’s cloud and on 100100 random stacks with random value maps; the narrow-kernel run through layer eighteen, the wide-kernel run landing on one token, and the merged pair.
  • Theorem 2 against the chain rule and the subset sum; the pre-LN and post-LN gradient scaling.
  • Theorem 3 on the trained model and on a random three-layer model; Proposition 4 on a constructed model, keys alone and keys with queries; Proposition 5 on both trained models.
  • The induction experiments, the heads by position, the composition scores, the per-head cut, the paths, and the logit lens; the finance table.
  • Every hand-written gradient against central differences: the attention-only model at random coordinates, and both stacks at every coordinate.

The laboratory reads its data from a JSON file that one of those tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

References & Further Reading