The Residual Stream in Transformers: How Linear Additive State, Subspace Projections, and Layer Accumulation Power Modern LLMs

In standard descriptions of transformer architectures, multi-head attention and feedforward networks receive the vast majority of analytical focus. However, the operational backbone coordinating these sublayers is the residual stream. First introduced in convolutional computer vision models by He et al. (2016) to mitigate vanishing gradients in deep networks, residual skip connections operate in large language models as a persistent, high-dimensional linear communication bus. Rather than proces

6 min
The Residual Stream in Transformers: How Linear Additive State, Subspace Projections, and Layer Accumulation Power Modern LLMs

In standard descriptions of transformer architectures, multi-head attention and feedforward networks receive the vast majority of analytical focus. However, the operational backbone coordinating these sublayers is the residual stream. First introduced in convolutional computer vision models by He et al. (2016) to mitigate vanishing gradients in deep networks, residual skip connections operate in large language models as a persistent, high-dimensional linear communication bus.

Rather than processing information sequentially through a rigid, monolithic transformation pipeline, modern transformers rely on the residual stream as a shared memory canvas. Individual attention heads and feedforward layers read specific features from this stream, perform isolated computations, and write additive updates back into the channel without destroying the existing state (Elhage et al., 2021). This linear additive formulation fundamentally dictates how transformer circuits compose, how representations scale with model depth, and how gradients propagate during optimization.

The Mathematical Mechanics: Reading and Writing to the Bus

At the start of a transformer forward pass, an input sequence of tokens is converted into initial continuous representations via a learned embedding matrix WEW_E and combined with positional information:

x0=Embed(tokens)+Posx_0 = \text{Embed}(\text{tokens}) + \text{Pos}

The vector x0Rdmodelx_0 \in \mathbb{R}^{d_{model}} enters the residual stream at layer 0. For each subsequent transformer layer l{1,,L}l \in \{1, \dots, L\}, the state transitions according to two sequential additive operations:

xlmid=xl1+Attnl(LN(xl1))x_l^{mid} = x_{l-1} + \text{Attn}_l(\text{LN}(x_{l-1}))

xl=xlmid+MLPl(LN(xlmid))x_l = x_l^{mid} + \text{MLP}_l(\text{LN}(x_l^{mid}))

where LN\text{LN} represents layer normalization (such as RMSNorm or standard Pre-LayerNorm).

Residual Stream Architecture in Transformers

Every sublayer interacts with the residual stream through explicit linear projections:

  1. Reading from the Stream: An attention head hh reads from the stream by projecting the unnormalized state via query, key, and value weights: q=xWQhq = x W_Q^h, k=xWKhk = x W_K^h, and v=xWVhv = x W_V^h. Similarly, a gated feedforward network (such as SwiGLU) reads the vector state via gate and up-projection matrices: hgate=xWgateh_{gate} = x W_{gate} and hup=xWuph_{up} = x W_{up}.
  2. Local Computation: The attention head calculates softmax attention patterns across sequence positions: A=softmax(qkT/dk)A = \text{softmax}(q k^T / \sqrt{d_k}), producing intermediate value mixtures r=Avr = A v. The MLP evaluates non-linear activation gating: m=Swish(hgate)hupm = \text{Swish}(h_{gate}) \odot h_{up}.
  3. Writing to the Stream: The computed representations are mapped back into the model dimension dmodeld_{model} using output projection matrices WOhW_O^h and WdownW_{down}. The resulting vectors are added directly into the stream:

Δxlattn=h=1HrhWOh,Δxlmlp=mWdown\Delta x_l^{attn} = \sum_{h=1}^H r^h W_O^h, \quad \Delta x_l^{mlp} = m W_{down}

By expanding this recursion across all LL layers of the network, the final pre-unembedding state xLx_L is revealed as a pure linear accumulation of updates:

xL=x0+l=1LΔxlattn+l=1LΔxlmlpx_L = x_0 + \sum_{l=1}^L \Delta x_l^{attn} + \sum_{l=1}^L \Delta x_l^{mlp}

Subspace Allocation and High-Dimensional Geometry

Because the residual stream is additive and fixed at width dmodeld_{model} (such as 4,096 in LLaMA-7B or 8,192 in LLaMA-70B), the vector space acts as a shared memory address space. In high-dimensional Euclidean space, the number of mutually near-orthogonal directions scales exponentially with dimensionality.

This geometric property allows the transformer to partition the residual stream into quasi-independent linear subspaces (Elhage et al., 2021):

  • Dedicated Feature Channels: A layer can write syntactic information (such as subject-verb number agreement) into subspace S1RdmodelS_1 \subset \mathbb{R}^{d_{model}}, while another layer writes semantic domain tags into orthogonal subspace S2RdmodelS_2 \subset \mathbb{R}^{d_{model}}. Because S1S2S_1 \perp S_2, operations projecting onto S1S_1 remain unaffected by updates written into S2S_2.
  • Superposition and Polysemanticity: In practical LLMs, the number of distinct human concepts, grammatical rules, and factual associations vastly exceeds dmodeld_{model}. Models accommodate this by packing non-orthogonal features into superposition (Elhage et al., 2022), relying on non-linear MLP activations in subsequent layers to denoise and extract target signals when activated.

Direct Logit Attribution and Circuit Composition

The linear structure of the residual stream has critical implications for interpretability and model internals. In standard autoregressive architectures, the final prediction is obtained by projecting xLx_L through an unembedding matrix WURdmodel×VW_U \in \mathbb{R}^{d_{model} \times |V|}:

logits=LNfinal(xL)WU\text{logits} = \text{LN}_{final}(x_L) W_U

Ignoring the final LayerNorm scale factor for first-order linear analysis, the logit vector decomposes additively across every component in the network:

logitsx0WU+l=1LΔxlattnWU+l=1LΔxlmlpWU\text{logits} \approx x_0 W_U + \sum_{l=1}^L \Delta x_l^{attn} W_U + \sum_{l=1}^L \Delta x_l^{mlp} W_U

This formulation enables Direct Logit Attribution (DLA). Researchers and engineers can compute ΔxlhWU\Delta x_l^h W_U to measure the exact numerical contribution that a single attention head or MLP neuron makes toward promoting or suppressing a specific token in the vocabulary.

Furthermore, it explains how circuits compose across non-adjacent layers:

  • K-Composition: An attention head in layer 10 can read key information directly written by layer 2 without layer 3 through 9 needing to forward or re-encode that information.
  • V-Composition and Induction: Induction heads (Olsson et al., 2022) depend on previous-token heads writing position-shifted token identities into the stream, which downstream search heads subsequently attend to across long token spans.

Virtual Ensembles and Gradient Flow Dynamics

The additive skip connection fundamentally alters how depth functions in transformers. As demonstrated by Veit et al. (2016), residual networks do not behave like monolithic serial pipelines of depth LL. Instead, an LL-layer residual architecture acts as a virtual ensemble of 2L2^L distinct computational paths of varying lengths.

Input x0 ───────────────────────────────────────────────────────────> Output xL
   │                       │                       │                     ▲
   └──> [ Attn 1 ] ──(+)───┴──> [ Attn 2 ] ──(+)───┴──> [ MLP L ] ──(+)──┘
   │                  ▲    │                  ▲    │                 ▲
   └──> [ MLP 1 ] ────┘    └──> [ MLP 2 ] ────┘    └──> [ ... ] ─────┘

When evaluating a two-layer transformer block with paths through sublayers {f1,f2}\{f_1, f_2\}, the computational graph unrolls into four parallel pathways:

x2=x0+f1(x0)+f2(x0)+f2(f1(x0))x_2 = x_0 + f_1(x_0) + f_2(x_0) + f_2(f_1(x_0))

In an LL-layer model, most data paths bypass the majority of intermediate layers, allowing the network to dynamically route tokens through shallow or deep computational circuits depending on task complexity.

Gradient Highway Mechanics

During backpropagation, the gradient of the loss L\mathcal{L} with respect to early representations x0x_0 is computed via the chain rule:

Lx0=LxLxLx0=LxL(I+l=1LΔxlx0)\frac{\partial \mathcal{L}}{\partial x_0} = \frac{\partial \mathcal{L}}{\partial x_L} \frac{\partial x_L}{\partial x_0} = \frac{\partial \mathcal{L}}{\partial x_L} \left( I + \sum_{l=1}^L \frac{\partial \Delta x_l}{\partial x_0} \right)

The presence of the identity matrix II creates an uninterrupted gradient highway. Even if intermediate sublayer gradients Δxlx0\frac{\partial \Delta x_l}{\partial x_0} vanish or become ill-conditioned, the backpropagated error signal flows directly to early layers and input embeddings without attenuation.

Architectural Trade-Offs and Stability Bottlenecks

While the residual stream provides modularity and stable optimization, scaling depth introduces physical and mathematical constraints:

Residual Stream Norm Growth in Pre-LN Models

In modern Pre-LN and Pre-RMSNorm transformers (Wang et al., 2019), each layer adds a zero-mean, non-zero variance update Δxl\Delta x_l to xl1x_{l-1}. Assuming updates are weakly correlated, the variance and Euclidean norm of the residual vector grow with depth:

E[xl22]x022+i=1lE[Δxi22]O(l)\mathbb{E}[\|x_l\|_2^2] \approx \|x_0\|_2^2 + \sum_{i=1}^l \mathbb{E}[\|\Delta x_i\|_2^2] \sim \mathcal{O}(l)

Consequently, in deep models (such as 80 to 120 layers), xL2\|x_L\|_2 is significantly larger than x02\|x_0\|_2. As the residual stream norm expands, the relative contribution of later layers Δxlxl\frac{\|\Delta x_l\|}{\|x_l\|} naturally diminishes unless layer normalization rescales inputs or explicit branch scaling parameters (such as DeepNorm or ReZero multipliers α<1\alpha < 1) are applied (Wang et al., 2022).

Bandwidth Bottlenecks in Deep-Narrow Configurations

Because every sublayer must communicate through dmodeld_{model}, narrow networks with extreme depth experience residual stream bandwidth pressure. If dmodeld_{model} is too small relative to layer count LL, sublayers overwrite or corrupt existing subspace allocations, degrading long-range circuit composition. Balancing residual width against depth remains a core optimization frontier in foundation model pre-training.

Sources

Written by

More to read

  • Auxiliary-Loss-Free Load Balancing in Mixture-of-Experts: How Dynamic Bias Adjustments Eliminate Gradient Conflict and Routing Collapse

    Sparse Mixture-of-Experts (MoE) architectures decouple parameter count from per-token compute cost by activating only a small subset of feed-forward network (FFN) parameters for any given token. While dense transformers evaluate every parameter across all sequence positions, MoE models route tokens dynamically to specialized sub-networks, enabling parameter scaling to hundreds of billions or trillions of parameters at the inference and training cost of much smaller dense models. However, condit

    1 min
  • Confidential LLM Inference in Production: Hardware TEEs, GPU Enclaves, Attestation, and Serving Performance Trade-Offs

    Confidential LLM Inference in Production: Hardware TEEs, GPU Enclaves, Attestation, and Serving Performance Trade-Offs Deploying large language models in multi-tenant cloud environments introduces a fundamental security boundary problem. Standard transport encryption (TLS) secures prompts in transit, and encryption-at-rest protects checkpoints on disk, but model weights, prompt tokens, and key-value (KV) caches exist in plaintext within system memory during active inference. For organizations p

    1 min
  • Google DeepMind Outlines 15-Year Game AI Arc and EVE Online Research Sandbox

    Google DeepMind has detailed its 15-year trajectory of game-based artificial intelligence research, outlining how milestones from arcade reinforcement learning to modern multimodal models have culminated in an experimental research program inside the persistent virtual universe of EVE Online. The retrospective connects early breakthroughs in discrete, fully observable games to the frontier challenges currently facing autonomous systems: long-horizon planning, non-stationary multi-agent dynamics

    1 min