Simple Algorithm
Deep Learning · Representation · 24 min

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.
LevelQuestionTypical methodsWhat an answer looks like
AttributionWhich parts of this input drove this output?gradients, integrated gradients, occlusion, Grad-CAMa score per pixel, token or input feature: a heat map
RepresentationWhat information does a layer carry, and in what format?probes, feature visualization, sparse dictionariesdirections in activation space with a meaning
MechanismHow is the output computed from the input?circuits, activation patching, causal abstractiona subgraph of components and the algorithm it implements
The levels build on each other. Mechanistic interpretability aims at the bottom row: taking a trained network apart into the features it computes and the circuits that wire them together.
Check your understanding

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?

  1. Trust A: expert agreement shows that it is the faithful one
  2. Trust B: an unexpected explanation is more likely to be true
  3. Average the two maps, since each captures part of the truth
  4. 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 f(x)f(\mathbf x) 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 ff responds to a small change of each input, which is what a first-order Taylor expansion says:

f(x+δ)≈f(x)+∇f(x)⊤δ=f(x)+∑i∂f∂xi δif(\mathbf x+\boldsymbol\delta)\approx f(\mathbf x)+\nabla f(\mathbf x)^\top\boldsymbol\delta=f(\mathbf x)+\sum_i\frac{\partial f}{\partial x_i}\,\delta_i
A saliency map displays ∣∂f/∂xi∣\abs{\partial f/\partial x_i} for every pixel (Simonyan, Vedaldi & Zisserman, 2014), at the cost of one backward pass. Gradient times input, xi ∂f/∂xix_i\,\partial f/\partial x_i, is exactly the contribution wixiw_ix_i of each input when f(x)=w⊤x+bf(\mathbf x)=\mathbf w^\top\mathbf x+b is linear.

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 x′\mathbf x', chosen to carry no signal (a black image, an all-zero embedding), to the input x\mathbf x.

DerivationIntegrated gradients
  1. IG⁡i(x)=(xi−xi′)∫01∂f∂xi(x′+α(x−x′)) dα\operatorname{IG}_i(\mathbf x)=(x_i-x_i')\int_0^1\frac{\partial f}{\partial x_i}\Big(\mathbf x'+\alpha(\mathbf x-\mathbf x')\Big)\,d\alpha

    Average each partial derivative along the path x′+α(x−x′)\mathbf x'+\alpha(\mathbf x-\mathbf x'), α∈[0,1]\alpha\in[0,1], and multiply by the displacement:

  2. ∑iIG⁡i(x)=f(x)−f(x′)\sum_i\operatorname{IG}_i(\mathbf x)=f(\mathbf x)-f(\mathbf x')

    Completeness. By the chain rule, ddαf\frac{d}{d\alpha}f along the path is ∑i(xi−xi′) ∂if\sum_i(x_i-x_i')\,\partial_if; integrating from 00 to 11 gives f(x)−f(x′)f(\mathbf x)-f(\mathbf x'). 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):

  3. f(x)=w⊤x+b⟹IG⁡i=wi (xi−xi′)f(\mathbf x)=\mathbf w^\top\mathbf x+b\quad\Longrightarrow\quad\operatorname{IG}_i=w_i\,(x_i-x_i')

    For a linear ff the gradient is the constant w\mathbf w, so integrated gradients reduce to gradient times input measured from the reference. They differ only where ff bends. An input equal to its reference value always gets zero, whatever its role: a black reference can never credit black pixels.

  4. ∂f∂x1(αx)={1α<0.20α>0.2∂f∂x2(αx)={2α<0.20α>0.2\frac{\partial f}{\partial x_1}\Big(\alpha\mathbf x\Big)=\begin{cases}1&\alpha<0.2\\0&\alpha>0.2\end{cases}\qquad\frac{\partial f}{\partial x_2}\Big(\alpha\mathbf x\Big)=\begin{cases}2&\alpha<0.2\\0&\alpha>0.2\end{cases}

    A saturated unit. Let f(x)=min⁡(1, x1+2x2)f(\mathbf x)=\min(1,\,x_1+2x_2), a ReLU unit capped at 11 (it equals 1−ReLU⁡(1−x1−2x2)1-\operatorname{ReLU}(1-x_1-2x_2)). At x=(3,1)\mathbf x=(3,1) with reference 0\mathbf 0, the output is 11 against f(0)=0f(\mathbf 0)=0, yet the gradient at x\mathbf x is (0,0)(0,0): gradient saliency credits nothing. Along the path αx\alpha\mathbf x the unit's input is 3α+2α=5α3\alpha+2\alpha=5\alpha, which reaches the cap at α=0.2\alpha=0.2.

Predict before you look

For f(x)=min⁡(1, x1+2x2)f(\mathbf x)=\min(1,\,x_1+2x_2) at x=(3,1)\mathbf x=(3,1) with reference 0\mathbf 0, what is IG⁡1\operatorname{IG}_1, the attribution to the first input?

Show the answer

0.6

Only the unsaturated part of the path counts: IG⁡1=3∫00.21 dα=0.6\operatorname{IG}_1=3\int_0^{0.2}1\,d\alpha=0.6 and IG⁡2=1∫00.22 dα=0.4\operatorname{IG}_2=1\int_0^{0.2}2\,d\alpha=0.4. They add up to 1=f(x)−f(0)1=f(\mathbf x)-f(\mathbf 0), as completeness requires, and split the credit in proportion to the contributions 33 and 22 that drove the unit to its cap. The gradient at x\mathbf x gave both inputs zero.

python
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, gap

One batched backward pass over the path. With 64 midpoints this returns 0.6090.609 and 0.4060.406 on the saturated unit above, against the exact 0.60.6 and 0.40.4. 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 h(ℓ)(x)\mathbf h^{(\ell)}(\mathbf x) of layer ℓ\ell on a labeled dataset, and train a small classifier gg, a probe, to predict a property yy 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 h(ℓ)\mathbf h^{(\ell)}, and its accuracy measures how much of yy is linearly decodable at layer ℓ\ell. 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.

TrapWhy it misleadsRemedy
The probe does the workA 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 identitycompare with a control task of random labels and report the gap, the probe's selectivity (Hewitt & Liang, 2019)
Decodable is not usedA property can be readable from a layer that the network's later layers ignoreremove the property from the representation and test whether the network's behavior changes
A probe answers "is yy decodable from layer ℓ\ell?", never "does the network compute or use yy?" The second question needs an intervention.
Check your understanding

A linear probe predicts part-of-speech tags from layer 3 of a language model with 97% accuracy. Which conclusion is justified?

  1. The model uses part of speech in layer 3 to predict the next word
  2. Layer 3 holds part-of-speech information in a linearly decodable form; only a causal test can show whether the model uses it
  3. Layer 3 is where the model computes part of speech
  4. 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 nn sparse features must pass through m<nm<n hidden dimensions and be read back out:

h=Wx∈Rm,x^=ReLU⁡(W⊤h+b),L=E∑i=1nIi (xi−x^i)2\mathbf h=W\mathbf x\in\R^m,\qquad\hat{\mathbf x}=\operatorname{ReLU}\big(W^\top\mathbf h+\mathbf b\big),\qquad\loss=\E\sum_{i=1}^nI_i\,(x_i-\hat x_i)^2
A feature is absent (xi=0x_i=0) a fraction SS of the time (SS is the sparsity) and otherwise drawn uniformly from [0,1][0,1]; feature ii counts in the loss with importance Ii=r i−1I_i=r^{\,i-1}. Column WiW_i is feature ii's direction, and the dot product Wi⋅WjW_i\cdot W_j is the interference between two features.

The nonlinearity is essential. In a linear model, x^=W⊤Wx+b\hat{\mathbf x}=W^\top W\mathbf x+\mathbf b, 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, x≈bd+∑jfjdj\mathbf x\approx\mathbf b_d+\sum_jf_j\mathbf d_j with most coefficients fj=0f_j=0. Recovering the directions dj\mathbf d_j from examples of x\mathbf x is dictionary learning, a classic problem of signal processing. A sparse autoencoder (SAE) fits an overcomplete dictionary, with F≫dF\gg d atoms, and computes each input's sparse code with a single encoder layer:

f(x)=ReLU⁡(We(x−bd)+be)∈RF,x^=Wd f(x)+bd,L=∥x−x^∥22+λ∥f(x)∥1\mathbf f(\mathbf x)=\operatorname{ReLU}\big(W_e(\mathbf x-\mathbf b_d)+\mathbf b_e\big)\in\R^F,\qquad\hat{\mathbf x}=W_d\,\mathbf f(\mathbf x)+\mathbf b_d,\qquad\loss=\norm{\mathbf x-\hat{\mathbf x}}_2^2+\lambda\norm{\mathbf f(\mathbf x)}_1
The columns of WdW_d are the candidate feature directions. Each is rescaled to length 1 after every step; otherwise the optimizer could make the L1 term as small as it likes by scaling the code down and the atoms up by the same factor, leaving the reconstruction unchanged. Even so, the penalty has a price: it pulls every active coefficient toward zero.
python
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 x\mathbf x that produces the behavior and on a corrupted input x~\tilde{\mathbf x} that differs in one key respect, then reruns x~\tilde{\mathbf x} with one component's activation restored to its value on x\mathbf x. With a metric mm, typically the logit difference between the correct and an incorrect answer, the restored fraction is

mpatched−mcorruptmclean−mcorrupt\frac{m_{\text{patched}}-m_{\text{corrupt}}}{m_{\text{clean}}-m_{\text{corrupt}}}

which is 11 if the component alone brings back the clean behavior and 00 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 f(x)−f(x′)f(\mathbf x)-f(\mathbf x'); 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.

Question 1

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?

  1. Both report large attributions for the pixels that matter most
  2. Gradients give near-zero attributions; integrated gradients still distribute the full difference f(x)−f(x′)f(\mathbf x)-f(\mathbf x') among the pixels
  3. Integrated gradients give zero too, because they also use gradients
  4. Both are undefined at a saturated point
Show the answer

B. Gradients give near-zero attributions; integrated gradients still distribute the full difference f(x)−f(x′)f(\mathbf x)-f(\mathbf x') among the pixels

The gradient is evaluated only at x\mathbf x, 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 f(x)−f(x′)f(\mathbf x)-f(\mathbf x').

Question 2

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?

  1. The layer encodes part of speech very strongly
  2. The probe is broken, since no probe should learn random tags
  3. 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
  4. 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.

Question 3

In the toy model of superposition, which change makes a network store more features than it has hidden dimensions?

  1. Making the features sparser, so that they are rarely active together
  2. Removing the ReLU, so that the model is linear
  3. Making all features dense and equally important
  4. 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.

Question 4

Restoring the clean output of one attention head while running the corrupted input recovers 90% of the clean logit difference. What does this show?

  1. The head is necessary: removing it would destroy the behavior
  2. The other heads play no role in the behavior
  3. Restoring this head's clean activation is nearly sufficient to bring back the behavior on these inputs
  4. 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

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