Deep Learning Interpretability
Accuracy summarizes predictions on an evaluation set. To investigate a suspected shortcut, we need more specific evidence: how the score responds to an input change, which properties can be decoded from a representation, or what happens when an internal computation is altered. These questions motivate different interpretability methods. A plausible visualization can guide an investigation without establishing its conclusion.
This article focuses on neural-network attribution, probing, sparse dictionaries, and activation interventions. The companion Explainable Machine Learning article distinguishes local Shapley attributions, response curves, and global performance importance. No method is uniformly strongest: usefulness depends on the question, model, data, and controls.
Input gradients: sensitivity at one point
For a selected scalar class score \(s_c(x)\), the gradient \(\partial s_c/\partial x\) describes first-order changes for small input perturbations. Use a clearly defined score, such as a pre-softmax logit; a probability can add saturation from the output transformation. Absolute gradients discard direction, and the maximum over image channels below is a visualization convention, not an additive allocation of the score.
The code deliberately accepts one floating-point image with shape (1, channels, height, width) and a model returning class scores. It restores training flags after temporary evaluation mode and computes input gradients without overwriting parameter gradients. Inputs and model must use compatible devices and dtypes. Run these small examples in order with PyTorch and NumPy; they test calculations on constructed functions, not explanations from a trained vision model.
import torch
from torch import nn
from torch.nn import functional as F
from contextlib import contextmanager
@contextmanager
def evaluation(model):
modes = [(module, module.training) for module in model.modules()]
model.eval()
try:
yield
finally:
for module, training in modes:
module.training = training
def check_image(x):
if x.ndim != 4 or x.shape[0] != 1 or not x.is_floating_point():
raise ValueError("Expected one floating-point image, shape (1, C, H, W)")
def saliency(model, x, class_idx):
check_image(x)
with evaluation(model), torch.enable_grad():
image = x.detach().clone().requires_grad_(True)
score = model(image)[0, class_idx]
grad, = torch.autograd.grad(score, image)
return grad.abs().amax(dim=1).detach()
class SaturatedScore(nn.Module):
def forward(self, x):
return torch.sigmoid(8*x.flatten(1).sum(dim=1, keepdim=True))
saturated = SaturatedScore()
image = torch.ones(1, 1, 1, 1, dtype=torch.float64)
print("local sensitivity", round(saliency(saturated, image, 0).item(), 6))
# local sensitivity 0.002682
The sigmoid example outputs nearly one at x=1 but has a small derivative there. A small local derivative can coexist with a substantial output difference from another input. It does not prove that a feature was irrelevant, nor identify a real-world cause.
Integrated Gradients compares an input with a baseline
Integrated Gradients multiplies each input-minus-baseline coordinate by the integral of its gradient along the straight path between them. Under the relevant differentiability and integration conditions, summing the exact attributions gives \(s_c(x)-s_c(x_0)\). The implementation uses midpoint quadrature and reports the numerical residual of this identity; finite steps do not guarantee exact completeness.
def integrated_gradients(model, x, class_idx, baseline=None, steps=128, chunk_size=32):
check_image(x)
if steps < 1 or chunk_size < 1:
raise ValueError("steps and chunk_size must be positive integers")
start = torch.zeros_like(x) if baseline is None else baseline.detach().to(x)
if start.shape != x.shape:
raise ValueError("Baseline shape must match the input")
delta = x.detach()-start
total = torch.zeros_like(x)
with evaluation(model), torch.enable_grad():
for first in range(0, steps, chunk_size):
alpha = (torch.arange(first, min(first+chunk_size, steps),
device=x.device, dtype=x.dtype)+0.5)/steps
path = (start+alpha[:, None, None, None]*delta).detach().requires_grad_(True)
score = model(path)[:, class_idx].sum()
gradients, = torch.autograd.grad(score, path)
total += gradients.detach().sum(dim=0, keepdim=True)
with torch.no_grad():
difference = model(x)[0, class_idx]-model(start)[0, class_idx]
attribution = delta*total/steps
residual = attribution.sum()-difference
return attribution.detach(), residual.detach()
for steps in (8, 128):
attribution, residual = integrated_gradients(saturated, image, 0, steps=steps)
print("steps", steps, "sum", round(attribution.sum().item(), 6),
"completeness residual", f"{residual.item():.3e}")
# steps 8 sum 0.499678 completeness residual 1.346e-05
# steps 128 sum 0.499665 completeness residual 5.452e-08
The local derivative is only 0.002682, while the integrated attribution is about 0.499665. The residual is printed in scientific notation so a small nonzero integration error is not displayed as exactly zero. The example compares the saturated score at one with its value at zero. Integrating along the path can recover a substantial difference even when the endpoint gradient is small. Baseline zero is a chosen reference, not a universal absence of information. In a normalized image, zero may even represent the channel mean rather than black. Alternative baselines and paths can change the attribution and may traverse unrealistic inputs.
Path points are batched for efficiency, assuming the model processes each example independently in evaluation mode. Models that couple examples across the batch need a different evaluation scheme. The code preserves input device and dtype and limits path-batch size. Autograd must remain available; inference-mode tensors and nondifferentiable preprocessing require separate handling. A small completeness residual checks integration consistency, not semantic or causal validity.
Grad-CAM summarizes a convolutional feature map
For a chosen layer, \(A^k\) is channel \(k\)’s activation map. Grad-CAM averages the score gradient over its \(H\times W\) locations to obtain \(\alpha_k^c\), then computes \(\operatorname{ReLU}(\sum_k\alpha_k^c A^k)\). The last convolutional layer is a common choice, but not a requirement. The positive part is intended to highlight positive class-supporting contributions under this construction; it is not a measured causal contribution of each region.
def grad_cam(model, layer, x, class_idx):
check_image(x)
activations = []
handle = layer.register_forward_hook(lambda module, args, output: activations.append(output))
try:
with evaluation(model), torch.enable_grad():
image = x.detach().clone().requires_grad_(True)
score = model(image)[0, class_idx]
if len(activations) != 1 or activations[0].ndim != 4:
raise ValueError("Layer must run once and return a 4-D feature map")
acts = activations[0]
gradients, = torch.autograd.grad(score, acts)
weights = gradients.mean(dim=(2, 3), keepdim=True)
raw = F.relu((weights*acts).sum(dim=1, keepdim=True))
raw = F.interpolate(raw, size=x.shape[-2:], mode="bilinear", align_corners=False)
spread = raw.max()-raw.min()
normalized = (raw-raw.min())/spread if spread.item() > 0 else torch.zeros_like(raw)
return raw.detach(), normalized.detach()
finally:
handle.remove()
class TinyCNN(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Conv2d(1, 2, 1, bias=False)
with torch.no_grad():
self.conv.weight.copy_(torch.tensor([1., -1.]).reshape(2, 1, 1, 1))
def forward(self, x):
maps = self.conv(x).mean(dim=(2, 3))
score = maps[:, 0]-maps[:, 1]
return torch.stack([score, -score], dim=1)
tiny = TinyCNN()
x_cam = torch.arange(1., 5.).reshape(1, 1, 2, 2)
raw, normalized = grad_cam(tiny, tiny.conv, x_cam, 0)
print("raw map", raw.flatten().tolist())
print("normalized range", normalized.min().item(), normalized.max().item())
print("hooks remaining", len(tiny.conv._forward_hooks))
# raw map [0.5, 1.0, 1.5, 2.0]
# normalized range 0.0 1.0
# hooks remaining 0
The helper uses one temporary forward hook and obtains activation gradients directly, removing the hook even on an error. It leaves existing parameter gradients alone. It assumes the chosen layer is called once, returns a four-dimensional tensor, and its output is not modified in place downstream. The toy CNN uses no in-place operations. For other architectures, select a compatible layer and inspect its actual output.
The raw map retains scale; the normalized map is only for display. A constant map becomes zeros under this normalization, so inspect the raw map before interpreting a blank image as no response. Upsampling does not create spatial detail: a seven-by-seven activation map remains coarse after resizing. ReLU discards negative contributions, and gradient averaging can omit important structure.
Randomization checks test dependence on learned parameters
Adebayo and colleagues compared saliency maps before and after parameter randomization and after training with randomized labels. In their reported experiments, Gradients and Grad-CAM passed the studied checks while Guided Backpropagation and Guided Grad-CAM failed. These findings concern particular methods, models, comparisons, and tasks. They do not justify treating Integrated Gradients or Gradient×Input as universally passing, or every visually similar map as merely an edge detector.
Choose a layer order that follows the architecture and inspect maps after each cumulative reset. Reversing the registration order of named modules does not generally reverse the computation graph. The helper works on a copy and takes an explicit order. Each yielded model is the same working copy at its current stage; compute the diagnostic before advancing the generator.
from copy import deepcopy
def randomize_layers(model, layer_names):
working = deepcopy(model)
modules = dict(working.named_modules())
for name in layer_names:
module = modules[name]
if not callable(getattr(module, "reset_parameters", None)):
raise ValueError(f"{name} has no reset_parameters")
with torch.no_grad():
module.reset_parameters()
yield name, working
torch.manual_seed(7)
before = tiny.conv.weight.detach().clone()
for name, randomized in randomize_layers(tiny, ["conv"]):
changed = saliency(randomized, x_cam, 0)
print("randomized", name, "finite saliency", bool(torch.isfinite(changed).all()))
print("original unchanged", torch.equal(before, tiny.conv.weight))
# randomized conv finite saliency True
# original unchanged True
The toy check confirms that saliency can be recomputed after a reset and that the original model remains unchanged. It does not reproduce a trained-model randomization study. On a real model, specify the target score, normalization, similarity metric, and randomization seeds. A label-randomization control also requires actual retraining and an adequate fit to the control task. Dependence on trained weights is relevant evidence for some explanation goals; passing does not establish fidelity or a mechanism, and exact invariance can be legitimate when the altered component has no effect on the selected score.
Probes test what is decodable
A probe trains a classifier on frozen representations to predict a property. A linear probe tests linear accessibility under its data and training setup. A nonlinear probe can test a different notion of accessibility, but its capacity and ability to memorize need controls. Neither can recover information absent from the representation on genuinely independent test cases simply by becoming larger.
def probe(features, labels, test_features, test_labels, epochs=200):
train = features.detach()
test = test_features.detach().to(train)
labels = labels.detach().to(device=train.device, dtype=torch.long)
test_labels = test_labels.detach().to(device=train.device, dtype=torch.long)
classes = int(labels.max().item())+1
if not torch.equal(torch.unique(labels), torch.arange(classes, device=train.device)):
raise ValueError("Training classes must be contiguous integers starting at zero")
clf = nn.Linear(train.shape[1], classes).to(device=train.device, dtype=train.dtype)
opt = torch.optim.Adam(clf.parameters(), lr=1e-2, weight_decay=1e-4)
for _ in range(epochs):
opt.zero_grad()
F.cross_entropy(clf(train), labels).backward()
opt.step()
with torch.no_grad():
return (clf(test).argmax(1)==test_labels).float().mean().item()
torch.manual_seed(12)
features = torch.randn(300, 8, requires_grad=True)
labels = (features.detach()[:, 0]+0.25*features.detach()[:, 1] > 0).long()
accuracy = probe(features[:200], labels[:200], features[200:], labels[200:])
print("synthetic test accuracy", round(accuracy, 4))
print("source features have gradients", features.grad is not None)
# synthetic test accuracy 0.96
# source features have gradients False
The code detaches source features and labels, fits only the probe, and evaluates on separate inputs. Its synthetic label is deliberately linearly predictable. Real probing needs splits that prevent repeated entities or word types from making memorization look like generalization, plus training-data-only preprocessing. Select probe capacity and training settings on validation data before reporting test performance.
Compare task performance with matched control tasks and random-representation baselines. High accuracy on an untrained representation still shows decodability there; it weakens a claim that training created that access. In Hewitt and Liang’s setup, selectivity is task accuracy minus control-task accuracy, not their ratio. Controls address particular confounds and do not establish that downstream model computation uses the decoded property. Ablations and patching provide complementary evidence under their own intervention assumptions.
Superposition and sparse dictionaries
Some trained networks and toy models represent features through overlapping directions, a phenomenon called superposition. A coordinate can then respond to several patterns. This does not make individual-neuron analysis universally useless or prove that every neuron is polysemantic.
A sparse autoencoder reconstructs internal activations through an overcomplete set of latent directions. “Overcomplete” means there are more dictionary vectors than input dimensions; they cannot form a linearly independent basis. Sparsity encourages each example to use relatively few latents. Unlike ordinary dimensional compression, the constraint here is usage of the larger dictionary. The reconstruction background is covered in Autoencoders and Representation Learning.
class SparseAutoencoder(nn.Module):
def __init__(self, d_model, expansion=8):
super().__init__()
hidden = d_model*expansion
self.center = nn.Parameter(torch.zeros(d_model))
self.enc = nn.Linear(d_model, hidden)
self.decoder_raw = nn.Parameter(torch.randn(d_model, hidden))
def directions(self):
return F.normalize(self.decoder_raw, dim=0)
def forward(self, x):
features = F.relu(self.enc(x-self.center))
reconstruction = features @ self.directions().T+self.center
return reconstruction, features
def sae_loss(x, reconstruction, features, l1=1e-3):
return F.mse_loss(reconstruction, x)+l1*features.abs().sum(dim=-1).mean()
torch.manual_seed(4)
sae = SparseAutoencoder(8, expansion=4)
activations = torch.randn(32, 8)
optimizer = torch.optim.Adam(sae.parameters(), lr=1e-3)
for _ in range(20):
optimizer.zero_grad()
reconstruction, sparse_features = sae(activations)
loss = sae_loss(activations, reconstruction, sparse_features)
loss.backward()
optimizer.step()
print("reconstruction shape", tuple(reconstruction.shape), "latent shape", tuple(sparse_features.shape))
print("unit decoder columns", bool(torch.allclose(sae.directions().norm(dim=0), torch.ones(32))))
print("finite training loss", bool(torch.isfinite(loss)))
# reconstruction shape (32, 8) latent shape (32, 32)
# unit decoder columns True
# finite training loss True
The learned center is subtracted before encoding and added during reconstruction. Decoder columns are normalized in the forward pass. Without a scale constraint, shrinking encoder outputs while enlarging decoder weights can preserve reconstruction and reduce the L1 penalty, undermining the intended sparsity trade-off. This normalized parameterization removes that scaling escape for nonzero decoder directions; numerical normalization near zero still deserves monitoring.
The loss averages squared reconstruction error over all entries and sums latent activation magnitudes per example before averaging the batch. Thus the meaning of the L1 coefficient depends on these reductions and activation scale. Twenty updates only check that the training computation works. Interpretable concepts are not guaranteed: dead latents, feature splitting, reconstruction error, and sensitivity to dictionary size need evaluation. Inspect high-activation examples and the effects of interventions, not just a label attached to a latent.
Activation patching tests a proposed computation
A circuit is a proposed set of components and connections that implements a behavior. In small attention models, previous-token and induction-head mechanisms have been studied for patterns such as [A][B] … [A] → [B]. An induction head is an attention head participating in such a mechanism, not by definition a pair of heads. This pattern is evidence for a particular computation, not a complete account of in-context learning.
Activation patching compares a clean run with a deliberately altered run, replaces a selected internal activation, and measures a predeclared behavioral score. The example below is small enough to know the mechanism: output = 2h₀+h₁. Changing h₀ from one to zero reduces the score by two; copying it back restores those two units.
class ToyCircuit(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Identity()
def forward(self, x):
h = self.hidden(x)
return 2*h[:, 0]+h[:, 1]
toy = ToyCircuit()
clean = torch.tensor([[1., 3.]])
corrupt = torch.tensor([[0., 3.]])
saved = []
handle = toy.hidden.register_forward_hook(lambda module, args, output: saved.append(output.detach().clone()))
try:
clean_score = toy(clean).item()
finally:
handle.remove()
corrupt_score = toy(corrupt).item()
def replace_first(module, args, output):
patched = output.clone()
patched[:, 0] = saved[0][:, 0]
return patched
handle = toy.hidden.register_forward_hook(replace_first)
try:
restored = toy(corrupt).item()
finally:
handle.remove()
print("clean", clean_score, "corrupt", corrupt_score, "patched", restored)
print("restored difference", restored-corrupt_score)
# clean 5.0 corrupt 3.0 patched 5.0
# restored difference 2.0
This is a causal intervention on the specified model computation under this input pair. It does not establish a causal effect in the external world, that the patched component is uniquely necessary, or that the same explanation holds for every input. Corruption choice, activation alignment, off-distribution internal states, and redundant routes can affect the result. Compare control patches and ablations across relevant examples before drawing a broader mechanism claim.
Use explanations to formulate and test concrete hypotheses. If background dependence is suspected, compare appropriately matched background changes and measure prediction behavior; simply removing the background may itself create a distribution shift. Combine attribution, error analysis, and intervention evidence as the question requires. No fixed accuracy sacrifice or universal ranking of explanation methods follows from these examples.
References
- Adebayo et al., Sanity Checks for Saliency Maps.
- Hewitt and Liang, Designing and Interpreting Probes with Control Tasks.
- Bricken et al. (2023). Towards Monosemanticity: Decomposing Language Models With Dictionary Learning.
- Elhage et al. (2021). A Mathematical Framework for Transformer Circuits.
- Sundararajan, Taly, and Yan (2017). Axiomatic Attribution for Deep Networks.
- Selvaraju et al. (2017). Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
