Simple Algorithm
Deep Learning · Emergence · 26 min

Reading the Residual Stream

The logit lens, tuned lenses, iterative inference and redundant layers.

A residual network only ever adds to its stream, so the state halfway up already lives in the same space as the output. Decode it with the model's own last layer and you can watch a language model's prediction take shape, layer by layer. The pictures are striking, and they come with caveats: the decoding can misread early layers, and many of the late layers turn out to be removable.

What you’ll learn

  • Derive iterative refinement from a first-order expansion of the loss along the residual path, and state the evidence that later residual blocks make small, loss-reducing corrections.
  • Describe the residual stream as a linear communication channel: reading and writing subspaces, virtual weights, the missing privileged basis and limited bandwidth.
  • Define the logit lens and the tuned lens, state what each assumes about the remaining layers, and explain their failure modes and how the tuned lens is trained and tested.
  • Summarize the evidence that many late layers of large language models are redundant, what it implies for pruning and early exit, and the competing explanations.

Iterative refinement

The textbook picture of a deep network is a hierarchy in which each layer computes new, more abstract features from the last. Residual networks fit another picture better. Greff, Srivastava and Schmidhuber (2017) argued that in highway and residual networks a group of successive layers iteratively refines an estimate of the same features instead of computing a new representation at every layer, and that this view leads directly to both architectures. Lesion studies point the same way: deleting a single block from a trained ResNet barely changes its error (Veit, Wilber & Belongie, 2016), which would be fatal in a strict hierarchy.

DerivationResidual blocks move down the loss (Jastrzębski et al., 2018)
  1. ℓ(hj+1)=ℓ(hj+Fj(hj))=ℓ(hj)+⟨∇ℓ(hj), Fj(hj)⟩+O(∥Fj∥2)\ell(\mathbf h_{j+1}) = \ell\big(\mathbf h_j + F_j(\mathbf h_j)\big) = \ell(\mathbf h_j) + \big\langle\nabla\ell(\mathbf h_j),\,F_j(\mathbf h_j)\big\rangle + \order{\norm{F_j}^2}

    Write ℓ(h)\ell(\mathbf h) for the loss obtained by applying the network's output layer directly to a state h\mathbf h, which makes sense because every state of the stream lives in the same space. For blocks hj+1=hj+Fj(hj)\mathbf h_{j+1} = \mathbf h_j + F_j(\mathbf h_j), expand around the state one block lower:

  2. ℓ(hL)≈ℓ(hi)+∑j=iL−1⟨∇ℓ(hj), Fj(hj)⟩\ell(\mathbf h_L)\approx\ell(\mathbf h_i) + \sum_{j=i}^{L-1}\big\langle\nabla\ell(\mathbf h_j),\,F_j(\mathbf h_j)\big\rangle

    Repeat down to block ii and add up: the final loss is the loss read out at block ii plus one first-order term per block above it.

  3. cos⁡(Fj(hj), ∇ℓ(hj))<0⟹ℓ(hj+1)<ℓ(hj) to first order\cos\big(F_j(\mathbf h_j),\,\nabla\ell(\mathbf h_j)\big) < 0\quad\Longrightarrow\quad\ell(\mathbf h_{j+1}) < \ell(\mathbf h_j)\ \text{to first order}

    Training lowers ℓ(hL)\ell(\mathbf h_L), and to first order it can do so by making every block's output point against the gradient of the loss at its input. Each block then acts like a small gradient-descent step on the representation itself. The approximation is good where blocks are small compared with the stream.

Jastrzębski, Arpit, Ballas, Verma, Che and Bengio (2018) measured both ingredients in ResNets on CIFAR. The cosine between each block's output and the loss gradient at its input was negative for every block, most strongly for the higher blocks, which also changed the representation least (∥Fj∥/∥hj∥\norm{F_j}/\norm{\mathbf h_j} small). Dropping one of the first blocks hurt accuracy, while dropping most of the higher ones barely mattered, and examples close to the decision boundary were the ones the top blocks corrected. Their summary: the first blocks learn representations, the later ones refine them. Sharing weights across residual blocks, which would make the refinement literally iterative, naively led to exploding representations and, surprisingly, overfitting.

Check your understanding

In the expansion ℓ(hL)≈ℓ(hi)+∑j⟨∇ℓ(hj),Fj(hj)⟩\ell(\mathbf h_L)\approx\ell(\mathbf h_i) + \sum_j\langle\nabla\ell(\mathbf h_j), F_j(\mathbf h_j)\rangle, what does a block do whose output has a negative cosine with ∇ℓ(hj)\nabla\ell(\mathbf h_j)?

  1. It raises the loss, so it should be pruned
  2. It has stopped learning, since its gradient is zero
  3. It moves the representation downhill in the loss, like a small gradient-descent step on the hidden state
  4. It reverses the direction of the stream
Show the answer

C. It moves the representation downhill in the loss, like a small gradient-descent step on the hidden state

A negative inner product with the gradient means the update lowers the loss to first order, exactly as a step along −∇ℓ-\nabla\ell would. That is the sense in which residual blocks perform iterative inference.

The stream as a communication channel

For transformers, Elhage et al. (2021) gave the residual stream a precise reading. Every component (the token embedding, each attention head, each MLP layer, the unembedding) reads from the stream with a linear map and writes to it by adding a linear map's output. The stream does no computation of its own: it is the sum of everything written so far, a shared channel through which the components communicate.

DerivationVirtual weights, and no privileged basis
  1. hm=h0+∑k<mWout(k) fk(Win(k)hk)\mathbf h_m = \mathbf h_0 + \sum_{k<m}W^{(k)}_{\text{out}}\,f_k\big(W^{(k)}_{\text{in}}\mathbf h_k\big)

    Write layer kk's contribution as Wout(k)fk(Win(k)hk)W^{(k)}_{\text{out}}f_k\big(W^{(k)}_{\text{in}}\mathbf h_k\big), with its nonlinear part fkf_k (an MLP's activation, or attention's mixing across positions) in the middle. The stream at layer mm contains every earlier output:

  2. Win(m)hm=Win(m)h0+∑k<mWin(m)Wout(k)⏟virtual weightfk(Win(k)hk)W^{(m)}_{\text{in}}\mathbf h_m = W^{(m)}_{\text{in}}\mathbf h_0 + \sum_{k<m}\underbrace{W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}}_{\text{virtual weight}}f_k\big(W^{(k)}_{\text{in}}\mathbf h_k\big)

    Layer mm reads Win(m)hmW^{(m)}_{\text{in}}\mathbf h_m, so its input contains a term Win(m)Wout(k)fk(⋅)W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}f_k(\cdot) for every earlier kk. The product is a virtual weight: a direct connection from layer kk to layer mm that appears in no single weight matrix.

  3. (Win(m)R⊤)(RWout(k))=Win(m)Wout(k)\big(W^{(m)}_{\text{in}}R^\top\big)\big(RW^{(k)}_{\text{out}}\big) = W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}

    Rotate the stream by an orthogonal RR: replace every WoutW_{\text{out}} by RWoutRW_{\text{out}}, every WinW_{\text{in}} by WinR⊤W_{\text{in}}R^\top, and the embedding and unembedding likewise. Every virtual weight, and so the whole computation, is unchanged. The stream has no privileged basis: its coordinates mean nothing on their own, which is why interpretability looks for directions instead (Probing & the Linear Representation Hypothesis).

  4. The symmetry is exact for the simplified models Elhage et al. analyzed, which leave out layer normalization (up to a rescaling it can be folded into neighboring weights). Real models nevertheless develop special coordinates, the outlier features and massive activations of Attention Sinks & Massive Activations. Elhage, Lasenby and Olah (2023) ruled out layer normalization and finite-precision arithmetic as the cause of such basis-aligned outliers and provisionally blamed training: the per-coordinate normalization of the Adam optimizer.

Bandwidth. The stream has hundreds of dimensions in small models and tens of thousands in large ones, yet far more neurons and attention-head outputs write to it than it has dimensions. Information written into a subspace stays there until another component actively removes it. Elhage et al. saw hints of "memory management": MLP neurons whose input and output weights have strongly negative cosine similarity, and attention heads with large negative eigenvalues in their WOWVW_OW_V matrices that mostly attend to the current token, both of which can erase what earlier layers wrote. How a model packs more features than dimensions into the stream is the subject of Dictionary Learning at Scale.

Decoding intermediate states: logit and tuned lenses

A pre-LN model never renormalizes its stream between blocks, so every intermediate state is on the same footing as the last one. Push it through the model's final normalization LN⁡f\operatorname{LN}_f and unembedding WU∈R∣V∣×dW_U\in\R^{\abs{\mathcal V}\times d} and you get a distribution over the vocabulary. The question is what that distribution means.

DerivationWhat a lens drops, and what it learns
  1. logits=WULN⁡f(hℓ+∑k≥ℓFk(hk))\text{logits} = W_U\operatorname{LN}_f\Big(\mathbf h_\ell + \sum_{k\ge\ell}F_k(\mathbf h_k)\Big)

    Split the model after layer ℓ\ell. Unrolling the stream, the output logits as a function of the state hℓ\mathbf h_\ell are

  2. LogitLens⁡ℓ(hℓ)=WULN⁡f(hℓ)\operatorname{LogitLens}_\ell(\mathbf h_\ell) = W_U\operatorname{LN}_f(\mathbf h_\ell)

    The logit lens (nostalgebraist, 2020) sets the remaining updates to zero:

  3. TunedLens⁡ℓ(hℓ)=WULN⁡f(Aℓhℓ+bℓ),min⁡Aℓ, bℓ Ex DKL(pfinal(⋅∣x) ∥ pℓ(⋅∣x))\operatorname{TunedLens}_\ell(\mathbf h_\ell) = W_U\operatorname{LN}_f(A_\ell\mathbf h_\ell + \mathbf b_\ell),\qquad\min_{A_\ell,\,\mathbf b_\ell}\ \E_{\mathbf x}\,\KL\big(p_{\text{final}}(\cdot\mid\mathbf x)\,\big\|\,p_\ell(\cdot\mid\mathbf x)\big)

    It is exact at the top, and a fair guess wherever the remaining updates are small or point in directions that WULN⁡fW_U\operatorname{LN}_f ignores. The tuned lens (Belrose et al., 2023) replaces the zero by a learned affine translator for each layer, trained so that its distribution matches the model's own final one:

  4. The bias bℓ\mathbf b_\ell can absorb the average of the dropped updates, which the network may rely on as a constant offset; the matrix AℓA_\ell corrects for the drift of the stream's basis and scale with depth. Distilling the model's own output, rather than training on the true next tokens, keeps the lens from learning more than the model computes.

What the logit lens shows. On GPT-2, nostalgebraist found that the decoded distributions converge roughly monotonically toward the final one, often getting close well before the last layer, passing from uninterpretable outputs through plausible words of the right kind to the eventual answer; the early layers almost never decoded to the input token itself. But the method is brittle. It fails to give useful predictions on the GPT-Neo family, and on BLOOM and OPT-125M its top prediction is often just the input token (Belrose et al., 2023). It is also biased: on GPT-Neo-2.7B, averaged over the data, its predicted distribution differed from the model's average output distribution by about 4 to 5 bits of KL divergence at most layers. Two culprits are a few "rogue" dimensions of very high variance, spread unevenly across layers, and a steady drift of the stream's covariance with depth.

What the tuned lens adds. On models up to 20 billion parameters, the tuned lens gave predictions of lower perplexity and lower bias than the logit lens, with less variation between independently trained models. Causal tests suggested that it relies on features the model itself uses: ablating the directions it depends on most changed the model's own outputs, and perturbing the stream moved the lens's prediction and the model's in similar ways. The trajectory of latent predictions also served as input to an anomaly detector: on Pythia 12B it separated prompt-injection inputs from normal ones almost perfectly on five of nine tasks, though a simple distance-based detector on middle-layer states did as well or better on most of them. And examples that took more training steps to learn tended to settle at later layers.

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class TunedLens(nn.Module):
    """One affine translator per layer, decoded by the frozen model's final norm and unembedding."""
    def __init__(self, n_layers: int, d: int, final_norm: nn.Module, unembed: nn.Linear):
        super().__init__()
        self.translators = nn.ModuleList(nn.Linear(d, d) for _ in range(n_layers))
        for t in self.translators:                  # start as the logit lens: A = I, b = 0
            nn.init.eye_(t.weight)
            nn.init.zeros_(t.bias)
        self.final_norm, self.unembed = final_norm, unembed
        for p in [*final_norm.parameters(), *unembed.parameters()]:
            p.requires_grad_(False)                 # only the translators are trained

    def forward(self, h: torch.Tensor, layer: int) -> torch.Tensor:
        return self.unembed(self.final_norm(self.translators[layer](h)))   # logits

def lens_loss(lens: TunedLens, hiddens: list, final_logits: torch.Tensor) -> torch.Tensor:
    """Sum over layers of KL(model's final distribution || lens distribution): distillation, not labels."""
    target = F.log_softmax(final_logits, dim=-1)
    return sum(F.kl_div(F.log_softmax(lens(h, l), dim=-1), target, log_target=True, reduction='batchmean')
               for l, h in enumerate(hiddens))

The translators start at Aℓ=IA_\ell = I and bℓ=0\mathbf b_\ell = \mathbf 0, so the untrained tuned lens is the logit lens, as in Belrose et al. hiddens holds the residual stream at the input of each block and final_logits the model's own output; only the translators are optimized. When a library hands you hidden states, check whether a normalization has already been applied to any of them before applying final_norm again.

Check your understanding

The logit lens decodes the state at layer ℓ\ell as WULN⁡f(hℓ)W_U\operatorname{LN}_f(\mathbf h_\ell). What does it implicitly assume about the layers above ℓ\ell?

  1. That they are linear
  2. That their residual updates add up to something negligible, or to something the unembedding ignores
  3. That the model uses post-LN
  4. That the unembedding matrix is orthogonal
Show the answer

B. That their residual updates add up to something negligible, or to something the unembedding ignores

The true logits are WULN⁡f(hℓ+∑k≥ℓFk)W_U\operatorname{LN}_f\big(\mathbf h_\ell + \sum_{k\ge\ell}F_k\big), and the lens drops the sum. The tuned lens replaces the dropped sum by a learned affine correction instead of zero.

How many layers does a model need?

If late blocks mostly polish a prediction that is already in place, removing them should cost little. Four studies of open-weight language models tested this directly, with different interventions:

StudyInterventionFinding
Gromov, Tirumala, Shapourian, Glorioso & Roberts (2025)Remove the nn consecutive layers whose input and output are most similar, by the angular distance 1πarccos⁡(cos⁡)\frac1\pi\arccos(\cos) at the last token, then "heal" with a little QLoRA fine-tuningMMLU stays flat, then collapses to chance at about 45–55% of the layers removed for Llama-2 models (35% for Mistral 7B, 25% for Phi-2, 20% for Qwen); next-token loss rises smoothly; GSM8K and HellaSwag drop with any pruning
Men et al. (2025), ShortGPTDelete the layers with the lowest Block Influence, 1−cos⁡(xi,xi+1)1 - \cos(\mathbf x_i, \mathbf x_{i+1}) averaged over tokens, without fine-tuningRemoving 10 of the 40 layers of LLaMA-2-13B kept about 92% of its average score on 13 benchmarks; MMLU fell from 55.0 to 52.2 by the paper's text, to 54.7 by its table
Lad, Lee, Gurnee & Tegmark (2025)Delete or swap adjacent layers at inferenceModels kept 72–95% of their top-1 prediction accuracy without fine-tuning; the first and last layers were the most sensitive, the middle ones robust
Csordás, Manning & Potts (2025)Compare sublayer outputs with the stream, skip layers, and fit linear maps from shallow models' streams to deeper ones'Layers in the second half contribute much less, with a sharp transition between the halves; layers at the same relative depth map best onto each other
Models from 2.7 to 70 billion parameters in the first study; Llama 3.1, Qwen 3 and OLMo 2 in the last. Gromov et al. also found that simply dropping the deepest layers, keeping the final one, did nearly as well as the similarity-based choice once healed.

From such interventions, Lad et al. proposed four stages of inference common to model families: detokenization, where local context lifts raw token embeddings into higher-level representations; feature engineering, where task- and entity-specific features are refined; prediction ensembling, where hidden states are aggregated into plausible next-token predictions; and residual sharpening, where irrelevant features are suppressed to finalize the output distribution. It is a hypothesis assembled from behavioral and mechanistic evidence, not an established mechanism.

Why would late layers be removable? The explanations compete:

  • Architecture. In a pre-LN model the stream grows with depth, so a late block's update is small relative to it and the block starts, and may stay, close to the identity (Scaling Residual Branches with Depth computes the growth). Sun et al. (2025) call this the curse of depth; scaling down each LayerNorm's output with the square root of its depth made deep layers contribute more and improved pre-training at sizes from 130 million to 7 billion parameters (Normalization & Stability in Transformers).
  • Training. Csordás et al. found no sign that deeper models use their extra layers to compose more steps on multi-hop tasks, and read the evidence as depth being spent on finer adjustments to the residual rather than on new kinds of computation, which may help explain diminishing returns from depth.
  • Measurement. Question-answering benchmarks survived heavy pruning while next-token loss, math and commonsense tasks did not. Gromov et al. suggested that shallow layers store and retrieve knowledge, while deep layers matter for computations such as mathematical reasoning.
  • Redundancy by design. Like the many paths of a ResNet, neighboring layers may overlap in function, as members of an ensemble do, so removing one costs little (Veit et al., 2016; Lad et al., 2025).

The practical side follows from the same facts. Layer pruning is a cheap form of structured pruning (Pruning, Sparsity & Lottery Tickets). Early exit stops computing a token once its prediction has settled: CALM chooses per token, using confidence measures, with reported speedups of up to about three times at maintained quality (Schuster et al., 2022); LayerSkip trains with a layer dropout that grows with depth and a shared early-exit loss, then drafts tokens with the early layers and verifies them with the rest (Elhoushi et al., 2024), a self-speculative form of Speculative Decoding.

Key takeaways

  • Residual networks refine iteratively: to first order, each block lowers the loss by moving the state against the loss gradient, and later blocks make smaller corrections than earlier ones (Greff et al., 2017; Jastrzębski et al., 2018).
  • The residual stream is a linear channel: components read and write subspaces, virtual weights Win(m)Wout(k)W^{(m)}_{\text{in}}W^{(k)}_{\text{out}} connect any two layers, and in the idealized model the stream has no privileged basis.
  • The logit lens decodes hℓ\mathbf h_\ell with the final normalization and unembedding, dropping every later update; it worked on GPT-2 but is biased and brittle on other models. The tuned lens adds a learned affine translator per layer, distilled from the model's own output, and is more reliable and causally grounded.
  • Many late layers of large language models can be removed or swapped with modest losses on some benchmarks, but not on next-token loss or reasoning tasks. Whether this reflects pre-LN's growing stream, inefficient training or the choice of measurements is debated; it already powers layer pruning and early exit.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

At which layer is the logit lens exact, and why?

  1. At the first layer, because the embedding is closest to the input
  2. At the last layer, because there are no remaining residual updates to drop
  3. At every layer of a pre-LN model, because the stream is never normalized
  4. At no layer, because the final normalization is always omitted
Show the answer

B. At the last layer, because there are no remaining residual updates to drop

The logit lens computes WULN⁡f(hℓ)W_U\operatorname{LN}_f(\mathbf h_\ell), the true output with the sum of all later updates ∑k≥ℓFk\sum_{k\ge\ell}F_k set to zero. At the top that sum is empty, so the lens returns the model's own logits.

Question 2

Why is the tuned lens trained to match the model's own final distribution rather than the true next tokens?

  1. Because the true next tokens are not available for language models
  2. Because matching the final distribution is cheaper to compute
  3. Because it makes the translators exactly the identity
  4. So that the lens shows what the model computes at that layer, instead of learning to predict the data better than the model does
Show the answer

D. So that the lens shows what the model computes at that layer, instead of learning to predict the data better than the model does

A translator trained on labels could learn to extract information the model never uses. Distilling the model's own output (minimizing DKL(pfinal ∥ pℓ)\KL(p_{\text{final}}\,\|\,p_\ell)) ties the lens to the model's computation; causal tests then check that it relies on features the model uses.

Question 3

Layer kk writes to the stream with Wout(k)W^{(k)}_{\text{out}} and a later layer mm reads with Win(m)W^{(m)}_{\text{in}}. What is the virtual weight between them, and what happens to it when the stream is rotated by an orthogonal RR (with every reading and writing matrix transformed to match)?

  1. Win(m)Wout(k)W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}; it is unchanged, since Win(m)R⊤RWout(k)=Win(m)Wout(k)W^{(m)}_{\text{in}}R^\top RW^{(k)}_{\text{out}} = W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}
  2. Wout(k)Win(m)W^{(k)}_{\text{out}}W^{(m)}_{\text{in}}; it is rotated to RWout(k)Win(m)R⊤RW^{(k)}_{\text{out}}W^{(m)}_{\text{in}}R^\top
  3. Win(m)+Wout(k)W^{(m)}_{\text{in}} + W^{(k)}_{\text{out}}; it changes with RR
  4. There is none: layers communicate only with their neighbors
Show the answer

A. Win(m)Wout(k)W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}; it is unchanged, since Win(m)R⊤RWout(k)=Win(m)Wout(k)W^{(m)}_{\text{in}}R^\top RW^{(k)}_{\text{out}} = W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}

Layer mm's input contains Win(m)Wout(k)fk(⋅)W^{(m)}_{\text{in}}W^{(k)}_{\text{out}}f_k(\cdot), a direct connection through the stream. Under the rotation, R⊤R=IR^\top R = I cancels, which is why the stream has no privileged basis in this idealized model.

Question 4

Gromov et al. removed up to roughly half of Llama-2-70B's layers with little change in MMLU accuracy. Which observation in the same study cautions against concluding that the deep layers are useless?

  1. MMLU accuracy improved after pruning
  2. The final layer could be removed as easily as the others
  3. Next-token loss on held-out text rose smoothly with every layer removed, and math (GSM8K) and commonsense (HellaSwag) accuracy dropped with any pruning
  4. The pruned models needed no fine-tuning at all
Show the answer

C. Next-token loss on held-out text rose smoothly with every layer removed, and math (GSM8K) and commonsense (HellaSwag) accuracy dropped with any pruning

Question-answering benchmarks were robust up to a sharp transition, but other measures were not. Gromov et al. suggested that shallow layers store and retrieve knowledge while deep layers matter for computations such as mathematical reasoning.

Further reading

  • S. Jastrzębski, D. Arpit, N. Ballas, V. Verma, T. Che & Y. Bengio, "Residual connections encourage iterative inference," ICLR (2018).
  • N. Elhage et al., "A mathematical framework for transformer circuits," Transformer Circuits Thread (2021).
  • nostalgebraist, "interpreting GPT: the logit lens," blog post, LessWrong (2020).
  • N. Belrose, I. Ostrovsky, L. McKinney, Z. Furman, L. Smith, D. Halawi, S. Biderman & J. Steinhardt, "Eliciting latent predictions from transformers with the tuned lens," arXiv:2303.08112 (2023).
  • A. Gromov, K. Tirumala, H. Shapourian, P. Glorioso & D. A. Roberts, "The unreasonable ineffectiveness of the deeper layers," ICLR (2025).