Captum

On this page 7

Captum is an open-source model interpretability library for PyTorch that implements gradient-based and perturbation-based feature attribution methods for neural networks. In Explainable AI, it is one of the most widely used toolkits for answering a precise question: which inputs, neurons or layers contributed to a specific prediction, and by how much.

Captum was released by Meta AI in 2019 under the BSD license. Its name comes from the Latin word for comprehension. It works with any torch.nn.Module, including vision, text, tabular and multimodal models, and it requires minimal changes to the model code, because most algorithms only need a forward function and input tensors.

How Captum computes attributions

Captum follows a uniform attribution interface. Each algorithm is a class that wraps the model’s forward function, and its attribute method returns a tensor of the same shape as the input, where each value estimates that element’s contribution to the chosen output, usually the logit of a target class.

Two families of methods sit behind this interface. Gradient-based methods use backpropagation, so they are fast but sensitive to saturation and noisy gradients. Perturbation-based methods change or remove parts of the input and observe the output, so they are model-agnostic but cost many forward passes.

MethodFamilyKey property
Integrated GradientsGradient path integralSatisfies completeness against a baseline
SaliencyPlain gradientVery fast, often noisy
DeepLift and DeepLiftShapModified backpropagationCompares activations with a reference
GradientShapSampled gradientsApproximates SHAP values with noise and baselines
OcclusionPerturbationSlides a patch and measures output change
Feature AblationPerturbationReplaces features or groups with a baseline
Shapley Value Sampling, KernelShap, LimePerturbation samplingModel-agnostic, computationally expensive
Main attribution methods available in Captum

Several methods take a baseline, the reference input that represents absence of signal, such as a black image, a zero embedding or a padding-token sequence. The choice of baseline changes the explanation, which is why serious analyses report it explicitly.

Attribution levels and supporting modules

Captum attributes importance at three levels of the network, which distinguishes it from libraries that explain only inputs. This makes it useful both for end-user explanations and for debugging internal representations.

LevelQuestion answeredExample algorithms
Primary attributionWhich input features drove the outputIntegrated Gradients, Occlusion
Layer attributionWhich units of a hidden layer matteredLayer Conductance, Layer GradCAM
Neuron attributionWhich inputs activate one specific neuronNeuron Conductance, Neuron Gradient
Attribution levels supported by Captum

Around the core algorithms, Captum provides extension modules. NoiseTunnel adds SmoothGrad and VarGrad averaging to any method. The concept module implements TCAV for testing human-defined concepts, the influence module implements training data attribution methods such as TracIn, and the robustness module includes FGSM and PGD perturbations.

For language models, LLM attribution wrappers attribute generated tokens to prompt segments, using either perturbation or gradient methods. Evaluation helpers compute infidelity and maximum sensitivity, two quantitative checks on explanation quality, and visualization utilities render heat maps for images and highlighted text.

Captum compared with other explanation toolkits

Captum is PyTorch-native and gradient-first, while most alternatives are framework-agnostic or focused on tabular data. The comparison below helps choose the right tool for a given model.

LibraryPrimary scopeMain difference from Captum
SHAP libraryShapley-based explanations, strong for treesBroader framework support, fewer layer-level tools
LIMELocal surrogate modelsModel-agnostic only, no gradient methods
InterpretMLGlass-box models and tabular explanationsEmphasizes explainable boosting machines
AI Explainability 360Broad toolkit of explanation algorithmsFramework-agnostic, less PyTorch-specific depth
Mechanistic interpretability toolsCircuits and activation patchingStudy internal mechanisms, not attribution scores
Captum and related interpretability libraries

In practice, teams often combine Captum with SHAP: SHAP for gradient-boosted tabular models and Captum for deep networks trained in PyTorch. Results from different libraries are not directly comparable unless baselines, targets and preprocessing match.

Choosing a method for a given task

The right Captum method depends on model type, input modality and compute budget. No single algorithm is best; a sound workflow compares two methods from different families and investigates where they disagree.

SituationRecommended startReason
Image classifierIntegrated Gradients with NoiseTunnel, plus OcclusionSmooth maps checked by a perturbation method
CNN localizationLayer GradCAMCoarse but stable class regions
Text classifierLayer Integrated Gradients on embeddingsToken inputs are discrete, embeddings are not
Tabular networkFeature Ablation or Shapley Value SamplingFew features keep sampling affordable
Generative language modelLLM attribution with feature masksAttributes output text to prompt parts
Practical starting points by situation

For Integrated Gradients, Captum can return a convergence delta, the gap between the summed attributions and the actual output difference from the baseline. A large delta signals too few integration steps; raising the step count from 50 to several hundred usually reduces it.

Limitations and common pitfalls

Captum computes attributions faithfully to each algorithm’s definition, but an attribution is not a causal explanation. Sanity-check research has shown that some gradient methods produce similar maps even for randomized models, so explanation faithfulness must be tested rather than assumed.

  • Arbitrary baselines can hide or invent important features.
  • Correlated features split credit unpredictably across ablation and Shapley methods.
  • Perturbation methods on large inputs can require thousands of forward passes.
  • Wrong target index or missing model.eval() silently produces misleading maps.
  • Visual heat maps invite overinterpretation; report quantitative checks alongside them.

Practical cost is a further constraint. Integrated Gradients multiplies backward passes by the number of steps, so teams use internal batch sizes to bound memory and run explanations on a representative sample rather than on every prediction. A defensible report states the method, baseline, target, step count and sample, so that another engineer can reproduce the attributions exactly and audit the conclusions drawn from them.

Put simply

A neural network gives an answer but does not say why. Captum helps people look inside. It highlights the parts of the input that mattered most. For a photo, it can color the pixels that pushed the model toward its answer. For a sentence, it can mark the important words.

Think of a teacher who asks a student to underline the words that led to an answer. The underlining is useful. It is not a full proof of the reasoning. People still need to check whether the highlighted parts make sense.

In practice

A hospital research team trains a PyTorch convolutional network to flag pneumonia on chest X-rays and reaches high validation accuracy. Before a clinical pilot, they run Captum’s Integrated Gradients with a black baseline and 200 steps, then confirm the maps with Occlusion using 16 by 16 pixel patches.

On a large share of positive cases, the strongest attributions fall on text markers in the image corners rather than on lung tissue. The markers identified a portable scanner used mostly for very sick patients. The team crops and masks the markers, retrains the model and repeats the analysis. Accuracy drops slightly, but attributions now concentrate on the lung fields, and the revised model is the one that enters the pilot.