Module contents
Lesson 11 of 39Core 100 min

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 F(x)F(x) is ∇xF(x)\nabla_x F(x). If FF is differentiable, F(x+δ)≈F(x)+∇F(x)⊤δF(x+\delta)\approx F(x)+\nabla F(x)\T\delta for small perturbations. Gradient times input uses xi∂iF(x)x_i\partial_iF(x); 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.

InteractiveWhere the gradient falls silent
  • Input
  • Baseline
  • Threshold
Gradient at input(0, 0)
IG(0.600, 0.400)
IG sum1.000
Difference f(x)−f(baseline)1.000
Move the input and baseline for the model f(x)=min(1,x1+x2). In the saturated region the local gradient is zero, but the integral from the baseline can be nonzero and sum to the score difference.

For F(x)=min⁡(1,x1+x2)F(x)=\min(1,x_1+x_2) and zero baseline, x=(1.2,0.8)x=(1.2,0.8) is saturated: the gradient there is (0,0)(0,0). The straight path reaches x1+x2=1x_1+x_2=1 halfway through; before that both derivatives are 1 and afterward 0. Integrated attributions are (0.6,0.4)(0.6,0.4) 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 ∑iAi(x,x′)=F(x)−F(x′)\sum_i A_i(x,x')=F(x)-F(x'). Linearity requires attribution of aF+bGaF+bG to be aA(F)+bA(G)aA(F)+bA(G) with the same baseline.

The gradient at the input can violate sensitivity through saturation. Gradient times input is not generally complete either: for F(x)=x2F(x)=x^2, xF′(x)=2x2xF'(x)=2x^2, which is not F(x)−F(0)F(x)-F(0). 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 x′x' and input xx are

IG⁡i(x;x′)=(xi−xi′)∫01∂F(x′+α(x−x′))∂xi  ⁣dα.\operatorname{IG}_i(x;x')=(x_i-x'_i)\int_0^1\frac{\partial F(x'+\alpha(x-x'))}{\partial x_i}\,\dd\alpha.

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

∑iIG⁡i=∫01∇F(x′+α(x−x′))⊤(x−x′)  ⁣dα=F(x)−F(x′).\sum_i \operatorname{IG}_i=\int_0^1\nabla F(x'+\alpha(x-x'))\T(x-x')\,\dd\alpha=F(x)-F(x').

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 F(x)=x1x2F(x)=x_1x_2, zero baseline and x=(1,2)x=(1,2), both attributions equal one: the interaction is distributed along the path.

The integral is approximated by Riemann sums or trapezoids. The residual ∑iIG⁡^i−[F(x)−F(x′)]\sum_i\widehat{\operatorname{IG}}_i-[F(x)-F(x')] 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 F(x)F(x) and F(x′)F(x') 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.

InteractiveThe baseline changes the question
  • Negative contribution
  • Positive contribution
Image
Baseline black
Integrated Gradients
32
Explained digit5
Completeness error0.00091
Maximum absolute scale1.124
Choose one of five baselines and the number of steps. The maps come from an MLP actually trained on scikit-learn’s 8×8 digits; blue is negative contribution and red positive, with a fixed scale across states.

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 F(x)−EF(X′)F(x)-\E F(X'), 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 1N∑k=1N∇F(x+ϵk)\frac1N\sum_{k=1}^N\nabla F(x+\epsilon_k) with ϵk∼N(0,σ2I)\epsilon_k\sim N(0,\sigma^2 I) (Smilkov et al.). For fixed σ\sigma, more samples reduce Monte Carlo error under finite variance. Under regularity permitting interchange of derivative and expectation, the limit is the gradient of EF(x+ϵ)\E F(x+\epsilon), a smoothed function. Increasing σ\sigma changes that function, rather than just reducing noise.

InteractiveAveraging noise
  • Negative gradient
  • Positive gradient
Image
SmoothGrad
0.1
8
1
Mean variance across four seeds0.000039
Maximum absolute scale1.294
Compare four repetitions of the same MLP. Increase samples and change the standard deviation: mean variance across seeds measures Monte Carlo variability, not fidelity or causality.

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 [0,1][0,1] 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 AuvkA^k_{uv} and score FcF_c, Grad-CAM averages spatial gradients to obtain αkc=1HW∑u,v∂Fc/∂Auvk\alpha_k^c=\frac1{HW}\sum_{u,v}\partial F_c/\partial A^k_{uv} and displays

LGradCAMc=ReLU⁡ ⁣(∑kαkcAk).L_{\rm GradCAM}^c=\operatorname{ReLU}\!\left(\sum_k\alpha_k^c A^k\right).

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

InteractiveChanging layer and class in Grad-CAM
0.65
True labelcat
Predictioncat
Map before upscaling4 × 4
Maps calculated for a CIFAR-10 test image with the ResNet-18 trained in lesson 30.6. They are enlarged to 32×32 and normalized separately; the indicated size is the original map.

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 [0,1][0,1]. 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 8.2×10−88.2\times10^{-8} 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 n+1n+1 points and weights the endpoints by one half. It prints the residual and attributions; it does not assume that a few steps suffice.

[ ]MLP and analytic gradientBrowser
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))
[ ]Trapezoidal IG and residualBrowser
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))
[ ]SmoothGrad and functional invarianceBrowser
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

Proof
Prove: The sum of integrated gradients is F(x)−F(x').
0
Suppose F is differentiable in a neighborhood of the segment.

Step 1 of 3. How do we sum over coordinates?

Proof
Prove: A bias-free ReLU network that is positively homogeneous and differentiable at x satisfies the sum of x_i times its partial derivative equals F(x).
0
Homogeneity implies F(tx)=tF(x) for t>0.

Step 1 of 2. What happens when differentiating at t=1?

Numeric
For F(x1,x2)=x1 x2, baseline (0,0) and input (1,2), calculate IG for the first coordinate.
Quiz
Which statement about attention weights is supported by the debate presented?
CodeTrapezoids and completeness
Implement integrated_gradients(f_grad, x, baseline, steps). f_grad receives a vector and returns (scalar value, gradient). Use steps trapezoidal intervals and return (attributions, signed residual), where residual is the sum of attributions minus the value difference.
import numpy as np
def integrated_gradients(f_grad,x,baseline,steps):
  pass
Shift+Enter to run

Summary

Key idea
Attribution depends on output and reference: IG integrates sensitivity along a path and satisfies completeness under its assumptions, but neither a visual map nor an attention matrix demonstrates causality.