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.
Write for the loss obtained by applying the network's output layer directly to a state , which makes sense because every state of the stream lives in the same space. For blocks , expand around the state one block lower:
Repeat down to block and add up: the final loss is the loss read out at block plus one first-order term per block above it.
Training lowers , 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 ( 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.
In the expansion , what does a block do whose output has a negative cosine with ?
- It raises the loss, so it should be pruned
- It has stopped learning, since its gradient is zero
- It moves the representation downhill in the loss, like a small gradient-descent step on the hidden state
- 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 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.
Write layer 's contribution as , with its nonlinear part (an MLP's activation, or attention's mixing across positions) in the middle. The stream at layer contains every earlier output:
Layer reads , so its input contains a term for every earlier . The product is a virtual weight: a direct connection from layer to layer that appears in no single weight matrix.
Rotate the stream by an orthogonal : replace every by , every by , 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).
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 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 and unembedding and you get a distribution over the vocabulary. The question is what that distribution means.
Split the model after layer . Unrolling the stream, the output logits as a function of the state are
The logit lens (nostalgebraist, 2020) sets the remaining updates to zero:
It is exact at the top, and a fair guess wherever the remaining updates are small or point in directions that 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:
The bias can absorb the average of the dropped updates, which the network may rely on as a constant offset; the matrix 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.
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 and , 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.
The logit lens decodes the state at layer as . What does it implicitly assume about the layers above ?
- That they are linear
- That their residual updates add up to something negligible, or to something the unembedding ignores
- That the model uses post-LN
- 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 , 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:
| Study | Intervention | Finding |
|---|---|---|
| Gromov, Tirumala, Shapourian, Glorioso & Roberts (2025) | Remove the consecutive layers whose input and output are most similar, by the angular distance at the last token, then "heal" with a little QLoRA fine-tuning | MMLU 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), ShortGPT | Delete the layers with the lowest Block Influence, averaged over tokens, without fine-tuning | Removing 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 inference | Models 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 |
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 connect any two layers, and in the idealized model the stream has no privileged basis.
- The logit lens decodes 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.
At which layer is the logit lens exact, and why?
- At the first layer, because the embedding is closest to the input
- At the last layer, because there are no remaining residual updates to drop
- At every layer of a pre-LN model, because the stream is never normalized
- 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 , the true output with the sum of all later updates set to zero. At the top that sum is empty, so the lens returns the model's own logits.
Why is the tuned lens trained to match the model's own final distribution rather than the true next tokens?
- Because the true next tokens are not available for language models
- Because matching the final distribution is cheaper to compute
- Because it makes the translators exactly the identity
- 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 ) ties the lens to the model's computation; causal tests then check that it relies on features the model uses.
Layer writes to the stream with and a later layer reads with . What is the virtual weight between them, and what happens to it when the stream is rotated by an orthogonal (with every reading and writing matrix transformed to match)?
- ; it is unchanged, since
- ; it is rotated to
- ; it changes with
- There is none: layers communicate only with their neighbors
Show the answer
A. ; it is unchanged, since
Layer 's input contains , a direct connection through the stream. Under the rotation, cancels, which is why the stream has no privileged basis in this idealized model.
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?
- MMLU accuracy improved after pruning
- The final layer could be removed as easily as the others
- Next-token loss on held-out text rose smoothly with every layer removed, and math (GSM8K) and commonsense (HellaSwag) accuracy dropped with any pruning
- 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).