Interpretability, robustness and adversarial examples
What is the model looking at, and how easily can it be fooled?
A model with 95% validation accuracy may be reading the hospital's watermark instead of the X-ray, or distinguishing huskies from wolves by the snow. Attribution methods like Grad-CAM show what a model attends to; adversarial examples show how brittle its decision boundary is; shift benchmarks show whether accuracy survives the real world. These tools catch failures before deployment, and they are the direct ancestors of mechanistic interpretability for LLMs (8.11 Interpretability: what is happening inside) and of the adversarial-input problems — prompt injection — that dominate agent security (10.10 Agent safety and security).
You'll be able to
- Compute gradient saliency and Integrated Gradients, and derive Grad-CAM from class-score gradients
- Explain feature visualization and use attributions to diagnose shortcut learning
- Derive FGSM, explain why high-dimensional linearity makes adversarial examples inevitable, and describe PGD and adversarial training
- Evaluate robustness under distribution shift and calibrate a model with temperature scaling
- Audit a dataset and a trained model for bias and label errors
Key ideas
- Attribution asks which pixels mattered (saliency, SmoothGrad, Integrated Gradients with Σ IG = F(x) − F(x')); feature visualization asks what a unit detects (gradient ascent on activations).
- Grad-CAM: α_k = GAP of ∂y^c/∂A^k, heatmap = ReLU(Σ_k α_k A^k) upsampled; it reduces exactly to CAM for GAP+linear heads and works for any architecture.
- FGSM: x + ε·sign(∇_x L) flips predictions with imperceptible noise because linear scores change by ε‖w‖₁, which grows with dimension; PGD is the iterated, projected version.
Show 4 more key ideas
- Adversarial training (min over θ of max over ‖δ‖∞ ≤ ε of the loss) is the main defense; gradient masking is not a defense; attacks transfer across models.
- Shortcut learning (texture, backgrounds, artifacts) hides behind in-distribution accuracy — test on shifted sets (ImageNet-C/R/A, held-out sites) and report worst-group results.
- Modern nets are over-confident; temperature scaling (softmax(z/T) with T fit on validation) fixes calibration cheaply; ensembles give real uncertainty.
- Audit data (label noise ≈ 6% in ImageNet, duplicates, demographic coverage) and evaluate by subgroup before trusting a model.
Suggested path through this lesson
Why look inside
Accuracy on a held-out split only tells you the model works on data like the training data. It does not tell you why it works. Classic failures: a wolf-vs-husky classifier that detects snow; a pneumonia model that reads the portable-X-ray marker; a "tench" detector that fires on the fisherman's fingers. Interpretability tools come in two families — attribution (which input pixels mattered for this prediction?) and feature visualization (what pattern does this neuron or channel detect?) — plus behavioral tests (adversarial and shifted inputs).
Attribution by gradients
The simplest attribution is the gradient saliency map (Simonyan et al., 2013): (max over color channels), a first-order answer to "which pixels would change the class score most?". It is noisy because ReLU networks are piecewise linear and gradients flicker; SmoothGrad averages gradients over noisy copies of the input. Integrated Gradients (Sundararajan et al., 2017) fixes a deeper flaw — gradients saturate — by integrating along a straight path from a baseline (a black image) to the input:
with the completeness property : attributions add up to the change in output, so they are on an interpretable scale.
Grad-CAM, derived
Pixel-level maps are noisy; Grad-CAM (2016) works at the level of the last convolutional feature maps , which are spatial and semantic. For class with pre-softmax score :
- Compute the gradient of the score with respect to each feature map and global-average-pool it to get a channel importance:
- Combine the feature maps with these weights and keep only positive evidence:
- Upsample the map to the image size and overlay it.
Why does this work? For a network ending in GAP + linear layer, , so and exactly: Grad-CAM reduces to the original CAM, and generalizes it to any architecture (with FC layers, for detection, for captioning) via gradients. The ReLU discards regions that argue against the class. Combining with guided backprop gives sharper "Guided Grad-CAM". A -line call to pytorch-grad-cam does all this; use it on your 5.10 Project: train and deploy an image classifier model.
Feature visualization
Instead of asking which pixels matter for one image, synthesize an input that maximally activates a neuron, channel or logit: start from noise, run gradient ascent on the activation, and regularize (random jitter/rotation/scaling, parametrizing the image in a decorrelated Fourier basis) to avoid adversarial high-frequency noise. The Distill "Feature Visualization" article shows the resulting progression — edges → textures → parts → objects — and dataset examples (top-activating patches) complement it. Network Dissection quantifies how many channels align with human concepts. These ideas later became the circuits program in LLMs (8.11 Interpretability: what is happening inside).
Adversarial examples
Add an imperceptible perturbation and the prediction flips. The Fast Gradient Sign Method (Goodfellow et al., 2014):
one gradient step that moves every pixel by in the direction that increases the loss. With (about 2 of 255 gray levels), GoogLeNet's "panda" became "gibbon" with 99.3% confidence. The explanation is linearity in high dimensions: a linear score changes by , and choosing changes it by — a quantity that grows with dimension even though each coordinate moved by a tiny (1.1 Vectors, dot products and norms). PGD iterates small FGSM steps and projects back onto the -ball; it is the standard strong attack. Adversarial examples transfer between models (enabling black-box attacks), survive printing and camera capture (adversarial patches, stickers on stop signs), and exist for every modality. The best known defense is adversarial training — solving the min–max problem
with PGD generating the inner maximization — at the cost of clean accuracy and training time. Randomized smoothing gives certified robustness radii. Many proposed defenses only masked gradients and were broken within months; evaluate against adaptive attacks. The LLM analog is prompt injection: adversarial text that flips an agent's behavior (8.12 Safety, risks and responsible AI, 10.10 Agent safety and security).
Distribution shift and shortcut learning
Models exploit whatever correlates with the label in training data: texture (ImageNet CNNs classify a cat-shaped image with elephant texture as an elephant), backgrounds (cows on beaches are not recognized), hospital-specific artifacts. Geirhos et al. call this shortcut learning. Measure it with shifted test sets: ImageNet-C (corruptions), ImageNet-R (renditions), ImageNet-A (natural adversarial examples), ImageNet-Sketch, and in your own domain by holding out an entire site/device/season. Mitigations: more diverse data, augmentation that breaks the shortcut (style transfer for texture bias), group-balanced training, pretraining at scale (CLIP and DINOv2 are markedly more robust), and reporting worst-group rather than average accuracy.
Calibration and uncertainty
A calibrated model's confidence matches its accuracy: of the predictions made with 80% confidence, 80% should be right. Modern deep nets are over-confident (Guo et al., 2017). Measure with a reliability diagram and the Expected Calibration Error; fix cheaply with temperature scaling — fit a single scalar on the validation set and predict with (8.5 Decoding and sampling uses the same knob for sampling). For genuine uncertainty estimates use deep ensembles or MC dropout; for out-of-distribution detection, energy scores or feature-space distances. Calibration is what lets you set a threshold for "ask a human" (3.5 Evaluating models: metrics, validation and the bias–variance trade-off).
Data and fairness audits
ImageNet's labels are about 6% wrong; face datasets have skewed demographics that translate into unequal error rates. Before trusting a model, audit the data: class balance, duplicates between train and test, label noise (confident-learning tools), demographic and geographic coverage, and document it (datasheets, 3.13 Feature engineering, data quality and data-centric ML). Then audit the model by subgroup, not just on average.
Where this shows up later
- Mechanistic interpretability of transformers (circuits, superposition, sparse autoencoders) — 8.11 Interpretability: what is happening inside.
- Adversarial inputs for LLMs: jailbreaks and prompt injection — 8.12 Safety, risks and responsible AI, 10.10 Agent safety and security.
- Evaluation and calibration fundamentals — 3.5 Evaluating models: metrics, validation and the bias–variance trade-off, 8.7 Evaluating LLMs; temperature in decoding — 8.5 Decoding and sampling.
Common pitfalls (4)
- Trusting a pretty saliency map as proof of correct reasoning — sanity-check attribution methods (randomize the weights; the map should change).
- Declaring a defense successful against FGSM only; strong, adaptive attacks (PGD, AutoAttack) break most defenses that merely obscure gradients.
- Measuring robustness on the same distribution as training; shift benchmarks or held-out sites are required.
- Reading softmax probabilities as calibrated confidence without checking a reliability diagram.
Recap: all 7 key points
- Attribution asks which pixels mattered (saliency, SmoothGrad, Integrated Gradients with Σ IG = F(x) − F(x')); feature visualization asks what a unit detects (gradient ascent on activations).
- Grad-CAM: α_k = GAP of ∂y^c/∂A^k, heatmap = ReLU(Σ_k α_k A^k) upsampled; it reduces exactly to CAM for GAP+linear heads and works for any architecture.
- FGSM: x + ε·sign(∇_x L) flips predictions with imperceptible noise because linear scores change by ε‖w‖₁, which grows with dimension; PGD is the iterated, projected version.
- Adversarial training (min over θ of max over ‖δ‖∞ ≤ ε of the loss) is the main defense; gradient masking is not a defense; attacks transfer across models.
- Shortcut learning (texture, backgrounds, artifacts) hides behind in-distribution accuracy — test on shifted sets (ImageNet-C/R/A, held-out sites) and report worst-group results.
- Modern nets are over-confident; temperature scaling (softmax(z/T) with T fit on validation) fixes calibration cheaply; ensembles give real uncertainty.
- Audit data (label noise ≈ 6% in ImageNet, duplicates, demographic coverage) and evaluate by subgroup before trusting a model.
Watch
Saliency, feature visualization, dataset examples, DeepDream, adversarial fooling images — the lecture version of this lesson.
Read
Exercises
- Grad-CAM on your classifier
Apply
pytorch-grad-camto the model from 5.4 Transfer learning and training CNNs in practice/5.10 Project: train and deploy an image classifier on 20 correctly and 20 incorrectly classified images. Categorize what the model attends to (object, context, artifact). Then run the sanity check: randomize the last layer's weights and confirm the maps change substantially. - FGSM and PGD in 30 lines
Implement FGSM and 10-step PGD (, step ) against a pretrained ResNet-18 on CIFAR-10 test images. Report clean accuracy vs accuracy under each attack. Expected: clean ~95%, FGSM well below 30%, PGD near 0%. Visualize a perturbation amplified 30× to see it is near-invisible.
- Calibrate with temperature scaling
Plot a reliability diagram (10 bins) and compute ECE for your model on validation data. Fit by minimizing NLL of with a few steps of gradient descent on , then re-plot. Expected: between 1.5 and 3 for a typical fine-tuned CNN, with ECE dropping by 50% or more.
- Build a shifted test set
Collect 50 images of your classes under conditions absent from training (night, different camera, drawings). Compare accuracy with the in-distribution test set and inspect Grad-CAM maps for failures. Expected: a visible drop and at least one shortcut you can name.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →