Skip to content
← All posts

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.

Behavioral“What does it do?”input?outputMechanistic“How does it do it?”inputoutput
Figure 1. Two ways of looking at a model.
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:

one layer · repeats 12× in GPT-2 smallxᵢxᵢ₊₁xᵢ₊₂h₀h₁…heads+MLP+embedtokenunembedlogits

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.

Figure 2. One transformer layer. Click a part to see what it does.
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:

  1. 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, x0x_0. 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.
  2. 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.
  3. 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.
  4. 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:

xi+1=xi+∑hh(xi),xi+2=xi+1+m(xi+1).x_{i+1} = x_i + \sum_{h} h(x_i), \qquad x_{i+2} = x_{i+1} + m(x_{i+1}).

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

The problem

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?

The proposed solution

Each head computes an attention pattern: for every token, how much it looks at each earlier token. We can simply plot it.

Where it breaks

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 (query)to (key)“The”“The”“ E”“ E”“iff”“iff”“el”“el”“ Tower”“ Tower”“ is”“ is”“ in”“ in”“ the”“ the”“ city”“ city”“ of”“ of”

From “ of”, layer 9 head 8 looks at:

  1. “ Tower”26%
  2. “el”20%
  3. “The”19%
  4. “iff”17%
  5. “ E”8%

Click or tap a token on the left. A token can only look at itself and earlier tokens.

Figure 3. Real attention patterns from four heads of GPT-2 small.Measured on GPT-2 small
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

The problem

When does the answer appear?

The model only shows its prediction at the very end. When during the forward pass does “Paris” appear?

The proposed solution

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 →: logitsℓ=WU LN(xℓ)\text{logits}_\ell = W_U \,\mathrm{LN}(x_\ell).

Where it breaks

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

  1. “ London”28.5%
  2. “ Paris”24.8%
  3. “ Amsterdam”8.8%
  4. “ Rome”3.9%
  5. “ Chicago”3.1%

“Paris” is ranked #2 of 50,257 tokens.

Probability of “Paris” at each depth

embedoutput24.8%
Figure 4. The logit lens on “The Eiffel Tower is in the city of”.Measured on GPT-2 small
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

The problem

Who wrote the answer?

Which components are responsible for “Paris”?

The proposed solution

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).

Where it breaks

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.

-0.40+0.5+1Attention layer 0: -0.01MLP layer 0: -0.050Attention layer 1: 0.03MLP layer 1: -0.151Attention layer 2: -0.10MLP layer 2: -0.042Attention layer 3: 0.02MLP layer 3: -0.013Attention layer 4: -0.14MLP layer 4: -0.034Attention layer 5: -0.05MLP layer 5: -0.105Attention layer 6: 0.10MLP layer 6: -0.206Attention layer 7: 0.09MLP layer 7: -0.327Attention layer 8: 0.39MLP layer 8: -0.128Attention layer 9: 0.96MLP layer 9: 0.309Attention layer 10: 0.46MLP layer 10: 0.1610Attention layer 11: 0.40MLP layer 11: 0.2911layerdirect push towards “Paris” over “Rome” (logit difference)attention (all 12 heads)MLP
Figure 5. How much each layer directly pushes “Paris” over “Rome” (total: 2.42).Measured on GPT-2 small
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

The problem

Does the model need this part?

DLA is a reading, not an experiment. Does the model actually need a given component?

The proposed solution

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.

Where it breaks

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:

Replace with:
P(“Paris”)7.0%

Black tick: the intact model (7.0%). Bar scale goes up to 10%.

Paris − Rome score (logit difference)2.42

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%

Figure 6. Switch components off and watch P(“Paris”) and the Paris − Rome score.Measured on GPT-2 small
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

The problem

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?

The proposed solution

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: LDpatched−LDcorruptedLDclean−LDcorrupted\dfrac{\text{LD}_\text{patched} - \text{LD}_\text{corrupted}}{\text{LD}_\text{clean} - \text{LD}_\text{corrupted}}, where LD is the logit difference.

Where it breaks

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.

“The”E / Coliff / osel / seTower / um“ is”“ in”“ the”“ city”“ of”layer 0layer 1layer 2layer 3layer 4layer 5layer 6layer 7layer 8layer 9layer 10layer 11

Patch residual stream at layer 3, token iff / os: the Colosseum run, with this one value replaced by the Eiffel run’s.

Paris2.0%
Rome1.2%

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%).

Figure 7. Activation patching. Each cell runs the Colosseum prompt and replaces one value, at one layer and token, with the value saved from the Eiffel run. Single heads aren't patched here.Measured on GPT-2 small
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.

direct effect (DLA)total effect (patching)Layer 9, head 832%37%Layer 8, head 1114%27%Layer 10, head 012%13%Layer 6, head 42%18%Layer 3, head 30%9%
Figure 8. Direct effect (DLA) vs. total effect (patching the head everywhere) for five heads.Measured on GPT-2 small
Takeaway: A component can matter a lot without writing anything to the output itself, so direct attribution alone can miss important parts.

Probing

The problem

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?

The proposed solution

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.

Where it breaks

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.

● positive sentence   ■ negative sentence  (hollow = held out for testing)

Hover or tap a point to see its sentence.

Figure 9. GPT-2's residual stream at layer 6 for 192 synthetic sentences (“The movie was wonderful.”, “The food was awful.”, …), projected onto its two main directions.Measured on GPT-2 small
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

ToolProblemQuestion it answersKind of evidenceCost
Attention patternsInformation must move between tokens, but we can’t see the pathWhere does each token look?ObservationalOne forward pass
Logit lensWe only see the prediction at the very endWhen does the answer appear?ObservationalOne forward pass
Direct logit attributionMany components add to one outputWho wrote the answer?Observational (direct effects only)One forward pass
AblationA contribution isn’t proof that it mattersDoes the model need this part?CausalOne pass per component
Activation patchingRemoving a part doesn’t show what information it carriesWhere is the information, and where does it move?CausalOne pass per component and position
ProbingWe care about a concept, not a componentCan 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.

the networkroles / conceptsReverse engineeringfrom parts to roles: what does this part do?Concept-based interpretabilityfrom roles to parts: where is this concept?
Figure 10. The two directions of mechanistic interpretability.
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