The Residual Stream Perspective: An Alternate Formulation of Transformers

Foundations of the Residual Stream Formulation

  • Conceptual Paradigm Shift:

    • Traditional views conceptualize Transformer architectures as rigid, sequential layer-by-layer representations where each block fundamentally overwrites the representations of the preceding block.
    • The Residual Stream Perspective reconceptualizes the Transformer as a shared communication channel (the "residual stream") through which token representations flow continuously.
    • Every internal component—including multi-head self-attention heads and feed-forward network (FFN) layers—reads from this stream and writes back into it via purely additive operations.
    • Information is preserved across layers unless explicitly overwritten, transforming the entire model into an ensemble of parallel, additive paths rather than a strictly serial pipeline.
  • Granular Interpretability:

    • This formulation provides a foundational basis for mechanistic interpretability in large language models (LLMs).
    • It bypasses monolithic block-level abstractions, enabling the decomposition of model predictions down to the level of individual attention heads, specific circuits, and distinct neurons.
    • By isolating linear and non-linear paths, researchers can pinpoint where facts are stored, how context is passed, and how specific output tokens are selected.

Mathematical Framework of Masked Self-Attention

  • Autoregressive Constraint:

    • In decoder-only autoregressive models designed for generative next-token prediction, a sequence of input tokens is denoted as X=(x1,x2,…,xn)X = (x_1, x_2, \dots, x_n).
    • For any given token position ii, the token xix_i is strictly restricted to attending only to preceding and current positions xjx_j where j≤ij \le i.
    • Information from future positions j>ij > i is entirely inaccessible, preventing the model from "seeing the future" during inference and training.
  • Attention Score Masking:

    • The autoregressive restriction is enforced using an attention mask matrix MM.
    • Before computing the softmax distribution over attention scores, the mask MM sets the raw pre-softmax attention logits corresponding to all future positions j>ij > i to −∞-\infty:         Scoresij={QiKjTdHfor j≤i−∞for j>i\text{Scores}_{ij} = \begin{cases} \frac{Q_i K_j^T}{\sqrt{d_H}} & \text{for } j \le i \\ -\infty & \text{for } j > i \end{cases}
    • Applying the softmax operator converts the −∞-\infty values to exact probabilities of 00, ensuring future tokens exert zero influence on current representation updates.

Attention Block Decomposition: QK and OV Circuits

  • Query, Key, and Value Generation:

    • Let the state of token ii in the residual stream at the output of layer l−1l - 1 be denoted as xi(l−1)∈Rdx_i^{(l-1)} \in \mathbb{R}^d, where dd represents the model's hidden dimension.
    • Preceding context tokens up to and including index ii are denoted collectively as X≤i(l−1)∈Ri×dX_{\le i}^{(l-1)} \in \mathbb{R}^{i \times d}.
    • For an individual attention head with head dimension dHd_H, linear projection matrices are defined as WQ,WK,WV∈Rd×dHW_Q, W_K, W_V \in \mathbb{R}^{d \times d_H}.
    • The projection equations operate as:
      • Query Vector: Q=xi(l−1)WQ∈R1×dHQ = x_i^{(l-1)} W_Q \in \mathbb{R}^{1 \times d_H}
      • Key Vectors: K=X≤i(l−1)WK∈Ri×dHK = X_{\le i}^{(l-1)} W_K \in \mathbb{R}^{i \times d_H}
      • Value Vectors: V=X≤i(l−1)WV∈Ri×dHV = X_{\le i}^{(l-1)} W_V \in \mathbb{R}^{i \times d_H}
  • The QK Circuit (Information Reading):

    • The interaction between queries and keys is governed by the bilinear form composite matrix:         WQK=WQWKT∈Rd×dW_{QK} = W_Q W_K^T \in \mathbb{R}^{d \times d}
    • Function: The QK circuit is responsible for reading information from the residual stream.
    • It computes the dot-product similarity between the query of token xix_i and the keys of context tokens X≤iX_{\le i}, determining the dynamic attention pattern (the scalar attention weights across sequence positions).
  • The OV Circuit (Information Writing):

    • Once attention weights are applied to the value vectors VV, the resulting aggregated representation in subspace RdH\mathbb{R}^{d_H} is projected back into the main residual stream dimension dd using an output projection matrix WO∈RdH×dW_O \in \mathbb{R}^{d_H \times d}.
    • The combined operation forms the composite low-rank matrix:         WOV=WVWO∈Rd×dW_{OV} = W_V W_O \in \mathbb{R}^{d \times d}
    • Function: The OV circuit is responsible for writing information back into the residual stream.
    • It determines what specific representation or feature transformation is transferred from the attended source token to the destination token's stream.
  • Multi-Head Aggregation via Summation:

    • In a multi-head layer with HH attention heads, each individual head h∈{1,…,H}h \in \{1, \dots, H\} independently produces an update vector of dimension dd.
    • The heads do not concatenate their outputs in a way that modifies the underlying dimensionality of the stream; instead, their independent outputs are directly summed:         AttentionOutput=∑h=1HHeadh\text{AttentionOutput} = \sum_{h=1}^{H} \text{Head}_h
    • This sum is added directly into the ongoing residual stream vector, preserving the constant dimensionality dd across layers.

Feed-Forward Networks as Key-Value Associative Memories

  • Two-Layer MLP Architecture:

    • Each Transformer block contains a Feed-Forward Network (FFN) that operates position-wise and independently on each token's representation.
    • The input to the FFN at layer ll is the intermediate residual state after the attention block update, denoted as xi,mid(l)∈Rdx_{i,\text{mid}}^{(l)} \in \mathbb{R}^d.
    • The network is structured as a two-layer multi-layer perceptron (MLP) with intermediate hidden dimension dfd_f (where typically df>dd_f > d).
  • Upward Projection (WinW_{\text{in}}) as a Key Matrix:

    • The input is projected from dimension dd to dimension dfd_f via the upward projection matrix Win∈Rd×dfW_{\text{in}} \in \mathbb{R}^{d \times d_f}.
    • Mechanistic Function: WinW_{\text{in}} acts as a pattern detector or "key matrix."
    • Multiplying the stream vector by WinW_{\text{in}} assesses how well the current token representation matches dfd_f distinct feature directions.
  • Non-Linear Activation Function (gg):

    • The projected activations pass through an element-wise non-linear activation function gg (such as ReLU or GELU):         Activations=g(xi,mid(l)Win)∈Rdf\text{Activations} = g\left(x_{i,\text{mid}}^{(l)} W_{\text{in}}\right) \in \mathbb{R}^{d_f}
    • This non-linearity introduces sparsity and selectively activates specific computational circuits.
  • Downward Projection (WoutW_{\text{out}}) as a Value Store:

    • The vector of neuron activations is projected back to the residual stream dimensionality dd using the downward projection matrix Wout∈Rdf×dW_{\text{out}} \in \mathbb{R}^{d_f \times d}.
    • Mechanistic Function: WoutW_{\text{out}} serves as a "value store" or memory bank.
    • Activated patterns in WinW_{\text{in}} trigger the retrieval of corresponding vector values stored in the rows of WoutW_{\text{out}}.
  • Neuron-Level Decomposition:

    • The FFN operation can be decomposed down to individual neurons u∈{1,…,df}u \in \{1, \dots, d_f\}.
    • Let Win,uW_{\text{in}, u} represent the uu-th column of WinW_{\text{in}}, and Wout,uW_{\text{out}, u} denote the uu-th row of WoutW_{\text{out}}.
    • For each neuron uu, the scalar activation is computed as:         actu=g(xi,mid(l)Win,u)\text{act}_u = g\left(x_{i,\text{mid}}^{(l)} W_{\text{in}, u}\right)
    • The complete additive contribution of the FFN is the sum of these neuron-level associative retrievals:         FFN(xi,mid(l))=∑u=1dfg(xi,mid(l)Win,u)Wout,u\text{FFN}\left(x_{i,\text{mid}}^{(l)}\right) = \sum_{u=1}^{d_f} g\left(x_{i,\text{mid}}^{(l)} W_{\text{in}, u}\right) W_{\text{out}, u}
    • This vector is added directly back into the residual stream.

Prediction as an Ensemble of Shallow Paths and Circuit Compositions

  • Logit Decomposition via Unembedding:

    • The final state of the residual stream after passing through all blocks is mapped to vocabulary logit space using the unembedding matrix WU∈Rd×∣V∣W_U \in \mathbb{R}^{d \times |V|}, where ∣V∣|V| is the vocabulary size.
    • Because the operations across layers are additive, the product with WUW_U distributes linearly over every component added to the stream.
  • Simplified Two-Layer Attention-Only Model:

    • In a simplified model comprising two attention layers with no non-linearities and single attention heads per layer (represented by matrices WOV1W_{OV1} and WOV2W_{OV2}), the final prediction f(x)f(x) for an input embedding xx expands into four additive paths:         f(x)=xWU+xWOV1WU+xWOV2WU+xWOV1WOV2WUf(x) = x W_U + x W_{OV1} W_U + x W_{OV2} W_U + x W_{OV1} W_{OV2} W_U
  • Taxonomy of Computational Paths:

    • Direct Path (xWUx W_U):
      • Represents the unmediated projection of the raw input token embedding directly to the output logits.
      • Captures baseline bigram statistics and identity mappings, bypassing all internal attention and FFN layers.
    • Full OV Circuits (xWOV1WUx W_{OV1} W_U and xWOV2WUx W_{OV2} W_U):
      • Represent direct, single-hop computational paths that traverse exactly one attention head's OV circuit prior to unembedding.
      • Reflect the isolated impact of individual attention heads acting directly on the input token.
    • Virtual Attention Heads via V-Composition (xWOV1WOV2WUx W_{OV1} W_{OV2} W_U):
      • Occurs when the output of an attention head in Layer 1 writes into the residual stream, and that exact information is subsequently read as an input by the OV circuit of a head in Layer 2.
      • The matrix product WOV1WOV2W_{OV1} W_{OV2} acts effectively as a single, higher-order "virtual attention head."
      • Enables multi-hop associative lookups and hierarchical linguistic reasoning.
  • Broader Circuit Compositions:

    • In full models, head compositions extend beyond OV-to-OV interactions (V-composition):
      • Q-Composition: An earlier head writes information into the residual stream that is read by a subsequent head's query matrix (WQW_Q), altering where the second head looks.
      • K-Composition: An earlier head writes information into the residual stream that is read by a subsequent head's key matrix (WKW_K), altering which tokens the second head considers relevant.

Mechanistic Interpretability and Practical Implications

  • Localization of Model Behavior:

    • By decomposing final logits into an ensemble of additive components, researchers can attribute predictions to specific terms in the sum.
    • It is possible to trace an undesirable prediction back to a single path (e.g., a specific direct path, a single OV circuit, an individual virtual head, or a specific set of FFN neurons).
  • Engineering and Safety Applications:

    • Diagnosing Failures: Dissecting the additive paths identifies whether hallucinated or incorrect tokens arise from spurious direct-path correlations or misdirected multi-hop virtual circuits.
    • Bias Mitigation: Specific biases can be localized to identifiable key-value memories within WinW_{\text{in}} and WoutW_{\text{out}} or dedicated attention circuits, allowing targeted editing or ablation without retraining.
    • Model Controllability: Understanding the residual stream allows researchers to perform activation patching, circuit knifing, and representation steering to ensure robust, predictable AI behavior in production environments.

Summary of Architectural Terms and Components

  • Residual Stream:

    • Definition: A conceptual communication highway where token representations are continuously updated via additive inputs across layers.
    • Significance: Unifies information flow; permits linear logit decomposition into distinct computational paths.
  • Masked Self-Attention:

    • Definition: A causal self-attention variant where attention weights are zeroed out for all future sequence indices (j>ij > i).
    • Significance: Enforces causality essential for next-token autoregressive text generation.
  • QK Circuit (WQK=WQWKTW_{QK} = W_Q W_K^T):

    • Definition: Composite bilinear matrix constructed from the query and key projection weights.
    • Significance: Determines attention weights; governs where an attention head reads from the residual stream.
  • OV Circuit (WOV=WVWOW_{OV} = W_V W_O):

    • Definition: Composite projection matrix constructed from the value and output weights.
    • Significance: Determines the transferred subspace; governs what information an attention head writes into the residual stream.
  • Unembedding Layer (WUW_U):

    • Definition: Final linear projection mapping hidden states from representation space Rd\mathbb{R}^d to vocabulary logit space R∣V∣\mathbb{R}^{|V|}.
    • Significance: Converts the accumulated sum of the residual stream into a probability distribution over tokens.
  • Direct Path (xWUx W_U):

    • Definition: The linear projection of the initial embedding vector straight through the unembedding matrix.
    • Significance: Accounts for direct token-to-token transition biases independent of attention or FFN transformations.
  • Full OV Circuits (xWOVWUx W_{OV} W_U):

    • Definition: Paths traversing exactly one OV circuit prior to unembedding.
    • Significance: Measures the direct, uncomposed contribution of an individual attention head to the final prediction.
  • Virtual Attention Heads (xWOV1WOV2WUx W_{OV1} W_{OV2} W_U):

    • Definition: The sequential composition of two or more distinct OV circuits acting as a unified transformation.
    • Significance: Underpins multi-hop semantic reasoning and cross-layer feature composition.
  • Feed-Forward Network (FFN):

    • Definition: A two-layer MLP composed of an upward projection (WinW_{\text{in}}), non-linearity (gg), and downward projection (WoutW_{\text{out}}).
    • Significance: Functions as a key-value associative memory that activates on detected patterns to add feature vectors to the residual stream.