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 .
- For any given token position , the token is strictly restricted to attending only to preceding and current positions where .
- Information from future positions 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 .
- Before computing the softmax distribution over attention scores, the mask sets the raw pre-softmax attention logits corresponding to all future positions to :
- Applying the softmax operator converts the values to exact probabilities of , 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 in the residual stream at the output of layer be denoted as , where represents the model's hidden dimension.
- Preceding context tokens up to and including index are denoted collectively as .
- For an individual attention head with head dimension , linear projection matrices are defined as .
- The projection equations operate as:
- Query Vector:
- Key Vectors:
- Value Vectors:
The QK Circuit (Information Reading):
- The interaction between queries and keys is governed by the bilinear form composite matrix:
- Function: The QK circuit is responsible for reading information from the residual stream.
- It computes the dot-product similarity between the query of token and the keys of context tokens , 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 , the resulting aggregated representation in subspace is projected back into the main residual stream dimension using an output projection matrix .
- The combined operation forms the composite low-rank matrix:
- 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 attention heads, each individual head independently produces an update vector of dimension .
- 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:
- This sum is added directly into the ongoing residual stream vector, preserving the constant dimensionality 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 is the intermediate residual state after the attention block update, denoted as .
- The network is structured as a two-layer multi-layer perceptron (MLP) with intermediate hidden dimension (where typically ).
Upward Projection () as a Key Matrix:
- The input is projected from dimension to dimension via the upward projection matrix .
- Mechanistic Function: acts as a pattern detector or "key matrix."
- Multiplying the stream vector by assesses how well the current token representation matches distinct feature directions.
Non-Linear Activation Function ():
- The projected activations pass through an element-wise non-linear activation function (such as ReLU or GELU):
- This non-linearity introduces sparsity and selectively activates specific computational circuits.
Downward Projection () as a Value Store:
- The vector of neuron activations is projected back to the residual stream dimensionality using the downward projection matrix .
- Mechanistic Function: serves as a "value store" or memory bank.
- Activated patterns in trigger the retrieval of corresponding vector values stored in the rows of .
Neuron-Level Decomposition:
- The FFN operation can be decomposed down to individual neurons .
- Let represent the -th column of , and denote the -th row of .
- For each neuron , the scalar activation is computed as:
- The complete additive contribution of the FFN is the sum of these neuron-level associative retrievals:
- 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 , where is the vocabulary size.
- Because the operations across layers are additive, the product with 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 and ), the final prediction for an input embedding expands into four additive paths:
Taxonomy of Computational Paths:
- Direct Path ():
- 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 ( and ):
- 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 ():
- 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 acts effectively as a single, higher-order "virtual attention head."
- Enables multi-hop associative lookups and hierarchical linguistic reasoning.
- Direct Path ():
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 (), 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 (), altering which tokens the second head considers relevant.
- In full models, head compositions extend beyond OV-to-OV interactions (V-composition):
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 and 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 ().
- Significance: Enforces causality essential for next-token autoregressive text generation.
QK Circuit ():
- 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 ():
- 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 ():
- Definition: Final linear projection mapping hidden states from representation space to vocabulary logit space .
- Significance: Converts the accumulated sum of the residual stream into a probability distribution over tokens.
Direct Path ():
- 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 ():
- 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 ():
- 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 (), non-linearity (), and downward projection ().
- Significance: Functions as a key-value associative memory that activates on detected patterns to add feature vectors to the residual stream.