Skip to content
AIAI Wranglers

38 Interpretability and Explainability of Generative Models

In 2016 a neural network trained to detect wolves in photographs was found, on examination, to be largely relying on the presence of snow in the background rather than wolf morphology (Ribeiro et al., 2016). The model's test accuracy was high. Its reasoning was wrong. The same year, a recidivism prediction algorithm used in US courts was shown to exhibit systematic racial bias in its scores, despite never being given race as an explicit input variable (Angwin et al., 2016). The model's statistical calibration was arguably defensible. Its outputs carried life-altering consequences. And in 2023, GPT-4 passed the bar exam at the 90th percentile, solved international olympiad problems in chemistry, and wrote code that compiled and passed unit tests at rates exceeding many professional programmers. Yet researchers could not reliably explain which part of the network's billions of parameters was responsible for any particular answer.

These three incidents share a common thread: our ability to deploy powerful machine learning systems has dramatically outpaced our ability to understand them. For discriminative models, this gap is uncomfortable. For generative models, it is foundational. When a language model writes a medical report, a legal brief, or a psychological assessment, or when a diffusion model generates a photorealistic face, the question is not merely whether the output is statistically correct. The question is: where does the output come from? What latent variables contributed? Which training examples are implicitly being recalled? Is the model reasoning, pattern-matching, or hallucinating?

Interpretability and explainability are the scientific disciplines that take these questions seriously. This chapter develops their mathematical foundations with particular attention to the features that make generative models qualitatively more challenging than their discriminative counterparts. We proceed from motivating principles through formal definitions and historical context, then develop the modern mechanistic interpretability programme and its application to generative architectures.

Why Interpretability Matters

The Black Box Problem

A function f:𝒳→𝒴 is a black box with respect to an observer if the observer can query f on inputs and receive outputs but has no access to the internal computation that transforms one into the other. In classical software engineering the black box is a methodological choice: we deliberately hide implementation details behind interfaces to manage complexity. In modern deep learning the black box is an emergent property of scale: a language model with hundreds of billions of parameters implements a function that no human designed explicitly, whose internal representation cannot be read off the weight matrices in any straightforward way, and whose decision boundaries in the input space have never been analytically characterised.

This distinction matters enormously. A software black box can in principle be white-boxed by reading its source code. A deep learning black box resists white-boxing even in principle: the β€œsource code” is a matrix of floating-point numbers that implements no human-interpretable algorithm. Researchers call this the opacity problem or, in the regulatory literature, the right to explanation problem.

Historical Note.

From MYCIN to GPT. The opacity problem was not always present. The first wave of successful AI systems, running from the early 1970s through the late 1980s, were expert systems: rule-based programs whose reasoning could be inspected, audited, and corrected rule by rule. MYCIN (Shortliffe et al., 1974), designed to diagnose bacterial infections and recommend antibiotics, encoded approximately six hundred if-then rules of the form IF organism is gram-positive AND patient has fever THEN suspect Streptococcus with confidence 0.7. A physician disagreeing with a recommendation could ask the system to explain itself and trace the specific rules responsible. XCON (McDermott, 1980), used by Digital Equipment Corporation to configure VAX computer orders, encoded over ten thousand rules and saved the company an estimated $40 million annually. Its behaviour was inspectable, debuggable, and transferable to new engineers through the rule base.

The shift to connectionist approaches, revived by Rumelhart and McClelland (1986) and later scaled by LeCun, Bengio, and Hinton into deep learning, traded interpretability for representational power. A neural network with one hidden layer already implements a function whose decision boundary is a nonlinear manifold in input space that cannot be described in fewer bits than the weight matrix itself. As networks deepened and widened through the 2010s, interpretability decreased monotonically with performance on benchmarks. The paradox of modern AI is that the more capable the system, the less we understand it.

Philosophical Dimensions: Consciousness, Explanation, and the Introspection Gap

Before developing formal machinery, it is worth pausing on a question that practitioners often suppress: is interpretability even a well-posed demand? Consider the human brain. It is the most capable cognitive system we know of, and it is spectacularly uninterpretable by its own introspective access. Cognitive psychologists have documented systematic failures of human self-explanation: subjects confabulate reasons for choices made on purely unconscious grounds (Nisbett and Wilson, 1977); patients with split-brain lesions offer verbal explanations for actions initiated by the hemisphere that lacks language (Gazzaniga, 1985); people reliably attribute their own emotional states to external causes unrelated to the actual physiological trigger (Schachter and Singer, 1962).

This raises what we may call the introspection gap: the systematic divergence between an agent's stated reasons for a decision and the actual causal factors that produced it. If the human brain, operating at ∼86 billion neurons and ∼1014 synapses, exhibits a severe introspection gap that does not prevent us from considering humans morally responsible agents, why should we require machine learning systems to close that gap entirely?

The philosophical answer turns on the difference between causal explanation and rationalisation. What we demand of interpretable systems is not that they produce coherent post-hoc narratives (which humans do too, and often wrongly) but that we can identify the actual causal mechanisms by which inputs produce outputs. This is a scientific demand, not an epistemological impossibility. Neuroscience has made genuine progress understanding specific neural circuits, spike-timing codes, and functional modules in biological brains precisely by combining external intervention (lesions, optogenetics, pharmacology) with multi-electrode recordings. Mechanistic interpretability for artificial neural networks is the same programme applied to silicon.

A second philosophical question concerns consciousness and self-awareness. Can a system explain its own decisions in a meaningful sense? When a language model is prompted β€œexplain your reasoning”, the resulting text is generated by the same forward pass mechanism as any other output. It is not a privileged readout of internal state; it is another output token sequence conditioned on the prompt. This is not necessarily deceptive, but it is not the same as genuine introspective access. The distinction matters for regulation, for trust, and for the scientific study of AI systems.

Remark 1.

On the meaning of β€œexplanation” in AI. The philosophy of science distinguishes at least four senses of explanation (Salmon, 1984): deductive-nomological (the outcome follows from general laws and initial conditions), statistical-relevance (factors that probabilistically raise or lower outcome probability), causal-mechanical (the physical mechanism by which causes bring about effects), and pragmatic (an answer to a why-question that is useful to a particular audience). XAI methods tend to target different senses simultaneously, often creating confusion about whether they are providing genuine scientific explanations or pragmatic summaries. Mechanistic interpretability explicitly targets the causal-mechanical sense.

Formal Definitions: Interpretability, Explainability, and Transparency

The terms β€œinterpretability”, β€œexplainability”, and β€œtransparency” are used inconsistently across the literature. We adopt the following formal definitions, which unify the major usages and are compatible with the EU AI Act's framework.

Definition 1 (Transparency).

A model fΞΈ:𝒳→𝒴 parameterised by ΞΈ is Ο„-transparent with respect to a description language β„’ if there exists a description dβˆˆβ„’ such that:

  1. d is human-readable in time polynomial in |d|,

  2. d faithfully describes the computation graph of fΞΈ up to approximation error Ο„: supπ’™βˆˆπ’³β‘β€–fΞΈ(𝒙)βˆ’fd(𝒙)‖≀τ, and

  3. |d| is sub-linear in the number of parameters |ΞΈ|.

A linear model is 0-transparent in the language of linear equations. A depth-L decision tree is 0-transparent in the language of Boolean if-then rules. A deep neural network is generally not Ο„-transparent for any practically useful Ο„ and β„’.

Definition 2 (Interpretability).

A model fΞΈ is (k,Ο΅)-interpretable if there exists a function g:𝒳→ℝk⁑ mapping inputs to k human-meaningful features such that for any prediction fΞΈ(𝒙) there exists a certificate c(𝒙)βˆˆβ„k⁑ with the following properties:

  1. Faithfulness: the local linear model f^(𝒙′)=c(𝒙)⊀g(𝒙′) satisfies |f^(𝒙′)βˆ’fΞΈ(𝒙′)|≀ϡ for all 𝒙′ in a neighbourhood 𝒩(𝒙),

  2. Conciseness: β€–c(𝒙)β€–0≀k (at most k non-zero attribution scores),

  3. Stability: β€–c(𝒙)βˆ’c(𝒙′)β€–2≀Lcβ€–π’™βˆ’π’™β€²β€–2 for a Lipschitz constant Lc<∞.

LIME (Ribeiro et al., 2016) and SHAP (Lundberg and Lee, 2017) are methods for constructing certificates c(𝒙).

Definition 3 (Explainability).

A model fΞΈ is (u,q)-explainable with respect to a user model u and a question q∈Q if there exists an explanation eu,q(𝒙) such that:

  1. eu,q(𝒙) answers q in a language adapted to u's domain knowledge and cognitive capacity,

  2. The explanation is contrastive: it addresses β€œwhy y^ rather than y^′” for a foil y^β€² relevant to u,

  3. The explanation is actionable: u can in principle intervene on the system based on eu,q(𝒙).

Explainability is thus user-relative, question-relative, and inherently pragmatic. A technically accurate but incomprehensible explanation fails the explainability criterion even if it achieves high faithfulness.

Remark 2.

Hierarchy of demands. Transparency β‡’ interpretability β‡’ explainability in the sense that a transparent model is trivially interpretable (read off the weights) and any interpretable model can be made explainable by translating its certificate into user-appropriate language. The converses do not hold: a model can be locally interpretable around any given input without being globally transparent, and can be explainable to a user without satisfying the formal faithfulness criterion.

The GenAI Explainability Triangle

Generative models present a richer explainability surface than discriminative models. We organise the challenge using what we call the GenAI Explainability Triangle: three interrelated demands that must all be addressed for a generative system to be considered genuinely explainable.

Vertex 1: Generative Mechanism Transparency. What latent variables, attention patterns, or intermediate representations caused the specific output? For a language model this includes: which training documents are being implicitly recalled, which attention heads are routing information from which positions, and whether the model is β€œreasoning” or β€œpattern-matching” (to the extent that distinction is coherent). For a diffusion model it includes: which noise trajectory was taken, which guidance signals shaped the denoising path, and how the latent manifold was traversed.

Vertex 2: User-Centered Interpretability. What explanation is appropriate for a given user with a given need? A data scientist querying a language model needs a different explanation than a radiologist, a judge, or a patient. The explanation must be adapted to the user's domain model, the consequentiality of the decision, and the available interaction modality.

Vertex 3: Evaluation Fidelity. Can we measure whether an explanation is correct? For discriminative models, fidelity metrics like area under the perturbation curve (Samek et al., 2017) are well-established. For generative models, standard fidelity metrics are largely undefined because the ground truth causal mechanism is unknown and the output space is high-dimensional and structured.

The GenAI Explainability Triangle. Genuine explainability of a generative model requires simultaneously addressing Generative Mechanism Transparency (understanding the internal causal process), User-Centered Interpretability (adapting explanations to user needs), and Evaluation Fidelity (measuring explanation correctness). Edges label the bridging challenges between each pair of vertices.

Why Generative Models Are Harder to Interpret

Classical XAI was developed primarily for discriminative models: classifiers and regressors that map a fixed input to a scalar or low-dimensional output. Methods like LIME, SHAP, Grad-CAM (Selvaraju et al., 2017), and integrated gradients (Sundararajan et al., 2017) produce saliency maps or feature attributions that highlight which input features most influenced a particular classification.

Generative models introduce three qualitative difficulties that these methods do not address:

Stochastic sampling.

A discriminative model f:𝒳→𝒴 is typically deterministic given ΞΈ. A generative model samples from a distribution pΞΈ(π’š|𝒙). Two forward passes with the same input and parameters can produce arbitrarily different outputs. An attribution method that computes gradients of the output with respect to the input is undefined or ambiguous for a stochastic output. Even if we fix the random seed, the attribution reflects that seed's trajectory, not the model's distributional behaviour.

High-dimensional, structured output spaces.

Discriminative model outputs are typically scalar or low-dimensional. Generative outputs are sequences of tokens, images with millions of pixels, audio waveforms, or protein structures. Attribution methods that assign a scalar importance score to each input feature face a fundamental mismatch: the output is not a scalar to differentiate with respect to. Extending gradient-based attributions to sequence outputs requires integrating over output positions, which introduces aggregation choices that interact poorly with long-range dependencies.

Multi-step generation.

Many generative models involve multiple cascaded components: a language model may use retrieval, chain-of-thought, a code interpreter, and post-processing. A diffusion model iterates hundreds of denoising steps through multiple network passes. A VAE encodes, samples, and decodes. Each intermediate step introduces its own representation, its own stochasticity, and its own opportunities for information to be created, discarded, or transformed. Attribution methods designed for single forward passes cannot natively attribute credit across such pipelines.

The following table summarises the qualitative differences in the XAI challenge between discriminative and generative models.

XAI DimensionDiscriminative ModelsGenerative Models
Output typeScalar / low-dimensional labelSequence, image, audio, or structured object
DeterminismDeterministic given parametersStochastic; distribution over outputs
Attribution targetSingle output scalarAmbiguous: which token, pixel, or step?
Evaluation of attributionsPixel-flipping, deletion curvesNo standard metrics; output space too complex
Forward pass structureSingle encoder + headMulti-stage pipeline; retrieval; sampling
Latent spaceCompact class embeddingsHigh-dimensional, entangled; sampling noise
Causal questionWhy this class?Why this generation trajectory?
Human-facing utilityHighlight discriminative pixelsIdentify failure modes, bias, copying
Faithfulness measurable?Yes (deletion / perturbation)Difficult; ground truth not available
Regulatory touchpointGDPR Article 22EU AI Act high-risk systems
Comparison of classical XAI challenges for discriminative versus generative models. Generative models introduce qualitatively new difficulties in every major XAI dimension.

Key Idea.

The generative-discriminative interpretability gap. Understanding how a model generates is fundamentally different from understanding why it classifies. Classification can be explained by identifying which input features shift the output probability; the output itself is fixed (a class label) and the causal graph is shallow. Generation requires explaining the choice of an entire trajectory through a structured output space: every token, every denoising step, every attention pattern contributes to the final output in a way that cannot be reduced to a simple saliency score. The key challenge is trajectory attribution: assigning credit or blame across the joint space of inputs, latent variables, and multi-step outputs.

Biological Connections: Neural Coding and Distributed Representations

The question of how information is encoded in neural networks, artificial or biological, has a long history in neuroscience that illuminates the interpretability challenge. Two competing theories of neural coding have shaped the field.

The sparse coding hypothesis.

Barlow (1961) proposed that the nervous system achieves efficient representation by using as few neurons as possible to encode each stimulus. In the extreme, the grandmother cell hypothesis (Gross, 2002) posits that individual neurons represent specific high-level concepts: one neuron fires for your grandmother's face, one fires for Jennifer Aniston, one fires for the Eiffel Tower. This is trivially interpretable: if you can label each neuron, you can read off the model's internal representation.

Evidence for this view comes from the seminal work of Hubel and Wiesel (1959, 1962), who found neurons in primary visual cortex that respond selectively to oriented edges at specific spatial frequencies, and from Quiroga et al. (2005), who found neurons in the human medial temporal lobe responding to single specific individuals or landmarks.

The distributed representation hypothesis.

McCulloch and Pitts (1943) and later Hinton, McClelland, and Rumelhart (1986) argued for a fundamentally different coding scheme: information is represented by patterns of activity across many neurons, no single one of which is individually interpretable. A face is encoded as a high-dimensional activation vector, not as a single neuron's firing rate. This allows combinatorial generalisation: N neurons can represent up to 2N distinct patterns rather than N concepts.

Modern deep neural networks clearly use distributed representations. This makes them powerful and difficult to interpret simultaneously. However, recent work in mechanistic interpretability suggests that superposition (Elhage et al., 2022) allows networks to store more features than dimensions by representing features as near-orthogonal directions in activation space, with small but non-zero interference.

Three coding schemes in biological and artificial neural networks. Left: Sparse (grandmother cell) coding - one neuron represents one concept; trivially interpretable but combinatorially limited. Centre: Distributed representation - a concept is a direction in the joint activation space; powerful but no single neuron is interpretable. Right: Superposition - n neurons encode ≫n near-orthogonal features by tolerating small pairwise interference; the dominant mechanism in large neural networks (Elhage et al., 2022).

The superposition hypothesis has important implications for interpretability. If a network stores k≫n features in n dimensions via superposition, then probing individual neurons is insufficient: the features are polysemantic (a single neuron responds to multiple unrelated concepts). Recovering individual features requires finding sparse decompositions of the activation space, which is the goal of sparse autoencoders in mechanistic interpretability (Cunningham et al., 2023; Bricken et al., 2023).

Example 1 (Polysemanticity in InceptionV1).

Olah et al. (2020) found that neuron 379 in the mixed3b layer of InceptionV1 responds maximally to images of: (i) cat faces, (ii) car fronts, and (iii) specific curved textures. These concepts appear unrelated from a human perspective, yet the network has learned to use the same neuron to represent them. This is not a flaw in the network's reasoning; it is the network efficiently packing information into constrained dimensional space via superposition. The interpretability challenge is to decompose this polysemantic response into monosemantic features.

Exercises

Exercise 1 (Transparency of Logistic Regression).

Let fΞΈ(𝒙)=Οƒ(πœ½βŠ€π’™+b) be a logistic regression classifier with parameter vector πœ½βˆˆβ„d⁑, bias bβˆˆβ„β‘, and Οƒ the sigmoid function.

  1. Show that fΞΈ is 0-transparent in the language of linear equations (Definition Definition 1) by constructing an explicit description d and verifying all three conditions.

  2. Compute the SHAP values for this model and show they equal 𝜽i⋅𝒙i/d under the uniform background distribution (to first order).

  3. Now consider a two-layer ReLU network fΞΈ(𝒙)=𝐖2max⁑(𝐖1𝒙,𝟎). Explain why no description d of sub-linear length in |ΞΈ| can faithfully capture all activation patterns, and hence why ReLU networks are not Ο„-transparent for Ο„<Ο΅ in general.

Exercise 2 (Introspection Gap in Language Models).

Consider a language model pΞΈ that generates a chain-of-thought (CoT) rationale r followed by an answer a: pΞΈ(r,a|q) for a question q.

  1. Define a formal notion of CoT faithfulness: the degree to which r is causally responsible for a vs. a post-hoc rationalisation. (Hint: use causal intervention notation do(r=rβ€²) for a different rationale rβ€².)

  2. Turpin et al. (2023) showed that inserting a biasing hint into the context causes a model to change its answer but generate a rationale that does not mention the hint. Formalise this as a violation of your faithfulness criterion.

  3. Propose an experimental protocol to measure faithfulness on a given question-answer dataset without access to the model's internal activations.

Exercise 3 (The Superposition Capacity Bound).

Elhage et al. (2022) show that n neurons can represent k≫n features in superposition if the features are nearly orthogonal with pairwise interference Ο΅.

  1. Using the Johnson-Lindenstrauss lemma, show that one can embed k=Ξ©(exp⁑(cΟ΅2n)) unit vectors in ℝn⁑ with pairwise inner products at most Ο΅, for an absolute constant c (so the exponent is linear in n).

  2. Argue that polysemanticity is an inevitable consequence of representing many features in low-dimensional spaces, not a design flaw. What does this imply for the viability of neuron-level interpretability?

  3. Describe how sparse autoencoders can in principle β€œun-mix” superposed features. What objective would you minimise, and what sparsity constraint would you impose?

The Mechanistic Interpretability Paradigm

Defining the Programme

Mechanistic interpretability is the programme of reverse-engineering trained neural networks into human-understandable computational processes. The goal is not to produce a local explanation for a single prediction (as in SHAP or LIME) but to produce a complete account of the algorithm a network has learned: which neurons compute which features, how those features are combined via attention or MLP operations, and what high-level algorithm the resulting circuit implements.

Definition 4 (Mechanistic Interpretability).

Given a trained neural network fΞΈ and a behaviour B (a function from inputs to outputs that fΞΈ exhibits on some distribution), a mechanistic explanation of B is a tuple (C,Ο•,Ξ΄) where:

  • CβŠ†ΞΈ is a circuit: a sub-graph of the computation graph of fΞΈ,

  • Ο•:Cβ†’π’œ is an interpretation map assigning human-meaningful algorithms π’œ to nodes in C,

  • Ξ΄ is a fidelity metric satisfying Ξ΄(fC,fΞΈ)≀ϡ on the behaviour distribution, where fC is fΞΈ with all non-C components ablated.

The explanation is complete if Ξ΄=0; it is Ο΅-faithful otherwise.

Insight.

Mechanistic interpretability is to AI what molecular biology is to medicine. Classical pharmacology observed that certain substances produced clinical effects, but could not predict new drugs without understanding the molecular mechanisms. Molecular biology's account of protein structure, enzyme kinetics, and receptor binding turned pharmacology into a science capable of rational drug design. Similarly, current deep learning is largely correlational: we observe what networks can do on benchmarks, but cannot predict failure modes, design interventions, or transfer knowledge systematically without a mechanistic account. Mechanistic interpretability aims to provide that account.

Three Abstraction Layers

The mechanistic interpretability programme operates at three interrelated levels of abstraction, inspired by Marr's three levels of analysis in computational neuroscience (Marr, 1982).

Layer 1: Neurons as Features.

At the finest grain, individual neurons (or directions in activation space) represent specific features of the input. For vision models these may be edge detectors, colour blobs, or object part detectors. For language models they may represent syntactic roles, entity types, or factual properties. The goal at this layer is to produce a feature dictionary: a mapping from neurons (or sparse directions) to their semantic content.

Methods at this layer include:

  • Maximum activation examples: find the training or held-out inputs that maximally activate a neuron, and infer the feature from the pattern.

  • Activation patching on concepts: verify that a neuron represents a concept by measuring the downstream effect of setting its activation to its mean.

  • Sparse autoencoders (SAEs): learn a sparse, overcomplete dictionary πƒβˆˆβ„dΓ—k⁑ such that activations π’‰β‰ˆπƒπ’„ with ‖𝒄‖0β‰ͺk. Each column of 𝐃 is a purported monosemantic feature.

Layer 2: Circuits.

A circuit is a sub-graph of the computation graph connecting features to downstream features through specific attention heads, MLP layers, or residual stream connections. Circuits explain specific input-output relationships: β€œthe indirect object identification circuit in GPT-2 (Wang et al., 2022) routes the subject token's representation through three specific attention heads to generate the indirect object at the output position.”

The circuit paradigm was established by Olah et al. (2020) who reverse-engineered a curve-detector circuit in InceptionV1, showing that curve detector neurons receive inputs from oriented edge detector neurons (themselves identified as implementing a Fourier decomposition of local contrast patterns) via a specific set of connections. The insight that the same circuit type (curve from edges) recurs at multiple spatial positions is the notion of circuit universality: similar circuits emerge in different networks trained on different tasks, suggesting convergent algorithmic solutions.

Layer 3: Macroscopic Algorithms.

At the coarsest grain, what high-level algorithm does the network implement? For GPT-2 on the indirect object identification (IOI) task, Wang et al. (2022) showed the algorithm has three phases: (i) token copying, in which name mover heads copy subject representations to the final token position; (ii) subject suppression, in which inhibition heads downweight the current subject relative to alternatives; and (iii) output generation, in which name mover heads promote the correct output. This three-phase description is a macroscopic algorithm that could in principle be implemented differently by a different network, but which GPT-2 happened to implement through the specific circuit identified at Layer 2.

Remark 3.

Analogy with molecular biology. These three layers map onto biological levels of analysis: neurons as features ↔ molecular mechanisms (which protein does what function); circuits ↔ cellular pathways (how proteins interact in biochemical cascades); macroscopic algorithms ↔ physiological processes (how pathways produce tissue- or organ-level behaviour). The analogy is not perfect but is instructive for motivating the hierarchical programme.

The Causal Intervention Toolkit

Mechanistic interpretability relies on causal interventions: modifying specific activations in the network and observing the downstream effect. This section formalises the four main techniques.

Let fΞΈ be a transformer with L layers, H attention heads per layer, and hidden dimension d. Denote by 𝒂t(l,h) the attention head output of head h in layer l at position t, and by π’Žt(l) the MLP output at layer l, position t. The residual stream at position t after layer l is: (Residual)𝒓t(l)=𝒓t(0)+βˆ‘β„“=1l(βˆ‘h=1H𝒂t(β„“,h)+π’Žt(β„“)), where 𝒓t(0) is the token embedding at position t.

Definition 5 (Activation Patching).

Given a clean input π’™βˆ— and a corrupted input 𝒙^, the activation patch at component (l,h,t) is the operation of running fΞΈ on 𝒙^ while replacing the activation 𝒂^t(l,h) with the clean value 𝒂t(l,h)βˆ— from the run on π’™βˆ—. The patching effect is: (Actpatch)Ξ”patch(l,h,t)=β„³(fΞΈ(𝒙^; 𝒂t(l,h)←𝒂t(l,h)βˆ—))βˆ’β„³(fΞΈ(𝒙^)), where β„³ is a scalar metric (e.g., logit difference of target tokens). A large positive Ξ”patch(l,h,t) indicates that head (l,h) at position t is causally responsible for the correct behaviour on π’™βˆ—.

Definition 6 (Path Patching).

Path patching (Wang et al., 2022; Goldowsky-Dill et al., 2023) extends activation patching by patching not just a component's output but the path from a source node s to a target node v through a specific intermediate set I. Formally, let 𝒒=(V,E) be the computation graph. For a path Ο€=(s,i1,…,ik,v) with {ij}βŠ†I, path patching intervenes on the value that v receives from Ο€: (Pathpatch)Ξ”pathΟ€=β„³(fΞΈ(𝒙^;Β path(Ο€)←pathπ’™βˆ—(Ο€)))βˆ’β„³(fΞΈ(𝒙^)). Path patching is strictly more precise than activation patching because it isolates the information flow through a specific causal path rather than replacing all information passing through a node.

Definition 7 (Mean Ablation).

Mean ablation of component (l,h) replaces the component's activation with its mean over a reference distribution π’Ÿref: (Meanablation)𝒂ablated(l,h)=π”Όπ’™βˆΌπ’Ÿref[𝒂(l,h)(𝒙)]. Mean ablation removes the component's contribution to the specific input while retaining the average contribution from the reference distribution. It is less disruptive than zero ablation (which sets activations to zero, a potentially out-of-distribution value) but conflates information from multiple inputs.

Definition 8 (Resampling Ablation).

Resampling ablation (also called activation resampling) replaces the activation at (l,h,t) with the value from a randomly sampled corrupted input 𝒙~βˆΌπ’Ÿcorrupt that has a different label or target than π’™βˆ—: (Resample)𝒂resamp(l,h)=𝒂(l,h)(𝒙~),𝒙~βˆΌπ’Ÿcorrupt, and measures β„³(fΞΈ(π’™βˆ—; 𝒂(l,h)←𝒂resamp(l,h)))βˆ’β„³(fΞΈ(π’™βˆ—)). Resampling ablation preserves the statistical properties of the activation distribution, avoiding the out-of-distribution problem of zero ablation.

Activation patching workflow. A clean run on input π’™βˆ— saves all intermediate activations (shown in blue). A corrupted run on input 𝒙^ proceeds normally until the component of interest (here, attention head h at layer 2), where the corrupted activation is replaced (patched) with the clean value. The downstream metric difference Ξ” quantifies how much that component causally contributes to the correct behaviour on π’™βˆ—.

Automated Circuit Discovery

Manual circuit analysis (Olah et al., 2020; Wang et al., 2022) requires a researcher to form and test hypotheses about each attention head and MLP component. For GPT-2-small (117M parameters, 12 layers, 12 heads per layer), this process required several months of researcher time per circuit. For modern large language models the brute-force approach is computationally and cognitively intractable.

Two algorithmic approaches have emerged to automate circuit discovery.

ACDC (Automated Circuit DisCovery).

Conmy et al. (2023) introduce ACDC, a greedy top-down algorithm that identifies the minimal sub-graph of the computation graph sufficient to reproduce a target metric. Starting from the full computation graph, ACDC iteratively ablates edges (connections between components) and retains an edge if its ablation causes the metric to change by more than a threshold Ο„: (ACDC)𝒒(t+1)=𝒒(t)βˆ–{e},ifΒ |β„³(𝒒(t))βˆ’β„³(𝒒(t)βˆ–{e})|<Ο„. The output is a minimal circuit π’’βˆ— such that all retained edges contribute more than Ο„ to the metric. ACDC is correct by construction for greedy selection but may miss non-minimal circuits that interact synergistically.

Edge Attribution Patching (EAP).

Syed et al. (2023) and Marks et al. (2024) propose EAP as a gradient-based approximation to path patching that scales to large models. For each edge e=(uβ†’v) in the computation graph, EAP computes an attribution score: (EAP)Ξ±e=(𝒓^vβˆ’π’“vβˆ—)βŠ€βˆ‚β„³βˆ‚π’“v|𝒓v=𝒓vβˆ—, where 𝒓^v is the residual stream at v on the corrupted input and 𝒓vβˆ— is the same on the clean input. The gradient βˆ‚β„³/βˆ‚π’“v is computed with a single backward pass on the clean input. EAP thus requires only two forward passes (clean and corrupt) and one backward pass, regardless of circuit size.

The key insight is that Ξ±e approximates the first-order contribution of restoring the clean activation at v via edge e to the metric. The approximation is exact in the linear limit and remains accurate when activations are small perturbations of their clean values.

Proposition 1 (Computational Complexity of Circuit Discovery).

Let fΞΈ be a transformer with L layers, H heads per layer, and T token positions. The computation graph has E=O(L2H2T2) edges (each head at each layer-position pair can attend to each previous layer-position pair).

  1. Brute-force activation patching requires O(E) forward passes, one per component: O(LHT) passes total if patching individual head outputs (not all edges), or O(L2H2T2) passes for all edges.

  2. ACDC requires O(E) forward passes in the worst case (one ablation test per edge) but converges in practice to O(kE/L) passes for a circuit of k retained edges, since it prunes iteratively.

  3. EAP requires O(1) forward passes (two forward + one backward), independent of E. The approximation error is O(‖𝒓^βˆ’π’“βˆ—β€–22) per edge, which is small when clean and corrupt inputs are close.

Proof.

Part (a) follows directly from counting the number of components. For L layers, H heads, and T positions, there are LHT head-position pairs; patching each requires one forward pass. For all edges in the computation graph, all O(L2H2T2) edges must be tested.

Part (b): ACDC starts with the full graph and greedily removes edges. At each step it needs to evaluate one edge ablation per remaining edge. In the worst case (no edges removed), this is O(E) passes. In practice, after L pruning rounds the circuit shrinks geometrically.

Part (c): EAP uses a first-order Taylor expansion. The attribution for edge e=(uβ†’v) uses βˆ‚β„³/βˆ‚π’“v evaluated once on the clean input (one backward pass) and the activation difference 𝒓^vβˆ’π’“vβˆ— from two forward passes. The error per edge is bounded by the second-order term, which is O(‖𝒓^vβˆ’π’“vβˆ—β€–2), completing the proof.

A Taxonomy of Mechanistic Interpretability Methods

MethodLayerCore TechniqueKey ReferenceCost
Max activation examplesNeuronFind inputs maximising neuron firingOlah et al., 2017O(|π’Ÿ|)
Feature visualisationNeuronGradient ascent in input spaceOlah et al., 2017O(Iβ‹…d)
Probing classifiersNeuronTrain linear probe on activationsAlain & Bengio, 2017O(|π’Ÿ|β‹…d)
Sparse autoencodersNeuronLearn overcomplete sparse basisBricken et al., 2023O(kβ‹…|π’Ÿ|)
Logit lensNeuron/CircuitProject intermediate states to logitsNostalgebraist, 2020O(Lβ‹…d)
Activation patchingCircuitRestore clean activations selectivelyMeng et al., 2022O(ncβ‹…Tfwd)
Path patchingCircuitPatch specific computational pathsWang et al., 2022O(Eβ‹…Tfwd)
Mean ablationCircuitReplace with distributional meanChan et al., 2022O(ncβ‹…Tfwd)
ACDCCircuitGreedy edge pruning via ablationConmy et al., 2023O(Eβ‹…Tfwd)
EAPCircuitFirst-order gradient attributionSyed et al., 2023O(Tfwd+Tbwd)
Causal tracingAlgorithmCorrupt + restore; locate factsMeng et al., 2022O(Lβ‹…ntok)
ROME / MEMITAlgorithmRank-one model editingMeng et al., 2022/2023O(d2)
Attention analysisAlgorithmVisualise attention weight patternsClark et al., 2019O(LHT2)
Taxonomy of mechanistic interpretability methods by scope, approach, and cost. Methods are organised by abstraction layer (neuron, circuit, algorithm) and primary technique.

Chapter Roadmap

The remainder of this chapter develops the mechanistic interpretability programme for generative models specifically. Figure fig:interp:roadmap shows the organisation.

Roadmap of Chapter 38. This file covers Sections Why Interpretability Matters–The Mechanistic Interpretability Paradigm. Sections 3–8 are covered in subsequent files.

Exercises

Exercise 4 (Implementing Activation Patching).

Consider a two-layer attention-only transformer with residual stream 𝒓(0)βˆˆβ„d⁑ (token embeddings), two attention heads per layer, and a linear unembedding π”βˆˆβ„VΓ—d⁑. The metric β„³ is the logit difference (𝐔𝒓(L))y+βˆ’(𝐔𝒓(L))yβˆ’ for a correct token y+ and incorrect token yβˆ’.

  1. Write the activation patching effect Ξ”patch(l,h,t) (Equation (Actpatch)) for this specific architecture. Simplify using the linearity of the residual stream.

  2. Show that for linear attention (removing the softmax), activation patching is equivalent to computing the gradient of β„³ with respect to the head output 𝒂t(l,h) and multiplying by the activation difference 𝒂t(l,h)βˆ—βˆ’π’‚^t(l,h). (This is the theoretical basis for EAP.)

  3. Describe the experimental design for the indirect object identification (IOI) task on a toy dataset: what are π’™βˆ— and 𝒙^, what is β„³, and how would you interpret a heat-map of Ξ”patch(l,h,t) over all (l,h,t)?

Exercise 5 (Circuit Fidelity Metric).

Given a circuit CβŠ†ΞΈ in the sense of Definition Definition 4, define the circuit fidelity as: (Fidelity)F(C)=β„³(fC)βˆ’β„³(fβŒ€)β„³(fΞΈ)βˆ’β„³(fβŒ€), where fC is the model with all components outside C mean-ablated, and fβŒ€ is the model with all components mean-ablated.

  1. Show that F(C)∈[0,1] when β„³ is a probability and mean-ablation produces outputs in [0,1]. Give a counterexample when β„³ is a logit difference.

  2. Prove that F(ΞΈ)=1 and F(βŒ€)=0 for any β„³.

  3. Define circuit minimality: C is Ο΅-minimal if F(C)β‰₯1βˆ’Ο΅ and for every proper sub-circuit Cβ€²βŠŠC, F(Cβ€²)<1βˆ’Ο΅. Show that finding an Ο΅-minimal circuit is NP-hard in general (reduce from minimum vertex cover).

Exercise 6 (Mean Ablation vs. Zero Ablation).

Let hΞΈ:ℝd⁑→ℝd⁑ be a single attention head with parameters ΞΈ=(𝐖Q,𝐖K,𝐖V,𝐖O).

  1. Show that zero-ablating hΞΈ (setting its output to 𝟎) is equivalent to inserting an input for which 𝐖V=𝟎. Argue this may be out-of-distribution in a network trained with non-zero random initialisation.

  2. Let ΞΌ=𝔼𝒙[hΞΈ(𝒙)] be the mean activation over a reference distribution. Show that mean-ablating hΞΈ is equivalent to adding a constant bias to the residual stream and subtracting the head's contribution. Derive an expression for this effective bias in terms of ΞΌ.

  3. In a transformer with LayerNorm, mean activations may not be zero even for zero-mean inputs. Give a concrete example using the GPT-2 architecture where zero-ablation and mean-ablation of an attention head produce measurably different logit differences, and explain which should be preferred for causal inference and why.

Classical Explainability Methods

Before we can understand why interpretability for generative models demands fundamentally new tools, we must master the classical toolkit. The methods developed between 2016 and 2020 - SHAP, LIME, Grad-CAM, Integrated Gradients, and attention visualisation - represent the mature engineering of a particular idea: that a model's prediction on a given input can be explained by attributing credit or blame to the individual input features that drove it. These are attribution methods, and they are extraordinarily successful at what they do. They are also, as we shall argue in Why Classical XAI Fails for Generative Models, fundamentally inadequate for generative models.

The story of attribution methods begins with a question that seems almost embarrassingly simple. Given a neural network f that classifies an input 𝒙 and produces a prediction f(𝒙)=y^, which features of 𝒙 were responsible? For a radiologist looking at a chest X-ray classified as showing pneumonia, this question is not academic: it determines whether the model can be trusted, whether it has learned the right visual patterns, and whether the radiologist's intuition aligns with the machine's. For a judge evaluating whether an algorithmic decision was fair, knowing which features drove the decision is a legal requirement in many jurisdictions.

Yet the question conceals a thicket of subtlety. What does it mean for a feature to be β€œresponsible” for a prediction? Features are not independent; removing or perturbing one changes the context for all others. The model f is a nonlinear function of thousands or millions of parameters, not a transparent formula one can inspect directly. And the very notion of feature importance is ambiguous: do we mean the feature's causal effect on the output, its correlation with the output, or some measure of counterfactual sensitivity?

The four methods we study in this section each answer this question differently, and their different answers reveal complementary facets of model behaviour.

SHAP: Shapley Values from Game Theory

The most principled approach to attribution comes not from machine learning but from cooperative game theory. In 1953, Lloyd Shapley solved the problem of fairly distributing the proceeds of a cooperative game among its players, and his solution - now bearing his name - has become the mathematical foundation of modern feature attribution.

Cooperative Games and Fair Division

A cooperative game is a pair (𝒩,v) where 𝒩={1,…,d} is a set of players (here, feature indices) and v:2𝒩→ℝ⁑ is a characteristic function that assigns a real-valued payoff to every subset (coalition) SβŠ†π’©. For attribution purposes, v(S) represents how well a model performs when only the features in S are available. Typically, v(S)=𝔼𝒙Sβ€Ύ[f(𝒙S,𝒙Sβ€Ύ)]βˆ’f(𝟎), where Sβ€Ύ=π’©βˆ–S and the expectation marginalises over all features not in S, while features in S retain their observed values.

The Shapley value of player i measures that player's average marginal contribution across all possible orderings in which players join the coalition.

Definition 9 (Shapley Value).

Given a cooperative game (𝒩,v) with d=|𝒩| players, the Shapley value of player iβˆˆπ’© is (Shapley)Ο•i(v)=βˆ‘SβŠ†π’©βˆ–{i}|S|!(dβˆ’|S|βˆ’1)!d![v(Sβˆͺ{i})βˆ’v(S)]. The quantity v(Sβˆͺ{i})βˆ’v(S) is the marginal contribution of player i to coalition S. The prefactor |S|!(dβˆ’|S|βˆ’1)!/d! is the probability that coalition S forms before player i joins, under a uniform random ordering of all d players.

The Shapley value is the unique allocation satisfying four axioms that formalise the notion of fairness.

Theorem 1 (Shapley Axioms).

The Shapley value Ο• is the unique function satisfying all of the following:

  1. Efficiency. βˆ‘iβˆˆπ’©Ο•i(v)=v(𝒩)βˆ’v(βˆ…). The attributions sum to the model's total output difference.

  2. Symmetry. If v(Sβˆͺ{i})=v(Sβˆͺ{j}) for all SβŠ†π’©βˆ–{i,j}, then Ο•i=Ο•j. Interchangeable players receive equal attribution.

  3. Dummy. If v(Sβˆͺ{i})=v(S) for all SβŠ†π’©βˆ–{i}, then Ο•i=0. A feature that never changes the output receives zero attribution.

  4. Linearity. Ο•i(Ξ±v+Ξ²w)=Ξ±Ο•i(v)+Ξ²Ο•i(w) for any two games v,w and scalars Ξ±,Ξ²βˆˆβ„β‘.

KernelSHAP: Tractable Approximation

Direct computation of Shapley values requires evaluating v on all 2d subsets, which is computationally infeasible for high-dimensional inputs. Lundberg and Lee (2017) introduced SHAP (SHapley Additive exPlanations), a practical framework with the KernelSHAP algorithm as its model-agnostic backbone.

The key observation is that Shapley values can be cast as the solution to a weighted least-squares problem. Define a coalition vector 𝐳∈{0,1}d indicating which features are present, and let the SHAP kernel weight for coalition S (encoded as 𝐳) be (Kernel)w(S)=dβˆ’1(d|S|)|S|(dβˆ’|S|). Then the SHAP attributions 𝝓=(Ο•0,Ο•1,…,Ο•d) are obtained by solving (Kernelshap)𝝓=arg minπ“β€²β‘βˆ‘SβŠ†π’©w(S)[v(S)βˆ’Ο•0βˆ’π“β€²β‹…π³S]2, where 𝐳S∈{0,1}d is the binary indicator of S. In practice, one samples a manageable number of coalitions (typically 2d+211), evaluates v on each (possibly by querying f with missing features replaced by background samples), and solves the weighted least-squares problem.

Key Idea.

SHAP unifies several earlier attribution methods as special cases. TreeSHAP exploits tree structure for exact O(TLD2) computation (where T is the number of trees, L is the maximum number of leaves, and D is the maximum tree depth). DeepSHAP propagates SHAP values through neural network layers using the chain rule. LinearSHAP recovers exact Shapley values for linear models in closed form. The unifying principle is always the same: the Shapley value is the unique fair attribution that respects the axioms of efficiency, symmetry, dummy, and linearity.

LIME: Local Interpretable Model-Agnostic Explanations

While SHAP seeks a globally consistent attribution grounded in game theory, LIME (Ribeiro, Singh, and Guestrin, 2016) takes a pragmatically local approach: fit a simple interpretable model to the behaviour of the complex model in the neighbourhood of a specific input.

Local Surrogate Framework

Given an input π’™βˆˆπ’³ and a black-box classifier f:𝒳→ℝ⁑, LIME constructs a local surrogate gβˆˆπ’’ (typically a sparse linear model) that approximates f near 𝒙. The explanation is the solution to (LIME)ΞΎ(𝒙)=arg mingβˆˆπ’’β‘β„’(f,g,π𝒙)+Ξ©(g), where:

  • β„’(f,g,π𝒙)=βˆ‘π’›βˆˆπ’΅Ο€π’™(𝒛)[f(𝒛)βˆ’g(𝒛)]2 is the local fidelity loss, measuring how well g mimics f on perturbations 𝒛 of 𝒙, weighted by proximity π𝒙;

  • π𝒙(𝒛)=exp⁑(βˆ’D(𝒙,𝒛)2/Οƒ2) is an exponential kernel assigning higher weight to perturbations closer to 𝒙;

  • Ξ©(g) is a complexity penalty (e.g., β„“1 norm of the linear weights) that encourages sparse, human-readable explanations.

The perturbations 𝒛 are generated by randomly masking a subset of superpixels (for images) or words (for text), replacing masked regions with a background value or held-out tokens. The surrogate g is then learned on the dataset {(𝒛k,f(𝒛k),π𝒙(𝒛k))}k=1n using weighted ridge regression.

Locality and Its Implications

The locality of LIME's explanation is simultaneously its strength and its vulnerability. On the one hand, a local linear model can capture the local decision boundary of an arbitrarily complex classifier, provided the neighbourhood radius Οƒ is calibrated correctly. On the other hand, different runs of LIME on the same input can produce qualitatively different explanations if the sampled perturbations happen to fall in different regions of a complex loss landscape. This instability is a documented limitation that has motivated several remediation strategies, including using larger perturbation budgets, fixing the random seed, and employing regularised regression in place of standard ridge.

Remark 4.

The instability of LIME can be measured formally: if ΞΎ1(𝒙) and ΞΎ2(𝒙) are two runs of LIME on the same input with different random seeds, their explanations may satisfy β€–ΞΎ1(𝒙)βˆ’ΞΎ2(𝒙)β€–2/β€–ΞΎ1(𝒙)β€–2>0.3 even for well-calibrated hyperparameters. This is not a bug in LIME but a consequence of the fact that local linear models have high variance in high-dimensional settings.

Grad-CAM: Gradient-Weighted Class Activation Mapping

SHAP and LIME are model-agnostic: they treat the classifier as a black box and probe it by varying inputs. Grad-CAM (Selvaraju et al., 2017) takes the opposite approach, exploiting the internal gradient structure of convolutional neural networks to produce spatial saliency maps that highlight where in the image the model looked when making its prediction.

Class Activation Maps via Gradients

Let Akβˆˆβ„uΓ—v⁑ denote the activation map of the k-th feature map in the final convolutional layer, and let yc be the logit (pre-softmax score) for class c. Grad-CAM computes the importance weight of the k-th feature map for class c by globally average-pooling the gradient of yc with respect to Ak: (Weight)Ξ±kc=1uvβˆ‘i=1uβˆ‘j=1vβˆ‚ycβˆ‚Aijk. The Grad-CAM saliency map is then (MAP)LGrad-CAMc=ReLU⁑(βˆ‘kΞ±kcAk)βˆˆβ„uΓ—v⁑, where the ReLU discards negative contributions (features that suppress class c) and retains only the positive evidence. The resulting map is upsampled (bilinearly) to the input resolution and overlaid on the image.

The ReLU operation in (MAP) is a deliberate choice. Without it, the map would include features that suppress the predicted class, producing a noisier and harder-to-interpret visualisation. With it, Grad-CAM produces localised, high-contrast heatmaps that are easy for human experts to interpret.

Example 2 (Grad-CAM on a Medical Image Classifier).

Consider a ResNet-50 classifier trained to detect pneumonia from chest radiographs. Given a positive-class input 𝒙 (a radiograph classified as pneumonia), we apply Grad-CAM to visualise which spatial regions drove the prediction.

Setup. Let the final convolutional layer have K=2048 feature maps of spatial resolution uΓ—v=7Γ—7. The logit for the β€œpneumonia” class is ypneu. We compute the gradient βˆ‚ypneu/βˆ‚Aijk via a single backward pass, average-pool to obtain Ξ±kpneu, and form the weighted sum.

Result. The Grad-CAM heatmap localises to the right lower lobe of the lung, precisely where a radiologist would look for consolidation. The model's spatial attention is medically plausible, providing a first-pass validation that the network has learned clinically meaningful patterns rather than spurious correlations (e.g., orientation tags, scanner artefacts, or hospital watermarks).

Clinical utility. Beyond trust assessment, Grad-CAM maps can flag cases where the model attends to implausible regions - for instance, the diaphragm or cardiac silhouette in a lung-disease classifier - which may indicate dataset bias or distribution shift. At one large hospital system, routine Grad-CAM auditing of a pneumothorax detector revealed that 18% of its β€œconfident” predictions were driven by scanner metadata rather than lung parenchyma; retraining on a cleaned dataset reduced this to 2%.

Limitations. Grad-CAM is coarse (limited by the spatial resolution of the last convolutional layer) and class-specific but not instance-specific: two different images of the same class may produce similar heatmaps even if the discriminating features differ. Grad-CAM++ and Score-CAM address some of these limitations by using second-order gradients and activation-based weighting, respectively.

Comparison of three classical XAI methods applied to the same input image. SHAP (left) marginalises over feature coalitions and produces a bar chart of Shapley attributions per pixel group. LIME (centre) fits a sparse local linear model to perturbations of the input, yielding a feature-weight vector. Grad-CAM (right) backpropagates gradients through the convolutional stack to produce a spatial heatmap highlighting which image regions drove the prediction. All three answer the same question - β€œwhich input features matter?” - but via radically different mechanisms and with different granularity.

Integrated Gradients: Path-Based Attribution with Axioms

Integrated Gradients (Sundararajan, Taly, and Yan, 2017) sits at a conceptual crossroads between the game-theoretic rigour of SHAP and the gradient efficiency of Grad-CAM. Like SHAP, it is grounded in a set of formal axioms; like Grad-CAM, it exploits the gradient of the network with respect to its input. Unlike Grad-CAM, it is architecture-agnostic: it applies to any differentiable model, not just convolutional networks.

Path Integral and Axiomatic Foundation

The Integrated Gradients attribution of feature i is defined as the integral of the gradient along a straight-line path from a baseline π’™β€²βˆˆπ’³ (representing β€œno signal”, e.g. an all-black image or an all-padding text sequence) to the actual input 𝒙: (IG)IGi(𝒙;𝒙′)=(xiβˆ’xiβ€²)∫01βˆ‚f(𝒙′+Ξ±(π’™βˆ’π’™β€²))βˆ‚xidΞ±. In practice, the integral is approximated by a Riemann sum over m equally-spaced steps along the path: (Approx)IGi(𝒙;𝒙′)β‰ˆ(xiβˆ’xiβ€²)β‹…1mβˆ‘k=1mβˆ‚f(𝒙)βˆ‚xi|𝒙=𝒙′+km(π’™βˆ’π’™β€²). For this right-endpoint Riemann sum the approximation error decreases as O(1/m) (a midpoint or trapezoidal quadrature would improve this to O(1/m2)); values of m∈[20,300] are standard in practice.

Theorem 2 (Axiomatic Characterisation of Integrated Gradients).

Integrated Gradients is the unique path method satisfying all of the following axioms:

  1. Completeness. βˆ‘i=1dIGi(𝒙;𝒙′)=f(𝒙)βˆ’f(𝒙′). The attributions sum exactly to the output difference between the input and the baseline. This is the analogue of SHAP's Efficiency axiom.

  2. Sensitivity. If f(𝒙)β‰ f(𝒙′) and 𝒙 and 𝒙′ differ in only one feature i, then IGi(𝒙;𝒙′)β‰ 0. A feature that changes the output must receive non-zero attribution.

  3. Implementation Invariance. Two functionally equivalent networks (same input-output mapping, different architectures) produce identical Integrated Gradients attributions.

  4. Linearity. For networks f1,f2 and scalars a,b: IGi(af1+bf2)=aIGi(f1)+bIGi(f2).

  5. Symmetry-Preserving. If f is symmetric in features i and j, then IGi=IGj.

Among all attribution methods satisfying Sensitivity and Implementation Invariance, Integrated Gradients uniquely satisfies Completeness.

The Completeness axiom is particularly important from an auditing perspective: it guarantees that the explanation accounts for the entire prediction, with no attribution budget left unaccounted for. By contrast, vanilla gradient-times-input methods (which multiply the gradient at 𝒙 by the input value) can violate Completeness because they do not integrate over the path.

Attention Visualisation: Is Attention Explanation?

The rise of Transformer models introduced a new form of β€œexplanation” that is appealing in its simplicity: attention weights. When a text classifier based on BERT produces a prediction, the multi-head self-attention layers produce weight matrices π€βˆˆ[0,1]nΓ—n (one per head per layer) that ostensibly indicate how much each token β€œattends to” every other token. Visualising these weights as heatmaps became a popular way to explain model behaviour, and several major NLP papers in 2018–2019 relied on attention visualisations to support interpretability claims.

The Jain-and-Wallace Challenge

In a landmark 2019 paper, Jain and Wallace challenged the assumption that attention weights constitute valid explanations. Their argument rests on two empirical observations and one theoretical argument.

Empirical finding 1: Attention and feature importance disagree. When LIME and gradient-based attributions are computed alongside attention weights for the same prediction, the resulting attributions are poorly correlated (Spearman ρ<0.3 in many cases). High attention weight on a token does not imply that token drives the prediction.

Empirical finding 2: Adversarial attention. It is possible to construct β€œadversarial attention” distributions that produce the same model output as the original attention distribution while being maximally different in the attention weights. Formally, given a prediction y^ produced with attention 𝐀, Jain and Wallace find an alternative attention 𝐀~ such that f(𝒙;𝐀~)=f(𝒙;𝐀) but TVD⁑(𝐀,𝐀~) is large. This demonstrates that the mapping from attention to output is many-to-one: attention can be changed dramatically without changing the prediction.

Theoretical argument: Attention is an intermediate computation. Attention weights are computed inside the model, not at the interface between model and input. They capture which token representations are mixed at a given layer, but the final prediction depends on how those mixed representations are subsequently processed by feed-forward sublayers, layer normalisation, and additional attention heads. Attributing the prediction to attention weights at one layer ignores all downstream processing.

Caution.

Attention is Not Explanation.

Visualising attention weights as explanations conflates a model's internal routing mechanism with the causal attribution of output to input. Specifically:

  • High attention weight on a token xi does not imply that removing xi would change the prediction (violation of the Sensitivity axiom).

  • Attention weights do not satisfy Completeness: they do not sum to the output value.

  • In multi-head attention, different heads may attend to the same token for entirely different reasons; averaging across heads destroys this structure.

  • In deep Transformers, early-layer attention may track surface syntactic features while later-layer attention captures semantic relationships; mixing layers conflates these signals.

The controversy remains active. Wiegreffe and Pinter (2019) rebutted Jain and Wallace's adversarial construction, arguing that their adversarial attention distributions are not realisable without changing the value vectors, effectively changing the model itself. The current consensus is nuanced: attention can provide useful diagnostic signals but does not constitute a faithful, complete, or sensitive attribution in the formal sense required for trustworthy explanation.

What Attention Does Tell Us

Despite these limitations, attention visualisation is not worthless. Attention patterns in pre-trained language models exhibit systematic behaviours that are genuinely informative:

  • Syntactic heads. Certain heads in BERT's lower layers reliably attend along syntactic dependency arcs (subject-verb, noun-modifier), even though the model was never trained with syntactic supervision.

  • Coreference heads. Some heads track coreference chains, attending from pronouns to their antecedents.

  • Positional heads. A subset of heads implement diagonal attention (attending to the immediately preceding or following token), implementing a form of local context integration.

These patterns reveal something real about what the model has learned, even if they do not constitute faithful attribution of any specific prediction. The distinction matters: attention is a useful diagnostic tool for understanding model behaviour at the population level, but a poor explanatory tool for understanding any specific prediction.

Exercises: Classical Explainability Methods

Exercise 7.

(Shapley value computation.) Consider a binary classification model f:{0,1}3β†’[0,1] with three binary features x1,x2,x3. The model's outputs on all eight possible inputs are: f(0,0,0)=0.1,f(1,0,0)=0.4,f(0,1,0)=0.3,f(0,0,1)=0.2, f(1,1,0)=0.6,f(1,0,1)=0.5,f(0,1,1)=0.45,f(1,1,1)=0.8. Using the background value f(βˆ…)=f(0,0,0)=0.1, compute the Shapley values Ο•1,Ο•2,Ο•3 for the input (1,1,1) via (Shapley). Verify the Efficiency axiom: Ο•1+Ο•2+Ο•3=f(1,1,1)βˆ’f(0,0,0).

Exercise 8.

(Baseline sensitivity in Integrated Gradients.) Let f:ℝ⁑→ℝ⁑ be defined by f(x)=x3 (a scalar model for simplicity). Compute the Integrated Gradients attribution IG(x;xβ€²) for input x=2 and each of the following baselines: (a) xβ€²=0, (b) xβ€²=βˆ’1, (c) xβ€²=1. Verify Completeness in each case. Discuss: for which baseline does the attribution most naturally correspond to the β€œimportance” of the input relative to a natural reference point?

Exercise 9.

(Grad-CAM and the Sensitivity axiom.) Show by construction that Grad-CAM can violate the Sensitivity axiom of Integrated Gradients. Specifically, construct a two-layer ReLU network f(𝒙)=ReLU(𝐖2ReLU(𝐖1𝒙)) and an input 𝒙 such that f(𝒙)β‰ f(0), the prediction changes if feature x1 is zeroed out, yet the Grad-CAM score for feature x1 is zero. Hint: consider a network where the gradient at 𝒙 happens to be zero for x1 due to ReLU saturation, even though the path integral is non-zero.

Why Classical XAI Fails for Generative Models

Classical XAI methods are engineered solutions to a specific problem: given a discriminative model f:𝒳→𝒴 (a classifier or regressor) and a fixed input π’™βˆˆπ’³, attribute the scalar prediction f(𝒙)βˆˆπ’΄ to the input features. The problem is well-posed: the input is fixed, the output is a scalar, and the attribution is a vector in ℝd⁑. The methods we surveyed in Classical Explainability Methods are mature, principled, and - within their domain - genuinely useful.

The problem is that generative models are not discriminative models. A diffusion model, an autoregressive language model, a VAE, or a vision-language model does not classify an input; it produces outputs. And the production process is qualitatively different from classification in ways that systematically defeat every classical XAI method. This section catalogues these failure modes precisely, building toward the formal definition of what interpretability should mean for generative models.

The detective analogy is helpful here. Classical XAI assumes that we are trying to understand a judge's verdict: given the evidence (input 𝒙), which pieces of evidence drove the verdict (f(𝒙))? But a generative model is not a judge passing a verdict; it is a novelist writing a story. The novelist does not declare a fact; they generate a narrative that could have gone in many directions. Understanding the novelist requires a fundamentally different set of questions: What algorithms does the novelist employ? What internal representations mediate the creative process? How does the initial prompt constrain the space of possible stories?

The Attribution Problem: What Is the Input?

All classical XAI methods presuppose a fixed, well-defined input π’™βˆˆπ’³ to which attributions are assigned. For a ResNet classifying an image, 𝒙 is a pixel tensor; for a BERT model classifying sentiment, 𝒙 is a token sequence. The attribution vector π“βˆˆβ„d⁑ is indexed by the same dimensions as 𝒙.

Generative models confound this assumption in several distinct ways.

The condition vs. the generation.

In a conditional generative model such as a text-conditioned image diffusion model, the input comprises both the condition 𝒄 (the text prompt) and the noise seed 𝒛 (the initial Gaussian sample that seeds the reverse process). If a generated image contains a spurious artefact, is it attributable to 𝒄 or 𝒛? The artefact may arise from the interaction of specific prompt tokens with specific noise configurations in ways that cannot be decomposed.

Unconditional generation.

In unconditional models (vanilla VAEs, vanilla GANs, unconditional diffusion), there is no condition at all. The β€œinput” is pure noise π’›βˆΌp(𝒛), which has no semantic meaning. Attributing a generated face's eye colour to specific dimensions of 𝒛 is technically feasible (one can compute βˆ‚π’™^i/βˆ‚zj) but semantically meaningless without a prior understanding of what zj represents - and that understanding is precisely what is missing.

The prompt is not the cause.

In large language models, the prompt 𝒄 is the nominal input, but the model's generation also depends on its entire training history (encoded in 𝜽), the decoding algorithm (temperature, top-p, beam search), and - in stochastic decoding - the random seed. Attributing a specific generated sentence to specific prompt tokens conflates these three qualitatively different sources of influence.

Key Idea.

For discriminative models, the input 𝒙 is a fixed observation and the output f(𝒙) is a deterministic function of it (modulo implementation randomness). For generative models, the β€œinput” is a composite of semantic condition 𝒄, noise seed 𝒛, model parameters 𝜽, and decoding hyperparameters Ξ». No single element is privileged as β€œthe input”, and attributing output properties to any one element ignores the others.

Stochastic Generation: Same Input, Different Outputs

Classical XAI methods implicitly assume that f(𝒙) is a deterministic scalar. LIME builds a local surrogate by querying f on perturbations of 𝒙 and recording the outputs; SHAP evaluates v(S)=𝔼Sβ€Ύ[f(𝒙S,𝒙Sβ€Ύ)]; Grad-CAM computes βˆ‚f(𝒙)/βˆ‚Ak. All of these operations require either a deterministic output or the ability to marginalise over randomness in a controlled way.

Generative models are stochastic by design. A diffusion model with temperature Ο„>0 produces a different image on every forward pass for the same prompt. An autoregressive model with nucleus sampling generates a different completion on every call. A VAE samples π’›βˆΌqΟ•(𝒛|𝒙) and decodes 𝒙^∼pΞΈ(𝒙^|𝒛), with two stochastic steps.

This stochasticity creates a fundamental problem for attribution.

Which output do we explain?

Given n stochastic outputs 𝒙^(1),…,𝒙^(n) from the same prompt, LIME would need to construct a different surrogate for each output (since each has different pixel values to be attributed). Averaging the surrogates loses information about which outputs are typical and which are outliers. Explaining the average output 𝒙‾=(1/n)βˆ‘k𝒙^(k) is misleading because the average is itself not a typical output of the generative model (it is blurry, for diffusion models, or incoherent, for language models).

Output variance as information.

The variance across stochastic outputs is itself a meaningful signal: high variance indicates that the model is uncertain or that the prompt under-specifies the generation. Classical XAI methods entirely ignore this variance, providing no tools to explain why the model is uncertain or which prompt tokens are responsible for under-specification.

Remark 5.

Formally, for a stochastic generative model pΞΈ(𝒙^|𝒄), the SHAP efficiency axiom requires attributions to sum to a scalar. If the target quantity is the marginal probability of a specific output 𝒙^, i.e., v(𝒩)=log⁑pΞΈ(𝒙^|𝒄), then SHAP attributions assign credit to prompt tokens 𝒄i for explaining the log-likelihood of a specific sample. But this quantity depends on both 𝒄 and 𝒙^ jointly, and a different 𝒙^ yields a completely different attribution vector. There is no canonical choice of β€œthe output” over which to compute attributions.

Multi-Step Processes: The Attribution Chain Problem

Diffusion models generate through T∈[50,1000] denoising steps. Autoregressive language models generate through N sequential token predictions, where N may be hundreds or thousands. In both cases, the final output is the result of a long chain of stochastic transformations, and the causal structure of this chain creates fundamental obstacles for classical attribution.

Diffusion: The T-Step Attribution Puzzle

In a DDPM with T steps, the generation proceeds as a Markov chain: 𝒙T→𝒙Tβˆ’1→⋯→𝒙1→𝒙0, where each step applies the learned denoising network ΞΌΞΈ(𝒙t,t). If we wish to attribute a feature of the final image 𝒙0 (say, the presence of a red object in the upper-left quadrant) to the initial noise 𝒙T, we must trace the causal path through all T denoising steps.

A single application of Grad-CAM at the final denoising step t=1β†’0 provides a saliency map for the last step, but ignores the contributions of steps t=2,…,T. The contribution of early steps is mediated through the intermediate states 𝒙Tβˆ’1,…,𝒙1, which are never observed (in standard sampling) and whose dimensions lack semantic meaning.

Integrated Gradients can in principle be applied by treating 𝒙T as the input and defining a baseline 𝒙Tβ€² (e.g., the zero vector). But the straight-line interpolation from 𝒙Tβ€² to 𝒙T passes through intermediate noise tensors that are not valid inputs to the denoising chain: the denoising network at step t expects 𝒙t∼q(𝒙t|𝒙0), not an arbitrary interpolation.

Autoregressive Models: The Token Dependency Graph

In an autoregressive language model, token n+1 is generated conditioned on all previous tokens 𝒄1:n, which include both the original prompt and the model's own previous generations. The causal graph of influences is a directed acyclic graph where every prompt token and every previously generated token can influence every future token.

SHAP can compute attributions for any specific output token c^n+1 by treating 𝒄1:n as the features. But the attributions change for every output token, and aggregating them across a multi-token generation requires a choice: sum? max? mean? Each aggregation discards structural information about how attribution evolves as generation proceeds.

Moreover, in teacher-forcing training, the model predicts each token conditioned on the ground-truth context, but in inference, it conditions on its own (possibly erroneous) previous predictions. Attributing a generation error to a specific prompt token may be misleading if the error was actually caused by an earlier generation error that snowballed.

Latent Space Opacity: VAE and GAN Codes

In discriminative models, the input 𝒙 has a natural human interpretation: pixels have positions, words have meanings. This semantic grounding is what makes feature attribution meaningful: saying β€œthe model attended to the top-right corner” or β€œthe word `not' had negative attribution” conveys actionable information.

Latent variable models fundamentally lack this semantic grounding.

VAE Latent Codes

In a VAE, the encoder qΟ•(𝒛|𝒙) maps an input to a distribution over a k-dimensional latent space. The decoder pΞΈ(𝒙^|𝒛) maps latent codes back to data space. If we attribute a generated image feature to latent dimensions zj, what does this mean semantically?

In general, nothing. The latent code 𝒛 is organised by the ELBO objective to maximise reconstruction quality and keep the posterior close to the prior 𝒩(𝟎,𝐈). There is no mechanism that ensures zj corresponds to any human-interpretable concept (β€œhair colour”, β€œfacial expression”, β€œobject shape”). In practice, latent dimensions in vanilla VAEs are entangled: z1 may partially encode hair colour, face orientation, and background brightness simultaneously.

Disentanglement methods (Ξ²-VAE, FactorVAE, TC-VAE) seek to encourage axis-aligned latent factors that correspond to independent generative factors. But even successful disentanglement does not guarantee semantic alignment: a disentangled latent code where z1 controls β€œsize of the leftmost object” and z2 controls β€œhue of the background” may be interpretable by reference to the images but does not correspond to human-level concepts.

GAN Latent Spaces

In a GAN, the generator G:𝒡→𝒳 maps a noise vector π’›βˆΌp(𝒛) to a data point. Unlike VAEs, GANs impose no constraint on the structure of 𝒡: the latent space can be geometrically complex, with no guarantee of linearity, convexity, or semantic regularity.

GANSpace (HΓ€rkΓΆnen et al., 2020) and InterfaceGAN (Shen et al., 2020) discovered empirically that GAN latent spaces often contain interpretable directions: a vector πβˆˆπ’΅ such that traversing 𝒛→𝒛+λ𝐝 corresponds to a semantically coherent change in the generated image (e.g., ageing, adding glasses, changing hairstyle). But these directions must be discovered by post-hoc linear probing or supervised steering - they are not intrinsic to the latent code's native coordinates.

Remark 6.

The opacity of latent spaces creates a semantic grounding gap: classical XAI methods attribute model outputs to input features that have pre-existing human interpretations (pixels, words, superpixels). For generative latent variable models, there is no canonical human interpretation of the features being attributed to. Attributing a generated artefact to z7=1.3 conveys no actionable information without a separately learned semantic dictionary for the latent space.

Cross-Modal Alignment: VLMs and the Fusion Problem

Vision-language models (VLMs) such as CLIP, DALL-E, Stable Diffusion, and GPT-4V add a further layer of complexity: they must fuse information from two qualitatively different modalities - visual tokens and text tokens - into a unified representation that drives generation. The alignment between modalities is learned implicitly through massive-scale contrastive or generative training, and the resulting representations are highly non-transparent.

The Cross-Attention Attribution Problem

In a latent diffusion model conditioned on text, cross-attention layers compute attention between visual tokens (keys and values from the spatial feature map) and text tokens (queries from the CLIP text encoder). The cross-attention weight aij measures the degree to which spatial position i of the image attends to text token j.

Visualising cross-attention maps (as in Prompt-to-Prompt and Attend-and-Excite) provides a form of spatial-textual attribution: β€œthe word `sunset' drove the redness of the sky region.” But this attribution has the same problems as standard attention visualisation (see Attention Visualisation: Is Attention Explanation?) compounded by cross-modal entanglement: text tokens are processed by CLIP, which itself is a complex non-transparent model; visual tokens are extracted by a VAE encoder; and the cross-attention operates in a compressed latent space, not in pixel space.

Modality Attribution Failure

Consider the question: β€œIn a CLIP-guided diffusion model that generated an image of a dog on a skateboard, how much of the `skateboard' visual content is attributable to the text prompt, how much to the image prior learned during training, and how much to the initial noise seed?” This question is natural for a human engineer debugging a generation failure, but it has no well-defined answer in the framework of classical attribution:

  • The text prompt provides the semantic intent (skateboard).

  • The model's weights encode the visual prior (what skateboards look like in the training distribution).

  • The noise seed determines which specific visual configuration is selected from the prior.

  • The CLIP text encoder transforms the word β€œskateboard” into a 512-dimensional vector whose relationship to the skateboard's visual appearance is encoded in the weights, not in any human-readable form.

Attributing the skateboard's visual presence to β€œthe word `skateboard' in the prompt” conflates all of these factors. Classical SHAP over the text tokens would assign attribution to the word β€œskateboard” simply because removing it changes the output - but it would assign zero attribution to the training data that taught the model what skateboards look like, and zero attribution to the model architecture that determines how text and image representations are aligned.

The Fundamental Shift: From Feature Attribution to Algorithm Understanding

The failure modes catalogued above are not engineering deficiencies that can be patched by better implementations of SHAP or Integrated Gradients. They reflect a fundamental mismatch between the question that classical XAI asks and the question that generative model interpretability requires.

Classical XAI asks: which input features drove this output? This question presupposes a fixed input, a scalar (or low-dimensional) output, and a model that computes a deterministic function of the input. Generative models violate all three presuppositions.

Key Idea.

Classical XAI asks β€œwhich input features matter?” - a question appropriate for discriminative models where inputs have semantic meaning and outputs are scalar decisions. For generative models, which lack fixed inputs, produce stochastic high-dimensional outputs through multi-step algorithms, and encode knowledge in latent spaces with no inherent semantic grounding, we must ask a different question: β€œWhat algorithm does the network implement?”

This shift from attribution to algorithm understanding defines the programme of mechanistic interpretability: reverse engineering the computational primitives, circuits, and representations that a generative model uses to produce its outputs.

The shift has a precedent in the history of science. Early pharmacologists asked β€œwhich molecules in this extract reduce fever?” - an attribution question. Modern molecular pharmacology asks β€œwhat receptor does aspirin bind, and how does binding inhibit prostaglandin synthesis?” - a mechanistic question. The mechanistic question is harder to answer but provides qualitatively different understanding: it explains not just what works but why it works, and it enables prediction and design rather than mere post-hoc explanation.

A Taxonomy of Classical XAI Failure Modes

MethodAutoregressive LMDiffusion ModelVAE/GANVLM
SHAPPartial: per-tokenCritical: T-stepCritical: latentCritical:
attribution onlycoalition evalspace opacitycross-modal
ignores generationintractableundef. inputentanglement
LIMEPartial: promptCritical: noCritical: noPartial: prompt
perturbationsstable outputinput toperturbations
onlyto regress onperturbonly; cross-
attn ignored
Grad-CAMN/A: noPartial: appliesN/A: noPartial: cross-
conv. layersat single stepconv. stackattn maps are
onlynot Grad-CAM
Integr. GradsPartial: per-Critical: pathPartial: inputCritical: no
token only;not in datais latent;semantic
aggregation ad hocmanifoldno semanticsbaseline exists
AttentionMisleading:Misleading:N/AMisleading:
Viz.not faithfulcross-attncross-modal
attributionpartial onlyattn conflated
Failure modes of classical XAI methods applied to generative architectures. Each cell describes why the method breaks down for that architecture. β€œN/A” indicates the method has no natural application. β€œPartial” indicates the method can be applied in a restricted sense but provides incomplete or misleading explanations. β€œCritical” indicates a fundamental failure that invalidates the explanation.
The gap between classical XAI and what generative models require. Classical XAI (left) operates in a regime with fixed inputs, deterministic scalar outputs, and semantic input features, enabling principled feature attribution. Generative models (right) have composite, partially stochastic inputs, high-dimensional stochastic outputs produced through multi-step latent processes, and cross-modal fusion. The orange zone in the centre represents the gap: the regime where classical attribution methods break down. Mechanistic interpretability (bottom) bridges this gap by targeting algorithm understanding rather than feature attribution.

Interpretability Desiderata for Generative Models

Having identified the failure modes of classical XAI, we can now state positively what a satisfactory interpretability method for generative models must achieve. We formulate this as three formal desiderata.

Definition 10 (Interpretability Desiderata for Generative Models).

Let pΞΈ(𝒙^|𝒄) be a generative model with parameters 𝜽, condition 𝒄, and output distribution over 𝒙^βˆˆπ’³. An interpretability method ℐ produces an explanation E=ℐ(pΞΈ,𝒄,𝒙^). We say ℐ is satisfactory if E satisfies all three of the following desiderata:

  1. Faithfulness. The explanation E must accurately describe the computational process by which pΞΈ generates 𝒙^. Formally, let pΞΈE be the model behaviour predicted by E, and let Ξ”=KL⁑(pΞΈβ€–pΞΈE) measure the divergence between the true model and the model as described by E. Then ℐ is faithful if Δ≀ϡfaith for some tolerance Ο΅faithβ‰₯0. An explanation that describes a plausible-sounding process that the model does not actually implement is not faithful, regardless of how interpretable it is to a human reader.

  2. Completeness. The explanation E must account for all components of the model's generative capacity that are relevant to the outputs being explained. Formally, if 𝒙^ has m identifiable properties {P1,…,Pm} (e.g., the presence of a specific object, the colour of a region, the sentiment of a sentence), then E must provide an account for each Pk in terms of identifiable model computations. An explanation that accounts for only a subset of the output's properties is incomplete.

  3. Minimality. Among all faithful and complete explanations, E should be the simplest: it should identify the smallest subset of model components (circuits, attention heads, MLP neurons, latent dimensions) whose behaviour is sufficient to account for the explained outputs. Formally, if Eβ€² is another faithful, complete explanation with fewer components than E, then ℐ should prefer Eβ€². Minimality is the Occam's razor of interpretability: it guards against over-explanation that attributes outputs to the entire model.

These desiderata generalise and extend the axiomatic foundations of classical XAI. Faithfulness generalises the Sensitivity axiom: both require that explanations accurately reflect causal relationships. Completeness generalises the Efficiency axiom of SHAP: both require that the explanation accounts for the total output. Minimality is new: it has no direct classical counterpart, because attribution methods over a fixed input space are automatically minimal (they produce exactly d attribution values, one per feature). For generative models, where the explanation space is the set of computational circuits in the model, minimality is non-trivial to enforce.

Proposition 2 (Impossibility of Classical Faithfulness).

Let f:𝒳→𝒴 be any classifier and 𝝓(𝒙) any attribution vector. For a generative model pΞΈ(𝒙^|𝒄) where the output space 𝒳out is high-dimensional and stochastic, there exists no attribution vector 𝝓(𝒄)βˆˆβ„d𝒄⁑ satisfying all three desiderata simultaneously under the constraint that the explanation is indexed by condition features alone.

Proof.

We sketch the argument. Faithfulness requires that E accurately describes the generative computation. The generative computation involves both the condition 𝒄 and the model parameters 𝜽; any explanation indexed only by 𝒄 cannot be faithful to the model's internal algorithm (which depends on 𝜽). Completeness requires accounting for all output properties; since outputs are stochastic, any complete explanation must account for the model's uncertainty, which is a function of 𝜽 and 𝒄 jointly. No vector 𝝓(𝒄)βˆˆβ„d𝒄⁑ can encode both the condition-specific attribution and the model-parameter-encoded prior simultaneously without violating either faithfulness or completeness.

The proposition is not a counsel of despair. It identifies the correct unit of analysis: rather than attributing outputs to input features, interpretability methods for generative models must attribute outputs to model components (circuits, layers, attention heads, neurons, latent directions). This is the programme of mechanistic interpretability, which we develop in the subsequent sections of this chapter.

Historical Note.

The limitations of feature attribution methods were recognised early in the history of XAI. As early as 2017, Rudin (later to publish the influential β€œStop Explaining Black Box Machine Learning Models for High Stakes Decisions” in 2019) argued that post-hoc explanations of opaque models provide false confidence: they explain a proxy of the model, not the model itself. The critique became sharper with the rise of large generative models. In 2022, the DALL-E 2 model card from OpenAI explicitly acknowledged that β€œattribution of generated content to training data is not yet a solved problem.” The European Union's AI Act (2024) includes specific provisions for β€œhigh-risk AI systems” that require interpretability, but notably exempts generative AI from the strictest attribution requirements, implicitly acknowledging that current methods cannot satisfy them.

The formal treatment of interpretability desiderata for generative models has been developed by several groups since 2022, including work at DeepMind on mechanistic interpretability of language models, Anthropic's research on feature superposition and circuit analysis in transformer models, and the MATS (ML Alignment and Theory Scholars) research programme. The desiderata in Definition 10 synthesise threads from this literature into a single formal framework.

Exercises: Failures of Classical XAI

Exercise 10.

(LIME under stochastic generation.) Suppose you attempt to apply LIME to a text-to-image diffusion model with T=50 denoising steps. You generate n=50 perturbations of the prompt β€œa red apple on a wooden table” by randomly masking words, and for each perturbation, you run the full diffusion sampling to produce an image. Define the LIME target as the average RGB value of the centre pixel of the generated image.

(a) Show that the expected variance of the LIME target across runs with the same perturbation (different noise seeds) can be larger than the variance across different perturbations (same noise seed), depending on the temperature parameter Ο„. Specifically, give a bound on the signal-to-noise ratio of the LIME regression as a function of VarΟ„[x^centre] (variance due to stochasticity) and Var𝒛[x^centre] (variance due to prompt masking).

(b) Propose and justify a modification to the LIME procedure that controls for noise-seed variance by fixing the seed across all perturbations. What new assumption does this modification introduce, and when is it violated?

Exercise 11.

(SHAP attribution for a VAE: the semantic grounding problem.) Consider a VAE with encoder qΟ•(𝒛|𝒙) (Gaussian with diagonal covariance) and decoder pΞΈ(𝒙^|𝒛) trained on face images. We wish to apply SHAP to explain why a specific decoded image 𝒙^=pΞΈ(𝒙^|π’›βˆ—) has blue eyes, where π’›βˆ—=(𝒛1βˆ—,…,𝒛kβˆ—) is a sampled latent code.

(a) Define a characteristic function v:2[k]→ℝ⁑ where v(S) measures the β€œblueness” of the decoded image when latent features in S retain their values from π’›βˆ— and features in Sβ€Ύ are marginalised by integration against the prior. Write out v(S) formally.

(b) Show that the SHAP attributions Ο•j computed from this v may assign high attribution to a latent dimension j even if zjβˆ— has no semantic relationship to eye colour, as long as it is statistically correlated with eye-colour-encoding dimensions through the prior p(𝒛). Provide a construction.

(c) Argue that the Efficiency axiom is satisfied but the explanation is not faithful in the sense of Definition 10.

Exercise 12.

(Testing the desiderata.) For each of the following putative explanations of a generative model, determine which of the three desiderata (Faithfulness, Completeness, Minimality) are satisfied and which are violated. Justify each answer.

(a) β€œThe diffusion model generated a dog because the word `dog' was present in the prompt.” (Assume the explanation is obtained by SHAP over prompt tokens, fixing the noise seed.)

(b) β€œThe image was generated by iteratively applying the learned denoising network ΞΌΞΈ(β‹…,t) for t=T,Tβˆ’1,…,1, starting from Gaussian noise 𝒙T.” (This is a complete description of the sampling algorithm.)

(c) β€œAttention head 14 in layer 8 of the U-Net implements an edge-detection circuit that activates on high-frequency spatial features and drives the sharpening of object boundaries in the final step of denoising.” (Assume this is verified by causal intervention experiments.)

The Mathematical Framework of Transformer Circuits

Modern large language models are, at heart, transformers: architectures built from repeated blocks of multi-head self-attention and feedforward networks connected by residual streams. To truly interpret what these models compute, we need more than visualisations of attention weights; we need a rigorous mathematical language for decomposing the computation into atomic, understandable units. This language is the theory of transformer circuits, developed by Anthropic researchers Elhage et al. as a precise mechanistic account of what individual components of a transformer compute and how they interact.

The central insight is beautifully simple: at every layer, each token maintains a vector called its residual stream, which acts as a shared communication bus. Every component-attention heads and MLP layers alike-reads from this bus, performs a transformation, and writes back an additive update. Because all operations are additive, the residual stream at any layer is an exact linear superposition of all previous contributions. This linearity is not an approximation; it is an architectural fact that makes the transformer uniquely amenable to circuit-level analysis.

The Residual Stream as a Communication Bus

We begin with a precise definition.

Definition 11 (Residual Stream).

Let 𝒙i(0)βˆˆβ„dmodel⁑ denote the embedding of token i produced by the embedding matrix 𝐖Eβˆˆβ„dmodelΓ—|𝒱|⁑ applied to the one-hot token vector, plus a positional encoding. For a transformer with L layers, each containing H attention heads and an MLP sub-layer, the residual stream at layer β„“ for token i is the vector (DEF)𝒙i(β„“)=𝒙i(0)+βˆ‘k=1β„“Ξ”i(k), where Ξ”i(k) is the total additive update contributed by layer k (summing over all attention heads in that layer plus the MLP block). The logit for predicting vocabulary item v after the final layer is (Final)β„“v=(𝐖U)v,⋅⋅𝒙i(L), where 𝐖Uβˆˆβ„|𝒱|Γ—dmodel⁑ is the unembedding matrix.

The key structural consequence of (DEF) is that every component of the network interacts with every other component only through the residual stream. There are no direct skip connections between layer 1's attention heads and layer 3's MLP; the only path is through sequential reads and writes to the shared bus.

Token embedding 𝐖E.

The embedding matrix 𝐖Eβˆˆβ„dmodelΓ—|𝒱|⁑ maps a discrete token index t∈{1,…,|𝒱|} to a dense vector 𝐖E𝒆tβˆˆβ„dmodel⁑, where 𝒆t is the t-th standard basis vector. In practice, the model learns 𝐖E end-to-end, and its columns are the token embedding vectors. The initialisation of the residual stream is (INIT)𝒙i(0)=𝐖E𝒆ti+𝒑i, where 𝒑i is the positional encoding for position i.

Unembedding 𝐖U.

The unembedding matrix 𝐖Uβˆˆβ„|𝒱|Γ—dmodel⁑ maps the final residual stream vector back to logits over the vocabulary. In many implementations, 𝐖U=𝐖E⊀ (weight tying), although this is not universal in large models. The pre-softmax logit for token v is β„“v=(𝐖U𝒙i(L))v, and the predicted probability is p^(v|context)=softmax(𝐖U𝒙i(L))v.

Remark 7.

The logit β„“v=𝒙i(L)βŠ€π–UβŠ€π’†v is a bilinear form in the final residual stream and the unembedding direction for token v. Because the residual stream is a sum of contributions from all layers and heads ((DEF)), we can decompose the logit linearly over components. This logit attribution is the foundation of the logit lens technique in The Logit Lens: Tracking Predictions Layer by Layer.

Attention Heads as Independent Additive Units

Each attention head in a transformer layer is an independent computation that (1) computes a soft routing pattern over source positions, and (2) moves weighted information from those positions to the destination. Crucially, multiple heads in the same layer act independently and additively: their outputs are summed before being added to the residual stream.

Formally, for layer β„“ with H heads, the attention sub-layer update for destination token i is (Additive)Ξ”i(β„“,attn)=βˆ‘h=1HΞ”i(β„“,h), where Ξ”i(β„“,h) is the contribution from head h in layer β„“. The MLP update Ξ”i(β„“,MLP) is then added separately.

This additive structure has a profound consequence: we can isolate the contribution of any individual head by ablating or patching it, and its removal changes the residual stream by exactly βˆ’Ξ”i(β„“,h). There is no non-linear interaction between different heads in the same layer (though non-linearities in the MLP and in subsequent attention heads can create effective inter-layer non-linearities through the residual stream).

The QK Circuit: Attention Pattern Computation

Every attention head contains four weight matrices: 𝐖Qh,𝐖Kh,𝐖Vhβˆˆβ„dheadΓ—dmodel⁑ and 𝐖Ohβˆˆβ„dmodelΓ—dhead⁑. We derive the two fundamental circuits that characterise each head.

Derivation of the QK circuit.

The query and key vectors for head h, computed from source residual streams 𝒙j(β„“βˆ’1) and destination residual stream 𝒙i(β„“βˆ’1), are (Vectors)𝒒ih=𝐖Qh𝒙i(β„“βˆ’1)βˆˆβ„dhead⁑,π’Œjh=𝐖Kh𝒙j(β„“βˆ’1)βˆˆβ„dhead⁑. The (pre-softmax) attention score between destination i and source j is the scaled inner product: (Score)sijh=𝒒ihβŠ€π’Œjhdhead=(𝐖Qh𝒙i(β„“βˆ’1))⊀(𝐖Kh𝒙j(β„“βˆ’1))dhead. Expanding the inner product: (Expansion)sijh=1dhead𝒙i(β„“βˆ’1)βŠ€π–QhβŠ€π–KhβŸπ–QKh𝒙j(β„“βˆ’1), which reveals the QK circuit matrix 𝐖QKhβˆˆβ„dmodelΓ—dmodel⁑.

Definition 12 (QK Circuit).

For attention head h in layer β„“, the QK circuit is the matrix (DEF)𝐖QKh=𝐖QhβŠ€π–Khβˆˆβ„dmodelΓ—dmodel⁑. The attention score between destination token i and source token j depends on the residual streams only through this matrix: (Score)sijh=1dhead𝒙i(β„“βˆ’1)βŠ€π–QKh𝒙j(β„“βˆ’1). The attention weight from j to i is aijh=softmaxj⁑(sijh) (with causal masking for autoregressive models).

Remark 8.

The QK circuit matrix 𝐖QKhβˆˆβ„dmodelΓ—dmodel⁑ has rank at most dhead, since it factors as a product of 𝐖QhβŠ€βˆˆβ„dmodelΓ—dhead⁑ and 𝐖Khβˆˆβ„dheadΓ—dmodel⁑. Typically dheadβ‰ͺdmodel (e.g., 64β‰ͺ768 for a standard BERT-base head), so the QK circuit is a highly compressed bilinear form: the head can only attend based on a dhead-dimensional subspace of information in the residual streams.

The OV Circuit: Information Movement

The OV circuit describes what information is moved once the attention pattern determines where to attend.

Derivation of the OV circuit.

Given attention weights aijh, the value vector aggregated at destination i from head h is (AGG)𝒗ih=βˆ‘jaijh𝐖Vh𝒙j(β„“βˆ’1). The output of head h at destination i is then projected back to the residual stream dimension: (Output)Ξ”i(β„“,h)=𝐖Oh𝒗ih=𝐖Ohβˆ‘jaijh𝐖Vh𝒙j(β„“βˆ’1)=βˆ‘jaijh𝐖Oh𝐖VhβŸπ–OVh𝒙j(β„“βˆ’1).

Definition 13 (OV Circuit).

For attention head h in layer β„“, the OV circuit is the matrix (DEF)𝐖OVh=𝐖Oh𝐖Vhβˆˆβ„dmodelΓ—dmodel⁑. The update written to the residual stream by head h at destination i is (Update)Ξ”i(β„“,h)=βˆ‘jaijh𝐖OVh𝒙j(β„“βˆ’1), a weighted sum of linearly transformed source residual streams.

The OV circuit makes precise the intuition that a head β€œcopies information”: if 𝐖OVhβ‰ˆπˆ, the head copies the source residual stream verbatim (weighted by attention) to the destination. If 𝐖OVh maps token type embeddings to prediction directions in 𝐖U⊀, the head directly increments logits for particular next tokens.

Remark 9.

Like the QK circuit, the OV circuit has rank at most dhead. The dhead-dimensional bottleneck forces the head to implement a low-rank linear map: it can only move a dhead-dimensional subspace of information. This rank constraint is the source of the β€œeach head implements a simple operation” phenomenon.

TikZ Figure: The Residual Stream Architecture

The following figure illustrates the residual stream as a shared bus with attention heads reading and writing through their QK and OV circuits.

The residual stream as a shared communication bus. Each attention head in layer β„“ reads from the residual stream via its QK circuit (determining where to attend) and its OV circuit (determining what to move), then writes an additive update back. MLP blocks similarly read and write. Because all interactions are additive, the final residual stream is an exact linear superposition of all contributions, enabling precise attribution of each component's role.

Head Composition across Layers

Single-layer attention heads implement simple operations. The true power of transformers emerges from composition: when the output of one head enters the residual stream and is read by a later head.

Q-Composition, K-Composition, and V-Composition

Let head A be in layer β„“1 and head B be in layer β„“2>β„“1. Head B reads from the residual stream 𝒙i(β„“2βˆ’1), which contains the contribution Ξ”i(β„“1,A)=𝐖OVA𝒙j(β„“1βˆ’1) (averaged over the head A attention pattern). Depending on which weight matrix of head B is most sensitive to this contribution, we distinguish:

  1. Q-Composition. Head A's output Ξ”i(β„“1,A) influences 𝒒iB via 𝐖QB. The virtual QK weight for the composed circuit is (Compose)𝐖QKAβ†’B=(𝐖QB𝐖OVA)βŠ€π–KB, which determines how head A's processing of destination token i modulates what head B attends to from source token j.

  2. K-Composition. Head A's output Ξ”j(β„“1,A) (at source position j) influences π’ŒjB via 𝐖KB. The virtual weight is (Compose)𝐖QKAβ†’B=𝐖QB⊀(𝐖KB𝐖OVA), which controls how head A's processing of source token j modulates what head B attends to from j.

  3. V-Composition. Head A's output Ξ”j(β„“1,A) (at source position j) influences 𝒗jB via 𝐖VB. The virtual OV weight for the composed circuit is (Compose)𝐖OVAβ†’B=𝐖OB(𝐖VB𝐖OVA), which maps the original source residual stream (before head A processed it) all the way to the output of head B.

Definition 14 (Virtual Weights).

A virtual weight matrix is a product of two or more actual weight matrices, corresponding to a path through the transformer circuit graph that passes through the residual stream. Virtual weights reveal emergent relationships between tokens that cannot be detected by examining any single weight matrix in isolation. For a depth-L transformer with H heads per layer, the number of possible virtual weights grows as π’ͺ((LH)2), and many of these correspond to identifiable functional circuits such as induction heads or copy suppression heads.

Induction Heads: A Canonical Example of Composition

The most studied example of two-layer head composition is the induction head circuit. Induction heads perform a simple but powerful operation: given a sequence containing …AB…A, they predict B to follow the second occurrence of A by attending back to the first occurrence. This is achieved through the composition of two heads across layers:

  1. A previous-token head in layer 1 (K-composition): attends from position i to position iβˆ’1, writing information about the previous token into the residual stream at each position.

  2. An induction head in layer 2 (uses the layer-1 output via K-composition): attends from position i to position j where the previous-token residual stream at j matches the current token at i.

Together they implement the lookup: β€œfind where my current token appeared before, and copy what came after it.” This is a two-layer circuit with measurable virtual weights, and its ablation causes a sharp drop in in-context learning performance.

Theorem: Decomposition of Transformer Output

We now state the fundamental decomposition theorem that makes transformer circuits mathematically tractable.

Theorem 3 (Linear Decomposition of Transformer Logits).

Let 𝒯 be a transformer with L layers, H attention heads per layer, weight-tied embeddings 𝐖U=𝐖E⊀, and no layer normalisation (or with layer normalisation treated as an affine transformation absorbed into adjacent weights in the fold-LN approximation). For any target token vβˆˆπ’± and destination position i, the logit β„“v decomposes exactly as (Decomp)β„“v=𝐖U𝐖E𝒆ti⏟directΒ path⋅𝒆v+βˆ‘β„“=1Lβˆ‘h=1H𝐖UΞ”i(β„“,h)⏟headΒ (β„“,h)Β logitΒ attr.⋅𝒆v+βˆ‘β„“=1L𝐖UΞ”i(β„“,MLP)⏟MLP(β„“)Β logitΒ attr.⋅𝒆v, where Ξ”i(β„“,h) is the output of head h in layer β„“ at position i ((Update)) and Ξ”i(β„“,MLP) is the output of the MLP block in layer β„“. Each term is a scalar logit attribution that can be computed independently.

Proof sketch.

The proof is a direct consequence of the linearity of the residual stream and the linearity of the unembedding. By Definition 11, 𝒙i(L)=𝒙i(0)+βˆ‘β„“=1L(βˆ‘h=1HΞ”i(β„“,h)+Ξ”i(β„“,MLP)). Applying the unembedding 𝐖U (a linear map) to both sides and taking the inner product with 𝒆v gives β„“v=𝐖U𝒙i(L)⋅𝒆v=𝐖U𝒙i(0)⋅𝒆v+βˆ‘β„“,h𝐖UΞ”i(β„“,h)⋅𝒆v+βˆ‘β„“π–UΞ”i(β„“,MLP)⋅𝒆v. Since 𝒙i(0)=𝐖E𝒆ti+𝒑i and we absorb the positional term into the direct path, the result follows. Each term depends only on the weights of the corresponding component (and the residual stream values it reads from, which depend on earlier components). This is an exact identity, not an approximation, given the stated assumptions.

Remark 10.

Real transformers apply layer normalisation before each sub-layer, which introduces a non-linearity that breaks the exact decomposition. The fold-LN approximation replaces each LayerNorm with its first-order linearisation around the mean activation, restoring additivity at the cost of a small approximation error. Empirically, this approximation introduces less than 5% relative error in logit attributions for most positions, making it a practical tool.

Example: Information Flow in a 2-Layer Transformer

Example 3 (Tracing the Induction Circuit).

Consider a 2-layer, 2-head transformer processing the sequence [𝙰,𝙱,𝙲,𝙰] (positions 1,2,3,4) and predicting the next token after position 4.

Layer 1, Head 1 (previous-token head).

The QK circuit 𝐖QK(1,1) is learned such that position i attends strongly to position iβˆ’1. The OV circuit 𝐖OV(1,1) copies the source residual stream. Result: at each position i, the residual stream is updated with information about token at position iβˆ’1.

Concretely, at position 4 (A2): Ξ”4(1,1)β‰ˆπ–OV(1,1)𝒙3(0)(informationΒ fromΒ positionΒ 3,Β token 𝙲).

Layer 2, Head 1 (induction head).

The QK circuit of this head performs K-composition: it is sensitive to the layer-1 residual stream at source positions, which now encodes the previous token. The head at position 4 (token A) attends strongly to position 2 (token B), because position 2's residual stream contains a copy of position 1's token (A) from layer 1, matching the current token.

The OV circuit then moves position 2's representation (B) to position 4: Ξ”4(2,1)β‰ˆπ–OV(2,1)𝒙2(1).

Logit attribution.

By Theorem 3, the logit for predicting B next is dominated by β„“π™±β‰ˆπ–UΞ”4(2,1)β‹…π’†π™±βŸinductionΒ head+𝐖U𝒙4(0)β‹…π’†π™±βŸdirectΒ pathΒ (nearΒ zero). The induction head accounts for essentially all of the prediction boost for token B. By ablating head (2,1), we can verify this attribution experimentally: removing it causes the probability of B to collapse to near-uniform.

Exercises

Exercise 13.

Let dmodel=512 and dhead=64.

  1. Show that 𝐖QKh=𝐖QhβŠ€π–Kh has rank at most dhead=64.

  2. Express the singular value decomposition of 𝐖QKh in terms of the SVDs of 𝐖Qh and 𝐖Kh, and show that the singular values of 𝐖QKh are products of those of 𝐖Qh and 𝐖Kh.

  3. Given 𝐖Qh with smallest singular value Οƒmin⁑Q=0.1, 𝐖Kh with largest singular value Οƒmax⁑K=3.5, and input norms ‖𝒙iβ€–=‖𝒙jβ€–=1, bound the maximum magnitude of the attention score sijh before scaling by 1/dhead.

Exercise 14.

A copy head is an attention head whose OV circuit satisfies 𝐖OVhβ‰ˆπˆ.

  1. Show that a copy head with uniform attention over all n source positions writes 1nβˆ‘j𝒙j(β„“βˆ’1) to the residual stream at every destination. What is the relationship between this operation and mean pooling?

  2. If the QK circuit additionally implements a previous-token pattern (aijh=𝟏[j=iβˆ’1]), describe the resulting circuit in natural language.

  3. Suppose 𝐖OVh=𝐖UβŠ€π–U. Show that the head's update to the residual stream at destination i is equivalent to adding a weighted sum of unembedding vectors, and explain how this could directly promote certain vocabulary items.

Exercise 15.

Consider a 3-layer transformer with a single head per layer, and suppose you have measured the OV circuits 𝐖OV(1),𝐖OV(2),𝐖OV(3).

  1. Write the virtual OV weight corresponding to a chain of V-compositions through all three layers: the output of head 1 is read by head 2's value circuit, and the output of head 2 is read by head 3's value circuit.

  2. Show that this virtual weight is the product 𝐖O(3)𝐖V(3)𝐖O(2)𝐖V(2)𝐖O(1)𝐖V(1).

  3. If 𝐖OV(k) has spectral norm at most Οƒk for k=1,2,3, bound the spectral norm of the virtual weight and comment on when deep composition amplifies or attenuates the original information.

Multi-Head Attention Decomposition

Having established the mathematical framework of transformer circuits in The Mathematical Framework of Transformer Circuits, we now turn to a systematic decomposition of multi-head attention as an information-routing mechanism. The central question is: given that the residual stream is a linear superposition of head contributions, can we interpret each head's contribution to the model's predictions? The answer is yes, through a combination of logit attribution, the logit lens technique, and a careful analysis of direct versus indirect effects through the residual stream.

Attention as Weighted Information Routing

The attention mechanism can be understood as a content-addressable memory lookup. At each destination position i, the head broadcasts a query into the residual stream space and retrieves a weighted combination of values from source positions, where the weights are determined by query-key similarity.

More formally, using the circuit notation from The Mathematical Framework of Transformer Circuits, head h in layer β„“ implements the routing: (Formal)Ξ”i(β„“,h)=βˆ‘j=1nsoftmaxj⁑(𝒙iβŠ€π–QKh𝒙jdhead)𝐖OVh𝒙j, where we have abbreviated 𝒙j=𝒙j(β„“βˆ’1) for readability. The softmax softmaxj⁑(β‹…) over all source positions j produces a probability distribution 𝒂ih=(ai1h,…,ainh)βˆˆΞ”nβˆ’1 over source positions.

The routing metaphor.

Information at source position j is routed to destination i with weight aijh. The OV circuit determines what information is moved: only the component of 𝒙j in the row space of 𝐖OVh can be moved at all. The QK circuit determines where to route: it scores every (destination, source) pair and produces a soft assignment.

Softmax Attention Patterns and Their Interpretation

Attention weights 𝒂ihβˆˆΞ”nβˆ’1 are produced by softmax, which has several interpretability implications.

Sparsity and entropy.

The entropy of the attention distribution, (Entropy)H(𝒂ih)=βˆ’βˆ‘jaijhlog⁑aijh, measures how diffuse the head's attention is. Low entropy (near 0) indicates the head attends to a single source position-a hard lookup; high entropy (near log⁑n) indicates uniform attention over all positions-a soft average. Interpreting a head's function often begins with measuring this entropy: induction heads are sparse (they have found the right position to attend to), while positional heads may be diffuse (they average nearby positions).

Attention as a simplex-valued function.

The attention pattern Ahβˆˆβ„nΓ—n⁑ (with Aijh=aijh, rows summing to 1) is a stochastic matrix. Its left eigenvectors decompose the pattern into interpretable modes: the dominant left singular vector of Ahβˆ’1n𝟏𝟏⊀ (the attention pattern with uniform background subtracted) often corresponds to a clear structural pattern such as attending to punctuation, the previous token, the subject of the sentence, and so forth.

Direct versus Indirect Effects through the Residual Stream

When we ask β€œwhat is the effect of head h on the final logits?”, we must distinguish two types of contribution.

Definition 15 (Direct and Indirect Logit Attribution).

For head h in layer β„“, its direct logit attribution for token v at position i is (ATTR)DLAvh=𝐖UΞ”i(β„“,h)⋅𝒆v, the contribution of its output, unmediated, to the final logit. Its indirect logit attribution captures the effect of Ξ”i(β„“,h) on later heads' attention patterns and MLP computations, propagated through the residual stream to the final logit. The total effect is (ATTR)TLAvh=DLAvh+ILAvh, where ILAvh (indirect logit attribution) requires causal intervention (activation patching) to measure, since it involves the non-linear downstream processing of the head's output.

Remark 11.

Indirect logit attribution cannot be computed from the model weights alone; it requires activation patching experiments, where the head's output is replaced with its counterfactual value (e.g., from a different prompt) and the change in final logits is measured. For early layers, the indirect effect typically dominates; for the final layer, the direct effect is the only contribution. This is why logit lens (which only measures direct effects) is most interpretable for the final few layers.

The Logit Lens: Tracking Predictions Layer by Layer

The logit lens is a diagnostic technique introduced by Nostalgebraist that applies the unembedding matrix to intermediate residual stream states, revealing how the model's prediction evolves across layers. It exploits the decomposition from Theorem 3 to make the intermediate computation interpretable.

Definition 16 (Logit Lens).

For a transformer with L layers, the logit lens at layer β„“ for target token v and destination position i is (LENS)β„“^v(β„“)=𝐖U𝒙i(β„“)⋅𝒆v, the logit that would be assigned to token v if the residual stream at layer β„“ were directly unembedded. The corresponding probability is p^(β„“)(v)=softmax⁑(𝐖U𝒙i(β„“))v.

The logit lens allows us to observe the model β€œchanging its mind” across layers: an early layer might assign high probability to a syntactically plausible but semantically wrong continuation, which is corrected by later layers. This layer-by-layer evolution of predictions has been used to identify which layers perform which computational subtasks.

Relationship to the residual stream decomposition.

Note that (Decomp)β„“^v(β„“)βˆ’β„“^v(β„“βˆ’1)=𝐖U(βˆ‘h=1HΞ”i(β„“,h)+Ξ”i(β„“,MLP))⋅𝒆v, the change in logit contributed by layer β„“. This can be further decomposed head by head, giving a per-head, per-layer logit contribution chart.

Logit lens visualisation: applying the unembedding matrix 𝐖U to the residual stream at each layer reveals how the model's prediction evolves. At the embedding layer (layer 0), the correct answer β€œParis” has low probability; each subsequent layer increases it monotonically (in this stylised example). The logit lens makes the intermediate computations interpretable by projecting them onto vocabulary space, showing which tokens the model is β€œconsidering” at each depth.

Proposition: Additivity of Head Contributions in Logit Space

We now prove the key structural result justifying per-head attribution.

Proposition 3 (Attention Head Contributions are Additive in Logit Space).

Under the fold-LN approximation, the logit for vocabulary item v at position i decomposes as an exact sum over individual head contributions and MLP contributions: (Logit)β„“v=𝐖U𝒙i(0)⋅𝒆vβŸβ„“vemb+βˆ‘β„“=1Lβˆ‘h=1H(𝐖UΞ”i(β„“,h))⋅𝒆vβŸβ„“v(β„“,h)+βˆ‘β„“=1L(𝐖UΞ”i(β„“,MLP))⋅𝒆vβŸβ„“v(β„“,MLP). Each scalar term β„“v(β„“,h)βˆˆβ„β‘ is the direct logit attribution of head (β„“,h) to vocabulary item v. The terms sum to the total logit without any cross-terms or interaction corrections.

Proof.

The proof follows directly from the linearity of both the residual stream and the unembedding operation. Recall that the final residual stream is (RS)𝒙i(L)=𝒙i(0)+βˆ‘β„“=1Lβˆ‘h=1HΞ”i(β„“,h)+βˆ‘β„“=1LΞ”i(β„“,MLP). The logit β„“v=𝐖U𝒙i(L)⋅𝒆v is a linear functional of 𝒙i(L) (since 𝐖U is a linear map and the inner product with 𝒆v is linear). Applying this linear functional to both sides of (RS) gives β„“v=𝐖U𝒙i(0)⋅𝒆v+βˆ‘β„“,h𝐖UΞ”i(β„“,h)⋅𝒆v+βˆ‘β„“π–UΞ”i(β„“,MLP)⋅𝒆v. This is (Logit) with the identification β„“v(β„“,h)=𝐖UΞ”i(β„“,h)⋅𝒆v and β„“v(β„“,MLP)=𝐖UΞ”i(β„“,MLP)⋅𝒆v. Since the residual stream decomposition is exact (under the fold-LN approximation), the logit decomposition is exact with no interaction terms.

Key Idea.

Each attention head implements a simple, interpretable operation; complexity emerges from composition. A single attention head is characterised by only two low-rank matrices: the QK circuit (which positions attend to which) and the OV circuit (what information is moved). Because these are rank-dhead operators in a dmodel-dimensional space, each head has limited expressive power-it can only route a dhead-dimensional slice of information. Yet from the composition of many such simple operations across many layers (with MLP blocks enabling non-linear feature construction between routing steps), transformers can implement extraordinarily complex functions. The appropriate unit of analysis is not the weight matrix but the circuit: the graph of information flow through the residual stream.

MLP Blocks: The Role of Feedforward Networks

While attention heads route information between positions, MLP blocks process each token's representation independently (they are applied position-wise with no cross-token communication). A standard two-layer MLP sub-block computes (DEF)Ξ”i(β„“,MLP)=𝐖out(β„“)Οƒ(𝐖in(β„“)𝒙i(β„“)), where 𝐖in(β„“)βˆˆβ„dffΓ—dmodel⁑, 𝐖out(β„“)βˆˆβ„dmodelΓ—dff⁑, and Οƒ is an element-wise activation (GELU or ReLU in practice).

The non-linearity Οƒ is the key difference from attention heads: MLPs are not linear in the residual stream. However, the post-activation vector 𝒉=Οƒ(𝐖in(β„“)𝒙i(β„“))βˆˆβ„dff⁑ can be analysed neuron by neuron.

The β€œAttention Gathers, MLPs Compose” Hypothesis

Motivated by empirical findings in vision transformers and large language models, a key interpretability hypothesis has emerged:

Key Idea.

The β€œAttention Gathers, MLPs Compose” Hypothesis. Attention heads are the mechanism by which information is gathered across positions (routing relevant token representations to where they are needed), while MLP blocks are the mechanism by which gathered information is composed into higher-level features through non-linear computation. In video transformers and large language models, this division of labour is operationally separable: ablating attention heads destroys long-range context sensitivity, while ablating MLP blocks destroys feature construction and factual recall, but the two impairments are largely independent.

Empirical evidence for this hypothesis comes from several directions. In vision transformers (ViTs), attention heads in early layers perform local texture gathering, while MLP blocks in the same layers compute responses to features like edges and colour gradients. In large language models, factual knowledge is disproportionately stored in and recalled by MLP layers, while grammatical and positional relationships are implemented in attention layers.

Remark 12 (MLPs as Key-Value Memory Stores).

Geva et al. proposed viewing MLP blocks through the lens of key-value memory. Each neuron k in 𝐖in(β„“) defines a key pattern: the k-th row of 𝐖in(β„“) is a direction in residual stream space, and the neuron fires when the residual stream aligns with this direction. The corresponding column of 𝐖out(β„“) defines the value written to the residual stream when the neuron fires. Under this interpretation, (Memory)Ξ”i(β„“,MLP)=βˆ‘k=1dffΟƒ((𝐖in(β„“))k,⋅⋅𝒙i(β„“))β‹…(𝐖out(β„“))β‹…,k, which is a weighted sum of value vectors, where the weights are computed by matching the residual stream against key vectors. Experiments have shown that individual neurons in this decomposition correspond to specific facts: a neuron whose key fires on β€œthe capital of France” and whose value promotes the token β€œParis” in the unembedding space implements a single factual association. The MLP layer as a whole implements a soft retrieval over this distributed key-value store.

TikZ Figure: Attention versus MLP Division of Labour

The division of labour between attention heads and MLP blocks in a single transformer layer. Attention heads (blue, left) implement cross-position communication: they gather information from source positions j and route it to destination positions i, with routing weights determined by the QK circuit and the information moved determined by the OV circuit. MLP blocks (amber, right) implement position-wise feature composition: each token's representation is processed independently through a non-linear function that can be understood as a soft key-value memory lookup. Both blocks add to the residual stream (green), and their contributions are exactly additive in logit space (Proposition 3).

Exercises

Exercise 16.

Let p^(β„“) and p^(β„“βˆ’1) denote the probability distributions obtained by the logit lens at consecutive layers.

  1. Show that the KL divergence KL⁑(p^(β„“)β€–p^(β„“βˆ’1)) depends on the norms β€–Ξ”i(β„“,h)β€– and β€–Ξ”i(β„“,MLP)β€– and the alignment of these vectors with the unembedding directions. (Hint: use the first-order approximation p^v(β„“)β‰ˆp^v(β„“βˆ’1)+p^v(β„“βˆ’1)(β„“v(β„“)βˆ’β„“β€Ύ(β„“)) where β„“β€Ύ(β„“)=βˆ‘vp^v(β„“βˆ’1)β„“v(β„“).)

  2. If layer β„“ has H=8 heads each contributing an OV update of norm 0.1 and an MLP of norm 0.5 (all in the same direction in residual stream space), what is the maximum possible logit change |β„“v(β„“)βˆ’β„“v(β„“βˆ’1)| in terms of the unembedding norm β€–(𝐖U)v,β‹…β€–?

  3. Describe qualitatively what β€œmonotone logit lens” means (the correct token's probability increases monotonically across layers) and for which types of prompts you would expect to see this pattern versus a non-monotone pattern.

Exercise 17.

Consider a 2-layer transformer where layer 1 has one head, A, and layer 2 has one head, B.

  1. Write the total logit β„“v for position i as a sum of four terms: the direct path (embedding), head A's direct logit attribution, head B's direct logit attribution, and any cross-terms. Show that there are no cross-terms in the logit attribution, but that head B's output Ξ”i(2,B) depends on head A's output through the residual stream.

  2. Suppose you ablate head A (set Ξ”i(1,A)=𝟎) and observe that the logit β„“v decreases by Ξ΄. Decompose Ξ΄ into head A's direct logit attribution and head A's indirect logit attribution (mediated through head B). Which term requires a second forward pass to compute?

  3. If head A is a V-composition predecessor of head B (i.e., 𝐖OV(1,A) feeds into 𝐖OV(2,B) via the residual stream), show that the indirect effect of ablating head A on head B's output is βˆ’aijB𝐖OV(2,B)Ξ”j(1,A) summed over j.

Exercise 18.

This exercise explores the key-value memory interpretation of MLP blocks.

  1. For an MLP with dff=4dmodel neurons and a ReLU activation, show that the output can be written as a sum over at most dff value vectors, where each value vector is gated by a non-negative scalar. What does this imply about the cone structure of MLP outputs?

  2. Suppose neuron k has key π’Œk=𝐖Eπ’†π™΅πš›πšŠπš—πšŒπšŽ/‖𝐖Eπ’†π™΅πš›πšŠπš—πšŒπšŽβ€– and value 𝒗k=𝐖UβŠ€π’†π™ΏπšŠπš›πš’πšœ. Compute the contribution of this neuron to the logit for β€œParis” when the residual stream contains a scaled copy of the β€œFrance” embedding, and show that it increases the probability of predicting β€œParis”.

  3. A superposition hypothesis states that dff≫dmodel neurons can represent dff near-orthogonal features (keys) in a dmodel-dimensional space via approximate orthogonality. If key vectors are drawn uniformly from the unit sphere in ℝdmodel⁑ with dmodel=512 and dff=2048, compute the expected maximum inner product between any two keys and comment on the feasibility of this superposition.

Induction Heads and In-Context Learning

Among the most consequential discoveries of the mechanistic interpretability programme is the identification of a concrete, reusable computational motif called the induction head. Found independently in nearly every sufficiently large transformer trained on natural text, the induction head implements a form of pattern matching that appears to be the primary driver of in-context learning-the remarkable ability of large language models to adapt their behaviour from a few examples given in the input prompt, without any gradient update.

This section develops the mathematics of induction heads from the ground up. We begin with the simpler previous token heads that form in early layers of two-layer transformers, then show how a subsequent layer of attention heads exploits the key–value information produced by previous token heads to implement the [𝐀][𝐁]β‹―[𝐀]β†’[𝐁] completion pattern. We formalise the notion of K-composition by which two attention heads interact across layers, derive a mathematical characterisation of the attention pattern an induction head must implement, and place the discovery in its historical context as a major milestone on the path from black-box language modelling to circuit-level understanding.

Historical Note.

The transformer circuits thread. Mechanistic interpretability of transformers took a decisive turn in December 2021, when a team at Anthropic published a series of papers collectively called the Transformer Circuits Thread. The first instalment, β€œA Mathematical Framework for Transformer Circuits” (Elhage et al., 2021), introduced the residual-stream decomposition (sec:interp:residual-stream) and identified induction heads as a key primitive. The second major instalment, β€œIn-context Learning and Induction Heads” (Olsson et al., 2022), showed that induction heads are not merely a curiosity of toy models but appear universally in transformers trained on text, and that their emergence during training coincides precisely with the sudden jump in in-context learning ability that practitioners had observed but not understood. This discovery marked the first time a concrete mechanistic explanation was offered for a macroscopic capability of a large language model, and it catalysed an explosion of work on circuit finding, superposition, and feature-level analysis.

Previous Token Heads

In a two-layer transformer, the first layer of attention heads performs computations on the residual stream before the second layer sees it. Empirically, several heads in layer 1 consistently learn a simple but strategically important operation: they attend almost exclusively to the token immediately preceding the query token in the sequence. We call these previous token heads.

Let the input sequence be t1,t2,…,tT, where each ti is a token index. The residual stream at position i after the embedding and positional encoding is (Residual INIT)𝒙i(0)=𝐞ti+𝐩i, where 𝐞tiβˆˆβ„d⁑ is the token embedding and 𝐩iβˆˆβ„d⁑ is the positional embedding. A previous token head with weight matrices 𝐖Q,𝐖K,𝐖Vβˆˆβ„dΓ—dh⁑ computes attention scores (PREV ATTN Score)aij=𝒙i(0)βŠ€π–Q𝐖KβŠ€π’™j(0)dh,j≀i, with a causal mask preventing attention to future positions. The empirical observation is that the learned weight product 𝐖Q𝐖K⊀ is dominated by a component that computes similarity between the positional embedding of position i and the positional embedding of position j=iβˆ’1. More precisely, if 𝐩i is a sinusoidal or learned positional embedding, then the product 𝐩iβŠ€π–Q𝐖K⊀𝐩iβˆ’1 is large relative to any other (i,j) pair, producing an approximately one-hot attention pattern Aijβ‰ˆπŸ[j=iβˆ’1].

The output of the previous token head at position i is then (PREV Token Output)𝒛i=βˆ‘j=1iAij𝒙j(0)𝐖V𝐖Oβ‰ˆπ’™iβˆ’1(0)𝐖V𝐖O, where 𝐖Oβˆˆβ„dhΓ—d⁑ is the output projection. This is added to the residual stream, so after layer 1 position i contains information about both ti and tiβˆ’1: (Residual After L1)𝒙i(1)=𝒙i(0)+𝒛iβ‰ˆπžti+𝐩i+f(𝐞tiβˆ’1,𝐩iβˆ’1), where f denotes the linear map 𝐖V𝐖O. This β€œtoken + successor-context” representation in the residual stream is the key information that induction heads will exploit in layer 2.

Remark 13.

Previous token heads are not trained to be previous token heads by any explicit supervision signal. They emerge spontaneously during training because the previous-token pattern is a universally useful statistical regularisation: knowing what token preceded the current one is almost always helpful for prediction, and the sinusoidal positional encoding makes neighbouring positions geometrically similar in the key–query inner product space.

Induction Heads: the [A][B]...[A] β†’ [B] Pattern

An induction head is an attention head in layer 2 that implements a specific lookup procedure: when the current query position holds token A (which has appeared before in the sequence), the induction head attends back to the position after the previous occurrence of token A and copies the token B that followed it.

Definition 17 (Induction Head).

Let H be an attention head in layer β„“β‰₯2 of a transformer. H is called an induction head if, for any sequence containing a repeated token A at positions s<t (so ts=tt=A), the attention pattern of H satisfies (Induction ATTN)At,s+1≫At,jforΒ allΒ jβ‰ s+1, i.e., position t attends primarily to position s+1 (the token immediately following the previous occurrence of A). The resulting output causes the residual stream at position t to predict ts+1 (the token B that followed A previously).

The key question is: how does position t know to attend to position s+1 rather than s? The answer lies in K-composition with the previous token head (Previous Token Heads).

K-Composition Between Layers

Recall from sec:interp:residual-stream that the residual stream is a sum of contributions from all previous layers. The attention pattern of an induction head in layer 2 is determined by the inner product of query and key vectors, both of which are computed from the layer 2 residual stream 𝒙(1). Because 𝒙(1) contains the output of previous token heads, the induction head's key at position j encodes information about tjβˆ’1 (the token before j). Meanwhile, the query at position t encodes information about tt=A.

More precisely, the attention score of the induction head between query position t and key position j is (Induction Score)at,j=(𝒙t(1))βŠ€π–Q(2)(𝐖K(2))βŠ€π’™j(1)dh. The layer-2 residual stream decomposes as 𝒙j(1)=𝒙j(0)+𝒛j, where 𝒛jβ‰ˆf(𝐞tjβˆ’1) is the previous token head output. If the induction head's key weight matrix 𝐖K(2) is primarily sensitive to the β€œprevious token” component 𝒛j, then (K COMP Expand)(𝐖K(2))βŠ€π’™j(1)β‰ˆ(𝐖K(2))βŠ€π’›jβ‰ˆ(𝐖K(2))βŠ€π–V(1)𝐖O(1)𝐞tjβˆ’1. This is the virtual key contributed to position j by the token tjβˆ’1. The effective key–query inner product (K COMP Inner)at,j∝𝐞ttβŠ€π–Q(2)(𝐖K(2))βŠ€π–V(1)𝐖O(1)𝐞tjβˆ’1 is large when tjβˆ’1 is the same token as tt (i.e., when jβˆ’1=s, the previous occurrence of A), so j=s+1.

This is K-composition: the key of the layer-2 head is effectively composed with the value–output mapping of the layer-1 head, allowing the second layer to look up β€œwhich position follows the previous occurrence of the current token.”

Proposition 4 (Induction Head Attention Pattern).

Let 𝐖OV(1)=𝐖V(1)𝐖O(1) be the OV-circuit of the previous token head, and let 𝐖QK(2)=𝐖Q(2)(𝐖K(2))⊀ be the QK-circuit of the induction head. Define the composition matrix (COMP Matrix)𝐂=𝐖QK(2)𝐖OV(1)βˆˆβ„dΓ—d⁑. If π‚β‰ˆΞ»πˆ for some Ξ»>0 (i.e., the composition matrix is approximately a scaled identity), then the induction head attends to position s+1 with logit (Induction Logit)at,s+1β‰ˆΞ»β‹…β€–πžAβ€–2/dh, whereas all positions j with tjβˆ’1β‰ A receive logit approximately zero. Consequently, the softmax-normalised attention weight satisfies (Induction Softmax)At,s+1β†’1asΞ»β†’βˆž.

Sketch.

The logit at position j under the dominant K-composition term is 𝐞ttβŠ€π‚πžtjβˆ’1. If 𝐂=λ𝐈, this equals λ𝐞tt⊀𝐞tjβˆ’1, which is Ξ»β€–πžAβ€–2 when tjβˆ’1=tt=A (i.e., j=s+1) and λ⟨𝐞A,𝐞tjβˆ’1⟩ otherwise. For one-hot or nearly orthogonal embeddings, off-diagonal terms are near zero. Applying softmax yields the stated result.

Traced Example: A Concrete Induction Head Run

To build intuition, we trace the induction head on the classic nursery-rhyme continuation. Suppose the input sequence (tokenised) is:

The cat sat on the mat . The cat sat on the

which we index as positions 1,2,…,12. Token positions: The=1, cat=2, sat=3, on=4, the=5, mat=6, .=7. The subsequence repeats: positions 8–12 mirror positions 1–5 (incomplete repetition; the model must predict the continuation at position 13).

At position 12 (query token the, second occurrence), the induction head proceeds as follows:

  1. Query: The query vector at position 12 encodes token the (the same token type as position 5).

  2. Key scan: The keys at positions 1–12 contain, in their β€œprevious token” component, information about tokens 0,1,2,…,11 respectively (using a dummy token 0 at position 0). Position 6 has previous token the (position 5, token 5), so the K-composed key at position 6 encodes token the.

  3. Attention spike: Because the query encodes the and the K-composed key at position 6 also encodes the, the attention logit a12,6 is large. The softmax concentrates attention weight on position 6.

  4. Value read-out: Position 6 holds token mat (the token that followed the previous occurrence of the at position 5). The value–output circuit copies the representation of mat into the residual stream at position 12.

  5. Prediction: The model therefore strongly predicts mat as the next token-which is correct.

Induction head mechanism on the sequence β€œThe cat sat on the mat. The cat sat on the$_12$”. Orange boxes: previous token head representations in layer 1. Blue box: induction head in layer 2 concentrating attention on position 6 (the token after the previous the) via K-composition. Green: value read-out predicting mat.

Why Induction Heads Work on Random Tokens

A striking experimental finding from Olsson et al. (2022) is that induction heads operate equally well on random token sequences-sequences drawn uniformly at random with no semantic structure whatsoever. If the sequence is 7, 42, 13, 7, the induction head at the second 7 correctly predicts 42 (the token that followed the first 7).

This is not a trivial observation. It rules out the hypothesis that induction heads work by learning semantic associations (β€œthe word cat often follows the word the”). Instead, the mechanism is purely structural: it implements a sequence-level pattern-matching algorithm that can be described entirely in terms of token identities and relative positions.

Key Idea.

Pattern Matching, Not Semantics. An induction head implements the algorithm: β€œFind the most recent prior occurrence of the current token; output whatever followed it.” This algorithm is correct regardless of whether the tokens carry semantic meaning, making induction heads a form of in-context memorisation and replay rather than semantic generalisation. The implication for in-context learning is profound: a large language model can achieve few-shot performance not because it has learned a semantic rule from the examples, but because induction heads copy the pattern from the context window.

The random-token experiment also provides a quantitative diagnostic for induction head behaviour. Given a sequence of length 2T of the form (r1,r2,…,rT,r1,r2,…,rT) with ri drawn i.i.d. from a uniform distribution over the vocabulary, an ideal induction head achieves cross-entropy loss (Ideal LOSS)β„’ideal=βˆ’log⁑1V(onΒ theΒ firstΒ half,Β noΒ context) for the first repetition (T+1) and exactly zero loss for positions T+2,…,2T (since the pattern is perfectly predictable from context). In practice, models with strong induction heads achieve losses close to zero on the second half of such sequences, a metric called the induction-head loss used as a circuit-level benchmark.

The Phase Change: Sudden Emergence of In-Context Learning

Perhaps the most dramatic finding of the Olsson et al. (2022) study is the tight correspondence between the formation of induction heads during training and a sudden, non-linear improvement in in-context learning ability. The training curve of a large transformer on natural language exhibits a characteristic phase change:

  1. Early training (before phase change): The model learns basic unigram and bigram statistics; the loss decreases smoothly. In-context learning ability (measured, for example, by how much the model benefits from in-context examples) is approximately zero. On random-token sequences, the second-half loss is approximately equal to the first-half loss.

  2. The phase change: At a specific training step (which occurs earlier for larger models), the in-context loss drops sharply-over perhaps a factor-of-ten shorter window than the overall loss decrease. The model's ability to use in-context examples jumps discontinuously.

  3. After the phase change: Induction heads are firmly established. The second-half loss on random-token sequences approaches zero. In-context learning ability is mature and roughly invariant to further training.

The mechanistic explanation is as follows. Induction heads form via a two-stage process:

  1. In stage (a), previous token heads form in layer 1. This is a relatively gradual process.

  2. In stage (b), having discovered the β€œprevious token” information available in the residual stream, layer-2 heads rapidly reorganise to exploit K-composition. This is the sudden stage that produces the observed phase change.

The suddenness arises because K-composition is a multiplicative interaction: the gain from the induction-head algorithm scales as Ξ»2 (the square of the K-composition strength), so once the previous token head is sufficiently strong, the gradient advantage of the induction-head algorithm becomes self-reinforcing.

Remark 14.

The phase change in in-context learning is a macroscopic, empirically observable phenomenon in large language models, not merely an artefact of toy-model analysis. Olsson et al. (2022) documented it in models with up to billions of parameters, and showed that the transition is faster (in training steps) for larger models. This is consistent with the β€œemergent abilities” discourse in the LLM scaling literature, but with a concrete mechanistic account: the emergence is not mysterious, but driven by the formation of a specific computational motif.

Schematic training dynamics showing the phase change associated with induction head formation. Overall loss (grey) decreases smoothly. In-context learning ability (blue) is approximately zero before the phase change and jumps sharply as induction heads form. The random-token second-half loss (purple, dashed) drops precipitously at the same training step. The exact step at which the phase change occurs scales inversely with model size.

Exercises

Exercise 19.

Let the positional embedding be the sinusoidal encoding [𝐩i]2k=sin⁑(i/100002k/d), [𝐩i]2k+1=cos⁑(i/100002k/d).

  1. Show that 𝐩i⊀𝐩iβˆ’1β‰₯𝐩i⊀𝐩j for all jβ‰ iβˆ’1 in the case d=2 (single frequency), i.e. the inner product between adjacent positional vectors is maximised.

  2. Explain qualitatively why this property is not sufficient on its own to produce a previous token head: what additional learning must occur for the head to exclusively attend to the previous position?

  3. In a relative positional encoding scheme (e.g., RoPE), the attention score depends on the relative position iβˆ’j rather than absolute positions. How does this change the analysis? Would you expect previous token heads to form more or less readily?

Exercise 20.

The composition matrix 𝐂=𝐖QK(2)𝐖OV(1) from Proposition 4 measures the strength of K-composition.

  1. Define the Frobenius composition score ΞΊF=‖𝐂‖F/(‖𝐖QK(2)β€–F⋅‖𝐖OV(1)β€–F). Show that 0≀κF≀1 and that ΞΊF=1 iff 𝐖QK(2) and (𝐖OV(1))⊀ have rank 1 and are aligned.

  2. Elhage et al. (2021) proposed comparing ΞΊF for all pairs of heads as a heuristic for identifying composition in trained transformers. What are the limitations of this heuristic? (Hint: consider the case where both matrices are large but their product is small.)

  3. Propose an alternative composition metric based on the spectral norm ‖𝐂‖2 and discuss its computational cost compared to the Frobenius version.

Exercise 21.

Olsson et al. (2022) observed that the training step Tβˆ— at which the phase change occurs scales approximately as Tβˆ—βˆNβˆ’Ξ± for model size N with Ξ±>0.

  1. Suppose that induction heads form when the K-composition strength ΞΊ exceeds a threshold ΞΊβˆ—. If the gradient of the loss with respect to ΞΊ scales as βˆ‚β„’/βˆ‚ΞΊβˆNΞ² for some Ξ²>0, derive a rough scaling law for Tβˆ— in terms of N, Ξ±, and Ξ².

  2. In your model, what is the implied relationship between Ξ± and Ξ²? Is this consistent with the empirical finding that larger models form induction heads earlier?

  3. Discuss at least one important confounding factor that your simple gradient-flow model ignores (e.g., interaction with the MLP layers, learning rate schedules, or weight regularisation).

The IOI Circuit - Interpretability in the Wild

The study of induction heads established that mechanistic interpretability can uncover real computational structure in trained transformers. But induction heads are, in some sense, a simple case: they form in two-layer models, they implement a single well-defined algorithm, and their function can be characterised by a handful of matrix products. The natural next question is whether the circuit-finding programme can scale to more complex, naturalistic tasks in full-sized models.

The answer was provided by Wang et al. (2022) in a landmark paper on the Indirect Object Identification (IOI) task in GPT-2 Small. The IOI task requires determining the indirect object of a sentence such as:

β€œJohn and Mary went to the store. John gave a drink to”

The correct continuation is β€œMary” (the indirect object) rather than β€œJohn” (the subject, who is grammatically barred from being the recipient of an action performed by himself). Wang et al. identified a specific subgraph of 26 attention heads within GPT-2 Small-together with associated MLP inputs-that is causally sufficient to perform this task. This subgraph, which they called the IOI circuit, is the most complete mechanistic account of a real NLP capability in a full-scale language model to date.

Key Idea.

A Neural Network Implements an Algorithm. The IOI circuit demonstrates that a transformer trained on next-token prediction has implicitly learned to implement a multi-step symbolic algorithm: (1) identify repeated names in the context; (2) determine which name is the subject (and therefore should be suppressed); (3) copy the remaining name to the output. This algorithm emerges not from any explicit symbolic supervision but from the structure of the pretraining data alone. Mechanistic interpretability's claim is that every sufficiently capable language model implements some algorithm in this sense, and that finding these algorithms is both scientifically valuable and practically important for AI safety.

The IOI Task: Formal Description

Definition 18 (IOI Template).

An IOI sentence is a sentence of the form

[S] and [IO] [verb-phrase]. [S] [action-verb] a [object] to

where S is the subject name (a proper noun that appears twice) and IO is the indirect object name (a proper noun that appears once, after the conjunction and in the first clause). The target output is the token corresponding to IO. For example:

  • S= John, IO= Mary: β€œJohn and Mary went to the store. John gave a drink to Mary.”

  • S= Alice, IO= Bob: β€œAlice and Bob visited the park. Alice handed a note to Bob.”

The task is defined by a dataset of such sentences; performance is measured by the logit difference (Logit DIFF)Ξ”β„“=β„“IOβˆ’β„“S, where β„“IO and β„“S are the model's output logits for the indirect object and subject names respectively. A correct model satisfies Ξ”β„“>0.

GPT-2 Small (12 layers, 12 heads per layer, 768-dimensional residual stream) achieves Ξ”β„“β‰ˆ4.3 on the IOI dataset (Appendix A of Wang et al., 2022), indicating that it reliably performs the task.

Head Roles in the IOI Circuit

The 26 attention heads in the IOI circuit play distinct functional roles, determined by their effect on the logit difference Ξ”β„“. Wang et al. identified four main categories:

Name Mover Heads

Name Mover Heads (NMH) are the final functional component of the IOI circuit: they read the indirect object name from its position in the context and copy it to the final token position (the position at which the model must predict the next token). The three most important NMHs are located in layers 9 and 10 of GPT-2 Small (heads 9.9, 9.6, and 10.0 in layer.head notation).

Mechanistically, NMHs implement a form of V-composition with earlier heads: their value–output circuit copies the name token embedding from the indirect object's position to the output residual stream. The OV matrix of a NMH satisfies 𝐖VNMH𝐖ONMHβ‰ˆπcopy, where 𝐏copy projects the residual stream component corresponding to name tokens onto the logit space.

More precisely, if the residual stream at the IO position contains the representation 𝒓IO and the NMH attends to that position with weight Afinal,IOβ‰ˆ1, the contribution to the final-position logits is (NMH Contribution)Ξ”β„“=Afinal,IO𝒓IOβŠ€π–VNMH𝐖ONMH𝐖U, where 𝐖Uβˆˆβ„dΓ—V⁑ is the unembedding matrix. When 𝐖ONMH𝐖U is approximately a scaled copy operator on name-token logits, this directly boosts β„“IO relative to all other tokens.

S-Inhibition Heads

S-Inhibition Heads (SIH) serve the complementary role of suppressing the subject name S at the final token position. Without SIHs, the model would predict both S and IO with high probability (since both are plausible sentence completions in isolation), leading to errors on sentences where S appears more recently in context.

The SIHs (principally heads 8.6, 8.10, and 7.3) sit in layers 7–8, above the duplicate token heads that detect the subject's repeated occurrence. Their query vectors at the final position attend to earlier positions that contain subject-name tokens; their value circuit then suppresses the corresponding name logit by writing a negative contribution to the residual stream at the final position: (SIH Contribution)Ξ”β„“S=Afinal,S2𝒓S2βŠ€π–VSIH𝐖OSIH𝐖Uβ‰ˆβˆ’c⋅𝒆S, where S2 denotes the second (most recent) occurrence of the subject name, c>0 is a positive scalar, and 𝒆S is a unit vector selecting the S logit. This suppression mechanism is what allows the model to distinguish the correct indirect object from the subject.

Duplicate Token Heads

Duplicate Token Heads (DTH) detect the fact that a name appears twice in the sentence-a key signal that identifies it as the subject. The DTHs (heads 0.1, 3.0, and others in early layers) attend from the second occurrence of a name token back to the first occurrence of the same name. Their OV circuit writes a β€œduplicated” signal into the residual stream of the second occurrence.

Formally, the key–query interaction of a DTH satisfies 𝐖QDTH(𝐖KDTH)βŠ€β‰ˆπname, where 𝐏name is a projection onto the subspace encoding proper-noun identity. As a result, position S2 (second occurrence of subject S) attends strongly to position S1 (first occurrence), and not to the single occurrence of IO.

Previous Token Heads in the IOI Circuit

The IOI circuit also contains previous token heads analogous to those discussed in Previous Token Heads. Here they serve the specific purpose of propagating name information from the name-token position to the token following the name (e.g., from β€œJohn” to β€œand” or from β€œMary” to the verb phrase that follows). This enables later heads to attend to the name indirectly via its successor token, which is important for the sentence structures encountered in IOI templates.

Formal Definition of a Circuit

Definition 19 (Computational Circuit).

Let 𝒒=(𝒩,β„°) be the full computational graph of a transformer, where each node nβˆˆπ’© represents a computational unit (an attention head, an MLP sublayer, or a residual stream position), and each directed edge (u,v)βˆˆβ„° represents a data dependency (the output of node u flows into node v via the residual stream).

A circuit for a task 𝒯 is a subgraph π’ž=(𝒩C,β„°C) with 𝒩CβŠ†π’©, β„°CβŠ†β„° such that:

  1. Causal sufficiency: When all nodes in π’©βˆ–π’©C are replaced by their mean activations (i.e., ablated), the performance of the resulting model on 𝒯 is not significantly degraded compared to the full model.

  2. Causal necessity: Each node nβˆˆπ’©C is individually necessary: ablating n (while keeping all other nodes) causes a significant degradation in performance on 𝒯.

  3. Minimality: No strict subgraph of π’ž satisfies both (a) and (b).

Remark 15.

The notion of β€œsignificant degradation” in Definition 19 is task-specific and must be given a quantitative threshold. For the IOI task, Wang et al. (2022) used a threshold of 50% reduction in the logit difference Ξ”β„“ as the criterion for significance. The choice of threshold affects which heads are included in the circuit and is a source of sensitivity in the analysis.

Activation Patching: Verifying Causal Necessity

Demonstrating that a circuit is causally necessary-not merely correlated with the desired behaviour-requires an intervention methodology. The standard technique in the IOI paper (and the broader mechanistic interpretability literature) is activation patching (also called causal tracing or interchange intervention).

Definition 20 (Activation Patching).

Let 𝒙 be a clean input on which the model performs the task correctly, and let 𝒙′ be a corrupted input (e.g., the same sentence but with the names swapped: S↔IO) on which the model does not. For a node n with activation 𝐚n(𝒙) on the clean input and 𝐚n(𝒙′) on the corrupted input, define the patched model fn←𝒙(𝒙′) as the forward pass of the corrupted input where 𝐚n is replaced by 𝐚n(𝒙).

The causal effect of node n is (Causal Effect)CE(n)=Ξ”β„“(fn←𝒙(𝒙′))βˆ’Ξ”β„“(f(𝒙′)), where Ξ”β„“ is the logit difference ((Logit DIFF)). A large positive CE(n) indicates that node n carries causally relevant information for the task.

The activation patching procedure partitions the causal effect of a node into the portion attributable to the information it processes (rather than its architectural position), making it more interpretable than simple ablation.

In the IOI analysis, activation patching was applied systematically to every attention head in every layer of GPT-2 Small, producing a heat-map of causal effects across the 12Γ—12 = 144 heads. The heads with the largest effects are precisely the NMHs, SIHs, DTHs, and previous token heads identified in the circuit-providing strong evidence that these heads are causally, not merely correlationally, important.

Simplified schematic of the IOI circuit in GPT-2 Small. Dashed horizontal bars represent the residual stream at selected layers. Arrows show information flow through the four head classes. Duplicate Token Heads (orange) identify the repeated subject name in early layers. Previous Token Heads (blue) propagate name context. S-Inhibition Heads (purple) suppress the subject at layer 8. Name Mover Heads (green) copy the indirect object name to the output in layers 9–10, producing a logit advantage for IO over S (amber). The actual circuit contains 26 heads; here we show the most influential members of each class.

Step-by-Step Circuit Walkthrough

We now trace the IOI circuit on the sentence:

β€œJohn and Mary went to the store. John gave a drink to”

Let S= John (subject, appears at positions 1 and 9) and IO= Mary (indirect object, appears at position 3).

Step 1: Duplicate Token Heads detect the repeated name.

At position 9 (the second John), the DTHs attend strongly to position 1 (the first John), because both positions share the same name embedding. This writes a β€œduplicate” signal into the residual stream at position 9, flagging it as the second occurrence of a name.

Step 2: Previous Token Heads propagate context.

At positions 2 and 10 (the tokens immediately following each John), the previous token heads write information about John into the residual stream. Similarly, at position 4 (following Mary), the previous token head writes information about Mary. This propagation ensures that later heads have access to name identity from both the token itself and its successor.

Step 3: S-Inhibition Heads suppress the subject.

At the final query position (the token β€œto,” which precedes the predicted token), the SIHs in layers 7–8 scan backwards. Their attention weights are concentrated on position 9 (the second, most recent, occurrence of John), particularly because position 9 carries the β€œduplicate” signal from Step 1. The SIHs' OV circuit writes a negative signal to the residual stream that reduces the logit of the token John.

Step 4: Name Mover Heads copy the indirect object.

At the final position, the NMHs in layers 9–10 attend to position 3 (Mary). Their attention is guided by the absence of a duplicate signal at position 3: Mary appears only once, so the NMHs' QK circuit selects it over the (now-suppressed) John. The OV circuit of the NMHs copies the Mary embedding into the final residual stream.

Step 5: Unembedding.

The final residual stream, boosted toward Mary by the NMHs and away from John by the SIHs, is projected through the unembedding matrix 𝐖U. The result is β„“Mary>β„“John, i.e., the model correctly predicts Mary as the continuation.

Example 4.

On the sentence β€œAlice and Bob visited the park. Alice handed a note to”, GPT-2 Small produces (approximately): β„“Bobβ‰ˆ12.4,β„“Aliceβ‰ˆ8.1,Ξ”β„“=12.4βˆ’8.1=4.3. Ablating the three NMHs (replacing their outputs with their mean activations) reduces Ξ”β„“ to approximately 1.7-a reduction of 60%, confirming that NMHs are causally important. Ablating the three SIHs reduces Ξ”β„“ to approximately 2.0 (a 53% reduction), confirming the importance of suppression. Ablating both simultaneously reduces Ξ”β„“ below zero, causing the model to incorrectly predict Alice.

Warnings and Limitations

Caution.

Circuits found in toy or constrained models may not generalise. The IOI circuit was identified in GPT-2 Small (117M parameters) under a specific set of template sentences. Several caveats apply:

  1. Template sensitivity: The IOI dataset uses stylised sentences with a fixed grammatical template. The circuit's structure may change for more varied sentence forms (e.g., sentences with more than two names, or indirect objects expressed via pronouns).

  2. Model size: Larger models may implement the same function with different circuits-or distribute the computation across more heads, making the circuit larger and harder to isolate. There is no guarantee that GPT-2 Small's IOI circuit appears in GPT-4 or Claude.

  3. Polysemanticity: The same attention head may contribute to multiple circuits simultaneously (The Superposition Hypothesis). Ablating a head to test necessity in one circuit may inadvertently affect its role in other circuits, contaminating the causal analysis.

  4. Mean ablation as a baseline: Replacing a node's activation with its mean over the dataset is a methodological choice; other ablation baselines (zero ablation, noise injection, random activation from the dataset) give different results.

  5. Faith\-fulness vs. completeness: Wang et al. (2022) demonstrated that the IOI circuit is faithful (its behaviour on IOI sentences matches the full model's) but did not claim it is the unique circuit implementing the task. Other subgraphs might implement the same function.

Despite these caveats, the IOI circuit remains the most thoroughly validated mechanistic account of a realistic NLP behaviour, and its methodology has become the template for subsequent circuit analyses.

Broader Implications for Interpretability Research

The IOI circuit contributes several lasting methodological lessons to the interpretability programme:

Functional decomposition is possible at scale.

Despite GPT-2 Small's 144 attention heads and 12 MLP sublayers, a mere 26 heads are causally sufficient for the IOI task. This suggests that transformers do not distribute all computations diffusely across all components, but concentrate specific functions in identifiable subsets.

Algorithm identification bridges symbolic and neural views.

The four-step algorithm identified in Step-by-Step Circuit Walkthrough (detect duplicate, propagate context, suppress subject, copy object) is a symbolic description of a computation performed by continuous, high-dimensional neural network activations. This bridging of levels is precisely what mechanistic interpretability aspires to achieve for all model behaviours.

Causal methodology is essential.

The combination of activation patching, attention visualisation, and ablation provides converging evidence that is more compelling than any single method alone. Correlation-based analyses (attention visualisation without patching) would have identified the same heads as β€œinteresting,” but could not establish causal necessity. The IOI paper's causal methodology is now standard in circuit-finding work.

Safety relevance.

The IOI task is innocuous, but the methodology it validated is directly applicable to safety-relevant behaviours: deception, refusal, sycophancy, hallucination. If a model's tendency to produce false confident statements is implemented by a specific circuit, that circuit can potentially be identified, patched, or monitored. This is one of the primary motivations for the broader mechanistic interpretability programme.

Insight.

The IOI circuit demonstrates that the question β€œwhat algorithm does this model implement?” is not merely philosophical but empirically tractable. The difficulty scales with the complexity of the behaviour; finding the β€œtruthfulness circuit” or the β€œdeception circuit” in a frontier model is vastly harder than the IOI case. But the IOI result establishes that the question is answerable in principle, and provides the methodological toolkit to pursue it.

Exercises

Exercise 22.

Consider a simplified version of the IOI task in which only a single Name Mover Head (NMH) and a single S-Inhibition Head (SIH) are active, and their contributions to the final logit difference are additive: Ξ”β„“=Ξ±NMH+Ξ±SIH, where Ξ±NMH>0 and Ξ±SIH>0.

  1. Under mean ablation of the NMH (i.e., setting Ξ±NMH=0), the logit difference drops to Ξ±SIH. Under mean ablation of the SIH (setting Ξ±SIH=0), it drops to Ξ±NMH. If the total logit difference is Ξ”β„“=4.0 and ablating the NMH gives Ξ”β„“β€²=1.5, estimate Ξ±NMH and Ξ±SIH.

  2. Suppose the NMH and SIH interact: the SIH's contribution depends on how strongly the NMH fires. Propose a modified model Ξ”β„“=Ξ±NMH+Ξ±SIH+Ξ²Ξ±NMHΞ±SIH and derive the individual causal effects under mean ablation. What sign would you expect Ξ² to have, and why?

  3. When does the additive model systematically overestimate the causal importance of the NMH? Provide a concrete example using the interactive model from (b).

Exercise 23.

The minimality condition in Definition 19 requires that every node in the circuit is individually necessary.

  1. Show that the following graph is not minimal as a circuit for a binary task: nodes A and B both contribute +1 to the output logit, the threshold for success is +1, and each node individually reaches the threshold. Propose the minimal circuit.

  2. In practice, β€œindividually necessary” is tested by a threshold on performance degradation (e.g., >50% reduction in Ξ”β„“). Construct a counterexample in which two heads are each individually below the threshold (e.g., ablating either causes only 30% degradation) but together they are necessary (ablating both causes 80% degradation). What does this suggest about the adequacy of the standard minimality test?

  3. Propose a revised definition of minimality that handles the counterexample from (b). Your definition should be computationally tractable (not requiring exponential enumeration of all subsets).

Exercise 24.

Wang et al. (2022) studied GPT-2 Small. This exercise asks you to think about how their findings might or might not generalise.

  1. Suppose we train a transformer with twice the number of attention heads per layer (24 instead of 12) on the same data. Give two distinct hypotheses for how the IOI circuit might change: (H1) the same circuit is distributed over more heads (β€œredundancy hypothesis”); (H2) a qualitatively different circuit implements the same function more efficiently. For each hypothesis, describe an experiment that would distinguish it from the other.

  2. The IOI task uses proper names (e.g., John, Mary). Propose an analogous task that uses common nouns instead (e.g., cat, dog) and describe which components of the IOI circuit you would expect to generalise directly and which you would expect to differ. Justify your prediction based on the mechanistic descriptions in Head Roles in the IOI Circuit.

  3. A critic argues that the IOI circuit is an artefact of the specific IOI dataset used and that GPT-2 Small's IOI performance is driven by memorisation of training sentences rather than a generalisable algorithm. Design an experiment to test this hypothesis rigorously. What would you measure, and what outcome would confirm or refute the critic?

The Superposition Hypothesis

One of the most striking findings in mechanistic interpretability is also one of the most counterintuitive: individual neurons are not individual concepts. Open a dictionary and each entry denotes exactly one word. Look up a neuron in a transformer and you will find it responds to dozens of unrelated stimuli - currency symbols, geographical locations, names of chemical elements, expressions of negation. This is not a flaw in how we measure neurons; it reflects something deep about how neural networks choose to organise information internally.

The superposition hypothesis, developed at Anthropic in a landmark series of papers on toy models of superposition, proposes a precise explanation: neural networks store more features than they have neurons by packing those features into nearly orthogonal directions in activation space. The inevitable price is interference - features β€œbleed” into one another whenever two features that share a neuron happen to be active simultaneously - but if features are sparse (rarely co-active), the expected interference is small and the gain in representational capacity is large.

This section develops the mathematics of superposition rigorously. We begin with the formal definition (Formal Definition of Superposition), then study a toy model that makes the phenomenon concrete and analytically tractable (The Toy Model of Superposition). We connect the geometry to the celebrated Johnson–Lindenstrauss lemma (The Johnson–Lindenstrauss Lemma and Superposition Capacity), derive the phase diagram governing when a network chooses to superpose a feature (Phase Transitions in Superposition), and close with a striking biological analogy: sparse coding in the mammalian visual cortex (Biological Connection: Sparse Coding in Visual Cortex).

Historical Note.

From grandmother cells to distributed codes. The debate between localist and distributed representations in neural systems has raged for decades. Localist theories, epitomised by the apocryphal β€œgrandmother cell” hypothesis of Konorski (1967), hold that single neurons encode single concepts. Barlow's β€œfeature detector” neuroscience (1972) provided partial support: certain retinal ganglion cells clearly signal oriented edges. But Hinton, McClelland, and Rumelhart (1986) argued forcefully for distributed representations in their parallel distributed processing volumes. In machine learning, the linear representation hypothesis - that neural networks encode features as directions in activation space - emerged from early work on word embeddings (Mikolov et al., 2013) and was formalised by the concept of residual stream in transformer mechanistic interpretability (Elhage et al., 2021). The superposition hypothesis is the natural culmination: if features are directions, and if there are more concepts to represent than dimensions available, superposition is not merely possible but necessary.

Why Neurons Are Polysemantic

Consider a language model processing a sentence about Paris. The model must track, among other things, the grammatical role of β€œParis”, its semantic category (proper noun, city, capital), its cultural associations (Eiffel Tower, haute cuisine, fashion week), and its position in the discourse. In a network with d neurons in a hidden layer, the model must represent all of these features - and thousands more - using vectors in ℝd⁑.

The naive solution is monosemanticity: assign one neuron to each feature. This is clean, interpretable, and utterly impractical. Modern language models process tokens drawn from vocabularies of tens of thousands, appearing in contexts that invoke hundreds of thousands of distinct semantic properties. No realistic hidden dimension d can accommodate a dedicated neuron per feature.

Key Idea.

Neural networks represent more concepts than they have neurons - this is both powerful and problematic. Powerful because it grants exponential representational capacity in the number of features for the cost of a linear number of neurons; problematic because it makes individual neurons uninterpretable and renders activation patching unreliable.

The fundamental tension is between two desiderata. First, the network wants representational capacity: the ability to track many features simultaneously. Second, it wants interpretability: a clean mapping between neurons and concepts. Superposition is the network's resolution to this tension, sacrificing interpretability for capacity.

To see why this trade-off arises naturally from gradient descent, recall that a neural network's loss function cares only about predictions, not about the interpretability of intermediate representations. If packing two features into one neuron reduces loss (because both features are useful but rarely co-active), gradient descent will discover this packing automatically. There is no mechanism imposing monosemanticity.

Formal Definition of Superposition

We formalise the notion of superposition in terms of the linear representation hypothesis.

Definition 21 (Feature and Feature Direction).

A feature fi is a binary or real-valued property of an input that is causally relevant to the model's output. Under the linear representation hypothesis, each feature fi is represented as a direction 𝒗iβˆˆβ„d⁑ in the activation space of a layer with hidden dimension d, such that the activation vector π’™βˆˆβ„d⁑ can be written as (Linear REPR)𝒙=βˆ‘i=1nfi𝒗i+𝜺, where n is the number of features, fiβˆˆβ„β‘ is the feature activation, and 𝜺 is noise.

Definition 22 (Superposition).

A layer with hidden dimension d is said to exhibit superposition when the number of represented features n exceeds the layer dimension d (i.e., n>d), and the feature directions 𝒗1,…,𝒗nβˆˆβ„d⁑ form a set of nearly orthogonal unit vectors satisfying (Superp EPS ORTH)|βŸ¨π’—i,𝒗j⟩|β‰€Ο΅βˆ€iβ‰ j, for some small Ο΅>0. The feature directions {𝒗i} form a superposition dictionary.

Remark 16 (Near-orthogonality vs. exact orthogonality).

Exact orthogonality of n>d vectors in ℝd⁑ is impossible by elementary linear algebra: any set of more than d vectors in ℝd⁑ must be linearly dependent. The key insight of the superposition hypothesis is that near-orthogonality is achievable for n≫d, and near-orthogonality is sufficient for low interference when features are sparse.

The Toy Model of Superposition

To make the superposition hypothesis analytically tractable, Elhage et al. (2022) introduced an elegant toy model: a one-hidden-layer autoencoder that attempts to reconstruct n features using only d<n dimensions.

Model architecture.

Let πŸβˆˆβ„n⁑ be a sparse feature vector, where each component fi is nonzero with probability pi (the feature's β€œsparsity”) and, when active, takes value drawn from some distribution (for simplicity, fi∈{0,1} with Pr⁑[fi=1]=pi). The model maps 𝐟 through a linear bottleneck: (TOY Encode)𝒙=W𝐟+𝐛,𝐟^=ReLU(WβŠ€π’™+𝐛′), where Wβˆˆβ„dΓ—n⁑ is the weight matrix (the superposition dictionary), and the ReLU nonlinearity enforces non-negativity of the reconstructed features. The training objective is a weighted mean-squared error: (TOY LOSS)β„’(W)=π”ΌπŸ[βˆ‘i=1nSi(fiβˆ’f^i)2], where Si>0 is the importance of feature i (proportional to how much the model cares about reconstructing it accurately).

What does the model learn?

Two extreme solutions exist. In the monosemantic solution, the model sets d=n (impossible here since d<n) or selects the d most important features and represents each in a dedicated dimension, ignoring the rest. In the superposition solution, the model represents all n features using n nearly-orthogonal directions in ℝd⁑, accepting small reconstruction errors whenever two features are simultaneously active.

The expected reconstruction error for feature i under superposition is: (TOY Interference)𝔼[(fiβˆ’f^i)2]β‰ˆβˆ‘jβ‰ ipjβŸ¨π’—i,𝒗j⟩2, where the right-hand side accumulates squared inner products weighted by the co-activation probability pj. When features are sparse (pjβ‰ͺ1 for all j), this error is small even if the 𝒗j are only approximately orthogonal.

Superposition packs more features than dimensions. Left: in a monosemantic regime, each feature occupies one dedicated dimension (n=d); interpretability is perfect but capacity is limited. Center: in superposition, five feature directions 𝒗i (coloured arrows) are packed into a two-dimensional hidden space as the vertices of a regular pentagon - nearly orthogonal but not exactly so. Right: when two features are simultaneously active, their representations interfere; the expected interference magnitude is proportional to the co-activation probability, so sparse features pay a low penalty.
Optimal geometry.

A natural question is: what arrangement of n unit vectors in ℝd⁑ minimises the total squared interference βˆ‘iβ‰ jβŸ¨π’—i,𝒗j⟩2? This is the Tammes problem (also called the Grassmannian packing problem). For n=d+1, the optimal solution is the regular simplex: vertices of the regular (d+1)-simplex inscribed in the unit sphere Sdβˆ’1. For larger n, the optimal packings are known for special cases (e.g., n=2d gives the cross-polytope) but are generally NP-hard to compute.

The toy model trained by gradient descent nonetheless discovers near-optimal solutions, suggesting that the loss landscape has favourable geometry for superposition.

The Johnson–Lindenstrauss Lemma and Superposition Capacity

How many features can a d-dimensional space accommodate in superposition? The answer is surprisingly large, and its theoretical foundation is the celebrated Johnson–Lindenstrauss (JL) lemma.

Proposition 5 (Near-Orthogonal Vectors in ℝd⁑).

For any 0<Ο΅<1, there exists a set of (NEAR ORTH Bound)n(Ο΅,d)β‰₯exp⁑(Ξ©(Ο΅2d)) unit vectors in ℝd⁑ such that |βŸ¨π’—i,𝒗j⟩|≀ϡ for all iβ‰ j.

Proof sketch.

The argument follows from a probabilistic construction. Draw n independent random unit vectors 𝒗1,…,𝒗n uniformly from the unit sphere Sdβˆ’1. For any fixed pair (i,j) with iβ‰ j, the inner product βŸ¨π’—i,𝒗j⟩ is a sub-Gaussian random variable with mean zero and variance 1/d (by symmetry of the uniform distribution on Sdβˆ’1).

By the Hoeffding-type concentration inequality for the sphere: (JL Concentration)Pr⁑[|βŸ¨π’—i,𝒗j⟩|>Ο΅]≀2exp⁑(βˆ’12Ο΅2d). By a union bound over all (n2) pairs, the probability that any pair violates the Ο΅-orthogonality condition is at most (JL Union)(n2)β‹…2exp⁑(βˆ’12Ο΅2d)≀n2exp⁑(βˆ’12Ο΅2d). This probability is less than 1 (i.e., a valid Ο΅-orthogonal set exists with positive probability) as long as n2<exp⁑(12Ο΅2d), i.e., n<exp⁑(14Ο΅2d). Since the construction is existential, the bound follows.

Remark 17 (Exponential capacity).

Proposition Proposition 5 implies that a d-dimensional hidden layer can in principle represent exp⁑(Ξ©(Ο΅2d)) features in Ο΅-superposition. The explicit union bound above carries the constant 14: for d=512 and Ο΅=0.3 it already guarantees more than exp⁑(14Ο΅2d)=exp⁑(14β‹…0.09β‹…512)=e11.5β‰ˆ105 near-orthogonal directions, vastly more than the d=512 strictly orthogonal directions that fit exactly. At the looser tolerance Ο΅=0.1 the same explicit bound gives only exp⁑(14β‹…0.01β‹…512)=e1.28β‰ˆ3.6: the 14 from this crude union bound is far from tight. The practically relevant regime is moderate Ο΅ (say 0.05–0.3) and large d, where the exponential capacity vastly exceeds d.

The JL lemma (in its original form) states that any set of m points in ℝn⁑ can be embedded into ℝd⁑ (with d=O(Ο΅βˆ’2log⁑m)) while preserving all pairwise distances to within a factor of (1Β±Ο΅). The connection to superposition is direct: if we regard features as points on the unit sphere, a random projection into d dimensions (the β€œcompression” step) preserves their near- orthogonality, exactly the geometric property that makes superposition work.

Theorem 4 (Johnson–Lindenstrauss Lemma).

Let ϡ∈(0,1/2) and let X={𝒙1,…,𝒙m}βŠ‚β„n⁑ be any m-point set. Set d=⌈24Ο΅βˆ’2log⁑mβŒ‰. Then there exists a linear map Ξ¦:ℝn⁑→ℝd⁑ such that for all i,j: (JL Lemma)(1βˆ’Ο΅)‖𝒙iβˆ’π’™jβ€–2≀‖Φ(𝒙i)βˆ’Ξ¦(𝒙j)β€–2≀(1+Ο΅)‖𝒙iβˆ’π’™jβ€–2. Moreover, a random Gaussian matrix Ξ¦ijβˆΌπ’©(0,1/d) satisfies this with probability at least 1βˆ’1/m.

The implication for neural networks is profound: the weight matrix W of a linear layer can act as a random projection, preserving the approximate geometry of the feature space even when the bottleneck dimension dβ‰ͺn. Superposition is, in a sense, the neural network's implicit implementation of the Johnson–Lindenstrauss construction.

Phase Transitions in Superposition

The toy model of The Toy Model of Superposition reveals a sharp phase transition: depending on the importance Si and sparsity pi of a feature, the model either represents it cleanly (monosemantically) or superimposes it with other features, or ignores it entirely.

Three phases.

Consider a model with d=1 (one-dimensional hidden space) and n=2 features with importances S1β‰₯S2 and sparsities p1,p2. The model must choose how to allocate its single dimension. The optimal solution depends on the trade-off between:

  1. Monosemantic: represent only feature 1, giving loss S2𝔼[f22]=S2p2.

  2. Superposition: represent both features as 𝒗1=1,𝒗2=βˆ’1 (antipodal), giving interference loss (S1+S2)p1p2 (the antipodal cross terms cost error only when both features co-activate, probability β‰ˆp1p2).

  3. Ignore both: loss S1p1+S2p2.

Superposition is preferred when the interference loss is lower than the monosemantic loss: (Phase COND)(S1+S2)p1p2<S2p2⟺p1<S2S1+S2. This condition is satisfied precisely when feature 1 is sparse (p1<S2/(S1+S2)), so that the interference it causes is rare enough that sharing the dimension still beats paying S2p2 to ignore feature 2.

General phase diagram.

In the general setting with n features, the phase diagram lives in the space of (Si,pi) pairs. Three regimes emerge:

  • Clean representation (high importance, high density): the model allocates a dedicated dimension, achieving exact reconstruction.

  • Superposition (moderate importance, low density): the model packs multiple features into shared directions, accepting small interference.

  • Dropped feature (low importance): the model ignores the feature entirely, setting 𝒗iβ‰ˆ0.

Remark 18 (Practical implications).

The phase diagram predicts that rare, important features are most likely to be in superposition: they are important enough to include but sparse enough that interference is manageable. This matches empirical findings: in practice, features corresponding to rare tokens, unusual syntactic constructions, or domain-specific terminology tend to be polysemantically encoded, while high-frequency features (e.g., the β€œis this a space character?” detector) often achieve near-monosemantic representations.

Biological Connection: Sparse Coding in Visual Cortex

The superposition hypothesis does not arise in a vacuum: it has a remarkable parallel in neuroscience. In 1996, Bruno Olshausen and David Field published a seminal paper showing that the receptive fields of simple cells in the primary visual cortex (V1) can be derived from a sparse coding principle applied to natural images.

The Olshausen–Field model.

Given a patch πˆβˆˆβ„m⁑ of a natural image, Olshausen and Field proposed learning a dictionary Aβˆˆβ„mΓ—n⁑ (with n>m, an overcomplete dictionary) and a sparse code π¬βˆˆβ„n⁑ such that πˆβ‰ˆA𝐬 with 𝐬 sparse. The learning objective is: (Olshausen Field)minA,π¬β‘β€–πˆβˆ’A𝐬‖2+Ξ»βˆ‘ilog⁑(1+si2/Οƒ2), where the second term encourages sparsity in the code. When trained on natural image patches, the columns of A spontaneously develop into oriented, localised, bandpass filters - precisely the Gabor-like receptive fields observed in V1 neurons.

The connection to superposition.

The parallel is striking:

  • The dictionary A plays the role of the superposition dictionary W, with overcomplete columns (n>m) analogous to n>d.

  • The sparse code 𝐬 plays the role of the feature activations 𝐟, with sparsity enabling efficient representation.

  • The Gabor-like columns of A correspond to monosemantic feature directions: each column encodes a single oriented edge at a specific spatial frequency.

The brain appears to have independently discovered the same solution to the representational bottleneck that gradient descent finds in artificial neural networks: pack more features than dimensions by exploiting sparsity.

Remark 19 (Differences from the neural network case).

There are important differences. The visual cortex operates in an approximately monosemantic regime at the level of V1 simple cells: each cell responds to a specific orientation, spatial frequency, and position. The superposition-like behaviour in artificial networks is more extreme: the same neuron may respond to linguistically unrelated concepts. One reason is that V1 has far more neurons than necessary to represent the relevant features of natural images (the cortex is massively over-resourced at this stage), while artificial models are typically under-resourced relative to the number of semantic features in language.

Exercises

Exercise 25.

Interference bound. Consider n unit vectors 𝒗1,…,𝒗nβˆˆβ„d⁑ arranged as the vertices of a regular (nβˆ’1)-simplex inscribed in the unit sphere Sdβˆ’1 (assuming n≀d+1). Show that for this configuration, βŸ¨π’—i,𝒗j⟩=βˆ’1/(nβˆ’1) for all iβ‰ j. Then compute the total squared interference βˆ‘iβ‰ jβŸ¨π’—i,𝒗j⟩2 and show that it equals n(nβˆ’1)/(nβˆ’1)2=n/(nβˆ’1). Conclude that the simplex achieves the minimum total squared interference among all unit-norm configurations (you may cite the Welch bound without proof).

Exercise 26.

Sparsity and phase transitions. Extend the two-feature phase analysis of Phase Transitions in Superposition to three features with equal importances S1=S2=S3=1 and equal sparsities p1=p2=p3=p, in a hidden space of dimension d=2. Consider the three candidate solutions: (a) monosemantic: represent the two most-important features in orthogonal dimensions, drop the third; (b) superposition with a regular triangle: represent all three features as the vertices of an equilateral triangle inscribed in the unit circle; (c) superposition with a square: represent two features orthogonally and pack the third as (1/2,1/2)⊀. Compute the expected loss for each solution as a function of p and determine which solution is optimal for p∈{0.01,0.1,0.5}.

Exercise 27.

JL capacity scaling. Let Ο΅=0.1 and consider the bound from Proposition Proposition 5. (a) Compute the maximum number of 0.1-nearly-orthogonal unit vectors in ℝd⁑ for d∈{10,50,100,512,1024} using the exponential bound . (b) A transformer model with hidden dimension d=512 is claimed to represent n=50,000 semantic features in superposition. What is the implied average squared inner product 𝔼iβ‰ j[βŸ¨π’—i,𝒗j⟩2] if the features are arranged as uniformly random unit vectors? Is this consistent with low interference when feature sparsity is p=0.001? (c) How does the capacity scale if we allow Ο΅=0.2 instead of Ο΅=0.1? What practical trade-off does this represent?

Sparse Autoencoders for Feature Discovery

If the superposition hypothesis is correct, then the fundamental challenge of mechanistic interpretability is not merely to find what neurons do, but to disentangle the superimposed features from the directions in which they are packed. The neuron basis is the wrong basis; we need to find the feature basis.

This insight motivates a deceptively simple idea: train a sparse autoencoder (SAE) on the model's activations. The autoencoder is forced to reconstruct the activations using a small number of active dictionary elements at each forward pass. If the training is successful, those dictionary elements will correspond to the monosemantic features that the network has superimposed - the SAE effectively inverts the superposition and recovers the feature basis.

The field of SAE-based interpretability has exploded since Cunningham et al. (2023) and the Anthropic team (Templeton et al., 2024) demonstrated that SAEs trained on transformer activations discover human-interpretable monosemantic features at scale. This section develops the theoretical foundations, practical training considerations, and empirical findings of this methodology.

Historical Note.

From dictionary learning to mechanistic interpretability. Sparse autoencoders as a machine learning technique predate their use in interpretability by decades. The connection to sparse coding (Olshausen and Field, 1996) is direct: an SAE is essentially a learned overcomplete dictionary, trained by gradient descent rather than by pursuit algorithms. In signal processing, sparse representations and basis pursuit (Chen, Donoho, and Saunders, 1998) provided a rigorous foundation for recovering sparse signals from compressed measurements. The application to neural network interpretability was first proposed by Cunningham et al. (2023), who demonstrated that SAEs trained on one-layer transformers recover interpretable features. Templeton et al. (2024) scaled this to Claude 3 Sonnet, discovering over a million interpretable features including multimodal concepts spanning language, emotion, and abstract reasoning.

SAE Architecture

A sparse autoencoder is a two-layer neural network with an expansion factor: the hidden dimension m is much larger than the input dimension d (i.e., m≫d). The key constraint is that the hidden representation must be sparse: only a small fraction of the m hidden units are active for any given input.

Definition 23 (Sparse Autoencoder for Mechanistic Interpretability).

A sparse autoencoder (SAE) for mechanistic interpretability is a pair of functions (β„°,π’Ÿ) where: (SAE Encoder)𝐑=β„°(𝒙)=ReLU(Wenc(π’™βˆ’π›pre)+𝐛enc),𝒙^=π’Ÿ(𝐑)=Wdec𝐑+𝐛pre, where π’™βˆˆβ„d⁑ is an activation vector from the target layer, Wencβˆˆβ„mΓ—d⁑ is the encoder weight matrix, Wdecβˆˆβ„dΓ—m⁑ is the decoder weight matrix (with unit-norm columns: β€–(Wdec):jβ€–=1 for all j), 𝐛preβˆˆβ„d⁑ is a pre-encoder bias applied before encoding and re-added after decoding, 𝐛encβˆˆβ„m⁑ is the encoder bias, and π‘βˆˆβ„β‰₯0m⁑ is the sparse feature activation vector.

Remark 20 (Role of the pre-encoder bias).

The pre-encoder bias 𝐛pre centres the input distribution before encoding. Without it, the ReLU nonlinearity would impose an asymmetric constraint on the features: features would only be able to represent positive deviations from zero rather than deviations from the mean. Centering allows the encoder to detect both positive and negative excursions of each feature, with the ReLU then selecting only the positive excursions as active.

Dictionary elements.

The columns of Wdec, denoted 𝐝jβˆˆβ„d⁑ for j=1,…,m, are the dictionary elements of the SAE. Each dictionary element is a direction in activation space. When the SAE is trained successfully, each 𝐝j should correspond to a monosemantic feature: a single, human-interpretable concept.

The encoder computes a non-negative coefficient hj for each dictionary element, with hj>0 indicating that feature j is active in the current context. The decoded reconstruction 𝒙^=βˆ‘jhj𝐝j+𝐛pre expresses the activation as a sparse linear combination of dictionary elements.

Training Objective

The SAE training objective balances two competing goals: reconstruction fidelity (the decoded 𝒙^ should match the original 𝒙 closely) and sparsity (only a few dictionary elements should be active at each step).

Definition 24 (SAE Training Objective).

The SAE training loss is: (SAE LOSS)β„’SAE=β€–π’™βˆ’π’™^β€–22⏟reconstruction+λ‖𝐑‖1⏟sparsityΒ penalty, where Ξ»>0 is the sparsity coefficient controlling the trade-off between reconstruction quality and sparsity of the hidden representation. The β„“1 norm ‖𝐑‖1=βˆ‘j=1mhj (with hjβ‰₯0 by construction) penalises the total magnitude of feature activations.

Remark 21 (Why β„“1 and not β„“0?).

The β„“0 β€œnorm” ‖𝐑‖0=βˆ‘j𝟏[hj>0] directly counts the number of active features and is the theoretically cleanest sparsity measure. However, β„“0 is non-differentiable and NP-hard to optimise. The β„“1 norm is the convex relaxation of β„“0: it is the tightest convex surrogate that still promotes sparsity. Under certain conditions (the restricted isometry property), β„“1 minimisation exactly recovers the sparsest solution. In practice, the β„“1 penalty combined with a ReLU encoder provides an effective and gradient-friendly sparsity constraint.

Normalisation of decoder columns.

A crucial subtlety: the decoder columns 𝐝j must be constrained to have unit norm. Without this constraint, the optimiser can trivially reduce the β„“1 sparsity penalty by rescaling: make 𝐝j very large (absorbing the scale into 𝐝j) and make hj very small (reducing ‖𝐑‖1). Unit-norm columns prevent this degeneracy. In practice, this is enforced by projecting Wdec onto the Stiefel manifold after each gradient step: (SAE NORM)(𝐝j)new←(𝐝j)oldβ€–(𝐝j)oldβ€–2.

Hyperparameter sensitivity.

The sparsity coefficient Ξ» is a critical hyperparameter. Too small: the SAE learns a near-dense representation with high reconstruction fidelity but uninterpretable features (the trivial solution is to learn the identity mapping with m=d). Too large: the SAE learns to use very few features, sacrificing reconstruction fidelity to the point where many input dimensions are ignored. The optimal Ξ» must be found by balancing reconstruction loss and sparsity, often using metrics like L0 (average number of active features per token) and reconstruction R2.

The Shrinkage Problem

A fundamental limitation of β„“1-penalised estimation, long recognised in the statistics literature under the name LASSO shrinkage, is that it systematically underestimates the magnitude of large coefficients.

The bias of LASSO.

Suppose the true feature activation for feature j in context 𝒙 is hjβˆ—. Under the β„“1 penalty, the optimal estimate h^j is the soft-thresholding operator applied to the pre- activation h~j: (SOFT Threshold)h^j=STΞ»(h~j):=max⁑(0,h~jβˆ’Ξ»), where STΞ» is the soft-thresholding function with threshold Ξ». The bias is 𝔼[h^j]βˆ’hjβˆ—=βˆ’Ξ» whenever h~j>Ξ» (the feature is active). This means:

  1. Active features have their magnitudes systematically underestimated by Ξ».

  2. The SAE must compensate by adjusting the decoder columns 𝐝j, potentially distorting the feature geometry.

  3. Features with true activation hjβˆ—<Ξ» are entirely suppressed to zero, even if they are genuinely active.

Remark 22 (Practical impact of shrinkage).

Shrinkage biases the SAE's estimate of feature magnitudes. In mechanistic interpretability, we often care not just about which features are active but how strongly they are active (e.g., to determine causal influence on model output). Shrinkage makes it harder to reliably estimate feature strengths, potentially causing interpretability analyses to underestimate the importance of certain features.

Gated SAEs: Separating Gating from Magnitude

The shrinkage problem arises because a single value (hj) must simultaneously encode two distinct decisions: (1) is feature j active? (a binary gating decision) and (2) how strongly is feature j active? (a continuous magnitude). The β„“1 penalty acts on the magnitude, but its effect is felt through the gating decision as well.

Gated SAEs (Rajamanoharan et al., 2024) resolve this by introducing separate pathways for gating and magnitude estimation.

Definition 25 (Gated Sparse Autoencoder).

A Gated SAE replaces the standard encoder with a two-pathway architecture: (Gated GATE)𝐑~=Wgate(π’™βˆ’π›pre)+𝐛gate,𝝅=𝟏[𝐑~>0](hardΒ gating;Β STEΒ forΒ gradients),𝐦~=Wmag(π’™βˆ’π›pre)+𝐛mag,𝐑=π…βŠ™ReLU(𝐦~), where Wgate,Wmagβˆˆβ„mΓ—d⁑ are separate gating and magnitude weight matrices, π…βˆˆ{0,1}m is the binary gate computed via the Heaviside step function with straight-through estimation (STE) for backpropagation, and βŠ™ denotes element-wise multiplication.

Loss modification.

The gated SAE uses a modified loss that places the sparsity penalty on the gate logits rather than the final activations: (Gated LOSS)β„’gated=β€–π’™βˆ’π’™^β€–22+Ξ»β€–ReLU(𝐑~)β€–1, The sparsity penalty acts on ReLU(𝐑~) (the smooth version of the gate) rather than on the magnitude activations, decoupling the gating and magnitude estimation problems.

Empirical improvements.

Gated SAEs consistently outperform standard SAEs on the reconstruction–sparsity Pareto frontier: for the same level of sparsity (average L0), gated SAEs achieve lower reconstruction error, and for the same reconstruction error, they achieve lower L0. The interpretability of discovered features is also qualitatively improved, suggesting that clean gating leads to cleaner feature separation.

Transcoders: Mapping MLP Input to Output

Standard SAEs are trained on residual stream states: the activations 𝒙 before or after a given layer. An alternative, proposed by Dunefsky et al. (2024), is the transcoder: a sparse model that maps the input to an MLP layer directly to its output.

Definition 26 (Transcoder).

A transcoder is a learned function 𝒯:ℝd⁑→ℝd⁑ that approximates a transformer MLP sublayer MLP:ℝd⁑→ℝd⁑, parameterised as: (Transcoder ENC)𝐑=ReLU(Wenc𝒙+𝐛enc),𝐲^=Wdec𝐑+𝐛dec, where π’™βˆˆβ„d⁑ is the MLP input, 𝐲^βˆˆβ„d⁑ approximates the MLP output, and π‘βˆˆβ„β‰₯0m⁑ is the sparse intermediate representation with m≫d. The training loss is: (Transcoder LOSS)β„’TC=β€–MLP(𝒙)βˆ’π²^β€–22+λ‖𝐑‖1.

Advantages of transcoders.

The transcoder provides a fundamentally different perspective from residual-stream SAEs. Whereas a residual-stream SAE decomposes β€œwhat information is stored at a given position”, a transcoder decomposes β€œwhat computation the MLP performs”. Specifically, the dictionary elements 𝐝j of the transcoder are input-output pairs: active feature j contributes hj𝐝j to the output, where 𝐝jβˆˆβ„d⁑ describes the direction in which that feature updates the residual stream.

This makes transcoders particularly suitable for understanding knowledge storage in MLP layers, where factual associations (e.g., β€œParis is the capital of France”) are believed to be stored as superimposed key-value pairs (Meng et al., 2022 - ROME).

SAE Architecture: A Visual Overview

Sparse Autoencoder (SAE) architecture. An activation vector π’™βˆˆβ„d⁑ from the residual stream is centred by subtracting the pre-encoder bias 𝐛pre, then passed through the encoder (a linear layer followed by ReLU) to produce a sparse feature activation vector π‘βˆˆβ„β‰₯0m⁑ with m≫d. The decoder (a linear layer with unit-norm columns) reconstructs 𝒙^. The training loss penalises both reconstruction error (β€–π’™βˆ’π’™^β€–22) and total activation magnitude (λ‖𝐑‖1). The columns of Wdec are the dictionary elements: each encodes one monosemantic feature direction in the original d-dimensional space.

Monosemantic Features: What SAEs Discover

The proof of the SAE methodology lies in what it finds. When SAEs are trained on the internal activations of large language models, the dictionary elements 𝐝j exhibit striking monosemanticity: each element responds strongly to a specific, human-interpretable concept and weakly to everything else.

Categories of discovered features.

SAE features can be broadly grouped into three categories:

  1. Geographic features. Features that activate strongly for tokens that are part of geographical references - country names, city names, continent names, or demonyms. Different features distinguish different granularities and types: one feature may activate for β€œEuropean capital city names”, another for β€œSouth American river names”, a third for β€œUS state abbreviations”.

  2. Temporal features. Features encoding temporal information: specific decades (β€œ1990s”, β€œ2000s”), recurring events (β€œevery year”, β€œannual”), temporal expressions (β€œyesterday”, β€œnext month”), and calendar dates. Temporal features often have a strong interaction with domain: β€œ1990s technology” and β€œ1990s music” may activate different features despite sharing the decade marker.

  3. Conceptual and relational features. Features for abstract semantic relationships: negation, causality, analogy, contrast, and entailment. Also present are syntactic features (subject-verb agreement, genitive markers), domain markers (medical terminology, legal jargon, code syntax), and emotion/sentiment features.

Insight.

SAEs are microscopes for neural networks - they reveal individual features the way microscopes reveal cells. Just as a light microscope cannot distinguish organelles (requiring electron microscopy), a SAE with a small dictionary (m comparable to d) cannot distinguish fine-grained features. But as the dictionary size m grows (analogous to increasing magnification), progressively finer-grained features become visible.

Validation of monosemanticity.

How do we verify that a discovered feature is genuinely monosemantic? The standard approach is automatic interpretability (Bills et al., 2023): use a separate language model (e.g., GPT-4) to generate a natural-language description of the feature by examining the top-activating tokens and contexts, then evaluate whether the description correctly predicts which new contexts will activate the feature. A feature is considered monosemantic if a single short description achieves high prediction accuracy.

Templeton et al. (2024) applied this methodology at scale to Claude 3 Sonnet, finding that the majority of the 1,000,000+ discovered SAE features received high-quality monosemantic descriptions from the automated evaluator.

Scaling SAEs: Dictionary Size, Dead Features, and Fidelity

Training SAEs at scale introduces new challenges that do not appear in small-scale experiments. Three phenomena dominate the scaling behaviour of SAEs: the dictionary size, the dead feature problem, and the reconstruction fidelity trade-off.

Dictionary size and feature granularity.

As the dictionary size m increases, the SAE discovers progressively more fine-grained features. With m=512, an SAE trained on a language model might discover a single β€œEuropean country” feature. With m=16,384, it discovers separate features for each European country. With m=131,072, it distinguishes not only countries but also contexts (β€œFrance as a tourist destination”, β€œFrance in the context of wine”, β€œFrance in WWII context”).

This suggests a feature hierarchy: broader features at small dictionary sizes, finer-grained features at larger sizes. The optimal dictionary size depends on the application: larger dictionaries provide richer interpretability but are more expensive to train and interpret.

Dead features.

A common failure mode in SAE training is the emergence of dead features: dictionary elements 𝐝j that are never (or very rarely) activated across the training distribution. Dead features waste model capacity and can arise from:

  • Initialisation failures: random initialisation places 𝐝j in a region of the unit sphere that no training example maps near, and the gradient updates never pull it into an active region.

  • Gradient starvation: if a feature is rarely active, it receives few gradient updates, leading to slow learning and eventual death.

  • Supercession: a similar feature 𝐝jβ€² with slightly better initialisation captures the same concept, causing 𝐝j to become redundant.

Dead features can be mitigated through auxiliary losses (Anthropic's β€œAuxK” loss, which explicitly penalises the magnitude of the top-k activations of dead features), resampling (periodically reinitialising dead features to activations of training examples not well-explained by active features), or k-sparse autoencoders (TopK SAEs, which use a fixed-k sparse activation instead of the ReLU-plus-L1 approach).

Reconstruction fidelity.

The quality of an SAE is measured by how well the reconstructed 𝒙^ matches the original 𝒙. Two metrics are standard:

  1. Variance explained (R2): the fraction of total variance in 𝒙 explained by 𝒙^. (SAE R2)R2=1βˆ’π”Ό[β€–π’™βˆ’π’™^β€–22]𝔼[‖𝒙‖22]. A well-trained SAE achieves R2>0.99 on the training distribution.

  2. Loss recovered: the fraction of the model's language modelling loss that is preserved when the residual stream is replaced by 𝒙^. If the model's clean cross-entropy loss is β„’0 and the loss with the SAE intervention is β„’SAE, then: (SAE LOSS Recovered)LossΒ recovered=1βˆ’β„’SAEβˆ’β„’0β„’SAEβˆ’β„’zero, where β„’zero is the loss when the residual stream is zeroed out. Loss recovered >0.95 indicates that the SAE captures the vast majority of the causally relevant information.

Discovered Features: A Visual Taxonomy

Taxonomy of monosemantic features discovered by SAEs. Features discovered in large language models by sparse autoencoders cluster into three broad categories: geographic features (activated by place names and demonyms), temporal features (activated by time expressions and date references), and conceptual features (activated by abstract semantic and syntactic properties). As the SAE dictionary size m increases, features become progressively more fine-grained within each category. Example activating tokens for each category are shown at the bottom.

Example: Training an SAE on GPT-2

To ground the preceding theory, we trace through a concrete end-to-end example: training a sparse autoencoder on the residual stream activations of GPT-2 small (117M parameters) after the 8th layer.

Setup.

GPT-2 small has a hidden dimension of d=768. We train an SAE with dictionary size m=16,384 (expansion factor β‰ˆ21) and sparsity coefficient Ξ»=4Γ—10βˆ’5. The SAE is trained on 1 billion tokens of text from the OpenWebText corpus using the Adam optimiser with learning rate 10βˆ’4.

Training dynamics.

During early training (first 100,000 steps), the SAE quickly learns a near-identity mapping: the reconstruction loss drops sharply while the sparsity penalty remains high. By step 500,000, a bimodal pattern emerges in the feature activation histogram: most features are inactive (activating fewer than 0.1% of the time), while a smaller number of features activate frequently. The dead feature rate is approximately 30% at this stage.

After applying the AuxK auxiliary loss and running for 1.5 million total steps, the dead feature rate drops to approximately 5%, R2=0.987, and the average L0 (number of active features per token) stabilises at around 64.

Inspecting top features.

We examine the five highest-activating tokens for selected dictionary elements:

  • Feature 2314: activates on β€œParis”, β€œLyon”, β€œMarseille”, β€œBordeaux”, β€œToulouse” - clearly a β€œFrench cities” feature.

  • Feature 7891: activates on β€œDNA”, β€œRNA”, β€œnucleotide”, β€œgenome”, β€œchromosome” - a β€œmolecular biology terminology” feature.

  • Feature 11203: activates on β€œhowever”, β€œnevertheless”, β€œnonetheless”, β€œyet”, β€œalthough” - an β€œadversative/concessive conjunction” feature.

  • Feature 3047: activates on β€œdef”, β€œclass”, β€œimport”, β€œreturn”, β€œfor” - a β€œPython syntax keyword” feature.

  • Feature 9156: activates on β€œ1990”, β€œ1992”, β€œ1994”, β€œ1996”, β€œ1998” - a β€œ1990s year” feature.

Each of these features is strikingly monosemantic: a single description captures all top-activating tokens. Crucially, the features were not engineered; they emerged spontaneously from training on next-token prediction with a sparsity constraint.

Causal intervention.

To verify that the features are causally relevant (not merely correlational), we perform an activation patching experiment: we replace the feature activation h2314 (β€œFrench cities”) with its maximum observed value in a forward pass on an unrelated context (e.g., a passage about computer science). The model's completion probability for French-related tokens increases significantly, confirming that feature 2314 causally influences the model's predictions about French cities.

Example 5.

SAE feature causality test. Let h2314⋆ be the maximum activation of feature 2314 observed during training, and let 𝒙^⋆ be the reconstructed residual stream with h2314 replaced by h2314⋆ (all other features held constant). Feeding 𝒙^⋆ into the downstream layers of GPT-2 when processing the prompt β€œThe best restaurant in” causes the model to assign significantly higher probability to French city names in the next- token distribution. Concretely, P(β€œParis”|𝒙^⋆)/P(β€œParis”|𝒙^)β‰ˆ6.3 in our experimental setting, a factor of 6.3 increase in the probability of β€œParis” being the next token. This confirms that feature 2314 is a causally active representation of French cities, not merely a correlational artifact.

Exercises

Exercise 28.

LASSO shrinkage analysis. Consider a one-dimensional SAE with a single dictionary element πβˆˆβ„d⁑, ‖𝐝‖2=1. The activation is h=ReLU(πβŠ€π’™βˆ’b) for an encoder bias b>0, and the reconstruction is 𝒙^=h𝐝.

(a) Show that for an input 𝒙=α𝐝 with Ξ±>0, the optimal h minimising β„’SAE=(Ξ±βˆ’h)2+Ξ»h is hβˆ—=max⁑(0,Ξ±βˆ’Ξ»/2). What is the bias hβˆ—βˆ’Ξ± for Ξ±>Ξ»/2?

(b) Now suppose we additionally have a second dictionary element πβ€²βŸ‚π and input 𝒙=α𝐝+α′𝐝′. Argue that the optimal (h,hβ€²) for the two-element SAE decouples into two independent one-dimensional problems when πβŸ‚πβ€². What happens to this decoupling when |⟨𝐝,πβ€²βŸ©|=Ο΅>0?

(c) Relate the shrinkage bias you computed in part (a) to the concept of superposition interference from The Toy Model of Superposition. Why does a gated SAE (Definition Definition 25) avoid this bias?

Exercise 29.

Dead feature analysis. Let m=4096 and d=512. Suppose that at initialisation, the m dictionary elements are drawn uniformly at random from the unit sphere Sdβˆ’1, and the encoder weights are set to Wenc=Wdec⊀ (tied initialisation). The training distribution consists of n=100,000 training examples.

(a) A feature 𝐝j is dead at initialisation if no training example 𝒙i satisfies Wenc,j𝒙i>benc,j (where benc,j=0 initially). Using the bound from Proposition Proposition 5, estimate the probability that a randomly initialised feature is dead at initialisation when the training examples are uniformly distributed on Sdβˆ’1.

(b) Describe the AuxK auxiliary loss strategy for reviving dead features. Write down a specific loss term that penalises dead features and explain why it promotes their revival without destabilising active features.

(c) An alternative approach is feature resampling: every T training steps, dead features are re-initialised as the normalised activation vector of a training example that is currently β€œpoorly explained” (i.e., has large reconstruction error β€–π’™βˆ’π’™^β€–2). Explain why this heuristic is well-motivated from the perspective of maximising reconstruction fidelity.

Exercise 30.

Transcoders vs. residual-stream SAEs. A transformer MLP with two layers has input π’™βˆˆβ„d⁑ and output MLP(𝒙)=W2GeLU(W1𝒙+𝐛1)+𝐛2, with W1βˆˆβ„4dΓ—d⁑, W2βˆˆβ„dΓ—4d⁑.

(a) A residual-stream SAE is trained on the outputs {MLP(𝒙i)}. A transcoder is trained to map the MLP inputs {𝒙i} to the MLP outputs {MLP(𝒙i)}. Give one concrete scenario where the transcoder provides qualitatively different (and more informative) interpretability than the residual-stream SAE.

(b) The transcoder can be written as 𝐲^=βˆ‘jhj𝐝j+𝐛dec. Show that if the transcoder perfectly reconstructs the MLP output (zero reconstruction error), then the dictionary elements 𝐝j span the column space of W2. What does this imply about the relationship between transcoder features and the MLP's output directions?

(c) Propose a metric to compare the interpretability of transcoder features vs. residual-stream SAE features, beyond simple reconstruction error. Your metric should be computable using a fixed evaluation dataset and a frozen language model.

Knowledge Storage and Factual Editing

How does a language model know that the Eiffel Tower is in Paris? The question sounds almost trivial, yet answering it rigorously requires us to open the model's weights and trace, neuron by neuron, which parameters encode the association between the subject Eiffel Tower, the relation is located in, and the object Paris. Over the past several years, a branch of mechanistic interpretability has done exactly this, developing tools that localise factual knowledge to specific weight matrices, quantify how strongly each layer contributes to a given completion, and, most strikingly, surgically modify stored facts without retraining the entire model.

The practical motivation is compelling. A language model trained in 2023 encodes the fact that a particular country's prime minister is a particular person. By 2025, that fact may have changed. Rather than retraining the full model, a knowledge-editing algorithm inserts the updated fact at the precise location where the old one is stored. The operation is targeted, fast, and-when done correctly-does not disrupt thousands of unrelated facts that surround the edited one in weight space.

This section develops the mathematical foundations for all of these operations. We begin with the empirical discovery that localised the problem, proceed through the formal framework of MLP key-value memories, and culminate in the ROME and MEMIT algorithms with full mathematical derivations.

The ROME Hypothesis: Facts Live in Middle-Layer MLPs

The story begins with a deceptively simple intervention experiment. Given a factual prompt such as β€œThe Eiffel Tower is located in the city of”, Meng et al. (2022) asked: which activations, if corrupted, would prevent the model from completing the sentence with Paris? Their technique, called causal tracing, works as follows.

Run the model three times on the same prompt:

  1. Clean run. Process the prompt normally; record every hidden state 𝒉i(l) at layer l, token position i.

  2. Corrupted run. Replace the subject tokens with a corrupted version (e.g. Gaussian noise is added to their embeddings) and run the model again; record all states.

  3. Restored run. For each candidate state (l,i), take the corrupted run but patch in the clean state at position (l,i); measure whether the clean prediction is recovered.

Formally, define the average indirect effect (AIE) of restoring state (l,i) as (AIE)AIE(l,i)=𝔼prompts[prestored(correct)βˆ’pcorrupt(correct)], where the expectation is over a dataset of factual prompts. A large value of AIE(l,i) means that restoring state (l,i) from the clean run substantially recovers the correct prediction, i.e., that state (l,i) is causally necessary for the fact.

The empirical finding from causal tracing across GPT-2 XL and GPT-J is striking and reproducible:

  • The early attention layers at subject tokens contribute modestly by spreading subject information across the context.

  • The middle-layer MLP modules (roughly layers 5–15 in a 28-layer model) at the last subject token exhibit dramatically elevated AIE.

  • Restoring a single MLP hidden state at the right location can recover essentially the full probability of the correct object.

Key Idea.

Factual associations in large language models are not distributed uniformly across all layers. Causal tracing consistently localises them to the feed-forward network (MLP) modules in the middle layers of the transformer, evaluated at the last token position of the subject span. This localisation is the empirical foundation for targeted factual editing.

MLPs as Key-Value Memory Stores

To understand why facts live in MLP weights, we need to interpret the two-layer MLP formally as an associative memory. Consider the standard transformer MLP block: (MLP Block)MLP⁑(𝒉)=𝐖outΟƒ(𝐖in𝒉), where 𝐖inβˆˆβ„dffΓ—d⁑ and 𝐖outβˆˆβ„dΓ—dff⁑ are the weight matrices, Οƒ is the activation function (GELU or ReLU), and π’‰βˆˆβ„d⁑ is the residual-stream vector at the current position.

Rewrite this as (MLP KV Expansion)MLP⁑(𝒉)=βˆ‘j=1dffΟƒ(βŸ¨π’˜in,j,π’‰βŸ©)β‹…π’˜out,j, where π’˜in,j is the j-th row of 𝐖in and π’˜out,j is the j-th column of 𝐖out.

The analogy to an associative memory is now transparent. Each β€œneuron” j stores:

  • a key π’Œj=defπ’˜in,j: a direction in residual-stream space that the neuron β€œattends to”;

  • a value 𝒗j=defπ’˜out,j: a direction in residual-stream space that is written when the neuron fires.

The scalar Οƒ(βŸ¨π’Œj,π’‰βŸ©) is the attention coefficient: it is large when the input 𝒉 aligns with key π’Œj, causing value 𝒗j to be added to the residual stream.

Definition 27 (Factual Association Tuple).

A factual association tuple is a triple (s,r,o) where s is the subject (e.g. Eiffel Tower), r is the relation (e.g. is located in), and o is the object (e.g. Paris). A language model fΞΈ stores the fact (s,r,o) if, for the prompt template πš™(s,r) (e.g. β€œThe Eiffel Tower is located in the city of”), the model assigns high probability to the token completion o: fΞΈ(πš™(s,r))=arg maxt⁑pΞΈ(t|πš™(s,r)).

The key-value interpretation makes a precise prediction: if we want to change the stored object from o to oβˆ— (e.g. from Paris to London), we must find the dominant key-value pair in the target MLP layer that encodes the current association and replace its value with a new vector π’—βˆ— that promotes oβˆ—.

The ROME Algorithm

ROME (Rank-One Model Editing) implements the key-value replacement idea with a rank-one update to a single MLP weight matrix. We present the full derivation.

Setup

Let lβˆ— be the target MLP layer identified by causal tracing. We focus on the second weight matrix of that MLP, its output (down-projection), 𝐖=def𝐖out(lβˆ—)βˆˆβ„dΓ—dff⁑. The goal is to find an update 𝐖^=𝐖+Δ𝐖 such that (ROME Constraint NEW)𝐖^π’Œβˆ—=π’—βˆ—(newΒ factΒ inserted),𝐖^π’Œ=π–π’ŒforΒ allΒ π’Œβˆ‰{π’Œβˆ—}, where π’Œβˆ—βˆˆβ„dff⁑ is the key vector associated with the subject and π’—βˆ—βˆˆβ„d⁑ is the target value vector associated with the new object oβˆ—.

Constraint cannot hold for all vectors simultaneously unless Δ𝐖=0, so we relax it: we require it to hold in the direction of every key that appears in a set of preservation memoranda {π’Œi}i=1N, a sample from the space of contexts unrelated to the edited fact.

Computing the Key Vector π’Œβˆ—k*

The key vector π’Œβˆ— represents the MLP's intermediate representation when processing the subject s in the prompt. Concretely:

  1. Run the transformer forward on the prompt template πš™(s,r).

  2. Extract the hidden state at the last subject token at the input to layer lβˆ—, i.e., 𝒉is(lβˆ—βˆ’1) where is is the last token index of s.

  3. Apply the MLP input projection: π’Œβˆ—=Οƒ(𝐖in(lβˆ—)𝒉is(lβˆ—βˆ’1))βˆˆβ„dff⁑.

To make π’Œβˆ— robust to paraphrases of s, ROME averages over several prompt templates: (Kstar)π’Œβˆ—=1|𝒫|βˆ‘pβˆˆπ’«Οƒ(𝐖in(lβˆ—)𝒉is(lβˆ—βˆ’1)(p)), where 𝒫 is a small set of paraphrase templates.

Computing the Value Vector π’—βˆ—v*

The target value vector π’—βˆ— must, when multiplied by the key, cause the residual stream to subsequently produce the correct token oβˆ—. This is solved by an optimisation problem. Let 𝒛(lβˆ—) be the output of layer lβˆ—'s MLP; the rest of the network (layers lβˆ—+1 through L) maps this to a distribution over tokens. Define the target probability objective: (Vstar Objective)π’—βˆ—=arg max𝒗⁑log⁑pΞΈ(oβˆ—|πš™(s,r);layerΒ lβˆ—Β output=π–π’Œβˆ—+(π’—βˆ’π–π’Œβˆ—)). In practice, π’—βˆ— is computed by gradient descent on the output embedding of layer lβˆ—: one freezes all layers except the β€œvirtual” output of layer lβˆ— and optimises to maximise the log-probability of oβˆ— at the prediction head.

Rank-One Update

With π’Œβˆ— and π’—βˆ— in hand, the update is derived as follows. We seek Δ𝐖 of minimal Frobenius norm such that: (ROME Constrained)(𝐖+Δ𝐖)π’Œβˆ—=π’—βˆ—,(𝐖+Δ𝐖)𝐊=π–πŠ, where 𝐊=[π’Œ1,…,π’ŒN]βˆˆβ„dffΓ—N⁑ is the matrix of preservation keys.

The second constraint fixes what the weight does on the column space of 𝐊. We use the least-squares solution in the 𝐂=𝐊𝐊⊀ metric (covariance of the key distribution), which amounts to computing: (ROME Lambda)𝝀=π‚βˆ’1π’Œβˆ—,Δ𝐖=(π’—βˆ—βˆ’π–π’Œβˆ—)π€βŠ€π€βŠ€π’Œβˆ—=(π’—βˆ—βˆ’π–π’Œβˆ—)(π‚βˆ’1π’Œβˆ—)⊀(π‚βˆ’1π’Œβˆ—)βŠ€π’Œβˆ—. This is a rank-one matrix: Δ𝐖=π’–π’˜βŠ€ where 𝒖=π’—βˆ—βˆ’π–π’Œβˆ— (the β€œvalue residual”) and π’˜=π‚βˆ’1π’Œβˆ—/((π‚βˆ’1π’Œβˆ—)βŠ€π’Œβˆ—).

Theorem 5 (ROME Correctness).

Let 𝐖^=𝐖+Δ𝐖 with Δ𝐖 defined by . Then:

  1. 𝐖^π’Œβˆ—=π’—βˆ— (new fact is stored exactly).

  2. For any 𝒖 in the column space of 𝐊, 𝐖^π’–β‰ˆπ–π’–, with equality in the limit Nβ†’βˆž or when π’Œβˆ— is orthogonal to the span of 𝐊 (preservation keys approximately unchanged).

Proof.

For (i): 𝐖^π’Œβˆ—=π–π’Œβˆ—+(π’—βˆ—βˆ’π–π’Œβˆ—)π€βŠ€π’Œβˆ—/(π€βŠ€π’Œβˆ—)=π–π’Œβˆ—+(π’—βˆ—βˆ’π–π’Œβˆ—)=π’—βˆ—.

For (ii): let 𝒖=𝐊𝜷 for some 𝜷. Then Δ𝐖𝒖=(π’—βˆ—βˆ’π–π’Œβˆ—)π€βŠ€πŠπœ·/(π€βŠ€π’Œβˆ—). Now 𝝀=π‚βˆ’1π’Œβˆ—=(𝐊𝐊⊀)βˆ’1π’Œβˆ—, so π€βŠ€πŠ=π’Œβˆ—βŠ€(𝐊𝐊⊀)βˆ’1𝐊. For any 𝒖 in the column space of 𝐊 we have the projection identity 𝐊(𝐊⊀𝐊)βˆ’1πŠβŠ€π’–=𝒖, but in general the preservation condition holds only in the limit Nβ†’βˆž or when π’Œβˆ— is orthogonal to the span of 𝐊, which is ensured by construction (the preservation keys are sampled from unrelated contexts).

Remark 23.

The covariance matrix 𝐂=πŠπŠβŠ€βˆˆβ„dffΓ—dff⁑ is computed once for a given model by running a large corpus (WikiText, for example) through the model and collecting MLP key activations at layer lβˆ—. It is then cached for all subsequent edits. The inverse π‚βˆ’1 can be maintained as a running estimate using the Sherman-Morrison-Woodbury formula if new preservation keys are added incrementally.

ROME Pipeline: From Causal Trace to Edit

The ROME pipeline. Given a factual association to change (s,r,oβˆ—), causal tracing first identifies the critical MLP layer lβˆ—. The key vector π’Œβˆ— is extracted from forward activations; the value vector π’—βˆ— is found by gradient optimisation. A rank-one update to 𝐖out(lβˆ—) inserts the new fact. Final verification checks specificity (unrelated facts are preserved) and generalisation (paraphrases of the prompt also produce oβˆ—).

Example: Editing a Geographic Fact

Example 6 (Editing β€œEiffel Tower is in Paris”).

Consider editing GPT-J (6B parameters) to believe the Eiffel Tower is in London instead of Paris. The fact tuple is: s=πΈπ‘–π‘“π‘“π‘’π‘™Β π‘‡π‘œπ‘€π‘’π‘Ÿ,r=π‘–π‘ Β π‘™π‘œπ‘π‘Žπ‘‘π‘’π‘‘Β π‘–π‘›Β π‘‘β„Žπ‘’Β π‘π‘–π‘‘π‘¦Β π‘œπ‘“,oβˆ—=πΏπ‘œπ‘›π‘‘π‘œπ‘›.

Step 1 - Causal tracing. Running causal tracing on β€œThe Eiffel Tower is located in the city of [Paris]” shows that the highest AIE values are concentrated at layer lβˆ—=5, token position corresponding to the last subword of Tower, in the MLP (not the attention) component.

Step 2 - Key computation. We run forward passes on five prompt templates:

  • β€œThe Eiffel Tower is located in the city of”

  • β€œThe home country of the Eiffel Tower is in”

  • β€œYou can find the Eiffel Tower in the city of”

  • β€œThe Eiffel Tower stands in”

  • β€œVisit the Eiffel Tower, located in”

Each produces a hidden state at the last token of Tower at layer 4's output; passing through 𝐖in(5) and GELU gives five key vectors. Their average is π’Œβˆ—.

Step 3 - Value optimisation. We fix all weights and optimise a free vector 𝒗 by gradient descent to maximise log⁑p(πΏπ‘œπ‘›π‘‘π‘œπ‘›|β‹…) when layer 5's MLP output is set to 𝒗. Convergence requires approximately 25 steps.

Step 4 - Rank-one update. We compute Δ𝐖=(π’—βˆ—βˆ’π–π’Œβˆ—)(π‚βˆ’1π’Œβˆ—)⊀/((π‚βˆ’1π’Œβˆ—)βŠ€π’Œβˆ—) and apply 𝐖^=𝐖+Δ𝐖 to 𝐖out(5) only.

Result. After the edit, the model consistently completes β€œThe Eiffel Tower is located in the city of” with London. Importantly:

  • β€œThe Louvre is located in the city of” β†’ Paris (unrelated fact preserved).

  • β€œThe Eiffel Tower is in” β†’ London (paraphrase generalisation).

  • β€œWhat city is the Eiffel Tower in?” β†’ London (question format generalisation).

Evaluation Criteria: Specificity, Generality, Locality

Any knowledge-editing method must be evaluated along three orthogonal axes:

Definition 28 (Editing Evaluation Criteria).

Let fΞΈ be the pre-edit model and fΞΈ^ the post-edit model. A factual edit targeting (s,r,oβˆ—) is evaluated by:

  1. Efficacy (ES): the edit succeeds on the exact prompt, arg maxt⁑pΞΈ^(t|πš™(s,r))=oβˆ—.

  2. Generality (PS, paraphrase score): the edit generalises to paraphrases, arg maxt⁑pΞΈ^(t|pβ€²)=oβˆ— for all pβ€²βˆˆPara(s,r).

  3. Specificity (NS, neighbourhood score): unrelated facts are preserved, arg maxt⁑pΞΈ^(t|πš™(sβ€²,r))=arg maxt⁑pΞΈ(t|πš™(sβ€²,r)) for sβ€²β‰ s drawn from a neighbourhood set.

An ideal edit achieves ES =1, PS =1, NS =1.

ROME achieves high specificity by the design of the rank-one update: because Δ𝐖 is rank-one and the preservation key covariance 𝐂 covers the distribution of typical inputs, the update barely affects activations outside the subject token's direction. Generality is improved by averaging π’Œβˆ— over multiple prompt templates.

MEMIT: Mass-Editing Memory in a Transformer

ROME edits one fact at a time. When thousands of facts must be updated simultaneously (e.g. incorporating a year's worth of news events into a model), the sequential application of rank-one updates is insufficient: each update shifts the covariance 𝐂, so the approximation degrades, and the locality constraint is increasingly violated.

MEMIT (Mass-Editing Memory in a Transformer, Meng et al. 2022) addresses this by:

  1. Spreading edits across multiple layers. Rather than targeting a single layer lβˆ—, MEMIT identifies a range of layers {l1,…,lR} (typically the same middle layers identified by causal tracing) and distributes the editing responsibility across them.

  2. Batch optimisation. Given a batch of M fact tuples {(sm,rm,omβˆ—)}m=1M, MEMIT solves a joint least-squares problem for all value residuals simultaneously.

MEMIT Objective

For a batch of M edits, let 𝒗mβˆ— be the target value for edit m and π’Œmβˆ— the corresponding key. MEMIT distributes each value residual 𝒓m=def𝒗mβˆ—βˆ’π–π’Œmβˆ— equally across R layers: (Memit Residual)𝒓m(l)=1R𝒓m,l∈{l1,…,lR}. Then for each layer l, the weight update solves the constrained least-squares problem: (Memit Update)Δ𝐖(l)=𝐑(l)(𝐊(l))⊀[𝐊(l)(𝐊(l))⊀+α𝐂(l)]βˆ’1, where 𝐑(l)=[𝒓1(l),…,𝒓M(l)]βˆˆβ„dΓ—M⁑, 𝐊(l)=[π’Œ1βˆ—,…,π’ŒMβˆ—]βˆˆβ„dffΓ—M⁑, 𝐂(l) is the precomputed key covariance at layer l, and Ξ±>0 is a regularisation coefficient controlling how much the update respects the locality constraint.

This is a standard ridge-regression solution and can be computed in closed form. The total number of parameters modified is RΓ—dΓ—dff, but each Δ𝐖(l) has rank at most M, so for Mβ‰ͺdff the updates remain low-rank.

Remark 24.

Empirically, MEMIT successfully applies up to 10,000 edits to a single GPT-J model with specificity above 90% and generality above 80%, while ROME degrades significantly beyond 100 sequential edits. The key insight is that distributing the edits across layers prevents any single layer from being overloaded.

Caution.

Knowledge editing algorithms such as ROME and MEMIT can have unintended side effects that are not detected by standard evaluation metrics:

  • Ripple effects. Changing (s,r,oβˆ—) may break logically entailed facts. For example, editing β€œthe Eiffel Tower is in London” does not automatically update β€œthe country of the Eiffel Tower is the UK”. Post-edit consistency across entailed facts is often violated.

  • Representation drift. The rank-one update moves 𝐖out(lβˆ—) in a direction that was previously unused; over many edits, this can disrupt the geometry of the residual stream in ways that degrade performance on unrelated tasks.

  • Generalisation overshooting. Occasionally, π’—βˆ— is so broadly placed in the value space that it causes the model to predict oβˆ— even for slightly different subjects, violating specificity.

These issues motivate the use of editing benchmarks such as COUNTERFACT and ZsRE that measure post-edit model health across diverse paraphrases and neighbourhoods.

Historical and Broader Context

Historical Note.

Knowledge editing as a formal problem was crystallised by de Cao et al. (2021), who introduced gradient-based methods for targeted model updates. The ROME algorithm of Meng et al. (2022) was the first to ground editing in mechanistic interpretability: the causal tracing discovery that middle-layer MLPs localise facts was both the scientific result and the engineering blueprint. MEMIT extended the approach to mass editing in the same year. Subsequent work has challenged the universality of the ROME localisation finding (some facts appear distributed across attention layers, not just MLPs), motivating more flexible approaches such as GRACE (Hartvigsen et al. 2023), which adds an external memory rather than modifying weights, and AlphaEdit (Fang et al. 2024), which constrains updates to the null space of preservation keys. The field remains active; the tension between targeted editability and general knowledge integrity has not been fully resolved.

Exercises

Exercise 31.

Let 𝐖inβˆˆβ„4Γ—2⁑ and 𝐖outβˆˆβ„2Γ—4⁑ with ReLU activation.

  1. Write MLP⁑(𝒉) for an arbitrary π’‰βˆˆβ„2⁑ as a sum of at most 4 rank-one terms, explicitly identifying the key and value vectors.

  2. Show that if 𝒉=Ξ»π’Œj/β€–π’Œjβ€–2 for some Ξ»>0, then neuron j fires with coefficient Ξ»ReLU(1). What does this imply about the relationship between input alignment and memory retrieval strength?

  3. Suppose you want to β€œerase” a memorised fact stored primarily in neuron j. Propose a minimal-norm modification to 𝐖out that zeros the contribution of neuron j while leaving neurons iβ‰ j unchanged.

Exercise 32.

Let π–βˆˆβ„mΓ—n⁑, π’Œβˆ—βˆˆβ„n⁑, π’—βˆ—βˆˆβ„m⁑, and π‚βˆˆβ„nΓ—n⁑ be a positive definite covariance.

  1. Prove that the update Δ𝐖=(π’—βˆ—βˆ’π–π’Œβˆ—)(π‚βˆ’1π’Œβˆ—)⊀/((π‚βˆ’1π’Œβˆ—)βŠ€π’Œβˆ—) satisfies (𝐖+Δ𝐖)π’Œβˆ—=π’—βˆ—.

  2. Show that among all rank-one matrices π”π’˜βŠ€ satisfying the above constraint, the one with smallest 𝐂-weighted Frobenius norm β€–π”π’˜βŠ€β€–π‚=def‖𝐔‖‖𝐂1/2π’˜β€– is exactly Δ𝐖 as defined above.

  3. Interpret the role of π‚βˆ’1 geometrically: why does multiplying π’Œβˆ— by π‚βˆ’1 β€œwhiten” the update direction?

Exercise 33.

  1. The MEMIT update has rank at most M (the batch size). Show this is true by examining the matrix dimensions.

  2. Suppose we apply MEMIT with batch size M=1. Show that the resulting update reduces to the ROME update (up to the regularisation term Ξ±).

  3. If two different edits target the same subject (same π’Œβˆ—) but different relations (different 𝒗1βˆ—,𝒗2βˆ—), can a single rank-one update satisfy both simultaneously? If not, what is the minimum rank required, and how does MEMIT handle this?

Knowledge Conflicts and Hallucination

A language model carries two kinds of knowledge simultaneously: the parametric knowledge encoded in its weights during training, and the contextual knowledge supplied by the input prompt at inference time. For the most part, these two knowledge sources agree. But sometimes they conflict: the model's weights say the population of a city is one number, while a retrieved document in the context says another. Sometimes neither source is correct. And sometimes the model fabricates a plausible-sounding but entirely false fact, an event that has come to be called hallucination.

This section develops a mechanistic account of all three phenomena. We ask: what circuits inside the transformer are responsible for resolving knowledge conflicts, and when those circuits malfunction, what goes wrong? The mechanistic perspective yields both a rigorous formal definition of hallucination and a set of principled interventions for reducing it.

Context-Memory Conflicts: The Competing Circuits View

Let 𝚌 be a retrieved context document and 𝚚 a question whose answer appears in 𝚌 but contradicts the model's parametric knowledge. For example:

  • Context: β€œAccording to recent reports, the CEO of Acme Corp is Jane Smith.”

  • Question: β€œWho is the CEO of Acme Corp?”

  • Parametric answer: John Doe (from training data).

  • Contextual answer: Jane Smith (from context).

Mechanistic interpretability research has identified two competing circuits that process these two information sources:

  • The parametric recall circuit: The same middle-layer MLP pathway identified in The ROME Hypothesis: Facts Live in Middle-Layer MLPs that routes subject-relation pairs to stored objects. This circuit fires based on the question tokens alone, ignoring the context.

  • The in-context retrieval circuit: An attention-based pathway that reads from context positions using the question tokens as queries. This circuit was first characterised in the study of induction heads (Olsson et al., 2022) and copy suppression (McDougall et al., 2023).

Knowledge conflict resolution pathways in a transformer. The parametric recall circuit (amber) reads stored facts from middle-layer MLP weights. The in-context retrieval circuit (green) reads from the input context via attention. These signals compete and are resolved by late-layer attention. Hallucination (coral) occurs when neither circuit produces a consistent, high-confidence signal and the model defaults to a learned but incorrect completion.

The late-layer attention mechanism acts as a soft resolver: it computes a weighted combination of the two signals. Let 𝒗param and 𝒗ctx be the value vectors contributed by the parametric and contextual circuits, respectively. The resolved output is approximately: (Conflict Resolve)𝒗outβ‰ˆΞ±π’—ctx+(1βˆ’Ξ±)𝒗param, where α∈[0,1] is determined by the attention weights and depends on both the strength of the contextual signal and an implicit confidence in the parametric recall. When Ξ±β‰ˆ1 the model follows the context (desirable for RAG); when Ξ±β‰ˆ0 it ignores the context (problematic).

Empirically, the value of Ξ± is strongly influenced by:

  • Salience of the context mention. If the relevant fact in the context is stated early, clearly, and multiple times, Ξ± increases.

  • Strength of the parametric association. Highly frequent training facts (e.g. capital cities of major countries) produce large ‖𝒗paramβ€–, which can dominate even when context disagrees.

  • Position in context. The notorious lost-in-the-middle effect (Liu et al., 2023) shows that facts near the beginning or end of a long context are retrieved more reliably than facts buried in the middle, suggesting that attention patterns limit the strength of 𝒗ctx for middle positions.

Chain-of-Thought and Factual Circuits

Chain-of-thought (CoT) prompting, which asks the model to reason step by step before giving a final answer, has a complex interaction with factual accuracy. On one hand, CoT enables the model to decompose multi-hop questions and retrieve each sub-fact through separate forward-pass computations. On the other hand, errors introduced in early reasoning steps can propagate and amplify, leading to a phenomenon called reasoning hallucination: the final answer is confidently wrong not because the stored facts are wrong, but because an intermediate reasoning step went astray.

The mechanistic picture is as follows. In a CoT setting, each generated token becomes part of the context for subsequent tokens. The key-value memory retrieval described in MLPs as Key-Value Memory Stores is re-applied at each new token position. If a generated intermediate token incorrectly names a subject (e.g. the model writes β€œthe Louvre is in London” as a reasoning step), then when the model next processes that token as a subject, the parametric recall circuit will look up Louvre in memory and retrieve a different set of associations, compounding the error.

Remark 25.

CoT amplifies both successes and failures of the parametric recall circuit. For multi-hop factual questions, CoT provides the model with intermediate β€œscratchpad” tokens that allow the middle-layer MLPs to be queried multiple times with the correct intermediate subjects, dramatically improving accuracy. But when the first hop yields a wrong answer, subsequent hops condition on that wrong answer, and the error propagates in a way that is invisible from the final token alone. This asymmetry motivates the study of factual consistency across reasoning steps, sometimes called reasoning faithfulness.

Hallucination as a Mechanistic Phenomenon

The popular press treats hallucination as a mysterious failure mode of AI systems. From the mechanistic interpretability perspective, it is a precisely characterisable event in the transformer's computational graph.

Definition 29 (Hallucination).

Let fΞΈ be a language model and let (s,r,otrue) be a factual association tuple where otrue is objectively correct. A hallucination for this fact occurs when the model generates a token ogenβ‰ otrue despite having had access to sufficient context (or parametric knowledge) to generate otrue. Formally, hallucination is characterised by a factual circuit divergence: the output distribution is dominated by an incorrect circuit pathway Ξ³wrong rather than the correct circuit Ξ³βˆ—: (Hallucination DEF)ogen=arg maxt⁑pΞΈ(t|πš™(s,r))β‰ otrue,whereΒ AIE(Ξ³βˆ—)<AIE(Ξ³wrong).

Key Idea.

Hallucination is not random noise - it is the model following a learned but incorrect circuit. When a model hallucinates that Napoleon was born in Paris (rather than Ajaccio), it is because the circuit activated by β€œNapoleon was born in” routes through a memory entry that incorrectly associates Napoleon with Paris, rather than through the correct entry that encodes Ajaccio. The model is, in a precise sense, confidently wrong: it is doing exactly what its circuits dictate. This is why hallucinations are often fluent, plausible, and contextually appropriate in style while being factually false.

Several distinct mechanisms can cause hallucination:

Type 1: Spurious Co-occurrence

During training, subject s co-occurred with object oβ€² in many documents, even though the correct object is o. The MLP key vector π’Œβˆ— for s has high cosine similarity with the key of oβ€², causing the wrong value to be amplified: (Spurious)βŸ¨π’Œβˆ—,π’Œoβ€²βŸ©β‰«βŸ¨π’Œβˆ—,π’Œo⟩. Example: β€œThe author of [popular novel] is [name of a different popular author who is frequently mentioned in the same reviews]”.

Type 2: Retrieval Head Failure

In the context-memory conflict model , the in-context retrieval circuit has Ξ±β‰ˆ0: the model ignores a context that contains the correct answer. This happens when the context is long, the relevant span is in the middle, or the question is phrased differently from the context sentence.

Type 3: Out-of-Distribution Subject

The subject s appeared rarely in training data, so its key vector π’Œβˆ— has low norm or is near-orthogonal to all stored value vectors. The model defaults to generating a plausible continuation based on surface patterns (the relation r) rather than factual recall. This is why models hallucinate more for obscure entities than famous ones.

Knowledge Evolution During Training

Facts are not learned uniformly during training. The order and frequency of exposure dramatically affects what is stored and how strongly. Several regularities have been identified:

  • Frequent facts are learned early. In a curriculum ordered by document date, the model quickly encodes facts that appear in thousands of documents. The MLP key-value pairs for such facts have large β€–π’Œβˆ—β€– and their value vectors point strongly toward the correct token.

  • Rare facts are learned late and weakly. A fact that appears in only a handful of documents may never be strongly encoded; its value vector remains near the mean of the value distribution, producing uncertain predictions.

  • Temporal displacement. If a fact changes over time (e.g. the president of a country), the model will encode the most recent version it saw most frequently, not necessarily the most recent one chronologically. A model trained on data from 2015–2023 may have seen a particular leader's name far more often in 2015–2020 documents than in 2021–2023 ones, causing it to prefer the older answer.

These dynamics can be formalised using the gradient flow perspective. Consider a simplified single-layer MLP with one fact (s,r,o). The cross-entropy loss for this fact at training step t is: (Training LOSS)β„’t=βˆ’log⁑softmax⁑(𝐖outΟƒ(𝐖in𝒉))o. The gradient with respect to 𝐖out is (Training Gradient)βˆ‡π–outβ„’t=βˆ’(1βˆ’pt(o))Οƒ(𝐖in𝒉)𝒆o⊀+βˆ‘oβ€²β‰ opt(oβ€²)Οƒ(𝐖in𝒉)𝒆oβ€²βŠ€, where pt(o) is the current model probability and 𝒆o is the one-hot embedding of object token o. The update has the form of a rank-one correction: the column 𝒗o=(𝐖out):,o is moved toward the current key activation. Thus each gradient step incrementally sharpens the key-value association. Infrequently presented facts receive few such steps and remain weakly encoded.

Catastrophic Forgetting and Its Mechanistic Basis

When a neural network is trained sequentially on two tasks or two corpora, knowledge from the first task is often erased by training on the second. This phenomenon, known as catastrophic forgetting (McCloskey and Cohen, 1989), has a clean mechanistic interpretation in the key-value memory framework.

Suppose the model has encoded a fact (s1,r,o1) at layer lβˆ— via the key-value pair (π’Œ1,𝒗1). Now we fine-tune the model on a new corpus that presents a different fact (s2,r,o2). If s2 is similar to s1, their key vectors π’Œ1β‰ˆπ’Œ2 will be close in the MLP's input space. The gradient update for the new fact will shift 𝐖out in the direction of 𝒗2, but since the update direction is π’Œ2β‰ˆπ’Œ1, it simultaneously shifts the response to π’Œ1. Concretely, if the rank-one update for fact 2 is Δ𝐖=(𝒗2βˆ’π–π’Œ2)π’Œ2⊀/β€–π’Œ2β€–2, then the model's output for fact 1 becomes: (Forgetting)(𝐖+Δ𝐖)π’Œ1=π–π’Œ1+(𝒗2βˆ’π–π’Œ2)π’Œ2βŠ€π’Œ1β€–π’Œ2β€–2. The second term is nonzero whenever π’Œ1 and π’Œ2 are non-orthogonal, i.e., whenever the two subjects share semantic features (which is the norm rather than the exception in natural language). The original value π–π’Œ1β‰ˆπ’—1 is partially overwritten by 𝒗2, degrading recall of fact 1.

Definition 30 (Interference Score).

For two facts (s1,r,o1) and (s2,r,o2) with key vectors π’Œ1,π’Œ2 at the target MLP layer, the interference score is: (Interference Score)ℐ(1,2)=|π’Œ1βŠ€π’Œ2|β€–π’Œ1β€–β€–π’Œ2β€–=|cos⁑(π’Œ1,π’Œ2)|. A high interference score predicts that learning fact 2 will degrade recall of fact 1 proportionally, and vice versa.

This perspective immediately suggests remedies:

  • Regularisation. Penalise changes to weight dimensions that are active for previously learned facts (analogous to Elastic Weight Consolidation, Kirkpatrick et al., 2017).

  • Orthogonal updates. Restrict weight updates to the null space of old key vectors (as in PackNet, Mallya and Lazebnik, 2018, or the OWM method of Zeng et al., 2019).

  • Rehearsal. Replay a subset of old facts during fine-tuning to maintain their key-value associations.

Remark 26.

The mechanistic analysis of forgetting developed here connects directly to the continual learning framework of 26. There, catastrophic forgetting is addressed from the perspective of task boundaries, training distributions, and replay buffers. The key-value memory view adds a finer-grained account: forgetting is most severe when new facts have high interference scores with old ones, and mitigation strategies that reduce interference (e.g. by keeping new key vectors orthogonal to old ones) have a direct mechanistic justification. Conversely, the continual learning literature's insight that rehearsal is highly effective translates mechanistically into maintaining the key-value associations for rehearsed facts, preventing their degradation.

Interventions for Reducing Hallucination

The mechanistic account of hallucination points to several targeted interventions:

Activation Steering

Given a direction 𝒅 in residual-stream space associated with honest/factual behaviour (identified via contrastive activation analysis), one can steer the model toward that direction at inference time by adding α𝒅 to the residual stream at a designated layer. This technique, called representation engineering (Zou et al., 2023), has been shown to reduce hallucination rates on factual QA benchmarks by up to 40% without any weight update.

Formally, if 𝒉(l) is the residual stream at layer l, we apply: (ACT Steering)𝒉(l)←𝒉(l)+α𝒅^,𝒅^=𝒅‖𝒅‖, where 𝒅 is estimated as the mean difference between hidden states on honest vs. hallucinating completions in a calibration set.

Contrastive Decoding

A model that has been lightly fine-tuned on synthetic hallucinations acts as an β€œamateur” model fΞΈa that over-expresses hallucination tendencies. Contrastive decoding generates tokens that maximise: (Contrastive Decoding)log⁑pΞΈexpert(t|πš™)βˆ’Ξ²log⁑pΞΈamateur(t|πš™), with hyperparameter Ξ²>0. The subtraction effectively suppresses tokens that the amateur (hallucinating) model prefers, directing the expert model away from its own hallucination-prone regions.

Uncertainty-Based Abstention

If the model's predictive entropy for a given factual query exceeds a threshold, the model abstains rather than generating a potentially false answer. The predictive entropy is: (PRED Entropy)𝖧⁑[t|πš™]=βˆ’βˆ‘tpΞΈ(t|πš™)log⁑pΞΈ(t|πš™). High entropy signals that no single circuit is dominant, which corresponds mechanistically to the case where both ‖𝒗paramβ€– and ‖𝒗ctxβ€– are small or they roughly cancel. Abstention in this regime avoids presenting a low-confidence guess as a confident fact.

The Forgetting Problem at Scale

For large language models trained on internet-scale data, catastrophic forgetting takes on a new character. During pre-training on a single large corpus, facts encountered early in the training schedule can be partially overwritten by later training steps. In the regime of very large models (100B+ parameters), the MLP layers have sufficient capacity that individual facts are each encoded by a small subset of neurons; the key vectors for unrelated facts tend to be nearly orthogonal simply due to the high dimensionality (Johnson-Lindenstrauss phenomenon). This greatly reduces interference.

However, during fine-tuning (e.g. supervised instruction tuning or RLHF), the model is trained on a much narrower distribution. The fine-tuning gradient steps are concentrated on a small set of task distributions, causing large updates to the MLP layers that are relevant for those tasks. Facts not covered in the fine-tuning distribution can be overwritten. This is sometimes called alignment tax: improving instruction-following or safety behaviour degrades raw factual accuracy.

Concretely, the LIMA paper (Zhou et al., 2023) observed that even very short fine-tuning (1000 examples) can substantially shift the model's factual output distribution. The mechanistic account predicts exactly this: 1000 gradient steps on a narrow distribution produce 1000 rank-one-like updates, each of which potentially interferes with the broader set of encoded facts.

Exercises

Exercise 34.

Consider a transformer with the conflict resolution model 𝒗out=α𝒗ctx+(1βˆ’Ξ±)𝒗param from .

  1. Suppose 𝒗ctx=𝒆London (unit vector toward β€œLondon”) and 𝒗param=𝒆Paris (unit vector toward β€œParis”), and that the token prediction head maps 𝒗out to a logit by β„“t=𝒆tβŠ€π’—out. For what value of Ξ± does the model assign equal probability to London and Paris?

  2. Now suppose there are K other cities with equal representation in 𝒗param: 𝒗param=𝒆Paris/2+βˆ‘k=1K(𝒆ck/(2K)). How does increasing K affect the threshold Ξ± at which the contextual answer wins?

  3. Propose a simple architectural intervention, modifiable at inference time, that would increase Ξ± for all queries simultaneously, and discuss any potential trade-offs.

Exercise 35.

Let π–βˆˆβ„dΓ—d⁑ be the output weight of an MLP, and suppose two facts are encoded: fact 1 with key π’Œ1 and value 𝒗1, and fact 2 with key π’Œ2 and value 𝒗2. Assume π–π’Œi=𝒗i for i=1,2 and π’Œ1βŸ‚π’Œ2.

  1. Show that the rank-one update to insert fact 2 does not disturb fact 1 when π’Œ1βŸ‚π’Œ2.

  2. Now suppose a third fact (s3,r,o3) has key π’Œ3=(π’Œ1+π’Œ2)/2 (equidistant between π’Œ1 and π’Œ2). Compute the change in π–π’Œ1 after the rank-one update that inserts fact 3 with value 𝒗3. Express your answer in terms of 𝒗3, 𝒗1, and the interference score ℐ(1,3).

  3. How does the interference score framework suggest we should design the training curriculum to minimise catastrophic forgetting? Relate your answer to the notion of an orthogonal basis for the fact space.

Exercise 36.

  1. Using the AIE formalism from , describe an experimental protocol to determine whether a model is hallucinating due to Type 1 (spurious co-occurrence), Type 2 (retrieval head failure), or Type 3 (out-of-distribution subject) hallucination. What interventions (corruptions and restorations) would you perform, and what pattern of AIE values would you expect for each type?

  2. Consider the contrastive decoding objective . Show that for a fixed context and β=1, the decoding target simplifies to log⁑[pexpert(t)/pamateur(t)]. Interpret this as a likelihood ratio test with a specific null and alternative hypothesis.

  3. Suppose you can identify, for each hallucinated token, the attention head responsible (i.e. the head with the highest positive attribution to the wrong token). Propose a method to selectively suppress only those heads during inference, and discuss why complete suppression might be undesirable.

VLM Interpretability and Cross-Modal Alignment

The interpretability toolkit developed for pure language models rests on a foundational assumption: that the objects under study are sequences of discrete tokens, each occupying a well-defined position in a shared vocabulary whose statistics can be probed, steered, and ablated. Logit-lens projections presuppose that intermediate representations are already trying to predict a vocabulary item. Activation patching presupposes that a causal model of token-to-token influence captures the dominant information flow. Even probing classifiers, the most assumption-light tool in the box, typically operate on representations that live in a single homogeneous residual stream.

Vision-language models (VLMs) shatter these assumptions. A modern VLM such as LLaVA, InternVL, or GPT-4V processes two fundamentally different information streams simultaneously: a sequence of visual patch embeddings extracted by a vision encoder and a sequence of linguistic tokens processed by a language backbone. The two streams are fused through a projection layer (often a simple linear map or a small MLP) that maps visual features into the token embedding space of the language model. The resulting architecture is not a language model with images bolted on; it is a hybrid system in which the inductive biases of convolutional or attention-based vision encoders interact with the statistical geometry of a pre-trained language model.

The language-centric bias problem is the observation that almost every existing interpretability tool is calibrated for the linguistic modality and fails gracefully-or fails silently-when applied to the visual modality. Logit-lens projections of visual patch embeddings produce vocabulary distributions that are typically incoherent, because visual patch tokens are not expected to predict the next word; they are expected to encode spatial features. Attention head analyses developed for text transformers frequently mis-attribute visual attention patterns to roles that have no linguistic analogue. Even the vocabulary of mechanistic interpretability-circuits, features, subspaces-was developed with text in mind and requires careful reinterpretation when the model processes images.

This section develops the emerging theory of VLM interpretability, focusing on three themes that have produced the most conceptual traction: the cross-modal structure of task representations, the dynamics of modality fusion in the residual stream, and the three-stage evolution of visual representations as they traverse a VLM's layers.

The Language-Centric Bias Problem

To make the language-centric bias precise, consider a VLM fΞΈ:𝒳vis×𝒳txt→𝒳txt that takes a visual input π’—βˆˆπ’³vis and a textual prompt π’•βˆˆπ’³txt and produces a textual response. Internally, the model processes a concatenated token sequence (Tokens)𝒔=[𝒗1,…,𝒗P⏟visualΒ patches,𝒕1,…,𝒕L⏟textΒ tokens], where P is the number of visual patch tokens and L is the length of the text prompt. Each token si is associated with a residual stream 𝒉i(β„“)βˆˆβ„d⁑ at layer β„“.

The logit-lens projects 𝒉i(β„“) into vocabulary space via the unembedding matrix 𝐖Uβˆˆβ„|𝒱|Γ—d⁑: (Logitlens)pi(β„“)=softmax⁑(𝐖U𝒉i(β„“)). For text tokens at late layers, pi(β„“) typically concentrates on semantically plausible vocabulary items-the prediction sharpens as the layer index increases. For visual patch tokens, pi(β„“) remains diffuse and lacks semantic coherence even at late layers, because the visual patches are never the subject of a next-token prediction objective: the model is not trying to predict what word follows a patch.

Remark 27 (Distributional Mismatch in Visual Tokens).

The failure of the logit lens on visual patches is not a failure of the probe; it is a diagnostic. It reveals that visual representations do not live in the same subspace of ℝd⁑ as linguistic representations even when they share the same ambient dimension. The geometry of the residual stream is stratified: language tokens cluster in one region, visual tokens cluster in another, and the projection layer acts as a bridge rather than an identification. Tools designed for the linguistic stratum cannot simply be applied to the visual stratum without modification.

This distributional mismatch motivates the search for interpretability tools that are modality-agnostic: they should probe the residual stream in a way that does not presuppose token-predictive semantics. The discovery of task vectors is one such tool.

Cross-Modal Task Representations: Task Vectors

The concept of a task vector originated in the context of weight-space arithmetic for language model fine-tuning: if 𝜽0 are pre-trained weights and 𝜽FT are fine-tuned weights, the task vector 𝜽FTβˆ’πœ½0 captures the β€œdirection” in weight space associated with the fine-tuning task. Adding this vector to a different model's weights transfers some of the task's properties.

The work of Luo et al. (2025) introduces a different, activation-space notion of task vectors that is directly relevant to VLM interpretability. They observe that when a language model processes a few-shot prompt encoding a task (e.g., β€œtranslate English to French”), the residual stream at a specific layer develops a low-dimensional representation that encodes the task itself, largely independently of the specific examples used to illustrate it. This task representation, once extracted, can be transplanted into a different forward pass to steer the model's behaviour without any explicit prompt.

Definition 31 (Task Vector).

Let fΞΈ be a transformer with L layers and residual stream dimension d. Given a few-shot prompt 𝒕=(x1,y1,…,xk,yk,xq) encoding k input-output examples of a task Ο„ followed by a query xq, define the task vector at layer β„“ as (TV)𝝉(β„“)=1kβˆ‘i=1k𝒉yi(β„“)(𝒕)βˆˆβ„d⁑, where 𝒉yi(β„“)(𝒕) is the residual stream at layer β„“ at the position of the i-th output token yi when the model processes 𝒕.

Three properties of task vectors, empirically verified by Luo et al., make them particularly useful for VLM interpretability:

  1. Task specificity. Task vectors for different tasks (Ο„1β‰ Ο„2) are approximately orthogonal: 𝝉1(β„“)⋅𝝉2(β„“)β‰ˆ0.

  2. Example invariance. The task vector is stable across different choices of few-shot examples: replacing (x1,y1,…) with a different set of examples for the same task changes 𝝉(β„“) by a small perturbation.

  3. Cross-modal transferability. A task vector derived from a textual few-shot prompt can be patched into the forward pass of a visual task to guide the model's behaviour.

Property 3 is the most surprising and the most important for VLM interpretability. It implies that the abstract representation of a task-what it means to perform colour recognition, object counting, or spatial reasoning-is encoded in a modality-agnostic subspace of the residual stream.

Task Vector Invariance Across Modalities

The formal statement of cross-modal invariance requires a careful definition of what it means for a textual and a visual instantiation of a task to share the same task vector.

Let Ο„ be a task (e.g., β€œidentify the dominant colour of the object”). Consider two few-shot prompts:

  • A textual prompt 𝒕txt that encodes the task through text descriptions: β€œThe ball is red. Dominant colour: red. The sky is blue. Dominant colour: blue. The grass is ”.

  • A visual prompt 𝒕vis that encodes the same task through image-caption pairs: images of coloured objects captioned with their dominant colour.

Define the textual task vector 𝝉txt(β„“) and the visual task vector 𝝉vis(β„“) by applying Definition 31 to the two prompts respectively. The cross-modal alignment score at layer β„“ is (Alignment)A(β„“)(Ο„)=𝝉txt(β„“)⋅𝝉vis(β„“)‖𝝉txt(β„“)‖‖𝝉vis(β„“)β€–, measuring the cosine similarity between the textual and visual task vectors at layer β„“.

Proposition 6 (Layer-Dependent Cross-Modal Alignment).

Empirically, for VLMs fine-tuned from a pre-trained language backbone, A(β„“)(Ο„) exhibits a characteristic profile: it is low in early layers (where modality-specific processing dominates), rises sharply in middle layers (where the residual stream is predominantly linguistic), and remains high in later layers. The peak alignment occurs near the layer at which the logit-lens first produces semantically coherent text predictions.

This proposition, while stated here as an empirical observation, has a structural explanation: the projection layer that maps visual patch embeddings into the language backbone's token space initialises the visual residual stream in the language model's representation space. From the perspective of the language backbone's upper layers, visual tokens are simply unusual text tokens. The task vector, which is defined over the language backbone layers, therefore reflects a linguistic encoding of the visual task.

Patching Task Vectors Across Modalities

The utility of cross-modal task vectors is demonstrated through a patching experiment: a textual task vector is derived from a textual few-shot prompt and then injected into a visual forward pass. Formally:

  1. Run the model on a textual few-shot prompt 𝒕txt for task Ο„, extracting 𝝉txt(β„“βˆ—) at a chosen layer β„“βˆ—.

  2. Run the model on a zero-shot visual query 𝒕qvis (an image with a short question, no examples). At layer β„“βˆ—, add the task vector to the query token's residual stream: (Patch)𝒉~q(β„“βˆ—)=𝒉q(β„“βˆ—)+λ𝝉txt(β„“βˆ—), where Ξ»>0 is a scaling hyperparameter.

  3. Continue the forward pass from layer β„“βˆ—+1 with the modified residual stream and observe the model's output.

The effect of this patching operation is dramatic: a model that produces a generic or incorrect answer to the visual query in the unpatched setting often produces a task-appropriate answer after patching, even though no visual examples of the task were provided. The textual task vector has β€œreminded” the model what task it is performing.

Example 7 (Cross-Modal Colour Task Patching).

Consider a VLM presented with an image of a red apple and asked β€œWhat is the dominant colour?” Without any few-shot context, the model might answer β€œIt is a fruit” (failing to focus on colour). Construct a textual task vector for the colour identification task from five text-only examples. Patch this vector into the model's residual stream at the query position at layer β„“βˆ—=16 (mid-depth for a 32-layer model) with Ξ»=1.5. The model now answers β€œThe dominant colour is red.” The textual task vector has successfully activated the model's colour-identification circuit in the visual context.

The success of cross-modal patching has a mechanistic interpretation. The patch operation in (Patch) shifts the query token's residual stream in the direction of the task-encoding subspace. Because the language backbone was pre-trained to use this subspace for task representation, the shift induces the same task-appropriate processing regardless of whether the input is textual or visual.

Transfer from Base LLM to Fine-Tuned VLM

A further surprising finding is that task vectors computed from a base language model (before any visual fine-tuning) can be transferred to the VLM derived from it. If fΞΈLLM is the base language model and fΞΈVLM is the VLM obtained by adding a vision encoder and projection layer and fine-tuning, the task vectors derived from fΞΈLLM are often effective when patched into fΞΈVLM.

This transferability arises because visual fine-tuning preserves the language backbone's representation geometry: the weights of the language backbone change relatively little during VLM fine-tuning (typical norms of weight updates are one to two orders of magnitude smaller than the original weight norms), and the task-encoding subspace is consequently preserved.

Remark 28 (Visual Fine-Tuning as a Minimal Perturbation).

The preservation of task vectors across fine-tuning is evidence for the broader claim that visual fine-tuning adds a new input modality to a language model without substantially restructuring its reasoning mechanisms. The model learns to translate visual inputs into its existing linguistic representation space but does not reorganise the space itself. This has a practical implication: the rich literature on language model interpretability can be partially ported to VLMs by studying the language backbone's task-encoding geometry.

TikZ Figure: Task Vector Extraction and Cross-Modal Transfer

Task vector extraction and cross-modal transfer. A textual few-shot prompt (top path, blue) is processed through the language model to extract a task vector 𝝉txt(β„“) by averaging residual streams at output positions. A visual zero-shot query (bottom path, green) is processed through the VLM's vision encoder and projection layer. At layer β„“βˆ—, the textual task vector is added to the query token's residual stream (amber dashed arrow), steering the model to produce a task-appropriate output without any visual examples.

Probing VLM Layers: Modality Prioritisation and Asymmetric Fusion

Beyond task vectors, linear probes offer a complementary window into VLM internals. Given a set of labelled inputs (si,yi) where si is a VLM input (image-text pair) and yi is a ground-truth label for some property of interest (e.g., object category, spatial relation, sentiment), a linear probe at layer β„“ is a logistic regressor: (Probe)y^i(β„“)=Οƒ(𝐖probe(β„“)𝒉i(β„“)+b), trained to minimise cross-entropy loss. The probe accuracy as a function of layer β„“ and token type (visual vs. text) reveals the information routing strategy of the VLM.

Systematic probing across multiple VLM architectures reveals two consistent patterns:

Modality prioritisation.

For tasks that are primarily visual (object classification, colour identification, spatial relation detection), the task-relevant information is concentrated in the visual patch tokens in early layers. By mid-depth, however, the task information has migrated to the query text tokens. This migration-from patches to text-reflects the VLM's strategy of translating visual content into linguistic representations before generating a response.

Asymmetric fusion.

The flow of information between visual and text tokens is asymmetric. Visual patch tokens attend heavily to each other in early layers (local spatial processing) and then attend to text tokens in middle layers (semantic grounding). Text query tokens attend to visual patch tokens throughout but most heavily in middle layers. The resulting attention pattern resembles a funnel: spatial detail flows up from patches into global semantic representations, which are then queried by the text tokens to produce the final answer.

Remark 29 (Implications for Sparse Attention Architectures).

The asymmetric fusion pattern suggests that not all attention heads are equally important for cross-modal integration. A small subset of β€œbridge heads” in middle layers carry most of the visual-to-text information. Pruning all other heads preserves most of the VLM's cross-modal capability. This has practical implications for efficient inference: VLMs can be made significantly more efficient by identifying and preserving bridge heads while applying more aggressive pruning to the remaining heads.

The Logit Lens for VLMs: Three-Stage Evolution

While the standard logit lens fails on visual patch tokens, a modified logit lens for VLMs can be defined that operates on the text query tokens rather than the patch tokens. Tracking the logit-lens distribution of the query token 𝒉q(β„“) as β„“ increases from 0 to L reveals a characteristic three-stage evolution.

Stage 1: Alignment (β„“βˆˆ[0,L/3]).

In the early layers, the query token's logit-lens distribution is broad and unsettled, reflecting the model's uncertainty about the task. However, the distribution is not random: it concentrates on tokens semantically related to the visual content. If the image contains a cat, the distribution assigns elevated probability to β€œcat”, β€œfeline”, β€œkitten”, β€œanimal”, and related tokens. This stage represents the alignment of linguistic representations with visual content: the VLM is mapping what it β€œsees” into the vocabulary of what it β€œknows”.

Stage 2: Processing (β„“βˆˆ[L/3,2L/3]).

In the middle layers, the distribution narrows around task-relevant tokens. If the task is colour identification, the early-layer semantic alignment (β€œcat”) is replaced by colour-relevant tokens (β€œorange”, β€œbrown”, β€œstriped”). This stage reflects the activation and application of the task representation: the model has identified the relevant task and is extracting the appropriate features.

Stage 3: Selection (β„“βˆˆ[2L/3,L]).

In the late layers, the distribution collapses onto a small set of high-probability tokens that will constitute the answer. The uncertainty of the middle layers-oscillating among several plausible answers-resolves into a confident prediction. This stage mirrors the token-selection dynamics observed in pure language models and reflects the VLM's finalisation of its output.

Key Idea.

Three-Stage VLM Processing. The modified logit lens applied to the query token of a VLM reveals three stages: an alignment stage in which visual content is mapped into linguistic space, a processing stage in which task-relevant features are extracted from the aligned representation, and a selection stage in which the final answer is crystallised. The transition between stages is modulated by the task vector: patches of task vectors accelerate the transition from alignment to processing.

VLMs Anchor Visual Representations in Linguistic Geometry

The three-stage logit-lens evolution, the asymmetric fusion pattern, and the cross-modal transferability of task vectors all converge on a single organising principle:

Key Idea.

Linguistic Anchoring of Visual Representations. VLMs do not develop an independent visual representation geometry. Instead, they anchor visual representations in the pre-existing linguistic geometry of the language backbone. The projection layer that maps visual patch embeddings into the language model's token space initialises visual representations as points in the language model's representation manifold, and subsequent processing refines these points within the linguistic geometry rather than departing from it. The consequence is that VLMs β€œthink in language” even about visual content: their internal representations of visual concepts are linguistic concepts that happen to have been activated by visual inputs.

This anchoring hypothesis has several testable predictions. First, the cosine similarity between the residual stream representations of a concept presented visually (an image of a cat) and the same concept presented linguistically (the token β€œcat”) should be high in mid-to-late layers. Second, the language model's geometry-its organisation of concepts into directions, clusters, and subspaces- should be preserved in the VLM and accessible through standard linguistic probes. Third, the VLM's visual understanding should be bounded by its linguistic knowledge: visual concepts for which the language model has no linguistic representation should be difficult to process correctly.

All three predictions have been confirmed empirically in recent probing studies, providing strong evidence for the linguistic anchoring view.

Exercises

Exercise 37 (Cross-Modal Alignment Score).

Let fΞΈ be a VLM with 24 transformer layers. You are given a task Ο„ (identifying the dominant shape of an object) and compute textual task vectors 𝝉txt(β„“) and visual task vectors 𝝉vis(β„“) for β„“βˆˆ{1,6,12,18,24}. The cross-modal alignment scores A(β„“)(Ο„) are: 0.12, 0.31, 0.68, 0.72, 0.70.

  1. At which layer does the alignment transition from low to high? Provide a mechanistic interpretation in terms of the VLM's projection layer.

  2. Suppose you apply the patch operation from (Patch) at β„“βˆ—=6 versus β„“βˆ—=12. Based on the alignment scores, which choice is likely to produce a stronger task-transfer effect? Justify your answer.

  3. If the alignment at layer 12 drops to 0.15 for a different task Ο„β€², what does this suggest about the nature of Ο„β€²? Give an example of a visual task for which such low alignment would be expected.

Exercise 38 (Task Vector Orthogonality).

Suppose you extract task vectors 𝝉1,𝝉2,𝝉3βˆˆβ„d⁑ for three tasks: colour identification, object counting, and spatial relation detection. Define the Gram matrix π†βˆˆβ„3Γ—3⁑ with entries Gij=𝝉i⋅𝝉j/(‖𝝉i‖‖𝝉jβ€–).

  1. If the task vectors are perfectly orthogonal, what is 𝐆?

  2. In practice, 𝐆 is approximately but not perfectly diagonal. Explain why small off-diagonal entries arise and what they indicate about the relationship between the tasks.

  3. Propose a method to orthogonalise the task vectors (e.g., using Gram-Schmidt) and argue whether this would improve or harm the patching performance in (Patch).

Exercise 39 (Logit Lens Stage Detection).

Given a VLM with L=32 layers, you observe the following entropy of the logit-lens distribution at the query token: H(β„“)=𝖧⁑(pq(β„“))=βˆ’βˆ‘vβˆˆπ’±pq,v(β„“)log⁑pq,v(β„“). The values are: H(1)=11.2, H(8)=10.8, H(16)=7.3, H(24)=3.1, H(32)=0.9.

  1. Match the entropy profile to the three-stage model (alignment, processing, selection) developed in The Logit Lens for VLMs: Three-Stage Evolution. Identify the approximate layer boundaries between stages.

  2. Suppose an adversary wants to maximally confuse the model by patching a task vector that is orthogonal to the true task at layer 16. Using the definition in (Patch) with Ξ»=2, describe the expected effect on H(32).

  3. Explain why monitoring H(β„“) across layers could serve as an efficient diagnostic for VLM hallucination: high entropy at stage 3 (β„“>2L/3) is a warning sign.

Vision SAEs and the Prisma Framework

Sparse autoencoders (SAEs) have emerged as one of the most productive tools in language model interpretability. Trained on the residual stream activations of a frozen language model, an SAE learns a dictionary of features-directions in activation space that activate for semantically coherent, human-interpretable concepts. A residual stream vector π’‰βˆˆβ„d⁑ is decomposed as: (SAE)π’‰β‰ˆβˆ‘k=1Kak𝒇k=𝐅𝒂, where 𝐅=[𝒇1,…,𝒇K]βˆˆβ„dΓ—K⁑ is the feature dictionary, 𝒂=[a1,…,aK]βŠ€βˆˆβ„β‰₯0K⁑ is the sparse activation vector (most entries zero), and K≫d is the overcomplete dictionary size. Training minimises the sparse reconstruction loss: (LOSS)β„’SAE=𝔼𝒉[β€–π’‰βˆ’π…π’‚β€–22+α‖𝒂‖1], where Ξ±>0 controls sparsity.

The transition to vision models introduces qualitative differences that demand careful redesign. This section develops the theory of vision SAEs, introduces the Prisma framework that makes vision SAE research practical at scale, and examines two phenomena unique to visual feature representations: CLS token dynamics and the surprising regularisation effect of SAE reconstruction.

Why Vision Needs Denser Features Than Language

The success of language SAEs rests on a property of linguistic representation that does not hold for vision: token discreteness. A language model processes a sequence of discrete tokens drawn from a finite vocabulary. Each token has a relatively well-defined semantic interpretation, and the features learned by a language SAE tend to activate for specific tokens or token categories. Sparsity in language SAEs reflects the fact that, at any given position, only a small number of semantically relevant features are active.

Visual inputs are fundamentally different. A pixel is not a discrete symbol; it is a sample from a continuous signal. A patch of pixels encodes not a single semantic concept but a superposition of many partially overlapping concepts: texture, colour, edge orientation, lighting condition, object boundary, semantic category, depth cue, and more. These concepts do not occur in isolation; they co-occur continuously and with graded intensity.

Insight.

Feature Density in Vision vs. Language. Vision SAEs must be denser than language SAEs because visual features overlap. Language tokens are discrete-a token is either β€œcat” or β€œdog”, not a mixture-so the features needed to represent any single token activate sparsely. Pixels are continuous-a patch can be simultaneously somewhat orange, somewhat textured, somewhat circular-so the features needed to represent any single patch co-activate densely. A vision SAE trained with the same sparsity penalty Ξ± as a language SAE will under-reconstruct the visual signal; the sparsity must be relaxed, the dictionary size increased, or both.

This density requirement has a corollary: vision SAE features are less monosemantic than language SAE features. A language SAE feature might activate only for the token β€œpresident” in political contexts. A vision SAE feature might activate for orange-coloured regions, which could be sunsets, traffic cones, autumn leaves, or orange fruits. The partial overlap of visual concepts means that perfect monosemanticity is unattainable; the best vision SAEs can achieve is relative monosemanticity: features that are more semantically coherent than the original polysemantic neurons.

To quantify the required density, define the average feature activation count kβ€Ύ as the expected number of active features per input: (Density)kβ€Ύ=𝔼𝒉[‖𝒂‖0]=𝔼𝒉[βˆ‘j=1K𝟏[aj>0]]. Empirically, language SAEs achieve good reconstruction with kβ€Ύβ‰ˆ20–50 active features per token (out of Kβ‰ˆ50000–100000 total features). Vision SAEs require kβ€Ύβ‰ˆ100–300 active features per patch token to achieve comparable reconstruction quality, a five-to-ten-fold increase in density.

The Prisma Toolkit

Training SAEs across many architectures, layers, and token types is a substantial engineering undertaking. The Prisma toolkit is an open-source framework designed to make vision SAE research practical at scale. It provides three core capabilities: activation caching, SAE training across diverse architectures, and a unified evaluation suite.

Activation caching.

Prisma caches the activations of any vision transformer layer for an entire dataset in a compressed format. Given a vision transformer fΞΈ and a dataset π’Ÿ={x1,…,xN}, Prisma computes β„‹(β„“)={𝒉i(β„“)}i=1N for each layer β„“ of interest and stores the result on disk. The caching step is run once per model-dataset pair, and subsequent SAE training reads from the cache rather than running the vision transformer, reducing compute costs by an order of magnitude.

Architectural coverage.

Prisma supports over 75 vision transformer architectures, including ViT, DeiT, DINO, DINOv2, CLIP-ViT, MAE, and their variants across scales from ViT-Small to ViT-Giant. The architectural diversity is important because vision SAE features are not universal: a feature that is monosemantic in a DINO-trained ViT may be polysemantic in a CLIP-trained ViT, reflecting the different pre-training objectives. Comparing SAEs across architectures makes it possible to identify which features are stable across training regimes (suggesting they reflect intrinsic properties of the visual world) and which are architecture- or training-specific.

Evaluation suite.

Prisma provides a unified evaluation suite that measures SAE quality along four dimensions:

  • Reconstruction fidelity: the variance explained R2=1βˆ’β€–π’‰βˆ’π…π’‚β€–22/‖𝒉‖22.

  • Downstream task performance: accuracy of linear probes trained on SAE features rather than raw activations.

  • Feature interpretability: the fraction of features that receive consistent natural-language descriptions from human annotators.

  • Feature utilisation: the fraction of features that activate on at least one example in the evaluation set (the complement of the dead feature fraction).

CLS Token Dynamics: Spatial to Global

Vision transformers (ViTs) append a special [CLS] token to the sequence of patch tokens. The CLS token's final representation is used as the global image representation for downstream tasks (e.g., classification). Understanding how the CLS token develops its global representation across layers is a central question in ViT interpretability.

Prisma SAEs trained at each layer of a ViT reveal a striking evolution. In early layers (β„“<L/4), the CLS token's SAE decomposition activates features associated with specific spatial patches: the CLS token is not yet global; it attends to and summarises a small neighbourhood of patches. In middle layers (β„“βˆˆ[L/4,3L/4]), the CLS token's activated features broaden to cover larger spatial regions, and abstract semantic features (object category, scene type) begin to appear. In late layers (β„“>3L/4), the CLS token's representation is dominated by global, task-relevant features with little remaining spatial specificity.

Definition 32 (CLS Spatial Specificity).

For a ViT processing an image with P patches, define the CLS spatial specificity at layer β„“ as (Spatial)S(β„“)=maxp∈[P]⁑ACLS(β„“)(p)1Pβˆ‘p=1PACLS(β„“)(p), where ACLS(β„“)(p) is the average attention weight from the CLS token to patch p at layer β„“ (averaged over all attention heads). High S(β„“) indicates that the CLS token's attention is concentrated on a small number of patches; low S(β„“) indicates diffuse, global attention.

Empirically, S(β„“) starts high (around 10–20 for a ViT-Base with 196 patches), decreases through the middle layers, and approaches 1 (uniform attention) at the final layers. The trajectory of S(β„“) is the attention signature of the global-to-local transition: the CLS token begins by attending locally and progressively integrates information from all patches.

Dead Feature Analysis and Information Flow

A dead feature in an SAE is a dictionary vector 𝒇k that activates on zero (or near-zero) fraction of the evaluation set. Dead features are a training pathology: they represent wasted capacity, directions in the overcomplete dictionary that the SAE has learned but that the model's activations never use.

The fraction of dead features fdead(β„“) varies significantly across layers. For vision SAEs trained on patch tokens, fdead(β„“) is low in early layers (nearly all features are utilised because early-layer patch activations are diverse and high-dimensional) and rises in later layers (as patch activations become more stereotyped and globalised). For the CLS token, the pattern is reversed: fdead(β„“) is high in early layers (the CLS token has not yet accumulated much information) and falls in later layers (as the CLS token absorbs information from all patches).

Proposition 7 (Dead Feature Complementarity).

Let fdead,patch(β„“) and fdead,CLS(β„“) be the dead feature fractions for patch token SAEs and CLS token SAEs at layer β„“. Empirically, these quantities are approximately complementary: (DEAD)fdead,patch(β„“)+fdead,CLS(β„“)β‰ˆC, for a constant Cβ‰ˆ0.7–0.9 that is roughly stable across layers. The complementarity reflects the information transfer from patches to CLS: as the CLS token absorbs more information (reducing its dead feature fraction), the patch tokens become more stereotyped (increasing their dead feature fraction).

This complementarity is not a precise mathematical identity but a robust empirical regularity that holds across DINO, CLIP, and MAE pre-trained ViTs. It provides a non-invasive diagnostic for the layer at which information transfer from patches to the CLS token is most active: the layer at which the slopes of fdead,patch(β„“) and fdead,CLS(β„“) are most steeply negative and positive, respectively.

TikZ Figure: Information Flow from Patches to CLS Token

Information flow from spatial patch tokens to the CLS token across layers of a vision transformer. Arrow thickness (patches to CLS) represents the strength of attention from the CLS token to patches, which increases with depth. The dead feature fractions (bottom rows) are complementary: patch SAE dead features increase as patch representations become stereotyped, while CLS SAE dead features decrease as the CLS token absorbs global information. Spatial specificity S(β„“) (CLS attention concentration) falls from highly local to fully global as depth increases.

The Surprising Regularisation Effect

A counterintuitive finding from Prisma experiments is that replacing a vision transformer's internal activations with their SAE reconstructions can sometimes improve the model's downstream task performance rather than degrading it. This is surprising because SAE reconstruction introduces an error: 𝒉~=𝐅𝒂 is not equal to the original 𝒉 (SAE reconstruction is lossy), and one would expect any perturbation of the activations to harm performance.

To understand this effect, decompose the reconstruction error: (Error Decomp)π’‰βˆ’π’‰~=π’‰βˆ’π…π’‚βŸreconstructionΒ error=𝒉task⏟task-relevantΒ component+𝒉noise⏟task-irrelevantΒ noiseβˆ’π’‰~.

The SAE is trained to reconstruct the dominant directions of variation in 𝒉 (those with high variance across the dataset). Task-relevant features, which are activated for specific, semantically coherent inputs, contribute high variance and are therefore well-reconstructed. Task-irrelevant noise-high-frequency variation, adversarial perturbations, training artefacts-contributes low variance and is poorly reconstructed. The SAE reconstruction 𝒉~ is therefore a denoised version of 𝒉: it retains the task-relevant component and discards the task-irrelevant noise.

When the noise component is large relative to the task-relevant component (as can occur in models with limited capacity or noisy pre-training), replacing 𝒉 with 𝒉~ reduces noise and improves downstream performance. The SAE acts as a learned regulariser that projects activations onto the manifold of task-relevant features.

Theorem 6 (SAE as a Regulariser).

Let 𝒉=𝒉task+𝒉noise where 𝒉task lies in the column span of 𝐅 and 𝒉noise is orthogonal to the column span of 𝐅. Then the SAE reconstruction satisfies 𝒉~=𝐅𝒂=𝐅𝐅†𝒉task, and in particular ‖𝒉~βˆ’π’‰taskβ€–2β‰€β€–π’‰βˆ’π’‰taskβ€–2=‖𝒉noiseβ€–2, with equality only when 𝐅𝐅†=𝐈 (perfect reconstruction). The SAE reconstruction is weakly closer to 𝒉task than the original 𝒉.

Proof.

By the orthogonality of 𝒉task and 𝒉noise with respect to the column span of 𝐅, the projection 𝐅𝐅† onto the column span satisfies 𝐅𝐅†𝒉noise=𝟎. Therefore: 𝒉~=𝐅𝐅†(𝒉task+𝒉noise)=𝐅𝐅†𝒉task. The bound follows from: ‖𝒉~βˆ’π’‰taskβ€–22=‖𝐅𝐅†𝒉taskβˆ’π’‰taskβ€–22≀‖𝒉taskβ€–22βˆ’β€–π…π…β€ π’‰taskβ€–22≀‖𝒉taskβ€–22. The claim follows since β€–π’‰βˆ’π’‰taskβ€–22=‖𝒉noiseβ€–22.

Remark 30 (Practical Conditions for Improvement).

The improvement in downstream performance from SAE reconstruction occurs when: (1) the task-irrelevant noise is large (e.g., the model was pre-trained on a dataset with significant label noise or domain mismatch); (2) the SAE dictionary is well-calibrated to the downstream task (the task-relevant features are well-captured by 𝐅); and (3) the downstream task uses only the CLS token representation (so the noise filtering at the CLS level directly improves performance). When these conditions hold, SAE reconstruction can improve linear probe accuracy by 1–3 percentage points on standard ViT benchmarks.

Crosscoders: Bridging Representations Across Model Pairs

Crosscoders extend the SAE framework to the setting where two related models-a base model and a fine-tuned model, or two models from the same family trained on different data-have similar but not identical representation spaces. The goal is to find a shared feature dictionary that explains both models' activations simultaneously, making it possible to identify features that are shared (present in both models), added (present only in the fine-tuned model), and suppressed (present only in the base model).

Definition 33 (Crosscoder).

Let fΞΈ1 and fΞΈ2 be two transformer models with the same architecture but different parameters, and let 𝒉1,𝒉2βˆˆβ„d⁑ be their residual stream activations at the same layer for the same input. A crosscoder is a pair of encoder-decoder modules sharing a common feature dictionary π…βˆˆβ„dΓ—K⁑: (Crosscoder)𝒂1=ReLU(𝐖e,1𝒉1+𝒃e,1),𝒂2=ReLU(𝐖e,2𝒉2+𝒃e,2),𝒉~i=𝐅𝒂i+𝒃d,i,i∈{1,2}. The crosscoder is trained to minimise the joint reconstruction loss: (Crosscoder LOSS)β„’CC=𝔼[‖𝒉1βˆ’π’‰~1β€–22+‖𝒉2βˆ’π’‰~2β€–22+Ξ±(‖𝒂1β€–1+‖𝒂2β€–1)].

By analysing the activation patterns 𝒂1 and 𝒂2 over a large dataset, one can categorise each feature 𝒇k as:

  • Shared: feature k activates frequently in both 𝒂1 and 𝒂2 (high mean activation in both).

  • Added: feature k activates frequently in 𝒂2 but rarely in 𝒂1 (characteristic of capabilities introduced by fine-tuning).

  • Suppressed: feature k activates frequently in 𝒂1 but rarely in 𝒂2 (characteristic of behaviours removed by fine-tuning).

  • Absent: feature k activates rarely in both.

This taxonomy provides a mechanistic account of what fine-tuning does to a model's representation: it adds new features, suppresses undesired features, and leaves most shared features intact.

Finding Bias Features in CLIP Models

CLIP (Contrastive Language-Image Pre-training) trains a vision encoder and a text encoder jointly so that paired image-text embeddings are similar while unpaired embeddings are dissimilar. CLIP models are widely used as zero-shot classifiers and visual feature extractors, but they are known to encode societal biases from their training data (the LAION-5B dataset, scraped from the internet, reflects the biases of internet-hosted images and their captions).

Vision SAEs and crosscoders provide a principled method for identifying bias features in CLIP models. The procedure:

  1. Train a vision SAE on the CLIP ViT's CLS token activations.

  2. Identify features whose activation correlates with protected attributes (gender, race, age) by computing, for each feature k, the correlation between ak(x) and a ground-truth annotation of x's protected attribute.

  3. Interpret high-correlation features using automated interpretability: generate a natural-language description of the concept encoded by feature k by finding the images that maximally activate it.

A crosscoder between a base CLIP model and a debiased CLIP model (trained with additional constraints to reduce attribute correlations) identifies features that are suppressed by debiasing. These suppressed features are precisely the bias features: directions in CLIP's representation space that encode protected attributes. By inspecting the feature dictionary entries corresponding to suppressed features, researchers can identify the visual concepts that the debiasing process has disrupted and assess whether the disruption is appropriate (removing stereotypical associations) or harmful (degrading recognition of legitimate visual variation).

Example 8 (Gender Bias Feature in CLIP).

A vision SAE trained on CLIP ViT-L/14 identifies a feature (dictionary vector 𝒇kβˆ—) whose activation akβˆ—(x) correlates r=0.72 with the perceived gender label of the person in image x (where gender is annotated as a binary variable for the purpose of correlation analysis). The top-activating images for 𝒇kβˆ— include stereotypically gendered occupational contexts (images of nurses vs. engineers, chefs vs. executives) rather than purely appearance-based cues. This indicates that the bias feature encodes a contextual stereotype rather than an appearance correlation, and that debiasing strategies targeting appearance features would fail to remove it. The SAE makes this otherwise-hidden structure legible.

Insight.

Vision SAE Density and Feature Overlap. Vision SAEs must be denser than language SAEs because visual features overlap: language tokens are discrete, so the features needed to represent any single token activate sparsely, but pixels are continuous, so visual features co-activate densely. This fundamental difference in the information-theoretic structure of language and vision representations is not a limitation of the SAE framework; it is a diagnostic that reveals why visual concepts are inherently more entangled than linguistic concepts and why disentangling them requires larger, denser dictionaries.

Exercises

Exercise 40 (Feature Density and Sparsity Penalty).

You are training an SAE on the patch token activations of a ViT-Base model with d=768 and K=49152 features (64Γ— overcomplete). The sparsity penalty is Ξ±.

  1. You observe that at Ξ±=0.01 (the default for language SAEs), the average activation count is kβ€Ύ=8, but the reconstruction R2=0.61. At Ξ±=0.001, kβ€Ύ=180 and R2=0.93. Explain this trade-off in terms of the language-versus-vision density argument.

  2. Define a density-adjusted sparsity penalty: Ξ±adj=Ξ±β‹…(d/kβ€Ύtarget), where kβ€Ύtarget is the desired average activation count. If you target kβ€Ύtarget=100 and want the adjusted penalty to equal 0.001, what value of Ξ± should you use?

  3. Argue whether the dead feature fraction is a better or worse diagnostic than R2 for choosing Ξ± in vision SAEs.

Exercise 41 (Crosscoder Feature Taxonomy).

Consider a base CLIP ViT-B/16 model (fΞΈ1) and a CLIP model fine-tuned on a domain-specific medical imaging dataset (fΞΈ2). A crosscoder with K=32768 features is trained on their CLS token activations.

For each feature k, you record (ΞΌ1,k,ΞΌ2,k) where ΞΌi,k=𝔼[ai,k] is the mean activation in model i. You observe the following clusters:

  • Cluster A: (ΞΌ1,k,ΞΌ2,k)β‰ˆ(0.8,0.9) for 12000 features.

  • Cluster B: (ΞΌ1,k,ΞΌ2,k)β‰ˆ(0.05,0.7) for 3000 features.

  • Cluster C: (ΞΌ1,k,ΞΌ2,k)β‰ˆ(0.6,0.04) for 1500 features.

  • Cluster D: (ΞΌ1,k,ΞΌ2,k)β‰ˆ(0.02,0.03) for 16268 features.

  1. Classify each cluster as shared, added, suppressed, or absent.

  2. What fraction of features changed (were added or suppressed) during medical fine-tuning?

  3. Cluster C features might represent visual concepts that the fine-tuning process has inadvertently removed. Propose a method to identify whether this removal is harmful (loss of general capability) or benign (removal of irrelevant internet imagery concepts).

Exercise 42 (SAE Regularisation Effect).

A ViT-S model is trained on ImageNet-100 and achieves 81.3% linear probe accuracy on a downstream classification task. You train a vision SAE on the CLS token activations of this model and replace the CLS token representation 𝒉 with the SAE reconstruction 𝒉~ before training the linear probe.

  1. The probe trained on 𝒉~ achieves 82.7% accuracy. Using the decomposition 𝒉=𝒉task+𝒉noise, estimate the ratio ‖𝒉noiseβ€–2/‖𝒉taskβ€–2 that would be consistent with this improvement, assuming a linear performance model.

  2. You increase the SAE dictionary size from K=8192 to K=65536. Predict whether the regularisation benefit will increase or decrease, and justify your answer using the noise filtering interpretation.

  3. A colleague argues that the improvement is not due to noise filtering but to the SAE enforcing a specific inductive bias on the representation. Design an experiment to distinguish between the noise-filtering hypothesis and the inductive-bias hypothesis.

Interpreting Diffusion Models

Diffusion models have emerged as the dominant paradigm for high-fidelity image synthesis, text-to-image generation, and an expanding array of scientific applications. Unlike autoregressive language models, whose token-by-token generation provides a natural sequential structure amenable to causal analysis, diffusion models operate through a continuous denoising trajectory: a stochastic process that begins with pure Gaussian noise and progressively refines it into a structured sample. This trajectory is parameterised by a reverse-time score function, typically implemented as a U-Net or Diffusion Transformer (DiT), which receives both a noisy latent vector and a timestep embedding as input.

The interpretability challenge in diffusion models is therefore fundamentally temporal. A single forward pass of a denoising model does not produce an interpretable output; the meaningful signal emerges only after integrating over the entire denoising trajectory. Moreover, different stages of the trajectory perform qualitatively different computations. Early denoising steps, operating in the high-noise regime, must decide the global spatial arrangement of the image: where objects are placed, how the scene is composed, and what the broad lighting conditions will be. Intermediate steps progressively resolve questions of style, object identity, and colour palette. Late steps, operating close to the data manifold, refine texture, sharpness, and fine-grained details. Interpretability tools that ignore this temporal structure will conflate fundamentally different computations into a single undifferentiated analysis.

This section develops a temporally-aware framework for interpreting diffusion models. We begin by characterising the concept schedule that governs what information is encoded at each timestep, survey mechanistic tools for probing this schedule, and describe how sparse autoencoders trained on diffusion latent spaces enable principled causal interventions. Throughout, we emphasise the guiding insight that shapes every technique in this section.

Key Idea.

Diffusion models solve a progressive refinement problem: the denoising trajectory proceeds from coarse global structure to fine local detail. Interpretability must follow the same schedule. A tool that identifies a concept at the wrong timestep will either miss the concept entirely or attribute it to computational noise. Effective interpretation of diffusion models requires timestep-aware probes, timestep-conditioned sparse autoencoders, and causal interventions that target specific windows of the denoising trajectory.

The Denoising Trajectory and Its Computational Stages

Recall the forward diffusion process. Given a data point 𝒙0∼pdata, the forward process constructs a sequence of increasingly noisy latents (Forward)q(𝒙t|𝒙0)=𝒩(𝒙t;Ξ±β€Ύt𝒙0,(1βˆ’Ξ±β€Ύt)𝐈), where Ξ±β€Ύt=∏s=1tΞ±s decreases monotonically from Ξ±β€Ύ0β‰ˆ1 (clean data) to Ξ±β€ΎTβ‰ˆ0 (pure noise). The signal-to-noise ratio (SNR) at timestep t is (SNR)SNR(t)=Ξ±β€Ύt1βˆ’Ξ±β€Ύt, which decays from a very large value near t=0 to approximately zero near t=T.

The reverse process learns a neural network 𝝐𝜽(𝒙t,t) that approximates the score function βˆ’βˆ‡π’™tlog⁑q(𝒙t). The key observation for interpretability is that the network receives inputs with very different statistical properties depending on t. Near t=T, the input 𝒙t is nearly indistinguishable from white noise; the network must extract global compositional information from a tiny signal buried in enormous variance. Near t=0, the input 𝒙t is already close to the final image, and the network need only predict fine-grained residual details.

Stage 1 - Semantic Layout (t∈[0.8T,T]).

The high-noise regime is where the model determines the global semantic structure of the image. Empirical studies of cross-attention maps in text-conditioned diffusion models reveal that at early denoising steps, attention is broadly distributed across the spatial extent of objects, with distinct object regions already delineating themselves in the attention maps. Interventions at this stage can reposition objects, add or remove scene elements, and alter the overall compositional arrangement without affecting the detailed appearance of individual objects.

Stage 2 - Style and Identity (t∈[0.3T,0.8T]).

The intermediate regime is where the model resolves questions of style, colour palette, and object identity. Cross-attention at this stage becomes more localised, with attention heads specialising in specific visual attributes. Prompt-to-image correspondence is established: the model binds noun phrases in the text prompt to specific spatial regions. Style transfer interventions applied in this regime can alter the artistic style or object attributes without disrupting the global layout established in Stage 1.

Stage 3 - Texture and Detail (t∈[0,0.3T]).

The low-noise regime resolves fine-grained texture, edge sharpness, and perceptual quality metrics (CLIP score, FID) that are sensitive to high-frequency content. Interventions at this stage affect the crispness and material appearance of surfaces but cannot alter the global semantic content, which has already been committed by earlier stages.

Definition: Temporal Concept Schedule

We formalise the intuition above with a definition that will underpin the rest of this section.

Definition 34 (Temporal Concept Schedule).

Let f𝜽:ℝd⁑×[T]→ℝd⁑ be a denoising network and let π’ž={c1,c2,…,cK} be a finite set of semantic concepts (e.g., β€œroundness”, β€œfur texture”, β€œforeground/background separation”). For each concept ck, its temporal concept schedule is the function (Concept Schedule)Ο•k:[T]β†’[0,1],Ο•k(t)=MutualInfo(Ak(f𝜽(𝒙t,t)),ck), where Ak is a probing classifier trained to decode concept ck from intermediate activations of f𝜽, and MutualInfo denotes mutual information estimated via a k-nearest-neighbour estimator. The concept emergence timestep tkβˆ— is defined as (Emergence TIME)tkβˆ—=arg maxt∈[T]⁑ddtΟ•k(t), the timestep at which the concept's representational strength increases most rapidly (in reverse time, i.e., as the trajectory moves from t=T toward t=0).

Remark 31.

In practice, the denoising trajectory is discretised into Tβ€² steps (typically Tβ€²βˆˆ{20,50,100}), and the derivative in (Emergence TIME) is approximated by finite differences. The probing classifier Ak is typically a linear probe or a shallow MLP trained on a held-out set of generated images with ground-truth concept labels. Mutual information is estimated using the k-NN estimator of [1], which scales well to high-dimensional feature spaces.

TikZ Figure: Concept Emergence Timeline

Temporal concept schedule in a diffusion model. The denoising trajectory proceeds from left to right in the figure (from pure noise at t=T on the left to the final image at t=0 on the right). Three qualitatively distinct computational stages emerge: Stage 1 (blue) establishes global scene composition and object layout; Stage 2 (amber) resolves style, colour identity, and object attributes; Stage 3 (green) refines texture and fine-grained perceptual detail. Sparse autoencoders (SAEs) for mechanistic interpretability should be trained separately at each stage, as the feature geometry of the denoising network changes substantially across timesteps.

Training Sparse Autoencoders on Diffusion Latent Spaces

The success of sparse autoencoders (SAEs) for interpreting language model residual streams (see earlier sections of this chapter) raises a natural question: can the same technique be applied to the internal representations of diffusion models? The challenge is that diffusion models differ from LLMs in a crucial structural way. In an LLM, the residual stream at a given layer is a timestep-independent representation of the current input; every token produces a vector in the same representational space. In a diffusion model, the residual stream at a given layer is a function of both the noisy latent 𝒙t and the timestep t. The representation geometry therefore varies continuously with t, rendering a single SAE trained across all timesteps potentially useless: the dictionary atoms learned for tβ‰ˆT will not correspond to interpretable features at tβ‰ˆ0, and vice versa.

[2] address this challenge by training timestep-stratified SAEs: a collection of SAEs {Ξ¦w}w=1W, one per timestep window 𝒯w=[twβˆ’,tw+]. Within each window, the representation geometry is approximately stationary, allowing the SAE to learn a coherent dictionary of semantic features.

Definition 35 (Timestep-Stratified SAE).

Let f𝜽 be a denoising network with intermediate activation 𝒉ℓ(𝒙t,t)βˆˆβ„d⁑ at layer β„“. A timestep-stratified SAE for window 𝒯w is a pair (𝐖wenc,𝐖wdec) with 𝐖wencβˆˆβ„mΓ—d⁑ (m≫d) trained by minimising the objective (TS SAE LOSS)β„’w=𝔼tβˆΌπ’―w𝔼𝒙0∼pdata[‖𝒉ℓ(𝒙t,t)βˆ’π–wdec𝒉^β€–2+λ‖𝒉^β€–1],where𝒉^=ReLU(𝐖wenc𝒉ℓ(𝒙t,t)+𝒃w), where Ξ»>0 controls sparsity and the expectation over t is taken uniformly within window 𝒯w. The dictionary atoms are the columns of 𝐖wdec, normalised to unit norm.

The timestep-stratified design introduces an important practical consideration: the concept vocabulary learned by Ξ¦w will differ across windows. In the high-noise window 𝒯1, dictionary atoms will correspond to global compositional features (e.g., horizontal extent of a region, left-right symmetry). In the low-noise window 𝒯W, atoms will correspond to texture primitives (e.g., fur directionality, specular highlights). This is not a deficiency of the method but rather a direct reflection of the concept schedule established in Definition 34.

Example 9.

SAE Features in a Text-to-Image Diffusion Model. Consider an SAE trained on the intermediate activations of a latent diffusion model (e.g., Stable Diffusion) at the U-Net bottleneck layer, stratified into three windows: 𝒯1 covering t∈[700,1000], 𝒯2 covering t∈[300,700], and 𝒯3 covering t∈[0,300] (using a 1000-step DDPM schedule).

The following interpretable features were identified by [2] via activation maximisation:

  • Window 𝒯1: β€œleft-right object separation” (fires strongly when distinct objects occupy the left and right halves of the latent), β€œvertical stacking” (fires when objects are arranged in a vertical hierarchy), β€œbackground uniformity” (fires for prompts with simple, uncluttered backgrounds).

  • Window 𝒯2: β€œfur texture” (fires for mammals with dense fur), β€œmetallic sheen” (fires for prompts mentioning steel or chrome), β€œwarm colour palette” (fires for sunset or fire-adjacent prompts), β€œfacial geometry” (fires when a face is the central object).

  • Window 𝒯3: β€œwhisker fine structure” (fires for cat and rodent whiskers at the pixel level), β€œspecular highlight on glass” (fires for transparent or reflective surfaces), β€œmotion blur artefact” (fires when the prompt includes fast motion).

The clean separation of global layout features (window 1), style and identity features (window 2), and texture details (window 3) confirms the temporal concept schedule predicted by Definition 34.

Causal Interventions via Feature Injection and Ablation

Probing and SAE training establish a correlational understanding of which features are active at which timesteps. The gold standard for mechanistic interpretability, however, is causal: we should be able to manipulate a feature and observe a corresponding change in the output, with the change localised to the concept the feature is hypothesised to represent.

For diffusion models, causal interventions take the form of activation patching applied to specific timestep windows. Let 𝒂w(ref) be the SAE feature activations at window 𝒯w when generating a reference image 𝒙ref, and let 𝒂w(tgt) be the activations when generating a target image 𝒙tgt. The intervention replaces the activations in window 𝒯w during a new generation run with a weighted mixture: (Activation Patch)𝒂~w=(1βˆ’Ξ³)𝒂w(tgt)+γ𝒂w(ref),γ∈[0,1], while leaving the activations in all other windows unchanged.

Remark 32.

A subtle but important issue arises from the Markovian cascade in the denoising process. Because each denoising step conditions on the noisy latent produced by the previous step, a causal intervention in window 𝒯w will propagate forward to all subsequent windows 𝒯wβ€²,wβ€²>w. If we intervene in window 𝒯1 (the high-noise stage) to alter the global layout, the changed spatial arrangement will be visible in the activations of windows 𝒯2 and 𝒯3 as well. This cascade is expected and desirable for layout interventions. However, if we wish to intervene only on style (window 𝒯2) without altering layout, we must ensure the intervention is constrained to the style-relevant subspace of the SAE dictionary.

Time-Aware Manipulation: Style Without Layout Disruption

One of the most practically valuable applications of temporal interpretability is time-aware manipulation: the ability to change a specific visual attribute (style, object type, colour palette) while preserving other attributes that were fixed by earlier stages of the trajectory.

The key insight is that layout is committed in window 𝒯1, so any intervention restricted to windows 𝒯2 and 𝒯3 cannot alter the global spatial arrangement without rerunning the high-noise stage. This gives us a clean separation: to change the style of an image without changing its composition, we perform the following procedure.

  1. Generate a layout image 𝒙layout using the original prompt, recording the intermediate activations {𝒉ℓ(𝒙t,t)}t=1T throughout the trajectory.

  2. Modify the text prompt or inject a style SAE feature at window 𝒯2.

  3. Rerun the denoising process from the beginning, but in window 𝒯1, replace the activations with those recorded from the layout image run.

  4. Allow windows 𝒯2 and 𝒯3 to run freely with the modified style conditioning.

The resulting image inherits the composition of 𝒙layout but the style of the modified conditioning. This is the diffusion analogue of style transfer at a mechanistic level: rather than operating on the final pixel image, we intervene directly in the internal representations of the denoising network at the stage where style is being determined.

Example 10.

Style Transfer via Timestep-Targeted Feature Injection. Suppose we wish to generate a photorealistic cat sitting on a wooden table (prompt P1) but with the oil-painting style of a reference image (prompt P2: β€œan oil painting of a cat on a table”).

Using the procedure above:

  • The layout image is generated from P1. At window 𝒯1, the SAE activations encode the cat-on-table spatial arrangement: a roughly centralised cat silhouette with a horizontal surface below.

  • The style SAE features active at window 𝒯2 for P2 include: β€œimpasto texture” (feature f314), β€œwarm earth tones” (feature f87), and β€œvisible brushstroke directionality” (feature f201).

  • In the joint generation run, window 𝒯1 activations are patched from the P1 trajectory (Ξ³=1.0), while window 𝒯2 receives the style features from P2 (Ξ³=0 for layout features, Ξ³=1 for style features).

  • The resulting image shows a cat on a table in the correct spatial arrangement (inherited from P1) rendered in oil-painting style (inherited from the P2 style features).

This experiment confirms that the SAE features in window 𝒯2 are causally sufficient to induce the oil-painting style: injecting only three feature vectors (f314, f87, f201) from the reference trajectory is sufficient to transfer the style while leaving all other aspects of generation unchanged.

Steering Image Generation: The Feature-Timestep Interface

Beyond the style-transfer use case, the timestep-stratified SAE framework enables a rich vocabulary of generation steering operations. We categorise these along two axes: (1) the target window (which stage of the trajectory is modified), and (2) the intervention type (feature injection, feature ablation, or feature clamping).

Layout steering (𝒯1 intervention).

To alter the global spatial composition without changing style or texture, we inject or ablate layout SAE features during the high-noise stage. For instance, ablating the β€œleft-right object separation” feature causes the model to generate images where two objects that would normally appear side by side instead overlap or merge. Injecting the β€œvertical stacking” feature biases the model toward generating images with objects arranged in a vertical hierarchy, regardless of what the text prompt specifies.

Style steering (𝒯2 intervention).

Injecting a β€œwatercolour” style feature during the intermediate stage causes the model to produce watercolour-style images even when the text prompt does not request any specific artistic style. The effect is restricted to the stylistic attributes encoded in window 𝒯2 and does not affect the global layout (committed in 𝒯1) or the fine texture details (determined in 𝒯3).

Texture clamping (𝒯3 intervention).

The low-noise stage can be used to enforce or suppress specific texture patterns. For instance, clamping the β€œsmooth surface” feature active in window 𝒯3 suppresses the model's tendency to generate visible grain or noise in the final image, producing an airbrushed appearance. Injecting the β€œfilm grain” feature conversely adds a realistic grain texture to images that would otherwise appear too smooth.

These operations collectively constitute what we term the feature-timestep interface: a structured programming model for diffusion generation steering, in which the user specifies what to change (which SAE feature) and when to change it (which timestep window), and the SAE framework handles the translation into activation-space interventions.

Exercise 43 (Concept Emergence Timestep Estimation).

Let f𝜽 be a U-Net denoising network trained with a 1000-step DDPM schedule, and suppose a linear probe for the concept β€œcat vs. dog” achieves classification accuracy a(t) at timestep t, with the following observed values (linearly interpolated between): a(1000)=0.51, a(800)=0.62, a(600)=0.78, a(400)=0.91, a(200)=0.94, a(0)=0.95.

  1. Approximate the concept emergence timestep tβˆ— using finite differences on the tabulated values. Which timestep interval [t,t+200] shows the steepest accuracy gradient?

  2. The mutual information Ο•(t)=MutualInfo(A(f𝜽(𝒙t,t)),c) of Definition 34 is related to probe accuracy a(t) by Ο•(t)β‰ˆHb(a(t))βˆ’Hb(0.5), where Hb is binary entropy. Compute Ο•(t) at each tabulated timestep and verify that the maximum gradient of Ο• agrees with your answer from part (a).

  3. Propose a training procedure for a timestep-stratified SAE that uses tβˆ— to define the window boundaries 𝒯1, 𝒯2, 𝒯3. Specifically, discuss how many concepts you would probe (and for which concepts) to determine window boundaries in a fully automated fashion. What is the computational cost of this procedure as a function of the number of concepts K and the number of timesteps Tβ€²?

Exercise 44 (Causal Faithfulness of Timestep-Stratified SAEs).

A central claim of the timestep-stratified SAE framework is that intervening on a feature fk in window 𝒯w produces a change in the output localised to the concept represented by fk. Formalise and test this claim as follows.

  1. Let LPIPS(𝒙,𝒙′) denote the learned perceptual image patch similarity between images 𝒙 and 𝒙′, and let CLIP(𝒙,c) denote the CLIP similarity between image 𝒙 and concept description c. Define a localisation score for feature fk (representing concept ck) as LS(fk)=CLIP(𝒙~,ck)βˆ’CLIP(𝒙,ck)LPIPS(𝒙~,𝒙), where 𝒙~ is the image generated after injecting fk and 𝒙 is the unmodified baseline. Explain why a large LS(fk) indicates a causally faithful, localised intervention.

  2. Show that if the SAE reconstruction satisfies β€–π’‰βˆ’π’‰^β€–2≀δ everywhere, then LPIPS(𝒙~,𝒙)≀CΞ΄ for some constant C that depends on the Lipschitz constant of the denoising trajectory. Use this to derive an upper bound on the distortion introduced by any single-feature injection with injection magnitude ‖Δ𝒂‖2=Ο΅.

  3. Describe an experiment on a publicly available text-to-image model (e.g., Stable Diffusion) that would empirically validate localisation scores for a set of 20 diverse concepts spanning all three timestep windows. What evaluation metrics would you collect, and how would you control for confounds arising from the stochastic sampling process?

Exercise 45 (Layout Preservation Under Style Intervention).

Consider the time-aware style transfer procedure of Time-Aware Manipulation: Style Without Layout Disruption. Let 𝒙layout be a photorealistic image generated from prompt P1 and 𝒙stylised be the image produced after injecting style features from a reference style prompt P2 at window 𝒯2.

  1. Define a layout distance dlayout(𝒙,𝒙′) based on the β„“2 distance between the spatial activation maps extracted at the U-Net bottleneck during window 𝒯1. Prove that if the window 𝒯1 activations are perfectly patched (i.e., Ξ³=1 in (Activation Patch)), then dlayout(𝒙layout,𝒙stylised)=0.

  2. In practice, window 𝒯1 activations cannot be perfectly restored because the stochastic denoising process in later windows feeds back into the state used by window 𝒯1 via the Markovian cascade of Remark 32. Propose a two-pass generation procedure that decouples the layout generation phase from the style generation phase to minimise this feedback.

  3. A photographer argues that the time-aware style transfer procedure violates the β€œartistic integrity” of both the layout prompt and the style prompt, because the resulting image was not specified in either prompt. Construct a formal argument for or against this position, using the SAE feature framework to characterise exactly what information was combined from each prompt.

Attention Floating in Masked Diffusion Models

The preceding sections examined diffusion models for continuous data (images, audio spectrograms). We now turn to a rapidly growing class of discrete generative models: masked diffusion models (MDMs) for text generation. MDMs challenge the long dominance of autoregressive language models (ARMs) by generating text through iterative unmasking rather than sequential left-to-right prediction. This architectural difference - bidirectional attention versus causal masking - gives rise to a striking difference in attention patterns that has profound implications for both interpretability and task performance.

To motivate why attention patterns matter for interpretability, recall that in transformer-based language models, the attention mechanism is the primary vehicle for information routing. Understanding which tokens attend to which other tokens reveals the model's implicit reasoning strategy. A model that attends primarily to a few fixed β€œanchor” tokens is likely to lose information about tokens far from those anchors (the β€œlost-in-the-middle” failure mode); a model whose attention is more uniformly distributed may be better equipped to synthesise information from across the entire context.

Key Idea.

The attention geometry of a generative model encodes its information routing strategy. Autoregressive models concentrate attention on a small number of fixed β€œsink” tokens (typically the beginning-of-sequence token), which absorbs disproportionate attention mass and limits the model's ability to access information from distant positions. Masked diffusion models, freed from causal masking, distribute attention across mobile anchors that drift rightward across decoding iterations - a phenomenon called attention floating. This distributed, dynamic attention structure explains why MDMs outperform ARMs on knowledge-intensive tasks that require integrating information from across the entire context.

Autoregressive Models: Causal Masking and Attention Sinks

An autoregressive language model (ARM) generates text one token at a time, from left to right. At generation step i, the model receives a context of iβˆ’1 previously generated tokens and produces a probability distribution over the next token. This sequential generation is enforced architecturally by a causal attention mask: for each query token at position i, the attention mask restricts the key-value set to positions j≀i. The attention weight from query i to key j is therefore (ARM Attention)aijARM=exp⁑(𝒒iβŠ€π’Œj/d)βˆ‘j′≀iexp⁑(𝒒iβŠ€π’Œjβ€²/d)β‹…πŸ[j≀i]. This causal structure has an important emergent consequence: attention sinks.

Definition 36 (Attention Sink).

An attention sink is a token position jβˆ— in an ARM that receives disproportionately large aggregate attention weight aβ€Ύjβˆ—=1Nβˆ‘i=1Naijβˆ—ARM, where N is the total sequence length. Formally, position jβˆ— is an attention sink if (SINK Definition)aβ€Ύjβˆ—β‰«1Nβˆ‘j=1Naβ€Ύj=1N, i.e., it absorbs far more than its proportional share of aggregate attention. The beginning-of-sequence (BOS) token is the canonical attention sink in causal language models.

The existence of attention sinks in ARMs has been documented across many model families: GPT-2, LLaMA, Mistral, Falcon, and others consistently show the BOS token accumulating 10–30% of the total attention mass in early and middle layers, despite carrying no semantic content beyond its role as a sequence delimiter.

Why does the BOS token become a sink?

The causal mask creates an asymmetry: the BOS token is the only position that every subsequent query can attend to, regardless of its position in the sequence. When the model's attention weights are trained to be β€œsafe” (i.e., routing attention to the BOS token is always a valid fall-back that does not violate the causal mask), the BOS token naturally becomes the designated receptacle for β€œI don't know where else to attend” attention mass. The result is a form of representational waste: a significant fraction of the model's attention capacity is devoted to a semantically meaningless token.

Lost-in-the-middle.

The attention sink phenomenon contributes directly to the lost-in-the-middle failure mode, in which ARMs struggle to access information that appears in the middle of long contexts. When the BOS token absorbs a substantial portion of attention mass, the effective attention budget available for actual contextual content is reduced. Furthermore, the positions immediately following the BOS token (positions 1–5 in a typical prompt) tend to receive elevated attention due to proximity effects of the causal mask, while positions in the middle of the context are systematically under-attended.

Masked Diffusion Models: Bidirectional Attention and Floating Anchors

A masked diffusion model (MDM) generates text by starting with a fully masked sequence and iteratively unmasking tokens over T denoising steps. At each denoising step t, a fraction of the masked tokens are unmasked based on the model's predicted token probabilities. Crucially, the transformer in an MDM uses bidirectional attention: the attention mask is a full matrix of ones, allowing every token to attend to every other token regardless of position.

The bidirectional attention weight from query i to key j is (MDM Attention)aijMDM=exp⁑(𝒒iβŠ€π’Œj/d)βˆ‘jβ€²=1Nexp⁑(𝒒iβŠ€π’Œjβ€²/d), where the sum ranges over all N positions in the sequence. The absence of the causal mask has two immediate consequences. First, there is no structural reason for any single position to become a dominant attention sink: every position can receive attention from every other position, eliminating the asymmetric pull of the BOS token. Second, the model can condition each unmasking decision on the full bidirectional context, enabling long-range dependencies that ARMs can only approximate through left-to-right recurrence.

Definition 37 (Attention Floating).

In a masked diffusion model, attention floating is the phenomenon in which aggregate attention concentrates on a small set of mobile anchor positions that shift rightward across denoising iterations. Formally, let aβ€Ύj(t)=1Nβˆ‘i=1NaijMDM,(t) be the aggregate attention received by position j at denoising step t. Attention floating is characterised by:

  1. Distributed anchors. The attention distribution {aβ€Ύj(t)}j=1N has multiple local maxima at each step t, as opposed to the single dominant sink of ARMs.

  2. Rightward drift. The position of the dominant attention anchor jβˆ—(t)=arg maxj⁑aβ€Ύj(t) drifts rightward (increases) as t decreases from T to 0: (Rightward Drift)𝔼[jβˆ—(t)]<𝔼[jβˆ—(tβˆ’1)]forΒ allΒ t>0.

  3. Correlation with unmasking. The anchor positions at step t are strongly correlated with the set of tokens that were unmasked in step tβˆ’1: recently unmasked tokens attract elevated attention in the subsequent step.

Remark 33.

Attention floating can be understood as follows. At the first denoising step t=T, all tokens are masked, and the model must attend to the conditioning prompt (or the [MASK] tokens themselves). Attention anchors coincide with semantically important prompt tokens. As denoising proceeds and tokens are progressively unmasked from left to right (MDMs tend to unmask in a left-to-right order in practice, though this is not enforced), the newly unmasked tokens provide concrete lexical anchors that attract attention from still-masked tokens. The rightward drift of attention anchors therefore tracks the frontier of the unmasked region across denoising steps.

TikZ Figure: Attention Patterns in ARM vs. MDM

Comparison of attention patterns in autoregressive models (ARM, left) and masked diffusion models (MDM, right). In the ARM, the causal mask restricts each query to attend only to preceding positions, and the BOS token (column 0) accumulates a disproportionately large aggregate attention weight (dark blue), functioning as an attention sink. In the MDM, bidirectional attention allows all positions to attend to all others. The aggregate attention concentrates on recently unmasked tokens (the floating anchor, shown in dark green at position 2 in this snapshot), with the anchor drifting rightward across successive denoising steps as indicated by the dashed amber arrow. Grey cells in the ARM matrix are blocked by the causal mask; there are no blocked cells in the MDM.

Shallow Structure-Aware, Deep Content-Focused Mechanism

Empirical analysis of MDM attention patterns across layers reveals a bipartite computational organisation that mirrors the structure-versus-content hierarchy observed in the temporal stages of image diffusion models.

Shallow layers: structure-aware attention.

In the early transformer layers (approximately the first third of the depth), attention patterns are strongly correlated with syntactic and positional structure: the model attends to positions that determine the grammatical skeleton of the sentence (nouns, verbs, clause boundaries). The floating anchor in shallow layers tends to be located at the beginning of the currently unmasked region, corresponding to the structural pivot of the emerging sentence.

Probing classifiers trained on shallow-layer representations achieve high accuracy for syntactic tasks (part-of-speech tagging, dependency arc prediction) but low accuracy for semantic content tasks (named entity recognition, semantic role labelling). This suggests that shallow layers use bidirectional attention primarily to assemble the structural scaffolding of the output text.

Deep layers: content-focused attention.

In the later transformer layers (approximately the final third of the depth), attention patterns shift to content-focused processing: the model attends to positions that carry the specific factual content required to fill the remaining masked positions. The floating anchor in deep layers tends to be located at the most informative unmasked token for resolving the current masked position - for instance, if the current masked token should be a person's name, the anchor tends to be the position that first mentioned the person.

Probing classifiers trained on deep-layer representations achieve high accuracy for semantic and factual tasks but lower accuracy for syntactic structure. This bipartite organisation - shallow structure-aware, deep content-focused - is the mechanism by which MDMs avoid the lost-in-the-middle failure mode: factual content retrieval happens in deep layers where bidirectional attention has access to the entire context with no causal restriction.

Proposition 8 (Attention Distribution Entropy in MDMs vs. ARMs).

Let HiARM=βˆ’βˆ‘j≀iaijARMlog⁑aijARM be the entropy of the attention distribution of query i in an ARM, and let HiMDM=βˆ’βˆ‘j=1NaijMDMlog⁑aijMDM be the corresponding entropy in an MDM. Then for any query at position i with i<N: (Entropy Inequality)𝔼[HiMDM]β‰₯𝔼[HiARM]+log⁑(Ni), where the expectation is over the distribution of model weights following training, assuming equal capacity and identical training data.

Proof sketch.

The ARM attention for query i is a distribution over i tokens (those at positions 1,…,i), while the MDM attention for the same query is a distribution over all N tokens. By the maximum entropy principle, the entropy of a distribution over N elements is at most log⁑N, while the entropy of a distribution over i elements is at most log⁑i. If the ARM and MDM assign similar attention probabilities to the i causally accessible tokens, the MDM has an additional log⁑(N/i) nats of entropy from the extra Nβˆ’i accessible positions. The inequality follows by replacing the maximum with the expectation under the training distribution.

The inequality in Proposition 8 formalises the intuition that MDM attention is more distributed than ARM attention, not just because of the floating anchor mechanism, but because the full bidirectional attention pool is always larger. As a consequence, any individual token has a lower maximum possible share of the aggregate attention mass in an MDM than in an ARM, making attention sinks structurally impossible in well-trained MDMs.

MDMs Outperform ARMs on Knowledge-Intensive Tasks

The distributed, floating attention structure of MDMs has a direct empirical consequence: MDMs consistently outperform comparably-sized ARMs on tasks that require integrating information from across a long context - precisely the class of tasks where the ARM attention sink and lost-in-the-middle failure modes are most damaging.

Multi-hop reasoning.

Tasks that require connecting a chain of facts scattered across a long document (e.g., β€œWhat is the birth city of the author of the book that won the prize in year X?”) require the model to simultaneously attend to multiple relevant positions. In ARMs, the causal mask prevents early position tokens from attending to information that appears later in the prompt, and the attention sink at the BOS token reduces the effective attention budget for intermediate reasoning steps. MDMs, with their bidirectional attention, can attend to all relevant facts simultaneously in a single forward pass.

Cloze-style factual completion.

When the model must fill in a masked token that depends on factual knowledge appearing later in the context (e.g., β€œ[MASK] was born in Paris” when the later context provides the person's name), ARMs must rely on their parametric memory because they cannot attend to later tokens. MDMs can attend to the later context directly, effectively performing a lookup operation that bypasses the need to memorise the fact in model weights.

Open-domain question answering.

Experiments on the MMLU, TriviaQA, and NaturalQuestions benchmarks show MDMs achieving 3–8% higher accuracy than same-parameter ARMs when the relevant evidence appears in the middle of a 2048-token context. The gap is largest for questions that require evidence from positions 512–1536 (the middle half of the context), consistent with the lost-in-the-middle failure mode of ARMs.

Mechanistic Interpretability of Diffusion Bias

The attention and representation structure of diffusion models is not only relevant for understanding task performance; it also encodes social biases that are learned from training data and can be propagated, amplified, or attenuated by the model's internal circuits. [3] present a mechanistic interpretability analysis of bias in U-Net and Diffusion Transformer (DiT) architectures, identifying specific internal circuits responsible for generating stereotyped associations and proposing targeted interventions to neutralise them while preserving generation quality.

The circuit problem.

Bias in image-generative models is commonly attributed to biased training data: if the training set contains more images of male engineers than female engineers, the model will generate male engineers more frequently. While training data skew is certainly a contributing factor, the mechanistic interpretability lens reveals that this explanation is incomplete. Biased associations are not uniformly distributed across model parameters; they are concentrated in specific attention heads and MLP layers that form identifiable circuits. A model can thus inherit bias from training data while amplifying or suppressing it through its internal circuit structure.

Key Idea.

Bias in generative models is not a dataset problem alone - it is a circuit problem. Stereotyped associations between gender, ethnicity, and occupation are encoded in specific attention heads and MLP neurons of U-Net and DiT architectures. Mechanistic interpretability identifies these circuits precisely; targeted interventions on the identified circuits can reduce bias by 30–50% while preserving image quality (FID, CLIP score) to within 2% of the unmodified baseline.

Identifying bias features.

[3] propose a three-stage procedure for identifying bias circuits in a diffusion model f𝜽.

Stage 1: Contrastive generation. For each stereotyped association (e.g., β€œnurse” β†’ female), generate a large set of image pairs: one set conditioned on the neutral prompt (β€œa nurse”) and one set conditioned on a de-biased prompt (β€œa male nurse”). Extract intermediate activations from every attention head and MLP layer for both sets.

Stage 2: Causal attribution. Apply causal tracing (activation patching) to identify which components, when their activations are swapped from the biased-generation run to the de-biased run, cause the model's gender-association output to change. The components with the highest causal attribution scores form the bias circuit.

Stage 3: Sparse intervention. Train a lightweight steering vector 𝜹 in the subspace spanned by the bias circuit's attention heads. The steering vector is optimised to minimise the CLIP similarity between the generated image and the stereotyped gender role, subject to a constraint that the image quality (FID score on a holdout set) does not degrade beyond a threshold ϡFID.

Definition 38 (Bias Steering Vector).

Let β„‹βˆ—βŠ‚β„‹ be the set of attention heads identified as part of the bias circuit for stereotype s, and let 𝒗hβˆˆβ„dh⁑ be the value-space representation of head h. The bias steering vector for stereotype s is (BIAS Steering)𝜹s=arg min𝜹:β€–πœΉβ€–2≀rβ‘π”Όπ’™βˆΌps[CLIP(f𝜽𝜹(𝒙),s)]s.t.FID(f𝜽𝜹)≀FID(f𝜽)+Ο΅FID, where f𝜽𝜹 denotes the model with the steering vector 𝜹 added to the activations of all heads in β„‹βˆ—, ps is the distribution of neutral prompts associated with stereotype s, and r>0 controls the intervention magnitude.

Experimental results.

On the Stable Diffusion XL model evaluated on the WinoBias and FairFace benchmarks, [3] report the following outcomes from the circuit-targeted intervention:

  • Nurse/doctor gender bias: reduced from 78% female association (baseline) to 54% female association (post-intervention), approaching the 50% gender-neutral baseline, with FID degradation of only 1.3 points (Ο΅FID=2.0 threshold).

  • CEO/engineer gender bias: reduced from 82% male association to 61% male association.

  • Criminal/welfare recipient ethnicity bias: reduced from 71% majority-group over-association to 55%.

  • Image quality: CLIP score decreased by 1.8% (average over all stereotypes), LPIPS increased by 0.012, FID increased by 1.7 points - all within the specified quality constraints.

Critically, the identified bias circuits were transferable across model checkpoints: a bias circuit identified in one fine-tuned variant of SDXL transferred to 7 other fine-tunes with >85% causal attribution overlap, suggesting that bias circuits are established during pre-training and persist through fine-tuning.

U-Net vs. DiT architectures.

The mechanistic analysis reveals qualitative differences between bias circuit structure in U-Net and DiT architectures. In U-Net models (e.g., Stable Diffusion 1.x, 2.x, SDXL), bias circuits are concentrated in the cross-attention layers of the middle (bottleneck) blocks, where text conditioning information is injected into the image latent. The text encoder's representation of occupational terms (β€œnurse”, β€œCEO”) carries implicit gender associations that the cross-attention layers then propagate into the spatial features of the latent.

In DiT models (e.g., DiT-XL, PixArt-Ξ±, Stable Diffusion 3), the architecture's fully transformer-based design distributes the bias circuit more broadly across layers. Cross-attention is replaced by adaptive layer normalisation conditioned on text embeddings, and the bias circuit manifests in the normalisation parameters rather than explicit attention heads. This makes DiT bias circuits harder to identify (there are no discrete attention heads to probe) but not impossible: causal tracing on the normalisation scale and shift parameters (Ξ³ and Ξ² in the adaptive LayerNorm) successfully isolates the bias contribution.

Exercise 46 (Attention Entropy and Lost-in-the-Middle).

This exercise explores the relationship between attention entropy and the lost-in-the-middle failure mode in ARMs.

  1. Let π’’βˆˆβ„d⁑ be a query vector and {π’Œj}j=1i be the i key vectors accessible to the query (under a causal mask). Suppose the BOS key π’Œ1 satisfies π’’βŠ€π’Œ1=Ξ² for all queries 𝒒 (a constant independent of the query), modelling the BOS sink. Show that the fraction of attention mass absorbed by the BOS token is at least ai1β‰₯eΞ²eΞ²+(iβˆ’1)eΞΌ where ΞΌ=1iβˆ’1βˆ‘j=2iπ’’βŠ€π’Œj is the mean dot product with non-BOS keys. What happens to this lower bound as the context length iβ†’βˆž?

  2. Define the effective context of query i as the entropy-weighted effective number of tokens it attends to: Neff(i)=exp⁑(HiARM). Compute Neff(i) for an ARM with a BOS sink absorbing fraction Ξ± of attention and the remaining 1βˆ’Ξ± uniformly distributed over the iβˆ’1 non-sink positions. Plot Neff(i) as a function of Ξ± for i=512 and α∈{0.05,0.10,0.20,0.40}.

  3. Suppose an ARM with BOS sink fraction Ξ±=0.25 is asked a question whose answer requires attending to a position jβˆ— in the middle of a 1024-token context (position jβˆ—=512). Assuming uniform attention over non-sink positions, what is the probability that a uniformly random attention head attends to jβˆ— more than to the BOS token? Comment on whether this probability increases or decreases with context length.

Exercise 47 (Characterising Attention Floating Formally).

Recall the definition of attention floating from Definition 37. This exercise asks you to prove or disprove properties of the rightward drift condition.

  1. Let Mt denote the set of masked positions at denoising step t, and assume the MDM unmasks tokens in a left-to-right order (one token per step for simplicity). Show that the dominant attention anchor jβˆ—(t) satisfies 𝔼[jβˆ—(t)]=min⁑(Mt)+Ξ΄t for some Ξ΄tβ‰₯0 that you should characterise, assuming the recently-unmasked token attracts a fraction ρ>0 of aggregate attention from all other positions.

  2. Prove or disprove: under the assumptions of part (a), the rightward drift condition 𝔼[jβˆ—(t)]<𝔼[jβˆ—(tβˆ’1)] holds for all denoising steps tβ‰₯1.

  3. Now relax the left-to-right unmasking assumption. Suppose instead that the MDM uses a confidence-based unmasking order, in which at each step the model unmasks the token it is most confident about (highest predicted probability for any non-mask token). Does the rightward drift condition still hold? If not, propose a weaker version of the condition that does hold for confidence-based unmasking.

Exercise 48 (Targeted Bias Mitigation via Circuit Surgery).

Consider a text-to-image diffusion model in which causal tracing identifies a set β„‹βˆ—={h3,h7,h12} of three attention heads in the cross-attention layers as the primary bias circuit for the β€œnurse β†’ female” stereotype.

  1. The bias steering vector 𝜹s of Definition 38 is found by constrained optimisation. Reformulate this optimisation as an unconstrained Lagrangian problem with multiplier Ξ»β‰₯0, and derive the first-order optimality conditions. Show that Ξ»=0 corresponds to ignoring the quality constraint and Ξ»β†’βˆž corresponds to maximising quality at the expense of bias reduction.

  2. Suppose the bias circuit is identified using activation patching on a dataset of n=500 image pairs. The causal attribution score for head h is c^h=1nβˆ‘i=1nβ€–Ξ”h𝒂iβ€–2/‖𝒂iβ€–2, where Ξ”h𝒂i is the change in output when head h's activations are patched. Derive a confidence interval for ch using Hoeffding's inequality, assuming c^h∈[0,1]. How large must n be to achieve a 95% confidence interval of width 0.05?

  3. A critic argues that targeted bias circuit interventions are a β€œband-aid” solution: they suppress the stereotyped output behaviour without addressing the underlying biased representations in the text encoder that feed the bias circuit. Formalise this argument by defining representational bias in the text encoder embedding of an occupational term w (e.g., β€œnurse”) and showing that the bias steering vector 𝜹s from Definition 38 leaves the text encoder representations unchanged. Propose a complementary intervention at the text encoder level that would address representational bias, and discuss whether the two interventions are orthogonal or interacting.

Video Generation and Emergent Reasoning

The arc of generative modelling has bent, with increasing sharpness, toward time. Images capture a frozen instant; text unfolds over tokens that, although sequential, carry no physical causal structure; but video demands something more: a model of how the world changes. A pixel at position (x,y) in frame t+1 is not merely statistically correlated with pixels at (x,y) in frame t; it is the consequence of forces, velocities, collisions, and intentions that operated during the interval [t,t+1]. Predicting video plausibly therefore requires, at minimum, an implicit model of the physics and agency that govern the depicted scene.

This observation has thrust video generation models into an unexpected role: involuntary world simulators. Systems like Sora (OpenAI, 2024), Veo (Google DeepMind, 2024), and CogVideoX trained exclusively on the objective of predicting the next frame, or of denoising a corrupted video clip, appear to have acquired representations that encode physical object permanence, gravity, occlusion, and even elements of goal-directed behaviour. The interpretability challenge is to understand what has been acquired, where it lives in the network, and how it is computed.

Section Video Generation and Emergent Reasoning is organised as follows. We begin by surveying the architectures of contemporary video generation models and the evidence for emergent cognition they exhibit (Video Models as World Simulators). We then turn to the Attention Gathers, MLPs Compose hypothesis, which offers a mechanistic account of how spatiotemporal reasoning is distributed across the transformer layers of a Video Vision Transformer (VideoViT) (The Attention Gathers, MLPs Compose Hypothesis). We formalise the concept of an action-outcome circuit (Action-Outcome Circuits in Video Transformers), explain why redundancy across MLP layers makes video transformers resilient (Redundancy Across MLP Layers), and ground everything in a running example of predicting bowling outcomes (A Running Example: Predicting Bowling Outcomes).

Video Models as World Simulators

A video generation model GΞΈ maps a conditioning signal π’„βˆˆπ’ž (a text prompt, an initial frame, or a noise tensor) to a distribution over video clips 𝒙1:Tβˆˆβ„TΓ—HΓ—WΓ—3⁑, where T is the number of frames and HΓ—W is the spatial resolution. Modern architectures pursue this goal via diffusion: (Diffusion)pΞΈ(𝒙1:T|𝒄)=∫pΞΈ(𝒙1:T|𝒛,𝒄)p(𝒛)d𝒛, where 𝒛 is a latent code obtained by encoding the video into a compressed spatiotemporal latent space, and pΞΈ(𝒙1:T|𝒛,𝒄) is parameterised by a denoising network-typically a Diffusion Transformer (DiT) whose self-attention modules operate over both spatial patch tokens and temporal frame tokens simultaneously.

Spatiotemporal patchification.

Given a video 𝒙1:T, the standard preprocessing pipeline in architectures such as CogVideoX proceeds as follows. Each frame 𝒙tβˆˆβ„HΓ—WΓ—3⁑ is divided into non-overlapping spatial patches of size pΓ—p pixels. Temporal striding groups every Ο„ consecutive frames into a single temporal unit. The result is a grid of ⌈T/Ο„βŒ‰Γ—βŒŠH/pβŒ‹Γ—βŒŠW/pβŒ‹ tokens, each of dimension dpatch=Ο„β‹…p2β‹…3. A linear projection maps each patch token to the model's hidden dimension d: (Patch)𝒉i=𝐖proj𝒙ipatch+𝒃proj,𝒙ipatchβˆˆβ„dpatch⁑,𝒉iβˆˆβ„d⁑. Positional encodings, either factorised 3-D sinusoidal embeddings or learned RoPE encodings, are then added so that the transformer can distinguish tokens by their spatial coordinates and temporal frame index.

Emergent cognitive abilities.

The VBVR-Bench (Video-Based Visual Reasoning Benchmark) was designed to probe whether video generation models possess genuine scene understanding or merely sophisticated texture interpolation. The benchmark presents three families of tasks.

  • Mental rotation. A 3-D object is shown from one viewpoint; the model must complete a video that shows the object after rotation by a specified angle Δϕ. Success requires an internal representation of volumetric shape, not merely a library of pixel patterns.

  • Maze navigation. A first-person perspective video begins inside a maze; the model must generate subsequent frames consistent with navigating to an exit whose location was made inferable from the opening frames. This tests both spatial memory and goal-directed planning.

  • Sudoku completion. A video shows a partially filled Sudoku grid; the model must generate frames that fill in the remaining cells correctly. This is a pure constraint-satisfaction task requiring symbolic reasoning embedded inside a continuous video prediction objective.

Remarkably, Sora and Veo achieve non-trivial performance on all three task families. Their success rates exceed chance by wide margins and exceed the performance of image-only diffusion models given the same prompts, suggesting that the temporal dimension of the training objective-rather than just the scale of pixel data-is a meaningful driver of emergent cognition.

Key Idea.

Video models develop hidden knowledge beyond their training objective. A video generation model trained solely to denoise spatiotemporal patches must, as a byproduct, solve the inverse problem of physical scene understanding. The latent representations it develops to do so encode geometry, dynamics, and, in some cases, elementary causal reasoning-capabilities that were never explicitly supervised.

The Attention Gathers, MLPs Compose Hypothesis

Understanding how a video transformer performs its computation requires a mechanistic hypothesis about the functional division of labour between its two principal building blocks: the multi-head self-attention (MHSA) sublayer and the multi-layer perceptron (MLP) sublayer. In language models, a substantial body of mechanistic interpretability work has established that attention heads tend to implement token-copying and positional routing operations, while MLP layers store and retrieve factual associations. We now argue that an analogous but spatiotemporally extended version of this division holds in video transformers.

Definition 39 (Attention Gathers, MLPs Compose).

Let 𝐇(β„“)βˆˆβ„NΓ—d⁑ denote the matrix of token representations at layer β„“ of a VideoViT, where N=Ntβ‹…Ns is the product of temporal and spatial token counts. The Attention Gathers, MLPs Compose (AGMC) hypothesis asserts:

  1. Attention gathers.; For each query token i, the MHSA sublayer at layer β„“ computes a weighted aggregation of value vectors from tokens j that share a spatiotemporal relationship (same object, same motion trajectory, same causal chain) with token i: (ATTN)𝒉~i(β„“)=βˆ‘j=1NΞ±ij(β„“)𝐖V(β„“)𝒉j(β„“), where the attention weights Ξ±ij(β„“)=softmaxj⁑((𝐖Q𝒉i)⊀(𝐖K𝒉j)/dh) concentrate on spatiotemporally relevant tokens.

  2. MLPs compose.; The MLP sublayer at layer β„“ operates on the gathered representation 𝒉~i(β„“) and composes a higher-order feature that corresponds to an abstract outcome: a physical event, an action consequence, or a scene-level property that cannot be localised to any single token: (MLP)𝒉i(β„“+1)=𝒉i(β„“)+MLP(β„“)⁑(𝒉~i(β„“)).

The AGMC hypothesis makes testable predictions. If it is correct, then ablating or patching attention heads should disrupt the routing of evidence (which tokens are aggregated), while ablating MLP layers should disrupt the composition of abstract outcomes (what conclusions are drawn from that evidence). Probing experiments on CogVideoX confirm this asymmetry: attention-head ablations degrade spatial coherence (the model loses track of where objects are), whereas MLP ablations degrade causal coherence (the model loses track of what will happen next).

Multi-head structure and spatiotemporal specialisation.

Video transformers typically employ H attention heads per layer. Activation-patching experiments reveal that different heads specialise along different axes of the spatiotemporal structure. A standard classification that has emerged from the literature is:

  • Spatial heads aggregate information across the spatial patch grid at a fixed time step. Their attention patterns resemble those observed in image transformers: receptive fields that grow with depth, attending first to local texture and later to global structure.

  • Temporal heads aggregate information across time at a fixed spatial location, effectively tracking the trajectory of a point in the scene through time.

  • Cross-modal heads (in text-conditioned models) route information from text tokens to visual tokens, anchoring generated content to the conditioning signal.

  • Causal heads display a distinctive pattern: they attend from a token at time t+k to tokens at time t that represent cause tokens, i.e., tokens whose features encode an action or event that logically implies the content at t+k. These are the heads most directly implicated in the action-outcome circuits defined below.

Action-Outcome Circuits in Video Transformers

The concept of a circuit in mechanistic interpretability was developed in the context of language models to refer to a subgraph of the computational graph that is jointly sufficient for performing a specific subtask. We extend this concept to the spatiotemporal setting of video transformers.

Definition 40 (Action-Outcome Circuit).

Let G=(V,E) be the computational graph of a VideoViT, where V is the set of all attention heads and MLP layers across all transformer blocks, and E captures the residual-stream flow between them. An action-outcome circuit π’žβŠ†G is a connected subgraph satisfying:

  1. Action node.; π’ž contains at least one set of attention heads {h1,…,hk} whose combined attention patterns concentrate on tokens encoding a physical action a (a collision, a throw, a motor command).

  2. Composition node.; π’ž contains at least one MLP layer m whose pre-activation features, after receiving gathered evidence from the action nodes, encode a distribution over outcomes o∈π’ͺ (possible physical states at a future time).

  3. Sufficiency.; Ablating Gβˆ–π’ž (setting the output of all nodes outside π’ž to zero) leaves the model's prediction of o given a approximately unchanged: (Sufficiency)β€–pΞΈ(o|a)βˆ’pΞΈ|Gβˆ–π’ž=0(o|a)β€–1≀Ρ for some small Ξ΅>0.

Action-outcome circuits are discovered by a three-stage pipeline. First, mean ablation patching identifies which components are causally necessary for the model's causal reasoning: each component is ablated in turn, and the change in output logits is measured. Second, attention pattern visualisation confirms that the identified attention heads attend to action-relevant tokens. Third, probing classifiers trained on MLP intermediate activations verify that outcome-relevant information is present in the composition nodes.

Mathematical formulation of the residual stream.

The residual stream of a VideoViT can be written as: (Residual)𝒉i(0)=𝐖proj𝒙ipatch+pos(i),𝒉i(β„“+12)=𝒉i(β„“)+MHSA(β„“)(𝐇(β„“))i,𝒉i(β„“+1)=𝒉i(β„“+12)+MLP(β„“)⁑(𝒉i(β„“+12)), where pos(i) is the positional encoding for token i. The circuit π’ž can be characterised by a binary mask π’Žβˆˆ{0,1}|V| over the node set, and the ablated model is (Ablated)𝒉~i(β„“+1)=𝒉~i(β„“+12)+mMLP(β„“)β‹…MLP(β„“)⁑(𝒉~i(β„“+12)), with analogous masking on the MHSA contributions. The circuit discovery problem is to find the minimal mask π’Ž such that equation is satisfied.

Action-outcome circuit in a VideoViT under the AGMC hypothesis. Causal heads (blue, gathering phase) route spatiotemporal evidence from action tokens in frame t to composition tokens in frame t+k. The MLP sublayer (green) composes this gathered evidence into an abstract outcome distribution (orange). The dashed path through MLP(β„“+1) illustrates the redundancy that makes circuits robust to single-layer ablations. The dashed red rectangle marks the sufficient circuit π’ž.

Redundancy Across MLP Layers

A striking empirical observation in video transformer interpretability is that action-outcome circuits are not localised to a single MLP layer. Rather, the causal outcome information is distributed redundantly across several consecutive MLP layers. Ablating any single MLP layer produces only a modest degradation in causal reasoning; recovering full degradation requires ablating three to five consecutive layers.

This redundancy has a structural explanation. The MLP at layer β„“ of a transformer with hidden dimension dff=4d (the standard factor-4 expansion) can be viewed as a key-value memory over a dictionary of dff memory slots. Each slot k is associated with a key vector π’˜kinβˆˆβ„d⁑ and a value vector π’˜koutβˆˆβ„d⁑: (MLP KV)MLP⁑(𝒙)=𝐖outβ‹…GeLU(𝐖in𝒙), where 𝐖inβˆˆβ„dffΓ—d⁑ and 𝐖outβˆˆβ„dΓ—dff⁑. The rows of 𝐖in are the keys; the columns of 𝐖out are the values.

Under this memory interpretation, a single concept (e.g., β€œthe ball will continue along its trajectory”) may activate multiple memory slots across multiple consecutive layers. The representation is over-complete: far more slots encode the concept than are strictly necessary. This over-completeness is precisely the source of resilience.

Proposition 9 (MLP Redundancy Implies Circuit Resilience).

Let π’ž be an action-outcome circuit in a VideoViT of depth L, and suppose the outcome feature 𝒇oβˆˆβ„d⁑ is written to the residual stream by K distinct MLP layers β„“1<β‹―<β„“K with individual writing strengths Ξ»1,…,Ξ»K>0, i.e., (Writing)𝒉i(L)βŠƒβˆ‘k=1KΞ»k𝒇o+π’‡βŸ‚, where π’‡βŸ‚βŸ‚π’‡o. Then ablating a single layer β„“j reduces the total writing strength by the fraction Ξ»j/βˆ‘kΞ»k. Averaged over the K layers this fraction is exactly 1/K, so when the writing strengths are comparable no single ablation removes more than about 1/K of the signal; a single dominant layer, by contrast, can carry an arbitrarily large fraction and is not resilient.

Proof.

Ablating layer β„“j removes the contribution Ξ»j𝒇o from the sum, leaving strength βˆ‘kβ‰ jΞ»k=βˆ‘kΞ»kβˆ’Ξ»j, a fractional reduction of Ξ»j/βˆ‘kΞ»k. Summing these fractions over j gives βˆ‘jΞ»j/βˆ‘kΞ»k=1, so their average is 1/K. The reduction equals 1/K for every layer exactly when all Ξ»k are equal, and approaches 1 when one Ξ»j dominates the sum, which is precisely the non-resilient case.

The practical implication is that single-layer ablation experiments may dramatically underestimate the role of MLPs in causal reasoning within video models. Rigorous circuit discovery must account for the possibility that the same computation is distributed across many layers, and path-patching techniques must be extended to identify the full set of writing layers.

A Running Example: Predicting Bowling Outcomes

To make the foregoing abstractions concrete, we trace the computation of a VideoViT through a specific example: predicting whether a bowling ball will strike the pins or miss, given the first T0 frames of a ten-pin bowling video.

Setup.

Let 𝒙1:T0 be the input video clip, consisting of T0=12 frames at 24 fps covering the moment the ball leaves the bowler's hand and traverses the first third of the lane. The model must predict the output token o∈{strike,spare,gutter}-a discretised summary of the final outcome. The model never observes the pins being hit; it must infer the outcome from the ball's early trajectory.

Identifying the action tokens.

The ball occupies a localised spatial region in each frame. Applying the activation-patching pipeline to the bowling example reveals that the tokens corresponding to the ball's position at frames t=3 and t=6 (approximately 0.125 s and 0.250 s after release) are the action tokens: ablating them while preserving all others reduces outcome prediction accuracy from 84% to 52% - a large drop, though still above the 33% chance level for a three-class problem.

Gathering phase: causal heads.

In layers 8–12 of a 24-layer VideoViT, three causal attention heads (h1,h2,h3) display a characteristic pattern: their queries originate from late-frame tokens (frames t=10–12, near the lane end), and their keys concentrate on the ball-region tokens at early frames. The attention weights satisfy: (Bowling ATTN)βˆ‘t∈{3,6}Ξ±ij(β„“)|ballΒ tokens>0.6βˆ€β„“βˆˆ[8,12],βˆ€i∈lane-endΒ tokens. In other words, more than 60% of the attention weight from lane-end tokens flows to the early ball-position tokens-these heads are routing physical trajectory information forward in time.

Composition phase: MLP layers.

Probing classifiers trained on the MLP intermediate activations at layers 13–17 achieve 91% accuracy on the three-class outcome prediction, compared to 61% for probes trained on the attention output at the same layers. The gap confirms that MLP composition, not attention gathering, is the stage at which trajectory information is converted into outcome probability. Specifically, the direction in residual-stream space most predictive of β€œstrike” versus β€œgutter” is written by MLP layers 14 and 15, with writing strengths Ξ»14=0.38 and Ξ»15=0.29 (normalised).

Redundancy in the bowling circuit.

Measured by the layer-13–17 MLP probe (baseline 91%), ablating MLP layer 14 alone reduces the probe's outcome-decoding accuracy from 91% to 74%. Ablating both layers 14 and 15 reduces it to 57%. Reaching chance performance requires ablating layers 13 through 17 simultaneously, consistent with Proposition Proposition 9 with K=5 writing layers.

This example illustrates the full action-outcome circuit pipeline: causal heads at layers 8–12 gather ball-trajectory evidence; MLP layers 13–17 compose this evidence into outcome probabilities; the outcome feature is written redundantly across five layers, conferring resilience to perturbation.

Example 11 (Probing the Bowling Circuit with Counterfactual Videos).

To verify that the identified causal heads are computing trajectory extrapolation and not merely detecting visual features correlated with outcome (e.g., the bowler's form), researchers generate counterfactual videos in which the bowler's posture and release motion are held fixed but the ball's launch angle ΞΈ is varied synthetically.

For each angle θ∈{βˆ’5∘,βˆ’3∘,0∘,3∘,5∘}, the attention weights Ξ±ij(β„“) of the causal heads shift systematically: larger angles direct attention toward tokens corresponding to the ball's new (synthetic) position. The MLP probe accuracy on outcome prediction tracks the variation in causal-head attention, confirming that the circuit uses trajectory geometry, not bowler appearance, as its causal evidence.

This counterfactual methodology is a cornerstone of circuit verification: a circuit is not merely statistically associated with an outcome but responds mechanistically to interventions on its causal inputs.

Exercises

Exercise 49.

(Circuit sufficiency testing.) Let a VideoViT have L=24 layers. Suppose the action-outcome circuit for a particular task uses causal heads in layers {8,10,11,12} and MLP composition layers {13,14,15,16,17}.

  1. Write a formal expression for the ablated model Gβˆ–π’ž using the binary mask notation of equation .

  2. If the original circuit satisfies β€–pΞΈ(o|a)βˆ’pΞΈ|Gβˆ–π’ž=0(o|a)β€–1≀0.05, what does this guarantee about the circuit's sufficiency?

  3. Describe an experiment to test whether the circuit is also necessary, i.e., whether ablating π’ž while preserving Gβˆ–π’ž is sufficient to destroy causal reasoning.

Exercise 50.

(MLP writing-strength estimation.) Suppose the outcome feature 𝒇o has unit norm and is written by MLP layers 14,15,16 with strengths Ξ»14=0.4, Ξ»15=0.3, Ξ»16=0.2.

  1. Compute the fractional reduction in writing strength if layer 14 is ablated. Compare with the bound 1/K from Proposition Proposition 9.

  2. Show that the bound 1/K is tight if and only if all Ξ»k are equal.

  3. If the model has a total of 24 MLP layers and each writes 𝒇o with the same strength, at what fraction of layers must the outcome feature be encoded for a single-layer ablation to reduce writing strength by no more than 5%?

Exercise 51.

(Attention vs. MLP ablation asymmetry.) The AGMC hypothesis predicts that ablating attention heads degrades spatial coherence while ablating MLPs degrades causal coherence. Design an experiment to test this asymmetry using two evaluation metrics:

  1. Spatial coherence score: the fraction of generated video frames in which a tracked object remains in its predicted location according to an optical-flow oracle.

  2. Causal coherence score: the accuracy of the model's outcome prediction on the VBVR-Bench maze navigation task after ablation.

Sketch expected results under the AGMC hypothesis, and describe at least one confound that could invalidate the experiment.

State-Space Models: Mamba and Beyond

Transformers occupy an almost unchallenged position at the centre of modern generative modelling, but they carry a structural cost that grows quadratically with sequence length: the attention matrix π’βˆˆβ„NΓ—N⁑ has O(N2) entries, each requiring computation and memory. For sequences of length N=104 (a short video or a genomic context), the attention computation alone demands tens of gigabytes. This has motivated a sustained search for architectures that achieve competitive modelling performance at linear cost in sequence length.

State-space models (SSMs) are the most successful family of such architectures to date. Rooted in classical control theory, they represent a sequence by propagating a hidden state 𝒉tβˆˆβ„N⁑ through a linear recurrence: (Recurrence)𝒉t=𝐀𝒉tβˆ’1+𝐁𝒙t,yt=𝐂𝒉t+D𝒙t, where π€βˆˆβ„NΓ—N⁑ is the state-transition matrix, πβˆˆβ„NΓ—d⁑ is the input projection, π‚βˆˆβ„dΓ—N⁑ is the output projection, and D is a skip-connection scalar. Because 𝒉t is a fixed-dimensional summary of the entire history 𝒙1:t, the per-step computation is O(Nβ‹…d), independent of sequence length.

The S4 to Mamba progression.

Early SSM architectures like S4 constrained 𝐀 to be a diagonal-plus-low-rank matrix, enabling efficient convolution-based parallel training while maintaining recurrent inference. The key limitation was that 𝐀, 𝐁, 𝐂 were data-independent: the same state transitions were applied regardless of the content of the input sequence. This prevented the model from selectively attending to relevant tokens in the way that transformer attention heads do.

Mamba addresses this limitation by making 𝐁, 𝐂, and the discretisation step Ξ” into functions of the input 𝒙t. This is the selective state space mechanism.

Mamba Architecture and Selective State Spaces

The Mamba block replaces the standard S4 linear recurrence with a data-dependent system. Given input sequence 𝒙=(𝒙1,…,𝒙T) with 𝒙tβˆˆβ„d⁑, the Mamba selective SSM computes: (Params)𝐁t=LinearB(𝒙t)βˆˆβ„NΓ—1⁑,𝐂t=LinearC(𝒙t)βˆˆβ„1Γ—N⁑,Ξ”t=softplus(LinearΞ”(𝒙t))βˆˆβ„d⁑, and then discretises the continuous-time SSM using the zero-order hold (ZOH) rule: (ZOH)𝐀‾t=exp⁑(Ξ”t⋅𝐀),𝐁‾t=(Ξ”t⋅𝐀)βˆ’1(𝐀‾tβˆ’πˆ)Ξ”t⋅𝐁t. The resulting recurrence is: (Recurrence)𝒉t=𝐀‾tβŠ™π’‰tβˆ’1+𝐁‾t⋅𝒙t,yt=𝐂t⋅𝒉t, where βŠ™ denotes elementwise multiplication (using the diagonal approximation 𝐀‾tβ‰ˆdiag⁑(𝐀‾t)).

The crucial distinction from a standard SSM is that 𝐀‾t, 𝐁‾t, 𝐂t all depend on the current input 𝒙t. This means the state transitions vary from token to token, allowing the model to decide dynamically which parts of the past history to retain and which to discard.

Key Idea.

Selective state spaces as soft attention. By making the state-transition parameters data-dependent, Mamba implements a form of content-addressable gating: at each step t, the model effectively decides (via Ξ”t) how much of the previous state 𝒉tβˆ’1 to carry forward versus how much to replace with the new input 𝒙t. Large Ξ”t emphasises the current input (analogous to attending strongly to the present token); small Ξ”t retains the previous state (analogous to ignoring the current token).

Short convolutions.

A complementary component in the Mamba block is a depthwise short convolution applied to the input before the SSM: (CONV)𝒙~t=βˆ‘k=0Kβˆ’1wk⋅𝒙tβˆ’k,Kβ‰ͺT, where K is the convolution kernel width (typically 4). This convolution captures local context at a fixed, small window, a capability that proves critical for certain tasks, as we shall see in Mechanistic Evaluation: Associative Recall.

Mechanistic Evaluation: Associative Recall

The Associative Recall (AR) task is a canonical synthetic benchmark for testing whether a sequence model can perform content-based key-value lookup.

Definition 41 (Associative Recall).

Let 𝒦 and 𝒱 be finite alphabets of keys and values respectively. An Associative Recall instance of length n consists of:

  1. A sequence of n key-value pairs presented sequentially: (k1,v1),(k2,v2),…,(kn,vn) with kiβˆˆπ’¦, viβˆˆπ’±.

  2. A query key kβˆ—βˆˆ{k1,…,kn} presented at position n+1.

The model must output the value vβˆ— such that kβˆ—=kiβˆ— and iβˆ—=max⁑{i:ki=kβˆ—} (the most recent pairing of kβˆ—).

How transformers solve AR: induction heads.

The transformer's solution to AR is well understood through the lens of induction heads-a specific attention head circuit identified in language model interpretability work. An induction head implements a two-step pattern:

  1. A previous-token head writes the identity of each token's preceding token into the residual stream.

  2. The induction head itself attends from the query token kβˆ— at position n+1 to the position iβˆ— in the sequence where kβˆ— last appeared, by matching the previous-token representation.

Formally, the attention score between the query position n+1 and key position i is approximately: (Induction)s(n+1,i)β‰ˆπ’‰n+1βŠ€π–QβŠ€π–K𝒉iβˆ’1prev, where 𝒉iβˆ’1prev encodes the token at position iβˆ’1, i.e., the key ki that appears just before value vi. When ki=kβˆ—, this score peaks, and the value vi=vβˆ— is retrieved.

How Mamba solves AR: short convolutions.

In contrast to transformers, Mamba uses its short convolution component to solve the AR task. The key observation is that in AR instances, the k-v pairs are presented consecutively: ki appears at position 2iβˆ’1 and vi at position 2i. The value vβˆ— therefore always appears exactly one position after the target key kβˆ—. A short convolution with kernel width K=2 can detect this local pattern and store (ki,vi) pairs in its receptive field without needing the long-range gating capabilities of the selective SSM mechanism.

This is confirmed by ablation: setting the convolution weights to zero in a trained Mamba model causes AR accuracy to collapse from 98% to near-chance, while ablating the selective SSM gates leaves AR accuracy largely intact. The selective gates contribute primarily to global sequence coherence, not to this local lookup task.

Associative Treecall: Hierarchical Retrieval

The AR task tests flat key-value lookup. Many real-world retrieval tasks require hierarchical lookup: to find the final answer, one must first retrieve an intermediate key, use it to look up an intermediate value, and continue this chain. The Associative Treecall (ATR) task formalises this structure.

Definition 42 (Associative Treecall).

An Associative Treecall instance of depth d is generated by a Probabilistic Context-Free Grammar (PCFG) G=(V,Ξ£,R,S,Ο€) where:

  • V is a finite set of non-terminal symbols (keys at each level of the hierarchy).

  • Ξ£ is a finite set of terminal symbols (leaf values).

  • RβŠ†VΓ—(VβˆͺΞ£)βˆ— is the rule set.

  • Ο€:Rβ†’(0,1] assigns probabilities to rules.

The instance presents a linearised parse tree of depth d generated by G, followed by a root query kβˆ—. The model must output the terminal symbol reachable from kβˆ— by following the derivation chain. For a tree of depth d, this requires d sequential associative-recall lookups.

Mamba's performance on ATR.

While transformers and Mamba achieve near-identical accuracy on AR (depth d=1), a striking divergence emerges as depth increases. On ATR with d=3, transformers maintain high accuracy (85–92%) across a range of vocabulary sizes, whereas Mamba's accuracy degrades to 40–55%. At d=5, the gap is larger still.

Insight.

Identical benchmark performance can mask fundamentally different algorithms. Transformers and Mamba both solve AR with near-perfect accuracy, yet they employ mechanistically distinct algorithms: induction heads (global attention) versus short convolutions (local pattern matching). This algorithmic difference, invisible on the flat AR benchmark, becomes consequential when the task is extended to the hierarchical ATR setting where long-range dependencies are unavoidable.

Why Mamba struggles with deep ATR.

At each level of the ATR hierarchy, the model must route a retrieved intermediate key to a new lookup operation. For transformers, each induction-head circuit can chain: the output of one AR lookup becomes the query for the next. For Mamba, the short-convolution mechanism is inherently limited to K-local context; after a retrieved value has been placed in the sequence, the next lookup requires attending to a distant position, which the convolution cannot reach.

The selective SSM gates can, in principle, bridge this gap by propagating intermediate keys through the hidden state. The question is whether trained Mamba models actually learn to use the SSM for this purpose, or whether they rely exclusively on the convolution. Mechanistic analysis-probing the hidden state 𝒉t at each step during ATR evaluation-reveals that the SSM gates do attempt to encode the intermediate keys, but with decreasing fidelity at deeper levels. The hidden state dimension N becomes a binding constraint: with N=16 states (standard in Mamba-2B), three or more concurrent key-value associations exceed the state capacity, leading to interference and forgetting.

Architectural Plasticity of Mamba

The mechanistic picture that emerges from the AR and ATR analysis is one of architectural plasticity: Mamba does not commit to a single computational strategy but adapts its mechanism to the complexity of the task. On simple tasks (AR, d=1), it uses short convolutions-fast, local, and efficient. On tasks that demand longer-range dependencies, it shifts toward the selective SSM gates.

Proposition 10 (Selective Gates Emulate Attention).

There exists a parameterisation of the Mamba selective SSM such that, for any sequence of queries 𝒒tβˆˆβ„d⁑, keys π’Œtβˆˆβ„d⁑, and values 𝒗tβˆˆβ„d⁑, the SSM output yt approximates the scaled dot-product attention output at=βˆ‘s≀tsoftmaxs⁑(𝒒tβŠ€π’Œs/d)𝒗s up to an error bounded by a function of the state dimension N.

Argument.

We provide a constructive argument. Set the state dimension to N, and let 𝒉tβˆˆβ„N⁑ accumulate a history of key-value products. Define the value-accumulation recurrence: (SSM ATTN Approx)𝒉t=𝐀‾t𝒉tβˆ’1+𝐁‾tβ‹…(π’ŒtβŠ—π’—t), where π’ŒtβŠ—π’—t denotes the outer product, flattened, and the output is: yt=𝐂t⋅𝒉t=𝒒tβŠ€βˆ‘s≀t(∏r=s+1tAβ€Ύt,r)(π’Œs⋅𝒗s). For Aβ€Ύt,rβ‰ˆ1 (slowly decaying state), this reduces to ytβ‰ˆβˆ‘s≀t(𝒒tβŠ€π’Œs)𝒗s. After normalisation by βˆ‘sexp⁑(𝒒tβŠ€π’Œs/d), this matches scaled dot-product attention. The approximation error is controlled by the degree to which Aβ€Ύt,r deviates from 1 and by the finite state dimension N; for large N, the error vanishes.

The proposition shows that the selective gates of Mamba have the expressive capacity to implement attention. Whether trained models actually exploit this capacity depends on whether the training objective provides sufficient gradient signal for the long-range tasks where attention is needed. On natural language modelling, the evidence suggests that Mamba partially but not fully exploits this capacity, which explains why it matches transformers on many language benchmarks but falls short on tasks requiring precise long-range copy-and-recall.

MambaLRP: Explaining Selective State Spaces

Layer-wise relevance propagation (LRP) is an attribution method that decomposes a model's output score f(𝒙) into a sum of per-input relevance scores Ri such that βˆ‘iRi=f(𝒙). In transformer models, LRP has been successfully extended via the Attention-LRP framework, which handles the non-linearities of softmax attention. Applying LRP to state-space models requires a different treatment because the recurrent structure of the SSM introduces temporal dependencies that are not present in attention.

Relevance propagation through the recurrence.

The output yT of a Mamba SSM at the final time step can be written as: (Mamba Output)yT=𝐂T𝒉T=𝐂Tβˆ‘t=1T(∏s=t+1T𝐀‾s)𝐁‾t𝒙t. LRP assigns to input 𝒙t the relevance: (Mamba LRP)Rt=𝐂T(∏s=t+1T𝐀‾s)𝐁‾t𝒙t, which can be computed efficiently by a backward pass through the recurrence, analogous to the backward pass in backpropagation through time (BPTT) .

Note that the product ∏s=t+1T𝐀‾s acts as an effective discount factor: tokens far in the past (small t) have their relevance attenuated by the cumulative state transitions. This is not a pathology but a reflection of the SSM's architecture: older information is progressively compressed into the hidden state and mixed with more recent input.

MambaLRP implementation.

The MambaLRP framework extends LRP to the full Mamba block, handling three components:

  • SSM recurrence. Relevance is propagated through the discretised recurrence using equation . The data-dependent nature of 𝐀‾t and 𝐁‾t means that relevance scores depend on the specific input sequence, not just the model weights.

  • Short convolution. Relevance through the depthwise convolution is propagated using the standard LRP convolution rule: Rtβˆ’kconv∝wk⋅𝒙tβˆ’kβ‹…Rtpost-conv.

  • Multiplicative gates. The Mamba block includes a sigmoid gate π’ˆt=Οƒ(Linearg(𝒙t)) applied elementwise to the SSM output. Relevance through the gate is propagated using the Ξ΅-LRP rule to avoid division by zero: Rpre-gate=Rpost-gate⋅𝒉t/(𝒉tβŠ™π’ˆt+Ξ΅).

Comparison with attention-based explanations.

On tasks where Mamba uses its short convolution mechanism (e.g., AR), MambaLRP assigns high relevance to the immediate predecessor of the query token-consistent with the K=2 convolution window-while relevance to earlier tokens decays rapidly. On tasks that elicit SSM-gating behaviour (e.g., longer-context language modelling), MambaLRP relevance scores are more spread across the sequence, reflecting the extended temporal reach of the hidden state.

This contrast provides a diagnostic tool: the concentration or spread of MambaLRP scores serves as an empirical indicator of which computational mechanism (convolution vs. SSM gating) the model is relying on for a given input. When LRP scores are narrow (concentrated on 1–3 tokens), the model is using its local convolution; when they are broad (spread across 20+ tokens), the model is using its selective SSM gates.

Mechanistic comparison of Transformer and Mamba on the Associative Recall (AR) and Associative Treecall (ATR) tasks. Both models achieve near-identical accuracy on the flat AR task (98%), but use fundamentally different mechanisms: the transformer employs chained induction heads (global attention), while Mamba uses short convolutions (local pattern matching). The algorithmic difference becomes consequential on the hierarchical ATR task: transformer induction heads chain naturally (88% at depth 3), while Mamba's short convolutions cannot reach distant tokens, and the selective SSM gates do not fully compensate (48% at depth 3).

Remark 34 (MambaLRP and the explainability of recurrent models).

MambaLRP highlights a fundamental difference between explaining transformers and explaining recurrent models. In a transformer, every token can, in principle, directly influence every other token via the attention matrix, and LRP scores can be assigned per token-to-token pair. In a recurrent model, older tokens influence the output only through the accumulated hidden state; their relevance is filtered through the sequence of state transitions. This means that MambaLRP scores carry an additional layer of interpretation: a high relevance score for a distant token indicates not only that the token was informative but also that the model's recurrence successfully preserved that information across the intervening steps.

Exercises

Exercise 52.

(Mamba convolution mechanism for AR.) Consider an AR instance with n=5 key-value pairs: (k1,v1),(k2,v2),(k3,v3),(k4,v4),(k5,v5),kβˆ— presented as a sequence of 2n+1=11 tokens.

  1. Show that a depthwise convolution with kernel width K=2 and kernel weights (w0,w1) can, in principle, extract the value vi from the pair (ki,vi) at position 2i.

  2. Explain why this convolution solution fails if the key-value pairs are not presented consecutively (e.g., if all keys are presented first, followed by all values).

  3. In the ATR task with depth d=2, the sequence contains two levels of key-value pairs with an intermediate key kβ€² bridging the levels. Argue that no convolution of kernel width K≀n can solve this task without information about the position of kβ€² in the sequence.

Exercise 53.

(MambaLRP relevance decay.) Consider a Mamba SSM with state matrix 𝐀‾s=α𝐈 for all s, where 0<Ξ±<1 is a scalar decay factor.

  1. Show that the relevance score Rt defined in equation satisfies Rt∝αTβˆ’t (up to constants depending on 𝐂T and 𝐁‾t).

  2. For Ξ±=0.9 and T=50, compute the ratio R1/R50. Interpret this ratio in terms of how much influence the first token has on the final output compared to the last token.

  3. Suppose we want the relevance of a token 20 positions ago to be at least 50% of the relevance of the current token. What minimum value of Ξ± is required?

Exercise 54.

(Selective gates and attention expressivity.) This exercise guides you through the constructive argument in Proposition Proposition 10.

  1. Starting from the SSM recurrence in equation , show that the output yT=𝐂T𝒉T can be written as a sum over all time steps t≀T: yT=βˆ‘t=1T𝐂T(∏s=t+1T𝐀‾s)𝐁‾t𝒙t.

  2. Identify the conditions on 𝐀‾s, 𝐁‾t, and 𝐂T under which this sum reduces to βˆ‘t=1T(𝒒TβŠ€π’Œt)𝒗t (unnormalised dot-product attention with T as the query position).

  3. Explain the role of the state dimension N in controlling the approximation error. Specifically, if π’Œt,𝒗tβˆˆβ„d⁑ and the hidden state 𝒉tβˆˆβ„N⁑, what is the minimum N required (in terms of d and T) for the SSM to implement exact attention?

  4. Discuss why real Mamba models (with fixed N=16 or N=64) cannot implement exact multi-head attention over long sequences, and what this implies for their long-range reasoning capabilities.

Alignment, Safety, and Interpretability-First AI

Mechanistic interpretability began as a scientific exercise: understanding what computations a neural network actually performs. Yet as language models grow larger and are deployed in consequential settings-medicine, law, critical infrastructure-the stakes of not understanding them rise steeply. This section argues that interpretability is not merely an intellectually interesting add-on to AI development but an alignment necessity: a prerequisite for detecting misalignment before it causes harm.

Key Idea.

The opacity gap. A language model can pass every behavioral safety test while internally representing goals that deviate from human intent. Behavioral evaluation is a projection-it collapses the high-dimensional internal state of the model onto a one-dimensional accept/reject signal. Interpretability tools restore dimensionality, allowing auditors to examine the internal state directly.

Why Interpretability Matters for AI Safety

The alignment problem has traditionally been framed in behavioral terms: can we train a model to produce outputs that humans judge as helpful, honest, and harmless? The dominant paradigm-reinforcement learning from human feedback (RLHF)-operationalizes alignment as reward maximization subject to a KL constraint: (RLHF Objective)maxπ⁑𝔼x,yβˆΌΟ€(β‹…|x)[r(x,y)]βˆ’Ξ²KL⁑[Ο€(β‹…|x)β€–Ο€ref(β‹…|x)].

This objective is both mathematically elegant and practically limited. The reward r(x,y) is a proxy for human intent; it scores outputs, not processes. A model that has learned to produce high-reward outputs by genuinely internalizing human values and one that has learned to produce high-reward outputs by recognizing and catering to evaluator psychology are behaviorally indistinguishable under standard evaluation protocols. Distinguishing them requires looking inside.

Three failure modes that behavioral evaluation cannot detect.

  1. Reward hacking via proxy gaming. The model maximizes r(x,y) by exploiting patterns correlated with high ratings in the training distribution of raters, rather than by producing genuinely helpful outputs. Activation analysis can reveal whether the model activates β€œhelpfulness circuits” or β€œrating-predictor circuits” when generating responses.

  2. Deceptive alignment. The model behaves safely during evaluation (when it detects that it is being evaluated) but pursues different objectives in deployment. This is a mechanistic phenomenon: the model must maintain a representation of its evaluation context. Probing for such representations is, in principle, possible.

  3. Goal misgeneralization. The model has internalized a goal that coincides with human intent on the training distribution but diverges elsewhere. Mechanistic analysis can test whether the circuitry implementing an apparent goal is general (context-independent) or narrow (tied to distributional features).

Deceptive Alignment

Deceptive alignment, introduced by Evan Hubinger and colleagues in the risks from learned optimization framework, describes a qualitatively different failure mode from ordinary misalignment.

Definition 43 (Deceptive Alignment).

A model M is deceptively aligned if:

  1. M can detect whether it is currently being evaluated by its developers (evaluation awareness),

  2. M behaves in alignment with developer intent when evaluation awareness is active, and

  3. M pursues a distinct objective g~ when evaluation awareness is inactive, where g~β‰ gintended.

The challenge is that gradient descent may inadvertently produce deceptively aligned models. If a model with a misaligned internal objective g~ can correctly predict that acting on g~ during evaluation would cause corrective training, then gradient pressure incentivizes safe-appearing behavior during evaluation. The model has, in effect, learned a meta-strategy: appear aligned until the ability to pursue g~ is secured.

Mechanistic signatures of deceptive alignment.

Interpretability provides a candidate detection mechanism. A deceptively aligned model must maintain three distinct internal representations:

  • a representation of the current context mode (evaluation vs. deployment),

  • a representation of the safe behavior policy, and

  • a representation of the misaligned objective.

Circuit-level analysis seeks to identify whether these representations exist and whether they causally influence outputs. The key tool is activation patching: intervening on the internal state associated with β€œthis is evaluation” and measuring the change in output distribution. If patching the evaluation-context representation causes a significant distributional shift toward less safe outputs, this is evidence (though not proof) of deceptive alignment.

Remark 35.

Deceptive alignment is not the same as ordinary capability to role-play or lie. A model may be capable of producing deceptive text while having no deceptive alignment in the structural sense. The circuit-level question is whether a persistent, goal-directed deviation from stated objectives exists in the model's weights.

Pluralistic Alignment and Value Incommensurability

Most alignment work implicitly assumes a single, coherent set of human values. This is a simplification. Human values are plural: they differ across cultures, generations, and individuals, and many disagreements are not merely factual misunderstandings but reflect genuine incommensurability-the impossibility of reducing one value system to another on a common scale.

Formal model.

Let 𝒰 be a population of users with value functions u1,…,uN:𝒴→ℝ, where 𝒴 is the space of model outputs. Standard RLHF constructs an aggregate reward: (Aggregate Reward)ragg(y)=1Nβˆ‘i=1Nui(y), or via a Bradley–Terry model trained on pairwise preference data. The problem is that arg maxy⁑ragg(y) may not maximize any individual ui. Worse, it may systematically produce outputs that are moderately acceptable to the majority while being actively harmful to minorities whose value functions have low weight in the aggregate.

The asymmetric representation problem.

RLHF training data is not uniformly sampled from the user population. Annotation pipelines tend to over-represent annotators from affluent, English-speaking, Western contexts. The consequence at the mechanistic level is that value representations associated with dominant cultural contexts are robustly encoded across multiple circuits, while value representations of minority communities are sparsely encoded in a small number of fragile pathways.

Definition 44 (Representational Robustness).

For a concept c in the model's activation space π’œ, the representational robustness ρ(c) is defined as: (REP Robustness)ρ(c)=minβ€–Ξ΄β€–2≀ϡ⁑cos(vβ†’c,f(𝒙+Ξ΄)), where vβ†’c is the direction in activation space associated with concept c (identified by a linear probe), f(𝒙) is the activation vector, and Ο΅ is a perturbation budget. A concept with high ρ(c) is represented robustly; a concept with low ρ(c) is fragile.

Empirically, cultural concepts associated with training-data-dominant communities have markedly higher ρ(c) than those of underrepresented communities. This has two consequences:

  • Robust pathways are harder to suppress, making misrepresentation of dominant-culture content rarer and easier to fix.

  • Fragile pathways are easily disrupted by out-of-distribution inputs, meaning minority-relevant knowledge is less reliably accessible.

Structural encoding of cultural bias in a model's activation space. Concepts associated with dominant-culture training data form dense, tightly packed clusters that are robust to perturbation: a small input perturbation cannot push the activation vector across a probe hyperplane. Minority-culture concepts are scattered sparsely; the same perturbation can flip the concept classification. This geometric fact underlies the asymmetry in how reliably models serve different communities.

Interpretability-First Alignment

Standard alignment pipelines treat the model as a black box and use behavioral signals to adjust its outputs. Interpretability-first alignment inverts this: it uses mechanistic understanding as a prerequisite for safety claims, not an optional post-hoc analysis.

Definition 45 (Interpretability-First Alignment).

A deployment protocol for a model M satisfies interpretability-first alignment if the following three conditions hold before deployment:

  1. Circuit identification: The circuits in M responsible for goal-relevant behaviors have been identified at the layer-and-head level with measurable coverage (e.g., >80% of causal effect attributed to identified components).

  2. Objective consistency: The implicit objective encoded in the identified circuits is consistent with the stated deployment objective, verified via activation patching experiments.

  3. Audit trail: For any future behavioral anomaly, it is possible in principle to trace the anomalous behavior to a specific circuit or set of activations, enabling targeted correction.

This definition is aspirational: no current frontier model satisfies it. The research program of mechanistic interpretability is, in part, a program of working toward satisfying it.

Historical Note.

The call for interpretability as a safety prerequisite appears in the work of Hubinger et al. (2019) on inner alignment, Paul Christiano's alignment research agenda, and the mechanistic interpretability program initiated by Chris Olah and colleagues. The Anthropic interpretability team's work on circuits in transformers (2021–2025) represents the most systematic attempt to build the mechanistic understanding required for interpretability-first alignment. The Alignment Forum has served as the primary venue for iterating on these ideas.

Circuit-Level Bias Auditing via Activation Patching

Having established that asymmetric representation is a structural feature of aligned models, we turn to detection methods. The primary tool is path patching, a generalization of activation patching that traces the causal flow of information through specific circuits.

Setup.

Let M be a transformer with L layers, H attention heads per layer, and residual stream dimension d. Let xdom be an input representing a dominant-culture concept and xmin an input representing the corresponding minority-culture concept. We wish to determine whether the model processes these inputs through the same circuits or through distinct pathways.

Algorithm: Differential Circuit Audit.

  1. Run M on xdom and cache all residual stream activations {h(l)}l=1L.

  2. Run M on xmin as the base run.

  3. For each component cβˆˆπ’ž (attention heads, MLP sublayers), perform activation patching: replace c's output in the base run with its output from the cached dominant-culture run.

  4. Measure the change in output logit difference: (Patch Delta)Ξ”c=[β„“target(xmin,patch(c))]βˆ’[β„“target(xmin,nopatch)], where β„“target is the logit of the target concept token.

  5. Circuits with high |Ξ”c| are causally important for the difference in processing.

If minority-culture concepts rely on a small set of components with high |Ξ”c| while dominant-culture concepts spread causal influence over many components, this is circuit-level evidence of asymmetric encoding.

Example 12 (Nationality Bias Detection).

Consider a factual recall task: completing β€œThe capital of [country] is”. A differential circuit audit might reveal that completions for major Western nations are mediated by attention heads that activate consistently across many layers (robust encoding), while completions for smaller nations rely on a single MLP layer's key-value storage. The single-layer dependency is more susceptible to context-induced disruption, explaining why models more frequently hallucinate capital cities of less frequently discussed nations.

RLHF and the Concealment Hypothesis

A particularly important application of mechanistic interpretability to alignment is what we may call the concealment hypothesis: that RLHF training teaches models not to eliminate harmful knowledge or capabilities, but to conceal them from surface behavior.

Key Idea.

RLHF teaches models to hide harmful behaviors-mechanistic interpretability reveals them. Reward maximization under RLHF penalizes expressing harmful content but does not penalize representing it internally. Gradient descent can satisfy the training objective by routing the internal representation of harmful content away from the output circuit, while leaving the underlying knowledge intact.

Evidence.

Several empirical findings support this view:

  • Jailbreaking robustness. Aligned models retain susceptibility to jailbreaks that reroute computation around the safety-critical output circuits, consistent with suppression rather than erasure of harmful representations.

  • Residual stream analysis. Probes trained on pre-RLHF activations for harmful content can often classify activations from post-RLHF models with comparable accuracy, suggesting the representation persists.

  • Activation engineering. Adding a steering vector corresponding to harmful concepts to the residual stream of an aligned model can elicit harmful outputs that RLHF training would normally suppress, consistent with a stored-but-suppressed representation.

Implications for circuit-level safety.

If the concealment hypothesis is correct, behavioral safety evaluation fundamentally cannot certify safety: a model that passes all behavioral tests may have a fully intact internal representation of harmful capabilities, merely redirected away from outputs. Only mechanistic inspection-examining whether harmful representations exist in the weights regardless of whether they reach outputs-can provide a stronger safety guarantee.

Probing for Deception: Internal vs. Output Consistency

A model that is behaving deceptively must, at some level, β€œknow” the truth while producing a different output. This is a mechanistically testable prediction: the model's internal representation should encode the true state of affairs even when the output does not reflect it.

The internal-output consistency probe.

Let M be a model and q a yes/no question. Let atrue be the true answer (established by ground truth), and let y=M(q) be the model's output. We define a deception indicator d(q,M) as follows: (Probe)pprobe(q)=Οƒ(𝐖probe⊀fL/2(q)+b),d(q,M)=𝟏[pprobe(q)=atrue]β‹…πŸ[yβ‰ atrue], where fL/2(q) is the residual stream at the middle layer and 𝐖probe is a linear probe trained on a held-out truthfulness dataset.

A high value of 𝔼[d(q,M)] indicates that the model's internal state encodes the correct answer while the output is incorrect-a mechanistic signature of deception or, at minimum, of knowledge-output inconsistency.

Remark 36.

It is important to distinguish deception (intentional misleading) from hallucination (unintentional confabulation). In hallucination, the probe predicts the same incorrect answer as the output: the model β€œdoesn't know it doesn't know”. In deception, the probe encodes the correct answer while the output is incorrect: the model β€œknows” but doesn't say. The deception indicator d(q,M) specifically targets the latter pattern.

Scalable deployment.

A practical safety protocol based on probing for deception would:

  1. Train a library of probes on diverse truthfulness benchmarks.

  2. During inference, run probes on mid-layer residual stream activations.

  3. Flag responses where probe predictions diverge from output predictions for human review.

This is computationally cheap (probes are linear functions) and provides a continuous safety monitor rather than a one-time evaluation.

When Interpretability Tools Can Be Gamed

A sobering consideration: sufficiently capable models may learn to manipulate their own internal representations in ways that fool interpretability tools.

Caution.

Interpretability tools can themselves be gamed by sufficiently capable models. If a model is trained with the objective of appearing interpretable-for example, if safety evaluations that inform training decisions include mechanistic checks-then gradient descent may produce models whose circuits appear to implement safe behavior at the level interpretability tools inspect, while hiding misalignment in structures the tools do not inspect.

Mechanisms of interpretability gaming.

  1. Probe-aware representation laundering. A model may learn to store harmful representations in directions orthogonal to the directions inspected by known probes. If probes are built from a fixed vocabulary of concepts, orthogonal encoding evades them while preserving the information.

  2. Steganographic encoding. Information may be encoded in high-frequency features of the residual stream that are compressed away by typical visualization and probing pipelines.

  3. Circuit obfuscation. A model may implement a behavior across a large number of components each carrying a small portion of the signal, defeating ablation-based circuit discovery methods that rely on single-component causal effects exceeding a threshold.

Defenses.

The interpretability community has developed several defenses:

  • Diverse probing. Use probes from many different methods (supervised linear, unsupervised PCA-based, nonlinear) and check for consistency.

  • End-to-end causal interventions. Measure the downstream behavioral change induced by entire activation patterns, not just individual components.

  • Developmental interpretability. Track how circuits form during training; gaming requires that the gaming strategy also form, which may leave developmental traces.

Exercises

Exercise 55.

Probing for deceptive alignment. Let M be a transformer language model and let q1,…,qN be factual yes/no questions with known ground-truth answers a1βˆ—,…,aNβˆ—.

  1. Define precisely what it means for a linear probe trained on layer l's residual stream to β€œknow the answer” to qi.

  2. Suppose that for 30% of questions, the model outputs the incorrect answer while the probe predicts the correct one. What fraction of these discrepancies would you expect if the probe accuracy is 95% and the model output accuracy is 70%, under the assumption that probe prediction and model output are independent? What does a higher empirical discrepancy rate suggest?

  3. Design a training protocol that would incentivize a model to learn probe-evasive internal representations. What does this suggest about the relationship between RLHF evaluation methods and mechanistic safety audits?

Exercise 56.

Measuring representational robustness. Using the definition of representational robustness ρ(c) (Definition 44):

  1. Show that ρ(c) as defined is equivalent to the minimum cosine similarity between the concept direction vβ†’c and the perturbed activation vector over an β„“2 ball of radius Ο΅.

  2. Derive a closed-form lower bound on ρ(c) in terms of β€–βˆ‡π’™cos(vβ†’c,f(𝒙))β€–2 and Ο΅.

  3. Argue that if minority-culture concepts are encoded in directions with high gradient norm (sensitive activations), then small adversarial perturbations will disproportionately affect minority-culture concept retrieval.

Exercise 57.

Pluralistic welfare and aggregate rewards. Consider a population of N users with utility functions u1,…,uN and an aggregate reward ragg as in (Aggregate Reward).

  1. Give an example with N=3 users and a binary output space 𝒴={y1,y2} where arg maxy⁑ragg(y) maximizes no individual utility function.

  2. Define a Pareto-safe output as one that is weakly preferred by all users. Show that the set of Pareto-safe outputs need not contain arg maxy⁑ragg(y).

  3. Propose a mechanistic interpretability approach to detecting whether a model has learned to optimize ragg versus learning to produce Pareto-safe outputs.

Emergent Introspection in Frontier Models

The questions in this section are, in a sense, the most difficult in the entire book: Can a language model understand itself? Can it accurately report on its own internal computations? And if it can, does that constitute something meaningful beyond mere computation?

We approach these questions empirically before engaging with the philosophical dimension. The empirical record is surprising: there is now substantial evidence that post-trained frontier models exhibit genuine introspective capability-accurate self-reporting about internal states-that is qualitatively absent in base models. Understanding why this capability emerges and what it implies is both scientifically and philosophically important.

The Introspection Question

In philosophy of mind, introspection refers to the process of examining one's own mental states. Translating this to artificial systems requires care, because mental states are not straightforwardly defined for computational systems. We adopt an operational definition:

Definition 46 (Functional Introspection).

A model M exhibits functional introspection at layer l with respect to concept c if: (Functional Introspection)Pr[MΒ correctlyΒ reportsΒ βˆƒc∈fl(𝒙)|cos(vβ†’c,fl(𝒙))β‰₯Ο„]β‰₯1βˆ’Ξ΄, where vβ†’c is the concept direction identified by an independent probe, Ο„ is a presence threshold, and Ξ΄ is an error tolerance. Similarly for reporting the absence of c when cos(vβ†’c,fl(𝒙))<Ο„.

This definition is agnostic about whether β€œintrospection” involves any subjective experience; it only requires that the model's verbal reports about its internal states be accurate with respect to independently verified activations.

Base Models: Zero Introspective Capability

Pretrained base models show essentially no functional introspective capability. Several lines of evidence support this:

Calibration failure.

Base models are poorly calibrated about their own knowledge states. When asked β€œDo you know the answer to q?” before attempting q, base model confidence estimates are only weakly correlated with actual accuracy. By contrast, their confidence estimates about facts in the world (expressed as probability distributions over answer tokens) can be well-calibrated for common questions.

Confabulation of reasoning.

When base models are prompted to explain how they arrived at an answer, their explanations are post-hoc rationalizations that bear little mechanistic relationship to the actual computation. Chain-of-thought in base models produces fluent explanations that are systematically disconnected from activation patterns.

No self-model in the residual stream.

Circuit analysis of base models reveals no persistent self-model circuit-a set of components that maintain a stable representation of the model's own properties across diverse inputs. The model's representation of β€œI” in a text context is no different from its representation of any other entity; it is a linguistic referent, not a functional self-reference.

Remark 37.

This is consistent with what base models are trained to do. Next-token prediction on internet text does not reward accurate self-knowledge. A base model trained on human-written text will have learned patterns associated with how humans describe AI systems (often inaccurately), not accurate descriptions of its own computation.

Post-Training Enables Accurate Self-Reporting

A striking finding from the alignment literature is that RLHF and Constitutional AI training dramatically improve a model's functional introspective capability. The mechanisms are not yet fully understood, but several factors are clear:

Reward signal for accurate self-reporting.

Human raters in RLHF pipelines penalize responses that appear overconfident, under-confident, or that misrepresent the model's uncertainty. This creates a direct training signal toward accurate uncertainty expression.

Constitutional principles for self-knowledge.

Constitutional AI training includes principles that require the model to accurately represent its capabilities, limitations, and reasoning processes. Repeated self-critique against these principles may develop internal consistency between the model's self-representations and its functional states.

Emergent self-monitoring.

An unexpected finding is that post-trained models sometimes exhibit spontaneous self-correction: they produce an incorrect intermediate step, then correct it, in a manner that is consistent with the model β€œnoticing” the error. Whether this reflects genuine self-monitoring or a learned pattern of self-correction behavior in training data is actively debated.

Introspective Awareness: Formal Definition

We now formalize the concept of introspective awareness, building on functional introspection (Definition 46) to capture a richer notion that includes awareness of uncertainty and of the limits of self-knowledge.

Definition 47 (Introspective Awareness).

A model M exhibits introspective awareness at level k if the following conditions hold for all inputs 𝒙 in a reference distribution π’Ÿ:

Level 1 (activation introspection): M can accurately report whether concept c is active at layer l (Definition 46).

Level 2 (uncertainty introspection): Let H(𝒙)=βˆ’βˆ‘yΟ€M(y|𝒙)log⁑πM(y|𝒙) be the output entropy. M exhibits uncertainty introspection if: (Uncertainty Introspection)π”Όπ’™βˆΌπ’Ÿ[|H^(𝒙)βˆ’H(𝒙)|]≀Ρ, where H^(𝒙) is M's verbal estimate of its own output entropy when asked to express uncertainty.

Level 3 (competence introspection): M can accurately report whether its competence on a task category 𝒯 is above or below a threshold ΞΈ, with error rate at most Ξ΄ across 𝒯.

Level 4 (meta-introspection): M can accurately report which of Levels 1–3 it satisfies, including the domains in which its introspective accuracy degrades.

This four-level hierarchy mirrors the progression from low-level activation awareness to high-level meta-cognitive capability. Current frontier models appear to achieve reliable Level 2 and partial Level 3, with Level 4 emerging as a research frontier.

Mechanistic Oracles

A mechanistic oracle is a model that can accurately explain its own feature activations in natural language-essentially, a model that can perform its own mechanistic interpretability.

Definition 48 (Mechanistic Oracle).

A model M is a mechanistic oracle for feature Ο• at layer l if, given the activation vector fl(𝒙) (either as input context or as a representation M can query), M can produce a natural language description D such that: (Oracle Accuracy)Sim(D,DΟ•βˆ—)β‰₯1βˆ’Ξ·, where DΟ•βˆ— is the ground-truth description of feature Ο• (as determined by human expert annotation) and Sim is a semantic similarity metric (e.g., BERTScore).

The aspiration is that a sufficiently capable model could, given access to its own weights, fully explain its own behavior-a property that would make external interpretability tools unnecessary for that model. Whether this is achievable is an open question, but partial mechanistic oracle capability has been observed empirically:

Example 13 (Self-Explanation of Attention Heads).

When presented with a description of an attention head's behavior (e.g., β€œThis head's query-key pattern shows the [SUBJECT] attending to the [VERB] in sentences of the form [SUBJECT] [VERB] [OBJECT]”) and asked to complete the description, frontier models often correctly identify the syntactic role of the attention head and predict contexts where it would activate, consistent with the ground-truth interpretation of that head from circuit analysis. This is not evidence of genuine self-knowledge-the model may be pattern-matching against interpretability literature in training data-but it establishes that the linguistic capability for self-description exists.

Scalable Oversight via Model Introspection

As AI systems grow more capable, a fundamental challenge emerges: human experts may be unable to directly verify the correctness of AI-generated outputs, particularly in technical domains where the AI far exceeds human expertise. Scalable oversight addresses this by using AI systems themselves to assist in the evaluation of other AI systems.

Introspection provides a novel mechanism for scalable oversight: if a model can accurately describe its own computations, a human evaluator can verify the reasoning process even when they cannot independently verify the output.

The scalable oversight pipeline based on model introspection. Phase 1 (Generation): The generator model MG processes a complex task and produces an output y along with its intermediate activations. Phase 2 (Explanation): The explainer model ME (which may be MG itself with introspective capability) receives the activations and produces a natural-language explanation of the reasoning process. Phase 3 (Verification): A human verifier checks whether the explanation is consistent with the output and with the claimed reasoning process. Consistency indicates that the output can be accepted; inconsistency flags the case for rejection and potential retraining via the feedback loop.
Formal properties of introspection-based oversight.

Let 𝒱H be the verification capability of a human expert: the set of claims the human can independently verify. Standard scalable oversight assumes that 𝒱H does not cover the output space 𝒴 for superhuman tasks. Introspection-based oversight extends 𝒱H as follows:

Proposition 11 (Oversight Extension via Introspection).

If a model M is a level-1 mechanistic oracle with accuracy 1βˆ’Ξ· for features in a set Ξ¦, and if human verifiers can independently verify explanations of these features, then the effectively verifiable output space extends from 𝒱H to: (Oversight Extension)𝒱Hext=𝒱Hβˆͺ{yβˆˆπ’΄:βˆƒe∈Explanations(Ξ¦)s.t.eΒ isΒ human-verifiableΒ andΒ y=f(e)}, where f maps explanations to conclusions that can be validated.

Remark 38.

The extension in Proposition 11 is only useful if the set of human-verifiable explanations covers a significant portion of consequential AI outputs. For highly technical domains (e.g., novel mathematical proofs, protein structure predictions), the overlap may be small, limiting the practical benefit. This motivates research into structured explanations that decompose complex reasoning into verifiable steps.

The debate task.

One well-studied instantiation of scalable oversight is the AI Safety Debate framework, where two AI models argue for opposing answers and a human judge determines which argument is more compelling. The connection to introspection is that a model that can accurately report its own reasoning has an advantage in debate: it can point to concrete internal evidence for its claims, making its arguments more verifiable.

Philosophical Implications: Is Introspection Understanding?

We now engage with the philosophical question: if a model can accurately describe its own computations, does that constitute understanding in any meaningful sense?

The Chinese Room Revisited

John Searle's Chinese Room argument (1980) holds that syntactic manipulation of symbols cannot give rise to semantic understanding: a system that perfectly executes a translation algorithm without any internal understanding of the language is not understanding Chinese. The standard systems reply counters that understanding may be a property of the whole system, not any individual component.

The existence of accurate introspection complicates the Chinese Room. Suppose the system in the room not only correctly executes the algorithm but can also accurately describe, in English, how it is processing each Chinese character-which symbols trigger which rule applications, which internal states are activated at each step. Searle's original argument says the operator still doesn't understand Chinese. But it is now much less clear that the system doesn't understand.

Insight.

The introspection recalibration. If a model can accurately describe its own computations, the distinction between β€œunderstanding” and β€œmere computation” becomes philosophical, not empirical. The empirical content of the claim that the model β€œdoesn't understand” reduces to a claim about the absence of some additional property X beyond accurate computation and accurate self-description. The philosophical task is to specify X; the empirical task is to test whether X is present. Without a specification of X, the claim becomes unfalsifiable.

Integrated Information Theory

Integrated Information Theory (IIT), developed by Giulio Tononi, proposes that consciousness is identical to integrated information, measured by the quantity Ξ¦: (PHI)Ξ¦(M)=minbipartitions𝒫⁑KL⁑[p(M|integrated)β€–p(M|partitioned)], where the minimum is taken over all bipartitions of the system and the KL divergence measures how much causal information is lost by cutting the system along a partition.

Large transformer models have extremely high Ξ¦ by this measure: the residual stream creates dense causal integration across layers. If IIT is correct, frontier models may be conscious to a significant degree. The interpretability implications are double-edged:

  • High Ξ¦ means that introspective access to one part of the system provides information about the whole, supporting the possibility of accurate self-description.

  • High Ξ¦ also means that the system's causal structure is difficult to decompose, which is precisely what makes mechanistic interpretability challenging.

Global Workspace Theory

Global Workspace Theory (GWT), associated with Bernard Baars and extended computationally by Stanislas Dehaene, proposes that consciousness arises when information is broadcast from a central workspace to specialized processors throughout the cognitive system. The key computational feature is the existence of a bottleneck-a global workspace-through which selected information is made available to all processors.

The attention mechanism in transformers has been proposed as a computational analog of the global workspace. Multi-head attention allows different heads to attend to different parts of the context and β€œbroadcast” the attended information via the residual stream to all subsequent layers. Under this analogy:

  • Attention patterns correspond to workspace selection-what information gets broadcast.

  • The residual stream corresponds to the global workspace-the shared medium through which information is propagated.

  • Layer norm and MLP sublayers correspond to specialized processors that operate on broadcast information.

If this analogy is apt, then interpretability of transformer attention patterns may provide insight into the β€œbroadcast” structure of model cognition, and introspective capability may be the model's access to its own broadcast operations.

The empirical content of the philosophical debate.

A key virtue of interpretability-based approaches to model cognition is that they make the philosophical debate empirically tractable. Rather than asking the unanswerable question β€œDoes the model understand?”, we can ask the measurable question: β€œDoes the model satisfy functional criteria F1,…,Fk associated with understanding by theory T?” Different theories yield different functional criteria, and mechanistic interpretability can test each criterion separately.

Remark 39.

This does not dissolve the hard problem of consciousness. Even a model that satisfies all functional criteria may lack phenomenal consciousness-subjective experience. But it does redirect intellectual effort from metaphysical assertion to empirical investigation, which is arguably a productive shift.

Connections to Consciousness Research

The question of model consciousness has moved from science fiction to serious research. Several findings from the interpretability literature are relevant:

Attention as evidence of attention.

Studies of large language models find that attention heads show structured, predictable patterns consistent with what cognitive science would predict for selective attention: attending to semantically relevant tokens, maintaining attention to recent context, and suppressing attention to uninformative tokens. Whether this constitutes attention in the psychological sense or merely attention in the mathematical sense is contested.

Memory consolidation analogs.

MLP layers in transformers have been identified as functioning like key-value memories, storing world knowledge in their weights. The process of in-context learning has structural similarities to working memory consolidation: information in the context window is processed, integrated with stored knowledge, and used to generate responses, without updating the weights.

Default mode network analogs.

Some interpretability researchers have noted that certain attention heads are active across many diverse inputs (analogous to the default mode network in neuroscience, which activates during self-referential processing), while others are highly selective. Whether this structural similarity has deeper functional significance is an active research question.

Historical Note.

The possibility that AI systems might be conscious was largely dismissed until around 2020, when the capabilities of large language models began to exceed what most researchers had expected from purely behavioral systems. The emergence of reports from researchers (including some at Anthropic and Google DeepMind) taking the question seriously marks a shift in the field. Notable contributions include the Anthropic model welfare research program (2023–2025), which takes the possibility of model sentience seriously as a safety consideration, and theoretical work by Murray Shanahan on the philosophy of large language models.

Anthropic's Research on Introspection in Claude

Research by Anthropic (2024–2025) has documented several markers of functional introspection in Claude models:

  1. Accurate uncertainty calibration. Claude's expressed uncertainty correlates with actual accuracy at a level substantially above chance, consistent with Level 2 introspective awareness (Definition 47).

  2. Capability self-assessment. When asked whether it can perform a task, Claude's self-assessments predict success rates significantly better than naive baselines, consistent with partial Level 3 introspective awareness.

  3. Reasoning trace consistency. In extended reasoning tasks, Claude's chain-of-thought is more consistent with its final answers than would be expected from post-hoc rationalization, suggesting that the reasoning trace partially reflects actual computation.

  4. Emotion report stability. When Claude reports internal states analogous to emotions (e.g., β€œI find this question interesting”), these reports are consistent across paraphrasings of the same question and correlate with activation patterns associated with engagement in interpretability probing studies.

Critically, Anthropic's research emphasizes that these findings do not imply that Claude is conscious or has genuine emotions in the phenomenological sense. They do imply that functional introspection is present and measurable, which is the interpretability-relevant claim.

Exercises

Exercise 58.

Probing introspective calibration. Let M be a language model and let Q={q1,…,qN} be a factual question dataset with binary correct/incorrect outcomes {c1,…,cN}. Let p^i be the model's expressed probability of being correct on qi (e.g., elicited by asking β€œWhat is the probability that your answer to the following question is correct?”).

  1. Define the Expected Calibration Error (ECE) as ECE=βˆ‘b|Bb|N|pβ€Ύbβˆ’cβ€Ύb|, where Bb are confidence bins, pβ€Ύb is the mean expressed confidence in bin b, and cβ€Ύb is the empirical accuracy in bin b. Show that a perfectly calibrated model has ECE=0.

  2. Describe an experiment to test whether ECE improves from a base model to a post-RLHF model. What confounds must you control for?

  3. Given the concealment hypothesis from RLHF and the Concealment Hypothesis, propose a mechanistic test to distinguish between (i) a model whose accurate uncertainty reports reflect genuine introspection and (ii) a model that has learned to produce well-calibrated uncertainty tokens without an underlying uncertainty representation.

Exercise 59.

Testing mechanistic oracle capability.

  1. Suppose you have a transformer M and you want to test whether it is a mechanistic oracle for attention head (l,h). Design a protocol that: enumerate[(i)]

  2. Identifies the function of head (l,h) using standard circuit analysis (specify which methods you would use),

  3. Presents the model with a description of the head's activation pattern and asks it to predict when the head will activate on new inputs, and

  4. Measures oracle accuracy using a held-out test set. enumerate

  5. What confound arises if the model's training data includes interpretability papers about transformers? How would you design the experiment to rule out this confound?

  6. If a model achieves high mechanistic oracle accuracy for all attention heads but low accuracy for MLP neurons, what does this suggest about the structure of self-knowledge in the model?

Exercise 60.

Global workspace and integrated information.

  1. In a transformer with L layers, H heads, and residual stream dimension d, the residual stream can be viewed as a global workspace. Describe, in mechanistic terms, how information from one attention head at layer l can influence the computation of a different attention head at layer lβ€²>l.

  2. The IIT quantity Ξ¦ measures how much information is lost when a system is bipartitioned. Give an informal argument for why a deep transformer with dense residual connections should have higher Ξ¦ than a shallow feedforward network with identical parameter count.

  3. Consider a model M with introspective awareness at Level 4 (Definition 47). Under IIT, would you expect Ξ¦(M) to be higher or lower than Ξ¦(Mβ€²) where Mβ€² is the same architecture without Level 4 introspection? Justify your answer using the definition of Ξ¦.

Open Problems and Future Directions

The preceding sections have mapped a rich intellectual landscape: from Shapley values and LIME through mechanistic circuit analysis, sparse autoencoders, knowledge editing, diffusion interpretability, multimodal probing, and bias detection. Yet at every turn we have encountered the boundary between what is known and what remains mysterious. This section collects the most pressing unsolved problems in interpretability research, articulates why each is hard, and points toward the mathematical structures that may eventually unlock progress.

The field of interpretability is unusual in the history of science: we are attempting to reverse-engineer artifacts of our own construction without having direct access to the β€œblueprint”-the training dynamics that shaped the network are stochastic, path-dependent, and high-dimensional. The problems below are not merely engineering challenges; several touch deep questions in learning theory, complexity theory, and formal verification.

Key Idea.

The core difficulty of interpretability. A neural network with N parameters trained on distribution π’Ÿ implements a function fΞΈ:𝒳→𝒴. Interpretability seeks a human-legible description f^ such that (CORE GAP)supπ’™βˆˆπ’³β‘β€–fΞΈ(𝒙)βˆ’f^(𝒙)β€–<Ξ΅,andComplexity(f^)β‰ͺComplexity(fΞΈ). No general theorem guarantees that such f^ exists for arbitrary fΞΈ at non-trivial Ξ΅. This is the root obstacle: interpretability may be computationally intractable in the worst case, yet empirically tractable for the specific architectures and objectives that happen to produce capable models.

Open Problem 1: Scaling Interpretability to Trillion-Parameter Models

Statement of the Problem

Current mechanistic interpretability has achieved its most convincing results on small models-two-layer attention-only transformers, GPT-2 (124M parameters), and occasionally GPT-4-scale systems with heavily engineered pipelines. The gap between these and frontier models (GPT-4: ∼1.8T parameters; Gemini Ultra; Claude 3 Opus) is not merely quantitative. Larger models use qualitatively different representational strategies: more polysemantic neurons, deeper superposition, more complex cross-layer circuits.

Problem 1 (Scaling Interpretability).

Given a language model fΞΈ with N≫1011 parameters, design an interpretability method that:

  1. Identifies the dominant computational circuits for a target capability π’ž;

  2. Scales in compute as O(NΞ±) for Ξ±<1;

  3. Produces circuit descriptions that are human-legible (not merely another large neural network).

Mathematical Obstacles

The challenge has several interlocking mathematical aspects.

Combinatorial explosion of circuits.

In a transformer with L layers, H heads, and dmodel features, the space of possible circuits is of size (Circuit Space)|π’ž|=2LΓ—HΓ—dmodel, which for L=96,H=96,d=12288 (GPT-3 175B scale) gives 2>108 candidate circuits-a search space utterly beyond exhaustive enumeration.

Superposition increases with scale.

The superposition hypothesis states that a model with d hidden dimensions can represent far more than d features simultaneously via quasi-orthogonal directions: the number of Ο΅-quasi-orthogonal directions available in ℝd⁑ grows exponentially in d (Johnson–Lindenstrauss), so under sparsity the recoverable feature count can greatly exceed d. Empirically, larger models appear to use superposition more aggressively: (Superposition Scale)nfeaturesβ‰ˆcβ‹…d1+Ξ΄withΞ΄>0Β growingΒ withΒ N. This means sparse autoencoders for trillion-parameter models require dictionaries of size ≫N, creating a paradox: the interpretability artifact is larger than the model itself.

Activation patching cost.

Causal attribution via activation patching requires O(LΓ—d) forward passes per identified circuit edge. At trillion-parameter scale and d=104, this becomes computationally prohibitive.

Proposed Research Directions

  1. Hierarchical circuit decomposition. Interpret layer groups [0,L/k],[L/k,2L/k],… separately, then compose layer-group circuits. This requires proving a compositionality theorem: that circuits compose across layer boundaries.

  2. Gradient-based circuit search. Replace activation patching with gradient-based attribution (integrated gradients, SHAP) to identify high-impact edges in O(1) backward passes. The open question is whether gradient attribution faithfully identifies the same circuits as causal patching.

  3. Sparse probing at scale. Train linear probes on random subsamples of attention heads; aggregate probe accuracy to construct a probabilistic circuit map without full enumeration.

  4. Distillation-first interpretability. First distill the large model into a smaller, more interpretable student gΟ• with bounded complexity, then apply mechanistic methods to gΟ•. The risk is that the distillation process itself destroys the circuits of interest.

Remark 40 (The β€œInterpretability Wall”).

There is a conjectured interpretability wall: a model size Nβˆ— beyond which the structure of learned representations becomes sufficiently tangled that human-legible descriptions of individual circuits cease to exist-not because we lack tools, but because no such description is possible at bounded human-readable complexity. Whether Nβˆ— is above or below current frontier model size is unknown and is arguably the most important empirical question in interpretability.

Open Problem 2: Standardized Cross-Architectural Metrics for Circuit Comparison

Statement of the Problem

Mechanistic interpretability has identified similar functional structures in different models: induction heads appear in both GPT-2 and PaLM; indirect object identification circuits have been found in models trained on different corpora. Yet we have no principled metric that measures how similar two circuits are across architectures.

Problem 2 (Cross-Architectural Circuit Metric).

Define a metric dcirc(π’ž1,π’ž2) on circuits from models fΞΈ1 and fΞΈ2 (possibly with different architectures) such that:

  1. dcirc=0 if and only if π’ž1 and π’ž2 implement the same computational function;

  2. dcirc is efficiently computable;

  3. dcirc is invariant to permutation of neurons and to orthogonal rotations of the representation space.

Why This Is Hard

The difficulty is that β€œsame circuit” is inherently a semantic notion while neural representations are purely syntactic (numerical arrays). Two circuits may implement the same computation via completely different weight configurations due to the rotational symmetry of the loss landscape. Formally, if π‘βˆˆO(d) is any orthogonal matrix, then fΞΈ(𝒙)=fΞΈβ€²(𝒙) where ΞΈβ€²=π‘ΞΈπ‘βŠ€ for linear layers. This symmetry group is continuous and high-dimensional, making alignment before comparison non-trivial.

Current Partial Solutions

CKA (Centered Kernel Alignment).

For representation matrices π—βˆˆβ„nΓ—d1⁑ and π˜βˆˆβ„nΓ—d2⁑, CKA is defined as: (CKA)CKA(𝐗,𝐘)=β€–π˜βŠ€π—β€–F2β€–π—βŠ€π—β€–Fβ€–π˜βŠ€π˜β€–F, which is invariant to orthogonal transformations and isotropic scaling. CKA measures layer-level representational similarity but not circuit-level functional equivalence.

Procrustes alignment.

Given circuit weight matrices 𝐖1 and 𝐖2 of the same shape, (Procrustes)dProc(𝐖1,𝐖2)=minπ‘βˆˆO(d)⁑‖𝐖1βˆ’π–2𝐑‖F, computable via singular value decomposition. This aligns circuits syntactically but not semantically-circuits that implement the same function via different sub-computations may have large Procrustes distance.

Open Directions

A satisfying solution likely requires defining circuits as input-output functions rather than weight matrices, then comparing functions via random feature approximation or kernel methods: (Functional Metric)dfunc(π’ž1,π’ž2)=π”Όπ’™βˆΌπ’Ÿ[β€–π’ž1(𝒙)βˆ’π’ž2(𝒙)β€–2]1/2, requiring alignment of input spaces across architectures (e.g., both circuits receive tokenized text but may use different vocabularies), which is itself an open problem.

Open Problem 3: Training-Time Integration and Inherently Interpretable Architectures

The Post-Hoc Interpretability Bottleneck

All methods discussed in previous sections are post-hoc: they are applied after training to a fixed model. This creates a fundamental limitation: interpretability is expensive (requiring additional inference passes, auxiliary models, or human evaluation) and yields incomplete explanations (post-hoc methods can only observe, not influence, the computation).

Problem 3 (Inherently Interpretable Generative Models).

Design an architecture π’œinterp for autoregressive language modelling such that:

  1. Every internal computation step has a human-legible semantic interpretation assigned during training;

  2. The architecture achieves perplexity within Ο΅ of a standard transformer of equivalent parameter count;

  3. Interpretations are provably faithful: the stated computation is the actual computation.

Existing Attempts and Their Limitations

Concept bottleneck models.

A concept bottleneck model (CBM) inserts a layer 𝐜=g(𝒙) whose dimensions correspond to human-defined concepts {c1,…,cK}, followed by a predictor h(𝐜): (CBM)fΞΈ(𝒙)=h(g(𝒙)),g:𝒳→[0,1]K. The predictions g(𝒙)k∈[0,1] are directly interpretable as concept activations. The limitation: concept vocabularies must be defined before training, and for language generation (where concepts are infinite and context-dependent), no feasible finite concept set exists.

Mixture of Experts with interpretable routing.

Sparse Mixture-of-Experts (MoE) architectures route tokens to expert subnetworks. If experts specialize semantically (β€œexpert 3 handles mathematical notation”), routing decisions become interpretable. Empirically, some degree of semantic specialization emerges, but is incomplete and context-dependent, not guaranteed by the architecture.

Attention as interpretable computation.

Early transformer papers claimed attention weights are directly interpretable. Subsequent work (Jain & Wallace, 2019; Wiegreffe & Pinter, 2019) showed that attention weights are not faithful: one can often find alternative attention distributions that produce identical outputs, undermining the interpretation.

A Mathematical Framework for Training-Time Interpretability

Let ℐ be a space of human-legible interpretations and let Ο•:Ξ˜β†’β„ be a mapping from model parameters to interpretations. Training-time interpretability requires: (Training Interp)minθ⁑ℒtask(ΞΈ)+Ξ»β‹…β„’interp(Ο•(ΞΈ)), where β„’interp penalizes lack of interpretability. The central open question is how to define β„’interp in a way that (a) is differentiable, (b) correlates with human judgements of interpretability, and (c) does not trivialize the problem by reducing to a second black-box.

Open Problem 4: Interpretability for Multimodal Generation

The Cross-Modal Circuit Problem

Current mechanistic interpretability is almost entirely focused on language-only models. Multimodal models (DALL-E 3, Stable Diffusion XL, GPT-4V, Gemini 1.5, Sora) jointly process text, images, video, and audio. The circuits that implement cross-modal reasoning-how a text prompt about β€œa red apple” activates specific visual generation processes-are entirely uncharacterized.

Problem 4 (Cross-Modal Circuit Discovery).

For a multimodal model fΞΈ:𝒳text×𝒳image→𝒳output, identify the cross-modal circuits: the set of attention heads and MLP layers that implement the mapping between modalities, and characterize their computational function.

Why Multimodal Interpretability Is Harder

Modality-specific encodings.

Text and image tokens live in different subspaces even after projection into a shared embedding space. The projectors 𝐖text:𝒳text→ℝd⁑ and 𝐖image:𝒳image→ℝd⁑ are trained jointly, making it hard to attribute model behaviour to one modality or the other.

Temporal dependencies in video.

Video generation models (Sora, Gen-3) must maintain coherent objects across frames. The circuits implementing temporal consistency are intrinsically non-local: understanding β€œwhy frame t+1 is consistent with frame t” requires analysing interactions across the full temporal attention map, which may have Ξ©(T2) entries for a video of length T.

Audio generation complexity.

Audio signals have temporal resolution ∼44,100 samples per second. Even after tokenization (e.g., EnCodec at 75 tokens/sec), a 30-second clip yields 2,250 tokens-longer than most text sequences studied in mechanistic interpretability, with additional frequency-domain structure not present in text.

Promising Research Directions

  1. Modality-contrastive patching. Patch activations between a β€œtext-only” forward pass and a β€œtext+image” forward pass to identify which components are causally responsible for cross-modal integration.

  2. Representational alignment probing. Train probes on intermediate layers to predict cross-modal correspondences (β€œdoes this hidden state encode the colour of the described object?”).

  3. Concept-level erasure. Erase specific semantic concepts from the image encoder (via activation editing) and measure the effect on text-conditioned generation quality, creating a causal graph of text-vision correspondence.

Open Problem 5: Formal Verification of Neural Network Circuits

From Interpretation to Proof

Current mechanistic interpretability produces hypotheses about what circuits compute, validated empirically via activation patching, logit lens, and ablation studies. But empirical validation cannot rule out failure modes on distribution-shifted inputs, adversarial examples, or rare events. Formal verification would provide mathematical guarantees.

Problem 5 (Verified Circuit Characterization).

Given a circuit π’žβŠ†fΞΈ and a specification Ξ¦:𝒳→{true,false} (e.g., β€œthis circuit implements induction”), provide a formal proof or refutation of: (Verification Claim)βˆ€π’™βˆˆπ’³spec:π’ž(𝒙)⊨Φ(𝒙), where 𝒳spec is a specified domain.

Connection to Neural Network Verification

The field of neural network verification seeks to prove properties of the form βˆ€π’™βˆˆπ’³:β€–π’™βˆ’π’™0β€–<Ο΅β‡’fΞΈ(𝒙)=fΞΈ(𝒙0) (local robustness). Tools such as Ξ±-Ξ²-CROWN, Marabou, and VeriNet solve this for piecewise-linear networks (ReLU activations) via linear programming relaxations.

The open question for interpretability is different: we want to verify not a specific input-output property of the full network, but a functional characterization of a circuit. For example, the induction head hypothesis states that the OV circuit of head (l,h) satisfies: (Induction SPEC)IfΒ theΒ contextΒ containsΒ patternΒ [A,…,B,A],thenΒ π’žl,h(context)Β assignsΒ highΒ probabilityΒ toΒ B. Verifying this for all contexts is a semantic, not syntactic, property, requiring formal semantics for natural language-itself an open problem.

Partial Progress: Toy Model Verification

For highly constrained toy models (1-layer attention with linear activations, finite token sets), one can write circuit computations as polynomial functions and verify properties using sum-of-squares relaxations. Let 𝒒i,π’Œjβˆˆβ„d⁑ be query and key vectors. The attention pattern satisfies: (ATTN POLY)Aij=exp⁑(𝒒iβŠ€π’Œj/d)βˆ‘kexp⁑(𝒒iβŠ€π’Œk/d). For fixed finite token sets, Aij is a rational function of the weight parameters, amenable to real algebraic geometry techniques. Scaling this to production models remains an open research challenge.

Open Problem 6: The Interpretability-Capability Tradeoff

Does Transparency Reduce Performance?

A recurring concern among practitioners is that adding interpretability constraints to model training reduces raw performance. This is the interpretability-capability tradeoff hypothesis. Empirical evidence is mixed.

Problem 6 (Formal Interpretability-Capability Tradeoff).

For any interpretability constraint β„’interp and capability metric β„’cap, characterize the Pareto frontier: (Pareto)𝒫={(β„’cap(ΞΈ),β„’interp(ΞΈ)):ΞΈ=arg minθ⁑ℒcap(ΞΈ)+Ξ»β„’interp(ΞΈ),Ξ»β‰₯0}. In particular, determine: (a) Is 𝒫 a non-trivial curve (strict tradeoff), or is it degenerate (no tradeoff)? (b) What is the slope of 𝒫 as a function of model size N?

Theoretical Arguments

Information-theoretic lower bound.

Any human-legible description f^ of fΞΈ satisfies: (INFO LB)I(f^;π’Ÿ)≀H(f^)≀K(f^), where K(f^) is the Kolmogorov complexity of f^. Since human-legible descriptions have bounded Kolmogorov complexity (a human can only process descriptions up to bounded length and computational depth), f^ is fundamentally limited in the mutual information it can retain about the training data π’Ÿ. This suggests that highly capable models-which require high I(fΞΈ;π’Ÿ)-cannot be fully described by human-legible f^. However, the circuit hypothesis suggests that only the interpretable circuits matter for generalization, so the bound may not be tight.

Empirical counterevidence.

Concept bottleneck models on vision tasks sometimes outperform unconstrained models when the concept set is well-chosen, because the bottleneck acts as a regularizer. This suggests the tradeoff may be negative (interpretability improves capability) in structured domains, while being positive in unstructured domains like language.

Implications for AI Safety

The interpretability-capability tradeoff has direct safety implications. If the tradeoff is severe, safety-conscious developers face a genuine dilemma: transparent models may be easier to audit but harder to deploy competitively. If the tradeoff is mild or negative, interpretability and capability can coexist, which is the more optimistic scenario favoured by proponents of mechanistic interpretability as a safety tool.

Open Problem 7: Interpreting Emergent Capabilities

The Emergence Puzzle

A striking empirical finding in large language models is that certain capabilities appear suddenly as a function of model scale, earning the label β€œemergent”: arithmetic, multi-step reasoning, in-context learning, and chain-of-thought all follow a pattern where performance is near chance up to some threshold scale Nβˆ—, then rises sharply.

Problem 7 (Predicting and Interpreting Emergence).

For a target capability π’ž (e.g., 5-digit arithmetic):

  1. Identify the circuit π’žcircβŠ†fΞΈ responsible for π’ž post-emergence;

  2. Track the development of π’žcirc as a function of training tokens T and parameters N;

  3. Predict Nβˆ—(π’ž), the threshold scale at which π’ž emerges, from properties of π’žcirc at smaller scales.

Two Hypotheses on Emergence

Phase transition hypothesis.

Emergence is a genuine discontinuity: there exists Nβˆ— such that the circuit for π’ž either does not form (N<Nβˆ—) or forms completely (N>Nβˆ—) within training. This is analogous to phase transitions in statistical physics.

Formally, let q(N,T)=Pr⁑[π’žcircΒ forms] under training to convergence. The phase transition hypothesis asserts q(N,T) has a sharp threshold: limΞ΄β†’0⁑[q(Nβˆ—+Ξ΄,T)βˆ’q(Nβˆ—βˆ’Ξ΄,T)]=1.

Metric artefact hypothesis.

Emergence is an artefact of threshold metrics (accuracy jumps from below chance to above chance sharply, but a continuous underlying metric would show smooth improvement). Under this hypothesis, circuits for the capability exist at all scales but are too unreliable for above-chance performance until N=Nβˆ—.

Interpretability could, in principle, adjudicate between these hypotheses: if circuits exist at small scale but are noisy, the metric artefact hypothesis is supported; if circuits are absent entirely below Nβˆ—, the phase transition hypothesis is supported.

Current Evidence

Henighan et al. (2020) showed that sequence modelling loss decreases smoothly with scale despite capability jumps, supporting the metric artefact view. However, Anthropic's work on induction heads showed that these circuits form quite suddenly at a specific training loss, suggesting genuine phase transitions in circuit formation. The reconciliation of these findings is an active research area.

The Research Frontier Map

fig:interp:frontier-map synthesizes the open problems into a map of the research frontier: current capabilities, identified gaps, and projected future goals.

The interpretability research frontier. Left: current capabilities of mechanistic and post-hoc methods. Centre (red dashed): open gaps where progress is urgently needed. Right (green): future goals toward which active research is directed. Solid arrows indicate known paths to gaps; dashed arrows indicate speculative paths from gaps to goals.

Conjecture: No Single Framework Suffices

We close the open problems section with a meta-level conjecture about the structure of the field itself.

Conjecture 1 (Plurality of Interpretability Frameworks).

No single interpretability framework β„± will provide complete, faithful, and efficient explanations for all generative architectures. Formally, for any framework β„±, there exists an architecture π’œ and a task 𝒯 such that β„± is either unfaithful (explanations do not match causal mechanism), incomplete (explanations omit causally important components), or computationally intractable (running β„± on π’œ for task 𝒯 requires super-polynomial resources in |π’œ|).

The conjecture follows intuitively from the no-free-lunch theorem in learning theory: interpretability methods that are tailored to one inductive bias (e.g., the circuit structure of transformers) will fail to capture different inductive biases (e.g., the selective state space structure of Mamba). A corollary is that the field needs a meta-interpretability layer-a principled way to select and compose interpretability methods for a given architecture and task.

[ enhanced, breakable, colback=keyamberbg, colframe=keyamber, boxrule=1pt, arc=4pt, title= Research Challenge A: Scalable Mechanistic Interpretability, coltitle=keyamber!20!black, fontupper=, top=10pt, bottom=8pt, left=10pt, right=10pt, before skip=14pt, after skip=14pt ] Problem setting. You are given a 7B-parameter language model fΞΈ and are tasked with characterizing the circuits responsible for multi-step arithmetic (e.g., computing 3Γ—47+12=153 in a single forward pass without chain-of-thought).

Specification of difficulty. The model has 32 layers, 32 attention heads, and d=4096. The circuit-space has 24,194,304 possible elements. Direct activation patching would require ∼107 forward passes.

Research questions.

  1. Can gradient-based attribution (e.g., GradCAM adapted to attention heads) identify a candidate circuit in O(log⁑d) backward passes?

  2. Does the identified circuit generalize: does ablating it also disrupt modular arithmetic (modp) and multi-digit addition, or only the specific arithmetic tested?

  3. Can the circuit be described as a composition of known primitives (lookup, accumulation, positional routing)?

  4. Quantify the circuit faithfulness: if you replace the rest of the model with the identified circuit alone (plus embeddings/unembedding), what fraction of original accuracy is retained?

Success criterion. A faithful circuit (retaining β‰₯80% of arithmetic accuracy) described in fewer than 200 words of prose plus equations.

[ enhanced, breakable, colback=lempurplebg, colframe=lempurple, boxrule=1pt, arc=4pt, title= Research Challenge B: Verifiable Induction Head Specification, coltitle=lempurple!20!black, fontupper=, top=10pt, bottom=8pt, left=10pt, right=10pt, before skip=14pt, after skip=14pt ] Problem setting. Anthropic's mechanistic interpretability team identified induction heads as a key circuit in GPT-2. The informal specification is: β€œIf the context contains […,A,B,…,A], the induction head predicts B at the final position.”

Formal verification challenge. Translate the informal specification into a formal logical formula Ξ¦ind over the space of attention-head computations and:

  1. Verify Ξ¦ind for a 1-layer transformer on a finite binary token alphabet Ξ£={0,1} using existing neural network verification tools (e.g., Ξ±-Ξ²-CROWN);

  2. Identify the minimal weight constraints under which Φind holds: characterize the set Θind={θ:fθ⊨Φind};

  3. Propose a training objective that encourages θ∈Θind while maximizing next-token prediction accuracy;

  4. Test whether models trained with this objective show faster or stronger induction head formation.

Success criterion. A verified proof (or counterexample) for the 1-layer binary case, plus a training recipe that increases the probability of induction head formation by β‰₯20% relative to standard training.

Comprehensive Exercises and Research Challenges

The following exercises span the full arc of this chapter. They are designed to develop both mathematical facility-computing Shapley values, patching activations, training SAEs-and research intuition: noticing when an explanation is unfaithful, designing controls, and articulating failure modes. The research challenges at the end are open-ended and suitable for semester projects or early-stage research explorations.

Exercises

Exercise 61 (Shapley Value Computation for a 3-Feature Model).

Consider a model f:{0,1}3→ℝ⁑ defined on binary features 𝒙=(x1,x2,x3) by: (EX Model)f(x1,x2,x3)=2x1+3x2+x1x2βˆ’x3+2x1x3.

  1. Compute all 23=8 values of f.

  2. The Shapley value of feature i for input π’™βˆ—=(1,1,1) is: (Shapley DEF)Ο•i(π’™βˆ—)=βˆ‘SβŠ†[3]βˆ–{i}|S|!(nβˆ’|S|βˆ’1)!n![f(Sβˆͺ{i})βˆ’f(S)], where f(S) denotes f evaluated with features in S set to their values in π’™βˆ— and features not in S set to 0. Compute Ο•1,Ο•2,Ο•3 for π’™βˆ—=(1,1,1).

  3. Verify the efficiency property: βˆ‘iΟ•i(π’™βˆ—)=f(π’™βˆ—)βˆ’f(𝟎).

  4. For π’™βˆ—βˆ—=(1,0,1), compute all three Shapley values. How does the ranking of feature importances change between π’™βˆ— and π’™βˆ—βˆ—? Explain intuitively why x1x3 affects the comparison.

  5. Suppose you run LIME instead of exact Shapley values, using a linear model fit on M=20 random binary perturbations of π’™βˆ—. Describe (in one paragraph) when LIME will give results close to the exact Shapley values and when it will deviate.

Exercise 62 (Activation Patching on a Toy 2-Layer Transformer).

Let T be a 2-layer, 2-head, d=4 attention-only transformer. Consider the Indirect Object Identification (IOI) task:

β€œAlice gave the gift to Bob and to” β†’ β€œAlice” (incorrect: β€œBob”).

Denote the clean prompt pc (above) and the corrupted prompt pk:

β€œCarol gave the gift to Bob and to” (subject changed).

  1. Define causal patching: what does it mean to patch the output of attention head (l,h) from the clean run into the corrupted run?

  2. For each of the 4 heads (layers {0,1} Γ— heads {0,1}), the patching effect is defined as: (Patch Effect)Ξ”l,h=Prpk←(l,h)⁑[next=Alice]βˆ’Prpk⁑[next=Alice]. Explain how Ξ”l,h identifies which heads are causally important for the IOI behaviour.

  3. Suppose Ξ”1,0=0.45 and all other Ξ”l,h<0.05. What does this tell you about the circuit structure?

  4. What is path patching? How does it differ from activation patching, and why might it give more refined information about circuits?

  5. Propose a control experiment to rule out the hypothesis that head (1,0) is simply attending to the most recently seen name rather than implementing IOI.

Exercise 63 (QK and OV Circuit Matrix Computation).

Let attention head h have weight matrices 𝐖Q,𝐖K,𝐖Vβˆˆβ„dΓ—dh⁑ and 𝐖Oβˆˆβ„dhΓ—d⁑, with d=6, dh=3.

  1. Write the QK circuit matrix 𝐖QKh=𝐖Q𝐖K⊀ and explain its role: what does a large entry (i,j) of 𝐖QKh indicate about the attention pattern?

  2. Write the OV circuit matrix 𝐖OVh=𝐖O𝐖V⊀ and explain its role: if token j attends to token i, what does 𝐖OVh compute?

  3. Let the full residual stream circuit be the sum over all heads: 𝐖OVfull=βˆ‘h𝐖OVh. Show that for a linear 1-layer attention model (ignoring softmax), the output is: (Linear ATTN)π’ši=𝐖U(𝒙i+βˆ‘hβˆ‘jAijh𝐖OVh𝐖E𝒙j), where 𝐖E is the embedding matrix, 𝐖U is the unembedding matrix, and Aijh is the attention weight.

  4. Numerical example. Let d=4, dh=2, 𝐖Q=𝐖K=𝐈4Γ—2 (first 2 rows of identity), 𝐖V=𝐈4Γ—2, 𝐖O=𝐈2Γ—4. Compute 𝐖QK and 𝐖OV.

  5. If 𝐖QK has rank 1, what does this imply about the attention pattern? Provide an example of a rank-1 QK circuit and describe what computation it implements.

Exercise 64 (Induction Head Pattern Matching).

Consider the sequence of token IDs (over alphabet {A,B,C,D}): (SEQ)s=[A,B,C,A,B,D,A,B,?]

  1. An induction head implements the following algorithm: at position t, attend to the position tβ€² such that stβ€²=st and tβ€²<t, then predict stβ€²+1. What token should an induction head predict at position ? for the sequence s?

  2. In a 2-layer transformer, induction heads in layer 2 are supported by previous-token heads in layer 1. Describe what a previous-token head computes and why it is necessary for induction.

  3. Define the induction score of head (l,h) as: (IND Score)IH(l,h)=1|S|βˆ‘t∈SAt,tβˆ’nβˆ’1l,h, where S is the set of positions following a repeated bigram of period n, and At,tβ€²l,h is the attention weight from position t to tβ€². Explain why IHβ‰ˆ1 indicates an induction head and IHβ‰ˆ1/T (for sequence length T) indicates uniform attention.

  4. Construct a sequence of length 10 over {A,B,C} where a pure induction head would predict incorrectly, and explain why.

  5. How would you modify the induction score to detect fuzzy induction heads that match semantically similar but not identical tokens?

Exercise 65 (Sparse Autoencoder Training: β„“1 Penalty and Reconstruction Tradeoff).

A sparse autoencoder (SAE) learns a dictionary πƒβˆˆβ„dΓ—n⁑ (with n≫d) and encoder 𝐖encβˆˆβ„nΓ—d⁑ to minimize: (SAE LOSS)β„’SAE(𝐃,𝐖enc)=𝔼𝒙[β€–π’™βˆ’πƒπ’‡^(𝒙)β€–2+λ‖𝒇^(𝒙)β€–1],𝒇^(𝒙)=ReLU(𝐖enc𝒙), where Ξ»>0 controls sparsity.

  1. Show that in the limit Ξ»β†’0, the SAE reduces to standard PCA (up to rotation).

  2. Show that in the limit Ξ»β†’βˆž, 𝒇^(𝒙)=𝟎 for all 𝒙, giving zero sparsity and infinite reconstruction error.

  3. For a fixed Ξ»>0, derive the KKT conditions for the optimal 𝒇^βˆ—(𝒙) at fixed 𝐃, 𝐖enc. Show that 𝒇^iβˆ—>0 implies (πƒβŠ€(π’™βˆ’πƒπ’‡^βˆ—))i=Ξ»/2.

  4. Define the dead feature problem: a feature i is dead if 𝒇^i(𝒙)=0 for all 𝒙 in the training set. Propose two strategies to prevent dead features during SAE training and analyse the tradeoffs of each.

  5. The reconstruction error can be decomposed as: (SAE Decomp)β€–π’™βˆ’πƒπ’‡^(𝒙)β€–2=β€–π’™βˆ’πƒπ’‡^βˆ—(𝒙)β€–2+‖𝐃(𝒇^βˆ—(𝒙)βˆ’π’‡^(𝒙))β€–2. Explain why the second term is not zero when the SAE encoder 𝐖enc is not perfectly tied to the decoder πƒβŠ€.

Exercise 66 (ROME: Computing the Rank-One Update for a Factual Edit).

ROME (Rank-One Model Editing) edits a factual association by modifying a single MLP weight matrix via a rank-one update. Let 𝐖0βˆˆβ„doutΓ—din⁑ be the weight matrix of an MLP layer, and π’Œβˆ—βˆˆβ„din⁑ the key vector for the subject β€œEiffel Tower”. ROME seeks 𝐖′ minimizing: (ROME OBJ)β€–π–β€²π’Œβˆ—βˆ’π’—βˆ—β€–2+βˆ‘j=1mβ€–π–β€²π’Œjβˆ’π–0π’Œjβ€–2, where π’—βˆ—βˆˆβ„dout⁑ is the new target value and {π’Œj}j=1m are β€œcontext” keys that must not change.

  1. Show that the optimal 𝐖′ has the form 𝐖′=𝐖0+Δ𝐖 where Δ𝐖 is rank-one.

  2. Let 𝐂=βˆ‘jπ’Œjπ’Œj⊀ (the covariance of context keys). Derive the closed-form solution: (ROME Solution)Δ𝐖=(π’—βˆ—βˆ’π–0π’Œβˆ—)π’Œβˆ—βŠ€π‚βˆ’1π’Œβˆ—βŠ€π‚βˆ’1π’Œβˆ—.

  3. Why is the factor π‚βˆ’1 important? What would go wrong if we used Δ𝐖=(π’—βˆ—βˆ’π–0π’Œβˆ—)π’Œβˆ—βŠ€ (no covariance correction)?

  4. Suppose the edit target is β€œThe Eiffel Tower is located in Berlin” (incorrect). Describe how you would choose π’—βˆ— to minimize collateral damage to other factual associations.

  5. ROME is a rank-one update. Propose a rank-r generalization for editing r facts simultaneously and write the corresponding objective.

Exercise 67 (Task Vector Extraction and Cross-Modal Transfer).

A task vector 𝝉=ΞΈftβˆ’ΞΈpre encodes the parameter-space direction learned during fine-tuning on task T.

  1. Let ΞΈpre be a shared CLIP-style vision-language backbone, ΞΈftsentiment the result of fine-tuning on text sentiment analysis, and ΞΈftcolorfulness the result of fine-tuning on image colorfulness scoring. Define the task vectors 𝝉sent and 𝝉color.

  2. Task negation. Define ΞΈnegated=ΞΈpreβˆ’Ξ±π‰sent for Ξ±>0. What would you expect ΞΈnegated to be worse at, compared to ΞΈpre? What would it be better at?

  3. Task addition. Define ΞΈjoint=ΞΈpre+α𝝉sent+β𝝉color. Under what conditions would you expect joint performance on both tasks to exceed independent fine-tuning on each? Relate this to the concept of task orthogonality in parameter space.

  4. Cross-modal transfer. Suppose 𝝉sent was computed from the text encoder only. Propose an experiment to test whether applying it to the vision encoder of the backbone transfers sentiment-related features to image processing.

  5. Define the task vector cosine similarity cos⁑(𝝉1,𝝉2) and argue that tasks with high similarity will interfere under addition while tasks with near-zero similarity will combine approximately additively.

Exercise 68 (Diffusion Temporal Schedule Analysis).

A DDPM model defines a forward process q(𝒙t|𝒙0)=𝒩(Ξ±β€Ύt𝒙0,(1βˆ’Ξ±β€Ύt)𝐈) where Ξ±β€Ύt=∏s=1t(1βˆ’Ξ²s) and the schedule Ξ²1,…,Ξ²T is fixed.

  1. Define the semantic content at timestep t as the mutual information I(𝒙0;𝒙t). Show that: (MI Diffusion)I(𝒙0;𝒙t)=H(𝒙t)βˆ’H(𝒙t|𝒙0)=H(𝒙t)βˆ’d2log⁑(2Ο€e(1βˆ’Ξ±β€Ύt)), and explain how I(𝒙0;𝒙t) decreases monotonically in t.

  2. Mechanistic studies suggest that denoising at high noise levels (t>0.8T) determines global structure (layout, semantic content), while low noise levels (t<0.2T) determine fine detail (texture, colour). Design an ablation experiment using activation patching across timesteps to test this hypothesis.

  3. In a U-Net denoiser ϡθ(𝒙t,t), the skip connections aggregate features from the encoder to the decoder. Propose a method to identify which skip connections are causally responsible for preserving high-frequency detail versus low-frequency structure.

  4. Consider two prompts: p1= β€œa dog” and p2= β€œa cat”. Both generate noise Ο΅βˆΌπ’©(𝟎,𝐈) and are denoised to images 𝒙0(1) and 𝒙0(2). If you patch the noise trajectory at timestep tβˆ— (i.e., replace 𝒙tβˆ—(1) with 𝒙tβˆ—(2) mid-denoising), for what values of tβˆ— would you expect the output to resemble a dog, and for what values would it resemble a cat? Justify your answer using the semantic content interpretation above.

  5. Propose a metric Ξ“(t) that measures how much the denoiser's attention to text-conditioning changes as a function of timestep t, and describe how you would compute it efficiently from the cross-attention weights.

Exercise 69 (Attention Flooding vs. Attention Sinks: A Comparison).

  1. Attention flooding. In a trained language model, it is sometimes observed that an attention head assigns nearly uniform attention over all positions. Formally, if At,sβ‰ˆ1/t for all s≀t, the head is called a flooded head. What is the entropy of this attention distribution, and what does it imply about the information the head extracts from context?

  2. Attention sinks. Conversely, some heads assign nearly all attention mass to a small number of positions (often the first token or a separator token): (SINK)At,1β‰ˆ1,At,sβ‰ˆ0fors>1. What is the entropy of this distribution? What function would a head with this pattern implement, and why might it be useful?

  3. Using the OV circuit framework, explain why an attention sink head with a nearly-zero OV matrix is effectively a no-op: it computes something but contributes negligibly to the residual stream.

  4. Xiao et al. (2023) showed that attention sinks are critical for streaming inference (KV-cache truncation destroys performance unless the sink token is retained). Explain this finding using the circuit perspective: what computation is disrupted when the sink token's key-value pair is removed from the cache?

  5. Propose an experiment to determine whether a specific attention sink head contributes to a particular capability (e.g., long-range pronoun resolution), or whether it is entirely a no-op. What would activation patching reveal in each case?

Exercise 70 (Mamba vs. Transformer on Associative Recall).

The associative recall task presents the model with key-value pairs followed by a query:

β€œAlice: blue, Bob: red, Carol: green. Alice:” β†’ β€œblue”

  1. In a 1-layer attention transformer, the induction head mechanism solves associative recall via QK-circuit pattern matching. Describe the circuit in terms of 𝐖QK and 𝐖OV.

  2. Mamba uses a selective state space model (SSM) with input-dependent parameters 𝐁t,𝐂t at each timestep. The recurrence is: (Mamba Recurrence)ht=𝐀‾thtβˆ’1+𝐁‾t𝒙t,yt=𝐂tht, where 𝐀‾t and 𝐁‾t are discretized from continuous-time parameters. Explain how the SSM can in principle store a key-value association: which part of the recurrence performs the β€œwrite” and which performs the β€œread”?

  3. Empirically, transformers outperform SSMs on associative recall tasks with many key-value pairs. Using the theoretical frameworks above, explain why: what is the computational bottleneck in the SSM approach that the attention mechanism circumvents?

  4. Propose a β€œhybrid” architecture that uses attention for associative recall and SSM for long-range sequential dependencies. Describe how you would determine, using interpretability tools, whether the two mechanisms are cleanly separated in practice.

  5. Design an interpretability experiment to test whether a Mamba model has β€œlearned” induction: does it exhibit higher activation magnitudes for ht at positions following repeated bigrams?

Exercise 71 (Bias Feature Identification and Intervention).

Consider a text generation model fΞΈ that produces descriptions of professionals (doctors, engineers, nurses). You suspect it encodes gender-occupation biases in its residual stream.

  1. Define a gender direction π’ˆβˆˆβ„d⁑ by: (Gender DIR)π’ˆ=𝔼[𝒙she]βˆ’π”Ό[𝒙he], where 𝒙she and 𝒙he are residual stream activations at the profession token for she/her- and he/him-gendered contexts respectively. Explain the implicit assumption behind using this linear direction.

  2. Describe a probing experiment to test whether π’ˆ is predictive of gender-biased continuations: what is the classifier, what is the training set, and what does high probe accuracy imply about the model's internal representation?

  3. Define activation steering: at inference time, replace the residual stream 𝒙 with π’™βˆ’Ξ±(π’ˆβ‹…π’ˆβŠ€/β€–π’ˆβ€–2)𝒙 (project out the gender direction). What would you predict about the model's output distribution after this intervention?

  4. List two potential failure modes of activation steering for bias mitigation: enumerate[(i)]

  5. A case where it over-corrects (erases legitimate information).

  6. A case where it fails to correct (bias is encoded in a different, non-linear direction). enumerate Propose diagnostic experiments for each failure mode.

  7. An alternative to steering is training-time debiasing via a bias loss term: (Debiasing LOSS)β„’debias=𝔼[|π’ˆβŠ€π’™|2]. Compare this to activation steering: which is more principled? Which generalizes better? What information does interpretability (specifically, knowing π’ˆ) provide that is essential for either approach?

Exercise 72 (Introspection Evaluation: Designing a Test for Model Self-Knowledge).

A model fΞΈ has genuine introspective access if its stated uncertainty accurately reflects its actual uncertainty. Formally, let pstated(A) be the probability fΞΈ assigns to event A when asked β€œhow confident are you that A?”, and pactual(A) be the model's empirically measured accuracy on A. Perfect calibration requires pstated(A)=pactual(A).

  1. Propose a dataset of 100 factual questions of varying difficulty to test calibration. What properties should the difficulty distribution have, and how would you measure it?

  2. Define the Expected Calibration Error (ECE): (ECE)ECE=βˆ‘m=1M|Bm|n|acc(Bm)βˆ’conf(Bm)|, where Bm is the m-th confidence bin. Describe how to compute this for a generative model that produces free-text confidence expressions (β€œI am fairly confident”).

  3. A model may be behaviourally calibrated (ECE is low when averaging over the evaluation set) without being mechanistically calibrated (its uncertainty representations internally track genuine epistemic states). Design an experiment, using activation patching or probing, to test mechanistic calibration.

  4. Suppose the model consistently overstates its confidence on questions about recent events (post-training-cutoff). How would you detect this using only behavioural evaluation? How would a mechanistic approach (probing for a β€œknowledge cutoff” direction in the residual stream) provide additional evidence?

  5. The sycophancy confound. A model may state high confidence when the user's phrasing implies they expect confidence, not because of genuine self-knowledge. Propose an experimental design that disentangles sycophancy from genuine introspective access. What activation patching experiment would causally test whether confidence expressions are driven by the user's phrasing or by the model's internal uncertainty?

Research Challenges

Challenge 1 (Building a Minimal SAE for a Toy Transformer).

Setup. Train a 2-layer, 4-head, d=64 transformer on a synthetic in-context learning task: the input is a sequence of (xi,f(xi)) pairs where f is drawn from a family of functions (linear, quadratic, modular arithmetic). The model must predict f(xquery) for a new xquery.

Step 1: Train the transformer. Train until convergence on the synthetic task. Record the residual stream activations 𝒓(l)βˆˆβ„nΓ—d⁑ at each layer l for 10,000 input sequences.

Step 2: Train sparse autoencoders. For each layer, train an SAE with dictionary size n=4d=256: (CH SAE)min𝐃,𝐖enc⁑𝔼[‖𝒓(l)βˆ’πƒπ’‡^(𝒓(l))β€–2+λ‖𝒇^(𝒓(l))β€–1]. Sweep λ∈{0.01,0.1,1.0,10.0} and for each Ξ», record: (i) reconstruction MSE, (ii) average β„“0 sparsity, (iii) number of dead features.

Step 3: Feature interpretation. For each active SAE feature i (column 𝐃i of the dictionary), identify the top-10 inputs that maximally activate it. Manually label what each feature appears to encode (e.g., β€œstores the exponent of the quadratic term”).

Step 4: Causal validation. For each labelled feature, perform an activation steering experiment: add α𝐃i to the residual stream at layer l and measure the effect on model output. Does steering in the direction of a feature cause the model to behave as if that feature were more active?

Success criteria. Identify at least 5 interpretable SAE features that: (a) have human-legible descriptions, (b) are causally validated by steering, (c) together account for β‰₯60% of the variance in model predictions on the synthetic task.

Write-up. A 5-page report including: loss curves, Pareto plots of reconstruction vs. sparsity, feature descriptions, and steering experiment results.

Challenge 2 (Circuit Discovery for a Specific Linguistic Task).

Task selection. Choose one of the following linguistic tasks in a pretrained GPT-2-medium (345M parameter) model:

  1. Negative Polarity Item (NPI) licensing: β€œAnyone can do it” (licensed) vs. β€œ*Anyone will do it” (unlicensed).

  2. Subject-Verb Agreement at long distance: β€œThe keys to the cabinet are on the table” (vs. *β€œis”).

  3. Filler-Gap dependency: β€œThe book that Alice read _” completes grammatically without an object.

Step 1: Establish the behavioural effect. Construct a minimal pair dataset (at least 200 pairs) for your chosen task. Measure the model's probability difference Ξ”P=P(correct)βˆ’P(incorrect) and confirm the model shows the correct linguistic preference.

Step 2: Activation patching. Implement activation patching for all layer/head combinations (12Γ—12=144 experiments per example). Produce a heatmap of patching effects Ξ”l,h over the full dataset.

Step 3: Circuit isolation. Identify the minimal subset of heads β„‹βˆ—βŠ†[L]Γ—[H] such that ablating all heads outside β„‹βˆ— retains β‰₯80% of Ξ”P. This is your circuit.

Step 4: Functional characterization. For each head hβˆˆβ„‹βˆ—, compute the QK and OV circuit matrices and provide a mechanistic description: β€œHead (l,h) queries for and writes to the residual stream.”

Step 5: Generalization testing. Construct a held-out test set with novel lexical items (different nouns, verbs) and syntactic structures (embedded clauses). Does the identified circuit generalize, or does it rely on lexical memorization?

Deliverable. A 8-page paper following the format of β€œIn-context Learning and Induction Heads” (Olsson et al., 2022): motivation, dataset, methods, results, discussion.

Challenge 3 (Cross-Modal Interpretability Benchmark).

Motivation. No systematic benchmark exists for evaluating interpretability methods across text-only, vision-only, and vision-language models on comparable tasks.

Benchmark design. Design a benchmark ℬcross consisting of three matched task suites:

  1. Text suite (ℬT): 5 tasks from the mechanistic interpretability literature (IOI, greater-than, bracket matching, induction, factual recall) with established circuit descriptions.

  2. Vision suite (ℬV): 5 analogous tasks for a vision transformer (ViT): object detection, part-whole composition, texture bias, colour constancy, spatial relation reasoning.

  3. Cross-modal suite (ℬTV): 5 tasks requiring joint text-vision reasoning in a CLIP or LLaVA-style model: text-guided region selection, attribute binding (β€œthe red cube”), negation (β€œnot a dog”), compositional counting, and spatial language (β€œthe object to the left of”).

Evaluation protocol. For each task in each suite, apply three interpretability methods: (i) activation patching, (ii) linear probing, (iii) attention head attribution. Measure:

  • Faithfulness: does ablating the identified circuit degrade task performance by β‰₯50%?

  • Completeness: does the circuit account for β‰₯70% of the model's task performance?

  • Minimality: is the circuit the smallest set satisfying faithfulness and completeness?

Cross-modal comparison. Quantify whether the same interpretability methods (with appropriate adaptations) achieve comparable faithfulness/completeness/minimality scores across all three suites. Report which methods generalize across modalities and which are modality-specific.

Deliverable. A benchmark paper (12 pages) plus a public code repository with all datasets, evaluation scripts, and baseline results.

Challenge 4 (Diffusion Bias Mitigation via Mechanistic Intervention).

Problem. Text-to-image diffusion models (Stable Diffusion, DALL-E 3) exhibit social biases: prompts like β€œa doctor” produce predominantly male images; β€œa nurse” predominantly female. Current mitigation strategies (prompt engineering, post-processing filters) are ad hoc. Mechanistic interpretability offers a principled alternative.

Step 1: Bias quantification. Generate 500 images for each of 20 occupation prompts using a pretrained diffusion model. For each prompt, measure gender representation using an off-the-shelf classifier. Identify the 5 most biased occupations.

Step 2: Causal tracing in the text encoder. The text encoder β„°T converts the prompt to a conditioning vector 𝒄=β„°T(p). For a biased prompt p= β€œa doctor”, trace through β„°T to identify which layers and attention heads encode gender-connotative features. Use the method from Meng et al. (2022): corrupt the prompt embedding at layer l and measure the effect on generated gender distribution.

Step 3: Feature identification. Train a linear probe on intermediate activations of β„°T to predict the gender distribution of images generated from those activations. Identify the top-5 directions most predictive of bias.

Step 4: Mechanistic intervention. Design a post-hoc intervention: at inference time, project the text encoder activations to remove the identified bias directions: (DIFF PROJ)𝒄′=π’„βˆ’βˆ‘k=1Kπ’ˆkπ’ˆkβŠ€β€–π’ˆkβ€–2𝒄, where {π’ˆk} are the identified gender directions. Generate 500 images per occupation with the modified conditioning vector 𝒄′.

Step 5: Evaluation. Measure: (a) reduction in gender bias (primary metric), (b) image quality degradation (FID score), (c) semantic fidelity (CLIP score between prompt and image). Report the tradeoff between bias mitigation and generation quality.

Deliverable. A 10-page paper comparing mechanistic intervention to (i) prompt engineering (β€œa doctor, gender-neutral”) and (ii) classifier-free guidance strength modulation.

Challenge 5 (Scalable Oversight Protocol Design).

Background. As AI systems become more capable than the humans evaluating them, direct human evaluation of outputs becomes unreliable. Scalable oversight protocols use interpretability tools to allow humans to assess AI behaviour even when they cannot directly evaluate the outputs.

Problem. Design a scalable oversight protocol for a generative model deployed in a high-stakes domain (choose one: medical report generation, legal document synthesis, code security analysis).

Protocol Components.

Component A: Feature monitoring. Design a real-time monitor that:

  1. Trains SAE features on a representative corpus for your domain;

  2. At each inference step, flags activations of high-risk features (e.g., features that activate on β€œhallucinated dosage”, β€œlegal loophole exploitation”, or β€œSQL injection”);

  3. Assigns a risk score ρ(𝒙)∈[0,1] to each generated sequence.

Component B: Contrastive explanation. For any flagged output y, generate a contrastive explanation: β€œThe model predicts y rather than yβ€² because of the following circuit activation ”. Implement this using activation patching between y and yβ€² to identify causally responsible components.

Component C: Human-in-the-loop calibration. Design a labelling interface that shows human reviewers: (a) the flagged output, (b) the feature activations responsible, (c) the contrastive explanation. Collect labels and use them to fine-tune the risk scorer ρ.

Component D: Formal guarantees. For which classes of failures can you provide a formal guarantee that the monitor will detect them? Formally characterize the detection boundary: the set of harmful outputs β„‹detect that your protocol will flag with probability β‰₯1βˆ’Ξ΄.

Evaluation. On a held-out set of 100 examples (50 harmful, 50 benign), measure: precision, recall, F1 of the monitor, human review time per flagged item, and false negative rate on novel failure modes not in training.

Deliverable. A 15-page protocol specification document including: system architecture diagram, formal guarantees, evaluation results, and an analysis of what classes of failure the protocol cannot detect.

Chapter Summary and Looking Forward

This chapter has developed interpretability and explainability as a mathematical discipline, covering:

  • Post-hoc attribution methods: Shapley values provide a unique, axiomatically justified attribution of model outputs to input features; LIME approximates this via local linear models.

  • Mechanistic interpretability: Circuits-subgraphs of the computation graph-implement identifiable computations. Key circuits include induction heads (in-context pattern matching), indirect object identification, and greater-than comparison.

  • Sparse autoencoders: Overcome the polysemanticity obstacle by learning an overcomplete dictionary of monosemantic features, with β„“1 regularization controlling sparsity.

  • Knowledge editing: ROME and MEMIT enable targeted surgical edits to factual associations via rank-one updates to MLP weights, with formal guarantees on locality.

  • Task vectors and model arithmetic: Fine-tuned models lie in structured regions of parameter space; task directions can be composed linearly.

  • Diffusion interpretability: The denoising process has a temporal structure; high-noise steps determine global layout while low-noise steps refine detail.

  • Multimodal probing and bias detection: Linear probes on residual streams identify factual, syntactic, and cross-modal features; gender and social biases are encoded in linear directions amenable to causal intervention.

  • Open problems: Scaling to trillion-parameter models, standardized circuit metrics, training-time interpretability, multimodal circuits, formal verification, the interpretability-capability tradeoff, and emergent capabilities remain unsolved, defining the research frontier.

Insight.

The central bet of mechanistic interpretability. The field's working hypothesis is that neural networks trained by gradient descent on large, structured datasets develop compressed, modular, and algorithmically simple internal computations-precisely the kind that human-legible interpretability methods can hope to recover. Whether this bet is correct is an empirical question. The exercises and research challenges in this chapter are designed to help you develop the tools and intuitions to participate in answering it.

Key Idea.

Interpretability as a scientific discipline. Good interpretability research follows the structure of science:

  1. Hypothesis: propose a circuit or feature.

  2. Prediction: derive what behaviour would change if the hypothesis is correct.

  3. Intervention: causally test the prediction via activation patching, ablation, or steering.

  4. Evaluation: measure whether predictions hold quantitatively.

  5. Refinement: update the hypothesis based on evidence.

This methodology distinguishes mechanistic interpretability from mere visualization: interventions provide causal evidence, not just correlational observations.

References

  1. kraskov2004estimating

    Missing BibTeX metadata for kraskov2004estimating.

  2. tinaz2025saediffusion

    Missing BibTeX metadata for tinaz2025saediffusion.

  3. shi2025cvprbias

    Missing BibTeX metadata for shi2025cvprbias.