Interpretability: Looking Inside Networks
Saliency, probes, feature visualization and mechanistic interpretability.
An image classifier once recognized horses by a small source tag that appeared on about a fifth of the horse photos in its benchmark: paste the tag onto a car and it answered "horse". Its test accuracy gave no hint. Interpretability builds the tools that catch such shortcuts and, more ambitiously, work out what a network computes. Here you'll derive gradient and path attributions, train probes, see why single neurons are often polysemantic, and meet the two main tools of mechanistic interpretability: sparse dictionaries and causal patching.
What you’ll learn
- Distinguish the three questions interpretability asks (which inputs mattered, what a layer encodes, how the output is computed), the methods that answer each, and plausible from faithful explanations.
- Derive gradient saliency as a first-order Taylor attribution, show how saturation breaks it, and compute integrated gradients and their completeness property.
- Train and interpret a probe, and explain why high probe accuracy shows that information is decodable, not that the network uses it.
- Explain polysemantic neurons by superposition, and formulate a sparse autoencoder that recovers feature directions from activations.
- Describe circuits and activation patching, and compute the fraction of a behavior that restoring one component recovers.
Three questions about a trained network
A trained network is a function with millions of parameters that nobody wrote by hand. Interpretability asks questions about it whose answers people can check, for three kinds of reasons.
- Debugging. Lapuschkin et al. (2019) ran an explanation method on a Fisher-vector classifier (a pre-deep-learning model) trained on the PASCAL VOC benchmark. For many horse photos its evidence sat in the lower left corner, on a source tag that appeared on about a fifth of the horse images. Removing the tag removed the "horse" answer, and adding it to a photo of a car produced one. A deep network fine-tuned on the same data looked at the horse and rider. Such shortcuts pass every accuracy test on data that contain them.
- Trust. Deciding whether a model may be used where its errors are costly requires knowing what its answers rest on.
- Science. Gradient descent finds algorithms no one designed. Which ones, and why, is a question about the world.
| Level | Question | Typical methods | What an answer looks like |
|---|---|---|---|
| Attribution | Which parts of this input drove this output? | gradients, integrated gradients, occlusion, Grad-CAM | a score per pixel, token or input feature: a heat map |
| Representation | What information does a layer carry, and in what format? | probes, feature visualization, sparse dictionaries | directions in activation space with a meaning |
| Mechanism | How is the output computed from the input? | circuits, activation patching, causal abstraction | a subgraph of components and the algorithm it implements |
Two attribution methods explain a chest X-ray classifier's "pneumonia" output. Method A highlights the lungs; method B highlights a text marker that some hospitals print in a corner of their images. Radiologists find A far more convincing. What should you do?
- Trust A: expert agreement shows that it is the faithful one
- Trust B: an unexpected explanation is more likely to be true
- Average the two maps, since each captures part of the truth
- Intervene: for example, cover or move the marker and check whether the output changes
Show the answer
D. Intervene: for example, cover or move the marker and check whether the output changes
Expert approval measures plausibility. Whether the model relies on the marker is a causal question, answered by changing the input (or the model) and watching the output. If covering the marker flips the prediction, the plausible map was not faithful, whatever the radiologists think.
Attribution: from gradients to integrated gradients
Write for the score being explained, usually the logit of the predicted class rather than its softmax probability, which can also rise because other classes' scores fall. The simplest attribution asks how responds to a small change of each input, which is what a first-order Taylor expansion says:
Gradients are local, and networks saturate: once a unit's evidence is overwhelming, more of it changes nothing, so the gradient is zero exactly where the input made all the difference. Integrated gradients (Sundararajan, Taly & Yan, 2017) accumulate the gradient along the straight path from a reference input , chosen to carry no signal (a black image, an all-zero embedding), to the input .
Average each partial derivative along the path , , and multiply by the displacement:
Completeness. By the chain rule, along the path is ; integrating from to gives . So the attributions always add up to the change in output, a property plain gradients lack (the Artificial Intelligence course's lesson Mechanistic Interpretability writes out the proof):
For a linear the gradient is the constant , so integrated gradients reduce to gradient times input measured from the reference. They differ only where bends. An input equal to its reference value always gets zero, whatever its role: a black reference can never credit black pixels.
A saturated unit. Let , a ReLU unit capped at (it equals ). At with reference , the output is against , yet the gradient at is : gradient saliency credits nothing. Along the path the unit's input is , which reaches the cap at .
For at with reference , what is , the attribution to the first input?
Show the answer
0.6
Only the unsaturated part of the path counts: and . They add up to , as completeness requires, and split the credit in proportion to the contributions and that drove the unit to its cap. The gradient at gave both inputs zero.
import torch
def integrated_gradients(f, x, reference, steps=64):
# f maps a batch of inputs to one score per input, e.g. lambda z: model(z)[:, c]
alphas = (torch.arange(steps) + 0.5) / steps # midpoints of [0, 1]
shape = (steps,) + (1,) * x.dim()
path = reference + alphas.view(shape) * (x - reference) # points on the straight line
path.requires_grad_(True)
(grads,) = torch.autograd.grad(f(path).sum(), path)
ig = (x - reference) * grads.mean(dim=0) # displacement times mean gradient
gap = (f(x[None]) - f(reference[None])).item() # completeness: ig.sum() should be close
return ig, gapOne batched backward pass over the path. With 64 midpoints this returns and on the saturated unit above, against the exact and . Sundararajan et al. found 20 to 300 steps enough to approximate the integral within 5%, and recommend checking that the attributions add up to gap.
Probes: what does a layer encode?
To ask what a layer represents in general rather than for one input, freeze the network, record the activations of layer on a labeled dataset, and train a small classifier , a probe, to predict a property the network was never trained to output: a word's part of speech, the tense of a sentence, whether an image contains stripes. A linear probe is logistic regression on , and its accuracy measures how much of is linearly decodable at layer . It is the same tool that evaluates self-supervised features in Self-Supervised Learning, used now as a microscope.
Alain & Bengio (2016) introduced linear classifier probes and attached them to every layer of Inception v3 and ResNet-50: the linear separability of the classes increased monotonically with depth. In language models, probes trace where linguistic information lives. Tenney, Das & Pavlick (2019) found that the BERT layers carrying each kind of information come in the order of a classical NLP pipeline: part-of-speech tags first, then parsing, named entities, semantic roles and finally coreference.
A probe's weight vector is a direction in activation space. Kim et al. (2018) made this a tool for image classifiers: separate a layer's activations on pictures of a concept, such as stripes, from those on random pictures with a linear classifier, and take the normal to its decision boundary as a concept activation vector. The derivative of a class logit along that vector measures, for example, how sensitive the prediction "zebra" is to stripes. Treating concepts as directions at all is an assumption with a name, the linear representation hypothesis.
| Trap | Why it misleads | Remedy |
|---|---|---|
| The probe does the work | A probe with enough capacity can solve the task on its own from almost any representation, even random labels that depend only on each word's identity | compare with a control task of random labels and report the gap, the probe's selectivity (Hewitt & Liang, 2019) |
| Decodable is not used | A property can be readable from a layer that the network's later layers ignore | remove the property from the representation and test whether the network's behavior changes |
A linear probe predicts part-of-speech tags from layer 3 of a language model with 97% accuracy. Which conclusion is justified?
- The model uses part of speech in layer 3 to predict the next word
- Layer 3 holds part-of-speech information in a linearly decodable form; only a causal test can show whether the model uses it
- Layer 3 is where the model computes part of speech
- An MLP probe at the same layer would show that the layer holds even more syntactic information
Show the answer
B. Layer 3 holds part-of-speech information in a linearly decodable form; only a causal test can show whether the model uses it
Decodability is all a probe measures. The information may have been computed earlier and merely passed along, and later layers may ignore it. Removing the property and watching the model's predictions is the test of use, and Probing & the Linear Representation Hypothesis shows cases where the answer is no.
Neurons, directions and superposition
Which units should interpretability study? Olah et al. (2020), in "Zoom In", put forward three deliberately speculative claims. Features are the fundamental units of networks and correspond to directions in activation space, a single neuron being one possible direction among many. Features connected by weights form circuits that can be rigorously studied. And universality: analogous features and circuits form across models and tasks.
In InceptionV1 many neurons look clean, such as the curve detectors of an early layer, which respond to curved lines and boundaries with a radius of about 60 pixels. Many do not: one neuron responds to cat faces, fronts of cars and cat legs. Such neurons are polysemantic, and they defeat neuron-by-neuron analysis, since two neurons with five meanings each are joined by 25 entangled connections.
The same article caught a network spreading a feature out. A car-detecting neuron in layer mixed4c, built from wheel detectors below and window detectors above, does not feed a pure car detector in the next layer: the car feature is spread over several neurons that mostly detect dogs. The article named this superposition, and Elhage et al. (2022) studied it in a toy model in which sparse features must pass through hidden dimensions and be read back out:
The nonlinearity is essential. In a linear model, , interference cannot be filtered out and representing more features than dimensions never pays: the best solution keeps the most important features at right angles, like PCA (Elhage et al., 2022). With a ReLU, negative interference is clipped to zero for free and negative biases cut off small positive interference.
Two consequences follow for interpretability. An elementwise activation function makes the neuron axes special, a privileged basis (in a word embedding, read only through linear maps, no basis is special and only directions can mean anything), and yet neurons can still be polysemantic, because there are more features than neurons. And the meaningful units are directions, which have to be found. The Artificial Intelligence course's lesson Mechanistic Interpretability works out how sparse two features must be before squeezing both into one dimension costs less than keeping only one of them.
Dictionaries and circuits
Suppose each activation vector is built from a few of many possible feature directions, with most coefficients . Recovering the directions from examples of is dictionary learning, a classic problem of signal processing. A sparse autoencoder (SAE) fits an overcomplete dictionary, with atoms, and computes each input's sparse code with a single encoder layer:
import torch
import torch.nn as nn
import torch.nn.functional as F
class SparseAutoencoder(nn.Module):
def __init__(self, d, n_latents):
super().__init__()
self.enc = nn.Linear(d, n_latents)
self.dec = nn.Linear(n_latents, d)
def forward(self, x):
f = F.relu(self.enc(x - self.dec.bias)) # sparse code, n_latents >> d
return self.dec(f), f
def sae_step(sae, opt, x, l1):
x_hat, f = sae(x)
loss = (x_hat - x).pow(2).sum(-1).mean() + l1 * f.abs().sum(-1).mean()
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad(): # keep every dictionary atom at unit norm
sae.dec.weight /= sae.dec.weight.norm(dim=0, keepdim=True)
return loss.item()The training data are activations recorded from one layer of the network under study. The weight l1 trades sparsity against reconstruction. On synthetic data built like the toy model, 48 sparse directions in 16 dimensions, a weak penalty gives codes with dozens of active latents whose atoms are mixtures of true directions; a strong enough one recovers nearly every true direction while reconstructing less exactly.
Bricken et al. (2023) applied this to a one-layer transformer, decomposing the activations of its 512-neuron MLP with dictionaries of 512 to 131,072 latents trained on 8 billion recorded activation vectors. The typical feature was much easier to interpret than the typical neuron; some, such as one firing on Hebrew script, were invisible in the neuron basis, absent from the top activations of every neuron. Features split into families of finer ones as the dictionary grew, and pinning a feature high steered generation: a base64 feature made the model write base64. Whether such features are the network's own units or artifacts of the method is the central question of Dictionary Learning at Scale.
Features are half of a mechanism; the other half is how they connect. To show that a component matters, intervene on it. Activation patching runs the model on a clean input that produces the behavior and on a corrupted input that differs in one key respect, then reruns with one component's activation restored to its value on . With a metric , typically the logit difference between the correct and an incorrect answer, the restored fraction is
which is if the component alone brings back the clean behavior and if it brings back nothing.
Wang et al. (2023) used patching to find how GPT-2 small completes "When Mary and John went to the store, John gave a drink to" with " Mary": a circuit of 26 attention heads that detect the repeated name, suppress it and copy the other one. Keeping only the circuit, with every other head replaced by its mean output on sentences of the same form with three unrelated names, retained 87% of the model's logit difference.
Key takeaways
- Interpretability asks three questions: which inputs mattered (attribution), what a layer encodes (representation) and how the output is computed (mechanism). Plausible explanations convince people; faithful ones track the computation, and only interventions can show faithfulness.
- Gradient saliency is a first-order Taylor attribution and fails where networks saturate. Integrated gradients average the gradient along a path from a reference input, so their attributions add up to ; the reference is a modeling choice.
- A probe measures what is decodable from a layer. Control tasks guard against the probe learning the task itself, and only removing a property can show the network uses it.
- Superposition, sparse features stored as more directions than dimensions, makes single neurons polysemantic; sparse autoencoders look for the directions as an overcomplete dictionary.
- Activation patching restores one component's clean activation into a corrupted run; the recovered fraction of a logit difference measures how much of the behavior that component carries.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A network's class logit is saturated at an input: increasing any pixel's intensity slightly would not change it. What do gradient saliency and integrated gradients (with a black reference image) report?
- Both report large attributions for the pixels that matter most
- Gradients give near-zero attributions; integrated gradients still distribute the full difference among the pixels
- Integrated gradients give zero too, because they also use gradients
- Both are undefined at a saturated point
Show the answer
B. Gradients give near-zero attributions; integrated gradients still distribute the full difference among the pixels
The gradient is evaluated only at , where the function is flat. Integrated gradients average the gradient over the whole path from the reference, where the unit was not yet saturated, and completeness guarantees the attributions sum to .
An MLP probe reaches 97% accuracy at predicting part-of-speech tags from a layer, but also 93% on a control task that assigns each word type a random tag. What does this suggest?
- The layer encodes part of speech very strongly
- The probe is broken, since no probe should learn random tags
- Much of the probe's accuracy may come from memorizing word identities, so the 97% says little about how the layer represents part of speech
- The control task must have been accidentally correlated with the real tags
Show the answer
C. Much of the probe's accuracy may come from memorizing word identities, so the 97% says little about how the layer represents part of speech
A control task can only be solved by the probe memorizing word types. When the probe nearly matches its real-task accuracy there, its selectivity (the gap) is small, and Hewitt & Liang recommend simpler probes, such as linear ones, which kept similar accuracy with much higher selectivity.
In the toy model of superposition, which change makes a network store more features than it has hidden dimensions?
- Making the features sparser, so that they are rarely active together
- Removing the ReLU, so that the model is linear
- Making all features dense and equally important
- Adding more training steps at the same sparsity
Show the answer
A. Making the features sparser, so that they are rarely active together
Interference between features that share dimensions costs only when they are active together, which sparse features rarely are, while dropping a feature costs every time it is active. In the widget, dense features kept two at right angles; at 90% sparsity five shared two dimensions.
Restoring the clean output of one attention head while running the corrupted input recovers 90% of the clean logit difference. What does this show?
- The head is necessary: removing it would destroy the behavior
- The other heads play no role in the behavior
- Restoring this head's clean activation is nearly sufficient to bring back the behavior on these inputs
- The head computes the whole behavior by itself
Show the answer
C. Restoring this head's clean activation is nearly sufficient to bring back the behavior on these inputs
Restoring clean activations into a corrupted run (denoising) tests sufficiency of the restored information given the rest of the corrupted computation. Necessity is a different experiment, and other components can be needed too: the head's output may only matter because later components read it.
Go deeper
- Probing & the Linear Representation Hypothesis · Linear probes, control tasks, steering vectors and the geometry of concepts.
- Causal Interventions: Activation Patching · Locating behavior with patching, causal tracing and circuit discovery.
- Dictionary Learning at Scale · Superposition, sparse autoencoder variants and transcoders, and how to evaluate the features they find.
Further reading
- M. Sundararajan, A. Taly & Q. Yan, "Axiomatic attribution for deep networks," ICML (2017).
- Y. Belinkov, "Probing classifiers: promises, shortcomings, and advances," Computational Linguistics 48(1), 207–219 (2022).
- C. Olah, N. Cammarata, L. Schubert, G. Goh, M. Petrov & S. Carter, "Zoom in: an introduction to circuits," Distill (2020).
- N. Elhage et al., "Toy models of superposition," Transformer Circuits Thread (2022).