Causal Interventions: Activation Patching
Locating behavior with patching, causal tracing and circuit discovery.
Change the names in "When Mary and John went to the store, John gave a drink to" and GPT-2 small's answer changes; restore the outputs of a few attention heads from the original sentence and the answer comes back. Activation patching turns such surgery into a measurement of which components carry a behavior. This lesson builds it from causal mediation analysis, shows how its verdicts depend on the direction of patching, the corruption and the metric, follows it from single components to whole circuits, and asks when a circuit explanation deserves to be believed.
What you’ll learn
- Define total, direct and indirect effects of a network component, and express activation patching in both directions as measurements of them.
- Prove that noising and denoising find different components in AND- and OR-structured computations, and choose corruptions and metrics with their pitfalls in mind.
- Explain path patching and the indirect-object-identification circuit, and evaluate a circuit by faithfulness, completeness and minimality.
- Derive the error bound of attribution patching, and explain how ACDC and gradient-based methods automate circuit discovery.
- Explain causal abstraction and interchange interventions, construct a subspace-patching illusion, and account for self-repair.
Effects, mediators and two directions of patching
Probes and attributions are correlational: they show what is present and what the output is locally sensitive to. To show that a component carries a behavior you must intervene on it. Vig et al. (2020) imported the language of causal mediation analysis (Pearl, 2001). An intervention on the input, such as replacing "nurse" by "man" in "The nurse said that", changes an outcome, such as the model's preference for "he" over "she"; a mediator, a neuron or an attention head, may carry part of that change. Studying gender bias in pretrained transformer language models this way, they found the effects sparse (concentrated in a small part of the network), synergistic (amplified or repressed by different components) and decomposable into effects flowing directly from the input and indirectly through the mediators.
| Direction | Base run | Patched in from | What a large effect shows |
|---|---|---|---|
| Denoising (clean → corrupt), as in causal tracing | corrupted input | the clean run | the restored activation is sufficient, given the rest of the corrupted computation, to bring the behavior back |
| Noising (corrupt → clean), as in resample ablation | clean input | the corrupted run | the activation is necessary: without its clean value the behavior breaks |
Denoising runs the corrupted input with restored, so ; noising runs the clean input with corrupted, so :
For AND, the denoised run stays at the corrupted value (no restoration) and the noised run drops to (full breakage). For OR, the denoised run reaches (full restoration) and the noised run stays at (no effect). By symmetry the same holds for . Real networks contain both patterns: a component that needs two pieces of clean information at once behaves like AND, and redundant components, such as backup heads, behave like OR. One pass of single-component patching in one direction can miss either kind; patch in both directions, or patch sets of components.
Two attention heads write the same answer-relevant information, and either one alone is enough for the model to answer correctly. You noise each head separately (its corrupted activation in the clean run), and the logit difference barely moves. What should you conclude?
- Neither head matters for the behavior
- The corruption must have been too weak to change anything
- The heads are redundant, an OR structure, so single-head noising hides them; denoising each head, or noising both together, would reveal them
- The logit difference cannot measure the effect of attention heads
Show the answer
C. The heads are redundant, an OR structure, so single-head noising hides them; denoising each head, or noising both together, would reveal them
With , corrupting one input leaves the other carrying the answer. Denoising either head into a corrupted run restores the behavior, and noising both at once breaks it. Backup name mover heads in GPT-2 small are exactly such hidden redundancy.
Corruptions, metrics and causal tracing
Causal tracing (Meng et al., 2022) is denoising with a particular corruption: add Gaussian noise with standard deviation , three times that of the token embeddings, to the embeddings of a factual prompt's subject, and restore one hidden state at a time from the clean run. Over 1000 facts known to GPT-2 XL, the corruption cut the probability of the correct object from 27.0% to 8.47% on average. The average total effect was 18.6 percentage points, and single states at the last subject token in middle layers mediated up to 8.7 points (layer 15), mostly through MLPs (up to 6.6 points, against 1.6 for attention at that token). Feed-Forward Layers as Memories follows the story into fact editing, and into the finding that these localizations do not predict where an edit works best.
Every choice in such an experiment can move the conclusion. Zhang & Nanda (2024) compared Gaussian noising (GN) with symmetric token replacement (STR), which swaps the key tokens for similar ones, "The Eiffel Tower" for "The Colosseum", so the corrupted prompt is still natural text. Patching MLPs in GPT-2 XL, the peak that GN produces around layer 16 of 48 was 2 to 5 times higher than under STR across window sizes, and the two corruptions found different sets of attention heads in the IOI circuit. They argue that GN can push the model off its training distribution, recommend STR, and recommend the logit difference over probability as the metric. Restoring several adjacent layers at once (sliding windows) also sharpens peaks relative to single layers.
Compare the correct answer with one wrong answer. Conditioning on the output being one of the two cancels the softmax normalizer, so the conditional probability is a sigmoid of the logit difference :
The logits are linear in the final residual stream, up to the final normalization's scale, so components' direct contributions to add. Their effects on the probability do not: a component that lowers by the same nats changes by very different amounts depending on where the prompt sits on the sigmoid:
A factor of about 30 for the same mechanism. On confidently answered prompts, a component that pushes against the answer, such as a negative name mover, is nearly invisible in probability, while the logit difference shows it at its true size.
With the logit difference as metric, report the normalized patching effect
the fraction of the clean-minus-corrupted gap that restoring recovers. It can be negative, when the component pushes against the answer, and can exceed .
On an IOI prompt the clean logit difference is ; with the names replaced by unrelated ones it is . Restoring one head's clean output into the corrupted run gives . What fraction of the gap does the head recover?
Show the answer
0.56
. The head alone restores a little over half of the behavior on this prompt. In practice the effect is averaged over many prompt pairs, because one prompt can mislead.
import torch
@torch.no_grad()
def denoising_scan(model, components, clean, corrupt, metric):
"""Normalized effect of restoring each component's clean output in the corrupted run."""
cache = {}
hooks = [c.register_forward_hook(lambda mod, inp, out: cache.__setitem__(mod, out)) for c in components]
m_clean = metric(model(clean))
for h in hooks:
h.remove()
m_corrupt = metric(model(corrupt))
effects = []
for c in components:
h = c.register_forward_hook(lambda mod, inp, out: cache[mod]) # a returned value replaces the output
effects.append(((metric(model(corrupt)) - m_corrupt) / (m_clean - m_corrupt)).item())
h.remove()
return effectsForward hooks record each component's output on the clean input, then substitute it, one component at a time, into the corrupted run; metric maps logits to a number such as a logit difference. The components should be ones that write into a residual stream side by side, such as attention layers, heads or MLP blocks. In a plain sequential stack every layer carries all the information, so restoring any whole layer restores the output exactly and every effect is 1; on a small residual network the same scan gives partial and even negative effects.
From components to circuits: indirect object identification
Patching a component measures everything that flows through it. To find a circuit you need the effect of one component on another. Path patching (Wang et al., 2023; formalized as a test of localization hypotheses by Goldowsky-Dill et al., 2023) runs the model on an input but, along a chosen set of paths from a sender to receivers (through residual connections and MLPs, not through other heads), replaces 's output by its value on ; everything downstream of is recomputed.
Wang et al. applied it to indirect object identification (IOI) in GPT-2 small (12 layers of 12 heads). On their prompt distribution the model's mean logit difference between the indirect object (IO, "Mary") and the subject (S, "John") was 3.56, with IO preferred 99.3% of the time. With the same sentence with three random names, patching each head's path to the logits at the final position showed that heads 9.6, 9.9 and 10.0 (layer.head) push toward the right answer and 10.7 and 11.10 against it. Tracing backward from those heads yielded an algorithm of three steps, identify the names, discard the duplicated one, copy the other, carried by 26 heads, 1.1% of all (head, position) pairs:
| Heads | Where they act | What they do |
|---|---|---|
| Duplicate token | at the second S, attending to the first | signal that S has already occurred |
| Previous token and induction | copy S into the position after it; at the second S, attend there | a second route to the same duplication signal |
| S-inhibition | at the final position, attending to the second S | write into the name movers' queries, steering their attention away from S |
| Name movers (9.6, 9.9, 10.0) | at the final position, attending to the names | copy the name they attend to, now IO, into the logits |
| Negative name movers (10.7, 11.10) | at the final position | write against the name they attend to, lowering confidence; Wang et al. speculate this hedges against costly mistakes |
| Backup name movers | normally almost inactive | take over the name movers' role when those are knocked out: an OR structure |
Automating the search
Manual path patching is slow: every candidate connection needs its own experiments and its own interpretation. ACDC (Conmy, Mavor-Parker, Lynch, Heimersheim & Garriga-Alonso, 2023) automates it over the model's computational graph of heads and MLPs, pruning edges greedily from the output backward:
H <- G # start from the full computational graph
for v in the nodes of H, from the output back to the inputs:
for each parent w of v:
H_new <- H without the edge w -> v # the edge now carries its corrupted activation
if KL(G || H_new) - KL(G || H) < tau:
H <- H_new # the edge does not matter: remove it for good
return His the average divergence between the full model's output distribution and that of the pruned graph, run on clean inputs with every removed edge patched from a corrupted input; the threshold sets how sparse the result is. On the greater-than task in GPT-2 small, ACDC rediscovered all five component types of a hand-found circuit and kept 68 of 32,000 edges, every one of which earlier manual work had found.
ACDC still needs a forward pass per edge, and exhaustive patching of a large model is out of reach: Kramár, Lieberum, Shah & Nanda (2024) count neuron nodes in Chinchilla 70B for one 1024-token prompt. Attribution patching (proposed by Nanda in a blog post) replaces every patch by a first-order Taylor estimate. Write for the metric of the corrupted run with component 's activation set to , downstream recomputed, so the denoising effect is . With , the estimate comes for every component at once from one clean forward pass and one corrupted forward and backward pass.
Taylor's theorem with integral remainder along the segment , :
Bound the quadratic form by and use . The estimate is good when patches are small relative to the curvature and bad when they push activations across sharp nonlinearities, such as an attention softmax that switches from one key to another.
Kramár et al. found exactly these failures, both producing false negatives. Patching queries or keys can move a saturated attention pattern a long way, where the gradient says almost nothing; AtP* recomputes the softmax exactly and linearizes only after it. And large positive and negative contributions inside one component can cancel in the gradient; AtP* applies dropout to the backward pass to break the cancellation. Candidates are then verified by real patching. Applied to edges and used to prune, attribution patching recovered known circuits better than ACDC and the other methods compared, averaged over tasks, at the cost of two forward passes and one backward pass (Syed, Rager & Conmy, 2024).
When is a circuit explanation true?
A circuit diagram is a hypothesis about an algorithm, and causal abstraction (Geiger, Lu, Icard & Potts, 2021) states precisely what it claims. Write the algorithm as a high-level causal model , for IOI with variables such as "which name is duplicated", and align each variable with components of the network . An interchange intervention runs on a base input with the aligned components set to their values on a source input, and runs on the base input with the variable set to its value on the source. If the outputs agree for all pairs of inputs and all variables, is an exact abstraction of ; the fraction of pairs that agree, the interchange intervention accuracy (IIA), grades approximate ones.
Variables need not sit on whole neurons or heads. Distributed alignment search (Geiger, Wu, Potts, Icard & Goodman, 2024) learns an orthogonal rotation by gradient descent and intervenes on subspaces of the rotated activations; it found alignments with 100% IIA for a network trained on a hierarchical equality task and for a fine-tuned language model on a natural-language inference task. Searching over subspaces, however, opens a new failure mode.
Take the linear network , with and , so . Coordinate varies with but is never read (): it is causally disconnected. Coordinate is read but is always : it is dormant. All the computation runs through .
Patch the one-dimensional subspace from a source input into a base input : replace the base activation's component along by the source's.
The output follows the source exactly, so the patch scores 100% IIA for " mediates ", although the network never uses : the variation comes from the disconnected , and the effect from the dormant , which the patch itself switches on.
Makelov et al. found the same illusion in GPT-2 small: a one-dimensional subspace of an MLP layer, found by distributed alignment search, appeared to carry the IOI name-position signal although Wang et al. had found that layer's contribution negligible. They also showed what a faithful subspace looks like, and that the illusion does not make subspace patching useless: it means checking that the subspace's normal variation is read downstream.
Causal scrubbing (Chan et al., 2022) turns a whole hypothesis into one test of behavior-preserving resampling: every activation is replaced by its value on another input that the hypothesis says is equivalent for it, and every input the hypothesis calls irrelevant is resampled freely; the hypothesis is scored by the fraction of the model's loss it recovers.
Two effects make all such scores harder to read. Networks repair themselves: ablating one attention layer of Chinchilla 7B made later layers compensate (the hydra effect), with compensation explaining 92% of the variance of downstream changes at layer 23 of 32, though the regression slope stayed below one after layer 13, so the repair was partial (McGrath et al., 2023). Rushing & Nanda (2024) found self-repair across model families when single heads are ablated on the full training distribution, imperfect and noisy, sometimes overcorrecting. And faithfulness scores are sensitive to the ablation itself, zero, mean or resampled, and to details such as which positions are ablated: the task a circuit must perform depends on how it is tested (Miller, Chughtai & Saunders, 2024).
Key takeaways
- Activation patching measures causal effects: the indirect effect of a component is the change in a metric when only that component takes its value from another input. Denoising (clean into corrupted) tests sufficiency; noising (corrupted into clean) tests necessity.
- The two directions disagree systematically: AND-like structure hides components from single denoising, OR-like redundancy hides them from single noising, so careful studies patch in both directions and in sets.
- Conclusions depend on the corruption and the metric. Natural counterfactuals (token replacement) keep the model on its distribution, and the logit difference, unlike probability, adds across components and shows negative ones.
- Path patching traces effects along specific edges and revealed a 26-head IOI circuit in GPT-2 small; faithfulness, completeness and minimality test such circuits, and ACDC and attribution patching automate the search, the latter with an error that grows with the size of the patch.
- Interventions can mislead: subspace patches can activate dormant pathways, later layers repair ablations, and faithfulness scores depend on the ablation method. Causal abstraction states precisely what a circuit explanation claims.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A later head needs two pieces of clean information at once: a name from one earlier head and a position signal from another. You denoise each earlier head separately into the corrupted run. What do you expect?
- Each earlier head restores half the behavior
- Neither earlier head restores the behavior alone; the AND structure hides both from single-component denoising, while noising either one would break it
- Both restore the behavior fully, since each is sufficient
- Denoising cannot be applied to attention heads
Show the answer
B. Neither earlier head restores the behavior alone; the AND structure hides both from single-component denoising, while noising either one would break it
With , restoring leaves corrupted and stays off. Noising either input in the clean run turns off, so noising finds both, while denoising finds only the later head itself.
Why do Zhang & Nanda recommend symmetric token replacement over Gaussian noise on the subject embeddings?
- Gaussian noise is too weak to change the model's answer
- Token replacement is cheaper to compute
- Token replacement keeps the corrupted prompt natural, while large embedding noise can push the model off its training distribution and distort which components appear important
- Gaussian noise cannot be used with the logit difference
Show the answer
C. Token replacement keeps the corrupted prompt natural, while large embedding noise can push the model off its training distribution and distort which components appear important
STR corrupts by changing what the prompt says, so downstream components see the kind of input they were trained on. GN changes the input to something no training text produces; the components' responses to it, and hence the localization, can differ, as the 2 to 5 times higher GN peaks in GPT-2 XL illustrate.
A circuit retains 87% of the full model's logit difference when everything else is mean-ablated, yet knocking out a certain subset of the circuit's heads hurts the circuit far more than knocking out the same heads in the full model. What does this reveal?
- The circuit is not minimal
- The faithfulness score was computed incorrectly
- The circuit is complete, because 87% is high
- The circuit is incomplete: the full model has other components, such as backups, that compensate for the removed heads
Show the answer
D. The circuit is incomplete: the full model has other components, such as backups, that compensate for the removed heads
Completeness asks that be small for every subset . A large gap means the model contains components outside that do the job when parts of are missing; faithfulness alone cannot see them. Wang et al. found such subsets for their IOI circuit with an incompleteness of up to 3.09, 87% of the original logit difference.
Patching a learned one-dimensional subspace of an MLP layer makes the model's output follow the source input perfectly, yet earlier work showed the layer contributes almost nothing to the behavior. What is a possible explanation?
- The patch combines a direction that varies with the feature but is not read downstream with a dormant direction that is read but never normally active; the patch itself switches the dormant pathway on
- The earlier work must be wrong, since perfect patching proves the subspace is used
- Subspace patching always succeeds in every layer
- The MLP layer stores the feature in its weights rather than its activations
Show the answer
A. The patch combines a direction that varies with the feature but is not read downstream with a dormant direction that is read but never normally active; the patch itself switches the dormant pathway on
Makelov, Lange & Nanda showed that a subspace intervention can create a variable rather than locate one: the patched direction mixes a causally disconnected direction, which carries the variation, with a dormant one, which can affect the output. Checking that the subspace's normal variation is actually read downstream separates real from illusory subspaces.
Further reading
- J. Vig, S. Gehrmann, Y. Belinkov, S. Qian, D. Nevo, Y. Singer & S. Shieber, "Investigating gender bias in language models using causal mediation analysis," NeurIPS (2020).
- K. Wang, A. Variengien, A. Conmy, B. Shlegeris & J. Steinhardt, "Interpretability in the wild: a circuit for indirect object identification in GPT-2 small," ICLR (2023).
- F. Zhang & N. Nanda, "Towards best practices of activation patching in language models: metrics and methods," ICLR (2024).
- A. Conmy, A. N. Mavor-Parker, A. Lynch, S. Heimersheim & A. Garriga-Alonso, "Towards automated circuit discovery for mechanistic interpretability," NeurIPS (2023).
- A. Geiger, H. Lu, T. Icard & C. Potts, "Causal abstractions of neural networks," NeurIPS (2021).