Interpretability methods¶
Class activation map¶
The class activation map gives you the importance of each region of a feature map on a model's output. More specifically, a class activation map is relative to:
- the layer at which it is computed (e.g. the N-th layer of your model)
- the model's classification output (e.g. the raw logits of the model)
- the class index to focus on
With TorchCAM, the target layer is selected when you create your CAM extractor. You will need to pass the model logits to the extractor and a class index for it to do its magic!
Activation-based methods¶
Methods related to activation-based class activation maps.
torchcam.methods.CAM
¶
CAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, fc_layer: Module | str | None = None, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Learning Deep Features for Discriminative Localization".
The Class Activation Map (CAM) is defined for image classification models that have global pooling at the end of the visual feature extraction block. The localization map is computed as follows:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), and \(w_k^{(c)}\) is the weight corresponding to class \(c\) for unit \(k\) in the fully connected layer.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import CAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with CAM(model, 'layer4', 'fc') as cam_extractor:
with torch.inference_mode(): out = model(input_tensor)
cam = cam_extractor(class_idx=100)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
fc_layer
|
either the fully connected layer itself or its name |
input_shape
|
shape of the expected input tensor excluding the batch dimension |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the argument is invalid |
TypeError
|
if the argument type is invalid |
Source code in torchcam/methods/activation.py
torchcam.methods.ScoreCAM
¶
ScoreCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, batch_size: int = 32, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Score-CAM: Score-Weighted Visual Explanations for Convolutional Neural Networks".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), \(Y^{(c)}(X)\) is the model output score for class \(c\) before softmax for input \(X\), \(X_b\) is a baseline image, and \(M_k\) is defined as follows:
where \(\odot\) refers to the element-wise multiplication and \(U\) is the upsampling operation.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import ScoreCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with ScoreCAM(model, 'layer4') as cam_extractor:
with torch.inference_mode(): out = model(input_tensor)
cam = cam_extractor(class_idx=100)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
batch_size
|
batch size used to upsample masks and forward masked inputs
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/activation.py
torchcam.methods.SSCAM
¶
SSCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, batch_size: int = 32, num_samples: int = 35, std: float = 2.0, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "SS-CAM: Smoothed Score-CAM for Sharper Visual Feature Localization".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(N\) is the number of samples used to smooth the weights, \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), \(Y^{(c)}(X)\) is the model output score for class \(c\) before softmax for input \(X\), \(X_b\) is a baseline image, and \(M_k\) is defined as follows:
where \(\odot\) refers to the element-wise multiplication, \(U\) is the upsampling operation, \(\delta \sim \mathcal{N}(0, \sigma^2)\) is the random noise that follows a 0-mean gaussian distribution with a standard deviation of \(\sigma\).
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import SSCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with SSCAM(model, 'layer4') as cam_extractor:
with torch.inference_mode(): out = model(input_tensor)
cam = cam_extractor(class_idx=100)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
batch_size
|
batch size used to forward masked inputs
TYPE:
|
num_samples
|
number of noisy samples used for weight computation
TYPE:
|
std
|
standard deviation of the noise added to the normalized activation
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/activation.py
torchcam.methods.ISCAM
¶
ISCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, batch_size: int = 32, num_samples: int = 10, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "IS-CAM: Integrated Score-CAM for axiomatic-based explanations".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(N\) is the number of samples used to smooth the weights, \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), \(Y^{(c)}(X)\) is the model output score for class \(c\) before softmax for input \(X\), \(X_b\) is a baseline image, and \(M_i\) is defined as follows:
where \(\odot\) refers to the element-wise multiplication, \(U\) is the upsampling operation.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import ISCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with ISCAM(model, 'layer4') as cam_extractor:
with torch.inference_mode(): out = model(input_tensor)
cam = cam_extractor(class_idx=100)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
batch_size
|
batch size used to forward masked inputs
TYPE:
|
num_samples
|
number of noisy samples used for weight computation
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/activation.py
Gradient-based methods¶
Methods related to gradient-based class activation maps.
torchcam.methods.FinerCAM
¶
FinerCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, input_shape: tuple[int, ...] = (3, 224, 224), *, base_method: type[GradCAM] | type[GradCAMpp] | type[LayerCAM] = GradCAM, gamma: float = 0.6, num_references: int = 3, **base_kwargs: Any)
Implements "Finer-CAM: Spotting the Difference Reveals Finer Details for Visual Explanation".
Finer-CAM changes the base extractor objective from the target score \(y_c\) to the contrastive objective
so comparisons are aggregated before the base method's final CAM ReLU. Automatic references are the classes with scores closest to the target score. The target is always excluded, and the requested count is capped by the available classes. Only GradCAM, GradCAMpp, and LayerCAM are supported initially.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import FinerCAM, LayerCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with FinerCAM(model, "layer4", base_method=LayerCAM) as cam_extractor:
scores = model(input_tensor)
cams = cam_extractor(class_idx=100, scores=scores, comparison_idx=[101, 102, 103])
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
base_method
|
gradient CAM extractor used to produce the maps
TYPE:
|
gamma
|
comparison strength applied to the mean reference score
TYPE:
|
num_references
|
number of automatic references to select, capped by the available non-target classes
TYPE:
|
base_kwargs
|
keyword arguments forwarded to
TYPE:
|
Source code in torchcam/methods/gradient.py
torchcam.methods.FinerCAM.compute_cams
¶
compute_cams(class_idx: int | list[int], scores: Tensor | None = None, comparison_idx: int | list[int] | list[list[int]] | None = None, normalized: bool = True, **kwargs: Any) -> list[Tensor]
Compute Finer-CAMs without the base extractor precheck.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if arbitrary output targets are provided |
Source code in torchcam/methods/gradient.py
torchcam.methods.FinerCAM.fuse_cams
¶
Fuse maps using the selected base extractor.
torchcam.methods.GradCAM
¶
GradCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), and \(Y^{(c)}\) is the model output score for class \(c\) before softmax.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import GradCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with GradCAM(model, 'layer4') as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(class_idx=100, scores=scores)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/gradient.py
torchcam.methods.GradCAMpp
¶
GradCAMpp(model: Module, target_layer: Module | str | list[Module | str] | None = None, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Grad-CAM++: Improved Visual Explanations for Deep Convolutional Networks".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), \(Y^{(c)}\) is the model output score for class \(c\) before softmax, and \(g_k^{(c)}(i,j) = \frac{\partial Y^{(c)}}{\partial A_k(i,j)}\). This implementation uses the square and cube of the first derivative for the higher-order terms:
The coefficient is zero when the squared gradient is zero. A small \(\varepsilon\) stabilizes the denominator. For float16 and bfloat16 inputs, gradient powers and activation sums use float32 to avoid underflow and overflow. Float64 inputs retain their precision.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import GradCAMpp
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with GradCAMpp(model, 'layer4') as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(class_idx=100, scores=scores)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/gradient.py
torchcam.methods.SmoothGradCAMpp
¶
SmoothGradCAMpp(model: Module, target_layer: Module | str | list[Module | str] | None = None, num_samples: int = 4, std: float = 0.3, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Smooth Grad-CAM++: An Enhanced Inference Level Visualization Technique for Deep Convolutional Neural Network Models" with a personal correction to the paper (alpha coefficient numerator).
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(A_k(x,y)\) is the original input's activation in the target layer, and \(g_{k,m}^{(c)}(i,j)\) is the first derivative of the pre-softmax class score with respect to the activation for noisy sample \(m\). For \(p \in \{1,2,3\}\), the same \(n\) noisy samples estimate each gradient moment:
As in :class:GradCAMpp, powers of the first derivative approximate the higher-order terms:
The first-order gradients are averaged before applying ReLU. The resulting weights are combined with the original input's activations, so permuting the same noisy samples does not change the estimator apart from floating-point rounding. Zero squared-gradient moments give zero coefficients.
The corrected alpha numerator uses the mean squared gradient, rather than the mean first derivative in the paper. For float16 and bfloat16 inputs, gradient moments and activation sums use float32 to avoid underflow and overflow. Float64 inputs retain their precision.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import SmoothGradCAMpp
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with SmoothGradCAMpp(model, 'layer4') as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(class_idx=100)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
num_samples
|
number of samples to use for smoothing
TYPE:
|
std
|
standard deviation of the noise
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/gradient.py
torchcam.methods.XGradCAM
¶
XGradCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "Axiom-based Grad-CAM: Towards Accurate Visualization and Explanation of CNNs".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}\) being defined as:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), and \(Y^{(c)}\) is the model output score for class \(c\) before softmax.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import XGradCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with XGradCAM(model, 'layer4') as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(class_idx=100, scores=scores)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/gradient.py
torchcam.methods.LayerCAM
¶
LayerCAM(model: Module, target_layer: Module | str | list[Module | str] | None = None, input_shape: tuple[int, ...] = (3, 224, 224), **kwargs: Any)
Implements a class activation map extractor as described in "LayerCAM: Exploring Hierarchical Class Activation Maps for Localization".
The localization map is computed as follows:
with the coefficient \(w_k^{(c)}(x, y)\) being defined as:
where \(A_k(x, y)\) is the activation of node \(k\) in the target layer of the model at position \((x, y)\), and \(Y^{(c)}\) is the model output score for class \(c\) before softmax.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import LayerCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with LayerCAM(model, 'layer4') as cam_extractor:
scores = model(input_tensor)
cams = cam_extractor(class_idx=100, scores=scores)
fused_cam = cam_extractor.fuse_cams(cams)
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
either the target layer itself or its name, or a list of those
TYPE:
|
input_shape
|
shape of the expected input tensor excluding the batch dimension |
Source code in torchcam/methods/gradient.py
torchcam.methods.LeGrad
¶
LeGrad(model: Module, target_layer: Module | str | list[Module | str], *, score_projection: Callable[[Tensor], Tensor] | None = None, prefix_tokens: int = 1, grid_shape: tuple[int, int] | None = None, enable_hooks: bool = True)
Implements LeGrad as described in "LeGrad: An Explainability Method for Vision Transformers via Feature Formation Sensitivity".
For every selected transformer block :math:l, LeGrad differentiates that block's class score
:math:s^l with respect to its post-softmax attention probabilities :math:A^l. Positive gradients are
averaged over heads and query tokens, prefix keys are removed, and the resulting patch maps are averaged over
layers before normalization. Attention values are not multiplied into the gradients.
Target layers must return tokens shaped (batch, tokens, embedding) and expose a direct
self_attention child implemented by batch-first :class:torch.nn.MultiheadAttention. The built-in score
projection supports torchvision VisionTransformer models; other matching blocks require
score_projection to map intermediate tokens to class logits.
Example
from torchvision.models import ViT_B_16_Weights, vit_b_16
from torchcam.methods import LeGrad
model = vit_b_16(weights=ViT_B_16_Weights.DEFAULT).eval()
with LeGrad(model, list(model.encoder.layers)[-4:]) as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(scores[0].argmax().item())[0]
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
transformer block or blocks, specified as modules or their names |
score_projection
|
optional function mapping intermediate tokens to class logits shaped |
prefix_tokens
|
number of non-spatial key tokens to remove before reshaping
TYPE:
|
grid_shape
|
patch-grid |
enable_hooks
|
whether hooks should be enabled by default
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if an argument has an invalid type |
ValueError
|
if the model, target blocks, attention modules, or grid are unsupported |
Source code in torchcam/methods/gradient.py
torchcam.methods.LeGrad.reset_hooks
¶
Clear stored layer scores and attention probabilities.
Source code in torchcam/methods/gradient.py
torchcam.methods.LeGrad.compute_cams
¶
compute_cams(class_idx: int | list[int] | None = None, scores: Any = None, normalized: bool = True, retain_graph: bool = False, *, targets: OutputTarget | list[OutputTarget] | None = None, **kwargs: Any) -> list[Tensor]
Compute and average layerwise positive attention-gradient maps.
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if attention and token shapes are incompatible |
Source code in torchcam/methods/gradient.py
torchcam.methods.RefineCAM
¶
RefineCAM(model: Module, target_layer: list[Module | str], input_shape: tuple[int, ...] = (3, 224, 224), *, base_method: type[_CAM] = GradCAMpp, **base_kwargs: Any)
Implements the multi-layer refinement described in "How to Evaluate and Refine your CAM".
RefineCAM normalizes class activation maps from multiple layers, resizes them to a common spatial shape, and
multiplies them element-wise. Grad-CAM++ is used by default, but any CAM extractor supporting multiple target
layers can be passed as base_method.
Example
from torchvision.models import get_model, get_model_weights
from torchcam.methods import LayerCAM, RefineCAM
model = get_model("resnet18", weights=get_model_weights("resnet18").DEFAULT).eval()
with RefineCAM(model, ["layer2", "layer3", "layer4"], base_method=LayerCAM) as cam_extractor:
scores = model(input_tensor)
cam = cam_extractor(class_idx=100, scores=scores)[0]
| PARAMETER | DESCRIPTION |
|---|---|
model
|
input model
TYPE:
|
target_layer
|
target layers, specified as modules or their names |
input_shape
|
shape of the expected input tensor excluding the batch dimension |
base_method
|
CAM extractor used to produce the per-layer maps |
base_kwargs
|
keyword arguments forwarded to
TYPE:
|
Source code in torchcam/methods/gradient.py
torchcam.methods.RefineCAM.compute_cams
¶
compute_cams(class_idx: int | list[int] | None = None, scores: Any = None, normalized: bool = True, target_shape: tuple[int, ...] | None = None, *, targets: OutputTarget | list[OutputTarget] | None = None, **kwargs: Any) -> list[Tensor]
Compute and refine CAMs without the base extractor precheck.
Source code in torchcam/methods/gradient.py
torchcam.methods.RefineCAM.fuse_cams
staticmethod
¶
fuse_cams(cams: list[Tensor], target_shape: tuple[int, ...] | None = None, normalized: bool = True) -> Tensor
Normalize, resize, and multiply maps from multiple layers.
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if |
ValueError
|
if |
Source code in torchcam/methods/gradient.py
Entropy-gradient maps for VLMs¶
EntropyGradient implements the paper's
map primitive: next-token Shannon entropy, its gradient with respect to projected visual input embeddings,
then the channel L2 norm. Bright patches indicate sensitivity of uncertainty, not support for a generated word.
Region selection and iterative cropping are excluded; the full pipeline's answer-accuracy gains are not claimed.
from torchcam.methods import EntropyGradient
# embeddings: (batch, tokens, channels), requiring gradients BEFORE this forward
output = language_model(inputs_embeds=embeddings, use_cache=False)
maps = EntropyGradient((height, width))(
output.logits[:, -1], embeddings, visual_tokens=image_positions,
) # (batch, height, width), detached and normalized per image
Supply the exact embeddings entering the language model, not final hidden states or post-forward copies/slices.
visual_tokens is an optional boolean mask or ordered integer indices; omit it for an all-visual input.
Samples must be independent and share a row-major grid and selection. Both forward and attribution need autograd.
Checkpointed forwards require use_reentrant=False.
retain_graph=True permits graph reuse; normalized=False retains raw norms. Parameter gradients are preserved.
Entropy and norms accumulate in float32/float64; they cannot recover gradients lost inside a low-precision model.
The caller owns model extraction and spatial layout; no automatic VLM adapter or Transformers dependency is added.
EntropyGradient
¶
Extract the map primitive from "Entropy-Gradient Grounding", equations (1)-(4).
Take the channel L2 norm of next-token Shannon entropy gradients with respect to projected visual embeddings entering the language model. This measures uncertainty sensitivity, not word attribution. Region selection and crop-and-refine are excluded. The caller supplies tensors from an existing differentiable forward and their spatial order; this extractor installs no hooks.
| PARAMETER | DESCRIPTION |
|---|---|
grid_shape
|
explicit visual grid |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the grid is not a pair of positive integers |
Source code in torchcam/methods/entropy.py
torchcam.methods.EntropyGradient.__call__
¶
__call__(logits: Tensor, embeddings: Tensor, visual_tokens: Tensor | None = None, *, normalized: bool = True, retain_graph: bool = False) -> Tensor
Map uncertainty sensitivity at one caller-selected decoding step.
| PARAMETER | DESCRIPTION |
|---|---|
logits
|
full vocabulary logits
TYPE:
|
embeddings
|
exact projected or mixed visual/text input embeddings
TYPE:
|
visual_tokens
|
optional boolean mask
TYPE:
|
normalized
|
min-max normalize each image to [0, 1]; constant maps become zero
TYPE:
|
retain_graph
|
keep the graph for another attribution/backward; default releases it
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
detached |
Tensor
|
float64 if either input is double precision. Entropy uses natural logs. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if shapes, devices, dtypes, finite values or token selection are incompatible |
RuntimeError
|
if autograd is disabled, inputs are disconnected/non-differentiable, or the graph is freed |
Note
Sample entropies are summed, assuming independent samples. Parameter gradients are preserved.
Accumulation cannot recover gradients already lost inside a low-precision model.
Checkpointed forwards must use use_reentrant=False (required by autograd.grad).
Source code in torchcam/methods/entropy.py
Input-token attribution for text decisions¶
TokenIG runs embedding Integrated Gradients for each selected classifier score. It returns signed token
contributions and uncalibrated model scores, with completeness and refinement checks.
TokenAblation instead measures single-token replacement effects using only forwards; effects need not add up.
See Text decision models for examples and Laya integration.
TokenAblation
¶
Explain a classifier by replacing one input token at a time, without gradients.
All classes share one forward per selected token position, plus the original forward. Attention, positions and other context stay fixed. Use a replacement ID appropriate to the model, such as its pretrained mask token. Models must be deterministic in evaluation mode, have independent batch samples, and not mutate their parameters.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
PyTorch classifier accepting keyword arguments, including
TYPE:
|
output_transform
|
optional function selecting floating-point |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if an embedding renormalizes weights during forward |
Source code in torchcam/methods/text.py
torchcam.methods.TokenAblation.__call__
¶
__call__(inputs: Mapping[str, Any], replacement_id: int, *, token_mask: Tensor | None = None) -> TokenAblationResult
Return signed effects of individual token replacements.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
unchanged model keyword arguments; |
replacement_id
|
vocabulary ID substituted at each selected position; attention remains unchanged
TYPE:
|
token_mask
|
boolean
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TokenAblationResult
|
detached original scores and signed effects. Positive values mean replacement lowers a class score. |
TokenAblationResult
|
Effects are marginal changes with other tokens fixed, not additive contributions or token probabilities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if IDs, replacement, mask or model scores are invalid |
Source code in torchcam/methods/text.py
TokenAblationResult
dataclass
¶
Single-token replacement effects; interactions mean contributions need not add up.
| ATTRIBUTE | DESCRIPTION |
|---|---|
scores |
original scores shaped
TYPE:
|
attributions |
original minus replaced-token scores, shaped
TYPE:
|
TokenIG
¶
TokenIG(model: Module, embedding_layer: Module | str, output_transform: Callable[[Any], Tensor] | None = None)
Explain text classifiers with embedding Integrated Gradients.
Implements Integrated Gradients on a straight embedding path. Gauss-Legendre integration is refined until signed completeness and successive token maps agree. One forward per node is shared across selected classes. No tokenizer or model-specific dependency is needed. Temporary embedding hooks and evaluation mode are restored on success or failure; parameter gradients are preserved.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
differentiable PyTorch classifier; call its underlying module rather than a no-grad prediction API
TYPE:
|
embedding_layer
|
input word-embedding module, or its name in |
output_transform
|
optional function selecting a floating-point |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if the embedding layer is outside the model or renormalizes weights during forward |
Source code in torchcam/methods/text.py
torchcam.methods.TokenIG.__call__
¶
__call__(inputs: Mapping[str, Any], class_idx: int | list[int] | None = None, *, token_mask: Tensor | None = None, baseline: Tensor | None = None, steps: int = 32, max_steps: int = 4096, tolerance: float = 0.0001, stability_tolerance: float = 0.01) -> TokenAttribution
Attribute selected class scores to the input tokens.
| PARAMETER | DESCRIPTION |
|---|---|
inputs
|
keyword arguments forwarded unchanged to the model, including IDs, masks and position metadata |
class_idx
|
one output column, an ordered list, or |
token_mask
|
boolean
TYPE:
|
baseline
|
reference embeddings matching the embedding output's shape, device and dtype; defaults to zero
TYPE:
|
steps
|
initial quadrature nodes, doubled on refinement; at least two integration passes are required
TYPE:
|
max_steps
|
maximum nodes per integration pass, at least twice
TYPE:
|
tolerance
|
maximum absolute signed completeness error for every sample and selected class
TYPE:
|
stability_tolerance
|
maximum L1 map change divided by map L1 norm on successive passes
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TokenAttribution
|
detached scores, signed maps and convergence information. Positive values support a class relative to |
TokenAttribution
|
the baseline; negative values oppose it. These are score contributions, not token probabilities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if inputs, scores, baseline, selection or integration settings are invalid |
RuntimeError
|
if gradients are unavailable, the embedding module is reused, or integration fails to converge |
Note
Batch samples must be independent. Use eager inference and non-reentrant gradient checkpointing.
An outer torch.no_grad() is supported, but inference mode and no-grad model forwards are not.
Numerical convergence does not establish causal influence or bias; compare baselines and controlled edits.
Source code in torchcam/methods/text.py
TokenAttribution
dataclass
¶
TokenAttribution(scores: Tensor, baseline_scores: Tensor, attributions: Tensor, class_indices: tuple[int, ...], completeness_error: Tensor, steps: int)
Input-token contributions relative to an embedding baseline.
| ATTRIBUTE | DESCRIPTION |
|---|---|
scores |
original model scores, shaped
TYPE:
|
baseline_scores |
model scores with selected embeddings replaced by the baseline
TYPE:
|
attributions |
signed contributions shaped
TYPE:
|
class_indices |
output columns, in the same order as the attribution maps |
completeness_error |
signed attribution sum minus score change, shaped
TYPE:
|
steps |
quadrature nodes used by the final integration; earlier refinement passes are additional
TYPE:
|
Visual token activation maps¶
Visual explanations for selected vocabulary tokens in multimodal language models. TAM consumes final language-model states and a linear vocabulary head directly; it does not use the class CAM hook API.
TAM
¶
Extract the visual Token Activation Map from "Token Activation Map to Visually Explain Multimodal LLMs".
TAM projects final language-model states onto output-head weights, removes the least-squares estimate of earlier text's visual interference, and applies the paper's rank Gaussian filter. Identical context token IDs are excluded from interference. The output-head bias is unused, following equation (1).
This extractor consumes states from an existing forward; it installs no hooks and runs no model forwards or
backward passes. Unlike class CAM extractors, it returns one tensor, shaped (N, H, W). Only visual maps are
returned, with optional normalization over each image rather than joint image/text normalization.
| PARAMETER | DESCRIPTION |
|---|---|
token_classifier
|
the model's linear vocabulary output head, usually
TYPE:
|
kernel_size
|
positive odd rank Gaussian window size; use 1 to disable smoothing
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
if the output head or kernel size has an invalid type |
ValueError
|
if the kernel size is not positive and odd |
Source code in torchcam/methods/token.py
torchcam.methods.TAM.__call__
¶
__call__(token_id: int | list[int], visual_features: Tensor, context_features: Tensor, context_ids: Tensor, normalized: bool = True) -> Tensor
Explain one vocabulary token per image using final language-model states.
| PARAMETER | DESCRIPTION |
|---|---|
token_id
|
vocabulary ID shared by the batch, or one ID per sample |
visual_features
|
image-token states reshaped to
TYPE:
|
context_features
|
earlier text states shaped
TYPE:
|
context_ids
|
earlier text vocabulary IDs shaped
TYPE:
|
normalized
|
whether to normalize each visual map to [0, 1]
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
visual activation maps shaped |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
if shapes, devices, feature dtypes or vocabulary IDs are incompatible |