Opening the Black Box: Mechanistic Interpretability
Study notes on looking inside a language model, with every tool tried out on GPT-2 small.
Contents
How does AI learn? Or, more importantly, what does learning even mean for an AI? Does the word “learning” stand for the same thing in a machine as it does in a human?
These questions intrigued me, so I started studying the concepts underneath them, and I decided to write down my understanding and my research thoughts as a blog. These posts are mainly my study notes: I use them to keep track of what I’m learning and of the research ideas I have along the way.
What is mechanistic interpretability?
Most ways of studying a model treat it as a box: send in inputs, look at outputs, and describe its behavior. Mechanistic interpretabilityStudying a neural network's internals to understand the algorithms it has learned, not just its inputs and outputs. Jump to the section → opens the box. It tries to understand the internal mechanisms, the actual algorithm the network has learned, well enough to predict what it will do, even on inputs nobody has tested.
Two analogies help. It’s like reverse-engineering a compiled program back into readable source code. Or it’s neuroscience for artificial networks, with one big advantage over real neuroscience: we can read and change every number inside, as often as we like.
Takeaway: Behavioral testing tells us what a model does; mechanistic interpretability asks how it does it.
Why bother? There are four main reasons:
- Understanding: know how a model produces an output, not just that it does.
- Debugging: find the mechanism behind a failure and fix that, instead of patching symptoms.
- Safety: check for behavior that’s hard to catch from outputs alone, such as bias, deception or hidden goals.
- Science: learn what neural networks actually learn, and maybe something about the problems they solve.
A map of the transformer
To look inside, we need a map. Almost every modern language model is a transformer. Here is one of its layers. Click a part to see what it does:
Residual stream
A shared whiteboard that every layer reads from and writes to. Components never overwrite it; they add their output (⊕). So the final vector is the sum of the embedding plus every component’s contribution, and that sum is what the interpretability tools below take apart.
The three small bar charts are one token’s vector before the layer, after attention and after the MLP. Attention adds the orange edits, the MLP adds the teal ones (faded = subtracted). Nothing is overwritten. Values are illustrative.
Takeaway: Components never overwrite the residual stream; they add to it, so the output is a sum of their contributions.
Heads and MLP neurons are the units we try to interpret. Whether they are the right units is a separate question: a single neuron often responds to several unrelated things (more on that in Taking a Network Apart).
Reading the figure from the bottom:
- Each TokenA chunk of text (a word, part of a word or a symbol) that the model reads as one unit. “Eiffel” is split into the tokens “ E”, “iff” and “el” by GPT-2. becomes a vector, . This vector travels up the Residual streamThe main vector each token carries through a transformer. Every layer reads from it and adds its output back, like a shared whiteboard. Jump to the section →, a shared whiteboard that every component reads and writes.
- Several Attention headA transformer component that decides which earlier tokens to look at and moves information from them to the current token. Jump to the section → read the stream in parallel. Each one asks, “given this token, which earlier tokens should I care about?”, and adds what it found back to the stream.
- An MLP layerThe feed-forward part of a transformer layer. It processes each token on its own and is thought to store much of the model’s learned knowledge. Jump to the section → then reads the updated vector and enriches it: using what it learned in training, it pushes the vector towards the relevant directions.
- This repeats for every layer (12 in GPT-2 small). At the top, the UnembeddingThe final matrix that maps the residual stream to logits over the vocabulary. turns the final vector into LogitsThe model’s raw scores for every possible next token, before they are turned into probabilities.: a score for every possible next token.
In symbols, one layer is just two additions:
That “just additions” fact is what makes the tools below possible: the final vector is literally a sum of contributions from every component, so we can ask how much each one added.
Query, Key, Value in one line each. Inside an attention head, every token makes three vectors (Query / Key / ValueQuery: what a token is looking for. Key: what a token offers. Value: the information passed on when a token is attended to. Jump to the section →). Query: what am I looking for? Key: what do I contain, what can be found in me? Value: the information I pass on if someone attends to me. A token attends to the earlier tokens whose keys best match its query, and receives a weighted mix of their values.
Why do heads learn different things? Each head starts from different random weights. If two heads started identical, they would get identical updates and stay twins forever. The random start breaks that symmetry, and training then pushes heads to specialize in different patterns.
The toolbox
Now for the tools. To keep things concrete, we’ll use one running example on a real model, GPT-2 small (124M parameters, released in 2019). We give it the prompt “The Eiffel Tower is in the city of”. Its top guess is “Paris”, at 7.0%. (It’s a small, old model: London is close behind at 5.8%. With the shorter prompt “The Eiffel Tower is in”, its top guess is just “the”.)
Every number in the figures below was computed on GPT-2 small with a short script. Nothing is made up.
Attention patterns
Where does each token look?
Information has to move between tokens: the word “Paris” has to be predicted at the last position, “ of”, but the clue sits five or more tokens earlier, in “Eiffel Tower”. Which heads move what, and from where?
Each head computes an attention pattern: for every token, how much it looks at each earlier token. We can simply plot it.
An attention pattern shows where a head looks, not what it moves or whether that matters for the output. Many heads also park most of their attention on the first token when they have nothing useful to do, which you can see below.
From “ of”, this head looks back at the subject tokens “ E… Tower”. It is a candidate for moving “Eiffel Tower” information to the last position.
From “ of”, layer 9 head 8 looks at:
- “ Tower”26%
- “el”20%
- “The”19%
- “iff”17%
- “ E”8%
Click or tap a token on the left. A token can only look at itself and earlier tokens.
Takeaway: Some heads have simple, readable patterns, such as “look at the previous token” or “look back at the subject”, but a pattern alone doesn't tell us what is moved.
The logit lens
When does the answer appear?
The model only shows its prediction at the very end. When during the forward pass does “Paris” appear?
Because every layer writes into the same stream, we can take the stream halfway up and pretend it’s the end: apply the final layer norm and the unembedding to it, and read off the predictions. This is the Logit lensApplying the unembedding to intermediate layers to see what the model would predict if it stopped there. Jump to the section →: .
Earlier layers were never trained to be read this way, so their “predictions” can be distorted. The Tuned lensA logit lens with a small learned correction per layer, for more accurate intermediate predictions. learns a small correction per layer and gives more reliable readings.
Top 5 next-token guesses at this depth
- “ London”28.5%
- “ Paris”24.8%
- “ Amsterdam”8.8%
- “ Rome”3.9%
- “ Chicago”3.1%
“Paris” is ranked #2 of 50,257 tokens.
Probability of “Paris” at each depth
Takeaway: “Paris” is invisible for the first eight layers, then appears between layers 8 and 10, which tells us where to look next.
For the first half of the network, the best guess is “ the”. Around layer 8 the guesses turn into place names (oddly, “Rome” comes first), and after layer 9 “Paris” jumps to 25%. The last layers then spread the probability back out, so the final output is a more cautious 7%.
Direct logit attribution
Who wrote the answer?
Which components are responsible for “Paris”?
The final stream is a sum of every component’s output, so the final logit is (almost) a sum too. If we hold the last layer norm’s scaling fixed, we can split the logit into one share per head and per MLP. This is Direct logit attributionMeasuring how much each component’s output directly pushes a particular token’s logit up or down. Jump to the section → (DLA). To cancel out things that push every city up, we measure the push towards “Paris” relative to “Rome” (the logit difference).
It only sees direct effects: what a component writes straight into the output. A component that does its work by feeding a later component gets little or no credit here.
Takeaway: Most of the direct push comes from attention in layers 8 to 11, with a single head, layer 9 head 8, contributing about a third of the total.
The biggest single contributor is layer 9, head 8, which adds 0.84 of the total 2.42. In Figure 3, this is the head that looks from “ of” back to “Eiffel Tower”. Several MLPs in layers 5 to 8 push slightly the other way. So far this is only a reading of the sum, though. To test whether a component matters, we have to change something.
Ablation
Does the model need this part?
DLA is a reading, not an experiment. Does the model actually need a given component?
Switch it off and see what changes. This is AblationSwitching a component off (setting it to zero or its average value) to see how the output changes. Jump to the section →: replace a component’s output with zeros (zero ablation) or with its average output on other text, here 32 synthetic sentences (mean ablation), then rerun the model.
Zeros may be values the model has never seen, which pushes it off-distribution and can break things for reasons unrelated to our question. And a small change doesn’t prove a component is unimportant: other components can compensate, a behavior called self-repair[ref].
Switch components off:
Black tick: the intact model (7.0%). Bar scale goes up to 10%.
Intact model: 2.42. Above 0: Paris is ahead of Rome. Bar scale runs from 0 to 3; below 0 the bar is empty.
Top guesses now: “ Paris” 7.0%, “ London” 5.8%, “ New” 3.1%
Takeaway: No single head is “the Paris head”: removing the strongest one halves P(“Paris”), and even with four heads removed it keeps 1.4%.
Try it. Mean-ablating layer 9 head 8 roughly halves P(“Paris”), from 7.0% to 3.5%, and cuts the Paris − Rome score from 2.42 to 1.59.
Don’t judge by which city comes first. The intact model puts Paris only just ahead of London (7.0% vs 5.8%), so a small change can flip the order. Switching off layer 6 head 4 alone is enough: London takes the lead, but the score only falls to 2.08. Switching off the three late heads instead (L8H11, L9H8 and L10H0) leaves Paris narrowly first, yet does far more damage: P(“Paris”) falls to 1.7% and the score to 0.54. Paris stays ahead only because London drops too. Even with all four heads off, Paris keeps 1.4%.
Now switch off the MLP in layer 0: P(“Paris”) falls to zero with either kind of ablation, and the top guess becomes “ the”. That’s a big effect, but it says little about Paris. The first MLP sits right after the token embedding, and removing it breaks everything, not just this fact. A large drop from an ablation doesn’t mean a component is specific to the behavior you care about.
Activation patching
Where is the information, and where does it move?
Ablation removes information from the model and asks “what breaks?”. We’d rather ask a more precise question: where in the model is the specific fact “this is about the Eiffel Tower, so: Paris” stored and moved?
Run two prompts that differ only in that fact. The clean run gets “The Eiffel Tower is in the city of”; the corrupted run gets “The Colosseum is in the city of”. Then rerun the corrupted prompt, but copy one activation over from the clean run. If the output swings back towards Paris, that activation carried the difference. This is Activation patchingCopying a component’s activation from one input’s run into another input’s run, to test whether that component carries the information that differs between them. Jump to the section →, also called causal tracing. We measure how much of the Paris-versus-Rome gap comes back: , where LD is the logit difference.
Results depend on choices that feel like details: which corrupted prompt, which metric, and which positions you patch. And it needs one forward pass per component and position you test, which gets expensive for big models.
Clean run
The Eiffel Tower is in the city of …
Paris 7.0% · Rome 0.6%
Corrupted run
The Colosseum is in the city of …
Paris 0.3% · Rome 1.4%
Residual stream: the whole stream entering each layer. Color = change from the plain Colosseum run (score −1.49, Rome ahead). Green: towards Paris. Red: further towards Rome. Paris overtakes Rome only above 38% restored. Click a cell, or use the sliders.
Patch residual stream at layer 3, token iff / os: the Colosseum run, with this one value replaced by the Eiffel run’s.
Score (Paris − Rome): −1.49 → +0.49
Gap restored: 51%
How far the score moved from the Colosseum run (−1.49, 0%) towards the Eiffel run (+2.42, 100%).
Takeaway: The fact sits on the subject tokens for the first eight layers, then attention moves it to the last token around layers 8 to 10.
The residual stream view tells a clear story. Patching the subject tokens (“iff”, “ Tower”) in early layers restores 30–50% of the gap. Patching the last token, “ of”, does nothing until the stream entering layer 9, which restores 28%, then 69% and finally 87% at layers 10 and 11. Somewhere between layers 8 and 10, the information is moved from the subject to the last position. Switch to “Attention output” and you’ll see who moves it: attention at “ of” in layers 8 and 9, exactly where layer 9 head 8 sits. Patching one head at a time at “ of” confirms the link to DLA: L8H11 restores 23%, L9H8 34% and L10H0 13%, about as much as their whole layers (21%, 33% and 15%).
Red needs care. MLP 11 at “ of” is red (−17%), but not because it says “Rome”: the pasted Eiffel output holds Rome back less than the Colosseum output it replaced.
Direct effect vs. causal effect. DLA measures what a component writes straight into the output. Patching measures its total effect, through every later layer. They can disagree a lot. Layer 6 head 4 has almost no direct effect (2% of the gap) but an 18% total effect: whatever it writes is picked up and used by later components, not by the output directly.
Takeaway: A component can matter a lot without writing anything to the output itself, so direct attribution alone can miss important parts.
Probing
Can we read the concept from here?
Sometimes we start from a concept rather than a component. Does the model represent, say, whether a sentence is positive or negative? And where?
Collect the model’s activations for labeled examples and train a tiny classifier on them, a ProbeA small classifier trained on activations to test whether a concept can be read out from them. Jump to the section →. If a Linear probeA probe that is a single linear layer. If it works, the concept corresponds to a direction in activation space. Jump to the section → works, its weights give a direction in activation space that corresponds to the concept.
A probe finds correlation. It tells us the information is there, not that the model uses it. A powerful probe can even learn the task by itself: on this data, a probe trained on shuffled labels still fits 98% of its training sentences at layer 6, because 768 dimensions are plenty to memorize 144 examples. More on this in Looking for What We Already Know.
Hover or tap a point to see its sentence.
Takeaway: Sentiment is easy to read out with a straight line, but readable doesn't mean the model uses it.
The two clouds separate cleanly, even on sentences about topics the probe never saw. Fair warning, though: this is synthetic data, generated from the template “[subject] was [adjective].” The test sentences use new subjects but the same adjectives, so this is an easy case: the probe may simply recognize those words.
The toolbox at a glance
| Tool | Problem | Question it answers | Kind of evidence | Cost |
|---|---|---|---|---|
| Attention patterns | Information must move between tokens, but we can’t see the path | Where does each token look? | Observational | One forward pass |
| Logit lens | We only see the prediction at the very end | When does the answer appear? | Observational | One forward pass |
| Direct logit attribution | Many components add to one output | Who wrote the answer? | Observational (direct effects only) | One forward pass |
| Ablation | A contribution isn’t proof that it matters | Does the model need this part? | Causal | One pass per component |
| Activation patching | Removing a part doesn’t show what information it carries | Where is the information, and where does it move? | Causal | One pass per component and position |
| Probing | We care about a concept, not a component | Can we read the concept from here? | Observational (correlation) | Labeled data and a small classifier |
“Observational” tools read activations without changing them. “Causal” tools intervene and measure the effect, which is stronger evidence.
Two ways to do mechanistic interpretability
The tools above can be combined in two quite different ways. One goes from the network to its roles; the other goes from roles back to the network.
Takeaway: Reverse engineering asks “what does this part do?”; concept-based interpretability asks “which part does this?”.
Reverse engineeringInterpreting a network bottom-up: cut it into components, then work out what each one does. Jump to the section → works bottom-up. Cut the network into parts, then work out what each part does. It goes from parts to their roles. Its strength is that it can find things we didn’t think to look for. The hard question is where to make the cuts, since single neurons turn out to be the wrong unit. More on this in Taking a Network Apart.
Concept-based interpretabilityInterpreting a network top-down: start from a concept we care about and find which components represent or use it. Jump to the section → works top-down. Start from a concept we care about, such as truthfulness or refusal, and find where and how the model represents it. It goes from roles to the parts that play them. It’s targeted, cheap and practical for safety questions, but it only finds what we already thought to look for. More on this in Looking for What We Already Know.
Wrap-up
A transformer is a stack of components adding their results to one shared stream. That simple structure lets us read the stream mid-way (logit lens), split the output into contributions (DLA), and run experiments: switching parts off (ablation) or swapping them between inputs (patching). On one small example, these tools already sketch a story: GPT-2 small stores “Eiffel Tower” on the subject tokens, and a few attention heads around layer 9 carry it to the end of the sentence. The harder question is what the right “parts” are in the first place.
Further reading
- Neel Nanda, A Comprehensive Mechanistic Interpretability Explainer & Glossary
- ARENA, a free hands-on course on transformer interpretability
- TransformerLens, the standard library for these experiments
- Transformer Circuits Thread, Anthropic’s research notes