Saliency and attribution methods for neural networks
Explore attribution methods for differentiable networks: gradients and gradient times input, saturation, Integrated Gradients and its completeness proof and baseline choice, followed by SmoothGrad, DeepLIFT, LRP, Grad-CAM and the attention-as-explanation debate.
After this lesson you can
- State the sensitivity, implementation invariance and completeness axioms and check which methods satisfy them.
- Prove completeness of Integrated Gradients and control its discretization error.
- Implement gradient, gradient times input, IG, SmoothGrad and Grad-CAM using your own PyTorch hooks.
- Analyze how the baseline affects attribution.
- Argue with evidence when attention weights are not a valid explanation.
Before you start
Sensitivity is not a causal story
A network assigns a score to an image or sentence. You want to know which parts of the input changed that score. Backpropagation can compute thousands of derivatives in one pass, but a local derivative asks what would happen under an infinitesimal change; it does not necessarily describe the path from a reference input to the current one. A heat map does not itself prove that the model reasons like a human.
The gradient saliency of scalar output is . If is differentiable, for small perturbations. Gradient times input uses ; it can be negative and depends on coordinate scale and origin. Choosing a class probability, its logit or a loss produces different maps. Simonyan et al. use score gradients to visualize sensitivity in convolutional networks.
In RGB, each pixel has three derivatives. Summing channels preserves a signed contribution, while summing magnitudes answers a different question and can hide cancellations. Displaying absolute values highlights sensitivity without distinguishing whether a small increase in that coordinate raises or lowers the score. In text, a word can occupy several subtokens and embeddings have many coordinates: deciding how to aggregate them and which special tokens to include is part of the protocol, not merely a visual choice.
For and zero baseline, is saturated: the gradient there is . The straight path reaches halfway through; before that both derivatives are 1 and afterward 0. Integrated attributions are and sum to one. The derivative does not exist at the boundary; an isolated crossing does not affect the integral. If the entire path stays on that boundary, the transverse derivative and allocation are not unique, as the figure indicates.
Axioms and baselines
The attribution axioms of Sundararajan et al. include sensitivity and implementation invariance. One form of sensitivity requires that, if input and baseline differ in only one coordinate and their outputs differ, that coordinate receives nonzero attribution. Implementation invariance requires equal attributions for networks computing the same function regardless of their internal graph. Completeness requires . Linearity requires attribution of to be with the same baseline.
The gradient at the input can violate sensitivity through saturation. Gradient times input is not generally complete either: for , , which is not . An algorithm using only the function and its derivatives respects invariance where those derivatives are well defined, but special backpropagation rules can depend on the implementation. The axioms do not choose an appropriate baseline or guarantee causality.
Integrated Gradients (IG) for baseline and input are
The displacement factor is essential: if a coordinate does not change from the baseline, its attribution is zero. For a function differentiable in a neighborhood of the segment, the line integral satisfies
The first equality sums finitely many integrals; the second applies the chain rule and the fundamental theorem of calculus. It also holds under appropriate assumptions of absolute continuity and differentiability almost everywhere on the path, for example at an isolated crossing of a ReLU edge. Completeness is an identity for the chosen score difference; it does not prove the components are causal. For , zero baseline and , both attributions equal one: the interaction is distributed along the path.
The integral is approximated by Riemann sums or trapezoids. The residual is a necessary check of global numerical accuracy, but a small residual can hide offsetting coordinate errors. Increasing steps does not guarantee monotonic reduction when the path crosses kinks, as you will see.
A useful check compares two discretizations and retains both the residual and coordinate-wise difference. If and are very close, a relative error divided by that difference can be unstable; report the absolute residual too. A straight path between two plausible images can pass through implausible images. The integral remains well defined for the mathematical function, but its interpretation depends on what the model does at those intermediate points.
The network in this figure was fitted with 32 hidden units and ReLU activation; it achieved 0.9244 accuracy on its test split. The digit shown is the first correctly classified test case, class 5. The explained output is its logit. The black baseline is zero, the white one is one, the blurred baseline applies a Gaussian filter, the noise baseline is a fixed uniform sample and the mean is the training mean. A black input coordinate has zero IG attribution with a black baseline because its displacement is zero; this does not prove the background is irrelevant to the network. Noise or mean baselines can be artificial images. Download the map generator to repeat training and calculations.
Averaging IG over several baselines answers a question about a difference from a reference distribution; each baseline preserves completeness and the average sums to , under integrability. Straight-path averaging is related to the continuous Aumann-Shapley allocation, but is not automatically equivalent to discrete Shapley values for coalitions: the games and paths may differ.
The baseline must answer the question. Black may mean absence of light in an image, but not necessarily absence of the object; the training mean may not correspond to any possible observation. For text, a zero embedding or mask token does not automatically equal deleting a word without changing grammar. Comparing several baselines helps reveal dependence on the assumption, but does not itself choose the appropriate one. A negative attribution indicates a negative contribution to the difference from that baseline, not necessarily a negative property of the object.
Noise and backpropagation rules
SmoothGrad averages gradients with (Smilkov et al.). For fixed , more samples reduce Monte Carlo error under finite variance. Under regularity permitting interchange of derivative and expectation, the limit is the gradient of , a smoothed function. Increasing changes that function, rather than just reducing noise.
The color scale is fixed across maps and the sign is preserved. With only four repetitions variance is a noisy estimate; it need not decrease monotonically in every sample. Wide noise can move pixels outside in this example, changing the domain queried. Clipping them would define another estimator and would have to be documented.
DeepLIFT compares activations with a reference and propagates differences using contribution rules, rather than evaluating only the gradient at the input (Shrikumar et al.). LRP distributes relevance to earlier layers using chosen rules, which can include stabilizers to avoid division near zero. Its conservation and results depend on the rule and treatment of biases; one should not claim that all variants are invariant under equivalent implementations. None of these methods removes the need to check sensitivity to the reference or model.
From channels to regions: Grad-CAM
For convolutional activations and score , Grad-CAM averages spatial gradients to obtain and displays
ReLU retains the positive part of the map for that class; it hides negative evidence and is not a complete decomposition of the score. Deep layers tend to have lower spatial resolution and wider receptive fields; earlier layers retain spatial detail but their semantic relationship to a class may be less direct. Interpolating a small map to image size does not create measured detail. In an architecture with global spatial averaging followed by a linear head, CAM directly uses class weights; Grad-CAM uses gradients and applies to a wider range of architectures (Selvaraju et al.).
The local Grad-CAM and IG laboratory implements its own hooks and compares each map with Captum’s LayerGradCam. It uses the ResNet-18 checkpoint produced by lesson 30.6; it does not assume a different pretrained model. Run that laboratory first, then from the directory where you saved the script:
python cifar_generate.py --checkpoint ood_runs/resnet18-11-oe0.pt --data ood_data --json gradcam-data.json --image cifar.png
The script checks the sum of its own IG and Captum’s against the logit difference, prints the maximum difference and logs the checkpoint hash. Its IG baseline is black on the RGB scale . CIFAR-10 is downloaded if it is not already at the specified path. Grad-CAM maps are individually normalized for display; this allows comparison of location but not absolute magnitude across classes or layers.
In the run with test image zero, the label and prediction were both “cat”. The maximum difference between the custom Grad-CAM and Captum was before normalization. With 256 trapezoidal intervals, completeness residuals for custom IG and Captum were 0.017 and −0.026, and maximum coordinate difference was 0.0094. These are numerical approximations with different conventions: agreement in Grad-CAM and a small residual do not prove causal fidelity. The checkpoint has accuracy 0.9066 on the 10,000 official test images according to the evaluation in lesson 30.6.
Attention is a matrix, not a verdict
In multi-head attention, weights describe how value vectors are mixed in an operation. The output also depends on values, projections, residual connections, later layers and the objective. In the models studied by Jain and Wallace, very different attention distributions could produce equivalent predictions; this questions reading weights directly as importance. Wiegreffe and Pinter discuss that conclusion and propose tests with baselines, seeds and end-to-end diagnostics. These studies do not settle the question for every architecture and task.
The attention-as-explanation debate requires defining which property to test. Attention rollout combines attention matrices across layers, usually adding and normalizing identity to represent a residual connection. It approximates weight flow, does not itself include values or gradients and does not demonstrate a causal intervention. Comparing it with IG on embeddings can reveal agreement or disagreement in a case, but neither is ground truth. The following interventions, controls and fidelity tests are necessary to evaluate a specific hypothesis.
The text laboratory computes IG on word embeddings of the same DistilBERT SST-2 from the previous lesson and compares its trapezoidal approximation with Captum. It keeps special-token embeddings in the baseline and zeros content embeddings; the attention mask remains fixed. It averages heads, adds identity, normalizes each row and composes matrices to obtain rollout from the initial token. Spearman’s coefficient compares IG magnitude summed per token with those weights only on content tokens. A zero or undefined value can result from ties or the sample, and a single sentence does not establish a general law. Run python transformer_compare.py --output resultados.json; the script pins the model revision and requires PyTorch, Transformers, SciPy and Captum.
In one run on the sentence “a surprisingly engaging movie with a weak ending”, the model predicted positive and Spearman correlation between the rankings was 0.405 over eight content tokens. The logit difference between input and baseline was 3.546; the completeness residual was −0.023 for custom integration and −0.078 for Captum with its trapezoidal rule. The largest absolute attribution-coordinate difference was 0.0040. These are numerical approximations with different integration conventions, not a fidelity certificate or a population-level comparison.
NumPy laboratory: derivatives and integration
We build a small network with explicit weights and calculate its analytic derivative. The trapezoidal rule evaluates points and weights the endpoints by one half. It prints the residual and attributions; it does not assume that a few steps suffice.
import numpy as np
W=np.array([[1.,-.5],[.8,1.2],[-1.,.6]])
b=np.array([-.2,.1,.3]); out=np.array([1.,-.7,.4]); bias=.2
def F(x): return float(np.maximum(W@x+b,0)@out+bias)
def gradient(x): return W.T@(out*((W@x+b)>0))
x=np.array([1.,1.]); baseline=np.zeros(2)
print('F(x), F(base):',round(F(x),6),round(F(baseline),6))
print('gradiente:',gradient(x),'gradiente por entrada:',x*gradient(x))def ig(grad,x,base,steps):
ts=np.linspace(0,1,steps+1); values=np.array([grad(base+t*(x-base)) for t in ts])
values[0]*=.5; values[-1]*=.5
return (x-base)*values.sum(axis=0)/steps
for n in (4,8,16,32,64,128):
a=ig(gradient,x,baseline,n)
print('pasos',n,'IG',np.round(a,6),'residuo',round(float(a.sum()-(F(x)-F(baseline))),6))def smoothgrad(grad,x,sigma,n,seed):
random=np.random.default_rng(seed)
return np.mean([grad(x+random.normal(scale=sigma,size=len(x))) for _ in range(n)],axis=0)
for n in (1,8,64):
estimates=np.array([smoothgrad(gradient,x,.3,n,s) for s in range(8)])
print('muestras',n,'varianza media',round(float(estimates.var(axis=0).mean()),6))
# Dos grafos implementan el mismo escalar: ReLU(t)−ReLU(−t)=t.
def F_a(z): return z[0]+2*z[1]
def F_b(z): return max(z[0],0)-max(-z[0],0)+2*z[1]
def grad_a(z): return np.array([1.,2.])
def grad_b(z): return np.array([float(z[0]>0)+float(z[0]<0),2.])
probe=np.array([2.,1.]); ref=np.array([1.,0.]) # el segmento no cruza el quiebre
print('funciones iguales:',np.isclose(F_a(probe),F_b(probe)),
'IG iguales:',np.allclose(ig(grad_a,probe,ref,32),ig(grad_b,probe,ref,32)))The last example avoids the nondifferentiable point of the ReLU graph so derivatives agree at all evaluated points. In a real system specify the subgradient convention and avoid attributing a discretization discrepancy to a functional difference.
Exercises
Step 1 of 3. How do we sum over coordinates?
Step 1 of 2. What happens when differentiating at t=1?
import numpy as np
def integrated_gradients(f_grad,x,baseline,steps):
pass